content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_batchid_from_job(job_ads_dict): """ Get batchID string from condor job dict """ batchid = '{0}.{1}'.format(job_ads_dict['ClusterId'], job_ads_dict['ProcId']) return batchid
fe7fd25830d9b0e5f6e963958fc3f883a9c745de
670,588
import random def random_name() -> str: """Generate a random account name.""" return "temp" + str(random.randint(100000, 999999))
3a54c44bdaf2c8fa99674c727462848a5ac9b24e
670,590
def sort_by_tc(events): """Sorts events by their rec_start_tc.""" events.sort(key=lambda e: (e.rec_start_tc.frames, e.track)) return events
940a3700ffbd389152dd784f6580f0da970eda18
670,592
from pathlib import Path def get_immediate_directories(directory_path): """Gets the immediate sub-directories within a directory Args: directory_path (str): path to the directory Returns: list(str): list of sub-directories """ p = Path(directory_path) return [f for f in p.ite...
8aabf6279367733bc6b25aec2cf69fb2e8f1c0a0
670,595
def all_equal(s): """Return whether all elements in a list are equal.""" return len(set(s)) <= 1
a13d0e7bed1f2051337184a6c77d57ac5c8ece23
670,596
def get_node_ids(apic, args): """ Get the list of node ids from the command line arguments. If none, get all of the node ids :param apic: Session instance logged in to the APIC :param args: Command line arguments :return: List of strings containing node ids """ if args.switch is not None...
4daa84c0fb6e74daacc3a184918ca59c6d1b6add
670,598
def _html_tag(tag, contents, attr_string=''): """Wraps 'contents' in an HTML element with an open and closed 'tag', applying the 'attr_string' attributes. """ return '<' + tag + attr_string + '>' + contents + '</' + tag + '>'
d6c08b117a6ec89e8011a4e87db22fc7d1fa0ada
670,599
import pathlib def tmp_cache(config, tmpdir): """Move the cache to a temporary dir that is empty at the start of the test and deleted after the test.""" config['CACHE_ROOT_DIR'] = pathlib.Path(tmpdir) return config['CACHE_ROOT_DIR']
f4d18fa936a19f402a68e5552c534c86426c9e0e
670,600
import codecs def read_metafile(path): """ Read contents from given metafile """ with codecs.open(path, 'rb', 'utf-8') as f: return f.read()
14545384e8c60174c858d4899832f8196216ba42
670,602
def read_content_from_file(filename): """Simply reads content from a file. Used so we don't have to mock __builtin__.open() Args: filename (string): name of the file """ with open(filename, 'r') as fh: content = fh.read() return content
c4a6d246db590b86cba88d8d39f526422e30560f
670,604
import torch def collate_fn(data): """ Creates mini-batch from x, ivec, jvec tensors We should build custom collate_fn, as the ivec, and jvec have varying lengths. These should be appended in row form Args: data: list of tuples contianing (x, ivec, jvec) Returns: x: one hot enco...
06c25feda297aba9d000e1ffb1e2f648887ae89a
670,605
from bs4 import BeautifulSoup def extract_body_from_html(html_soup): """Return an XML beautiful soup object with the <body> of the input HTML file""" body = html_soup.body.extract() xml_soup = BeautifulSoup('', 'xml') xml_soup.append(body) return xml_soup
e017ceb805bd1da023201e56d633bdb6392adbc5
670,606
import yaml import json def load_config_file(config_file: str, child_name="dockerConfiguration") -> dict: """ Load OSDF configuration from a file -- currently only yaml/json are supported :param config_file: path to config file (.yaml or .json). :param child_name: if present, return only that child n...
2814bf1e67b79a4f48fd67564e00b0f822aedd64
670,608
def make_frame(contents, title=''): """ Wrap `contents` in \begin{frame} ... \end{frame}, optionally setting `title` """ lines = [r'\begin{frame}'] if title != '': lines.append(f'\\frametitle{{{title}}}') lines += [ f'{contents}', r'\end{frame}' ] return '\n'....
eded8f5646287a363edc22a91afda779bfbaaa15
670,609
def separate_words_and_numbers(strings): """ Separates words and numbers into two lists. :param strings: List of strings. :return: One list of words and one list of numbers """ filtered_words = [] filtered_numbers = [] for string in strings: if string.isdigit(): ...
d0846effcd81524620ed7d6c3e132a3d44f0f2ef
670,616
def intersection(lst1, lst2): """returns the intersection between two lists""" if (lst1 == None or lst2 == None): return [] lst3 = [value for value in lst1 if value in lst2] return lst3
eb02cb1163762d6f0ccdbf85c3c7a0146febb38e
670,617
import torch def _format_faces_indices(faces_indices, max_index): """ Format indices and check for invalid values. Indices can refer to values in one of the face properties: vertices, textures or normals. See comments of the load_obj function for more details. Args: faces_indices: List of...
1bbba9714a3359a0c98c5ebe1059ac0ebb035b0c
670,618
def _pairs(exercises): """ Returns a list of pairs of exercises in `excercises` """ pair_list = [] for i in range(len(exercises)//2): pair_list.append((exercises[2 * i], exercises[2 * i + 1])) return pair_list
81af596635cac3def4c8bdb79955fdfb4261527f
670,632
def _unique_metric_name(name, existing_metrics): """Returns a unique name given the existing metric names.""" existing_names = set([metric.name for metric in existing_metrics]) proposed_name = name cnt = 1 # Start incrementing with 1. # Increment name suffix until the name is unique. while proposed_name i...
005fa048ec1c9d0a03f28fa0024531d74f232b56
670,633
def V(x): """ potential energy function use units such that m = 1 and omega_0 = 1 """ return 0.5 * pow(x, 2.0)
1969edd5447657096353eda96cb281da68383e8f
670,635
def dms_to_deg(deg,min,sec): """Convert a (deg,arcmin,arcsec) to decimal degrees""" return deg+min/60.+sec/3600.
9eaf74e10d80cf66990836da950b2908af6677b1
670,636
def construct_network_config_string(cfg_list): """ Creates the network configuration string from a list of addresses created via convert_network_address_to_list Args: cfg_list (List): List of lists containing all the addresses Returns: cfg_string (str): String containing the numbers of...
5a2eefc6e6cb02644a75f1609432e085d04bebdc
670,639
def from_pandas_contextual(df): """ Convert contextual ``pandas.DataFrame`` to list of tuples. Args: df (DataFrame): anomalies, passed as ``pandas.DataFrame`` containing two columns: start and stop. Returns: list: tuple (start, end) timestamp. Raise...
bbf47db19777a82ef9c5372cf638f95bfb1465f3
670,642
import math def get_dist(x1,x2,y1,y2): """Find distance between two points""" return abs(math.sqrt(pow(x1-x2,2) + pow(y1-y2,2)))
dc83c92ff12260b01ea10b90546ad475a1e83e09
670,644
def get_X_Y(**cosmo): """The fraction of baryonic mass in hydrogen and helium. Assumes X_H + Y_He = 1. You must specify either 'X_H', or 'Y_He', or both. """ if 'X_H' in cosmo and 'Y_He' not in cosmo: X_H = cosmo['X_H'] Y_He = 1. - X_H elif 'Y_He' in cosmo and 'X_H' not in cosm...
02268d861543ba0bc7deaafa3c31d0cc50231112
670,645
from typing import List def do_materials_match( materials_1: List[str], materials_2: List[str], colors_1: List[str], colors_2: List[str] ) -> bool: """Returns whether the two given material lists match, or, if either of the given material lists are empty, returns whether the two given color li...
2ad205c9ade63da4134c6260005db6a8bf3ee0d0
670,646
def separate_appetizers(dishes, appetizers): """ :param dishes: list of dish names :param appetizers: list of appetizer names :return: list of dish names The function should return the list of dish names with appetizer names removed. Either list could contain duplicates and may require de-dupin...
2a3296751f7767143602b43ce3c07a09b6280729
670,647
def compute_loss(batch, output, loss_func): """Computes the loss of a given batch Args: batch (dict): The current batch output (tuple): Tuple of tensors (output of `TransformerModel`) loss_func (:obj:`nn.modules._Loss`): The loss function Returns: (:obj:`torch.Tensor`, int)...
0ced525c776fb5522555fd0b584040d02736d120
670,648
from typing import List import itertools def flatten_(list_of_lists: List[List]) -> List: """Reduce a lists of lists to a list, functionally >>> assert flatten_([[1, 2], [3, 4]]) == [1, 2, 3, 4] Thanks to CTT at https://stackoverflow.com/a/716482/500942 """ return list(itertools.chain.fr...
c516785b429ba113953cb5183074f3de72c73e19
670,650
def clean_data(df): """ Clean the dataset Args: df: (pandas.DatFrame) containing data to be cleaned Returns: df: (pandas.DataFrame) containing the cleaned dataset """ try: # clean target labels categories = df.categories.str.split(";", expand=True) cat_n...
676f43ebdb426155ce53d3632626aefca09b3b00
670,652
import torch def redistribute_errors(power_deltaE_hyab, cmax, pc, pt): """ Redistributes exponentiated HyAB errors to the [0,1] range :param power_deltaE_hyab: float tensor (with Nx1xHxW layout) containing the exponentiated HyAb distance :param cmax: float containing the exponentiated, maximum HyAB difference be...
3e5ce06b0e1ef68b3c04dbc4476ad7e890d91354
670,653
def decode_fit_par(fit_par, constraint_types): """ Translate the 1D array of fit parameters to individual lists. The fit paramters are sorted into the lists segment_borders, y_at_borders slope_at_borders based on the strings given in constraint_types. The three lists are used as arguments in piecew...
3fdf47c8a3cb1628accbe2f81b2e1e7a5efd41f3
670,656
import itertools def get_room_locations(room_top_left, room_width, room_height): """ Returns the locations within a room, excluding walls. This is a helper function for adding objects to a room. It returns a list of all (x,y) coordinates that fall within the room excluding the walls. Parameters ...
c9a7ad43c30153b6ff0e3eaafe7adb4751f54bfb
670,658
import random def random_fill_sparse(table,K): """ brief : fills in a matrix randomly args : matrix : empty matrix K : number of cells to be filled in Return : the matrix (numpy array) filled in with "X" values (char) Raises : K must be smaller than...
bd0834ed032623893b77c6e7e29c0125bce42c05
670,659
def calcular_longitud_cadena(cadena): """ Calcula la longitud de una cadena de caracteres. """ contador = 0 for c in cadena: contador += 1 return contador
93675f6c559b19e0ef01f99e96b0c6afa8cb259b
670,663
def process_text(response): """Returns the plaintext of the reponse.""" return response.text
65c6b8055fdcf0a86ba6985895da7b0bf2d172ec
670,664
def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new ha...
cf2b94ddf35100b05e2807218048c387d7a53242
670,665
import torch def square_norm(x): """ Helper function returning square of the euclidean norm. Also here we clamp it since it really likes to die to zero. """ norm = torch.norm(x, dim=-1, p=2) ** 2 return torch.clamp(norm, min=1e-5)
8ac4b7c388e718c933b5ea9855d169e609671a76
670,674
def dt_tstamp(dt_obj): """ Args: dt_obj (dt.datetime): datetime.datetime object Returns: int: timestamp """ return int(dt_obj.strftime('%s'))
33a367c888a19515d8590b7094439aed933003d5
670,675
def other_bond_index(bond, index): """Return the atom index for the other atom in a bond.""" if bond[0] == index: return bond[1] elif bond[1] == index: return bond[0] else: raise ValueError("Index %s not found in bond %s" % (index, bond))
e31bc9f490d4faead6ccfd8abe152e929a8b1961
670,677
def pretty_print_time(time, message=None): """Pretty print the given time""" days = time.days hours, remainder = divmod(time.seconds, 3600) minutes, seconds = divmod(remainder, 60) if message is not None: print(message) print(f'\t {days} days, {hours} hours, {minutes} minutes, {secon...
366caa41f110b984508376cf957d5050a04955e7
670,679
import re def is_fc_uid(uid): """Validate the FC initiator format.""" return re.match(r"(\w{2}:){15}\w{2}", uid, re.I) is not None
9e1d798cd1554a1515e2eeabcece110a02ed066a
670,680
def _make_url_args(url_args: dict): """ Make url parameters Args: url_args (Dict): Dict of url parametes Returns: str: The url parameters Example: input: {'test1': 1, 'test2': 2, 'test3': 3} output: "&test1=1&test2=2&test3=3" """ url = '' for key, v...
0680736981aeaa755a8dc9fc280876c5b1f0f1dd
670,686
def package_time(date_dict): """Package a time/date statement in a standardised form.""" return {"time_value": date_dict}
6c4097e162091e3992fa6ef57e83093cf0788c46
670,688
def validate_container_command(output: str, name: str) -> tuple: """ Validates output from one of the *_container functions, eg start_container. :param output: output from the command line :param name: container name or ID :return: success boolean, message """ if "no such container" in outpu...
29a48035e12ebd8d70a40a8c01ad514881aba382
670,690
from typing import Dict from typing import Any from typing import Tuple from typing import List def get_category_counts(cookie_data: Dict[str, Dict[str, Any]]) -> Dict[Tuple[str,str], List[int]]: """ Retrieve category counts for each cookie, to then be able to compute the majority opinion. Cookies are ide...
c15f27c3dbef48200bf98b5665a96c08ac5c3aeb
670,693
def standardize_tabletype(tabletype): """ Given the user defined type of table it returns the proper 'tabletype' expected by the pipeline Args: tabletype, str. Allows for a flexible number of input options, but should refer to either the 'exposure', 'processing', or 'unproc...
bb715f40708ad3bd55b495167d01fb586b5e7cde
670,695
def reorder_list_or_array(M, ordering): """ Reorders a list or array like object. """ if isinstance(M, list): return [M[i] for i in ordering] else: return M[ordering]
b3c215b75937f919bab1c17146e195793d2aade2
670,696
def standardise(x,l1,l2): """standardise data x to [0,1] Parameters x: original data l1: lower bound l2: upper bound ---------- Returns ------- standardised data """ return (x-l1)/float(l2-l1)
e4e76f1b9e5b1f4d46fcc56864069f7f87db60b2
670,698
def full_product_to_l3_product(full_product: str): """Returns l3 product name.""" return full_product.split("-")[1]
e644c565badf0e06645d4645f928dbfe87b3fc71
670,699
def strip_string(value): """Remove all blank spaces from the ends of a given value.""" return value.strip()
0f66367ffc2c651488875ace33e6a44b453c3262
670,700
import click def role_selection_is_valid(selection, account_roles): """Checks that the user input is a valid selection Args: selection: Value the user entered. account_roles: List of valid roles to check against. Returns: Boolean reflecting the validity of given choice. """ ...
63eb49eba68264de43d39fce89010b99b1410895
670,701
from typing import List def largest_element(arr: List[int]) -> int: """ Find the largest element in the array >>> largest_element([1,2,3,4,5]) 5 """ mx = arr[0] for i in arr: mx = max(i, mx) return mx
05c0390dd0b4be3298e771ce29e0f7723e8b71b7
670,702
import binascii def calc_crc32(memview): """ Calculate simple CRC-32 checksum over a memoryview of data """ crc = binascii.crc32(memview) & 0xffffffff return crc
b96bbf2019be3ab91c4ba1da0f0931cd908ed422
670,707
from typing import Iterable def calculate_large_sum(number_strings: Iterable[str]) -> str: """Calculate sum of large numbers. Args: number_strings: iterable of numbers as strings to sum up. Returns: The sum of the numbers as string. """ number_strings = list(number_strings) la...
90a2771dec149d37e9957d7cc721da57a9d2b6f7
670,711
import struct def i16(c, o = 0): """ Converts a 2-bytes (16 bits) string to an integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string """ return struct.unpack("<H", c[o:o+2])[0]
efabfd5e6aeef593a551c33d477b22b15996a715
670,714
def mapl(function, array): """ Map a function to an array (equivalent to python2 map) :param function: Function to be mapped :param array: List of values :return: List of returns values f = function array = [x0, x1, x2, ... xn] [f(x0), f(x1), f(x2) ... f(xn)] = mapl(f, a...
75c4873bc48a1e949a0b51d0bc0332b6b061e628
670,716
def connect_(pairs, n=1): """connect_ Connects two adjacent clusters if their distance is <= n :param pairs: Clusters of iterateables e.g., [(1,5),(7,10)] :param n: distance between two clusters """ if len(pairs) == 0: return [] start_, end_ = pairs[0] new_pairs = [] for i, ...
5348556c3f7c54d790b49525fce6b502b3e62a9f
670,717
def _distance(p1, p2): """ Returns distance between p1 point and p2 """ return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5
3e8f3327c295764875b36d5837432c1c03bf3aa7
670,718
def read_text_file(file_path): """Read a txt file""" with open(file_path, 'r') as f: return f.readlines()
4da902efcf3a1747152471128a8706f1b8742ed8
670,721
def created_by_external_idp_and_unconfirmed(user): """Check if the user is created by external IdP and unconfirmed. There are only three possible values that indicates the status of a user's external identity: 'LINK', 'CREATE' and 'VERIFIED'. Only 'CREATE' indicates that the user is newly created by an ...
67e9228e7fdb0e06e1c41d97f0b4ebc13bde1f10
670,725
def is_growth(name): """ Test if name is a growth rate-like variable""" return name in ["gam_leq_GB", "gam_great_GB"]
493e058d1f3f3eb03563e4f6f91bafdf978f77ee
670,726
def getCouplesInteraction(couples:list, interaction_type:bool): """ | Get couples according to their interaction. :param couple: list of couples :param interaction: type of the interaction (True or False) :type couple: CoupleJson :type interaction_type: bool :return: list of couples :...
a87db8fc027f53f49ff608baffe934f966e73fea
670,728
def _adjust_component(component: int) -> int: """Return the midpoint of the quadrant of the range 0-255 that the given component belongs to. Each quadrant spans 63 integers, and the midpoints are: 31, 95, 159, 223. >>> _adjust_component(25) 31 >>> _adjust_component(115) 95 """ if c...
444baac61f20dc32d05c60900f6fe7dbf7374d51
670,731
import torch import math def perspective(aspect_ratio, fov_y, near_clip, far_clip): """Computes perspective transformation matrices. Functionality mimes gluPerspective (external/GL/glu/include/GLU/glu.h). See: https://unspecified.wordpress.com/2012/06/21/calculating-the-gluperspective-matrix-and-othe...
d00430eb971f0b3c4edbfd3cc145a6da1fe02d99
670,732
from datetime import datetime def timestamp_zip(string: str) -> str: """ Adds the current date and a .zip ending to the given string. Example: > timestamp("foo") "foo-1997-09-14-1253.zip" """ timestamp = datetime.today().strftime("%Y-%m-%d-%H%M") return f"{string}-{timestamp}.zip"
ceb20c46b0620d5f98714634f74d4b6759d7a274
670,733
def _in_text(adict): """ Wrapper to add .* around matches so pattern can be found in words. Parameters ---------- adict : dict Dictonary with key = `pattern` Returns ------- wrapped_dict : dict Dictonary with key = `.*pattern.*` """ return dict((".*{}.*".forma...
0628c51a5fc03cc11ee1a5923b7f89ba2302cc58
670,738
def get_digit_c(number, digit): """ Given a number, returns the digit in the specified position, does not accept out of range digits """ return int(str(number)[-digit])
6e38e80fa6f2714cd6fd83ae01b208848dd55e2b
670,739
import mpmath def cdf(x, c, beta, scale): """ Cumulative distribution function of the Gamma-Gompertz distribution. """ with mpmath.extradps(5): if x < 0: return mpmath.mp.zero x = mpmath.mpf(x) beta = mpmath.mpf(beta) c = mpmath.mpf(c) scale = mpmath...
30ea5ad2b8366fb0d5b8373e70f44c2f571d9aa0
670,743
def calculate_temperature_rise_power_loss_weight( power_operating: float, weight: float, ) -> float: """Calculate the temperature rise based on the power loss and xfmr weight. :param power_operating: the power loss in W. :param weight: the weight of the device in lbf. :return: _temperature_rise...
38800f7c093720561cf266f5450679abef4e71fe
670,744
def _cast(x): """ Auxiliary function used to cast strings read from the config file to more useful types. For example, it will convert any of the strings true, TRUE, True, etc, to True (bool). :param x: :return: """ # -- At the moment, it is guaranteed that x is a string, however we may wa...
4499028492d76015623efa9e697907ad9abaedaa
670,747
def get_success_prob(n, pa): """ Calculate the probability of successful transmission input: n: number of nodes in the same communication range pa: the attempt probability (pa) return: the probability of successful transmission """ return (n - 1) * pa * (1 - pa) ** (n - 2)
1324a2364b99273eb38edc56bbd3753bf01b7943
670,748
def map_category_id(category_map): """ Assign an ID to each category """ category_id = {} id_category = {} counter = 0 for category in category_map: category_id[category['name']] = counter id_category[counter] = category['name'] counter += 1 return category_id, id_categor...
9d48427aeb0e8ae2ac53ec02768d3081f641fcb6
670,749
def lamson_setting(func, key): """Simple way to get the lamson setting off the function, or None.""" return func._lamson_settings.get(key)
8f6e04cbd197b1a4d3a7442a6c9edec4fbf69287
670,752
def getSquareDistanceOriginal(p1, p2): """ Square distance between two points """ dx = p1['x'] - p2['x'] dy = p1['y'] - p2['y'] return dx * dx + dy * dy
8650bcd719fc758dfd969a61f1a57c6f3a385bee
670,754
def is_not_false_str(string): """ Returns true if the given string contains a non-falsey value. """ return string is not None and string != '' and string != 'false'
49969a2899e3e2ca35ada15ff8d4b482dd3abe80
670,762
from pathlib import Path from typing import List import gzip def save_metadata_files(path: Path, contents: str) -> List[Path]: """Saves the metadata file and the corresponding compressed version of the file. :param path: The path to save the uncompressed metadata file at :param contents: The data to ...
d6bd3c74abe88cb3cbd4c22d6492bc117cb47e09
670,763
def create_random_files(tmpdirname, num_of_files=10): """ Create random files in dir given """ _files_created = [] # Create random files for i in range(1, num_of_files + 1): _object_key = f"{i}{i}{i}.txt" _test_file = tmpdirname.join(_object_key) _test_file.write("XXXXXX...
506d6aebeb92940d68a79810cf493994db0c8aad
670,767
def match_bag(context, bags): """Matches bag to the file for which an event is triggered and returns bag or list of all bags to run Fixity against. Args: context (obj): Object that contains event context information bags (set): List of bags to match against """ filename = context.res...
10296c29ef8d2cb9e813f395b7efaaa52aae170b
670,768
import torch def model_to(on_gpu, model): """Transfers model to cpu/gpu. Args: on_gpu (bool): Transfers model to gpu if True otherwise to cpu model (torch.nn.Module): PyTorch defined model. Returns: torch.nn.Module: The model after being moved to cpu/gpu. """ ...
c8731f84448cf6fccc387fe50b359e118cc2ce5e
670,773
def format_movie_year_min(pick_movie_year_min): """ Ensures that the minimum movie year is properly formatted (parameter is the minimum movie year) """ if bool(pick_movie_year_min) == True: movie_year_min = str(pick_movie_year_min) + "-01-01" else: movie_year_min = None retur...
5a97a1f059d5dfb445042ea0a31bb8aed6342a0f
670,775
def id_has_been_provided(entity_id): """ Simple function returning true or false if id has been provided. Created for readability purposes. """ return True if entity_id else False
51cfdf6f4d88d5ce7c38e5d4cdc066753155d4d7
670,776
def width0diameter(b, d): """Calculate rate width over diameter. :param b (float): impeller width [m] :param d (float): diameter [m] :return bd (float): width over diameter """ bd = b / d return bd
ace9712133f7b9b28f8fb755d57dc28fc4fc52ae
670,778
def remap_values(values, target_min=0.0, target_max=1.0, original_min=None, original_max=None): """ Maps a list of numbers from one domain to another. If you do not specify a target domain 0.0-1.0 will be used. Parameters ---------- val : list of int, list of long, list of float The val...
f9f9d2ceb02c1ac6e68330f8600dbc212105b7da
670,780
def match_gamma(value, gamma, gamma_mask): """Do a bitwise check of value with gamma using only the bits from gamma_mask""" return not (value & gamma_mask) ^ (gamma & gamma_mask)
16c1fda48964d7fc5a81b30081ddeb716869a7c6
670,781
def compare(song1, song2): """ Compares two songs and returns which is prefferec (1 or 2) or returns 0 if it's a tie. Numbers are returned as strings """ print("1:", song1.name, "by", song1.artist, "or,") print("2:", song2.name, "by", song2.artist, "?") # x is evaluated as a string and acts ...
fc2996b0e214b77932a540b89d2feacb276f5b0f
670,785
import json def json_recursive_size(data, level=0, maxlevel=None): """Get size of a JSON object recursively.""" ### HELPERS # how many levels remaining? remaining_levels = maxlevel - level if maxlevel is not None else None def length_now(d): """Get length of a json string.""" re...
3f95cbfe438a79b5ad22ba848dd29fc376563c04
670,793
import math def rspace_sum(rs, qs, basis, kappa, rlim): """ Real space part of the sum Parameters: rs -- list of particle positions qs -- list of particle charges basis -- real space basis kappa -- splitting parameter rlim -- size of lattice (one side of a cube of points...
28df62c94f5503386b1fa7b3557a9acee1404588
670,795
def findCompartment(rx, blocks, aR, aP, rR, metaboliteBlock): """ Derive information on compartment aspects of the reaction. Returns ------- 'type': String 'Transport','Exchange' or 'Normal' (kind of reaction). 'comp': compartment of SBML-model. arrow between compartments when reaction is 'Tran...
fe6efab25e6c69e745894dc39ca175d3b50a12e4
670,796
def revert_correct_V3SciYAngle(V3SciYAngle_deg): """Return corrected V3SciYAngle. Only correct if the original V3SciYAngle in [0,180) deg Parameters ---------- V3SciYAngle_deg : float angle in deg Returns ------- V3SciYAngle_deg : float Angle in deg """ if V3S...
2ef5e03bf249756fb04a05b28b04ca19bacd7cdd
670,798
def dynamic_range_compression(db, threshold, ratio, method='downward'): """ Execute dynamic range compression(https://en.wikipedia.org/wiki/Dynamic_range_compression) to dB. :param db: Decibel-scaled magnitudes :param threshold: Threshold dB :param ratio: Compression ratio. :param method: Downwa...
1c5434a4bda28959bfa4b71a594e2cf6fbd71b79
670,801
def fake_get_k8s_obj_always_successful(obj, _): """Mock of get_k8s_obj that always succeeds, returning the requested lightkube object""" return obj
e23bfafa535a45d785f8cd6c5b9097919ce7033d
670,807
def is_multiline(string: str) -> bool: """Check whether a string consists of multiple lines.""" return "\n" in string
22e79546aa2b9d5516a100c9b035bcf7e57ebb45
670,809
import requests def download_dff(url, path): """Downloads a missing DFF from the specified URL to a given FS path.""" resp = requests.get(url, stream=True) if resp.status_code != 200: print('DFF %s not found' % url) return False with open(path, 'wb') as fp: for chunk in resp.it...
d10e7983c1489446e5f337abf2c56f16b202fe39
670,814
import re def replace_fullwidth_alpha_numeral_to_halfwidth(text: str): """ Replace full-width alpha-numeral characters to half-width characters. Args: text (str): Text to replace. Returns: str: Replaced text. """ return re.sub(r'[A-Za-z0-9]', lambda mathobj: chr(ord(mathobj.g...
acf0d45e63a6595955c3da1d9f70424ea95c8d95
670,815
import math def qsub_format_memory(n): """Format memory in bytes for use in qsub resources.""" if n >= 10 * (1024 ** 3): return "%dGB" % math.ceil(n / (1024 ** 3)) if n >= 10 * (1024 ** 2): return "%dMB" % math.ceil(n / (1024 ** 2)) if n >= 10 * 1024: return "%dkB" % math.ceil(...
b0dc62c889b514382a7b5d97c4d9a85a1343f368
670,819
from typing import Tuple def get_mode(mode: str, line: str) -> Tuple[str, bool]: """Get the mode of the map. Args: mode (str): the current mode line (str): the line to check Returns: str, bool: the new mode, if the mode has changed """ if line == "" or line[0] == "#": ...
721d335ea1eaefbfc3f8a3ab60fb351d1b940674
670,820
def TAny(_): """Accepts any value. """ return True
bcecc3f3778004b81eac293c7a216d5726fa47d9
670,823
def argwhere_to_tuples(argwhere_array): """ Converts the output locations array of np.argwhere(...) to a list of tuples. :param argwhere_array: Output of np.argwhere(...). :return: List of tuples, each tuple representing one argwhere position. """ return [tuple(x) for x in argwhere_array]
231d1327c274d2d87186752db13170acddb59989
670,827
def get_future_suppression_from_r0(R0, scenario): """ Returns the future suppression level for a given R0 and a "future scenario". Parameters ---------- R0:float Reproduction number scenario: str 'no_intervention', 'flatten_the_curve', 'social_distancing'. Returns -----...
e30dd2e2e12fc44c78df5e2be492dfa4f52c55b5
670,829