content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_pip_package_name(provider_package_id: str) -> str: """ Returns PIP package name for the package id. :param provider_package_id: id of the package :return: the name of pip package """ return "apache-airflow-providers-" + provider_package_id.replace(".", "-")
e7aafbdfb0e296e60fedfcf7e4970d750e4f3ffa
3,657,462
import numpy def func_asymmetry_f_b(z, flag_z: bool = False): """Function F_b(z) for asymmetry factor. """ f_a , dder_f_a = func_asymmetry_f_a(z, flag_z=flag_z) res = 2*(2*numpy.square(z)-3)*f_a dder = {} if flag_z: dder["z"] = 8 * z * f_a + 2*(2*numpy.square(z)-3)*dder_f_a["z"] re...
5fc157856c379267c12137551f0eb5e6c4ddd3aa
3,657,463
def parse_args(): """Command-line argument parser for generating scenes.""" # New parser parser = ArgumentParser(description='Monte Carlo rendering generator') # Rendering parameters parser.add_argument('-t', '--tungsten', help='tungsten renderer full path', default='tungsten', type=str) parse...
4fad89d60f5446f9dbd66f4624a43b9436ee97a5
3,657,464
def unique_id(token_id): """Return a unique ID for a token. The returned value is useful as the primary key of a database table, memcache store, or other lookup table. :returns: Given a PKI token, returns it's hashed value. Otherwise, returns the passed-in value (such as a UUID token ID ...
9526e483f617728b4a9307bd10097c78ec361ad0
3,657,465
def encode_aval_types(df_param: pd.DataFrame, df_ret: pd.DataFrame, df_var: pd.DataFrame, df_aval_types: pd.DataFrame): """ It encodes the type of parameters and return according to visible type hints """ types = df_aval_types['Types'].tolist() def trans_aval_type(x): ...
a68ff812f69c264534daf16935d88f528ba35464
3,657,466
def first(iterable, default=None): """ Returns the first item or a default value >>> first(x for x in [1, 2, 3] if x % 2 == 0) 2 >>> first((x for x in [1, 2, 3] if x > 42), -1) -1 """ return next(iter(iterable), default)
6907e63934967c332eea9cedb5e0ee767a88fe8f
3,657,467
def generate_uuid_from_wf_data(wf_data: np.ndarray, decimals: int = 12) -> str: """ Creates a unique identifier from the waveform data, using a hash. Identical arrays yield identical strings within the same process. Parameters ---------- wf_data: The data to generate the unique id for. ...
e12a6a8807d68181f0e04bf7446cf5e381cab3f9
3,657,468
def aggregate(table, key, aggregation=None, value=None, presorted=False, buffersize=None, tempdir=None, cache=True): """Group rows under the given key then apply aggregation functions. E.g.:: >>> import petl as etl >>> >>> table1 = [['foo', 'bar', 'baz'], ... ...
22d857001d0dcadaed82a197101125e5ca922e07
3,657,469
def most_similar(sen, voting_dict): """ Input: the last name of a senator, and a dictionary mapping senator names to lists representing their voting records. Output: the last name of the senator whose political mindset is most like the input senator (excluding, of course, the input se...
6889d08af21d4007fa01dbe4946748aef0d9e3e6
3,657,471
def fixed_ro_bci_edge(ascentlat, lat_fixed_ro_ann, zero_bounds_guess_range=np.arange(0.1, 90, 5)): """Numerically solve fixed-Ro, 2-layer BCI model of HC edge.""" def _solver(lat_a, lat_h): # Reasonable to start guess at the average of the two given latitudes. init_guess = ...
544c1747450cac52d161aa267a6332d4902798d1
3,657,472
def fresh_jwt_required(fn): """ A decorator to protect a Flask endpoint. If you decorate an endpoint with this, it will ensure that the requester has a valid and fresh access token before allowing the endpoint to be called. See also: :func:`~flask_jwt_extended.jwt_required` """ @wraps(...
e5f30192c68018a419bb086522217ce86b27e6f6
3,657,473
import random def random_small_number(): """ 随机生成一个小数 :return: 返回小数 """ return random.random()
45143c2c78dc72e21cbbe0a9c10babd00100be77
3,657,474
def get_sample(df, col_name, n=100, seed=42): """Get a sample from a column of a dataframe. It drops any numpy.nan entries before sampling. The sampling is performed without replacement. Example of numpydoc for those who haven't seen yet. Parameters ---------- df : pandas.Data...
a4fb8e1bbc7c11026b54b2ec341b85310596de13
3,657,475
def gen_mail_content(content, addr_from): """ 根据邮件体生成添加了dkim的新邮件 @param content: string 邮件体内容 @return str_mail: 加上dkim的新邮件 """ try: domain = addr_from.split('@')[-1] dkim_info = get_dkim_info(domain) if dkim_info: content = repalce_mail(content, addr_from) ...
90ad569f8f69b7fa39edab799b41522fddc3ce97
3,657,476
import warnings def autocov(ary, axis=-1): """Compute autocovariance estimates for every lag for the input array. Parameters ---------- ary : Numpy array An array containing MCMC samples Returns ------- acov: Numpy array same size as the input array """ axis = axis if axi...
e17dcfcbdee37022a5ab98561287f891acfefaf6
3,657,477
def _optimize_rule_mip( set_opt_model_func, profile, committeesize, resolute, max_num_of_committees, solver_id, name="None", committeescorefct=None, ): """Compute rules, which are given in the form of an optimization problem, using Python MIP. Parameters ---------- set_o...
41c3ace270be4dcb4321e4eeedb23d125e6766c3
3,657,479
import itertools def Zuo_fig_3_18(verbose=True): """ Input for Figure 3.18 in Zuo and Spence \"Advanced TEM\", 2017 This input acts as an example as well as a reference Returns: dictionary: tags is the dictionary of all input and output paramter needed to reproduce that figure. """ ...
560272c4c28c8e0628403573dd76c0573ae9d937
3,657,480
def subscribe_feed(feed_link: str, title: str, parser: str, conn: Conn) -> str: """Return the feed_id if nothing wrong.""" feed_id = new_feed_id(conn) conn.execute( stmt.Insert_feed, dict( id=feed_id, feed_link=feed_link, website="", title=titl...
88a49ebaa4f766bfb228dc3ba271e8c98d50da99
3,657,481
def process_grid(procstatus, dscfg, radar_list=None): """ Puts the radar data in a regular grid Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of dictionaries data set configuration. Acc...
b414fb327d3658cc6f9ba1296ec1226b5d2a7ff6
3,657,483
def float_to_16(value): """ convert float value into fixed exponent (8) number returns 16 bit integer, as value * 256 """ value = int(round(value*0x100,0)) return value & 0xffff
0a587e4505c9c19b0cbdd2f94c8a964f2a5a3ccd
3,657,484
def create_keras_one_layer_dense_model(*, input_size, output_size, verbose=False, **kwargs ): """ Notes: https://www.tensorflow.org/tutorials/keras/save_and_load """ # ................................................... # Create model model = Seq...
d7d34d9981aac318bca5838c42ed7f844c27cfda
3,657,485
def API_encrypt(key, in_text, formatting:str = "Base64", nonce_type:str = "Hybrid"): """ Returns: Input Text 147 Encrypted with Input Key. """ try: # Ensure an Appropriate Encoding Argument is Provided. try: encoding = FORMATS[formatting] except: raise ValueError("Invalid Encoding Argume...
d7336197ba1d32d89c8dc0c098bfbc20c795168d
3,657,486
def convert_log_dict_to_np(logs): """ Take in logs and return params """ # Init params n_samples_after_warmup = len(logs) n_grid = logs[0]['u'].shape[-1] u = np.zeros((n_samples_after_warmup, n_grid)) Y = np.zeros((n_samples_after_warmup, n_grid)) k = np.zeros((n_samples_after_warmu...
1962fa563ee5d741f7f1ec6453b7fd5693efeca2
3,657,487
from pathlib import Path from typing import Callable def map_links_in_markdownfile( filepath: Path, func: Callable[[Link], None] ) -> bool: """Dosyadaki tüm linkler için verilen fonksiyonu uygular Arguments: filepath {Path} -- Dosya yolu objesi func {Callable[[Link], None]} -- Link al...
4f6aa7ee5ecb7aed1df8551a69161305601d0489
3,657,489
def half_cell_t_2d_triangular_precursor(p, t): """Creates a precursor to horizontal transmissibility for prism grids (see notes). arguments: p (numpy float array of shape (N, 2 or 3)): the xy(&z) locations of cell vertices t (numpy int array of shape (M, 3)): the triangulation of p for which the ...
555f8b260f7c5b3f2e215378655710533ee344d5
3,657,490
def count_datavolume(sim_dict): """ Extract from the given input the amount of time and the memory you need to process each simulation through the JWST pipeline :param dict sim_dict: Each key represent a set of simulations (a CAR activity for instance) each value is a list of ...
dabe86d64be0342486d1680ee8e5a1cb72162550
3,657,491
def context(): """Return an instance of the JIRA tool context.""" return dict()
e24e859add22eef279b650f28dce4f6732c346b8
3,657,493
def dist_to_group(idx: int, group_type: str, lst): """ A version of group_count that allows for sorting with solo agents Sometimes entities don't have immediately adjacent neighbors. In that case, the value represents the distance to any neighbor, e.g -1 means that an entity one to the left or righ...
74ae510de4145f097fbf9daf406a6156933bae20
3,657,494
from typing import AnyStr from typing import List from typing import Dict def get_nodes_rating(start: AnyStr, end: AnyStr, tenant_id: AnyStr, namespaces: List[AnyStr]) -> List[Dict]: """ Get the rating by node. :start (AnyStr) A timestamp, as...
b75d35fc195b8317ed8b84ab42ce07339f2f1bf3
3,657,495
def f(OPL,R): """ Restoration function calculated from optical path length (OPL) and from rational function parameter (R). The rational is multiplied along all optical path. """ x = 1 for ii in range(len(OPL)): x = x * (OPL[ii] + R[ii][2]) / (R[ii][0] * OPL[ii] + R[ii][1]) return x
5b64b232646768d2068b114d112a8da749c84706
3,657,496
def _str_conv(number, rounded=False): """ Convenience tool to convert a number, either float or int into a string. If the int or float is None, returns empty string. >>> print(_str_conv(12.3)) 12.3 >>> print(_str_conv(12.34546, rounded=1)) 12.3 >>> print(_str_conv(None)) <BLANKLINE...
d352e8f0956b821a25513bf4a4eecfae5a6a7dcd
3,657,497
def build_eval_graph(input_fn, model_fn, hparams): """Build the evaluation computation graph.""" dataset = input_fn(None) batch = dataset.make_one_shot_iterator().get_next() batch_holder = { "transform": tf.placeholder( tf.float32, [1, 1, hparams.n_parts, hparams.n_d...
3f3d1425d08e964de68e99ea0c6cb4397975427a
3,657,498
def _encodeLength(length): """ Encode length as a hex string. Args: length: write your description """ assert length >= 0 if length < hex160: return chr(length) s = ("%x" % length).encode() if len(s) % 2: s = "0" + s s = BinaryAscii.binaryFromHex(s) le...
fd85d5faf85da6920e4a0704118e41901f327d9c
3,657,499
def stemmer(stemmed_sent): """ Removes stop words from a tokenized sentence """ porter = PorterStemmer() stemmed_sentence = [] for word in literal_eval(stemmed_sent): stemmed_word = porter.stem(word) stemmed_sentence.append(stemmed_word) return stemmed_sentence
96337684deb7846f56acf302d1e0d8c8ab9743dd
3,657,500
def _queue_number_priority(v): """Returns the task's priority. There's an overflow of 1 bit, as part of the timestamp overflows on the laster part of the year, so the result is between 0 and 330. See _gen_queue_number() for the details. """ return int(_queue_number_order_priority(v) >> 22)
e61d6e1d04551ce55a533bfe7805f3358bb8d0ca
3,657,501
def test_generator_aovs(path): """Generate a function testing given `path`. :param path: gproject path to test :return: function """ def test_func(self): """test render pass render layer and AOV particularities """ assert path in g_parsed p = g_parsed[path] ...
a67b8f741a19f4d3733ab35699ef11a713e283b5
3,657,502
from typing import Union def delimited_list( expr: Union[str, ParserElement], delim: Union[str, ParserElement] = ",", combine: bool = False, min: OptionalType[int] = None, max: OptionalType[int] = None, *, allow_trailing_delim: bool = False, ) -> ParserElement: """Helper to define a de...
d1ac80f138a21ee21ecf76f918f1c7878863f80c
3,657,503
def get_minion_node_ips(k8s_conf): """ Returns a list IP addresses to all configured minion hosts :param k8s_conf: the configuration dict :return: a list IPs """ out = list() node_tuple_3 = get_minion_nodes_ip_name_type(k8s_conf) for hostname, ip, node_type in node_tuple_3: out.a...
9a93ddcd025e605805a9693dd14d58c92f53dc42
3,657,504
def calculate_ri(column): """ Function that calculates radiant intensity """ return float(sc.h * sc.c / 1e-9 * np.sum(column))
eac136f520ebbad0ea11f506c742e75fc524c4bb
3,657,505
def find_kw_in_lines(kw, lines, addon_str=' = '): """ Returns the index of a list of strings that had a kw in it Args: kw: Keyword to find in a line lines: List of strings to search for the keyword addon_str: String to append to your key word to help filter Return: i: In...
4b50c4eaecc55958fca6b134cc748d672c78d014
3,657,506
def delete_group(current_session, groupname): """ Deletes a group """ projects_to_purge = gp.get_group_projects(current_session, groupname) remove_projects_from_group(current_session, groupname, projects_to_purge) gp.clear_users_in_group(current_session, groupname) gp.clear_projects_in_group...
1a27cec1c3273bb56564587823ad04565867277f
3,657,507
def label_smoothed_nll_loss(lprobs, target, epsilon: float = 1e-8, ignore_index=None): """Adapted from fairseq Parameters ---------- lprobs Log probabilities of amino acids per position target Target amino acids encoded as integer indices epsilon Smoothing factor between...
eb09b7dd5c800b01b723f33cd0f7a84ae93b3489
3,657,508
import re def parse_date(regexen, date_str): """ Parse a messy string into a granular date `regexen` is of the form [ (regex, (granularity, groups -> datetime)) ] """ if date_str: for reg, (gran, dater) in regexen: m = re.match(reg, date_str) if m: ...
a141cad6762556115699ca0327b801537bab1c7e
3,657,511
def PreNotebook(*args, **kwargs): """PreNotebook() -> Notebook""" val = _controls_.new_PreNotebook(*args, **kwargs) return val
1974d3ed08a6811a871f7e069c4b74b97cb32e35
3,657,512
def user_voted(message_id: int, user_id: int) -> bool: """ CHECK IF A USER VOTED TO A DETECTION REPORT """ return bool( c.execute( """ SELECT * FROM reports WHERE message_id=? AND user_id=? """, (message_id, user_id), ...
baddfb69470699d611c050b6732d553f4f415212
3,657,513
import io def get_values(wsdl_url, site_code, variable_code, start=None, end=None, suds_cache=("default",), timeout=None, user_cache=False): """ Retrieves site values from a WaterOneFlow service using a GetValues request. Parameters ---------- wsdl_url : str URL of a servi...
57b9cbfbf713f5ac858a8d7a36464aae2a657757
3,657,514
def GetDot1xInterfaces(): """Retrieves attributes of all dot1x compatible interfaces. Returns: Array of dict or empty array """ interfaces = [] for interface in GetNetworkInterfaces(): if interface['type'] == 'IEEE80211' or interface['type'] == 'Ethernet': if (interface['builtin'] and ...
829cc1badf5917cc6302847311e5c8ef6aeebc11
3,657,515
def get_v_l(mol, at_name, r_ea): """ Returns list of the l's, and a nconf x nl array, v_l values for each l: l= 0,1,2,...,-1 """ vl = generate_ecp_functors(mol._ecp[at_name][1]) v_l = np.zeros([r_ea.shape[0], len(vl)]) for l, func in vl.items(): # -1,0,1,... v_l[:, l] = func(r_ea) r...
d987e5ceb28169d73ec23aaac2f7ab30a5e881c7
3,657,516
def search_transitions_in_freq_range(freq_min, freq_max, atomic_number, atomic_mass, n_min=1, n_max=1000, dn_min=1, dn_max=10, z=0.0, screening=False, extendsearch=None): """ -------------------------...
bd5fc3873909ce3937b6e94db9f04edb94dab326
3,657,517
async def test_async__rollback(): """Should rollback basic async actions""" state = {"counter": 0} async def incr(): state["counter"] += 1 return state["counter"] async def decr(): state["counter"] -= 1 async def fail(): raise ValueError("oops") try: w...
54cc780b01190bfd2ea2aacc70e62e8f0b3dfa64
3,657,518
import requests def is_referenced(url, id, catalog_info): """Given the url of a resource from the catalog, this function returns True if the resource is referenced by data.gouv.fr False otherwise :param :url: url of a resource in the catalog :type :url: string""" dgf_page = catalog...
15cfa64979f2765d29d7c4bb60a7a017feb27d43
3,657,520
import glob import functools def create_sema3d_datasets(args, test_seed_offset=0): """ Gets training and test datasets. """ train_names = ['bildstein_station1', 'bildstein_station5', 'domfountain_station1', 'domfountain_station3', 'neugasse_station1', 'sg27_station1', 'sg27_station2', 'sg27_station5', 's...
8642c5a10a5256fb9541be86676073c993b2faf8
3,657,521
def adjust_learning_rate(optimizer, step, args): """ Sets the learning rate to the initial LR decayed by gamma at every specified step/epoch Adapted from PyTorch Imagenet example: https://github.com/pytorch/examples/blob/master/imagenet/main.py step could also be epoch ...
359e2c5e0deb1abd156b7a954ecfae1b23511db2
3,657,522
def sigmoid(z): """sigmoid函数 """ return 1.0/(1.0+np.exp(-z))
80187d3711d18602a33d38edcc48eaad5c51818f
3,657,523
def beamformerFreq(steerVecType, boolRemovedDiagOfCSM, normFactor, inputTupleSteer, inputTupleCsm): """ Conventional beamformer in frequency domain. Use either a predefined steering vector formulation (see Sarradj 2012) or pass your own steering vector. Parameters ---------- steerVecType : (one...
f747122b0dff9a7b966813062b93a1cab8a91f3f
3,657,524
from typing import IO def createNewPY(): """trans normal pinyin to TTS pinyin""" py_trans = {} input_pinyin_list = IO.readList(r'docs/transTTSPinyin.txt') for line in input_pinyin_list: line_array = line.split(',') py_trans[line_array[0]] = line_array[1] return py_trans
e2bd5007cc217f72e3ffbeafd0ff75e18f8ec213
3,657,525
import re def search_wheelmap (lat, lng, interval, name, n): """Searches for a place which matches the given name in the given coordinates range. Returns false if nothing found""" # Calculate the bbox for the API call from_lat = lat - interval to_lat = lat + interval from_lng = lng - int...
88dfbf973fbd4891a4d8bf955335177ca3654016
3,657,526
from typing import Dict def get_entity_contents(entity: Dict) -> Dict: """ :param entity: Entity is a dictionary :return: A dict representation of the contents of entity """ return { 'ID': entity.get('id'), 'Name': entity.get('name'), 'EmailAddress': entity.get('email_addre...
3c9e133bf80bc4d59c6f663503b5083401acc4e0
3,657,527
def t68tot90(t68): """Convert from IPTS-68 to ITS-90 temperature scales, as specified in the CF Standard Name information for sea_water_temperature http://cfconventions.org/Data/cf-standard-names/27/build/cf-standard-name-table.html temperatures are in degrees C""" t90 = 0.9...
87ff55a196f01b8f1afd78381e7d012eafa079fa
3,657,528
def get_sort_accuracy_together(fake_ys, y): """ Args: fake_ys (np.ndarray): with shape (n_results, n_sample,). y (np.ndarray): with sample (n_sample,). Returns: corr (np.ndarray): with shape (n_result,) """ y_sort = np.sort(y) y_sort2 = np.sort(y)[::-1] fake_ys =...
4ba4810057bb936fdb5a94669796b0a260eeee49
3,657,529
def random_account_number(): """ Generate random encoded account number for testing """ _, account_number = create_account() return encode_verify_key(verify_key=account_number)
d662dc0acdc78f86baf2de998ab6ab920cc80ca0
3,657,530
def get_recommendation_summary_of_projects(project_ids, state, credentials): """Returns the summary of recommendations on all the given projects. Args: project_ids: List(str) project to which recommendation is needed. state: state of recommendations credentials: client credentials. """ recommen...
68cd42e4465bbdc85d88b82cb345b64a4ec1fec8
3,657,531
def selection_filter(file_path): """ 获得经过filter方法获得的特征子集 f_classif, chi2, mutual_info_classif """ df = pd.read_csv(file_path) delete_list = ['id'] df.drop(delete_list, axis=1, inplace=True) feature_attr = [i for i in df.columns if i not in ['label']] df.fillna(0, inplace=True) # ...
d6f6848c499f2d4899828e1e1bd0fb0ffe930186
3,657,532
def _process_voucher_data_for_order(cart): """Fetch, process and return voucher/discount data from cart.""" vouchers = Voucher.objects.active(date=date.today()).select_for_update() voucher = get_voucher_for_cart(cart, vouchers) if cart.voucher_code and not voucher: msg = pgettext( '...
ec15f13607cee7e4bdd2e16f9a44904638964d36
3,657,533
def is_insertion(ref, alt): """Is alt an insertion w.r.t. ref? Args: ref: A string of the reference allele. alt: A string of the alternative allele. Returns: True if alt is an insertion w.r.t. ref. """ return len(ref) < len(alt)
17d7d6b8dfdf387e6dd491a6f782e8c9bde22aff
3,657,534
from typing import Optional def identify_fast_board(switches: int, drivers: int) -> Optional[FastIOBoard]: """Instantiate and return a FAST board capable of accommodating the given number of switches and drivers.""" if switches > 32 or drivers > 16: return None if switches > 16: return Non...
27c0dca3e0421c9b74976a947eda5d6437598c01
3,657,535
import struct def encode_hop_data( short_channel_id: bytes, amt_to_forward: int, outgoing_cltv_value: int ) -> bytes: """Encode a legacy 'hop_data' payload to bytes https://github.com/lightningnetwork/lightning-rfc/blob/master/04-onion-routing.md#legacy-hop_data-payload-format :param short_channel_id...
51fda780036fdcbb8ff1d5cd77b422aaf92eb4fd
3,657,536
def extract_all_patterns(game_state, action, mask, span): """ Extracting the local forward model pattern for each cell of the grid's game-state and returning a numpy array :param prev_game_state: game-state at time t :param action: players action at time t :param game_state: resulting game-state at tim...
06e44c871a14b7685ca5dd165285cfe2c7076b85
3,657,537
def cond(*args, **kwargs): """Conditional computation to run on accelerators.""" return backend()['cond'](*args, **kwargs)
969307c62bd4a2eef6b16dffff953910524cc3c1
3,657,540
def singleton(cls): """Decorator that provides singleton functionality. >>> @singleton ... class Foo(object): ... pass ... >>> a = Foo() >>> b = Foo() >>> a is b True """ _inst = [None] def decorated(*args, **kwargs): if _inst[0] is None: _inst[...
4ae64aeaaba1b838232e4d7700d692dcc109be6d
3,657,542
import inspect def _with_factory(make_makers): """Return a decorator for test methods or classes. Args: make_makers (callable): Return an iterable over (name, maker) pairs, where maker (callable): Return a fixture (arbitrary object) given Factory as single argument """ de...
5841e80129b212bba2c6d0b1f89966fa0d5ce152
3,657,543
import time def timeItDeco(func): """ Decorator which times the given function. """ def timing(*args, **kwargs): """ This function will replace the original function. """ # Start the clock t1 = time.clock() # Run the original function and collect results result = fun...
9c59a512a9cf9eac190af4a88dbf8ccab2069f55
3,657,544
def apply_haste(self: Player, target: Player, rules: dict, left: bool) -> EffectReturn: """ Apply the effects of haste to the target: attack beats attack """ # "attack": {"beats": ["disrupt", "area", "attack"], "loses": ["block", "dodge"]} if left: # Remove attack from the attack: loses ...
0186fe8553cb89c73d9a3cfae35048cd465b9859
3,657,545
def get_mean_cube(datasets): """Get mean cube of a list of datasets. Parameters ---------- datasets : list of dict List of datasets (given as metadata :obj:`dict`). Returns ------- iris.cube.Cube Mean cube. """ cubes = iris.cube.CubeList() for dataset in datase...
492b5df11252beb691c62c58005ce2c3c1dcb3b8
3,657,546
async def gen_unique_chk_sum(phone, message, first_dial): """Generates a checksum in order to identify every single call""" return blake2b( bytes(phone, encoding="utf-8") + bytes(message, encoding="utf-8") + bytes(str(first_dial), encoding="utf-8"), digest_size=4, ).hexdigest...
c85076f4fd1e2814116ece59390bebb9f398a4f6
3,657,547
def getQtipResults(version, installer): """ Get QTIP results """ period = get_config('qtip.period') url_base = get_config('testapi.url') url = ("http://" + url_base + "?project=qtip" + "&installer=" + installer + "&version=" + version + "&period=" + str(period)) reques...
4ae01b33a2eed23a8d3ad7b7dd1d5a3bcc8d5ab8
3,657,548
def scaled_softplus(x, alpha, name=None): """Returns `alpha * ln(1 + exp(x / alpha))`, for scalar `alpha > 0`. This can be seen as a softplus applied to the scaled input, with the output appropriately scaled. As `alpha` tends to 0, `scaled_softplus(x, alpha)` tends to `relu(x)`. Note: the gradient for this ...
526c5169b1ac938e3f645e96dc7e65bb4acf64b5
3,657,549
def get_choice(options): """Devuelve como entero la opcion seleccionada para el input con mensaje message""" print(options) try: return int(input("Por favor, escoja una opción: ")) except ValueError: return 0
32e95e0113650d0b94449e5e31e7d8156ae85981
3,657,550
def _listminus(list1, list2): """ """ return [a for a in list1 if a not in list2]
3f05d8bfd4169d92bb51c4617536b54779b387c9
3,657,551
import pytesseract from pdf2image import convert_from_bytes def pdf_to_hocr(path, lang="fra+deu+ita+eng", config="--psm 4"): """Loads and transform a pdf into an hOCR file. Parameters ---------- path : str, required The pdf's path lang: str, optional (default="fra+deu+ita+eng") Su...
9619d45dc418f07634fd161f1dff50b4cf334e21
3,657,552
import httpx async def fetch_cart_response(cart_id: str) -> httpx.Response: """Fetches cart response.""" headers = await get_headers() async with httpx.AsyncClient(base_url=CART_BASE_URL) as client: response = await client.get( url=f'/{cart_id}', headers=headers, ) ...
2d2da772b257b43beda78f3b08c42c914c01f00d
3,657,553
def is_namespace_mutable(context, namespace): """Return True if the namespace is mutable in this context.""" if context.is_admin: return True if context.owner is None: return False return namespace.owner == context.owner
f5303e75b975a1ba51aa39c608ec5af339917446
3,657,555
def get_schularten_by_veranst_iq_id(veranst_iq_id): """ liefert die Liste der zu der Veranstaltung veranst_iq_id passenden Schularten """ query = session.query(Veranstaltung).add_entity(Schulart).join('rel_schulart') query = query.reset_joinpoint() query = query.filter_by(veranst_iq_id=veranst_iq_id) return q...
4c18b2fe73b17752ee2838815fa9fde8426a7ccb
3,657,556
def get_station_freqs(df, method='median'): """ apply to df after applying group_by_days and group_by_station """ #df['DATE'] = df.index.get_level_values('DATE') df['DAY'] = [d.dayofweek for d in df.index.get_level_values('DATE')] df['DAYNAME'] = [d.day_name() for d in df.index.get_level_values(...
aebc1a2486c48ff2d829fc70f1f2c4b38bd3017b
3,657,557
def faster_symbol_array(genome, symbol): """A faster calculation method for counting a symbol in genome. Args: genome (str): a DNA string as the search space. symbol (str): the single base to query in the search space. Returns: Dictionary, a dictionary, position-counts pairs of sym...
a1bbf70a211adcee14573534b62b4a4af5abdebd
3,657,558
def makeArg(segID: int, N, CA, C, O, geo: ArgGeo) -> Residue: """Creates an Arginie residue""" ##R-Group CA_CB_length = geo.CA_CB_length C_CA_CB_angle = geo.C_CA_CB_angle N_C_CA_CB_diangle = geo.N_C_CA_CB_diangle CB_CG_length = geo.CB_CG_length CA_CB_CG_angle = geo.CA_CB_CG_angle N_CA_C...
4539d48e37e7bacd637300136799b8f7b3dc635d
3,657,560
def shows_monthly_aggregate_score_heatmap(): """Monthly Aggregate Score Heatmap Graph""" database_connection.reconnect() all_scores = show_scores.retrieve_monthly_aggregate_scores(database_connection) if not all_scores: return render_template("shows/monthly-aggregate-score-heatmap/graph.html", ...
4bf26e21c7d76be96395fce43228ee0a80930e4e
3,657,562
import requests def run(string, entities): """Call a url to create a api in github""" # db = utils.db()['db'] # query = utils.db()['query'] # operations = utils.db()['operations'] # apikey = utils.config('api_key') # playlistid = utils.config('playlist_id') # https://developers.google.com/youtube/v3/docs/pla...
6a3a9899e8081c655e9a7eabc3e96f103a77a6bd
3,657,563
def gamma(surface_potential, temperature): """Calculate term from Gouy-Chapmann theory. Arguments: surface_potential: Electrostatic potential at the metal/solution boundary in Volts, e.g. 0.05 [V] temperature: Temperature of the solution in Kelvin, e.g. 300 [K] Returns: float """ product = sc.elementary_charg...
b8996f01bb221a5cd2f6c222d166a61f1759845f
3,657,564
def calculate_mask(maskimage, masks): """Extracts watershed seeds from data.""" dims = list(maskimage.slices2shape()) maskdata = np.ones(dims, dtype='bool') if masks: dataslices = utils.slices2dataslices(maskimage.slices) maskdata = utils.string_masks(masks, maskdata, dataslices) m...
4935cacb3689b844ab119ec3b24b9e59b7db7ec3
3,657,565
def Range(lo, hi, ctx = None): """Create the range regular expression over two sequences of length 1 >>> range = Range("a","z") >>> print(simplify(InRe("b", range))) True >>> print(simplify(InRe("bb", range))) False """ lo = _coerce_seq(lo, ctx) hi = _coerce_seq(hi, ctx) return R...
cb9cf3a334ba8509a54226c86c555257092a0951
3,657,566
import numpy def quantile(data, num_breaks): """ Calculate quantile breaks. Arguments: data -- Array of values to classify. num_breaks -- Number of breaks to perform. """ def scipy_mquantiles(a, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, limit=()): """ function copi...
24486e39fcefb9e6cf969067836d1793b9f4a7c8
3,657,567
def extract_conformers_from_rdkit_mol_object(mol_obj, conf_ids): """ Generate xyz lists for all the conformers in conf_ids :param mol_obj: Molecule object :param conf_ids: (list) list of conformer ids to convert to xyz :return: (list(list(cgbind.atoms.Atom))) """ conformers = [] for i i...
821977c0be57441b5146c9d5ef02a19320cf5b91
3,657,568
def create_embedding(name: str, env_spec: EnvSpec, *args, **kwargs) -> Embedding: """ Create an embedding to use with sbi. :param name: identifier of the embedding :param env_spec: environment specification :param args: positional arguments forwarded to the embedding's constructor :param kwargs...
70f4651f5815f008670de08805249d0b9dfc39e9
3,657,569
def _init_allreduce_operators(length, split_indices): """ initialize allreduce communication operators""" indices = split_indices[0] fusion = split_indices[1] op_list = () j = 0 for i in range(length): if j <= len(indices)-1: temp = indices[j] else: temp =...
91f752e049394b27340553830dce70074ef7ed81
3,657,570
def get_valid_fields(val: int, cs: dict) -> set: """ A value is valid if there's at least one field's interval which contains it. """ return { field for field, intervals in cs.items() if any(map(lambda i: i[0] <= val <= i[1], intervals)) }
3016e78637374eadf7d0e2029d060538fea86377
3,657,571
import glob import re def load_data_multiview(_path_features, _path_lables, coords, joints, cycles=3, test_size=0.1): """Generate multi-view train/test data from gait cycles. Args: _path_features (str): Path to gait sequence file _path_lables (str): Path to labels of corresponding gait sequen...
574ca69bf6a6637b4ca53de05f8e792844e134bb
3,657,572
def T_ncdm(omega_ncdm, m_ncdm): # RELICS ONLY? """Returns T_ncdm as a function of omega_ncdm, m_ncdm. ...
c3db4e4d2ac226f12afca3077bbc3436bd7a0459
3,657,573
import binascii def generate_initialisation_vector(): """Generates an initialisation vector for encryption.""" initialisation_vector = Random.new().read(AES.block_size) return (initialisation_vector, int(binascii.hexlify(initialisation_vector), 16))
4c05067d86cbf32de7f07b5d7483811c46307b64
3,657,575
def assign_score(relevant_set): """Assign score to each relevant element in descending order and return the score list.""" section = len(relevance[0])//3 score = [] s = 3 for i in range(3): if s == 1: num = len(relevance[0]) - len(score) score.extend([s]*num) ...
76a43780e1d1f37f7e0220ff0a0ca2ec484dd036
3,657,576