content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def int_to_mode(mode): """Returns the string representation in VPP of a given bondethernet mode, or "" if 'mode' is not a valid id. See src/vnet/bonding/bond.api and schema.yaml for valid pairs.""" ret = {1: "round-robin", 2: "active-backup", 3: "xor", 4: "broadcast", 5: "lacp"} try: return ret[mode] except KeyError: pass return ""
af4962c397578c9d62fc176dc1cf843ec0ff7064
406,418
def header_transform(key: str) -> str: """ Function returns header key in human readable :param key: header key :return: translated headers """ header_dict = { 'Cve': 'CVE ID', 'CVSS': 'CVSS Score', 'VRR': 'VRR Score', 'ThreatCount': 'Threat Count', 'VulnLastTrendingOn': 'Last Trending On Date', 'Trending': 'Trending', } return header_dict.get(key, '')
d5c654dc9c31b2fbbe412487692e2052810dde10
44,322
def tupleize(func): """A decorator that tuple-ize the result of a function. This is useful when the evaluation function returns a single value. """ def wrapper(*args, **kargs): return func(*args, **kargs), return wrapper
2a2a9d709177868bd47571f86ae026d666b2593b
10,439
def let_count(word: str) -> dict: """ Returns the count of letters in a string as a dictionary """ return {x: word.count(x) for x in set([x for x in word])}
ad379a1387cb861c93ac5f4ca187db0d17ded66e
481,891
def quoteStr(s, addQuotes=False, quoteDouble=False, quoteSingle=True): """ s (str) -- Source string parameter. Options: - addQuotes (bool|str) -- Add quotes around result string (default: False, don't quote). - quoteSingle (bool) -- Quote single quotes ('), default is True. - quoteDouble (bool) -- Quote double quotes ("), default is False. Returns string. """ if not isinstance(s, str): # type(s) != str: if s is None: s = '' else: s = str(s) if quoteDouble: s = s.replace('"', '\\"') if quoteSingle: s = s.replace('\'', '\\\'') if addQuotes: if addQuotes is True: addQuotes = "'" s = addQuotes + s + addQuotes return s
399ef818107e5409211348aa64386bbc2a24113c
650,868
def intdiv(p, q): """ Integer divsions which rounds toward zero Examples -------- >>> intdiv(3, 2) 1 >>> intdiv(-3, 2) -1 >>> -3 // 2 -2 """ r = p // q if r < 0 and q*r != p: r += 1 return r
dc1b507f4a5e71f93a3145bbffe8076ab43cf117
77,306
def scale_abcline(input_line, orig_dims, new_dims): """ :param input_line: line of form [a, b, c] from equation of form ax+by+c=0 :param orig_dims: tuple of (width, height) of original dimensions :param new_dims: tuple of (width, height) of new dimensions :return: scaled line of form [a', b', c'] from equation of form a'x+b'y+c'=0 """ # rescaling the horizon line according to the new size of the image # see https://math.stackexchange.com/questions/2864486/ # how-does-equation-of-a-line-change-as-scale-of-axes-changes?noredirect=1#comment5910386_2864489 horizon_vectorform = input_line.copy() net_width, net_height = orig_dims re_width, re_height = new_dims horizon_vectorform[0] = horizon_vectorform[0] / (re_width / net_width) horizon_vectorform[1] = horizon_vectorform[1] / (re_height / net_height) horizon_vectorform = horizon_vectorform / horizon_vectorform[2] return horizon_vectorform
ec583dbcf716cd67d9457df516ede44ecca7ec38
381,545
def swap_bbox_format(bbox_tuple): """Swap between (row0, col0, row1, col1) and (x0, y0, x1, y1) formats.""" assert len(bbox_tuple) == 4 return (bbox_tuple[1], bbox_tuple[0], bbox_tuple[3], bbox_tuple[2])
70f25efdde490acee7442a29f76117615fb1125c
588,699
def popcount_local(num): """Count 1's in an integer""" return bin(num).count("1")
b292cb82bc140d840127db359c3618a1fd8d5084
346,783
def check_xml_for_silence(sbf): """ Function to determine if a section marked in an Audacity xml file contains silence or sound. Parameters ---------- sbf : dictionary `<simpleblockfile>` tag parsed from Audacity xml file Returns ------- silence: boolean True if silence, False if sound """ if float(sbf['min']) == 0.0 and float(sbf['max']) == 0.0 and float(sbf[ 'rms']) == 0.0: return True else: return False
c6e0d80846888965412810099a30598fb81dda7c
95,432
import glob import json def parse_yang2proto_files(yang2proto_file_glob): """Parses a glob specifying yang2proto files to load as JSON.""" yang2proto = [] for yang2proto_filename in list(glob.glob(yang2proto_file_glob)): with open(yang2proto_filename) as yang2proto_fd: yang2proto.extend(json.load(yang2proto_fd)) return yang2proto
75f3dfe859d0e72b723c58d3d382a6a0410a066a
147,592
def is_same_py_file(file1, file2): """compares 2 filenames accounting for .pyc files""" if file1.endswith('.pyc') or file1.endswith('.pyo'): file1 = file1[:-1] if file2.endswith('.pyc') or file2.endswith('.pyo'): file2 = file2[:-1] return file1 == file2
836e3d4dcbb23f90b6a539fe63513cf40205eb29
522,327
def c2f(c: float, r: int = 2) -> float: """Celsius to Fahrenheit.""" return round((c * 1.8) + 32, r)
9c4d950b6fc91e797348d151722877932310337f
278,747
def any_are_not_none(*args) -> bool: """ Return True if any arg is not None. """ return any([arg is not None for arg in args])
555da8dc54b737ed9c221f3b8b0594a347bd09b1
406,243
import torch def calculate_tp_troch(pred_boxes, pred_scores, gt_boxes, gt_difficult=None, iou_thresh=0.5): """ calculate tp/fp for all predicted bboxes for one class of one image. 对于匹配到同一gt的不同bboxes,让score最高tp = 1,其它的tp = 0 Args: pred_boxes: Tensor[N, 4], 某张图片中某类别的全部预测框的坐标 (x0, y0, x1, y1) pred_scores: Tensor[N, 1], 某张图片中某类别的全部预测框的score gt_boxes: Tensor[M, 4], 某张图片中某类别的全部gt的坐标 (x0, y0, x1, y1) gt_difficult: Tensor[M, 1], 某张图片中某类别的gt中是否为difficult目标的值 iou_thresh: iou 阈值 Returns: gt_num: 某张图片中某类别的gt数量 tp_list: 记录某张图片中某类别的预测框是否为tp的情况 confidence_score: 记录某张图片中某类别的预测框的score值 (与tp_list相对应) """ if gt_boxes.numel() == 0: return 0, [], [] # 若无对应的boxes,则 tp 为空 if pred_boxes.numel() == 0: return len(gt_boxes), [], [] if gt_difficult is None: gt_difficult = torch.zeros((len(gt_boxes), 1)).to(gt_boxes) # 否则计算所有预测框与gt之间的iou ious = pred_boxes.new_zeros((len(gt_boxes), len(pred_boxes))) for i in range(len(gt_boxes)): gb = gt_boxes[i] area_pb = (pred_boxes[:, 2] - pred_boxes[:, 0]) * (pred_boxes[:, 3] - pred_boxes[:, 1]) area_gb = (gb[2] - gb[0]) * (gb[3] - gb[1]) xx1 = pred_boxes[:, 0].clamp(min=gb[0].item()) # [N-1,] yy1 = pred_boxes[:, 1].clamp(min=gb[1].item()) xx2 = pred_boxes[:, 2].clamp(max=gb[2].item()) yy2 = pred_boxes[:, 3].clamp(max=gb[3].item()) inter = (xx2 - xx1).clamp(min=0) * (yy2 - yy1).clamp(min=0) # [N-1,] ious[i] = inter / (area_pb + area_gb - inter) # 每个预测框的最大iou所对应的gt记为其匹配的gt max_ious, max_ious_idx = ious.max(dim=0) not_difficult_gt_mask = gt_difficult == 0 gt_num = not_difficult_gt_mask.sum().item() if gt_num == 0: return 0, [], [] # 保留 max_iou 中属于 非difficult 目标的预测框,即应该去掉与 difficult gt 相匹配的预测框,不参与p-r计算 # 如果去掉与 difficult gt 对应的iou分数后,候选框的最大iou依然没有发生改变,则可认为此候选框不与difficult gt相匹配,应该保留 not_difficult_pb_mask = (ious[not_difficult_gt_mask].max(dim=0)[0] == max_ious) max_ious, max_ious_idx = max_ious[not_difficult_pb_mask], max_ious_idx[not_difficult_pb_mask] if max_ious_idx.numel() == 0: return gt_num, [], [] confidence_score = pred_scores.view(-1)[not_difficult_pb_mask] tp_list = torch.zeros_like(max_ious) for i in max_ious_idx[max_ious > iou_thresh].unique(): gt_mask = (max_ious > iou_thresh) * (max_ious_idx == i) idx = (confidence_score * gt_mask.float()).argmax() tp_list[idx] = 1 return gt_num, tp_list.tolist(), confidence_score.tolist()
934462eb53bed7cc88bcc169d619cc46c44ae3a4
557,359
def beta_to_kelvin(beta): """ Convert :math:`\\beta` to Kelvin. Parameters ---------- beta : float Inversion temperature. Returns ------- T : float Temperature (K). """ kb=8.6173303E-5 ev = 1.0/float(beta) T = ev/kb return T
6f58f248fad6045cf1b9f9e6d29f162f3e01f515
577,771
def year_to_season(yr: str) -> int: """Converts a school year into a season e.g. year_to_season("2016-17") returns 2017 :param yr: String :returns: Int """ return int(yr[0:4]) + 1
51caeee1659e584cdd92a919cbdde257b718c76a
330,836
def first(items): """ Get the first item from an iterable. Warning: It consumes from a generator. :param items: an iterable :return: the first in the iterable """ for item in items: return item
2ed7fa730b1b1c1588bc98e93ac8ef02a669ae98
29,346
from typing import Dict def status_of_battery_event(data: Dict) -> bool: """Verifies whether the receives data indicates a valid battery status.""" for required in [ "chargePercent", "created", "current", "healthPercent", "isCharging", "sensorId", "state", "temperature", "trained", "voltage", ]: if isinstance(data.get(required), type(None)): return False return True
465cc8dff96016d3f3efdf216b01f511d4e94a46
381,598
def strftime(to_format): """strftime(to_format)(dt_obj) -> str Return datetime, time or date object dt_obj formatted with to_format. :: str -> (datetime.datetime|datetime.date|datetime.time) -> str >>> strftime('%Y-%m-%d')(datetime.date(2112, 12, 21)) '2112-12-21' """ return lambda dt_obj: dt_obj.strftime(to_format)
72a4f5ea1ebbe9b0734cb3f6b4890e7e18c3e601
337,226
from pathlib import Path import glob def get_target_path(tracking_file_source, target_dir): """ get_target_path(tracking_file_source, target_dir) Returns the target path (mouse/session specific) for a source json. Required args: - tracking_file_source (Path): source json path - target_dir (Path) : main target data directory (up to, but excluding mouse directories) Returns: - tracking_file_target (Path): target json path """ # identify target directories source_file_name = Path(tracking_file_source).name file_name_tokens = str(source_file_name).split("_") mouse_id = file_name_tokens[file_name_tokens.index("mouse") + 1] sess_id = file_name_tokens[file_name_tokens.index("session") + 1] target_direc_pattern = Path( target_dir, f"mouse_{mouse_id}", f"ophys_session_{sess_id}", f"ophys_experiment_*", "processed" ) target_direc = glob.glob(str(target_direc_pattern)) if len(target_direc) == 0: raise OSError( f"No directory found with pattern: {target_direc_pattern}." ) elif len(target_direc) > 1: target_matches = ", ".join([str(match) for match in target_direc]) raise NotImplementedError( f"Multiple directories found with pattern: {target_direc_pattern}, " f"namely {target_matches}" ) else: target_direc = target_direc[0] # set target path tracking_file_target = Path(target_direc, source_file_name) return tracking_file_target
b865c36c4f20f902cf42a919ceca379392ff85bc
294,506
def _without(o, *values): """ Return a version of the array that does not contain the specified value(s), or object that doesn't contain the specified key(s) """ if isinstance(o, dict): newlist = {} for k in o: if k not in values: newlist[k] = o[k] else: newlist = [] for v in o: if v not in values: newlist.append(v) return newlist
2851402bea72813b5563d352a84d97677dccd462
474,017
from typing import Set def bits_to_candidates(bits: int) -> Set[int]: """ Convert a bits representation into a set of candidates >>> bits_to_candidates(0b111) {1, 2, 3} >>> bits_to_candidates(0b111000101) {1, 3, 7, 8, 9} """ candidates = set() i = 1 while bits: bit = bits & 1 if bit: candidates.add(i) bits >>= 1 i += 1 return candidates
47a662da6423e730c5a15692a835b0c63ba5e69f
234,796
def is_valid_nuc(nuc): """Check if valid single letter base. Parameters ---------- nuc : str String to check if valid single nucleotide base Returns ------- is_valid : bool flag indicating valid nucleotide base """ valid_nucs = ['A', 'C', 'T', 'G', 'N'] is_valid = nuc in valid_nucs return is_valid
02009b030072c18cabdd152cde879b4f3974b9a5
130,715
def parse_client_time(config_root): """ Parse the client time (the duration that the test should be executed for) from the XML configuration. Parameters ---------- config_root : xml.Element The root of the XML config file. Returns ------- client_time : int The duration that the test should be executed for. Raises ------- KeyError If the relevant key (works.work.time) is not present in the XML file. """ try: return int(config_root.find('works').find('work').find('time').text) except: raise KeyError("Couldn't parse the config file for works.work.time.")
a871f0028d70636bac0b818d2c9eb7574183f49e
299,085
def lin_f(xy_s, xy_e): """Find a function representing for a line: y = ax + b :param: xy_s: tuple start point coordinate of the line :param: xy_s: tuple end point coordinate of the line """ a = (xy_e[1] - xy_s[1]) / (xy_e[0] - xy_s[0]) b = xy_e[1] - a * xy_e[0] return a, b
b1d62e205e713bf7a8ad69c236a87741221557f8
311,868
def to_lower_camel(name: str) -> str: """Converts snake_case string into lowerCamelCase.""" head, *tail = name.split("_") return head.lower() + "".join(x.title() for x in tail)
9229ce02b84310ec345d71feac8abbaf8b39fa61
436,273
def read_dictionary(path, multivals=False, func_key=lambda x: x, func_val=lambda x: x): """ Parameters ---------- path: str multivals: bool, default False func_key: function: str -> Any func_val: function: str -> Any Returns ------- dict[Any, Any] or dict[Any, list[Any]] """ d = {} for line in open(path): line = line.strip().split() if multivals: if len(line) == 2: key, val = line vals = [val] else: key = line[0] vals = line[1:] d[func_key(key)] = [func_val(val) for val in vals] else: if len(line) == 2: key, val = line else: key = line[0] val = " ".join(line[1:]) d[func_key(key)] = func_val(val) return d
375fd0cf61ea11dc9f8a16358e25433cd3591ae2
172,800
def calc_cent_scale(img): """ Calculates the centre of an image and the correct scale value. Parameters ---------- img : numpy.ndarray The image to process. Returns ------- c : int The coordinates of the centre of the image. s : float The scale of the image in relation to a 200x200 image. """ imgw = img.shape[1]; imgh = img.shape[0]; c = (int(imgw / 2), int(imgh / 2)); s = imgh / 200; return c , s;
1381a8030b10d8e0efa65f27b0b4322cf25d069c
564,803
def _vars_to_add(new_query_variables, current_query_variables): """ Return list of dicts representing Query Variables not yet persisted Keyword Parameters: new_query_variables -- Dict, representing a new inventory of Query Variables, to be associated with a DWSupport Query current_query_variables -- Dict, representing the Query Variables currently associated with the 'new_query_variables' Query mapped by tuple(table_name, column_name) >>> from pprint import pprint >>> test_new_vars = { 'great_fact': ['measure_a', 'measure_b'] ... ,'useful_dim': ['field_one'] ... ,'occasionally_useful_dim': ['field_two']} >>> persisted_vars = { ('great_fact', 'measure_a'): object() #fake ... ,('useful_dim', 'field_one'): object()#objects ... ,('useful_dim', 'field_two'): object()} >>> out = _vars_to_add(test_new_vars, persisted_vars) >>> pprint(out) # check detected additions {'great_fact': ['measure_b'], 'occasionally_useful_dim': ['field_two']} """ additional_fields_by_table_name = {} # Values to return # detect additions for new_variable_table_name, table_columns in new_query_variables.items(): for column_name in table_columns: key = (new_variable_table_name, column_name) #table+column tuple if key not in current_query_variables: # New Query Variable - add variable name to table's list table_variables = additional_fields_by_table_name.setdefault( new_variable_table_name ,list()) #default to new, empty list (if none exists yet) table_variables.append(column_name) return additional_fields_by_table_name
fd5ea2209b374ab9987a05c139ba1f28805f3eff
706,329
def get_safe(dat, start_idx=None, end_idx=None): """ Returns a filtered window between the two specified indices, with all unknown values (-1) removed. """ if start_idx is None: start_idx = 0 if end_idx is None: end_idx = 0 if dat.shape[0] == 0 else dat.shape[0] - 1 # Extract the window. dat_win = dat[start_idx:end_idx + 1] # Eliminate values that are -1 (unknown). return dat_win[dat_win != -1]
61d9974ca4c6d670e5aa253f9c757a842beae28f
217,606
def get_nn_dict(cnn, structure, ix): """ For the given atom indices, calculates the nearest neighbours using the crystalNN method. Args ---- cnn: CrystalNN The CrystalNN class object. structure: pymatgen.core.Structure Pymatgen Structure object. ix: list Indices (int) of atoms to get neighbours for. """ return { i:cnn.get_nn_info(structure,i) for i in ix }
cc88c67117505ae8203eb4a1e74470fe0faf4c4f
436,779
def vending_machine(snacks): """Cycles through sequence of snacks. >>> vender = vending_machine(('chips', 'chocolate', 'popcorn')) >>> vender() 'chips' >>> vender() 'chocolate' >>> vender() 'popcorn' >>> vender() 'chips' >>> other = vending_machine(('brownie',)) >>> other() 'brownie' >>> vender() 'chocolate' """ index = 0 def vender(): nonlocal index snak = snacks[index % len(snacks)] index += 1 return snak return vender
27f1789f8137044f692753c367dce82d83c98cc9
447,463
def proper_form(s:str)->str: """ return properly formed string for metric to be consistent, for example a_prc->AUPRC since in papers & other official documents we abbreviate "area under the precison recall curve" as AUPRC :parm s: any string :return: proper form of input value if we know it, the input value unchanged if not """ if s == "a_prc": return "\\ac{AUPRC}" elif s == "auc": return "\\ac{AUC}" elif s == "acc": return "accuracy" else: return s
1471523b292367aab150811f38b5cd6d04f15e58
430,719
def get_form_field(form, label): """ Return a bound field with the given label from a form """ return form.fields[label].get_bound_field(form, label)
94bbc89949d513c6abda4be0f1d4bc6cbdb85a0c
212,278
import re def generate_id(title, published_on=None): """Generates a report id given the report title and published date. This generally tries to be clever and uses the first letter of each name of the title, then the month date and year of the report as the ID. """ words = title.split() letters = [word[0] for word in words if re.match(r'\w', word[0])] slug = ''.join(letters).upper() if published_on: return '%s-%s' % (slug[:16], published_on.strftime('%Y-%m-%d')) else: return slug
ffdc6189a886b21bc78f5d9ddf0613e8b95caac4
307,145
def decide_model_actions(spec, model): """ either set the param hints or the bounds depending on the spec dict :param spec: dictionary of the params to be set on the model :param model: lmfit model object :return: the updated model object """ for param_key, param_value in spec['params'].items(): if param_value: # then set this value model.set_param_hint(param_key, value=param_value) for bound_key, bound_value in spec['bounds'].items(): if bound_value[0]: # then set lower bound model.set_param_hint(bound_key, min=bound_value[0]) if bound_value[1]: # then set upper bound model.set_param_hint(bound_key, max=bound_value[1]) return model
8792477b15d6fe75d4d31c0dfa2876a7c9115f09
377,161
import logging import zipfile import tarfile def get_archive_member_names(archive_file_name, archive_file_type): """ Gets all of the file names/members of the archive. :param archive_file_name: the file name/path of the archive :param archive_file_type: the file extention type: 'tar' or 'zip' :return: a list of the names/members in the archive on success, None if failure to open/read archive :rtype: bool """ logging.info("Checking archive... this may take a moment for large files.") try: if archive_file_type == 'zip': archive = zipfile.ZipFile(archive_file_name, 'r', allowZip64=True) return archive.namelist() elif archive_file_type == 'tar': archive = tarfile.open(archive_file_name, mode='r') archive_members = archive.getmembers() archive_name_list = [] for item in archive_members: if item.type == tarfile.DIRTYPE: #append a '/' to the end of the directory name to match zip output formatting archive_name_list.append(item.name + '/') else: archive_name_list.append(item.name) return archive_name_list except: # expected errors: (zipfile.BadZipFile, tarfile.ReadError), but catch all of them anyways logging.error("Error thrown attempting to read/open the archive. Please use 'zip' or 'tar' to create your archive.") return None
0285e878b74ac947b863bb16adf7a148230fd362
402,914
def add_heat(heatmap, bbox_list): """ Given a heatmap, add one to each pixel inside each bounding box in the specified list. Args: heatmap: Modify and return this heatmap. bbox_list: List of bounding boxes for potential car locations. Returns: A modified heatmap """ # Iterate through list of bboxes for box in bbox_list: # Add += 1 for all pixels inside each bbox # Assuming each "box" takes the form ((x1, y1), (x2, y2)) heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1 # Return updated heatmap return heatmap
4a387f946313830aaeb1181cbe15f310ce1494b7
560,538
import re def parse_colors(colors_string): """ Return a list of colors in the format '#XXXXXX' from colors_string or the default colors if no color is found. """ # RGB colors default_colors = ['#ff0000', '#00ff00', '#0000ff'] colors = [] if isinstance(colors_string, str): colors = re.findall('#[0-9a-fA-F]{6}', colors_string) try: assert colors != [] except AssertionError: colors = default_colors return colors
9be978564e17718b73a5087e96ce8d907d687004
268,621
def compss_wait_on(*args): """ Dummy compss_wait_on :param args: Objects to wait on :return: The same objects defined as parameter """ ret = list(map(lambda o: o, args)) ret = ret[0] if len(ret) == 1 else ret return ret
bbeeddaa6ea3efa6215a0d8f0cf02f5d01657804
532,467
def _get_bunch_bounds(bunch): """Return the data bounds of a bunch.""" if 'data_bounds' in bunch and bunch.data_bounds is not None: return bunch.data_bounds xmin, ymin = bunch.pos.min(axis=0) xmax, ymax = bunch.pos.max(axis=0) return (xmin, ymin, xmax, ymax)
8ec5db4a46f367050fd2504b7fd2e7940654af54
548,648
def view_exists(spark_session, view_name): """Return True if the specified view exists""" try: _ = spark_session.read.table(view_name) return True except: return False
c21998d87c9cc5715d1b3ef93bfea0b9cfecc19d
57,248
def add_node(nodes, parent, time): """Adds a node with specified parent and creation time. This functions assumes that a node has been already allocated by "child" functions `add_node_classifier` and `add_node_regressor`. Parameters ---------- nodes : :obj:`Nodes` The collection of nodes. parent : :obj:`int` The index of the parent of the new node. time : :obj:`float` The creation time of the new node. Returns ------- output : `int` Index of the new node. """ node_index = nodes.n_nodes nodes.index[node_index] = node_index nodes.parent[node_index] = parent nodes.time[node_index] = time nodes.n_nodes += 1 return nodes.n_nodes - 1
d204d618114b13ffcbfc038c91884f4a87e743c0
36,405
import re def remove_script_lines(text): """Remove the starting and ending lines produced by script(1).""" script_re = re.compile(r'^Script (started|done) on \w+ \d+ \w+ \d{4} ' r'\d\d:\d\d:\d\d \w+ \w+$') try: first_newline = text.index(b'\n') first_line = text[:first_newline].decode('ascii') except (ValueError, UnicodeDecodeError): pass else: if script_re.match(first_line): text = text[first_newline+1:] try: last_newline = text.rstrip().rindex(b'\n') last_line = text[last_newline+1:].decode('ascii') except (ValueError, UnicodeDecodeError): pass else: if script_re.match(last_line): text = text[:last_newline] return text
42a383f19cb44286b8d82ba1bdca228fc3b86988
195,450
import random def random_text(size): """Randomly generate text""" alphabet_and_numbers = 'abcdefghijklmnopqrstuvwqyz1234567890' return(''.join(random.choice(alphabet_and_numbers) for _ in range(size)))
fe72e51479756da32456a57c671d51ccee067d72
693,935
def hex_to_int(color): """ :hex_to_int: converts a string hexadecimal rgb code to a tuple rgb code consisting or integer values for each channel. :param color: string | hex code for a color (does not include the hashtag) :return: (r, g, b) | a tuple rgb code in integer form """ return int(color[:2], 16), int(color[2:4], 16), int(color[4:], 16)
f02ffca88cec926b530caa0fc20fc614dc4376a9
671,514
import struct import base64 import hashlib def ri_b64hash(path): """Get Base64 encoded hash of a router from a RouterInfo file""" with open(path, "rb") as f: data = f.read() cert_len = struct.unpack("!H", data[385:387])[0] public_data = data[:387+cert_len] return base64.b64encode(hashlib.sha256(public_data).digest(), altchars=b"-~").decode()
9bfad953b069b26c23cf35cc60e057077b10d397
308,701
def parse_int_list(s): """ Parse a comma-separated list of strings. The list may additionally contain ranges such as "1-5", which will be expanded into "1,2,3,4,5". """ result = [] for item in s.split(','): item = item.strip().split('-') if len(item) == 1: result.append(int(item[0])) elif len(item) == 2: start, end = item result.extend(range(int(start), int(end)+1)) else: raise ValueError("invalid range: '{0}'".format(s)) return result
b53508b1d7bed0f16a0c56175115f01d962cbeef
512,624
def get_config_from_package(package): """ Breaks a package string in module and class. :param package: A package string. :return: A config dict with class and module. """ package_x = package.split('.') package_conf = {} package_conf['class'] = package_x[-1] package_conf['module'] = '.'.join(package_x[:-1][:]) return package_conf
b6504372aac83d008e97463636d7bcd7533e061b
123,450
import math def uni_comp_strength(c, Phi): """ calculates and returns the Uniaxial Compressive Strength of the rock given Cohesion (c) and Friction Angle (Phi). """ return (2*c*math.cos(math.radians(Phi)))/(1-math.sin(math.radians(Phi)))
4db4cdbf494a8f4f063ca5827e7459b7ec5558d1
55,079
from typing import List def protein_list() -> List[str]: """Proteins to constrain as a pool set.""" return [ "prot_P21599", "prot_P0A9B2", ]
a94b8495285d4d656e7bb5287241e081e3954bdf
459,716
def get_examples(section_div, examples_class): """Parse and return the examples of the documentation topic. Parameters ---------- section_div : bs4.BeautifulSoup The BeautifulSoup object corresponding to the div with the "class" attribute equal to "section" in the html doc file. examples_class: Str The value of the "class" attribute of the <div> tag within section_div. "highlight-python" is the class which are used for examples in the webpage. Returns ------- Str: The examples for the topic. """ example = section_div.find("div", attrs={"class": examples_class}) if example: return example.text.strip() return
93da0bfc7fec2b2f7668fd24825068a91c672398
650,794
def data_exists(data, channel, column): """Check for a channel/column existing""" if channel in data: if column in data[channel].columns: return True return False
17f5ef1509e00bbcba018dc6cd6fa663b47905b3
211,099
import torch def ClassificationAccuracy(output, target): """ ClassificationAccuracy on a given batch Args: output(:obj:`torch.Tensor`) - predicted segmentation mask of shape BATCHES x SCORES FOR DIFFERENT CLASSES target(:obj:`torch.Tensor`) - expected segmentation mask of shape BATCHES x SCORES FOR DIFFERENT CLASSES Returns: Classification Accuracy averaged over the batch of images """ predictions = torch.argmax(output.data, 1) # indices of the predicted clases correct = (predictions == target).sum().item() total = output.size(0) return correct / total
024efd8715492e7c5a2984b1846840c297edfe27
32,848
def wordSplit(word): """Split the word into individual letters. Place these in a list.""" return list(word)
d2bd14a9f385e111e4b6a8a2ec8046dbc8188070
305,269
def _get_file_obj(fname, mode): """ Light wrapper to handle strings and let files (anything else) pass through """ try: fh = open(fname, mode) except (IOError, TypeError): fh = fname return fh
eb305e02a916f6e8d6b15b1ea4fc492a767e039a
318,983
import hashlib from pathlib import Path def label_generator(predictions, processor, filename): """Generates a unique label for the image based on the predicted class, a hash, and the existing file extension. Parameters ---------- predictions : np.array Output from model showing each target probability processor : keras.util Prediction utility unique to each model filename : str Path to image or image name Returns ------- new_label : str New label consisting of predicted class plus a hash """ # Hash predictions for always unique filename hashed = hashlib.sha1(predictions).hexdigest() # Get label from keras predictor label = processor(predictions, top=1)[0][0][1] # Capture original image suffix suffix = "".join(Path(filename).suffixes) new_label = f"{label}_{hashed}{suffix}" return new_label
8baba1aad6ad9a7f4d69b499a76b1b4079e79cb5
24,817
def transform_basis_name(name): """ Transforms the name of a basis set to an internal representation This makes comparison of basis set names easier by, for example, converting the name to all lower case. """ name = name.lower() name = name.replace('/', '_sl_') name = name.replace('*', '_st_') return name
a1fd3cc6c140c16a35ef795f18ce10f351d4bdbd
208,579
def morton2D(k, x, y): """ Computes and returns the morton code of the x, y coordinates each represented with k bits Args: k: Bits to represent each coordinate with x: X coordinate y: Y coordinate Returns: The morton code in integer format of the x, y coordinates of size 2*k """ result = (x << k) + y return result
f89a26fa522dfd6cdcf53c597411854fecc77848
498,977
def reverse_map(dict_of_sets): """Reverse a map of one-to-many. So the map:: { 'A': {'B', 'C'}, 'B': {'C'}, } becomes { 'B': {'A'}, 'C': {'A', 'B'}, } Args: dict_of_sets (dict[set]): A dictionary of sets, mapping one value to many. Returns: dict[set]: The reversed map. """ result = {} for key, values in dict_of_sets.items(): for value in values: result.setdefault(value, set()).add(key) return result
87b0679a0ebd00c3dbdcafc89fd2644b21ecbc85
698,671
def process_empty(p): """ Helper function for multiprocessing. Literally returns empty. Args: p: Point Returns: [p, 0, [], [], []] """ return [p, 0, [], [], []]
28d5cce2d6038fc47727809142a9bd59012f4ae8
566,022
import json def import_json(json_file): """Import json and convert it to a dictionary.""" with open(json_file) as jsonfile: # `json.loads` parses a string in json format file_dict = json.load(jsonfile) return file_dict
944b4ef534e26698b8ed24a67feadbe128934871
563,325
from bs4 import BeautifulSoup def gather_ids(soup: BeautifulSoup) -> set: """Gather all HTML IDs from a given page.""" return set(tag['id'] for tag in soup.find_all(id=True))
88acc128faeee08deeea2df8b101fee909c82219
130,242
def vast_count(c): """Run `vast count` and parse the result""" res = c.run('./vast-cloud run-lambda -c "vast count"', hide="stdout") return int(res.stdout.strip())
182c4be1b0f9b8b6b0b42d6545cb4ff4341ca31a
211,901
import re def get_ascent_type(bs_obj): """ gets the ascent style: Boulder, Mixed, Trad it will be useful for future difficulties classification and their representation :param bs_obj: BeautifulSoup object :return: str """ rez = bs_obj.find("span", {"class": re.compile("tags .+")}) if rez: return rez.text return "Unknown"
8bc1503eacde87ba51f75c85634b8291bb2a34fd
508,020
from typing import Tuple def n_syllables(n_syllables_per_word: Tuple[int, ...]) -> int: """ Compute the total number of syllables in a document. Args: n_syllables_per_word: Number of syllables per word in a given document, as computed by :func:`n_syllables_per_word()`. """ return sum(n_syllables_per_word)
1b16158200b39848a7ab2f128391a1b06f746b36
552,562
def _list_subclasses(cls): """ Recursively lists all subclasses of `cls`. """ subclasses = cls.__subclasses__() for subclass in cls.__subclasses__(): subclasses += _list_subclasses(subclass) return subclasses
4cebf48916c64f32fcd5dfff28ecde7a155edb90
649
def mod_5(x): """Return the remainder of x after dividing by 5""" return x % 5
d4aedd1349379ceca5b5af7f1b54bf55b8389aaf
53,288
def floats(float_list): """coerce a list of strings that represent floats into a list of floats""" return [float(number) for number in float_list]
7600eb6ff1fcb1771e237dfbbe3f61b4fe68f026
303,272
def NAMED(n, e): """ Puts the expression in a named-group :param: - `n`: the name of the group - `e`: regular expression :return: named-group """ return "(?P<{n}>{e})".format(n=n, e=e)
6a3b5958e1a2f29007ea37e7382a0333a3b41033
365,393
def map2(f, ls): """map to a depth of 2. That is, given a list of lists, apply f to those innermost elements """ return map(lambda l: map(f, l), ls)
e527f15e1e03524b358de099009b3362a7c8be3f
241,848
def youngs(vp=None, vs=None, rho=None, mu=None, lam=None, bulk=None, pr=None, pmod=None): """ Computes Young's modulus given either Vp, Vs, and rho, or any two elastic moduli (e.g. lambda and mu, or bulk and P moduli). SI units only. Args: vp, vs, and rho or any 2 from lam, mu, bulk, pr, and pmod Returns: Young's modulus in pascals, Pa """ if (vp is not None) and (vs is not None) and (rho is not None): return rho * vs**2 * (3.*vp**2 - 4.*vs**2) / (vp**2 - vs**2) elif (mu is not None) and (lam is not None): return mu * (3.*lam + 2*mu) / (lam + mu) elif (bulk is not None) and (lam is not None): return 9.*bulk * (bulk - lam) / (3.*bulk - lam) elif (bulk is not None) and (mu is not None): return 9.*bulk*mu / (3.*bulk + mu) elif (lam is not None) and (pr is not None): return lam * (1+pr) * (1 - 2*pr) / pr elif (pr is not None) and (mu is not None): return 2. * mu * (1+pr) elif (pr is not None) and (bulk is not None): return 3. * bulk * (1 - 2*pr) else: return None
127d0598a4e8d53c2e31b10c53ab1fddfedc4987
674,202
def quote(string: str) -> str: """ Wrap a string with quotes iff it contains a space. Used for interacting with command line scripts. :param string: :return: """ if ' ' in string: return '"' + string + '"' return string
460b394ddc3223bf3ff7b6fc9b7893802fd7e1b9
658,817
def climbStairs(n, dic = {0:0,1:1,2:2}): """ LeetCode-Problem: You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Solution: Exploring all possible ways to climb the stairs in 1 or 2 steps. And using the dictionary to keep record of the paths we already explored. """ if n in dic.keys(): return dic[n] else: dic[n] = climbStairs(n-1,dic) + climbStairs(n-2,dic) return dic[n]
cb006101f093b4aaf7f0ecf71b03ed74ec149e12
608,367
def find_indices(header): """Return the positions of relevant fields in our rows.""" return { 'subject': header.index("Course Subject Short Nm"), 'course_num': header.index("Course Number"), 'section_num': header.index("Section Nbr"), 'title': header.index("Course Title Nm"), 'instructor': header.index("Instructor Name"), 'ccn': header.index("Course Control Nbr"), 'grade_name': header.index("Grade Nm"), 'count': header.index("Enrollment Cnt"), 'letter': header.index("Grade Type Desc"), 'points': header.index("Average Grade"), }
a99cd596fa4b05c8f704a6b87bd795f0de02212f
506,462
def columns_to_lowercase(df): """Convert all columns with string names in a dataframe to lowercase. Arguments: df {pd.DataFrame} -- pandas dataframe Returns: pd.DataFrame -- input dataframe with columns converted to lowercase """ cols_to_rename = df.columns[[type(col) is str for col in df.columns]] cols_replace_dict = {name: name.lower() for name in cols_to_rename} return df.rename(columns=cols_replace_dict)
3e675dc4f689b26766320fa706c2f9714bc80a90
458,064
import tarfile def _only_csv_file(member: tarfile.TarInfo) -> bool: """Selector for CSV files only in a TAR file. Parameters ---------- member (tarfile.TarInfo) Tar archive member file Returns ------- bool Check if the file is a CSV """ return member.name.endswith('.csv')
e36189368a92c28bfc6dfd7ba9fa56002d59471d
141,833
def _str_dotted_getattr(obj, name): """Expands extends getattr to allow dots in x to indicate nested objects. Args: obj (object): an object. name (str): a name for a field in the object. Returns: Any: the value of named attribute. Raises: AttributeError: if the named attribute does not exist. """ for part in name.split('.'): obj = getattr(obj, part) return str(obj) if obj else None
0732137fe42432ae36245c4128a0f24317db9bf8
243,721
def subplt_c1_c2(turbine, axarr, c1, c2, c='Blues', xlim=None, ylim=None, xlabel=None, ylabel=None): """ hexbin plot of turbine[c1] vs turbine [c2] Args: turbine(:obj:`pandas dataframe`): data to be plotted axarr(:obj:`axis handle`): axis handle c1(:obj:`string`): column name of x axis c2(:obj:`string`): column name of y axis c(:obj:`string` or colormap handle): colormap Returns: hb(:obj:`plot handle`): """ hb = axarr.hexbin(turbine[c1], turbine[c2], cmap=c, gridsize=128, vmin=0, vmax=8) if xlim: axarr.set_xlim(xlim) if ylim: axarr.set_ylim(ylim) if xlabel: axarr.set_xlabel(xlabel) if ylabel: axarr.set_ylabel(ylabel) return hb
80dacf9334aba1e716ebac5d03c26170063afc06
139,370
from bs4 import BeautifulSoup def prettify_html(html: str) -> str: """ Create beautiful HTML using BeautifulSoup :param html: The input raw HTML :return: The beautiful HTML """ soup = BeautifulSoup(html) return soup.prettify()
f18372007fb4d8468da6ff81f0a31a900e3b6612
606,484
def string2mol2(filename, string): """ Writes molecule to filename.mol2 file, input is a string of Mol2 blocks """ block = string if filename[-4:] != '.mol2': filename += '.mol2' with open(filename, 'w') as file: file.write(block) return None
51043e7f4edde36682713455dc33c643f89db397
5,199
def are_users_same(users): """True if all users are the same and not Nones""" x = set(u.get('seq') for u in users) return len(x) == 1 and None not in x
0e58dbcaaa9fc9b9449efbf4454ceebb4de607a2
667,293
def convert_to_date(col): """Convert datetime to date.""" return col.date()
c6ac8febf4751e8f2c2c27fc740de286f2870cbe
704,820
def make_line_points(y1, y2, line): """ Convert a line represented in slope and intercept into pixel points """ if line is None: return None slope, intercept = line # make sure everything is integer as cv2.line requires it x1 = int((y1 - intercept)/slope) x2 = int((y2 - intercept)/slope) y1 = int(y1) y2 = int(y2) return ((x1, y1), (x2, y2))
4601d60bc3c3e395c66a4ac87dd4c544555185f6
471,760
def _is_direct(dep, tags): """ Given tags containing info about direct dependencies in format @direct//, returns true if given label is a direct dependency and false otherwise Args: dep: Package name to check for tags: Tags passed to the rule """ if (len(tags) == 0): return True for tag in tags: if tag.startswith("@direct//"): if dep == (tag[9:]): return True for tag in tags: if tag.startswith("@direct//"): return False return True
f185b45e6403cd2c8b1e32dd161a955b0f4f394b
361,388
def ij_to_list_index(i, j, n): """ Assuming you have a symetric nxn matrix M and take the entries of the upper triangular including the diagonal and then ravel it to transform it into a list. This function will transform a matrix location given row i and column j into the proper list index. :param i: row index of the matrix M :param j: column index of matrix M :param n: total number of rows / colums of n :return: The correct index of the lost """ assert j >= i, "We only consider the upper triangular part..." index = 0 for k in range(i): index += n - k - 1 return index + j
d2d1d9533abe2a8c07a2fd32d9721360c012289c
81,466
from typing import Sized from typing import Iterable from typing import Mapping import six def is_listy(x): """Return True if `x` is "listy", i.e. a list-like object. "Listy" is defined as a sized iterable which is neither a map nor a string: >>> is_listy(["a", "b"]) True >>> is_listy(set()) True >>> is_listy(iter(["a", "b"])) False >>> is_listy({"a": "b"}) False >>> is_listy("a regular string") False Note: Iterables and generators fail the "listy" test because they are not sized. Args: x (any value): The object to test. Returns: bool: True if `x` is "listy", False otherwise. """ return (isinstance(x, Sized) and isinstance(x, Iterable) and not isinstance(x, Mapping) and not isinstance(x, six.string_types))
ca8f1d6b025990e9083f94ecf0f9e4ec9b168876
691,433
import torch def normalize(x): """ Normalizes a batch of images with size (batch_size, 3, height, width) by mean and std dev expected by PyTorch models """ mean = torch.Tensor([0.485, 0.456, 0.406]) std = torch.Tensor([0.229, 0.224, 0.225]) return (x - mean.type_as(x)[None,:,None,None]) / std.type_as(x)[None,:,None,None]
74be29a93c547c2eaad302ff9a1454ac8641f502
336,334
def get_children(res,key): """ Returns a list with all keys in res starting with key Parameters ---------- res : dict results dictionary key : string a search key Returns ------- keys : list list of keys that start with key Examples -------- >>> get_keys_with({'time':[0,43200,86400],'A.B':[1000,5000,2000],'A.C':[2000,8000,3000]},'A') """ if key == '': return res.keys() else: keys = [] for k in res.keys(): if k.startswith(key): keys.append(k) return keys
437f74be254f228395fa9d8f1979ccec5e088436
364,826
def returnInput(*args): """ This is a function that returns exactly what is passed to it. Useful to hold a place in the dataflow without modifying the data. """ if len(args) == 1: # A single argument has been passed and is now packaged inside a tuple because of *. # Unpack it: args = args[0] return args
baa4e437bcec3de3ed354ba39c7e1d48806b8f29
468,415
import torch def topk_pool_with_region(x, region, k=32): """ Args: x: (B, F, M, P) region: (B, M, P) k: top k Returns: (B, F, M, topk) """ featdim = x.shape[1] _, region_idx = torch.topk(region, k=k, dim=2) # (B, M, k) index = region_idx.unsqueeze(1).repeat(1, featdim, 1, 1) # (B, F, M, k) pooled = torch.gather(x, dim=3, index=index) return pooled
b3d426855fb982242769ca49abe26a859be45236
315,488
def _encode_for_display(text): """ Encodes strings so they can display as ASCII in a Windows terminal window. This function also encodes strings for processing by xml.etree.ElementTree functions. Returns an ASCII-encoded version of the text. Unicode characters are converted to ASCII placeholders (for example, "?"). """ return text.encode('ascii', errors="backslashreplace").decode('utf-8')
59fa895204b764a105f0cc73f87f252c64e62871
694,624
def get_terminal_title(editor): """ Return the terminal title, e.g.: "filename.py (/directory) - Pyvim" """ eb = editor.current_editor_buffer if eb is not None: return '%s - Pyvim' % (eb.location or '[New file]', ) else: return 'Pyvim'
576544bf269a9daea7b7caee67a218940b51cfed
592,934
def rasterplot(channels, axes, title, unit, channel_labels=True, spike_count=True): """ Produce a raster plot of a spike train on a set of axes. Parameters ---------- channels : dict A dictionary of spike trains. Keys are channel labels, values are lists of spikes. axes : matplotlib.axes.Axes Set of axes to plot on. title : str Figure title. unit : str Units of time to include on x-axis. channel_labels : bool Whether or not to include y-axis labels. spike_count : bool Whether or not to include the number of spikes in the x-axis label. Returns ------- Dictionary mapping channels to offsets on y axis or None. """ if not channels: axes.set_xlim((0, 2)) axes.set_ylim((0, 2)) axes.set_axis_off() axes.set_title(title) axes.text(1, 1, "no spikes", ha="center") return labels = sorted(list(channels.keys())) events, nspikes = [], 0 for label in labels: events.append(channels[label].base) nspikes += len(channels[label]) y_offsets = list(range(len(labels))) axes.eventplot(events, linelengths=0.75, lineoffsets=y_offsets, color="black", lw=0.2) if channel_labels: axes.set_yticks(y_offsets) axes.set_yticklabels(labels) if spike_count: xlabel = "time / " + unit + "\n" + "#spikes = " + str(nspikes) else: xlabel = "time / " + unit axes.set_xlabel(xlabel) axes.set_ylabel("channel") else: axes.set_axis_off() axes.set_title(title) y_offsets_map = dict(zip(labels, y_offsets)) return y_offsets_map
8defd7827136058a2da04d391123ea062e6d4440
366,324
def symm_area(col, n): """ returns n + (n - 1) + ... + (n - col + 1) i.e., the number of matrix elements below and including the diagonal and from column 0 to column `col` """ return col * (2 * n - col + 1) // 2
e5c7970ee2b612f4678952056be0358c968e06b3
703,200
def uppercase_first_letter(string_: str) -> str: """Return string with first character upper case.""" return string_[0].upper() + string_[1:]
89ac25a2981039abf15b2f035aa8296f91acbaf4
93,970
def rebin(d, n_x, n_y=None): """ Rebin data by averaging bins together Args: d (np.array): data n_x (int): number of bins in x dir to rebin into one n_y (int): number of bins in y dir to rebin into one Returns: d: rebinned data with shape (n_x, n_y) """ if d.ndim == 2: if n_y is None: n_y = 1 if n_x is None: n_x = 1 d = d[:int(d.shape[0] // n_x) * n_x, :int(d.shape[1] // n_y) * n_y] d = d.reshape((d.shape[0] // n_x, n_x, d.shape[1] // n_y, n_y)) d = d.mean(axis=3) d = d.mean(axis=1) elif d.ndim == 1: d = d[:int(d.shape[0] // n_x) * n_x] d = d.reshape((d.shape[0] // n_x, n_x)) d = d.mean(axis=1) else: raise RuntimeError("Only NDIM <= 2 supported") return d
19c5273df3dad7795c92fd72fcfbeb8c37f66968
445,002
def get_release_tag_string(check_name, version_string): """ Compose a string to use for release tags """ return '{}-{}'.format(check_name, version_string)
470a330785a6c6c3b2337f11bb5eaee7e4747644
329,013
def rho_NFW(r, rs, rhos): """ The density profile [GeV/cm**3] of an NFW halo. Parameters ---------- r : the distance from the center [kpc] rs : the NFW r_s parameter [kpc] rhos : the NFW rho_s parameter [GeV/cm**3] """ res = rhos/(r/rs)/(1.+r/rs)**2 return res
3b8f97713610c1622815e15f13a75d39ad7e64ba
7,827