content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import json def has_tweeted_pet_already(pet_url, tweeted_path='.tweeted.json'): """Check if an item has already been tweeted. If not, the item is added to the "already tweeted" list. Parameters ---------- pet_url : str The url of the item that is being checked. Acts like a UUID. ...
57f90e22174963a8f6d81e500351f3fb00ea1073
598,850
import json def _eula_error_message(body: str) -> str: """ Constructs a user-friendly error indicating the required EULA acceptance and the URL where the user can do so. Parameters ---------- body: The body JSON string that may contain the EULA details. Returns ------- The string...
14b6e6c488f32deb4e131890c23efaff332ed726
598,852
from typing import List def _contains(n: float, range_: List[float]) -> bool: """ Test that n is within range (ends included). Order of range entries doesn't matter. :param n: Value to check. :param range_: Start and end of the range to check. :type n: float :type range_: list(float, floa...
ac4f1d981dc810bf50fff3d1cc1c8abb1ae3193d
598,853
def tally(predicate, iterable): """Count how many times the predicate is true. Taken from the Python documentation. Under the PSF license. :param predicate: Predicate function. :param iterable: Iterable sequence. :returns: The number of times a predicate is true. """ return sum(map(pre...
1717fd7c581772fc47a7d371bffcf43067b338aa
598,858
def node_draw_size(node): """given a row of a nodes() dataframe, return the size it should be drawn""" if 'draw_size' in node.axes[0]: # if this value has already been calculated return node.draw_size radius = 0 # aka don't show this node by default if 'HoursFlooded' in node and node....
4dbb03796bcfa896441fd7005d29f9929372154d
598,862
def infer_grid(img): """Infers 81 cell grid from a square image.""" squares = [] side = img.shape[:1] side = side[0] / 9 for i in range(9): for j in range(9): p1 = (i * side, j * side) # Top left corner of a bounding box p2 = ((i + 1) * side, (j + 1) * side) # Botto...
c35ae7a9ba0113e3798f75c59e9743bfcb53f1e2
598,866
def get_next_address(previous_address: int, both_addresses_xored: int) -> int: """ Returns the next address given the previous address and the xor of previous and next addresses :param previous_address: The address of the previous node :param both_addresses_xored: The XOR of the previous and the next node :retur...
96c42804a1c5bf5b7928af891881c1928df862d3
598,867
def lc(value): """Lower case and remove any periods to normalize for comparison.""" if not value: return u'' return value.lower().replace('.','')
7f1c0e703f632931e7117f198ba4592c3b174e0f
598,868
def get_tool_dependency( trans, id ): """Get a tool_dependency from the database via id""" return trans.sa_session.query( trans.model.ToolDependency ).get( trans.security.decode_id( id ) )
14619a3705dbd42732a2b7e4c06f04e0827df101
598,871
def add(*args): """Add all of the arguments together. If no arguments, then zero is returned (the neutral element of +) """ accumulator = 0 for v in args: accumulator += v return accumulator
6b06266397aded7e52e5c0169f2a371a7210d095
598,872
import math def find_distance_2d(p, q): """ Returns the distance between two points Parameters ---------- p: list a two-value list where p[0] is the x_value and p[1] is the y_value of 2nd point q: list a two-value list where q[0] is the x_value and q[1] is the y_value of 2nd ...
9d98c2a346e3b9f74ef042f41ce6417aa4b65318
598,874
def recursive_dichotomy(list, value, beginning, end): """ list: array of integers in ascending order value: value to return its position in the list beginning: first index of list (in this case 0) end: last index of list (in this case len(list)) return: False in value not in list, else the position of value...
a677ef0f7f0e4cc843da4fa96303655776d4515d
598,875
def bqm_reduced_to(bqm, variables, sample, keep_offset=True): """Reduce a binary quadratic model by fixing values of some variables. The function is optimized for ``len(variables) ~ len(bqm)``, that is, for small numbers of fixed variables. Args: bqm (:class:`dimod.BinaryQuadraticModel`): ...
ac6ba989e2ed5404004be621c64be19705128d38
598,877
import codecs def bom_strip(content: str, strip=True) -> str: """Remove the UTF-8 BOM marker from the beginning of a string. Args: content: string to remove BOM marker from if found strip: remove whitespace before & after removing BOM marker """ if strip: content = content.str...
0a527bd56d76ba58555cdab76a37252a9b47f58a
598,880
def rate_limit(limit: int, key=None): """ Decorator for configuring rate limit and key in different functions. :param limit: :param key: :return: """ def decorator(func): setattr(func, 'throttling_rate_limit', limit) if key: setattr(func, 'throttling_key', key) ...
ef1cf8ca57e0df5574381b1f4aeddffa90113fe2
598,881
import random def seed42(request): """A fixture that sets the random seed to 42, for consistency""" random.seed(42) return request
7abb0a70a2a147569e291d1511851fb74d66bdb2
598,884
def colour_distance_squared(colour1, colour2): """Square of the Euclidian distance between two colours""" dist_squared = sum((a - b) ** 2 for a, b in zip(colour1, colour2)) return dist_squared
378e05441f742fdf09e35528779d565fa3d2bcaa
598,887
from typing import Union from pathlib import Path from typing import Optional def get_cache(cache_dir: Union[Path, str], tile: str) -> Optional[bytes]: """Retrieve data from the cache :param cache_dir: Cache directory :param tile: Tile to attempt to retrieve :return: Tile from cache or None if not in...
59d592f57ff56cc62f99241b889ad918bbf1f3ae
598,890
def get_strongly_connected_node(graph, nodeset): """ Returns the node connected to the given node set the strongest. Returns None if there are no more nodes left. """ max_weight = 0 res = None for node in graph.nodes(): if node not in nodeset: cur_weight = 0 ...
d84e701a5c490834ebe0ea805a30a70ca1fdfcdb
598,892
def get_qualified(module, name): """Return a qualified module member ``name`` inside the named ``module``. The module (or package) first gets imported and the name is retrieved from the module's global namespace. """ # see __import__.__doc__ for why 'fromlist' is used module = __import__(m...
c2ebee0eaf6e5431bfc9d0fe22c88906d6fb6d4d
598,898
import math def _dcg(label, rank, weight=1.0, gain_fn=lambda l: math.pow(2.0, l) - 1.0, rank_discount_fn=lambda r: 1. / math.log(r + 1.0, 2.0)): """Returns a single dcg addend. Args: label: The document label. rank: The document rank starting from 1. weigh...
a201a7e46584b636f5a9972fcbdfa968606bf754
598,900
from typing import Dict def token_auth_header_field(token: str) -> Dict[str, str]: """ Bearer Token Authentication. Returns the "Authorization" header and token for use in a request. :param token: The basic authorization token. :return: A authorization header dictionary. """ return {"Aut...
028e3e6b2e43c134f6f51368fa3bd74529ac2cfe
598,906
import torch def _get_minibatch_jacobian(y, x): """Computes the Jacobian of y wrt x assuming minibatch-mode. Args: y: (N, ...) with a total of D_y elements in ... x: (N, ...) with a total of D_x elements in ... Returns: The minibatch Jacobian matrix of shape (N, D_y, D_x) """ ass...
dbc31dde566470c6acba71e72276343966f25196
598,907
import yaml def get_data(file_path): """ Loads the file from a location and returns the structure, the file is in YML and is converted to a dict :param file_path: :return: dict (treated as the same as JSON in python) """ with open(file_path) as inf: content = yaml.load(inf, Loader=...
57019e66f284aac511399f92962e585a91747691
598,911
def dct_reduce(reduce_fn, dcts): """Similar to `reduce`, but applies reduce_fn to fields of dicts with the same name. >>> dct_reduce(sum, [{"a": 1}, {"a": 2}]) {'a': 3} """ keys = dcts[0].keys() return {key: reduce_fn([item[key] for item in dcts]) for key in keys}
30daff2cb8c293adb6fe6cd3b04ec6364cddd905
598,913
def is_admin(user): """Checks if the user object is a member of the admin group or not.""" x = user.groups.filter(name='admin') return x
47a7d1cd718c37b4d87cd94e51c3cc39f742876c
598,914
def countBytes(arrays, base=False): """Returns total number of bytes consumed by elements of arrays. If *base* is **True**, use number of bytes from the base array.""" if base: getbase = lambda arr: arr if arr.base is None else getbase(arr.base) nbytes = lambda arr: getbase(arr).nbytes ...
60340c18ab15db97ca2936bfc6cf23706437b0c6
598,916
def all_databases(client, exclude=['local']): """ Yield all databases except excluded (default excludes 'local'). """ return ( client[db_name] for db_name in client.list_database_names() if db_name not in exclude )
2a7328d07520528915bf153fc2b40adbea071494
598,917
def get_segment_qname(segment): """ Return the qualified name of a read segment. :param segment: read segment :type segment: pysam.libcalignedsegment.AlignedSegment :return: qualified name :rtype: str or unicode """ return segment.qname
c36097809cc3552f8eb4962be383e948d3fefe50
598,920
def get_match_anchored(git_pattern: str) -> bool: """ is the pattern relative to the ignore file base directory The slash / is used as the directory separator. Separators may occur at the beginning, middle or end of the .gitignore search pattern. If there is a separator at the beginning or midd...
1d543eb3ef35697bbde9b31b17d969915f4ec69a
598,923
def parse_bool(value): """Parse string that represents a boolean value. Arguments: value (str): The value to parse. Returns: bool: True if the value is "on", "true", or "yes", False otherwise. """ return (value or '').lower() in ('on', 'true', 'yes')
43d8f3f54876718ae3b6c6b6237e9bb56d562780
598,924
def _GetObjcName(attr): """Returns the Objective-C name for the given attribute.""" if attr.name.startswith('init'): return 'getI' + attr.name[1:] return attr.name
db8819567c5636ddd783330d84a92be8ba23fb77
598,929
from random import uniform def randseg(start, stop, seglen): """Returns a random segment of length seglen between start and stop. Raises ValueError if the segment is not long enough. """ if stop-start < seglen: raise ValueError a = uniform(start, stop-seglen) b = a+seglen return (a, b)
17756af0c24909240fe6771da14cc46625a3031b
598,931
def compare_word(word_a: str, word_b: str) -> int: """Compare word property of `word_a` to `word_b` (unambiguous) Arguments: word_a {ScoredKeyword} -- keyword word_b {ScoredKeyword} -- keyword Returns: int -- `word_a lt word_b`: -1, `word_a eq word_b`: 0, ...
524c29b1c5323b8b09d823a4214147d281e68101
598,936
def slice_2d(X, rows, cols): """ Slices a 2D list to a flat array. If you know a better approach, please correct this. Args: X [num_rows x num_cols] multi-dimensional data rows [list] rows to slice cols [list] cols to slice Example: >>> X=[[1,2,3,...
a29acf960cb97d497ff6901d3e855a1c270bdf4c
598,941
def builtin_2nrotate(a, b, c, d, e, f): """Modify the stack: ( a b c d e f - e f a b c d ).""" return (e, f, a, b, c, d)
46b4b5348aac7bb1dff53d386b0fe62837c20cd2
598,945
def search_snapshot(snapshot_list, name): """Search recursively for the snapshot with the specified name. Args: snapshot_list (list): vm.snapshot.rootSnapshotList name (string) : snapshot name Return: vim.vm.Snapshot else None """ output = None for snap in snapshot_list...
0e50b8a71bdb9e207dd03a3da5def3b64698a4c9
598,947
import re def space_in_words(objects_string): """Insert a space between objects that have more than one capital letter eg. AntibodyChar --> Antibody Char""" add_space = re.sub(r"(\w)([A-Z])", r"\1 \2", objects_string) return add_space
eb61aaeb08ac7b09511b733e7d42eb5d3d6d768e
598,951
import random def random_split(L, nM=None): """ Split sequence L into two random subsequences M, N Length of M will be nM (defaults to len(L)//2) Return M, N """ nL = len(L) if nM == None: nM = nL//2 mark = [False for _ in range(nL)] for i in random.sample(range(nL), nM): ...
913a6f79c0e7ba1e535f4388e653e198f33a1f59
598,953
import re def __replace_tokenizer_toks(code_snippet: str) -> str: """ Function to replace special tokens introduced by the tokenizer/model (bos, eos, pad) :param code_snippet: String representing the code snippet :return: String containing the clean string """ pattern = re.compile("|".join(["<...
784554bcf8cc65f57c989f37c5e746fc30afe1d1
598,954
def filterOnNamespace(GOdict, namespace): """ Reduces the dictionary of goTerm objects to those belonging to a specific namespace. Parameters ---------- GOdict : dict A dictionary of GO objects generated by importOBO(). Keys are of the format `GO-0000001` and map to goTerm objects. ...
22da05edad74f788e8552f87db4f070ad31c7f2c
598,956
def get_round_digits(pair): """Get the number of digits for the round function.""" numberofdigits = 4 if pair: base = pair.split("_")[0] if base in ("BTC", "BNB", "ETH"): numberofdigits = 8 return numberofdigits
1dcdd675900a451f34c5fb0baa79d4b8da68c62d
598,961
import uuid def get_submission_meta_dict(xform, instance_id): """Generates metadata for our submission Checks if `instance_id` belongs to an existing submission. If it does, it's considered an edit and its uuid gets deprecated. In either case, a new one is generated and assigned. :param onadata....
489c8b646e2b16d39db5d47b7891c9ee216db197
598,964
def _leading_zero(l1): """ Add leading 0 if necessary """ return l1 if len(l1) == 2 else '0' + l1
ad9c110487ad9d65820a17a9096d5351f213c486
598,968
import torch def fft2(Z): """ Takes 2d FFT of the last two dimensions of Z. Args: Z: a data matrix (*, H, W) Returns: A tensor with the last two dimensions equal to 2d FFT of Z (*, H, W) """ return torch.fft.fft2(Z, norm="ortho")
f0f2ba8cb2f270706db119b4134a7cff5fbfadc5
598,971
import json def load_json(file_path: str) -> dict: """ Load json file. :param file_path: absolute file path. :return: a dict. """ with open(file_path, 'r') as f: result = json.load(f) return result
bfe3f4f9feb29589c7f5804de22ccd8e1b352d71
598,976
def from_epsg(code): """Given an integer code, returns an EPSG-like mapping. Note: the input code is not validated against an EPSG database. """ if int(code) <= 0: raise ValueError("EPSG codes are positive integers") return {'init': "epsg:%s" % code, 'no_defs': True}
1680a365ec01ddb81d314a899c6dc818d466bc65
598,977
def get_loc_lab(lat, lon): """Construct the USGS location label Construct a lat/lon location label such as n01e002 that is part of the labels used by the "Staged Products" HTTPS web directory access for USGS 1-arcsecond DEM TIFF files. Args: lat (int): Latitude lon (int): Longitude...
f6f789f480a9998fdecc2420802a0e818ae37c1e
598,980
import torch def tile_batch(x, multiplier, batch_dim=0): """Copy several times for all the tensors in a batch Given a batch of tensors whose shape is [..., bsz, ...], `tile_batch` copy all the tensors in this batch with k times (=> [..., bsz, k, ...]), and then restore its original dimension (=> [..., bs...
51eb221e267232211a8208f532ae77f9f8899c4d
598,982
def prc_list(mod): """ Retuns a list of partial response coefficients of a model. The list contains both species and flux partial response coefficients and partial response coefficients follow the syntax of 'prc_responder_parameter_route'. Parameters ---------- mod : PysMod The...
6afe9bb95201efdd76d19bdeca12ebf70fed5530
598,984
def get_scores(model, X_train, y_train, X_valid, y_valid, show = True ): """ Returns train and validation error given a model train and validation X and y portions Parameters ---------- model: sklearn classifier model The s...
b613fdef88bb062b1cc6e263eb7caeea630f31bf
598,988
def upper_chars(string, indices): """ Make characters uppercase in string :param string: string to modify :param indices: character indice to change to uppercase :return: uppercased string """ upper_string = "".join(c.upper() if i in indices else c for i, c in enumerate(string)) return ...
409a0dc99649d1ee5a3e8def0fa618f89b43b949
598,990
import re def isolate_glossary(word, glossary): """ Isolate a glossary present inside a word. Returns a list of subwords. In which all 'glossary' glossaries are isolated For example, if 'USA' is the glossary and '1934USABUSA' the word, the return value is: ['1934', 'USA', 'B', 'USA'] """...
2d16abc8f75007b6a043f81bcf9ffb7e35742184
598,993
import torch def get_backward_segment(backward_rnn_output, s, e, device): """Gets span representation in backward rnn Arguments: forward_rnn_output {tensor} -- backward rnn output s {int} -- span start e {int} -- span end device {int} -- device Returns: tensor -- ...
11189a690b1fb9b0420657882a47093f1099589b
598,995
import itertools def find_target(input, target=2020, combinations=2): """ Finds 'combinations' numbers that add up to 2020 Part 1: >>> find_target([1721, 979, 366, 299, 675, 1456]) (1721, 299) Part 2: >>> find_target([1721, 979, 366, 299, 675, 1456], combinations=3) (979, 366, 675) ...
fc26d4d08e59156b9970d82900c95bef5ba3e464
598,996
def ask(question: str) -> str: """Prints question and returns user input. Waits for newline.""" print(question) answer = input('> ').strip() return answer
25e8c3e0d10b166041ec830fe89ccc15dd9fdc67
598,999
def getFontSize(scale, image_size): """ Returns the font size depending on the size of the image scale - How large the font should be image_size - tuple of width and height of image @return - floating point value of font size """ imageScale = 2000. totalSize = image_size[0] + image_size...
c477f6d9abd472bfabee9fe61c44ed4be280c8d6
599,000
import math def getDist (mesh, i, j): """Calculates distance between two mesh vertices as described by index numbers.""" a,b,c, = mesh.vertices[i,0], mesh.vertices[i,1], mesh.vertices[i,2] d,e,f = mesh.vertices[j,0], mesh.vertices[j,1], mesh.vertices[j,2] dist = math.sqrt((a-d)**2 + (b-e)**2 + (c-f)**...
447a82a1b93511e0e5e7c6f340064acb5267d209
599,001
def fmt_shell_cmd_log_file_prologue(cmd): """ Create the prologue for a log file which holds the result of the execution of `cmd` """ return """$ %s %s """ % (cmd, "-" * 50)
cdd1923f0efef78b5f7ca610cf447ec37914ff1a
599,003
def partial_db_name(db_name, i): """Generates temporary database name.""" return '%s___%d.db' % (db_name.strip('.db'), i + 1)
9d70bb1535a4abb091a5e3607bab6f7599c3a2ad
599,005
def sql_esc(pattern): """ Apply SQLite escaping, if needed. Returns pattern and esc. """ esc = '' if "_" in pattern or "%" in pattern: esc = ' ESCAPE "!"' pattern = pattern.replace("!", "!!") pattern = pattern.replace("%", "!%") pattern = pattern.replace("_", "!_") return...
3480eebd5e79a4b7482798f79e16ef85b05a524a
599,006
def example_function(x): """Example function. :param x: Example argument. :type x: ``int`` :returns: ``int`` -- Doubles the argument. """ return 2 * x
95bda0c4aa78c665a94ba63acc37f74c4e020f75
599,010
def _get_rule_conditional_format(type_, values, format_, ranges): """ Get rule to conditionally highlight cells. :param type_: Type of conditional comparison to make. :param values: User entered values (using '=A1' notation). :param format_: Format of cells matching condition. :param ranges: Ran...
ed48c99b0f1486712d94e9fc503645371e41bc90
599,013
def is_satisfied(label, signal_values): """ Do signal values satisfy the label? >>> is_satisfied({'r':True}, dict()) True >>> is_satisfied(dict(), {'r':True}) True >>> is_satisfied({'r':True}, {'r':True, 'g':False}) True >>> is_satisfied({'r':True, 'g':False}, {'g':False}) True ...
540bb25d8feb498e018289a06e2d3d61405734f8
599,016
import torch import math def standard_normal_cdf(value): """ Compute the componentwise cdf of a gaussian with 0 mean and I covariance matrix Parameters ---------- value: float(s) Value to compute the cdf of Returns ------- float(s): The cdf applied to value """ ...
65ef70bb111d104c23e93c61e308df46c80cdb40
599,019
def m_to_f(meters): """ Convert meters to feet """ return meters / 0.3048
1d71796ab0c46469629d397ece20199e70799be7
599,027
import math def derive_similarity_tag(dag, log_base=1.618): """Derive the tag for similarity check from one computational DAG. The DAGs with the same tag are considered as similar tasks. The tag format is <op1-tag>_<op2-tag> ... <log(flop)>. If the tag is "", then the task is not considered to be si...
6a499422bfa5b9b05bb3b2a5f68e3fba31d224d8
599,029
def dfs_all_values(dfs, column): """Find all possible values of a column in the pandas.DataFram list :param dfs: list of pandas.DataFrame objects to draw on the subplot :type dfs: list[pandas.DataFrame] :param column: a columns :type column: str :return: a sorted list of possible values from th...
6300dd67307e2453fa7545834cf1eeffc8c1bb3b
599,033
def decide_alerting(oncallnumber, cfg): """Return the text provider to use depending on the conf and the number.""" # select the right sender depending of the number if oncallnumber[0:2] == "33": notifier = cfg["FR_sender"] else: notifier = "twilio" return notifier
a4241da3f92919b8f027358dc35415fe2f524940
599,034
def check_for_chr(sam): """ Check sam file to see if 'chr' needs to be prepended to chromosome """ if 'chr' in sam.references[0]: return True return False
22297aa592faab69d4f7293975738e51fdbacc24
599,037
def generate_new_row(forecast_date, target, target_end_date, location, type, quantile, value): """ Return a new row to be added to the pandas dataframe. """ new_row = {} new_row["forecast_date"] = forecast_date new_row["target"] = target new_row["target_end_date"] = targ...
212438098b7ad56f2046fdc3c5f6a73cab96f420
599,042
import re def parse_path_info(path): """Returns None or (year, theme) tuple. Handles urls of this type: - /2003 - /2003/ - /2003/index - /2003/index.theme """ match = re.match(r'^/(\d{4})(/index.*)?', path) if not match: return year, index_theme = match.groups() ...
9f6f8ede2d5ee3d5b49bac5f0b0d7fb745d4e470
599,046
def setup_element(format_element, element_count, max_element_count): """Interpolate element specific setup string.""" return format_element.format( max_element_count=max_element_count, element_count=element_count )
9b4e74abfa2361d83180a2ae6a83c7a5901efad3
599,049
def shlok_lengths(shlokasSyllables): """Return a dictionary of lengths of syllables of shlokas in shlokasSyllables. Input shlokasSyllables : list of lists of syllables in every shloka Ouptuts shlokLengths : dictionary of shlok_lengths:shlok_numbers """ shlokLengths = {} for i, shlokSylla...
b3253405aa435d90ecaaa60e6a7f5f77ea06ce68
599,050
def get_type(type_name, value): """Convert a string value to correct type based on a type specification""" if 'int' in type_name: return int(value) if 'float' in type_name: return float(value) if 'bool' in type_name: return 'True' in value if 'str' in type_name: retur...
7b2eb05717524a21ef36cd5ed26a104d9c82a3cd
599,051
def get_index(value, bitindex): """ Returns the bit at position `bitindex` of the integer `value` Parameters ---------- value : Integer Input value bitindex : Integer Bitindex selector of `value` """ # bitstring = '{0:32b}'.format(value) r...
88add805f98e930abab09ab9a518d5c8e1c22d4d
599,053
def get_features_lag(df, lag=1): """Get the time series lag Parameters ---------- df : dataframe DataFrame with the time series to lag lag : int Number of times the series will lag behind Returns ------- df_lag A DataFrame whit the lags of time series """ df_lag = df.shift(lag) df_lag.columns = ["...
b1c40bc7ab6fdb7b0484d89c9057faa04ef32110
599,059
import re def slugify(text): """Create a good-enough slug for the given text""" return re.sub(r'\W', '-', text).lower()
9e53cfe861ef01dd7cdd288de774b02a1e9f1c4e
599,061
def _split2(list_): """ Splits a list in 2 sublists. """ list_length = len(list_) if (list_length == 2): return (list_, []) else: midpoint = int(list_length / 2) return (list_[0:midpoint + 1], list_[midpoint:list_length])
00ec53328cac4d46717c208ba3beac18417dc308
599,063
from typing import Dict from typing import List def traverse_graph(root: str, graph: Dict[str, List[str]], depth: int) -> List[str]: """ Perform an iterative, DFS-based traversal of a given dependency graph. The provided `depth` arg determines how many layers you want to traverse. The smaller the number,...
337951d24ad5525e943566e4d2e2477d0d418864
599,067
def round_even(n): """Round a number to the nearest even integer.""" r = int(n) return r + 1 if r & 1 else r
88fd164cd9c143134b97d0584566d1b965a30814
599,071
def dict_minus(d, *keys): """Delete key(s) from dict if exists, returning resulting dict""" # make shallow copy d = dict(d) for key in keys: try: del d[key] except: pass return d
b4511f5239921f6c6054c36d42b0acfb7a0476c2
599,075
def get_target_image_size(image_size, size_factor): """ Given an image_size tuple and size_factor, return a new image_size tuple that is a multiple of size_factor and as close to original image_size as possible :param image_size: tuple of two integers :param size_factor: integer :return: tuple o...
d2ba8f5c019d2afd36781b74fa8a6d6919c363a4
599,076
def get_damage(attacker, defender): """Get damage dealt by attacker to defender.""" damage = attacker['Damage'] - defender['Armor'] return damage if damage > 0 else 1
3bb570cb84b2a54a9c6e209eb0db152eae6b17c8
599,079
def gethHfieldop(hx, hy, hz, l=2): """ Return magnetic field operator for one l-shell. Returns ------- hHfieldOperator : dict Elements of the form: ((sorb1,'c'), (sorb2,'a') : h_value where sorb1 is a superindex of (l, s, m). """ hHfieldOperator = {} for m in ra...
4d9f7e343de40fe68d8b4b2ee49ca894c5e063fb
599,087
def get_daily_ncname(year): """Get the daily netcdf filename for the given year""" return f"/mesonet/data/iemre/{year}_iemre_daily.nc"
f5aaac71ecb252163c697d8a49402cfab9e70095
599,090
def _get_package_name(package): """Get the name (or filename) for a package.""" return package["name"] or package["filename"]
7d91af326c07e350727d0cbaffa3648791bb51f2
599,091
import _struct def from_native_int64( raw_bytes, offset ): """ Reads a native-Endian 64-bit signed integer from an array of bytes. """ return _struct.unpack_from( "=q", raw_bytes, offset )[ 0 ], offset + 8
cf33c35a225e7d75b3a6bb9d38bc4c52c52c0c6d
599,094
def getVersions(lists:list, releases:dict) -> dict: """ Transform list of versions and releases in dictionary of versions Parameters ---------- lists : list lisf of versions releases : dict dictionary of all releases in one package Returns ...
fd2fff0cdcc28fc898cbb521b173869df2cc1a06
599,098
def time_based(t, eta_init, last_eta, d = 0.01): """Time-based learning rate with decay d.""" return last_eta/(1+d*t)
0d56d1cf8142b6364957d3723567c9d231b555e1
599,102
import torch def mask_tokens(inputs, tokenizer, mlm_probability=0.15): """ Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. """ labels = inputs.clone() # We sample a few tokens in each sequence for masked-LM training (with probability args.mlm_probabili...
0cada10e2ea46acf6bb995b194e922ad5414b864
599,107
def __long_substr(strings): """ Returns longest common substring of list of strings. taken from: # https://stackoverflow.com/questions/2892931/longest-common-substring- from-more-than-two-strings-python Parameters ---------- strings: list A list of strings. Returns -------...
a8596c6e027414fcd7f09a6bcbb3fa9e4588ad02
599,108
import re def name2label(name): """ Took from ToscaWidgets2. Convert a column name to a Human Readable name. 0) Take only last part of name leading to subfields 1) Strip _id from the end 2) Convert _ to spaces 3) Convert CamelCase to Camel Case 4) Upcase first character...
a3bf8559dd7ba1f696f47a0db0b6e48109db6020
599,109
def watt_hours(watts, hours): """Multiplies watts times the hours used""" return watts * hours
38e367ef25754fa47212b2459571fa6c3e6625d2
599,111
def rescale(tensor, max_, min_): """ Rescale a pytorch tensor to [0,1]. tensor: pytorch tensor with dimensions [batch,channels,width,height] max_: pytorch tensor containing the maximum values per channel min_: pytorch tensor containing the minimum values per channel outputs -> rescaled pytorch tenso...
c706f34bc821dc5f77b91353d8ba6d8a972faac8
599,119
import random def split_data(tweets, validation_split=0.1): """Split the data into training and validation sets Args: tweets (list): list of tuples validation_split (float, optional): validation split % Returns: (list, list): training-set, validation-set """ index = int((...
e6a60caeed6ea8d06fb782571a9709c7e004b03e
599,121
def age_bracket(x): """ Converts ages from [15,65] into age brackets (1,5). If age is out of that range, returns None Integer -> String """ if 15 <= x < 25: return '1' elif 25 <= x < 35: return '2' elif 35 <= x < 45: return '3' elif 45 <= x < 55: ret...
95963b7f2b9a07ee090e6e4a6d049ebe9dc402e1
599,123
def _compute_x_crossing( x1: float, y1: float, x2: float, y2: float, y_star: float) -> float: """Approximates the x value at which f(x) == y*. Args: x1: An x value. y1: f(x1). x2: An x value, where x2 > x1. y2: f(x2). y_star: The search value in [y1, y2]. Returns: The x value that gi...
ceb106ddfe865005b8e911e4a5ae63de2b11460d
599,124
def join_columns_with_divider(table, decorator): """Join each line in table with the decorator string between each cell""" return [decorator.join(row) for row in table]
3c87f1ccbd6ee58dac7e4375f8eb50d61fa22388
599,126
def should_skip_commit(commit): """Decides if |commit| should be skipped when computing the blame. Commit 5d4451e deleted all files in the repo except for DEPS. The next commit, 1e7896, brought them back. This is a hack to skip those commits (except for the files they modified). If we did not do this, cha...
6d33400ca4337523cec669b59ace1ad881e6fb04
599,127