content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import json def read_json(path): """Reads JSON from file. Args: path: the path to the JSON file Returns: a dict or list containing the loaded JSON Raises: ValueError: if the JSON file was invalid """ try: with open(path, "rt") as f: return json.lo...
dd29df960e2e3699119c3a0cafc256c29624e9cb
571,862
def _get_qualified_name(obj): """Return the Fully Qualified Name from an instance or class.""" module = obj.__module__ if hasattr(obj, '__name__'): obj_name = obj.__name__ else: obj_name = obj.__class__.__name__ return module + '.' + obj_name
fad5fdbc7e4a0170f9a433b5b86f968b9177ece9
571,867
def set_record_owners(record_metadata, owners): """Set the record's owners, assuming an RDM-Records metadata schema.""" metadata = record_metadata.copy() owners = [{"user": owner.id} for owner in owners] if "access" not in metadata: metadata["access"] = {} metadata["access"]["owned_by"] = ...
b75c0071f4cda20f8092aa14a41c636bfd2b5b70
571,868
def adjust_proportion_value_list(proportion_value_list, distributable_value): """ Adjust the calculated progress proportion value list to ensure that sum is equal to distributable_value. :param proportion_value_list: calculated progress proportion value list :param distributable_value: number of dis...
98e07f027e1c83a7382e8ba175c7d2b4065d5143
571,870
from pathlib import Path def dataDirectory(dataDirectoryName='data'): """ Return the directory that contains the data. We assume that the data folder is locate in a parent directory of this file and named 'data'. If your setup is different, you will need to change this method. """ dataDir...
3c26c8f3a52ed4fa595e9da5876b93581a3302e5
571,871
def check_variable_list_are_valid(variable_type_dict): """ Checks that the provided variable_type_dict is valid, by: - Confirming there is no overlap between all variable lists :param variable_type_dict: A dictionary, with keys describing variables types, and values listing particular variabl...
8a1abd12228aeb1d38528b458d83e37bb4cf73cc
571,873
def get_userinfo(claims, user): """ Get info about user into given claims dictionary. Specification of the standard claims is available at http://openid.net/specs/openid-connect-core-1_0.html#rfc.section.5.1 :type claims: dict :type user: django.contrib.auth.models.AbstractUser :rtype: dic...
9427e04f50f48d4799671703e08cef5564dd0097
571,875
def deduplicate(values: list): """Simple deduplicate that uses python sets""" return list(set(values))
adc4074ff9cbfec2d6d3ee973ea0533a88a4f828
571,878
def decayingAverage(newVal, oldVal, numSamples): """Averages oldVal with newVal over numSamples. Introduces newVal into oldVal, decaying oldVal by a single sample and introducing newVal by a single sample. Args: newVal: The new value to average. oldVal: The value to decay. numS...
e033b5c8745054f8418c409efa5c0f9db62d681b
571,879
def get_substrings(string, seperators=["/", "_", ".", ":", ";", " "], reverse=False): """ get substrings of string by removing each seperator. Args: string (str) seperators (list) reverse (bool): return substrings in reversed order Returns: substrings (list) ...
3ba48dfbc4cd542485ac3bbc771ce76445652e8d
571,888
from typing import Sequence def combination_sums(total: int, terms: Sequence[int]) -> int: """Counts the number of combinations that sum to a given value. Args: total: A positive integer, representing the target sum. terms: A sequence of positive integer values that can be combined. Retu...
a4d4ad659411fab14f41061cb3fd98a045bb092e
571,895
import re def abbreviate_package(stack_line): """ Abbreviate the package from a stack line: foo.bar.Class.method -> f.b.Class.method In a package name cannot be found the string is unchanged """ match_object = re.match(r'(?P<package>.*\.)(?P<remainder>[^.]+\.[^.]+)$', stack_line) if match_object ...
7b20ac990951dc249a1e86d214a627bca4deb4c5
571,896
from typing import List from typing import Counter def get_base_freq(reads: List[str]): """ Returns the aggregate frequency of bases in the sequencing reads >>> get_base_freq(["NAACGTTA"]) Counter({'A': 3, 'T': 2, 'N': 1, 'C': 1, 'G': 1}) >>> get_base_freq(["AACGTTA", "CGCGTTT"]) Counter({'T':...
60b5dc85e50ad6ea6a99ea949322bd4828a12cc3
571,900
def transform_dict_data(orig_dct: dict, key: str): """ Type dispatcher to modify get method in terms of return type :param orig_dct: original dictionary :type orig_dct: dict :param key: string with key to transform :type key: str :return: value :rtype: matches KEYTYPEMAP """ neste...
9369095cd0dd8a6d52b0f7357cb0f74e968b66c7
571,902
import torch def prepare_crop_params(bounding_boxes, image_height, image_width): """Return boxes truncated by image bounds. Arguments --------- bounding_boxes : torch.Tensor size [num_boxes, 10] Each row is a single bounding box. Column 0 is batch index. Columns 1 - 4...
9b941b23e6b763b64643597b037543020dcbdf91
571,903
import csv def load_original_file(filename, delimiter, skipline): """ File loader :param filename: str: path :param delimiter: str: delimiter used, passed to csv.reader :param skipline: bool: does the frst line contains column names (true) or data (then false) :return: data, firstline """ ...
88d985cd86607e4d0b485862246dd64133499c3e
571,907
def boundDefaults(linkograph, lowerBound, upperBound): """The common defualt bounds for most of the methods. The common bounds used for the methods are to have lowerBound at least 0, upperBound no more than len(linkograph)-1. Furthermore, if the upperBound is given, then linkograph[lowerBound, uppe...
7148be10b4d2b07f8c48908086c5271d556db540
571,909
def parse_fasta( f ): """Parses a fasta file f can either be a file name or a file handle. Returns a dictionary mapping keys to sequences Not optimised for large files """ if str == type( f ): f = open( f, 'r' ) results = { } key = None for line in f: line = line...
da06dcc8a5ad75d774228e222ef0c0e085a05d27
571,910
def _make_unique(l): """Check that all values in list are unique and return a pruned and sorted list.""" l=list(set(l)) l.sort() return l
1bcdd0da1bb65f9efe5afc2d471eb14e97fc2f8d
571,914
from pathlib import Path def read_indicator_file(recommendation_folder: str) -> bool: """Read an empty file left in the output path that indicated if the model should be registered""" output_path = Path(recommendation_folder) return len(list(output_path.glob("REGISTER"))) > 0
d43e2e52e7364531c0d79e14659981b3467ef419
571,917
def linear_gradient(x, y, theta): """ 특정 데이터 (x, y)에서 기울기와 y절편에 대한 편미분 벡터 리턴 :param x: 실제 데이터 :param y: 실제 데이터 :param theta: [theta1, theta2] 벡터(리스트). [기울기, y절편] """ slope, intersect = theta y_hat = slope * x + intersect # 예상값 error = y_hat - y # 오차 # error**2을 최소화하는 slope...
1b6e1f9bf3f9ac953d4a8329c715535765d456b7
571,918
from typing import Tuple import struct def peek_dataframe (pdu:bytes) -> Tuple[int,int]: """Peek at device short address and 16 bit sequence number of a data frame.""" addr,fctrl,seqno16 = struct.unpack("<iBH", pdu[1:8]) return (addr,seqno16)
cbb1cba9f68d4053378fd905852a6060a6e3f8ac
571,919
def _metatile_contents_equal(zip_1, zip_2): """ Given two open zip files as arguments, this returns True if the zips both contain the same set of files, having the same names, and each file within the zip is byte-wise identical to the one with the same name in the other zip. """ names_1 = s...
3b5ec1cfbea5cef52a24450ca4b22bc382c2d6be
571,920
import math def angle_between_three_points(point1, point2, point3): """ Calculate angle between point1 - point2 - point3 param point1 : (x1, y1) param point2 : (x2, y2) param point3 : (x3, y3) return absolute angle in degree integer """ angle = math.atan2(point1[1] - point2[...
c9b847f8ac4554297a91937e5d186ab301c8c28a
571,921
def getvalue(s): """ getvalue() takes a string like <aaa>bbbbb<cc> and returns bbbbb """ p = s.find('>') s = s[p+1:] s = s[::-1] # string reverse p = s.find('<') s = s[p+1:] s = s[::-1] # string reverse, again return s
1f0c03ea4f06b1bd71635d921aeebf7e9c1a1014
571,923
def labelFromString(s): """Work out if this operand is a label or not""" # Is it numeric? try: operand = int(s) return operand, None # just a normal number except: pass # Must be a label return None, s
19b60a584aade2ffa6040760da87b321b296511e
571,928
def yesorno(choice): """ Returns True if the choice starts with an uppercase or lowercase 'n' or 'y'.""" if choice.lower().startswith('y'): return True elif choice.lower().startswith('n'): return True else: return False
aae4cc525372b496b280708d9ce8fe17400bc39e
571,929
def dummy_dir(tmpdir_factory): """Returns the path to a temporary directory. """ dummy_dir = tmpdir_factory.mktemp('dummy_dir') return dummy_dir.strpath
0f2f96562945c30e6036ee3bc492d40ba949e43f
571,933
def is_webflow(commit): """ Check if commit is a valid "webflow" commit, i.e., whose committer is web-flow """ return commit['committer'] and (commit['committer']['login'] == 'web-flow')
ea520f68de3e01d1e9182b7f0087549d668c49ac
571,935
import math def distance(x1, y1, z1, x2, y2, z2): """Return distance between 2 points. Inputs are 6 floats.""" return math.sqrt((x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2)
c2cd627afc09e93d5bf2d8b3327fcc83d6318730
571,938
def nearby_valid_date(desired_date, dictionary): """ Sometimes we get a date (year, month, day) that does not exactly exist in another dictionary. We want to find a nearby date that does exist in that dictionary, but is part of the same month. """ for valid_date in dictionary: if (valid...
427f800bc9e546e1ae0619e13121a0aa965c2853
571,942
def pp_print_hex(h): """ Byte string to hex :param h: list of bytes :return: list of hex strings """ return map(lambda e: hex(ord(e)), h)
b4f7b68af107029754e843185dbcb9f3ad544cee
571,943
def get_legal_notice_private() -> str: """Return the one line legal notice we expect private files to have.""" return 'Copyright (c) 2011-2021 Eric Froemling'
55fec3e4ccdfaefa15e514fd9aa54a1ef04aa7b0
571,950
def to_base(base: int, number: int) -> str: """ Changes an integer from decimal base to other base. Args: base (int): New base of the number to be converted. number (int): Number to be converted to the new base. Returns: str: A string representation of the number in the new base. ...
833b4ab91a1052217561c5c9e62b79967b8710d7
571,951
def AlwaysOnFlagHandler(feature): """ This handler always returns True """ return True
65e6ff8a74d4e159121dc0901a6509bc05ed8180
571,953
from typing import OrderedDict def get_nested_schema_objects(parent_object, list_key): """ Generic method to extract a flattened list of child objects from a parent object and return an ID-keyed dictionary of those child objects. This method also patches on a `parent_id` attribute to each child objec...
17d026e2c4620fca0b5a2575c3ce3bfdf9cb34e7
571,957
def add_names_column(my_df): """ Add a column of corresponding state names to a dataframe. Params(my_df) is a df with a column called "abbrev" that has name abbre. Return a copy of the original dataframe, but wioth extra column. """ new_df=my_df.copy() name_map={"EA":"Elif Ayar","VA":"V...
c303edbd50924589a8f514d8fa3eaaf31edd6b89
571,959
def _reshape_fluxes(fittedFluxes): """ Reshaped the flux information from a dataframe to a dict to be used in constraint assigning functions. """ MFA_flux_bounds = {} for i, rxn in fittedFluxes.iterrows(): MFA_flux_bounds[rxn["rxn_id"]] = [rxn["flux_ub"], rxn["flux_lb"]] return MFA_f...
96ecbcb7db2b55071b32e7c5b8d10540c30d030a
571,963
def calc_list_average(l): """ Calculates the average value of a list of numbers Returns a float """ total = 0.0 for value in l: total += value return total / len(l)
bf0d1d347520c4120313c6c0f700d7ea7826bb67
571,964
def _overpass_filter_highway_upto_level(level): """ Generates an overpass filter (See https://wiki.openstreetmap.org/wiki/Overpass_API/Language_Guide) for selecting only streets upto importance `level`. Also deselects streets not relevant for public routing, e.g. provate pr driveways. """ stree...
2f018bbdd93f587715e5a95527cdc51b132b70bd
571,965
import re import codecs def reformat(string: str) -> str: """ format special characters such as \n, \\ and more. :param string: the string to format :return: the formatted string """ escape_sequence_re = re.compile(r''' ( \\U........ # 8-digit hex escapes | \\u.... ...
331c6fbd3788f55024aecffe87cd52d365b4667f
571,968
import numbers def _score(estimator, X_test, y_test, scorer): """Compute the score of an estimator on a given test set.""" if y_test is None: score = scorer(estimator, X_test) else: score = scorer(estimator, X_test, y_test) if hasattr(score, 'item'): try: # e.g. unw...
aa1418e2db956a1a81806b107cadc662abe18045
571,969
def _drop_nans(df): """removes rows where nan in all columns""" return df.dropna().reset_index(drop=True)
3acad3af81b8ff4bb744c18677e4018b2c13673e
571,970
import torch def all_isfinite(x): """Check the entire nested dictionary/list of tensors is finite (i.e. not nan or inf)""" if isinstance(x, torch.Tensor): return bool(torch.all(torch.isfinite(x))) elif isinstance(x, list): return all([all_isfinite(xi) for xi in x]) elif isinstance(...
101c14fdc6f63acc2dcaa387a2cfbed41f20dc9c
571,971
from bs4 import BeautifulSoup def add_html_declaration(html: str) -> str: """ Add in the declaration, i.e., "<!DOCTYPE html>", to the beginning of a string representation of an HTML file and return the new string. :param html: raw HTML content :type html: str :returns: HTML string :r...
4ddb8ac5c9ef9fe349d5cb451780725965731b9e
571,972
def _thread_title_check(original_post, history_item): """ Verify that the link titles match. On the original post, it will be removed, but we should still be able to extract the title of the submission it's on. Then we check to see if the title for that submission is in the r/ToR post, mirroring the...
2b1bbaaa709d9944f6ffec4fa2a2d0eca2507d9d
571,973
import torch def test_clf(args, model, test_loader, crit): """ Tests the classification model over the test set. """ model.eval() loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(args.device), target.to(args.device) ...
036f86dba4165dba761bdb1bf13613fb40f184bd
571,976
def is_pythagorean_triplet(a, b, c): """ A Pythagorean triplet is a set of three natural numbers a < b < c for which: a^2 + b^2 = c^2 Example: 3,4,5 3^2 + 4^2 = 5^2 9 + 16 = 25 :param int a: first number :param int b: second number :param int c: third numbe...
4589cb489425ad89650287da530a722d70b9e36e
571,979
def _validate_everything(item): """ Item validator which accepts any item and returns it unaltered. """ return item
b0f48c07c9991a44795e7907efbf7ed6d70cc85e
571,980
def parse_num_list_inv(list_int): """ Take a list of numbers and output a string that reduce this list based on delimiter: ; or : Note: we use ; instead of , for compatibility with csv format. Examples: [] -> '' [1, 2, 3] --> '1:3' [1, 2, 3, 5] -> '1:3;5' :param list_int: list of i...
903177d3521c0bd50e0094b518149ba579d71c1e
571,984
def rotate_image_faster(matrix): """ This is a faster approach from the discussions on leetcode: https://leetcode.com/problems/rotate-image/discuss/1737976/Python-or-visual-explanation-or-complexity-analysis It first transposes the matrix. i.e. or diagonal mirror ---------- |\ | ...
7e489bdee7951a2b9d797f5bb4fa1312942e0c39
571,986
import hashlib def hash_string(source, length=18): """Generate truncated to length hexdigest for provided source string. :param source: string to computes hash from. :type source: basestring :param length: truncate hash to the specified length. :type length: int :rtype: str """ return...
cb40c21660d9f725a2b386620b22eefa69f82062
571,987
def load_table_meta(loader, filename, index): """ Load the meta-data data associated with a table from the specified index within a file. """ return loader(filename, index)
323812b47a29d058d2153cdd61de842d0ec18b68
571,992
from pathlib import Path def get_filename(file_path: str) -> str: """Extract the name of the file from a file path and exclude any file extension""" if not file_path: raise ValueError("Invalid file/folder path") # Replace any backslash(es) in Windows file path with forwardslash(es) file_path =...
facf6c28ac7d775b6d7a33d3721661580b3b5236
571,993
def decimal_isolate(number, digitAmount): """ Isolates the decimal part of a number. If digitAmount > 0 round to that decimal place, else print the entire decimal. >>> decimal_isolate(1.53, 0) 0.53 >>> decimal_isolate(35.345, 1) 0.3 >>> decimal_isolate(35.345, 2) 0.34 >>> decima...
d88a9e627735144543fb6144819f1f89f2acff2d
571,999
def checksum(source: bytes) -> int: """Calculates the checksum of the input bytes. RFC1071: https://tools.ietf.org/html/rfc1071 RFC792: https://tools.ietf.org/html/rfc792 Args: source: Bytes. The input to be calculated. Returns: int: Calculated checksum. """ BITS = 16 # 16-...
b2a605bda741eb899510d38511545bc0d7dbd3d1
572,000
def solution(prices): # O(N) """ Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algori...
52d7e0a0bb013803a091b4c09968d62bb85470d3
572,003
def is_project(dirs, files): """Tests if a directory containing the given directories and files is a Maven project.""" return 'pom.xml' in files
936aa23613d055bf2fb20596c064df643ce524c6
572,004
def generate_module_cmd(module, input_json, output_json): """Generates a command string to use for subprocess calling Parameters ---------- module: str The current module being run input_json: str The path of the input for the module output_json: str The path of the output for the m...
9313fbea1bf7432c90932f96dbc6bd8292dc549f
572,007
def _sort_esystem(evals, evec_collection): """Utility function that sorts a collection of eigenvetors in desceding order, and then sorts the eigenvectors accordingly. Parameters ---------- evals : numpy array The unsorted eigenvalues. evec_collection : list of arrays List where ...
b4f2380cf337296e57460e07c3c074fda6c63f64
572,009
def get_in(coll, path, default=None): """Returns a value at path in the given nested collection.""" for key in path: try: coll = coll[key] except (KeyError, IndexError): return default return coll
4656d16372c64250c242df85cf1de4c0b1dd8530
572,014
def iteritems_nested(d): """ Collect dictionary keys until the deepest level. """ def fetch(suffixes, v0): if isinstance(v0, dict): for k, v in v0.items(): yield from fetch(suffixes + [k], v) else: yield (suffixes, v0) return fetch([], d)
6339a42c241cf163307563b74a6d1901105621a9
572,015
def parse_unsigned_int(data: bytes, bitlen: int): """Parses an unsigned integer from data that is `bitlen` bits long.""" val = '0b' + ''.join([f'{b:08b}' for b in data]) return int(val[0:2 + bitlen], 2)
69b5d57507db5061b4e0d7c82ecdb2b4e40a2c15
572,020
def string_if(x, y): """Returns the sequence x as string if y is one, else x.""" return "".join(x) if isinstance(y, str) else x
fbba930e3b7ffaecd822cb487284e9950408b606
572,021
def flexible_function(*args, **kwargs): """ A flexible function. - With no argument, the function should print "No argument" and return None - With number arguments, it prints "Numbers" and returns the product of the numbers - With named arguments, it prints "Named" and returns the value of the last nam...
3fb1db1a0ee2051e3af879842a5cf14a5c7e3f7d
572,022
def twiddle_bit(bb, bit): """ Flip a bit from on to off and vice-versa """ return bb ^ (1 << bit)
b2520909ce0165d46a72b84cadbb065da2ebd8c2
572,023
import random def roulette(probabilities): """Performs roulette wheel selection given the probabilities. Given a list of probabilities, selects one of the items randomly. The probabilities will be scaled if necessary, so the values do not need to sum to 1.0. Returns the index of the selected it...
38f80bd3ead8080c4d8a157a9f63602abce2bef9
572,025
def Between(field, from_value, to_value): """ A criterion used to search for records having `field`'s value included in a range defined by `from_value` and `to_value`. This is an idea criterion to seahrch using date conditions. For example * search for cases created between two dates * search ...
475c3d95abd792a87f6802e496598e0266553a09
572,029
import json import hashlib def default_observation(case_submitter_id, project_id, date, observation_type, line): """Creates a minimal observation.""" js = json.dumps(line, separators=(',',':')) check_sum = hashlib.sha256(js.encode('utf-8')).hexdigest() return { "type": "observation", ...
64fea2110cb27bd1cd82e7e34fb3826cb3ab5707
572,035
def get_source(data_handler): """Returns uuid (or filename if uuid not found) of the source file.""" return getattr(data_handler.dataset, 'file_uuid', data_handler.filename)
4725ed95eeff324dbebed5adf54476ef7b436157
572,040
def get_filter_value_from_question_option(option): """ Processes `option` into a search term value suitable for the Search API. The Search API does not allow commas in filter values, because they are used to separate the terms in an 'OR' search - see `group_request_filters`. They are removed from t...
ed51bb019a68f04e06ba691d50a2b1a850cb4d78
572,041
from datetime import datetime def datetime_to_cloudwatch_ts(dt): """ Convert a Python ``datetime`` instance to a CloudWatch timestamp, the number of milliseconds after Jan 1, 1970 00:00:00 UTC. """ epoch = datetime(1970, 1, 1, 0, 0, 0) return int((dt - epoch).total_seconds()) * 1000
1901b4775600a77ca08a5e4e44cb34e391cd224c
572,043
def apply_mask(Y, mask, axis=0): """Masks the data along a specified axis Parameters ---------- Y : array-like Data to be masked. mask : array-like Boolean vector containing True for each element to keep. axis : int, optional Axis along which to operate, by default 0. ...
2404c10ba19b743f99ae9f3315b0a561292c6088
572,044
def calculate_metrics(pred_correct_cnt, pred_cnt, correct_cnt): """calculate_metrics calculates metrics: precision, recall, f1-score. Args: pred_correct_cnt (int): the number of corrected prediction pred_cnt (int): the number of prediction correct_cnt (int): the numbert of truth Re...
bd91feb606e95fd2aea4400f5dfb9e9b9cfcb7de
572,045
def get_all_users(client): """ Fetch all users in the team. Includes deleted/deactivated users. """ output = client.api_call("users.list") return output['members']
32dd55651f68d1cddf36877fac3f8dadef7b7116
572,049
def timestampToSequence(response_list): """ Takes a DDB query and returns a dictionary of timestamp: sequence_number """ d = {} for item in response_list: d[item['approximate_arrival_timestamp']] = item[ 'confirmed_sequence_number'] return d
a3d696e7a9a89cb28c806b5be2c6850a7a9eef26
572,050
def splitevery(s, n): """splits a string every num chars and return the list""" return [s[x:x+n] for x in range(0,len(s), n)]
d2d5e15bf1a8aa746b771358f7e65391b4a3c38f
572,052
import torch def create_init_scores(prev_tokens, tensor): """ Create init scores in search algorithms Args: prev_tokens: previous token tensor: a type tensor Returns: - initial scores as zeros """ batch_size = prev_tokens.size(0) prev_scores = torch.zeros(batch_si...
0da0f693041602ed7e79f4f114fedac317419875
572,056
def drop_cols(df, list_of_strings_or_regexp):#,axis=1): """Take a df, a list of strings or regular expression and recursively removes all matching column names containing those strings or expressions. # Example: if the df_in columns are ['price','sqft','sqft_living','sqft15','sqft_living15','floors','bedro...
1aa806f9d1c0ed2b3a80d5af5e0ed2eb12ba3401
572,057
def http_upload_step(data, signed_url, content_type): """Returns a GCB step to upload data to the given URL via GCS HTTP API.""" step = { 'name': 'gcr.io/cloud-builders/curl', 'args': [ '-H', 'Content-Type: ' + content_type, '-X', 'PUT', '-d', ...
7316db122999dc97d1bb83715eb3bf3327a1a16c
572,058
import math def calculate_zoom(fov, height=1.0): """Calculates the zoom (distance) from the camera with the specified FOV and height of image. :param float fov: The FOV to use. :param float height: The height of the image at the desired distance. :rtype: A float representing the zoom (dis...
ddd3fa00a0855c9900ee3ea33bb65379f182818b
572,062
def get_category_link(text: str) -> str: """ Generate a category link. A markdown link beginning with '#' and text split with dash. Args: text {str} The text value to parse Returns: {str} The parsed text """ return f"#{text.lower().replace(' ', '-')}"
e01ad80d33faf0e137722b0468e5e42c8e1d83d6
572,066
def mathproblem(a,b,left=False): """ writes an equation for the math fact a+b=c in which the empty spot is on the right (c is unknown), or on the left if left is True (b is unknown). In other words, the equation is: a + b = ___ or a + ___ = c Examples: >>> mathproblem(1,4) ...
f13eb97d7ab9794a6bd53dfe9f6ac156b8729994
572,068
def apply_dropout(X, mask=None): """apply dropout operation Parameters ---------- X : tensor data to be masked mask : dropout mask Returns ------- masked_X : tensor dropout masked data """ if mask is not None: return X*mask; else: ...
20c7d080da42da39c7f40ea5fd300e169e44cf8a
572,069
def loo(X, axis=0): """Generates leave-one-out selections along a given axis. In the first iteration, the first item is left out. In following iterations, each item to leave out is replaced with the first item. This allows us to only make a single copy and perform all other operations in-place. ...
8285605035e1fee51393b01c9f9e19e396ce5375
572,073
def GetScraper(version): """Returns the scraper module for the given version. Args: version: version string of Chrome, or None for most recent Returns: scrape module for given version """ if version is None: version = "0.1.101.0" parsed_version = [int(x) for x in version.split(".")] if (pa...
2826ca8355a4a9329344af362d9f251b98043a36
572,075
import ipaddress def _IsValidIpv4CidrBlock(ipv4_cidr_block): """Validates that IPV4 CIDR block arg has valid format. Intended to be used as an argparse validator. Args: ipv4_cidr_block: str, the IPV4 CIDR block string to validate Returns: bool, True if and only if the IPV4 CIDR block is valid """...
2dde1d53a399205471d5a70b03f56cf61bca3185
572,077
import re def cleaning_up_product_specifications(text): """ Method used to clean up the feature product_specifications Parameters: ----------------- text (str): text to tokenize Returns: ----------------- text (str): Cleaned text """ text = re.findall(r"\"val...
592741138296fe2b4cc172e18cea91d1adfd0771
572,078
def inputs_to_set(inputSymbols): """Takes in the parameters passed to *args and puts them in a set and a list. The set will make sure there are no duplicates, and then the list will keep the original order of the input. :param inputSymbols: A list, dict, or tuple of stock tickers. :type inputSymbol...
68b4cfcacdfd7b1859e187d7ba4e26602dada062
572,079
from typing import List from typing import Any from typing import Optional def paginate( items: List[Any], offset: int = 0, limit: Optional[int] = None ) -> List[Any]: """ Mimic the behavior of database query's offset-limit pagination """ end = limit + offset if limit is not None else None ret...
f400df1a28feb772d81b28a89fe742bc38053875
572,081
def format_run_status(run, default='-'): """common formatting success boolean field""" if not run: return default return run.success
35f9c3cae32cf0a0082ff9490fb9cd4de19647b6
572,085
def _compute_delta( earlier_sample, later_sample, max_value): """Computes the difference between two samples of a value, considering that the value may have wrapped around in between""" if earlier_sample > later_sample: # Wraparound occurred return later_sample - (max...
f60803c1e1ed5c935e87b75222a1285eccec6164
572,087
def get_per_tensor_fanouts(model): """Returns a dictionary of {tensor_name: tensor_fanout} for the model.""" # make execution context to get a list of tensors per_tensor_fanouts = model.make_empty_exec_context() # replace every tensor with its fanout for tensor_name in per_tensor_fanouts.keys(): ...
ca5c1166801aafb0b8c78d22c2fa3d076e7b3302
572,088
def _SuffixName(name, suffix): """Add a suffix to the end of a target. Arguments: name: name of the target (foo#target) suffix: the suffix to be added Returns: Target name with suffix added (foo_suffix#target) """ parts = name.rsplit('#', 1) parts[0] = '%s_%s' % (parts[0], suffix) return '#'....
f20b1bad11ce591b10c233aece6a7f2d2edca3cf
572,089
def user_name_for ( name ): """ Returns a "user-friendly" version of a string, with the first letter capitalized and with underscore characters replaced by spaces. For example, ``user_name_for('user_name_for')`` returns ``'User name for'``. """ name = name.replace( '_', ' ' ) result = ...
ecbd6c83567251b3d89e49cacd37e7689c9d6442
572,090
def config_database_option(config, key, dbname=None, getbool=False): """ Get database-level config option """ if config is None: return None if dbname is None: return None section = 'database "{}"'.format(dbname) if not section in config: return None return config[section...
fd9f42c06ada9fd1a7f846da6e43ddac71e271fd
572,091
def get_top_rated_actors(top_rated, top_casts): """ Gets all actors with the most movie credits from the top rated list. :param top_rated: dictionary of top rated movies :param top_casts: dictionary of top rated casts :return: sorted list of actors with number of roles they stared in for a top rated...
4d6728d248e09e2d7750430de109a30231e2dd98
572,094
def _CheckNoSandboxedRendererSwitch(input_api, output_api): """Checks that tests do not add the AwSwitches.WEBVIEW_SANDBOXED_RENDERER command line flag. Tests should instead use @OnlyRunIn(MULTI_PROCESS). """ # This will not catch multi-line annotations (which are valid if adding # multiple switches), but is...
3ecc4528efd3b9b680d2a88a3dadbe095599c467
572,095
def _num_difference(obj_a, obj_b): """Return the number of instance attributes present only in one object.""" attrs_a = set(obj_a.__dict__) attrs_b = set(obj_b.__dict__) diff = attrs_a.symmetric_difference(attrs_b) privates = len([x for x in diff if x.startswith("_")]) return len(diff) - private...
9caf11457d00eb2bfc2c44b849c77b38486487ff
572,096
def build_profile_name(account: int, role: str) -> str: """ Builds a profile name from an account ID and role name :param account: the account ID :param role: the role name :return: a profile name """ return f"gatech_{account:12}_{role}"
bfcb399e34befd47174ce589b0d76a29489a8546
572,097