content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def riley_slice(a, b, max_denom, solver='mpsolve' if mpsolve_avail else 'scipy', **kwargs): """ Return an accurate approximation to the Riley slice. There are three possible solvers: the mpsolve solver (see https://numpi.dm.unipi.it/software/mpsolve), the solver built in to scipy foll...
df25eff8d798e7643cf01c4b87d4cbfced0433d1
3,600,100
import operator def gaussian_mixture_model( data, ntl_col='ntl2016', n_components=3, max_iter=1000, tol=1e-10, covariance_type='full', bin_labels=['low', 'medium', 'high'] ): """ Implements Gaussian Mixture Model (GMM) on the nighttime light intensities Parameters ---------- ...
754b2b34f2736d94206707eee8fc817a4272e1dd
3,600,101
import re def pretty_element(s): """ Returns formatted element name. Parameters ---------- s : str of format [A-Z][a-z]?[0-9]+ Returns ------- str LaTeX formatted string with superscript numbers. """ el = re.match('.*?([A-z]{1,3}).*?', s).groups()[0] m = r...
d67101fd7e55e5ff25b2f4e4d6db98eeffca06c8
3,600,102
def toLabel(x): """ Helper function for converting `x` to a single Label object """ if isinstance(x, _Label): return x # # do this manually when desired, as it "boxes" a circuit being inserted #elif isinstance(x,Circuit): return x.to_circuit_label() else: return _Label(x)
d68de645bb3c11f873ca184465fa279eed52c021
3,600,103
def tsps(x: np.ndarray): """Calculate tissue specificity score as defined in: > Ravasi, Timothy, Harukazu Suzuki, Carlo Vittorio Cannistraci, Shintaro > Katayama, Vladimir B. Bajic, Kai Tan, Altuna Akalin, et al. 2010. “An > Atlas of Combinatorial Transcriptional Regulation in Mouse and Man.” Cell ...
76962777299b537b6290abb8467f186dda235d02
3,600,104
def least_squares(y, tx): """Least squares regression using normal equations""" w = np.linalg.solve(tx.T@tx, tx.T@y) loss = compute_mse_loss(y, tx, w) return w, loss
172d4254aec8ac781206522daad082483088ba7a
3,600,105
def test_tensor_method_sub(): """test_tensor_method_sub""" class Net(Cell): def __init__(self): super(Net, self).__init__() self.sub = P.Sub() def construct(self, x, y): out = x - y return out.transpose() net = Net() x = ms.Tensor(np.on...
dc9ab1f371ee06cd90698eba9975728b3ec359a1
3,600,106
import re def grep(patterns, file_name): """ Search for the patterns in the given list in a file. Example: grep(["St9bad_alloc", "FATAL"], "athena_stdout.txt") -> [list containing the lines below] CaloTrkMuIdAlg2.sysExecute() ERROR St9bad_alloc AthAlgSeq.sysExecute...
4da0c77822bcf3e13f441dffb42e013a20fc6298
3,600,107
import re def all_whitespace(string): """ all_whitespace(string : str) -> bool >>> all_whitespace(' ') True Returns True if a string has only whitespace. """ return re.search('^[ \t]*(\r|\n|$)', string)
766b92da0b6e91fbcd05eed408cb5651cdf42b4e
3,600,108
from .multi import concat import fnmatch import tokenize import os def _read_single_hdf(path, key, start=0, stop=None, columns=None, chunksize=int(1e6), lock=None): """ Read a single hdf file into a dask.dataframe. Used for each file in read_hdf. """ def get_keys_and_stops(pat...
11e05cea832f07494f11ebda320abee8449ee669
3,600,109
def IsBattOrConnected(test_platform, android_device=None, android_device_map=None, android_device_file=None): """Returns True if BattOr is detected.""" if test_platform == 'android': if not android_device: raise ValueError('Must pass android device serial when determining ' ...
18378fbb8f7ced2ed5eba9536a40f664d3ca65d2
3,600,110
import copy import uuid import collections def deep_copy(item_original): """Return a recursive deep-copy of item where each copy has a new ID.""" item = copy.copy(item_original) item._id = uuid.uuid4().hex if hasattr(item, '_children') and len(item._children) > 0: children_new = collections.Or...
83c8ee5dd620e30a518391752905ba1966d27aa4
3,600,111
def converting_reactions(base): """Provide a model with a couple of converting reaction.""" a = cobra.Metabolite("atp_c", compartment="c") b = cobra.Metabolite("adp_c", compartment="c") c = cobra.Metabolite("gtp_c", compartment="c") c2 = cobra.Metabolite("gtp_e", compartment="e") c3 = cobra.Meta...
a6a4a158dd577031a613a6c70edfb266120aaf1d
3,600,112
def test_compile_too_high_bitwidth(default_compilation_configuration): """Check that the check of maximal bitwidth of intermediate data works fine.""" def function(x, y): return x + y function_parameters = { "x": EncryptedScalar(Integer(64, False)), "y": EncryptedScalar(Integer(64,...
62612b65e62fdea6b0b78a30848d9dc4251a4672
3,600,113
def reshape(x, shape, name=None): """ This operator changes the shape of ``x`` without changing its data. Some tricks exist when specifying the target shape. 1. -1 means the value of this dimension is inferred from the total element number of x and remaining dimensions. Thus one and only one dimen...
4c757d9e8d5bf649b64012dc169d349e138fc5e4
3,600,114
def calc_albedo_snow(ts, snow, dc=11.0, tc=21.9, a_ice=0.34, a_freshsnow=0.9, a_firn=0.53, **config): """ ! albedo calculated using 'time' - based on time since last snowfall(Oerlemans + Knap 1998) ! albedo = albedo output grid ! ts = time(days) since last snowfall ! snow = gr...
d29d2402e67db90afd541f358bdc8c1134a5da07
3,600,115
def normalise(X): """ here I mean make max 1 and min 0 and fit everything else in. should be by feature. X is np array returns X shame shape but normalised by feature. """ n,p = X.shape for column in range(p): X[:,column] = ((X[:,column] - np.max(X[:,column])) / (np.max(X[:,colum...
420696d9cbe689db2fdc60ba00acf248b6980038
3,600,116
import ctypes def unpack_udp_packet(packet: bytes) -> PackedLittleEndianStructure: """Convert raw UDP packet to an appropriately-typed telemetry packet. Args: packet: the contents of the UDP packet to be unpacked. Returns: The decoded packet structure. Raises: UnpackError if...
8b5d9416d4c922716e2d76116487ef1e800e5a18
3,600,117
import multiprocessing import concurrent import tqdm def Run(lines): """ Method runs the translation of graphs from g6 to lgi. Input: lines -- List with lines in g6-format Return: List with lines in lgi-format. """ num_in = len(lines) num_processes = multiprocessing.cpu_count() ...
469a2073c94108906e894b7afa5ca671a8cfbfec
3,600,118
import warnings def test_deprecate(deprecation_increment: int | None, details: str | None) -> None: """ Test the deprecation warnings/errors. If the removal_version is larger than the current, it should warn. If the removal_version is smaller or equal, it should raise an error. :param deprecatio...
43de52dddf41567d32a955ce15d6c52dff3e90dc
3,600,119
from scipy import signal def get_deimos_spec1d(fn, horne=False, smoothing=False, fixfile=True): """ Gets a reduced DEIMOS spec1d file's contents Parameters ---------- fn : str The spec1d file to load horne : bool If True, use the horne extraction, otherwise boxcar smoothin...
9a0248c838a61e582c8add51735e7042ac7e60f9
3,600,120
def edit_gallery(request, gallery_id): """ Edit an image in the gallery """ if not request.user.is_superuser: # Only superusers can edit products messages.error(request, 'Sorry, only store owners can do that.') return redirect(reverse('home')) gallery = get_object_or_404(Gallery, pk...
7681a512cfdd01c7de284a91c5d61e7294aeca34
3,600,121
def getItemUrlFromHasOfferUrl(has_offer_url): """ http://ho.lazada.vn/SH3gPd?url=http%3A%2F%2Fwww.lazada.vn%2Festar-ce390a-muc-in-laser-90a-den-238124.html%3Foffer_id%3D%7Boffer_id%7D%26affiliate_id%3D%7Baffiliate_id%7D%26offer_name%3D%7Boffer_name%7D_%7Boffer_file_id%7D%26affiliate_name%3D%7Baffiliate_name%7D%...
dd820521e8d1307f2f2570841a8fae62e4d59ae7
3,600,122
import sys def use_sys_args(): """ Parse the command line arguments using sys.args. """ # There are 2 possible ways to achieve the result in one line. # One using a map: # return sum(list(map(int, sys.argv[1:]))) # or using a list comprehension. return sum([int(i) for i in sys.argv[1:]]) ...
790b50332755d5a35637fa7ab9f33b41a89fc32f
3,600,123
import os def test_fetch(cfg, fold, sub_cond): """Return test data for a certain fold, based on the subject conditions. Parameters ---------- cfg: main.Configuration Configuration file fold: int current k-fold sub_cond: str seen/unseen subject conditions Returns ...
6b00091c84908949342df580e46c3a680cd470f6
3,600,124
from operator import concat def ppipe(iterable, func, chunk_size=1): """Multi-core pipe.""" out = pmap(func, iterable, chunk_size) return list(concat(out))
c1b24b6305e64a0b3ec548d1154a1cc637cde053
3,600,125
def gourgou(c,R=1): """ renvoie une fonction qui donne t en fonction de r dans une métrique de E. Gourgoulhon où la particule commence à la position c et atteint un horizon des évènements en R """ return (lambda r : c - r/R - np.log(abs(r/R)))
deb52b7e7e8f5bb66ada52096ca4275f85ea1953
3,600,126
from typing import Dict from pathlib import Path def train( dataset: Dict[str, pd.DataFrame], params: str, dataset_name: str = "winequality" ) -> None: """Train a model and save it to disk Args: dataset (Dict[str, pd.DataFrame]): The train and test sets. params (Dict[str, object]): The pa...
1c8906bdf10e2142d91dab99f758c0fe708c5c2a
3,600,127
def int_type(attribute: str): """ Auto-adds an ``__int__`` using the ``__int__`` of some attribute. Used to annotate a class as being "essentially an integer". Args: attribute: The name of the attribute of this class """ def __f(self): return float(getattr(self, attribute)) ...
b58b81fb9a3201b56435a54d178aec456fce2cf0
3,600,128
import os import json def diff_location(): """ :params none Returns the non-repeated address co-ordinates """ loc = input('Enter facebook archive extracted location: ') if not os.path.isdir(loc): print("The provided location doesn't seem to be right") exit(1) ...
b1ef5e3c4fd85351b45de5d33e54458f626333d2
3,600,129
import os def get_files(): """Get a list of files/folders in the cwd""" return os.listdir(os.getcwd())
4888620176a33a3ad97b49af7e532fd4f53bf8e3
3,600,130
import re import hashlib def auth(i): """ Input: { (web_vars_post) (web_vars_get) (web_vars_session) } Output: { return - return code = 0, if successful > 0, if error (error...
2ab5cf59a93c2926a1f3dcc92d9886a4b8d91b9c
3,600,131
def start_triage(): """ The endpoint Slack will start a new triage when recive "/triage" command. If user already exist, restart it :return: """ if verify_slack_token(request_token=request.form["token"]): if "command" in request.form and request.form["command"] == "/triage": ...
9cbf48ce5018bfaf3eaf6684e7e5570a6e32a6e9
3,600,132
def two_factor_setup(): """View function for two-factor setup. This is used both for GET to fetch forms and POST to actually set configuration (and send token). There are 3 cases for setting up: 1) initial login and application requires 2FA 2) changing existing 2FA information 3) user want...
79832821d006e94dac5b4a04350750a9f1086e76
3,600,133
def newDirectory(parent, path, name = None, owned=False, define=False): """ Creates a new Directory location :type parent: location :param parent: parent location :type path: string :param path: the path for this directory (name of directory) :type name: string :param nam...
3cf16f1256c8af79ef242d2e5fb7703f4f2ef91c
3,600,134
import os import imp def find_module(modname): """Finds and returns a module in the local dist/checkout. """ modpath = os.path.join( os.path.dirname(os.path.dirname(__file__)), "Lib") return imp.load_module(modname, *imp.find_module(modname, [modpath]))
ef308748c969889459abaef511bbf071d0ab6fe9
3,600,135
import logging def evaluate_sensitivity (dataset,subgroup,targetColumn): """Returns the Sensitivity of a subgroup.""" #Get confusion matrix cf = confusion_matrix(dataset,subgroup,targetColumn) #Calculate sensitivity sensitivity = cf[0][0] / (cf[0][0] + cf [0][1]) logging.info('Sensitivity...
c0e687f26712458619a5508d45a91bcc5c949030
3,600,136
import urllib import json def boshio_release_to_source(resource): """Look up the github source for a given bosh release Args: resource (dict): A bosh-io-release resource from a concourse pipeline Returns: tuple(str, str): The url to the repo, and the branch """ bosh_api_url = "h...
d9f40fcb56d9b3f08e570f38d519390f91789d26
3,600,137
def string_empty(string): """Return True if the input string is None or whitespace.""" return (string is None) or not (string and string.strip())
fddb1e639a57b29674ce6d0a101e875272731d77
3,600,138
from nautilus import models def MockModel(name='TestModel'): """ This function returns a nautilus model to use throughout the test suite. """ # local imports # return the mocked model return type(name, (models.BaseModel,), { 'name': models.fields.CharField(null=True), 'da...
ebfa5aa5e8624ed75137b15a04330a4efe26e226
3,600,139
import itertools def get_hoi_dataset_dicts(dataset_names, filter_empty=True): """ Load and prepare dataset dicts for HOI detection. Args: dataset_names (list[str]): a list of dataset names filter_empty (bool): whether to filter out images without instance annotations min_keypoints...
db6006f9360a00db5437346f57df0bcde84b856f
3,600,140
def memoize(user_function): """Memoization decorator for user function of 1+ parameters""" class Memodict(dict): """Memoization performs user function call on dict miss""" def __getitem__(self, *key): return dict.__getitem__(self, key) def __missing__(self, key): ...
e8f59f5e4460e332ff88bb235a6d8beb31065de2
3,600,141
import google.auth.compute_engine as google_auth_gce def IsGceAccountCredentials(cred): """Checks if the credential is a Compute Engine service account credential.""" # Import only when necessary to decrease the startup time. Move it to # global once google-auth is ready to replace oauth2client. # pylint: dis...
2b3b4331d5dbdc7c2dc9b049376386803d87c70c
3,600,142
import urllib def google_search(query, resultsToRetrieve, userAgent, sleepDelay=1): """ perform google search and handle exceptions """ try: search_results = search(query, stop=resultsToRetrieve, user_agent=get_random_user_agent()) #search_results = ["test result 1","test result 2"] if search_results != Non...
b51b1f6deaac6449ab19ca29b470897704dab982
3,600,143
def Dic_Test_Empty_Dic(indic): """ check if indic is a (nested) empty dictionary. """ if indic.keys()!=[]: for key,keydata in indic.items(): if isinstance(keydata,dict): if keydata=={}: pass else: return Dic_Test...
360e9190fd6ab23fb1d8b4d948647baed494f417
3,600,144
def _new_package_name(src,volume,src_chimera_file): """ return package file name src=/pnfs_path/<old_volume>/<package> to /pnfs_path/<volume>/<package> @type src: str @param src: source package full path @type volume: str @param volume: destination volume name ...
5078ddc562d1af65db4ef4277c8121c7e7abccd7
3,600,145
def session_factory(connection): """ pytest対象モジュールの引数に"session_factory"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 """ engine = create_engine(connection) session_factory = sessionmaker(bind=eng...
296d153f72a5eadf93c46015f36c1533c78c9b0a
3,600,146
def choose_OD(pos_OD, OD_no): """Chooses nodes for OD matrix according to their population size stochastically and probabilistically Args: pos_OD (list): a list of tuples representing the nodes and their population OD_no (int): Number of OD pairs to create Returns: OD_nodes [list]...
4df8f454eb436340d818fdd3923ebab3fac2f7bb
3,600,147
def nplml(theta, X, y, kernel, nugget=1e-10): """Compute the log marginal likelihood using numpy default solve (slower than cholesky)""" kernel_clone = kernel.clone_with_theta(theta) K = kernel_clone(X) K[np.diag_indices_from(K)] += nugget alpha = npsolve(K, y) # Compute log-likelihood (compare ...
6fc5a6a662138218dcb2ba64bd6c41a1f74e08de
3,600,148
def group_pairs(pairs, ret_dict=True): """ Taken from first example in https://docs.python.org/3/library/collections.html#defaultdict-examples :param ret_dict: :param pairs: :return: """ groups_dict = defaultdict(list) for key, val in pairs: groups_dict[key].append(val) if r...
93837dfb583d35547ae9baa8d9618186b2465606
3,600,149
def start_day_accept_order(): """ Получает день недели (0 - 7) с которого разрешён приём заказов. Переносит разрешаемый день на 1 один день вперёд, если текущее время больше, чем разрешённое для совершения заказа. Returns: int: `0 - 7`, то есть от понедельника до следующего понедельника. ...
a85487952c9ae65803507adcfaf86da98e9a34d8
3,600,150
import warnings import sys import joblib import boto3 def load_model(model_name, platform = None, authentication = None, verbose=True): """ This function loads a previously saved transformation pipeline and model from the current active directory into t...
19cf892f334942c368d043d41620abdc723185c8
3,600,151
def load_and_resize_image(img_path): """ Creates a tkinter image variable that can be displayed on GUI This function receives a filename as a parameter. This should be the name of a file containing a digital image. The file is first open and stored as a Pillow image file. It uses the Image.size prope...
d3cba268b50a1f4e439f251ae11f27213f9f122b
3,600,152
import os def bws_param_evaluation(): """ [Legacy] An older version of the BWS parameter evaluation. This version included a concept of bias windows; regions within weight space where biases would have an effect. This was later found to be superfluous and somewhat inelegant, so the concept was...
1051ca586097339a53f67e640bc396d652c2df6d
3,600,153
from sys import base_prefix def convert_base(src_number, target_base, src_base=None): """Convert the number to the specified base >>> convert_base(10, 2) '1010' >>> convert_base('10', 2) '1010' >>> convert_base('10', 10, src_base=8) '8' >>> convert_base('10', 10, src_base=10) '10'...
8d8afead3982b58aea36d84e7f4e55cc0d9a2d63
3,600,154
def peak_assignment(unknownhdf5_filename, key, knownhdf5_filename, external_peak_labels, precision=10, externallabelinput=True, plot=True): """ This function is a wrapper function from which all classification of peaks occurs. Parame...
43567b3065348116184a809cf7cccfc1b3ccdb65
3,600,155
import textwrap def make_settings(pypirc): """Returns a factory function for settings.Settings with defaults.""" default_pypirc = """ [pypi] username:foo password:bar """ def _settings(pypirc_text=default_pypirc, **settings_kwargs): pypirc.write(textwrap.dedent(pypirc...
48a694173a1fe97b621909525bf2681e08140bcb
3,600,156
def kernels(ell, cs, eig, D, A, G=DEFAULT_G, alpha=None): """Returns the density and squared sound speed kernels. I have tried to make this as notationally similar to Gough & Thompson (1991) as possible. The kernels are normalized to have unit integrals over the radius *r*. Parameters ...
d73a243a1e866cb28afc77af777648292c530fcb
3,600,157
from datetime import datetime import time import sys def do_run(args): """ Build a simulation queue based on the specified args and process it """ run_queue = Queue(maxsize=0) out_queue = Queue(maxsize=0) _LOG.info('Queueing the following targets to simulate:') excludes = read_excludes...
1af60ca8aa939d633c18a575e3e6dafa4dee7717
3,600,158
def zonal_levels_trend(ds): """ calculated trend for depth-lat_bin field input: ds .. xr Dataset ds.OHC_zonal_levels [J m^-2] output: trend .. xr DataArray containing trends of OHC [J m^-2 year^-1] """ assert 'OHC_zonal_levels' in ds dn = ('TLAT_bins', 'z_t'...
9e98a38a8683f0e11bda8322475ed168539d2be8
3,600,159
def ignore_unique(f, decorated_obj, args, kwargs): """ Ignores exceptions caused by unique constraints or indexes in the wrapped function. 'ncm' = non class method (version) """ dbsess = _find_sa_sess(decorated_obj) try: return f(*args, **kwargs) except Exception as ...
312b60527b2672cfdf94b7b0a78cf471dea3651e
3,600,160
def sell(): """Sell shares of stock""" if request.method == "POST": # ensure symbol was submitted if not request.form.get("symbol"): return apology("must provide symbol", 403) # ensure no. of shares was submitted elif not request.form.get("shares"): retu...
b83234407761942d0fb7ce74a83b75bcde4358b7
3,600,161
import imghdr def detect_image_type(filename): """ 获取图像文件类型 :param filename: :return: jpge|png|gif|tiff等。失败返回None """ return imghdr.what(filename)
a4701aa60927e730899ed8036d6f2d875aa0524a
3,600,162
from .motor_joint import Motor def motor(shape1, speed=5): """Creates a constant rotation of the given shape around its center point. The direction of rotation is controlled by the sign of the speed. Positive speed is clockwise, negative speed is counter-clockwise. :param shape1: The shape to c...
4ba4b2b2439ebadf7ffdb8e9b8ee7c35bc3e0ce4
3,600,163
import os def check_result(image_path, alose_list, file_lose_list): """ :param image_path: 切割出得数字标签区域保存位置 :param alose_list: 丢失的帧+ocr识别中被漏掉的帧,设置alose_list的原因是为了减少SIFT对比计算量 :param file_lose_list: ocr识别中被漏掉的帧 :return: 真实丢失的帧alose_list - file_lose_list """ for image in file_lose_list: ...
cd8cdcfeefc3af8cc26141c8f0077c875e955d9c
3,600,164
def build_stream(df,h5,line, wftype, filt, freq_min, freq_max): """ Build the Streams from events data in counts saved in hdf5 files as np.array line : integer, line number of the hdf5 File to plot wftype : str, waveform type 'ev_c', 'ev_gm' or 'noise' for events in counts, events in ground motion unit...
f78c58179d80e00b0841fe3539eda920c92d096c
3,600,165
def allowed_file(filename): """Checks if the extension of the given file is in ALLOWED_EXTENSIONS""" return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
f9d0bf2d2f9f3155bb04a499f78828126046568a
3,600,166
def english_to_french(english_text): """english to French translation""" translation= language_translator.translate(text=english_text, model_id="en-fr").get_result() french_text=translation['translations'][0]['translation'] return french_text
141fbd5eeed94cd8ec612e6483a711d1c2e6630f
3,600,167
def square_error(P, R, Γ, v): """Square error (SE), the combination of squared bias and the variance.""" bias = value_error(P, R, Γ, v) variance = sobel_variance(P, R, Γ) return variance + bias ** 2
cb7e3b4cad6b23f50a7f51433146ac30085292d0
3,600,168
import copy def build_sac_model( policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: AlgorithmConfigDict, ) -> ModelV2: """Constructs the necessary ModelV2 for the Policy and returns it. Args: policy: The TFPolicy that will use the models. obs_...
4edf4947d472fe5c3e163ad9ac963f145cf7ac86
3,600,169
def multiscan_file(file): """Deprecated API - use one of the Clamd*Socket classes instead.""" return socketinst.multiscan_file(file)
c9d175d44ce2d6aa63c2533adc5a893ede035ac7
3,600,170
def update_ports_tree(ports_tree): """ Updates the ports tree, either the default or the `ports_tree` specified CLI Example: .. code-block:: bash salt '*' poudriere.update_ports_tree staging """ _check_config_exists() if ports_tree: cmd = "poudriere ports -u -p {}".format(...
fc50e6209a6c53bde236d23f762614f0f7c69865
3,600,171
import numpy as np import tensorflow as tf import torch import random def apply_seed(seed=None): """Applies a global random seed to the application state. In particular, the method seeds Python's random module and numpy, tensorflow and pytorch packages if available. Arguments: seed: Int|None, the ra...
f7f4a9bc87fbc156482491611b557299c44b73a4
3,600,172
from typing import List from typing import Tuple def calculate_coefficients(data_points: List[List[float]]) -> Tuple[int]: """Calculate coefficients for an approximate linear mapping of batch size to inference time. Uses ordinary least squares to find the coefficients alpha and beta in the following: inf...
4ab279e3c72ab41b2273cf584a9c66b6a2de00e9
3,600,173
def news_review(): """ 需审核新闻页面显示 :return: """ page = request.args.get("page", 1) keywords = request.args.get("keywords", "") try: page = int(page) except Exception as e: current_app.logger.error(e) page = 1 news_list = [] current_page = 1 total_page ...
792afdcdb8aea002bb6c1eb9e47d3dfbbaeac3d1
3,600,174
def format_link_mutation(mutationname: str, identifier_1: str, identifier_2: str): """Create a mutation with link between two identifiers to send to the Contributor Environment. Arguments: mutationname: the name of the mutation to generate identifier_1: The unique identifier of the first object....
f9cfe5fad253872312a60bebb372ca1c723231d3
3,600,175
def model_to_request_body(body_model, content_type, body_model_root_element=None): """ Convert a Python dict (body model) to XML or JSON :param body_model: Model to be parsed. This model should have a root element. :param content_type: Target representation (Content-Type header value) :param body_mo...
6d2310b8a35bb108bec6f43ad4bc4ba5d7ba0bb5
3,600,176
def _get_ext_net_obj(ctx, name): """Returns ExternalNetwork object.""" platform = _get_platform(ctx) client = ctx.obj['client'] return ExternalNetwork( client, resource=platform.get_external_network(name))
994a55c06e20271b5da6b95eb36dc54f225f6346
3,600,177
from typing import List import torch from typing import Tuple def to_bi_tgt_out( tokens: List[List[int]], device: torch.device ) -> Tuple[LongTensor, LongTensor]: """Generate bidirection tgt and out Parameters ---------- tokens : List[List[int]] indices: [b, l] device : torch.device ...
c6440c7a7e8883275053e6686b735635252c9776
3,600,178
import json def to_formatted_json(output): """Output is a single record""" return f"{json.dumps(output, indent=4)}\n"
e437c8b34e510f6a72cc27ccb7b2a14c3f60e09d
3,600,179
def _permutation_worker(k: int, items: list) -> list: """The kth Johnson-Trotter permutation of all items.""" n = len(items) if n <= 1: return items else: group = k // n item = k % n position = n - item - 1 if group % 2 == 0 else item dummy = _permutation_worker(g...
c997721d2682a9bf54b42596b093956bc17cf94b
3,600,180
def getCoeffs(airfoilCode, alphaDeg): """ Calculates CL and CM at alphaDeg for NACA 4,5-digit airfoil """ if checkAirfoilType(airfoilCode) == 'NACA4': th, x, y, dy = getNACA4(airfoilCode, _nPoints) elif checkAirfoilType(airfoilCode) == 'NACA5': th, x, y, dy = getNACA5(airfoilCode, _nPoints) ...
3776fe4ae53724a86a5e13171d5e04b50c95e1a7
3,600,181
def matrix_vector_elementwise_multiply(data, multiplier, axis=None): """Elementwise multiply a matrix by a vector. Parameters ---------- data : array-like, shape=[n_samples, n_features] Input data multiplier : array-like, shape=[n_samples, 1] or [1, n_features] Vector by which to mu...
7094d2a77875a1cebe3844fb7d35c6a0524edac5
3,600,182
def vectorize_abc(df): """ takes an abc string and returns the note vector and timing vector, split by bars """ abc_string = df['abc'] accs, mod = get_sharps_or_flats(df['mode']) note_out = [] time_out = [] for bar in split_by_bar(abc_string): note, time = vectorize_bar(bar, acc...
10e26130f21c9ddab0397155f8ea5636bf5947b7
3,600,183
def update_config_value_by_config(config_to_update, config): """Update config_to_update according to config Example: Arguments: config_to_update: { "a": "b", "c": { "d": "e", "f": "g", }, } ...
f99366f7b434fa0c47bfc279cbd04d3b4e4d0af9
3,600,184
def tiny_vgg_p3(cfg, i=3, batch_norm=False): """This function is derived from torchvision VGG make_layers() https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py""" layers = [] in_channels = i for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, str...
7e2647a903fd57025f8888bc6a0d647fb2dc3ed2
3,600,185
def delete_versioned_object(connection, bucket_name, obj): """ Perform a delete on a versioned object, the requirements for these types of requests is to be able to pass the ``versionID`` as a query argument """ # if obj.delete_marker is False we should not delete this and we shouldn't # have be...
2ab191efd907f814af505b52a6f2a571ef9df036
3,600,186
def list_attributes(msg_type): """List all attributes with type description of a GRPC Message class.""" return [(f.name, get_field_description(f)) for f in msg_type.fields]
99cdcaa22672c129b3fd23ec17952a50cc755fbd
3,600,187
import sqlite3 def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file """ return sqlite3.connect(db_file)
4f134ebcf1d6cac0905e7966717c53a51df9902d
3,600,188
from typing import Tuple from typing import Callable def compose(*args: Tuple[Callable[[np.ndarray], np.ndarray]]) -> Callable[[np.ndarray], np.ndarray]: """composes given mappings """ assert len(args) > 0, 'Function compose requires at least one mapping as its parameter.' def _t(x: np.ndarray) -> np...
fa5e0a559b3ca5d0b85e96c4cf113bfd537bd502
3,600,189
def dot(q1,q2): """ Dot product of two quaternions >>> import qmathcore >>> a = qmathcore.quaternion('1+2i-2k') >>> b = qmathcore.quaternion('3-2i+8j') >>> qmathcore.dot(a,b) -1.0 """ Q1 = quaternion(q1) Q2 = quaternion(q2) return np.dot(Q1.q,Q2.q)
fb6a69c5715e53a8875cb83356b5828d38656f00
3,600,190
from typing import Dict def _results_data_row(row: Dict[str, str]): """ Transform the keys of each CSV row. If the CSV headers change, this will make a single place to fix it. """ return { "k": row["Key"], "v": row["Content"], }
97dc7f9842d7e6a564cbe66fd93e3dbaeca08517
3,600,191
import random def _trial_greedy_ssa_path_and_cost(r, inputs, output, size_dict, choose_fn, cost_fn): """A single, repeatable, greedy trial run. Returns ``ssa_path`` and cost. """ if r == 0: # always start with the standard greedy approach choose_fn = None else: random.seed(r) ...
c4dc7e311fe9bb377e548136d57c20a560ce06e2
3,600,192
def to_border_vtxfaces(components): """ [pm] """ if not components: return components if isinstance(components, list): pn = not is_string(components[0]) else: pn = not is_string(components) faces = to_face(components) inner_vf = to_vtxface(faces) border_vertices...
149626d156721b16df4e721c4cfd6b73955cb092
3,600,193
import logging def export_campaigns(api, assessment_id): """Add all the campaigns' data for an assessment to a list. Args: api (Gophish API): Connection to Gophish server via the API. assessment_id (string): Assessment identifier to get campaigns from. Returns: List of the assess...
69adc946cfc9dba1b4b87298fbbd0f9652d2b043
3,600,194
def build_cross_entropy_loss(logits, gold): """Constructs a cross entropy from logits and one-hot encoded gold labels. Supports skipping rows where the gold label is the magic -1 value. Args: logits: float Tensor of scores. gold: int Tensor of one-hot labels. Returns: cost, correct, total: the to...
192c09d334f3c155c9b0f6e3b78358468de86bb8
3,600,195
def wilcoxon_sgned_rank(ds1, ds2, alpha=0.05): """ is a non-parametric statistical hypothesis test used to compare two related samples, matched samples, or repeated measurements on a single sample to assess whether their population mean ranks differ (i.e. it is a paired difference test). """ ...
c455967fd915466761dc45517200779d5cecd0b1
3,600,196
import six def unwrap_placement(comp): """Strips `comp`'s placement, returning a single call to map, apply or value. For this purpose it is necessary to assume that all processing under `comp` is happening at a single placement. The other assumptions on inputs of `unwrap_placement` are enumerated as follo...
55a816f3e10bb5cf6a5635dda7a5df001631b232
3,600,197
def to_weight(df: pd.DataFrame, renorm=True): """ Converts molar quantities to mass quantities of the same order. Parameters ----------- df : :class:`pandas.DataFrame` Dataframe to transform. renorm : :class:`bool`, :code:`True` Whether to renormalise the dataframe after convert...
e4c50667ca44e12767d501c07aff00eb7bdec59b
3,600,198
def address_from_public_key(pubkey: bytes) -> str: """Extracts public key from an address Ripple address is in format: <1-byte ripple flag> <20-bytes account id> <4-bytes dSHA-256 checksum> - 1-byte flag is 0x00 which is 'r' (Ripple uses its own base58 alphabet) - 20-bytes account id is a ripemd16...
b8b56dce86239e270ea856c4a1ea75d1b9b305bd
3,600,199