content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def parse_variable_field(field, re_dict): """Function takes a MARC21 field and the Regex dictgroup and return a list of the subfields that match the Regex patterns. Parameters: field -- MARC21 field re_dict -- Regular Expression dictgroup """ output = [] if field is None or re_dict is N...
cffba9b15e7337b17eec03abc070cb760e8e16e9
681,360
import sys def _GetNominalBuildNumber(build_num, builds_list): """Verify the build number is in the available builds list. If the user-specified |build_num| is negative, then verify it is a valid ordinal index, and get the nominal build number for that index. If it is positive, then verify the nominal build ...
7ddf0433389a7b8aa02d64538add088d215b8703
681,361
from pathlib import Path from textwrap import dedent def _commands(fds_file: Path) -> str: """Return the commands for PBS job scheduler.""" return dedent( f""" # run fds in parallel mpiexec -np $MPI_NP fds_mpi {fds_file.name} """.rstrip() )
d1dfb5bce9b68591e64b6b027499b00728a6a0c4
681,362
import re import os def get_trailing_number(s): """ Search for a termination of a file name that has the ".csv" extension and that has a number at the end. It gives the number at the end of the file. This number can have any amount of digits. Example: x = get_trailing_number("my/path/to/file/any_4...
f91d6a1ecd2626cc2ada482c2c696d98a7341c95
681,364
def is_private(attribute): """Return whether an attribute is private.""" return attribute.startswith("_")
b278f67248bb6c5f1fe9080da25d342c912181d5
681,365
import re def single_line_conversion(line): """ converts a single line typedef to a using statement, preserving whitespace """ components = re.split('\s', line) name = components[-1][:-1] #last item, drop the trailing space typedef_index = 0 for c in components: if c == 'typedef': break typ...
d581d3957f16fce20e1f676c2c5fcb223d5ee392
681,366
import random import string def random_lc_alphanumeric_string(length): """Return random lowercase alphanumeric string of specified length.""" return ''.join(random.choice(string.ascii_lowercase + string.digits) for ii in range(length))
bdcf760a9e99a5d6de6fcaacc1e50e86df6956d8
681,367
def _atoms_formatter(molrec, geom, atom_format, ghost_format, width, prec, sp, xyze=False): """Format a list of strings, one per atom from `molrec`.""" nat = geom.shape[0] fxyz = """{:>{width}.{prec}f}""" sp = """{:{sp}}""".format("", sp=sp) atoms = [] for iat in range(nat): atom = [] ...
55f7491998cad0ee7e6c53a2614853f8e86831e4
681,368
def neg_pt(pt, curve): """Negate a point. Args: pt (tuple(int, int)): Point (x, y). Use (None, None) for point at infinity. curve (tuple(int, int, int)): (a, b, n) representing the Elliptic Curve y**2 = x**3 + a*x + b (mod n). Returns: tuple(int, int): Point -pt. ""...
82b7f32bff979de7b0fe390b98b82f6d9343b028
681,369
import json def json_to_dict(file_json): """Create dictionary from json file.""" with open(file_json) as infile: mydict = json.load(infile) return mydict
20ba6b79638663e80b968b2d8143d3d38e37fb70
681,371
import os def listPortNames(): """ Returns the available port names in the project. Ports are directories inside the 'root/port/' directory (if available). Port names are the name of those directories. Returns: - list of port name strings (if available). - None if port dir is not available or if not any port...
51975536b4e1c3ef77f4c652e7c1fcfa77b9288f
681,372
import sqlite3 def summary_data(db): """Quick overview of what's in a database. db - string, file name of the SQLite database to examine. """ summary = {} tables = ['Source', 'Messages', 'Report', 'Request', 'Network', 'Station', 'Summary', 'User', 'UserIP', 'Volume'] con = sq...
cb43660e574e532a19439ba1b70842e837629e32
681,373
import click def get_help_msg(command): """get help message for a Click command""" with click.Context(command) as ctx: return command.get_help(ctx)
ee4df236bf88b0e46d1fb2942d1c45697948335e
681,374
def marker_delay(session, Type='Real64', RepCap='', AttrID=1150061, buffsize=0, action=['Get', '']): """[Marker Delay] """ return session, Type, RepCap, AttrID, buffsize, action
4d1d4da634d4746fbf58551aca02dd0a10d23a98
681,375
def crop(im, size): """ Crops an image in the center. Parameters ---------- size : tuple, (height, width) Finally size after cropping. """ diff = [im.shape[index] - size[index] for index in (0, 1)] im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 + size[1]] re...
4b6b95c820eeb22c6af44a66a2e3f28fa99e48b5
681,377
def flatten_bands(bands): """ Flatten the bands such that they have dimension 2. """ flattened_bands = bands.clone() bands_array = bands.get_bands() flattened_bands.set_bands(bands_array.reshape(bands_array.shape[-2:])) return flattened_bands
72de24d604feccc8c9b5dca3b0dec391f662610a
681,378
import time def speedtest(func, *args, **kwargs): """ Test the speed of a function. """ n = 100 start = time.time() i = 0 while i < n: i += 1 func(*args, **kwargs) end = time.time() return (end - start) / n
8f7913babe40f5495d10022726f81e7419687e0c
681,379
from datetime import datetime def get_time(): """ readable timestamp in seconds. """ return int(datetime.now().strftime('%Y%m%d%H%M%S'))
30d135eb70567b5a7f48105edd192a108fb5ee62
681,380
def dict_of_branch_relays(relays, branches): """ Create dictionaries of the relay keys from the branch elements """ branch_relays = {k: list() for k in branches.keys()} for relay_name, relay in relays.items(): branch_relay_mappings = relay['branch'] if branch_relay_mappings: ...
b051ca8603d89dbd8b0a458dae63e1f556435ce6
681,381
import re def strip_suffix(raw_token, normaliser): """ THIS IS NAMED WRONG A lot of tokens have an inflected suffix that acts as either a preposition or article. This rule strips the suffix to see if the root token is in the lexicon. If it is the original token is returned. """ suffix...
f256f0c8ae9aab5e288d5ac56961103bfe5fc7cf
681,382
def wit_response(): """Example response from the wit client.""" return {'entities': {'intent': [{'value': 'test_intent'}]}}
b34ccb3437c5a6d5ca7468f66c338403bc680b66
681,383
def check_same_keys(d1, d2): """Check if dictionaries have same keys or not. Args: d1: The first dict. d2: The second dict. Raises: ValueError if both keys do not match. """ if d1.keys() == d2.keys(): return True raise ValueError("Keys for both the dictionaries ...
c989955e2051feb633a249670824e9ebf44a9415
681,384
import re def _MarkOptional(usage): """Returns usage enclosed in [...] if it hasn't already been enclosed.""" # If the leading bracket matches the trailing bracket its already marked. if re.match(r'^\[[^][]*(\[[^][]*\])*[^][]*\]$', usage): return usage return '[{}]'.format(usage)
ea1d896c36a173383f202d6cb04fb416b69eea36
681,385
def keep_type(adata, nodes, target, k_cluster): """Select cells of targeted type Args: adata (Anndata): Anndata object. nodes (list): Indexes for cells target (str): Cluster name. k_cluster (str): Cluster key in adata.obs dataframe Returns: list: Selected cells....
48aab391193c61867dea8be3a5afb7b93106bd09
681,386
from datetime import datetime def ticks_from_datetime(dt: datetime): """Convert datetime to .Net ticks""" if type(dt) is not datetime: raise TypeError('dt must be a datetime object') return (dt - datetime(1, 1, 1)).total_seconds() * 10000000
352b8624a4eae13dcdf5a40a1c7d57878fdeb636
681,387
import toml def toml_files(tmp_path): """Generate TOML config files for testing.""" def gen_toml_files(files={'test.toml': {'sec': {'key': 'val'}}}): f_path = None for name, config in files.items(): f_path = tmp_path / name with open(f_path, 'w') as f: ...
0548979d2c8c23e618b530acee3789c0893622eb
681,388
import csv def readCSV(filename): """ Reads the .data file and creates a list of the rows Input filename - string - filename of the input data file Output data - list containing all rows of the csv as elements """ data = [] with open(filename, 'rt', encoding='utf8') ...
65eb44a9900babeae09af340880a96f35eb9e25c
681,389
def _process_all_blocks(dataset): """ for all voxels, run chain in all blocks to update """ chain_outputs = {} voxel = dataset.all_voxels for key in list(dataset.blocks.keys()): if key == 'spectral': key = 'spectral' block = dataset.blocks[key] tmp =...
a9163fe577f7afb73eee3d772bcc5baa074c31c1
681,390
import re def is_phone_number(text,format=1): """ Checks if the given text is a phone number * The phone must be for default in format (000)0000000, but it can be changed Args: text (str): The text to match (optional) format (int): The number of the phone format that you want to check...
22cd24c9618e11cc8ad8ad98854a218ae8c523dd
681,391
def hamming_weight(x): """ Per stackoverflow.com/questions/407587/python-set-bits-count-popcount It is succint and describes exactly what we are doing. """ return bin(x).count('1')
eaa2721c060d1e3b1075d8037997ae48906ba22a
681,392
import torch def angles_to_matrix(angles): """Compute the rotation matrix from euler angles for a mini-batch. This is a PyTorch implementation computed by myself for calculating R = Rz(inp) Rx(ele - pi/2) Rz(-azi) For the original numpy implementation in StarMap, you can refer to: https://git...
bf3716b6489b8979a97856b17c29bf33ca0c5362
681,393
def _is_pronoun (mention) : """Check if a mention is pronoun""" components=mention.split() if components[1]=="PRON" : return True return False
d21cb3309e9e736a90cd706acb8d6f87ceea5114
681,394
import sys def fix_encoding(query): """ Encoding fixes for Python 2 and Python 3 cross-compatibilty. """ if sys.version_info > (3, 0): return query else: return query.encode("utf-8")
64f047ba03f0a9984020b59594190f9a7cf576a0
681,395
def method_with_unused_param(unused_input): """Provide and unused param.""" return 5
15d3630df8e6eda156cf0bc9b828e57278e47316
681,396
def email_footer(): """ Footer for the email. e.g. for privacy policy, link to update profile, etc. """ footer = "" return footer
dd31eaed01dbb34e2a00bc5892edbcab6152c289
681,397
import ast def quick_parse(line, *args, **kwargs): """ quick way to generate nodes """ if args or kwargs: line = line.format(*args, **kwargs) body = ast.parse(line).body if len(body) > 1: raise Exception("quick_parse only works with single lines of code") code = body[0] return ...
2230f523550d9d6f667ed305d888afaa8c142e9b
681,398
import os def NewStyle(name): """ -> Novos Styles :param name: Nome do novo estilos :return: Status do estilo """ def MontStyle(): """ -> Montar o Novo Style :return: Dicionario com os comandos e styles """ style = {} style['bg'] = str(input("Cor...
32794bee8f261fb3402e03f2319265ac79a07b29
681,399
def swap_clips(from_clip, to_clip, to_clip_name, to_in_frame, to_out_frame): """ Swaping clips on timeline in timelineItem It will add take and activate it to the frame range which is inputted Args: from_clip (resolve.mediaPoolItem) to_clip (resolve.mediaPoolItem) to_clip_name ...
0428b386b21cb87ba70c5e1ed31c37e7eaa3a6d7
681,400
import os import subprocess def _run_blastp(db1, db2, out, evalue, threads, force): """ Runs BLASTP between two organisms Parameters ---------- db1 : str Path to protein FASTA file for organism 1 db2 : str Path to protein FASTA file for organism 2 out : str Path fo...
62a8bd4429e8182f99a1159fb209626642581055
681,401
from bs4 import BeautifulSoup def strip_html_tags(text): """remove html tags from text""" soup = BeautifulSoup(text, "html.parser") stripped_text = soup.get_text(separator=" ") return stripped_text
cf5df73d168fbff37b128c0f6ee562d8c5767aa3
681,402
def generate_lawnmower(xmin, xmax, ymin, ymax, winds): """Generates a horizontal lawnmower path on the list """ current = [xmin, ymin] ystep = (ymax - ymin) / (2 * winds) path = [] path.append(current) for i in range(winds): path.append([xmax, current[1]]) path.append([xmax, curr...
31acae4dc76bc87679c4443d7ea355dc6e4bc62c
681,403
def _price_dish(dish): """ Computes the final price for ordering the given dish, taking into account the requested quantity and options. Args: dish (dict): KB entry for a dish, augmented with quantity and options information. Returns: float: Total price for ordering the requested q...
1ab29262540a8f875d60efa087ff9bf179bd74f5
681,404
import unicodedata def get_character_names(characters, verbose=False): """Print the unicode name of a list/set/string of characters. Args: characters (list/set/string): a list, string or set of characters. verbose (bool): if set to True, the output will be printed Returns: (dict)...
7c31ea49e8f03260185df7f308b9d6bd39ba6952
681,405
import time def parse_time(epoch_time): """Convert epoch time in milliseconds to [year, month, day, hour, minute, second]""" date = time.strftime('%Y-%m-%d-%H-%M-%S', time.gmtime(epoch_time/1000)) return [int(i) for i in date.split('-')]
1c7f1b14cd672b5c98497f9eeee9fcbf3dc3f72e
681,406
import typing import math def isanan(value: typing.Any) -> bool: """Detect if value is NaN.""" return isinstance(value, float) and math.isnan(value)
511389c909b48c4da5506b1bd9c222884814c77b
681,408
def fix_public_key(str_key): """eBay public keys are delivered in the format: -----BEGIN PUBLIC KEY-----key-----END PUBLIC KEY----- which is missing critical newlines around the key for ecdsa to process it. This adds those newlines and converts to bytes. """ return ( str_key ...
92bd730b103e9f32f716e71c66157797900b556f
681,409
def add_self_loop(edges, n_node): """Adds self loop.""" self_loop_edges = {(s, s) for s in range(n_node)} return edges.union(self_loop_edges)
fd6a1c845796f6a0c83b3e772812c088dbf0cea6
681,411
def _error_string(error, k=None): """String representation of SBMLError. Parameters ---------- error : libsbml.SBMLError k : index of error Returns ------- string representation of error """ package = error.getPackage() if package == "": package = "core" templa...
7555a481b8fd066239b7f6dfaaf332f859129855
681,413
def powmod(x, k, MOD): """ fast exponentiation x^k % MOD """ p = 1 if k == 0: return p if k == 1: return x while k != 0: if k % 2 == 1: p = (p * x) % MOD x = (x * x) % MOD k //= 2 return p
1112facd546858d0b9f793b90bf498a9e16e42d4
681,414
def remove_trail_idx(param): """Remove the trailing integer from a parameter.""" return "_".join(param.split("_")[:-1])
e3bbc8e51d90a5db6c718cee8f521afc9eaffee1
681,415
def keys(self): """Return xoutput_dict keys to behave like a dict""" return self.xoutput_dict.keys()
c85f7e11cd9946ecc3cf102becb180838a9aff2d
681,417
from typing import Optional from typing import Tuple from typing import Dict from typing import Union def _make_query( *, q: Optional[str] = None, interval: Optional[int] = None, start: Optional[str] = None, end: Optional[str] = None, table: Optional[str] = None, columns: Optional[Tuple[st...
da4dcef77da2242b77d226a688db3e096dee9e25
681,418
import re def get_qdyn_compiler(configure_log): """Return the name the Fortran compiler that QDYN was compiled with""" with open(configure_log) as in_fh: for line in in_fh: if line.startswith("FC"): m = re.search(r'FC\s*:\s*(.*)', line) if m: ...
71e0b9e448664a3a5df11587d63574cef22e0511
681,419
from typing import Tuple import subprocess def run_command(cmd: str) -> Tuple[int, str]: """ Execute given cmd param as shell command. :param cmd: shell command as string. :return: Return exit code and standard outpur of given cmd. """ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, s...
06b65ff2137322bb9d25394cf1dbc118b96919eb
681,421
import os import tempfile def get_data_dir(): """Get the DeepChem data directory.""" if 'DEEPCHEM_DATA_DIR' in os.environ: return os.environ['DEEPCHEM_DATA_DIR'] return tempfile.gettempdir()
f9d8e906d47305f34ae596c0e4e1339b8cf71caa
681,422
import pprint def determine_csv(channels, current_channel): """ params channels: list of dictionaries of channels current_channel: searched channel name """ pprint.pprint(channels) pprint.pprint(current_channel) result = [] for channel in channels: if str(channel['name']) =...
4ef68ee85e33b6a8a9adbb75ae827d06bdf7320c
681,423
import os def command_found(cmd='qsub'): """ Return True if the command was found.""" if True in [os.path.isfile(os.path.join(path, cmd)) and os.access(os.path.join(path, cmd), os.X_OK) for path in os.environ["PATH"].split(os.pathsep)]: return True return False
d60e88fb4dea7cbf4ca71490f37a118433b4e13b
681,424
def git_initial_branch_name() -> str: """ Provides the name of the initial branch to use. Note: This is only currently used to proved the old "master" branch name for forward compatibility. All the plumbing is in place to use this, but as of now it cannot be assumed that git >= 2.28.0 i...
252abcc1e50180404e10089337178fd39671921e
681,425
import os def find_all_files_in_dir_nr(directory): """ Finds all files (non-directories) in a directory. This function is not recursive. """ files = os.listdir(directory) # append base dir files = list(map(lambda x: os.path.join(directory, x), files)) # make sure each path is a file (and not a directory) f...
4d89db4f87fee30b9ef128f88aab6851831a9a69
681,426
import pathlib import json def _load_magic_map(path: pathlib.Path): """On loading, we need to change from div_str: [magic, pow] to (magic, pow) : div""" with path.open('r') as f: reverted_magic_map = json.load(f) magic_map = {} for divisor_str, magic_tuple_list in reverted_magic_map.items(): ...
a83a450319350b5c977829ec73fe1c475776042d
681,427
import argparse def parse_args(): """Parse arguments and return the path to the config file.""" parser = argparse.ArgumentParser(description=""" Automatically backup or restore personal files from the system. \n Full documentation at https://github.com/ZAdamMac/Tapestry/blob/master/DOCUMENTAT...
cb06af1b909336a377c3412b2039d400bf484135
681,428
def observations_da_1d(observations_ds_1d): """Historical timeseries from observations matching `hind_da_initialized_1d` and `hind_da_uninitialized_1d` mean removed xr.DataArray.""" return observations_ds_1d["SST"]
c7fa2ae5a829360495ed81632e3b5be5be2040c5
681,429
import logging def setup_formatter() -> logging.Formatter: """Setting up a custom formatter.""" return logging.Formatter( fmt="%(levelname)s -> [%(asctime)s][%(name)s|%(module)s] %(message)s" )
62708e5b3b413b8f2d3305a6aa3f0441d57a1a12
681,430
import subprocess import json def conda_env(): """Capture information about the conda environment this is being run in Returns ------- dict : A dictionary representing the packages installed """ data = subprocess.check_output(["conda", "list", "--json"]) try: j_data = jso...
e395a698f4b5e918bde8523baa3e1a6c3833e725
681,432
import csv def extract_sigma_flen(fpath): """ :return: """ sigma, mu, auc = 0, 0, 0 with open(fpath, 'r', newline='') as datfile: rows = csv.DictReader(datfile, delimiter='\t') for r in rows: if float(r['auc']) > auc: auc = float(r['auc']) ...
df0ee7d570bd1825fc024b02d8f7cb18c11709ae
681,433
import uuid def make_salt(): """ Generate a random salt A hex-encoded random UUID has plenty of entropy to be secure enough for our needs. """ return uuid.uuid4().hex
d3ef6568a767a6405a5bf557e8a8d42b543d969b
681,434
import re def is_ipv4(ip): """Checks if the ip address is a valid ipv4 address including CIDR mask.""" regex = r'^(\d+)[.](\d+)[.](\d+)[.](\d+)[/](\d+)$' pattern = re.compile(regex) return pattern.search(ip) is not None
34bfb4cc42dac255c1fab40fb34b6d9147b344c5
681,435
import requests def teach_tag_by_file(teach_url, tag, file_path): """Teach tagbox a single tag using a single file.""" file_name = file_path.split("/")[-1] file = {'file': open(file_path, 'rb')} data = {'tag': tag, "id": file_name} response = requests.post(teach_url, files=file, data=data) i...
05d15709e2883296a204d60e8b5aa50eac071470
681,436
import torch def get_observation_with_learnt_rho(x, gp_varproxi, cv_function, gamma): """ :param x: :param gp_varproxi: :param cv_function: :param gamma: :return: """ ys = cv_function(x.detach()) rhos = torch.cat([torch.clamp(gp_varproxi.posterior(x).mean.detach(), min=0.02)] * ys...
ef1745a76ad9217f463e9f3a5e0e71f3355e9686
681,437
def analyze_inputs(input_names, element_inputs): """ Get decoded names from the input_names (list) and the template element_inputs (odict). The output is a dict, with keys from element_inputs and values are picked with corresponding order from input_names. If element_inputs contains both 'name' ...
d9313dc7808ca780da9155665d25208073ef2d0b
681,438
def get_categories_info(categories_id, doc): """Get object name from category id """ for cate_infor in doc['categories']: if categories_id == cate_infor['id']: return cate_infor['name'] return None
bb43023542d9ea281546eac636e0aa1c9ce85388
681,439
def is_unique_corr(x): """Check that ``x`` has no duplicate elements. Args: x (list): elements to be compared. Returns: bool: True if ``x`` has duplicate elements, otherwise False """ return len(set(x)) == len(x)
a8044b71e8879fe2c4e573b337cbe0cd2b75cc5c
681,440
def getImageLink(url, img_url, caption): """ Converts a URL to a Markdown image link. """ return "[![{caption}]({img_url} =16x16)]({url})".format( caption=caption, img_url=img_url, url=url )
f92e49e082cd9eadfcd4f1ab734cd02fabf13d5e
681,441
def get_chars_from_guesses(guesses): """ gets characters from guesses (removes underscores), removes duplicates and sorts them in an array which is returned. example guess: "__cr_" """ guesses_copy = guesses.copy() guesses_copy = "".join(guesses_copy) return sorted("".join(set(guesses_copy.r...
b933795f41e9a9935ba110be4591f7e1b8ac7867
681,442
def getParameter(infile): """ get parameter from input file : param infile: an input file containing desired parameter """ with open(infile) as f: line = f.readline() line = line.strip().split() # the first element is the parameter return line[0]
de1a647b408b9bd298a14b0a35c979d8aaabfc32
681,443
def computeAbsPercentageError(true, predicted): """ :param true: ground truth value :param predicted: predicted value :return: absolute percentage error """ return abs((true - predicted) / true) * 100
faf1aa979186ec50b418beedb6b65aaa3eef642f
681,444
def lines(a, b): """Return lines in both a and b""" l1 = a.splitlines() l2 = b.splitlines() s1 = set(l1) s2 = set(l2) l = [i for i in s1 if i in s2] return l
e2193d755c8b4f437fb433ab68ea70702f05f863
681,445
def str_to_wlist(s, par_open = '(', par_close = ')'): """Converts a string to a list of words, where words are delimited by whitespaces.""" return s.replace(par_open, ' '+par_open+' ').replace(par_close, ' '+par_close+' ').split()
9da4e8070869be5490e316461a2c823ccc398ca7
681,446
def cbs_amplicon(seg_df, min_cn = 5): """get amplicon from cbs segmentation results """ return seg_df[seg_df.CN >= min_cn]
5d6a77b03344a8682319ae6487aec8358fab651c
681,447
import pandas as pd def _length_and_sr_of_wavs(z): """A dataframe containing information about the wavfiles of the files in the wfsr store Note: Don't depend on this yet -- it's in motion. """ def gen(): for k, (wf, sr) in z.items(): yield {'file': k, 'n_samples': len(wf), 'sr': s...
411e18144fadde07574db7c385f10be65a8495e8
681,448
def check_campus(department_name, department_dict, val): """ Returns the campus/college the given 'department_name' is in depending on the value of the 'val' parameter @params 'department_name': The full name of the department to search for 'department_dict': The dictionary of departm...
b1deedb4be6ad3781ed8d63408af342937977eb6
681,449
def getCharacterFromGame(gtitle: str) -> str: """Return a query to get characters with lower Ryu Number to a game. The query will retrieve the name and Ryu Number of a character whose Ryu Number is exactly one less than the Ryu Number of the game whose title is passed. This is used primarily for p...
299919a60e1d9a24c67d1efd200e9f2f804c2309
681,450
import subprocess def dirsize(dirpath): """Get directory size via ``du`` (`os.stat` is accurate).""" output = subprocess.check_output( ['du', '-k', dirpath]).decode('utf-8').strip() # first field of last line is size in KiB. Return size in bytes return int(output.split('\n')[-1].split()[0].str...
0f3758805be76472a503c0de4902e1b228417b23
681,451
def get_both_marks(course_record, course_code): """(str, str) -> str Return a string of coursemark and exammark if the course record matches with the course code. >>>get_both_marks('MAT,90,94', 'MAT') '90 94' >>>get_both_marks('MAT,90,94', 'ENG') '' """ if course_code in course...
790d92c8af7aaa9ba7370a98f629a34508bb788d
681,452
import os def _get_libdir(arch: int, root: str = '/') -> str: """Get the libdir corresponding to a binary class :param arch: Binary class (e.g. :data:`32` or :data:`64`) :param root: Directory where libdirs are searched :return: Libdir in the initramfs """ if arch == 64 and os.path.exists(roo...
0f51516ac4c99724a7294335ab41df2a67331ef7
681,453
import sys def get_songbird_params(p_diff_models: str, diff_dict: dict) -> dict: """ Get the parameters for songbird passed by the user. :param p_diff_models: file containing the parameters. :param diff_dict: parsed content of the file containing the parameters. :return: parameters. """ pa...
a4f3bc763ecf7a5f3cd604047445786c445e968c
681,454
def is_if(t): """Whether t is of the form if P then x else y.""" return t.is_comb("IF", 3)
f183e3a391bd7faabab0fc4473a8e895acd2e32a
681,455
def blit(destination, sprite, upper_left, layer=False, check=False): """ Blits one multidimensional array into another numpy array. """ lower_right = [ ((a + b) if ((a + b) < c) else c) for a, b, c in zip(upper_left, sprite.shape, destination.shape) ] if min(lower_right) < 0: ...
e912dc552644b8dbb49b0d24e4835e8915135821
681,456
def get_volume(module, system): """Return Volume or None""" try: try: volume = system.volumes.get(name=module.params['name']) except KeyError: volume = system.volumes.get(name=module.params['volume']) return volume except Exception: return None
d2c810c8f567c7d9e0ff967f72d3bfda0895cfe9
681,457
from typing import Union def pixel(value: Union[int, str]) -> str: """Support pure number input of the size.""" if isinstance(value, str): return value return f"{value}pt"
9d95b95f89cbf776c8ba0aa8a4b2f5dcedce5902
681,458
import json import re def dump_json(template): """ Returns template as normalized JSON string :param template: json string """ jstr = json.dumps(template, indent=2, sort_keys=True) # Common function jstr = re.sub(r'{\s*("Fn::GetAtt")\s*:\s*\[\s*("\S+")\s*,\s*("\S+")\s*\]\s*}', ...
0d6f7e5683f843ef18a58c02d630af0a08f2cdc2
681,459
def filled_grasp_field(filled_grasp_grid): """Return a GraspField instance from the filled_grasp_grid fixture""" return filled_grasp_grid.fields[0]
7225010072621bb87ec1cf838559c02272cb87f1
681,460
def mean_of_columns(mat): """Returns 1-row matrix representing means of corresponding columns """ return mat.mean(axis=0)
aaaf7ab5ce45d21ec4f0b03d311713117823315b
681,461
import os def get_ssm_variable_prefix() -> str: """ Use info from local environment to assemble necessary prefix for environment variables stored in the SSM param store under $DSS_DEPLOYMENT_STAGE/environment """ store_name = os.environ["DSS_PARAMETER_STORE"] stage_name = os.environ["DSS_DEPLO...
e5b4c3a631a26cd8c34fbe173c39f71222735665
681,462
def miniMaxSum(arr): """ find the minimum and maximum values that can be calculated by summing exactly four of the five integers """ arr = sorted(arr) return sum(arr[:-1]), sum(arr[1:])
34207a5f24a8486b037572aaef3f0a8d00017444
681,463
def wrap_xml(self, xml, encoding='utf-8', standalone='no'): """ Method that provides a standard svg header string for a file """ header = u'''<?xml version="1.0" encoding="%s" standalone="%s"?>''' % (encoding, standalone) header = header.encode("utf-8") return header + xml
87490ba4605697f6a2f752c4f79e16cbb4faf98a
681,464
import logging def collect_data(**kwargs): """ Ideally, a function that defines how data should be collected for training and prediction. In the real world, of course, there are often differences in data sources between training (data warehouse) and prediction (production application databas...
e0a003bdf3f96b824d3175b5e5cda6ef4c74a6df
681,465
import random def random_f32(): """ Returns [0.0, 1.0) >>> random_f32() < 1.0 True """ return float(random.random())
6479cd3eddca3a8e58049a6543a14e3163a5dd36
681,466
def get_buckets_keys_count(store): """ return dict: buckets -> count """ st = {} try: for line in (store.get('@') or '').split('\n'): if line: d, _, c = line.split(' ') if not d.endswith('/'): continue st[int(d[0], 16)] ...
a8734780f5eec469558ab751dae81c76a8ff05e4
681,467
def normalize_response(response): """ Transform response so that 'off' == 'away' """ if response == 'away': return 'off' else: return response
2e03465059bf4adcbb59c3f2dcd0caa3f83f8771
681,468