content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from unittest.mock import Mock def get_discovered_bridge(bridge_id="aabbccddeeff", host="1.2.3.4", supports_v2=False): """Return a mocked Discovered Bridge.""" return Mock(host=host, id=bridge_id, supports_v2=supports_v2)
588393281cef9289928936b9859d7bddfa660e8c
674,486
def host_get_id(host): """ Retrieve the host id """ return host['id']
73096a0ab4336a17b5bfe37b8807e0671a8ad075
674,488
def is_nds_service(network_data_source): """Determine if the network data source points to a service. Args: network_data_source (network data source): Network data source to check. Returns: bool: True if the network data source is a service URL. False otherwise. """ return bool(net...
eb078fa482fc02ce504b0718a5721294a67cdbcd
674,495
def opacity(token): """Validation for the ``opacity`` property.""" if token.type == 'number': return min(1, max(0, token.value))
04099d1d919ff59f9f2d4b8d9a228cbf1d03e3c9
674,505
def get_default_alignment_parameters(adjustspec): """ Helper method to extract default alignment parameters as passed in spec and return values in a list. for e.g if the params is passed as "key=value key2=value2", then the returned list will be: ["key=value", "key2=value2"] """ default_al...
79ab15863ef12269c3873f41020d5f6d6a15d745
674,510
def goldstein_price(x): """ Goldstein-Price function (2-D). Global Optimum: 3.0 at (0.0, -1.0). Parameters ---------- x : array 2 x-values. `len(x)=2`. `x[i]` bound to [-2, 2] for i=1 and 2. Returns ------- float Value of Goldstein-Price function. """ ...
b19f4a5e884a0f9520ced7f698a5996b2188857e
674,512
def get_titles(_stories): """ function extract titles from received stories :param _stories: list of stories including story title, link, unique id, published time :return: list of titles """ # Get the stories titles titles = [] for story in _stories: titles.append(story['title']...
280e9803ab87ef76fea4b778c638a5bde6906ade
674,514
def rgbToHex(rgb: tuple[int, int, int]) -> str: """ convert rgb tuple to hex """ return "#{0:02x}{1:02x}{2:02x}".format(rgb[0], rgb[1], rgb[2])
3a2c69c98852e449c0e0fff9b0e1483c93e1edfe
674,517
def make_sleep_profile_colnames(df): """ Create list of ordered column names for dataframe to be created from sleep_profile dictionary """ colnames = ['Time'] for i in range(11,16): colnames.append(df.columns[i] + ' MR Sum') colnames.append(df.columns[i] + ' Avg Sleep') ...
c7588a72cfd86f7c57aff6b85c18a426d7d404f5
674,518
def nice_column_names(df): """Convenience function to convert standard names from BigQuery to nice names for plotting""" cols = [ ('Open Access (%)', 'percent_OA'), ('Open Access (%)', 'percent_oa'), ('Open Access (%)', 'percent_total_oa'), ('Total Green OA (%)', 'percent_green'...
ebbeae9b4c6e18b851a181a1748a184dc5fa12b3
674,520
def calculate_FCF(r, T): """ Calculate FCF from given information :param r: Is the rate of inflation :param T: Is the time in years :return: No units cost factor """ r = r / 100 den = r * ((1 + r) ** T) num = ((1 + r) ** T) - 1 return den / num
47636ac93242a6ed31ffd1c03e37c88d5747f3d7
674,524
import sqlite3 def write_sqlite_file(plants_dict, filename, return_connection=False): """ Write database into sqlite format from nested dict. Parameters ---------- plants_dict : dict Has the structure inherited from <read_csv_file_to_dict>. filename : str Output filepath; should not exist before function c...
32ede716ae4666cab603c9df857054fef2b87ad1
674,525
from typing import Counter def determine_sentence_speaker(chunk): """ Validate for a chunk of the transcript (e.g. sentence) that there is one speaker. If not, take a majority vote to decide the speaker """ speaker_ids = [ word[3] for word in chunk ] if len(set(speaker_ids)) != 1: prin...
2e2cae81f7f76d3993b7cd64f67be58716010ccd
674,530
import random def random_liste(count): """ Returning a list containing 'count' no. of elements with random values between 0 and 100 (both inclusive) """ #Return a list of len 'count', with random numbers from 0..100 return [random.randint(0, 100) for _ in range(count)]
0514f990644549227313eb45ac2afb8cf732275a
674,536
def linear(interval, offset=0): """Creates a linear schedule that tracks when ``{offset + n interval | n >= 0}``. Args: interval (int): The regular tracking interval. offset (int, optional): Offset of tracking. Defaults to 0. Returns: callable: Function that given the global_step r...
0bae3b893312f112edafba15df566d8776efcb2f
674,541
def _is_valid_sub_path(path, parent_paths): """ Check if a sub path is valid given an iterable of parent paths. :param (tuple[str]) path: The path that may be a sub path. :param (list[tuple]) parent_paths: The known parent paths. :return: (bool) Examples: * ('a', 'b', 'c') is a valid ...
f78db91600298d7fd7cfbdc5d54cce1bff201d94
674,546
def get_valid_loss(model, valid_iter, criterion): """ Get the valid loss :param model: RNN classification model :type model: :param valid_iter: valid iterator :type valid_iter: data.BucketIterator :param criterion: loss criterion :type criterion: nn.CrossEntropyLoss :return: valid l...
1e82378ba528a3799058edd2490ec9fb0de16711
674,547
def clean(string): """ Cleans the string by making the case uniform and removing spaces. """ if string: return string.strip().lower() return ''
61ab1d486825b77108fbbdbbb2788dee1e31ad2a
674,552
def formatFloat(number, decimals=0): """ Formats value as a floating point number with decimals digits in the mantissa and returns the resulting string. """ if decimals <= 0: return "%f" % number else: return ("%." + str(decimals) + "f") % number
42b443bce700048521eec6fa7eb19782a71b2eab
674,555
def deserialize_tuple(d): """ Deserializes a JSONified tuple. Args: d (:obj:`dict`): A dictionary representation of the tuple. Returns: A tuple. """ return tuple(d['items'])
aa502d4e16e824b354b00e0055d782cd10fe6b48
674,556
def plan_window(plan, ending_after, starting_before): """ Return list of items in the given window. """ window_tasks = [] for task in plan: if ending_after < task['end'] and task['start'] < starting_before: window_tasks.append(task) return window_tasks
876847a2fa00ebd508299bce2ded82a2073bdf84
674,558
def helper(A, k, left, right): """binary search of k in A[left:right], return True if found, False otherwise""" print(f'so far ==> left={left}, right={right}, k={k}, A={A}') #1- base case if left > right: # if empty list there is nothing to search return False #2- solve the subprob...
3df455e6bf232b7f427c2e0763de1e848e7245e5
674,560
def override(left, right, key, default): """Returns right[key] if exists, else left[key].""" return right.get(key, left.get(key, default))
f6f5da1840aa4fa70fe0db400be9bebd2f21e383
674,561
def delete_fit_attrs(est): """ Removes any fit attribute from an estimator. """ fit_keys = [k for k in est.__dict__.keys() if k.endswith('_')] for k in fit_keys: del est.__dict__[k] return est
a84c919868ff353ac91f3f7714492e1e17db2af9
674,563
def retrieve_arguments(args): """ Further parses arguments from CLI based on type and constructs concise object containing the parameters that will dictate behavior downstream :param args - arguments retrieved from call to parser.parse_args as part of argparse library :returns dictionary containing all...
11f5a7bac5d1780f7cc091f0d38b28ff2d1afbab
674,564
def set_voltage(channel: int, value: float): """ Sets voltage on channel to the value. """ return f"VSET{channel}:{value}"
b7c28f2253a5e5d63e806cc82d597aaba0690fb8
674,565
def split_name(name): """ Split a name in two pieces: first_name, last_name. """ parts = name.split(' ') if len(parts) == 4 and parts[2].lower() not in ('de', 'van'): first_name = ' '.join(parts[:2]) last_name = ' '.join(parts[2:]) else: first_name = parts[0] last...
c96acf0137975cb1c0dc5b5093a3769d546c67b6
674,574
def jaccard_distance(text1, text2): """ Measure the jaccard distance of two different text. ARGS: text1,2: list of tokens RETURN: score(float): distance between two text """ intersection = set(text1).intersection(set(text2)) union = set(text1).union(set(text2)) return 1 -...
1a3095f086c648dfe8b334830a5d963e247cb92e
674,577
def chunks(_list, n): """ Return n-sized chunks from a list. Args: _list - A list of elements. n - Number defining the size of a chunk. Returns: A list of n-sized chunks. """ return list(map(lambda i: _list[i:i + n], range(0, len(_list), n)))
eeee00ce773cd298954ecfed3da405b55aaecbb0
674,586
def objective_rule(model): """ Maximize the sum of all rewards of activities that are 'picked' (selected) """ return sum(model.CHILD_ALLOCATED[cr, ca] * model.child_score[ca] for (cr, ca) in model.cr_ca_arcs)
1c8469a12819c7cc461018a75d5d9ae29ce7ada5
674,588
def remove_spaces(string): """ Remove triple/double and leading/ending spaces """ while ' ' in string: string = string.replace(' ', ' ') return string.strip()
7c2e0534654374c31247fa542e59e3baabe2a479
674,589
from typing import Union from typing import Optional from pathlib import Path def check_for_project(path: Union[str, "Path"] = ".") -> Optional["Path"]: """Checks for a Brownie project.""" path = Path(path).resolve() for folder in [path] + list(path.parents): if folder.joinpath("brownie-config.jso...
026ccf715c7dbf9f1e7f3add2d84f7e661996928
674,590
import colorsys def lighten_rgb(rgb, times=1): """Produce a lighter version of a given base colour.""" h, l, s = colorsys.rgb_to_hls(*rgb) mult = 1.4**times hls_new = (h, 1 - (1 - l) / mult, s) return colorsys.hls_to_rgb(*hls_new)
b03dbd8c5fbef2683367f43fcbbad177a2e0aa22
674,594
def recursive_length(item): """Recursively determine the total number of elements in nested list.""" if type(item) == list: return sum(recursive_length(subitem) for subitem in item) else: return 1.
597df9062da54a124711618eb21890997cd6cfa2
674,596
from typing import List def numeric_binary_search(ordered_numbers: List[int], search: int) -> int: """Simple numeric binary search Args: ordered_numbers(List[int]): an ordered list of numbers search(int): number to find Returns: int: found index or -1 """ assert isinstanc...
a543ff116d98fcb5b2b405ccd51d650b54692de4
674,597
import random def get_randints(lower, upper, exclude): """Generate a set of unique random numbers in a range (inclusive).""" numbers = [i for i in range(lower, upper, 1)] numbers.remove(exclude) random.shuffle(numbers) return numbers
ba272295bc9938f157b6b893632a3c8b9af96b3f
674,599
def knot_insertion_alpha(u, knotvector, span, idx, leg): """ Computes :math:`\\alpha` coefficient for knot insertion algorithm. :param u: knot :type u: float :param knotvector: knot vector :type knotvector: tuple :param span: knot span :type span: int :param idx: index value (degree-dep...
51e3e61eae5e562c47b67904873e4ffe327bb842
674,601
def pearsonchisquare(counts): """ Calculate Pearson's χ² (chi square) test for an array of bytes. See [http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test #Discrete_uniform_distribution] Arguments: counts: Numpy array of counts. Returns: χ² value """ np = sum(cou...
56440e7241451d66b67f7d55c7fa918cf758a5b7
674,604
def common_shape(imgs, axis): """ Find smallest height or width of all images. The value along `axis` will be `None`, the other will be the smallest of all values Args: imgs (list[np.array]): list of images axis (int): axis images will be concatenated along Returns: tup...
d0b357f20e955932e135aeedc318a969d7f9f883
674,609
def convert_image(img, coefs): """Sum up image channels with weights from coefs array input: img -- 3-d numpy array (H x W x 3) coefs -- 1-d numpy array (length 3) output: img -- 2-d numpy array Not vectorized implementation. """ x = img.shape[0] y = img.shape[1] re...
3f28eaf00a48ebb76e2b403750ee46b1c1930c38
674,610
def build_context(query, query_config): """Build context based on query config for plugin_runner. Why not pass QueryExecConfig to plugins directly? Args: query (str) query_config (QueryExecConfig) Returns: dict str -> str """ context = vars(query_config) context['query'] = query return c...
c1e6c93fd8d97e659eaa27e7b48494f600ebc8f9
674,611
def index_to_coordinates(string, index): """ Returns the corresponding tuple (line, column) of the character at the given index of the given string. """ if index < 0: index = index % len(string) sp = string[:index+1].splitlines(keepends=True) return len(sp), len(sp[-1])
fc21d15cade5d005895a226ae992b2e9792372f5
674,613
from typing import Iterable def binary_str_to_decimal(chars: Iterable[str]) -> int: """ Converts binary string to decimal number. >>> binary_str_to_decimal(['1', '0', '1']) 5 >>> binary_str_to_decimal('101010') 42 """ return int("".join(chars), base=2)
2dcd986c4c56c9a177ebf41138226f40464850a8
674,616
def mean(num_list): """ Return the average of a list of number. Return 0.0 if empty list. """ if not num_list: return 0.0 else: return sum(num_list) / float(len(num_list))
accfaf78a276654af94911ab0091d3a5650b49f3
674,617
import re def cnvt_to_var_name(s): """Convert a string to a legal Python variable name and return it.""" return re.sub(r"\W|^(?=\d)", "_", s)
b709f41809f863ccf5137e7ff4d0c444223ff31e
674,619
def quick_sort(collection: list) -> list: """ A pure Python implementation of quick sort algorithm :param collection: a mutable collection of comparable items :return: the same collection ordered by ascending Examples: >>> quick_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> quick_sort([]) ...
3ccf9a99e0434f80066f657e80c310b25ae11eae
674,620
def pow2(x): """Return the square of x :param float x: input value :rtype: float """ return x*x
955e83c526430582a542eb6c3b1d2ab92d7bff61
674,621
import re def is_mac_address(mac): """ Test for valid mac address :type mac: ``str`` :param mac: MAC address in the form of AA:BB:CC:00:11:22 :return: True/False :rtype: ``bool`` """ if re.search(r'([0-9A-F]{2}[:]){5}([0-9A-F]){2}', mac.upper()) is not None: return True ...
d67d20e85189307c35b6fdfaf42103128087691a
674,622
import json def create_label(name, color, repos, session, origin): """ Creates label :param name: name of the label :param color: color of the label :param repos: repository where label is created :param session: session for communication :param origin: repository where the label came fro...
c5f157673967c8f1b8928c3831abf4558ef5dc92
674,625
def num_leading_spaces(str): """ Return the number of leading whitespaces of given string """ for i, c in enumerate(str): if c != ' ': return i return len(str)
eef26534aed7b782246542b1cf9eef5cd222eb7e
674,635
def memoize(f): """A simple memoize decorator for functions.""" cache= {} def memf(*x): if x not in cache: cache[x] = f(*x) return cache[x] return memf
f1b318f37cddabfdb8e508c4f18386e49e6c14ee
674,636
import json def parse_json_file(file_path: str): """utility method to read a json file and return json object Parameters ---------- file_path : str full path to json file that needs to be parsed Returns ------- [type] json object parsed from the file """ with open...
100968b80f165397628d8523821f245c5c779d17
674,637
def to_int(x): """Convert bytes to an integer.""" return int(x.hex(), 16)
523bb07b8900f9cf364904f90da393b736cbdeda
674,638
from typing import OrderedDict def custom_sort_exps(exps): """ Sort the experiments according to JIRA LCLSECSD-210 Active first, OPS next and then descending run period/alphabetical within that run period """ # Python's sort is stable; so we sort multiple times lowest attr first exps = Ordered...
dcd76be3ac6a0c9b8b60b87b1c48b0a2823a363e
674,639
def _match_some(regexes, line, n_line, n_col): """Match patterns in order. Returns a tuple of match and token type or raises SyntaxError.""" for regex, token in regexes: match = regex.match(line, n_col) if match is not None: return match, token error = "No rules to match inpu...
c5b2f9f3efdee10b44357f9d4f1e81a09553d22e
674,641
def seconds_for_analysis(duration, measurement_type, selector): """Get duration for specified measurement type and selector.""" if measurement_type in duration: data = duration[measurement_type] if selector in data: return data[selector].duration_seconds return 0
56364f70d018982bffe84089f58699752f0cb207
674,647
def duplicates_checker(source, new): """ Checking for duplicates in existing list of contacts """ for item in source: if new == item['phone']: return False return True
5a7c7315ef3d9655369d75109b9073b99aea9486
674,648
def _multiplot_interval(from_date, to_date, points): """ Computes the size of the interval between points in a multiplot. :return: the multiplot interval size. :rtype: ``float`` """ if points < 2: return 0.0 return (to_date - from_date) / (points - 1)
3b475fb7a112d4cf11f0c8dc7648e99472015e5f
674,650
def wma(df, price, wma, n): """ The Weighted Moving Average calculates a weight for each value in the series. The more recent values are assigned greater weights. The Weighted Moving Average is similar to a Simple Moving average in that it is not cumulative, that is, it only includes values in the t...
bf1fb40987b1bafff01bcd408dc028b4ce02ece9
674,651
def recurse_combine(combo_items: list, idx: int = 0) -> list: """Recursively expands 'combo_items' into a list of permutations. For example recurse_combine([[A, B, C], [D, E], [F]]) returns [[A, D, F], [A, E, F], [B, D, F], [B, E, F], [C, D, F], [C, E, F]] """ result = [] if i...
effab4c6f29e353d19f88b23f7d2a3bfa854d431
674,653
def _ask_yes_no(prompt: str) -> bool: """Simple function that prompts user until they answer 'y' or 'n'""" answer = input(prompt).lower() while answer not in ("y", "n"): answer = input("Please enter 'y' or 'n': ").lower() if answer == "y": return True else: return False
79edd6287d4026102a886c25879b50938deaa373
674,655
def to_upper(string): """:yaql:toUpper Returns a string with all case-based characters uppercase. :signature: string.toUpper() :receiverArg string: value to uppercase :argType string: string :returnType: string .. code:: yaql> "aB1c".toUpper() "AB1C" """ return st...
eafb08654c65893e43d2a79407f625e862fd7b7e
674,656
def linspace(a, b, num_chunks): """Returns equidistant steps in [a, b] whose number matches num_chunks.""" assert isinstance(num_chunks, int) and num_chunks > 0, 'Number of chunks must be a natural number!' h = (b - a) / num_chunks return [a + i * h for i in range(num_chunks + 1)]
d752c0129287d9ce83265990deba6aa919e16d3f
674,658
def safe_hasattr(item: object, member: str) -> bool: """Safe version of ``hasattr()``.""" try: # some sketchy implementation (like paste.registry) of # __getattr__ cause hasattr() to throw an error. return hasattr(item, member) except Exception: return False
3aa60eb3cb454ca737414f0ecf2099afe43a82ae
674,660
import fnmatch def _get_pprint_include_names(table): """Get the set of names to show in pprint from the table pprint_include_names and pprint_exclude_names attributes. These may be fnmatch unix-style globs. """ def get_matches(name_globs, default): match_names = set() if name_glob...
a642ec20192f4dfedda293105dc83978b5ba20d2
674,662
def _recall(conf_mat): """ Compute the recall score, i.e. the ratio of true positives to true positives and false negatives. Answers the question: "Which share of the pixels that are actually slum was identified by the model as such?" :param conf_mat: Confusion matrix produced by conf_mat(). :retu...
d28d9b63106fb5bba83fbc45f009258716eb9cab
674,663
def recursive_lookup(dict_object, keys): """ Given a dict object and list of keys, nest into those keys. Raises KeyError if the path isn't found. >>> recursive_lookup({'foo': 1}, ['foo']) 1 >>> recursive_lookup({'foo': {'bar': 1}}, ['foo']) {'bar': 1} >>> recursive_lookup({'foo': {'bar':...
485a398649640fce5cfe370e8a28f13f5540ca18
674,664
from typing import Dict from typing import Any from typing import Literal from typing import Optional from typing import Union from typing import List def _check_for_override( systematic: Dict[str, Any], template: Literal["Up", "Down"], option: str ) -> Optional[Union[str, List[str]]]: """Returns an override ...
85cfbde0e2de2083b1ee378994ee388365750d6e
674,667
def get_table_id(current_page, objects_per_page, loop_counter): """ Calculate correct id for table in project page. This function is used only for pagination purposes. """ return ((current_page - 1) * objects_per_page) + loop_counter
36d12d316940b5982abb4bc89369c3df5e8a42b6
674,672
def get_kp_labels(bands_node, kpoints_node=None): """ Get Kpoint labels with their x-positions in matplotlib compatible format. A KpointsData node can optionally be given to fall back to if no labels are found on the BandsData node. The caller is responsible for ensuring the nodes match. This shou...
decd7c5f0a027fa975b7bdab692548f3c0c7d05a
674,676
def IndexOfMin(inputList): """ Return the index of the min value in the supplied list """ assert(len(inputList) > 0) index = 0 minVal = inputList[0] for i, val in enumerate(inputList[1:]): if val < minVal: minVal = val index = i + 1 return index
0f2ca9bdf78755aaf71eddc3ca2a5683af095dc5
674,677
def filter_profile(data, profile): """ Take a dataframe after it has been processed by merge_data, and a profile and returns a filtered dataframe of players with that profile. Valid profiles are 'long_inaccurate', 'long_accurate', 'short_inaccurate', 'short_inaccurate'. """ player_aggregates = d...
e60ff7d862f2635538094299977ac08655073bf8
674,678
def mat_like_array(start, end, step=1): """ Generate a matlab-like array start:end Subtract 1 from start to account for 0-indexing """ return list(range(start-1, end, step))
ce69ee207a543ade6c52e119682e4e5387266d71
674,681
def rotate(pos, vel, matrix): """ Rotate. Applies the rotation `matrix` to a set of particles positions `pos` and velocities `vel` Parameters ---------- pos : `np.ndarray`, shape = (N_part, 3) Positions of particles vel : `np.ndarray`, shape = (N_part, 3) Velocities of ...
d701380c86d0217be8d6ea297cf1678ca0d2d4d5
674,683
def generate_public(private, generator, modulus): """Calculates the public Diffie-Hellman key given g, p, and the private key""" return pow(generator, private, modulus)
9b6a4ec6cb858c248719a96f45a45638759100a1
674,686
import base64 def custom_jinja2_filter(string): """encodes a string using base64 schema""" return base64.b64encode(string.encode("UTF-8")).decode("UTF-8")
50e25472b44ea62cd7f8d1996454441889120e2b
674,687
def assume_role_response_to_session_kwargs(assume_role_resp): """Convert assume role response to kwargs for boto3.Session Also useful for creating AWS credentials file. """ return dict(aws_access_key_id=assume_role_resp['Credentials']['AccessKeyId'], aws_secret_access_key=assume_role_r...
08bcf3ba302229330708a3d827770ab5b206afdc
674,690
def join_ints(*ints): """Given a list of ints, return a underscore separated strings with them. >>> join_ints(1, 2, 3) '1_2_3' """ return '_'.join(map(str, ints))
e0fe79ac05e5473df319b76ddb22ffec3b06442c
674,691
import math def make_multiple(x, number): """ Increases x to be the smallest multiple of number """ return int(math.ceil(float(x) / float(number)) * number)
7b25e08beb911b5868e704274c0b36d4bd6449be
674,693
def zones2list(zones, type="power"): """Convert zones Strava response into a list Parameters ---------- zones : dict Strava API zones response type : {"power", "heart_rate"} Returns ------- y : list Zones boundaries with left edge set to -1 and right to 10000 """ ...
19e70764b7c4cb1098c586cdb56aeb83518a2bb9
674,694
def retrieve_commands(commands): """ Retrieve context needed for a set of commit actions """ config_commands = commands['config'] support_commit = commands.get('support_commit') config_verify = commands['config_verification'] return (config_commands, support_commit, config_verify)
c85f69f24581004033eb83d2d0177533c82c6bdf
674,695
import re def RemoveFrameShiftsFromAlignment(row_ali, col_ali, gap_char="-"): """remove frame shifts in an alignment. Frameshifts are gaps are 1, 2, 4, or 5 residues long. >>> RemoveFrameShiftsFromAlignment("ABC-EFG", "AB-DEFG") ('ABEFG', 'ABEFG') Arguments --------- row_ali : string ...
851b6e9e963b468656da6f4daf1213d403ca0d99
674,699
async def headers_middleware(req, handler): """ Middleware that adds the current version of the API to the response. """ resp = await handler(req) resp.headers["X-Virtool-Version"] = req.app["version"] resp.headers["Server"] = "Virtool" return resp
2c12a6644aafc1dcd2ef49ff5aead805b10cdc80
674,703
def loantovalue(purchaseprice, financedamount): """Return ratio of financed amount to purchase price. :param purchaseprice: Contract price of property. :type purchaseprice: double :param financedamount: Amount of money borrowed. :type financedamount: double :return: double """ return f...
5a88a690823a23607efc77a7fe0e6d7de48cef75
674,704
def squeeze(array): """Return array contents if array contains only one element. Otherwise, return the full array. """ if len(array) == 1: array = array[0] return array
738319557582597805d1f184d30d2ec3e13e9288
674,705
def to_label(name, capitalize=True): """Converts `name` into label by replacing underscores by spaces. If `capitalize` is ``True`` (default) then the first letter of the label is capitalized.""" label = name.replace("_", " ") if capitalize: label = label.capitalize() return label
fa030cd9ec337684f624e0df8295e82f7f6dc16b
674,706
from functools import reduce from typing import cast def cast_schema(df, schema): """Enforce the schema on the data frame. Args: df (DataFrame): The dataframe. schema (list): The simple schema to be applied. Returns: A data frame converted to the schema. """ spark_schema ...
1a8412a2a3a363589c18f09e672145e94a020aab
674,708
def get_social_auths_for_user(user, provider=None): """Get UserSocialAuths for given `user` Filter by specific `provider` if set Returns a QuerySet of UserSocialAuth objects """ social_users = user.social_auth if provider is None: social_users = social_users.all() else: soc...
1c7346aedf9795e94bc86b23d84ec73380b28561
674,714
def get_sub_series(sub_cats): """ Gets the series IDs of all the subseries that are in UTC time associated with a given load balancing station """ series = [] for category in sub_cats['category']['childseries']: if "UTC time" in category['name']: series.append(category['series_id']) ...
6af4dd8ba22fc39ae75af417ed86e331620db648
674,720
from typing import List def two_sum(nums: List[int], target: int) -> List[int]: """ https://leetcode.com/problems/two-sum/ :param nums: list of integers :param target: expected sum :return: list of two index of the two integers that when summed are equals to target :raises: ValueError when com...
6d4f19e69ec6180afddd3cd67a708429cea70e4f
674,723
from typing import Union from pathlib import Path def guess_format(filename: Union[str, Path]): """ Guess the output format from a given filename and return the corrected format. Any names not in the dict get passed through. """ extension = str(filename).rsplit(".", 1)[-1].lower() format_map ...
b5eb01e9cd2a294b31c5194a73fe3f0d3e6b3efc
674,729
def sub(num1, num2): """ Subtract two numbers """ return num1 - num2
f5e0b2e47302c50f79f1ba8a3d3bc6dffa8054c6
674,732
import re def remove_links(text: str) -> str: """ Removes links from a text. Args: text (:obj:`str`): Text to process. Returns: :obj:`str`: Text without links. """ # add empty character between two paragraph html tags to make processing easier te...
75bde7a53ccbcbc3007fde66f3573df457ecbda9
674,735
from typing import List def _validate_counts(counts: List[int]) -> bool: """ Validates the counts parameter. Parameters ---------- counts : List[integers] A list of counts. Raises ------ TypeError The ``counts`` parameter is not a list or one of the elements of this ...
a87095d1df60e75801ed81485a3223b8a3e6a8ea
674,737
def get_max_width(text_array): """Get the maximum width of a bunch of rows of text.""" width = 0 # Figure out the maximum width for row in text_array: if len(row) > width: width = len(row) return width
9fae5e9a6d634c641e8920fff4700db67e6cc895
674,739
import torch def generate_proposals(anchors, offsets, method="YOLO"): """ Generate all proposals from anchors given offsets. @Params: ------- anchors (tensor): Tensor of shape [B, A, H', W', 4] returned by `generate_anchors()`. Anchors are parameterized by the coordinates (x_tl, y...
133cfd328b38fffe7cbcb0bcae33e7af5d0c1c98
674,741
def constrain(value, lowest, highest): """Test whether `value` is within the range `(highest, lowest)`. Return `value` if it is inside the range, otherwise return `highest` if the value is *above* the range or `lowest` it the value is *below* the range. >>> constrain(-1, 2, 5) 2 >>> constra...
197668ebd855a79db217991788105b49860664ed
674,749
def first(mention): """ Compute the first token of a mention. Args: mention (Mention): A mention. Returns: The tuple ('first', TOKEN), where TOKEN is the (lowercased) first token of the mention. """ return "first", mention.attributes["tokens"][0].lower()
7cd0bc412d7b59fa26b2981b3d0c1a0c1465c0dc
674,753
def convert_velocity(val, old_scale="km/h", new_scale="m/s"): """ Convert from a velocity scale to another one among km/h, and m/s. Parameters ---------- val: float or int Value of the velocity to be converted expressed in the original scale. old_scale: str Original scale from ...
6a38ac70090f14a4a0d3989ce5a1a884067afd77
674,757
import calendar def get_month_dispatch_intervals(year, month): """Get all dispatch interval IDs for a given month""" days = range(1, calendar.monthrange(year, month)[1] + 1) intervals = range(1, 289) return [f'{year}{month:02}{d:02}{i:03}' for d in days for i in intervals]
543337d356313471abda6493e9b23a8057fb1f9a
674,759