content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import inspect def with_patch_inspect(f): """decorator for monkeypatching inspect.findsource""" def wrapped(*args, **kwargs): save_findsource = inspect.findsource save_getargs = inspect.getargs inspect.findsource = findsource inspect.getargs = getargs try: ...
711fa3099b0c6242b623305237f950120b3de19a
10,000
def apply_hux_f_model(r_initial, dr_vec, dp_vec, r0=30 * 695700, alpha=0.15, rh=50 * 695700, add_v_acc=True, omega_rot=(2 * np.pi) / (25.38 * 86400)): """Apply 1d upwind model to the inviscid burgers equation. r/phi grid. return and save all radial velocity slices. :param r_initial: 1...
31fb582cc8d31702d8ac8aabb2dd099f169b0c08
10,001
import inspect def requires_request_arg(method): """ Helper function to handle deprecation of old ActionMenuItem API where get_url, is_show, get_context and render_html all accepted both 'request' and 'parent_context' as arguments """ try: # see if this is a pre-2.15 get_url method that ta...
0ec09e34c04d4d54762051b01af8c80754d47125
10,002
def show_output_to_df( show_output: str, spark_session: SparkSession, default_data_type: str = 'string' ): """ Takes a string containing the output of a Spark DataFrame.show() call and "rehydrates" it into a new Spark DataFrame instance. Example input: +--------+--------+ |co...
0dd9372b29d191a846ac4a1e2251c118e4a01102
10,003
import math def Schwefel(arr: np.ndarray, seed: int = 0) -> float: """Implementation for BBOB Schwefel function.""" del seed dim = len(arr) bernoulli_arr = np.array([pow(-1, i + 1) for i in range(dim)]) x_opt = 4.2096874633 / 2.0 * bernoulli_arr x_hat = 2.0 * (bernoulli_arr * arr) # Element-wise multipli...
1588dc5fa7864c3bd7ed5639ca44dafcd5d7f405
10,004
def article_idx_to_words_row(article_idx): """ Given a tuple with an article and an index, return a Row with the index ad a list of the words in the article. The words in the article are normalized, by removing all non-'a-z|A-Z' characters. Any stop words (words of less than 2 characters) are ...
8a956e6be7d0b3e3076219929b8e5e2358f856ab
10,005
from tensorflow.keras.mixed_precision import experimental as mixed_precision def get_device_strategy(device, half=False, XLA=False, verbose=True): """ Returns the distributed strategy object, the tune policy anb the number of replicas. Parameters ---------- device : str Possible v...
c0c5d29490876812d3a3724638a17ebb0abdd54e
10,006
def make_mask( pois_gdf, link_gdf, ): """ :param pois_gdf: :param link_gdf: :return: """ mask = np.array([]) enum = np.array([]) return mask, enum
bd31fe0c0c9f1f1f38d1c4e1bf26bdeb3f2806ca
10,007
def SEMIMINUS(r1, r2): """aka NOT MATCHING (macro)""" return MINUS(r1, SEMIJOIN(r1, r2))
225e3385b03420a52fb11703ee58a251ff2bacd6
10,008
def Ineg_wrapper(valS, valI): """ Function used to wrap Inequalities into a suitable form for optimisation valS > valI --> Inequality is satisfied valS and valI can be float or 1d array """ epsilon = 1e-6 top = 1e3 ecart = valI - valS if ecart < epsilon: out = np.exp(ecart)...
1bf1f664845de8cc13750d6d021c1058687d91cc
10,009
def preprocess_imgs(set_name, img_size): """ Resize and apply VGG-15 preprocessing """ set_new = [] for img in set_name: img = cv2.resize( img, dsize=img_size, interpolation=cv2.INTER_CUBIC ) set_new.append(tf.keras.applications.vgg16.prepr...
52f1b677a053feac585b57847aab32c8d38c5b30
10,010
def get_shapes(galsim_img, center): """ Get shapes This function compute the moments of an image. Then return the sigma of the window function used (size of the object) and the amplitude (flux of the object). Parameters --------- galsim_img : galsim.image.Image Galsim.image object ...
3d6520d129c0c6bea93f91e332b477b777041a0b
10,011
def ascending_super_operator(hamAB, hamBA, w_isometry, v_isometry, unitary, refsym): """ ascending super operator for a modified binary MERA ascends 'hamAB' and 'hamBA' up one layer Args: hamAB (tf.Tensor): local Hamiltonian on the A-B lattice hamBA (tf.Tenso...
8692d2c0d02e82cb691c24977091665015aecdc6
10,012
def filteredhash(repo, maxrev): """build hash of filtered revisions in the current repoview. Multiple caches perform up-to-date validation by checking that the tiprev and tipnode stored in the cache file match the current repository. However, this is not sufficient for validating repoviews because the ...
de606e22c499eb53d6d83f68900d234e76498e35
10,013
import logging def filter_blast_by_amplicon(blast_hits, min_amplicon_len, max_amplicon_len): """ Filtering primers by putative amplicon that would be generated. If the amplicon size is outsize of the min/max, then the primers not legit off-targets. """ logging.info('Filtering to only hits producin...
8f84a5d615f65e7c21d5135d3f585b91c0f4667b
10,014
def cropImage(img): """ Crop the screen for only the relevant inventory section. Args: img (ndarray): The image of the Warframe inventory. Returns: ndarray: The image of only the inventory section containing items. """ #TODO: Allow user to manually define inventory section inst...
06f43fdf16e7090b6aa64f36599e5c83e523c4be
10,015
def determine_channel(channel_as_text): """Determine which channel the review is for according to the channel parameter as text, and whether we should be in content-review only mode.""" if channel_as_text == 'content': # 'content' is not a real channel, just a different review mode for # lis...
db8eeaae3c953cf497135f4d6e6071275a626dc2
10,016
from typing import List import argparse def parse_workflow_args(input: List[str] = None) -> argparse.Namespace: """Parses command-line style flags for the workflow. All unknown args are discarded to allow multiple parses on args. Args: input: An optional list of strings in the style of sys.argv...
6e4de2b2f1c83f6fa9cca3e21d81b34bdc1dd181
10,017
import requests def get_device_config(device_name, dnac_jwt_token): """ This function will get the configuration file for the device with the name {device_name} :param device_name: device hostname :param dnac_jwt_token: DNA C token :return: configuration file """ device_id = get_device_id_...
b092efbe307f3f7a73cc998275ad67ea064cd3ed
10,018
def get_ideas(): """ Gets all ideas from mongo """ return find('ideas')
e6c8a152c2bca775e17d6fa52b262b334ac693c0
10,019
import numpy def uppercase_dtype(dtype): """ Convert a dtype to upper case. A helper function. Do not use. """ pairs = dict([(key.upper(), dtype.fields[key]) for key in dtype.names]) dtype = numpy.dtype(pairs) return dtype
bf28581dbb6a857a12c1b056a5e1b6f7bdbbbc27
10,020
from sisyphus_control import Table import asyncio async def async_setup(hass, config): """Set up the sisyphus component.""" tables = hass.data.setdefault(DATA_SISYPHUS, {}) table_configs = config.get(DOMAIN) session = async_get_clientsession(hass) async def add_table(host, name=None): """...
dda9db725da8bf2b9d5178523afcaeaa16f740d0
10,021
from typing import Dict def mlp_prior(input_dim: int, zdim: int = 2) -> Dict[str, jnp.array]: """Priors over weights and biases in the default Bayesian MLP""" hdim = [64, 32] def _bnn_prior(task_dim: int): w1 = sample_weights("w1", input_dim, hdim[0], task_dim) b1 = sample_biases("b1", hd...
29c1d751f09a8da0c9f68209a5bcd48db12e1ca1
10,022
def get_biggest_spread_by_symbol(exchanges, symbol): """Get biggest spread by symbol.""" ask_exchange_id = "" min_ask_price = 99999999 bid_exchange_id = "" max_bid_price = 0 for exchange_id in exchanges: exchange = eval("ccxt.{0}()".format(exchange_id)) try: order_...
20eda8274e513d1e098c34c309833c58be6dbb4e
10,023
import os def gmag_filename(dates, stations): """Create a list of tuples for downloading: remote_file, local_file""" prefs = pyspedas.get_spedas_prefs() if 'themis_remote' in prefs: remote_path = prefs['themis_remote'] else: raise NameError('remote_path is not found in spd_prefs_txt.py...
af23467ad910524cb109f78b723425a9fe806c2e
10,024
def update_user(): """User update route :return: action status """ if 'data' in request.json: data = request.json['data'] if ('profile' in data) and ('theme' in data['profile']): current_user.profile.theme = data['profile']['theme'] services.db.session.commit() r...
f6b98a0e06f7b898737ffa0e6c395f2ddd18fc7b
10,025
from typing import List def on_deck(elements: List[int], all_vars): """all of the elements must be within the deck""" rules = [] for element in elements: var = all_vars[element - 1] rules.append(var >= 1) rules.append(var <= 52) return rules
2e90dfa45bd90a7c3b834000e070631af5952f36
10,026
def transform_data_to_dictionary(elements): """Parses each element in the list and parses it in a dictionary Args: elements (list): list of html elements Returns: dictionary: treated information. """ url_informations = {} for n in range(0, len(elements), 2): url_informa...
fd81fe7b6093577f32e460cb8a4d22cbbec92789
10,027
import math import torch def postprocess_new(u, x, lr_min, lr_max, num_itr, rho=0.0, with_l1=False,s=math.log(9.0)): """ :param u: utility matrix, u is assumed to be symmetric, in batch :param x: RNA sequence, in batch :param lr_min: learning rate for minimization step :param lr_max: learning rate...
51fb589a2a8ccaeb96b06192f6050ded91f81f07
10,028
def parse_api_error(response): """ Parse the error-message from the API Response. Assumes, that a check if there is an error present was done beforehand. :param response: Dict of the request response ([imdata][0][....]) :type response: ``dict`` :returns: Parsed Error-Text :rtype: ``str`` ...
acc4256b3245e3e2c10e3ba998bf577e0f51a33e
10,029
from typing import Union def login_manual_user_device(username: str, password: str, mac_address: str) -> Union[str, Token]: """Try to login by username and password. A token for auto-login is returned""" possible_user = User.get_by_username(username) if possible_user is None: fail_msg = f"No user ...
5dd6e1043ffea2cceacf1fc83e9713b4b0fd827b
10,030
def corrector_new(Ybus, Ibus, Sbus, V0, pv, pq, lam0, Sxfr, Vprv, lamprv, z, step, parametrization, tol, max_it, verbose, max_it_internal=10): """ Solves the corrector step of a continuation power flow using a full Newton method with selected parametrization scheme. solves for bus vol...
e4ff6d31916c34768152af998c1bc5ff4fdebcb7
10,031
import os def retrieve_files(dir, suffix='png|jpg'): """ retrive files with specific suffix under dir and sub-dirs recursively """ def retrieve_files_recursively(dir, file_lst): for d in sorted(os.listdir(dir)): dd = osp.join(dir, d) if osp.isdir(dd): retr...
30355f3bc7fae223d0670658818555a569910b58
10,032
def clique_ring(n_cluster=3, n_in_cluster=5): """Get adjacency matrix for cluster domain used by Schapiro et al 2013. Args: n_cluster: number of clusters, connected in a ring. n_in_cluster: number of nodes in each cluster. Each node is connected to all other nodes in cluster, except the edge connecti...
2b8dad4b52e456a933c66af7198b6363eb839c41
10,033
def get_halfnormal_mean_from_scale(scale: float) -> float: """Returns the mean of the half-normal distribition.""" # https://en.wikipedia.org/wiki/Half-normal_distribution return scale * np.sqrt(2) / np.sqrt(np.pi)
d5d0ac1e460d30ad544982a5f0bb7f463c64ede9
10,034
def cal_pr(y_hat, y_score): """ calculate the precision and recall curve :param y_hat: ground-truth label, [n_sample] :param y_score: predicted similarity score, [n_sample] :return: [n_sample] """ thresholds = np.arange(1, -0.001, -0.001) fps, tps = cal_binary_cls_curve(y_hat, y_score, t...
a64e38a51b5e8c8bdb6bbc26f4c99ae3746dfc64
10,035
def alert_source_create(context, values): """Create an alert source.""" return IMPL.alert_source_create(context, values)
7d55eed069b644c718ffb55f27d22a56c7483f73
10,036
def sanitise_utf8(s): """Ensure an 8-bit string is utf-8. s -- 8-bit string (or None) Returns the sanitised string. If the string was already valid utf-8, returns the same object. This replaces bad characters with ascii question marks (I don't want to use a unicode replacement character, beca...
11b864ade1c36e2b42ffbdd76ee2851f01ca7803
10,037
def trans_r2xy(r, phi, r_e, phi_e): """r,phi -> x,y """ x = np.array(r) * np.cos(phi) y = np.array(r) * np.sin(phi) err = np.array( [polar_err(i, j, k, l) for i, j, k, l in zip(r, phi, r_e, phi_e)] ) return x, y, err[:, 0], err[:, 1]
dcc9e1433bb40dd76d41b1031420600cdab96d67
10,038
def ldpc_bp_decode(llr_vec, ldpc_code_params, decoder_algorithm, n_iters): """ LDPC Decoder using Belief Propagation (BP). Parameters ---------- llr_vec : 1D array of float Received codeword LLR values from the channel. ldpc_code_params : dictionary Parameters of the LDPC code....
c9bd44c386ead2f9b968eb3a8c211d7af5e26a25
10,039
def edit_style_formats(style_format_id, **kwargs): """Create or edit styles formats. :param style_format_id: identifier of a specific style format """ if request.method == "POST": args = request.get_json() errors = StyleFormatsSchema().validate(args) if err...
a9c0cc004fb840ffcf2b9c0b45f43dc3535ea103
10,040
import logging import os def restore_snapshots(): """ Restore snapshot into correct directories. Returns: True on success, False otherwise. """ logging.info("Restoring Cassandra snapshots.") for directory in CASSANDRA_DATA_SUBDIRS: data_dir = "{0}/{1}/{2}/".format(APPSCALE_DATA_DIR, "cassandra", ...
d2ae1be7848d080e6142679355b6059c004e4d49
10,041
def volume_to_vtk(volelement, origin=(0.0, 0.0, 0.0)): """Convert the volume element to a VTK data object. Args: volelement (:class:`omf.volume.VolumeElement`): The volume element to convert """ output = volume_grid_geom_to_vtk(volelement.geometry, origin=origin) shp = get_volu...
710152ebdb56592a1485fa0c451bf135679cc949
10,042
def _in_delta(value, target_value, delta) -> bool: """ Check if value is equal to target value within delta """ return abs(value - target_value) < delta
92ab62a381fc1cfc6bbb82635f196ec4498babf4
10,043
def getpar(key, file='DATA/Par_file', sep='=', cast=str): """ Reads parameter from SPECFEM parfile """ val = None with open(file, 'r') as f: # read line by line for line in f: if find(line, key) == 0: # read key key, val = _split(line, sep) ...
05a2cf904dd1c5cdb71dd302e2a74c3397a6d1e2
10,044
from typing import Sequence import re def replace_links(text: str, replace, site: 'pywikibot.site.BaseSite') -> str: """Replace wikilinks selectively. The text is searched for a link and on each link it replaces the text depending on the result for that link. If the result is just None it skips that ...
84aba3f231e402af50a205a7b40e276c1de754c5
10,045
from typing import Dict def create_ok_response() -> flask.Response: """Creates a 200 OK response. :return: flask.Response. """ ok_body: Dict[str, str] = {"status": "OK"} return make_response(jsonify(ok_body), HTTP_200_OK)
4b60c712a1b123c8daa976239cf5abd813e50221
10,046
import os import sys def compile_ui_if_needed(ui_file_path: str, ignore_mtime: bool=False): """ The following will dynamically compile the Qt Designer '.ui' file given by C{ui_file_path}, and import and load the generated Python module. The generated module will have the name: C{ui_f...
f01e1825fc62b3276194f4d9930dfa6c05fc8c18
10,047
import os def pickleExists(name): """ Returns True if there is a pickle with name in cache, False otherwise. Used to prevent cache misses :param name: Name to look for in cache :return: True on hit, False on miss """ fileNames = [f for f in os.listdir(PICKLE_DIR) if name in f] return n...
b18a46761467a9dfa170217621f4a59db959bb3d
10,048
import time def format_timestamp(timestamp): """Formats an UTC timestamp into a date string. >>> format_timestamp("2014-04-08T12:41:34+0100") 'Tue, 08 Apr 2014 12:41:34' """ t = iso8601.parse_date(timestamp).timetuple() return time.strftime("%a, %d %b %Y %H:%M:%S", t)
f551c5bb984ad9d23d0c1d21103f340e6e4b104b
10,049
def _flat(xvals): """ Function for flat surface y=0, with boundary conditions Parameters ---------- xvals : np.array x-values of the surface. Returns ------- yvals : np.array y-Values of the initialized surface. """ yvals = np.zeros_like(xvals) return yvals
632ad5fa9acc30e7fae07942890dd9060ab6c859
10,050
import torch def regularized_laplacian(weights, labels, alpha): """Uses the laplacian graph to smooth the labels matrix by "propagating" labels Args: weights: Tensor of shape (batch, n, n) labels: Tensor of shape (batch, n, n_classes) alpha: Scaler, acts as a smoothing factor ...
12725881a121a3fb3455c0905d8db1a90b08dc4d
10,051
def weight_variable_glorot(input_dim, output_dim, name=""): """Create a weight variable with Glorot & Bengio (AISTATS 2010) initialization. """ init_range = np.sqrt(6.0 / (input_dim + output_dim)) initial = tf.random_uniform([input_dim, output_dim], minval=-init_range, ...
85b7ba1f46d0e154425cc884202021faf621bc0e
10,052
from typing import Tuple def pareto_plot(column: pd.Series, use_given_index: bool = False, figsize: Tuple[int, int] = (12, 8), return_freq_df: bool = False): """ Draw Pareto plot for categorical variable Arguments: ---------- column: pd.Series ...
8bf2f098a93076356ae00e702a05e4b831811609
10,053
import os def get_openshift_installer( version=None, bin_dir=None, force_download=False, ): """ Download the OpenShift installer binary, if not already present. Update env. PATH and get path of the openshift installer binary. Args: version (str): Version of the installer to downlo...
338dad7508981807a853c90c15481b4b149e6c2f
10,054
import argparse def parse_arguments(): """ Parse input arguments and store them in a global variable. Returns: Parsed arguments. """ parser = argparse.ArgumentParser(description='Generates a lexicon for gender recognition.') parser.add_argument('dataset', help='file with JSON objects ...
bad4bc4943dc18a63a676bd44b4babf210846085
10,055
from typing import Optional from typing import Dict import json def remove_external_id( role_name: str, dir_path: Optional[str], session=None, client=None, backup_policy: Optional[str] = "", bucket: Optional[str] = None, ) -> Dict: """The remove_external_id method takes a role_name as a st...
711fbe0bf12206688b3d372d97fe0e10f1aa59e1
10,056
def find_binaries(fw_path): """ Gets a list of possible binaries within a firmare sample. The list might contain false positives, angr will ignore them. :param fw_path: firmware path :return: a list of binaries """ cmd = "find \""+ fw_path + "\"" cmd += " -executable -type f...
53d4a8f8a9abcc9404392a1ba317fde2e583bc93
10,057
def get_core_count(): """ Find out how many CPU cores this system has. """ try: cores = str(compat.enum_cpus()) # 3.4 and up except NotImplementedError: cores = "1" # 3.2-3.3 else: if compat.enum_cpus() is None: cores = "1" return cores
2bd49d6189ba4f6ee92ae3e54cb629a8fb70e440
10,058
import ast from textwrap import dedent def ASTTailrec(func): """ This approach involves modifying the ast tree so we can just stick a decorator on such as ``` @ASTTailrec def fac(n, k=1): if n == 1: return k return fac(n-1, k*n) ``` This function has been heavily inspired...
62c61a41b7d48991517550c2820331e0c147c929
10,059
def vec2str(vec): """ transform the vector to captcha str""" _str = "" for i in range(4): v = vec[i*43: (i+1)*43] _str += chr(np.argwhere(v == 1)[0][0] + ord('0')) return _str
9f927b9b084b2aeff26686a0066bdbfb9ad4e3f3
10,060
def mnist(path=None, batchsize=20, xpreptrain=None, ypreptrain=None, dataset="train", **kwargs): """ Legacy MNIST loader. :type path: str :param path: Path to MNIST pickle file. :type batchsize: int :param batchsize: Batch size (no shit sherlock) :type xpreptrain: prepkit.preptrain :p...
65ab0c0ad529f5b9b6803585d00fb044a82db2a5
10,061
def rand_pad(ctvol): """Introduce random padding between 0 and 15 pixels on each of the 6 sides of the <ctvol>""" randpad = np.random.randint(low=0,high=15,size=(6)) ctvol = np.pad(ctvol, pad_width = ((randpad[0],randpad[1]), (randpad[2],randpad[3]), (randpad[4], randpad[5])), m...
83dd1de5c9914127c1d7fcc8d5e5068aa9f2864c
10,062
from typing import Tuple def _improve(tour: np.ndarray, matrix: np.ndarray, neighbours: np.ndarray, dlb: np.ndarray, it1: int, t1: int, solutions: set, k: int) -> Tuple[float, np.ndarray]: """ Последовательный 2-opt для эвристики Лина-Кернига tour: список городов matrix: матрица весов nei...
982a575fcde8e78186259f1970dc18850fd3b93e
10,063
def plot_step_with_errorbar(lefts, widths, y_coords, y_errs, errors_enabled=True, use_errorrects_for_legend=False, **kwargs): """Makes a step plot with error bars.""" lefts.append(lefts[-1] + widths[-1]) y_coords.append(y_coords[-1]) # prevent that we have labels for the step...
e532e71ada503474e5d52b24a1bf2a7fb2418e82
10,064
def intensity_modification(x): """ Intensity modification Parameters x: Tensor Returns x: Tensor """ x = x + tf.random.uniform(shape=[], minval=-0.05, maxval=0.05, dtype=tf.dtypes.float32) return x
c2ad13b6b123b3f053b88373ecfe7f4adfec87a3
10,065
def FormIdProperty(expression, **kwargs): """ Create a StringProperty that references a form ID. This is necessary because form IDs change when apps are copied so we need to make sure we update any references to the them. :param expression: jsonpath expression that can be used to find the field ...
5ac621dbd69df060de5280e8d893149ecb715b6f
10,066
import secrets def do_roll(dice: int, sides: int, _: int): """Given an amount of dice and the number of sides per die, simulate a dice roll and return a list of ints representing the outcome values. Modifier is ignored. """ dice = dice or 1 sides = sides or 1 values = sorted(((secrets.ran...
2073a37e5b76a85182e8cf786707ed18ca3f2474
10,067
def compute_logp_independent_block(X, alpha=None): """Compute the analytical log likelihood of a matrix under the assumption of independence. """ if alpha is None: alpha = np.ones(X.shape[1]) logp_ib = gammaln(alpha.sum()) - (gammaln(alpha)).sum() logp_ib += gammaln(X.sum(0) + alpha).sum() - gam...
831cdc63f8e131d3dfb797e054dfcd421f939ed5
10,068
def check_validity_label(labels): """ Check to see whether it makes a valid tuple Parameters: ----------- labels: A tuple of labels (Object_1, Object_2, Object_3, Return: ------- """ # Event is None -> All other values are None if labels[3] == 0: for...
c5a3d75813ab521b1e56789d64e7f14861075fb0
10,069
def flat_proj(v1, v2): """ Returns the flat projection of direction unit vector, v1 onto v2 """ temp1 = np.cross(v1, v2) temp2 = np.cross(temp1, v1) return proj(temp2, v2)
8a75dc118940cad6735f361ae3214358d78881e9
10,070
import torch from typing import Optional from typing import Tuple from typing import List def marching_cubes_naive( volume_data_batch: torch.Tensor, isolevel: Optional[float] = None, spacing: int = 1, return_local_coords: bool = True, ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: """ Run...
a7a4ac4a08bbc270091acc2ddd6a84eb4ee0ba37
10,071
def get_reshaped_ann_input(begin_state, new_state, action, pieces_player_begin, dice): """ save STATE and ACTION into 1-dimensional np.array. This should be an input to a ANN """ # look for the position of the given pawn before and after a move current_player = 0 input_ann = np.array(begin_state) in...
280434c00eb4734882323ce10a1b0b33230dab6e
10,072
def gc_resnet101(num_classes): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(GCBottleneck, [3, 4, 23, 3], num_classes=num_classes) model.avgpool = nn.AdaptiveAvgPool2d(1) return model
e6bb2e5e97fcf81d6abba34a2ee6c0638d39edf8
10,073
import os import torch def _write_data(x, y, sett, jtv=None): """ Format algorithm output. Args: jtv (torch.tensor, optional): Joint-total variation image, defaults to None. Returns: dat_y (torch.tensor): Reconstructed image data, (dim_y, C). pth_y ([str, ...]): Paths to reconstr...
7a06ded632fdabfd831b3d5f16e35f4fae1535f9
10,074
def compute_seatable_votes(votes, votetypes): """Compute the seatable votes. Parameters ---------- votes: pandas.DataFrame the votes of the seatable votes. votetypes: dict the information of the different types of vote variables. Returns ------- seatable_votes: numpy.nd...
1f8a32589918236e00d1c702cb23ecbc19d0cccb
10,075
from typing import Optional async def read_cookie(refresh_token: Optional[str] = Cookie(None)) -> JSONResponse: """Reads a cookie. Args: refresh_token: Name of the cookie. Returns: JSONResponse: Returns the value of the cookie as a json blurb. """ if refresh_token: ...
f7e4e20f138b24a6d1beda76b2c2e565f28e513c
10,076
def readAirfoilFile(fileName, bluntTe=False, bluntTaperRange=0.1, bluntThickness=0.002): """Load the airfoil file""" f = open(fileName) line = f.readline() # Read (and ignore) the first line r = [] try: r.append([float(s) for s in line.split()]) except Exception: pass while...
3b3da70ff36dc3a4ab2a186ee9712978f2658294
10,077
import argparse import os def get_args(): """ Return the args from the arg parser. :return: args (arg parser object). """ arg_parser = argparse.ArgumentParser() arg_parser.add_argument('-d', dest='debug', action='store_true', ...
51026faff016fe57e856c1c9e1a1b69d3d5d7067
10,078
import re def depListToArtifactList(depList): """Convert the maven GAV to a URL relative path""" regexComment = re.compile('#.*$') #regexLog = re.compile('^\[\w*\]') artifactList = [] for nextLine in depList: nextLine = regexComment.sub('', nextLine) nextLine = nextLine.strip() ...
52d27c3310a4fd17df857df4725079a4d93faa76
10,079
def configure_plugins_plugin_install_to_version(request, pk, version): """ View rendering for the install to version modal interface :param request: Request :param pk: The primary key for the plugin :param version: The version to install :return: a renderer """ plugin = get_object_or_40...
96e1076bdb84d6e0758d5ba03777a6576889cfdc
10,080
def _parameters_to_vector(parameters): """ This fix is required for pytorch >= 1.6.0, due to the change in memory format promotion rule. For more info, check: * https://github.com/pytorch/pytorch/pull/37968 * https://github.com/pytorch/pytorch/releases/tag/v1.6.0 and search "Note: BC-break...
f3b7d4cb8262cbbcbe2e5abace6e8e8162fb3a57
10,081
from utils.snowflake.id_worker import IdWorker from utils.limiter import limiter as lmt from utils.logging import create_logger from utils.converters import register_converters from redis.sentinel import Sentinel from rediscluster import StrictRedisCluster from models import db from .resources.user import user_bp from ...
1284a53c24d7fc4bf2ce0a0f00d6a3defea642d6
10,082
def select_variables(expr): """When called on an expression, will yield selectors to the variable. A selector will either return the variable (or equivalent fragment) in an expression, or will return an entirely new expression with the fragment replaced with the value of `swap`. e.g. >>> from ...
a147b1f1fc66373597b98085b13ffd326baf72e1
10,083
from typing import Callable from typing import Optional import glob def get_login(name_p: str, pass_p: str, auth_error: bytes = b'') -> Callable: """Decorator to ensure a player's login information is correct.""" # NOTE: this function does NOT verify whether the arguments have # been passed into the conne...
3b3a1eb36d92de373eab9414abef6dd44bf14502
10,084
import math def map_visualize(df: gpd.GeoDataFrame, lyrs='s', scale=0.5, figsize = (12,9), color = "red", ax = None, fig=None, *args, **kwargs): """Draw the geodataframe with the sa...
f59c72079f789e63ad7910e5c4ee62d93e5015e9
10,085
def unorm_to_byte(x): """float x in [0, 1] to an integer [0, 255]""" return min(int(256 * x), 255)
a6870a339b9b0d5466962a9129c717876d8d0a50
10,086
def eigh(a, largest: bool = False): """ Get eigenvalues / eigenvectors of hermitian matrix a. Args: a: square hermitian float matrix largest: if True, return order is based on descending eigenvalues, otherwise ascending. Returns: w: [m] eigenvalues v: [m, m]...
254f243bd5c70f606cc67111df03626a0eae25b0
10,087
def lowpass(x, dt, fc, order=5): """ Low pass filter data signal x at cut off frequency fc, blocking harmonic content above fc. Parameters ---------- x : array_like Signal dt : float Signal sampling rate (s) fc : float Cut off frequency (Hz) order : int, opti...
fd3cd4f7ccca9c2244c82420a560199633d082ab
10,088
def doRunFixPlanets(msName): """Generate code for running fixplanets on fields with (0,0) coordinates""" print('\n*** doRunFixPlanets ***') fieldIds = sfsdr.getFieldsForFixPlanets(msName) if len(fieldIds) != 0: casaCmd = '' mytb = aU.createCasaTool(tbtool) mytb.open(msName+'/...
2656505e91eeea545c1c91c169b183ac5dd5413a
10,089
def add_name_suffix( suffix, obj_names=None, filter_type=None, add_underscore=False, search_hierarchy=False, selection_only=True, **kwargs): """ Add prefix to node name :param suffix: str, string to add to the end of the current node :param obj_names: str or list(str), name of list of no...
c9355a5030c430d6efa6d8abc6b6d9128f77cb8e
10,090
def checksum(hdpgroup: list, algorithm: str = 'CRC32', chktag: str = '\'α') -> list: """List of checksums-like for detection of Non-intentional data corruption See https://en.wikipedia.org/wiki/Cksum See https://en.wikipedia.org/wiki/Checksum Args: hdpgroup (list): li...
66566fbef3c962d5bcdf56727ff66ddfdd8af9b7
10,091
def dsum(i0,i1,step = 1, box=[]): """ for a range of fits files compute the mean and dispersion from the mean """ for i in range(i0,i1+1,step): ff = 'IMG%05d.FIT' % i h1, d1 = getData(ff,box) #very specific for 16 bit data, since we want to keep the data in uint16 bze...
6e0048461e29a7de4f7c4322fa1e3213f8248e60
10,092
def _env_translate_obs(obs): """ This should only be used for the Tiger ENV. Parameters ---------- obs : list or array-like The observation to be translated. Returns ------- str A representation of the observation in English. """ if obs[0] == 1: return '...
761ff3f3269e41b44bdab098d3682630d928cdc6
10,093
def voter(address): """ Returns voter credentials. Parameters: address: address Returns: list of three values addresss (str), is_voter (bool), voted (bool). """ return contract.functions.voters(address).call()
91fd7adca6f8ed2e02dbe60b6241eb92f34a81b6
10,094
def E_disp_z(m, N, j_star=3.): """Vertical displacement as a function of vertical wavenumber.""" num = E0*b**3*N0**2 den = 2*j_star*np.pi*N**2 * (1 + m/beta_star(N, j_star))**2 return num/den
39e6b9b5d512d577c8109ecfb5657a0ef5a8ea42
10,095
def get_stereo_image(): """Retrieve one stereo camera image Returns: (mat): cv2 image """ img = core.get_stereo_image() if img is not None: return img else: return None
72e570672885e8ef8c14c9cd29d3f7c648f9abac
10,096
import time import requests def request_set_arm_state(token: str, arm_state: str): """Request set arm state.""" headers = { 'Authorization': 'Bearer %s' % token, 'Content-Type': 'application/json' } payload = { "Created": int(time.time()), "AppVersion": APP_VERSION, ...
28a8ad2a0d49305d80581c2257d3fb9495b3f680
10,097
def get_all_config(filename=None): """ Set default configuration options for configparse Config with defaults settings if no file will be passed Also with defaults sections and defaults keys for missing options in config :param filename: options config file to read :return: configparser object w...
9a5bdcd272f49be5bd8374e06f5b6579da91d64a
10,098
def check_for_end_or_abort(e): """Return a closure checking for END or ABORT notifications Arguments: e -- event to signal when the action is completed (will be set when an END or ABORT occurs) """ def check(notification, e = e): print("EVENT : " + \ Base_pb2.ActionEve...
91809c705666f4fd3aae7273760d5845fa35eadb
10,099