content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import re def validate_date(date): """Validate date format. :param date: The date that will be entered into the database. :type date: str :return: True if the date format is well formed with valid characters, false if not. :rtype: bool """ result = None date_format = "([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2})" result = re.match(date_format, date) if result is None: return False else: return True
c9bf560c6e25246e8713f93b4a85ac87a7693337
591,580
def green_channel(input_image): """ Split input_image channels and return only the green channel :param input_image: image :type input_image: numpy.ndarray :return: image with only the green channel :rtype: numpy.ndarray """ return input_image[:, :, 1]
47fd11ae7a68285fd59e539556b0efb856566c3f
458,972
import requests from bs4 import BeautifulSoup def get_next_page_doc_url_set(author_name,page_num,unit_name): """ this function support the function: def get_doc_url_set(author_name,unit_name): get urls of specified page. Args: author_name: author's name page_num: specified page number unit_name: author's unit name Return: return set of doc urls """ headers = { "Host":"yuanjian.cnki.com.cn", "Connection":"keep-alive", "Content-Length":"473", "Accept":"text/html, */*; q=0.01", "Origin":"http://yuanjian.cnki.com.cn", "X-Requested-With":"XMLHttpRequest", "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36", "DNT":"1", "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8", "Referer":"http://yuanjian.cnki.com.cn/Search/Result", "Accept-Encoding":"gzip, deflate", "Accept-Language":"zh-CN,zh;q=0.9,en;q=0.8" } cookies = { "UM_distinctid":"168ae2b533519-0c21eda9d60a5f-57b143a-ea600-168ae2b533827", "KEYWORD":"%E5%BC%A0%E4%B9%85%E7%8F%8D%24%E7%89%9B%E4%B8%BD%E6%85%A7%24%E7%9F%AD%E5%B0%8F%E8%8A%BD%E5%AD%A2%E6%9D%86%E8%8F%8C%E8%A1%A8%E8%BE%BE%E7%B3%BB%E7%BB%9F%E7%9A%84%E4%BC%98%E5%8C%96%E7%A0%94%E7%A9%B6", "SID":"110105", "CNZZDATA1257838124":"249878561-1549106680-%7C1549701224" } base_url = "http://yuanjian.cnki.net/Search/Result" data = { "searchType":"MulityTermsSearch", "Author":author_name, "ParamIsNullOrEmpty":"true", "Islegal":"false", "Order":"1", "Page":page_num, "Unit":unit_name } r = requests.post(base_url,cookies = cookies,headers = headers,data = data) bs = BeautifulSoup(r.text,"html.parser") doc_url_set = [item["href"] for item in bs.find_all("a",{"target":"_blank","class":"left"})] return doc_url_set
f70770a51be83277b2ce3d9233c089a6a73396a6
554,020
import math def pretty_duration(d): """Formats a time duration Formats a time duration in a human readable format Arguments: d {float} -- Duration in seconds Returns: str -- formated duration """ if d < 1: return "<1s" s = '' days = math.floor(d / 86400) if days: s += f'{days}d ' d = d % 86400 hours = math.floor(d / 3600) if days or hours: s += f'{hours}h ' d = d % 3600 mins = math.floor(d / 60) if days or hours or mins: s += f'{mins}m ' d = d % 60 secs = round(d) if not days: s += f'{secs}s' return s.strip()
6aa50f86aa2a5df8487bc99f3df8a67f5d71177f
564,973
def permute_axes(array, input_axes, output_axes): """ Transpose the array with input_axes axis order to match output_axes axis order. Assumes that array has all the dimensions in output_axes, just in different orders, and drops/adds dims to the input axis order. Arguments: array (ndarray): array to transpose input_axes (string): dimension order output_axes (string): dimension order Returns: ndarray: transposed array """ permutation = tuple(input_axes.find(dim) for dim in output_axes) return array.transpose(permutation)
6e9ddd84862dd79204bdc36a2ebf2fa25545911e
543,752
def convert_to_hex(rgba_color): """ Convert an RGBa reference to HEX :param rgba_color: RGBa color :return: HEX color """ red = int(rgba_color.red * 255) green = int(rgba_color.green * 255) blue = int(rgba_color.blue * 255) return '0x{r:02x}{g:02x}{b:02x}'.format(r=red, g=green, b=blue)
05f5ff9bb11c3d63a5d789c4e3ceae8ee4ef3659
253,267
def px2mm(pixels, resolution=1600, precision=2): """Convert scanned pixels to millimeters. Arguments: pixels: measurement in pixels. resolution: image resolution in pixels/inch. precision: number of significant digits for rounding. Returns: The converted measurement. """ return round(25.4 * pixels / resolution, precision)
7a35d6d9bc049273b092a5bd4ea5e4d608b7cace
597,813
from typing import Iterable from typing import Tuple from typing import Counter def filter_mutation_set_by_position(mutation_sets: Iterable[Tuple[Tuple[int, int], ...]], limit: int = 10): """Return a filtered mutation set, where each position is used a maximum of `limit` times.""" filtered_mutation_sets = [] position_counter = Counter() for mutation_set in mutation_sets: positions = [m[0] for m in mutation_set] if any([position_counter[position] >= limit for position in positions]): continue else: position_counter.update(positions) filtered_mutation_sets.append(mutation_set) return filtered_mutation_sets
7120a40e0e21ea3d03fcd4a9618c3791724eaec2
222,815
def quantum_state_preparation_qiskit(circuit, parameters, n = 2): """ Parameters ---------- circuit: qiskit circuit parameters: n*2 array each row contains rx and ry parameters Returns ------- qiskit circuit """ q = circuit.qregs for i in range(len(q)): circuit.rx(parameters[i][0], q[i]) circuit.ry(parameters[i][1], q[i]) circuit.cx(q[1], q[0]) return circuit
5443d7a4c29c6ab003f71e345d5a07925f538c21
19,973
def is_keyword(text): """Check whether text is likely to be a keyword.""" return len(text.strip()) < 4 and text.isalpha()
a971dc2040e6847a9dbe7230a3effb7b3e6b6ed1
134,281
import re def get_values(line): """ Returns the portion of an INSERT statement containing values """ capture = re.match(r'^INSERT\s+INTO\s+`?(.*?)`?\s*(\(.*?\))?\s*VALUES\s*(\(.*?$)', line) if capture is None: return None return capture.groups()[2]
2cb8b902d58bc7409415e875d1f32d690ebc8549
283,203
from datetime import datetime import pytz def ns_to_datetime(ns): """ Converts nanoseconds to a datetime object (UTC) Parameters ---------- ns : int nanoseconds since epoch Returns ------- nanoseconds since epoch as a datetime object : datetime """ dt = datetime.utcfromtimestamp(ns / 1e9) return dt.replace(tzinfo=pytz.utc)
8e70e06b01add515147e267c2490b552567afb09
646,667
def excel_column_to_column_index(excel_column: str) -> int: """Takes an excel column like 'A' and converts to column index""" return ord(excel_column.upper()) - 64
76c67c576bdf5236204022980305887ac3aa6f60
495,802
def format_helptext(value): """Handle formatting for HELPTEXT field. Apply formatting only for token with value otherwise supply with newline""" if not value: return "\n" return "\t {}\n".format(value)
426fa6ee036c5a8376645d6455c1681b1200e174
60,812
import re def format_text_time_zone(text): """Returns text after removing blank spaces inside time zone text. Parameters ---------- text : str the text to be formatted. Returns ------- str a string formatted to match time zone (ex. UTC+2). """ text = re.sub(r'\s*\+\s*', '+', text) text = re.sub(r'\s*-\s*', '-', text) return text
9902e9b27142ca0d5984165fdddf70164aa57048
112,308
import math def distance(p1, p2): """ Calculates the distance between two points. :param p1, p2: points :return: distance between points """ p1x, p1y = p1 p2x, p2y = p2 return math.sqrt((p1x - p2x) ** 2 + (p2y - p2y) ** 2)
13cc6d2c2007441478fec8f4b17f08113cbdc2e6
609,113
def linearization(X, Jfun, P): """Transform a covariance matrix via linearization Arguments: X: the point to linearize about, (n,) numpy array Jfun: function which takes the state and returns the (n x n) Jacobian of the function, f, which we want to transform the covariance by. It should return an (n x n) matrix df1dx1 df1dx2 ... df1dxn df2dx1 df2dx2 ... df2dxn ... ... ... ... dfndx1 dfndx2 ... dfndxn P: covariance matrix to transform Returns: P_prime: transformed covariance matrix """ A = Jfun(X) P_prime = A.dot(P.dot(A.T)) return P_prime
c24c4d0815842cc70ac31f0ba9f505bc0d743036
23,097
def sourceJoin(nick, ident, host): """sourceJoin(nick, ident, host) -> str Join a source previously split by sourceSplit and join it back together inserting the ! and @ appropiately. """ return "%s!%s@%s" % (nick, ident, host)
9aaed0b756c9425425018f63abeb3d119e270415
200,614
def getUniqueByID(seq): """Very fast function to remove duplicates from a list while preserving order Based on sort f8() by Dave Kirby benchmarked at https://www.peterbe.com/plog/uniqifiers-benchmark Requires Python>=2.7 (requires set()) """ # Order preserving seen = set() return [x for x in seq if x.id not in seen and not seen.add(x.id)]
fec0964de14a6cbf70b50816a68335c27243d56e
323,749
import base64 def auth_for_user(user): """ Formats the base64 string based on a user """ return base64.standard_b64encode( "{}:{}".format(user.username, user.password).encode() )
2c0b92747f57e8a527407fd8adf7570338a06a7a
394,435
def hasQueryMatch(qList, tweetJSON): """Returns true if a tweet containing any keyword in QUERY_KEYWORDS is found""" return any(keyword in tweetJSON['text'] for keyword in qList)
b0ff979b8c54f09450749ef134c7b9deabe7a231
628,722
def _agg_data(data_strs): """ Auxiliary function that aggregates data of a job to a single byte string """ ranges = [] pos = 0 for datum in data_strs: datum_len = len(datum) ranges.append((pos, pos+datum_len-1)) pos += datum_len return b"".join(data_strs), ranges
b752a9a466ed6eaf5a9c37ff05f532641f296237
426,664
def GetExcelStyleColumnLabel(ColNum): """Return Excel style column label for a colum number. Arguments: ColNum (int): Column number Returns: str : Excel style column label. """ Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ColLabelList = [] while ColNum: ColNum, SubColNum = divmod(ColNum - 1, 26) ColLabelList[:0] = Letters[SubColNum] return ''.join(ColLabelList)
bc2fd2214e812ba592758bbd779714ba7cadb530
483,669
from typing import Callable def override_input(inputs: list[str]) -> Callable[[str], str]: """ Returns a new input() function that accepts a string and repeatedly pops strings from the front the provided list and returns them as calls to input(). """ def _input(prompt: str) -> str: """ The new input() function. Prints a prompt and then modifies the provided list. """ print(prompt) if not inputs: raise RuntimeError("Not enough inputs provided.") return inputs.pop(0) return _input
c7db23b19361dd72cc6519a6f52537ed719341f5
409,892
def f(N): """ 1/(N^2 -1) """ # tmp = np.dtype(np.float32) # 单精度 tmp = 1/(pow(N,2) - 1) return tmp
9cee33913b2044eca704eeee5b4edacdeb25102c
526,665
from typing import Optional def plot_number_formatter(val: float, _: Optional[float], precision: int = 3) -> str: """ Format numbers in the plot. Parameters ---------- val : float The value. _ : [None | float] The position (needed as input from FuncFormatter). precision : int Precision of the tick Returns ------- tick_string : str The string to use for the tick """ tick_string = f"${val:.{precision}g}" check_for_period = False # Special case if 0.000x or 0.00x if "0.000" in tick_string: check_for_period = True tick_string = tick_string.replace("0.000", "") if tick_string[1] == "-": tick_string = f"{tick_string[0:3]}.{tick_string[3:]}e-03" else: tick_string = f"{tick_string[0:2]}.{tick_string[2:]}e-03" elif "0.00" in tick_string: check_for_period = True tick_string = tick_string.replace("0.00", "") if tick_string[1] == "-": tick_string = f"{tick_string[0:3]}.{tick_string[3:]}e-02" else: tick_string = f"{tick_string[0:2]}.{tick_string[2:]}e-02" if check_for_period: # The last character before e-0x should not be a period if len(tick_string) > 5 and tick_string[-5] == ".": tick_string = tick_string.replace(".", "") if "e+" in tick_string: tick_string = tick_string.replace("e+0", r"\cdot 10^{") tick_string = tick_string.replace("e+", r"\cdot 10^{") tick_string += "}$" elif "e-" in tick_string: tick_string = tick_string.replace("e-0", r"\cdot 10^{-") tick_string = tick_string.replace("e-", r"\cdot 10^{-") tick_string += "}$" else: tick_string += "$" return tick_string
ffc66a14f6003c038dedc4b44d0e4b94e956f265
555,041
def get_force_datakeeper(self, symbol_list, is_multi=False): """ Generate DataKeepers to store by default results from force module Parameters ---------- self: VarLoad A VarLoad object symbol_list : list List of the existing datakeeper (to avoid duplicate) is_multi : bool True for multi-simulation of multi-simulation Returns ------- dk_list: list list of DataKeeper """ dk_list = [] return dk_list
1321948d15f07914de30dab648d643121d94d491
622,795
def calc_mean_std(feat, eps=1e-5): """ Calculate channel-wise mean and standard deviation for the input features and preserve the dimensions Args: feat: the latent feature of shape [B, C, H, W] eps: a small value to prevent calculation error of variance Returns: Channel-wise mean and standard deviation of the input features """ size = feat.size() assert (len(size) == 4) N, C = size[:2] feat_var = feat.view(N, C, -1).var(dim=2) + eps feat_std = feat_var.sqrt().view(N, C, 1, 1) feat_mean = feat.view(N, C, -1).mean(dim=2).view(N, C, 1, 1) return feat_mean, feat_std
0c564490787a210a0b9947781905dcf16b9d655d
158,811
def reset_dupe_index(df, ind_name): """ Reset index and rename duplicate index column Parameters: df (pandas DataFrame): DataFrame to reset index ind_name (str): Name of column to reset Returns: df (pandas DataFrame): DataFrame with reset duplicate index """ df.rename({ind_name: ind_name+'_back'}, inplace=True, axis=1) df.reset_index(inplace=True) return(df)
213de79ad7108f759d2bcdf1bfb9eb9d8f193c19
96,256
import re def question2(records): """Combien de noms de régions mentionnées dans ce fichier comportent un nombre de lettres supérieur ou égal à 10 (espaces et tirets non compris) ? """ # On déduplique les noms noms = set(r.region for r in records) # On les nettoie. # Attention, ceci est un **générateur**, le nettoyage effectif n'est pas fait ici mais quand on # itère dessus noms = (re.sub(r"\W", "", n) for n in noms) # Feinte du chacal pour compter les éléments d'un itérable qui vérifient une condition sans # prendre de place en mémoire res = sum(1 for n in noms if len(n) >= 10) return res
11d4656c89d898d675261a29231b6ac1df7f9555
306,627
def product(val1, val2, val3): """Returns the product of the three input values """ product = val1 * val2 * val3 return product
7c9ee354eb0c132f7c875031058aa4f8f957ae9a
255,945
import bz2 def make_bz2(tar_file, destination): """ Takes a tar_file and destination. Compressess the tar file and creates a .tar.bz2 """ tar_contents = open(tar_file, 'rb') bz2file = bz2.BZ2File(destination + '.tar.bz2', 'wb') bz2file.writelines(tar_contents) bz2file.close() tar_contents.close() return True
62704974ef5831559425d93bb8e3c6cbbb1e3e4b
498,594
def find_first_entry(line, elements, start=0, not_found_value=-1): """ Find the index of the earliest position inside the `line` of any of the strings in `elements`, starting from `start`. If none are found, return `not_found_value`. """ first_entry=len(line) for e in elements: pos=line.find(e,start) if pos>0: first_entry=min(first_entry,pos) if first_entry==len(line): return not_found_value return first_entry
171f0f1cbbc9fbaa3d65faacec7e6eca673eb378
83,311
import base64 import gzip import json def extract_log_events(event): """Decode and decompress log data.""" log_data = event['awslogs']['data'] compressed_data = base64.b64decode(log_data) decompressed_data = gzip.decompress(compressed_data) json_data = json.loads(decompressed_data) log_stream = json_data['logStream'] log_events = json_data['logEvents'] return (log_stream, log_events)
f26196feb6a5e42f5177fe093f69486c4a531f16
379,477
def generate_link(word, link): """ Return a str like a markdown link :return: str (example: [python](https://en.wikipedia.org/wiki/Python_(programming_language))) """ return f'[{word}]({link})'
290ece2e7a947c721adf255b018164428dbb09f2
424,642
def __get_station(seedid): """Station name from seed id""" st = seedid.rsplit('.', 2)[0] if st.startswith('.'): st = st[1:] return st
ab0795ce4b252a25c9eb1ba96d7b2f595ab48774
482,142
from typing import Union from typing import Type from typing import Any import inspect from typing import Sequence def is_sequence(item: Union[object, Type[Any]]) -> bool: """Returns if 'item' is a sequence and is NOT a str type.""" if not inspect.isclass(item): item = item.__class__ return ( issubclass(item, Sequence) # type: ignore and not issubclass(item, str))
4aa68c2870c1c974e5e5e358a2428b5806408351
518,873
def _tr_xml_to_json_extension(xml_filename): """ _tr_xml_to_json_extension Translates example.xml to example.json (just the filename) """ if '.xml' in xml_filename: return xml_filename.replace('.xml', '.json') else: return xml_filename + '.json'
2a90c24f8a49d26ba0109af73de903cb3540550d
571,846
def get_centers(bins): """Return the center of the provided bins. Example: >>> get_centers(bins=np.array([0.0, 1.0, 2.0])) array([0.5, 1.5]) """ bins = bins.astype(float) return (bins[:-1] + bins[1:]) / 2
4f5b3454e1ef718302c7e5ea204954d498ca9e10
702,265
from typing import Iterable from typing import Hashable def any_in(x: Iterable[Hashable], y: Iterable[Hashable]) -> bool: """ Check if any elements in `x` is in `y`. Returns `True` if `x` is empty. Defined to improve readability. Examples: >>> any_in([1, 2, 2, 1, 2], [1, 2, 3]) True >>> any_in([1, 2, 2, 4, 2], [1, 2, 3]) True >>> any_in([1, 2, 2, 4, 2], [3, 5, 6]) False """ return bool(set(x).intersection(y))
9be46812d36c21668a0776a4e55d523af169814e
557,260
import re def _agg_removing_duplicates(agg_elem): """Aggregate while removing the duplicates. Aggregate the labels or alt labels together as a single element can have several Wikidata entities that need to be merged. Args: agg_elem (list of string): elem to aggregate Returns: string: aggregation with the deletion of the duplicates """ str_elem = '|'.join(agg_elem) list_elem = str_elem.split('|') # Removing the name of WikiData when there is no labels in the languages regex = re.compile(r'Q[0-9]+') list_elem = [elem for elem in list_elem if not regex.match(elem)] list_elem_without_duplicates = list(set(list_elem)) list_elem_without_duplicates.sort() elem_without_duplicates = '|'.join(list_elem_without_duplicates) return elem_without_duplicates
f0b17d9acdd97452a728ed990f8150a72cbbe0f8
685,980
import codecs def splinter_screenshot_getter_html(splinter_screenshot_encoding): """Screenshot getter function: html.""" def getter(browser, path): with codecs.open(path, "w", encoding=splinter_screenshot_encoding) as fd: fd.write(browser.html) return getter
dfc2018f65cff5a89b6fa488252544b9a368b501
185,428
def normalize_prefix(path): """Add trailing slash to prefix if it is not present >>> normalize_prefix("somepath") 'somepath/' >>> normalize_prefix("somepath/") 'somepath/' """ if path is None or path is '' or path is '/': return None elif path.endswith('/'): return path else: return path + '/'
6b9d921cf04e55e51b1919eee7cd5a6f1642d7e8
509,032
import hashlib def hash_file(readable_file): """ Returns SHA256 hash of readable file-like object """ buf = readable_file.read(4096) hasher = hashlib.sha256() while buf: hasher.update(buf) buf = readable_file.read(4096) return hasher.hexdigest()
5b878c81a81a7a35318e83cf4b532917aabbe917
330,929
import inspect def _first_param_empty(signature): """Check whether the first argument to this call is empty, ie. no with a default value""" try: first = next((signature.parameters.items()).__iter__()) return first[1].default == inspect._empty except StopIteration: return True
052db9e7db8ceaf78af58a378f0ebd3f7994bab8
71,401
def get_words(wlist): """ Extract words from a file. @param wlist String name of file to read @return list List of all possible answer words (strings) """ with open(wlist, "r", encoding="UTF-8") as f_file: ostr = f_file.read() return ostr.split()
1975f1e58c6b4dbcff212fd4a979133cf96d8d37
448,515
def extract_params(params): """ Extracts the values of a set of parameters, recursing into nested dictionaries. """ values = [] if isinstance(params, dict): for key, value in params.items(): values.extend(extract_params(value)) elif isinstance(params, list): for value in params: values.extend(extract_params(value)) else: values.append(params) return values
9c1fd2f0ba0b98d807fc1c6d8b435dce6ac8f3e5
362,362
def scale_to(x, from_max, to_min, to_max): """Scale a value from range [0, from_max] to range [to_min, to_max].""" return x / from_max * (to_max - to_min) + to_min
e48e1f6556ee39fbdbba3cf2aa62e4efbcefba1c
651,793
from typing import Dict def loss_dict() -> Dict[str, float]: """ Initialize loss dictionary for network sub-tasks """ # Add z in front of each key name so they appear on the bottom (and together) in tensorboard d = {'z_normals_loss': 0.0, 'z_scene_loss': 0.0, 'z_depth_loss': 0.0, 'z_conf_loss': 0.0, 'z_loc_loss': 0.0} return d
f8b5c2c3fb4dad0431cce29583e928d1ed1b772e
413,427
def coord(x, y, unit=1): """ Converts pdf spacing co-ordinates to metric. """ x, y = x * unit, y * unit return x, y
23bae6aef93de37c045f3a6eae8460ffed32c105
182,634
def X(val): """ Compact way to write a leaf node """ return val, []
88b3d62cec471d2614ff7c220de0dc20e0c74930
284,356
from warnings import warn def find_torder(dic, shape): """ Find the torder from the procpar dictionary. If propar dictionary is incomplete a UserWarning is issued and 'r' is returned. Parameters ---------- dic : dict Dictionary of parameters in the procpar file. shaoe : tuple of ints Shape of NMR data. Returns -------- torder : {'r', 'f', 'o'} File ording for using in :py:func:`read` or :py:func:`write`. """ ndim = len(shape) # 1 and 2D files are flat if ndim < 3: return 'f' # flat if "array" not in dic: warn("no array in dictionary, torder set to 'r'") return 'r' # extract the array list al = dic['array']['values'][0].split(',') # remove one dimension if non-phase parameter is present in array list if False in [s.startswith('phase') for s in al]: ndim = ndim - 1 if ndim < 3: return 'f' # flat if ndim == 3: if "phase" in al and "phase2" in al: if al.index("phase") > al.index("phase2"): return 'r' # regular else: return 'o' # opposite else: warn("missing phase order, torder set to 'r'") return 'r' if ndim == 4: if "phase" in al and "phase2" in al and "phase3" in al: if al.index("phase") > al.index("phase2") > al.index("phase3"): return 'r' # regular if al.index("phase") < al.index("phase2") < al.index("phase3"): return 'o' # opposite else: warn("bad phase order, torder set to 'r'") return 'r' else: warn("missing phase order, torder set to 'r'") return 'r' warn("No trace ordering for" + str(ndim) + "dimensional data, torder set to 'r'") return 'r'
ad50702de4cea2fe25618f59893c55dddead036b
306,504
def fn_name(fn): """Return str name of a function or method.""" s = str(fn) if s.startswith('<function'): return 'fn:' + fn.__name__ else: return ':'.join(s.split()[1:3])
67ed11485b1f8edfa517a84aafae56031edc01f8
427,198
import ipaddress def is_valid_ipv4_address(address): """Check if the given ipv4 address is valid""" invalid_list = ['0.0.0.0','255.255.255.255'] try: ip = ipaddress.IPv4Address(address) if (ip.is_reserved) or (ip.is_multicast) or (ip.is_loopback) or (address in invalid_list): return False except ipaddress.AddressValueError: return False return True
ec7d8450f3f9aaad0248474fecc22f220d227cb8
403,769
import sympy import six import random def _split_factors(integer): """Randomly factors integer into product of two integers.""" assert integer.is_Integer if integer == 0: return [1, 0] # Gives dict of form {factor: multiplicity} factors = sympy.factorint(integer) left = sympy.Integer(1) right = sympy.Integer(1) for factor, mult in six.iteritems(factors): left_mult = random.randint(0, mult) right_mult = mult - left_mult left *= factor ** left_mult right *= factor ** right_mult return left, right
5a0adbc43296c325ee01b2043e5096c9702ce562
635,070
def add_segment_final_space(segments): """ >>> segments = ['Hi there!', 'Here... ', 'My name is Peter. '] >>> add_segment_final_space(segments) ['Hi there! ', 'Here... ', 'My name is Peter.'] """ r = [] for segment in segments[:-1]: r.append(segment.rstrip()+' ') r.append(segments[-1].rstrip()) return r
6593cbd325cac7a102ec21a7bfc16e22e74dc31f
665,780
import torch def pad(seq_batch, pad_token=0, min_len=None): """Pads a list[list[Object]] so that each inner list is the same length. Args: seq_batch (list[list[Object]]): batch of sequences to pad. pad_token (Object): object to pad sequences with. min_len (int | None): all sequences padded to at least min_length if provided. Returns: padded (list[list[Object]]): seq_batch with inner lists padded with the pad token, if necessary. mask (torch.ByteTensor): tensor of shape (batch_size, padded_length). mask[i][j] = 0 if padded[i][j] is a padded element and 1 otherwise. """ max_len = max(len(seq) for seq in seq_batch) if min_len is not None: max_len = max(max_len, min_len) batch_size = len(seq_batch) mask = torch.ones(batch_size, max_len).byte() padded = [] for i, seq in enumerate(seq_batch): padding = max_len - len(seq) padded.append(seq + [pad_token] * padding) if padding > 0: mask[i, -padding:] = 0 return padded, mask
636604ded73b37353dc825589751180f8af96a11
408,103
def find_freq(wvec, freq_val): """ Helper function returns the nearest index to the frequency point (freq_val) """ return min(range(len(wvec)), key=lambda i: abs(wvec[i]-freq_val))
262605d4b641c36470a2985a0008e4ea0d79d4cf
624,221
def utc_to_esmf(utc): """ Converts a UTC datetime into ESMF format. :param utc: python UTC datetime :return: a string in ESMF format """ return "%04d-%02d-%02d_%02d:%02d:%02d" % (utc.year, utc.month, utc.day, utc.hour, utc.minute, utc.second)
e9bd2b37895c6578a6c03ff3ac59a6cd209612d5
341,043
def getlinktags(link): """ Return tags for a link (list) """ linktags = link.get('tags') if linktags is None: linktags = list() else: linktags = linktags.split(',') return linktags
cd44f493a43e4c7d53b4a6c6f7faff80582904f2
535,480
def _NormalizeArgd(rawDict): """ Normalize the argument dictionary. All parameters start with '#' will be checked whether it is not None(client did not pass it). After checking a new dictionary will be generated and returned. :param rawDict: a dict, contains request args with required attribute flag :return: A pair. First flag is bool to signal whether this request is valid, Second is a dict for the generated dict or check failure key. """ pureDict = {} for k in rawDict: if k[0] == '#' and rawDict[k] is None: return False, {"key": k[1:len(k)]} pureDict[k[1:len(k)]] = rawDict[k] if rawDict[k] != "None" else None return True, pureDict
b2778285370429c2a1e02b2bdde923fdb6828d9d
561,338
import math def choose_grid_size(train_inputs, ratio=1.0, kronecker_structure=True): """ Given some training inputs, determine a good grid size for KISS-GP. :param x: the input data :type x: torch.Tensor (... x n x d) :param ratio: Amount of grid points per data point (default: 1.) :type ratio: float, optional :param kronecker_structure: Whether or not the model will use Kronecker structure in the grid (set to True unless there is an additive or product decomposition in the prior) :type kronecker_structure: bool, optional :return: Grid size :rtype: int """ # Scale features so they fit inside grid bounds num_data = train_inputs.numel() if train_inputs.dim() == 1 else train_inputs.size(-2) num_dim = 1 if train_inputs.dim() == 1 else train_inputs.size(-1) if kronecker_structure: return int(ratio * math.pow(num_data, 1.0 / num_dim)) else: return ratio * num_data
1d3e30a6b7b419a1e2fcdc245830aa00d1ba493d
11,411
def available(func): """A decorator to indicate that a method on the adapter will be exposed to the database wrapper, and will be available at parse and run time. """ func._is_available_ = True return func
a0c886bccb9bbbdacfe23c5659929b8be68c004e
698,352
import re def camel_case_to_underscore(name): """Converts camel case names to underscore lower case.""" return re.sub( '([a-z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), name)
2bf5ec8ab0825f007d5d852f126843e7119ad0be
552,283
def count_keys(num_qubits): """ Return ordered count keys. """ return [bin(j)[2:].zfill(num_qubits) for j in range(2 ** num_qubits)]
dd5a5c5b5de39894ca113f24d15b1056ac68aff6
465,716
def _get_best_joint_indexes(max_span_length, logits, n_best_size): """Gets the n-best start and end indices from flat logits.""" indices = sorted(range(len(logits)), key=logits.__getitem__, reverse=True) indices = indices[:n_best_size] starts = [x // max_span_length for x in indices] offsets = [x % max_span_length for x in indices] starts, ends = zip(*[(s, s + offs) for s, offs in zip(starts, offsets)]) return starts, ends
0e6fe7a0401c84424eec10f087cb9d7edb53090c
222,930
def parse_attestation(attestation): """ Given a bytes of the attestation report of length 688, return a dict of each field of the report """ assert(len(attestation) == 752) parsed_report = {} parsed_report['nonce'] = attestation[:32] parsed_report['attest_pk'] = attestation[32:64] parsed_report['kernel_hash'] = attestation[64:112] parsed_report['kernel_sig'] = attestation[112:624] parsed_report['attest_sig'] = attestation[624:688] parsed_report['shared_secret_sig'] = attestation[688:] return parsed_report
5098acaef93f538822f31d5231a4e6f5e8fecc81
221,575
def get_keytable_path(opendkim_conf): """Returns the path to the KeyTable file from the OpenDKIM config. """ param = 'KeyTable' with open(opendkim_conf, 'r') as f: for line in f: if line.startswith(param): return line.replace(param, '').strip() msg = "Could not find '{}' parameter in OpenDKIM config at {}".format(param, opendkim_conf) raise RuntimeError(msg)
cc40686d6dd9440747dff76ea0ceaafc0c3357ad
642,842
import errno def ps_zombies_list(pids): """ Given a list of PIDs, return which are zombies :param pids: iterable list of numeric PIDs :return: set of PIDs which are zombies """ zombies = set() for pid in pids: try: with open("/proc/%d/stat" % pid) as statf: stat = statf.read() if ") Z " in stat: zombies.add(pid) except IOError as e: if e.errno != errno.ENOENT: raise # If the PID doesn't exist, ignore it return zombies
151c5e946923ef1fa9150dfc3df92a9d5c4e5b90
407,596
def GetBgpRoutingMode(network): """Returns the BGP routing mode of the input network.""" return network.get('routingConfig', {}).get('routingMode')
ae682acd55a74897dcd896ea52b8d146639bcf6a
493,152
def parse_volume_bindings(volumes): """ Parse volumes into a dict. :param volumes: list of strings :return: dict """ def parse_volume(v): if ':' in v: parts = v.split(':') if len(parts) > 2: hp, cp, ro = parts[0], parts[1], parts[2] return hp, cp, ro == 'ro' else: hp, cp = parts[0], parts[1] return hp, cp, False else: return None, v, False result = {} if volumes: for vol in volumes: host_path, container_path, read_only = parse_volume(vol) if host_path: result[host_path] = { 'bind': container_path, 'ro': read_only } return result
34a72defb428e109ac400b6ff31681dd6e16a9c5
660,483
from pathlib import Path def check_directory(dir_path: str): """create git instance Args: dir_path (str): fullpath of git root directory Raises: FileExistsError: dir_path does not exist FileExistsError: dir_path does not have .git directory Returns: string: directory path """ p = Path(dir_path) # exsist check if p.exists(): pass else: raise FileExistsError('the directory does not exist.') # .git directory check git_p = p / '.git' if git_p.exists(): pass else: raise FileExistsError('the directory does not have .git directory') return dir_path
fd27fbf11d93e5c03080b19e321938c256e5b9a0
396,451
import math def cosine_similarity(v1, v2): """ compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||) """ sumxx, sumxy, sumyy = 0, 0, 0 for i in range(len(v1)): x = v1[i] y = v2[i] sumxx += x*x sumyy += y*y sumxy += x*y return 1.0 - sumxy / math.sqrt(sumxx * sumyy)
ab5eb9782d74546663c59a844eecd39ef01a0a97
479,288
def get_manifest_out_of_files(files): """ Parses `files` for a file that ends with `androidmanifest.xml`. :param Set[str] files: list of paths to files as absolute paths :return: manifest string if in `files`, else None """ for file_name in files: if file_name.lower().endswith("androidmanifest.xml"): return file_name return None
6e9e209920a7bc1a810679ab3d20eb7e2a2048ef
614,140
def get_module_task_instance_id(task_instances): """ Return the first task instance that is a module node. """ for id in task_instances: if task_instances[id] == 'module_node': return id return None
0423f87090d9b71f5a83d07f8719ccb870f4d275
288,368
from typing import Callable def search(low: int, high: int, test: Callable[[int], bool]) -> int: """Binary search: [low..high) is the range to search; function "test" takes a single value from that interval and returns a truth value. The function must be ascending: (test(x) and y >= x) => test(y). Returns smallest argument in the interval for which the function is true, or "high" if the function is false for the entire interval. """ while low < high: mid = (low + high - 1) // 2 if test(mid): if mid == low: return low # found high = mid + 1 else: low = mid + 1 return high
047ee9fbb21461d02299f7d8a27dd37d29757717
76,181
import posixpath def decode_single_feature_from_dict( feature_k, feature, tfexample_dict): """Decode the given feature from the tfexample_dict. Args: feature_k (str): Feature key in the tfexample_dict feature (FeatureConnector): Connector object to use to decode the field tfexample_dict (dict): Dict containing the data to decode. Returns: decoded_feature: The output of the feature.decode_example """ # Singleton case if not feature.serialized_keys: data_to_decode = tfexample_dict[feature_k] # Feature contains sub features else: # Extract the sub-features from the global feature dict data_to_decode = { k: tfexample_dict[posixpath.join(feature_k, k)] for k in feature.serialized_keys } return feature.decode_example(data_to_decode)
e61120e6889c66c57813146845a3b15620ab5f33
473,461
def minSegment(self,*args,**kwargs): """ Get segment min length """ return self._np(isNorm=False,isSegment=True)
881bd0fc7f5ec45f30e16cd00f838636f6e3a645
176,487
def is_sim_meas(op1: str, op2: str) -> bool: """Returns True if op1 and op2 can be simultaneously measured. Args: op1: Pauli string on n qubits. op2: Pauli string on n qubits. Examples: is_sim_meas("IZI", "XIX") -> True is_sim_meas("XZ", "XX") -> False """ if len(op1) != len(op2): raise ValueError( "Pauli operators act on different numbers of qubits." ) for (a, b) in zip(op1, op2): if a != b and a != "I" and b != "I": return False return True
03484aed2c5d4a9181056ff376b8252eab69327c
238,485
def binary_boundary(t, d): """ Return the last <t integer that is a multiple of 2^d >>> binary_boundary(11, 4) 0 >>> binary_boundary(11, 3) 8 >>> binary_boundary(11, 2) 8 >>> binary_boundary(11, 1) 10 >>> binary_boundary(15, 4) 0 >>> binary_boundary(16, 4) 16 >>> binary_boundary(15, 3) 8 >>> binary_boundary(15, 2) 12 >>> binary_boundary(15, 1) 14 """ return t - (t & ((1<<d) - 1))
b4c3f1a183166fa113cad5634fe58c6ebfe06776
154,296
def collatz(n): """ The Collatz sequence generating function: f(n) = (1/2)n if n is even, or 3n + 1 if n is odd """ return int(n / 2) if n % 2 == 0 else 3*n + 1
58b68c63f17c72a1097a49456be5135ed85c48b4
592,781
def printBond(bond): """Generate bond line Parameters ---------- bond : Bond Object Bond Object Returns ------- bondLine : str Bond line data """ R0 = 0.1*bond.R0 K0 = bond.K0*836.80 return '<Bond class1=\"%s\" class2=\"%s\" length=\"%0.6f\" k=\"%0.6f\"/>\n' % (bond.atomA.type_q, bond.atomB.type_q, R0, K0)
813b5d67eaa9119efc74bf018e647486faa0074b
626,219
import hashlib def hash256(string): """ Create a hash from a string """ grinder = hashlib.sha256() grinder.update(string.encode()) return grinder.hexdigest()
7409e5053a3ee61f534ec05edfffaf63bd6ca3e6
656,348
def _get_tag_name_from_entries(media_entries, tag_slug): """ Get a tag name from the first entry by looking it up via its slug. """ # ... this is slightly hacky looking :\ tag_name = tag_slug for entry in media_entries: for tag in entry.tags: if tag['slug'] == tag_slug: tag_name = tag['name'] break break return tag_name
0906c849f632a0f17c0e5128cd13baf0f3d3264a
595,753
def request_add_host(request, address): """ If the request has no headers field, or request['headers'] does not have a Host field, then add address to Host. :param request: a dict(request key, request name) of http request :param address: a string represents a domain name :return: request after adding """ request.setdefault('headers', {}) request['headers'].setdefault('Host', address) return request
0ae2eb267e5042b3a662fb8f8b6bb4ec03c56b37
630,340
import struct def _pad_float32(pos: int) -> int: """ Helper method to pad to the next page boundary from a given position. Parameters ---------- pos : int Current offset Returns ------- padding : int Required padding in bytes. """ float_size = struct.calcsize('<f') return float_size - (pos % float_size)
29d6258ea15139b20f613b81fef389987f4581b0
295,366
def derivative_tanh(tanh_output): """ Compute derivative of Tanh function """ return 1 - tanh_output**2
8343d3bdb1b3385bd257f4ed7891b3414deec080
314,221
import requests def can_connect_to_wiktionary() -> bool: """Check whether WAN connection to Wiktionary is available.""" try: requests.get("https://en.wiktionary.org/wiki/linguistics") except (requests.ConnectionError, requests.ConnectTimeout): return False else: return True
61030a79f58f694f62693f02f35255e65a1e1390
211,059
def time_calc(ttime): """Calculate time elapsed in (hours, mins, secs) :param float ttime: Amount of time elapsed :return: int, int, float """ # create local copy tt = ttime # if not divisible by 60 (minutes), check for hours, mins, secs if divmod(tt, 60)[0] >= 1: h_t = divmod(tt, 60 * 60)[0] tt = tt - (h_t * 60 * 60) m_t = divmod(tt, 60)[0] tt = tt - (m_t * 60) s_t = tt return h_t, m_t, s_t # only return seconds else: h_t = 0 m_t = 0 s_t = tt return h_t, m_t, s_t
efcc768c0c45b846c4328ed2eef20a510d02d919
322,810
def to_hgvs(variants, reference=None, only_substitutions=True, sequence_prefix=False, sort=True): """An allele representation of a list of variants in HGVS [1]_. Parameters ---------- variants : list A list of variants. reference : str or None, optional The reference sequence. Other Parameters ---------------- only_substitutions : bool, optional Deleted symbols are filled in only for HGVS substitutions by default. sequence_prefix : bool, optional Prefix the allele description with the reference sequence (not RefSeq ID). sort : bool, optional The `variants` are sorted by default. Disable if already sorted. Returns ------- str The allele representation in HGVS. References ---------- [1] https://varnomen.hgvs.org/recommendations/DNA/variant/alleles/. """ prefix = "" if reference is not None and sequence_prefix: prefix = f"{reference}:g." if len(variants) == 0: return f"{prefix}=" if len(variants) == 1: return f"{prefix}{variants[0].to_hgvs(reference, only_substitutions)}" return f"{prefix}[{';'.join([variant.to_hgvs(reference, only_substitutions) for variant in (sorted(variants) if sort else variants)])}]"
f97014d556c4f99ddb4f759113f0ddc8975db3f7
410,618
def split_identifier(identifier): """Splits string at _ or between lower case and uppercase letters.""" prev_split = 0 parts = [] if '_' in identifier: parts = [s.lower() for s in identifier.split('_')] else: for i in range(len(identifier) - 1): if identifier[i + 1].isupper(): parts.append(identifier[prev_split:i + 1].lower()) prev_split = i + 1 last = identifier[prev_split:] if last: parts.append(last.lower()) return parts
820486a85e17756f49fb4b18be995f0d4d2a1e92
553,940
def kyc_token(chain, team_multisig, initial_supply): """Create the token contract.""" args = ["KYC token", "KYC", initial_supply, 18, True] # Owner set tx = { "from": team_multisig } contract, hash = chain.provider.deploy_contract('CrowdsaleToken', deploy_args=args, deploy_transaction=tx) return contract
75f505d063b24a943adf4b7692a49ee17feffde4
296,340
import torch def quat_conjugate(a: torch.Tensor) -> torch.Tensor: """Computes the conjugate of a quaternion. Args: a: quaternion to compute conjugate of, shape (N, 4) Returns: Conjugated `a`, shape (N, 4) """ shape = a.shape a = a.reshape(-1, 4) return torch.cat((-a[:, :3], a[:, -1:]), dim=-1).view(shape)
530eb2a8d8b9b87de2bfcaeb48729704908131cc
14,132
def get_seq(query_filepath): """ Get a sequence from a single-entry FASTA file. """ f = open(query_filepath,'r') lines = f.readlines() lines = [row.strip() for row in lines] # restituisce una copia della stringa con i caratteri iniziali e finali rimossi per le righe in fila lines = [row.replace('\n', '') for row in lines if not row.startswith('>')] return ''.join(lines)
fd77760a389e192d60ecc592e1a3ca8fa1c9b17e
618,876
def parse_colon_delimited_options(option_args): """Parses a key value from a string. Args: option_args: Key value string delimited by a color, ex: ("key:value") Returns: Return an array with the key as the first element and value as the second Raises: ValueError: If the key value option is not formatted correctly """ options = {} if not option_args: return options for single_arg in option_args: values = single_arg.split(':') if len(values) != 2: raise ValueError('An option arg must be a single key/value pair ' 'delimited by a colon - ex: "thing_key:thing_value"') key = values[0].strip() value = values[1].strip() options[key] = value return options
7d083298ed9c35853b352fe545d9e15a69089694
544,410
def GetLabel(plist): """Plists have a label.""" return plist['Label']
b6692b603c72e829fe819e22dc219905f6db151f
646,196
def output(output_name, product_index=0): """Return a selector function for a specified output of a product. :param output_name: the name of the output to select :param product_index: which product's outputs to look in """ return lambda facility: facility.products[product_index].outputs[output_name]
d038db0650352c6d94a9e794c31e56afce1c13ea
341,532
def to_money(money_value: float) -> str: """Returns the float as a string formatted like money.""" return '{:,.2f}'.format(money_value)
054251804e5d918ce81a949c705e91e7a26c70b2
255,085
def linecoef(p1, p2): """ Coefficients A, B, C of line equation (Ax + By = C) from the two endpoints p1, p2 of the line Input: p1, p2 the two points (x, y) of the line segment Output: Coefficients of the line equation """ # ref: https://stackoverflow.com/questions/20677795/ # how-do-i-compute-the-intersection-point-of-two-lines-in-python A = (p1[1] - p2[1]) B = (p2[0] - p1[0]) C = (p1[0] * p2[1] - p2[0] * p1[1]) return A, B, -C
03fac6db5b9b425e03421f963008876aff854a51
318,290
def _find_direct_matches(list_for_matching, list_to_be_matched_to): """ Find all 100% matches between the values of the two iterables Parameters ---------- list_for_matching : list, set iterable containing the keys list_to_be_matched_to : list, set iterable containing the values to match to the keys Returns ------- matched : dict all 100% matches """ matches = dict() for entry_a in list_for_matching.copy(): if entry_a in list_to_be_matched_to: matches[entry_a] = entry_a list_for_matching.remove(entry_a) list_to_be_matched_to.remove(entry_a) return matches
c333a6f719a768bdfc1f4b615b22c48dd7b34e73
438,997