content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_policy_list(cluster_name): """ 获取存储策略列表 :param cluster_name: :return: """ data = [] status = '' message = '' resp = {"status": status, "data": data, "message": message} pm = PolicyManager(cluster_name) try: sfo_policys = pm.policys() for policy in sfo_...
5b53acebbd7eaf52975bf393a4b4f87c7fe7e550
33,404
def package_air_ticket(request): """ view air ticket package for customer """ air_tickets = AirTicket.objects.all()[::-1] package_air_tickets = PackageAirTicket.objects.all()[::-1] context = { 'air_tickets': air_tickets, 'package_air_tickets': package_air_tickets, 'user_inf...
0e7f70d3f49d6a5ef25f669d3f58768e933050b2
33,405
def CheckNodeJSPackage(package): """ Check whether a node.js package is installed """ cmd = "node -e \"var d3=require('%s');\"" % package x = RunCommand(cmd) return x == 0
ba6709f641548bab52aafdc589f4730268b3b778
33,406
import re def compilable(tex): """Return tex-math content wrapped so that it can be compiled using tex.""" # remove "\usepackage{pmc}". It's not clear what the contents # of this package are (I have not been able to find it), but # compilation more often succeeds without it than with it. tex = te...
8381999e503194d7d9f2a1fbe751775a6bf48dd2
33,407
def filter_matches(matches, threshold=0.75): """Returns filterd copy of matches grater than given threshold Arguments: matches {list(tuple(cv2.DMatch))} -- List of tupe of cv2.DMatch objects Keyword Arguments: threshold {float} -- Filter Threshold (default: {0.75}) Returns: li...
c2cbec1da42d96575eb422bfdda6a1351e24508b
33,408
def V_PT(P, T, substance, eos = IDEAL_GAS): """Returns specific volume.""" mw = get_parameter(substance, 'molecular-weight') Vmol = eos.Vmol_PT(P, T, substance) return Vmol / mw
776164131c2e59295bcdf1100697c5ca84931074
33,409
def checks(poly_fit_left, poly_fit_right, poly_fitx_left, poly_fitx_right, poly_fity): """Check if found lanes make sense.""" # check curvature y_eval = np.max(poly_fity) curvature_left = (((1 + (2*poly_fit_left[0]*y_eval + poly_fit_left[1])**2)**1.5) /...
a5d2a807a29dfacc4b184aa591577161c3c5933c
33,410
from pathlib import Path def run( dataset_file: str = Path.joinpath(DATA_DIR, "processed", "winequality_clean.csv"), params_file: str = Path.joinpath(MODELS_DIR, "params.json").read_text(), ): """ Run the training process """ dataset = load_dataset(dataset_file) train_test = split_dataset(...
f2f82baebe910a8ada8dbfe77791e33d2a72e168
33,411
import string import random def createRandomStrings(l,n,chars=None,upper=False): """create list of l random strings, each of length n""" names = [] if chars == None: chars = string.ascii_lowercase #for x in random.sample(alphabet,random.randint(min,max)): if upper == True: ...
678b5aeb3cc98ae2b47822500fcbaff05081058a
33,412
def create_model(reader_input, base_model=None, is_training=True, args=None): """ given the base model, reader_input return the output tensors """ labels = reader_input[-1] cls_feats = base_model.final_sentence_representation cls_feats = fluid.layers.dropout( x=cls_feats, ...
9afcb97036c959ddf476e9844ab18cdf792ddbbd
33,413
def shot_mix(df1): """ Calculates the average of the poisson models for shots and shots on target """ df1["H_att_Poi_mix"] = (3*df1["H_att_PoiS"] + 3*df1["H_att_PoiST"] + 2*df1["H_att_PoiG"]) / 8 df1["A_att_Poi_mix"] = (3*df1["A_att_PoiS"] + 3*df1["A_att_PoiST"] + 2*df1["A_att_PoiG"]) / 8 df1["H...
6d7fe94ce4e90de26d0c5154ad2d0ae54d7409ca
33,414
def jobs(): """ lista de jobs """ rows = db(db.job).select(orderby=db.job.created_on) return locals()
067d7f9840cdd0ee52c7c2fefe3d5942170203c3
33,416
import base64 async def reserve_subdomain(request: Request, req: t.Optional[ReservationRequest] = None): """ Reserve a subdomain for use with an application. If no subdomain is given, a random subdomain is reserved and returned. If a set of SSH public keys is given, they are associated with the subd...
11d56868f6a0f4439ada5ad0755333c1b0ad9f74
33,417
def get_previous_quarter(today): """There are four quarters, 01-03, 04-06, 07-09, 10-12. If today is in the last month of a quarter, assume it's the current quarter that is requested. """ end_year = today.year end_month = today.month - (today.month % 3) + 1 if end_month <= 0: end_year -= 1 end_mo...
4175c80d2aa75c0e3e02cdffe8a766c4a63686d0
33,418
def extract_metadata(document): """Return the dict containing document metadata. :param document: :type document: :class:`docutils.nodes.document` :returns: docinfo data from document :rtype: dict From: https://github.com/adieu/mezzanine-cli @ mezzanine_cli/parser.py License: BSD (https://...
8c097569d240cc32ffc4496eda0e1e14e5269052
33,420
import scipy def ibp_loglik(Z, alpha): """Probability of an assignment matrix drawn from an IBP prior, where each customer chooses new dishes consecutively from the end, but otherwise the columns are unordered.""" N, K = Z.shape total = K * np.log(alpha) new_dish_counts = np.bincount(first_custome...
89178a93d32aefc7e1557363e27db4c6f2e9ee43
33,422
def neighbours(geohash): """ Returns all 8 adjacent cells to specified geohash:: | nw | n | ne | | w | * | e | | sw | s | se | :param geohash: string, geohash neighbours are required of :returns: neighbours as namedtuple of geohashes with properties n,ne,e,se,s,sw,w,nw ...
1fd5a515e9e72cc62b98d7cda57592ae1faa1595
33,423
def get_payload(address): """ According to an Address object, return a valid payload required by create/update address api routes. """ return { "address": address.address, "city": address.city, "country": str(address.country), "first_name": address.first_name, ...
34fde5090aae774a24a254ea7dd7f03cc0f784be
33,424
def new_alphabet(shift): """ :param shift: int, The magic number that user input to produce shifted. :return: str, a new_alphabet will be returned. """ first_half = ALPHABET[shift:] second_half = ALPHABET[:shift] # first_half = ALPHABET[(26 - shift):] # second_half = ALPHABET[0:(26 - shi...
71f3bf1c48647d8bc7641cb3070acebdb1d0170f
33,425
def _tensor_equal_tensor(x, y): """ Determine if two tensors are equal. Args: x (Tensor): first input tensor. y (Tensor): second input tensor. Returns: bool, if x == y return true, x != y return false. """ return F.equal(x, y)
a1149d02b520a79584a28c57424a4c1dfbdd4021
33,426
def CleanUnicodeString(s, separator=None): """Return list of words after lowering case and may be removing punctuations. Args: s: a unicode string. separator: default is None which implies separator of whitespaces and punctuation is removed. Returns: Lowered case string after removing runs of ...
c017cfd99d2153e3f10716f3664f665f315ecd89
33,427
def compute_cumulants(G, mus, R=None, return_R=False): """ Compute the cumulants of a Hawkes process given the integrated kernel matrix `G` and the baseline rate vector `mus` Arguments --------- G : np.ndarray The integrated kernel matrix of shape shape dim x dim mus : np.ndarray ...
1c1b48147af0b2d46f87d1f6050137d778db3e97
33,428
def interp_2d_to_3d(gs, grid, gt): """Interpolate 2D vector to a 3D grid using a georeferenced grid. Parameters ---------- gs : geopandas.GeoSeries Input geopandas GeoSeries grid : array_like 2D array of values, e.g. DEM gt : tuple GDAL-style geotransform coefficients fo...
fe0ae9ee3bb65a2b7ab255bb228a5d4411790d2d
33,429
import traceback def norecurse(f): """Decorator that keeps a function from recursively calling itself. Parameters ---------- f: function """ def func(*args, **kwargs): # If a function's name is on the stack twice (once for the current call # and a second time for the previous...
e7c7bebbbebcf53dad6772862f9ed4287c19a13d
33,430
def compare_model(models_list=None, x_train=None, y_train=None, calculate_accuracy=False, scoring_metrics=None, scoring_cv=3, silenced=False): """ Trains multiple user-defined model and pass out report Parameters ---------------- models_list: list a list of models to be trained ...
23f35fe1db665fe9b71262392a964d5562d09c69
33,431
def Material (colorVector): """ Material color. """ if colorVector == None: return None else: assert isinstance (colorVector, (list, tuple)) assert len (colorVector), 3 for cid in range (0, 3): assert colorVector[cid] >= 0 assert colorVector[ci...
89cee73c485669786f1a7cc4855ad8460c9db023
33,432
from typing import Callable def linear_objective( weights: np.ndarray, samples: np.ndarray, labels: np.ndarray, loss_fn: Callable ) -> float: """Calculates the final loss objective for a linear model""" # Compute scores for loss z = (samples @ weights) * labels # Mean loss over batch loss = np...
feac29c0d516897ac3c30c70c50364ff32407669
33,433
import itertools import pathlib def jpg_walk(path: str, filter_types: list) -> list: """ 获取指导目录全部的图片路径 """ with checkTimes("image walker"): pools = list( itertools.chain( *[ list(pathlib.Path(path).glob(f"**/*.{types}")) f...
53524f3758601fbdc5f7664c234d30b995dd48ab
33,435
import math def auto_border_start(min_corner_point, border_size): """Determine upper-right corner coords for auto border crop :param min_corner_point: extreme corner component either 'min_x' or 'min_y' :param border_size: min border_size determined by extreme_frame_corners in vidstab process :return:...
e09d48a8c8c59053516357cbfd320cf92a080cc4
33,436
def val(model): """ 计算模型在验证集上的分数 """ top_k = 3 # 状态置为验证 model.eval() # 数据准备 dataset = ZhiHuData(conf.dev_data) data_loader = DataLoader(dataset, batch_size=conf.batch_size) # 预测 predict_label_and_marked_label_list = [] for i, batch in enumerate(data_loader): title, conte...
402bbcc829ec7e51e6ff70ab0c2b0a1b24b08c46
33,437
import array def regress_origin(x, y): """Returns coefficients to regression "y=ax+b" passing through origin. Requires vectors x and y of same length. See p. 351 of Zar (1999) Biostatistical Analysis. returns slope, intercept as a tuple. """ x, y = array(x, "float64"), array(y, "float64") ...
6466f5cb38e3be1070d25051161809018601f689
33,438
import configparser def bootPropsConfig(artifact, resources, targetDir, scalaVersion = "2.13.1"): """Create the configuration to install an artifact and its dependencies""" scala = {} scala["version"] = scalaVersion app = {} app["org"] = artifact.org app["name"] = artifact.name app["vers...
66b8a4d641b3b1728e1d99c3f7bd7104806cdc50
33,439
import requests def broadcast_transaction(hex_tx, blockchain_client=BlockchainInfoClient()): """ Dispatch a raw transaction to the network. """ url = BLOCKCHAIN_API_BASE_URL + '/pushtx' payload = {'tx': hex_tx} r = requests.post(url, data=payload, auth=blockchain_client.auth) if 'submitte...
34953d3cbdcd83b4fd9f7971214653f32466db63
33,440
def concat(inputs_list, axis=-1): """ Concatenate input tensors list Parameters ---------- inputs_list: Input tensors list axis: Axis along which to concatenate the tensors """ return tf.concat(inputs_list, axis=axis)
42bbe9ca6873ad9e66e13dd4fb29780a01c5e941
33,443
import torch def string_to_tensor(string, char_list): """A helper function to create a target-tensor from a target-string params: string - the target-string char_list - the ordered list of characters output: a torch.tensor of shape (len(string)). The entries are the 1-shifted ind...
eb6c7fcccc9802462aedb80f3da49abec9edc465
33,444
def unique_nrpzs_active_subquery(): """Returns unique NRPZS within active centers.""" return db.session.query(OckovaciMisto.nrpzs_kod) \ .filter(OckovaciMisto.status == True) \ .group_by(OckovaciMisto.nrpzs_kod) \ .having(func.count(OckovaciMisto.nrpzs_kod) == 1) \ .subquery()
f46f3424b460e12d7096f165055ec7cf291eef91
33,446
def retrieve_context_service_interface_point_total_potential_capacity_total_size_total_size(uuid): # noqa: E501 """Retrieve total-size Retrieve operation of resource: total-size # noqa: E501 :param uuid: ID of uuid :type uuid: str :rtype: CapacityValue """ return 'do some magic!'
5a018beed4c7352235b8f29425ac28f47717091b
33,447
def index(): """ Index page. """ return render_template('dashboard/index.html')
e12209bc31f0a7f118359e847a3c39bd1a79f557
33,448
def is_tax_id_obligatory(country): """ Returns True if country is in EU or is Poland. Returns False for others. """ if country.name in all_eu_countries: return True return False
f9ae6f1baff4f77b2c6255f85e57833a1b7cc830
33,449
def indexTupleToStr(idx): """ Generate a string contains all the lowercase letters corresponding to given index list. Parameters ---------- idx : list of int A list of indices, each should be in [0, 26). Returns ------- str A string that corresponding to the indices...
5f234cff34b530316b6a957de7604321a82a309b
33,450
def _LookupPermset(role, status, access): """Lookup the appropriate PermissionSet in _PERMISSIONS_TABLE. Args: role: a string indicating the user's role in the project. status: a Project PB status value, or UNDEFINED_STATUS. access: a Project PB access value, or UNDEFINED_ACCESS. Returns: A Perm...
f9188ca34476e29e743ea92f689097a41c8dcb35
33,451
def _add_sld_boilerplate(symbolizer): """ Wrap an XML snippet representing a single symbolizer in the appropriate elements to make it a valid SLD which applies that symbolizer to all features, including format strings to allow interpolating a "name" variable in. """ return """ <StyledLayerDescri...
971199333570d5bc7baefec88f35b92922ef6176
33,452
def calculate_distance(location1, location2): """Calculate geodesic distance between two coordinates with ellipsoidal earth model. Args: location1: tuple of (latitude, longitude) as floats in Decimal Degrees location2: tuple of (latitude, longitude) as floats in Decimal Degrees Returns: A float in me...
569ae6af353d772234359ed70ac65e732ef2732a
33,453
def user(): """ form传值变量名: email,call,signature,mail,pre_school,address,detail_address,nickname 返回值: user_info: 用户个人信息的字典 """ if 'USR_ID' in session: if request.method == 'GET': user_info = query_db("SELECT * FROM student WHERE user_id = %s", ...
40a960150cab9b88d848f742109c5120f4a846a4
33,454
def sequence_names_match(r1, r2): """ Check whether the sequences r1 and r2 have identical names, ignoring a suffix of '1' or '2'. Some old paired-end reads have names that end in '/1' and '/2'. Also, the fastq-dump tool (used for converting SRA files to FASTQ) appends a .1 and .2 to paired-end reads if option -I ...
645ac09011cc4b94c5b6d60bf691b6b1734d5b6b
33,455
import torch def generate_mobile_module_lints(script_module: torch.jit.ScriptModule): """ Args: script_module: An instance of torch script module with type of ScriptModule Returns: lint_map: A list of dictionary that contains modules lints """ if not isinstance(script_module, torc...
4a6b25388fb549a273345f2f16f8e471c468a691
33,456
from typing import Set def manipulation(macid: MACID, decision: str, effective_set: Set[str]) -> bool: """Check whether a decision is motivated by an incentive for manipulation. Graphical Criterion: 1) There is a directed decision-free path from D_A to an effective decision node D_B. 2) There is a di...
d84df003733c7f18c668ef08a7804773b6e501c8
33,457
def _get_client_ids_meeting_condition(train_tff_data, bad_accuracy_cutoff, good_accuracy_cutoff, invert_imagery_likelihood, classifier_model): """Get clients that classify <bad_accuracy_cutoff or >good_ac...
c7d5878ee045eead44f50416aceac3005b0d4e2c
33,458
def get_wccp_service_group_settings( self, ne_id: str, cached: bool, ) -> dict: """Get per-group WCCP configuration settings from appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - wccp - GET - /wccp...
75e07296893eabafbbf0285134cf33cb3eb46480
33,459
def container_storage_opt() -> int: """Return the size for the 'storage_opt' options of the container. Return -1 if no option (or the default 'host') was given.""" if "storage_opt" in settings.DOCKER_PARAMETERS: storage = settings.DOCKER_PARAMETERS["storage_opt"].get("size", -1) if stor...
5d345bffd37dc0599d7ef137c08798a226322368
33,460
import copy def construct_insert_conversatie_query(graph_uri, conversatie, bericht, delivery_timestamp): """ Construct a SPARQL query for inserting a new conversatie with a first bericht attached. :param graph_uri: string :param conversatie: dict containing escaped properties for conversatie :par...
61710bc10985cbf91bba354cd06916b77da587d7
33,462
def _minimum_chunk_size_accuracy( data: pd.DataFrame, partition_column_name: str = NML_METADATA_PARTITION_COLUMN_NAME, prediction_column_name: str = NML_METADATA_PREDICTION_COLUMN_NAME, target_column_name: str = NML_METADATA_TARGET_COLUMN_NAME, required_std: float = 0.02, ): """Estimation of min...
3401ccb564cd69e82effc8d7c949feffe725a7fa
33,463
def estimate_directions(correlations, pairs): """Estimate directions from a correlation matrix for specific pairs. Parameters ---------- correlations : numpy.ndarray, shape=(n_samples, n_samples) A correlation matrix. Can contain nan values. pairs : numpy.ndarray, shape=(< n_samples, 2) ...
be4282922bd8b052a60211ab61c4c678ef154e05
33,464
def get_est_input_size(out, height, p2pkh_pksize, p2sh_scriptsize, nonstd_scriptsize, p2wsh_scriptsize): """ Computes the estimated size an input created by a given output type (parsed from the chainstate) will have. The size is computed in two parts, a fixed size that is non type dependant, and a variable ...
621cea04217ac7b1396d89ecdfa4e8a3812bd636
33,467
import win32com.client def VisumInit(path=None,COMAddress='Visum.Visum.125'): """ ### Automatic Plate Number Recognition Support (c) 2012 Rafal Kucharski info@intelligent-infrastructure.eu #### VISUM INIT """ Visum = win32com.client.Dispatch(COMAddress) if path != None: Visum.Load...
dc9ebcb271ba86f3ab1180bed6b3da553e416f7d
33,468
def get(section, option, default=None): """ Simple accessor to hide/protect the multiple depth dict access: conf["SECTION"]["OPTION"] """ if section in conf.keys(): if option in conf[section].keys(): return conf[section][option] return default
9ece13a6cf0df1f50f5d9db70c035aef88fe2412
33,469
def inceptionresnetv1(**kwargs): """ InceptionResNetV1 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for mod...
d424c883e03899cd37bc4f5421bd779ff85be991
33,470
from typing import Dict def series_length(x: np.array, freq: int = 1) -> Dict[str, float]: """Series length. Parameters ---------- x: numpy array The time series. freq: int Frequency of the time series Returns ------- dict 'series_length': Wrapper of len(x). ...
a84f8e9f66bc862237ddff5ac651e961147aeee2
33,472
import pygrib def _load_uvtp(date, time, latitude=-30, longitude=289.5): """Load U, V, T componenents of wind for GFS file given date and time.""" # do not want pygrib to be a dependency for the whole psfws package. # load in dataset (specific date/time given by args) try: grbs = pygrib.open(...
7cb414b26df805b946154f78782373955f3e6422
33,474
from typing import OrderedDict import six def ds2_variables(input, output_vars=False, names=None): """Generate a collection of `DS2Variable` instances corresponding to the input Parameters ---------- input : function or OrderedDict<string, tuple> or Pandas DataFrame or Numpy or OrderedDict<string, ty...
50bed5939530679dd36edd5a911b212687a085aa
33,475
import hashlib def register(): """Register User""" # forget any user_id session.clear() # If the user has been redirected through an event url event = request.args.get('event') # if user reached route via POST (as by submitting a form via POST) if request.method == 'POST': # ch...
b6eb1c717a1c52dd206d6bb4f17e768a5a33bbc1
33,477
from typing import Sequence def topological_sort(edges: Sequence[Sequence]) -> list: """Produce a topological sorting (if one exists) using a BFS approach. Args: edges (Sequence[Sequence]): A list of edges pairs, ex: [('A', 'B'), ('A', 'C')]. Returns: list: An array with a non-unique top...
48a48449e7cd9390abbe2b589994cd7476684f69
33,478
def map_currency(currency, currency_map): """ Returns the currency symbol as specified by the exchange API docs. NOTE: Some exchanges (kraken) use different naming conventions. (e.g. BTC->XBT) """ if currency not in currency_map.keys(): return currency return currency_map[currency]
98b235952b042109a4e2083ce6c8fd85690c22e3
33,479
def FastResultRow(cols): """Create a ResultRow-like class that has all fields already preparsed. Non-UTF-8-String columns must be suffixed with !.""" getters = {} _keys = [] for i, col in enumerate(cols.split()): if col[-1] == '!': col = col[:-1] getter = itemgetter(i...
61483f6b3e6627eb5b2125c3a458e3baf6d263eb
33,480
def new_answer(notification): """ Obtains a new answer body for notifs where **source is the post** """ answer = Answer.query.filter_by(id=notification.target_id).first() post = Post.query.filter_by(id=notification.source_id).first() if not isinstance(answer, Answer): return "A new ...
41755acbaa870f0fabb9295a75a47c7e652bbbc0
33,481
def gather_indexes(sequence_tensor, positions): """Gathers the vectors at the specific positions. Args: sequence_tensor: Sequence output of `BertModel` layer of shape (`batch_size`, `seq_length`, num_hidden) where num_hidden is number of hidden units of `BertModel` layer. positions: Pos...
82e1b4520cbac66d45d56fc1f66286578acab0dd
33,482
def _check_type(value, expected_type): """Perform type checking on the provided value This is a helper that will raise ``TypeError`` if the provided value is not an instance of the provided type. This method should be used sparingly but can be good for preventing problems earlier when you want to rest...
a18ecfe9d63e6a88c56fc083da227a5c12ee18db
33,483
def find_rbm_procrustes(frompts, topts): """ Finds a rigid body transformation M that moves points in frompts to the points in topts that is, it finds a rigid body motion [ R | t ] with R \in SO(3) This algorithm first approximates the rotation by solving the orthogonal procrustes problem. """ ...
ae478e3c2139fe5bef1beb5c12ce75b07dee98e7
33,484
from typing import Callable import functools def adapt_type_to_browse_processor() -> Callable[[MediaProcessorType], BrowseGeneratorType]: """ Create generator for media objects from provided ID's :return: Decorator """ def _decorate(func: MediaProcessorType): """ Decorate ...
bbed3ec54ca966cc1886d02abbf5ccae8daca25c
33,485
import healpy as hp def get_skyarea(output_mock, Nside): """ """ # compute sky area from ra and dec ranges of galaxies nominal_skyarea = np.rad2deg(np.rad2deg(4.0*np.pi/hp.nside2npix(Nside))) if Nside > 8: skyarea = nominal_skyarea else: pixels = set() for k in output_...
243e6d7a4b10673ed1d7fd03db48e7ac12c6ec0e
33,487
def get_patch_info(shape, p_size): """ shape: origin image size, (x, y) p_size: patch size (square) return: n_x, n_y, step_x, step_y """ x = shape[0] y = shape[1] n = m = 1 while x > n * p_size: n += 1 while p_size - 1.0 * (x - p_size) / (n - 1) < 50: n += 1 w...
b681f355ffbf3c7f5653996cd021950e2c9689d4
33,489
def validate_token(token=None): """Helps in confirming the Email Address with the help of the token, sent on the registered email address.\n Keyword Arguments: token -- Token passed in the user's email """ try: res = URLSafeTimedSerializer(SECRET).loads( # noqa token, salt=VERIF...
36ae68623cb04c0d3964c23b3ebc36a82376bec8
33,490
def rate2amount( rate: xr.DataArray, dim: str = "time", out_units: str = None ) -> xr.DataArray: """Convert a rate variable to an amount by multiplying by the sampling period length. If the sampling period length cannot be inferred, the rate values are multiplied by the duration between their time coor...
1a660711d6e5d7bffc14608e65aeb6d0ae5d7740
33,491
def makechis(d, N, maxchi): """Create the vector of chis for the chain. This is a length-N+1 list of exponents of d. The exponents are of the form [0, 1, 2, 1, 0] (if N+1 is odd) [0, 1, 2, 2, 1, 0] (if N+1 is even) Any numbers in the above exceeding ln(maxchi) / ln(d) are replace...
45dea0c399b1a8d8a055c28015d17f12d3ce5112
33,492
import requests def generate_input_f(reagent, MW, density): """ A helper function to properly formate input for concentration-to-amount calculations. Returns a dictionary where each key is a reagent component and each value is a sub-dictionary containing concentration, phase, molecular weight, and density...
2c8225509ba1512270a5ebfce130f79f2fba172c
33,493
def addCol(adjMatrix): """Adds a column to the end of adjMatrix and returns the index of the comlumn that was added""" for j in range(len(adjMatrix)): adjMatrix[j].append(0) return len(adjMatrix[0])-1
29ee11953cbdb757e8ea80e897751059e42f1d90
33,494
def get_table_m_1_a_5(): """表M.1(a)-5 居住人数4人における基準給湯量および入浴人数(生活スケジュール:平日(小)) Args: Returns: list: 表M.1(a)-5 居住人数4人における基準給湯量および入浴人数(生活スケジュール:平日(小)) """ # 表M.1(a)-5 居住人数4人における基準給湯量および入浴人数(生活スケジュール:平日(小)) table_m_1_a_5 = np.array([ (0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, ...
0ec4fbf123b503a31bf199f6a392147d07e8e714
33,495
import re def _get_first_sentence(s): """ Get the first sentence from a string and remove any carriage returns. """ x = re.match(r".*?\S\.\s", s) if x is not None: s = x.group(0) return s.replace('\n', ' ')
9e78fdba3a47c0f9faae6a938ab58498455555b2
33,498
def open_tsg_from_legos(filename): """ Open thermosalinograph (TSG) transect from the LEGOS dataset, and homogenize the coordinates Parameters ---------- filename : str Name of the file to open Returns ------- ds : xarray.Dataset The TSG transect under the ...
69c999c53fb8faff622b5f274e79ed6ef9415ddd
33,499
from datetime import datetime def get_current_time(): """Return timestamp for current system time in UTC time zone. Returns ------- datetime Current system time """ return datetime.datetime.utcnow()
606761fa1aabe0b9d0d1682b978efbae1a524fa3
33,500
def calculate_average(result): """Calculates the average package size""" vals = result.values() if len(vals) == 0: raise ValueError("Cannot calculate average on empty dictionary.") return sum(vals)/float(len(vals))
ea4b66b41533b0e8984b5137c39c744eec9d3e1f
33,501
def score_vectore(vector): """ :type vector: list of float :return: """ x = 0. y = 0. for i in range(0, len(vector)): if i % 2 == 0: if vector[i] > 12: x += vector[i] else: y += vector[i] + min(vector[i-1], vector[i]) return x, y
8fc60cb3cec65d5a3b8f0fea62777739e17249a4
33,502
def loudness_contour_equivalence(mean_loudness_value, phon_ref_value): """ Function that serves for the validation of the hearing model presented in Annex F of ECMA-74. Parameters ---------- Returns ------- """ # Conversion to phons of the loudness result that is in sones. phon_loudne...
410d6469caad75a2d9387ada9868a747a457dd86
33,503
def _compound_register(upper, lower): """Return a property that provides 16-bit access to two registers.""" def get(self): return (upper.fget(None) << 8) | lower.fget(None) def set(self, value): upper.fset(None, value >> 8) lower.fset(None, value) return property(get, set)
00f315cc4c7f203755689adb5004f152a8b26823
33,505
def get_joining_type_property(value, is_bytes=False): """Get `JOINING TYPE` property.""" obj = unidata.ascii_joining_type if is_bytes else unidata.unicode_joining_type if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['joiningtype'].get(negated, negated) ...
ad2f590658c927a91ef5d90ac09d5b927e2091f3
33,507
from typing import List def select_record_fields( record: dict, fields: List[str]) -> dict: """ Selects a subset of fields from a dictionary """ return {k: record.get(k, None) for k in fields}
4b56ba4bc683eb8d49540ccb8de79c08b900e7c8
33,508
def to_TProfile2D( fName, fTitle, data, fEntries, fTsumw, fTsumw2, fTsumwx, fTsumwx2, fTsumwy, fTsumwy2, fTsumwxy, fTsumwz, fTsumwz2, fSumw2, fBinEntries, fBinSumw2, fXaxis, fYaxis, fZaxis=None, fScalefactor=1.0, fZmin=0.0, fZmax=0....
6886a90bc4e134d03f255c2fcec211dbdbd435b0
33,509
def decode_check(string: str, digestfunc=sha256d_32) -> bytes: """ Convert base58 encoded string to bytes and verify checksum. """ result = decode(string) return verify_checksum(result, digestfunc)
e3cdca3d66a2822cf6d47756959f136c84bcae65
33,510
import pandas def label_by_wic(grasp_wic, exclude_C0=False): """Label each grasp by the whiskers it contains grasp_wic : DataFrame Index: grasp keys. Columns: whisker. Values: binarized contact. exclude_C0 : bool If False, group by all whiskers. If True, ignore C0, and gr...
0f1e552c68be0b77bad442b2432e071a74db4947
33,511
def selectBestFeature(dataSet: list): """ 计算信息增益,挑选最好的特征值 :param dataSet: 数据集 :return: """ # 不使用最后一列标签列 best_feature_idx = 0 gain = float('-inf') for feature_idx in range(len(dataSet[0])-1): gain_tmp = calcOneFeatureGain(dataSet, feature_idx) if gain_tmp > gain: ...
ced59e8748eb12a17951fb511c7cc6b8d5f88555
33,512
from typing import Callable import json def __interact_instances(client, action: Callable, status: str) -> dict: """ Interacts with the instances. It executes the callable from action. :param client: Sagemaker boto3 client. :param action: a callable (e.g. client.start_notebook_instance). :param st...
f067ce6d4d32718e6d25edb735534b3427eb9cc6
33,513
def _chordfinisher(*args, **kwargs): """ Needs to run at the end of a chord to delay the variant parsing step. http://stackoverflow.com/questions/ 15123772/celery-chaining-groups-and-subtasks-out-of-order-execution """ return "FINISHED VARIANT FINDING."
b68d09e755c2da468b98ab0466821770d2f7f4a7
33,514
def plot_reg_path(model, marker='o', highlight_c="orange", include_n_coef=False, figsize=None, fontsize=None): """Plots path of an L1/L2 regularized sklearn.linear_model.LogisticRegressionCV. Produces two adjacent plots. The first is a plot of mean coefficient values vs penalization strength. The second...
f868bf2ef5375598e29675b42234a5be470235f0
33,515
def create_object_count(app=None): """fetches all models of the passed in app and returns a dict containg the name of each class and the number of instances""" if app: models = ContentType.objects.filter(app_label=app) result = [] for x in models: modelname = x.model ...
a0697f9847e3a200fd235cbb000c7d67e711f9fd
33,516
def unique_name(prefix: str, collection) -> str: """ Prepares a unique name that is not in the collection (yet). Parameters ---------- prefix The prefix to use. collection Name collection. Returns ------- A unique name. """ if prefix not in collection: ...
8438588bd17e097ffc5bbe7b88f4c2aba2363250
33,517
async def get_pic(image_type: str, group_id: int, sender: int) -> list: """ Return random pics message Args: image_type: The type of picture to return image type list: setu: hPics(animate R-15) setu18: hPics(animate R-18) real: hPics(real ...
37f06676b508503ba54fab37e1e7418df0d144bc
33,518
def dispatch(req): """run the command specified in req.args; returns an integer status code""" err = None try: status = _rundispatch(req) except error.StdioError as e: err = e status = -1 ret = _flushstdio(req.ui, err) if ret: status = ret return status
1874580fff23796b025fc2cd2ecce9f21a5af692
33,519
def get_settings(from_db=False): """ Use this to get latest system settings """ if not from_db and 'custom_settings' in current_app.config: return current_app.config['custom_settings'] s = Setting.query.order_by(desc(Setting.id)).first() app_environment = current_app.config.get('ENV', 'p...
2154122bcdde3e0bc023103ed825d76234d489c1
33,520
def get_currency_crosses_list(base=None, second=None): """ This function retrieves all the available currency crosses from Investing.com and returns them as a :obj:`dict`, which contains not just the currency crosses names, but all the fields contained on the currency_crosses file is columns is None, ot...
da6588be01510c96d6e1dc85c82d7beed877002b
33,521
def define_git_repo(*, name: 'name', repo, treeish=None): """Define [NAME/]git_clone rule.""" (define_parameter.namedtuple_typed(GitRepoInfo, name + 'git_repo') .with_default(GitRepoInfo(repo=repo, treeish=treeish))) relpath = get_relpath() @rule(name + 'git_clone') @rule...
78dcd536c306020d2ffd6fe4355992b10fb0d9ad
33,522