content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_def_class(word): """ get_def_class() Purpose: Checks for a definitive classification at the word level. @param word. A string @return 1 if the word is a test term, 2 if the word is a problem term, 3 if the word is a treatment term, 0 ...
403ca0f45c61f00c3af7133bd2ce6f86387f01ab
642,301
def validate_font_size(size): """ Returns whether or not given size is an acceptable font size. """ try: size = int(size) except: return False return 0 < size < 70
a7772e1124ac01df056e25d62e6be3368cecf2a8
642,303
def to_lowercase(text): """ Transform all characters to lowercase :param text: input text :return: transformed text """ return text.lower()
8978f6846211570a95235c297093c1e7e0728f57
642,305
import collections def load_run(path): """Loads run into a dict of key: query_id, value: list of candidate doc ids.""" # We want to preserve the order of runs so we can pair the run file with the # TFRecord file. run = collections.OrderedDict() with open(path) as f: for i, line in enumerate(f): q...
8ec3fc1e465c558acf274c2f2bd8cdb4ea8f6292
642,306
def read_byte(file): """ Read a byte from file """ out = ord(file.read(1)) return out
8d7bd314df6282bdb1ded0f07c05de844f8f4eac
642,307
def find_colours(shapes): """ Takes a list of shapes with cells (y, x, colour) and finds their common and uncommon colours. Note that uncommon colours are a nested list, where each nested list corresponds to uncommon colours of a particular shape - different shapes could have different uncommon colours. ...
9b4fca558d8e140a6e1c34e0ca82886d41c4fb76
642,309
def get_HNF_diagonals(n): """Finds the diagonals of the HNF that reach the target n value. Args: n (int): The target determinant for the HNF. Retruns: diags (list of lists): The allowed values of the determinant. """ diags = [] for i in range(1,n+1): if...
01c46de6db5cbf70f0a431b7f06aba2a67c6f062
642,310
from datetime import datetime def get_date_time() -> str: """get the current system date time Args: None Returns: (str): date time in the format of Y-m-d-H-M-S """ now = datetime.now() return now.strftime("%Y-%m-%d-%H-%M-%S")
f5edfb2f3416c8837137c7daf6093584df5e0264
642,312
def file_extension(filename): """ Get file extension from filename """ return filename.rsplit('.', 1)[1].lower()
3b9a5de023e28aa145625df3f3a54db253b4c4eb
642,314
def version_diff(version1, version2): """Return string representing the diff between package versions. We're interested in whether this is a major, minor, patch or 'other' update. This method will compare the two versions and return None if they are the same, else it will return a string value indicati...
57bc2c607c7a98d1f4783dfffe54eb7c08612297
642,315
def get_vector_length_squared(carla_vector): """ Calculate the squared length of a carla_vector :param carla_vector: the carla vector :type carla_vector: carla.Vector3D :return: squared vector length :rtype: float64 """ return carla_vector.x * carla_vector.x + \ carla_vector.y ...
ee612d94c20441c88beea13b8091e62cc94cfce1
642,320
def version_str(version_info): """Format the python version information""" return "{}.{}".format(version_info[0], version_info[1])
3f7ba3c140e25eec4e128ec689cf2050ef4fb952
642,323
from typing import Set from typing import Dict def _sorted_value_indices(values: Set) -> Dict[str, int]: """Converts values to a Dict mapping to unique indexes. Values will be sorted. Example: >>> _sorted_value_indices({"b", "a", "c", "a"}) {"a": 0, "b": 1, "c": 2} """ return {va...
d6141d77e006b4bdca09f541f014624bc1e0b0fa
642,328
import requests import json def isdisambiguation(pagename): """Given a wikipedia page name, returns True if that page is a disambiguation page and False otherwise :param pagename: The name of a wikipedia page :type pagename: String :return: True if pagename is the name of a wikipedia page in...
466d481523b4e86a4562644798047a9a4544cab9
642,330
def _strip_lines(latex_string): """Strip Lines in Latex Source Arguments: latex_string {string} -- LateX Source Returns: string -- Latex with lines striped """ lines = latex_string.splitlines() result = [] for line in lines: result.append(line.strip()) return "\...
cc812db77ace6ca62a1ed88c5c59a4c02ead6fa8
642,333
def ms_to_seconds(time: float) -> float: """ Convert milliseconds to seconds. Parameters ---------- time : float A ``float`` of time in milliseconds. Returns ------- float Returns a ``float`` of the converted time in seconds. """ return round(time / 1000, 3)
4dbaf2e3d3680f41c71ddab1c1e7917154f40be1
642,337
def get_stat_output(args, first_year, stats_dict, top_words, data_list): """ Function to format output statistics for one subset of corpus between first_year and first_year + args.year_split. input: args (argparse object): input arguments first_year (int): start year...
179718c83cfd165be58da5c2ae90394f9f92e48c
642,345
import base64 def base64_from_hex(hexstr): """ Returns the base64 string for the hex string specified :param hexstr: The hex string to convert to base64 :return: The base64 value for the specified hes string """ return base64.b64encode(bytes(bytearray.fromhex(hexstr))).decode("utf8")
5d457d08ed47356073bd2238699b65a3c3037df3
642,348
def __dict_replace(s, d): """Replace substrings of a string using a dictionary.""" for key, value in d.items(): s = s.replace(key, value) return s
0377e3deced100e64ae73e5dcb1c7fd583a19f54
642,352
from typing import Union from typing import Sequence import torch from typing import Mapping def to_device(inp: Union[Sequence[torch.Tensor], torch.Tensor, Mapping[str, torch.Tensor]], device: Union[torch.device, str], detach: bool = False, **kwargs) -> \ Union[Sequence[torch.Tenso...
0cfda6e2e9cdd3b275145f49efd18afd34ad60b6
642,354
def K(A,L=None): """ Function we are trying to maximize: sum_{i<j} A[L[i]][L[j]] A is m x m matrix, L is a subset of range(m) (or defaults to range(m) if no L given) """ if L==None: L = range(len(A)) return sum([A[L[i]][L[j]] for j in range(len(L)) for i in range(j)])
de8c83c695a8262131b4bef707d48255a3be89de
642,361
def degree_to_DMS(degree): """Convert from plain degrees format to DMS format of geolocalization. DMS: "Degrees, Minutes, Seconds" is a format for coordinates at the surface of earth. Decimal Degrees = degrees + (minutes/60) + (seconds/3600) This measure permit to gain in precision when a degree...
e1acc43c4bf667df904b4d4d16e948b0dce40ec9
642,366
def safe_str_cmp(a, b): """Compare two strings in constant time.""" if len(a) != len(b): return False r = 0 for c, d in zip(a, b): r |= ord(c) ^ ord(d) return r == 0
aa3ab9ca592cba926d3cdb94e1273825401119ac
642,368
import torch def prod_matrix(pts_src: torch.Tensor, pts_dst: torch.Tensor): """ Returns the matrix of "x_i * y_j". :param pts_src: [R, D] matrix :param pts_dst: [C, D] matrix :return: [R, C, D] sum matrix """ x_col = pts_src.unsqueeze(1) y_row = pts_dst.unsqueeze(0) return x_col * ...
e4dbceedfb489f101ea9e65c1d6e2a3aaf8fbb89
642,371
import math def _pad(text, block_size): """ Performs padding on the given plaintext to ensure that it is a multiple of the given block_size value in the parameter. Uses the PKCS7 standard for performing paddding. """ no_of_blocks = math.ceil(len(text)/float(block_size)) pad_value = int(no_...
d5334e05924c2221c539d92e819e2188074faac8
642,374
import math def distance(pt_a, pt_b): """ Calculate distance between 2 points. @params: pt_a: (x, y) pt_b: (x, y) """ return math.sqrt((pt_a[0] - pt_b[0])**2 + (pt_a[1] - pt_b[1])**2)
f8f655d683011eb3161daf871f6158d8a91563ce
642,375
import torch def compute_returns(rewards, masks, discount, returns4traj=True): """ Using rewards to compute returns. :param rewards: rewards agent obtains per step. Size: batch_size x 1 :param masks: indicate the final step of each trajectory. 0 for last step and 1 for others. Size: batch_size x 1 ...
6817d26464b7b04d123a1b6e5d17179d0ba3a37d
642,378
def min_coins(coins, total): """ Computes the minimum number of coins which sum up to total. Params: coins: list of non-negative integers representing the values of the coins. total: int, in fact it has to be a non-negative integer. Returns tuple: (min_num_coins, picked_coins) ...
9630e851e5a2b8af24c5e557645913a340e0c5e0
642,380
def offset(coordinates, offset_scales): """Apply offsets to box coordinates # Arguments coordinates: List of floats containing coordinates in point form. offset_scales: List of floats having x and y scales respectively. # Returns coordinates: List of floats containing coordinates i...
7b70fead737c771f224dcff073fb76676134d76e
642,381
def getNumberOfMatches(segment): """ Get numnber of matches from alignment Do not consider insertion/deletion as mismatches """ parsed_MD = segment.get_aligned_pairs(with_seq=True) return len([ base for (read_pos, ref_pos, base) in parsed_MD if ((base is not None and base.isuppe...
61bb0170e1f10f2f9721b5441516e7accb29345d
642,382
def _cli_options(parameters): """Return command line options for parameters passed as AiiDA ArrayData """ arrayname = parameters.get_arraynames()[0] dVarray = parameters.get_array(arrayname) # array of volume change in %: -6, -2, ... ndV = 0 # number of non-zero volume changes options = '' ...
51274ccd0cb1980b08286980073efff3f0632461
642,383
def get_action_by_name(client, cluster, name): """ Get action by name from some object Args: client: ADCM client API objects cluster: cluster object name: action name Returns: (action object): Action object by name Raises: :py:class:`ValueError` ...
9089b2e5d5b5b131eea0ddd9a16dace9decc5905
642,388
def remove_title(text): """ Removes the title of a document :param text: text containing an article output from cleanhtml() :return: text of the article without title """ index = text.find("\n\n") if index != -1: return text[index+2:] else: return text
ff1364dce525eb8007381c9b4b51b26fcb24a07f
642,390
def _s(strs): """ Convert a byte array to string using UTF8 encoding. """ if strs is None: return None assert isinstance(strs, bytes) return strs.decode('utf8')
f437ff006c50184d3853f5a4d317c4ef3a761d2c
642,391
def _time2dict(time): """Convert PaStreamCallbackTimeInfo struct to dict.""" return {'input_adc_time': time.inputBufferAdcTime, 'current_time': time.currentTime, 'output_dac_time': time.outputBufferDacTime}
8ac1feab267d8d3a852fbb29f4692d39f8fe73ac
642,392
def format_traits(code, value): """Format traits as list of names. """ result = [] for trait in code: if value & code[trait]: result.append(trait) result.sort() return ','.join(result)
0e8db29db14f6f6918e983c8a461b193b92776a1
642,393
from typing import Any def int_from_str(arg: Any) -> int: """Take in an argument and try to return its int equivalent. Args: arg (Any): This can be any type. However, in general use it should be either an int or str. Returns: int: The int equivalent of the passed in argument. I...
b64a5744847c566edddc98d1aad1e793f641eca3
642,396
def parse_to( buffer, keyword ): """Continues through the buffer until a line with a first token that matches the specified keyword. """ while True: line = buffer.next() if line == '': return None values = line.split( None ) if values[ 0 ] == keyword: ...
749e3436a84eff879e602c886ad11fd5a6c1e94e
642,400
def returnPreds(preds, threshold): """ Return predicted binary values from prediction probabilities based on a given threshold Inputs: - preds: prediction probabilities - threshold: threshold for positive prediction value Output: - predicted_labels list of binary predicted labe...
7b8d606dc4ff0be8966dea1d26621d6ef3c07230
642,406
import hashlib def hashtext(stringText): """Return a string with first 16 numeric chars from hashing a given string """ #hashlib md5 returns same hash for given string each time return hashlib.md5(str(stringText).encode('utf-8')).hexdigest()[:16]
01b8a553ed6a8db309594138cb4393f7601999c8
642,413
def get_equipment_slot_string(equipment_item) -> str: """ This function is called specifically for the print_character_equipment function in information_printer.py Returns the string representation of an Equipment object or returns empty if there is no such item. """ if equipment_item: retur...
48fefe9f83056dff37f32c0841b1c55d4fe8b705
642,416
from time import strftime,localtime def datestring(seconds): """Format time in seconds since 1 Jan 1970 00:00 UST as local time string in the format '1-Jan-70 00:00:00'""" return strftime("%d-%b-%y %H:%M:%S",localtime(seconds))
e656b4c27236a4813c02c9e8d29d94b45b39644b
642,418
def left_canonical_form_mps(orig_mps, chi=0, threshold=1e-14, normalise=False): """ Computes left canonical form of an MPS See also -------- Tensor.left_canonise() """ mps = orig_mps.copy() mps.left_canonise(chi=chi, threshold=threshold, normalise=normalise) ...
22c3f997ba3b83a3d592b816f02cb4464ec72ef1
642,421
def as_dict(language_object): """ Get a dict representing a language """ # Previously we had a list of ISO_639_2b (bibliographic) languages in datasets.py represented e.g. # [u"wel", u"cym", u"cy", u"Welsh", u"gallois"] - now we have pycountry, so we favour the bibliographic name when # available. Frenc...
d3b3bd81ceb771abdfb9970bd87f916c4c1cdf02
642,422
def has(name, o): """Returns whether or not an object has an own property with the specified name""" if hasattr(o, str(name)): return True try: o[name] return True except (TypeError, KeyError): return False
066854da62cacb8aa739c8efcf6fcb69382c028c
642,424
def all_equal(elements): """ :param elements: A collection of things :return: True if all things are equal, otherwise False. (Note that an empty list of elements returns true, just as all([]) is True """ element_iterator = iter(elements) try: first = next(element_iterator) # Will throw ...
d4756b30603300e2021073fbe75740b82f66f644
642,425
def _get_physical_table(api, *, table_id: str) -> str: """ Returns the physical table name for a given GUID. """ r = api._metadata.detail(guid=table_id, type='LOGICAL_TABLE').json() return r['logicalTableContent']['physicalTableName']
964cf16af34bcc134b9ee188427c7f34dc1e138e
642,427
def get_decipher_values(values, text_key): """ Converts a Decipher values collection into a Quantipy values collection. Parameters ---------- values : list The values object from a block of Decipher metadata Returns ------- values : list The Quantipy values object ...
9d25e9574880ea8f0f079df857f09313067bca0e
642,429
def linear_search(lst, value): """ Searches for a specified value in a list. It performs linear search in an iterative way. @param lst: a list containing numbers @param value: value to search @return: True if value is found. Otherwise, False. """ for element in lst: if element ...
16106aed79dd0b1aed689ad0fb995743d0654514
642,432
def harmonic_mean_reward_fn(env, top1, top5, vloss, total_macs): """This reward is based on the idea of weighted harmonic mean Balance compute and accuracy provided a beta value that weighs the two components. See: https://en.wikipedia.org/wiki/F1_score """ beta = 1 # beta = 0.75 # How much to...
d230b60ec81a6bd4d1dd7576062f70b7a7229f94
642,433
import math def calculate_kl(p, q): """Calculate D_KL(P || Q) (the KL-divergence) in bits. D_KL(P || Q) is the `information gained when one revises one's beliefs from the prior probability distribution Q to the posterior probability distribution P`. (Wikipedia, Kullback–Leibler divergence) ...
06a474403090147bf1f85f23e6a30c818cab54f6
642,435
def compute_macd_custom( df, column_source, column_target_ema, column_target_macd, column_target_macd_signal, column_target_macd_histogram, time_period_fast, time_period_slow, time_period_macd): """ Compute Moving Average Convergence Divergence (MACD). When fast ema crosses above sl...
4f0078c7e6e3db1f9c1a6e1a45027eae7ba9917a
642,437
import random import string def client_token_generator(challenge_pk): """ Returns a 32 characters long client token to ensure idempotency with create_service boto3 requests. Parameters: None Returns: str: string of size 32 composed of digits and letters """ remaining_chars = 32 - len(str...
49571784dc37772c59fafe634beeeaa15200dd37
642,442
def apply_units(v, units): """Apply unit to a dimensionless value. Return dimensional values unchanged. Args: v (numeric, unit): The value to which units will be applied. units (unit): Unit to apply to the value. Returns: unit: A value with a Pint unit applied to it. Example: ...
df4056424c35062f346e8b7d98af6a15a9c0d46d
642,443
def mean_squared_error(a, initial=None): """Mean squared error (MSE). By default, assume the input array `a` is the residuals/deviations/error, so MSE is calculated from zero. Another reference point for calculating the error can be specified with `initial`. """ if initial is None: init...
204c14237b330644152b62b4432ac5867217159b
642,444
def ListVersionTags(client, messages, package, version): """Lists tags associated with the given version.""" list_tags_req = messages.ArtifactregistryProjectsLocationsRepositoriesPackagesTagsListRequest( parent=package, filter="version=\"{}\"".format(version)) list_tags_res = client.projects_locations_repos...
0e3befae26f053424e945a1602ebc8efe8e9cc20
642,445
import math import bisect def get_tile_coords_range(min_lat, min_long, max_lat, max_long, interval): """ Get the coordinates of the upper left corners of the list tiles containing the region. Args: min_lat: (float) The minimum latitude (farthest south). min_long: (float) The mini...
d938cc68eaa1821811c2bfab68a83c93c9a70901
642,448
def get_file_target(content, output, dependencies=None): """ Get a target that creates a file Parameters ---------- content : str file content output : str copy destination during build dependencies : list of str, optional outputs of target's dependencies, by default...
1aa8e67aa813874b16f8b9cb7fe46ebc96c9211a
642,449
def indent(text, prefix): """ Adds `prefix` to the beginning of non-empty lines in `text`. """ # Based on Python 3's textwrap.indent def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if line.strip() else line) return u"".join(prefixed_lines())
08d596f0641ab8b5077d70311c9f7b945d707877
642,452
def _flatten_yocto_conf(conf): """ Flatten conf entries. While using YAML *entries syntax, we will get list of conf entries inside of other list. To overcome this, we need to move inner list 'up' """ # Problem is conf entries that it is list itself # But we can convert inner lists to tuples, wh...
0651fb7678d8309fc7992e25c40f27b5fb99e93a
642,455
def load_corrupted_test_info(dataset): """Loads information for CIFAR-10-C.""" if dataset == 'cifar10': corruption_types = [ 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', 'frosted_glass_blur', 'motion_blur', 'zoom_blur', 'snow', ...
3208f2edd2516fe136d7504f3d9a8143b6e0f5b8
642,456
from typing import Union from datetime import datetime from typing import Tuple def parse_date_range(date_range: str) -> Union[datetime, Tuple[datetime, datetime]]: """Parse either a date string or date tuple from a string. Args: date_range (str): This can either be a string with a single date or a t...
3474ca8493ed3b5e15d54042615fc6d3ec514558
642,459
import itertools def flatten(iterable): """Concatenate several iterables.""" return itertools.chain.from_iterable(iterable)
868ef9e0bd02d7c0c67d096c74c8eb69d87b2bfa
642,461
def _has_annotation(var: str) -> bool: """Check if a variable has an annotation. 'self' and 'cls' can't have annotations. :param var: str String containing variable name, annotations, and default value :return: bool Returns whether or not the variable has an annotation """ if va...
da4b980e37f764937a96b720df15f9758b0ed0c9
642,462
from typing import List from typing import Tuple def _split_chunk_bounds( start: int, stop: int, multiple: int, ) -> List[Tuple[int, int]]: # pylint: disable=g-doc-args # pylint: disable=g-doc-return-or-yield """Calculate the size of divided chunks along a dimension. Example usage: >>> _split_chunk_...
ebbc2ff86ca29f3eb72040944bdcc61cbab318ca
642,463
def map_bound(value, in_low, in_high, out_low, out_high): """map with high and low bound handling.""" result = None if value <= in_low: result = out_low else: if value >= in_high: result = out_high else: # http://stackoverflow.com/a/5650012/574981 ...
17c3d2a00cc0050daac27d70aa62a5cbab989022
642,464
def search_fid_mock(self, criterion_type, criteria_list): """ Mock of TemporalDataMgr.search_functional_identifiers method Same parameters and types as the original function """ return [{"tsuid": "00001", "funcId": "FuncId_0001"}, {"tsuid": "00002", "funcId": "FuncId_0002"}, ...
22a681dddac4dec45155ae2c3f5b73ee94ab7fbb
642,466
import inspect def build(klass, **kwargs): """Build instance of klass using matching kwargs""" known_param_names = list(inspect.signature(klass).parameters.keys()) known_params = {n: kwargs[n] for n in known_param_names if n in kwargs} return klass(**known_params)
ae07ee5d784d7fd8d3ab5389a8771f614be8034d
642,468
def more_vowels(astring): """Solution to exercise C-4.18. Use recursion to write a Python function for determining if a string s has more vowels than consonants. """ string = astring.lower() vowels = 'aeiou' n = len(string) vowel_count = 0 def recurse(idx): nonlocal vowel_c...
7af30946a0314d04580eeae39d4c5a302b7c6d3e
642,470
from typing import Tuple def rgb_to_cmyk(r: int, g: int, b: int) -> Tuple[float, float, float, float]: """Convert RGB (Red Green Blue) to CMYK (Cyan Magenta Yellow Black). :param r: Red (0 to 255 inclusive). :param g: Green (0 to 255 inclusive). :param b: Blue (0 to 255 inclusive). :return: CMYK ...
c4a02d3fb66405940e4d50f578830ac5b8e809a9
642,471
def find_all(L, x): """Find indexes of all occurrences of *x* in list *L*, and return a list of them.""" out = [] prev = -1 while 1: try: prev = L.index(x,prev+1) out.append(prev) except: return out
9b2a061418cdee0767e37764edb6b60a791f52e9
642,479
def any_check(geom_test, gdf, how): """Improve speed for an 'any()' test on a list comprehension. Replace a statement like... .. code:: if any([geom_test.touches(g) for g in gdf.geometry]): ... with the following: .. code:: if any_check(geom_test, gdf, how='touches'): Inst...
42a1cdfc447c37fe028483e1ed74138e99c4904e
642,481
def drop_duplicates_sorted(df, subset=None, sep='', inplace=True): """ Drop duplicate rows based on unique combination of values from given columns. Combinations will be sorted on row axis before dropping duplicates. Params ------ df : pandas DataFrame subset : list of str Subs...
ee723e97b71985cc510c70bbf1ec0fdfac684484
642,482
def is_valid_energy(ext): """ Checks if energy format is compatible with GROMACS """ formats = ['edr'] return ext in formats
c46bae63df3daa8c11dd8efd981f3149866214de
642,489
def trim_the_firsts_e(L, e): """Return the list L without the first sequence of element(s) e. Eg. trim_the_firsts_e([0, 0, 1, 0, 1, 0]) -> [1, 0, 1, 0] :param L: the list to trim :param e: the element to remove :type L: list(int) :type e: int :return: the list L without the first(s) e(s) ...
b52b9a1bb2a94553735af335daa66898137f1424
642,490
def combine_dict_in_list(d1_, d2_): """ Merges two dictionaries, non-destructively, combining values on duplicate keys in a list >>> d1 = {'a': 'test', 'b': 'btest', 'd': 'dreg'} >>> d2 = {'a': ['cool', 'test'], 'b': 'main', 'c': 'clear'} >>> combine_dict_in_list(d1,d2) {'c': ['clear'], 'a': ['...
22163b4ed411d2f3a7fe0919604e357c288eb364
642,491
def part2(allergens): """Part 2 wants the list of unsafe ingredients, sorted by their allergen alphabetically, joined together into one string by commas. """ return ",".join( ingredient for (allergen, ingredient) in sorted(allergens.items()) )
4d1d1b32b673fabc47fc03fef6d32343f0a49532
642,492
from typing import List from functools import reduce def mult_list(list_: List[int], modulus: int = 0) -> int: """ Utility function to multiply a list of numbers in a modular group :param list_: list of elements :param modulus: modulus to be applied, use 0 for no modulus :return: product of the e...
0d460e1d96e72d68cc1bdfaf2a69ba97890a0845
642,494
from typing import Dict def get_j2k_parameters(codestream: bytes) -> Dict[str, object]: """Return a dict containing JPEG 2000 component parameters. .. versionadded:: 2.1 Parameters ---------- codestream : bytes The JPEG 2000 (ISO/IEC 15444-1) codestream to be parsed. Returns ---...
0e3f78a8de7904e2273ba9643ebccf1252c9cf3d
642,499
def _is_trivial_description(col_name, col_description): # type: (str, str) -> bool """ Heuristics to determine if the column has a trivial description (which we do not document). """ return col_description == col_name or \ col_description == "Property " + col_name or \ col_...
77fba30df7984326d000ed2415fd06f0b45252e9
642,500
def _original_var_name(var_name): """ Return the original variable name. """ if var_name.endswith('.quantized.dequantized'): return var_name[:-len('.quantized.dequantized')] if var_name.endswith('.quantized'): return var_name[:-len('.quantized')] if var_name.endswith('.dequantize...
a9745300ac1cb857dc2f3c782809819e042ba718
642,502
from pathlib import Path def get_input_paths(global_conf, local_conf): """Returns a 2-tuple: - Markdown Path or None - Input-file Paths or empty list """ del global_conf # Unused relative_markdown_path = None # Markdown is optional input_files = [] # Input file could be empty if "m...
a3b770074a0fab48eb782d4cfcb88bc41897445a
642,503
import torch def compute_kld(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor: """ Compute the expected/averaged kl-divergence from a batch of mu's and logvar's for a fully-factorized Gaussian distribution. Assume dim0 is the batch dimension, and all the rest are data dimension. .. note::...
b5f9fedaf27818bf33af05dfeaeaf01e4a638aa5
642,507
def check_complete(board): """Checks the board. If all matches have been found, returns True.""" for card in board: if not card["cleared"]: return False return True
36ed0748019ea321c69b6e75e59c79557199cb88
642,508
def elide_text(text: str, max_length: int) -> str: """Shorten a string to a max length and end it with an ellipsis.""" return text if len(text) < max_length else f"{text[:max_length]}..."
0fc2072c53eb70e7e2ed3fb1d132a9a608c4a400
642,511
import json def get_workout_data_from_file(fNamePath): """ Parses passed files and loads that json data to a Dictionary. Returns the Dictionary storing the json data. """ data = '' with open(fNamePath) as data_file: data = json.load(data_file) return data
69d22f7553ab57d8013bd4351deb4edabc642a8d
642,513
import json def load_json_schema(schema_file_name): """Load json schema from JSON file.""" with open(schema_file_name) as schema_file: return json.loads(schema_file.read())
40286cb00a2f3ff79cfc3629092ba3748221a528
642,516
def chen_celikovsky(XYZ, t, a=36, b=3, d=20): """ The Chen-Celikovsky Attractor. x0 = (0.1,0.1,0.1) """ x, y, z = XYZ x_dt = a * (y - x) y_dt = -x * z + d * y z_dt = x * y - b * z return x_dt, y_dt, z_dt
cb9b8427776e73610548a83ca9e5e2f2a4a6d3e2
642,517
def capitalize_first(string): """Returns string with its first character capitalized (if any)""" return string[:1].capitalize() + string[1:]
0d248ba79ee5bf2dd5031fe8a1229a601cd2c09b
642,520
def evaluate_old_grounding(grounding): """Return status of old grounding.""" if not grounding['db_refs']: return 'ungrounded' elif not grounding['correct']: return 'incorrect' else: return 'correct'
c19349d70e2c7e9f53cca827c7d2443228183619
642,522
def rotate(string, n): """Rotate characters in a string. Expects string and n (int) for number of characters to move. """ return string[n:] + string[:n]
97913787c51d9cb07274bf51285559d714ac00db
642,525
import logging def append_to_file(file_path: str, file_text: str) -> bool: """ Purpose: Append text to a file Args/Requests: file_path: file path file_text: Text of file Return: Status: True if appended, False if failed """ try: with open(file_path, "...
c6af52cd945367dc23da5d2bd1df17b1b52f05ed
642,528
import re def explode(bus_str): """ Explode a bus into its separate lines. This function takes a bus expression like "ADDR[0:3]" and returns "ADDR0,ADDR1,ADDR2,ADDR3". It also works if the order is reversed, e.g. "ADDR[3:0]" returns "ADDR3,ADDR2,ADDR1,ADDR0". If the input string is not a vali...
3ccc46795a3d2b95087987c1503ffac53d4ec734
642,530
def unique(mylist): """Finds unique elements of list""" return list(set(mylist))
67d889a98c50181c40546fa687e2ade8075fb315
642,532
def percent(val, val_max): """ Percentage calc :param val: value :param val_max: max value :return: ratio in percentage """ return float(val * 100) / val_max
2dbde830da389e98da7de3dd7138a3ee5b59e469
642,533
from typing import Collection def mean(iterable: Collection[float]) -> float: """ Returns the average value of an iterable """ return sum(iterable) / len(iterable)
d7780c052a4e7109694203a0967c94a81a4d2c29
642,534
import re def contains_chinese(text): """Returns whether the given text contains any chinese characters.""" return re.search(u'[\u4e00-\u9fff]', text)
a2ea77109b3af46cae1f99f8c7fb20fc6f1ab4b1
642,535
from typing import List from typing import Any def get_attr_path(data: dict, path: List[str]) -> Any: """ Used to get a value in a dict based on a path. Args: data (dict): A dict of data to be searched. path (list): An ordered list of string attrs to be used for searching through the obje...
e9b415910104f12b7cdff90dbbc7939f7542b931
642,541
def s2b(s): """ Converts a string to boolean value """ s = s.lower() return s == 'true' or s == 'yes' or s == 'y' or s == '1'
cd3fab7ab7f2a417a21d511fc2d33e07cb38fb31
642,542
def parse_td(row_html): """ Return the td elements from a row element. Parameters ---------- obj : node-like A DOM <tr> node. Returns ------- list of node-like These are the elements of each row, i.e., the columns. """ return row_html.find_all(("td", "th"), recurs...
7a4d4c2a253053a2f3e3b428b3d0b288a7d5021a
642,545