content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def spline(xyz, s=3, k=2, nest=-1): """ Generate B-splines as documented in http://www.scipy.org/Cookbook/Interpolation The scipy.interpolate packages wraps the netlib FITPACK routines (Dierckx) for calculating smoothing splines for various kinds of data and geometries. Although the data is evenly ...
97500c7a63bc076abd770c43fd3f6d23c30baa03
3,658,374
import time def load_supercomputers(log_file, train_ratio=0.5, windows_size=20, step_size=0, e_type='bert', mode="balance", no_word_piece=0): """ Load BGL, Thunderbird, and Spirit unstructured log into train and test data Parameters ---------- log_file: str, the file path of ra...
2282b8cbd975160e57ff62106a7e0bad3f337e5a
3,658,375
def is_running(service: Service) -> bool: """Is the given pyodine daemon currently running? :raises ValueError: Unknown `service`. """ try: return bool(TASKS[service]) and not TASKS[service].done() except KeyError: raise ValueError("Unknown service type.")
160c7c8da0635c9c11ebdaf711b794fc0a09adff
3,658,376
def PropertyWrapper(prop): """Wrapper for db.Property to make it look like a Django model Property""" if isinstance(prop, db.Reference): prop.rel = Relation(prop.reference_class) else: prop.rel = None prop.serialize = True return prop
9f93a37dffd433fd87ffa4bfdb65680a9ad1d02d
3,658,377
def drowLine(cord,orient,size): """ The function provides the coordinates of the line. Arguments: starting x or y coordinate of the line, orientation (string. "vert" or "hor") and length of the line Return: list of two points (start and end of the line) """ glo...
bc688cfe33dcf42ddac6770bbdf91ccc19c1b427
3,658,378
def bluetoothRead(): """ Returns the bluetooth address of the robot (if it has been previously stored) arguments: none returns: string - the bluetooth address of the robot, if it has been previously stored; None otherwise """ global EEPROM_BLUETOOTH_ADDRESS ...
c4e08d438b91b3651f27b374c0b38069ddd1eaaf
3,658,379
def is_step_done(client, step_name): """Query the trail status using the client and return True if step_name has completed. Arguments: client -- A TrailClient or similar object. step_name -- The 'name' tag of the step to check for completion. Returns: True -- if the step has succeeded....
a5373d7e00f0c8526f573356b5d71a2ac08aa516
3,658,380
def on_chat_send(message): """Broadcast chat message to a watch room""" # Check if params are correct if 'roomId' not in message: return {'status_code': 400}, request.sid room_token = message['roomId'] # Check if room exist if not db.hexists('rooms', room_token): {'status_code'...
01c7f15602653848c9310e90c0a353648fafbb52
3,658,381
from typing import Union def arima(size: int = 100, phi: Union[float, ndarray] = 0, theta: Union[float, ndarray] = 0, d: int = 0, var: float = 0.01, random_state: float = None) -> ndarray: # inherit from arima_with_seasonality """Simulate a realization from a...
24c3ac8af295d25facf0e65a4fc0925b22db9444
3,658,382
def gt_dosage(gt): """Convert unphased genotype to dosage""" x = gt.split(b'/') return int(x[0])+int(x[1])
819fc9beb834f57e44bcb0ac3e1d3c664c7efd42
3,658,383
from typing import Optional from typing import Dict from typing import Any def create_key_pair_in_ssm( ec2: EC2Client, ssm: SSMClient, keypair_name: str, parameter_name: str, kms_key_id: Optional[str] = None, ) -> Optional[KeyPairInfo]: """Create keypair in SSM.""" keypair = create_key_pai...
40cca5fd938aa6709a4d844c912b294c6aaba552
3,658,384
def sumofsq(im, axis=0): """Compute square root of sum of squares. Args: im: Raw image. axis: Channel axis. Returns: Square root of sum of squares of input image. """ out = np.sqrt(np.sum(im.real * im.real + im.imag * im.imag, axis=axis)) return out
6aa791d3c6a2e8e6fff0dbe0a364350d48fb4794
3,658,385
def biquad_bp2nd(fm, q, fs, q_warp_method="cos"): """Calc coeff for bandpass 2nd order. input: fm...mid frequency in Hz q...bandpass quality fs...sampling frequency in Hz q_warp_method..."sin", "cos", "tan" output: B...numerator coefficients Laplace transfer function A...denominator...
c7330f9bd4a1941359a54ea6e6d7e8fe7801f55e
3,658,388
def pullAllData(): """ Pulls all available data from the database Sends all analyzed data back in a json with fileNames and list of list of all "spots" intensities and backgrounds. Args: db.d4Images (Mongo db collection): Mongo DB collection with processed ...
97674c981af48f37e90667c00947673f1df34c66
3,658,389
def f2(): """ >>> # +--------------+-----------+-----------+------------+-----------+--------------+ >>> # | Chromosome | Start | End | Name | Score | Strand | >>> # | (category) | (int32) | (int32) | (object) | (int64) | (category) | >>> # |--------------+--...
159c5167bacbeed38578a8b574b31fa2f57f9467
3,658,390
def latin(n, d): """ Build latin hypercube. Parameters ---------- n : int Number of points. d : int Size of space. Returns ------- lh : ndarray Array of points uniformly placed in d-dimensional unit cube. """ # spread function def spread(points):...
416d8c8086eeeaf6e8ea0bf14c300750025455be
3,658,391
def _get_valid_dtype(series_type, logical_type): """Return the dtype that is considered valid for a series with the given logical_type""" backup_dtype = logical_type.backup_dtype if ks and series_type == ks.Series and backup_dtype: valid_dtype = backup_dtype else: valid_dtype = logic...
7b4bcd724d2d7a4029a794456882a8f59fc29006
3,658,392
def geometric_mean_longitude(t='now'): """ Returns the geometric mean longitude (in degrees). Parameters ---------- t : {parse_time_types} A time (usually the start time) specified as a parse_time-compatible time string, number, or a datetime object. """ T = julian_centuries...
c47f106392f507d7750f86cba6a7c16ba3270b11
3,658,393
def get_or_create(model, **kwargs): """Get or a create a database model.""" instance = model.query.filter_by(**kwargs) if instance: return instance else: instance = model(**kwargs) db.session.add(instance) return instance
6af359ebda80b81a0d02762d576ff407f0c186c4
3,658,396
def test_class_id_cube_strategy_elliptic_paraboloid(experiment_enviroment, renormalize, thread_flag): """ """ tm, dataset, experiment, dictionary = experiment_enviroment class_id_params = { "class...
fc5a17e5bf6b158ce242b4289938dec4d2d2e32b
3,658,397
from typing import Dict from typing import List def apply_filters(filters: Dict, colnames: List, row: List) -> List: """ Process data based on filter chains :param filters: :param colnames: :param row: :return: """ if filters: new_row = [] for col, data in zip(colnames,...
e52e8b2773dc4e794076b8a480e5eaaab50de06e
3,658,398
def kaiming(shape, dtype, partition_info=None): """Kaiming initialization as described in https://arxiv.org/pdf/1502.01852.pdf""" return tf.random.truncated_normal(shape) * tf.sqrt(2 / float(shape[0]))
153213279909bf01e9782e0e56d270632c502b27
3,658,399
def trunc_artist(df: pd.DataFrame, artist: str, keep: float = 0.5, random_state: int = None): """ Keeps only the requested portion of songs by the artist (this method is not in use anymore) """ data = df.copy() df_artist = data[data.artist == artist] data = data[data.artist != artist] ...
7157e223bdf87d0463820565e40eade3e1725ae5
3,658,400
async def test_postprocess_results(original, expected): """Test Application._postprocess_results.""" callback1_called = False callback2_called = False app = Application("testing") @app.result_postprocessor async def callback1(app, message): nonlocal callback1_called callback1_c...
9c2a6bdfcb281d62959135be01693baaaf266780
3,658,401
def task_migrate(): """Create django databases""" return { 'actions': ['''cd CCwebsite && python3 manage.py migrate'''] }
d0d146c2e628abbe33714ae0ff6a546aab9842cc
3,658,403
import numpy def distance_to_arc(alon, alat, aazimuth, plons, plats): """ Calculate a closest distance between a great circle arc and a point (or a collection of points). :param float alon, alat: Arc reference point longitude and latitude, in decimal degrees. :param azimuth: Arc a...
e8868a2ce9125cc75e587a8a408f5b479b6a198a
3,658,404
def model_predict(test_data: FeatureVector): """ Endpoint to make a prediction with the model. The endpoint `model/train` should have been used before this one. Args: test_data (FeatureVector): A unit vector of feature """ try: y_predicted = api.ml_model.predict_proba(test_data.to_...
c8b473d09092e03be85e986287350dd3115cf88d
3,658,405
def search_folders(project, folder_name=None, return_metadata=False): """Folder name based case-insensitive search for folders in project. :param project: project name :type project: str :param folder_name: the new folder's name :type folder_name: str. If None, all the folders in the project will ...
cf8a9d95efcdb90d0891ef4ca588edf6375ed2af
3,658,407
def tempo_para_percorrer_uma_distancia(distancia, velocidade): """ Recebe uma distância e a velocidade de movimentação, e retorna as horas que seriam gastas para percorrer em linha reta""" horas = distancia / velocidade return round(horas,2)
e7754e87e010988284a6f89497bb1c5582ea0e85
3,658,408
import math def getCorrection(start, end, pos): """Correct the angle for the trajectory adjustment Function to get the correct angle correction when the robot deviates from it's estimated trajectory. Args: start: The starting position of the robot. end: The position the robot is suppos...
9f1073cb4c071abfecac20c85c56e5fb1638de6e
3,658,409
import logging def main(input_filepath, output_filepath): """ Runs data processing scripts to turn raw data from (../raw) into cleaned data ready to be analyzed (saved in ../processed). """ logger = logging.getLogger(__name__) logger.info('making final data set from raw data...') df = loa...
fe799a34f9cb5811228853469dbff92592a87e69
3,658,410
def string2symbols(s): """ Convert string to list of chemical symbols. Args: s: Returns: """ i = None n = len(s) if n == 0: return [] c = s[0] if c.isdigit(): i = 1 while i < n and s[i].isdigit(): i += 1 return int(s[:i]) * s...
1f08ba5c02536f4b67c9bd573c0dde8fbe46dc74
3,658,411
import csv from typing import Counter def get_dictionary(filename, dict_size=2000): """ Read the tweets and return a list of the 'max_words' most common words. """ all_words = [] with open(filename, 'r') as csv_file: r = csv.reader(csv_file, delimiter=',', quotechar='"') for row in...
20917b0c9cda18d5436b438e0cdcf0c83d464899
3,658,413
def find_last_index(l, x): """Returns the last index of element x within the list l""" for idx in reversed(range(len(l))): if l[idx] == x: return idx raise ValueError("'{}' is not in list".format(x))
f787b26dd6c06507380bf2e336a58887d1f1f7ea
3,658,414
import requests import zipfile import io def download_query_alternative(user, password, queryid, batch_size=500): """ This is an alternative implementation of the query downloader. The original implementation only used a batch size of 20 as this allowed for using plain LOC files. Unfortunately this i...
2de7c3b453809c86093d1884438613985f7041b3
3,658,415
def parse_template(templ_str, event): """ Parses a template string and find the corresponding element in an event data structure. This is a highly simplified version of the templating that is supported by the Golang template code - it supports only a single reference to a sub element of the event s...
ec5c3822c390cbb4beff6428b91cd8b12157f2e3
3,658,416
import time def current_time_hhmm() -> str: """ Uses the time library to get the current time in hours and minutes Args: None Returns: str(time.gmtime().tm_hour) + ":" + str(time.gmtime().tm_min) (str): Current time formatted as hour:minutes "...
c7902ac8a8fb2528bacf6a5bc8459865604dd204
3,658,417
def configure(node): """ Generates the script to set the hostname in a node """ script = [] script.append(Statements.exec("hostname %s" % node.getName())) script.append(Statements.createOrOverwriteFile( "/etc/hostname", [node.getName()])) script.append(Statements.exec( "sed -i 's/127...
b0acf0f6a1363f1c7ad5a8e6dce6cb5d45586135
3,658,420
import random def processOptional(opt): """ Processes the optional element 50% of the time, skips it the other 50% of the time """ rand = random.random() if rand <= 0.5: return '' else: return processRHS(opt.option)
bda8130952f11f4df9342764d749dd6c93109d8e
3,658,421
def remove_non_paired_trials(df): """Remove non-paired trials from a dataset. This function will remove any trials from the input dataset df that do not have a matching pair. A matching pair are trial conditions A->B and B->A. """ # Define target combinations start_pos = np.concatenate(df['sta...
30b5b86d9354c55dd2514114dc1180f397f2e56c
3,658,422
def compute_weighted_means_ds(ds, shp, ds_name='dataset', time_range=None, column_names=[], averager=False, df_output=pd.DataFrame(), ...
e575d17eefe8de66c0b6fd63abcf5d3bd6cac6ae
3,658,423
def action_remove(indicator_id, date, analyst): """ Remove an action from an indicator. :param indicator_id: The ObjectId of the indicator to update. :type indicator_id: str :param date: The date of the action to remove. :type date: datetime.datetime :param analyst: The user removing the ac...
806c818cd4c18624d9713a02d5c1826cab43a631
3,658,424
def repack_orb_to_dalton(A, norb, nclosed, nact, nvirt): """Repack a [norb, norb] matrix into a [(nclosed*nact) + (nclosed*nvirt) + (nact*nvirt)] vector for contraction with the CI Hamiltonian. """ assert norb == nclosed + nact + nvirt assert A.shape == (norb, norb) # These might be availa...
05b356e9ded74c180d2a220f147cd69e91a5b597
3,658,425
def get_config(section="MAIN", filename="config.ini"): """ Function to retrieve all information from token file. Usually retrieves from config.ini """ try: config = ConfigParser() with open(filename) as config_file: config.read_file(config_file) return config[sect...
32d6c579b0ce002a601ea9041b54e9ce03858eb4
3,658,426
def _worst_xt_by_core(cores) -> float: """ Assigns a default worst crosstalk value based on the number of cores """ worst_crosstalks_by_core = {7: -84.7, 12: -61.9, 19: -54.8} # Cores: Crosstalk in dB worst_xt = worst_crosstalks_by_core.get(cores) # Worst aggregate intercore XT return worst_xt
331fdd7dc20db6909a6952483cfa9699f983a721
3,658,427
def _CheckUploadStatus(status_code): """Validates that HTTP status for upload is 2xx.""" return status_code / 100 == 2
d799797af012e46945cf413ff54d2ee946d364ba
3,658,428
def load(path: str, **kwargs) -> BELGraph: """Read a BEL graph. :param path: The path to a BEL graph in any of the formats with extensions described below :param kwargs: The keyword arguments are passed to the importer function :return: A BEL graph. This is the universal loader, which me...
871c7e3becac089758c94f7416def0020e63f9c1
3,658,429
from typing import Optional def smooth_l1_loss( prediction: oneflow._oneflow_internal.BlobDesc, label: oneflow._oneflow_internal.BlobDesc, beta: float = 1.0, name: Optional[str] = None, ) -> oneflow._oneflow_internal.BlobDesc: """This operator computes the smooth l1 loss. The equation is: ...
ddebf5ba77ca8e4d2a964e5c86e05a0b61db9ded
3,658,430
def get_model_fields(model, concrete=False): # type: (Type[Model], Optional[bool]) -> List[Field] """ Gets model field :param model: Model to get fields for :param concrete: If set, returns only fields with column in model's table :return: A list of fields """ if not hasattr(model._meta, 'g...
9e9172b2e606041c6f9dbf3a991e79d73518227f
3,658,431
def loss_fun(para): """ This is the loss function """ return -data_processing(my_cir(para))
5703755e3f5547be933f85224c103c58acbeaabb
3,658,432
def GetDynTypeMgr(): """Get the dynamic type manager""" return _gDynTypeMgr
7acf02dd2072ea819c847f53fbf11e68146b2400
3,658,433
def identifyEntity(tweet, entities): """ Identify the target entity of the tweet from the list of entities :param tweet: :param entities: :return: """ best_score = 0 # best score over all entities targetEntity = "" # the entity corresponding to the best score for word in tweet: ...
d6825dfddf01706ee266e0f1c82128a42bcb8554
3,658,434
def _apply_D_loss(scores_fake, scores_real, loss_func): """Compute Discriminator losses and normalize loss values Arguments --------- scores_fake : list discriminator scores of generated waveforms scores_real : list discriminator scores of groundtruth waveforms loss_func : objec...
9432962af57193c07a268d00a3f1f01d372cb6a0
3,658,436
import tempfile def get_temp_dir(): """ Get path to the temp directory. Returns: str: The path to the temp directory. """ return fix_slashes( tempfile.gettempdir() )
3d0dd90c8187ac7b13913e7d4cd2b481c712fa6b
3,658,437
import random def pick_op(r, maxr, w, maxw): """Choose a read or a write operation""" if r == maxr or random.random() >= float(w) / maxw: return "write" else: return "read"
a45f53bf12538412b46f78e2c076966c26cf61ac
3,658,438
def sim_nochange(request): """ Return a dummy YATSM model container with a no-change dataset "No-change" dataset is simply a timeseries drawn from samples of one standard normal. """ X, Y, dates = _sim_no_change_data() return setup_dummy_YATSM(X, Y, dates, [0])
a39ba5824644764ae2aaf4e4d95c68d1c26bd132
3,658,439
from functools import reduce import operator def get_queryset_descendants(nodes, include_self=False, add_to_result=None): """ RUS: Запрос к базе данных потомков. Если нет узлов, то возвращается пустой запрос. :param nodes: список узлов дерева, по которым необходимо отыскать потомков :param include...
7de9fe6c146c9569bc78b714b75238b770f9157e
3,658,441
from operator import mul def op_mul(lin_op, args): """Applies the linear operator to the arguments. Parameters ---------- lin_op : LinOp A linear operator. args : list The arguments to the operator. Returns ------- NumPy matrix or SciPy sparse matrix. The resu...
a1f770d2132fc9c3a60d4de3c3d87f59a03241eb
3,658,442
def comparator(x, y): """ default comparator :param x: :param y: :return: """ if x < y: return -1 elif x > y: return 1 return 0
53fc36f1afc3347689a1230c5ee3ba25d90f1239
3,658,443
def set_trait(age, age_risk_map, sex, sex_risk_map, race, race_risk_map): """ A trait occurs based on some mix of """ if age in age_risk_map: risk_from_age = age_risk_map[age] else: risk_from_age = 0 if sex in sex_risk_map: risk_from_sex = sex_risk_map[sex] else: ri...
fe9f6c75ae4d7f80c2da86af4315b35fe29df482
3,658,444
def tidy_expression(expr, design=None): """Converts expression matrix into a tidy 'long' format.""" df_long = pd.melt( _reset_index( expr, name='gene'), id_vars=['gene'], var_name='sample') if design is not None: df_long = pd.merge( df_long, _reset_index...
7c904e13a55f38cc05309b5927f2fdbb23c3f8c9
3,658,446
def get_optimizer(name): """Get an optimizer generator that returns an optimizer according to lr.""" if name == 'adam': def adam_opt_(lr): return tf.keras.optimizers.Adam(lr=lr) return adam_opt_ else: raise ValueError('Unknown optimizer %s.' % name)
8c97ee9f4b77d0fc80914ac7cbb49a448d48644a
3,658,448
from typing import List def get_multi(response: Response, common: dict = Depends(common_parameters)) -> List[ShopToPriceSchema]: """List prices for a shop""" query_result, content_range = shop_to_price_crud.get_multi( skip=common["skip"], limit=common["limit"], filter_parameters=common...
f97868e66c7743127d2d2951b732ff4c62708ae5
3,658,449
from datetime import datetime def send_crash(request, machine_config_info, crashlog): """ Save houdini crashes """ machine_config = get_or_save_machine_config( machine_config_info, get_ip_address(request), datetime.datetime.now()) save_crash(machine_config, crashlog, datetime.datet...
43e44950bdb4b6dc305bb1f36651daa31b4f813e
3,658,450
def apply_HAc_dense(A_C, A_L, A_R, Hlist): """ Construct the dense effective Hamiltonian HAc and apply it to A_C. For testing. """ d, chi, _ = A_C.shape HAc = HAc_dense(A_L, A_R, Hlist) HAc_mat = HAc.reshape((d*chi*chi, d*chi*chi)) A_Cvec = A_C.flatten() A_C_p = np.dot(HAc_mat, A_Cv...
b13f9db7287fcdf275e8f7c9a7fb542e7b79323c
3,658,452
def min_index(array, i, j): """Pomocna funkce pro razeni vyberem. Vrati index nejmensiho prvku v poli 'array' mezi 'i' a 'j'-1. """ index = i for k in range(i, j): if array[k] < array[index]: index = k return index
4c59362fac2e918ba5a0dfe9f6f1670b3e95d68c
3,658,453
def filterControlChars(value, replacement=' '): """ Returns string value with control chars being supstituted with replacement character >>> filterControlChars(u'AND 1>(2+3)\\n--') u'AND 1>(2+3) --' """ return filterStringValue(value, PRINTABLE_CHAR_REGEX, replacement)
a0f508d281f0c12311a5c2aa2f898def5eb38913
3,658,454
import csv def write_trt_rpc(cell_ID, cell_time, lon, lat, area, rank, hmin, hmax, freq, fname, timeformat='%Y%m%d%H%M'): """ writes the rimed particles column data for a TRT cell Parameters ---------- cell_ID : array of ints the cell ID cell_time : array of datetime...
fd634914a8c3d96d10d4dcc81514d492d6be899c
3,658,456
def get_tag(string: str) -> Tag: """Получить тему.""" return Tag.objects.get(tag=string)
816bbaecc4cf45e2fc75b1e428842b5502a353bc
3,658,457
def average_precision(gt, pred): """ Computes the average precision. This function computes the average prescision at k between two lists of items. Parameters ---------- gt: set A set of ground-truth elements (order doesn't matter) pred: list A list of predicted elements (order does mat...
ca265471d073b6a0c7543e24ef0ba4f872737997
3,658,458
import math def rotate_coo(x, y, phi): """Rotate the coordinates in the *.coo files for data sets containing images at different PAs. """ # Rotate around center of image, and keep origin at center xin = 512. yin = 512. xout = 512. yout = 512. cos = math.cos(math.radians(phi)) ...
a57a4c36119e96d757bd23f28a0790f6d68661fc
3,658,459
def ip_block_array(): """ Return an ipBlock array instance fixture """ return ['10.0.0.1', '10.0.0.2', '10.0.0.3']
c74756f34b97d2550cb238bd63e0c9505f3935d3
3,658,460
from pathlib import Path import joblib def load_model(model_name, dir_loc=None, alive_bar_on=True): """Load local model_name=model_s if present, else fetch from hf.co.""" if dir_loc is None: dir_loc = "" dir_loc = Path(dir_loc).absolute().as_posix() file_loc = f"{dir_loc}/{model_name}" if...
1847e061c6980fd4fd185f79d48682cbf7cb14ff
3,658,461
from typing import Generator def get_dev_requirements() -> Generator: """Yield package name and version for Python developer requirements.""" return get_versions("DEVELOPMENT")
728658648d6bce6fecbf4c1bc6b6de42c315b3c0
3,658,462
def _ndb_key_to_cloud_key(ndb_key): """Convert a ndb.Key to a cloud entity Key.""" return datastore.Key( ndb_key.kind(), ndb_key.id(), project=utils.get_application_id())
ce71b0d13f2e37ded12bf87ad133492a9b68d0c7
3,658,463
def inference(H, images, train=True): """Build the MNIST model up to where it may be used for inference. Parameters ---------- images: Images placeholder, from inputs(). train: whether the network is used for train of inference Returns ------- softmax_linear: Output tensor with the com...
bf7e0f60bdc85d52fb6778cc40eedaa63c0387e3
3,658,464
def UniqueLattice(lattice_vectors,ind): """ Takes a list with two tuples, each representing a lattice vector and a list with the genes of an individual. Returns a list with two tuples, representing the equivalent lattice vectors with the smallest cell circunference. """ x_1 = lattice_vectors(0,ind) ...
e2474a54cf3351ff112ecb6d139eec8eac2ef1fa
3,658,466
def register_errors(app: Flask): """注册需要的错误处理程序包到 Flask 程序实例 app 中""" @app.errorhandler(400) # Bad Request 客户端请求的语法错误,服务器无法理解 def bad_request(e): return render_template('error.html', description=e.description, code=e.code), 400 @app.errorhandler(404) # Not Found 服务器无法根据客户端的请求找到资源(网页) def...
27634a139aab88215b77e53a25758d6096571a09
3,658,467
def websafe_encode(data): """Encodes a byte string into websafe-base64 encoding. :param data: The input to encode. :return: The encoded string. """ return urlsafe_b64encode(data).replace(b'=', b'').decode('ascii')
ed5b06d2fab3dcc64275cb0046cabd88f63894ec
3,658,468
from typing import Union def gravatar(email: Union[str, list]) -> str: """Converts the e-mail address provided into a gravatar URL. If the provided string is not a valid e-mail address, this function just returns the original string. Args: email: e-mail address to convert. Returns: ...
8807eefd40472068310455c1c477933dbaa67be0
3,658,469
def bar_2_MPa(value): """ converts pressure in bar to Pa :param value: pressure value in bar :return: pressure value in Pa """ return value * const.bar / const.mega
d6c8084a6603f74bd1fb11739e4f4d9100cf14de
3,658,470
def walk(x, y, model, theta, conditions=None, var2=0.01, mov=100, d=1, tol=1e-3, mode=True): """Executes the walker implementation. Parameters ---------- x : np.ndarray An $(m, n)$ dimensional array for (cols, rows). y : np.ndarray An $n$ dimensional array that will be ...
ef7386f4c7141edfcdeb041b47d741e186f207e2
3,658,471
def izbor_letov(): """Glavna stran.""" # Iz cookieja dobimo uporabnika in morebitno sporočilo (username, ime, priimek) = get_potnik() c.execute("SELECT distinct drzava FROM lokacija ORDER BY drzava") drzave=c.fetchall() drzava_kje = bottle.request.forms.drzava_kje mesto_kje = bottle.request.forms.mesto_kje l...
664de2c3cf2507ac43efa22105a51b1e14ad441a
3,658,472
def generate_data_from_cvs(csv_file_paths): """Generate data from list of csv_file_paths. csv_file_paths contains path to CSV file, column_name, and its label `csv_file_paths`: A list of CSV file path, column_name, and label """ data = [] for item in csv_file_paths: values = read_csv(item[0]...
1c9f393a18edc9c2fcc3f28cdbeb71fb9c006731
3,658,473
import math import torch def log_density_gaussian(x, mu, logvar): """Calculates log density of a gaussian. Parameters ---------- mu: torch.Tensor or np.ndarray or float Mean. logvar: torch.Tensor or np.ndarray or float Log variance. """ normalization = - 0.5 * (math.log(2...
3fdc751aa58b3ec82e1aa454f593879d5da4c310
3,658,474
def invalid_hexadecimal(statement): """Identifies problem caused by invalid character in an hexadecimal number.""" if statement.highlighted_tokens: # Python 3.10 prev = statement.bad_token wrong = statement.next_token else: prev = statement.prev_token wrong = statement.bad_t...
a0b252001dd1f0f466302a131c2a460743a8c197
3,658,475
def get_pool_name(pool_id): """Returns AS3 object name for TLS profiles related to pools :param pool_id: octavia pool id :return: AS3 object name """ return "{}{}".format(constants.PREFIX_TLS_POOL, pool_id)
2a850d48f52d822712cdfc3543532c9b0dd80fd6
3,658,476
def search_sliceable_by_yielded_chunks_for_str(sliceable, search_string, starting_index, down, case_insensitive): """This is the main entry point for everything in this module.""" for chunk, chunk_start_idx in search_chunk_yielder(sliceable, starting_index, down): found_at_chunk_idx = search_list_for_st...
7179179403098cd1d3993a35cf59c9162384ac4d
3,658,477
def split_page(array, limit, index): """ 按限制要求分割数组,返回下标所指向的页面 :param array: 需要分割的数组 :param limit: 每个数组的大小 :param index: 需要返回的分割后的数组 :return: 数组 """ end = index * limit start = end - limit return array[start:end]
ecce83d6e2e09d47e124536f294ece1e1631e6b6
3,658,478
def creatKdpCols(mcTable, wls): """ Create the KDP column Parameters ---------- mcTable: output from getMcSnowTable() wls: wavelenght (iterable) [mm] Returns ------- mcTable with an empty column 'sKDP_*' for storing the calculated KDP of a given wavelength. """ ...
9adc20c1ff94778bec4551156b5774863eb2203f
3,658,479
def get_products_by_user(user_openid, allowed_keys=None, filters=None): """Get all products that user can manage.""" return IMPL.get_products_by_user(user_openid, allowed_keys=allowed_keys, filters=filters)
458664aa75c5b423ccfb2a80287c565cae51e0d0
3,658,480
def sample_from_ensemble(models, params, weights=None, fallback=False, default=None): """Sample models in proportion to weights and execute with model_params. If fallback is true then call different model from ensemble if the selected model throws an error. If Default is not None then return default if ...
c771108cb36cff2cb48af22a9efaad749d267ce0
3,658,481
def Flatten(matrix): """Flattens a 2d array 'matrix' to an array.""" array = [] for a in matrix: array += a return array
00389b4dd295274d8081331d6ae78f233f0b5b59
3,658,482
def create_verification_token( data: dict ) -> VerificationTokenModel: """ Save a Verification Token instance to database. Args: data (dictionary): Returns: VerificationToken: Verification Token entity of VerificationTokenModel object Raises: None """ ...
9008bc298c8e8075031f7e14e8cb0f288e894869
3,658,483
from typing import Union from typing import Sequence from typing import Tuple def _find_highest_cardinality(arrays: Union[int, Sequence, np.ndarray, Tuple]) -> int: """Find the highest cardinality of the given array. Args: arrays: a list of arrays or a single array Returns: The highest ...
abe9ad85ffabb88f9097b9c2de97319f1342f586
3,658,484
def rowmap(table, rowmapper, header, failonerror=False): """ Transform rows via an arbitrary function. E.g.:: >>> import petl as etl >>> table1 = [['id', 'sex', 'age', 'height', 'weight'], ... [1, 'male', 16, 1.45, 62.0], ... [2, 'female', 19, 1.34, 55.4], ...
dabceae8171330d3f8c4cdba7b50be2106ad1438
3,658,486
def squeeze(dataset, how: str = 'day'): """ Squeezes the data in dataset by close timestamps Args: dataset (DataFrame) - the data to squeeze how (str) - one of 'second', 'minute', 'hour', 'day', 'month' (default day) Returns: dataset (DataFrame) - a dataframe where the indexes are squeez...
e41cbc4e054218b1f88ed0745fcc980df29ac8d4
3,658,487
def callback(): """ Process response for "Login" try from Dropbox API. If all OK - redirects to ``DROPBOX_LOGIN_REDIRECT`` url. Could render template with error message on: * oAuth token is not provided * oAuth token is not equal to request token * Error response from Dropbox API Def...
8b35d67d065a5ec65606b6e505cfccc51460fe1c
3,658,488
def get_ws_param(args, attr): """get the corresponding warm start parameter, if it is not exists, use the value of the general parameter""" assert hasattr(args, attr), 'Invalid warm start parameter!' val = getattr(args, attr) if hasattr(args, 'ws_' + attr): ws_val = getattr(args, 'ws_' + attr) ...
ea1d762654153602f8ad54048e54995c26304e40
3,658,489
def _redundant_relation(lex: lmf.Lexicon, ids: _Ids) -> _Result: """redundant relation between source and target""" redundant = _multiples(chain( ((s['id'], r['relType'], r['target']) for s, r in _sense_relations(lex)), ((ss['id'], r['relType'], r['target']) for ss, r in _synset_relations(lex)),...
cc32c55a35cd7056a249ad05bd0b483af18fcd3a
3,658,490