content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import re def date_to_version(tag): """Convert a tag from YYYYMMDD to y.M.D where y is years after 2020.""" if re.match(r"\d\d\d\d\d\d\d\d", tag): year = int(tag[2:4]) - 20 month = int(tag[4:6]) day = int(tag[6:8]) return f"{year}.{month}.{day}" return tag
543709b9e5739008139714a513286af2fd71f404
615,084
def neighbours_alive_count(grid, row, col): """ Takes a grid and a position and returns the number of living neighbour cells.""" rows = range(max(0, row - 1), min(len(grid) - 1, row + 1) + 1) cols = range(max(0, col - 1), min(len(grid[0]) - 1, col + 1) + 1) return len([1 for x in cols for y in rows ...
f3f50e7e4eee6a5a4aa17eddf8e248b4448a9cde
615,086
def _partial_match(buffer, string, safe_size): """ Helper to handle the possible edge case of a string partially occurring at the end of buffer currently under analysis. @param buffer buffer to inspect @param string string to find @param safe_size size of buffer suffix where the partial match i...
b30865f585c8dc97743979f0c7624c137b45dd37
615,092
import math def z_dir_imp_factor(z, num_waves, total_wave_length, **kwargs): """ Returns the imperfection factor based on the z-direction. :param float z: Coordinate in length direction. :param int num_waves: Number of half-wave lengths, either 1 or 2. :param float total_wave_length: Range of the loca...
40a3beffa9b76692daa24b542ea9e251c6e6f227
615,094
def date_format(date: str) -> dict: """Formating the date for dict structure Example: >>> date = date_format("Mai 15, 2015") >>> print(date) Output: { "month": "Mai", "day": "15", "year": "2015", "full_date":...
b76cfc0414d8a224b378105a3b3c1e477e417d69
615,097
def pagify(text: str, delim="\n", *, shorten_by=0, page_length=2000): """ Chunk text into manageable chunks. This does not respect code blocks or special formatting. """ list_of_chunks = [] chunk_length = page_length - shorten_by deliminator_test = text.rfind(delim) if deliminator_test...
9551e36c555b66b58a196d7041187710b5cc1597
615,099
def l2_norm(x): """ Calculates the l2 norm of the input tensor. Args: x: tensor, any shape tensor to take the l2 norm of. Returns: float, l2 norm of the input """ return x.view(-1).dot(x.view(-1))
beba8abb86b49a95259de6bcef6286617276de6f
615,103
from datetime import datetime def convert_day(x): """ Converts TIME field to an integer representing the day of the week eg - 2019-02-10 -> 0 (Sunday) """ current_date = datetime.strptime(x, "%Y-%m-%dT%H:%M") return current_date.strftime('%w')
55883b0ef1f4bc4eea747827dac094bb46d2e2a6
615,106
def isPrime(num): """ Tell whether the given number is a prime number """ if num < 1: return False if num == 1: return True for i in range(2, int(num / 2) + 1): if num % i == 0: return False return True
26700094bd9fa205c57656e14a70e4a0de131c5d
615,107
def plusMinus(arr): """Function that calculates the ratio of positive, negative and 0 values in a given array""" l = len(arr) p = 0 n = 0 z = 0 for val in arr: if val > 0: p += 1 elif val < 0: n += 1 else: z += 1 p_ratio = roun...
a4ed90950b72c4f0c797a48c4ff4782c5ac608f3
615,110
def decremental_mean(mu_i, n, x): """ Calculates the mean after removing x from a vector with given mean and size. :param mu_i: Mean before removing x. :param n: Number of elements before removing x. :param x: Element to be removed. :return: New mean. """ delta = (mu_i - x) / float(n -...
771032968316de14c7aef319e81cbb831ef98b9c
615,111
def format_decimal_as_string(value): """ Convert a decimal.Decimal to a fixed point string. Code borrowed from Python's moneyfmt recipe. https://docs.python.org/2/library/decimal.html#recipes """ sign, digits, exp = value.as_tuple() if exp > 0: # Handle Decimals like '2.82E+3' ...
f31cf34006ea44969213d3810c6a70a38f19a307
615,114
def _make_exact(h): """Make sure h is an exact representable number This is important when calculating numerical derivatives and is accomplished by adding 1 and then subtracting 1.. """ return (h + 1.0) - 1.0
8dffb368271f1634e4f3d9d42e35f98603565076
615,115
def subword_tokenizer(text, dictionary): """ The MaxMatch algorithm, also known as the greedy longest-match-first algorithm, matches a token with the appropriate sub-word tokens. It's used in BERT's wordpiece tokenizer. It takes in a string, and a dictionary of sub-words Reference: https://githu...
ddbe931b4bb949aa4f09d053b069bc7b333ed43b
615,116
def isfloat(value: str) -> bool: """ Check if the given string is a float. :param value: String to check :return: True if float """ try: float(value) return True except ValueError: return False
0c097df3984d8acbc37aef4527df82640b7eee6b
615,117
def insert(tup, loc, val): """ >>> insert(('a', 'b', 'c'), 0, 'x') ('x', 'b', 'c') """ L = list(tup) L[loc] = val return tuple(L)
aaae64538eedcaa1c364caf0a93792a7aab5fa11
615,123
import json def load_json(jsonfile): """ Opens and loads a .json file. """ with open(jsonfile) as f: j = json.load(f) return j
13dd362637340671f63021771a4e109d76a14161
615,124
def dict_get(d, key, default=None): """Return non-None value for key from dict. Use default if necessary.""" val = d.get(key, default) return default if val is None else val
61d7974a6c22096ecc80ea8a5e03afb3cd34bbb0
615,126
def _convert_bytes_to_megabytes(b): """Converts bytes to megabytes""" return b / 1000 ** 2
004940b28d6b9797696ee38c511b3d6ead307308
615,128
def round_key(matrix, key_block): """ This function is used for both AES encryption and AES decryption. The function will divide the matrix into four 4 bytes blocks (each column as a block), and perform XOR operation between block and key which contained in the key_block. At last, create and return the...
adc8f837cea594b38197430103042aa4e00fed39
615,130
def _get_layer_from_layermap(layermap, layerid): """ Get corresponding layer name and purpose from layermap Parameters ---------- layermap : dict() layermap dictionary layerid : [int, int] layermap id Returns ------- [str, str] layer name and purpose """ ...
d326a037e3fb94f97674857a1092e63bef2e80c2
615,134
def linear(a, x): """ Simple linear fit function. :param a: Coefficients array of length 2 :param x: free parameter :return: float """ return a[0] + a[1] * x
7f7bb442b1d75abbd420b534e81466891ea12e47
615,136
from typing import Dict from typing import Any import yaml def read_config(path: str) -> Dict[str, Any]: """ Reads the config dictionary from the yaml file. Args: path (str): Path to the .yaml file. Returns: Dict[str, Any]: Configuration. """ with open(path, 'r', encoding='...
50839c2fff9b0e15f109c2235ecbe36657fffe95
615,139
def remove_out_of_range(df, range_list): """Set any values out of range to NAN. Args: - df: a wide format df (e.g. the result of data_loader) - range_list: a list of dictionaries. Each dictionary has three keys 'variable', 'high' and 'low'. e.g. {'variable': 'aao2', 'hig...
6d29a01b8665bca93c60459be5d27f1da5252b10
615,140
import re def humanize_placeholders(msgid): """Convert placeholders to the (google translate) service friendly form. %(name)s -> __name__ %s -> __item__ %d -> __number__ """ return re.sub( r'%(?:\((\w+)\))?([sd])', lambda match: r'__{0}__'.format( match...
26802cbeac5bdce433f8b8e43d88a9d26a9cee35
615,143
def format_data(shapelet, offset=0.0): """ Prints a shapelet in a formatted way so that it can be visualized with other tools afterwards. The formatted shapelet is returned as a string by this function. """ data = "" for x,y in enumerate(shapelet): data += "{}\t{}\n".format(x+offset,y) data += "\n...
c88dcc3d39c18947737891ed0e37022ac31489ab
615,146
def serialized_time(time): """ Return a serialized version of a datetime instance in the format of a ``DateTimeField`` from Django Rest Framework. Logic taken from: https://github.com/encode/django-rest-framework/blob/6ea7d05979695cfb9db6ec3946d031b02a82952c/rest_framework/fields.py#L1217-L1221 ...
94b27481c73c1036272229e967ebb68ac2443789
615,147
def _get_nn_layers(spec): """ Returns a list of neural network layers if the model contains any. Parameters ---------- spec: Model_pb A model protobuf specification. Returns ------- [NN layer] list of all layers (including layers from elements of a pipeline """ ...
b992a9fab6b5e042fece06ae384f784f7ec38719
615,149
import re def _get_indent(t): """Returns the indentation in the first line of t""" search = re.search(r"^(\s*)\S", t) return "" if search is None else search.groups()[0]
c89b0d2c17c98ead765df1da5479e40dc042caf3
615,151
def get_value(key, attrs): """ Find the key and return it's value """ for attr in attrs: if attr[0] == key: return attr[1]
8410379168e5a7aabaf4f20194e746adfeac06af
615,152
def should_suspend(partial_result) -> bool: """Check the state of the result to determine if the orchestration should suspend.""" return bool(partial_result is not None and hasattr(partial_result, "is_completed") and not partial_result.is_completed)
31155c7106b6a7e42dd2dcc7ec024d29c62a29fa
615,155
import re def find_attribute_idx(newline_split_docs): """Finds the possible split between the header and Attribute annotations Args: newline_split_docs: new line split text Returns: idx: -1 if none or the idx of Attributes """ for idx, val in enumerate(newline_split_docs): ...
72e5895b5877206915b8a1bc81fd12169a209474
615,156
def parse_s3_uri(s3_uri): """ Given a URI of the form s3://<bucket>/<key> parse into bucket, key tuple For a trivial parse this is faster than using urlparse(s3_uri) """ return s3_uri.replace("s3://", "").split("/", 1)
328851ff8a9cc5eecbe8097b0b80bcfc4023368c
615,157
def norm(value_string): """ Normalize the string value in an RTE pair's ``value`` or ``entailment`` attribute as an integer (1, 0). :param value_string: the label used to classify a text/hypothesis pair :type value_string: str :rtype: int """ valdict = {"TRUE": 1, ...
76fa6a42a1387c72c2c16d502f12de26ff8f6839
615,158
def linear_search(lst: list, value: object) -> int: """ Return the index <i> of the first occurance of <value> in the list <lst>, else return -1. >>> linear_search([1, 2, 3, 4], 3) 2 >>> linear_search([1, 2, 3, 4], 5) -1 >>> linear_search([1, 2, 3, 4], 4) 3 >>> linear_search([1,...
3319658a7f3159a9b480c60149c31c33c749a265
615,160
import tempfile import csv def write_named_temp_csv(rows): """ Write the provided rows to a named temporary file. :param rows: List of lists to be written. :return: A named temporary file containing the rows. """ ntf = tempfile.NamedTemporaryFile(suffix=".csv") with open(ntf.name, "w") as...
476c0405bc0fe94cb20112771f3caed67ce116cc
615,163
def append_lags(df, base_col, offsets, group_col='player_id'): """ Calculate "lag" of base_col (raw of previous nth row) :param df: Input DataFrame :param base_col: Name of column to "lag" :param offsets: List of integer offsets (number of rows to lag) :param group_col: Column to group on prior...
4e4738597ce6733fc89be89f99647040b6053079
615,167
async def infer_type_dot(engine, a, b): """Infer the return type of dot.""" t = await engine.assert_same('type', a, b) return t
7f69c95ce953814a0fd70d5afb8bcc8d07ef8077
615,168
def image_directive(image, width=None, align=None, alt=None): """Generate an RST Image directive.""" if width is None: width = '300' if align is None: align = 'center' if alt is None: alt = image return (".. image:: %s\n :width: %s\n :align: %s\n" " :alt:...
c56741097de848288fc9ac450d638cfd890e3ef9
615,169
import torch def rot_from_yaw(yaw): """ Get rotation matrix from yaw Args: yaw: float value representing yaw Returns: 3x3 rotation matrix """ if not isinstance(yaw, torch.Tensor): yaw = torch.Tensor([yaw]) cos = torch.cos(yaw) sin = torch.sin(yaw) z = yaw.new_tens...
0ca3306e8ffb7e16780b0733a4e31125c7cca394
615,171
def rcumode2band(rcumode): """ Map rcumode to band string as used in beamctl arguments Parameters ---------- rcumode: int or str The RCU mode. Returns ------- band: str The band name. """ rcumode = str(rcumode) if rcumode == "3": band = "10_90" el...
9a810c163df8178d02cb350879e82bd7701fd68a
615,172
import copy def injected_cube_position(example_dataset_ifs_crop): """ Inject a fake companion into an example cube. Parameters ---------- example_dataset_ifs_crop : fixture Taken automatically from ``conftest.py``. Returns ------- dsi : VIP Dataset injected_position_yx : ...
4a04deb841d440a4ae9b54180ab0a57d3533edba
615,173
import re def islatitude(value): """ Return whether or not given value is valid latitude. If the value is valid latitude, this function returns ``True``, otherwise ``False``. Examples:: >>> islatitude('-90.000') True >>> islatitude('+99.9') False :param value: s...
66bdd21306ac7370cc7c475bea0304d2fa09fd8c
615,180
def check_valid(number, input_base=10): """ Checks if there is an invalid digit in the input number. Args: number: An number in the following form: (int, int, int, ... , '.' , int, int, int) (iterable container) containing positive integers of the input base input_ba...
0aee543d64cb5e5cf8be33c1e00e7960d51d4a3d
615,183
def d_timeToString(dateString): """ input: string output: string description: format dateString to yyyymmddHHMM example: 2018-08-26 14:18:40 ->> 201808261418 """ return dateString.replace("-", "").replace(" ", "").replace(":", "...
c15cfb267da643220070095c26ae0a8b49902dee
615,186
def stetson_source_chunk(image, ix, iy, nhalf): """Extract a source image chunk.""" return image[iy-nhalf:iy+nhalf+1, ix-nhalf:ix+nhalf+1]
a81b22525e0eceb3d854cddf9f218a353db93f55
615,187
import re def convert_camel_case(operation): """ Converts ``CamelCaseOperationName`` into ``python_style_method_name``. """ return re.sub('([a-z])([A-Z])', r'\1_\2', operation).lower()
f045959dcc752095c8010b4ac4bc0af82c1304ba
615,190
def extract_record_info(instances, info_needed_tuple): """ From a list of sqlalchemy class objects (records from a single table), get the instance attributes specified in the info needed tuple. :param instances: an iterable containing class instances (inst iter) :param info_needed_tuple: tuple cont...
1d24c5cecc56e538616c3c26ad1b3c7c3cbd5ada
615,193
def maybe_to_list(maybe_tensor): """Tries to convert an object that may be a tensor to a list. """ try: return maybe_tensor.tolist() except AttributeError: return maybe_tensor
67fb1b00eef3a69b0b6e7bbeec77dbf446fb019e
615,195
import math def getZPoisson(s, b, stat, syst): """ The significance for optimisation. s: total number of signal events b: total number of background events stat: relative MC stat uncertainty for the total bkg. syst: relative syst uncertainty on background Note that the function already a...
1fc429449793a28800674cafe5ebc436c0c14bcd
615,200
def _GetEnvAsDict(arch): """Gets the saved environment from a file for a given architecture.""" # The environment is saved as an "environment block" (see CreateProcess() # for details, which is the format required for ninja). We convert to a dict # here. Drop last 2 NULs, one for list terminator, one for traili...
7bc88356995676eb1c7a5d5b0ac90487e39b7d82
615,201
def format_configuration(name, value, nearest, path, item_type): """Helper function for formating configuration output :param str name: name of the section being set, eg. paging or log :param str value: new value of the section :param str nearest: value of the nearest set section :param str path: pa...
9fd83da65efe9b8d123d6dabc3e369268b4da9bb
615,204
def multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multi...
a68a573dca42d9f70a22fd44c0c7d60f2676ea02
615,208
import torch def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False): """Calculate overlap between two set of bboxes. If ``is_aligned`` is ``False``, then calculate the ious between each bbox of bboxes1 and bboxes2, otherwise the ious between each aligned pair of bboxes1 and bboxes2. A...
af9ee62b4fc47766b0f382787b4f38df46b66a74
615,209
def still_a_dependency(dependency): """ Defines the criteria for which a dependency is deemed complete (and therefore no longer a dependency). Args: dependency, Table.Row or dict. Processing row corresponding to the required input for the job in prow. This must...
428eb94243e1697cdc6bb083d0f739453731505f
615,214
import random def estimate_occ_per_ap(prob_dist=[0.405, 0.345, 0.125, 0.092, 0.033]): """ Randomly generates a number of occupants between 1 and 5 Parameters ---------- prob_dist : list (of floats), optional Defines probability distribution of occupants per apartment Default: [0.4...
68e778f73e96822ebf3e47e4d9d290da8ca96e53
615,217
import torch def edge_clamp(B_cp, edge_idx, clamp_val=0, device='cpu', dtype=torch.float32): """ Clamp edges of each component of Bcp to clamp_val. RH 2020 Args: B_cp (list of torch.Tensor): Beta Kruskal tensor. List of tensors of shape (n_feature...
46a459a2fa423efea8e7e46d4c236a2868479e25
615,218
def return_string(input_string, replace=[], replace_with=[]): """ Return a stripped string with optional character replacements. Parameters ---------- input_string : string arbitrary string replace : list of strings strings to substitute replace_with : list of strings ...
2304a476033bf6501d27cbc6060da8eea4e16242
615,221
import yaml def _read_config(filename): # pragma: no cover """Read YAML configuration file.""" with open(filename, "r") as reader: return yaml.safe_load(reader)
5be5a8c31262fac10c7c6d6733a197425a7950f6
615,222
def mutation_type(alleles): """ Is this mutation a transition (A <-> G and C <-> T) or a transversion (everything else). """ return 'ts' if set(alleles) == {'A', 'G'} or set(alleles) == {'C', 'T'} else 'tv'
240db6082f9d894e899668c042068ba166a0b334
615,223
import io def get_parameters(file_desc: io.BufferedReader, start_index: int, end_index: int): """ Get part of file :param file_desc: file descriptor :param start_index: Index of the start reading :param end_index: Index of the end reading :return: part of the file """ file_desc.seek(s...
078c64a89ed43b342114856de76a9af75d41c41d
615,228
def has_common(l1, l2): """Returns truthy value if there are common elements in lists l1 and l2""" return set(l1) & set(l2)
cd036fdf70112ce50f14d0a32eccd9fe066ee8dd
615,231
def dict_merge(*dicts): """Merge dictionaries into a single dictionary. """ merged = {} for dict in dicts: merged.update(dict) return merged
c52317c02a5e2481642e1e1eef92e781d053063e
615,233
def verMod11(cprNumbStr): """Perform modulus 11 check for validity of CPR-number. Input: cprNumbStr, str[10], holds a full CPR number Output: True/False, logical, returns failure or succes of check """ if len(cprNumbStr) != 10: raise ValueError("CPR-number to be va...
83358a98000be2676a7e6aab8410f8947397effd
615,241
def findMean(num): """Find the mean of a list of numbers""" length = len(num) sumList = sum(num) return f"Mean value of {num} is {round((sumList / length) ,2)}"
8fbaa6f3a5062cf66acb356f5b018aa7509ec4df
615,245
def add(arg1,arg2): """ Add two values arg1 and arg2 """ return arg1+arg2
7e93188410cce030885ce5281a5a862a8eab711d
615,247
def _common_neighbors(G, u, v): """Get the set of common neighbors between two nodes.""" return set(G[u]) & set(G[v])
3bacd2ba9535c31c8e25fc93b1a85086f7825d89
615,249
def get_Rgap_mec(self): """Returns the radius of the center of the mecanical airgap Parameters ---------- self : Machine Machine object Returns ------- Rgap_mec: float Radius of the center of the mecanical airgap [m] """ stator = self.stator rotor = self.rotor ...
17bcaa33823e27376948fb3e60edaf73870d1804
615,253
def hex_str(an_int): """Convert an int to an hexadecimal string.""" return '{:#x}'.format(an_int)
a29290961c88f9e7c2601f7ed804f3d7e3e7d1cd
615,256
def isDict(val): """Returns true if the passed value is a python dictionary type, otherwise false. **Parameters:** * val - value to test **Returns:** True if the passed value is a dictionary, otherwise false.""" return isinstance(val, dict)
e6d8842b71802a42c37a3f24102c96e5a2815c19
615,259
def sanitize_df(df): """Drops empty rows and columns from the DataFrame and returns it""" # Delete empty rows for i in df.index.tolist()[-1::-1]: if df.iloc[i].isna().all(): df.drop(i, inplace=True) else: break # Delete empty columns cols = [] for column i...
59783e7c7626f899ec487cd2151b98e1a20d1e6f
615,261
def anchor(title): """Return an anchor '#a-title' for a title 'A title'""" return '#' + title.replace(' ', '-')
93d5b467fdb820881522b141ab010f42132128dd
615,266
import base64 def base64_encode(value): """Encode the value in base64""" return base64.b64encode(value)
e8073be8e7b02f36937258f8cbfd2e6eb635a72b
615,267
from typing import Iterable from typing import Any from typing import Optional from typing import Iterator from typing import Tuple import itertools def enumerate_cycle( iterable: Iterable[Any], *, times: Optional[int] = None, ) -> Iterator[Tuple[int, Any]]: """Return iterator of tuples in...
9a49fee443166760227e8211cabd21f3dc56963d
615,269
from typing import Callable def filter_values(d: dict, predicate: Callable) -> dict: """ Returns new subset dict of d where values pass predicate fn >>> d = {'Homer': 39, 'Marge': 36, 'Bart': 10} >>> filter_values(d, lambda x: x < 20) {'Bart': 10} """ return {k: v for k, v in d.items() if...
551b00222361cdb684820d8ce2c22e407d65d362
615,270
from pathlib import Path def get_content(*fps): """Return content for specified file path parts. If the file doesn't exist, return ''. Arguments: fps (List(str)): One or more path parts to be joined with current directory Returns: str: Content of the specified file, othe...
4631c898c776ab8ea88ee4db6c90e4402e37e578
615,275
from typing import Tuple def center_coord(image_size: int, subimage_size: int) -> Tuple[int, int]: """Center a subimage in image along some axis, given image and subimage sizes.""" x0 = (image_size - subimage_size) // 2 x1 = x0 + subimage_size return x0, x1
e5c21f8b23c5b3f165a9468c01e6e63d54aed1d8
615,276
import torch def bbox_iou(box1, box2): """ Returns the IoU of bounding boxes of tensor box1 vs tensor box2 IoU equals (area of rectangular overlap of the boxes / total area of both boxes combined) Params: box1: comparison box 1 - tensor box2: comparison box 2 - tensor Returns: ...
2ad745afcd97c6db071f56c61512c42a1c7ae8b0
615,277
import time def get_windows_timestamp_now() -> int: """ Windows Timestamp in hundreds of ns since 01.01.1601 – 00:00:00 UTC >>> assert get_windows_timestamp_now() > 10000 >>> save_time = get_windows_timestamp_now() >>> time.sleep(0.1) >>> assert get_windows_timestamp_now() > save_time ""...
4674138cdff9205afe7f414678d5fa3dc9e87d60
615,279
def compose(d1, d2): """Compose two homomorphisms given by dicts.""" res = dict() for key, value in d1.items(): if value in d2.keys(): res[key] = d2[value] return res
4a51ab279e9a1507c0c3453587f0e8a81e982e58
615,280
def predict_sex(x_coverage, y_coverage): """Make a simple yet accurate prediction of a samples sex. The calculation is based on the average coverage across the X and Y chromosomes. Note that an extrapolation from a subsection of bases is usually quite sufficient. Args: x_coverage (float): ...
fad139a4c16c348cfb259af3b1b2c19b1790a107
615,286
def multiply(x,y): """Return the result of x multiplied by y""" return x*y
32583cc89fc05fd60448c4fd61240c2d2ef8d747
615,292
import ssl import smtplib def configure_smtp(settings_dict): """ Configures the SMTP gateway. Args: settings_dict (dict) Returns: smtplib.SMTP: The SMTP connection. Raises: Exception: If anything goes wrong. """ # Create a SSL context ...
5f4b7444506a0448eebf5b1606724b5300837a93
615,295
def z_score(x, df): """Calculate a z score for each x value, using estimates from a pandas data frame with the columns 'mu' and 'sd' and index coressponding to the x values""" z = (x.transpose() - df['mu'])/df['sd'] return z.transpose()
3c9349d55b561de3c02a1cccb03bf5d13583da6c
615,297
def convert_from_bytes(bytes): """Convert bytes to higher orders Args: bytes (int): size in bytes Returns: str: size in higher order """ for unit in ["bytes", "KB", "MB", "GB", "TB"]: if bytes < 1000: return f"{bytes:.2f} {unit}" bytes /= 1000
7677adfc34449c6e108577e0b2240c8f204bfca5
615,301
def quote_nonascii(s): """Like urllib.parse.quote, but explicitly only escaping non-ascii characters.""" return "".join(chr(c) if c <= 127 else "%%%02X" % c for c in s.encode('utf8'))
fcb1f1d324207b90288454460258395a6846842c
615,302
import torch def flip(flip, data = None, target = None, probs = None): """ Args: flip: boolean whether to apply flip augmentation data: input data to augment BxCxWxH target: labels to augment BxWxH probs: probability masks to augment BxCxWxH Returns: data, target...
989c556047f6563dc451f527d8096c799d1f1a63
615,307
import time def timeit(f, log=True): """ Times the execution of the function ``f`` Returns: *: result of applying ``f`` to ``args`` and ``kw`` float: time needed to execute ``f`` Usage ----- Either use it as .. code-block:: python @timeit def new_fn(): ...
0b2e4200bac2c086008433b4476ba9069a8b574f
615,315
import socket def is_port_open(port): """ Checks if the port is open on localhost by creating a socket connection to it. :param port: The port as a number :return: True if open, false otherwise """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: return sock.connect_ex((...
51ab6b8a5259f2628a2b9d163acda2c266130566
615,318
import csv def read_file(filename): """Read csv file with rows: x, y""" px = [] py = [] with open(filename) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: px.append(float(row[0])) py.append(float(row[1])) return px, py
e1d2c606bb8ebb06331380219a8012282354256d
615,323
import struct def structparse_ip_header_embedded_protocol(bytes_string: bytes): """Takes a given bytes string of a packet and returns information found in the IP header about the embedded protocol at the next level of encapsulation. Examples: >>> from scapy.all import *\n >>> icmp_pcap = rdpc...
9c456ea3da7904bed363c7fd77480662e3184b8a
615,334
def linear_normal(g, input, weight, bias): """Symbolic function for `linear`. PyTorch `nn.Linear` will be exported as ONNX node 'Gemm'. """ return g.op( 'Gemm', input, weight, bias, alpha_f=1.0, beta_f=1.0, transA_i=0, transB_i=1)
7fad1ef60d63d72f6b6dd39077aeed663d492cde
615,335
def grid_dist(cell1, cell2): """Euclidian distance between two points In particular, 1 for adjacent cells and √2 for diagonally touching square cells """ return ((cell1[0] - cell2[0]) ** 2 + (cell1[1] - cell2[1]) ** 2) ** 0.5
ec3b641bdfe4b2d0091e5fef35ba14afd9391004
615,336
import math def percentile(data, pc): """Naive algorithm to compute the pc'th percentile of a list of (sorted) data. Linear interpolation is used when the percentile lies between two data points. It is assumed that the data contains no NaN or similar. """ if pc < 0 or pc > 100: raise Value...
e96c8368528688fcda9d60a5bc0fb39428bfd040
615,338
from typing import Optional import re def keys_and_input_text(obj: dict) -> Optional[bool]: """Filter input text and IDs on left side of page :param obj: pdf character :return: Whether to keep the filtered character """ if "fontname" in obj.keys(): if obj["x0"] < 50: matches ...
b90b932b98cbcd8a810857574fb010f7b1d5c898
615,339
def get_N1(nvols, TR, HP): """ Get the low frequency point Parameters ---------- TR : float Temporal Resolution nvols : int Number of volumes HP : float HighPass Low Cutoff Frequency Returns ------- n1 : float Low Frequency Point """ ...
1f61e44579960f9f6fbff28d1a8f87166b3deef8
615,342
import uuid def generate_secret_key() -> str: """ Generate secret key. Returns: str: secret key in 32 characters uuid4 format. """ return str(uuid.uuid4().hex)
b0b0c08d8bd92d73e662d1f49f5a71da8ba94077
615,346
import torch def quaternion_multiply(quaternion1, quaternion2): """Multiply quaternion1 by quaternion2. Args: quaternion1: N x 4 quaternions quaternion2: N x 4 quaternions Returns: res: N x 4 """ x1, y1, z1, w1 = quaternion1[:, 0], quaternion1[:, 1], quaternion1[:, 2], qu...
c1e0b69fe0aafb411906727e8636ee6ac6e32061
615,349
def duplicate(x, rep): """Duplicate x rep times. Args: x (torch.Tensor): Tensor to replicate rep (int): Number of times to replicate Returns: torch.Tensor: Replicated Tensor """ return x.expand(rep, *x.shape).reshape(-1, *x.shape[1:])
bf9c5aee0d0c0c567569db84c11a850283288f0f
615,351
import struct def turn_plink_assoc_line_into_bin(line): """ This turns a non header line from a standard plink repeated univariate association file (*.qassoc) into a byte format. The format represents in order: short (h): chromosome (only numeric chromosome allowed) int (i): position ...
555c15a68c8580fabd162dadbad78459b04b2c6c
615,352