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 ...
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.ge...
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...
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"]: auth...
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) ma...
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.Full...
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(...
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...
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 == '...
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 Eu...
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 --...
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...
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...
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 ...
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 ...
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.du...
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...
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....
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(...
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....
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{{{}{},".f...
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]) ...
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 vi...
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...
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 ...
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() # em...
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://st...
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`. ...
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 * 25...
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_...
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 ...
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...
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 """...
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...
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 - %(leve...
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...
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.te...
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 ...
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....
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, lis...
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): ...
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(): ...
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_dis...
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.w...
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,...
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 cl...
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 th...
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 ...
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) ...
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. ...
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...
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 T...
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('.'): f...
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), ...
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...
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:...
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 ...
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_...
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...
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'] ...
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 ...
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