content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_conversion(scale, limits): """ Get the conversion equations for each axis. limits: dict of min and max values for the axes in the order blr. """ fb = float(scale) / float(limits['b'][1] - limits['b'][0]) fl = float(scale) / float(limits['l'][1] - limits['l'][0]) fr = float(scale) / ...
28f1699671456e321b355feb59f11d269208d4b2
626,829
import re def humanish(remote_url): """Get the humanish part of a remote git url equivalent of the following multiexpression sed search and replace: sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g' https://stackoverflow.com/questions/13839879/how-to-determine-the-humanish-part-of-a-git-repos...
bc12ee3b2a14dd4e5f3b6f9aeed5fab32f1ad804
626,830
def is_shared_to(video: dict) -> bool: """ Checks if a video was shared to an account. Returns True if it was shared to another account, False otherwise. """ shared = video.get('sharing') if shared and shared.get('to_external_acct'): return True return False
ba2a5799bfe32ee9d1ea67c238fe41cdbf550778
626,832
def UDLD_x(x, p): """ x = np.pi*B_m*theta_rad/lambda_m p = {'A0':..., 'Ap':..., 'p':...} """ return p['A0'] - (p['Ap']*x)**[p['p']]
d33b5747a022c99be0465ea1aced58997535e755
626,834
def input_data_task_id(conf): # type: (dict) -> str """Retrieve input data task id :param dict conf: configuration object :rtype: str :return: task id """ return conf['task_id']
da0dc2cc199d39369d160beecc403b772e0ed17c
626,835
from typing import Any from typing import List def listify(collection: Any) -> List: """ Takes a given collection and returns a list of the elements, handling strings correctly Parameters ---------- collection: tuple, set, str Any type of collection or string Returns ------- ...
c17c852a6b2a767a2009a2535fc5bfd53ce3b87f
626,836
import time def timeit_repeat(fct, number, repeat): """ Returns a series of *repeat* time measures for *number* executions of *code* assuming *fct* is a function. """ res = [] for r in range(0, repeat): t1 = time.perf_counter() for i in range(0, number): fct() ...
c8a291908c0f52bb31d9a271b6efe34e1f242b21
626,837
def normalize_strides( strides ): """Normalize strides of the same format. Args: strides: An integer or pair of integers. Returns: A pair of integers. Raises: ValueError: Input strides is neither an integer nor a pair of integers. """ if isinstance(strides, (list, tuple)) and len(strides)...
447bd01f69fc0a0044741e3d28f6b6d298067459
626,839
def requires_grid(func): """Solves the puzzle before returning""" def wrapped(self, *args, **kwargs): if self.grid is None: self.init_grid() return func(self, *args, **kwargs) return wrapped
21793daff61fd8c74bb26dc03db36549ec8ac999
626,841
def realign_shifted_streams(tokens, durations, F0s, shifts): """ Durations are shifted by 1, F0 by 2 >>> tokens = ["<s>", "t1", "t2", "t3", "</s>", "x", "x"] >>> durations = ["<0>", "<0>", "d1", "d2", "d3", "<0>", "x"] >>> F0s = ["<0>", "<0>", "<0>", "f1", "f2", "f3", "<0>"] >>> shifts = [1,...
e29675e36fd68a16c46f351874ef4002ffde81d4
626,843
def create_nested_item(dictionary, *keys): """Create an empty item with specific keys and positions in a dictionary. The dictionary can be a nested dictionary containing lists, these lists can also contain nested dictionaries, and so on. The keys list can contain string (which refer dictionary keys) an...
707d6605f6d7990ff8ac7067e7024f0ab3b79ab1
626,844
def ssv(words): """Convert a words list into space separated values""" line = "" for w in words: if len(line) != 0: line += ' ' line += w return line
fa852de3005140a1cfc8d4379fb0c202718e9a3d
626,845
def get_region_filename(region, subregion): """Returns the filename needed to download/manage PBF files. Parameters ---------------------- region : str subregion : str Returns ---------------------- filename : str """ base_name = '{}-latest.osm.pbf' if subregion is None: ...
a55c42aa2a5ac572ad06748e4104d54966250dcb
626,846
from typing import Dict from typing import Any def is_aromatic(n: str, d: Dict[str, Any]) -> bool: """Adds indicator of aromaticity of the atom to the node data. :param n: Node name, this is unused and only included for compatibility with the other functions. :type n: str :param d: Node data :typ...
005d65ec07233379df4ebd5546ebeb7df8c052b7
626,847
from typing import OrderedDict def get_data_types(data): """ returns a dictionary with column names and their respective data types :param pandas.DataFrame data: a dataframe :rtype: dict[str,str] """ dtypes = data.dtypes return OrderedDict(zip(dtypes.index, dtypes.astype(str)))
5dcaf1ca6fde0d1011210e60913ee7052dfb58d4
626,848
def getValue (segment, tagName): """ get an xml element text value """ try: value = segment.find(tagName).text.strip() except: value = '' else: if len(value) == 0: value = '' return value
cc732765041380626a38687492c5b6fac1599f49
626,849
import math def dist_to_resol(distance, pixel_size, detector_size, wavelength, two_theta=0): """Convert from distance in mm to resolution in angstroms. Arguments: pixel_size -- pixel size of detector detector_size -- width of detector distance -- detector distance energy -...
e628af1566a25b904cb08c0150256ab2eb26c51b
626,850
def _bool_to_str(val): """ Convert Python bool to string 'true' or 'false'. Note we cannot use the standard conversion to str, as Python uses 'True' and 'False', whereas C++ uses 'true' and 'false'. """ return 'true' if val else 'false'
b4c8ff69f6be5bac17ddd4735d44e823bf748e99
626,851
from pathlib import Path def config_path(): """Path to the configuration file.""" path = Path('~') / '.mtscomp' path = path.expanduser() return path
a48e912a3f93f5ce5c2f45a9d094cffcc53dbd98
626,852
def check_same_vertex(v_target: list, v_searchers: list): """Check if the searchers and target are in different initial vertices""" common_el = set(v_target) - (set(v_target) - set(v_searchers)) if len(common_el) > 0: print("searchers can't be in same vertex as target at t = 0") return False...
1eb65f5e20641cffb866135a3d9d3480376017c8
626,853
import os import pwd def authenticate(): """Check the system user list for authorized users.""" allowed = [] if os.access("/etc/slam/users", os.R_OK): accessf = open("/etc/slam/users") allowed = accessf.read().split("\n") accessf.close() if not allowed: allowed = ["root...
3a4c924d134d494fa9f2aa9c21d2cfab8f36baef
626,854
import csv def read_tsv(csvfn): """ Read in the table of terms. Each row defines the column in the template file """ rows = [] col_names = [] with open(csvfn) as csvfile: data = csv.DictReader(csvfile, delimiter='\t') for row in data: rows.append(row) ...
1898dbad9ffe02115c3a80b6fe89ceaa22a6a73b
626,855
def expected_table(): """Return dynamodb table name fixture.""" return "test-certbot-ventilator-certificates"
32ed9b50ff53cd0f7d4fbbbc51ce859cc35d79a7
626,856
import warnings def link(endpoint=None, is_for_list=False, **kwargs): """ Used to mark a method on a ViewSet that should be routed for GET requests. """ msg = 'link is pending deprecation. Use detail_route instead.' warnings.warn(msg, PendingDeprecationWarning, stacklevel=2) def decorator(fun...
48aed282bf9be468ae598562c57cf7ce0af159af
626,857
import time def timestamp2date(timestamp): """ 时间戳转换为日期 Parameters ---------- timestamp: int or str 用户账号 Returns ------- datetime: 转换好的日期:年-月-日 时:分:秒 """ time_array = time.localtime(int(timestamp)) datetime = time.strftime("%Y-%m-%d %H:%M:%S", time_array) ...
72c6465ba5886e32a778dac3f83ea057d645cf7c
626,858
import subprocess def java_version(): """Show Java version Returns: str: Result of ``java -version`` """ try: res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT) res = res.decode() except FileNotFoundError: res = ( "`java -ve...
d3bfb7a38c1714626b050bae28e2fd78420e0ec4
626,859
def __data_to_string(write_data): """ Converts data array to string.""" return "".join(["{:08b}".format(data) for data in write_data])
04e697701494da6541193d059ce620551959a059
626,861
import difflib def check_spelling(data, words): """This function taks a city name and check for the closest match in a list of words.""" jsn = {} id_manager = [] for i in difflib.get_close_matches(words.lower(), list(data.keys()), n=15): if list(data[i].values())[0]['ID'] not in id_manager: ...
ffb733c7d91e6d3f7a0b6ae53ebfc27c2c61b5ef
626,862
import json def get_warn_file(guild_id: int, user_id: int): """ Returns the JSON data of the user's warn file. Or the legacy "get_warns()", now that I think about it. """ try: with open(f"data/servers/{guild_id}/warns/{user_id}.json", 'r', newline="\n", encoding='utf-8') ...
7ba1daff6fc454d23eb10cb344c00f3393b88c41
626,863
import itertools def generate_dictionary(input): """ """ # import libraries # function dictionary = input.split() dictionary = dict(itertools.zip_longest(*[iter(dictionary)] * 2, fillvalue="")) return dictionary
7b8478d15e71e8f936f0bb4550ab192202afcbc8
626,864
import subprocess def lsattr(path): """ NB. Difficult to replace with in-Python version. See <https://stackoverflow.com/questions/35501249/python-get-linux-file-immutable-attribute/38092961#38092961> """ try: output = subprocess.check_output( ['lsattr', '-d', path], shell=Fals...
62900ff79a080210f20c59ab15a3e4c6789256a8
626,865
import codecs def open_enc(fn, utf16): """ Open a file for reading with either the standard built-in open() or the open in the codecs module for reading UTF-16 encoded files. :param fn: Name of the file to open :param utf16: Boolean flag to specify a UTF-16 file """ if utf16: retu...
3b0bf61e16a3cb5c46bc47fdcae761cce13940d1
626,866
def get_order_from_file(pixtable_fname): """Find the polynomial degree used when creating the pixel table""" order_wl = 4 found = False with open(pixtable_fname) as tab_file: while True: line = tab_file.readline() if line[0] != '#': # Reached the end of th...
4d4035be82840b5b2ab791ffaad6e54d1e0cb527
626,867
from pathlib import Path def account_exists(account_id='jodel_account'): """Checks whether an account has already been created.""" if Path('./' + account_id + '.pkl').is_file(): return True else: return False
d5163967d6af2809204f2dce7d8bd3cc492219e9
626,868
def replace_sublist(li, target, replacement): """ Replace a sublist with another sublist. Not very effcient. If 'eq' is given, this will be used to compare items. """ result = [] i = 0 while i < len(li): if li[i : i + len(target)] == target: i += len(target) result.extend(replacement) ...
13196261d469625e0e50b12ba24e036fe6a1de02
626,869
def array_qtys_to_strs(lst): """Convert Pint quantities in a NumPy array to strings. Args: - ``lst (numpy.ndarray Quantity)``: a list of values that has a Pint unit attached to it """ return [str(value) for value in lst]
70afb1a5fd8970ce13973dc679b6d7c1edffae9b
626,870
import zlib def crc32File(filename, skip=0): """Computes the CRC-32 of the contents of filename, optionally skipping a certain number of bytes at the beginning of the file. """ with open(filename, 'rb') as stream: discard = stream.read(skip) return zlib.crc32(stream.read()) & 0xfffffff...
f591971106b4b54376e8bc971c12bb2fd2040fda
626,872
def float_input(label, name=None, multiline=False, hint="", extra="", input_type="text", input_mask=None): """ hint is a paragraph explaining what could be put in, or limitations to inputs. Possibly should be made visible on focus extra is string that will be added to the attributes area of the input, usefu...
1d058a0017b5db031b25a18ae1648da6d0728f64
626,875
def sanitize_package_name(name): """ Sanitize package name Args: name (str): package name. Returns: str: sanitized package name. """ return name.replace("+", "plus").strip(" ")
02d94441d77343e3e7ce5c676a091c191152c22e
626,876
def json_get(item, path, default=None): """ Return the path of the field in a dict. Arguments: item (dict): The object where we want to put a field. path (unicode): The path separated with dots to the field. default: default value if path not found. Return: The value. ...
0860fe65e5a6802d3f623c5bbea1543d2a98b0ec
626,877
import os import gzip def read_cell_barcode_tag_file(infile): """ Read in table of cell barcodes and associated group Note that each cell barcode can be in multiple groups Returns a dictionary where the cell barcode is the key, value is a list of tuples. Each tuple in the list is the read ta...
1a519c3bcaeaaf3a02ebb8afc1c58df05cf49ef9
626,878
from typing import List def common_words(sentence1: List[str], sentence2: List[str]) -> List[str]: """ Input: Two sentences - each is a list of words in case insensitive ways. Output: those common words appearing in both sentences. Capital and lowercase words are treated as the same word. ...
0002b28f2b4722c7554487db737327e333fbde54
626,879
def gene_size_dict(tab_sep_file): """select accn, group_concat(qdiff) from rice_b_setaria64_gturco_2011_4_11app_real group by accn""" handle = open(tab_sep_file) fh = handle.read() gene_size_dict = {} for line in fh.split("\n")[:-1]: gene, cnss = line.split("\t") gene_size_dict[g...
a80efb271bccda1cc02360d811845e6fe6728e6c
626,880
def format_text(text: str, trade_data: dict): """Formats different keywords for text stitching """ item_filter = ["item2", "item3", "item4"] var_filter = ["id", "serialNumber", "assetId", "name", "originalPrice", "assetStock"] for side in ("give", "take"): for item in trade_data[side]['items...
3e5c864521c3c8b5f73501ef560767f3f4140921
626,881
def lng180(lng): """Returns a longitude in degrees between {-180, 180] given a longitude in degrees.""" newlng = float(lng) if lng <= -180: return lng + 360 if newlng > 180: return lng - 360 return lng
7ca14cc485cdb7c56b622ab38398c0e559ce4532
626,882
def v1_group_by(iterable, key_func): """Group iterable by key_func. We could also use the get method to both get the list or default the list to an empty list and then assign back to the same key, That's a bit messy though. There's not really an elegant way to refactor that to one line while still...
73406f81e6f16732203dff03a3171e992b2065fa
626,883
import math def _get_tissue_subparts_coords(subtissue, patch_size, min_decimal_keep): """Inputs a tissue part resulting from '_get_tissue_parts_indices'. This tissue part is divided into N subparts and returned. Argument min_decimal_keep basically decides if we should reduce the N subparts to N-1 subp...
3197e39e3a3b61d10473b86c3d9ec785f51709d6
626,884
from typing import List from typing import Dict from typing import Any def prepare_target_for_drive_activity(targets_list: List) -> str: """ :param targets_list: Target entity in context data. :return: Prepared markdown string. """ targets_data: str = '' for target in targets_list: d...
2b336f2c91baae3010334ccea8cbb00c15f11c72
626,885
from datetime import datetime def _calc_elapsed(start, fmt=True): """Returns hours, minutes, seconds; formats to {H}h, {m} min., {s}s if fmt""" elapsed = datetime.now() - start hours, remainder = divmod(elapsed.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) if fmt: ...
4a80656b6d71d2c7ed22fb80504f8a076ef43bdd
626,886
import argparse def subcommand_parser(): """ Necessary for handling -h in, e.g., ho probe aws -h """ parser = argparse.ArgumentParser( parents=[], conflict_handler='resolve', ) return parser
976b17ff14b814d15abc330d9d02702959c6b962
626,887
def divide_by(value, arg): """ Returns the result of the division of value with arg. """ result = 0 try: result = value / arg except: # error in division pass return result
f1ff4eee6f6392c9bb9ec8b3fd4fe5ec295c048f
626,888
def paramter_group(network, weight_decay, no_weight_decay_filter, gc_flag): """paramter_group""" filter_len = len(no_weight_decay_filter) if filter_len > 0: decayed_params = [] no_decayed_params = [] for param in network.trainable_params(): if all([key not in param.name f...
42f939b4caf6cf0c3fb1b4581eb6833769cf59bf
626,889
def dropout_mask(x, sz, dropout): """ Applies a dropout mask whose size is determined by passed argument 'sz'. Args: x (nn.Variable): A torch Variable object sz (tuple(int, int, int)): The expected size of the new tensor dropout (float): The dropout fraction to apply This method use...
6c1b721dd8e4721a4159de8b56ef753ea65962db
626,890
def select_sort(items): """ 选择排序, 搜索整个列表,找到最小项位置 """ for i in range(len(items)-1): min_index = i for j in range(i+1, len(items)): if items[j] < items[min_index]: min_index = j if min_index != i: items[min_index], items[i] = items[i], items...
187668ed95a42b153122b436ca9a2ff7419ee59e
626,891
import glob def seslist(sub): """ list session for given partcipant """ seslist=glob.glob('{}/ses-*'.format(sub)) return seslist
911a4404e919990a52da589a13a39872174113b0
626,892
import torch def sample_logits(embedding, bias, labels, inputs, sampler): """ embedding: an nn.Embedding layer bias: [n_vocab] labels: [b1, b2] inputs: [b1, b2, n_emb] sampler: you may use a LogUniformSampler Return logits: [b1, b2, 1 + n_sample] """ tru...
547f871ef487ed7f2051d315fb7dda695628df49
626,893
def generate_seeds(): """generate some dummy values for initial feature testing and unit tests""" values = {} values["name1"] = "Bilbo Baggins" values["name2"] = "Frodo Baggins" values["name3"] = "Gollum" values["pic1"] = "http://37.media.tumblr.com/9b1dd3fca479e767b605c308ece10461/tumblr_n067vr...
8444bd367dfe05becab02e7859269db6f11bac5a
626,894
def is_empty_input(input_messages): """Check if input is empty""" if not input_messages: return True return False
e30b0994188d604d6c4a602ce80a28f1c70616c4
626,896
import torch def nms(boxes, scores, overlap=0.7): """Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. Args: scores: (N) FloatTensor boxes: (N, 4) FloatTensor overlap: (float) The overlap thresh for suppressing unn...
91ad89a607d52b5a51398b882c9e83bf5cccea73
626,897
import inspect def is_generator(obj): """ Return True if ``obj`` is a generator """ return inspect.isgeneratorfunction(obj) or inspect.isgenerator(obj)
c0b7f570351d2af9d3e70bdb0eff73245a9c599b
626,898
def arr_to_dict(arr, keys): """Array back to dictionary.""" assert len(arr) == len(keys) return {x: y for x, y in zip(sorted(keys), arr)}
ba6f83753e72be97e856c86e71c283b6342505c5
626,899
def calculBMI(w, h): """ (float, float) -> float Retourne l'indice de masse corporelle avec le poids et la hauteur Restrictions: w, h >= 0 """ return w / (h * h)
005ce1972cf22e71cae296edacd0ac502d6131e2
626,901
def calc_zcr(frame): """ # Calculate Zero Crossing Rate Args: frame (numpy.ndarray): piece of audio list. Returns: int: number of zero crossing rate """ i = 1 aux = 0 while i < len(frame): aux += 1 if (frame[i-1] * frame[i]) < 0 else 0 i += 1 return aux
a869e7d7eb858b29da82007462c8783997e678ef
626,902
def _check_rows(rows, check, in_range=True, return_test="any"): """Check all rows to be in/out of a certain range and provide testing on return values based on provided conditions Parameters ---------- rows : pd.DataFrame data rows check : dict dictionary with possible values of...
0abc767d9da1cdba469d171244259bae13b64e61
626,903
import codecs def decode_text_part(part): """Extract the payload from a text/plain mime part as a unicode string""" txt = part.get_payload(decode=True) charset = part.get_content_charset('latin1') # Make sure the charset is supported and fallback to 'ascii' if not try: codecs.lookup(charse...
a8a6ebf795eec0acef9d6d73b0d3491b9e418dbf
626,904
def calcite(piezometer=None): """ Data base for calcite piezometers. It returns the material parameter, the exponent parameter and a warn with the "average" grain size measure to be use. Parameter --------- piezometer : string or None the piezometric relation References ---------- ...
7c96972d8a71118fd3262c2f7cc0d5d741e6f014
626,905
import argparse def parse_args(): """ Parse arguments from command line input """ parser = argparse.ArgumentParser(description='Receiver parameters') parser.add_argument('--continuous', type=bool, default=True, help='Decide if receiver should listen continuously.', ...
bf83903ddf187a041f1f47c25de533efc89a49a9
626,906
def lstDiffSingle(a, b): """Intelligently find difference in 2 lsts Parameters: ----------- a : np.float32, float first lst in hours b : np.float32, float second lst in hours Returns: -------- diff: float the absolute difference Comments: --------- ...
84507c5d95962ce55eb84c3cc3a89c212e1ac34d
626,907
import re def _without_nbt_style(s: str) -> str: """ Given a full string with NBT styling, return the string without coloring and recomb symbols. :param s: The given string. :return: The given string without NBT styling. """ return re.sub('§ka|§.', '', s).strip()
bc6a5c24847f43038bcf7b8de84da4330df4b0eb
626,908
import random def randbytes(length: int) -> bytes: """ Generate a random bytes object. :param length: Length of the random bytes object. :return: Random bytes object. """ return bytes(random.getrandbits(8) for _ in range(length))
928f60010dc294dfdd030e5a8c9796f05f4ba1d7
626,909
def row2dict(row): """Map a single row of an sqlalchemy declarative class query to a dictionary. NOTE: maps everything to string. Does not account for types """ dict_ = {} for column in row.__table__.columns: dict_[column.name] = getattr(row, column.name) return dict_
8d3edef4fd753ba83eb31ca55a8a965bee035ced
626,910
import math def nuclear_repulsion_energy(efpobj, use_efp_frags=True, use_point_charges=False): """Computes nuclear repulsion energy for `efpobj`. Parameters ---------- use_efp_frags : bool, optional If True (default), compute NRE using the efp fragment subsystem. use_point_charges : bool,...
54b1ae50e3c29b4dc632f915891b028d23b8ddb6
626,912
def MoveStr2List(mv: str) -> list: """ param: mv: str [x_src, y_src, x_dst, y_dst] return: mv_list: List-> [int: x_src, y_src, x_dst, y_dst] """ mv_list = [] if mv != " ": mv_list = list(map(int, mv[1:-1].split(","))) return mv_list
dedb0d2b044c5e1dd990d76fbf4986661408ebf2
626,913
import json def get_client_id(): """ Requires a file "client_id.json" with the following content: {"client_id": "12493b54-c073-4c44-7a41-633a3569f636"} :return: """ with open("client_id.json") as file: _id = json.load(file) return _id["client_id"]
88d8a017ce5468f88f2bdc2920e0c35932e41d4c
626,914
def get_initial_data(event): """ Processing event to fill in form data """ initial = event.__dict__ initial['tags'] = event.get_tags() initial['audience'] = event.get_audience_array() initial['theme'] = event.get_theme_array() return initial
8c63545cb199c61e3898ca55172a32e59fcaaf37
626,915
from pathlib import Path def sorted_glob(p: Path, pattern="*"): """ return sorted filenames for matched files. """ names = [x.name for x in p.glob(pattern)] names.sort() return names
4b36944a8cd2097eb1bdc26164c6194e058c7e87
626,916
def yes_no_interactive(): """ Prompt user for a yes/no confirmation and repeat until valid answer is received. """ while True: confirm = input("Confirm? (y/n): ") if confirm.upper() == "Y": return True if confirm.upper() == "N": return False print(...
703ab9ea03f88012ea05e251980745ac4cfe722e
626,917
import torch def generate_linear_data(n=1000): """ Generates an example dataset that can be seperated linearly Output: inputs : nx2 dimension FloatTensor targets : nx1 dimension LongTensor with range [0,1] """ torch.manual_seed(123) inputs = torch.rand(n,2) targets = torch.s...
c3cc6167afc75b848f5e9c416609daf3854a0ff5
626,918
def check_market_name(market, exchange='bittrex'): """ Avoids abbreviations and lower cases failures. """ market = market.upper() if exchange == 'bittrex': if '-' in market: # and len(market) > 5: return market return 'BTC-' + market elif exchange == 'binance': ...
676cd71bf8e7dbd6d6d0ca13dbeedc16f33055ed
626,919
def nonstandard(cls): """ Testcase decorator that marks the test as being non-standard. These tests are not automatically added to the "standard" group. """ cls._nonstandard = True return cls
e444b636cc182cee2720bb2c301b23c25e2f5ed9
626,920
import random def train_test_split(filelist, p=0.85, seed=17): """Return train and test set of filenames This function follows `define_train_list` and uses its output """ random.seed(seed) train_list, test_list = dict(), dict() for utterance, files in filelist.items(): gt_filepath, filenames = files[...
b15425268a67b8e5fc07e565cbfa3f5af2f541ad
626,922
def controller_get_pm_trend(): # noqa: E501 """Returns the PM2.5 trend # noqa: E501 :rtype: List[PmTrend] """ return 'do some magic!'
784d4080d893001d7c656780c2e09e6ade0f2944
626,923
import numpy def cumulative_prob(vals, max_val): """ Compute cumulative probability. Given a list of SWW scores in region ``vals``, return list ``freqs_cum`` where probability that randomly picked value in `vals` is equal or greater than i equals freqs_cum[i]. Max_val is the largest possible...
bce31ce9b6401949df1b9b65ff58af479dd9fdd1
626,925
import torch def quadratic_bezier(params: torch.Tensor, t: torch.Tensor) -> torch.Tensor: """Evaluate a batch of quadratic bezier curves at different points. Args: params: torch.Tensor of size [batch, 3, D]. Each batch item is interpreted as four points corresponding to the start point, the fir...
890e888d71695a539c51cc704302cc42f699c56c
626,926
def SET_IS_SUBSET(*expressions): """ Takes two arrays and returns true when the first array is a subset of the second, including when the first array equals the second array, and false otherwise. https://docs.mongodb.com/manual/reference/operator/aggregation/setIsSubset/ for more details :param ...
5bd37dcf44a8ca413fc4bd8da7211a35c9dd1ef6
626,927
def OR_AND_product_fuzzy(Z_n, U_d): """ Compute probability of emitting a zero for fuzzy vectors under OR-AND logic. """ out = 1 for l in range(Z_n.shape[0]): out *= 1 - Z_n[l] * U_d[l] return 1 - out
adfa85c81589566664b658dd6b5ac2cdef4294db
626,928
def get_log_params(prog: str, cfg: dict, def_logfile: str) -> tuple: """Get the log file, level and size for the given program from config The logfile is supposed to be defined by a variable called logfile within the hierarchy of the config dictionary. Thus, the poller log file will be {'poller': {'log...
893740ac086bd0eaede6eaa649646379f7b234bb
626,929
def function(): """subpackage.module2.function""" return "subpackage.module2.function"
26a27dcd2200d0629ee1e8f31f14132d38da928a
626,930
import re def compress(self, chars): """ :type chars: List[str] :rtype: int """ chars[:] = re.sub(r'(?<=(.))\1+', lambda m: str(1 + len(m.group())), ''.join(chars)) return len(chars)
206f0d2cfcec84aed04f39efbb469b237cea0f52
626,931
def has_view_restrictions(page): """Returns True if the page has view restrictions set up, False otherwise.""" return page.view_restrictions.count() > 0
97780a4091c1461bdbeabb04f2fd8cd5a28b18ae
626,932
def swizzled_bundleIdentifier(self, original): """ Swizzle [NSBundle bundleIdentifier] to make NSUserNotifications work. To post NSUserNotifications OS X requires the binary to be packaged as an application bundle. To circumvent this restriction, we modify `bundleIdentifier` to return a fake bundle...
5980da2e1b781ef98e6ca68e105cf6d46f8f97a0
626,933
def kl_vb_bmc(vb,nsamples): """ Deprecated. Use vb.kullback_proposal_bmc """ return vb.kullback_proposal_bmc(nsamples)
66340ec33ad4de71e09ff27c2aea31e6b1e2dbb4
626,934
def drop_prefix(s, pattern): """ Remove prefix pattern of a string. :param s: string :param pattern: string pattern """ if s.startswith(pattern): return s[len(pattern):] return s
ea8ceb13089eb907f550174d82118e1e9c32bddf
626,935
def getAPNTopicFromX509(x509): """ Given an L{X509} certificate, extract the UID value portion of the subject, which in this context is used for the associated APN topic. @param x509: the certificate @type x509: L{X509} @return: C{str} topic, or empty string if value is not found """ s...
ad6b6922727c73aea7240a931bc2ed783a649680
626,936
def dec2hp(dec): """ Converts Decimal Degrees to HP Notation (float) :param dec: Decimal Degrees :type dec: float :return: HP Notation (DDD.MMSSSS) :rtype: float """ minute, second = divmod(abs(dec) * 3600, 60) degree, minute = divmod(minute, 60) hp = degree + (minute / 100) + (s...
f081e69c2bede5143a769729f1eb8df9aa3bf8c7
626,937
import os def is_json(filename): """ Check if file is a json file (look if the extension is .json) """ extension = os.path.splitext(filename)[1] return extension == '.json'
2cae260b6039e5f6906e69881f2b6d95a36b0d66
626,938
def mean_normalization(x): """ This script is to do mean normalization for DataFrame Parameter: x: format: DataFrame rows:feature columns:samples Returns: output:DataFrame; after mean normalization. rows:feature columns:samples """ for ...
15905088d458c7a9b0e19b1f1d558fb2541b18dc
626,939
def _validate_value(attribute_id, value, datatype=None): """It accepts an optional datatype to validate the values. The values are not necessarily be an instance of this datatype. They will be checked for a common super-class. The function returns the found super-class, so that callers can save and r...
d5aec108430c5a663c6de9c416a4afd4b77d2e86
626,940
import numpy def logsumexp(arr,axis=0): """Faster logsumexp?""" minarr= numpy.amax(arr,axis=axis) if axis == 1: minarr= numpy.reshape(minarr,(arr.shape[0],1)) if axis == 0: minminarr= numpy.tile(minarr,(arr.shape[0],1)) elif axis == 1: minminarr= numpy.tile(minarr,(1,arr.sh...
49523a54db70267a76822dceac2eb33bfcd254e3
626,941
def gcd_single(a, b): """ Returns the greatest common divisor of the integers `a` and `b` using Euclid's Algorithm [1]_. Parameters ---------- a, b : int The two integers to calculate the greatest common divisor for. Returns ------- gcd : int Greatest common divisor...
557eeadca50d2f1bf0c78a84f2c6104e080810a5
626,942