content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def merge_partial_elements(element_list): """ Merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list: list List of all the elements. Returns ------- list: List of merged elem...
10c38fd6edea81f8f1eb54ba209f80cba4a56f62
590,991
def make_joint(withdraw, old_password, new_password): """Return a password-protected withdraw function that has joint access to the balance of withdraw. >>> w = make_withdraw(100, 'hax0r') >>> w(25, 'hax0r') 75 >>> make_joint(w, 'my', 'secret') 'Incorrect password' >>> j = make_joint(w,...
85aa05c509c8ff9143b892a462255201ffff59a9
590,995
from typing import List def gamess_hessian_list() -> List: """Return an array of GAMESS methods with Hessians. Appended to procedures['hessian']. """ val = [] val.append("gms-hf") val.append("gms-scf") val.append("gms-mp2") # fd val.append("gms-ccd") # fd val.append("gms-ccsd") ...
2bf4a588482b6d301cbc1e8f15b018861042b09e
590,998
import math def logmgf_exact(q, priv_eps, l): """Computes the logmgf value given q and privacy eps. The bound used is the min of three terms. The first term is from https://arxiv.org/pdf/1605.02065.pdf. The second term is based on the fact that when event has probability (1-q) for q close to zero, q can on...
1ec43453a24eaf43c891163a63eea98f0dedf045
591,002
from typing import Dict from typing import List import re def _split_words_in_western_languages( text: str, regex_dictionary_terms: Dict[str, str]) -> List[str]: """Splits western text into words. If a group of words in the text match a regex in the regex_dictionary_terms they will be added as one string t...
c34683a1565da4baecc3b98c5e927b5b06000c48
591,003
from typing import Dict def is_function_signature(jsdoc_output: Dict) -> bool: """ Checks to see if the passed jsdoc output is a function signature :param jsdoc_output: the output of the jsdoc tool :return: True, if output is a function signature, False otherwise """ return jsdoc_output is not...
06474ea359dd9eee38be73cc3707400609f189db
591,004
from typing import List def get_labels(clusters: List[List[List]]) -> List[int]: """Get the label of each cluster. Args: clusters: A list of clusters. Returns: A list of labels. """ labels = [] for i, cluster in enumerate(clusters): labels.extend([i for _ in range(len...
32a56b41ed4c6db595f0264e2ae79d12233b52f6
591,005
def buildTriggerIDToEventIDIndex(trigger_dict, event_dict): """ Build dict from trigger ID to Event ID from datastructures.datatypes.Event class """ index = {} for event_id, event in event_dict.items(): trigger_id = event.arguments[event.name] if trigger_id not in index: index[tr...
9164770dd060a8e2d7d40fb18d33f1a0903b199a
591,010
def is_ipv4_addr(host): """is_ipv4_addr returns true if host is a valid IPv4 address in dotted quad notation. """ try: d1, d2, d3, d4 = map(int, host.split('.')) except (ValueError, AttributeError): return False if 0 <= d1 <= 255 and 0 <= d2 <= 255 and 0 <= d3 <= 255 and 0 <= d4...
87945f56d039a5fa4fa75bb0b428bf1f381d1322
591,012
def get_chunk_data_coords(nbt_file): """ Gets the coords stored in the NBT structure of the chunk. Takes an nbt obj and returns the coords as integers. Don't confuse with get_global_chunk_coords! """ level = nbt_file.__getitem__('Level') coordX = level.__getitem__('xPos').v...
4da2c1906269b2c7b4395e68cda72126aea549ef
591,013
def not_success(status): """ Whether the GitHub status is not a success. :param dict status: a GitHub API status. :return bool: whether the status isn't a success """ return status['state'] != u'success'
d103bad03a680980fd154b49a33e1f73489a998a
591,015
import six def byte_to_char(bin_input): """ Given byte as string or int, return character >>> byte_to_char("0010010") '2' >>> byte_to_char(100) 'd' """ if isinstance(bin_input, six.string_types): return chr(int(bin_input, base=2)) else: return chr(bin_input)
686f28ce95aee1ecb409afecb7dca4d890a4d45c
591,016
def _SheriffIsFound(sheriff_key): """Checks whether the sheriff can be found for the current user.""" try: sheriff_entity = sheriff_key.get() except AssertionError: # This assertion is raised in InternalOnlyModel._post_get_hook, # and indicates an internal-only Sheriff but an external user. return...
51f7a5d09d55f1f4a75aeaeedccb9dbcf3bbcdf4
591,017
def split_long_selectors(css: str) -> str: """Split too large CSS Selectors chained with commas if > 80 chars.""" result = "" for line in css.splitlines(): cond_1 = len(line) > 80 and "," in line and line.strip().endswith("{") cond_2 = line.startswith(("*", ".", "#")) if cond_1 and c...
b723324f01a87b9ff3eeae1d111fd5cf30760aec
591,025
def get_location(bucket_name, s3_client): """ Returns the bucket location. :param bucket_name: Name of the bucket. :param s3_client: s3_client instance. :return: String with bucket's region. """ loc = s3_client.get_bucket_location( Bucket=bucket_name)["LocationConstraint"] if loc is None: ...
31f6e325b67a32857a2c060401fe92179e022fd3
591,028
import re def arr2str(array): """Converts an array into a one line string Arguments: array {array} -- Array to convert Returns: str -- The string representation """ return re.sub(r'\s+', ' ', str(array).replace('\r', '').replace('\n', '').replace( ...
7c75944a44f67b68b72907bc963122cf182f1fbe
591,029
def v2s(val): """Turn possibly missing value into string""" return val if val is not None else '-'
b295aa954c7cf86fa0ba7c46656bd1e1b958f7dd
591,032
def read_taxid_list(filename, _dict=None): """ Read a taxID list file. A taxID list file consists of three tab separated columns: 1. ID type, 2. ID of sequence, 3. NCBI taxonomy ID for the sequence. It is headed by one line starting with the '#' char. Parameters ---------- filename : str ...
1c9748985de32f9be8866c122a80890adec21063
591,038
def getAddressClass(binaryString): """ This will calculate the address class of the IP address based on bits of binary string A: 0... B: 10.. C: 110. D: 1110 E: 1111 """ # initialize variable addressClass="" # troubleshooting # print(binaryString) # determine the address class if binaryStri...
688eb01345c569c213e11a2a5dc3f962fba7405f
591,040
def calc_sub_total(sales, goods_name): """ 统计指定商品的销售额 :param sales: 销售记录列表 :param goods_name: 要统计的商品名 :return: 指定商品的销售额 """ total = 0 for s in sales: if s.name == goods_name: amount = s.price * s.quantity total += amount return total
3fb7e2a529aead16005a9915b88423115eeb53cd
591,042
def threshold(data): """ Threshold: measure of how scattered the sign is (deviation). Parameters ---------- data: array-like 2D matrix of shape (time, data) Returns ------- thresholdData: 1D numpy array containing the total threshold value for a given signal Reference --------- Guillén, P....
316a247880a24369758661c6a65b9dabdbd3abbc
591,045
def _cvxsearch(f, x1, x2): """Optimises a convex, integer-domain function using binary search.""" x = x1 + (x2-x1)//2 # midpoint. y1, y, y2 = f(x1), f(x), f(x2) if x2-x1 == 1: return (x1, y1) if y1 <= y2 else (x2, y2) # Recurse on the half-region containing the local minimum. if y >= y1...
32e10f6a1c345874a7919bca6c7a12ba6adf6fe8
591,046
def mac_addr_convert(mac_address=u""): """ Function for providing single format for MAC addresses. :param str mac_address: MAC address to be converted. :return: MAC address in format `XX:XX:XX:XX:XX:XX`. """ try: mac = mac_address.replace(".", "") mac = [mac[i:i + 2].upper() for...
4ab89d817e14712629ea6f9ce05327bf70cf4de1
591,052
def truncatewords(s, n, ellipsis=' [...]'): """ Truncates the string `s` to at most `n` words. """ words = s.split() if len(words) > n: return ' '.join(words[:n]) + ellipsis else: return ' '.join(words)
fc75a07be78d763cfbcfd9760bddd4be7cef6728
591,057
import re def get_references(message): """Returns list of entries from References header""" reference_re = re.compile(r'(<.*?>)') refs = ''.join(message.references.split()) # remove whitespace return reference_re.findall(refs)
21db2c6de657af6f0556a739da4a06a671ecc7e3
591,059
from typing import Iterable def ensure_iterable(value): """ensure that the results of a command are always iterable""" if isinstance(value, Iterable): return value return tuple((value,))
32ce448b9cc6003abf93f3448c948d32790d14ad
591,060
def number_to_dp(number, dp, default="", en_dash_for_minus=True): """Format number to dp decimal places, optionally using a UTF-8 en dash for minus signs.""" if number is None: return default s = "{:.{precision}f}".format(number, precision=dp) if en_dash_for_minus: s = s.replace("-",...
ef63ba1aee102a475ff8e6c84742adab03032863
591,061
def get_library(phrase, lib, localize, devices): """ Return the library type if the phrase contains related keywords. """ for device in devices: if device.lower() in phrase: phrase = phrase.replace(device.lower(), "") tv_keywords = localize["shows"] + \ localize["season"]["keywor...
6db0c9a31e2604ed2b65f77a348fc9bc024691c7
591,062
def version_tuple_to_str(version_tuple): """ Convert the given version tuple to a string. :param version_tuple: Version tuple to convert. :return: String representation of version tuple. """ return ".".join([str(x) for x in version_tuple])
f9bea4a27ec617c1df72635d33fdae8237e87ed6
591,063
import random def random_length(length): """ Produce a random integer of a given length. """ return str(random.randint((10 ** length) // 9, 10 ** length - 1))
d5967121d92edb31b4fa87c7fbb61fb9b354a910
591,065
import hashlib import base64 def compute_sri_hash(filename, block_size=4096): """ Compute a SRI-compliant hash with SHA256 :param filename: path to the file :param block_size: size of the block for reading binary data :return: a base64-encoded hash """ sha256_hash = hashlib.sha256() wi...
abdbd3fbfc432289f7412f79417bc92630ce3d03
591,066
def rename_benchmark(benchmark_name): """We updated our benchmark name from "ours" to "ours-nc".""" if benchmark_name == 'ours': return 'ours-nc' return benchmark_name
edb9a288f23d0cc40586d237ce970d8c723ac5fe
591,067
def clear_results(json_data: dict) -> dict: """ Clears the results in the json file so that it can be analysed using the COM interface. Parameters ---------- json_data : dict A Python dictionary of the data held within the json model file. Returns ------- json_data : dict ...
84caeb318dc613f5ed4ccd66873a1f2ef7a4d4e5
591,068
def add_line_to_csv(file_path, line, linebreak="\n"): """Add a line to a CSV file.""" try: with open(file_path, "a") as file: file.write(line + linebreak) return 1 except: return 0
4587d2fe544a1824e78ee75509092af473a99019
591,071
import json def _importData(filePath): """Import json data Args: filePath (str): file path Returns: dict: json contents """ try: with open(filePath, "r") as f: data = json.load(f) return data except Exception as e: print(e)
45023d5e408a019f83ebb9551d96c3f1c202cc2b
591,073
import zipfile def _is_zip_file(zip_file_path): """ Return True or False if a given path is a Zip file """ return zipfile.is_zipfile(zip_file_path)
3a1f24445aff4dbc432f271464f8f9bc86e3bd76
591,074
def bahai_cycle(date): """Return 'cycle' element of a Bahai date, date.""" return date[1]
ce370b543b904071aacd7be8a1a519bbd758acf8
591,076
from typing import Optional import hashlib def sha1_hash(string: Optional[str] = None) -> str: """Avoid a TypeError when hashing strings >>> assert sha1_hash('fred') == '31017a722665e4afce586950f42944a6d331dabf' >>> assert sha1_hash() == 'da39a3ee5e6b4b0d3255bfef95601890afd80709' """ seed = "" if...
c5965cea225aa33a7a5abc9a2ae1089466e9121f
591,081
def get_pgeom(aor, e): """ The geometric transit probability. See e.g. Kipping (2014) for the eccentricity factor http://arxiv.org/abs/1408.1393 :param aor: the dimensionless semi-major axis (scaled by the stellar radius) :param e: the orbital eccentricity """ return...
83fbc61d1f93c6831e796feb3a71ae63519798a1
591,082
def resolve_weights(smartirs): """Check the validity of `smartirs` parameters. Parameters ---------- smartirs : str `smartirs` or SMART (System for the Mechanical Analysis and Retrieval of Text) Information Retrieval System, a mnemonic scheme for denoting tf-idf weighting varian...
b9085fbf380cc6d1f1619c98c8d9bea450dae52e
591,086
import re def job_name_matches_template(job_name, template): """Checks if the job name matches the job template string. For example, a job named 'gate-stackviz-npm-run-test' will match a template string 'gate-{name}-npm-run-{command}'. :param job_name: the job name to check :param template: the ...
038f68b3d28b62497e44ee25dddb0da1ff33758c
591,094
def percentile(sorted_values, p): """Calculate the percentile using the nearest rank method. >>> percentile([15, 20, 35, 40, 50], 50) 35 >>> percentile([15, 20, 35, 40, 50], 40) 20 >>> percentile([], 90) Traceback (most recent call last): ... ValueError: Too few data points (0...
a2704a59629b4634fb1f651fdbbfd9b19209816e
591,095
def get_new_model(width=1400, height=1600): """Return an initialized ERDplus object.""" return dict( www='erdplus.com', version=2, connectors=[], shapes=[], width=width, height=height )
3323b975b096cf8e27b763e4f83a6a6f899582e4
591,096
import re def parse(filename): """Searches the file for lines that start with `# TEAM:` or `# COMPONENT:`. Args: filename (str): path to the file to parse. Returns: a dict with the following format, with any subset of the listed keys: { 'component': 'component>name', 'team': 'team@e...
f353dd44fefdb0e01a8889920417c83aa879b929
591,097
def reverse_comp(seq): """take a sequence and return the reverse complementary strand of this seq input: a DNA sequence output: the reverse complementary of this seq""" bases_dict = {'A':'T', 'T':'A', 'G':'C', 'C':'G'} ##get the complementary if key is in the dict, otherwise return the base retu...
ff270fa8fea83accb26628c83a31a9d1f03c1f35
591,098
def d_binary_cross_entropy(y_pred, y_targ): """derivative of binary cross-entropy loss""" return (y_pred - y_targ) / (y_pred * (1 - y_pred))
36ff42c10e13e03740417bc6bfb8760b68ebb138
591,100
import six import unicodedata import re def wtq_normalize(x): """Returns the normalized version of x. This normalization function is taken from WikiTableQuestions github, hence the wtq prefix. For more information, see https://github.com/ppasupat/WikiTableQuestions/blob/master/evaluator.py Args: x: th...
60720c1dbcdde2ac6bfe127ef90e4f8d0670209b
591,102
def _create_keys_string(entity, keys) -> str: """Create formatted string for requested keys if non-null in entity. :param Dict entity: entity to check against, eg a Disease or Statement :param Tuple keys: key names to check :return: formatted String for use in Cypher query """ nonnull_keys = [f"...
0b0fea6d1bb608c5f4a919606cb11084c26b14e8
591,103
import pytz def as_hour(dst): """Returns the hours and minutes of a datetime (Normalized if appropriate) """ if dst.tzinfo is not None and dst.tzinfo != pytz.utc: dst = pytz.utc.normalize(dst) return dst.strftime("%H:%M")
bee9dfe33fb40f97aade3f0eea0cc69d98f2360c
591,105
from typing import Any from typing import Type def raise_exception_if_invalid_type( parameter_name: str, parameter_value: Any, expected_type: Type, ) -> None: """Raises a TypeError if the `parameter_value` given is not of the type `expected_type`; otherwise returns None""" if not i...
00932fd5f9da063ed0a8ee232d8fa13121837730
591,106
def get_colorbar_range(ctl): """ Return the range of a color transfer function (ctl) as a list = [min, max] I am sure there is a better way of doing this, but for now I am getting the minimum and maximum values from the ctl.RGBPoints. """ rgbPoints = ctl.RGBPoints min = rgbPoints[0] max = r...
3f130c327fc415c44083f5d0c795cbfa62fcdedf
591,107
def initial_guess(initial_amplitude,initial_translational_offset,initial_stddev,initial_vertical_offset): """ Create array with amplitude, phase and initial offset to be used in the curve fit Args: initial_amplitude (array): guess for the initial values of the amplitudes of the gaussians ...
c08064e67847643472653b1f93bbf3a63e6dea21
591,108
import collections import logging import itertools def ExpandNamedTestCases(inputs, *remove_keys, **extra_configs): """Expands testcase with new config dimensions. Example: inputs = ( {'testcase_name': 'test1', 'gender': 'male'} {'testcase_name': 'test2', 'gender': 'female'} ) remove_keys...
fb8e22baa744e4080061f14032e024aefdaae8f4
591,109
def calculate_axis_ratio(img): """ Function returns axis-ratio of image. Parameters: ------------------------------ img: (array), input image Returns: ------------------------------ float, Axis ratio (horizontal/vertical) """ if len(img.shape) == 2: h...
21df0e0bab55fccba07c7f7297356443c1cce146
591,110
from datetime import datetime def aggregate_by_day(df, col="T"): """Given a data frame of hourly data, compute statistics by day Parameters ---------- df : DataFrame Must have columns {'year', 'month', 'day'} col : str, optional The column to aggregate. Defaults to 'T' Return...
bba439a7b1b6bf5b179bd53a350793e9e3251406
591,111
def answerYesNo(prompt): """ returns the response to a y/n question prompt (reprompts until user provides a valid response) params: prompt (string): prompt to show user before awaiting input return (bool): True if user responds yes, False if user responds no """ val = "" while val no...
da32852cc1eeb2f06e44afb0105f0c5a3b89bdb1
591,118
import math def dec2sex(dec_hours, microsecond=False): """ Convert a time in decimal hours to sexagesimal. Parameters ---------- dec_hours : float A time in decimal hours. microsecond : boolean If true, will output a 4-tuple (hour, minute, second, microsecond). If false, ...
60fd3af7c5798a945dadf4b28022ccb62dd4b9f4
591,119
import time def open(my_instrument, mode='ON', collect=False): """ Function to activate and measure the open circuit potential (OCP) of the system. The correction will then be active on the intrument. Once this funciton is ran, the new OCP will be stored in the instrument and unless tuned off, ...
8d9c4e424139e9db0c1bc55df7510253972bdff3
591,125
def create_news_item_text_from_boards(prefix: str, board_names: set) -> str: """Create a news item string from the list of boards.""" return f"{prefix} {', '.join(sorted(board_names))}.\n"
8ac89bcefb20876d1d32adf3604fcdd08426b934
591,126
def get_img_dims(img): """ Get width and height of an image. :param img: :return: tuple(width, height) """ height, width = img.shape[:2] return width, height
b5c7d61feac6e6ac1526dbe6e012911ccde76f55
591,128
def group_bools(df, column_in, column_out): """ group_bools indexes each grouping of anomalies (1) and valid points (0) as numbered sets. Used for anomaly correction. Arguments: df: data frame with required columns: 'detected_event': boolean array of classified data points Return...
83b4d1c1eacc9de6d533caa9130b2ced211141b9
591,129
import hashlib def md5(text: str) -> str: """ Computes the MD5 hash of ``text``. :param text: The text to be hashed using the MD5 hashing algorithm. :return: The MD5 hash of the text. """ return hashlib.md5(text.encode('utf-8')).hexdigest()
f55fb25cb5e8fe60a2b1004356b0acefb854dda3
591,132
def get_digit(number, digit): """ Given a number, returns the digit in the specified position, for an out of range digit returns 0 """ digit_sum = 0 for i in range(digit): # Accumulate all the other digits and subtract from the original number digit_sum += number - ((number // 10**(i+1)) * 10**(i+1...
67ba5dbffb0ad5bdf2a8f7d59970428a1195e868
591,139
def _clean_up_value(value: str) -> str: """Cleans up a field value.""" return value.strip()
0bfbf840c9103665f3628278dd91135a189d4973
591,142
from typing import Union from typing import Collection from typing import Any from typing import Iterator from typing import Tuple from typing import Set def set_cmp( a: Union[Collection[Any], Iterator[Any]], b: Union[Collection[Any], Iterator[Any]] ) -> Tuple[Set[Any], Set[Any], Set[Any]]: """Compare the ele...
b4016111c70b8cbf781734fecdbbd67e9b9c48ad
591,143
def fixupFieldName(key): """Capitalize field names and turn '_' to space.""" if key == "clinical_int": return "Clinical Interpretation" return " ".join(s[0].upper() + s[1:] for s in key.replace('_', ' ').split())
5f4d98786f499b02d6266dc4d2e36a7cd2d18490
591,149
import click def validate_path(ctx, param, value): """Validates the formatting of the submitted path""" if value[-1] == "/": return value else: raise click.BadParameter("Include / at the end of the path.")
70b3fd5bbe5ebdd05fc2261e9395cd6bc637e6df
591,152
def get_input_variables(data_set): """Returns independent variables.""" target = data_set.columns[len(data_set.columns) - 1] return data_set.drop(target, axis=1)
87f0a8e26254d7a0e2f56ab39d90aaf786a4cf5f
591,154
def _a_in_b(first, second): """ Check if interval a is inside interval b. Parameters ---------- a : pybedtools.Interval First interval. b : pybedtools.Interval Second interval. Returns ------- bool True if a is inside b, false otherwise. """ return f...
f641502f5997c300fff6d64f903f46246833bad7
591,156
def snake_to_pascal(snake_name: str) -> str: """ Convert an snake_case string to PascalCase :param snake_name: snake case text :return: pascal case conversion """ return ''.join([w.capitalize() for w in snake_name.lower().split('_')])
4e3dbedbdd1e8020ef7a0b5b4bfd0322c4dfa40a
591,158
def _sample_vector_dist(rng): """Sample a vector distribution config.""" choice = rng.choice(["normal", "uniform"]) if choice == "normal": mean = rng.normal(0, 1) std = rng.uniform(0, 2) return choice, {"mean": mean, "std": std} elif choice == "uniform": min_v = rng.uniform(-5, 2.5) max_v = ...
f796963c2291ca2723de46168dd21631aa444722
591,161
def Gdynamic(psat, beta, Tbath, Tc): """ Dynamic Thermal conductance between the bolo and the bath, Gdynamic = dP/dTbolo Args: psat : saturation power [W] beta : thermal carrier index Tbath : bath temperature [K] Tc : bolo transition temperature [K] """ return (psat * (beta + ...
5e915a3ac9f0b80b7874fca4a30077ae3913f04c
591,162
def absMagToPower(am, absMagSun=4.75, absLumSun=3.846e33): """ Convert absolute magnitude to power scale The default values for the absolute magnitude and luminosity of the Sun are adopted from Harmanec and Prsa 2011 (2011PASP..123..976H). Parameters ---------- am : float Absol...
e462390375bfe7fc40d0d49494426832a3b5ee91
591,166
import hashlib def checksum(filepath=None, content=None, hash_fn=hashlib.sha1): """ Compute the checksum of given file, `filepath` :param filepath: Absolute path to the file to compuste its checksum :param content: a (unicode) str gives the content of the file :param hash_fn: Hash algorithm to co...
eeb3a822b7296cc3a9741c31cd67db46586783e1
591,167
def parse_inline_css(style: str) -> dict: """Parse an inline CSS 'style' string into a dictionary.""" css = {} for key_value_str in style.split(';'): key, value = key_value_str.split(':') key = key.strip() value = value.strip() try: value = int(value) ex...
70f79388f889ccbd31e94eec67aa8083a2860289
591,168
import functools def sorted_data(func): """Decorator to sort data passed to stats functions.""" @functools.wraps(func) def inner(data, *args, **kwargs): data = sorted(data) return func(data, *args, **kwargs) return inner
7b2ee9668a875e8716edb4e83fc8e59b7f287314
591,169
def extender (l, tail) : """Return list `l` extended by `tail` (`l` is changed in place!) >>> extender ([1, 2, 3], (4, 5)) [1, 2, 3, 4, 5] >>> extender ([], [1]) [1] """ xtend = l.extend if isinstance (tail, (list, tuple)) else l.append xtend (tail) return l
6a69c321369b65e8d414cc673d7de377e8a45e03
591,171
def sumOutputSerializeSizes(outputs): # outputs []*wire.TxOut) (serializeSize int) { """ sumOutputSerializeSizes sums up the serialized size of the supplied outputs. Args: outputs list(TxOut): Transaction outputs. Returns: int: Estimated size of the byte-encoded transaction outputs. ...
23126602dd07b86a73750014fa0d3f6ae8bc2171
591,172
def update_nested_dict(data: dict, to_update: dict) -> dict: """ Returns an updated version of the `data` dict updated with any changes from the `to_update` dict. This behaves differently from the builting`dict.update` method, see the example below. Example using `update_nested_dict`: >>> data = {...
b1e933f0599654774f0c795f7e49945e8e108ce8
591,174
def init_fuel_tech_p_by(all_enduses_with_fuels, fueltypes_nr): """Helper function to define stocks for all enduse and fueltype Arguments ---------- all_enduses_with_fuels : dict Provided fuels fueltypes_nr : int Nr of fueltypes Returns ------- fuel_tech_p_by : dict ...
ae446542efaa7cf90ce97596ec66fe2cccfdc450
591,179
def getWL(rawEMGSignal): """ Get the waveform length of the signal, a measure of complexity of the EMG Signal.:: WL = sum(|x(i+1) - xi|) for i = 1 --> N-1 * Input: * raw EMG Signal as list * Output: * wavelength of the signal :param rawEMGSignal: the ra...
59ccff9615120c5cda7b4e834260ad2e06a7f380
591,180
import random import string def get_random_string(length=15): """Get random string with letters and digits. Args: length (int): Length of random string. Default: 15. """ return ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(length))
a3fd2188a96e8b98e05d1d71b73393110a8510f9
591,182
def check_float(cell): """validate the value is floatable""" text = cell.text() value = float(text) return value, True
1a3ff6fc62beece2be09d4e722289611345ae07b
591,183
def is_number_char(c: str) -> bool: """Check if char c is part of a number.""" return c.isdigit() or c == "."
e19b9b62ec9d80691db041cee95eb6c17adab6a4
591,184
import inspect def public_attrs_fromdict(dic): """ Return all public names of *dic*. Public names do not begin with '_', are not function and are not *property*! """ return [attr for attr in dic \ if not attr.startswith('_') \ and not inspect.isroutine(dic[attr]) \ ...
69470e21ab91c14bca13c85c295b94f35a840ad5
591,185
def _filter_data_by_labels(X, y, label_filters): """ Filter out features and labels based on label :param X: Features :param y: Labels :param label_filters: Labels to use :return: Features and labels that have been a label in label_filters """ assert len(y) == len(X) x_ys = zip(X, y)...
732d9e643fcf97d33b64823b2f8bcbdab5e4d581
591,191
import torch def add_gaussian(x, gs_stdev): """Apply isotropic additive Gaussian noise to a PyTorch tensor.""" return x + torch.empty_like(x).normal_(0, gs_stdev)
a180d64543491643d38667a16d1545b3037c26fc
591,192
def o2_counts_to_uM(o2_counts): """ Description: Conversion of oxygen counts from a SBE 16+ V2 CTD with an Aanderaa Optode to Dissolved oxygen in micro-moles/L """ DO = (o2_counts / 10000.0) - 10.0 return DO
ad9f28cd19ef88f6ce1c22587abe89832154dc97
591,193
def stats_quantile(data, q): """ Return the specified quantile(s) q of the supplied list. The function can be called with either a single value for q or a list of values. In the latter case, the returned value is a tuple. """ sx = sorted(data) def get_quantile(q1): pos =...
a3577149efc95d00e84b53784436344fd0d54a47
591,194
from typing import Any from typing import Union import torch def move_to_device(obj: Any, device: Union[str, torch.device]): """Moves object to the given device. Args: obj: Object (tensor, list or dict of tensors or nested object). device: Device to move object to. Returns: Moved...
0fa200f8ef97062eab02f4ed5cbf319d8e750e8f
591,200
from typing import List def strip_links_from_required(l_required: List[str]) -> List[str]: """ >>> required = ['lib_regexp @ git+https://github.com/bitranox/lib_regexp.git', 'test'] >>> assert strip_links_from_required(required) == ['lib_regexp', 'test'] """ l_req_stripped: List[str] = list() ...
9a00f9259770af8d2bf5d0c324eef0074b8e4d4f
591,201
from typing import Any from typing import Optional from typing import Iterable from typing import Dict import inspect def get_public_attrs( obj: Any, *, include_single_underscore: bool = False, include_methods: bool = False, include_also: Optional[Iterable[str]] = None ) -> Dict[str, Any]: """Retu...
a9a30ecfb4a7d2b84da753becc79d9aada130514
591,204
def randomize_model_list(modelList, randomizationStrength, numCopies, seed=None): """ Applies random unitary perturbations to a models. If `modelList` is a length-1 list, then `numCopies` determines how many randomizations to create. If `modelList` containes multiple model...
80fff0a074c123b077eab38ed1c72bb45fb0089a
591,207
def is_in_dict(searchkey, searchval, d): """ Test if searchkey/searchval are in dictionary. searchval may itself be a dict, in which case, recurse. searchval may be a subset at any nesting level (that is, all subkeys in searchval must be found in d at the same level/nest position, but searchval ...
98299cacf42b6d4f3069307f8c1ccb6d6bcb20fe
591,210
def has_key_true(adjustspec, key): """ Checks if the key is in the adjustspec and if the key is True. return: :bool: if the key is set and is True """ if (key in adjustspec) and adjustspec[key] is True: return True else: return False
bdc88f85dac34463101cb61fbed07fcb126acbd3
591,212
def get_chunks(data, size): """ Function to return iterables of items from data of size 'size' """ return (data[pos:pos + size] for pos in range(0, len(data), size))
abad7c6dfaecc8fc9d1ef6424f7d511d0ff05d19
591,214
def get_value(cookie): """get the value portion of a cookie""" _, value = str(cookie).split(': ', 1) return value
d5140796ed8dfcc28b74732986abea37931e7d86
591,217
def dict_to_conf_str(obj): """Dump dict as key=value to str object.""" config_list = [] for key in sorted(obj.keys()): value = obj[key] config_list.append("%s=%s" % (key, obj[key])) return '\n'.join(config_list)
95c5c299118c4ab13d99e9b2f9af1f4db3c31f32
591,223
def compogen(g_s, symbol): """ Returns the composition of functions. Given a list of functions ``g_s``, returns their composition ``f``, where: f = g_1 o g_2 o .. o g_n Note: This is a General composition function. It also composes Polynomials. For only Polynomial composition see ``comp...
adba18398e59041028d27dd730e29d03c78d61ae
591,232
def unsigned(n: int, size: int) -> int: """ Convert a signed integer to an unsigned integer :param sint n: value to convert :param in size: byte width of n Defaults to architecture addressing size. :return int: unsigned conversion """ size *= 8 return n & ((1 << size) - 1)
67753f1eb7db4c104677b624331a02b0a939bd23
591,235