content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def create_list(value, sublist_nb, sublist_size): """ Create a list of len sublist_size, filled with sublist_nb sublists. Each sublist is filled with the value value """ out = [] tmp = [] for i in range(sublist_nb): for j in range(sublist_size): tmp.append(value) out....
1ecf6c88390167584d1835430c359a7ed6d6b40b
5,264
def getGpsTime(dt): """_getGpsTime returns gps time (seconds since midnight Sat/Sun) for a datetime """ total = 0 days = (dt.weekday()+ 1) % 7 # this makes Sunday = 0, Monday = 1, etc. total += days*3600*24 total += dt.hour * 3600 total += dt.minute * 60 total += dt.second return(tot...
16caa558741d8d65b4b058cf48a591ca09f82234
5,266
def _round_to_4(v): """Rounds up for aligning to the 4-byte word boundary.""" return (v + 3) & ~3
c79736b4fe9e6e447b59d9ab033181317e0b80de
5,267
def lower_threshold_projection(projection, thresh=1e3): """ An ugly but effective work around to get a higher-resolution curvature of the great-circle paths. This is useful when plotting the great-circle paths in a relatively small region. Parameters ---------- projection : class ...
165c657f1ec875f23df21ef412135e27e9e443c6
5,269
def has_param(param): """ Generate function, which will check `param` is in html element. This function can be used as parameter for .find() method in HTMLElement. """ def has_param_closure(element): """ Look for `param` in `element`. """ if element.params.get(param,...
6800725c378714b5161772f0a2f9ef89ae278400
5,273
def get_all_keys(data): """Get all keys from json data file""" all_keys = set(data[0].keys()) for row in data: all_keys = set.union(all_keys, set(row.keys())) return list(all_keys)
5532af993f87bf4e00c7bec13eb971e0114e736c
5,274
def _ngl_write_atom( num, species, x, y, z, group=None, num2=None, occupancy=1.0, temperature_factor=0.0, ): """ Writes a PDB-formatted line to represent an atom. Args: num (int): Atomic index. species (str): Elemental species. x, y, z (float): Ca...
92a5d62f3c4f6d927aa5a6010b217344d0d241d3
5,275
def get_insert_components(options): """ Takes a list of 2-tuple in the form (option, value) and returns a triplet (colnames, placeholders, values) that permits making a database query as follows: c.execute('INSERT INTO Table ({colnames}) VALUES {placeholders}', values). """ col_names = ','.join(opt[0] for opt in o...
3e1deecd39b0e519124278f47713d5b3a1571815
5,276
import torch def add_dims_right(tensor, ndims, right_indent=0): """ Add empty dimensions to the right of tensor shape """ assert right_indent >= 0 for i in range(ndims): tensor = torch.unsqueeze(tensor, -1-right_indent) return tensor
7d4c1b47eb659f0bcfc9dbcf7f7b04c1ccbafb80
5,279
def get_submodel_name(history = 60, lag = 365, num_neighbors = 20, margin_in_days = None, metric = "cos"): """Returns submodel name for a given setting of model parameters """ submodel_name = '{}-autoknn-hist{}-nbrs{}-margin{}-lag{}'.format(metric, ...
69fa276a86c39f342ffceba72408ab6970dd0a41
5,280
import csv def create_column_dicts(path_to_input): """Creates dictionaries: {column_index, column_name} and {column_name, column_index}""" cols = {} with open(path_to_input, newline="") as csvfile: inputreader = csv.reader(csvfile, delimiter=",") row = next(inputreader) for i, ...
13bf2e3c99fea9b1d2580b7bfc34e445af8b7e98
5,285
import string def get_sentiment(text, word_map): """ Identifies the overall sentiment of the text by taking the average of each word. Note: Words not found in the word_map dict are give zero value. """ # remove all punctuation text = text.translate(str.maketrans("", "", string.punctuatio...
ee9e57c999539c0126e5c0d38711a617e82dab10
5,286
def read_warfle_text(path: str) -> str: """Returns text from *.warfle files""" try: with open(path, "r") as text: return text.read() except Exception as e: raise Exception(e)
ba15fe6a62fbefe492054b0899dcdbff35462154
5,294
def units_to_msec(units, resolution): """Convert BLE specific units to milliseconds.""" time_ms = units * float(resolution) / 1000 return time_ms
49588d7961593b2ba2e57e1481d6e1430b4a3671
5,300
def is_data(data): """ Check if a packet is a data packet. """ return len(data) > 26 and ord(data[25]) == 0x08 and ord(data[26]) in [0x42, 0x62]
edb2a6b69fde42aef75923a2afbd5736d1aca660
5,302
def get_tf_metric(text): """ Computes the tf metric Params: text (tuple): tuple of words Returns: tf_text: format: ((word1, word2, ...), (tf1, tf2, ...)) """ counts = [text.count(word) for word in text] max_count = max(counts) tf = [counts[i]/max_count for i in range(0, len(counts))] return text, tf
6397e150fa55a056358f4b28cdf8a74abdc7fdb6
5,303
import struct def incdata(data, s): """ add 's' to each byte. This is useful for finding the correct shift from an incorrectly shifted chunk. """ return b"".join(struct.pack("<B", (_ + s) & 0xFF) for _ in data)
89633d232d655183bee7a20bd0e1c5a4a2cc7c05
5,308
import math def tangent_circle(dist, radius): """ return tangent angle to a circle placed at (dist, 0.0) with radius=radius For non-existing tangent use 100 degrees. """ if dist >= radius: return math.asin(radius/float(dist)) return math.radians(100)
bcde88456a267239566f22bb6ea5cf00f64fa08e
5,310
import re def server_version(headers): """Extract the firmware version from HTTP headers.""" version_re = re.compile(r"ServerTech-AWS/v(?P<version>\d+\.\d+\w+)") if headers.get("Server"): match = version_re.match(headers["Server"]) if match: return match.group("version")
24151f3898430f5395e69b4dd7c42bd678626381
5,314
def parse_locator(src): """ (src:str) -> [pathfile:str, label:either(str, None)] """ pathfile_label = src.split('#') if len(pathfile_label)==1: pathfile_label.append(None) if len(pathfile_label)!=2: raise ValueError('Malformed src: %s' % (src)) return pathfile_label
970bc1e2e60eec4a54cd00fc5984d22ebc2b8c7a
5,317
from typing import List from typing import Optional def check(s: str) -> None: """ Checks if the given input string of brackets are balanced or not Args: s (str): The input string """ stack: List[str] = [] def get_opening(char: str) -> Optional[str]: """ Gets the...
720018e5b39e070f48e18c502e8a842feef32840
5,319
def format_address(msisdn): """ Format a normalized MSISDN as a URI that ParlayX will accept. """ if not msisdn.startswith('+'): raise ValueError('Only international format addresses are supported') return 'tel:' + msisdn[1:]
f5a5cc9f8bcf77f1185003cfd523d7d6f1212bd8
5,320
import math def ellipse_properties(x, y, w): """ Given a the (x,y) locations of the foci of the ellipse and the width return the center of the ellipse, width, height, and angle relative to the x-axis. :param double x: x-coordinates of the foci :param double y: y-coordinates of the foci :param...
95864eac0feb9c34546eefed5ca158f330f88e3d
5,324
def _get_precision_type(network_el): """Given a network element from a VRP-REP instance, returns its precision type: floor, ceil, or decimals. If no such precision type is present, returns None. """ if 'decimals' in network_el: return 'decimals' if 'floor' in network_el: return 'flo...
b3b451a26ec50ce5f2424ea7a3652123ae96321d
5,327
def collections(id=None): """ Return Collections Parameters ---------- id : STR, optional The default is None, which returns all know collections. You can provide a ICOS URI or DOI to filter for a specifict collection Returns ------- query : STR A query, which can...
0cd1704d2ac43f34d6e83a3f9e9ead39db390c2e
5,331
def bib_to_string(bibliography): """ dict of dict -> str Take a biblatex bibliography represented as a dictionary and return a string representing it as a biblatex file. """ string = '' for entry in bibliography: string += '\n@{}{{{},\n'.format( bibliography[entry]['type'], ...
c8fc4247210f74309929fdf9b210cd6f1e2ece3f
5,335
def get_tile_prefix(rasterFileName): """ Returns 'rump' of raster file name, to be used as prefix for tile files. rasterFileName is <date>_<time>_<sat. ID>_<product type>_<asset type>.tif(f) where asset type can be any of ["AnalyticMS","AnalyticMS_SR","Visual","newVisual"] The rump is defined as <da...
15b517e5ba83b2cfb5f3b0014d800402c9683815
5,339
import re def MatchNameComponent(key, name_list, case_sensitive=True): """Try to match a name against a list. This function will try to match a name like test1 against a list like C{['test1.example.com', 'test2.example.com', ...]}. Against this list, I{'test1'} as well as I{'test1.example'} will match, but ...
ad522feba9cabb3407e3b8e1e8c221f3e9800e16
5,342
def _non_overlapping_chunks(seq, size): """ This function takes an input sequence and produces chunks of chosen size that strictly do not overlap. This is a much faster implemetnation than _overlapping_chunks and should be preferred if running on very large seq. Parameters ---------- seq : ...
15b5d2b4a7d8df9785ccc02b5369a3f162704e9e
5,344
def neighbour(x,y,image): """Return 8-neighbours of image point P1(x,y), in a clockwise order""" img = image.copy() x_1, y_1, x1, y1 = x-1, y-1, x+1, y+1; return [img[x_1][y], img[x_1][y1], img[x][y1], img[x1][y1], img[x1][y], img[x1][y_1], img[x][y_1], img[x_1][y_1]]
8e645f7634d089a0e65335f6ea3363d4ed66235b
5,348
def gravity_effect(position, other_position): """Return effect other_position has on position.""" if position == other_position: return 0 elif position > other_position: return -1 return 1
25130c253cb888057e9b52817cac9cf3778a4c69
5,350
import fnmatch def ignore_paths(path_list, ignore_patterns, process=str): """ Go through the `path_list` and ignore any paths that match the patterns in `ignore_patterns` :param path_list: List of file/directory paths. :param ignore_patterns: List of nukeignore patterns. :param process: Function t...
63196e54eb4505cbe12ebf77d2a42fede68c1d0b
5,351
def reachable(Adj, s, t): """ Adj is adjacency list rep of graph Return True if edges in Adj have directed path from s to t. Note that this routine is one of the most-used and most time-consuming of this whole procedure, which is why it is passed an adjacency list rep rather than a list of ver...
dc0ea0c6d2314fa1c40c3f3aa257a1c77892141f
5,353
def concatenate_unique(la, lb): """Add all the elements of `lb` to `la` if they are not there already. The elements added to `la` maintain ordering with respect to `lb`. Args: la: List of Python objects. lb: List of Python objects. Returns: `la`: The list `la` with missing elements from `lb`. ""...
307fde291233727c59e2211afc3e0eed7c8ea092
5,354
def create_feature_indices(header): """ Function to return unique features along with respective column indices for each feature in the final numpy array Args: header (list[str]): description of each feature's possible values Returns: feature_indices (dict): unique feature names as...
a29d8c4c8f3a31ad516216756b7eba7eb4110946
5,364
def lower(word): """Sets all characters in a word to their lowercase value""" return word.lower()
f96b1470b3ab1e31cd1875ad9cbf9ed017aa0158
5,365
def _in_dir(obj, attr): """Simpler hasattr() function without side effects.""" return attr in dir(obj)
f95e265d278e3014e8e683a872cd3b70ef6133c9
5,366
def get_element_parts( original_list: list, splitter_character: str, split_index: int ) -> list: """ Split all elements of the passed list on the passed splitter_character. Return the element at the passed index. Parameters ---------- original_list : list List of strings to be spli...
8c663fd64ebb1b2c53a64a17f7d63e842b457652
5,380
from typing import Tuple from typing import Dict def parse_line_protocol_stat_key(key: str) -> Tuple[str, Dict[str, str]]: """Parseline protocolish key to stat prefix and key. Examples: SNMP_WORKER;hostname=abc.com,worker=snmp-mti will become: ("SNMP_WORKER", {"hostname": "abc.com", "...
a6806f7dd67fb2a4734caca94bff3d974923f4b2
5,382
def zero_at(pos, size=8): """ Create a size-bit int which only has one '0' bit at specific position. :param int pos: Position of '0' bit. :param int size: Length of value by bit. :rtype: int """ assert 0 <= pos < size return 2**size - 2**(size - pos - 1) - 1
7ebdcc1ac9db4ad934108f67a751b336b4f18011
5,391
def unpack_uid(uid): """ Convert packed PFile UID to standard DICOM UID. Parameters ---------- uid : str packed PFile UID as a string Returns ------- uid : str unpacked PFile UID as string """ return ''.join([str(i-1) if i < 11 else '.' for pair in [(ord(c) >> 4...
cb131f3df386c40382cf70ddee5125f901de5fa8
5,398
from typing import Counter def generate_samples(n_samples, func, *args, **kwargs): """Call a function a bunch of times and count the results. Args: n_samples: Number of time to call the function. func: The function results are counted from. *args **args: The arguments to pass ...
625c2bf6713420e26704d2c2842504343be09434
5,400
def capitalize_1(string): """ Capitalizes a string using a combination of the upper and lower methods. :author: jrg94 :param string: any string :return: a string with the first character capitalized and the rest lowercased """ return string[0].upper() + string[1:].lower()
9ad830a6d38e19b195cd3dff9a38fe89c49bd5c8
5,401
def get_url_and_token(string): """ extract url and token from API format """ try: [token, api] = string.split(":", 1) [_, _, addr, _, port, proto] = api.split("/", 5) url = f"{proto}://{addr}:{port}/rpc/v0" except Exception: raise ValueError(f"malformed API string : {string}"...
f3abd327c9de2d098100e539f701bf2fff1742f5
5,403
import json def handle_error(ex, hed_info=None, title=None, return_as_str=True): """Handles an error by returning a dictionary or simple string Parameters ---------- ex: Exception The exception raised. hed_info: dict A dictionary of information. title: str A title to b...
4b7bc24c9b4fd83d39f4447e29e383d1769e6b0f
5,405
def command(cmd, label, env={}): """Create a Benchpress command, which define a single benchmark execution This is a help function to create a Benchpress command, which is a Python `dict` of the parameters given. Parameters ---------- cmd : str The bash string that makes up the command ...
487e7b8518ae202756177fc103561ea03ded7470
5,409
import struct def decode_ia(ia: int) -> str: """ Decode an individual address into human readable string representation >>> decode_ia(4606) '1.1.254' See also: http://www.openremote.org/display/knowledge/KNX+Individual+Address """ if not isinstance(ia, int): ia = struct.unpack('>H', ...
6f107f47110a59ca16fe8cf1a7ef8f061bf117c7
5,411
from pathlib import Path def _validate_magics_flake8_warnings(actual: str, test_nb_path: Path) -> bool: """Validate the results of notebooks with warnings.""" expected = ( f"{str(test_nb_path)}:cell_1:1:1: F401 'random.randint' imported but unused\n" f"{str(test_nb_path)}:cell_1:2:1: F401 'IPy...
4baa419ad4e95bf8cc794298e70211c0fa148e5b
5,412
def _split_uri(uri): """ Get slash-delimited parts of a ConceptNet URI. Args: uri (str) Returns: List[str] """ uri = uri.lstrip("/") if not uri: return [] return uri.split("/")
91b48fff83041fe225a851a9e3016e3722bd9771
5,413
import re def split_range_str(range_str): """ Split the range string to bytes, start and end. :param range_str: Range request string :return: tuple of (bytes, start, end) or None """ re_matcher = re.fullmatch(r'([a-z]+)=(\d+)?-(\d+)?', range_str) if not re_matcher or len(re_matcher.groups(...
a6817017d708abf774277bf8d9360b63af78860d
5,428
def min_equals_max(min, max): """ Return True if minimium value equals maximum value Return False if not, or if maximum or minimum value is not defined """ return min is not None and max is not None and min == max
1078e9ed6905ab8b31b7725cc678b2021fc3bc62
5,433
import socket def validate_args(args): """ Checks if the arguments are valid or not. """ # Is the number of sockets positive ? if not args.number > 0: print("[ERROR] Number of sockets should be positive. Received %d" % args.number) exit(1) # Is a valid IP address or valid name ? tr...
37a77f59ae78e3692e08742fab07f35cf6801e54
5,439
def fibonacci(n: int) -> int: """ Calculate the nth Fibonacci number using naive recursive implementation. :param n: the index into the sequence :return: The nth Fibonacci number is returned. """ if n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2)
08de1ff55f7cada6a940b4fb0ffe6ba44972b42d
5,443
def AverageZComparison(x, y): """ Take the average of second and third element in an array and compare which is bigger. To be used in conjunction with the sort function. """ xsum = x[1]+x[2] ysum = y[1]+y[2] if xsum < ysum: return -1 if xsum > ysum: return 1 return 0
84c9e7b92df4b3e4914c769293f71790def5e4dd
5,450
from pathlib import Path def parse_taxid_names(file_path): """ Parse the names.dmp file and output a dictionary mapping names to taxids (multiple different keys) and taxids to scientific names. Parameters ---------- file_path : str The path to the names.dmp file. Returns ----...
1d136f73a56ac8d3c02fd53c6e7928a39440e27a
5,451
from typing import List def count_pairs(array: List[int], difference: int) -> int: """ Given an array of integers, count the number of unique pairs of integers that have a given difference. These pairs are stored in a set in order to remove duplicates. Time complexity: O(n^2). :param array: is th...
e027e8885f4c4531da9b7dab7de8e84a7004c913
5,457
def binary_tail(n: int) -> int: """ The last 1 digit and the following 0s of a binary representation, as a number """ return ((n ^ (n - 1)) + 1) >> 1
63460cef7b39b7e7ee2ec880810ff71d82be01e9
5,459
from datetime import datetime def time_left(expire_date): """Return remaining days before feature expiration or 0 if expired.""" today_dt = datetime.today() expire_dt = datetime.strptime(expire_date, "%d-%b-%Y") # Calculate remaining days before expiration days_left_td = expire_dt - today_dt ...
652acd27b0d4fa9b21321df4ff8ce6ce15b97ed6
5,460
def video_id(video_id_or_url): """ Returns video id from given video id or url Parameters: ----------- video_id_or_url: str - either a video id or url Returns: -------- the video id """ if 'watch?v=' in video_id_or_url: return video_id_or_url.split('watch?v=')[1] e...
9f680ac621e1f5c6314a6a3e97093d786fa7ea33
5,461
import importlib def _bot_exists(botname): """ Utility method to import a bot. """ module = None try: module = importlib.import_module('%s.%s' % (botname, botname)) except ImportError as e: quit('Unable to import bot "%s.%s": %s' % (botname, botname, str(e))) return module
c091be6d586faa8aacd48b30f4ce2f4fcc665e0b
5,467
def _format_exponent_notation(input_number, precision, num_exponent_digits): """ Format the exponent notation. Python's exponent notation doesn't allow for a user-defined number of exponent digits. Based on [Anurag Uniyal's answer][answer] to the StackOverflow question ['Python - number of digits i...
59f61897c70ca1d9f95412b2892d5c9592e51561
5,468
def npv(ico, nci, r, n): """ This capital budgeting function computes the net present value on a cash flow generating investment. ico = Initial Capital Outlay nci = net cash inflows per period r = discounted rate n = number of periods Example: npv(100000, 15000, .03, 10) """ pv_nc...
fa3128de0fe8a2f7b8bbe754f0e1b1e1a0eb222d
5,470
def maybe_flip_x_across_antimeridian(x: float) -> float: """Flips a longitude across the antimeridian if needed.""" if x > 90: return (-180 * 2) + x else: return x
50fac7a92d0ebfcd003fb478183b05668b9c909c
5,479
import collections def _group_by(input_list, key_fn): """Group a list according to a key function (with a hashable range).""" result = collections.defaultdict(list) for x in input_list: result[key_fn(x)].append(x) return result
288c108588f9e4ea60c4dac6ff656c8c8ffde580
5,484
def multiply_values(dictionary: dict, num: int) -> dict: """Multiplies each value in `dictionary` by `num` Args: dictionary (dict): subject dictionary num (int): multiplier Returns: dict: mapping of keys to values multiplied by multiplier """ return ( {key: value * ...
16eb87d60da64d648113858ba5cb4308137e0a14
5,488
from typing import Any def desg_to_prefix(desg: str) -> Any: """Convert small body designation to file prefix.""" return (desg.replace('/', '').replace(' ', '') .replace('(', '_').replace(')', '_'))
badde1e3ec9c3f669c7cce8aa55646b15cc5f4c8
5,489
def field2nullable(field, **kwargs): """Return the dictionary of swagger field attributes for a nullable field. :param Field field: A marshmallow field. :rtype: dict """ attributes = {} if field.allow_none: omv = kwargs['openapi_major_version'] attributes['x-nullable' if omv < 3...
dd5d4cd63aeede4ef9356baa9fe9a48bd5f87841
5,490
def get_chrom_start_end_from_string(s): """Get chrom name, int(start), int(end) from a string '{chrom}__substr__{start}_{end}' ...doctest: >>> get_chrom_start_end_from_string('chr01__substr__11838_13838') ('chr01', 11838, 13838) """ try: chrom, s_e = s.split('__substr__') start, ...
5dbce8eb33188c7f06665cf92de455e1c705f38b
5,498
def is_multioutput(y): """Whether the target y is multi-output (or multi-index)""" return hasattr(y, "shape") and y.ndim == 2 and y.shape[1] > 1
bcdaa46c304fec50c173dffca5f1f1d5d8871a58
5,515
from typing import Optional def prepare_error_message(message: str, error_context: Optional[str] = None) -> str: """ If `error_context` is not None prepend that to error message. """ if error_context is not None: return error_context + ": " + message else: return message
ea95d40797fcc431412990706d5c098a07986156
5,521
from datetime import datetime def calcular_diferencia_dias(fin_dia): """ Obtiene la diferencia de dias entre una fecha y hoy """ hoy = datetime.now() end = datetime.strptime(str(fin_dia), '%Y-%m-%d') return abs(end - hoy).days
41b732f3bb09d2deca4be034273a5fed74971386
5,526
def pairwise_list(a_list): """ list转换为成对list "s -> (s0,s1), (s1,s2), (s2, s3), ..." :param a_list: list :return: 成对list """ if len(a_list) % 2 != 0: raise Exception("pairwise_list error!") r_list = [] for i in range(0, len(a_list) - 1, 2): r_list.append([a_list[i], a...
5142fb2e00c931ab57fc9028eb9b6df5a98c0342
5,530
from datetime import datetime def read_hotfilm_from_lvm(filename, dt=1e-3): """Reads 2-channel hotfilm data from a Labview text file.""" times = [] ch1 = [] ch2 = [] data = [line.rstrip() for line in open(filename).readlines()] line = data[0].split(',')[1:] t = [int(float(n)) for n in line...
e0dadac656120173e5833e6eb36498943613e8f5
5,532
def draft_github_comment(template, result): """ Use a template to draft a GitHub comment :template: (str) the name of the template file :result: (ContentError) the error to display in the comment """ # start with template with open(template, 'r') as f: contents = f.read() # replace variables in template wi...
42842b7af06da8a54c0647e5aac079132e82de5a
5,536
import csv def get_zip_rate_areas(file_path): """ reads zips.csv file and returns the content as a dictionary Args: file_path: the path to zips.csv file Returns: a dictionary mapping each zip code into a set of rate areas """ zip_rate_areas = dict() with open(file_pat...
d8405bc466e7bbe949fded4360d4f184024653d2
5,537
def get_file_encoding(filename): """ Get the file encoding for the file with the given filename """ with open(filename, 'rb') as fp: # The encoding is usually specified on the second line txt = fp.read().splitlines()[1] txt = txt.decode('utf-8') if 'encoding' in txt: ...
c91a8f71429ed5f6eccd7379c66b4ee4c2d73989
5,539
from typing import List import logging def get_all_loggers() -> List: """Return list of all registered loggers.""" logger_dict = logging.root.manager.loggerDict # type: ignore loggers = [logging.getLogger(name) for name in logger_dict] return loggers
97059a78925ff669a841644b186e39ccd366472d
5,544
import typing def intensity(pixel: typing.Tuple[int, int, int]) -> int: """Sort by the intensity of a pixel, i.e. the sum of all the RGB values.""" return pixel[0] + pixel[1] + pixel[2]
5ba060d409a2f0df148cdc50684b80f920cf314f
5,547
def get_boundary_from_response(response): """ Parses the response header and returns the boundary. :param response: response containing the header that contains the boundary :return: a binary string of the boundary """ # Read only the first value with key 'content-type' (duplicate keys are allowed)...
66a0112598b2210cca1a2210f6af963dfee641f7
5,553
import re def to_alu_hlu_map(input_str): """Converter for alu hlu map Convert following input into a alu -> hlu map: Sample input: ``` HLU Number ALU Number ---------- ---------- 0 12 1 23 ``` ALU stands for array LUN number ...
8e211b7efa3f8dd23c042f046d881daf987062bc
5,558
def _default_value(argument, default): """Returns ``default`` if ``argument`` is ``None``""" if argument is None: return default else: return argument
52eed8ddaf3c52adba69044cc462fc11279670c5
5,564
def is_constant_type(expression_type): """Returns True if expression_type is inhabited by a single value.""" return (expression_type.integer.modulus == "infinity" or expression_type.boolean.HasField("value") or expression_type.enumeration.HasField("value"))
66a3237971299df3c7370f039d87a8b5f4ae2be5
5,565
def check_strand(strand): """ Check the strand format. Return error message if the format is not as expected. """ if (strand != '-' and strand != '+'): return "Strand is not in the expected format (+ or -)"
9c2e720069ad8dcc8f867a37925f6e27e91dcb3f
5,575
def _copy_df(df): """ Copy a DataFrame """ return df.copy() if df is not None else None
263bf1cf9cbdae371ea3e4685b4638e8a5714d7f
5,576
def autosolve(equation): """ Automatically solve an easy maths problem. :type equation: string :param equation: The equation to calculate. >>> autosolve("300 + 600") 900 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[0]) except Value...
a4db1dedffdccc44d7747c4743f4f2eaf8dbd81a
5,577
def api_url(service: str = "IPublishedFileService", function: str = "QueryFiles", version: str = "v1") -> str: """ Builds a steam web API url. :param service: The steam service to attach to. :param function: The function to call. :param version: The API version. :return: ...
2538ab8c8035c491611585089ddd3a1625e423cc
5,578
def cleaned_reviews_dataframe(reviews_df): """ Remove newline "\n" from titles and descriptions, as well as the "Unnamed: 0" column generated when loading DataFrame from CSV. This is the only cleaning required prior to NLP preprocessing. INPUT: Pandas DataFrame with 'title' and 'desc' colum...
8f805f556667f5d734d4d272a2194784d37ce99c
5,581
def not_list(l): """Return the element wise negation of a list of booleans""" assert all([isinstance(it, bool) for it in l]) return [not it for it in l]
6d30f5dd587cdc69dc3db94abae92a7a8a7c610d
5,582
def line_edit_style_factory(txt_color='white', tgt_layer_color='white', bg_color='#232323'): """Generates a string of a qss style sheet for a line edit. Colors can be supplied as strings of color name or hex value. If a color arg receives a tuple we assume it is either an rgb or ...
10670afc32ec1c19d09dd72fc0e23bb1583ba3af
5,587
def CallCountsToMockFunctions(mock_function): """A decorator that passes a call count to the function it decorates. Examples: @CallCountsToMockFunctions def foo(call_count): return call_count ... ... [foo(), foo(), foo()] [0, 1, 2] """ counter = [0] def Result(*args, **kwargs)...
cc621cabdf87ff554bb02c25282e99fadcaaa833
5,589
async def ping(): """ .ping: respond with pong """ return "pong"
988165efb5087fd838a2930dbe4ed540b2d70037
5,590
def merge_sort(array): """ Merge Sort Complexity: O(NlogN) """ if len(array) > 1: mid = len(array) // 2 left = array[:mid] right = array[mid:] left = merge_sort(left) right = merge_sort(right) array = [] # This is a queue implementation. We c...
73b3ac5b950f5788cbc3e7c98d2a4d5aac427929
5,593
def ErrorCorrect(val,fEC): """ Calculates the error correction parameter \lambda_{EC}. Typical val is 1.16. Defined in Sec. IV of [1]. Parameters ---------- val : float Error correction factor. fEC : float Error correction efficiency. Returns ------- float ...
83c4483c56c7c3b79060dd070ec68f6dfd5ee749
5,595
def are_in_file(file_path, strs_to_find): """Returns true if every string in the given strs_to_find array is found in at least one line in the given file. In particular, returns true if strs_to_find is empty. Note that the strs_to_find parameter is mutated.""" infile = open(file_path) for line in i...
474234a35bf885c5f659f32a25c23580f2014cc2
5,597
def text_box_end_pos(pos, text_box, border=0): """ Calculates end pos for a text box for cv2 images. :param pos: Position of text (same as for cv2 image) :param text_box: Size of text (same as for cv2 image) :param border: Outside padding of textbox :return box_end_pos: End xy coordinates for t...
5bd2b46fe3456ccdef1407b90256edeb310d92bc
5,604
from typing import List from typing import Tuple def cnf_rep_to_text(cnf_rep: List[List[Tuple[str, bool]]]) -> str: """ Converts a CNF representation to a text. :param cnf_rep: The CNF representation to convert. :return: The text representation of the CNF. """ lines = [] for sentence in ...
dec3754493cfb0bd9fb5e68d2bab92a40bd0f294
5,605
def reshape_for_linear(images): """Reshape the images for the linear model Our linear model requires that the images be reshaped as a 1D tensor """ n_images, n_rgb, img_height, img_width = images.shape return images.reshape(n_images, n_rgb * img_height * img_width)
dffc5e7d0f96c4494443a7480be081b8fe6b4abd
5,606
from json import load import logging def read_drive_properties(path_name): """ Reads drive properties from json formatted file. Takes (str) path_name as argument. Returns (dict) with (bool) status, (str) msg, (dict) conf """ try: with open(path_name) as json_file: conf = lo...
18b9051801b032f5aa5532da0cfcca8793be8c91
5,608
def _get_variable_names(expression): """Return the list of variable names in the Numexpr `expression`.""" names = [] stack = [expression] while stack: node = stack.pop() if node.astType == 'variable': names.append(node.value) elif hasattr(node, 'children'): ...
db75b0066b89bc7a6a022a56b28981910836524c
5,611
def get_boundary_levels(eris): """Get boundary levels for eris.""" return [func(eris.keys()) for func in (min, max)]
20d98447e600fecc3b9495e9fb5e5d09ff3b3c1e
5,613