content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def reverse_dict_old(dikt): """ takes a dict and return a new dict with old values as key and old keys as values (in a list) example _reverse_dict({'AB04a':'b', 'AB04b': 'b', 'AB04c':'b', 'CC04x': 'c'}) will return {'b': ['AB04a', 'AB04b', 'AB04c'], 'c': 'CC04x'} """ new_dikt = {} for k, v in dikt.items(): if v in new_dikt: new_dikt[v].append(k) else: new_dikt[v] = [k] return new_dikt
50155858fbbe52dc8daae66e6a94c8885b80ba05
5,971
def get_card_names(cards): """ :param cards: List of card JSONs :return: List of card names (str) """ names = [] for card in cards: name = card.get("name") names.append(name) return names
a30ad1ef7d8beaab0451d6f498254b0b5df3cf6d
5,980
import re def clean_value(value, suffix): """ Strip out copy suffix from a string value. :param value: Current value e.g "Test Copy" or "test-copy" for slug fields. :type value: `str` :param suffix: The suffix value to be replaced with an empty string. :type suffix: `str` :return: Stripped string without the suffix. """ # type: (str, str) -> str return re.sub(r"([\s-]?){}[\s-][\d]$".format(suffix), "", value, flags=re.I)
d2ec3b3affbf71411039f234c05935132205ae16
5,983
def config_split(config): """ Splits a config dict into smaller chunks. This helps to avoid sending big config files. """ split = [] if "actuator" in config: for name in config["actuator"]: split.append({"actuator": {name: config["actuator"][name]}}) del(config["actuator"]) split.append(config) return split
2006534ece382c55f1ba3914300f5b6960323e53
5,985
import colorsys def hex_2_hsv(hex_col): """ convert hex code to colorsys style hsv >>> hex_2_hsv('#f77f00') (0.08569500674763834, 1.0, 0.9686274509803922) """ hex_col = hex_col.lstrip('#') r, g, b = tuple(int(hex_col[i:i+2], 16) for i in (0, 2 ,4)) return colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
a80e9c5470dfc64c61d12bb4b823411c4a781bef
5,987
def tousLesIndices(stat): """ Returns the indices of all the elements of the graph """ return stat.node2com.keys() #s=stat.node2com.values() global globAuthorIndex global globTfIdfTab #pprint(globAuthorIndex) #pprint(stat.node2com.values()) #glob node->index return [globAuthorIndex[x] for x in stat.node2com] #return stat.node2com.values() #def varianceGroupe(): #def distanceListePointsCentre(indexsCommunaute, centre):
fa847ee3913d521778ee3462c8e946f0ff001c76
5,989
def calculate_gc(x): """Calculates the GC content of DNA sequence x. x: a string composed only of A's, T's, G's, and C's.""" x = x.upper() return float(x.count('G') + x.count('C')) / (x.count('G') + x.count('C') + x.count('A') + x.count('T'))
aae64ff550ef26e75518bdad8a12b7cda9e060d2
5,992
def hasattrs(object, *names): """ Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the listed attributes :param names: a variable amount of attribute names to check for :return: True if the object contains each named attribute, false otherwise """ for name in names: if not hasattr(object, name): return False return True
f3a2fc308d041ed0de79e3389e30e02660a1d535
5,997
import json def try_parse_json(json_): """Converts the string representation of JSON to JSON. :param str json_: JSON in str representation. :rtype: :class:`dict` if converted successfully, otherwise False. """ if not json_: return False try: return json.loads(json_) except ValueError: return False
077819cf82e307aacf3e56b11fbba26a79559968
5,999
def setup_config(quiz_name): """Updates the config.toml index and dataset field with the formatted quiz_name. This directs metapy to use the correct files Keyword arguments: quiz_name -- the name of the quiz Returns: True on success, false if fials to open file """ try: conf_file = open("config.toml", 'r') lines = conf_file.readlines() conf_file.close() for i in range(len(lines)): if lines[i].startswith("index"): lines[i] = "index = 'idx-{0}'\n".format(quiz_name.replace(" ", "_")) if lines[i].startswith("dataset"): lines[i] = "dataset = '{0}'\n".format(quiz_name.replace(" ", "_")) conf_file = open("config.toml", 'w') with conf_file: conf_file.writelines(lines) except Exception as e: print(e) return False return True
28aba9399926f27da89953c8b0c6b41d95a12d96
6,003
from typing import Dict def _average_latency(row: Dict): """ Calculate average latency for Performance Analyzer single test """ avg_sum_fields = [ "Client Send", "Network+Server Send/Recv", "Server Queue", "Server Compute", "Server Compute Input", "Server Compute Infer", "Server Compute Output", "Client Recv", ] avg_latency = sum(int(row.get(f, 0)) for f in avg_sum_fields) return avg_latency
f321cb4d55af605298225f2f0146a9a71ee7895b
6,006
def to_vsizip(zipfn, relpth): """ Create path from zip file """ return "/vsizip/{}/{}".format(zipfn, relpth)
6f5baf380bd7ab8a4ea92111efbc0f660b10f6f8
6,007
def requires_moderation(page): """Returns True if page requires moderation """ return bool(page.get_moderator_queryset().count())
8f1cfa852cbeccfae6157e94b7ddf61d9597936e
6,011
def valid_parentheses(string): """ Takes a string of parentheses, and determines if the order of the parentheses is valid. :param string: a string of parentheses and characters. :return: true if the string is valid, and false if it's invalid. """ stack = [] for x in string: if x == "(": stack.append(x) elif x == ")": if len(stack) > 0: stack.pop() else: return False return not stack
e8438404c461b7a113bbbab6417190dcd1056871
6,013
def has_form_encoded_header(header_lines): """Return if list includes form encoded header""" for line in header_lines: if ":" in line: (header, value) = line.split(":", 1) if header.lower() == "content-type" \ and "x-www-form-urlencoded" in value: return True return False
e4fe797e4884161d0d935853444634443e6e25bb
6,014
def attr(*args, **kwargs): """Decorator that adds attributes to classes or functions for use with unit tests runner. """ def wrapped(element): for name in args: setattr(element, name, True) for name, value in kwargs.items(): setattr(element, name, value) return element return wrapped
77d20af87cef526441aded99bd6e24e21e5f81f9
6,016
def nn(value: int) -> int: """Casts value to closest non negative value""" return 0 if value < 0 else value
08672feaefa99881a110e3fc629d4a9256f630af
6,017
def lat_long_to_idx(gt, lon, lat): """ Take a geotransform and calculate the array indexes for the given lat,long. :param gt: GDAL geotransform (e.g. gdal.Open(x).GetGeoTransform()). :type gt: GDAL Geotransform tuple. :param lon: Longitude. :type lon: float :param lat: Latitude. :type lat: float """ return (int((lat - gt[3]) / gt[5]), int((lon - gt[0]) / gt[1]))
3fafcc4750daa02beaedb330ab6273eab6abcd56
6,020
def BSMlambda(delta: float, S: float, V: float) -> float: """Not really a greek, but rather an expression of leverage. Arguments --------- delta : float BSM delta of the option V : float Spot price of the option S : float Spot price of the underlying Returns ------- float lambda Note ---- Percentage change in the option price per percentage change in the underlying asset's price. """ return delta*(S / V)
ea9bf546a7cf46b3c2be01e722409663b05248e1
6,021
import pwd def uid_to_name(uid): """ Find the username associated with a user ID. :param uid: The user ID (an integer). :returns: The username (a string) or :data:`None` if :func:`pwd.getpwuid()` fails to locate a user for the given ID. """ try: return pwd.getpwuid(uid).pw_name except Exception: return None
f9054e4959a385d34c18d88704d376fb4b718e47
6,022
def adjacent_powerset(iterable): """ Returns every combination of elements in an iterable where elements remain ordered and adjacent. For example, adjacent_powerset('ABCD') returns ['A', 'AB', 'ABC', 'ABCD', 'B', 'BC', 'BCD', 'C', 'CD', 'D'] Args: iterable: an iterable Returns: a list of element groupings """ return [iterable[a:b] for a in range(len(iterable)) for b in range(a + 1, len(iterable) + 1)]
951418b30d541e1dcdd635937ae609d429e3cd70
6,032
def end_position(variant_obj): """Calculate end position for a variant.""" alt_bases = len(variant_obj['alternative']) num_bases = max(len(variant_obj['reference']), alt_bases) return variant_obj['position'] + (num_bases - 1)
e49110a1102ea2ca53053858597247799065f8e1
6,034
import functools def decorator_with_keywords(func=None, **dkws): # NOTE: ONLY ACCEPTS KW ARGS """ A decorator that can handle optional keyword arguments. When the decorator is called with no optional arguments like this: @decorator def function ... The function is passed as the first argument and decorate returns the decorated function, as expected. If the decorator is called with one or more optional arguments like this: @decorator(optional_argument1='some value') def function .... Then decorator is called with the function argument with value None, so a function that decorates is returned, as expected. """ # print('WHOOP', func, dkws) def _decorate(func): @functools.wraps(func) def wrapped_function(*args, **kws): # print('!!') return func(*args, **kws) return wrapped_function if func: return _decorate(func) return _decorate
64c4ddd26cc04a43cbf559600652113db81b79ae
6,041
from datetime import datetime def parse_line(line): """ Extract all the data we want from each line. :param line: A line from our log files. :return: The data we have extracted. """ time = line.split()[0].strip() response = line.split(' :') message = response[len(response) - 1].strip('\n') channel = response[1].split('#') username = channel[0].split('!') username = username[0] channel = channel[1] time = datetime.strptime(time, '%Y-%m-%d_%H:%M:%S') return time, channel, username, message
72b4362b7628d31996075941be00e4ddcbd5edbc
6,042
from typing import Counter def reindex(labels): """ Given a list of labels, reindex them as integers from 1 to n_labels Also orders them in nonincreasing order of prevalence """ old2new = {} j = 1 for i, _ in Counter(labels).most_common(): old2new[i] = j j += 1 old2newf = lambda x: old2new[x] return [old2newf(a) for a in labels]
c12afd3b6431f10ccc43cce858e71bc504088a6e
6,044
import string def is_valid_matlab_field_label(label): """ Check that passed string is a valid MATLAB field label """ if not label.startswith(tuple(string.ascii_letters)): return False VALID_CHARS = set(string.ascii_letters + string.digits + "_") return set(label).issubset(VALID_CHARS)
ea1358e94f4fc936cb12b9cad5d7285ee39dba55
6,053
def variantCombinations(items): """ Calculates variant combinations for given list of options. Each item in the items list represents unique value with it's variants. :param list items: list of values to be combined >>> c = variantCombinations([["1.1", "1.2"], ["2.1", "2.2"], ["3.1", "3.2"]]) >>> len(c) 8 >>> for combination in c:print combination ['1.1', '2.1', '3.1'] ['1.1', '2.1', '3.2'] ['1.1', '2.2', '3.1'] ['1.1', '2.2', '3.2'] ['1.2', '2.1', '3.1'] ['1.2', '2.1', '3.2'] ['1.2', '2.2', '3.1'] ['1.2', '2.2', '3.2'] """ assert isinstance(items, list) and list if len(items) == 1: result = items[0] else: result = [] subItems = variantCombinations(items[1:]) for masterItem in items[0]: for subItem in subItems: if isinstance(subItem, list): item = [masterItem] item.extend(subItem) result.append(item) else: result.append([masterItem, subItem]) return result
72bfdb19db3cf692e4260a5f75d10324e562f20e
6,055
def fahrenheit2celsius(f: float) -> float: """Utility function to convert from Fahrenheit to Celsius.""" return (f - 32) * 5/9
5161b29998553ad6ff497e698058f330433d90b3
6,063
def pollard_brent_f(c, n, x): """Return f(x) = (x^2 + c)%n. Assume c < n. """ x1 = (x * x) % n + c if x1 >= n: x1 -= n assert x1 >= 0 and x1 < n return x1
5037b3feac2f131645fbe6ceb00f0d18417a7c04
6,064
def tpu_ordinal_fn(shard_index_in_host, replicas_per_worker): """Return the TPU ordinal associated with a shard.""" return shard_index_in_host % replicas_per_worker
773313750ce78cf5d32776752cb75201450416ba
6,065
def getObjectInfo(fluiddb, objectId): """ Get information about an object. """ return fluiddb.objects[objectId].get(showAbout=True)
baad59e6585e04a8c2a8cca1df305327b80f3768
6,071
import csv def snp2dict(snpfile): """Get settings of dict from .snp file exported from save&restore app. Parameters ---------- snpfile : str Filename of snp file exported from save&restore app. Returns ------- r : dict Dict of pairs of PV name and setpoint value. """ with open(snpfile, 'r') as fp: csv_data = csv.reader(fp, delimiter=',', skipinitialspace=True) next(csv_data) header = next(csv_data) ipv, ival = header.index('PV'), header.index('VALUE') settings = {line[ipv]: line[ival] for line in csv_data if line} return settings
cb902b3f8796685ed065bfeb8ed2d6d83c0fe80b
6,073
import math def pol2cart(r,theta): """ Translate from polar to cartesian coordinates. """ return (r*math.cos(float(theta)/180*math.pi), r*math.sin(float(theta)/180*math.pi))
69753e1cadd36ec70da1bf2cf94641d4c7f78179
6,077
def spread(self, value="", **kwargs): """Turns on a dashed tolerance curve for the subsequent curve plots. APDL Command: SPREAD Parameters ---------- value Amount of tolerance. For example, 0.1 is ± 10%. """ return self.run("SPREAD,%s" % (str(value)), **kwargs)
a92c8e230eadd4e1fde498fa5650a403f419eaeb
6,084
import re def repair_attribute_name(attr): """ Remove "weird" characters from attribute names """ return re.sub('[^a-zA-Z-_\/0-9\*]','',attr)
f653a5cb5ed5e43609bb334f631f518f73687853
6,085
def HasPositivePatterns(test_filter): """Returns True if test_filter contains a positive pattern, else False Args: test_filter: test-filter style string """ return bool(len(test_filter) > 0 and test_filter[0] != '-')
9038bf799efbe4008a83d2da0aba89c0197c16a1
6,087
def module_of_callable(c): """Find name of module where callable is defined Arguments: c {Callable} -- Callable to inspect Returns: str -- Module name (as for x.__module__ attribute) """ # Ordinal function defined with def or lambda: if type(c).__name__ == 'function': return c.__module__ # Some callable, probably it's a class with __call_ method, so define module of declaration rather than a module of instantiation: return c.__class__.__module__
116e46a3e75fcd138e271a3413c62425a9fcec3b
6,093
import json def invocation_parameter(s) : """argparse parameter conversion function for invocation request parameters, basically these parameters are JSON expressions """ try : expr = json.loads(s) return expr except : return str(s)
cca1a9c3514def152295b10b17ef44480ccca5a9
6,097
def dumpj(game): """Dump a game to json""" return game.to_json()
bac5480ea2b3136cbd18d0690af27f94e4a2b6a3
6,100
import types def _get_functions_names(module): """Get names of the functions in the current module""" return [name for name in dir(module) if isinstance(getattr(module, name, None), types.FunctionType)]
581384740dc27c15ac9710d66e9b0f897c906b96
6,101
import ast def ex_rvalue(name): """A variable store expression.""" return ast.Name(name, ast.Load())
4afff97283d96fd29740de5b7a97ef64aad66efe
6,102
def stateDiff(start, end): """Calculate time difference between two states.""" consumed = (end.getTimestamp() - start.getTimestamp()).total_seconds() return consumed
1f76903e2486e2c378f338143461d1d15f7993a6
6,103
import copy import random def staticDepthLimit(max_depth): """Implement a static limit on the depth of a GP tree, as defined by Koza in [Koza1989]. It may be used to decorate both crossover and mutation operators. When an invalid (too high) child is generated, it is simply replaced by one of its parents. This operator can be used to avoid memory errors occuring when the tree gets higher than 90-95 levels (as Python puts a limit on the call stack depth), because it ensures that no tree higher than *max_depth* will ever be accepted in the population (except if it was generated at initialization time). :param max_depth: The maximum depth allowed for an individual. :returns: A decorator that can be applied to a GP operator using \ :func:`~deap.base.Toolbox.decorate` .. note:: If you want to reproduce the exact behavior intended by Koza, set the *max_depth* param to 17. .. [Koza1989] J.R. Koza, Genetic Programming - On the Programming of Computers by Means of Natural Selection (MIT Press, Cambridge, MA, 1992) """ def decorator(func): def wrapper(*args, **kwargs): keep_inds = [copy.deepcopy(ind) for ind in args] new_inds = list(func(*args, **kwargs)) for i, ind in enumerate(new_inds): if ind.height > max_depth: new_inds[i] = random.choice(keep_inds) return new_inds return wrapper return decorator
cdcb1e58a681b622ced58e9aa36562e1fedb6083
6,104
def replace_last(source_string, replace_what, replace_with): """ Function that replaces the last ocurrence of a string in a word :param source_string: the source string :type source_string: str :param replace_what: the substring to be replaced :type replace_what: str :param replace_with: the string to be inserted :type replace_with: str :returns: string with the replacement :rtype: str :Example: >>> import chana.lemmatizer >>> chana.lemmatizer.replace_last('piati','ti','ra') 'piara' """ head, _sep, tail = source_string.rpartition(replace_what) return head + replace_with + tail
6fbc36824b960fb125b722101f21b5de732194c5
6,109
def unescape(text): """Unescapes text >>> unescape(u'abc') u'abc' >>> unescape(u'\\abc') u'abc' >>> unescape(u'\\\\abc') u'\\abc' """ # Note: We can ditch this and do it in tokenizing if tokenizing # returned typed tokens rather than a list of strings. new_text = [] escape = False for c in text: if not escape and c == u'\\': escape = True continue new_text.append(c) escape = False return u''.join(new_text)
7db9fa5bb786ea5c1f988ee26eed07abe66a2942
6,110
def removeZeros(infile, outfile, prop=0.5, genecols=2): """Remove lines from `infile' in which the proportion of zeros is equal to or higher than `prop'. `genecols' is the number of columns containing gene identifiers at the beginning of each row. Writes filtered lines to `outfile'.""" nin = 0 nout = 0 with open(infile, "r") as f: hdr = f.readline() columns = hdr.split("\t") ncols = len(columns)-genecols maxzeros = ncols*prop with open(outfile, "w") as out: out.write(hdr) while True: line = f.readline() if line == '': break nin += 1 pline = line.rstrip("\r\n").split("\t") nzeros = 0 for v in pline[genecols:]: if float(v) == 0: nzeros += 1 if nzeros < maxzeros: out.write(line) nout += 1 return (nin, nout)
43feba21513be4a8292c08918e16b3e34a73c341
6,112
def getPositionPdf(i): """Return the position of the square on the pdf page""" return [int(i/5), i%5]
859fd00c1475cfcb4cd93800299181b77fdd6e93
6,116
def dur_attributes_to_dur(d_half, d_semiqvr): """ Convert arrays of d_hlf and d_sqv to d. - See eq. (2) of the paper. """ def d_hlf_dur_sqv_to_d(d_hlf, d_sqv): return 8 * d_hlf + d_sqv d = d_hlf_dur_sqv_to_d(d_half, d_semiqvr) return d
aeea74f929ef94d94178444df66a30d0d017fd4e
6,117
def filter_score_grouped_pair(post_pair): """ Filter posts with a positive score. :param post_pair: pair of post_id, dict with score, text blocks, and comments :return: boolean indicating whether post has a positive score """ _, post_dict = post_pair post_score = post_dict['score'] return post_score and int(post_score) > 0
c824eacd43b44c85fc7acf102fdde2413a7c4d0e
6,120
def add_upper_log_level(logger, method_name, event_dict): """ Add the log level to the event dict. """ event_dict["level"] = method_name.upper() return event_dict
36ccdf335473136fe8188ff99ed539920ee39fa7
6,126
def zigzag2(i, curr=.45, upper=.48, lower=.13): """ Generalized version of the zig-zag function. Returns points oscillating between two bounds linearly. """ if abs(i) <= (upper-curr): return curr + i else: i = i - (upper-curr) i = i%(2*(upper-lower)) if i < (upper-lower): return upper-i else: return 2*lower-upper+i
a51624af520121eb7285b2a8a5b4dc5ffa552147
6,131
def discriminateEvents(events, threshold): """ Discriminate triggers when different kind of events are on the same channel. A time threshold is used to determine if two events are from the same trial. Parameters ---------- events : instance of pandas.core.DataFrame Dataframe containing the list of events obtained with mne.find_events(raw). threshold : float Time threshold in milliseconds. Keeps an event if the time difference with the next one is superior than threshold. Returns: newData : instance of pandas.series.Series List of trial number filling the requirements. """ # calculate the rolling difference (between n and n+1) events['diff'] = events[0].diff() # replace the nan with the first value events['diff'].iloc[0] = events.iloc[0, 0] # select events with time distance superior to threshold events = events[events['diff']>threshold] events = events.reset_index(drop=True) del events['diff'] return events
0078548ea463c01d88b574185b3dcb5632e5cd13
6,133
def parse_movie(line, sep='::'): """ Parses a movie line Returns: tuple of (movie_id, title) """ fields = line.strip().split(sep) movie_id = int(fields[0]) # convert movie_id to int title = fields[1] return movie_id, title
9d7a13ca3ddf823ff22582f648434d4b6df00207
6,136
def strip_newlines(s, nleading=0, ntrailing=0): """strip at most nleading and ntrailing newlines from s""" for _ in range(nleading): if s.lstrip(' \t')[0] == '\n': s = s.lstrip(' \t')[1:] elif s.lstrip(' \t')[0] == '\r\n': s = s.lstrip(' \t')[2:] for _ in range(ntrailing): if s.rstrip(' \t')[-2:] == '\r\n': s = s.rstrip(' \t')[:-2] elif s.rstrip(' \t')[-1:] == '\n': s = s.rstrip(' \t')[:-1] return s
cd9c55d4ac7828d9506567d879277a463d896c46
6,141
def xyz_to_lab(x_val, y_val, z_val): """ Convert XYZ color to CIE-Lab color. :arg float x_val: XYZ value of X. :arg float y_val: XYZ value of Y. :arg float z_val: XYZ value of Z. :returns: Tuple (L, a, b) representing CIE-Lab color :rtype: tuple D65/2° standard illuminant """ xyz = [] for val, ref in (x_val, 95.047), (y_val, 100.0), (z_val, 108.883): val /= ref val = pow(val, 1 / 3.0) if val > 0.008856 else 7.787 * val + 16 / 116.0 xyz.append(val) x_val, y_val, z_val = xyz # pylint: disable=unbalanced-tuple-unpacking cie_l = 116 * y_val - 16 cie_a = 500 * (x_val - y_val) cie_b = 200 * (y_val - z_val) return cie_l, cie_a, cie_b
c2478772659a5d925c4db0b6ba68ce98b6537a59
6,142
def infer(model, text_sequences, input_lengths): """ An inference hook for pretrained synthesizers Arguments --------- model: Tacotron2 the tacotron model text_sequences: torch.Tensor encoded text sequences input_lengths: torch.Tensor input lengths Returns ------- result: tuple (mel_outputs_postnet, mel_lengths, alignments) - the exact model output """ return model.infer(text_sequences, input_lengths)
e7937395956e2dcd35dd86bc23599fbb63417c22
6,149
def _is_course_or_run_deleted(title): """ Returns True if '[delete]', 'delete ' (note the ending space character) exists in a course's title or if the course title equals 'delete' for the purpose of skipping the course Args: title (str): The course.title of the course Returns: bool: True if the course or run should be considered deleted """ title = title.strip().lower() if ( "[delete]" in title or "(delete)" in title or "delete " in title or title == "delete" ): return True return False
c32c69e15fafbc899048b89ab8199f653d59e7a8
6,156
from typing import OrderedDict def map_constructor(loader, node): """ Constructs a map using OrderedDict. :param loader: YAML loader :param node: YAML node :return: OrderedDictionary data """ loader.flatten_mapping(node) return OrderedDict(loader.construct_pairs(node))
21bf92d0c3975758ae434026fae3f54736b7f21d
6,157
def usage_percentage(usage, limit): """Usage percentage.""" if limit == 0: return "" return "({:.0%})".format(usage / limit)
7caf98ddb37036c79c0e323fc854cbc550eaaa60
6,162
from typing import Dict def strip_empty_values(values: Dict) -> Dict: """Remove any dict items with empty or ``None`` values.""" return {k: v for k, v in values.items() if v or v in [False, 0, 0.0]}
982814edbd73961d9afa2e2389cbd970b2bc231e
6,164
def metric_wind_dict_to_beaufort(d): """ Converts all the wind values in a dict from meters/sec to the corresponding Beaufort scale level (which is not an exact number but rather represents a range of wind speeds - see: https://en.wikipedia.org/wiki/Beaufort_scale). Conversion table: https://www.windfinder.com/wind/windspeed.htm :param d: the dictionary containing metric values :type d: dict :returns: a dict with the same keys as the input dict and values converted to Beaufort level """ result = {} for key, value in d.items(): if key != 'deg': # do not convert wind degree if value <= 0.2: bf = 0 elif 0.2 < value <= 1.5: bf = 1 elif 1.5 < value <= 3.3: bf = 2 elif 3.3 < value <= 5.4: bf = 3 elif 5.4 < value <= 7.9: bf = 4 elif 7.9 < value <= 10.7: bf = 5 elif 10.7 < value <= 13.8: bf = 6 elif 13.8 < value <= 17.1: bf = 7 elif 17.1 < value <= 20.7: bf = 8 elif 20.7 < value <= 24.4: bf = 9 elif 24.4 < value <= 28.4: bf = 10 elif 28.4 < value <= 32.6: bf = 11 else: bf = 12 result[key] = bf else: result[key] = value return result
b26ddb5e9c0423612a9c7086030fd77bbfa371ad
6,170
def str_igrep(S, strs): """Returns a list of the indices of the strings wherein the substring S is found.""" return [i for (i,s) in enumerate(strs) if s.find(S) >= 0] #return [i for (s,i) in zip(strs,xrange(len(strs))) if s.find(S) >= 0]
bae8afdb7d0da4eb8384c06e9f0c9bc3f6a31242
6,171
import base64 def is_base64(s): """Return True if input string is base64, false otherwise.""" s = s.strip("'\"") try: if isinstance(s, str): sb_bytes = bytes(s, 'ascii') elif isinstance(s, bytes): sb_bytes = s else: raise ValueError("Argument must be string or bytes") return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes except Exception: return False
6ce7bc4ddc79d5d50acce35f7995033ffb7d364a
6,175
def get_mod_from_id(mod_id, mod_list): """ Returns the mod for given mod or None if it isn't found. Parameters ---------- mod_id : str The mod identifier to look for mod_list : list[DatRecord] List of mods to search in (or dat file) Returns ------- DatRecord or None Returns the mod if found, None otherwise """ for mod in mod_list: if mod['Id'] == mod_id: return mod return None
1fac309e4dfadea6da34946eb695f77cbbd61f92
6,177
import math def distance(point1, point2): """ Return the distance between two points.""" dx = point1[0] - point2[0] dy = point1[1] - point2[1] return math.sqrt(dx * dx + dy * dy)
7605d98e33989de91c49a5acf702609272cf5a68
6,178
def cumulative_sum(t): """ Return a new list where the ith element is the sum of all elements up to that position in the list. Ex: [1, 2, 3] returns [1, 3, 6] """ res = [t[0]] for i in range(1, len(t)): res.append(res[-1] + t[i]) return res
14b2ef722f72e239d05737a7bb7b3a6b3e15305f
6,180
import random def particle_movement_x(time): """ Generates a random movement in the X label Parameter: time (int): Time step Return: x (int): X position """ x = 0 directions = [1, -1] for i in range(time): x = x + random.choice(directions) return x
0dff68080dbfd56997cffb1e469390a1964a326f
6,187
def _format_td(timedelt): """Format a timedelta object as hh:mm:ss""" if timedelt is None: return '' s = int(round(timedelt.total_seconds())) hours = s // 3600 minutes = (s % 3600) // 60 seconds = (s % 60) return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
071f25c3c8cfc75cacf2fedc7002527897362654
6,193
def extract_protein_from_record(record): """ Grab the protein sequence as a string from a SwissProt record :param record: A Bio.SwissProt.SeqRecord instance :return: """ return str(record.sequence)
a556bd4316f145bf23697d8582f66f7dcb589087
6,198
import torch def calc_IOU(seg_omg1: torch.BoolTensor, seg_omg2: torch.BoolTensor, eps: float = 1.e-6) -> float: """ calculate intersection over union between 2 boolean segmentation masks :param seg_omg1: first segmentation mask :param seg_omg2: second segmentation mask :param eps: eps for numerical stability :return: IOU """ dim = [1, 2, 3] if len(seg_omg1.shape) == 4 else [1, 2] intersection = (seg_omg1 & seg_omg2).sum(dim=dim) union = (seg_omg1 | seg_omg2).sum(dim=dim) return (intersection.float() / (union.float() + eps)).mean().item()
6586b1f9995858be9ab7e40edd1c3433cd1cd6f4
6,199
def td_path_join(*argv): """Construct TD path from args.""" assert len(argv) >= 2, "Requires at least 2 tdpath arguments" return "/".join([str(arg_) for arg_ in argv])
491f1d50767a50bfbd7d3a2e79745e0446f5204c
6,200
import torch def calculate_segmentation_statistics(outputs: torch.Tensor, targets: torch.Tensor, class_dim: int = 1, threshold=None): """Compute calculate segmentation statistics. Args: outputs: torch.Tensor. targets: torch.Tensor. threshold: threshold for binarization of predictions. class_dim: indicates class dimension (K). Returns: True positives , false positives , false negatives for segmentation task. """ num_dims = len(outputs.shape) assert num_dims > 2, "Found only two dimensions, shape should be [bs , C , ...]" # noqa: S101 assert outputs.shape == targets.shape, "shape mismatch" # noqa: S101 if threshold is not None: outputs = (outputs > threshold).float() dims = [dim for dim in range(num_dims) if dim != class_dim] true_positives = torch.sum(outputs * targets, dim=dims) false_positives = torch.sum(outputs * (1 - targets), dim=dims) false_negatives = torch.sum(targets * (1 - outputs), dim=dims) return true_positives, false_positives, false_negatives
ccc017dd5c7197565e54c62cd83eb5cdc02d7d17
6,201
import torch def polar2cart(r, theta): """ Transform polar coordinates to Cartesian. Parameters ---------- r, theta : floats or arrays Polar coordinates Returns ------- [x, y] : floats or arrays Cartesian coordinates """ return torch.stack((r * theta.cos(), r * theta.sin()), dim=-1).squeeze()
c13225a49d6435736bf326f70af5f6d4039091d8
6,204
def backoff_linear(n): """ backoff_linear(n) -> float Linear backoff implementation. This returns n. See ReconnectingWebSocket for details. """ return n
a3a3b3fc0c4a56943b1d603bf7634ec50404bfb3
6,207
def check_dna_sequence(sequence): """Check if a given sequence contains only the allowed letters A, C, T, G.""" return len(sequence) != 0 and all(base.upper() in ['A', 'C', 'T', 'G'] for base in sequence)
2f561c83773ddaaad2fff71a6b2e5d48c5a35f87
6,209
import random def random_tolerance(value, tolerance): """Generate a value within a small tolerance. Credit: /u/LightShadow on Reddit. Example:: >>> time.sleep(random_tolerance(1.0, 0.01)) >>> a = random_tolerance(4.0, 0.25) >>> assert 3.0 <= a <= 5.0 True """ value = float(value) if tolerance == 0.0: return value return value + value * random.uniform(-tolerance, tolerance)
abe631db8a520de788540f8e0973537306872bde
6,217
def find_scan_info(filename, position = '__P', scan = '__S', date = '____'): """ Find laser position and scan number by looking at the file name """ try: file = filename.split(position, 2) file = file[1].split(scan, 2) laser_position = file[0] file = file[1].split(date, 2) scan_number = file[0] except IndexError: laser_position = -1 scan_number = -1 return laser_position, scan_number
f98afb440407ef7eac8ceda8e15327b5f5d32b35
6,218
import requests def cleaned_request(request_type, *args, **kwargs): """ Perform a cleaned requests request """ s = requests.Session() # this removes netrc checking s.trust_env = False return s.request(request_type, *args, **kwargs)
b6c99c85a64e5fd78cf10cc986c9a4b1542f47d3
6,227
import yaml def load_config_file(filename): """Load configuration from YAML file.""" docs = yaml.load_all(open(filename, 'r'), Loader=yaml.SafeLoader) config_dict = dict() for doc in docs: for k, v in doc.items(): config_dict[k] = v return config_dict
d61bb86e605a1e744ce3f4cc03e866c61137835d
6,228
def empty_filter(item, *args, **kwargs): """ Placeholder function to pass along instead of filters """ return True
d72ac5a0f787557b78644bcedd75e71f92c38a0b
6,231
import re def remove_mentions(text): """Remove @-mentions from the text""" return re.sub('@\w+', '', text)
5cbdd40a602f24f8274369e92f9159cbb2f6a230
6,235
def _flat(l): """Flattens a list. """ f = [] for x in l: f += x return f
9b2e432d79f08840d417601ff950ff9fa28073ef
6,236
from typing import Union from pathlib import Path def find_mo(search_paths=None) -> Union[Path, None]: """ Args: search_paths: paths where ModelOptimizer may be found. If None only default paths is used. Returns: path to the ModelOptimizer or None if it wasn't found. """ default_mo_path = ('intel', 'openvino', 'deployment_tools', 'model_optimizer') default_paths = [Path.home().joinpath(*default_mo_path), Path('/opt').joinpath(*default_mo_path)] executable = 'mo.py' for path in search_paths or default_paths: path = Path(path) if not path.is_dir(): continue mo = path / executable if not mo.is_file(): continue return mo return None
4657e15649692415dd10f2daa6527cade351d8fc
6,241
import math def point_in_wave(point_x, frequency, amplitude, offset_x, offset_y): """Returns the specified point x in the wave of specified parameters.""" return (math.sin((math.pi * point_x)/frequency + offset_x) * amplitude) + offset_y
5a91c9204819492bb3bd42f0d4c9231d39e404d8
6,245
def map_to_docs(solr_response): """ Response mapper that only returns the list of result documents. """ return solr_response['response']['docs']
2661b9075c05a91c241342151d713702973b9c12
6,246
import json def generate_prompt( test_case_path, prompt_path, solutions_path, tokenizer, starter_path=None ): """ Generate a prompt for a given test case. Original version from https://github.com/hendrycks/apps/blob/main/eval/generate_gpt_codes.py#L51. """ _input = "\nQUESTION:\n" with open(prompt_path, "r") as f: data = f.readlines() data = "".join(data) _input += data if starter_path != None: with open(starter_path, "r") as f: data = f.readlines() data = "".join(data) data = "\n" + data # + "\n" _input += data else: # _input += "\n\n" pass with open(test_case_path, "r") as f: data = json.load(f) if not data.get("fn_name"): _input += "\nUse Standard Input format" # \n" else: _input += "\nUse Call-Based format" # \n" _input += "\nANSWER:\n" return _input
ecd3218839b346741e5beea8ec7113ea2892571e
6,252
def format_header(header_values): """ Formats a row of data with bolded values. :param header_values: a list of values to be used as headers :return: a string corresponding to a row in enjin table format """ header = '[tr][td][b]{0}[/b][/td][/tr]' header_sep = '[/b][/td][td][b]' return header.format(header_sep.join(header_values))
5b7cd734a486959660551a6d915fbbf52ae7ef1e
6,258
import importlib def load_attr(str_full_module): """ Args: - str_full_module: (str) correspond to {module_name}.{attr} Return: the loaded attribute from a module. """ if type(str_full_module) == str: split_full = str_full_module.split(".") str_module = ".".join(split_full[:-1]) str_attr = split_full[-1] module = importlib.import_module(str_module) return getattr(module, str_attr) else: return str_full_module
f96dd56c73745e76ccc9c48dda4ba8a6592ab54b
6,259
def quick_sort(seq): """ Реализация быстрой сортировки. Рекурсивный вариант. :param seq: любая изменяемая коллекция с гетерогенными элементами, которые можно сравнивать. :return: коллекция с элементами, расположенными по возрастанию. Examples: >>> quick_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> quick_sort([]) [] >>> quick_sort([-2, -5, -45]) [-45, -5, -2] """ length = len(seq) if length <= 1: return seq else: # В качестве pivot используется последний элемент. pivot = seq.pop() # lesser - часть коллекции, которая меньше pivot, будет тут. # greater - части коллекции, которая меньше pivot, будет тут. greater, lesser = [], [] for element in seq: if element > pivot: greater.append(element) else: lesser.append(element) # Рекурсивно вызывается функция сортировки отдельно для # greater и lesser. В конце все части объединяются в единую # коллекцию. Между ними вставляется pivot. return quick_sort(lesser) + [pivot] + quick_sort(greater)
46b56b5d29ca31a872e1805b66f4529a8bf48c6b
6,261
def normalize_query_result(result, sort=True): """ Post-process query result to generate a simple, nested list. :param result: A QueryResult object. :param sort: if True (default) rows will be sorted. :return: A list of lists of RDF values. """ normalized = [[row[i] for i in range(len(row))] for row in result] return sorted(normalized) if sort else normalized
1df57ef889be041c41593766e1ce3cdd4ada7f66
6,262
from typing import List def count_jobpairs(buildpairs: List) -> int: """ :param buildpairs: A list of build pairs. :return: The number of job pairs in `buildpairs`. """ counts = [len(bp['jobpairs']) for bp in buildpairs] return sum(counts)
30c345698400fd134456abcf7331ca2ebbfec10f
6,263
def calc_water(scenario, years, days_in_year): """Calculate Water costs Function Args: scenario (object): The farm scenario years (int): The no. of years the simulation will analyse days_in_year (float): The number of days in a year Returns: cogs_water (list): Cost of Goods Sold expenditure on Water as a time series for each year water_consumption (list): The amount of water consumed each year """ water_consumption = [0] for y in range(years+1): if y == 1: water_consumption.append(scenario.system_quantity * 0.95 * days_in_year + (1900*12)) elif y > 1: water_consumption.append((scenario.system_quantity * 0.95 * days_in_year + (1900*12)) * scenario.growing_area_mulitplier) cogs_water = [i * scenario.water_price for i in water_consumption] return cogs_water, water_consumption
ed23060e64c928a545897edef008b8b020d84d3c
6,266
import json def enqueue_crawling_job(delegate_or_broadcast_svc, job_id, urls, depth): """ Used to enqueue a crawling job (or delegate a sub-url on a current job) to the worker pool. :type delegate_or_broadcast_svc: ZeroMQDelegatorService or ZeroMQBroadcastService. :param delegate_or_broadcast_svc: The web API service uses a ZeroMQBroadcastService to announce new crawling jobs. The crawler service uses ZeroMQDelegatorService to delegate any sub-links found while scouring a page. :param int job_id: The job ID that these URLs fall under. :param set urls: The URLs to crawl. We'll send out one announcement per URL. :param int depth: The depth that this crawl will be at. 0 being initial. :rtype: int :returns: The number of crawler announcements made. One per URL. """ message_dict = { 'job_id': job_id, 'depth': depth } for url in urls: message_dict['url'] = url message_str = json.dumps(message_dict) delegate_or_broadcast_svc.send_message(message_str) return len(urls)
6a211346edd6f921bf26ed08adcee98cff066764
6,268
import re def camel_to_snake(text: str) -> str: """ A helper function to convert `camelCase` to `snake_case`. - e.g. `bestBigBrawlerTime` -> `best_big_brawler_time` ### Parameters text: `str` The text to restructure from `camelCase` to `snake_case`. ### Returns `str` The restructured `snake_case` text. """ return re.compile(r"(?<!^)(?=[A-Z])").sub("_", text).lower()
b9ac748bf0cc345c7cfb0bade1e4b1e9cbdf712c
6,272
import ast def extract_ast_class_def_by_name(ast_tree, class_name): """ Extracts class definition by name :param ast_tree: AST tree :param class_name: name of the class. :return: class node found """ class ClassVisitor(ast.NodeVisitor): """ Visitor. """ def __init__(self): self.found_class_node = None def visit_ClassDef(self, node): # pylint: disable=invalid-name """ Visit class definition. :param node: node. :return: """ if node.name == class_name: self.found_class_node = node visitor = ClassVisitor() visitor.visit(ast_tree) return visitor.found_class_node
011f1cb8d965db8e30e6f4281704a6140103946b
6,276
from typing import Callable def _scroll_screen(direction: int) -> Callable: """ Scroll to the next/prev group of the subset allocated to a specific screen. This will rotate between e.g. 1->2->3->1 when the first screen is focussed. """ def _inner(qtile): if len(qtile.screens) == 1: current = qtile.groups.index(qtile.current_group) destination = (current + direction) % 6 qtile.groups[destination].cmd_toscreen() return current = qtile.groups.index(qtile.current_group) if current < 3: destination = (current + direction) % 3 else: destination = ((current - 3 + direction) % 3) + 3 qtile.groups[destination].cmd_toscreen() return _inner
e778b6ef8a07fe8609a5f3332fa7c44d1b34c17a
6,280
import torch def decorate_batch(batch, device='cpu'): """Decorate the input batch with a proper device Parameters ---------- batch : {[torch.Tensor | list | dict]} The input batch, where the list or dict can contain non-tensor objects device: str, optional 'cpu' or 'cuda' Raises: ---------- Exception: Unsupported data type Return ---------- torch.Tensor | list | dict Maintain the same structure as the input batch, but with tensors moved to a proper device. """ if isinstance(batch, torch.Tensor): batch = batch.to(device) return batch elif isinstance(batch, dict): for key, value in batch.items(): if isinstance(value, torch.Tensor): batch[key] = value.to(device) elif isinstance(value, dict) or isinstance(value, list): batch[key] = decorate_batch(value, device) # retain other value types in the batch dict return batch elif isinstance(batch, list): new_batch = [] for value in batch: if isinstance(value, torch.Tensor): new_batch.append(value.to(device)) elif isinstance(value, dict) or isinstance(value, list): new_batch.append(decorate_batch(value, device)) else: # retain other value types in the batch list new_batch.append(value) return new_batch else: raise Exception('Unsupported batch type {}'.format(type(batch)))
a0bd4a5dff0b5cf6e304aede678c5d56cb93d1dd
6,286
import io def read_bytes(n: int, reader: io.IOBase) -> bytes: """ Reads the specified number of bytes from the reader. It raises an `EOFError` if the specified number of bytes is not available. Parameters: - `n`: The number of bytes to read; - `reader`: The reader; Returns the bytes read. """ buff = reader.read(n) if not isinstance(buff, bytes): raise ValueError('The reader is expected to return bytes.') if len(buff) != n: raise EOFError(f'Unable to read {n} bytes from the stream.') return buff
bb3d00fc7667839864f4104a94a26e682f058fdc
6,287
import json def _format_full_payload(_json_field_name, _json_payload, _files_payload): """This function formats the full payload for a ``multipart/form-data`` API request including attachments. .. versionadded:: 2.8.0 :param _json_field_name: The name of the highest-level JSON field used in the JSON payload :type _json_field_name: str :param _json_payload: The JSON payload data as a dictionary :type _json_payload: dict :param _files_payload: The payload for the attachments containing the IO stream for the file(s) :type _files_payload: dict :returns: The full payload as a dictionary :raises: :py:exc:`TypeError` """ _full_payload = { _json_field_name: (None, json.dumps(_json_payload, default=str), 'application/json') } _full_payload.update(_files_payload) return _full_payload
feacd27be3e6fcbd33f77fa755be513a93e3cdeb
6,288
def read_slug(filename): """ Returns the test slug found in specified filename. """ with open(filename, "r") as f: slug = f.read() return slug
e1882d856e70efa8555dab9e422a1348594ffcaf
6,291