content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def read_file(file, delimiter): """Reads data from a file, separated via delimiter Args: file: Path to file. delimiter: Data value separator, similar to using CSV. Returns: An array of dict records. """ f = open(file, 'r') lines = f.readlines() records = [] for line in lines: ...
d686ef236195638a3e1c6c71823c40ad3a72ccac
681,252
import csv def readAIAresponse(csvFile): """Obtains the SDO/AIA responses from a .csv file. Parameters ---------- csvFile : str The .csv file with the SDO/AIA responses in it. First line should be labels for each column as a comma seperated string, e.g. row1=['logt, A94, A171']. ...
aa45e64ff945d3c2947012a0be1988a1c2c8d833
681,256
def get_pickle_file_path(file_name, target, folder): """ Returns a path to a saved file Parameters ---------- file_name: str name of the saved file target: str name of target column folder: str name of the folder file is saved in Returns ------- path to ...
e71925a50f8d637d83b620b202ad63e8e4ff7b0f
681,260
def model_zero(x, k, y0, y1): """ One-compartment first-order exponential decay model :param x: float time :param k: float rate constant :param y0: float initial value :param y1: float plateau value :return: value at time point """ return y0 - (k * x)
0a2a82d3531568ccc3ea1c3b4fb4c7897e56fcbd
681,263
def concatenate_codelines(codelines): """ Compresses a list of strings into one string. """ codeline = "" for l in codelines: codeline = codeline + l return codeline
4780c947aba149893d10cafc25c704596f9909e2
681,266
from typing import Any def to_pipeline_params(params: dict[str, Any], step_prefix: str): """Rename estimator parameters to be usable an a pipeline. See https://scikit-learn.org/stable/modules/compose.html#pipeline. """ return {"{0}__{1}".format(step_prefix, key): value for key, value in params.items(...
4bd5fef01d23a2da79f8182ae30bebbef3ca2e88
681,268
def toutf8(ustr): """Return UTF-8 `str` from unicode @ustr This is to use the same error handling etc everywhere if ustr is `str`, just return it """ if isinstance(ustr, str): return ustr return ustr.encode("UTF-8")
e4fda18058cd34da13e7884761004082f95b3087
681,269
def RemoveUppercase(word): """Remove the uppercase letters from a word""" return word.lower()
dddf1792f16e3dbcbb310ac9c6456031aefeb11f
681,272
def plural(count=0): """Return plural extension for provided count.""" ret = 's' if count == 1: ret = '' return ret
45fcf037d4727483e09723367180c717efe526a4
681,273
def degreeDays(dd0, T, Tbase, doy): """ Calculates degree-day sum from the current mean Tair. INPUT: dd0 - previous degree-day sum (degC) T - daily mean temperature (degC) Tbase - base temperature at which accumulation starts (degC) doy - day of year 1...366 (integer) OUT...
db7eb093656373b8f4f4cdba7cebdee1e5092e8d
681,275
def obj_to_dict(obj, *args, _build=True, _module=None, _name=None, _submodule=None, **kwargs): """Encodes an object in a dictionary for serialization. Args: obj: The object to encode in the dictionary. Other parameters: _build (bool): Whether the object is to be built on de...
a5881d0d65fb43c43109efb8c5313e04c791eb9e
681,276
def identity(x): """x -> x As a predicate, this function is useless, but it provides a useful/correct default. >>> identity(('apple', 'banana', 'cherry')) ('apple', 'banana', 'cherry') """ return x
041ae6204b56fbbe90df0cb974db1f277d2e854b
681,280
def epoch2checkpoint(_epoch: int) -> str: """ Args: _epoch: e.g. 2 Returns: _checkpoint_name: e.g. 'epoch=2.ckpt' """ return f"epoch={_epoch}.ckpt"
8111d952dac9a356cf14846a88d2c87721ff8b50
681,282
def ED(first, second): """ Returns the edit distance between the strings first and second.""" if first == '': return len(second) elif second == '': return len(first) elif first[0] == second[0]: return ED(first[1:], second[1:]) else: substitution = 1 + ED(first[1:], se...
e0b8e1c6538ab5cc96266c9638dd1da7f33a7a39
681,286
def remove_slash(path: str) -> str: """Remove slash in the end of path if present. Args: path (str): Path. Returns: str: Path without slash. """ if path[-1] == "/": path = path[:-1] return path
d714454d17d05ea842b6f1b88fe7e5d65bd1de15
681,289
def chk_chng(src_flist,dst_flist): """ Returns unchanged file list and changed file list Accepts source file list and dsetination file list""" uc_flist = [] c_flist = [] for files in src_flist: if files in dst_flist: uc_flist.append(files) else: c_flist.ap...
99c21b204ea5145edd81dc88aadb279cdaa643c8
681,292
def cnn_estimate(inputs, network, est_fn): """ Estimated labelf by the trained cnn network Inputs ====== inputs: np.ndarray The test dataset network: lasagne.layers The trained cnn network Output ====== label_est: np.ndarray The estimated labels """ ...
0c1f66ed6746d216e7fe180fed660580b55b8db2
681,293
def _can_append_long_entry(e, f): """True if f is a FATDirEntry that can follow e. For f to follow e, f and e must have the same checksum, and f's ordinal must be one less than e""" return ( f.LDIR_Chksum == e.LDIR_Chksum and f.long_name_ordinal() + 1 == e.long_name_ordinal() )
caf73ddda8b7d4dff02e0fdf14d6a10c22098185
681,302
def get_declared_licenses(license_object): """ Return a list of declared licenses, either strings or dicts. """ if not license_object: return [] if isinstance(license_object, str): # current, up to date form return [license_object] declared_licenses = [] if isinstan...
bd466497097d55ef6348650683819b6432f8454e
681,303
import math def to_acres(km2): """ square KM to acres """ if math.isnan(km2): return 0 return round(km2 * 247.11)
cb59770998d88b95a98f02b6cd2a976c27513036
681,305
def extract_transcript_sequences(bed_dic, seq_dic, ext_lr=False, full_hits_only=False): """ Given a dictionary with bed regions (region ID -> BED row) and a sequence dictionary (Sequence ID -> sequence), extract the BED region sequences a...
bb81e0ff820ac4de762213358a783d1174152ee2
681,310
import random def getRandomColor(colorsList): """Returns a random color from <colorsList> or OFF""" if len(colorsList) > 0: return colorsList[random.randint(0, len(colorsList)-1)] return 0, 0, 0
71ffb37f96281ee0978367ec983893dc9749d797
681,313
from typing import Union def uri_from_details(namespace: str, load_name: str, version: Union[str, int], delimiter='/') -> str: """ Build a labware URI from its details. A labware URI is a string that uniquely specifies a labware definition. :returns str: The URI...
5cf688704116d9f2d14cbe25fc455b4454fe96b8
681,316
def npm_download_url(namespace, name, version, registry='https://registry.npmjs.org'): """ Return an npm package tarball download URL given a namespace, name, version and a base registry URL. For example: >>> expected = 'https://registry.npmjs.org/@invisionag/eslint-config-ivx/-/eslint-config-ivx-0...
6adcf8728b37f59de7b03b8fa5d8de3bd3bc712b
681,317
import bisect def find_le(a, x): """Find the rightmost value of A which is less than or equal to X.""" i = bisect.bisect_right(a, x) if i: return a[i-1] return None
20a1b85908771d7eb2cb7398e22f899242b5c347
681,322
def get_status_color(status): """Return (markup) color for test result status.""" colormap = {"passed": {"green": True, "bold": True}, "failed": {"red": True, "bold": True}, "blocked": {"blue": True, "bold": True}, "skipped": {"yellow": True, "bold": True}} r...
c0c23ab6c37202fd78c4ddfe66226077bbb9ad1e
681,329
def date_month(date): """Find the month from the given date.""" return date.month
2473c70e38de923074a3534f8320b3df5689fc3d
681,331
def packages(package_helper): """Return the list of specified packages (i.e. packages explicitely installed excluding dependencies)""" return package_helper.specified_packages()
7b6ed3eb4180dcd88d1ace52db3015571e58f623
681,332
def _kron(vec0,vec1): """ Calculates the tensor product of two vectors. """ new_vec = [] for amp0 in vec0: for amp1 in vec1: new_vec.append(amp0*amp1) return new_vec
491ec6539a5352c1a744b1b856b4e1412755f4fc
681,336
def get_container_name(framework): """Translate the framework into the docker container name.""" return 'baseline-{}'.format({ 'tensorflow': 'tf', 'pytorch': 'pyt', 'dynet': 'dy' }[framework])
172dfb49d25646aa1253bc257db5bc712c1229e9
681,340
def _merge_temporal_interval(temporal_interval_list): """ Merge the temporal intervals in the input temporal interval list. This is for situations when different actions have overlap temporal interval. e.g if the input temporal interval list is [(1.0, 3.0), (2.0, 4.0)], then [(1.0, 4.0)] will be returne...
1d7db003ed068b02f14fb9ef02b051044ab75d11
681,341
def datetimeToReadable(d, tz): """Returns datetime as string in format %H:%M %m/%d/%Y %d datetime object %returns string of object in readable format.""" return d.astimezone(tz).strftime("%H:%M %m/%d/%Y")
ad4d93d9d112703f7f8c3455dd9128e350c2be07
681,342
def _default_call_out_of_place(op, x, **kwargs): """Default out-of-place evaluation. Parameters ---------- op : `Operator` Operator to call x : ``op.domain`` element Point in which to call the operator. kwargs: Optional arguments to the operator. Returns -------...
8aaec539ebaa2005cc2e8163a5ac4e20ae12b0c8
681,347
import uuid def gen_id() -> str: """Generate new Skybell IDs.""" return str(uuid.uuid4())
77cdcf546c95071f618119b5f493d7a46426c5bd
681,350
def wrap_list(list_, idx): """Return value at index, wrapping if necessary. Parameters ---------- list_ : :class:`list` List to wrap around. idx : :class:`int` Index of item to return in list. Returns ------- :class:`list` element Item at given index, index will...
9875ccfa8c9885753bcbc6782e0b7926bb69bbf2
681,351
from typing import Tuple def get_tensor_dimensions(n_atom_types : int, n_formal_charge : int, n_num_h : int, n_chirality : int, n_node_features : int, n_edge_features : int, parameters : dict) -> Tuple[list, list, list, list, int]: """ Returns dimensions for...
7c1da4fccf7e3d944a08e3be70751bd4f2422ed7
681,354
def djb2(s: str) -> int: """ Implementation of djb2 hash algorithm that is popular because of it's magic constants. >>> djb2('Algorithms') 3782405311 >>> djb2('scramble bits') 1609059040 """ hash = 5381 for x in s: hash = ((hash << 5) + hash) + ord(x) return hash & ...
52cc44035ec1cc20e6f635a6e2715f08e7ee9887
681,355
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
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
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 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 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 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
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
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
def _is_pronoun (mention) : """Check if a mention is pronoun""" components=mention.split() if components[1]=="PRON" : return True return False
d21cb3309e9e736a90cd706acb8d6f87ceea5114
681,394
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
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 _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
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
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
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 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 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
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 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
def mean_of_columns(mat): """Returns 1-row matrix representing means of corresponding columns """ return mat.mean(axis=0)
aaaf7ab5ce45d21ec4f0b03d311713117823315b
681,461
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
def normalize_response(response): """ Transform response so that 'off' == 'away' """ if response == 'away': return 'off' else: return response
2e03465059bf4adcbb59c3f2dcd0caa3f83f8771
681,468
def sec2ts(time_s): """ Convert time in seconds to timestamp """ return int(time_s * 1e9)
40cc4240a17c502182562224264c283571e6f33c
681,469
import re def find_cites(f): """Return keys to cited papers. """ with open(f) as fp: lst = re.findall(r"{{(.+?)}}", fp.read()) refs = [] for l in lst: if "site.data.refs" in l: refs.append(l.split(".")[3]) return sorted(set(refs))
c54033c52e995dcfed331f68d73897756bbb125c
681,470
def mag(*args): """ Magnitude of any number of axes """ n = len(args) return (sum([abs(arg)**2 for arg in args]))**(1/2)
61ac6e83c251e47afa8f94e1ffa214e72d9b16cb
681,477
def probe_id(subscription_id, resource_group_name, load_balancer_name, name): """Generate the id for a probe""" return '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Network/loadBalancers/{}/probes/{}'.format( subscription_id, resource_group_name, load_balancer_name, na...
64cacdcc4a084ddc551532fac1f71decc4c286fc
681,480
def search_by_sware_hware(nodes: list, option: int) -> dict: """ Search by software/hardware. Return all unique entries in ``nodes`` list at ``option`` index as keys and all hostnameswhich contains the entry in list as value. :param nodes: list of nodes. :param option: Index in the nodes list(...
5ee7978f26bccbe577c6e2c8deff23745de595f2
681,486
from typing import Iterable from typing import List import string def quote_args(args: Iterable[str]) -> List[str]: """Quote the arguments which contain whitespaces""" r = [] for arg in args: if any(map(lambda c: c in string.whitespace, arg)): r.append(f'"{arg}"') else: ...
bcc59d7b684e8330b31fc240edcbf28b1c69c33f
681,490
import hashlib def get_file_md5(path): """ Retrieves the md5sum of a file's contents. Args: path: string path of the file to hash. Returns: string md5sum hash. """ hash_md5 = hashlib.md5() with open(path, 'rb') as in_file: hash_md5.update(in_file.read()) ret...
afbc03e2da7b6140db54cf0e1d268db1c44a8ceb
681,491
def finite_diff(expression, variable, increment=1): """ Takes as input a polynomial expression and the variable used to construct it and returns the difference between function's value when the input is incremented to 1 and the original function value. If you want an increment other than one supply ...
d216fd03af231c25ca786ca191a27e0ce498de87
681,494
def parse_file(file_path): """Parse file with lines: retailer url Args: file_path: The path to the url file Returns: dict: {'retailer1': 'url1', 'retailer2': 'url2'...} """ file = open(file_path) retailer_dict = {} for line in file: try: words_in_lin...
d7047aee3f9171264f49b97cf422f9b0ad94ca2a
681,495
def _sar_range(dicoms): """Find the minimum and maximum SAR values in a list of DICOM headers.""" sars = set([float(d.SAR) for d in dicoms]) return str(min(sars)), str(max(sars))
ab2eab38a491d15af15e9301ecb7ff783207e954
681,500
def get_from_list(list, name): """ searches through list of objects with a .name attribute or surface_shaders and returns the object if it exists or None if not """ for item in list: if item.name == name: return item return None
3013b60f19be5f7b425762717b990ed4c7ae9081
681,501
def format_size(nb_bytes): """ Format a size expressed in bytes as a string Parameters ---------- nb_bytes : int the number of bytes Return ------ formated : str the given number of bytes fromated Example ------- >>> format_size(100) '100.0 bytes' >...
0a3147d75571bc862749c41d0465ffe89b3c4ab4
681,504
def get_method_color(method): """ Return color given the method name. """ color = {} color['Random'] = 'blue' color['Target'] = 'cyan' color['Minority'] = 'cyan' color['Loss'] = 'yellow' color['BoostIn'] = 'orange' color['LeafInfSP'] = 'brown' color['TREX'] = 'green' colo...
42cb4c7a8ecac135697a335dbc72a10fcb4e2da9
681,505
import gzip import bz2 import lzma def fopen(filename, mode=None): """GZ/BZ2/XZ-aware file opening function.""" # NOTE: Mode is not used but kept for not breaking iterators. if filename.endswith('.gz'): return gzip.open(filename, 'rt') elif filename.endswith('.bz2'): return bz2.open(fi...
b384cae1b40b409b3d16b4431565d493da8d363f
681,506
def to_celsius(fahrenheit): """ Accepts degrees Fahrenheit (fahrenheit argument) Returns degrees Celsius """ celsius = (fahrenheit - 32) * 5/9 return celsius
ddb0b75550d623802bcbde70be39ed53d7c3d0c6
681,511
def get_build_info(input_file): """Get build information in UCSC notation, if possible.""" build_dict = { "hg38": ["GRCh38"], "hg19": ["GRCh37", "b37"], "mm10": ["GRCm38"], "mm9": ["MGSCv37"], "rn6": ["Rnor_6.0"], } with open(input_file, "r") as tfile: bu...
54fa87f95b92462bb1879a040213746b0aa99c41
681,518
def is_even(number: int) -> bool: """ This method will find if the number passed is even or not :param number : a number :return: True if even False otherwise """ if number <= 0: return False return number % 2 == 0
f39ff3ac60c1a9a6c4c08df62fba01b0ad940726
681,523
def _parse_ref_dict(reference_dict, strict=True): """Parse the referenced dict into a tuple (TYPE, ID). The ``strict`` parameter controls if the number of keys in the reference dict is checked strictly or not. """ keys = list(reference_dict.keys()) if strict and len(keys) != 1: raise V...
fd15711b5c3abda9e4f1246a84a407cd29f3dd38
681,525
def yLP2DP(lpY, lptLT, lPix = 1.0): """Convert logical coordinates into device coordinates lpY - y logical coordinate lptLT - logical coordinates of left top screen corner lPix - zoom value, number of logical points inside one device point (aka pixel) return coordinate in device c...
8f0bb59f882bd9b33b37235bd064cd4bc21b35c8
681,531
def dot_dir_dir(direction1, direction2): """ Evaluates the dot product of a direction with another direction. PARAMETERS ---------- direction{1, 2}: Point RETURN ------ : float """ return sum((dir_coord1*dir_coord2 for dir_coord1, dir_coord2 in zip(direction1.coords, direct...
bb0364394b961f427156a01b7a4361d889f46e8f
681,532
def lowercase_words(text): """ Method used to transform text to lowercase" Parameters: ----------------- text (string): Text to clean Returns: ----------------- text (string): Text after transforming to lowercase. """ text = text.lower() return text
941a23032dd7416eb03570c2629edb74b3d315d9
681,537