content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def moving_sum(x, start_idx: int, end_idx: int): """ From MONOTONIC CHUNKWISE ATTENTION https://arxiv.org/pdf/1712.05382.pdf Equation (18) x = [x_1, x_2, ..., x_N] MovingSum(x, start_idx, end_idx)_n = Sigma_{m=n−(start_idx−1)}^{n+end_idx-1} x_m for n in {1, 2, 3, ..., N} x : src_len, batch_size start_idx : start idx end_idx : end idx Example src_len = 5 batch_size = 3 x = [[ 0, 5, 10], [ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13], [ 4, 9, 14]] MovingSum(x, 3, 1) = [[ 0, 5, 10], [ 1, 11, 21], [ 3, 18, 33], [ 6, 21, 36], [ 9, 24, 39]] MovingSum(x, 1, 3) = [[ 3, 18, 33], [ 6, 21, 36], [ 9, 24, 39], [ 7, 17, 27], [ 4, 9, 14]] """ assert start_idx > 0 and end_idx > 0 assert len(x.size()) == 2 src_len, batch_size = x.size() # batch_size, 1, src_len x = x.t().unsqueeze(1) # batch_size, 1, src_len moving_sum_weight = x.new_ones([1, 1, end_idx + start_idx - 1]) moving_sum = ( torch.nn.functional.conv1d( x, moving_sum_weight, padding=start_idx + end_idx - 1 ) .squeeze(1) .t() ) moving_sum = moving_sum[end_idx:-start_idx] assert src_len == moving_sum.size(0) assert batch_size == moving_sum.size(1) return moving_sum
fa3cb672e23fccad75965da2ca10955134167c7e
3,742
def make_sequence_output(detections, classes): """ Create the output object for an entire sequence :param detections: A list of lists of detections. Must contain an entry for each image in the sequence :param classes: The list of classes in the order they appear in the label probabilities :return: """ return { 'detections': detections, 'classes': classes }
019d3b74699af20a9f3cbc43b575e8bae5e15946
3,743
def encode(value): """ Encode strings in UTF-8. :param value: value to be encoded in UTF-8 :return: encoded value """ return str(u''.join(value).encode('utf-8'))
697f99f028d4b978b591d006273b9d5f688711f3
3,747
def get_season(months, str_='{}'): """ Creates a season string. Parameters: - months (list of int) - str_ (str, optional): Formatter string, should contain exactly one {} at the position where the season substring is included. Returns: str """ if months is None: return '' elif len(set(months).difference([1, 2, 12])) == 0: return str_.format('DJF') elif len(set(months).difference([3, 4, 5])) == 0: return str_.format('MAM') elif len(set(months).difference([6, 7, 8])) == 0: return str_.format('JJA') elif len(set(months).difference([9, 10, 11])) == 0: return str_.format('SON') elif len(set(months).difference([11, 12, 1, 2, 3])) == 0: return str_.format('NDJFM') elif len(set(months).difference([5, 6, 7, 8, 9])) == 0: return str_.format('MJJAS') else: return str_.format('-'.join(map(str, months)))
73b4e8169f08ef286a0b57779d22c3436538fc30
3,748
def total_value(metric): """Given a time series of values, sum the values""" total = 0 for i in metric: total += i return total
4454bfaeb0797bc03b14819bde48dc8f5accc4d3
3,752
def pt_to_tup(pt): """ Convenience method to generate a pair of two ints from a tuple or list. Parameters ---------- pt : list OR tuple Can be a list or a tuple of >=2 elements as floats or ints. Returns ------- pt : tuple of int A pair of two ints. """ return (int(pt[0]),int(pt[1]));
7013b2477959f528b98d364e4cc44ac8700fb366
3,760
def flatten(lst): """Shallow flatten *lst*""" return [a for b in lst for a in b]
203e971e43aea4d94bfa0ffa7057b416ef0bf545
3,763
def sep_num(number, space=True): """ Creates a string representation of a number with separators each thousand. If space is True, then it uses spaces for the separator otherwise it will use commas Note ---- Source: https://stackoverflow.com/questions/16670125/python-format-string-thousand-separator-with-spaces :param number: A number :type number: int | float :param space: Separates numbers with spaces if True, else with commas :type space: bool :return: string representation with space separation :rtype: str """ if space: return '{:,}'.format(number).replace(',', ' ') else: return '{:,}'.format(number)
ee7dfbb60fb01bb7b6bb84cbe56ec50dfab4b339
3,764
def LowercaseMutator(current, value): """Lower the value.""" return current.lower()
7fed0dc4533948c54b64f649e2c85dca27ee9bc5
3,767
import pathlib def testdata(request): """ If expected data is required for a test this fixture returns the path to a folder with name '.testdata' located in the same director as the calling test module """ testdata_dir = '.testdata' module_dir = pathlib.Path(request.fspath).parent return module_dir / testdata_dir
5d9a440b178aca00635f567420aaa9c406a1d7d2
3,770
def drop_useless_columns(data): """Drop the columns containing duplicate or useless columns.""" data = data.drop( labels=[ # we stay in a given city "agency_id", "agency_name", "agency_short_name", # we stay on a given transportation network "transportation_type", "transportation_subtype", # we already have stop id "stop_name_unofficial", # we already have line name "line_id", # we don't need this "circuit_transfer", ], axis=1, ) return data
7a47625a5df7e9fa66cefe2f326af3f0b9f59b79
3,773
import re def normalize(string: str) -> str: """ Normalize a text string. :param string: input string :return: normalized string """ string = string.replace("\xef\xbb\xbf", "") # remove UTF-8 BOM string = string.replace("\ufeff", "") # remove UTF-16 BOM # string = unicodedata.normalize("NFKD", string) # convert to NFKD normal form string = re.compile(r"[0-9]").sub("0", string) # map all numbers to "0" string = re.compile(r"(?:''|``|[\"„“”‘’«»])").sub("'", string) # normalize quotes string = re.compile(r"(?:[‒–—―]+|-{2,})").sub("--", string) # normalize dashes string = re.compile(r"\s+").sub(" ", string) # collapse whitespace characters return string.strip()
2adaeffb60af598dad40bd6f5cd7e61e6b238123
3,775
def extract_data(mask, dra, ddc, dra_err, ddc_err, ra_rad, dc_rad, ra_dc_cor=None): """Get a clean sample based on mask Parameters ---------- mask : array of boolean mask for extract data dra/ddc : array of float R.A.(*cos(Dec.))/Dec. differences dra_err/ddc_err : array of float formal uncertainty of dra(*cos(dc_rad))/ddc ra_rad/dc_rad : array of float Right ascension/Declination in radian Returns ---------- dra_new/ddc_new: array of float R.A.(*cos(Dec.))/Dec for the clean sample. differences dra_err_new/ddc_err_new: array of float formal uncertainty of dra(*cos(dc_rad))/ddc for the clean sample ra_rad_new/dc_rad_new: array of float Right ascension/Declination in radian for the clean sample ra_dc_cor_new: array of float covariance/correlation coefficient between dra and ddc for the clean sample """ # Extract the clean sample dra_new, ddc_new = dra[mask], ddc[mask] dra_err_new, ddc_err_new = dra_err[mask], ddc_err[mask] ra_rad_new, dc_rad_new = ra_rad[mask], dc_rad[mask] if ra_dc_cor is None: ra_dc_cor_new = ra_dc_cor else: ra_dc_cor_new = ra_dc_cor[mask] return dra_new, ddc_new, dra_err_new, ddc_err_new, ra_rad_new, dc_rad_new, ra_dc_cor_new
70286c6134fb19833f6033c827bb2ab2cd26afb1
3,776
def update_instance(instance, validated_data): """Update all the instance's fields specified in the validated_data""" for key, value in validated_data.items(): setattr(instance, key, value) return instance.save()
2f4d5c4ec9e524cbe348a5efad9ecae27739b339
3,779
import pipes def _ShellQuote(command_part): """Escape a part of a command to enable copy/pasting it into a shell. """ return pipes.quote(command_part)
31ccd5bd64de657cd3ac5c36c643e9f2f09f2318
3,780
import math def circlePoints(x, r, cx, cy): """Ther dunction returns the y coordinate of a circonference's point :x: x's coordinate value. :r: length of the radius. :cx: x coordinate of the center. :cy: y coordinate of the center.""" return math.sqrt(math.pow(r,2) - math.pow(x-cx, 2)) + cy
c2cc14a845dccbcf62a38be3af69808024289adc
3,781
import torch def get_gram_matrix(tensor): """ Returns a Gram matrix of dimension (distinct_filer_count, distinct_filter_count) where G[i,j] is the inner product between the vectorised feature map i and j in layer l """ G = torch.mm(tensor, tensor.t()) return G
ad86f06768c07d6fe1ff509d996991f786ea1ffa
3,782
def get_all_contained_items(item, stoptest=None): """ Recursively retrieve all items contained in another item :param text_game_maker.game_objects.items.Item item: item to retrieve items\ from :param stoptest: callback to call on each sub-item to test whether\ recursion should continue. If stoptest() == True, recursion will\ continue :return: list of retrieved items :rtype: [text_game_maker.game_objects.items.Item] """ ret = [] if not item.is_container: return ret stack = [item] while stack: subitem = stack.pop(0) for i in subitem.items: ret.append(i) if i.is_container: if stoptest and stoptest(i): continue stack.append(i) return ret
d04e5c297dddb70db83637e748281f04b08b6a25
3,785
def conv_seq_to_sent_symbols(seq, excl_symbols=None, end_symbol='.', remove_end_symbol=True): """ Converts sequences of tokens/ids into a list of sentences (tokens/ids). :param seq: list of tokens/ids. :param excl_symbols: tokens/ids which should be excluded from the final result. :param end_symbol: self-explanatory. :param remove_end_symbol: whether to remove from each sentence the end symbol. :return: list of lists, where each sub-list contains tokens/ids. """ excl_symbols = excl_symbols if excl_symbols else {} assert end_symbol not in excl_symbols coll = [] curr_sent = [] for symbol in seq: if symbol in excl_symbols: continue if symbol == end_symbol: if not remove_end_symbol: curr_sent.append(symbol) coll.append(curr_sent) curr_sent = [] else: curr_sent.append(symbol) if curr_sent: coll.append(curr_sent) return coll
a87da4bb5c34882d882832380f3831929ad41415
3,786
def param_value(memory, position, mode): """Get the value of a param according to its mode""" if mode == 0: # position mode return memory[memory[position]] elif mode == 1: # immediate mode return memory[position] else: raise ValueError("Unknown mode : ", mode)
e02ed7e1baea57af4b08c408b6decadee9c72162
3,787
import math def longitude_to_utm_epsg(longitude): """ Return Proj4 EPSG for a given longitude in degrees """ zone = int(math.floor((longitude + 180) / 6) + 1) epsg = '+init=EPSG:326%02d' % (zone) return epsg
f17a03514cc9caf99e1307c0382d7b9fa0289330
3,791
def compute_node_depths(tree): """Returns a dictionary of node depths for each node with a label.""" res = {} for leaf in tree.leaf_node_iter(): cnt = 0 for anc in leaf.ancestor_iter(): if anc.label: cnt += 1 res[leaf.taxon.label] = cnt return res
a633f77d0fff1f29fe95108f96ccc59817179ddd
3,792
import hashlib def calc_sign(string): """str/any->str return MD5. From: Biligrab, https://github.com/cnbeining/Biligrab MIT License""" return str(hashlib.md5(str(string).encode('utf-8')).hexdigest())
3052e18991b084b3a220b0f3096d9c065cf4661c
3,794
def remove_prefix(utt, prefix): """ Check that utt begins with prefix+" ", and then remove. Inputs: utt: string prefix: string Returns: new utt: utt with the prefix+" " removed. """ try: assert utt[: len(prefix) + 1] == prefix + " " except AssertionError as e: print("ERROR: utterance '%s' does not start with '%s '" % (utt, prefix)) print(repr(utt[: len(prefix) + 1])) print(repr(prefix + " ")) raise e return utt[len(prefix) + 1:]
fa6717e34c6d72944636f6b319b98574f2b41a69
3,795
def format_ucx(name, idx): """ Formats a name and index as a collider """ # one digit of zero padding idxstr = str(idx).zfill(2) return "UCX_%s_%s" % (name, idxstr)
c3365bf66bca5fe7ab22bd642ae59dfb618be251
3,796
def eval_add(lst): """Evaluate an addition expression. For addition rules, the parser will return [number, [[op, number], [op, number], ...]] To evaluate that, we start with the first element of the list as result value, and then we iterate over the pairs that make up the rest of the list, adding or subtracting depending on the operator. """ first = lst[0] result = first for n in lst[1]: if n[0] == '+': result += n[1] else: result -= n[1] return result
5d6972ccc7a0857da224e30d579b159e89fb8dce
3,799
def validate_target_types(target_type): """ Target types validation rule. Property: SecretTargetAttachment.TargetType """ VALID_TARGET_TYPES = ( "AWS::RDS::DBInstance", "AWS::RDS::DBCluster", "AWS::Redshift::Cluster", "AWS::DocDB::DBInstance", "AWS::DocDB::DBCluster", ) if target_type not in VALID_TARGET_TYPES: raise ValueError( "Target type must be one of : %s" % ", ".join(VALID_TARGET_TYPES) ) return target_type
db33903e36849fb8f97efecb95f1bbfa8150ed6f
3,800
def cprint(*objects, **kwargs): """Apply Color formatting to output in terminal. Same as builtin print function with added 'color' keyword argument. eg: cprint("data to print", color="red", sep="|") available colors: black red green yellow blue pink cyan white no-color """ colors = { "black": "\033[0;30m", "red": "\033[0;31m", "green": "\033[0;92m", "yellow": "\033[0;93m", "blue": "\033[0;34m", "pink": "\033[0;95m", "cyan": "\033[0;36m", "white": "\033[0;37m", "no-color": "\033[0m" } color = kwargs.pop('color', 'no-color') return print(colors[color], *objects, colors['no-color'], **kwargs)
42d0f2357da7f84404a888cf717a737d86609aa4
3,801
def HHMMSS_to_seconds(string): """Converts a colon-separated time string (HH:MM:SS) to seconds since midnight""" (hhs,mms,sss) = string.split(':') return (int(hhs)*60 + int(mms))*60 + int(sss)
f7a49ad5d14eb1e26acba34946830710384780f7
3,812
def _replace_token_range(tokens, start, end, replacement): """For a range indicated from start to end, replace with replacement.""" tokens = tokens[:start] + replacement + tokens[end:] return tokens
2848a3ad2d448e062facf78264fb1d15a1c3985c
3,813
def center_crop(im, size, is_color=True): """ Crop the center of image with size. Example usage: .. code-block:: python im = center_crop(im, 224) :param im: the input image with HWC layout. :type im: ndarray :param size: the cropping size. :type size: int :param is_color: whether the image is color or not. :type is_color: bool """ h, w = im.shape[:2] h_start = (h - size) / 2 w_start = (w - size) / 2 h_end, w_end = h_start + size, w_start + size if is_color: im = im[h_start:h_end, w_start:w_end, :] else: im = im[h_start:h_end, w_start:w_end] return im
ac280efd4773613f08632fe836eecc16be23adf8
3,815
def num(value): """Parse number as float or int.""" value_float = float(value) try: value_int = int(value) except ValueError: return value_float return value_int if value_int == value_float else value_float
a2ea65c2afa0005dbe4450cb383731b029cb68df
3,816
def __format_event_start_date_and_time(t): """Formats datetime into e.g. Tue Jul 30 at 5PM""" strftime_format = "%a %b %-d at %-I:%M %p" return t.strftime(strftime_format)
4db0b37351308dfe1e7771be9a9ad8b98f2defa6
3,817
from typing import List from typing import MutableMapping def parse_template_mapping( template_mapping: List[str] ) -> MutableMapping[str, str]: """Parses a string template map from <key>=<value> strings.""" result = {} for mapping in template_mapping: key, value = mapping.split("=", 1) result[key] = value return result
49eb029a842be7c31d33444235452ecad4701476
3,818
def shorten_str(string, length=30, end=10): """Shorten a string to the given length.""" if string is None: return "" if len(string) <= length: return string else: return "{}...{}".format(string[:length - end], string[- end:])
d52daec3058ddced26805f259be3fc6139b5ef1f
3,824
def parse_healing_and_target(line): """Helper method that finds the amount of healing and who it was provided to""" split_line = line.split() target = ' '.join(split_line[3:split_line.index('for')]) target = target.replace('the ', '') amount = int(split_line[split_line.index('for')+1]) return [amount, target]
3f11c0807ab87d689e47a79fc7e12b32c00dbd95
3,828
import torch def as_mask(indexes, length): """ Convert indexes into a binary mask. Parameters: indexes (LongTensor): positive indexes length (int): maximal possible value of indexes """ mask = torch.zeros(length, dtype=torch.bool, device=indexes.device) mask[indexes] = 1 return mask
0235d66f9ee5bdc7447819122b285d29efd238c9
3,830
def check_pass(value): """ This test always passes (it is used for 'checking' things like the workshop address, for which no sensible validation is feasible). """ return True
aa3a5f536b5bc729dc37b7f09c3b997c664b7481
3,831
def get_trader_fcas_availability_agc_status_condition(params) -> bool: """Get FCAS availability AGC status condition. AGC must be enabled for regulation FCAS.""" # Check AGC status if presented with a regulating FCAS offer if params['trade_type'] in ['L5RE', 'R5RE']: # AGC is active='1', AGC is inactive='0' return True if params['agc_status'] == '1' else False # Return True if a presented with a contingency FCAS offer (AGC doesn't need to be enabled) else: return True
fa73ae12a0934c76f12c223a05161280a6dc01f1
3,833
def normalize_field_names(fields): """ Map field names to a normalized form to check for collisions like 'coveredText' vs 'covered_text' """ return set(s.replace('_','').lower() for s in fields)
55bdac50fd1fcf23cfec454408fbcbbae96e507e
3,836
def remove_comments(s): """ Examples -------- >>> code = ''' ... # comment 1 ... # comment 2 ... echo foo ... ''' >>> remove_comments(code) 'echo foo' """ return "\n".join(l for l in s.strip().split("\n") if not l.strip().startswith("#"))
1d3e1468c06263d01dd204c5ac89235a17f50972
3,840
import pathlib def is_dicom(path: pathlib.Path) -> bool: """Check if the input is a DICOM file. Args: path (pathlib.Path): Path to the file to check. Returns: bool: True if the file is a DICOM file. """ path = pathlib.Path(path) is_dcm = path.suffix.lower() == ".dcm" is_dcm_dir = path.is_dir() and any( p.suffix.lower() == ".dcm" for p in path.iterdir() ) return is_dcm or is_dcm_dir
1e20ace9c645a41817bf23a667bd4e1ac815f63f
3,842
def axLabel(value, unit): """ Return axis label for given strings. :param value: Value for axis label :type value: int :param unit: Unit for axis label :type unit: str :return: Axis label as \"<value> (<unit>)\" :rtype: str """ return str(value) + " (" + str(unit) + ")"
cc553cf4334222a06ae4a2bcec5ec5acb9668a8f
3,844
def extract_tag(inventory, url): """ extract data from sphinx inventory. The extracted datas come from a C++ project documented using Breathe. The structure of the inventory is a dictionary with the following keys - cpp:class (class names) - cpp:function (functions or class methods) - cpp:type (type names) each value of this dictionary is again a dictionary with - key : the name of the element - value : a tuple where the third index is the url to the corresponding documentation Parameters ---------- inventory : dict sphinx inventory url : url of the documentation Returns ------- dictionary with keys class, class_methods, func, type but now the class methods are with their class. """ classes = {} class_methods = {} functions = {} types = {} get_relative_url = lambda x: x[2].replace(url, '') for c, v in inventory.get('cpp:class', {}).items(): classes[c] = get_relative_url(v) class_methods[c] = {} for method, v in inventory.get('cpp:function', {}).items(): found = False for c in class_methods.keys(): find = c + '::' if find in method: class_methods[c][method.replace(find, '')] = get_relative_url(v) found = True break if not found: functions[method] = get_relative_url(v) for typename, v in inventory.get('cpp:type', {}).items(): types[typename] = get_relative_url(v) return {'class': classes, 'class_methods': class_methods, 'func':functions, 'type': types }
dcda1869fb6a44bea3b17f1d427fe279ebdc3a11
3,847
from collections import Counter from typing import Iterable def sock_merchant(arr: Iterable[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([6, 5, 2, 3, 5, 2, 2, 1, 1, 5, 1, 3, 3, 3, 5]) 6 """ count = Counter(arr).values() ret = sum(n // 2 for n in count) return ret
1b3b8d37ccb3494ed774e26a41ebba32c87a632c
3,857
def int_from_bin_list(lst): """Convert a list of 0s and 1s into an integer Args: lst (list or numpy.array): list of 0s and 1s Returns: int: resulting integer """ return int("".join(str(x) for x in lst), 2)
a41b2578780019ed1266442d76462fb89ba2a0fb
3,858
def sort_ipv4_addresses_with_mask(ip_address_iterable): """ Sort IPv4 addresses in CIDR notation | :param iter ip_address_iterable: An iterable container of IPv4 CIDR notated addresses | :return list : A sorted list of IPv4 CIDR notated addresses """ return sorted( ip_address_iterable, key=lambda addr: ( int(addr.split('.')[0]), int(addr.split('.')[1]), int(addr.split('.')[2]), int(addr.split('.')[3].split('/')[0]), int(addr.split('.')[3].split('/')[1]) ) )
97517b2518b81cb8ce4cfca19c5512dae6bae686
3,864
def script_with_queue_path(tmpdir): """ Pytest fixture to return a path to a script with main() which takes a queue and procedure as arguments and adds procedure process ID to queue. """ path = tmpdir.join("script_with_queue.py") path.write( """ def main(queue, procedure): queue.put(procedure.pid) """ ) return f"file://{str(path)}"
7c2c2b4c308f91d951496c53c9bdda214f64c776
3,866
import re def parseCsv(file_content): """ parseCsv ======== parser a string file from Shimadzu analysis, returning a dictonary with current, livetime and sample ID Parameters ---------- file_content : str shimadzu output csv content Returns ------- dic dic with irradiation parameters """ irradiation_parameters = {} irradiation_parameters['sample'] = file_content.split(',')[0].split(':')[1].replace("\"", "").strip() irradiation_parameters['current'] = re.sub(' +',' ',file_content.split(',')[12]).split(' ')[3] irradiation_parameters['current'] = int(re.findall('\d+', irradiation_parameters['current'])[0]) irradiation_parameters['livetime'] = int(re.sub(' +',' ',file_content.split(',')[12]).split(' ')[13]) return(irradiation_parameters)
cc20a906c23093994ce53358d92453cd4a9ab459
3,869
import re def matchatleastone(text, regexes): """Returns a list of strings that match at least one of the regexes.""" finalregex = "|".join(regexes) result = re.findall(finalregex, text) return result
1e0775413189931fc48a3dc82c23f0ffe28b333e
3,874
def get_keys(mapping, *keys): """Return the values corresponding to the given keys, in order.""" return (mapping[k] for k in keys)
e3b8bdbdff47c428e4618bd4ca03c7179b9f4a2b
3,876
def total_examples(X): """Counts the total number of examples of a sharded and sliced data object X.""" count = 0 for i in range(len(X)): for j in range(len(X[i])): count += len(X[i][j]) return count
faf42a940e4413405d97610858e13496eb848eae
3,877
def make_linear_colorscale(colors): """ Makes a list of colors into a colorscale-acceptable form For documentation regarding to the form of the output, see https://plot.ly/python/reference/#mesh3d-colorscale """ scale = 1.0 / (len(colors) - 1) return [[i * scale, color] for i, color in enumerate(colors)]
dabd2a2a9d6bbf3acfcabcac52246048332fae73
3,884
def odd_occurrence_parity_set(arr): """ A similar implementation to the XOR idea above, but more naive. As we iterate over the passed list, a working set keeps track of the numbers that have occurred an odd number of times. At the end, the set will only contain one number. Though the worst-case time complexity is the same as the hashmap method implemented below, this will probably be significantly faster as dictionaries have much longer lookup times than sets. Space complexity: $O(n)$; Time complexity: $O(n)$. Parameters ---------- arr : integer Returns ------- integer """ seen_odd_times = set() for num in arr: if num in seen_odd_times: seen_odd_times.remove(num) else: seen_odd_times.add(num) return list(seen_odd_times)[0]
57f9362e05786724a1061bef07e49635b1b2b142
3,886
import copy def _merge_meta(base, child): """Merge the base and the child meta attributes. List entries, such as ``indexes`` are concatenated. ``abstract`` value is set to ``True`` only if defined as such in the child class. Args: base (dict): ``meta`` attribute from the base class. child (dict): ``meta`` attribute from the child class. Returns: dict: Merged metadata. """ base = copy.deepcopy(base) child.setdefault('abstract', False) for key, value in child.items(): if isinstance(value, list): base.setdefault(key, []).extend(value) else: base[key] = value return base
ba219b8091244a60658bee826fbef5003d3f7883
3,887
def trunc(x, y, w, h): """Truncates x and y coordinates to live in the (0, 0) to (w, h) Args: x: the x-coordinate of a point y: the y-coordinate of a point w: the width of the truncation box h: the height of the truncation box. """ return min(max(x, 0), w - 1), min(max(y, 0), h - 1)
3edecdfbd9baf24f8b4f3f71b9e35a222c6be1ea
3,889
def param_to_secopt(param): """Convert a parameter name to INI section and option. Split on the first dot. If not dot exists, return name as option, and None for section.""" sep = '.' sep_loc = param.find(sep) if sep_loc == -1: # no dot in name, skip it section = None option = param else: section = param[0:sep_loc] option = param[sep_loc+1:] return (section, option)
7d7e2b03cb67ed26d184f85f0328236674fa6497
3,894
def rotate_char(c, n): """Rotate a single character n places in the alphabet n is an integer """ # alpha_number and new_alpha_number will represent the # place in the alphabet (as distinct from the ASCII code) # So alpha_number('a')==0 # alpha_base is the ASCII code for the first letter of the # alphabet (different for upper and lower case) if c.islower(): alpha_base = ord('a') elif c.isupper(): alpha_base = ord('A') else: # Don't rotate character if it's not a letter return c # Position in alphabet, starting with a=0 alpha_number = ord(c) - alpha_base # New position in alphabet after shifting # The % 26 at the end is for modulo 26, so if we shift it # past z (or a to the left) it'll wrap around new_alpha_number = (alpha_number + n) % 26 # Add the new position in the alphabet to the base ASCII code for # 'a' or 'A' to get the new ASCII code, and use chr() to convert # that code back to a letter return chr(alpha_base + new_alpha_number)
b1259722c7fb2a60bd943e86d87163866432539f
3,896
import itertools def _get_indices(A): """Gets the index for each element in the array.""" dim_ranges = [range(size) for size in A.shape] if len(dim_ranges) == 1: return dim_ranges[0] return itertools.product(*dim_ranges)
dc2e77c010a6cfd7dbc7b7169f4bd0d8da62b891
3,899
def slices(series, length): """ Given a string of digits, output all the contiguous substrings of length n in that string in the order that they appear. :param series string - string of digits. :param length int - the length of the series to find. :return list - List of substrings of specified length from series. """ if len(series) < length: raise ValueError("Length requested is shorter than series.") if length < 1: raise ValueError("Length requested is less than 1.") substrings = [] for index, number in enumerate(series): sub = series[index:index + length] if len(sub) == length: substrings.append(sub) return substrings
ea2d1caf26a3fc2e2a57858a7364b4ebe67297d6
3,902
from typing import Tuple def get_subpixel_indices(col_num: int) -> Tuple[int, int, int]: """Return a 3-tuple of 1-indexed column indices representing subpixels of a single pixel.""" offset = (col_num - 1) * 2 red_index = col_num + offset green_index = col_num + offset + 1 blue_index = col_num + offset + 2 return red_index, blue_index, green_index
cb4a1b9a4d27c3a1dad0760267e6732fe2d0a0da
3,905
def compute_t(i, automata_list, target_events): """ Compute alphabet needed for processing L{automata_list}[i-1] in the sequential abstraction procedure. @param i: Number of the automaton in the L{automata_list} @type i: C{int} in range(1, len(automata_list)+1) @param automata_list: List of automata @type automata_list: C{list} of L{Automaton} @param target_events: List of events to preserve after abstraction @type target_events: C{set} of L{Event} @return: New alphabet for the next step in sequential abstraction @rtype: C{set} of L{Event} """ processed = set() for j in range(0, i): processed = processed.union(automata_list[j].alphabet) unprocessed = target_events.copy() for j in range(i, len(automata_list)): unprocessed = unprocessed.union(automata_list[j].alphabet) result = processed.intersection(unprocessed) processed.clear() unprocessed.clear() return result
88fc64aaf917d23a29e9400cf29705e6b20665c3
3,914
def strip_new_line(str_json): """ Strip \n new line :param str_json: string :return: string """ str_json = str_json.replace('\n', '') # kill new line breaks caused by triple quoted raw strings return str_json
f2faaa80dca000586a32a37cdf3dff793c0a2d9b
3,915
def getObjectInfo(fluiddb, about): """ Gets object info for an object with the given about tag. """ return fluiddb.about[about].get()
8614edaf44944fcc11882ac2fcaa31ba31d48d30
3,924
def is_iterable(obj): """ Return true if object has iterator but is not a string :param object obj: Any object :return: True if object is iterable but not a string. :rtype: bool """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
c7a1353f7f62a567a65d0c4752976fefde6e1904
3,932
def f_all(predicate, iterable): """Return whether predicate(i) is True for all i in iterable >>> is_odd = lambda num: (num % 2 == 1) >>> f_all(is_odd, []) True >>> f_all(is_odd, [1, 3, 5, 7, 9]) True >>> f_all(is_odd, [2, 1, 3, 5, 7, 9]) False """ return all(predicate(i) for i in iterable)
c0a0e52587a7afc9da143ac936aab87ad531b455
3,938
from typing import List from typing import Tuple from typing import Set from typing import Dict def _recursive_replace(data): """Searches data structure and replaces 'nan' and 'inf' with respective float values""" if isinstance(data, str): if data == "nan": return float("nan") if data == "inf": return float("inf") if isinstance(data, List): return [_recursive_replace(v) for v in data] if isinstance(data, Tuple): return tuple([_recursive_replace(v) for v in data]) if isinstance(data, Set): return set([_recursive_replace(v) for v in data]) if isinstance(data, Dict): return {k: _recursive_replace(v) for k, v in data.items()} return data
b5c21d806b462070b2d1eec7d91a5dc700f6b0ed
3,939
def audio_sort_key(ex): """Sort using duration time of the sound spectrogram.""" return ex.src.size(1)
ec940df6bf2b74962f221b84717f51beba5c4f5f
3,942
def is_versioned(obj): """ Check if a given object is versioned by inspecting some of its attributes. """ # before any heuristic, newer versions of RGW will tell if an obj is # versioned so try that first if hasattr(obj, 'versioned'): return obj.versioned if not hasattr(obj, 'VersionedEpoch'): # overly paranoid here, an object that is not versioned should *never* # have a `VersionedEpoch` attribute if getattr(obj, 'version_id', None): if obj.version_id is None: return False return True # probably will never get here return False return True
7f5ad90ffce6a8efde50dba47cdc63673ec79f60
3,944
import ast def maybe_get_docstring(node: ast.AST): """Get docstring from a constant expression, or return None.""" if ( isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str) ): return node.value.value elif ( isinstance(node, ast.Expr) and isinstance(node.value, ast.Str) ): return node.value.s
23171c739f3c9ae6d62ecf3307ac7c3409852d6b
3,947
def _find(xs, predicate): """Locate an item in a list based on a predicate function. Args: xs (list) : List of data predicate (function) : Function taking a data item and returning bool Returns: (object|None) : The first list item that predicate returns True for or None """ for x in xs: if predicate(x): return x return None
94d8dd47e54e1887f67c5f5354d05dc0c294ae52
3,949
def _extract_action_num_and_node_id(m): """Helper method: Extract *action_num* and *node_id* from the given regex match. Convert *action_num* to a 0-indexed integer.""" return dict( action_num=(int(m.group('action_num')) - 1), node_id=m.group('node_id'), )
f1e5f0b81d6d82856b7c00d67270048e0e4caf38
3,953
def sse_pack(d): """For sending sse to client. Formats a dictionary into correct form for SSE""" buf = '' for k in ['retry','id','event','data']: if k in d.keys(): buf += '{}: {}\n'.format(k, d[k]) return buf + '\n'
a497c7ab919115d59d49f25abfdb9d88b0963af3
3,961
def filter_dictionary(dictionary, filter_func): """ returns the first element of `dictionary` where the element's key pass the filter_func. filter_func can be either a callable or a value. - if callable filtering is checked with `test(element_value)` - if value filtering is checked with `element_value == filter_func` :param dictionary: :param test: :return: >>> filter_dictionary({'arg': 'test'}, 'test') 'arg' >>> filter_dictionary({}, 'test') >>> def is_test(value): ... return value == 'test' >>> filter_dictionary({'arg': 'test'}, is_test) 'arg' """ if not callable(filter_func): test_func = lambda x: x == filter_func else: test_func = filter_func for key, value in dictionary.iteritems(): if test_func(value): return key
f5fa77a51241323845eb9a59adc9df7f662f287b
3,964
from typing import List def two_loops(N: List[int]) -> List[int]: """Semi-dynamic programming approach using O(2n): - Calculate the product of all items before item i - Calculate the product of all items after item i - For each item i, multiply the products for before and after i L[i] = N[i-1] * L[i-1] if i != 0 else 1 R[j] = N[j+1] * R[j+1] if j != (len(N) - 1) else 1 A[i] = L[i] * R[i] N[0] = 3 N[1] = 7 N[2] = 1 N[3] = 4 N[4] = 8 N[5] = 9 L[0] = 1 = 1 L[1] = (1) * 3 = 3 L[2] = (3) * 7 = 21 L[3] = (21) * 1 = 21 L[4] = (21) * 4 = 84 L[5] = (84) * 8 = 672 R[5] = 1 = 1 R[4] = (1) * 9 = 9 R[3] = (9) * 8 = 72 R[2] = (72) * 4 = 288 R[1] = (288) * 1 = 288 R[0] = (288) * 7 = 2016 A = [L[0]*R[0], L[1]*R[1], L[2]*R[2], L[3]*R[3], L[4]*R[4], L[5]*R[5]] A = [2016, 864, 6048, 1512, 756, 672] """ items_len = len(N) of_left = [1 for _ in range(items_len)] of_right = [1 for _ in range(items_len)] for i in range(items_len): j = (items_len - 1) - i # Invert i; start counting from len(N) to 0. of_left[i] = N[i-1] * of_left[i-1] if i != 0 else 1 of_right[j] = N[j+1] * of_right[j+1] if i != 0 else 1 return list(map(lambda p: p[0] * p[1], zip(of_left, of_right)))
3620aa19833b2e967b2c295fa53ba39bf3b6b70d
3,968
def rgb_to_hex(r, g, b): """Turn an RGB float tuple into a hex code. Args: r (float): R value g (float): G value b (float): B value Returns: str: A hex code (no #) """ r_int = round((r + 1.0) / 2 * 255) g_int = round((g + 1.0) / 2 * 255) b_int = round((b + 1.0) / 2 * 255) r_txt = "%02x" % r_int b_txt = "%02x" % b_int g_txt = "%02x" % g_int return r_txt + g_txt + b_txt
a5181c475c798bbd03020d81da10d8fbf86cc396
3,969
def odd(x): """True if x is odd.""" return (x & 1)
9cd383ea01e0fed56f6df42648306cf2415f89e9
3,971
import re def remove_conjunction(conjunction: str, utterance: str) -> str: """Remove the specified conjunction from the utterance. For example, remove the " and" left behind from extracting "1 hour" and "30 minutes" from "for 1 hour and 30 minutes". Leaving it behind can confuse other intent parsing logic. Args: conjunction: translated conjunction (like the word "and") to be removed from utterance utterance: Full request, e.g. "set a 30 second timer" Returns: The same utterance with any dashes replaced by spaces. """ pattern = r"\s\s{}".format(conjunction) remaining_utterance = re.sub(pattern, "", utterance, flags=re.IGNORECASE) return remaining_utterance
67313565c7da2eadc4411854d6ee6cb467ee7159
3,973
def othertitles(hit): """Split a hit.Hit_def that contains multiple titles up, splitting out the hit ids from the titles.""" id_titles = hit.Hit_def.text.split('>') titles = [] for t in id_titles[1:]: fullid, title = t.split(' ', 1) hitid, id = fullid.split('|', 2)[1:3] titles.append(dict(id = id, hitid = hitid, fullid = fullid, title = title)) return titles
fa5bbb47d26adbc61817e78e950e81cc05eca4a6
3,974
from typing import List def read_plaintext_inputs(path: str) -> List[str]: """Read input texts from a plain text file where each line corresponds to one input""" with open(path, 'r', encoding='utf8') as fh: inputs = fh.read().splitlines() print(f"Done loading {len(inputs)} inputs from file '{path}'") return inputs
27b00f4dfcdf4d76e04f08b6e74c062f2f7374d0
3,975
def _file_path(ctx, val): """Return the path of the given file object. Args: ctx: The context. val: The file object. """ return val.path
7c930f2511a0950e29ffc327e85cf9b2b3077c02
3,977
def total_angular_momentum(particles): """ Returns the total angular momentum of the particles set. >>> from amuse.datamodel import Particles >>> particles = Particles(2) >>> particles.x = [-1.0, 1.0] | units.m >>> particles.y = [0.0, 0.0] | units.m >>> particles.z = [0.0, 0.0] | units.m >>> particles.vx = [0.0, 0.0] | units.ms >>> particles.vy = [-1.0, 1.0] | units.ms >>> particles.vz = [0.0, 0.0] | units.ms >>> particles.mass = [1.0, .5] | units.kg >>> particles.total_angular_momentum() quantity<[0.0, 0.0, 1.5] m**2 * kg * s**-1> """ # equivalent to: # lx=(m*(y*vz-z*vy)).sum() # ly=(m*(z*vx-x*vz)).sum() # lz=(m*(x*vy-y*vx)).sum() return (particles.mass.reshape((-1,1)) *particles.position.cross(particles.velocity)).sum(axis=0)
8eca23b7b1a8fc8a7722543f9193f0e4a3397f24
3,979
def find_contiguous_set(target_sum: int, values: list[int]) -> list[int]: """Returns set of at least 2 contiguous values that add to target sum.""" i = 0 set_ = [] sum_ = 0 while sum_ <= target_sum: sum_ += values[i] set_.append(values[i]) if sum_ == target_sum and len(set_) >= 2: return set_ i += 1 return []
64b6c1f99946856a33a79fed3d43395a5a9c1000
3,981
def move_character(character: dict, direction_index=None, available_directions=None) -> tuple: """ Change character's coordinates. :param character: a dictionary :param direction_index: a non-negative integer, optional :param available_directions: a list of strings, optional :precondition: character keys must contain "X-coordinate" and "Y-coordinate" :precondition: character values must be integers :precondition: direction_index must be a non-negative integer validated by validate_option function or None :precondition: availabe_directions each item must be either "north", "south", "east" or "west", or None :postcondition: updates character X or Y coordinate based on direction choice if availabe_directions is not None :postcondition: makes character X or Y coordinate be equal to the previous coordinates :return: new character's coordinates as a tuple >>> protagonist = {"Y-coordinate": 1, "X-coordinate": 1, "Previous coordinates": (0, 1)} >>> move_character(protagonist, 0, ["south", "west"]) (2, 1) >>> protagonist = {"Y-coordinate": 1, "X-coordinate": 1, "Previous coordinates": (0, 1)} >>> move_character(protagonist) (0, 1) """ directions_dictionary = {"north": -1, "south": 1, "west": -1, "east": 1} if available_directions is not None: direction = available_directions[direction_index] character["Previous coordinates"] = character["Y-coordinate"], character["X-coordinate"] if direction in "north south": character["Y-coordinate"] += directions_dictionary[direction] else: character["X-coordinate"] += directions_dictionary[direction] else: character["Y-coordinate"] = character["Previous coordinates"][0] character["X-coordinate"] = character["Previous coordinates"][1] return character["Y-coordinate"], character["X-coordinate"]
cc5cc3115437d0dc4e9b7ba7845565ee8147be30
3,982
def scrap_insta_description(inst) -> str: """ Scrap description from instagram account HTML. """ description = inst.body.div.section.main.div.header.section.find_all( 'div')[4].span.get_text() return description
898fa0d1cb44606374b131b8b471178a22ab74ed
3,983
def __get_from_imports(import_tuples): """ Returns import names and fromlist import_tuples are specified as (name, fromlist, ispackage) """ from_imports = [(tup[0], tup[1]) for tup in import_tuples if tup[1] is not None and len(tup[1]) > 0] return from_imports
28df8225ad9440386342c38657944cfe7ac3d3ca
3,985
import random import hmac def hash_password(password, salthex=None, reps=1000): """Compute secure (hash, salthex, reps) triplet for password. The password string is required. The returned salthex and reps must be saved and reused to hash any comparison password in order for it to match the returned hash. The salthex string will be chosen randomly if not provided, and if provided must be an even-length string of hexadecimal digits, recommended length 16 or greater. E.g. salt="([0-9a-z][0-9a-z])*" The reps integer must be 1 or greater and should be a relatively large number (default 1000) to slow down brute-force attacks.""" if not salthex: salthex = ''.join([ "%02x" % random.randint(0, 0xFF) for d in range(0,8) ]) salt = [] for p in range(0, len(salthex), 2): salt.append(int(salthex[p:p+2], 16)) salt = bytes(salt) if reps < 1: reps = 1 msg = password.encode() for r in range(0,reps): msg = hmac.HMAC(salt, msg, digestmod='MD5').hexdigest().encode() return (msg.decode(), salthex, reps)
cac468818560ed52b415157dde71d5416c34478c
3,988
def mixed_social_welfare(game, mix): """Returns the social welfare of a mixed strategy profile""" return game.expected_payoffs(mix).dot(game.num_role_players)
72c465211bdc79c9fcf2b1b9d8c7dd5abae5d8df
3,993
def _rec_filter_to_info(line): """Move a DKFZBias filter to the INFO field, for a record. """ parts = line.rstrip().split("\t") move_filters = {"bSeq": "strand", "bPcr": "damage"} new_filters = [] bias_info = [] for f in parts[6].split(";"): if f in move_filters: bias_info.append(move_filters[f]) elif f not in ["."]: new_filters.append(f) if bias_info: parts[7] += ";DKFZBias=%s" % ",".join(bias_info) parts[6] = ";".join(new_filters or ["PASS"]) return "\t".join(parts) + "\n"
496056126bdf390a6213dfad5c40c4a14ec35caa
3,996
def get(isamAppliance, cert_dbase_id, check_mode=False, force=False): """ Get details of a certificate database """ return isamAppliance.invoke_get("Retrieving all current certificate database names", "/isam/ssl_certificates/{0}/details".format(cert_dbase_id))
34ade7c42fcc1b1409b315f8748105ee99157986
4,000
import random def t06_ManyGetPuts(C, pks, crypto, server): """Many clients upload many files and their contents are checked.""" clients = [C("c" + str(n)) for n in range(10)] kvs = [{} for _ in range(10)] for _ in range(200): i = random.randint(0, 9) uuid1 = "%08x" % random.randint(0, 100) uuid2 = "%08x" % random.randint(0, 100) clients[i].upload(str(uuid1), str(uuid2)) kvs[i][str(uuid1)] = str(uuid2) good = total = 0 # verify integrity for i, (c, kv) in enumerate(zip(clients, kvs)): for k, v in kv.items(): vv = c.download(k) if vv == v: good += 1 total += 1 return float(good) / total
384aa2b03169da613b25d2da60cdd1ec007aeed5
4,002
import xxhash def hash_array(kmer): """Return a hash of a numpy array.""" return xxhash.xxh32_intdigest(kmer.tobytes())
9761316333fdd9f28e74c4f1975adfca1909f54a
4,004
def idxs_of_duplicates(lst): """ Returns the indices of duplicate values. """ idxs_of = dict({}) dup_idxs = [] for idx, value in enumerate(lst): idxs_of.setdefault(value, []).append(idx) for idxs in idxs_of.values(): if len(idxs) > 1: dup_idxs.extend(idxs) return dup_idxs
adc8a0b0223ac78f0c8a6edd3d60acfaf7ca4c04
4,007
def aslist(l): """Convenience function to wrap single items and lists, and return lists unchanged.""" if isinstance(l, list): return l else: return [l]
99ccef940229d806d27cb8e429da9c85c44fed07
4,008
def enough_data(train_data, test_data, verbose=False): """Check if train and test sets have any elements.""" if train_data.empty: if verbose: print('Empty training data\n') return False if test_data.empty: if verbose: print('Empty testing data\n') return False return True
f11014d83379a5df84a67ee3b8f1e85b23c058f7
4,011
def inc(x): """ Add one to the current value """ return x + 1
c8f9a68fee2e8c1a1d66502ae99e42d6034b6b5c
4,015
from datetime import datetime def parse_iso8601(dtstring: str) -> datetime: """naive parser for ISO8061 datetime strings, Parameters ---------- dtstring the datetime as string in one of two formats: * ``2017-11-20T07:16:29+0000`` * ``2017-11-20T07:16:29Z`` """ return datetime.strptime( dtstring, '%Y-%m-%dT%H:%M:%SZ' if len(dtstring) == 20 else '%Y-%m-%dT%H:%M:%S%z')
415a4f3a9006109e31ea344cf99e885a3fd2738d
4,026
import re def is_youtube_url(url: str) -> bool: """Checks if a string is a youtube url Args: url (str): youtube url Returns: bool: true of false """ match = re.match(r"^(https?\:\/\/)?(www\.youtube\.com|youtu\.be)\/.+$", url) return bool(match)
97536b8e7267fb5a72c68f242b3f5d6cbd1b9492
4,031
def item_len(item): """return length of the string format of item""" return len(str(item))
7d68629a5c2ae664d267844fc90006a7f23df1ba
4,033
def is_numeric(array): """Return False if any value in the array or list is not numeric Note boolean values are taken as numeric""" for i in array: try: float(i) except ValueError: return False else: return True
2ab0bb3e6c35e859e54e435671b5525c6392f66c
4,034