content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import random def init(size): """Creates a randomly ordered dataset.""" # use system time as seed random.seed(None) # set random order as accessor order = [a for a in range(0, size)] random.shuffle(order) # init array with random data data = [random.random() for a in order] return (order, data)
975ab66f4e759973d55a0c519609b6df7086d747
71,500
from datetime import datetime def get_json_raw_data(mdate=None): """ 使用json返回指定日期的raw_data,为空为当天 :param: mdate, 'YYYY-MM-DD' :return: dict{raw_data} """ today = datetime.datetime.today() zero_today = datetime.datetime(today.year, today.month, today.day, 0, 0, 0) zero_today = datetime.d...
defc1c8d33c646ffe4afc1e4ed6f5a424c05a611
71,501
import os import time import json import pathlib def api_save(session): """ Saves minerva-author project information in json file. Args: session: unique string identifying save output Returns: OK on success """ if request.method == "POST": data = request.json data = ma...
9901ae137775736c633ed86a6bdd83bb0c9cb208
71,502
async def get_password(email): """Getting user password. """ user = await User.query.where(User.email == email).gino.all() if not user: return False return user[0].password
71819dab9a94b49b7583c22077ae2ca9e02d3282
71,503
def _form_is_rejected(action_name, tracker): """Check if the form got rejected with the most recent action name.""" return ( tracker.get("active_form", {}).get("name") and action_name != tracker["active_form"]["name"] and action_name != ACTION_LISTEN_NAME )
32945962b23a9eb58ab274d5e826419646d09148
71,504
def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0): """KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1). Args: mu: mu parameter of the distribution. log_var: log(var) parameter of the distribution. mu_p: optional mu from a learned prior distribution log_var_p: optional log(var)...
3464a3f66cd2d35a05b887eceddcbf69b21360c7
71,505
from typing import List import tqdm import torch def convert_examples_to_features( examples, tokenizer, max_seq_length, doc_stride, max_query_length, labels_available, symbol_based_hypothesis: bool, padding_strategy="max_length", threads=None, tqdm_enabled=True, ): """ ...
0eb1c986e2ccbe46f7314e62da3b0180636afd83
71,506
def saliency_map(connection, image, mode='heatmap', sigma=8, ax=None, show=True, **kwargs): """ Saliency Map plot. Parameters ---------- connection : network, connection Network based on which will be computed saliency map. image : 3D array-like tensor Image ba...
9d7d8c46908f273bcc7941dc23e9a7833879c831
71,507
import os.path import pandas as pd import tkinter def gather_scripts(extensions=('.py', '.R'), df_documentation='', path='', github_repo_url=''): """ Function::: gather_scripts Description: List scripts in repository and scrape documentation inform...
a8db6632bdeb97786037729781066fcffa70c025
71,508
import hashlib def getB64FileSha256Hash(file: str) -> str: """ Calculate the sha256 hash of a given file and return it in base64 format :param file: The full path to the file :return: base64 string representing the file hash in sha256 """ sha256Hash = hashlib.sha256() with open(file, "rb"...
e0a10e80bc177f81d21353f80d1572785c86a61e
71,509
def format_permissions(permission_bound_field): """ Given a bound field with a queryset of Permission objects, constructs a list of dictionaries for 'objects': 'objects': [ { 'object': name_of_some_content_object, 'add': (add_permission_for_object...
6b4b6f3488af1c5b47d8ae23e0e87d53ac1a925f
71,510
def ADFileTimeToUnix(ad_time): """Converts AD double-wide int format to seconds since the epoch format. Args: ad_time: a 64-bit integer time format used by AD with the number of 100ns intervals since January 1, 1601. Note: cribbed from filetimes.py at http://reliablybroken.com/b/2009/09/ Ret...
dffd259c165ad132b4e3a45f98f37fb053a1fbb5
71,511
def U1Gate(theta): """Auxiliary function for the ``U1Gate``.""" return ex.PhaseGate(theta)
05f35468906375146a354b2fa44b58c3901aa2a2
71,512
import os def puml_component(architecture_file: str, output_directory: str = None) -> PluginExecutionResult: """ Convert an AaC model to Plant UML component diagram. Args: architecture_file: str: Path to a yaml file containing an AaC usecase from which to generate a Plant UML component diagram. ...
200b57bbcc7ef6445b8c10b795d831eeff8b79c6
71,513
from typing import Dict def parser(api_data: Dict, country_codes_translator: CountryCodesTranslator): """ DESCRIPTION: This function paste out daily updates of govtrack data from JSON into DataFrame format. :param api_data: [JSON] non-parsed data. :param country_codes_translator: [CountryCodesTran...
a5688ffdb521e8840f28010e0be30eb902809b10
71,514
def to_bytes(string_to_convert, encoding=None, errors='strict'): """ Given bytes, bytearray, str, or unicode, return bytes """ if encoding is None: # Try utf-8 first, and fall back to detected encoding encoding = ('utf-8', __salt_system_encoding__) if not isinstance(encoding, (tuple,...
224565ba02d0bbbbddf11ddf5f15c9d4b3402271
71,515
def download_song(folder: str, url: str, requester: Member) -> Song: """ Download a video from youtube Return a Song class with the music data """ ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': f'{folder}/%(id)s.%(ext)s', # 'ratelimit': 10240, #limit download rat...
c6bca404a027dd163727ec1db84204445d4760fc
71,516
def captured_sensor(): """Create a captured today ArloSensor.""" data = _get_named_tuple({"captured_today": [0, 0, 0, 0, 0]}) return _get_sensor("Captured Today", "captured_today", data)
9c65386dc10a1e7466aeae1169e9bc3d44723968
71,517
def get_client(fallback=False, fallback_cores=None, fallback_threaded=False, **specs): """Try to connect to an existing Dask scheduler with the supplied specs. Args: specs: Worker resource specifications, eg. cores=10, memory="8GB". The scheduler's cluster will have access to a certain numb...
6b8276be742c31f0c2b480912a3c859b75994a55
71,518
def Unzip(iterable, container=None): """ iterable >> Unzip(container=None) Same as izip(*iterable) but returns iterators for container=None >>> [(1, 2, 3), (4, 5, 6)] >> Unzip(tuple) >> Collect() [(1, 4), (2, 5), (3, 6)] :param iterable iterable: Any iterable, e.g. list, range, ... :para...
86a05b353f5fa27aa17282c79e0441166c856f17
71,519
def get_scores(session, submission_id): """Get the scores for each fold of a submission. Parameters ---------- session : :class:`sqlalchemy.orm.Session` The session to directly perform the operation on the database. submission_id : int The id of the submission. Returns ----...
972774dc572cfd190245329acdff708f7356af26
71,520
def load_npy(npy_fn): """ :param npy_fn: :return: (numpy) raw signal array """ return np.load(npy_fn)[0]
e31567890f515c2bfa36b97859ad85bba205673f
71,521
def samples(): """ Create collection of Samples, useful for mocking a Project. :return Iterable[Sample]: collection of bare bones Sample objects, with only name and protocol defined """ return [ Sample({SAMPLE_NAME_COLNAME: sn, "protocol": p}) for sn, p in PROTOCOL_BY_SAMPLE...
a05de6cdf420a4a456893fb73baa487f4f544b4d
71,522
def build_unet_generator(): """ Create the U-Net Generator using the hyperparameter values defined below """ kernel_size = 4 strides = 2 leakyrelu_alpha = 0.2 upsampling_size = 2 dropout = 0.5 output_channels = 1 input_shape = (256, 256, 1) input_layer = Input(shape=input_sh...
b245cf900554d172f9dc150dab06820c5babdbc3
71,523
def v(n): """compute u value of the lhs matrix""" return ((n ** 2) * (n + 1)) / 2
897f905b04812711841f06599565343d65af013e
71,524
import re def decodeAsOpenSearch(url): """ Decode data hidden inside a url format for searches Parameters: url- the url to decode Returns: a string with the decoded data """ # pattern = 'http://www.baidu.com/s\?wd=(?P<englishText>[a-zA-Z0-9+]+)' pattern = 'http://'+ domain + '/s\?wd=(?P<englishText>[...
4812441bad3496b624a24d1a71117831ce4ba1d8
71,525
import inspect import logging def get_rt( code, _from=None, double_check=False, double_check_threhold=0.005, handler=True ): """ universal fetcher for realtime price of literally everything. :param code: str. 规则同 :func:`get_daily`. 需要注意场外基金和外汇中间价是不支持实时行情的,因为其每日只有一个报价。对于 investing 的数据源,只支持网址格式代码。 ...
59ad4a58acadd694085613a34dc4b82a488e9cca
71,526
def create_fnet(widths, orthoinit, llbias, bnidx=-1): """ Creates feature-generating network, a multi-layer perceptron. Parameters: widths: list of widths of layers (including input and output widths) orthoinit: whether to use orthogonal weight initialization llbias: whether to use bias in the last ...
9ee85e2042fe2d652cb3a73947404ea8b553e2ba
71,527
import torch from typing import OrderedDict def restore_network(net, pt_model, only_backbone=False): """ Restore weight. Full or partial depending on `only_backbone`. """ strict = False if only_backbone else True state_dict = torch.load(pt_model) # create new OrderedDict that does not contain ...
c354a4e7f73586c24195cc05b2e1307ae6022568
71,528
import os import glob import pdb def load_linear_pngs(instr, data_type, label_dict, debug=False, single_copy=False, spit_path=os.getenv('SPIT_DATA'), subset=None, images_only=False): """ Load PNGs Parameters ---------- instr : str Name of instrument, ...
44727f849dbe7e26c674442f97e39b3d1c6baf03
71,529
import argparse def parse_args(): """ Parses command line arguments. """ parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=ARGPARSE_DESCRIPTION) parser.add_argument('--source-csv-filename', dest="source_csv_filename", ...
0f91703b92ceae99ac30cc43f3371b4a6f8cf05e
71,530
def convert_dottable(natural_dict: dict) -> DottableDict: """Convert a dictionary to DottableDict. Args: natural_dict (dict): Dictionary to convert to DottableDict. Returns: DottableDict: Dottable object. """ dottable_dict = DottableDict(natural_dict) for k, v in natural_dict.i...
be3b3ef2be845f149c7820348dc87d20fb9fbdd5
71,531
def create_experiment(args): """ Create a single experiment from arguments. :param args: The parsed arguments. :return: A new experiment with its own trainer. """ experiment_name = get_experiment_name(args) config = build_experiment_config_dict(args) trainer = get_trainer(args=args, conf...
fd0c48f10a6bcb17c12a9f73ede45751c4ed339d
71,532
def _get_song_index(song_id: str) -> int: """ Given a MSD-format song ID, return the corresponding integer index from `msdutils.song_ids`. Can be used to create a vector of the songs each user has and has not listened to -- see `create_user_vector()`. """ return song_ids[song_ids['song...
b121ef3cb7bfd67283a9ab0ba9ba46824b0450a6
71,533
from typing import Tuple from typing import List def make_gear_triangles(height: float, **kwargs) -> Tuple[List[float], List[int]]: """ 歯車の立体形状を生成し、三角形のリストを返す height以外の引数はmake_gear_figureと同じ デフォルトでY軸が歯車の高さに対応するが、height_axisオプション(値はx,y,zから選択)で変更可能 :param height: 歯車の高さ :return: (vertices, indice...
dfabfe9da1e0074e9214605ced4afd0f5550fa84
71,534
def multivariate_normal(mean, cov, size=None, check_valid='ignore', tol=1e-8, dtype=float): """(experimental) Multivariate normal distribution. Returns an array of samples drawn from the multivariate normal distribution. Its probability density function is defined as .. math:: ...
efa1f8593777b308a5ef6ae7c1c0ddcb72d8b06b
71,535
def white_tophat(input, size = None, footprint = None, structure = None, output = None, mode = "reflect", cval = 0.0, origin = 0): """Multi-dimensional white tophat filter. Either a size or a footprint, or the structure must be provided. An output array can optionally be provided. The orig...
aebabf9819d32e3f9b324f9ecdaf47adc2bcf13c
71,536
def svn_wc_create_conflict_result(*args): """ svn_wc_create_conflict_result(svn_wc_conflict_choice_t choice, char merged_file, apr_pool_t pool) -> svn_wc_conflict_result_t """ return apply(_wc.svn_wc_create_conflict_result, args)
4220a1e1109fbb2658f655305816df8343e74e40
71,537
import math def is_prime(num): """ check whether a number is a prime :param num: :return: """ if num % 2 == 0 and num > 2: return False for i in range(3, int(math.sqrt(num))+1, 2): if num % i == 0: return False return True
ee2d52833a8f4f3ce29ff64be4ad94ba8b119214
71,538
def create_many_particle_state(imsize=None, N=None, phi=None, radius=5.0, polydispersity=0.0, seed=None, **kwargs): """ Creates a random packing of spheres and generates the state. In order to specify the state, either (phi, imsize) or (N, phi) or (N, imsize) must be given. Any more than that an...
245c4a770a6ca0f2452413fa08c167ad7b1ed5fa
71,539
def sxc2(plot, *args, **kwargs): """scale_x_continuous(trans='log2',...)""" if not "trans" in kwargs: kwargs["trans"] = "log2" return plot + p9.scale_x_continuous(*args, **kwargs)
1983d88d45487e40459309d2c7480ae157930581
71,540
def ratio_cap_letters(email): #def ratio_cap_letters(sent_list): # for testing """ calculates the ratio of upper case letters except for at the beginning of the sentence # percentage = a/(b-c) # a: total contiguously capitalized letters NOT at the beginning of sentence # b: total letters # c: ca...
3342c0106f69d201d707299eb76e0f37eab02f9e
71,541
def pick_highest(board): """ :param board: The current gamestate :return: The move with the highest rating """ options = get_possibilities(board, Player.COMPUTER.value) scores = [evaluate(x[0]) for x in options] return options[scores.index(max(scores))][1]
3b904ec461b6ab70dd0a189e579a352b24b3878e
71,542
from typing import Callable from typing import Optional def forced_exit_message(callback: Callable[[HWND], Optional[bool]]) -> MessageEntry: """Listens for a window that should be forced to exit.""" return True, windows_constants.HSHELL_ENDTASK, _window_handle_callback(callback),
2fa398f9b690979c1d63fe77981b4b9d37b8191c
71,543
import sqlite3 def import_sqlite3(sql_file, separator): """Read sqlite db""" conn = sqlite3.connect(sql_file) conn.row_factory = sqlite3.Row cursor = conn.cursor() data = [] for row in cursor.execute('SELECT * FROM items'): row = import_data(row, separator) if row != None: ...
95f74e4a67704227a349d91dadada33c24691aed
71,544
from typing import Optional def is_boolean_type(property_schema: dict) -> Optional[bool]: """Return true if the JSON Schema type is a boolean or None if detection fails.""" if "anyOf" not in property_schema and "type" not in property_schema: return None # Could not detect data type for property_t...
c092ab064139bf8bb92e59afae9829eb9bf5e6c2
71,545
def change_angle_origin(angles, max_positive_angle): """ Angles in DICOM are all positive values, but there is typically no mechanical continuity in across 180 degrees :param angles: angles to be converted :type angles list :param max_positive_angle: the maximum positive angle, angles greater than t...
4a8b7d14719034cec659deaa257b53f9a7a79bb5
71,546
def greedy_set_cover(universe, subsets, costs): """Approximate greedy algorithm for set-covering. Can be used on large inputs - though not an optimal solution. Args: universe (list): Universe of elements subsets (dict): Subsets of U {S1:elements,S2:elements} costs (dict): Costs of e...
aef8aa0b345d5ba01db841bdfb6485661d245d5d
71,547
def get_classmap(samples): """Get {location: classIdx} mapping""" def parser(info, networks): return info['__location'] locations = list(parse_samples(samples, parser)) return {location: i for i, location in enumerate(sorted(set(locations)))}
2d79d37dceba0502cd6d13f274bd3984336a1d1d
71,548
def tokenize_guitarset_example( ds: tf.data.Dataset, spectrogram_config: spectrograms.SpectrogramConfig, codec: event_codec.Codec, is_training_data: bool, onsets_only: bool, include_ties: bool ) -> tf.data.Dataset: """Tokenize a GuitarSet transcription example.""" def _preprocess_example(ex, name): ...
e140fc47069cda39614905299ba49e064b363cd6
71,549
def _pascal_triangle_map(size: int) -> np.ndarray: """Array representation of pascal's triangle, centered Args: size (int): width and height of the triangle Returns: Numpy array containing centered pascal's triangle. The numbers are repeated four times in squares and the squares ar...
a48bf9a9eee6982acbce520b0269abed0fcfb529
71,550
def relabel(labels): """Relabel the cluster labels so that they appear in order """ labels = labels.copy() d = {} k = 0 for i in range(len(labels)): j = labels[i] if j not in d: d[j] = k k += 1 labels[i] = d[j] return labels
8407d569252af82d112edfb1391ec323903cd457
71,551
def dumps(): """Convert to a Json string everything we have in this system.""" return json_lib.dumps(dump(), separators=(',', ':'))
7b66245f71268e5a094d0b6cb8696f095d3d00b4
71,552
def dict_to_ions(idict): """ Manipulate dict into an ion astropy Table Will likely be deprecated Parameters ---------- idict : dict Returns ------- table : astropy.Table """ # Could probably use add_row or dict instantiation table = None for ion in idict.keys(): ...
e262f3601e1a80689cbaaed3ada257f571b9f438
71,553
def hunderline(*content, sep=" "): """ Make underlined text (HTML) :param content: :param sep: :return: """ return html_decoration.underline(value=html_decoration.quote(_join(*content, sep=sep)))
44f286ebd7eebab94eea0db5d4178ad6599ccad4
71,554
def encoded_jwt_expired(claims, kid, rsa_private_key): """ Return an example JWT that has already expired. Args: claims (dict): fixture kid (str): fixture rsa_private_key (str): fixture Return: str: JWT containing claims encoded with private key """ headers = {...
f495d66f0c29c824a378fcae3d14be71fc64916a
71,555
import typing def get_required_intents_for(event_type: typing.Type[Event]) -> typing.Collection[intents.Intents]: """Retrieve the intents that are required to listen to an event type. Parameters ---------- event_type : typing.Type[Event] The event type to get required intents for. Return...
beeffe5425f0190c986ee870e23b6c2efe4d548f
71,556
def transform_dictQPV(Dinit, index_param, percent=0, index=0, global_test=False): """ Transform a specific value of Threshold dictionary. A sorting condition should be respected : q < p < v. :param Dinit: Dictionary containing the dictionary which should be modified. In form of a list of dictionarie...
3935ca58e0f030820319af3df48a9c0ebb0f81bd
71,557
import os def is_writable(location): """ Return True if the file at location has writeable permission set. Does not follow links. """ if location: if is_dir(location): return os.access(location, os.R_OK | os.W_OK | os.X_OK) else: return os.access(location, o...
be995d792ba72130b9d842b977033978b8cabd4f
71,558
import re def setup_controls(joystick): """ Joystick wrapper. """ if re.search('playstation', joystick.get_name(), re.I): return Ps3Controller(joystick) elif re.search('X-box', joystick.get_name(), re.I): return XboxController(joystick) elif re.search('Saitek', joystick.get_name(), re.I): return MySaite...
e172df6a46ab833468431eba6d54d539dbe56db9
71,559
def read_homography_calibrator_params(): """ Reads the homography calibrator parameters file """ return read_yaml_file(homography_calibrator_params_file)
35db1223aa596d63c444893aa249b297e79681a9
71,560
from pathlib import Path import re def get_vara_status(llvm_folder: Path) -> GitStatus: """Retrieve the git status of VaRA.""" try: with local.cwd(llvm_folder / LLVMProjects.vara.path): fetch_remote('origin') git_status = git['status'] stdout = git_status('-sb') ...
06d7e653e9b9676101fd8934977a5cdfcbfb5b75
71,561
def get_chunks(): """ Get the hosts of the content and index chunks assigned to an index server :return: List of dictionary of hosts, empty list if no chunks assigned """ # requester = request.remote_addr requester = request.get_json()['host'] # Get all index servers for requester resul...
78887610bc796a3e0ae6cb5d1e220d592b33d019
71,562
from typing import List from typing import Dict from typing import Any def create_service_color_instances(tasks: List[EcsTask], port: int) -> List[Dict[str, Any]]: """Create the instances for the service-colors""" return [ { 'ipv4': task.host_ipv4, 'port': port, } ...
5aded8db5716796a55b75b82cbffd4ffaf189c12
71,563
from typing import List from typing import Optional def find_story_conflicts( trackers: List[TrackerWithCachedStates], domain: Domain, max_history: Optional[int] = None, ) -> List[StoryConflict]: """Generates `StoryConflict` objects, describing conflicts in the given trackers. Args: track...
d0ca7385dd4d407e1a0c485a4ae2d72d3c75db61
71,564
def scan_markdown_content_for_all_paths(content: str): """ Search a markdown formatted content string for links and return a set of file links Search for all links and build set of those links where the link is not a link to a 'https:\\' address, and then return the set of local file links. The return...
dc5a51a4a66e0bbc08516882891271ed24fa293e
71,565
def _is_sparse_variable(x): """ Returns ------- boolean True iff x is a L{SparseVariable} (and not a L{TensorType}, for instance). """ if not isinstance(x, Variable): raise NotImplementedError( "this function should only be called on " "*variable...
fea0729919b21769c32138b11bb0ae2688435c63
71,566
def recon(W, v, proj, mask, bounds, iters, stop, fp): """ Intermediate function that checks whether or not CUDA is present before calling the main reconstruction routine. If CUDA is not present then pre-computed results are loaded. I would recommend to use recon_iter() if you want to implement this ...
59a1b2abb1be6ba47a4688f8880e9f2ce0791725
71,567
def test_function_arbitrary_arguments(): """ Arbitrary Argument Lists @see: https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists Functions can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple. Before the variable number of argum...
45394f82a40ae1e42b9b5cf31bee9346de06e28e
71,568
def from_ecdf(diff_data, n, seed=1): """ Parameters ---------- diff_data : netcdf4 dataset containing waiting times as peak differences. n : int number of nodes. Returns ------- array of waiting times with lentgh n. """ inter_diffs = diff_data['diffs_v2'][2...
916c820a821fc95a5b588a8ed3a1d6de208e4ff1
71,569
def load(export_dir, obj_template): """Load a nested structure from export_dir. Args: export_dir: The directory to load from. obj_template: An object that provides the nested structure to mimic. Returns: Loaded nested structure. Raises: FileNotFoundError: No such file or directory. """ i...
e227da8c858beec570792fe68a9f604a2e6fda64
71,570
def load_CIFAR10_small_data(cifar10_dir, save_folder = 'data', classes=None): """ loads a subset of CIFAR10 classes """ if classes is None: classes = np.array([0,1,2]) classes_string = '' #else: classes_string = '_' + '_'.join([str(x) for x in np.sort(classes).tolist()]) # create ...
f0f64a6d15ff4ed9c7c84e8a8687b708da51b1f7
71,571
def TempC500mb(tempc, pres): """Temperature in Celsius at 500 mb INPUTS: Temperature profile from sounding - tempc (C) Pressure profile from sounding pres (hPa) OUTPUTS: Temp(C) Source: http://weather.uwyo.edu/upperair/indices.html Prints a warning if a pressure value below 2000 Pa input...
3f7487bf92ee15d05addc996e44b1ff55b57d5fc
71,572
import numpy def transform_to_p1(points_abc, sym_elems, shift, centrosymmetry, indexes_xyz, densities): """Transoform indexes_xyz and densities to P1 space group. Parameters ---------- points_abc : numpy.int [6] DESCRIPTION. sym_elems : numpy.int [13, n_sym_elems]...
387ef51b2bc798a583b3665e12a3be38edb5e285
71,573
def _pilot_state_progress(pid, current, target): """ See documentation of 'unit_state_progress' below. """ # first handle final state corrections if current == CANCELED: if target in [DONE, FAILED, CANCELED]: return[target, []] # allow to transition from FAILED to DONE (don...
0535490ac15eae6e9250884d1566885a2f13ae92
71,574
def bounding_rect(mask, pad=0): """Returns (r, b, l, r) boundaries so that all nonzero pixels in mask have locations (i, j) with t <= i < b, and l <= j < r.""" nz = mask.nonzero() if len(nz[0]) == 0: # print('no pixels') return (0, mask.shape[0], 0, mask.shape[1]) (t, b), (l, r) = [...
850db378abb0a8e1675e0937b66dfb4061ced50b
71,575
def block_diagonal(dirichl_space, neumann_space, A): """ Compute the block-diagonal preconditioner for system matrix A. Suitable for direct formulation. """ ep_in = PARAMS.ep_in ep_ex = PARAMS.ep_ex kappa = PARAMS.kappa identity = sparse.identity(dirichl_space, dirichl_space, dirichl_sp...
1838df20aed14c38ecb2e1f157683137a6a3a409
71,576
import os def api_key_gen(): """ Generates 16 character random hex to be used as key :return: a new api key for the user """ return hexlify(os.urandom(8)).decode('ascii')
8051ef6dfc89f197d9d3e3cfee6458b41a2de811
71,577
import torch def process_pair(data, global_labels): """ :param path: graph pair data. :return data: Dictionary with data, also containing processed DGL graphs. """ edges_1 = data["graph_1"] + [[y, x] for x, y in data["graph_1"]] edges_2 = data["graph_2"] + [[y, x] for x, y in data["graph_2"]]...
a4547e0fb772a9eeb9d40572176d95f8a9342f74
71,578
def chat(): """Chat room. The user's name and room must be stored in the session.""" name = session.get('name', '') log('/chat request', request) if name == '': return redirect(url_for('.index')) return render_template('chat.html')
6128a51554e6c363fa44d5ae084c2951066f0ee6
71,579
from .__temp_model_builder import build_fn as temp_build_fn def keras_prep_workflow(model_initializer, build_fn, extra_params, source_script): """Conduct preparation steps necessary before hyperparameter optimization on a `Keras` model. Such steps include parsing and modifying `build_fn` to be of the form use...
78e9ef5778a132f0c713dd04b3cc6eda97d5d183
71,580
def telemetry(fn): """Decorate CLI and other functions that need special Sentry client handling. This decorator is only required on functions that: 1) Specifically catch and re-raise exceptions. 2) Call sys.exit() directly. """ @wraps(fn) def telemetry_wrapper(*args, **kwargs): ...
d1bc298c02a4b8d096c3af8826065e9b247d680c
71,581
from typing import Tuple def _get_average_buy_units_sold( operations_by_type: OperationsByType ) -> Tuple[OperationIterable, OperationIterable]: """Gets list of operations that were sold using average method. Args: operations_by_type: Operations by type. Raises: ValueError: sold more units than we...
97210ea3bf842ff657ff3d0749ebf8196a2a130d
71,582
from os.path import isfile def isFile(path: str): """ Check whether path points to a file """ return isfile(path)
44808693af570ebe18526830c96276522e5ad4ff
71,583
import csv def get_return_fields(filepath): """Extract the returnable fields for results from the file with description of filters in ENA as a dictionary with the key being the field id and the value a list of returnable fields filepath: path with csv with filter description """ returnable_fi...
d70efe68de8cbd100b66cee58baf6ca542cb81a8
71,584
import json def get_config_from_json(json_file): """ Get the config from a json file :param json_file: :return: config(namespace) or config(dictionary) """ # parse the configuration file with open(json_file, "r") as config_file: config_dict = json.load(config_file) # convert t...
5a2e22a4edfd8411500ee1a381bc2682df71fd40
71,585
def create_headers(type, code, length, conn): """ This function creates the headers needed to send a correct HTTP response to the client. The content of the headers depends on the generated output code, the type and length of the content we send back and whether or not we close the TCP connection. ...
68b54bea8417cd875f40568cf2743fc5c58e9dae
71,586
def filter_convergence(x, zx, lens_efficiency, cosmology): """Filter for convergence. This function computes the filter for the convergenge power spectra, described in [1]_. Parameters ---------- x: (nx,) array_like Array of comoving distances at which evaluate the lensing effic...
0d00135d49e59eeadbffaf7be6056238b10fa455
71,587
def GenerateMLNetWrapper(function, output_name): """ The starting to create the C# Files. It takes in a function from the function list and builds all the output based on that. """ # should be fine to have constant required_namespaces = ["Microsoft.ML", "Microsoft.ML.Data", "Microsoft....
d5d1e80e6ef778996ecc1913abf65396ef43bcf9
71,588
def check_flacs(flacs): """ Check if the given flacs are suitable for transcoding. :param flacs: A `list` of `mutagen.flac.FLAC` objects. :returns: A string containing a description of the problem if there was one, or `None` if no problems were detected. """ if any(flac.info.chan...
3004ef891fb6d7b1b20ba40009448b99e08c3784
71,589
def cov_eig_kl(m, y, k=None): """computes similarity of x, y covariance matrices""" s1, s2 = get_svd(m, y) if k is not None: s1, s2 = s1[:k] - s2[:k] d = F.kl_div(F.softmax(s1) - F.softmax(s2)) return d
8a465043b6173ab337eabe119f55023cdbe2bab2
71,590
def generic_sum(algorithm): """compute digest based on algorithm passed in parameter :param algorithm: hashlib algorithm to use :return: digest returned by the algorithm """ def hash_sum(fileobj): """compute digest by chunks multiple of the block_size :param fileobj: Open file(-l...
5f3f3e00b9a1878d416491a06453cfeed4e0884c
71,591
def load_as_dataset(relative_path, version=iati.version.STANDARD_VERSION_ANY): """Load a specified test data file as a Dataset. Args: relative_path (str): The path of the file, relative to the root test data folder. Folders should be separated by a forward-slash (`/`). version (str): The versio...
31f97575a2ebd50a4b3cf9583ea238dea7293840
71,592
def solid_angle(ra_lim, dec_lim): """ Calculate solid angle with given ra & dec range. All angles in degrees. Parameters ---------- ra_lim : list-like, optional ra limits. dec_lim : list-like, optional dec limits. Returns ------- area : float Solid angle ...
477ed7fac6ce65e45cba5b6f1334f9554ac5064c
71,593
def plot_lor_fit(data, skew=1, full=1, plt=plt): """Fits a Lorentzian function to a dataset and plot the result. 'data' is a data array with elements [x-axis data,y-axis data]; 'skew' is 1 (default) to subtract a linear background, and 0 to use no slope; 'full' is 1 (default) to fit the whole datas...
55d6f9688f5c8b9cf3bcd85db6e762e0e196a5cb
71,594
def jacobian(x, *args): """Calculates jacobian of log-linear model.""" data, n_features, lambda_, datapath, verbose, store_intermediate, weights_fname = args empirical_counts = np.zeros(shape=n_features) expected_counts = np.zeros(shape=n_features) transformed = data for feat_dict in transfo...
382500f421eca01b64b6e5d7fb71158e5cd7a42a
71,595
def parse(data, raw=False, quiet=False): """ Main text parsing function Parameters: data: (string) text data to parse raw: (boolean) output preprocessed JSON if True quiet: (boolean) suppress warning messages if True Returns: List of Dictionaries...
e4d980ac8ecd147bf530651cf9ef08f5af7aecd5
71,596
def index(): """ Student index * list available activities (GET) - along with information about them (also how many spaces available) """ chosen_activity = student_chosen_activity() activities = [] for activity in dict_sql_query("SELECT * FROM activities"): activities.appe...
fda2591ce06e653ce19d68a4f56fdbadd78dee55
71,597
def Phi_batch(X, theta, MSE_reduction, W_1, W_2): """ Computes MSE-loss for batch X containing N samples (rows) by averaging or summing the individual sample losses. """ N = X.shape[0] # Accumulate loss over all batches loss_batch = 0.0 for n in range(N): x = X[n, :].reshape(1,...
19045d73507f06ac2ecbb3f206f3b8d17a222638
71,598
import os def read(fname): """ Utility function to read the README file. :rtype : String """ return open(os.path.join(os.path.dirname(__file__), fname)).read()
c0e4a775f42b03c1c10083389d6a0b11fe88ad8d
71,599