content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def near_points(px, qx, r, pxtree=None, qxtree=None): """ Finds points in qx that are within a distance r of any point in px Parameters: px, required, float(np, dim), coordinates of px qx, required, float(nq, dim), coordinates of py r, required, float, radius of closeness ...
d9ee596d0b3dc02247f8df31ea521a978b79a1f2
3,628,719
def batch_dtype(observation_space, action_space): """Returns a batch dtype for the provided observation and action spaces. Args: observation_space -- the observation space action_space -- the action space Returns a complex numpy dtype for the batch """ states_dtype = np.dtype((obse...
1525d9a2817a97b748ffd06c20b88b2e7d25a538
3,628,720
def runQuery(tStart, tStop): """ Get all the rows from all the events within the time period of _tStart_ and _tStop_. :param tStart: start of the time period :param tStop: stop of the time period :return: an array of all the events between _tStart_ and _tStop_ """ mariadb_connection = mariad...
b3dd62cc41a8a5da331190303b4008a135c07dbb
3,628,721
from datetime import datetime import pytz def get_aware_utc_now(): """Create a timezone aware UTC datetime object from the system time. :returns: an aware UTC datetime object :rtype: datetime """ utcnow = datetime.utcnow() utcnow = pytz.UTC.localize(utcnow) return utcnow
b0b102b8d7d49e0d7d4041a476502cdd683dc8af
3,628,722
from typing import Optional from typing import Callable from typing import Iterator from typing import Any import inspect def iterpoints(resp: dict, parser: Optional[Callable] = None) -> Iterator[Any]: """Iterates a response JSON yielding data point by point. Can be used with both regular and chunked respons...
000c2c873ab38378bb42945ed3304213b254061a
3,628,723
def evaluation(board: chess.Board, deciding_agent): """ Basic heuristic. :param board: The current state of the game The current state of the game :param deciding_agent: The identity of the "good" agent. :return: Heuristic value for the state """ # Define 1 for myself and -1 for rival: ...
95bbc6c7b3dfd20b7c88b172f5b42adbada64247
3,628,724
import time def calculate_temperature(T0, setpoint, K, omega, Tvar): """ Calculate temperature according to the following formula: :math:`T_{output} = T_{var} exp^{-(t - t_0)/K} sin(ω t) + T_{setpoint}` """ t = time.monotonic() return ((Tvar * np.exp(-(t - T0) / K) * ...
3c56efe329e7f393b0bf1d6829fdcd0b0b32a557
3,628,725
def nodes_visited_for_seq_ref(distance, max_array, min_array, list_parent_node): """ """ boolean_grp = np_logical_and(np_less_equal(distance, max_array), np_greater(distance, min_array)) count_visited_nodes = np_sum(boolean_grp) not_boolean_grp = np_logical_not(boo...
a85b86a28993d25f9c3b0a3b1f6ff0d8db5edab6
3,628,726
def bdc_plot_datasets(datasets, zoom = 4, layout=Layout(width='600px', height='600px')): """Plot Dataset tiles """ bbox = get_bounds(datasets, datasets[0].crs) bbox_pol = shapely.wkt.loads(bbox.wkt) project = partial( pyproj.transform, pyproj.Proj(datasets[0].crs.crs_str), ...
6c05b84571dbef30116debb3605f14e56acb176c
3,628,728
def indexation(obj, key): """:yaql:operator indexer Returns value of attribute/property key of the object. :signature: obj[key] :arg obj: yaqlized object :argType obj: yaqlized object, initialized with yaqlize_indexer equal to True :arg key: index name :argType key: keyword :re...
3848641447a50e0059c7ce4d68318ff832d2f5f1
3,628,730
def convert_output_key(name): """ Convert output name into IE-like name :param name: output name to convert :return: IE-like output name """ if not isinstance(name, tuple): return name if len(name) != 2: raise Exception('stats name should be a string name or 2 elements tuple ' ...
d5c59766c615e0e7b45f173948692050a7b890e3
3,628,731
def collection(identifier: str): """Get a collection. --- tags: - collection parameters: - name: prefix in: path description: The identifier of the collection required: true type: string example: 0000001 - name: format description: The file type in:...
1f37d74617d6e92fa4f955214b1f613856a8dadf
3,628,732
def tensor_shape_proto(output_size): """ The shape of this tensor. """ return TensorShapeProto(dim=[TensorShapeProto.Dim(size=d) for d in output_size])
f5b89370c62259349c27c0da1558b2abb5160173
3,628,733
def check_raises(physical_line, filename): """Check raises usage N354 """ ignored_files = ["./tests/unit/test_hacking.py", "./tests/hacking/checks.py"] if filename not in ignored_files: if re_raises.search(physical_line): return (0, "N354 ':Please use ':rai...
9c735f485fdf73d0914abd105ddb6ff39140fda2
3,628,734
def eval_expr(src, env=None, **kwargs): """ Similar to eval_ast, but receives expression as a string and variables as keyword arguments. """ env = {} if env is None else env env.update(kwargs) return eval_ast(parser(src), env)
752e7198476f528916e2252a0d78b0586f7a88b8
3,628,735
def tasksInView(): # pragma: no cover """Iterate over all the tasks in view.""" return filter(isTask, itemsInView())
b46b9c75590bc36aac015470e1d04183752a7855
3,628,736
def in_polygon(point, polygon): """Simple wrapper on the within method of shapely points Params: point (POINT) a shapely point object polygon (POLYGON) a shapely polygon object (the target overlap area) Returns: (bool) whether or not the point is within polygon expressed as a boolean "...
0a26d023672162a53affddfe23a89361d900d9a0
3,628,737
def sort_points(points:list) -> list: """ Returns a list of point tuples equivalent to points, but sorted in order by ascending x coordinate. >>> sort_points([(5,4),(2,3)]) [(2,3),(5,4)] >>> sort_points([(1,1),(3,2),(2,3)]) [(1,1),(2,3),(3,2)] >>> sort_points([(99,120),(0,10),(200,...
007b20889ad7b474b891196da1ee9ed6e3286812
3,628,738
def NASNetMobile(input_shape=None, include_top=True, weights='imagenet', input_tensor=None, pooling=None, classes=1000): """Instantiates a Mobile NASNet model in ImageNet mode. Optionally loads weights pre-trained on ImageNet. N...
5cbfb237566dab72376fb14b167e48e2cb69b219
3,628,740
def dcn_resnet152(pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) if pretrained: pretrained_model = model_zoo.load_url(model_urls['resnet1...
edf6ab41af211cc37f04bf6614497be9e7a77293
3,628,741
import string def preprocessing(text): """Exclude punctuations and digits from text.""" text = process_tweets(text) text = text.lower() exclude = string.punctuation + string.digits for i in exclude: text = text.replace(i, "") return text
f390ce2b0c1a1ff831b5a7c7b2491b9c860ad4e4
3,628,742
import typing def parse_patter(pats: typing.List[str]) -> typing.Tuple[typing.List[str], typing.List[str]]: """ 分析匹配项 ======== /xx/ # 只匹配根目录下文件夹 xx/ # 匹配所有的文件夹 /xx # 只匹配根目录下文件 xx # 匹配所有的文件 !xx # 除xx之外 ========= /xx/ => xx + xx/** xx/ => xx + xx/...
17eca544b157fe2ad406e1c4385c49acc53ff0d7
3,628,743
def index(): """Job Status Index.""" return render_template('fts_index.html')
bd382655aea46c910ef66c6563a094186d5b2a51
3,628,744
def calc_brownian_displacement(dt, viscosity, particle_diameter, temperature): """ Calculate brownian motion characteristic displacement per dt """ kb = 1.3806e-23 # (J/K) Boltzmann constant dx = np.sqrt(2*kb*temperature*dt/(3*np.pi*viscosity*particle_diameter)) return dx
1bfdba75d0ad30b1f0dca790c47e004afa39b1b1
3,628,747
def manhattan_distance(v1, v2, norm=False): """ return ||v1 - v2||_1 """ v1, v2 = check_pairwise_vector(v1, v2, norm) diff = v1 - v2 K = np.abs(diff).sum() return K
c41f6c529bb7604a4ca0aa6487d8a2cc5225bf04
3,628,748
def read_data_submit(ftdi, buf, size): """ read_data_submit(context ftdi, unsigned char * buf, int size) -> transfer_control Reads data from the chip. Does not wait for completion of the transfer nor does it make sure that the transfer was successful. Use libusb 1.0 asynchronous API. Parame...
a70652e72d9a425e052b723fc12102742eab6121
3,628,749
def set_spines(ax, plot_params): """ Sets spines of the shift graph to be invisible if chosen by the user Parameters ---------- ax: Matplotlib ax Current ax of the shift graph plot_parms: dict Dictionary of plotting parameters. Here `invisible_spines` is used """ spines ...
4e74ce30f52d465e9470f608cd8c909dfae4d0a5
3,628,750
def update_user(id): """Method to handle update a user""" try: data = request.get_json() or {} user = Authentication() response = user.update_user(id, data) return response except KeyError: return ({"Error": "An error occured"})
398e28b6fb03f505512738ad28824e0c885693b4
3,628,751
import types def _normalize_resources(resources): """ Exclude any resources that have `/facebook` in the path as these are internal and require internal FB infra. Only applies to resources specified in the `dict` format Will also go ahead an invert the dictionary using `_invert_dict` """ if r...
16a0bd8cd1d4e4ec5ad8e929d8be969d95a1924e
3,628,752
def parse_targets(target): """ Parse provided targets :param target: Targets :return: List of IP addresses """ if '-' in target: ip_range = target.split('-') try: t = IPRange(ip_range[0], ip_range[1]) except AddrFormatError: try: st...
94e9a5784f0fa18bf7677e08fed62ee542a429d0
3,628,754
def lgam(x): """Natural log of the gamma fuction: see Cephes docs for details""" if x < -34: q = -x w = lgam(q) p = floor(q) if p == q: raise OverflowError("lgam returned infinity.") z = q - p if z > 0.5: p += 1 z = p - q ...
e165ee0f53aef367350ed964ae2d31374b847d59
3,628,755
def matches(G, queue): """ If the sequence in 'queue' correspond to a node in 'G', return the sequence id, otherwise return False """ if not queue: return False seq = 0 for a in queue: try: seq = G[seq][a] except KeyError: return False ...
859f43f6457b4add4cda88495a8dc6c4a559e5d5
3,628,756
def get_mu_sigma(prices, returns_model='mean_historical_return', risk_model='ledoit_wolf', frequency=252, span=500): """Get mu (returns) and sigma (asset risk) given a expected returns model and risk model prices (pd.DataFrame) – adjusted closing prices of the asset, each row i...
272196b663e43696166fa7134b6dd5d9c6a9c49c
3,628,757
def getPortList(chute): """ Get a list of ports to expose in the format expected by create_container. Uses the port binding dictionary from the chute host_config section. The keys are expected to be integers or strings in one of the following formats: "port" or "port/protocol". Example: po...
eb97568befca72f6d9cb6c455d8d9ad03b13eebf
3,628,758
from typing import Union from typing import Tuple from typing import Any from typing import Sequence def _apply_kraus_single_qubit( kraus: Union[Tuple[Any], Sequence[Any]], args: 'ApplyChannelArgs' ) -> np.ndarray: """Use slicing to apply single qubit channel. Only for two-level qubits.""" zero_left = li...
89b4d1ee99aafc01b8727c7a2c88337fac8e1273
3,628,759
def get_itk_array(path_or_image): """ Get an image array given a path or itk image. Parameters ---------- path_or_image : str or itk image Path pointing to an image file with extension among *TIFF, JPEG, PNG, BMP, DICOM, GIPL, Bio-Rad, LSM, Nifti (.nii and .nii.gz), Analyze, SD...
c8d16f5fb4bc55695183c1cb8b9dd20b57a9909f
3,628,760
def get_datasets_dbpedia(subset, limit): """ Loads dbpedia data from files, split the data into words and generates labels. Returns split sentences and labels. """ datasets = dict() data = [] target = [] target_int =[] target_names = [] filename = 'data/dbpedia/'+subset+'.cs...
03f567e814b3ca0227b558177feb8a2165256cfc
3,628,761
def cv_read(path): """Read an image using opencv. Args: path: path to image Returns: numpy array containing the RGB image """ image = cv2.imread(path) image = bgr_to_rgb(image) return image
3a3fff8edc5d533c394f611c020cc70986844608
3,628,762
def get_git_log_raw_output_for_two_commits(commit1, commit2): """ Get the git log raw output for a git commit. :param commit1: the first commit, which occurs earlier than commit2 :param commit2: the second commit, which occurs later than commit1 returns the git command output """ if not comm...
0acf4c81b38968e376de2294be1c6f6c1a47a53e
3,628,763
def _ragged_tile_axis(rt_input, axis, repeats): """Tile a dimension of a RaggedTensor to match a ragged shape.""" assert axis > 0 # Outermost dimension may not be ragged. if not ragged_tensor.is_ragged(rt_input): rt_input = ragged_conversion_ops.from_tensor(rt_input, ragged_rank=1) if axis > 1: retur...
1bed0ee8f239be0e370a5a853829699c4cfac511
3,628,766
import re def camelcase_to_snakecase(value: str) -> str: """ Convert a string from snake_case to camelCase. >>> camelcase_to_snakecase('') '' >>> camelcase_to_snakecase('foo') 'foo' >>> camelcase_to_snakecase('fooBarBaz') 'foo_bar_baz' >>> camelcase_to_snakecase('foo_bar_baz') ...
05fe02739e8152bc64ab35bd842162b5d7c3ab4c
3,628,767
from deephaven.TableTools import emptyTable def colorTable(): """ Returns a table which visualizes all of the named colors. :return: table which visualizes all of the named colors. """ return emptyTable(1) \ .updateView("Colors = colorNames()") \ .ungroup() \ ...
4a359979d9f44b8f6174f4a7939fd98da942cb2d
3,628,768
def not_found(error): """Custom error handler for bad requests""" return jsonify(dict(error = 'Not Found, resource not found')), 404
89e125144637258a4b663c489967f6187ce50744
3,628,769
def string_distance(str1, str2): """ 计算两个字符串之间的编辑距离 @author: 仰起脸笑的像满月 @date: 2019/05/15 :param str1: :param str2: :return: """ m = str1.__len__() n = str2.__len__() distance = np.zeros((m + 1, n + 1)) for i in range(0, m + 1): distance[i, 0] = i for i in rang...
1dbdcddd13f7a7f5d62e6028a045f224d10984a1
3,628,770
def best_archiver(random, population, archive, args): """Archive only the best individual(s). This function archives the best solutions and removes inferior ones. If the comparison operators have been overloaded to define Pareto preference (as in the ``Pareto`` class), then this archiver will form ...
20d606f5ea4d76b1c6bd2acfd6bf1017e694f026
3,628,771
def contacts_per_person_normal_self_30(): """ Real Name: b'contacts per person normal self 30' Original Eqn: b'30' Units: b'contact/Day' Limits: (None, None) Type: constant b'' """ return 30
cbb35d2d87ed961a7295615598294d231de032dd
3,628,774
import re def process_text2phrases(text, clinical_ner_model): """ 用于从文本中提取Clinical Text Segments :param text:自由文本 :param clinical_ner_model: Stanza提供的预训练NER模型 :return: List[PhraseItem] """ tokenizer = SpanTokenizer() spliters = getSpliters() stopwords = getStopWords() # 将文本处理成正...
c92e3bc458ee75b472cf4766b7d6111004589a62
3,628,775
def get_all(isamAppliance, check_mode=False, force=False): """ Receives all services """ return isamAppliance.invoke_get("Receiving all Services", module_uri)
67f6939c1b7b30898064c1b196bff852424e90e7
3,628,776
from scipy.stats import norm def numeric_outlier(feature, keep_rate=0.9545, mode='right', feature_scale=None): """feature clip outlier. Args: feature: pd.Series, sample feature. keep_rate: default 0.9545, method: default 'right', one of ['left', 'right', 'both'], statistical dist...
6d675cad7694fa6481e979f19dc35b9e99cdff38
3,628,777
def elk_index(hashDict): """ Index setup for ELK Stack bulk install """ index_tag_full = {} index_tag_inner = {} index_tag_inner['_index'] = "hash-data" index_tag_inner['_id'] = hashDict['hashvalue'] index_tag_full['index'] = index_tag_inner return index_tag_full
9adcc529b88b319180e223ba9e47bda51e628478
3,628,778
def build_2d_gauss_data(mu_1, mu_2, sig_1, sig_2, samples, changes={}, w=50, alpha=0.1, lags=0): """Build a bivarite dataset following a Gaussian distribution. Parameters ---------- mu_1 : float Mean of x_1. mu_2 : float Mean of x_2. sig_1 : float ...
4b523e4c417fc223a19a1630004d0479fbe02b42
3,628,779
def parse_between_expression(var_dict, variable, expression_dict): """ Takes an integer variable and a string:string expression_dict. The key string is a semicolon-separated expression denoting the lower and upper bounds of the value it can match, while the value string is a simple arithmetic expression...
221c1d6d5da3f079fb9bad6f9a6908a036720d7c
3,628,780
def get_tag(el): """ :returns: `geographic_msgs/KeyValue`_ message for `<tag>` *el* if any, None otherwise. """ pair = None key = el.get('k') if key != None: pair = KeyValue() pair.key = key pair.value = get_required_attribute(el, 'v') return pair
2650603e5b88a51cef3dce3ef29478c3ccda79ca
3,628,781
from typing import Dict from typing import Any from typing import Tuple def json_to_transactions(json_data: Dict[Any, Any]) -> Tuple[Transaction, ...]: """ Convert json data to tuple of transaction objects. Parameters ---------- json_data : The transactions data where the values are hexad...
2444e778331874eff4b2b385b0b9aab113a436c2
3,628,782
def textureLightingCost(texParam, img, vertexCoord, sh, model, renderObj, w = (1, 1), option = 'tl', constCoef = None): """ Energy formulation for fitting texture and spherical harmonic lighting coefficients """ if option is 'tl': texCoef = texParam[:model.numTex] shCoef = texParam[model...
95a54db4eba8ac799cde237805999ee47078d2ab
3,628,783
def find_reaction_by_index(rxn:list,num:int)-> object: """ find reactions by chemkin reaction index :param rxn: (list) rmg reaction list :param num: (int) chemkin reaction index :return: rmg reaction """ #x1 = [] for react in rxn: if react.index==num: #x1.append(react...
99e98bd29fbce92d538e41f6dda124be2c861dc1
3,628,784
def timeIntegration(params): """ TIMEINTEGRATION : Simulate a network of aLN modules Return: rates_exc: N*L array : containing the exc. neuron rates in kHz time series of the N nodes rates_inh: N*L array : containing the inh. neuron rates in kHz time series of the N nodes ...
8f97380549d58e6b20a6df4ede3e16fd84b19d57
3,628,786
def string_similarity(s1, s2): """ Get a float representation of the difference between 2 strings. Args: s1: string s2: string Returns: float """ return SequenceMatcher(None, s1, s2).ratio()
42faeb337edade5290d58a9f712d8de9a51118f5
3,628,787
from re import T import torch def pinv(mat: T.FloatTensor) -> T.FloatTensor: """ Compute matrix pseudoinverse. Args: mat: A square matrix. Returns: tensor: The matrix pseudoinverse. """ U, s, V = torch.svd(mat) S = unsqueeze(s.reciprocal(), axis=0) return multiply(V,...
0727e4b980cf1284920e431ed90e2fa5922083d2
3,628,788
from typing import Mapping def get_remappings_full() -> Mapping[str, str]: """Get the remappings for xrefs based on the entire xref database.""" return _get_curated_registry()["remappings"]["full"]
89dbf2f65a628ec7b5df010df0af5863ad4433ae
3,628,789
def attention(img, att_map): """ Inputs: img -- original image att_map -- attention map, in this case shape (7,7) or (7,7,1,1) else. To visualize just imshow new_img """ att_map = np.reshape(att_map, [7,7]) att_map = att_map.repeat(32, axis=0).repeat(32, axis=1) att_map = n...
262e33d7ec2d4ed0c97acccebc9e98ce8d35babe
3,628,790
import scipy def _winsorize_wrapper(x, limits): """ Wraps scipy winsorize function to drop na's """ if hasattr(x, 'dropna'): if len(x.dropna()) == 0: return x x[~np.isnan(x)] = scipy.stats.mstats.winsorize(x[~np.isnan(x)], ...
49cade19f486d596241ef5eaf18c2a8c3c7a078f
3,628,791
def haversine(lon1, lat1, lon2, lat2, unit = 'km'): """Calculate the great circle distance between two lat/lons. Adapted from https://stackoverflow.com/questions/4913349 Parameters ---------- lon1 : :obj:`float` or vector of :obj:`float` Longitude of 1st point lat1 : :obj:`float` or ve...
09aabd13b60b863d38199a9e156f4d2240e0903e
3,628,792
def get_datatype() -> str: """Returns a user specified datatype to be used elsewhere. Returns ------- desired_datatype: str User specified datatype from list. """ data_func, data_args = get_inquirer("choices") data_args["choices"] = DATATYPE_NAMES datatype_call = data_func(**dat...
3b0a2d187dc61336b3d23e9c2ae88347a2859b5f
3,628,793
def stereonet2xyz(lon, lat): """ Converts a sequence of longitudes and latitudes from a lower-hemisphere stereonet into _world_ x,y,z coordinates. Parameters ---------- lon, lat : array-likes Sequences of longitudes and latitudes (in radians) from a lower-hemisphere stereonet ...
3ecb65cf60bed31199745df50199a6e666f9e3fd
3,628,794
def sky_to_cartesian(rdd, degree=True, dtype=None): """ Transform distance, RA, Dec into cartesian coordinates. Parameters ---------- rdd : array of shape (3, N), list of 3 arrays Right ascension, declination and distance. degree : default=True Whether RA, Dec are in degrees (`...
9e70245ccb2c6c0c97a4be4e2e5c00398d119564
3,628,795
def delete(id): """Delete post function""" data = Post.query.get(id) db.session.delete(data) db.session.commit() flash("Post successfully deleted") return redirect(url_for(".index2"))
4988c197429208e8e54a52370706aa211067cc5d
3,628,796
import six def repeat_n_times(n, fn, *args, **kwargs): """ Repeat apply fn n times. Args: n: n times. fn: a function or a list of n functions. *args: additional args. Each arg should either be not a list, or a list of length n. **kwargs: additional keyword args. Ea...
f08437f560f1ec6eb967c4236e017a6b123df8e0
3,628,797
def get_submissions(request, domain_id=0): """ Takes a POST containing a tar of all MD5's and returns a tar of all missing submissions Heh, this is explicitly against good REST methodology We leave this inside the django-rest 'Resource' so we can use their authentication tools """ try:...
c689f429665867e1b74f8ca8d11bdcfc3e89930f
3,628,798
import uuid def generate_unique_str(allow_dashes=True): """ Generate unique string using uuid package Args: allow_dashes (bool, optional): If true use uuid4() otherwise use hex that will skip dash in names. Defaults to True. """ if allow_dashes: unique_str = str(uuid.uuid4()) ...
9a08364837ea719454b885fcb344631005e7a610
3,628,799
import ssl import socket import time async def tls(q, where, timeout=None, port=853, source=None, source_port=0, one_rr_per_rrset=False, ignore_trailing=False, sock=None, backend=None, ssl_context=None, server_hostname=None): """Return the response obtained after sending a query via TL...
9a2904719b338387721350d4ff0fe95cf0332cf4
3,628,800
def create_resource(): """Users resource factory method""" return wsgi.Resource(Controller())
db9b827051463b0e629dab13602ccd731e8f718f
3,628,801
import re def validip(ip, defaultaddr="0.0.0.0", defaultport=8080): """ Returns `(ip_address, port)` from string `ip_addr_port` >>> validip('1.2.3.4') ('1.2.3.4', 8080) >>> validip('80') ('0.0.0.0', 80) >>> validip('192.168.0.1:85') ('192.168.0.1', 85) ...
5a353c8e8a008935f94905445ff12ba517b350d0
3,628,802
def get_rcs2body(el_deg=37.0, az_deg=0.0, side='left') -> isce3.core.Quaternion: """ Get quaternion for conversion from antenna to spacecraft ijk, a forward- right-down body-fixed system. For details see section 8.1.2 of REE User's Guide (JPL D-95653). Parameters ---------- el_deg : float ...
7f9d4470b3640daf6742e438225fc5f7faa59790
3,628,803
import urllib def obtain_parse_wiki_stocks_sp500(url): """Download and parse the Wikipedia list of S&P500 constituents using requests and libxml. Returns a list of tuples for to add to MySQL.""" # Get S&P500 website content req = urllib.request.Request(url) response = urllib.request.urlopen(req) data...
13f088ee4e84c9bb377daa0bfb989c06d82359c7
3,628,804
import calendar def parseISO(s): """Parse ISO8601 (string) date into a floating point seconds since epoch UTC. The string must be an ISO8601 date of the form YYYY-MM-DDTHH:MM:SS[.fff...](Z|[+-]dd:dd) If something doesn't parse, a DateFormatError will be raised. The return value is floatin...
05886cdbb90020a7331f70a708a970aff1bd1b61
3,628,805
import requests import time def _get_data(url, attempts=5): """ Downloads data from a given url. Parameters ---------- url : str url to fetch data from attempts : int number of times to try to download the data in case of failure R...
b58bf34b5abeada9fa1fa2fec37511d8500a6e12
3,628,806
def ldns_str2period(*args): """LDNS buffer.""" return _ldns.ldns_str2period(*args)
a8840efd7ec114c343bc389a776931db23095082
3,628,807
def create_doctor_image_upload_url(): """Creates url for uploading image for doctor""" return reverse('doctor:doctor-image-upload')
f403f80ed996d19c816fc074277976260b2f31e4
3,628,808
from pathlib import Path def reformat_peer_data_csv(csv_file_path, time_step=0.005): """Reformat PEER motion records to column-wise, and save to csv. Typically, PEER data is given in a plane text file, with data disposed in horizontal consecutive arrays. This function serializes it in a single column...
c9d4301f8b418e40195049bae742195339e8fd2d
3,628,809
import six def compute_eval_metrics(labels, predictions, retriever_correct, reader_correct): """Compute eval metrics.""" # [] exact_match = tf.gather( tf.gather(reader_correct, predictions["block_index"]), predictions["candidate"]) def _official_exact_match(predicted_answ...
66cffa3d3f7b44f9d6b92e386eea1528d0f970d0
3,628,810
def tf_lovasz_grad(gt_sorted): """ Code from Maxim Berman's GitHub repo for Lovasz. Computes gradient of the Lovasz extension w.r.t sorted errors See Alg. 1 in paper """ gts = tf.reduce_sum(gt_sorted) intersection = gts - tf.cumsum(gt_sorted) union = gts + tf.cumsum(1. - gt_sorted) ...
756ddd32382c5361ecb3c0e8fd89de4882650d62
3,628,811
def phone_setup_4g_for_subscription(log, ad, sub_id): """Setup Phone <sub_id> Data to 4G. Args: log: log object ad: android device object sub_id: subscription id Returns: True if success, False if fail. """ return phone_setup_data_for_subscription(log, ad, sub_id, G...
07d91e295c7b007c0af6141a1fab94d473924243
3,628,812
import inspect import gc def empty(shape, dtype=np.float, order='c', description=None, verbose=None): """ Return a new aligned and contiguous array of given shape and type, without initializing entries. """ shape = tointtuple(shape) dtype = np.dtype(dtype) if verbose is None: verb...
4e5c980d83394ebf72cd3559dbfcb716a1e22c55
3,628,813
def IDcorner(landmarks): """landmarks:检测的人脸5个特征点 """ corner20 = twopointcor(landmarks[2, :], landmarks[0, :]) corner = np.mean([corner20]) return corner
06eae06d6efe563e177dbbeb791cea561596f418
3,628,814
def QColorAlpha(*args): """Build a QColor with alpha in one call This function allows to create a `QColor` and set its alpha channel value in a single call. If one argument is provided and it is a string parsable as hex, it is parsed as `#RRGGBBAA`. Else, the single argument is passed to QColor and thus alpha is ...
62c73b3a01b8330b836289aba3d31db97c6a9735
3,628,816
def video_signatures_exist(files, pipeline: PipelineContext): """Check if all required signatures do exist.""" return not any(missing_video_signatures(files, pipeline))
22467a8e2d58990cb9d210293e49e3238c1925b8
3,628,817
def _run_gn_desc_list_dependencies(build_output_dir: str, target: str, gn_path: str) -> str: """Runs gn desc to list all jars that a target depends on. This includes direct and indirect dependencies.""" return subprocess_utils.run_command( [gn_path, 'desc', '--all...
0785bdff84b79649451d3413bce858d20d2bc52e
3,628,818
def trainTfidfModel(tsvFile, wordIndex, ngram, dictionary): """ Train tf-idf model""" reader = DescriptionReader(tsvFile, wordIndex, ngram) # construct the dictionary one query at a time tfidf_model = models.tfidfmodel.TfidfModel( dictionary.doc2bow(d) for d in reader ) return tfidf_model
6020f8ec3e3ebe5ad280dd6dc40ed38860e77f5c
3,628,819
def IsUnion(sid): """ Is a structure a union? @param sid: structure type ID @return: 1: yes, this is a union id 0: no @note: Unions are a special kind of structures """ s = idaapi.get_struc(sid) if not s: return 0 return s.is_union()
e94e3b3fedf234a5781ddbf577290a9f07fcc25f
3,628,820
def import_atm_mass_info(): """ Funtion to load dictionary storing atomic mass information by atom type. dict dictionary of atomic mass by atom name """ massdict = {'H': 1.00797, 'HE': 4.0026, 'LI': 6.941, 'BE': 9.01218, ...
c470495f30d77b41642bfd07f52a82b7a060ffb5
3,628,821
def defaults(group1): """ Get globals for all model tests. """ values = Defaults() values.account_attributes = { 'uid': "tux", 'uidNumber': 10, 'givenName': "Tux", 'sn': "Torvalds", 'cn': "Tux Torvalds", 'telephoneNumber': "000", 'mail': "tuz@example....
ff82cb0f0f5177ffbc9d4c118b998e1e837ccac9
3,628,822
def get_move(state: State) -> State: """Get next move, check if it's legitimate. If it's not, record the error or the quit choice. Otherwise, update the board and determine if there's a winner or a draw.""" new_move = input(f'Player {state.player}, what is your move? [q to quit]: ') i...
2c76f2b06f246fa121138241b6b5da9c5e7e9981
3,628,823
def _project_im_rois(im_rois, scales): """Project image RoIs into the image pyramid built by _get_image_blob. Arguments: im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates scales (list): scale factors as returned by _get_image_blob Returns: rois (ndarray): R x 4 ma...
05c542fdfecd24d9578f26db6e0071e99cc9c2d1
3,628,824
def preprocess_recipe( adata, min_expr_level=None, min_cells=None, use_hvg=False, scale=False, n_top_genes=1500, pseudo_count=1.0, ): """A simple preprocessing recipe for scRNA data Args: adata (sc.AnnData): Input annotated data object min_expr_level (int, optional): ...
0b4c68ec3db9857dce824080d3bc26bd01d93ed4
3,628,825
async def pympler_tracker_diff(request: web.Request) -> web.StreamResponse: """ Get Pympler tracker diff: https://pympler.readthedocs.io/en/latest/ Example: curl -v -X POST 'localhost:9999/pympler/tracker/diff' curl -v -X POST 'localhost:9999/pympler/tracker/diff?print' """ global _tracker ...
644e6dfd5bca455ab4058cab4982c1c4880a1b6e
3,628,826
import time def toggle_40g_local(module): """ Method to toggle 40g ports to 10g ports. :param module: The Ansible module to fetch input parameters. :return: The output messages for assignment. """ output = '' cli = pn_cli(module) clicopy = cli cli += ' lldp-show format local-port n...
836bce0a54e9cdcb571490d9de42b6cf292710f5
3,628,827
def lazy_index(index): """Produces a lazy index Returns a slice that can be used for indexing an array, if no slice can be made index is returned as is. """ index = asarray(index) assert index.ndim == 1 if index.dtype.kind == 'b': index = index.nonzero()[0] if len(index) == 1: ...
907320c50921a66908154ed3475243d784effa9c
3,628,829
import copy def extreme_contrast(image: Image) -> Image: """ T081 Matthew Gray Returns a copy of the image that has extreme contast, the RGB values for each pixel are either 255 or 0. >>> file = load_image(choose_file()) >>> red_image = red_filter(file) >>> show(red_image) ...
d3ffd9c86dabb4994dd112627d3e6c2ef865e52b
3,628,830
def remove_batch_from_layout(layout): """ The tf-mesh layout splits across batch size, remove it. Useful for prediction steps, when you no longer want large batches. :param layout: string describing tf-mesh layout :return: layout minus batch dimension """ layout = layout.split(',') ret_...
44d032504055e1133a6dc97ea040ff44ea2ac327
3,628,831