content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Type from typing import Hashable def _lookup(key: str, typ: Type, *args, **kwargs) -> Hashable: """ Gets the value of the given key in args, defaulting to the first positional. :param key: key to find value of in args. :param typ: type that dispatch is being perform on. :param args: positional args. :param kwargs: keyword args. :return: value of the key in the given args. """ if key in kwargs: value = kwargs[key] else: try: if typ.__qualname__.endswith('.__new__'): value = args[1] else: value = args[0] except IndexError: raise TypeError(f'missing dispatch parameter {key!r} on {typ.__name__}') return value
195e95cd1d77137890d0608195677c344e698ad7
701,750
def MakeStatefulPolicyPreservedStateDiskEntry(messages, stateful_disk_dict): """Create StatefulPolicyPreservedState from a list of device names.""" disk_device = messages.StatefulPolicyPreservedStateDiskDevice() if stateful_disk_dict.get('auto-delete'): disk_device.autoDelete = ( stateful_disk_dict.get('auto-delete').GetAutoDeleteEnumValue( messages.StatefulPolicyPreservedStateDiskDevice .AutoDeleteValueValuesEnum)) # Add all disk_devices to map return messages.StatefulPolicyPreservedState.DisksValue.AdditionalProperty( key=stateful_disk_dict.get('device-name'), value=disk_device)
10b1fcb79b46455bef8bbfba90c84bcdb80773df
701,751
def _doc(from_func): """copy doc from one function to another use as a decorator eg:: @_doc(file.tell) def tell(..): ... """ def decorator(to_func): to_func.__doc__ = from_func.__doc__ return to_func return decorator
907a12da3700cee02e4f369d5230bd8be04e55ea
701,752
import re def validate_time_string(value, is_list): """ Checks that a "time string" quant is correctly formatted. A time string can contain three kinds of expressions, separated by + or -: Base values, which are just numeric (with an optional exponent on e form) Delta values, which are the same as above with a '*i' or 'i' suffix Variables, which are strings that are formatted according to the variable name rules If the string is correctly formatted, a polished version is returned. Otherwise, the original string is returned with an 'INVALID: ' prefix. """ # Strip the input down to the essential part value = value.replace('INVALID:', '').strip() input_str = value.replace(' ', '') # Split the string if the quant accepts multiple values if is_list: strings = input_str.split(',') else: strings = [input_str] result = '' for idx, s in enumerate(strings): accum_string = '' if idx == 0 else ', ' first = True if len(s) == 0: return f'INVALID: {value}' while len(s) > 0: prefix = '[+-]?' if first else '[+-]' var_rex = re.compile(prefix + r'[A-Za-z_]+[0-9A-Za-z_]*(\*i)?') var_match = var_rex.match(s) if var_match: # Remove the matched part from input match_str = var_match.group() match_len = len(match_str) s = s[match_len:] first = False if match_str[0] in ('+', '-'): match_str = f'{match_str[0]} {match_str[1:]}' # Add a space after variable name accum_string += f'{match_str} ' continue # No variable match, check for numeric value num_rex = re.compile(prefix + r'(([0-9]*\.[0-9]+)|([0-9]+))(e-?[0-9]+)?(\*?i)?', re.I) num_match = num_rex.match(s) if num_match: # Remove the matched part from input match_str = num_match.group() match_len = len(match_str) s = s[match_len:] first = False # Temporarily remove first char if it's a + or - if match_str[0] in ('+', '-'): # Put a space after the sign prefix_char = f'{match_str[0]} ' match_str = match_str[1:] else: prefix_char = '' # Perform some cleanup while match_str.startswith('0') and len(match_str) > 1 and match_str[1].isnumeric(): match_str = match_str[1:] # Insert a zero if the number starts with a period if match_str.startswith('.'): match_str = '0' + match_str match_str = f'{prefix_char}{match_str} ' match_str = match_str.replace('I', 'i') match_str = match_str.replace('e', 'E') accum_string += match_str continue # No match, invalid input return f'INVALID: {value}' result += accum_string.strip() return result
802e7503f19ed1a5bb47ad887d1fe15219225fe1
701,753
def reducejson(j): """ Not sure if there's a better way to walk the ... interesting result """ authors = [] for key in j["data"]["repository"]["commitComments"]["edges"]: authors.append(key["node"]["author"]) for key in j["data"]["repository"]["issues"]["nodes"]: authors.append(key["author"]) for c in key["comments"]["nodes"]: authors.append(c["author"]) for key in j["data"]["repository"]["pullRequests"]["edges"]: authors.append(key["node"]["author"]) for c in key["node"]["comments"]["nodes"]: authors.append(c["author"]) unique = list({v['login']:v for v in authors if v is not None}.values()) return unique
90e50ff58e830fbe902a42c4256b19d9c6c46ff0
701,754
async def async_setup(hass, hass_config): """Set up the Plaato component.""" return True
b2c620c58aabcf788310e3aaf9cdf836f9be15ba
701,755
def json_value(obj): """Format obj in the JSON style for a value""" if type(obj) is bool: if obj: return '*true*' return '*false*' if type(obj) is str: return '"' + obj + '"' if obj is None: return '*null*' assert False
fc34c619d550af029536437c0eec7163e3ce673c
701,756
import re def get_hostmask_regex(mask): """Get a compiled regex pattern for an IRC hostmask :param str mask: the hostmask that the pattern should match :return: a compiled regex pattern matching the given ``mask`` :rtype: :ref:`re.Pattern <python:re-objects>` """ mask = re.escape(mask) mask = mask.replace(r'\*', '.*') return re.compile(mask + '$', re.I)
6e46d907d51e32139168d6f6405ca45ca38bbb98
701,757
from typing import Any import yaml from typing import List def read_yaml(file: Any) -> dict: """Read yaml file. Return dict.""" if isinstance(file, str) and any(file.endswith(x) for x in ('.yml', '.yaml')): with open(file, "r", encoding='utf-8') as fp: return yaml.load(fp, Loader=yaml.FullLoader) data: List[dict] = yaml.load(file, Loader=yaml.FullLoader) return {} if len(data) == 0 else data[0]
d696372cb5fb0b494d257b296dd6ac7946e296ff
701,758
def read_ffindex(file): """Read a ffindex and return a list of all the lines in the file . Args: file (string): path to the ffindex Returns: list of string: The file read line by line """ fh = open(file, "r") index = [] for line in fh: index.append(line.rstrip().split()) fh.close() return index
fae6494ddbda63abae1161f9fd22c8a94f506407
701,760
def get_field_from_args_or_session(config, args, field_name): """ We try to get field_name from diffent sources: The order of priorioty is following: read_default_contract_address - command line argument (--<field_name>) - current session configuration (default_<filed_name>) """ rez = getattr(args, field_name, None) # type(rez) can be int in case of wallet-index, so we cannot make simply if(rez) if rez is not None: return rez rez = config.get_session_field("default_%s" % field_name, exception_if_not_found=False) if rez: return rez raise Exception("Fail to get default_%s from config, should specify %s via --%s parameter" % ( field_name, field_name, field_name.replace("_", "-")))
8979a90814bcab9c72f54835a31d69971f8b1437
701,761
import importlib def resolve(module_name, obj_name): """ Resolve a named object in a module. """ return getattr(importlib.import_module(module_name), obj_name)
87ccef3456d28615b82a89a8e4ce405403eaade9
701,762
def get_num_shorts(string_list): """ Returns the number of occurences of 'Short' in an input string list. Args: string_list(list of string objects) Returns: numShorts(int): Number of occurences of 'Short' """ numShorts = 0 for marker in string_list: if (marker == 'Short'): numShorts += 1 return numShorts
b8e9da454590a8b29965696be3265053cfc78729
701,763
import pandas def _try_to_date(x): """Wrapper around :func:`pandas.to_datetime` that returns the input unaltered if it's not a date. Don't attempt converting numeric or boolean arrays. """ if x.dtype.kind != 'U': # unicode string return x try: # In case of ambiguity, prefer European format DD/MM/YYYY to the # American format MM/DD/YYYY return pandas.to_datetime(x, dayfirst=True) except ValueError: return x
01d296b0578933954a3b6593fd52fc15620cc1cd
701,764
import jinja2 def create_j2env(template_dir) -> jinja2.Environment: """ Create a Jinja2 enviornment instance used when template building the containerlab topology file. Parameters ---------- template_dir: str The file path where the Jinja2 template file is located. Returns ------- A Jinja2 enviornment instance that will be used to template build the containerlabs topology file. """ env = jinja2.Environment( trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True, loader=jinja2.FileSystemLoader([template_dir]), undefined=jinja2.StrictUndefined, ) return env
1d6559eae0346c0b9fd6171c18da5f2d94e1db86
701,765
import ast def _unpack_lists(input_list): """Unpacks a list of strings containing sublists of strings such as provided by the data table in the 2d U-net training pipeline card Args: input_list (list): list of strings which contain sublists Returns: list: list of hidden items from the table (first member in sublist) """ return [ast.literal_eval(item)[0] for item in input_list]
e80cd60e46b0ec5b5dd9b4a88ebe7193c0645f48
701,766
import torch def ln2float(module): """Batchnorm to Float.""" if isinstance(module, torch.nn.LayerNorm): print('Warning: Casting LayerNorm to fp32 ...') module.float() for child in module.children(): ln2float(child) return module
42bb1769a42a722f5332c0d4f1e635cdca2d6451
701,768
from datetime import datetime def convert_time(timestring, date='1990-01-01'): """Convert time string to have leading zeros. :param timestring: Byte array in '%H:%M:%S' without leading zeros. :param date: Date of the timestamp (defaults to 1990-01-01) :return: time object """ return datetime.strptime(' '.join((date, timestring.decode())), '%Y-%m-%d %H:%M:%S')
118e205396118e7e64c7b368dc4347d0a6daab63
701,769
import torch def compute_accuracy(logits, labels, mask): """Compute the accuracy""" logits = logits[mask] labels = labels[mask] _, indices = torch.max(logits, dim=1) correct = torch.sum(indices == labels) return correct.item() * 1.0 / len(labels)
a7ee234837024598fc95fa9c54c55802ea411577
701,770
def consistent(a, b): """ It is possible for an argument list to satisfy both A and B """ return (len(a) == len(b) and all(issubclass(aa, bb) or issubclass(bb, aa) for aa, bb in zip(a, b)))
e79ec485c667d9d85692eb43de3f8442a28e94ec
701,771
def remove_duplicate_edges(G, max_ratio = 1.5): """ function for deleting duplicated edges - where there is more than one edge connecting a node pair. USE WITH CAUTION - will change both topological relationships and node maps :param G: a graph object :param max_ratio: most of the time we see duplicate edges that are clones of each other. Sometimes, however, there are valid duplicates. These occur if multiple roads connect two junctions uniquely and without interruption - e.g. two roads running either side of a lake which meet at either end. The idea here is that valid 'duplicate edges' will have geometries of materially different length. Hence, we include a ratio - defaulting to 1.5 - beyond which we are sure the duplicates are valid edges, and will not be deleted. """ G2 = G.copy() uniques = [] deletes = [] for u, v, data in G2.edges(data = True): if (u,v) not in uniques: uniques.append((v,u)) t = G2.number_of_edges(u, v) lengths = [] for i in range(0,t): lengths.append(G2.edges[u,v,i]['length']) if max(lengths) / min(lengths) >= max_ratio: pass else: deletes.append((u,v)) for d in deletes: G2.remove_edge(d[0],d[1]) print(G2.number_of_edges()) return G2
bc2a23081749e3dcb135ceea5aad004a7331e794
701,772
def just_nucs(seqs): """eliminate sequences containing gaps/Ns, along the 1st axis, match each base in seqs to <= 3 element-wise, give the indices of those just_nucs seq idx. """ (indices,) = (seqs <= 3).all(axis=1).nonzero() just_bases = seqs.take(indices, axis=0) return just_bases
142bb7aa905e34d5e12fcfe3233bc3f80d440916
701,773
def get_domain_server_version(domain): """ Get the Server version based on the Server header for the web server. """ if domain.canonical.server_version is not None: return domain.canonical.server_version if domain.https.server_version is not None: return domain.https.server_version if domain.httpswww.server_version is not None: return domain.httpswww.server_version if domain.httpwww.server_version is not None: return domain.httpwww.server_version if domain.http.server_version is not None: return domain.http.server_version return None
56966c986a5390c8a9aaa0fb71b19bfe2ca7361a
701,774
def build_lst(a, b): """ function to be folded over a list (with initial value `None`) produces one of: 1. `None` 2. A single value 3. A list of all values """ if type(a) is list: return a + [b] elif a: return [a, b] else: return b
1e47b7bf2987a52b77266d6949af40f1c7df0109
701,775
def foo_1(x): """ test >>> foo_1(4) 2.0 """ return x ** .5
e8f7d3e9486e8c794a8c5761cea156b770851971
701,776
import re import json import time import requests import traceback def track(headers, body): """ 数据追踪,解决1金币问题 :param headers: :param body: :return: """ try: url = 'https://mqqapi.reader.qq.com/log/v4/mqq/track' timestamp = re.compile(r'"dis": (.*?),') body = json.dumps(body) body = re.sub(timestamp.findall(body)[0], str( int(time.time() * 1000)), str(body)) response = requests.post( url=url, headers=headers, data=body, timeout=30).json() if response['code'] == 0: return True else: return except: print(traceback.format_exc()) return
71ce3ca86a49877abde9d598114c0b9899a1bea4
701,777
import pandas import numpy def try_to_datetime(x, frmt=''): """Try to convert a string to a date. In case of failure, return nan""" try: if frmt == '': return pandas.to_datetime(x) else: return pandas.to_datetime(x, format=frmt) except: return numpy.nan
f639a5fdc4170531b3bf660ee0979041a8aab123
701,778
import os def food_image_upload_path(filename): """美食图片上传路径""" return os.path.join( "food_image", "%Y/%m", filename )
d7ee8ed6f0027edc0fecba6aa2c3e64919abb7ab
701,779
def scraperMode(): """ The operating mode of the scraper. It can either send notification if text is found on the page, or waiting and keep refreshing until the text goes away from the page. :return: the mode """ print("In which mode should the scraper behave?\nInsert the corresponding number...") print("1. Send a notification when the text inserted is found in the website") print("2. Send a notification when the text inserted isn't on the website anymore") mode = input() print() return mode
f60a2fdb73ed92c970c764d8327b11f40edfbd45
701,780
def func(arg1, arg2): """magic function """ return arg2, arg1
eb5841ce5765d44ede5162aa8bf51ec370c35b00
701,781
def gt(value, other): """Greater than""" return value > other
943d50ded0dfcb248eefb060d28850154693956b
701,782
def point_dist(a, b): """ Distance between two points. """ return ((a[0]-b[0]) ** 2 + (a[1]-b[1]) ** 2) ** 0.5
ad3490e25fb21a555ee2d12bead5fa476f682566
701,783
def quote(s: str) -> str: """ Quotes the identifier. This ensures that the identifier is valid to use in SQL statements even if it contains special characters or is a SQL keyword. It DOES NOT protect against malicious input. DO NOT use this function with untrusted input. """ if not (s.startswith('"') and s.endswith('"')): return '"' + s.replace('"', '""') + '"' else: return s
b4530f7570384beedbb7aafd02e642862a484bb8
701,784
def _mangle_dimension_name(name): """Return a dimension name from a mixpanel property name.""" fixed_name = name.replace("$", "_") fixed_name = fixed_name.replace(" ", "_") return fixed_name
b18738f4c27fcebe7a93f724bfd45414e075f0a6
701,785
def update_dict(old_data, new_data): """ Overwrites old usa_ids, descriptions, and abbreviation with data from the USA contacts API """ old_data['usa_id'] = new_data.get('usa_id') if new_data.get('description') and not old_data.get('description'): old_data['description'] = new_data.get('description') if new_data.get('abbreviation') and not old_data.get('abbreviation'): old_data['abbreviation'] = new_data['abbreviation'] return old_data
bec860144de28f5e3097e92216d94e6025223d2e
701,786
def min_box(box1, box2): """ return the minimum of two bounding boxes """ ext = lambda values: max(values) if sum(values) <= 0 else min(values) return tuple(tuple(ext(offs) for offs in zip(dim[0], dim[1])) for dim in zip(box1, box2))
58c8a0fa75c66f1327df13a4e7b5a0f7385c805e
701,787
import math def exempt_milliwatts_sar(cm: float, ghz: float) -> float: """Calculate power threshold for exemption from routine radio frequency exposure evaluation. Note: narrow range of applicable frequencies. FCC formula is "based on localized specific absorption rate (SAR) limits." Source: FCC 19-126 p.23 :param cm: Distance from antenna to person (centimeters) :param ghz: Frequency of RF source (gigahertz, NOTE different unit from other functions) :return: time-averaged power threshold for exemption (milliwatts) :raises ValueError: if frequency or distance out of range (0.3 - 6 GHz; 0 - 40 cm) """ if 0.3 <= ghz < 1.5: erp20 = 2040 * ghz elif 1.5 <= ghz <= 6: erp20 = 3060 else: raise ValueError("frequency out of range: %s GHz" % str(ghz)) x = -1 * math.log10(60 / (erp20 * math.sqrt(ghz))) if 0 <= cm <= 20: p_threshold = erp20 * (cm / 20) ** x elif 20 < cm <= 40: p_threshold = erp20 else: raise ValueError("distance out of range: %s cm" % str(cm)) return p_threshold
d705c3fd2388204d188e95d9013fe0c574f9e82a
701,789
import typing import re def replace_cif_reference(refs: typing.Iterable[str], new_sub_str: str) -> typing.List: """Replace the "cif-reference-0" to bec new names with increasing index.""" ans = [] source = r"@article{.*," for i, ref in enumerate(refs): ref2 = re.sub(source, "@article{{{}{},".format(new_sub_str, i), ref) ans.append(ref2) return ans
014f633c8eef43093944ec8f63690b59c446c2c1
701,790
import uuid def random_string() -> str: """ Create a 36-character random string. Returns ------- str """ return str(uuid.uuid4())
f01e291f6d36a8468a256af0fad83e2d468b471d
701,791
def _extent(x, y): """Get data extent for pyplot imshow. Parameters ---------- x: list Data array on X-axis. y: list Data array on Y-axis. Returns ------- [float, float, float, float] X and Y extent. """ dx, dy = .5 * (x[1] - x[0]), .5 * (y[1] - y[0]) return [x[0] - dx, x[-1] + dx, y[-1] + dy, y[0] - dy]
1b8a062e2060dc99d3fcdc32fe6fd1952f468a6a
701,792
import feedparser # type: ignore def get_posts_details(rss=None): """ Take link of mrss feed as argument """ if rss is not None: # import the library only when url for feed is passed # parsing partner feed partner_feed = partner_feed = feedparser.parse(rss) # getting lists of partner entries via .entries posts = partner_feed.entries # print(posts) # dictionary for holding posts details # print(partner_feed.entries[0]) posts_details = {"Partner Title" : partner_feed.feed.title, "Partner Feed" : partner_feed.feed.updated} post_list = [] # iterating over individual posts for post in posts: temp = dict() # if any post doesn't have information then throw error. try: temp["post_title"] = post.title temp["post_URL"] = post.link temp["post_cover_image"] = post.media_thumbnail # temp["author"] = post.author # temp["time_published"] = post.published except: pass post_list.append(temp) # storing lists of posts in the dictionary posts_details["posts"] = post_list return posts_details # returning the details which is dictionary else: return None
eee63b49ab4cf7c1746b752cb0a436b18fb7201e
701,794
def _normalize_newlines(text: str) -> str: """Normalizes the newlines in a string to use \n (instead of \r or \r\n). :param text: the text to normalize the newlines in :return: the text with the newlines normalized """ return "\n".join(text.splitlines())
6b53b42e8cec72a8e63ec0065776f47de2fba835
701,796
def pick_from_greatests(dictionary, wobble): """ Picks the left- or rightmost positions of the greatests list in a window determined by the wobble size. Whether the left or the rightmost positions are desired can be set by the user, and the list is ordered accordingly. """ previous = -100 is_picked_list = [] for pos, is_greatest in dictionary.items(): is_picked = False if is_greatest: if previous not in range(pos - wobble, pos + wobble + 1): is_picked = True previous = pos is_picked_list.append(is_picked) return is_picked_list
52685877620ab7f58a27eb6997ec25f3b499e3a4
701,797
def replace_layer(model, layer_name, replace_fn): """Replace single layer in a (possibly nested) torch.nn.Module using `replace_fn`. Given a module `model` and a layer specified by `layer_name` replace the layer using `new_layer = replace_fn(old_layer)`. Here `layer_name` is a list of strings, each string indexing a level of the nested model.""" if layer_name: nm = layer_name.pop() model._modules[nm] = replace_layer(model._modules[nm], layer_name, replace_fn) else: model = replace_fn(model) return model
2e0ee082d6ab8b48979aa49e303a0e12583812b7
701,798
def genInvSBox( SBox ): """ genInvSBox - generates inverse of an SBox. Args: SBox: The SBox to generate the inverse. Returns: The inverse SBox. """ InvSBox = [0]*0x100 for i in range(0x100): InvSBox[ SBox[i] ] = i return InvSBox
8ddf7e338e914f6cb6c309dc25705601326160c0
701,799
def get_unassigned(values:dict, unassigned:dict): """ Select Unassigned Variable It uses minimum remaining values MRV and degree as heuristics returns a tuple of: unassigned key and a list of the possible values e.g. ('a1', [1, 2, 3, 4, 5, 6, 7, 8, 9]) """ values_sort = dict() # empty dictionary to store length of possible values array for key in values.keys(): length = len(values[key]) # get the length of possible values array values_sort[key] = (length) # add to dictionary for sorting in next step # sort the dictionary including lengths of possible values from small to large # this is to later on assign the items with the minimum number of remaining values first values_sorted = dict(sorted(values_sort.items(), key=lambda item: item[1], reverse=False)) for key in values_sorted.keys(): if unassigned[key] == True: length = values_sorted[key] if length > 1: vars = values[key] return key, vars
32ff78f7a6443bfbf4406c420ba87e254e88d5c3
701,800
def is_superset_of(value, superset): """Check if a variable is a superset.""" return set(value) <= set(superset)
8b40089430dedef72566e93eb551b35001ec2e96
701,801
from datetime import datetime def datetime_to_year(dt: datetime) -> float: """ Convert a DateTime instance to decimal year For example, 1/7/2010 would be approximately 2010.5 :param dt: The datetime instance to convert :return: Equivalent decimal year """ # By Luke Davis from https://stackoverflow.com/a/42424261 year_part = dt - datetime(year=dt.year, month=1, day=1) year_length = datetime(year=dt.year + 1, month=1, day=1) - datetime(year=dt.year, month=1, day=1) return dt.year + year_part / year_length
5f4ae29d57d13a344e70016ab59dbc0a619db4d8
701,802
def ek_R56Q(cell): """ Returns the R56Q reversal potential (in mV) for the given integer index ``cell``. """ reversal_potentials = { 1: -96.0, 2: -95.0, 3: -90.5, 4: -94.5, 5: -94.5, 6: -101.0 } return reversal_potentials[cell]
a61d33426e4c14147677c29b8e37381981f0d1db
701,803
def gtk_menu_position(event, *args): """ Create a menu at the given location for an event. This function is meant to be used as the *func* parameter for the :py:meth:`Gtk.Menu.popup` method. The *event* object must be passed in as the first parameter, which can be accomplished using :py:func:`functools.partial`. :param event: The event to retrieve the coordinates for. """ if not hasattr(event, 'get_root_coords'): raise TypeError('event object has no get_root_coords method') coords = event.get_root_coords() return (coords[0], coords[1], True)
2670b4c2b3f5d7ad7fa74a836ec1b918a724c436
701,804
import torch def ssim(x, y): """Calculate ssim value of x (3D) in respect to y (3D). :param x: preprocessed predicted tensor (3D) :type x: torch.Tensor :param y: preprocessed groundtruth tensor (3D) :type y: torch.Tensor """ # pre-computation C1 = (0.01 * 255) ** 2 C2 = (0.03 * 255) ** 2 flatten_x = torch.flatten(x, start_dim=1) flatten_y = torch.flatten(y, start_dim=1) tot_pixel = x.size(1) * x.size(2) # calculate miu miux = torch.mean(x, dim=(1, 2)) miuy = torch.mean(y, dim=(1, 2)) mean_subtracted_x = flatten_x - miux.unsqueeze(1) mean_subtracted_y = flatten_y - miuy.unsqueeze(1) # calculate phi supportx = torch.sum(mean_subtracted_x ** 2, dim=1) phix = torch.sqrt(supportx / (tot_pixel - 1)) supporty = torch.sum(mean_subtracted_y ** 2, dim=1) phiy = torch.sqrt(supporty / (tot_pixel - 1)) phixy = torch.sum(mean_subtracted_x * mean_subtracted_y, dim=1) / (tot_pixel - 1) # calculate ssim result = torch.mean(((2 * miux * miuy + C1) * (2 * phixy + C2)) / ((miux ** 2 + miuy ** 2 + C1) * (phix ** 2 + phiy ** 2 + C2))).item() return result
e94d4565f694ecdc8f7e72f692861b9982e66b11
701,805
import re def _sort_nd2_files(files): """ The script used on the Nikon scopes is not handling > 100 file names correctly and is generating a pattern like: ESN_2021_01_08_00_jsp116_00_P_009.nd2 ESN_2021_01_08_00_jsp116_00_P_010.nd2 ESN_2021_01_08_00_jsp116_00_P_0100.nd2 ESN_2021_01_08_00_jsp116_00_P_011.nd2 So this function parses the last number and treats it as an int for sorting """ pat = re.compile(r"(.*_)(\d+)(\.nd2)$") file_splits = [] did_split = None for file in files: g = pat.match(file) if g is not None: file_splits += [(g.group(1), g.group(2), g.group(3))] assert did_split is True or did_split is None did_split = True else: assert did_split is False or did_split is None did_split = False if did_split: numerically_sorted = sorted(file_splits, key=lambda x: int(x[1])) return ["".join(i) for i in numerically_sorted] else: return sorted(files)
17a034323412174beab3fd9cfb23e315a26d4d5a
701,806
def _suppression_polynomial(halo_mass, z, log_half_mode_mass, c_scale, c_power): """ :param halo_mass: halo mass :param z: halo redshift :param log_half_mode_mass: log10 of half-mode mass :param c_scale: the scale where the relation turns over :param c_power: the steepness of the turnover The functional form is: c_wdm / c_cdm = (1 + c_scale * mhm / m)^c_power * redshift_factor where redshift_factor = (1+z)^(0.026 * z - 0.04) (Bose et al. 2016) :return: the ratio c_wdm over c_cdm """ if c_power > 0: raise Exception('c_power parameters > 0 are unphysical') if c_scale < 0: raise Exception('c_scale parameters < 0 are unphysical') mhm = 10 ** log_half_mode_mass mass_ratio = mhm / halo_mass concentration_factor = (1 + c_scale * mass_ratio) ** c_power redshift_factor = (1 + z) ** (0.026 * z - 0.04) rescale = redshift_factor * concentration_factor return rescale
e0d72ae6c092ff01864cfb74d18143b070f075c9
701,807
import torch def KLDiv_loss(x, y): """Wrapper for PyTorch's KLDivLoss function""" x_log = x.log() return torch.nn.functional.kl_div(x_log, y)
e288c3e60fab90a30693b6d5856bd2964f421599
701,808
def limit_vals(input_value, low_limit, high_limit): """ Apply limits to an input value. Parameters ---------- input_value : float Input value. low_limit : float Low limit. If value falls below this limit it will be set to this value. high_limit : float High limit. If value falls above this limit it will be set to this value. Returns ------- float Returns input value unless it falls above or below the entered limits. """ if input_value < low_limit: return low_limit elif input_value > high_limit: return high_limit else: return input_value
4520da27c81338631ea0d35651c7e3170de0524c
701,809
import torch def get_mask( ref, sub, pyg=False ): """ Get the mask for a reference list based on a subset list. Args: ref: reference list sub: subset list pyg: boolean; whether to return torch tensor for PyG Return: mask: list or torch.BoolTensor """ mask = [item in sub for item in ref] if pyg: mask = torch.BoolTensor(mask) return mask
07e4b092b5becaaec8bc070990259701bc3a00b7
701,810
def get_merged_overlapping_coords(start_end): """merges overlapping spans, assumes sorted by start""" result = [start_end[0]] prev_end = result[0][-1] for i in range(1, len(start_end)): curr_start, curr_end = start_end[i] # if we're beyond previous, add and continue if curr_start > prev_end: prev_end = curr_end result.append([curr_start, curr_end]) elif curr_end > prev_end: prev_end = curr_end result[-1][-1] = prev_end else: pass # we lie completely within previous span return result
22220778a66e069d98d1129b32f024e61fde1859
701,811
import logging from pathlib import Path def init_logger(log_file=None, log_file_level=logging.NOTSET): """ Example: init_logger(log_file) logger.info("abc'") """ if isinstance(log_file, Path): log_file = str(log_file) log_format = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S') logger_ = logging.getLogger() logger_.setLevel(logging.INFO) console_handler = logging.StreamHandler() console_handler.setFormatter(log_format) logger_.handlers = [console_handler] if log_file and log_file != '': file_handler = logging.FileHandler(log_file) file_handler.setLevel(log_file_level) # file_handler.setFormatter(log_format) logger_.addHandler(file_handler) return logger_
65df2b9377062aa562b88eadd334447b14c100d3
701,812
def HtmlRenderer(tooltip): """ A renderer that implements all tooltip features in html. """ ret = [] USE_STYLE = True lineTpl = '<div style="%s">%s</div>' sideTpl = '<span style="%s">%s</span>' for idx, line in enumerate(tooltip): lineHtml = [] lineStyle = [] if idx == 0: lineStyle.append("font-size: 110%;") for side in line: style = ["color: #%06x;" % (side.color())] if side.side() == side.RIGHT: style.append("float: right;") lineHtml.append(sideTpl % (" ".join(style), side.text())) text = lineTpl % (" ".join(lineStyle), " ".join(lineHtml)) ret.append(text) return "\n".join(ret)
fc4cbd326138085f39ee339973279e73be5f2af8
701,813
def html_to_spreadsheet_cell(html_element): """ Parse HTML elmement, like <a href=www.google.com>Google</a> to =HYPERLINK(www.google.com, Google) """ link = html_element.find("a") if link: return '=HYPERLINK("{}", "{}")'.format(link['href'], link.contents[0]) else: return html_element.text
f0c797f59ed55d1ce6aab32ff8c40cf83577ee27
701,814
def _get_class(canonical_name: str): """ Gets a class by it's canonical name. Mind that this can only work with classes that does not require any argument during instantiation. :param canonical_name: the canonical name of the class to load dynamically, e.g. x.y.Module.Class :returns: the instance of the class. """ parts = canonical_name.split('.') module = ".".join(parts[:-1]) m = __import__( module ) for comp in parts[1:]: m = getattr(m, comp) return type(parts[-1], (m,), {})()
289630cf65fcb915da4f4b49baa650d2e27e7a7c
701,815
from typing import Tuple def parseOptionWithArgs(plugin: str) -> Tuple[str, str]: """Parse the plugin name into name and parameter @type plugin: str @param plugin: The plugin argument @returns tuple[str, str]: The plugin name and parameter """ if '=' in plugin: plugin, param = plugin.split('=', 1) else: plugin = plugin param = '' return (plugin, param)
0e1f85f2e31349bf7ddcdc2d35b9ba815a61ec06
701,816
def knapsack(p, v, cmax): """Knapsack problem: select maximum value set of items if total size not more than capacity :param p: table with size of items :param v: table with value of items :param cmax: capacity of bag :requires: number of items non-zero :returns: value optimal solution, list of item indexes in solution :complexity: O(n * cmax), for n = number of items """ n = len(p) opt = [[0] * (cmax + 1) for _ in range(n + 1)] sel = [[False] * (cmax + 1) for _ in range(n + 1)] # --- basic case for cap in range(p[0], cmax + 1): opt[0][cap] = v[0] sel[0][cap] = True # --- induction case for i in range(1, n): for cap in range(cmax + 1): if cap >= p[i] and opt[i-1][cap - p[i]] + v[i] > opt[i-1][cap]: opt[i][cap] = opt[i-1][cap - p[i]] + v[i] sel[i][cap] = True else: opt[i][cap] = opt[i-1][cap] sel[i][cap] = False # --- reading solution cap = cmax solution = [] for i in range(n-1, -1, -1): if sel[i][cap]: solution.append(i) cap -= p[i] return (opt[n - 1][cmax], solution)
484ae09e663c834e42a9e05d684138d4fb6ddf08
701,817
def adresa_inceput(netmask, ip): """ Ia un netmask si un IP si determina adresa de inceput a retelei :param (str) netmask: :param (str) ip: :return adresa_inceput (str): """ netmask_nums = netmask.split(".") ip_nums = ip.split(".") adresa_inceput = "" for i in range(0, 4): adresa_num = int(netmask_nums[i]) & int(ip_nums[i]) adresa_inceput += str(adresa_num) adresa_inceput += "." return adresa_inceput[:len(adresa_inceput)-1]
dcbe18f68b216d6772fcad01e43829bc33de43c9
701,818
def get_usage_data_labels(usage_data): """Return dict with human readable labels for each of the groups in each of the given usage data timeframes.""" labels = {} timeframe_formats = {"day": "%H", "week": "%b %d", "month": "%b %d", "year": "%b %Y"} for timeframe, timeframe_data in usage_data.items(): labels[timeframe] = [group["datetime"].strftime(timeframe_formats[timeframe]) for group in timeframe_data] # Modify hourly labels to signify that it is covering a period of an hour. labels["day"] = [f"{label}:00-{int(label) + 1:02}:00" for label in labels["day"]] return labels
7c8610a7feb8a3a4a6454f508bfb9c95ccba55ff
701,819
def has_same_disk_several_positions(board): """ Check if the same disk appears multiple times on the same board Returns True is there is one or are multiple appearances, False if not """ used_disks = list(board.values()) for pos in range(len(used_disks) - 1, -1, -1): if used_disks[pos] is None: del used_disks[pos] for pos in range(len(used_disks)): for subpos in range(pos + 1, len(used_disks)): if used_disks[pos] is used_disks[subpos]: return True return False
b184e5c8bfb34c9819e4ffb146c4159c4d247a4c
701,820
def filter(function, iterable) -> object: """filter.""" if function is None: return (item for item in iterable if item) return (item for item in iterable if function(item))
36bfce957476f934a18c2bb3a24e994ec2799973
701,821
def modify_primer_file( infile, outfile ): """! @brief add subfix number to all primers """ counter = 0 mapping_table = {} with open( outfile, "w" ) as out: with open( infile, "r" ) as f: line = f.readline() while line: if line[0] == ">": if counter % 2 == 0: name = line.strip() out.write( ">primer" + str( counter / 2 ) + '_%_' + str( counter / 2 )+ '_%_1\n' ) mapping_table.update( { "primer" + str( counter / 2 ) + '_%_' + str( counter / 2 ) + '_%_1': name[1:] } ) else: name = line.strip() out.write( ">primer" + str( counter / 2 ) + '_%_' + str( counter / 2 )+ '_%_2\n' ) mapping_table.update( { "primer" + str( counter / 2 ) + '_%_' + str( counter / 2 )+ '_%_2': name[1:] } ) counter += 1 else: out.write( line ) line = f.readline() return mapping_table
20802c5578adceddafa6c7584a2da5c17b80ede6
701,822
def format_currency(amount): """Convert float to string currency with 2 decimal places.""" str_format = str(amount) cents = str_format.split('.')[1] if len(cents) == 1: str_format += '0' return '{0} USD'.format(str_format)
b90d064fe6b095227e5c590ad8d175f072e07957
701,823
def _get_delay_time(session): """ Helper function to extract the delay time from the session. :param session: Pytest session object. :return: Returns the delay time for each test loop. """ return session.config.option.delay
466ce191962df90ee8cdc1a5f8a004094eb9e79f
701,825
from typing import Sequence def is_overlapping_lane_seq(lane_seq1: Sequence[int], lane_seq2: Sequence[int]) -> bool: """ Check if the 2 lane sequences are overlapping. Overlapping is defined as:: s1------s2-----------------e1--------e2 Here lane2 starts somewhere on lane 1 and ends after it, OR:: s1------s2-----------------e2--------e1 Here lane2 starts somewhere on lane 1 and ends before it Args: lane_seq1: list of lane ids lane_seq2: list of lane ids Returns: bool, True if the lane sequences overlap """ if lane_seq2[0] in lane_seq1[1:] and lane_seq1[-1] in lane_seq2[:-1]: return True elif set(lane_seq2) <= set(lane_seq1): return True return False
155e3a962f3f457a868585798e1ab8d92c9f115f
701,826
def output_handler(data, context): """Post-process TensorFlow Serving output before it is returned to the client. Args: data (obj): the TensorFlow serving response context (Context): an object containing request and configuration details Returns: (bytes, string): data to return to client, response content type """ if data.status_code != 200: raise ValueError(data.content.decode('utf-8')) response_content_type = context.accept_header prediction = data.content return prediction,response_content_type
7d1bbcb2310c4527c5ae9cfcd51be660532555df
701,827
def largest_rectangle(h): """Hackerrank Problem: https://www.hackerrank.com/challenges/largest-rectangle/problem Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. Args: h (list): List of building heights Returns: (int): The largest area formed from the buildings """ largest_area = 0 # Iterate through each building in list, and then determine the area if that building is the lowest height for i in range(len(h)): num_buildings = 0 # Compare against buildings to the left for left in range(i, -1, -1): if h[left] >= h[i]: num_buildings += 1 else: break # Compare buildings to the right for right in range(i + 1, len(h)): if h[right] >= h[i]: num_buildings += 1 else: break # Next, calculate the area formed by this building and it's neighbors area = h[i] * num_buildings # Set as largest new area if it's the current largest if area > largest_area: largest_area = area return largest_area
7d7b66929e8416fdf8fe64e080ec5ed288c72d88
701,828
def fahr2cel(t): """Converts an input temperature in fahrenheit to degrees celsius Inputs: t: temperature, in degrees Fahrenheit Returns: Temperature, in C """ return (t - 32) * 5 / 9
b55f2405e06b124adf23b7833dedbe42ff9f75ba
701,829
import os def load_fonts(): """ Load all fonts in the fonts directory """ return [os.path.join('fonts1', font) for font in os.listdir('fonts1')]
96e339324e2a84a55bef1a307cb0d46343b7f1f6
701,830
from pathlib import Path import os import subprocess def decompress(full_bzip_filename: Path, temp_pth: Path) -> str: """ Decompresses .bz2 file and returns the non-compressed filename Args: full_bzip_filename: Full compressed filename temp_pth: Temporary path to save the native file Returns: The full native filename to the decompressed file """ base_bzip_filename = os.path.basename(full_bzip_filename) base_nat_filename = os.path.splitext(base_bzip_filename)[0] full_nat_filename = os.path.join(temp_pth, base_nat_filename) if os.path.exists(full_nat_filename): os.remove(full_nat_filename) with open(full_nat_filename, "wb") as nat_file_handler: process = subprocess.run( ["pbzip2", "--decompress", "--keep", "--stdout", full_bzip_filename], stdout=nat_file_handler, ) process.check_returncode() return full_nat_filename
4fdacd7340a75de056f08557c87509b0b899b1a8
701,831
def to_int(value): """Converts the given string value into an integer. Returns 0 if the conversion fails.""" try: return int(value) except (TypeError, ValueError): return 0
f219844de96d1d2236e94c4427c0ad27cc4b587b
701,832
def _default_function(l, default, i): """ EXAMPLES:: sage: from sage.combinat.integer_vector import _default_function sage: import functools sage: f = functools.partial(_default_function, [1,2,3], 99) sage: f(-1) 99 sage: f(0) 1 sage: f(1) 2 sage: f(2) 3 sage: f(3) 99 """ try: if i < 0: return default return l[i] except IndexError: return default
05da74d0c4ecee914928e8760d75730efc3434e5
701,833
def convert_headers_str(_str): """ convert headers str to dict """ _list = [i.strip() for i in _str.split('\n')] headers_dict = dict() for i in _list: k, v = i.split(':', 1) headers_dict[k.strip()] = v.strip() return headers_dict
cc80c1c2f5fc128243e59529808685335f7cead4
701,834
def cross(a, b): """Cross Product function Given vectors a and b, calculate the cross product. Parameters ---------- a : list First 3D vector. b : list Second 3D vector. Returns ------- c : list The cross product of vector a and vector b. Examples -------- >>> import numpy as np >>> from .pyCGM import cross >>> a = [6.25286248, 7.91367254, 18.63620527] >>> b = [3.49290439, 4.42038315, 19.23948238] >>> np.around(cross(a, b),8) array([ 6.98757956e+01, -5.52073543e+01, -1.65361000e-03]) """ c = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return c
d71244391e28af7b42eff45af62cc936b8651cd2
701,835
import random def rand_sampling(ratio, stop, start=1) : """ random sampling from close interval [start, stop] Args : ratio (float): percentage of sampling stop (int): upper bound of sampling interval start (int): lower bound of sampling interval Returns : A random sampling list """ assert 0 <= ratio and ratio <= 100, 'The ratio must be between 0 and 100.' assert stop >= start, 'Invalid interval' sample_pool = [i for i in range(start, stop + 1)] select_num = int(len(sample_pool) * ratio) return sorted(random.sample(sample_pool, select_num))
9b54c6b364e71a97d7cd9fa392790c4afde2bae0
701,836
def contain_same_digit(a, b): """ This function tests whether or not numbers a and b contains the same digits. """ list_a = list(str(a)) list_b = list(str(b)) if len(list_a) == len(list_b): for elt in list_a: if elt not in list_b: return False return True else: return False
a09feb891e5413593531e56871a92c335e585d7b
701,837
import yaml def read_yaml(config_path): """Load config files.""" with open(config_path) as file: data = yaml.load(file, Loader=yaml.FullLoader) return data
b46882ad841228edb3398a5742fa4dea6c4e9495
701,838
def parse_range(string): """ Parses IP range for args parser :param string: formatted string X.X.X.X-Y.Y.Y.Y :return: tuple of range """ ip_rng = string.split("-") return [(ip_rng[0], ip_rng[1])]
6f38e105284d58af2cef94275c25e02ad76acb80
701,839
import os def all_files_from(dir, ext=''): """Quick function to get all files from directory and all subdirectories """ files = [] for root, dirnames, filenames in os.walk(dir): for filename in filenames: if filename.endswith(ext) and not filename.startswith('.'): files.append(os.path.join(root, filename)) return files
e6e2fc545ceda51a2b4560829b0e995c164c5d9c
701,841
import requests import re def get_title(url: str): """ Get the Title of the web page and generates markdown formated link""" html_source = requests.get(url).text title = re.findall('<title>(.*?)</title>', html_source)[0].strip() return f"[{title}]({url})"
c6b0a559e7e3369d34e6266b7636d5c4a13ed2f0
701,842
def item_cost_entry() -> float: """Return the sum of all user entries.""" print('\nENTER ITEMS (ENTER 0 TO END)') subtotal: float = 0.0 while True: cost: float = float(input('Cost of item: ')) if cost == 0: break else: subtotal += cost return subtotal
d9d5bdc53f2d37f348d477086935cba3ba6a8e7e
701,843
def square(vx=1.0, vy=0, wz=0.8, t=16): """ Generate square trajectory, starting and ending at origin. """ time_points = range(t) speed_points = ( # Get set (0, 0, 0, 0), # Walk forward and then turn left (vx, 0, 0, 0), (vx, 0, 0, 0), (0, 0, 0, wz), (0, 0, 0, wz), # Walk forward and then turn left (vx, 0, 0, 0), (vx, 0, 0, 0), (0, 0, 0, wz), (0, 0, 0, wz), # Walk forward and then turn left (vx, 0, 0, 0), (vx, 0, 0, 0), (0, 0, 0, wz), (0, 0, 0, wz), (vx, 0, 0, 0), (vx, 0, 0, 0), # Walk to start point (0, 0, 0, 0)) # and relax. return time_points, speed_points
7db4f1c13cb3055b45e96b0e85934df0c6aa0389
701,844
def make_message(name): """Constructs a welcoming message. Input: string, Output:string.""" message = "Good morning, %s! Nice to see you."%name return message
ac5c9f845cd6779fa37758ec6b27b69dd325fb7d
701,845
def image_update(client, image_id, values, purge_props=False): """ Set the given properties on an image and update it. :raises NotFound if image does not exist. """ return client.image_update(values=values, image_id=image_id, purge_props=purge_props)
ddd89c57cefa2972833ce87e382572406fbb811f
701,847
def _parse_vertex_tuple(s): """Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k' ...).""" vt = [0, 0, 0] for i, c in enumerate(s.split('/')): if c: vt[i] = int(c) return tuple(vt)
e83182401b6443726660caf3688008f6209aed13
701,848
import torch def tfidf_transform(tfidf_vectorizer, corpus_data, cuda0): """ Apply TFIDF transformation to test data. Args: vectorizer_train (object): trained tfidf vectorizer newsgroups_test (ndarray): corpus of all documents from all categories in test set Returns: X_test (ndarray): tfidf word-document matrix of test data """ corpus_list = corpus_data["text"].tolist() tfidf_vector = tfidf_vectorizer.fit_transform(corpus_list) X_test = torch.t(torch.tensor(tfidf_vector.todense(), dtype=torch.float64, device=cuda0)) return X_test
6f18b7114579412e1442b1c6220f34b7f643a2ab
701,849
def numStationsNotIgnored(observations): """ Take a list of ObservedPoints and returns the number of stations that are actually to be used and are not ignored in the solution. Arguments: observations: [list] A list of ObservedPoints objects. Return: [int] Number of stations that are used in the solution. """ return len([obs for obs in observations if obs.ignore_station == False])
279f4075bc1fe155e4fa8b39758997c9748f06b8
701,850
def get_status(req_sheet, row_num): """ Accessor for JIRA Key Args: req_sheet: A variable holding an Excel Workbook sheet in memory. row_num: A variable holding the row # of the data being accessed. Returns: A string value of the Notes """ return (req_sheet['G' + str(row_num)].value)
3e1de0013bc0efc5824f5261ff4c0b278f486ea8
701,851
def summation(num) -> int: """This function makes numbers summation.""" return sum(range(1, num + 1))
78983a3e60be914987fd1dc91d5097e1edb326da
701,852
def get_mapshape_from_searchmap(hashtable): """Suppose keys have the form (x, y). We want max(x), max(y) such that not necessarily the key (max(x), max(y)) exists Args: hashtable(dict): key-value pairs Returns: int, int: max values for the keys """ ks = hashtable.keys() h = max([y[0] for y in ks]) w = max([x[1] for x in ks]) return h+1, w+1
cf5cb2051fc9254d70c60a71d2c7f9e378b0a39e
701,853
def det(a, b): """ Calculate the determinent between two vectors @param[a] One vector represented as [x,y] @param[b] One vector represented as [x,y] """ return a[0] * b[1] - a[1] * b[0]
61dfcbf421241ac9885643554bbf0c235f698098
701,854
def comments_search(posts,comments): """ :param posts1:Список со словарями, в которых данные публикаций :param comments:Список со словарями, в которых данные комментариев :return:Измененные список posts, с комментариями к постам с статусом sponsored """ for post in posts: post['comms'] = [] for comment in comments: if comment['post_id'] == post['id']: post['comms'].append(comment['comment']) return posts
e5d57854693de563b9a5beb7ca5f5e40b8d68d5a
701,855
import torch def update_weights(batch, batch_dic): """ Readjust weights so they sum to 1. Args: batch_dic (dict): Dictionary with extra conformer information about the batch batch (dict): Batch dictionary Returns: new_weights (torch.Tensor): renormalized weights """ old_weights = batch["weights"] conf_idx = torch.LongTensor(batch_dic["conf_idx"]) new_weights = old_weights[conf_idx] new_weights /= new_weights.sum() if torch.isnan(new_weights).any(): new_weights = torch.ones_like(old_weights[conf_idx]) new_weights /= new_weights.sum() return new_weights
90131e119e9d2cb849b79346fd2f5f86411f652b
701,856
import ast def _get_all_names(tree): """ Return list of all words. :param tree: _ast.Module object :return: list with words """ return (node.id for node in ast.walk(tree) if isinstance(node, ast.Name))
2b7f39af8bbe0c253d0206bcc86a8a0d05c7686e
701,857