content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def separable_hnn(num_points, input_h_s=None, input_model=None, save_path='temp_save_path', train=True, epoch_save=100): """ Separable Hamiltonian network. :return: """ if input_h_s: h_s = input_h_s model = input_model else: h_s = HNN1DWaveSeparable(nn....
c9912f69b4367a2ed83ce367970551f31e0cb087
28,671
def get_n_largest(n, lst, to_compare=lambda x: x): """ This returns largest n elements from list in descending order """ largests = [lst[0]]*n # this will be in descending order for x in lst[1:]: if to_compare(x) <= to_compare(largests[-1]): continue else: fo...
4ef85d8656ae152ecab65d3a01bce7f885c47577
28,672
from natsort import natsorted import collections from typing import Optional from typing import Union def base_scatter( x: Optional[Union[np.ndarray, list]], y: Optional[Union[np.ndarray, list]], hue: Optional[Union[np.ndarray, list]] = None, ax=None, title: str = None, ...
72e159af3ffad86e66b53789368edbb3a7bc406a
28,673
def lambda_sum_largest_canon(expr, real_args, imag_args, real2imag): """Canonicalize nuclear norm with Hermitian matrix input. """ # Divide by two because each eigenvalue is repeated twice. real, imag = hermitian_canon(expr, real_args, imag_args, real2imag) real.k *= 2 if imag_args[0] is not Non...
41e2d460fc5d18d65e1d7227093ecaf88a925151
28,674
def dp_palindrome_length(dp, S, i, j): """ Recursive function for finding the length of the longest palindromic sequence in a string This is the algorithm covered in the lecture It uses memoization to improve performance, dp "dynamic programming" is a Python dict containing previously computed values ...
10a8ac671674ba1ef57cd473413211a339f94e62
28,675
def ellip_enclose(points, color, inc=1, lw=2, nst=2): """ Plot the minimum ellipse around a set of points. Based on: https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py """ def eigsorted(cov): vals, vecs = np.linalg.eigh(cov) order = vals.argsort()[::-1...
c6f3fabfb306f29c5c09ffee732d5afea2c1fe33
28,676
def catalog_dictionary_per_observation(cats, obs_nums, targets, defaults): """Translate a dictionary of catalogs from a case of either: 1. Separate catalogs for each target name 2. Separate catalogs for each target name and instrument into a dictionary of catalogs for each instrument and observation ...
b418e0315b242c251d6796636fdd3fdbcfefbfa5
28,677
def sierpinkspi(p1, p2, p3, degree, draw, image, colors): """ Draw Sierpinksi Triangles. """ colour = colors draw.polygon(((p1[0], p1[1]), (p2[0], p2[1]), (p3[0], p3[1])), fill=colour[degree]) if degree > 0: sierpinkspi(p1, mid(p1, p2), mid(p1, p3), degree-1, draw, image, colors) ...
c43662d50a655eed4298e34d2f9830e678a0ca96
28,678
def generate_depth_map(camera, Xw, shape): """Render pointcloud on image. Parameters ---------- camera: Camera Camera object with appropriately set extrinsics wrt world. Xw: np.ndarray (N x 3) 3D point cloud (x, y, z) in the world coordinate. shape: np.ndarray (H, W) O...
f219d2128bdecf56e8e03aef7d6249b518d55f06
28,679
def create_own_child_column(X): """ Replaces the column 'relationship' with a binary one called own-child """ new_column = X['relationship'] == 'own-child' X_transformed = X.assign(own_child=new_column) X_transformed = X_transformed.drop('relationship', axis=1) return X_transformed
303ec8f073920f0bba6704740b200c7f3306b7bd
28,681
def find_next_gate(wires, op_list): """Given a list of operations, finds the next operation that acts on at least one of the same set of wires, if present. Args: wires (Wires): A set of wires acted on by a quantum operation. op_list (list[Operation]): A list of operations that are implement...
287a3b2905f86dff0c75027bcba6bd00bab82fd8
28,682
def FDilatedConv1d(xC, xP, nnModule): """1D DILATED CAUSAL CONVOLUTION""" convC = nnModule.convC # current convP = nnModule.convP # previous output = F.conv1d(xC, convC.weight, convC.bias) + \ F.conv1d(xP, convP.weight, convP.bias) return output
900065f6618f1b4c12191b1363ce6706ec28d222
28,683
def load_spans(file): """ Loads the predicted spans """ article_id, span_interval = ([], []) with open(file, 'r', encoding='utf-8') as f: for line in f.readlines(): art_id, span_begin, span_end = [int(x) for x in line.rstrip().split('\t')] span_interval.append((span_b...
8f8de31e1d1df7f0d2a44d8f8db7f846750bd89f
28,684
def is_stupid_header_row(row): """returns true if we believe row is what the EPN-TAP people used as section separators in the columns table. That is: the text is red:-) """ try: perhaps_p = row.contents[0].contents[0] perhaps_span = perhaps_p.contents[0] if perhaps_span.get("style")=='color: rgb(...
124108520486c020d2da64a8eb6f5d266990ae02
28,685
def get_cli_parser() -> ArgumentParser: """Return an ArgumentParser instance.""" parser = ArgumentParser(description="CLI options for Alice and Bob key share") parser.add_argument('-p', help='Prime p for information exchange', type=int) parser.add_argument('-g', help='Prime g for information exchange', ...
2ca9feff2940064163d8b5724b647ab56f4ea5e6
28,686
import re def _get_http_and_https_proxy_ip(creds): """ Get the http and https proxy ip. Args: creds (dict): Credential information according to the dut inventory """ return (re.findall(r'[0-9]+(?:\.[0-9]+){3}', creds.get('proxy_env', {}).get('http_proxy', ''))[0], re...
b18d89718456830bdb186b3b1e120f4ae7c673c7
28,687
def geometric_expval(p): """ Expected value of geometric distribution. """ return 1. / p
3afb3adb7e9dafa03026f22074dfcc1f81c58ac8
28,689
def make_ticc_dataset( clusters=(0, 1, 0), n_dim=3, w_size=5, break_points=None, n_samples=200, n_dim_lat=0, sparsity_inv_matrix=0.5, T=9, rand_seed=None, **kwargs): """Generate data as the TICC method. Library implementation of `generate_synthetic_data.py`, original can be found at...
7c77d5ea4ff9e87681b0494333c49e24360b7072
28,690
from dustmaps import sfd from dustmaps import planck def get_dustmap(sourcemap, useweb=False): """ get the dustmap (from the dustmaps package) of the given source. Parameters --------- sourcemap: [string] origin of the MW extinction information. currently implemented: planck, sfd ...
a5daec02601c968d25942afe1577ad301bbb6a55
28,692
def make_retro_pulse(x, y, z, zenith, azimuth): """Retro pulses originate from a DOM with an (x, y, z) coordinate and (potentially) a zenith and azimuth orientation (though for now the latter are ignored). """ pulse = I3CLSimFlasherPulse() pulse.type = I3CLSimFlasherPulse.FlasherPulseType.retro...
de6fa8905276122c501b5a80842a12abfa2a81f1
28,693
def shiftLeft(col, numBits): """Shift the given value numBits left. >>> spark.createDataFrame([(21,)], ['a']).select(shiftLeft('a', 1).alias('r')).collect() [Row(r=42)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.shiftLeft(_to_java_column(col), numBits))
769cbcb4f66473bdeb789c1326aa58e763c4f320
28,694
def lerp(x0: float, x1: float, p: float) -> float: """ Interplates linearly between two values such that when p=0 the interpolated value is x0 and at p=1 it's x1 """ return (1 - p) * x0 + p * x1
c4114dcb5636e70b30cd72a6e7ceab1cd683fa8d
28,695
def discard_events(library, session, event_type, mechanism): """Discards event occurrences for specified event types and mechanisms in a session. Corresponds to viDiscardEvents function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier t...
72010fae64bb0a1e615ce859d150f7f24f2c7171
28,696
def getSpeed(spindle=0): """Gets the interpreter's speed setting for the specified spindle. Args: spindle (int, optional) : The number of the spindle to get the speed of. If ``spindle`` is not specified spindle 0 is assumed. Returns: float: The interpreter speed setting, with a...
a7c759ff91c079aacd77d7aa0141f42aa9ca60af
28,697
def appointment() -> any: """ Defines route to appointment booking page. :return: String of HTML template for appointment booking page or homepage if booking was successful. """ if request.method == 'POST': user_input = request.form.to_dict() try: request_is_valid(request...
5c55c0387300f21cfea45809bdf534ace4137fc6
28,698
def wait_for_task(task, actionName='job', hideResult=False): """ Waits and provides updates on a vSphere task """ while task.info.state == vim.TaskInfo.State.running: time.sleep(2) if task.info.state == vim.TaskInfo.State.success: if task.info.result is not None and not hideResult:...
c750238117579236b159bf2389e947e08c8af979
28,700
def _get_candidate_names(): """Common setup sequence for all user-callable interfaces.""" global _name_sequence if _name_sequence is None: _once_lock.acquire() try: if _name_sequence is None: _name_sequence = _RandomNameSequence() finally: _on...
bc42c4af0822fcaa419047644e9d4b9d064a42fd
28,701
def relative_difference(x: np.array, y: np.array) -> np.array: """ Returns the relative difference estimator for two Lagrange multipliers. """ maximum = np.max([x, y]) minimum = np.min([x, y]) difference = maximum-minimum return np.abs(difference) / np.max(np.abs([x, y, difference, 1.]))
6b169a3deb3f6ed91958744521aa8028451fb3d8
28,702
def ConvertPngToYuvBarcodes(input_directory='.', output_directory='.'): """Converts PNG barcodes to YUV barcode images. This function reads all the PNG files from the input directory which are in the format frame_xxxx.png, where xxxx is the number of the frame, starting from 0000. The frames should be consecut...
43cc0dd4126b0699212064e445608c82123ad7b9
28,703
from pathlib import Path def _ignore_on_copy(directory, contents): # pylint: disable=unused-argument """Provides list of items to be ignored. Args: directory (Path): The path to the current directory. contents (list): A list of files in the current directory. Returns: list: A li...
3a551f6a252406b88fb19c0dc8180631cd5996ce
28,704
def registDeptUser(request): """ ํ™ˆํƒ์Šค ํ˜„๊ธˆ์˜์ˆ˜์ฆ ๋ถ€์„œ์‚ฌ์šฉ์ž ๊ณ„์ •์„ ๋“ฑ๋กํ•ฉ๋‹ˆ๋‹ค. - https://docs.popbill.com/htcashbill/python/api#RegistDeptUser """ try: # ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ CorpNum = settings.testCorpNum # ํ™ˆํƒ์Šค ๋ถ€์„œ์‚ฌ์šฉ์ž ๊ณ„์ •์•„์ด๋”” DeptUserID = "deptuserid" # ํ™ˆํƒ์Šค ๋ถ€์„œ์‚ฌ์šฉ์ž ๊ณ„์ •๋น„๋ฐ€๋ฒˆํ˜ธ DeptUserPW...
e5f923ac4290fd029eafdf6e408d7847be9d0c6b
28,705
import torch def generate_fake_data_loader(): """" Generate fake-DataLoader with four batches, i.e. a list with sub-lists of samples and labels. It has four batches with three samples each. """ samples1 = torch.tensor([[2., 2., 2., 2.], [2., 2., 0., 0.], [0., 0., 2., 2.]]) samples2 = torch.tensor([[1....
4d86ab464653f5766a44f03e41fd2c26714cabf1
28,709
def get_RV_K( P_days, mp_Mearth, Ms_Msun, ecc=0.0, inc_deg=90.0, nsamples=10000, percs=[50, 16, 84], return_samples=False, plot=False, ): """Compute the RV semiamplitude in m/s via Monte Carlo P_days : tuple median and 1-sigma error mp_Mearth : tuple media...
11cdb7bfeef27d5a05638d74232e105a22fa0222
28,711
def arc(color, start_angle, stop_angle, width, height, x=None, y=None, thickness=1, anchor='center', **kwargs): """ Function to make an arc. :param color: color to draw arc :type color: str or List[str] :param start_angle: angle to start drawing arc at :type start_angle: int :param ...
42c0a53632315ff03b92c53cbc172a0cfd08f5a7
28,712
def calculate_shapley_value(g, prob_vals, maxIter=20000): """ This algorithm is based on page 29 of the following paper: https://arxiv.org/ftp/arxiv/papers/1402/1402.0567.pdf :param g: the graph :param prob_vals: a list. it contains the weight of each node in the graph :param maxIter: maximum ...
41329a17f0914597bcf457ea04e9dc0a7053ae62
28,713
from typing import List from typing import Dict from typing import Any async def complete_multipart_upload(bucket: str, s3_key: str, parts: List, upload_id: str) -> Dict[str, Any]: """Complete multipart upload to s3. Args: bucket (str): s3 bucket s3_key (str): s3 prefix parts (List): ...
01441cbc196f594bead4dd9a9b17fe1a3c8bfa4d
28,714
def build_mask(module='A', pixscale=0.03): """Create coronagraphic mask image Return a truncated image of the full coronagraphic mask layout for a given module. +V3 is up, and +V2 is to the left. """ if module=='A': names = ['MASK210R', 'MASK335R', 'MASK430R', 'MASKSWB', 'MASKLWB'] ...
97e068fe8eef6e8fdd65b1e426428001cf549332
28,715
async def update_login_me( *, password: str = Body(...), new_email: tp.Optional[EmailStr] = Body(None, alias='newEmail'), new_password: tp.Optional[str] = Body(None, alias='newPassword'), current_user: models.User = Depends(common.get_current_user), uow: IUnitOfWork = Depends(common.get_uow), ) ...
ec3f56ee474d19a4fd89c51940f3a198322672a1
28,716
def comp_sharpness(is_stationary, signal, fs, method='din', skip=0): """ Acoustic sharpness calculation according to different methods: Aures, Von Bismarck, DIN 45692, Fastl Parameters: ---------- is_stationary: boolean True if the signal is stationary, false if it is time varying ...
a8ae39740c90e824081e3979d5ff2b5c96a8ad75
28,717
def load_hobbies(path='data', extract=True): """ Downloads the 'hobbies' dataset, saving it to the output path specified and returns the data. """ # name of the dataset name = 'hobbies' data = _load_file_data(name, path, extract) return data
e60e024d0fe1766c599a3b693f51522cb7d7303a
28,718
def is_viable(individual): """ evaluate.evaluate() will set an individual's fitness to NaN and the attributes `is_viable` to False, and will assign any exception triggered during the individuals evaluation to `exception`. This just checks the individual's `is_viable`; if it doesn't have one, this a...
c1e5c839f362e99800dcd1a996be9345cabb4261
28,719
def combine_counts(hits1, hits2, multipliers=None, total_reads=0, unmatched_1="Unknown", unmatched_2="Unknown", ): """ compile counts into nested dicts """ total_counted = 0 counts = {} # ke...
505e91f6538267e40f438926df201cf25cb1a3f9
28,720
def root(): """Serves the website home page""" return render_template("index.html")
676c966da523108bd9802c2247cf320993815124
28,721
import string import random def getCookie(): """ This function will return a randomly generated cookie :return: A cookie """ lettersAndDigits = string.ascii_lowercase + string.digits cookie = 'JSESSIONID=' cookie += ''.join(random.choice(lettersAndDigits) for ch in range(31)) return co...
6fff76d37921174030fdaf9d4cb8a39222c8906c
28,722
def get_authenticated_igramscraper(username: str, password: str): """Gets an authenticated igramscraper Instagram client instance.""" client = Instagram() client.with_credentials(username, password) #client.login(two_step_verificator=True) client.login(two_step_verificator=False) return client
c8f7cf4500aa82f11cf1b27a161d75a7261ee84a
28,723
def read_in_nn_path(path): """ Read in NN from a specified path """ tmp = np.load(path) w_array_0 = tmp["w_array_0"] w_array_1 = tmp["w_array_1"] w_array_2 = tmp["w_array_2"] b_array_0 = tmp["b_array_0"] b_array_1 = tmp["b_array_1"] b_array_2 = tmp["b_array_2"] x_min = tmp["x...
3f2366ab9fd4b4625c8b7d00b1191429678b466b
28,724
def crop_zeros(array, remain=0, return_bound=False): """ Crop the edge zero of the input array. Parameters ---------- array : numpy.ndarray 2D numpy array. remain : int The number of edges of all zeros which you want to remain. return_bound : str or bool Select the m...
13cb5a0a289ef622d3dd663777e6a0d2814b5104
28,725
def go_info_running(data, info_name, arguments): """Returns "1" if go is running, otherwise "0".""" return '1' if 'modifier' in hooks else '0'
8027d0106e379156225c87db1959110fcfac6777
28,726
def letra_mas_comun(cadena: str) -> str: """ Letra Parรกmetros: cadena (str): La cadena en la que se quiere saber cuรกl es la letra mรกs comรบn Retorno: str: La letra mรกs comรบn en la cadena que ingresa como parรกmetro, si son dos es la letra alfabรฉticamente posterior. """ letras_e...
c36a753717365164ca8c3089b398d9b6e358ef3f
28,727
def dwt2(image, wavelet, mode="symmetric", axes=(-2, -1)): """Computes single level wavelet decomposition for 2D images """ wavelet = ensure_wavelet_(wavelet) image = promote_arg_dtypes(image) dec_lo = wavelet.dec_lo dec_hi = wavelet.dec_hi axes = tuple(axes) if len(axes) != 2: r...
4ee7e1f3c19bb1b0bf8670598f1744b7241b235d
28,728
def recommended_global_tags_v2(release, base_tags, user_tags, metadata): """ Determine the recommended set of global tags for the given conditions. This function is called by b2conditionsdb-recommend and it may be called by conditions configuration callbacks. While it is in principle not limited to...
8396dcc2d54a5e36dfe5485d33ef439059a944c6
28,729
def plot_corelation_matrix(data): """ Plotting the co-relation matrix on the dataset using the numeric columns only. """ corr = data.select_dtypes(include=['float64', 'int64']).iloc[:, 1:].corr() # Generate a mask for the upper triangle mask = np.zeros_like(corr, dtype=np.bool) mask[np....
49e89f3ba844f0bf9676bca4051c72ad1305294f
28,730
import urllib from bs4 import BeautifulSoup def product_by_id(product_id): """ Get Product description by product id :param product_id: Id of the product :return: """ host = "https://cymax.com/" site_data = urllib.urlopen(host + str(product_id) + '--C0.htm').read() soup = BeautifulSou...
2f2f3abfd0dcf5a124ae4a1bd3975734fbac7783
28,731
def overlap(X, window_size, window_step): """ Create an overlapped version of X Parameters ---------- X : ndarray, shape=(n_samples,) Input signal to window and overlap window_size : int Size of windows to take window_step : int Step size between windows Returns ...
4f53be9c87d0ce9800a6e1b1d96ae4786eace78b
28,732
def may_ozerov_depth_3_complexity(n, k, w, mem=inf, hmap=1, memory_access=0): """ Complexity estimate of May-Ozerov algorithm in depth 3 using Indyk-Motwani for NN search [MayOze15] May, A. and Ozerov, I.: On computing nearest neighbors with applications to decoding of binary linear codes. In: Annual I...
b390a515626185912cbc234fbebd492a0e154bbb
28,733
import json import copy def unpack_single_run_meta(storage, meta, molecules): """Transforms a metadata compute packet into an expanded QC Schema for multiple runs. Parameters ---------- db : DBSocket A live connection to the current database. meta : dict A JSON description of ...
3a3237067b4e52a5f7cb7d5ecc314061eaaa2b15
28,734
def getKey(event): """Returns the Key Identifier of the given event. Available Codes: https://www.w3.org/TR/2006/WD-DOM-Level-3-Events-20060413/keyset.html#KeySet-Set """ if hasattr(event, "key"): return event.key elif hasattr(event, "keyIdentifier"): if event.keyIdentifier in ["Es...
0935ad4cb1ba7040565647b2e26f265df5674e1d
28,735
def get_long_season_name(short_name): """convert short season name of format 1718 to long name like 2017-18. Past generations: sorry this doesn't work for 1999 and earlier! Future generations: sorry this doesn't work for the 2100s onwards! """ return '20' + short_name[:2] + '-' + short_name[2:]
314ef85571af349e2e31ab4d08497a04e19d4118
28,736
from typing import List from typing import Any from typing import Dict def make_variables_snapshots(*, variables: List[Any]) -> str: """ Make snapshots of specified variables. Parameters ---------- variables : list Variables to make snapshots. Returns ------- snapshot_name : ...
d6a7bf5be51ebe7f4fb7985b2a440548c502d4ec
28,737
def sext_to(value, n): """Extend `value` to length `n` by replicating the msb (`value[-1]`)""" return sext(value, n - len(value))
683316bd7259d624fddb0d9c947c7a06c5f28c7e
28,738
def parse_matching_pairs(pair_txt): """Get list of image pairs for matching Arg: pair_txt: file contains image pairs and essential matrix with line format image1 image2 sim w p q r x y z ess_vec Return: list of 3d-tuple contains (q=[wpqr], t=[xyz], essential matrix) ...
6697e63a091b23701e0751c59f8dc7fe0e582a97
28,739
import threading from typing import OrderedDict def compile_repo_info(repos, all=False, fetch=False): """Compiles all the information about found repos.""" # global to allow for threading work global git_info git_info = {} max_ = len(repos) threads = [] for i, repo in enumerate(repos): ...
b3cbdcdd53ce2c5274990520756390f396156aaa
28,740
def histogram2d(x, y, bins=10, range=None, weights=None, density=False): # pylint: disable=redefined-builtin """ Computes the multidimensional histogram of some data. Note: Deprecated numpy argument `normed` is not supported. Args: x (Union[list, tuple, Tensor]): An array with shape `(...
8b537168cb7248ccd2959c95ae4fb742b81aa225
28,741
def get_project_arg_details(): """ **get_project_arg_details** obtains project details from arguments and then returns them :return: """ project_id = request.args.get('project_id') names = request.args.get('names') cell = request.args.get('cell') email = request.args.get(...
5efcaebf0efe89a5d8fa5f52d50777041b545177
28,742
def vibronic_ls(x, s, sigma, gamma, e_vib, kt=0, n_max=None, m_max=None): """ Produce a vibronic (Frank-Condom) lineshape. The vibronic transition amplitude computed relative to 0 (ie: relative to the electronic transition energy). Lines are broadened using a voigt profile. Parameter...
428f0c44566cf3a824902fc9f7fb8012089d1b89
28,743
import re import requests def handleFunction(command,func): """ Function to calculate, Translate """ try: # re.search(r"(?i)"+func,' '.join(SET_OF_FUNCTIONS)) if("calculate" == func.lower()): func,command = command.split() try: return eval(command) except: return "Sorry! We are unable to cal...
c5ff05b0b31a7441f7efaf9ce76c496f3f708eea
28,744
import json def auth(): """returns worker_id !!!currently!!! does not have auth logic""" response_body = {} status_code = 200 try: auth_token = request.args.get("auth_token", None) resp = fl_events_auth({"auth_token": auth_token}, None) resp = json.loads(resp)["data"] excep...
bbbeb0dbf7401b11e56399890f43a799f859eb87
28,745
def get_templates_environment(templates_dir): """Create and return a Jinja environment to deal with the templates.""" env = Environment( loader=PackageLoader('charmcraft', 'templates/{}'.format(templates_dir)), autoescape=False, # no need to escape things here :-) keep_trailin...
9f3571ce4cb8f18f64912e6c259bc2f1022698f2
28,747
import numpy as np def return_U_given_sinusoidal_u1(i,t,X,u1,**kwargs): """ Takes in current step (i), numpy.ndarray of time (t) of shape (N,), state numpy.ndarray (X) of shape (8,), and previous input scalar u1 and returns the input U (shape (2,)) for this time step. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...
b5faba122af139f29f20dbce983b84fe5c0c277c
28,748
def verify(s): """ Check if the cube definition string s represents a solvable cube. @param s is the cube definition string , see {@link Facelet} @return 0: Cube is solvable<br> -1: There is not exactly one facelet of each colour<br> -2: Not all 12 edges exist exactly once<br> ...
d3e765af153a7400d84e59c72d292a9ccd9170f5
28,749
from typing import cast import copy def copy_jsons(o: JSONs) -> MutableJSONs: """ Make a new, mutable copy of a JSON array. >>> a = [{'a': [1, 2]}, {'b': 3}] >>> b = copy_jsons(a) >>> b[0]['a'].append(3) >>> b [{'a': [1, 2, 3]}, {'b': 3}] >>> a [{'a': [1, 2]}, {'b': 3}] """ ...
c9fffefe0dd541e20a7a3bef503e0b1af847909d
28,750
def string_to_dot(typed_value): # type: (TypedValue) -> Tuple[List[str], List[str]] """Serialize a String object to Graphviz format.""" string = f'{typed_value.value}'.replace('"', r'\"') dot = f'_{typed_value.name} [shape="record", color="#A0A0A0", label="{{{{String | {string}}}}}"]' return [dot], ...
287d2c886aca5ca940b323b751af91e33ed54fc4
28,751
def resolve_country_subdivisions(_, info, alpha_2): """ Country resolver :param info: QraphQL request context :param alpha_2: ISO 3166 alpha2 code :param code: ISO 3166-2 code """ return CountrySubdivision.list_for_country(country_code=alpha_2)
56ffa7343f1da686819c85dee54770cd4d1564d3
28,752
from typing import Tuple def bool2bson(val: bool) -> Tuple[bytes, bytes]: """Encode bool as BSON Boolean.""" assert isinstance(val, bool) return BSON_BOOLEAN, ONE if val else ZERO
3d4456f6db88939966997b8a49c3d766b1ef4ba1
28,753
def isbn13_to_isbn10 (isbn_str, cleanse=True): """ Convert an ISBN-13 to an ISBN-10. :Parameters: isbn_str : string The ISBN as a string, e.g. " 0-940016-73-6 ". It should be 13 digits after normalisation. cleanse : boolean If true, formatting will be stripped from the ISBN before conversion. :Re...
b39d6d9f7a850a8b0edbb6b9502f4d6bb73f8848
28,754
import json def import_data(): """Import datasets to internal memory""" with open('data/names.json') as f: data_names = json.load(f) with open('data/issues.json') as f: data_issues = json.load(f) with open('data/disasters.json') as f: data_disasters = json.load(f) with open...
11db10c2c56b6b714ecffa57510c9a79abfa1d86
28,755
def synthesize_ntf_dunn(order=3, osr=64, H_inf=1.5): """ Alias of :func:`ntf_dunn` .. deprecated:: 0.11.0 Function has been moved to the :mod:`NTFdesign` module with name :func:`ntf_dunn`. """ warn("Function superseded by ntf_dunn in " "NTFdesign module", PyDsmDeprecationWarn...
2920ec676ab070ebb5f7c95e245baf078b723fae
28,756
def schedule_notification() -> str: """Randomly select either news or covid stats to add to the notifcation column, if there is already a 'news' item in the notificaitons column then it will update the item with a newer piece of news""" #NEWS news_title, news_content = get_news() notif_exists =...
9aed44251170dc124f71b11bf482ef009ebe973e
28,757
def _parse_hexblob(blob: str) -> bytes: """ Binary conversions from hexstring are handled by bytes(hstr2bin()). :param blob: :return: """ return bytes(hstr2bin(blob))
e49348f7cb15bbba850dbf05c0a3625427d0ac2d
28,758
from typing import List from typing import Dict def _row_to_col_index_dict(headers: List[Cell]) -> Dict[str, int]: """Calculate a mapping of cell contents to column index. Returns: dict[str, int]: {MFP nutrient name: worksheet column index} mapping. int: N """ return {h.value: h.col - ...
11f7a68cd211b216d2a27850be99291cc830d52f
28,759
def preprocess_cat_cols(X_train, y_train, cat_cols=[], X_test=None, one_hot_max_size=1, learning_task=LearningTask.CLASSIFICATION): """Preprocess categorial columns(cat_cols) in X_train and X_test(if specified) with cat-counting(the same as in catboost) or with one-hot-encoding, depends ...
10402fe0fd534eb73598fa99a1202b970202f2c0
28,760
def get_start_time(period, time_zone=None): """Doc.""" today = pd.Timestamp.today(tz=time_zone or 'Europe/Stockholm') if period == 'thisyear': return pd.Timestamp(f'{today.year}0101').strftime('%Y-%m-%d %H:%M:%S') elif period in DAYS_MAPPER: return (today - pd.Timedelta(days=DAYS_MAPPER....
c5e9ab4543f813f7210bc278e83d9c4a554d242b
28,761
def setup_textbox(parent, font="monospace", width=70, height=12): """Setup for the textboxes, including scrollbars and Text widget.""" hsrl = ttk.Scrollbar(parent, orient="horizontal") hsrl.pack(side=tk.BOTTOM, fill=tk.X) vsrl = ttk.Scrollbar(parent) vsrl.pack(sid...
674bc72eefacc16485a4b369535f1253187e5ded
28,762
def generate_mock_statuses(naive_dt=True, datetime_fixtures=None): """ A dict of statuses keyed to their id. Useful for mocking an API response. These are useful in``Timeline`` class testing. May be set to have a utc timezone with a ``False`` value for the ``naive_dt`` argument. """ mock_status...
aca7bd235ef6fd404f8da894b6917636d7895dcb
28,763
import hashlib def hashlib_mapper(algo): """ :param algo: string :return: hashlib library for specified algorithm algorithms available in python3 but not in python2: sha3_224 sha3_256, sha3_384, blake2b, blake2s, sha3_512, shake_256, shake_128 """ algo = algo.lower() if algo == "...
56830caccd0b3f88982bfe09a8789002af99c1e7
28,765
def partition_cells(config, cells, edges): """ Partition a set of cells - cells -- A DataFrame of cells - edges -- a list of edge times delimiting boundaries between cells Returns a DataFrame of combined cells, with times and widths adjusted to account for missing cells """ # get indices of...
c8532cbf148802b482380f8978dbc8d9d3b1b35f
28,766
from typing import List from typing import Union def timing_stats(results: List[Result]) -> List[str]: """Calculate and format lines with timings across completed results.""" def percentile(data: List[float], percent: int) -> Union[float, str]: if not data: return '-' data_sorted =...
08d671b2866674924dc070dda2e7e85a4c56c064
28,767
import logging def analyse_gamma( snps_object, output_summary_filename, output_logger, SWEEPS, TUNE, CHAINS, CORES, N_1kG, fix_intercept=False, ): """ Bayesian hierarchical regression on the dataset with the gamma model. :param snps_object: snps instance :param ou...
fac6111e4ad87d63d89d2942e5cfc28023950117
28,768
def dpc_variant_to_string(variant: _DV) -> str: """Convert a Basix DPCVariant enum to a string. Args: variant: The DPC variant Returns: The DPC variant as a string. """ return variant.name
2eb7eeff47eb36bea47714b9e233f3d286925d3b
28,769
import secrets from datetime import datetime async def refresh_token(request: web.Request) -> web.Response: """ Refresh Token endpoints """ try: content = await request.json() if "token" not in content: return web.json_response({"error": "Wrong data. Provide token."}, status=400) ...
a8008a33793ccb7b34900724b62fb3add061fa30
28,770
def get_my_choices_projects(): """ Retrieves all projects in the system for the project management page """ proj_list = Project.objects.all() proj_tuple = [] counter = 1 for proj in proj_list: proj_tuple.append((counter, proj)) counter = counter + 1 return proj_tuple
f35563adb12aff32ac1b60152b3085c63dc839f0
28,771
import math def normalDistributionBand(collection, band, mean=None, std=None, name='normal_distribution'): """ Compute a normal distribution using a specified band, over an ImageCollection. For more see: https://en.wikipedia.org/wiki/Normal_distribution :param band: the nam...
57b0d6beb590126253c4934e403487bd69c7c094
28,773
import torch def compute_ctrness_targets(reg_targets): """ :param reg_targets: :return: """ if len(reg_targets) == 0: return reg_targets.new_zeros(len(reg_targets)) left_right = reg_targets[:, [0, 2]] top_bottom = reg_targets[:, [1, 3]] ctrness = (left_right.min(dim=-1)[0] / l...
538a63b6adcd73fbd601d6e61eea5f27642746fa
28,774
import hashlib import hmac import base64 def create_hmac_signature(key:bytes, data_to_sign:str, hashmech:hashlib=hashlib.sha256) -> str: """ Creates an HMAC signature for the provided data string @param key: HMAC key as bytes @param data_to_sign: The data that needs to be signed @param hashmech: ...
0c3f5b8bef6e3330e8c24fca62ce2707b0de5286
28,775
def CV_range( bit_depth: Integer = 10, is_legal: Boolean = False, is_int: Boolean = False ) -> NDArray: """ Returns the code value :math:`CV` range for given bit depth, range legality and representation. Parameters ---------- bit_depth Bit depth of the code value :math:`CV` range. ...
e1eb079e4e75cb7b8353d88e13bb7eb82d15428c
28,776
import torch def bw_transform(x): """Transform rgb separated balls to a single color_channel.""" x = x.sum(2) x = torch.clamp(x, 0, 1) x = torch.unsqueeze(x, 2) return x
3ecec3ada4b75486ff96c30890e8a3e173ca7d31
28,777
def fom(A, b, x0=None, maxiter=None, residuals=None, errs=None): """Full orthogonalization method Parameters ---------- A : {array, matrix, sparse matrix, LinearOperator} n x n, linear system to solve b : {array, matrix} right hand side, shape is (n,) or (n,1) x0 : {array, matri...
b95ac8b383150e57ffd599fb2e77608dd7503d9d
28,778
def get_gprMax_materials(fname): """ Returns the soil permittivities. Fname is an .in file. """ materials = {'pec': 1.0, # Not defined, usually taken as 1. 'free_space': 1.000536} for mat in get_lines(fname, 'material'): props = mat.split() materials[props[-1]] = f...
f56e720c5c2209b67ca521b779ce9472665beb6a
28,779
import random def generate_utt_pairs(librispeech_md_file, utt_pairs, n_src): """Generate pairs of utterances for the mixtures.""" # Create a dict of speakers utt_dict = {} # Maps from speaker ID to list of all utterance indices in the metadata file speakers = list(librispeech_md_file["speaker_ID"]...
9079fa35b961de053c86b08527085e8eb84609b8
28,780
def simpson(so, spl: str, attr: str, *, local=True, key_added=None, graph_key='knn', inplace=True) -> None: """Computes the Simpson Index on the observation or the sample level Args: so: SpatialOmics instance spl: Spl for which to compute the metric attr: Categorical feature in SpatialO...
d10fd40305f384d75f8c33d391a87f6b5c8adcd5
28,781