content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import itertools def correlation_matrix( spark, idf, list_of_cols="all", drop_cols=[], stats_unique={}, print_impact=False ): """ :param spark: Spark Session :param idf: Input Dataframe :param list_of_cols: List of columns to analyse e.g., ["col1","col2"]. Alternatively, c...
647d655cc2c2d9234c9ea1e54dc08128ae5c622b
28,900
def _model_variable_getter(getter, name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, collections=None, caching_device=None, partitioner=None, rename=None, use_resource=None, **_): ...
b61f94d17efd344dbec264b3882b3df0c950e900
28,901
def password_check(value, user): """ Check that the password passes the following validation: Password is long enough (based on configuration setting) Password contains at least one digit Password contains at least one letter Password contains at least one uppercase character Password conta...
0c166198a4603edc866f43abea4e5be20050562f
28,902
def copiar_dic(origen): """ Devuelve una copia nueva de ``origen`` con el menor estado compartido posible. Utiliza `fusionar_dics` debajo del capó, con un dict ``base`` vacío; consulte su documentación para obtener detalles sobre el comportamiento. .. versionadded:: 1.0 """ return fu...
8cf3cddc2bb999201c65af610196883fcbf97342
28,903
def get_all_users(conn): """Iterator that yields all IAM users, to simplify getting all users. The amazon interface presents a "next" token that has to be guarded. This makes that easier. However it doesn't present the returned object, only the list of user dicts Enables this sort of search: In [210]: r = get...
0e75aced4948b0a9511a2fc8f230c9500b626c95
28,904
def to_weight(df: pd.DataFrame, renorm=True): """ Converts molar quantities to mass quantities of the same order. E.g.: mol% --> mass% mol-ppm --> mass-ppm """ MWs = [pt.formula(c).mass for c in df.columns] if renorm: return renormalise(df.multiply(MWs)) else: return ...
db2ae5e8bcc2a5b54a85166da16f4e4158bd4c9c
28,905
import numpy def sind(ang: ArrayLike) -> ArrayLike: """Return the sine of an angle specified in degrees. Parameters ---------- ang : float An angle, in degrees. """ return numpy.sin(numpy.radians(ang))
f38563dc25a29b58e3448484f76913365646a311
28,906
import array def linscale(x, lb_in, ub_in, lb_out, ub_out): """linscale scales x according to the provided bounds. Parameters ---------- x : (N, x_dim) numpy array lb_in : scalar or 1D list of len x_dim or (1,) or (x_dim,) numpy array Returns ------- xs : (N, x_dim) numpy array ...
f9e4e095da2ab07e8f91edc76cb1a2bde35c2cbc
28,907
def sync_from(src, dest): """Synchronize a directory from Dropbox.""" return False
fe1339c59c25044bdf48e50e12cab80aa9a7ec63
28,908
import re def transcribe(seq: str) -> str: """ transcribes DNA to RNA by generating the complement sequence with T -> U replacement """ #stores the complement, RNA seq RNA_seq = "" #generate complement sequence #DNA->ACTG->A-><-T, C-><-G #T->U replacement keep_alpha_only ...
baa9b13f537e02cc034732bd2d6e439e05acf70a
28,909
def filter_timeline_actions(tim, **filters): """tim (dict) contains info for one TIM""" actions = tim['timeline'] for field, required_value in filters.items(): if field == 'time': # Times are given as closed intervals: either [0,134] or [135,150] acceptable_times = range(requ...
9f354e7d9d40b3ad31fd9d7cb256598b1fde11ba
28,910
def _make_n_rows(x, n, y=None): """ Multiplies or reduces the rows of x to get exactly *n* rows. """ if n < x.shape[0]: if y is None: return x[:n].copy() return x[:n].copy(), y[:n].copy() if len(x.shape) < 2: r = np.empty((n,), dtype=x.dtype) if y is n...
8b29deb282a327945e73b73b0332e663040f6c40
28,911
def calculate_match_unnormd_fft( params_h: Binary, params_d: Binary, fs, pad_low, pad_high, S_n=S_n_LISA ): """ Inner product of waveforms, maximized over Phi_c by taking absolute value and t_c using the fast Fourier transform. """ df = fs[1] - fs[0] wf_h = amp(fs, params_h) * jnp.exp(1j * P...
841bf210be371d2a3b80d39330fbe60194a1972f
28,912
def _force_merge(session, model, new_model): """Force merge an existing `model` with a `new_model` by copying the primary key values from `model` to `new_model` before calling ``session.merge(model)``. """ pk_cols = mapper_primary_key(model.__class__) for col in pk_cols: setattr(new_mod...
4e80e732c576a733e724b4b3aee1613facf3b366
28,913
def get_alignment(ra_difference, dec_difference): """ This function ... :param ra_difference: :param dec_difference: :return: """ ra_alignment = None dec_alignment = None if np.isclose(ra_difference, 1.0, atol=0.0001): # if RA increment is close to 1 with a positive x increment ...
a209819d3e9cc47ace3ada1bcb084a02a23dc432
28,914
def three_to_one_with_mods(res: str) -> str: """ Converts three letter AA codes into 1 letter. Allows for modified residues. :param res: Three letter residue code str: :type res: str :return: 1-letter residue code :rtype: str """ return RESI_THREE_TO_1[res]
6d54ebf5941933cf0f9ef5b72ec6d0b69598b444
28,915
def sent2features(sent, pos_lex=None, neg_lex=None): """ Converts a sentence (list of (word, pos_tag) tuples) into a list of feature dictionaries """ return [word2features(sent, i, pos_lex, neg_lex) for i in range(len(sent))]
91cc95abfc0c699e71bc4c2f96608ca2dd199d53
28,916
def effect_of_travel_range_on_afv_attractiveness(): """ Real Name: b'Effect of travel range on AFV Attractiveness' Original Eqn: b'AFV travel range/travel range max' Units: b'Dmnl' Limits: (None, None) Type: component b'' """ return afv_travel_range() / travel_range_max()
f2058ae6be2a2cb356359f3889566405d87484cc
28,917
def serialize_read(function_code: int, transaction_id: int, unit_address: int, first_address: int, count: int) -> str: """ Universal function for handling serialization of all read type messages. Args: function_code: Unique function code. transaction_id: Unique ID of the transaction. ...
c329defe2a64ad33d2a5620e09b8d4145457416c
28,918
import torch from typing import Union from typing import Tuple from typing import Optional def plot_locally_connected_weights( weights: torch.Tensor, n_filters: int, kernel_size: Union[int, Tuple[int, int]], conv_size: Union[int, Tuple[int, int]], locations: torch.Tensor, input_sqrt: Union[int...
26f41b33a41592cf1091b482dfc41daa62adc37e
28,919
import copy def draw_box_list(img_bgr, box_list, thickness=-1, color=None, is_overlap=True, is_arrow=False, is_text=True, is_show=False, is_new=False, save_name=None): """ 绘制矩形列表 """ if is_new: img_bgr = copy.deepcopy(img_bgr) n_box = len(box_list) if not color: ...
fc6e7b33617fbed33f0a0a24f9880ed0b0a0119e
28,920
def adjust_protons(formula, protons): """ @param formula: chemical formula as string @param protons: number of hydrogens to add/remove as intager @return: new formula as string """ if not protons: return (formula,"") protons = int(protons) Notes = "" #The whole function assum...
a422e90f20022b5e58ba3c36e92562d554cfea2e
28,921
def angsep(ra1,dec1,ra2,dec2): """Compute the angular separations between two points on a sphere Parameters: - ra1 - Right ascension of first position - dec1 - Declination of first position - ra2 - Right ascension of second position - dec2 - Declination of second position Note: All inp...
430107145de60aa7f572f64824a34c2acc0dd353
28,922
from typing import Callable from typing import Dict from typing import Any from typing import Type def construct_schema_function_without_choices() -> Callable: """ Modifies model example and description if needed. Note that schema extra has to be a function, otherwise it's called to soon before all t...
e9d3d44013b088ba8f582f87828e99e8cb7654ab
28,923
def is_cross_not_claimed(event_list, team): """Returns if event list has a cross-not-claimed Goalkeeper event; cross not successfully caught""" cnc = False for e in event_list[:1]: if e.type_id == 53: cnc = True return cnc
c63080119d057f9eb8dfc950724f67f8e4d6be86
28,924
import numpy import math def _do_monte_carlo_run(pools, lulc_counts): """Do a single Monte Carlo run for carbon storage. Returns a dict with the results, keyed by scenario, and # including results for sequestration. """ # Sample carbon-per-grid-cell from the given normal distribution. # We s...
03ddcf90c135ce02f7692557f31bb530390d2a7a
28,925
def compute_partition(df): """Perform compute on a partition Partitions are perfectly aligned along 1 minute and the timestamp index is sorted. Below is a reasonably costly operation that aggregates data from each timestep. That dataframe would aggregate what the timestep had (i.e., measureme...
d4b727c3160932a5655e6a6aa62c664d21d8d5e6
28,926
def first_impressions_view(request): """First impressions view.""" auth = False try: auth = request.cookies['auth_tkt'] auth_tools = request.dbsession.query( MyModel ).filter(MyModel.category == 'admin').all() except KeyError: auth_tools = [] query = reque...
6ab837580d07cf6b9bf0b48bbf296b9acc084384
28,927
def mysql_create_tables(): """ when using mysql database, this is the function that is used to create the tables in the database for the first time when you run the nettacker module. Args: None Returns: True if success otherwise False """ try: ...
c953f24d98ad919f57cd262087731dc1fcfc8886
28,928
def get_camera_intrinsic_parameters(stub): """ Get camera intrinsic params from gprc detection server. """ request = detection_server_pb2.Empty() try: response = stub.GetCameraIntrinsicParameters(request) return response except grpc.RpcError as err: logger.error(err.details()) #p...
7c971ec183ffcff1d1173af2dd8a6d540d8c360b
28,929
def version_strategy(version: str) -> AwesomeVersionStrategy: """Return the version stragegy.""" if is_buildver(version): return AwesomeVersionStrategy.BUILDVER if is_calver(version): return AwesomeVersionStrategy.CALVER if is_semver(version): return AwesomeVersionStrategy.SEMVER...
b62014bbdd10e04bf0b39e1619eac9e4c408bb83
28,930
def get_transcript_name(ids): """Get transcript name.""" return _search(transcript_name_re, ids)
bc8915f6efe1b468409e14bb622aa8d6b90fa26d
28,932
def rank_items(ratings, similarities): """ (アイテムのインデックス, 予測した評価値)のタプルリストをランキング(評価値の降順ソート)で返す """ ranking = [ ] for i, r in enumerate(ratings): if r != -1: continue ranking.append((i, predict_rating(ratings, i, similarities))) return sorted(ranking, key=lambda r: r[...
dc9088e122a601664660eb712aa7437afb1290a1
28,933
def hex2(n, uppercase=True): """ Return 2 characters corresponding to the hexadecimal representation of `n`. :param n: 0 <= int < 256 :param uppercase: bool :return: str (length == 2) """ assert isinstance(n, int) assert 0 <= n < 256 assert isinstance(uppercase, bool), type(upperca...
6cda31436914b116817ff7506d489265b51b68dc
28,934
import csv from typing import OrderedDict def get_split_statistics(filepath): """ Computes the label frequency, amount of utterances and tokens for a preprocessed tsv file. """ label_freq = defaultdict(int) amount_tokens = 0 with open(filepath, 'r') as file: reader = csv.Dict...
44e4d94fc547d08cabc7450fedc29b403ddd7320
28,935
def cast_int(value): """ Cast value to 32bit integer Usage: cast_int(1 << 31) == -1 (where as: 1 << 31 == 2147483648) """ value = value & 0xffffffff if value & 0x80000000: value = ~value + 1 & 0xffffffff return -value else: return value
c9c6da6e072bff6b241bc3feda6b0b02cb08cdb3
28,936
def dense_fast_decode( src_vocab_size, trg_vocab_size, max_in_len, n_layer, enc_n_layer, n_head, d_key, d_value, d_model, d_inner_hid, prepostprocess_dropout, attention_dropout, relu_dropout, preprocess_cmd, ...
86485e470c4f2aefa445807fc892e508e9690b28
28,937
def fixed_rotation_objective(link,ref=None,local_axis=None,world_axis=None): """Convenience function for fixing the given link at its current orientation in space. If local_axis and world_axis are not provided, the entire link's orientation is constrained. If only local_axis is provided, the link...
69f918217e5f5a310f5c81c7c0469347ccc9d068
28,938
def chinese_cut(text): """ 进行中文分词 :param text: 中文数据 :return: 分词后的数据 """ return ' '.join(jieba.cut(text))
0e70bf1d65dbb8d01118bdb6b8f248a860a169f1
28,939
def bottleneck_block_(inputs, filters, is_training, strides, use_projection=False, pruning_method='baseline', init_method='baseline', data_format='channels_first', ...
3e1a5448bbaef54a1be46e2c5067c1f7603b1551
28,940
def WaitForOperation(client, operation_ref, message): """Waits until the given operation finishes. Wait loop terminates when the operation's status becomes 'DONE'. Args: client: interface to the Cloud Updater API operation_ref: operation to poll message: message to be displayed by progress tracker ...
d94f8db634e1fd09426461d1b412de8ea404efed
28,941
def ifloordiv(): """//=: Inplace floor divide operator.""" class _Operand: def __init__(self): self.value = '' def __ifloordiv__(self, other): self.value = "int(val/{})".format(other) return self item = _Operand() item //= 2 return item.value
351c27cffe9a919641b43f62df166e93827f468f
28,942
def search_custom_results(result_id): """ Search a result for predictions. request['maxPredictionSort'] - when true sort by max prediction request['all'] - include values in download request['page'] - which page of results to show request['perPage'] - items per page to show :param result_id:...
2ab31458eccec466c27a3e85d84352b5919a7047
28,943
def create_1_layer_ANN_classification( input_shape, num_hidden_nodes, num_classes, activation_function='relu' ): """ Creates a 1 layer classification ANN with the keras backend. Arguments: input_shape (int tuple): The shape of the input excluding batch. num_hidden_nodes (i...
8e557be241f7b269cc12488dff9ecf96b3ff3fd2
28,944
def unsqueeze(x, axis, name=None): """ :alias_main: paddle.unsqueeze :alias: paddle.unsqueeze, paddle.tensor.unsqueeze, paddle.tensor.manipulation.unsqueeze Insert single-dimensional entries to the shape of input Tensor ``x``. Takes one required argument axis, a dimension or list of dimensions that will ...
d261f74692b8fb2ad3295aa2e621313a89b9197e
28,945
def get_kills_info_player_match(player_id,match_id,prt=False): """ get ONE player in ONE match's kills information :param player_id: :param match_id: :param prt: :return: list of kill information """ info = get_player_info_match_id(player_id,match_id) info_kills = {} if('hero_kil...
7deca277a8315fa9f0f7dddbef0297a43b15b39e
28,946
from typing import Dict def update_args(args: Dict, inv_file: str, conf_file: str) -> Dict: """ Add inventory file and config file in the correct spots inside the arguments Args: args (Dict): controller args inv_file (str): inventory file conf_file (str): config file Returns:...
c1cd377785f0af26740d5cecd73186caaa6c79b6
28,947
def _add_vessel_class(df): """Creates 'Class' column based on vessel LOA ft.""" df.loc[:, "Class"] = "Panamax" post_row = (df.loc[:, "LOA ft"] > 965) post_loc = df.loc[post_row, :].index post_pan = df.index.isin(post_loc) df.loc[post_pan, "Class"] = "Post-Panamax" return df
5abec9f0bee8d7d6c734100c64a7624fdb5fb672
28,948
def async_generate_ptr_query(ip): """Generate a ptr query with the next random id.""" return message.make_query(ip.reverse_pointer, rdatatype.PTR)
3b9086f7a3c13aead6c277362997968e65035b1a
28,949
def masked_within_block_local_attention_1d(q, k, v, block_length=64, name=None): """Attention to the source and a neighborhood to the left within a block. The sequence is divided into blocks of length block_length. Attention for a given query position can only see memory positions less than or equal to the que...
1babc20ef4d89bda21d4b96bc61c6017087f2927
28,950
import requests def catch_all(path): """ Repeats the request to the latest version of default service by replacing all occurrences of the hostname to the new_host defined above. The replacement happens for: - URL and URL query string - Headers, including cookie headers - The body, if...
c11a1de657c6095a77a0114a965733526f1b926f
28,951
def fix_community_medium( tax, medium, min_growth=0.1, max_import=1, minimize_components=True, n_jobs=4, ): """Augment a growth medium so all community members can grow in it. Arguments --------- tax : pandas.Dataframe A taxonomy specification as passed to `micom.Communi...
c77cf77ec29ea160bc1c623247f103dc88d7b9b5
28,953
def _p_wa_higher_wb(k1, k2, theta1, theta2): """ :param k1: Shape of wa :param k2: Shape of wb :param theta1: Scale of wa :param theta2: Scale of wb :return: """ a = k2 b = k1 x = theta1 / (theta1 + theta2) return betainc(a, b, x)
a0b3934039ed480074faaba118c5a7e218a41905
28,954
def noisify_binary_asymmetric(y_train, noise, random_state=None): """mistakes: 1 -> 0: n 0 -> 1: .05 """ P = np.eye(2) n = noise assert 0.0 <= n < 0.5 if noise > 0.0: P[1, 1], P[1, 0] = 1.0 - n, n P[0, 0], P[0, 1] = 0.95, 0.05 y_train_noisy = multiclass...
b0656d04d95a21108dd8c1ed76e464eed6c32b11
28,955
import json def get_solved_problems(user_id, custom=False): """ Get the solved and unsolved problems of a user @param user_id(Integer): user_id @param custom(Boolean): If the user_id is a custom user @return(Tuple): List of solved and unsolved problems """ if user_id is N...
5a178953246e58db33a25e65b121772192804369
28,956
import click from typing import Optional from typing import Union def run_link(ctx: click.Context, link: str, language: str) -> Optional[Union[list, str]]: """ Make a multiline prompt for code input and send the code to the api. The compiled output from the api is returned. """ console = ctx.obj[...
2dbb4fcaaf0898884bee73bb8380a307a4f21f74
28,959
def cdiff(alpha, beta): """ Difference between pairs :math:`x_i-y_i` around the circle, computed efficiently. :param alpha: sample of circular random variable :param beta: sample of circular random variable :return: distance between the pairs """ return center_angle(alpha - beta)
a820bf74bb5ad0edb1f33c80a2f9f2a9723d7e25
28,960
def split_buffer(buffer): """Returns a tuples of tuples in the format of (data, separator). data should be highlighted while separator should be printed unchanged, after data. Args: buffer (str): A string to split using SPLIT_RE. """ splits = SPLIT_RE.split(buffer) # Append an empty se...
33d344b2a91440c2e51304664a87431514fe6aff
28,962
def save_verify_img(browser, id): """ Save the verification code picture in the current directory. :param: browser :param: id return: verify_code """ verify_img = browser.find_element_by_id(id) # Get the coordinates of the specified label left = verify_img.location['x'] top = ver...
a406edadb7165512d54b613d2bd5136c2e81ea37
28,963
def write_values(value): """Write a `*values` line in an LTA file. Parameters ---------- value : [sequence of] int or float or str Returns ------- str """ if isinstance(value, (str, int, float)): return str(value) else: return ' '.join([str(v) for v in value])
705aeb1cbbe1ef3d9deca2b5e360f4c72cb3a25e
28,964
def denormalize_spectrogram(S, is_mel): """Denormalize log-magnitude spectrogram.""" if is_mel: return S * hp.mel_normalize_variance + hp.mel_normalize_mean else: return S * hp.lin_normalize_variance + hp.lin_normalize_mean
8e26d1b2f038c201faa473d14763bb8916a38bd3
28,965
def get_pixel(color: str, intensity: float): """Converts a color and brightness to a Pixel""" return Pixel(*[int(i*intensity) for i in color])
d4198c4d003b098884eeaecffa407cb0b2066900
28,966
def findOverlapOrNearest(gs, ts, tree, start, end): """ first to check direct overlap with TSS, if no or multiple items, then get the close one @param gs: {tss: cLoops2.ds.Gene}, tss is key and int @pram ts: [tss] @param tree: KDTree from TSSs @param start: query start @param end: query end ...
8c3c8c85a22063a1f8f7ffcfdb832dd4b357a485
28,967
import numpy def get_front_types(locating_var_matrix_m01_s01, warm_front_percentile=DEFAULT_FRONT_PERCENTILE, cold_front_percentile=DEFAULT_FRONT_PERCENTILE): """Infers front type at each grid cell. M = number of rows in grid N = number of columns in grid :par...
92d4bc84839c8f7f5e23697807ce01ec947d10c0
28,969
def rainfall_rate(radar, gatefilter, kdp_name, zdr_name, refl_name='DBZ_CORR', hydro_name='radar_echo_classification', temperature_name='temperature'): """ Rainfall rate algorithm from csu_radartools. Parameters: =========== radar: Py-ART radar structure. r...
6af6b29cc635659cef127f2fa780f2feb2f5926a
28,970
def get_wrestlers(): """Grabs a list of all of the wrestlers from the database. @return A list of Wrestler objects, or an empty list if no wrestlers have been created. """ wrestlers = db.get_wrestlers() return map(lambda w: Wrestler(**w), wrestlers)
d0440780b0cd3e7fbb726718703ba6e81bf1ab1a
28,971
def masterUniversalTransferSubacc(fromAccountType, toAccountType, asset, amount, fromEmail="", toEmail="", recvWindow=""): """# Universal Transfer (For Master Account) #### `POST /sapi/v1/sub-account/universalTransfer (HMAC SHA256)` ### Weight: 1 ### Parameters: Name |Type |Mandatory |Description --------|-------...
d517c6c471aa4e7d90bde557116fd257abba2831
28,973
def allpass(source, g): """First order Shroeder all pass filter. y[n] + g y[n-1] = g.conjugate() x[n] + x[n-1].""" return polezero(source, 1.0, g.conjugate(), g, 1.0)
5b5bdeb4455c25ceb7b9df338938a868cf9de3b3
28,974
def read_data_and_split(train_csv_path = '../data/clean/bank_train.csv', test_csv_path = '../data/clean/bank_test.csv'): """ Reads the data from the given paths and returns predictors and response variables separately for train and test sets Parameters ---------- train_c...
fac0abcbcb7e701a94fa68bf1e7b51cf92c4e800
28,975
def get_bro(fn_config, readonly=True): """ Convenience function to get a bro with a datastore initialized with a config file Args: fn_config: path to the config file readonly: load database readonly? Returns: A true bro """ store = datastore.DataStore() store.read...
b15136879e50c1e90f605b315ee827f5a05b72e7
28,976
def get_sample_metadata_token() -> str: """Get sample-metadata Bearer auth token for Azure or GCP depending on deployment config.""" deploy_config = get_deploy_config() if deploy_config.cloud == "azure": scope = f"api://smapi-{deploy_config.sample_metadata_project}/.default" return get_azur...
33e6abddee618578fb2a62506b81cee6cb8a3875
28,977
def replace_module_params(source, target, modules): """Replace selected module params in target by corresponding source values.""" source, _ = hk.data_structures.partition( lambda module, name, value: module in modules, source) return hk.data_structures.merge(target, source)
5ef7de2a7a05e6ab1f2301056a11998c5721cb29
28,978
def get_knmi_at_locations(model_ds, start='2010', end=None, nodata=-999): """get knmi data at the locations of the active grid cells in model_ds. Parameters ---------- model_ds : xr.DataSet dataset containing relevant model grid information ...
1e9cb066d818788c428835501be0ee04a3e3ec43
28,980
def coordinate_x_and_y_as_ndarray(x, y): """ Utility function to coordinate the two scalar/np.ndarray variables x and y as NumPy Arrays. The following cases are considered: 1) if x is array of length n; y is array of length m, then: x, y ---> (m, n) shaped arrays creating a mesh...
bea9c1cc04d16fd3d7326c350b1169f0a12a0f7a
28,981
def cos_sim(vec1, vec2): """ Returns the cosine similarity between given two vectors """ return vec1.dot(vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
4a35a419bfe3a51299ac94a4245c943516812889
28,982
def makeTrans(tup: tuple): """ 生成一个字典格式的单词释义""" def toStr(s): return s if type(s) is str else str(s, encoding="utf-8") res = None if len(tup) >= 4: res = { "word": toStr(tup[0]), "phonetic": toStr(tup[1]), "translation": toStr(tup[2]), "exc...
f5c578c83f0256cc8fa64abff2335de135ae9bfc
28,983
def _keepbits_interface(da, keepbits): """Common interface to allowed keepbits types Parameters ---------- da : :py:class:`xarray.DataArray` Input data to bitround keepbits : int, dict of {str: int}, :py:class:`xarray.DataArray` or :py:class:`xarray.Dataset` How many bits to keep as int...
94101e6d18a587c0d952caaf7154a05884dbcfb2
28,984
def calc_fraction(i, q, u, transmission_correction=1): """ Method for determining the fractional polarization. Parameters ---------- i : float Stokes I parameter. q : float Stokes Q parameter. u : float Stokes U parameter. transmission_correction : float (Default...
d2488351d860377ef8a38a7e6a29ff385798e3c6
28,985
from typing import Union from re import S def label(node: Union["SQLNode", None]) -> Symbol: """Returns a default alias for the node; to use when rendering to SQL. The implementation for subclasses of SQLNodes is defined in `nodedefs.py`. """ if node is None: return S("_") else: ra...
a97295329dab1d54052b7f23656d23e4e0dc040e
28,986
def mean(list): """Function that returns the mean of a list""" sum = 0 for num in list: sum += num return sum/len(list)
972544f64f87860a078405a4938226f7fab307c2
28,987
import six def replace( key, value, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_TIME, min_compress_len=DEFAULT_MIN_COMPRESS_LEN, ): """ Replace a key on the memcached server. This only succeeds if the key already exists. This is the opposite of :mod:`memcached.add <salt....
b8a83f75c423eb20499abf9ee99c39e38c849a61
28,988
import torch def cpu(): """Defined in :numref:`sec_use_gpu`""" return torch.device('cpu')
899a95ed4b806280eda315c17a2d3e6d3f94e039
28,989
def get(name): """ Get configuration identified by name """ return CONFIGS[name]
5774bd9a505f6a9c402456f520a2cae268e4f0d4
28,990
def gpu_layout_factory(op): """ Generates a list of possible layouts given an op Arguments: op: Computation graph op which runs on the device Returns: List of possible layout assignment descriptors """ if isinstance(op, AssignOp): return GPULayoutAssignment.generate_ew_...
fa9363368ec41454dcdd7ded508dc21b638bf985
28,991
def dropout(tensor, noise_shape=None, random_mask=None, probability=0.1, scale=True, seed=None, return_mask=False, name="dropout"): """ With probability `probability`, outputs `0` otherwise outputs the input element. If ``scale`` i...
bade8e9a66a288097860bb33e33a1503ba822262
28,992
def get_words_for_board_optimize_fast(word_tuples, board_size, packing_constant=1.1): """Try different combinations of words to maximize the overlap_avoidance_probability metric First try to maximize the minimum, and if that can be easily achieved, then maximize the mean.""" # Identify the longest words inc...
4c671ed58da3cb10f8493d28b3e4eda0aa265f73
28,993
import re def parse_timedelta(time_str: str) -> timedelta: """ Parse a time string e.g. (2h13m) into a timedelta object. Stolen on the web """ regex = re.compile( r"^((?P<days>[\.\d]+?)d)?((?P<hours>[\.\d]+?)h)?((?P<minutes>[\.\d]+?)m)?((?P<seconds>[\.\d]+?)s)?$" ) time_str = replace(...
886bdc01d707ba4e0b04a6b1f1ac665e2c3965bd
28,994
from vrml import node def delSceneGraph( cls ): """Delete the scenegraph associated with a prototype""" return node.PrototypedNode.scenegraph.fdel( cls )
e16e97c0c70423f459de1e43646db84b0f02f06a
28,995
from typing import Any def get_node_active_learning_heuristic_by_name( name: str, **kwargs: Any, ) -> NodeActiveLearningHeuristic: """ Factory method for node active learning heuristics. :param name: The name of the heuristic. :param kwargs: The keyword-based arguments. :...
aab06e172b15ee64b410cdd8ca90f9f137143078
28,996
from skimage.exposure import rescale_intensity def apply_elastic_transform_intensity(imgs, labels, strength=0.08, shift=0.3, sigma_max=0.2, N=20, random_state=None): """This function wraps the elastic transform as well as adding random noise and gamma adjustment to augment a batch of images. Parameters ...
51af4c8dd8e5e76cf6ababc9096bbd1dd7f57a08
28,997
def byte_size(num, suffix='B'): """ Return a formatted string indicating the size in bytes, with the proper unit, e.g. KB, MB, GB, TB, etc. :arg num: The number of byte :arg suffix: An arbitrary suffix, like `Bytes` :rtype: float """ for unit in ['','K','M','G','T','P','E','Z']: ...
8db3a1c4c5e3740baf606abe3f0dcc108ab04e97
28,998
def reduce_grid_info(grid_fnames, noise_fnames=None, nprocs=1, cap_unique=1000): """ Computes the total minimum and maximum of the necessary quantities across all the subgrids. Can run in parallel. Parameters ---------- grid_fnames: list of str subgrid file paths noise_fnames: list...
ceaad828396d8894def288d29357799b0bd8a10d
28,999
from typing import OrderedDict def generate_record( category_name: str, x1: float, y1: float, x2: float, y2: float, sample_data_token: str, filename: str, ) -> OrderedDict: """Generate one 2D annotation record given various informations on top of the 2D bounding box coordinates. ...
77fb545a1235527a439f2323bfa077128f57e08a
29,000
def create_fan_in_profile(): """Create the fan in profile.""" regions = [ MetricRegion("1-10", 1, 10), MetricRegion("11-20", 11, 20), MetricRegion("21-50", 21, 50), MetricRegion("50+", 51, 1001), ] return MetricProfile("Fan in", regions)
3266f772c6081343eb60f4bb32234bf6d47e4393
29,001
def from_parmed( structure, compound=None, coords_only=False, infer_hierarchy=True ): """Backend-specific loading function - parmed. Parameters ---------- structure : pmd.Structure New structure to be loaded. compound : mb.Compound, optional, default=None Host mb.Compound that w...
2c3437faa3ddf228f8b51ac6dfb0dae059a033af
29,002
from scipy.spatial.transform import Rotation as R def get_transform(x: float, y: float, z: float, angle: float, scale_x: float = 1, scale_z: float = 1) -> list: """ Compute transformation matrix :param x: X position of center :param y: Y position of center :param z: Z position of center :param...
12ddeafbc375c981b07d3e13b1d34558b1608e17
29,003
import json def read_json(file_path: str): """ Load json files. Args: file_path: path to the file """ with open(file_path) as f: return json.load(f)
96f3f8e5c9d40286f122fde42d881e6a7c7cc260
29,004
def ds_from_df_from_dtypes(df, y_columns, standardize_X=False): """ Convert a pandas dataframe into a dataset with the respective d_types of the input features. Parameters: ---------- df: pandas dataframe the dataframe used for the conversion. y_columns: string or list of strings ...
d48476e9135724f925b46f20fbf96b72726bfa33
29,006
def login_cookies(): """working login """ cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) html = opener.open(LOGIN_URL).read() data = parse_form(html) data['email'] = LOGIN_EMAIL data['password'] = LOGIN_PASSWORD encoded_data = urllib.urlenco...
f21436e6aae3516e21ba0a99f2742ad1168a9a4d
29,007
def list_images(args): """List deployed images.""" table = repos.Repo(args.root).get_images() for image_id in sorted(table): podvs = table[image_id] if podvs: podvs = ' '.join('%s@%s' % pv for pv in podvs) print('%s %s' % (image_id, podvs)) else: p...
549dac8961057ab1bfdea45b5560915233b388c5
29,008