content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def version_match(required, candidate): """Test that an available version satisfies the required version. To be suitable a version must be of the same major version as required and be at least a match in minor/patch level. eg. 3.3 is a match for a required 3.1 but 4.1 is not. :param tuple require...
45a9593dcb1c85ec9bab99b8f2fbb35986370fe3
570,498
import math def nCr(n, r): """ Compute the binomial coefficient n! / (k! * (n-k)!) Parameters ---------- n : int Number of samples r : int Denominator Returns ------- ret : int Value """ return math.factorial(n) / math.factorial(r) / math.factorial...
83c5788fc747de3c218195ef85a7bfcec6eb96ae
570,500
import platform def shlib_name(library: str) -> str: """Returns the platform-specific name of the shared library""" if platform.system() == 'Linux': return 'lib' + library + '.so' elif platform.system() == 'Windows': return library + '.dll' elif platform.system() == 'Darwin': r...
86d7c63c2ba0af8b3c13912ab60c0e187c1504ae
570,502
def new_len(s): """ This is our personal length function. s: It is should be iterable and I will tell the length. """ l=0 for i in s: l+=1 return l
e367366f327cfd3c7730759bf42fed0602a8b3b8
570,504
def _LeftMostFace(holes, points): """Return (hole,index of hole in holes) where hole has the leftmost first vertex. To be able to handle empty holes gracefully, call an empty hole 'leftmost'. Assumes holes are sorted by softface.""" assert(len(holes) > 0) lefti = 0 lefthole = holes[0] ...
73943b63da39a66ad8b4d00619c8df19bbbaee85
570,507
def find_hpo_row(sheet, hpo): """ Finds the row index of a particular HPO site within a larger sheet. Parameters ---------- sheet (dataframe): dataframe with all of the data quality metrics for the sites. hpo (string): represents the HPO site whose row in the particular she...
ec395a83c2fc8bb6d10b6d504f6f4adc0a6ddcaa
570,512
def preprocess(text): """ Pre-process text for use in the model. This includes lower-casing, standardizing newlines, removing junk. :param text: a string :return: cleaner string """ if isinstance(text, float): return '' return text.lower().replace('<br />', '\n').replace('<br>', '\...
1d3044e145d938e70e828f0f13cce24dd7134a7c
570,514
import torch def setup_grid(range_lim=4, n_pts=1000, device=torch.device("cpu")): """ Return a tensor `xy` of 2 dimensional points (x,y) that span an entire grid [-range_lim,range_lim] with `n_pts` discretizations. """ x = torch.linspace(-range_lim, range_lim, n_pts, device=device) y = torch.l...
841755cb4eadb6ae3f2a743eca92387a1a9598e1
570,515
def find_first(dictionary, condition): """ utility for finding the first occurrence of a passing condition for a key and value pair in a dict """ for key, value in dictionary.items(): if condition(key, value): return key, value return None
a277204267ad33e7d0e7042e4103d8d66e14949a
570,517
def _axis_id_to_slice(axis_id: int, tile_length: int, n_px: int) -> slice: """Take the axis_id from a dask block_id and create the corresponding tile slice, taking into account edge tiles.""" if (axis_id * tile_length) + tile_length <= n_px: return slice(axis_id * tile_length, (axis_id * tile_length...
58be88c9bf3e2070aeecb1485ee3d0270ab6f785
570,518
def valid(text, chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"): """Returns a copy of text than only contains characters in chars This function is case-sensitive. >>> valid("Barking") 'B' >>> valid("KL754", "0123456789") '754' >>> valid("BEAN", "abcdefghijklmnopqrstuvwxyz") '' ""...
939c39d1b672e1e2ade35249702b4fccac7ec296
570,519
from typing import OrderedDict def get_priority_ordered_labels(label_id_priority_fname): """ ordered_priority_dict = get_priority_ordered_labels(label_id_priority_fname) read the input .csv file into a priority dictionary struct Args: label_id_priority_fname: with Header = Label, ID, Priority ...
f85369260caa26297a63793bb4f6b64bb3a2861c
570,525
import torch def l2_loss(weight): """ L2 weight regularization :param weight: weight to regularize :return: loss """ return torch.sum(weight ** 2)
016a475c24bdcdaba6f55eb78326fac2b4148ac6
570,526
def _browser_server_address() -> str: """Internet address where users should point their browsers in order to connect to the app. Can be IP address or DNS name and path. This is used to: - Set the correct URL for CORS and XSRF protection purposes. - Show the URL on the terminal - Open the brows...
54337f8d654173cb8c6a18102d767b41a5cb06cf
570,527
def divideDict(data, col): """ Divides the data into the one from the left LIDAR and the right LIDAR """ # Dividing the dictionary in two data_left = data['collections'][col]['data']['left_laser'] data_right = data['collections'][col]['data']['right_laser'] return data_left, data_r...
cec93716c0195daec341ec2467bf8432c65891fb
570,528
def get_topic_name(prefix, table, operation): """Create a topic name. The topic name needs to be synced between the agents. The agent will send a fanout message to all of the listening agents so that the agents in turn can perform their updates accordingly. :param prefix: Common prefix for the age...
277a2b3d193f39630be0fb8722521aa0d3e6c9da
570,532
def model_predict(model, inputs): """ Predict. """ # print(inputs) return model.predict( x=inputs, batch_size=None, verbose=0, steps=None, workers=5, use_multiprocessing=False,)
c91d54ac7fcbe1907da7d25eee1e84069cb1b908
570,533
import re import warnings def _read_next_tag(fp): """Read the next tag from the tag file. Attempts to read the next line from the text file opened as `fp` (using the `readline` file object method---quack quack!) for use as a sector tag. A "Stepleton" bootloader prints all but the last sector's tag to the scr...
b773d387a618087e888ad7381821ce50040eca4c
570,534
def _unit_empty_map(value, empty): """ Map unit values for CoNLL-U columns to a string or None if empty. Args: value: The value to map. empty: The empty representation for this unit. Returns: None if value is empty and value otherwise. """ return None if value == empty else value
8d9a1b9ba07a03f59800198a42967a8756703f9c
570,536
def file_name_to_ref_p_and_restored_p(fileName): """ Returns the appropriate filename based on the extension as denoted in the pipeline :param fileName: :return: Tuple of reference and restored filenames """ refPuncFileName = fileName + "_reference_punc.txt" restoredPuncFileName = fileName +...
3803d916952d42b9f444b25c7e8219207d7555a7
570,539
def isBangaloreCallingCode(callingCode): """ Helper function that checks if the callingCode is a Bangalore number (080) """ return callingCode == "(080)"
01cb4d636139c8d32d93afd72b0286ec6b9df4e2
570,540
import json def get_schedule(connection, id, fields=None, error_msg=None): """Get information of a specific schedule by `schedule_id`. Args: connection(object): MicroStrategy connection object returned by `connection.Connection()`. schedule_id(str): ID of the schedule fiel...
9f86f2fe3015b5e71f33b4d1524b009cc11a578b
570,543
import re def get_label(file): """ Read lines of a file and try to find a doxygen label. If the label is not found return None. Assume the label is in the first line """ with open(file, 'r', encoding='utf-8') as f: line = f.readline() label = re.search(r'\{\#(.+)\}', line) ...
2f61b21d5e12bddef2268fbec5ba85d646973b6f
570,544
from typing import AnyStr def to_str(bytes_or_str: AnyStr, encoding="utf-8") -> str: """Based on Effective Python Item 3: Know the difference between bytes str and unicode """ if isinstance(bytes_or_str, bytes): return bytes_or_str.decode(encoding) # Instance of str return str(bytes_or...
7cb6dfe5ce6984df7bee713ac17d5157c38cbccc
570,545
def is_genotyped_or_well_imputed(info, r2=0): """Determine if the current variant was genotyped or was well-imputed Parameters ---------- info : str Data from the INFO column of an imputed VCF file r2 : float R-squared threshold for inclusion based on imputation quality ...
b644e6e377489d92996e1709fa498f3d24102731
570,546
import hashlib import functools def sha256sum(filepath, bufsize: int = 32_768) -> str: """Return SHA-256 hexdigest from reading ``filepath``.""" h = hashlib.sha256() with open(filepath, 'rb') as f: for data in iter(functools.partial(f.read, bufsize), b''): h.update(data) return h.h...
4ffbdd9cd21757a9c037e50adb366add1a013359
570,558
import random def train_model(model, X, Y, epochs=100, version=0, run_number=0): """ Shorthand function for training a new model. This function names each run of the model using the TensorBoard naming conventions. Parameters ---------- model: Keras model instance Compiled Kera...
59abd239bc9600f3259c524d1c1b3dcc391ec7c0
570,561
def safe_get(mapping: dict, key, default=None): """ :param mapping: dictionary of key values :param key: key being searched for :param default: default value in case key was not present in the dict :return: default value if the key is not present in the mapping dictionary, else the value in the dict...
e337f82958a0d384b963874298d870ec8e4cb5be
570,563
def isList(x): """ returns True if argument is of type list, otherwise False >>> isList(3) False >>> isList([5,10,15,20]) True """ return ( type(x) == list ) # True if the type of x is a list
ed1c3dd9b16fb5ed5307bf138de3c5fd1fa0e546
570,565
def filter_results(results, skip_list): """ Remove results for methods on the skip list. """ result = [] for method, res in results: include = True for skip in skip_list: if skip in method: include = False break if include: ...
594c53afaa079ce2bb1942879ecd7a076d23390c
570,567
def lag(x, n = 1, default = None): """Return an array with each value replaced by the previous (or further backward) value in the array. Arguments: x: a pandas Series object n: number of next values backward to replace each value with default: what to replace the n final values of the a...
e4c0af6e4d2e12e044b83c56c8f049cc334d6f9f
570,571
def _find_capacity_at_bus(plant, bus_id, gentypes): """Find total capacity of plants with the given type(s) at the given bus. :param pandas.DataFrame plant: plant DataFrame from Grid object. :param int bus_id: index of bus to find generators at. :param [list/tuple/set/str] gentypes: list/tuple/set of s...
94675c0490d8f8e2485865ee092a94cc21ad6140
570,573
from typing import Iterable def intersection(sets: Iterable[set]): """Intersection of sets""" try: s = next(sets := iter(sets)) except StopIteration: return set() else: s = set(s) for x in sets: s.intersection_update(x) return s
c2fc164516296b87788ae065d787932b914bd489
570,576
from typing import List def load_words(file: str) -> List[str]: """ Loads words from input file where there is a word in every line. :param file: path to file :return: List of words """ with open(file) as f: words: List[str] = f.readlines() return words
ced5398f3232f1a55d8c44d2f362fbb06366df3b
570,585
def downscale_ls_seed_points_list(input_course_list,downscale_factor,nlat_fine,nlon_fine): """Downscale a list of land sea seed points by scaling their coordinates Arguments: input_course_list: list of tuples, a list of course latitude longitude coordinates (latitude first) giving the position of the c...
d2387733bb46d4b875e629e4a7bfa9a9388c4d60
570,590
import re def remove_number(input_text: str) -> str: """ Remove number in the input text """ processed_text = re.sub('\d+', '', input_text) return processed_text
04451a8f65c89e8dfd657d36c73cd28e497aeb59
570,591
def params(f): """ Read header parameters like ## key=value into a dictionary :param f: file handler :return: {key: value} """ params = {} pos = f.tell() line = f.readline() while line.startswith("#") or line == "\n": if line.startswith("##"): line = line[2:].rstrip("\n") try: idx = line.index("="...
8eecb4331fbf321941f2f6ebc29abd94b13f4aa5
570,593
def get_all_saas_apps(self) -> list: """Get list of unique SaaS applications in the internet services database .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - spPortal - GET - /spPortal/internetDb/serviceIdToSaasId...
5a783815b4e3247b0fc5a97c6c714fb9199a4016
570,594
def find_selected_options(option_prefix: str, redcap_record:dict) -> list: """ Find all choosen options within *redcap_record* where option begins with provided *option_prefix*. Note: Values of options not choosen are empty strings. """ return [ value for key, value in r...
6526fd00e52a18fa1b23bedb3d694d1ee6156f1c
570,595
def picker(field_name): """returns function that picks a field out of a dict""" return lambda row: row[field_name]
2d775db577ccc29a90796dd9660f5dc46e971478
570,596
def get_rsb_texture_name(filename: str) -> str: """Match source texture names to RSB texture names that were shipped""" ext = filename.lower()[-4:] newfilename = filename if ext in (".bmp", ".tga"): #Replace extension with .RSB newfilename = newfilename[:-4] newfilename += ".RSB"...
283cbc65f3b575ac5aca460a4229db33052b1371
570,606
import csv def read_csv (in_pth): """ Slurp in the contents of a CSV file. Args: in_pth (str): the path of the CSV file to read in Returns: a sequence of records as dicts. """ with open (in_pth, 'rU') as in_hndl: rdr = csv.DictReader (in_hndl) return [r for r in rdr]
238278f768012430555c26d6fe315e7fa3f3d7b8
570,611
def downloading_complete(dct,flag=None): """ Utility function: check if all files in the dictionary have been successefully downloaded. You can se the flag to: * 'op' to only check for final products (forecast are ignored) * 'fc' to only check for forecast products (final are ignore...
368f2ff6aa128d4664250b397e77c0f3a9e4ddb3
570,614
import fnmatch def filter_out_bans(mappings, bans): """Get a list of mappings minus any that match the patterns in ``bans`` :return: List of Mappings """ new_mappings = [] for mapping in mappings: for ban in bans: if fnmatch.fnmatch(mapping.pattern, ban): b...
1376c31462b823d82f09344af62aea14b478f47b
570,615
def _get_heading_vector(fly): """Calculates the heading vectors for a specified fly across all frames. Parameters ---------- fly : Fly Fly to calculate heading vector for. Returns ------- heading_vectors : np.array of shape [N, 2]. Heading vector of fly in each frame. "...
9ed925aa7489a51314ad4a9b5abb24ea5e90dca2
570,616
def _is_jamo(i): """ Function for determining if a Unicode scalar value i is within the range of Jamo. :param i: Unicode scalar value to lookup :return: Boolean: True if the lookup value is within the range of Hangul syllables, otherwise False. """ if i in range(0x1100, 0x11ff + 1): # Range of...
d71dd9a681c7f65d0aa23fa5b1139d676c39ea47
570,618
def funcArgsLength(fn): """ Get the number of args for function fn Not count *args and **kwargs """ return fn.__code__.co_argcount
c2e302749a931369083eee04e7eb66a9c2c3ac01
570,620
def identity(chip): """Determine the identity of a chip. Args: chip (dict): A chip Returns: tuple: Tuple of the chip identity field """ return tuple([chip['x'], chip['y'], chip['ubid'], chip['acquired']])
e3b1e7ac56eab651d83377adab8cc89b0ab2ba04
570,621
def calculate_cure_rate(confirmed, cure): """ 计算治愈比例 :param confirmed: 确诊人数 :param cure: 治愈人数 :return: 治愈比例 """ cure_rate = cure / confirmed * 100 return cure_rate
d866e21d61dcc8262292daffca7d5dc557ebede6
570,627
from typing import List def _open_target_file(target_fn: str) -> List[List[float]]: """ Args: target_fn (str): filename/path for target values file Returns: list[list[float]]: lists of target values, in preparation for torch.tensor of shape (n_targets, 1) """ with ope...
8a8d497c659255247a867a9b1f9479f28321b23e
570,630
def select_second(L): """Return the second element of the given list. If the list has no second element, return None. """ if len(L) < 2: return None return L[1]
022d69f7ba50d88d941278b6c990dbb9405c2dcd
570,632
def create_error_payload(exception, message, endpoint_id): """ Formats an error message to be added in case of failure """ print(f'{exception}: {message}') error_payload = { 'status': 'MESSAGE_ERROR', 'message': f'{exception}: {message}' } return error_payload
dfb5e9b9ca3760927c69df4e2a37de3ee177941a
570,636
import math def abs_angle_difference(a: float, b: float) -> float: """ Find the difference between two angles, treating anti-parallel as 0 """ r = a - b r = (r + math.pi/2) % math.pi - math.pi/2 return abs(r)
df93a270c1967426ba9008cbd899a06c8e3e320e
570,637
def _create_listing_group_info( client, listing_group_type, parent_criterion_resource_name=None, case_value=None, ): """Creates the listing group info with the provided parameters. Args: client: The Google Ads API client. listing_group_type: The listing group type. paren...
f0d508eab0010609516b95ae59d2ef6ba8a7bca2
570,641
def get_package(version): """Get package name based on version. Package changed to orion instead of orion.core at 0.1.6 """ if version >= '0.1.6': return 'orion' return 'orion.core'
c8a01abeb7f9a61e7c30b737d72aabda739e6f76
570,644
def discreteTruncate(number, discreteSet): """ Truncates the number to the closest element in the positive discrete set. Returns False if the number is larger than the maximum value or negative. """ if number < 0: return False discreteSet.sort() for item in discreteSet: if number...
8a37a2e836417ffbf505e0474b1b3e4bf19a00cd
570,651
def constituent_register_subname(host_model): ############################################################################### """Return the name of the subroutine used to register (initialize) the constituents for this run. Because this is a user interface API function, the name is fixed.""" return "{}_...
7fbe26fc6c179ee0b7d0cf594b192de808601132
570,652
from typing import Optional import re def _env_var(string: str) -> Optional[str]: """Return a value between curly braces, if detect `%ENV{}` pattern. Parameters ---------- string: str String to check Returns ------- Optional[str] Return env variable name if the pattern is...
0e009c0f73d1baadf87e3634186ed592ff9bf5e6
570,656
def _fmt_readable_granules(dset, **kwds): """ Create list of readable granule names for CMR queries Parameters ---------- cycles : list List of 91-day orbital cycle strings to query tracks : list List of Reference Ground Track (RGT) strings to query files : list List...
8f018394b3c79acf8137151c655c233bfd127763
570,664
def square_of_sum_minus_sum_of_square(N): """ This function computes, for a given integer N, the difference beetwen the square of the sum and the sum of squares (sum of integer beetwen 1 and N). """ carre_somme = 0 somme_carre = 0 for i in range(1,N+1): somme_carre += i**2 carre_somme += i carre_somme = car...
0f569e724139e5f5edf851c71248358a176a1930
570,674
def _get_assembler(cc_toolchain): """Find the path to riscv-unknown-elf-as.""" # Note: the toolchain config doesn"t appear to have a good way to get # access to the assembler. We should be able to access it via the # the compiler, but I had trouble with //hw/ip/otbn/util/otbn-as invoking # the com...
318a1098675713a4ee2d8b697b654a0e28a6eb2f
570,677
def rel_font(value, max_font): """Returns relative font size based on max_font""" font_size = 8 + int(int(value)/int(max_font) * 60) return str(font_size)
b4484172a4217a138a9a66da4b5bb8a3a2d81a74
570,682
def _parse_mut(mut): """ Parse mutation field to get position and nts. """ multiplier = 1 if mut.startswith("-"): mut = mut[1:] multiplier = -1 nt = mut.strip('0123456789') pos = int(mut[:-2]) * multiplier return nt, pos
ed5c9795b14af4c6fca49dc992adeff473f6f80c
570,685
def descendants(network,root,include_self=False): """Returns a list of all descendant concepts form the given root.""" def _descendants(network,root,concepts): concepts.append(root) for rel in network.relationships_from(root): _descendants(network,rel.target,concepts) concepts =...
72f144cd3b24fdc4e384974ec71e4ba4f7aeaeba
570,686
def _compute_win_probability_from_elo(rating_1, rating_2): """Computes the win probability of 1 vs 2 based on the provided Elo ratings. Args: rating_1: The Elo rating of player 1. rating_2: The Elo rating of player 2. Returns: The win probability of player 1, when playing against 2. """ m = max(...
150a0593152439e1cb5ed57cd7718c79ffe7cf20
570,687
def calc_percentage_nees_within_ci(nees, ci): """ Calculates the percentage of NEES within the confidence interval """ within_ci = [ind_nees < ci[1] and ind_nees > ci[0] for ind_nees in nees] return sum(within_ci) / len(nees)
76ea05ba06bfebd4ffd38035f849b3edeacb34ea
570,688
def matrix_vector_multiply(M, v): """ Multiply n * n matrix M with a n-dimensional vector v """ return [ sum([v[k] * m for k, m in enumerate(M[i])]) for i in range(len(M)) ]
4b90d8f377eae396680eadcde250ddf12e66e7ee
570,693
import uuid import random def uuid_alpha() -> str: """Generates an uuid that always starts with an alpha char.""" uuid_ = str(uuid.uuid4()) if not uuid_[0].isalpha(): c = random.choice(["a", "b", "c", "d", "e", "f"]) uuid_ = f"{c}{uuid_[1:]}" return uuid_
21aa35417b42e929456a35f354ed8dd179de3fee
570,696
def determine_paired(args) -> bool: """ Determine whether we should work in paired-end mode. """ # Usage of any of these options enables paired-end mode return bool( args.paired_output or args.interleaved or args.adapters2 or args.cut2 or args.pair_filter ...
3a79f44fe6bfc59f15b81bb765745abba3ca1277
570,697
def get_is_verbose(ctx): """Returns whether or not verbose mode is enabled""" if hasattr(ctx, "riptide_options"): return ctx.riptide_options["verbose"] if hasattr(ctx, "parent"): if hasattr(ctx.parent, "riptide_options"): return ctx.parent.riptide_options["verbose"] return Tr...
a520056fc7e12b0893a51189b0eb63279dd1dec1
570,699
import inspect def is_method(object): """Check if the given object is a method""" return inspect.ismethod(object)
29388812da0ac0bed6f9a1fc771023b5e46965ce
570,700
def _extract_sicd_tx_rcv_pol(str_in): """ Extract the tx and rcv components from the sicd style tx/rcv polarization string. Parameters ---------- str_in : str Returns ------- str, str """ if str_in is None: return 'UNKNOWN', 'UNKNOWN' if not isinstance(str_in, str...
d8d45452d64db2f34e4bec1f1b62bbf52b1f3eca
570,705
def _lower_if_str(item): """ Try to convert item to lowercase, if it is string. Args: item (obj): Str, unicode or any other object. Returns: obj: ``item.lower()`` if `item` is ``str`` or ``unicode``, else just \ `item` itself. """ if isinstance(item, str): ...
eb73ddfd9efcc9c3f8fa4b46fe8f76c138be1a02
570,707
import math def calculate_circle_spacing(radius_m, overlap_m=0): """ Takes a radius in meters and an overlap in meters. Calculates the minimum spacing of circles of the given radius that will ensure no gaps between them. This is equal to the width of a square that fits inside the circle. The overl...
659734de76adf967ce136da2e7f4323451e555ab
570,712
def format_currency(number, flag=False): """ Format number as currency :param number: Number to be formated (float) :param flag: True/False :return: Number string formated as currency flag: False: Uses comma ',' as thousands separators and dot '.' as decimal separator ...
130da1521ea52bb6c571f4df7b1529c2efb75108
570,714
import math def mixed_base_num(n, base_digits): """Converts a base-10 number ``n`` into a mixed base number with digit values described by the ``base_digits`` array. :param n: A base-10 number :type n: int :param base_digits: A list of integers representing the largest value for each ...
3b8e032b09970a6ab4e3e2c5e673b94903d04034
570,716
def g4_upper(x, constants, variables): """ Constraint on the maximum ratio of isotropic to combined isotropic/kinematic hardening at saturation. :param np.ndarray x: Parameters of updated Voce-Chaboche model. :param dict constants: Defines the constants for the constraint. :param dict variables: Define...
9ee8184458af0facb2cde2563ed31eb68d9edffa
570,717
def _mean_var(frame, weights=None): """ Compute the (weighted) mean and variance :param frame: Single column H2OFrame :param weights: optional weights column :return: The (weighted) mean and variance """ return frame.mean(), frame.var()
e6f668569e2da094086de2f465ef17cb7515075c
570,719
def single_pcrosstalk(total_pcrosstalk: float) -> float: """ Inverse formula to ``total_pcrosstalk'' Parameters ---------- total_pcrosstalk : float The probability of total crosstalk events. Returns ------- p_crosstalk : float The probability of a single crosstalk event...
401934183dd50dfad5f15ca91a183054e756e4e7
570,721
def section_marks(section, line_end=''): """A pair of start/end Travis fold marks.""" return ('travis_fold:start:{0}{1}'.format(section, line_end), 'travis_fold:end:{0}{1}'.format(section, line_end))
79dc56791f804da1faefcaf12a2302d42ec36fa0
570,730
def r_in(td, r_0): """Calculate incident countrate given dead time and detected countrate.""" tau = 1 / r_0 return 1. / (tau - td)
ced519ed2c9f2f546f5d06605213488ede9c2f21
570,732
def _series_to_dict(x, index_name='index'): """ Change Pandas Series to Dict With Index Parameters ---------- x : pandas Series index_name : return dict key of index name """ x_dict = x.to_dict() x_dict[index_name] = x.name return x_dict
6eaeac294c9ba746affe09232e2ab9c8b440a62e
570,734
import torch def normal_kl(mean1, logvar1, mean2, logvar2): """ source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12 Compute the KL divergence between two gaussians. Shapes are automatically broadcasted, so batches can be compa...
97f13d8c49cf21bbf94bad7769e3825df71589bb
570,737
from typing import List from typing import Any def multi_remove(elems: List[Any], indices: List[int]) -> List[Any]: """Remove multiple indicies in a list at once.""" return [i for j, i in enumerate(elems) if j not in indices]
d8680cea1ed2034278eae2098f2375140833922f
570,738
def parse_detexify_id(detexify_id): """Parse an id from Detexify into package, encoding and symbol.""" splitted = detexify_id.split("-") package, encoding, symbol = splitted[0], splitted[1], splitted[2:] symbol = "-".join(symbol) symbol = symbol.replace("_", "\\") return (package, encoding, symb...
dc3559f6c4a7422e7bab4c3bac5d2e18345f19b5
570,740
def arg(*args, **kwargs): """Utility function used in defining command args.""" return ([*args], kwargs)
7b3643b9136215321b63392fa018b52181161b00
570,742
def qual(clazz): """Return full import path of a class.""" return clazz.__module__ + '.' + clazz.__name__
9ffc5575dd0a08181e77053c34d4a9fc4e200346
570,744
def every(predicate, iterable): """ Iterate over iterable, pass the value to the predicate predicate and return True if all the predicate returns True for all the values. @param predicate: Predicate function. @param iterable: Iterable containing the elements to test. @return: Return True if all...
0b289485857709e106b657083e72ca651892e5f0
570,745
def clementine_edr_vector_tags(label): """ compose tags related to position and velocity vectors in label -- basically just flattening lists and flipping the sign of one of the vectors """ sc_target_position_vector = label["SC_TARGET_POSITION_VECTOR"] sc_sun_position_vector = label["SC_SUN_POSIT...
addb745d505867014989c01b6d51572fc6d1eebe
570,748
def squareRoot(num): """[summary] Uses the heron-procedure. Arguments: num {[float]} -- [radikant] Returns: [float] -- [result] """ xn = num / 10.0 # init step EPSILON = 0.001 # precision while abs(xn**2 - num) > EPSILON: xn = 0.5 * (xn + (num/xn)) retu...
8f4e2e042046992ebd52a4e7ca3d78165b550368
570,749
def reassign_decl(node): """Get the declaration for a re-assignment of the test_var.""" return node.body[3].body[0]
93d5d86cc694cff41df1e78c2ed8a12fbe5a6684
570,757
def get_normalized_progress(current_progress, start_ndist): """ Return normalized current progress with respect to START LINE of the track. Args: current_progress: current_progress to normalize (0 - 100) start_ndist: start_ndist to offset (0.0 - 1.0) Returns: normalized current...
f9d61f47dbb7bcbe932484aba538fbd42a4a05a0
570,758
def fib(n: int) -> int: """ Calculates the n-th Fibonacci number in O(log(n)) time. See: [Exercise 1.19](https://bit.ly/3Bhv2JR) """ if n < 0: fib_neg = fib(-n) return fib_neg if (1 - n) % 2 == 0 else -fib_neg a, b, p, q = 1, 0, 0, 1 while n: if n % 2 == 0: ...
37cddb25947aa514c4ed1a1b5052e3cc9862d48a
570,760
def cvt_str_to_sym(str): """Helper for interpret_w_eps --- Given a string, interpret it in all possible ways and return a set of pairs of (first, rest). E.g. "ab" interpreted as ("", "ab") as well as ("a", "b"). However, "" interpreted only as ("", ""). """ if str == "": ...
29a876349556ce43cde5b47b179d06ad866b8eb5
570,763
def read_dates(infile): """Read a file of dates (one per line) and write to a list. Assumes there is a metadata file corresponding to infile which has exactly the same name but ends with .met """ fin = open(infile, 'r') date_list = [] for line in fin: date_list.append(line.rs...
eed6adf78f5cdac4ae5366cc4fb794b35bd014f3
570,766
from typing import List def assigns_mapping_category(mapping_result: List, map_evidence: str) -> str: """Function takes a mapping result and evidence and uses it to determine the mapping category. Args: mapping_result: A list containing mapping results for a given row. The list contains three items: ...
0a54faadfcbfb835d8251cbc65f501768e17886a
570,767
def z_score_residuals(residual_df): """Standardize residuals by the mean and standard deveiation of each condition Parameters ---------- residual_df: DataFrame Dataframe of residuals with the first column as construct barcodes and the subsequent conditions as residuals Returns ------- ...
29629814b48bc33ea2af2ab984adcdb980e4b645
570,769
def sort_predictions(data_loader, results): """Recovers the dataset order when bucketing samplers are used.""" if getattr(data_loader.batch_sampler, 'store_indices', False): results = [results[i] for i, j in sorted( enumerate(data_loader.batch_sampler.orig_idxs), key=lambda k: k[1])] ret...
ef6bad042694f3fcd9e36ee0526f546c28df1720
570,772
from datetime import date def voto(nascimento): """-> Determina a obrigatoriedade (acima de 18 anos ou abaixo de 65), a opcionalidade (entre 16 e 18 anos ou a partir de 65) ou o impedimento de votar(menos de 16 anos), de acordo com a idade do indivíduo, calculada pelo anos de nascimento fornecido. :param nasciment...
e9b9e6d4fdba0dba380615aac317ae3d8268b527
570,773
def undefer_group(loadopt, name): """Indicate that columns within the given deferred group name should be undeferred. The columns being undeferred are set up on the mapping as :func:`.deferred` attributes and include a "group" name. E.g:: session.query(MyClass).options(undefer_group("larg...
fe0e84354f138a0bc5cdffd105e9c4180a98a28f
570,775