content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def user_is_mozillian(user): """Check if a user belongs to Mozillians's group.""" return user.groups.filter(name='Mozillians').exists()
09216ccdfaadbe44be9a0113bddea901b709447e
680,991
def compute_age(date, dob): """ Compute a victim's age. :param datetime.date date: crash date :param datetime.date dob: date of birth :return: the victim's age. :rtype: int """ DAYS_IN_YEAR = 365 # Compute the age. return (date - dob).days // DAYS_IN_YEAR
39a88d3f780f46b50d4d64aa0f05f54d20389396
680,992
import io def _read_bytes(fp, size, error_template="ran out of data"): """ Read from file-like object until size bytes are read. Raises ValueError if not EOF is encountered before size bytes are read. Non-blocking objects only supported if they derive from io objects. Required as e.g. ZipExtFile ...
388a244d26bf030db1fc18086c64779a34bf904e
680,993
from pathlib import Path def extract_extension_from_file(file: str) -> str: """Extract extension from file name. :param file: Path of file we want to extract the extension from. :return: Extension of file (e.g., mp3) """ return Path(file).suffix.lower()[1:]
e20a50662c519c69187ae2cb3d929afc6cfb615c
681,001
def _is_model(layer): """Returns True if layer is a model. Args: layer: a dict representing a Keras model configuration. Returns: bool: True if layer is a model. """ return layer.get('config').get('layers') is not None
bb19a8c2da747a98c3d34c85902a3a1f989b6c44
681,003
def check_blank_after_last_paragraph(docstring, context, is_script): """Multiline docstring should end with 1 blank line. The BDFL recommends inserting a blank line between the last paragraph in a multi-line docstring and its closing quotes, placing the closing quotes on a line by themselves. """ ...
64f32e62a65d513e092a501db6fcdcd1ca9ce9db
681,013
import re def normalize(tokens : list) -> str: """ Removes non-english characters and returns lower case versions of words in string form. """ subbed = [re.sub("[^a-zA-Z]+", "", s).lower() for s in tokens] filtered = filter(None, subbed) return " ".join(list(filtered))
9997d779f8b92894aa641b1b14e43ab182018619
681,015
def one_or_more(pattern, greedy=True): """ one or more repeats of a pattern :param pattern: an `re` pattern :type pattern: str :param greedy: match as much as possible? :type greedy: bool :rtype: str """ return (r'(?:{:s})+'.format(pattern) if greedy else r'(?:{:s})+?'.form...
83158602e863210c178e6dcee2b650655971fef0
681,016
def isstringlike(item): """Checks whether a term is a string or not""" return isinstance(item, str)
db0a88ebea37a5050e212db130da02bc6bdc07d5
681,018
def _update_gn_executable_output_directory(commands): """Update the output path of executables and response files. The GN and ZN builds place their executables in different locations so adjust then GN ones to match the ZN ones. Args: commands: list of command strings from the GN build. Retur...
68e14ca2e8d20b5d8a7462de8883a60c071636bf
681,020
def innerscripts_to_array(p): """Extracts inner scripts from page""" res = [] all = p.xpath('//script') for tag in all: if 'src' in tag.attrib: continue else: item = {'text' : tag.text_content()} if 'type' in tag.attrib: item['type'] = tag.attrib['type...
66780626b854ecefdf629b1b7ba8d7327dcd206e
681,022
def validate_int(arg): """Guard against value errors when attempting to convert a null to int""" if len(arg) < 1: return 0 return int(arg)
ab7cc52f4f8330840b6406cafd01b3a594e0e451
681,023
def genome_size(peaks_file, haploid=True): """ Finds the genome size of an organsim, based on the peaks file created by kmercountexact.sh :param peaks_file: Path to peaks file created by kmercountexact. :param haploid: Set to True if organism of interest is haploid, False if not. Default True. :retu...
4dac59dc012e5d101479e3055ae668fe1e4484c5
681,024
import time def issued_and_expiration_times(seconds_to_expire): """ Return the times in unix time that a token is being issued and will be expired (the issuing time being now, and the expiration being ``seconds_to_expire`` seconds after that). Used for constructing JWTs Args: seconds_to_ex...
0f2fc78f94cf605e784083cc805cf67858ee8b5c
681,029
def get_json(request_obj, remove_token=True): """ This function is responsible for getting the json data that was sent with with a request or return an empty dict if no data is sent Args: ~~~~~ request_obj: request object that data should be attached to Returns: ~~~~~~~~ di...
e3dc01488df4fbe2b54f2f9a88df1e5beb443992
681,032
def parse_op_and_node(line): """Parse a line containing an op node followed by a node name. For example, if the line is " [Variable] hidden/weights", this function will return ("Variable", "hidden/weights") Args: line: The line to be parsed, as a str. Returns: Name of the parsed op type. N...
3ea15d42192286bd8b81b0f0f5fdf0c2be7f8c93
681,033
from typing import List def lines_to_list(lines: str) -> List[str]: """Split a string into a list of non-empty lines.""" return [line for line in lines.strip().splitlines() if line]
970615170ac035f945982f188190f3920550e251
681,034
def _invert(ax,x,y): """ Translate pixel position to data coordinates. """ try: xdata,ydata = ax.transAxes.inverted().transform((x,y)) except: # Support older matplot xdata,ydata = ax.transAxes.inverse_xy_tup((x,y)) return xdata,ydata
ee27170a977ab5c3d2798b49a67412e1e8fd21d7
681,035
def r(line): """ Selects rho from a given line. """ r, _ = line return r
555f4fecc67f895ddf69f568b856ab7a8bdad3dd
681,037
def get_value_counts_categorical(df, column, alt_filter, ascending=False): """ Count the number of rows in `df` where `alt_filter == True` for each unique value in `df.loc[alt_filter, column]`. Parameters ---------- df : pandas DataFrame The dataframe containing the column that we wish ...
837ac319a4937739f731cb6e4ae7072879a651e0
681,039
def canonicalShape(shape): """Calculates a *canonical* shape, how the given ``shape`` should be presented. The shape is forced to be at least three dimensions, with any other trailing dimensions of length 1 ignored. """ shape = list(shape) # Squeeze out empty dimensions, as # 3D image can ...
0f11a7298253fe9655846a663f5761cd17ae2880
681,045
def _to_long_sha_digest(digest, repo): """Returns the full 40-char SHA digest of a commit.""" return repo.git.rev_parse(digest) if len(digest) < 40 else digest
d1a7bc87e32917b2ef24db8b201e7f2509d705a8
681,049
import torch def tversky_index(yhat, ytrue, alpha=0.3, beta=0.7, epsilon=1e-6): """ Computes Tversky index Args: yhat (Tensor): predicted masks ytrue (Tensor): targets masks alpha (Float): weight for False positive beta (Float): weight for False negative ...
c6c13e26555467469829ee2f9b4096ff0705ee99
681,052
def _is_plugable_7port_hub(node): """Check if a node is a Plugable 7-Port Hub (Model USB2-HUB7BC) The topology of this device is a 4-port hub, with another 4-port hub connected on port 4. """ if '1a40:0101' not in node.desc: return False if not node.HasPort(4): return False return '1a40:0101' in...
a2725a708fb9bc6d7611d0b278545c503152d7e2
681,053
def load_file(filename): """ Loads and returns the contents of filename. :param filename: A string containing the filepath of the file to be loaded/ :type filename: str :return: Contents of the loaded file. :rtype: str """ with open(filename, "r") as fh: return fh.read()
3685ffa5faa775805ff5d4fa13750b9874cef752
681,057
def morphology_used_in_fitting(optimized_params_dict, emodel): """Returns the morphology name from finals.json used in model fitting. Args: optimized_params_dict (dict): contains the optimized parameters, as well as the original morphology path emodel (str): name of the emodel ...
1f935675543a178d65021cfad8f5b4aa5b0d9951
681,058
def rivers_with_station(stations): """ Args: stations: list of MonitoringStation objects Returns: A set of names (string) of rivers that have an associated monitoring station. """ rivers = set() for s in stations: rivers.add(s.river) return rivers
e866eedcffb25cff8a6a682401db1484f1009d7c
681,064
def f16(value): """ Multiply with maximum value of a number 16bit (0xFFFF) :param value: Input value :return: value * 0xFFFF """ return int(round(65536 * value))
0556c481163c7e676b0160765ad0a7a0ca1306f2
681,066
def sval(val): """ Returns a string value for the given object. When the object is an instanceof bytes, utf-8 decoding is used. Parameters ---------- val : object The object to convert Returns ------- string The input value converted (if needed) to a string """...
423c4934edde09939d83f988dcedb6d19146fb8d
681,067
def _superclasses(obj, cls): """return remaining classes in object's MRO after cls""" mro = type(obj).__mro__ return mro[mro.index(cls)+1:]
afa47a46fff3d7b525988baae57579e240a40c06
681,071
def _align_sentence_spans_for_long_sentences(original_sentence_spans, trimmed_sentence_spans): """Align new token spans after enforcing limits to the original locations in raw text. This is needed to keep track of each token's location in original document. After enforcing sentence limits, some sentences g...
144b71600846aee5293bc1ce10837fbe35d79c7a
681,072
def _strip_mongodb_id(x): """ Rename the ``_id`` key from a dict as ``id``, if the latter doesn't already exist. If that's the case, remove the key. Update the object in-place. """ if "_id" in x: if "id" not in x: x["id"] = x.pop("_id") else: del x["_id"] ...
c2f9824b55234c638ce3b88fcef01c1a26937e9f
681,073
def phony(params: dict) -> str: """ Build phony rules according to 42 rules """ phony = "all re clean fclean norm bonus" if params["library_libft"]: phony += " libft" if params["library_mlx"] and params["compile_mlx"]: phony += " minilibx" return phony
0db9f695caa3801467f7d6d3efecc070e0bda6ec
681,074
def next_power_of_2(v): """ Returns the next power of 2, or the argument if it's already a power of 2. """ v -= 1 v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 return v + 1
231925c06c493f1113616fea4cb6c0269c2f7f01
681,076
import requests import json def edit_link(token, link, title): """ Edits an already existing Bitly links title. Args: token (str): Bitly access token. link (str): Shortened URL to be edited by Bitly. title (str): Updated Bitly link title. Returns: Bitly status informa...
3fbdc07f0e2d7b54787295250654ffffbf97054b
681,083
def check_lat(lat): """ Checks whether the input latitude is within range and correct type Parameters ---------- lat : float or int latitude (-90 to 90) in degrees Returns ------- None. Raises an exception in case """ if isinstance(lat, (int, float)): if abs(lat...
a4b87645b0f1a19c79da387352b49ba12277a39d
681,084
def merge_p(bi,p,bigrams): """ Calculates the merge probability by combining the probs of the bigram of words and the prob of merge. Arguments bi : bigram p : p(MG->mg) from grammar (should be 1) Returns combined probability of merge op and bigram """ (w1,w2)=bi return bi...
58831a487e0bb441fa3f19e0deead0a1f7632df8
681,085
def combine(a, b): """ sandwiches b in two copies of a and wrap by double quotes""" c = '"' + a + b + a + '"' return c
984361527233b31799516a5a696f630aa88a1daf
681,086
def _find_get(root, path, value, defa=False): """ Error catching of things required to be set in xml. Gives useful errormessage instead of stuff like "AttributeError: 'NoneType' object has no attribute 'get'" Parameters ---------- root : Element Element in xml-tree to find parameter...
c51e4d99ba536d6100e21acf99e008d4da102574
681,088
from typing import List def find_string_anagrams(str1: str, pattern: str) -> List[int]: """ This problem follows the Sliding Window pattern and is very similar to Permutation in a String. In this problem, we need to find every occurrence of any permutation of the pattern in the string. We will use a list ...
281dba1d21d779ab4060a8889ffb0ab81f061d30
681,090
def create_suffix(suffix, index): """Create suffix using an index Args: suffix (string): Base suffix index (int/string): Index Returns: string: Suffic """ i = "%02d" % (int(index) + 1,) return suffix + "-" + i
bfb133372a7797fc7dfd011ce26dbdd0956d996d
681,091
def is_substring(text: str, elements: set) -> bool: """ Check if a string is a substring of any string in a set Args: text (str): text to be tested elements (set(str)): set of string to be tested against for substring condition Return: (bool): whether or not if text is a substr...
de576a5ef9cdfed82233f071520bc6e3c76674fb
681,092
def _format_error(error: list) -> dict: """ Convert the error type list to a dict. Args: error (list): a two element list with the error type and description Returns: dict: explicit names for the list elements """ return {'error_type': error[0], 'description': error[1]}
842dd6b456ac25e90c79f720ea59794188001234
681,095
def token_identity(it, token_payload=None): """ Echo back what it gets. """ return (it, token_payload)
6fe367d1e908a8812c8372e5909b54c8bb7b17f5
681,096
def first(s): """Return the first element from an ordered collection or an arbitrary element from an unordered collection. Raise StopIteration if the collection is empty. """ return next(iter(s))
85535e7ccd25812154190c2bfb9dcfd7c48cfeff
681,104
def auth_headers(token): """Return a list of Authorization headers corresponding to token.""" return [('Authorization', 'Bearer %s' % token)]
b42cc008ba2aa13d722214beef074f02a537c045
681,105
import json def burn_in_info(skeleton, info): """Burn model info into the HTML skeleton. The result will render the hard-coded model info and have no external network dependencies for code or data. """ # Note that Python's json serializer does not escape slashes in strings. # Since we're inl...
86cc51a18601ce9b0656e915c6b10d07bc1fead2
681,108
import requests def make_request(url): """ Make request to an URL :param url: any url :return: success and response if successful, otherwise error """ try: return 'success', requests.get(url) except requests.exceptions.ConnectionError: return 'connection error', None
5612c3728519fa732937d3863a643e1d68eb1e4d
681,109
def quotes_inner(quoted: str) -> str: """ For a string containing a quoted part returns the inner part """ left_quote = quoted.find('"') right_quote = quoted.rfind('"') if right_quote < 0: right_quote = len(quoted) return quoted[left_quote + 1:right_quote]
737718431d353e3ac9bd21fd625a61557b423d68
681,114
def guess_lon_lat_columns(colnames): """ Given column names in a table, return the columns to use for lon/lat, or None/None if no high confidence possibilities. """ # Do all the checks in lowercase colnames_lower = [colname.lower() for colname in colnames] for lon, lat in [('ra', 'dec'), (...
f8f1385bc1a694241d98077c8ad499015e36021b
681,118
def get_pkt_data(il, offset, use_index=False, size=4): """ Returns llil expression to get data from packet at offset :param il: llil function to generate expression with :param offset: packet offset to retrieve :param use_index: add the index register to offset if true :param size: number of byt...
a7f466cb0666ee6d02368bae9f55c335d47f9100
681,122
def copy_to_len_sliced(s, l): """Returns the maximim length string made of copies of `s` with the length exactly `l`; if the length of `s` doesn't match, it ends with the beginning slice of `s`. Parameters ---------- s : string String to be copied and sliced. l : int Th...
165b2ab2358f5742139f947e3f370637c8a9ffe4
681,123
import math def t_test(image1, image2): """Performs a Student's t-test for the provided images.""" num = image1.rms[0] - image2.rms[0] denom = math.sqrt(((image1.stddev[0]**2)/image1.count[0]) + ((image2.stddev[0]**2)/image2.count[0])) if denom == 0: return 0 t = num / denom if t < 0: ...
6b276fd0fd45e5a263e326e94fde850ca6e441a8
681,125
def normalize(grid): """ normalize grid to (0,1) """ field = grid.T.values min_h, max_h = field.min(), field.max() return (field - min_h) / (max_h - min_h)
0bd5bb6cac14a283aaa8ca6dabc914b920fcfa3a
681,127
def fastaParserSpectraClusterPy(header): """Custom parser for fasta headers adapted from https://github.com/spectra-cluster/spectra-cluster-py :param header: str, protein entry header from a fasta file :returns: dict, parsed header """ isUniprot = lambda h: h[0:3] in ['sp|', 'tr|', 'up|'] ...
b5695bc412523a586f77c15587916d4b885ef5ef
681,130
def column_check(df, column): """Check if `column` is in `df`.""" return column in df.columns
b584753a3b3789e90436bcc368af21f99a8a7348
681,131
def paths_same_disk(photos_path:str, export_path:str)->bool: """ Checks if the provided input path and the export path are "located" on the same disk. :param photos_path: path to photos :type photos_path: str :param export_path: path to the directory where the photo folder structure will be created...
07476953bbaec5ad0045b064ea5ce09e246ebca1
681,135
def get_handcrafted_feature_names(platform): """ Returns a set of feature names to be calculated. Output: - names: A set of strings, corresponding to the features to be calculated. """ names = set() ###############################################################################################...
ccdf430b0403c1152f40c9c0bdf5fbb380d8f0c1
681,137
from pathlib import Path def make_path_like(path_like): """Attempts to convert a string to a Path instance.""" if isinstance(path_like, Path): return path_like try: return Path(path_like) except TypeError: raise TypeError(f'could not convert to Path: {path_like}')
5b3eeffc8cad733c684deae0338218a1eaac494b
681,143
import tempfile import json def write_json_temp_file(data): """Writes the provided data to a json file and return the filename""" with tempfile.NamedTemporaryFile(delete=False, mode='wb') as temp_file: temp_file.write(json.dumps(data).encode('utf-8')) return temp_file.name
15c0b5df8b56fed6d7016d3dd34de203ab56a62e
681,144
def read_input(path: str) -> list: """ Read game board file from path. Return list of str. >>> read_input("check.txt") ['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'] """ with open(path, 'r') as lines: state = [] for line in lines: s...
87fcbe0af89167c1c76f81118ab0164b56940087
681,146
def pairs(clustergenerator, labels): """Create an iterable of (N, {label1, label2 ...}) for each cluster in a ClusterGenerator, where N is "1", "2", "3", etc. Useful to pass to e.g. vambtools.writer_clusters. Inputs: clustergenerator: A ClusterGenerator object labels: List or array of c...
5751e2e58a2e4694067ec0c4b7f8e3c3953ef171
681,147
def cubec_to_cubei(cubec): """Cube centimetre to cube inch""" return cubec * 0.061
1db3f73336d4322405a9aabddfb186a0e882f3d8
681,151
import math def determine_padding(filter_shape, output_shape="same"): """Method which calculates the padding based on the specified output shape and the shape of the filters.""" if output_shape == "valid": return (0, 0), (0, 0) elif output_shape == "same": filter_height, filter_widt...
12ef1c8d624f0dfd161c8723736610fa86c9ce1d
681,154
from typing import Sequence from typing import Optional from typing import Callable def make_add_field_names_preprocessor( field_names: Sequence[str], field_indices: Optional[Sequence[int]] = None, ) -> Callable: """Make a preprocessor to add field names to a dataset. Create a preprocessor that converts ...
55389339ffd44669cfb7f0571bb893524c7df0a4
681,156
def strip_parentheses(string): """ Remove parentheses from a string, leaving parentheses between <tags> in place Args: string: the string to remove parentheses from Returns: the processed string after removal of parentheses """ nested_parentheses = nesting_level = 0 res...
dc05344a9c5f9de2e53546104ffff2925ca2c628
681,157
def parse_multplt(path): """ Parses multplt.def file and returns list of lists like: [station, channel type (e.g. SH), channel (E, N or Z)]. """ data = [] with open(path, "r") as f: lines = f.readlines() tag = "DEFAULT CHANNEL" for line in lines: if line[:len(tag...
c1d0d33c60c200bf16a6277f5e9110af334c98c2
681,158
def run_query(client, query): """ Runs BigQuery queryjob :param client: BigQuery client object :param query: Query to run as a string :return: QueryJob object """ return client.query(query)
d75c2aedd3855b1d4c3881a74539e1ffdd4dc174
681,163
def add_scalebar(image_obj, scalebar_px): """ Adds a scalebar to the input image and returns a new edited image """ ## set the indentation to be ~2.5% inset from the bottom left corner of the image indent_px = int(image_obj.height * 0.025) ## set the stroke to be ~0.5% image size stroke = int(im...
23a155ecae997f5b871ffddbc63c581029ae780b
681,167
def lerp(a, b, x): """Linear interpolation between a and b using weight x.""" return a + x * (b - a)
b6790c221e797bfa0fe063a22ebced60eab877db
681,170
def pretty_eta(seconds_left): """Print the number of seconds in human readable format. Cited from baselines (OpenAI) Examples: 2 days 2 hours and 37 minutes less than a minute Paramters --------- seconds_left: int Number of seconds to be converted to the ETA Returns ...
15f9b3f679fe671e0c19fb76ecd5d6129d89c3a6
681,173
import copy def update_categories(desired_name2id: dict, coco_dict: dict) -> dict: """ Rearranges category mapping of given COCO dictionary based on given category_mapping. Can also be used to filter some of the categories. Arguments: --------- desired_name2id : dict {"big_veh...
2a2e18d50ce20742406c400fcee341442d35a7da
681,175
def _EdgeStyle(data): """Helper callback to set default edge styles.""" flow = data.get("flow") if flow in {"backward_control", "backward_data", "backward_call"}: return "dashed" else: return "solid"
22a43f452cf365bd405d458992986995cb573f44
681,178
import math def _flat_hex_coords(centre, size, i): """ Return the point coordinate of a flat-topped regular hexagon. points are returned in counter-clockwise order as i increases the first coordinate (i=0) will be: centre.x + size, centre.y """ angle_deg = 60 * i angle_rad = math.pi / 180...
eeb1e7539ae182e5ed720d35ba85c019e9dc6529
681,180
import requests def make_get_request(uri: str, payload): """ Function to make a GET request to API Endpoint :param uri: :param payload: :return: """ response = requests.get(uri, payload) if response.status_code != 200: return None else: return response.json()
cf7c97415658b3d7a059f862a7251b66ecf2ca59
681,182
def has_two_adjacent(password): """Check if the password contains a pair of adjacent digits""" last_char = None num_adjacent = 0 for char in password: if char == last_char: num_adjacent += 1 else: if num_adjacent == 1: return True las...
debd82c62f859296ed2227de8ed1705fc9f7c288
681,184
import torch def dot(A, B, dim=-1): """ Computes the dot product of the input tensors along the specified dimension Parameters ---------- A : Tensor first input tensor B : Tensor second input tensor dim : int (optional) dimension along the dot product is computed (...
b8859730dec5987cf566f6292b66d5087b230e97
681,186
from typing import Union def check_prefix(prefix: Union[str, tuple, list], content: str): """Determines whether or not the prefix matches the content. Parameters ---------- prefix : Union[str, tuple, list] The affix that appears at the beginning of a sentence. content : str The s...
1dfbe3efdd8540c6f1c6af29fe73811543e2a48b
681,188
def _account_data(cloud): """Generate the auth data JSON response.""" claims = cloud.claims return { 'email': claims['email'], 'sub_exp': claims['custom:sub-exp'], 'cloud': cloud.iot.state, }
2ff4233ef3e45b538400853a06497a2991957b9a
681,190
def _determine_start(lines): """ Determines where the section listing all SMART attributes begins. :param lines: the input split into lines. :type lines: list[str] :return: the index of the first attribute. :rtype: int """ cnt = 0 for idx, val in enumerate(lines): if lines[...
157805d2d028eea1d0627758e3c0f49344da215d
681,193
def specificrulevalue(ruleset, summary, default=None): """ Determine the most specific policy for a system with the given multiattractor summary. The ruleset is a dict of rules, where each key is an aspect of varying specificity: - 2-tuples are the most specific and match systems with that summary. ...
8ec24d461fcc875be7df6b7fabba5cdcb7cc7244
681,199
def rotate90_point(x, y, rotate90origin=()): """Rotates a point 90 degrees CCW in the x-y plane. Args: x, y (float): Coordinates. rotate90origin (tuple): x, y origin for 90 degree CCW rotation in x-y plane. Returns: xrot, yrot (float): Rotated coordinates. """ # Translate ...
172b74f4aaa5453520ed9669d1f76d3103c51b06
681,201
def is_dict(value): """Checks if value is a dict""" return isinstance(value, dict)
9c20c4a0f83a4003eb22ab077fb10c1e25bb8c53
681,202
def get_ordinal_suffix(number): """Receives a number int and returns it appended with its ordinal suffix, so 1 -> 1st, 2 -> 2nd, 4 -> 4th, 11 -> 11th, etc. Rules: https://en.wikipedia.org/wiki/Ordinal_indicator#English - st is used with numbers ending in 1 (e.g. 1st, pronounced first) ...
854a33897b73892346ec3094caae0dfe7d8fef1d
681,204
import hashlib def unique_hash(input_str: str) -> str: """Uses MD5 to return a unique key, assuming the input string is unique""" # assuming default UTF-8 return hashlib.md5(input_str.encode()).hexdigest()
206912b345e1dff3139b53ba94569bdb7ad565de
681,208
def show_price(price: float) -> str: """ >>> show_price(1000) '$ 1,000.00' >>> show_price(1_250.75) '$ 1,250.75' """ return "$ {0:,.2f}".format(price)
3c3c9a7532e1a84ddcf5b58d348dda778fdf5e59
681,211
def format_title(title, first_title): """ Generates the string for a title of the example page, formatted for a 'sphinx-gallery' example script. Parameters ---------- title : string The title string. first_title : boolean Indicates whether the title is the first title of the ...
836b973caa1da8f849e52be6a34ffb5ca09ff66a
681,215
import torch def get_saliency(interpreter, inputs, target): """ Perform integrated gradient for saliency. """ # define saliency interpreter # interpreter = captum.attr.Saliency(net) attribution = interpreter.attribute(inputs, target) attribution = torch.squeeze(attribution) return torch.su...
5767e2addd0b23c350ad5c7924100f713ec12d6a
681,216
import collections def parse_gtid_range_string(input_range): """Converts a string like "uuid1:id1-id2:id3:id4-id5, uuid2:id6" into a dict like {"uuid1": [[id1, id2], [id3, id3], [id4, id5]], "uuid2": [[id6, id6]]}. ID ranges are sorted from lowest to highest""" # This might be called again for a value...
285d99b35857235e8205657eb0bb366ca1b536d1
681,219
import string def _clean_string(s): """Clean up a string. Specifically, cleaning up a string entails 1. making it lowercase, 2. replacing spaces with underscores, and 3. removing any characters that are not lowercase letters, numbers, or underscores. Parameters ---------- s: s...
5e7f26e6e18cad549ec1115900b961f8b738b4b4
681,224
def frontiers_from_time_to_bar(seq, bars): """ Convert the frontiers in time to a bar index. The selected bar is the one which end is the closest from the frontier. Parameters ---------- seq : list of float The list of frontiers, in time. bars : list of tuple of floats The b...
97402b27ffd69a68adc350e95e663bd6e7ee13d5
681,230
def split_int(i, p): """ Split i into p buckets, such that the bucket size is as equal as possible Args: i: integer to be split p: number of buckets Returns: list of length p, such that sum(list) = i, and the list entries differ by at most 1 """ split = [] n = i / p # min ...
2aedf0a008d91f1635aa1117901ae525fbdb7d7e
681,234
def findNthFibonnachiNumberIterative(n: int) -> int: """Find the nth fibonacchi number Returns: int: the number output """ if n <= 2: return 1 first, second = 0, 1 while n-1: third = first + second first = second second = third n -= 1 return...
6767cc7b46774c7ced74b2b82e380dc41dcfbdfb
681,238
def load_factor(ts, resolution=None, norm=None): """ Calculate the ratio of input vs. norm over a given interval. Parameters ---------- ts : pandas.Series timeseries resolution : str, optional interval over which to calculate the ratio default: resolution of the input ti...
0478f96a494d798bf034cd8f7fc64176e9a26b0f
681,241
def construct_iscsi_bdev(client, name, url, initiator_iqn): """Construct a iSCSI block device. Args: name: name of block device url: iSCSI URL initiator_iqn: IQN name to be used by initiator Returns: Name of created block device. """ params = { 'name': name,...
e4ea3f17077207d1fb78286ced63e9a14f39f170
681,242
def min_interp(interp_object): """ Find the global minimum of a function represented as an interpolation object. """ try: return interp_object.x[interp_object(interp_object.x).argmin()] except Exception as e: s = "Cannot find minimum of tthe interpolation object" + str(interp_object....
ab2f719fe493c1b7a52bd883946a0e44040c0816
681,244
def hasSchema(sUrl): """ Checks if the URL has a schema (e.g. http://) or is file/server relative. Returns True if schema is present, False if not. """ iColon = sUrl.find(':'); if iColon > 0: sSchema = sUrl[0:iColon]; if len(sSchema) >= 2 and len(sSchema) < 16 and sSchema.islower...
69fa64c6e7079aa554aef24aed21ddb9634400fe
681,247
def check_knight_move(lhs, rhs): """check_knight_move checks whether a knight move is ok.""" col_diff = abs(ord(lhs[0]) - ord(rhs[0])) row_diff = abs(int(lhs[1]) - int(rhs[1])) return (col_diff == 2 and row_diff == 1) or (col_diff == 1 and row_diff == 2)
fb8aad86a278249da7fbdc5f341c5024b0cbfb82
681,249
def remove(self): """Remove this node. @return: self """ self.parent.remove_creator(self) return self
96df3a910f6c6cef5f95723c94e5bde9070e2847
681,250
from datetime import datetime def timestamp_ddmmyyyyhhmmss_to_ntp(timestamp_str): """ Converts a timestamp string, in the DD Mon YYYY HH:MM:SS format, to NTP time. :param timestamp_str: a timestamp string in the format DD Mon YYYY HH:MM:SS :return: Time (float64) in seconds from epoch 01-01-1900. ...
bf2239de21973ae537cee94022e9d2781f7cbd52
681,251