content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import copy def fillMetadata (f, txid, extra): """ Retrieves a transaction by id and constructs a dict that contains the given "extra" fields plus all the basic metadata (like inputs and outputs) as retrieved from Xaya Core. """ rpc = f.env.createCoreRpc () tx = rpc.gettransaction (txid)["hex"] data ...
d2ccb2203f4943da9877a85ca98349fee5b55883
80,654
def is_available(resource): """ Helper to check if resource is available. """ return resource.get("status") == "ready"
997a3ab4667e31d3f58e250463ea62b90ef19d72
80,656
def elapsed(sec): """ Formatting elapsed time display """ mins, rem = int(sec / 60), sec % 60 text = "%.1f" %(rem) ending = "s" if mins > 0: text = "%d:" %(mins) + text ending = "m" return text+ending
3cb61df21df5343473dadfbce80989407b3cdab4
80,661
def getLineAfterText(text, prefix, startPos=0, includeText=False): """Extracts the remainder of a line after a prefix""" # StartPos = index in the text to start looking at # Find the prefix prefixLoc = text.find(prefix, startPos) if prefixLoc < 0: raise Exception('Desired text not found...
83773442959bc25564240ca8e513bc2809737809
80,665
import json def decode(params): """ Converts a dictionary of SageMaker hyperparameters generated by `encode(...)` to a JSON-encodable dictionary of parameters. """ result = {} for k, v in params.items(): parts = k.split(".") k, d = parts[0], result for subk in parts[1:]...
1f613fabe4aaff4bdf9460e7712d317a13463c58
80,666
async def get_index(db, index_id_or_version, projection=None): """ Get an index document by its ``id`` or ``version``. :param db: the application database client :type db: :class:`~motor.motor_asyncio.AsyncIOMotorClient` :param index_id_or_version: the id of the index :type index_id_or_version...
a41c6afaf63222d0dde1f7c19b99d981561d4ced
80,667
def criterion_mapping(crit): """Returns mapping tuple (table, patient, start, end, code, status, value, fields) table: is a table reference for the episode patient: expression for episode patient ID start: expression for episode start date/time end: expression for episode...
9e41d14c28e081bfee0569d093b44d915598f8b3
80,669
from typing import Union from typing import Tuple from typing import List def pack_version_number(version_buffer: Union[Tuple[int, int, int], List[int]]) -> str: """ Packs the version number into a string. Args: version_buffer: (Union[Tuple[int, int, int], List[int]]) the version to be packed ...
1b71d43843876c4e07e799562fbc7a2a8270272a
80,675
def _to_bool(text): """Convert str value to bool. Returns True if text is "True" or "1" and False if text is "False" or "0". Args: text: str value Returns: bool """ if text.title() in ("True", "1"): result = True elif text.title() in ("False", "0"): result ...
d84d523a71ac5550dba41b274dbcb3b1d08d74cd
80,684
def default(copysets, copyset): """Check that always passes. The check function checks for custom constraints, such as rack or tier awareness. 'copysets' contains a list of copysets build_copysets has generated so far, and 'copyset' is the copyset that build_copysets wants to check as a valid. ...
94a3fb774c8254689baaf93f690023244a2777b4
80,688
def line_line_intersection(x1,y1,x2,y2,x3,y3,x4,y4): """ https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection Line 1 point 1 = (x1,y1) Line 1 point 2 = (x2,y2) Line 2 point 1 = (x3,y3) Line 2 point 2 = (x4,y4) """ intersection_x = ((x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4))/((x...
1b4a8cf08c733cb5f2e24deb44bff2ff7603fec4
80,691
def compute_xdot(data, dt): """Compute xdot for a chunk of snapshots. Parameters ---------- data : (Nfull, n_samples) ndarray The dataset. Here Nfull = numvariable*38523. dt : float The timestep size Returns ------- xdot : (Nfull, n_samples-4) ndarray Time deriv...
be03d4862ba6eebc972e1396e3755f46edc4d341
80,695
from typing import Union def non_negative(diff: Union[float, int]) -> Union[float, int]: """Returns 0 if diff is negative or positive value.""" return 0 if diff < 0 else diff
c0ef7f7661633e48558e6066e0b1cac4c4e89f62
80,699
def mode(lst): """Calculates the mode of a list""" return max(set(lst), key=lst.count)
6bf4393a3e8b3904d0c06fee483e7ca1338af12a
80,701
def plot_map(m, x, y, data, clevs, cmap, norm, mesh, filled, **map_kwargs): """ Producing a map plot Parameters ---------- m: Basemap object Handle for the map object returned from 'map_setup' function data: numpy array 2D data array to plot x,y: numpy ar...
e27edc9f8043925bf0a0de9da9dc18c5293f3585
80,704
def listtostring(listin): """ Converts a simple list into a space separated sentence, effectively reversing str.split(" ") :param listin: the list to convert :return: the readable string """ ans = "" for l in listin: ans = ans + str(l) + " " return ans.strip()
e27b407d28535254d3375687d17d1c92df34d4d8
80,705
def paths(bot, nb_name): """Returns the paths of notebook to execute and to write.""" nb_dir = bot.config.papermill.nb_dir #Notebook directory (from config) nb_dir = nb_dir if nb_dir.endswith('/') else nb_dir+'/' #append '/' if missing path_in = nb_dir + nb_name path_out = nb_dir + bot.config.paperm...
775d7e3d3eb9cdab81fdfe5556470152dff7427e
80,706
from typing import Callable def bisect(ok: int, ng: int, pred: Callable[[int], bool]) -> int: """Finds the boundary that satisfies pred(x). Precondition: ok < ng Args: pred(x): A monotonic predicate (either decreasing or increasing). ok: A known int value that satisfies pred(x). ng: A ...
821ae5923e648153ed1eb8a110021cb6fc0fd246
80,709
def get_coordinate_from_line(coordinate, line): """ Returns a value of a coordinate from a line """ for word in line.split(","): if str(coordinate)+"=" in word: if coordinate == "phi": return float(word[word.index("=")+1:]) else: return flo...
99b456d2ba78ae682514f1fcb884a5fc7b47879b
80,711
def max(x): """Find maximal of array elements and corresponding indices along axis = 1 Args: x: array-like Returns: max_vals_along_axis and max_indices_along_array """ if len(x.shape) != 2: raise ValueError('The size of x shape must be 2 dimension') max_vals = x.max(...
11cea43653a600d65d074374fec3ca2228dea98b
80,715
from typing import Tuple from typing import Union import re def parse_thread_url(url: str) -> Tuple[str, Union[str, None]]: """Parses a URL to a thread ID and optionally a post ID.""" pattern = re.compile(r"(t-[0-9]+)(?:.*#(post-[0-9]+))?") match = pattern.search(url) if not match: raise Value...
75588281b0d777543acaab15e59ac7b7e2b0791a
80,716
def primersOverlap(l,r): """ Inputs: left primer Segment right primer Segment Check if two primers overlap Returns: Boolean """ return l[3]['coords'][1] > r[3]['coords'][0]
baa44503ac33f74eba4fda635f6247dd979a4dfb
80,718
def add_suffix(txt, suffix): """add the given to every element in given comma separated list. adds suffix before -. Example: add_suffix("hello,john", "ga:") -> "ga:hello,ga:john" """ if txt is None: return None elements = txt.split(",") elements = ["-" + suffix + e[1:] if ...
f11865c6f3ab836e5e58336db7471f264ea181b0
80,723
def do_not_recurse(value): """ Function symbol used for wrapping an unpickled object (which should not be recursively expanded). This is recognized and respected by the instantiation parser. Implementationally, no-op (returns the value passed in as an argument). Parameters ---------- va...
f11a907e0376fec00e3b4335717edf95395acbc2
80,729
def services_contain_id(services_data, service_id): """ Tests if service_id is id of service. :param services_data: list of services :param service_id: id of service :return: True if service_id is service """ for service in services_data: if service_id == service['id']: ...
e404d8b13842f5d1533a7503c633a70405612c8c
80,730
from typing import List def ngrams(tokens: List, n: int): """ Args: tokens: List of elements n: N-gram size Returns: List of ngrams """ return [tokens[i : i + n] for i in range(len(tokens) - n + 1)]
197bf76e6113eaf83589887e7ac35020a32ab1ab
80,738
import six def get_model_instances(model_class, instances_or_ids, sep=',', ignore_invalid=True, raise_on_error=True): """ Get model instances by ids. :param model_class: :param instances_or_ids: :param sep: :param ignore_invalid: :param raise_on_error: only effective when ignore_invalid is...
93500dfd7f244a7173136e094c8e0676b43d4f66
80,741
def add_or_delete(old, new, add_fun, del_fun): """ Given an 'old' and 'new' list, figure out the intersections and invoke 'add_fun' against every element that is not in the 'old' list and 'del_fun' against every element that is not in the 'new' list. Returns a tuple where the first element is the l...
d11052532953c2d50dff27078591b587edb3c5ba
80,743
import math def PSNR(L2loss, I=2): """ Function that calculates the PSNR metric according to eq. 3 L2loss: a float I: set to 2 since the paper assumes the HR and SR pixel values are between [-1,1] """ x = I ** 2 / L2loss # calculating the argument for the log psnr = 10 * math.log10(x) # ...
fef7286356bea15b9dc4a875f76c989f322858fa
80,745
import base64 def get_session_key(request): """ Extract and decode the session key sent with a request. Returns None if no session key was provided. """ session_key = request.COOKIES.get('session_key', None) if session_key is not None: return base64.b64decode(session_key) return sessio...
4d40e33108f728ee47b82490f251b5002346ffb6
80,746
def check_pointing(timestamp, point_0, point_2, point_4, point_41): """Check if timestamp is at pointing 0, 2, 4, 41""" if timestamp in point_0: point = 0 elif timestamp in point_2: point = 2 elif timestamp in point_4: point = 4 else: point = 41 return point
a339d267dca1129bdd7c4793749c85201460e07d
80,747
def query_periods(query_type=None, month_starts=[], month_ends=[]): """Generate a dictionary with consecutive monthly intervals to query where dates are formatted a little differently depending on the API to query. API date formatting: - AirNow API: Expects dates in format ``'YYYY-MM-DDTHH'`` ...
0d6d6a0c987fe05f91699597e84f6b2a867f1898
80,750
def set_offset(chan_obj): """ Return a tuple of offset value and calibrate value. Arguments: chan_obj (dict): Dictionary containing channel information. """ physical_range = chan_obj['physical_max'] - chan_obj['physical_min'] digital_range = chan_obj['digital_max'] - chan_o...
06ab3aeafcb1ba26799d3ac2696b62909928310d
80,751
def invcalcbarycentric(pointuv, element_vertices): """ Convert barycenteric coordinates into 3d https://en.wikipedia.org/wiki/Barycentric_coordinate_system https://math.stackexchange.com/questions/2292895/walking-on-the-surface-of-a-triangular-mesh :param pointuv: Point in barycenteric coordinates ...
9aebf9e0579321788b242653a8c51b20dcad2fea
80,752
def get_hosp_given_case_effect(ve_hospitalisation: float, ve_case: float) -> float: """ Calculate the effect of vaccination on hospitalisation in cases. Allowable values restricted to effect on hospitalisation being greater than or equal to the effect on developing symptomatic Covid (because otherwise h...
1f3058e1d30ee78b65ad0b46d13187c7efe7d055
80,771
def get_first_line(comment): """Gets the first line of a comment. Convenience function. Parameters ---------- comment : str A complete comment. Returns ------- comment : str The first line of the comment. """ return comment.split("\n")[0]
ce474c0c59105f505943b85a1f1ef8205b929e5e
80,776
def get_doc(mod_obj): """ Gets document-name and reference from input module object safely :param mod_obj: module object :return: documentation of module object if it exists. """ try: doc_name = mod_obj.get('document-name') ref = mod_obj.get('reference') if ref and doc_na...
13921ee2354385dbb3988dcd698552c606784602
80,777
def convert_args_to_latex(file: str) -> list: """ Takes the file created when plotting figures with 'save=True' with quantum_HEOM and converts the arguments into strings that render correctly in LaTeX, printing them to console. The 2 lines corrspond to the 2 sets of arguments for 1) initialisin...
59abf521939aa85b7f2bd7b045b6f697a51dda46
80,778
def class_is_list(cls): """ Return True if cls_name is a list object """ return (cls.find("of_list_") == 0)
4ff0b83efcef4cfcc5bd4a92fe5549923919972f
80,780
def unite(oEditor, partlist, KeepOriginals=False): """ Unite the specified objects. Parameters ---------- oEditor : pywin32 COMObject The HFSS editor in which the operation will be performed. partlist : list List of part name strings to be united. KeepOriginals :...
7f89ea41c65dfd7daca885cc5c138130db0f7bc0
80,783
def better_bottom_up_mscs(seq: list) -> tuple: """Returns a tuple of three elements (sum, start, end), where sum is the sum of the maximum contiguous subsequence, and start and end are respectively the starting and ending indices of the subsequence. Let sum[k] denote the max contiguous sequence ending ...
a41f2f8a772cba2cf9166c2db2e39abd30bb7361
80,787
def create_cubes(n): """returns list of cubes from 0 to n""" result = [] for x in range(n): result.append(x**3) # entire 'result' list in memory (inefficient) return result
59055269162ba33407ea0ede9747b77b74e504db
80,788
import re def get_device_number(device): """Extract device number. Ex: "D1000" → "1000" "X0x1A" → "0x1A """ device_num = re.search(r"\d.*", device) if device_num is None: raise ValueError("Invalid device number, {}".format(device)) else: device_num_str = device_num.gro...
4a62aae822ed931a12574c31feafa3108bf783e3
80,792
def extract_roi(image, bounding_box): """Extract region of interest from image defined by bounding_box. Args: image: grayscale image as 2D numpy array of shape (height, width) bounding_box: (x, y, width, height) in image coordinates Returns: region of interest as 2D numpy array ...
2a5639492d67bb173f4c68b3d755ed0fe0ab6e31
80,795
from typing import Callable def filter_dict(d: dict, cond: Callable = bool) -> dict: """Filter a `dict` using a condition *cond*. Args: d: `dict` to filter cond: `Callable` which will be called for every value in the dictionary to determine whether to filter out the key. ...
8b704db11baa7d07ef61a0ebf7db6c0dfc2baa88
80,799
from typing import Iterable def simple_chunker(a: Iterable, chk_size: int): """Generate fixed sized non-overlapping chunks of an iterable ``a``. >>> list(simple_chunker(range(7), 3)) [(0, 1, 2), (3, 4, 5)] Most of the time, you'll want to fix the parameters of the chunker like this: >>> from fu...
863b15cf69eda9aa097c6e13ef7798c83961feba
80,802
def message_get_signal(message, signal_name): """Loop over signals to find the requested signal. Arguments: message: dict, the message provided by message_decode() signal_name: str, name of the signal (from DBC) Return: signal: dict, information about the decoded signal """ ...
6ec04e9d8229a32e85e1edc9ed679d89d6a12867
80,806
def find_brute(T, P): """Return the lowest index of T at which substring P begins (or else -1).""" n, m = len(T), len(P) # introduce convenient notations for i in range(n-m+1): # try every potential starting index within T k = 0 # an index into pa...
914d736e3a801fd6b44bb6f10e58535cb348bcf4
80,813
def linear_decay(x0, alpha, T, t): """Compute the linear decay rate of quantity x at time t. x(t) = x0 - (1-alpha) * x0 * t / T if t <= T x(t) = alpha * x0 if t > T Args: x0: Initial value alpha: Linear decay coefficient (alpha > 0) T: Time at which to stop decay...
68effbff6a15d895d599d6f21c836f1dc12d6dd0
80,815
def parse (line): """Parses line into an `(action, value)` pair.""" return line[0], int(line[1:])
1b48e5b8979fafc40129e620c15b292591f09112
80,816
def sub(x, y): """ subtract two values and returns a value""" return x - y
1ccfb2086bfb8bdc4d575fa1e78873d76a539d65
80,824
def indices_between_times(times, start, end): """ When provided with a list of times, a start time and an end time, returns a tuple containing the first index where the time is greater than 'start' and the last index where the time is less than 'end'. """ indices = [-1, -1] for i...
25af6ee6cd0e026d0779dff5897aa3d2535d7996
80,831
def describe_pressure(pressure): """Convert pressure into barometer-type description.""" if pressure < 970: description = "storm" elif 970 <= pressure < 990: description = "rain" elif 990 <= pressure < 1010: description = "change" elif 1010 <= pressure < 1030: descrip...
ad43061cc5e715ac8450a746c4322401aa380b41
80,833
import torch def Conv2dGroup( in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1, padding: int = 0, bias: bool = True, num_groups=1, **kwargs, ): """A 2D convolution followed by a group norm and ReLU activation.""" return torch.nn.Sequential( tor...
eb723c3673a263c573022681cc5b30018c8647b6
80,836
def parseOptions(userOptions, jobOptions): """ Verifies that user supplied options fit the criteria for a set of job options Args: userOptions: a set of user supplied options jobOptions: an option schema for a job Returns: a list of errors (can be empty) options to s...
166ce216cbe511b5a2c25e6b928b94e0ffd1f66e
80,837
def _create_issue_search_results_json(issues, **kwargs): """Returns a minimal json object for Jira issue search results.""" return { "startAt": kwargs.get("start_at", 0), "maxResults": kwargs.get("max_results", 50), "total": kwargs.get("total", len(issues)), "issues": issues, ...
2bf918fc89a1ebf1bbedde2f65ae8527499272c2
80,840
def _full_qualified_name(obj): """ Gets the full qualified name of an object """ klass = obj.__class__ module = klass.__module__ if module == 'builtins': return klass.__qualname__ # avoid outputs like 'builtins.str' return f'{module}.{klass.__qualname__}'
d062c119cea05b6a58a17ae85afa2505c210ea05
80,845
def get_yes_or_no_input(prompt): """ Prompts the user for a y/n answer returns True if yes, and False if no :param prompt: (String) prompt for input. :return: (Boolean) True for Yes False for No """ while True: value = input(prompt + " [y/n]: ") if v...
f1796ee4cd648c2f3ccfd62ea0ad6463813c084f
80,846
def make_multi_simple(edge_list): """ Takes the edge list of a graph and returns the simple graph obtained by removing loops and multiple edges """ new_edges = sorted(set([tuple(sorted(e)) for e in edge_list])) # slow remove duplicates new_edges = list(filter(lambda e: e[0] != e[1], new_edges)) # re...
e8b3c615b1378f8d534567449c0da5959562e2e7
80,847
def month2label(month): """ Convert month to four season numbers :param month: :return: """ if month in [1,2,3]: return 1 elif month in [4,5,6]: return 2 elif month in [7,8,9]: return 3 else: return 4
ed1ba43094648b8ba2c96f5afd33fedc8624d9f9
80,853
import random import string def get_tmp_suffix(length=None): """ Returns random filename extension as a string of specified length """ length = 10 if length is None else length return "." + "".join(random.choices(string.ascii_uppercase + string.digits, k=length))
cd3c67ccadc375b34dbc97ed299182dfadc98328
80,854
from typing import Any from typing import Iterable def objectIsObjectIterable(o: Any) -> bool: """Decide whether o is an iterable of objects. like typing.Iterable, but more restricted for serializabiliy checking. :return: True if o is of a type considered to be an iterable of objects, but not a string ...
8c29d7f96914be56e2ed645c37034f6fb265ea6b
80,857
def string_fraction(numerator, denominator): """ Format a fraction as a simplified string. """ if denominator == 1: return f"{numerator}" else: return f"{numerator}/{denominator}"
c0449d66cb90246ef204f9aa512e31eed8f3989e
80,862
def _get_serial_bitrate(config): """ Get the serial port bitrate to be used for the tests. """ return config.getoption("--serial-bitrate")
4efc298f19c16d2e7cda9eaf280127f8b642bd9d
80,863
def process_string(string): """ # strip() method removes whitespace, \n, \t at the beginning and end (both sides) of a string :param string: any string :return: processed string """ string = string.strip() string = string.strip('\n') string = string.strip('\t') string = string.stri...
b519784fdc4ce7b2dbed320aada4e920ac0df0ff
80,867
def is_greyscale_palette(palette): """Return whether the palette is greyscale only.""" for i in range(256): j = i * 3 if palette[j] != palette[j + 1] != palette[j + 2]: return False return True
4a8473736a7ad77cb6a2330d09b344ce5ad4ba5d
80,870
def decimal_to_hexadecimal(decimal: int)-> str: """Convert a Decimal Number to a Hexadecimal Number.""" if not isinstance(decimal , int): raise TypeError("You must enter integer value") if decimal == 0: return '0x0' is_negative = '-' if decimal < 0 else '' decimal = abs(decimal) ...
feb4c7e1f93527f140f3a037c535711d9d65df88
80,872
def search_services(query, services, quiet): """ Search map services for the given query string. query is a string to search for in featureclasses, databases, maps, or service names services is a list of MapService objects to search through quiet is a value in [0, 1, 2] that determines what to retu...
df92cb9a2eee9425efb8ceaa9ad6a25b34d00b12
80,873
def add_dicts(d1, d2): """ Function takes two dictionaries and merges those to one dictionary by adding values for same key. """ if not d2: return d1 for _k in d2: if _k in d1: d1[_k] += d2[_k] else: d1[_k] = d2[_k] return d1
7d8b07fdfc5b84f873180bac7186c5c48be3747a
80,874
def select_nodes(batch_data, roots): """ Run 'select' in MCTS on a batch of root nodes. """ nodes = [] for i, root in enumerate(roots): data = batch_data[i] game = data[0] state = data[1] player_1 = data[2] player_2 = data[3] root = roots[i] p...
bf6684814314b78200e115fdbb245c0a861fd74a
80,876
def ParentId(tpe, id): """ A criterion used to search for records by their parent's id. For example * search for observables by case id * search for tasks by case id * search for logs by task id * search for jobs by observable id Arguments: tpe (str): class name of the parent: ...
ca94147e2c750b5e6b0a4b2d37c520d6682e90cb
80,878
def oct2hex(x): """ Convert octal string to hexadecimal string. For instance: '32' -> '1a' """ return hex(int(x, 8))[2:]
78dee661443be2ba2b2e39a21746a3da3cf6ec5c
80,882
def extract_data(df, filter_missing=True): """Extract data from evalmetrics output. An evalmetrics output contains the data as well as metadata fields associated with the data. This function takes a df containing evalmetrics output fields as columns, applies cleaning and conforming, and extracts th...
81697ab4bd906bac68f4755b8ff04cd511d7b480
80,886
def remove_query_string(url): """ Returns url without any query string parameters. """ return url.split("?")[0]
f99a607e68e9e086f3c0f3296806dba8979a45fd
80,897
def train_test_valid_split(ts, prediction_length): """ This function slices input Time Series ts into train, test and validation set with the following ratio: * Training set will start at the beginning of the input time series and is truncated right before 2*prediction_length elements from the end. ...
cdd49a9bcdf02f42c74cb80939f8b17f0ff85b24
80,899
def get_sail_angle(awa): """Get the sail angle from an apparent wind angle.""" assert isinstance(awa, float) or isinstance(awa, int) if awa <= 180: sail_angle = awa / 2 else: sail_angle = (360 - awa) / 2 return round(sail_angle, 2)
554dfe1f4c2be1b9781efcac13255ea04b8d02d0
80,915
def decimal_converter(amount: int = 0, decimals: int = 18) -> str: """ Moves the decimal point for token amount. Parameters ---------- amount: int The amount of tokens. decimals: int The decimals of the token. Returns ------- str Amount of tokens divided by ...
ca3f4eb15c9a59b41f371f4c639650e17b9934fb
80,918
def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: """ Convert molarity to normality. Volume is taken in litres. Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration """ ...
977fecee48a6964b17b14448255f81b1ba177da3
80,919
def expand_2d_to_3d(file_data_2d, lens): """ Restore the 2D file data back to 3D. Args: file_data_2d: A 2D nested list lens: A list of integers recording the number of files in each CL. Returns: A 3D nested list. """ restore_3d_file_data = [] prefix_train = 0 fo...
a03a2a1faed79b1433046e92de20bc801e2bdcba
80,920
from typing import Sequence def decode_chunk_path(chunk_path: str) -> Sequence[int]: """Split a string chunk path into integer indices""" parts = chunk_path.split(".") int_parts = [int(x) for x in parts] return int_parts
4428ec3c8348d568b9bd326b5dcf7f3c25c807f9
80,924
def apply_headers(response): """Add headers to each response.""" response.headers["X-Thoth-Version"] = "v0.6.0-dev" return response
a7a603e470b1bff0937b2da467c5ed4a3daf2769
80,925
import textwrap import base64 def _bytes_to_pem_str(der_bytes, pem_type): """ Utility function for creating PEM files Args: der_bytes: DER encoded bytes pem_type: type of PEM, e.g Certificate, Private key, or RSA private key Returns: PEM String for a DER-encoded certificate o...
75a6963f31c405b9ef38dd33be7e08e1f779ea3d
80,926
import time def unixtime(msg): """Get the unix timestamp from a spark message object""" t = time.strptime(msg.created, '%Y-%m-%dT%H:%M:%S.%fZ') return int(time.mktime(t))
17ca1c2d8315a06837c329f6ea3f13523a090a2f
80,928
def mask_to_range(mask): """converts a boolean mask into a range string, e.g. [True,True,True,False,True] -> '1-3,5'""" rangespec = [] i = 0 while i < len(mask): if not mask[i]: i = i+1 continue j = i+1 while j < len(mask) and mask[j]: j = j+1 j = j-1 if i != j: rangespec.append('%i-%i' % (i...
3357543bc0f7ecbd7db7f336c8c3a28afff31794
80,930
def parse_response_status(status: str) -> str: """Create a message from the response status data :param status: Status of the operation. :return: Resulting message to be sent to the UI. """ message = status if status == 'SUCCESS': message = "Face authentication successful...
7eab8fa4b115d79c014070fd78d7d088011bf226
80,931
def supplement_flag_str(name,entry): """ Generate flag for newly-assigned committee member. Arguments: name (str): Faculty name entry (dict): Student entry Returns: (str): flag string """ value = "#" if (name in entry.get("supplement_committee",set())) else "" return val...
811d7106edb61717568ff96f205702e5b3a968bf
80,932
def readFile(fileName): """Read all file lines to a list and rstrips the ending""" try: with open(fileName) as fd: content = fd.readlines() content = [x.rstrip() for x in content] return content except IOError: # File does not exist return []
f44d8230990c9a1388161381e0cf5903dfb530c7
80,935
from typing import Dict def json_to_selector(selectors: Dict[str, str]) -> str: """Convert a json dict into a selector string.""" return ', '.join(f"{k}={v}" for k, v in selectors.items())
7e7f275e2f805cc968709a3c7825223482295d7d
80,936
def name_string_cleaner(record): """ Pandas Helper function to clean "name" column. Args: record (str): Strings in "name" column. Returns: str: Cleaned string. """ if "MIDAS" in str(record): return "midas" elif "TMU" in str(record): return "tmu" elif "TA...
b6db22384517880e55524dfe585d90f5887e856a
80,942
import csv def read_delim(path): """Read in tab delimited file.""" data = [] with open(path) as handle: myreader = csv.reader(handle, delimiter='\t') data = list(myreader) return data
b487c6c070fe8b5094d0c9d14c2b3453a2e84f24
80,946
import re def check_money_words(line): """ Return true this line contains words that reference money :param line: the line to check :return: True if this line references money """ m = re.compile('(gem|orb|bloodsilver)').search(line) if m: return True return False
e3d61783515cbdd28939489d77977d936a6d1520
80,949
import torch def compute_class_weight(n_samples, n_classes, class_bincount): """ Estimate class weights for unbalanced datasets. Class weights are calculated by: n_samples / (n_classes * class_sample_count) :param n_samples: :param n_classes: :param class_bincount: :return: """ ret...
1f8f02bee178cfab957d939bce543ae015e39407
80,953
def inventory_report(products): """Print a summary of the list of products """ product_count = len(products) if product_count <= 0: return "No products!" total_price, total_weight, total_flam = 0, 0, 0 for prod in products: total_price += prod.price total_weight += pr...
35172b62de6f945de3fcd287bf268d703744a456
80,954
import csv def write_spds_to_csv_file(spds, path, delimiter=',', fields=None): """ Writes the given spectral power distributions to given *CSV* file. Parameters ---------- spds : dict Spectral power distribut...
8ab38b2b91a2e81ca3b18eb5528e5050d795b32d
80,956
def df_fn(s, mobi_fn): """ Derivative (element-wise) of water fractional flow Parameters ---------- s : ndarray, shape (ny, nx) | (ny*nx,) Saturation mobi_fn : callable Mobility function lamb_w, lamb_o, dlamb_w, dlamb_o = mobi_fn(s, deriv=True) where: lamb_w : water mob...
1658a604d2c531c371f7536002a1f8d074b2a842
80,957
def exclude_by_dict(text, known_words): """ Determines whether text is not good enough and should be excluded. "Good enough" is defined as having all its words present in the `known_words' collection.""" return not all(map(lambda word: word in known_words, text.split()))
4129ea2430537f6b16fb4d987deff1257354fc1f
80,959
def _f3_matrix_multiplication(matrix, backend): """ Computes X @ X^H @ X and X^H @ X. """ matrix_dag_matrix = backend.matmul( matrix.conj(), matrix, transpose_A=True, transpose_B=False) matrix3 = backend.matmul( matrix, matrix_dag_matrix, transpose_A=False, transpose_B=False) return matrix3, mat...
fccfad4e8732f22dbbbc3037268fc9e1e863f83a
80,960
def score_defaults(gold_labels): """Calculates the "all false" baseline (all labels as unrelated) and the max possible score. Parameters ---------- gold_labels : Pandas DataFrame DataFrame with the reference GOLD stance labels. Returns ------- null_score : float The score f...
876d47c60c53d6532f99632d4350fed9bbd83e92
80,964
def get_sequence_start(mmap, position): """ Get start of sequence at position (after header) """ return mmap.find(b"\n", position + 1)
40c8e78c4aadc899fc5d46bdafb98c8aadcb2cd8
80,967
def merge_small_dims(var_shape, reshape_size): """Computes the shape of the variable for preconditioning. If the variable has several small dimensions, we can reshape it so that there are fewer big ones. e.g for a convolution (512, 5, 5, 1024) we could reshape it into (512, 25, 1024). Args: ...
268e69cae2fc4b1aab78e519eb735453fd774f25
80,976