hexsha
stringlengths
40
40
size
int64
1
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
239
max_stars_repo_name
stringlengths
5
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
239
max_issues_repo_name
stringlengths
5
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
239
max_forks_repo_name
stringlengths
5
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.03M
avg_line_length
float64
1
958k
max_line_length
int64
1
1.03M
alphanum_fraction
float64
0
1
4a102362397af8fb5c0a1ce280ddc752356d7ab2
4,840
py
Python
cipher/process_multitask.py
kaczmarj/cipher
e1ad5bb4ca86a7c45f54bb4fdb6f05d6c4a1b1a9
[ "MIT" ]
null
null
null
cipher/process_multitask.py
kaczmarj/cipher
e1ad5bb4ca86a7c45f54bb4fdb6f05d6c4a1b1a9
[ "MIT" ]
null
null
null
cipher/process_multitask.py
kaczmarj/cipher
e1ad5bb4ca86a7c45f54bb4fdb6f05d6c4a1b1a9
[ "MIT" ]
null
null
null
""" This script will take the following arguments in the command line, import helper functions from an external script, and conduct all preprocessing steps Parameters: ----------- metadata: str location for metadata table containing experiment information data_dir: str directory containing corresponding sequencing data files output:str Optional.Directory for output file. Default to current directory assembly: str Optional. Default to be 'GRCh38' chrom_size:str Optional. Location for .chome.size file subset: str Optional. Path where the subset of metadata table used will be saved as a to_csv. Default to current directory criteria: dict Optional.Dictionary of column, value pairs to use in making a selection Defulat to {'Output type':'IDR thresholded peaks'} exp_accession_list:list Optional. List of experiments to select, if empty select all in the metadata table """ # TODO: the documentation is likely part of the parser help message. We can probably # remove it. from optparse import OptionParser import subprocess from .metadata_to_samplefile import create_samplefile from .bed_generation import multitask_bed_generation from .seq_hdf5 import make_h5 def main(): parser = OptionParser() parser.add_option( "--feature_size", dest="feature_size", default=1000, help="length of selected sequence regions", ) parser.add_option( "--fasta", dest="fasta", help="length of selected sequence regions" ) parser.add_option( "--output", dest="h5_output", default="output.h5", help="Directory for output h5 file. Default to current directory", ) parser.add_option( "--sample_output", dest="exp_output", default="sample_beds.txt", help="Directory for output sample file. Default to current directory", ) parser.add_option( "--bed_output", dest="bed_output", default="merged_features", help="Directory for output merged peak bed file. Default to current directory", ) parser.add_option( "--header_output", dest="header_output", default="output_header", help="Directory for output h5 file. Default to current directory", ) parser.add_option( "--fasta_output", dest="fa_output", default="selected_region.fa", help="Directory for output sub-fasta file. Default to current directory", ) parser.add_option( "--assembly", dest="g_assembly", default="GRCh38", help="genome assembly used for reference. Optional.", ) parser.add_option( "--chrom_size", dest="chrom_size", help="Location of chromosome size file" ) parser.add_option( "--subset", dest="subset_output", default="selected_data.csv", help="path where the subset of metadata table used will be saved as a to_csv", ) parser.add_option( "--criteria", dest="criteria", default={}, help="dictionary of column, value pairs to use in making a selection", ) parser.add_option( "--exp_accession_list", dest="exp_accession", default=None, help="List of experiments to select, if empty select all in the metadata table", ) parser.add_option( "--merge_overlap", dest="overlap", default=200, help=( "if two peak regions overlaps more than this amount, they will be" " re-centered and merged into a single sample" ), ) (options, args) = parser.parse_args() if len(args) != 2: parser.error("Must provide data directory and metadata table path.") else: data_dir = args[0] metadata_path = args[1] # call package functiond create_samplefile( data_dir, metadata_path, assembly=options.g_assembly, sample_output_path=options.exp_output, subset_output_path=options.subset_output, criteria=options.criteria, exp_accession_list=options.exp_accession, ) multitask_bed_generation( options.exp_output, chrom_lengths_file=options.chrom_size, feature_size=options.feature_size, merge_overlap=options.overlap, out_prefix=options.bed_output, ) # TODO: shell=True is probably not necessary here. Remove once tests are in place. subprocess.call( "bedtools getfasta -fi {} -s -bed {} -fo {}".format( options.fasta, options.bed_output + ".bed", options.fa_output ), shell=True, ) make_h5( options.fa_output, options.bed_output + "_act.txt", options.h5_output, options.header_output, ) if __name__ == "__main__": main()
30.440252
88
0.651033
4a10244368b2afb1e88e770cad4cacbab409fc36
8,304
py
Python
setup.py
dnaveenr/datasets
f144ba69aee057e9e1447796712302adc3d6558a
[ "Apache-2.0" ]
null
null
null
setup.py
dnaveenr/datasets
f144ba69aee057e9e1447796712302adc3d6558a
[ "Apache-2.0" ]
null
null
null
setup.py
dnaveenr/datasets
f144ba69aee057e9e1447796712302adc3d6558a
[ "Apache-2.0" ]
null
null
null
# Lint as: python3 """ HuggingFace/Datasets is an open library of datasets. Note: VERSION needs to be formatted following the MAJOR.MINOR.PATCH convention (we need to follow this convention to be able to retrieve versioned scripts) Simple check list for release from AllenNLP repo: https://github.com/allenai/allennlp/blob/master/setup.py To create the package for pypi. 0. Prerequisites: - Dependencies: - twine: "pip install twine" - Create an account in (and join the 'datasets' project): - PyPI: https://pypi.org/ - Test PyPI: https://test.pypi.org/ 1. Change the version in: - __init__.py - setup.py - docs/source/conf.py 2. Commit these changes: "git commit -m 'Release: VERSION'" 3. Add a tag in git to mark the release: "git tag VERSION -m 'Add tag VERSION for pypi'" Push the tag to remote: git push --tags origin master 4. Build both the sources and the wheel. Do not change anything in setup.py between creating the wheel and the source distribution (obviously). First, delete any "build" directory that may exist from previous builds. For the wheel, run: "python setup.py bdist_wheel" in the top level directory. (this will build a wheel for the python version you use to build it). For the sources, run: "python setup.py sdist" You should now have a /dist directory with both .whl and .tar.gz source versions. 5. Check that everything looks correct by uploading the package to the pypi test server: twine upload dist/* -r pypitest --repository-url=https://test.pypi.org/legacy/ Check that you can install it in a virtualenv/notebook by running: pip install huggingface_hub fsspec aiohttp pip install -U tqdm pip install -i https://testpypi.python.org/pypi datasets 6. Upload the final version to actual pypi: twine upload dist/* -r pypi 7. Fill release notes in the tag in github once everything is looking hunky-dory. 8. Update the documentation commit in .circleci/deploy.sh for the accurate documentation to be displayed. Update the version mapping in docs/source/_static/js/custom.js with: "python utils/release.py --version VERSION" Set version to X.X.X+1.dev0 (e.g. 1.8.0 -> 1.8.1.dev0) in: - setup.py - __init__.py 9. Commit these changes: "git commit -m 'Release docs'" Push the commit to remote: "git push origin master" """ import os from setuptools import find_packages, setup REQUIRED_PKGS = [ # We use numpy>=1.17 to have np.random.Generator (Dataset shuffling) "numpy>=1.17", # Backend and serialization. # Minimum 5.0.0 to support mix of struct and list types in parquet, and batch iterators of parquet data, masks in StructArray "pyarrow>=5.0.0", # For smart caching dataset processing "dill", # For performance gains with apache arrow "pandas", # for downloading datasets over HTTPS "requests>=2.19.0", # progress bars in download and scripts "tqdm>=4.62.1", # dataclasses for Python versions that don't have it "dataclasses;python_version<'3.7'", # for fast hashing "xxhash", # for better multiprocessing "multiprocess", # to get metadata of optional dependencies such as torch or tensorflow for Python versions that don't have it "importlib_metadata;python_version<'3.8'", # to save datasets locally or on any filesystem # minimum 2021.05.0 to have the AbstractArchiveFileSystem "fsspec[http]>=2021.05.0", # for data streaming via http "aiohttp", # To get datasets from the Datasets Hub on huggingface.co "huggingface_hub>=0.1.0,<1.0.0", # Utilities from PyPA to e.g., compare versions "packaging", ] AUDIO_REQUIRE = [ "librosa", ] VISION_REQURE = [ "Pillow>=6.2.1", ] BENCHMARKS_REQUIRE = [ "numpy==1.18.5", "tensorflow==2.3.0", "torch==1.6.0", "transformers==3.0.2", ] TESTS_REQUIRE = [ # test dependencies "absl-py", "pytest", "pytest-datadir", "pytest-xdist", # optional dependencies "apache-beam>=2.26.0", "elasticsearch<8.0.0", # 8.0 asks users to provide hosts or cloud_id when instantiating ElastictSearch() "aiobotocore", "boto3", "botocore", "faiss-cpu>=1.6.4", "fsspec[s3]", "moto[s3,server]==2.0.4", "rarfile>=4.0", "s3fs==2021.08.1", "tensorflow>=2.3,!=2.6.0,!=2.6.1", "torch", "torchaudio", "soundfile", "transformers", # datasets dependencies "bs4", "conllu", "h5py", "langdetect", "lxml", "mwparserfromhell", "nltk", "openpyxl", "py7zr", "tldextract", "zstandard", # metrics dependencies "bert_score>=0.3.6", "rouge_score", "sacrebleu", "scipy", "seqeval", "scikit-learn", "jiwer", "sentencepiece", # for bleurt "torchmetrics==0.6.0", # for comet: https://github.com/PyTorchLightning/metrics/issues/770 "mauve-text", # to speed up pip backtracking "toml>=0.10.1", "requests_file>=1.5.1", "tldextract>=3.1.0", "texttable>=1.6.3", "Werkzeug>=1.0.1", "six~=1.15.0", # metadata validation "importlib_resources;python_version<'3.7'", ] TESTS_REQUIRE.extend(VISION_REQURE) TESTS_REQUIRE.extend(AUDIO_REQUIRE) if os.name != "nt": # dependencies of unbabel-comet # only test if not on windows since there're issues installing fairseq on windows TESTS_REQUIRE.extend( [ "wget>=3.2", "pytorch-nlp==0.5.0", "pytorch_lightning", "fastBPE==0.1.0", "fairseq", ] ) QUALITY_REQUIRE = ["black~=22.0", "flake8>=3.8.3", "isort>=5.0.0", "pyyaml>=5.3.1"] EXTRAS_REQUIRE = { "audio": AUDIO_REQUIRE, "vision": VISION_REQURE, "apache-beam": ["apache-beam>=2.26.0"], "tensorflow": ["tensorflow>=2.2.0,!=2.6.0,!=2.6.1"], "tensorflow_gpu": ["tensorflow-gpu>=2.2.0,!=2.6.0,!=2.6.1"], "torch": ["torch"], "s3": [ "fsspec", "boto3", "botocore", "s3fs", ], "streaming": [], # for backward compatibility "dev": TESTS_REQUIRE + QUALITY_REQUIRE, "tests": TESTS_REQUIRE, "quality": QUALITY_REQUIRE, "benchmarks": BENCHMARKS_REQUIRE, "docs": [ "docutils==0.16.0", "recommonmark", "sphinx==3.1.2", "sphinx-markdown-tables", "sphinx-rtd-theme==0.4.3", "sphinxext-opengraph==0.4.1", "sphinx-copybutton", "fsspec<2021.9.0", "s3fs", "sphinx-panels", "sphinx-inline-tabs", "myst-parser", "Markdown!=3.3.5", ], } setup( name="datasets", version="1.18.4.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots) description="HuggingFace community-driven open-source library of datasets", long_description=open("README.md", encoding="utf-8").read(), long_description_content_type="text/markdown", author="HuggingFace Inc.", author_email="thomas@huggingface.co", url="https://github.com/huggingface/datasets", download_url="https://github.com/huggingface/datasets/tags", license="Apache 2.0", package_dir={"": "src"}, packages=find_packages("src"), package_data={"datasets": ["py.typed", "scripts/templates/*"], "datasets.utils.resources": ["*.json", "*.yaml"]}, entry_points={"console_scripts": ["datasets-cli=datasets.commands.datasets_cli:main"]}, install_requires=REQUIRED_PKGS, extras_require=EXTRAS_REQUIRE, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Intended Audience :: Education", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], keywords="datasets machine learning datasets metrics", zip_safe=False, # Required for mypy to find the py.typed file )
31.574144
129
0.645352
4a10245e274ca2fa0f82248ba13daab998aa1510
1,736
py
Python
code/a.py
PaulRenauld/k-mean-cuda
3a905e875e3f2f80e4087ef142d100c7c1d86180
[ "MIT" ]
null
null
null
code/a.py
PaulRenauld/k-mean-cuda
3a905e875e3f2f80e4087ef142d100c7c1d86180
[ "MIT" ]
null
null
null
code/a.py
PaulRenauld/k-mean-cuda
3a905e875e3f2f80e4087ef142d100c7c1d86180
[ "MIT" ]
null
null
null
import sys import matplotlib.pyplot as plt if __name__ == '__main__': f1 = "../results/n100000k50.csv" f2 = "../results/n100000k50a.csv" y_col = 1 x1_buf = [] x2_buf = [] y1_buf = [] y2_buf = [] with open(f1) as file1: with open(f2) as file2: lines1 = file1.readlines() lines2 = file2.readlines() for line in lines1[1:]: line = "".join(line.split()).split(',') if line[0].replace('.', '').isnumeric(): x1_buf.append(float(line[0])) y1_buf.append(float(line[y_col])) for line in lines2[1:]: line = "".join(line.split()).split(',') if line[0].replace('.', '').isnumeric(): x2_buf.append(float(line[0])) y2_buf.append(float(line[y_col])) header = "".join(lines1[0].split()).split(',') plt.xlabel(header[0]) plt.ylabel(header[y_col]) plt.show() fig, ax1 = plt.subplots() color = 'tab:red' ax1.set_xlabel('k parameter') ax1.set_ylabel('original silhouette', color=color) ax1.plot(x1_buf, y1_buf, color=color) ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis color = 'tab:blue' ax2.set_ylabel('approximation', color=color) # we already handled the x-label with ax1 ax2.plot(x2_buf, y2_buf, color=color) ax2.tick_params(axis='y', labelcolor=color) fig.tight_layout() # otherwise the right y-label is slightly clipped plt.show()
35.428571
99
0.521889
4a1024eca226a73fb9d6e97b0f88955ef27d860d
443
py
Python
pb2.4/run_google24.py
bumptech/cypb
e3bff4757d86ab8b8b99f6be2352549c180999c3
[ "BSD-3-Clause" ]
2
2021-01-03T17:03:41.000Z
2021-06-14T17:38:33.000Z
pb2.4/run_google24.py
bumptech/cypb
e3bff4757d86ab8b8b99f6be2352549c180999c3
[ "BSD-3-Clause" ]
null
null
null
pb2.4/run_google24.py
bumptech/cypb
e3bff4757d86ab8b8b99f6be2352549c180999c3
[ "BSD-3-Clause" ]
1
2021-01-13T11:16:34.000Z
2021-01-13T11:16:34.000Z
import time import connexiopb from connexio_pb2 import * msg = "CiAKBUF0YXNoGghBdGFtdXJhZCINSGV6cmV0a3VsaXlldioUChJhdGFteXJhdEBnbWFpbC5jb20q\nFAoSYXRhbXVyYWRAY29ubmV4LmlvKhQKEmF0YW11cmFkQGdtYWlsLmNvbTIOCgwrOTkzNjc2NDI2\nNDIyDgoMKzk5MzEyMjcwMjAzYh50aGlzIGlzIG5vdGUgZmllbGQgZm9yIGNvbnRhY3Q=\n".decode("base64") start = time.time() for i in range(5000): c = Contact() c.ParseFromString(msg) end = time.time() print end-start print c
26.058824
251
0.835214
4a102629af76facf5aaa672ee52027e95f45c43f
14,025
py
Python
dev.py
Schrodinger1926/Project-4
3a5a79529d141895031ce7007e1119d02d2e0ce0
[ "MIT" ]
null
null
null
dev.py
Schrodinger1926/Project-4
3a5a79529d141895031ce7007e1119d02d2e0ce0
[ "MIT" ]
null
null
null
dev.py
Schrodinger1926/Project-4
3a5a79529d141895031ce7007e1119d02d2e0ce0
[ "MIT" ]
null
null
null
import sys import os import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from moviepy.editor import VideoFileClip IMG_INPUT_DIR = 'test_images' IMG_OUTPUT_DIR = 'test_images' CALIB_DATA_DIR = 'camera_cal' RND_DIR = 'rnd' M, Minv = None, None def get_img_points(img_abs_path): # Read image (RGB) img = mpimg.imread(img_abs_path) img_size = (720, 1280) # convert to gray scale gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # find chess corners in the given image ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None) return ret, corners # gradient and magnitude thresholding def abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh=(0, 255)): # Calculate directional gradient gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) omapper = { 'x': (1, 0), 'y': (0, 1) } grad = cv2.Sobel(gray, cv2.CV_64F, omapper[orient][0], omapper[orient][1], ksize = sobel_kernel) grad = np.absolute(grad) sgrad = np.uint8(255*grad/np.max(grad)) bgrad = np.zeros_like(sgrad) bgrad[(sgrad > thresh[0]) & (sgrad < thresh[1])] = 1 return bgrad def mag_thresh(img, sobel_kernel=3, thresh=(0, 255)): # Calculate gradient in both x and y gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gradx = cv2.Sobel(gray, cv2.CV_64F, 1, 0) grady = cv2.Sobel(gray, cv2.CV_64F, 0, 1) # Resultant mag = np.sqrt(gradx**2 + grady**2) # Scale smag = np.uint8(255*mag/np.max(mag)) # Get binary image bmag = np.zeros_like(smag) bmag[(smag > thresh[0]) & (smag < thresh[1])] = 1 return bmag def dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)): # Calculate gradient in both x and y gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gradx = cv2.Sobel(gray, cv2.CV_64F, 1, 0) grady = cv2.Sobel(gray, cv2.CV_64F, 0, 1) # Get angle grad = np.arctan2(np.absolute(grady), np.absolute(gradx)) bgrad = np.zeros_like(grad) # Apply threshold bgrad[(grad > thresh[0]) & (grad < thresh[1])] = 1 return bgrad def s_select(img, thresh=(0, 255)): # Convert to HLS color space img_hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) # Apply a threshold to the S channel img_s_channel = img_hls[:, :, 2] # Apply threshold binary_output = np.copy(img_s_channel) # placeholder line binary_output[(img_s_channel > thresh[0]) & (img_s_channel < thresh[1])] = 1 return binary_output def get_warped_image(image): global M global Minv # h, w = image.shape[0], image.shape[1] h, w = (300 ,420 ) #offset = 150 # offset for dst points offset = 50 # offset for dst points """ src1 = np.float32([[557, 477], [370, 610], [959, 626], [727, 477]]) """ src1 = np.float32([[564, 466], [301, 644], [998, 644], [711, 466]]) dst = np.float32([[offset, offset], [offset, h], [w - offset, h], [w - offset, offset]]) M = cv2.getPerspectiveTransform(src1, dst) Minv = cv2.getPerspectiveTransform(dst, src1) # Supply custom shape #img_size = (420 , 420) # Warp the image using OpenCV warpPerspective() warped = cv2.warpPerspective(image, M, (w, h), flags = cv2.INTER_LINEAR) bwarped = np.zeros_like(warped) bwarped[warped >= 0.90] = 1 #bwarped[330:, :] = 0 #print(bwarped.shape) return bwarped # window settings window_width = 50 window_height = 80 # Break image into 9 vertical layers since image height is 720 margin = 100 # How much to slide left and right for searching def window_mask(width, height, img_ref, center,level): output = np.zeros_like(img_ref) output[int(img_ref.shape[0]-(level+1)*height):int(img_ref.shape[0]-level*height),max(0,int(center-width/2)):min(int(center+width/2),img_ref.shape[1])] = 1 return output def find_window_centroids(image, window_width, window_height, margin): window_centroids = [] # Store the (left,right) window centroid positions per level window = np.ones(window_width) # Create our window template that we will use for convolutions # First find the two starting positions for the left and right lane by using np.sum to get the vertical image slice # and then np.convolve the vertical image slice with the window template # Sum quarter bottom of image to get slice, could use a different ratio l_sum = np.sum(image[int(3*image.shape[0]/4):,:int(image.shape[1]/2)], axis=0) l_center = np.argmax(np.convolve(window,l_sum))-window_width/2 r_sum = np.sum(image[int(3*image.shape[0]/4):,int(image.shape[1]/2):], axis=0) r_center = np.argmax(np.convolve(window,r_sum))-window_width/2+int(image.shape[1]/2) # Add what we found for the first layer window_centroids.append((l_center,r_center)) # Go through each layer looking for max pixel locations for level in range(1,(int)(image.shape[0]/window_height)): # convolve the window into the vertical slice of the image image_layer = np.sum(image[int(image.shape[0]-(level+1)*window_height):int(image.shape[0]-level*window_height),:], axis=0) conv_signal = np.convolve(window, image_layer) # Find the best left centroid by using past left center as a reference # Use window_width/2 as offset because convolution signal reference is at right side of window, not center of window offset = window_width/2 l_min_index = int(max(l_center+offset-margin,0)) l_max_index = int(min(l_center+offset+margin,image.shape[1])) l_center = np.argmax(conv_signal[l_min_index:l_max_index])+l_min_index-offset # Find the best right centroid by using past right center as a reference r_min_index = int(max(r_center+offset-margin,0)) r_max_index = int(min(r_center+offset+margin,image.shape[1])) r_center = np.argmax(conv_signal[r_min_index:r_max_index])+r_min_index-offset # Add what we found for that layer window_centroids.append((l_center,r_center)) return window_centroids def r_channel_threshold(image, thresh = (0, 255)): r_channel = image[:, :, 2] r_binary = np.zeros_like(r_channel) r_binary[(r_channel > thresh[0]) & (r_channel < thresh[1])] = 1 return r_binary def g_channel_threshold(image, thresh = (0, 255)): g_channel = image[:, :, 1] g_binary = np.zeros_like(g_channel) g_binary[(g_channel > thresh[0]) & (g_channel < thresh[1])] = 1 return g_binary def l_select(img, thresh=(0, 255)): # Convert to HLS color space img_hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) # Apply a threshold to the L channel img_l_channel = img_hls[:, :, 1] # Apply threshold binary_output = np.copy(img_l_channel) # placeholder line binary_output[(img_l_channel > thresh[0]) & (img_l_channel < thresh[1])] = 1 return binary_output def process_image(image): # undistort image image = cv2.undistort(image, mtx, dist, None, mtx) ksize = 3 # Gradient thresholding gradx = abs_sobel_thresh(image, orient = 'x', sobel_kernel = ksize, thresh = (100, 255)) # Magnitude thresholding mag_binary = mag_thresh(image, sobel_kernel = ksize, thresh = (100, 255)) # Directional thresholding dir_binary = dir_threshold(image, sobel_kernel = 5, thresh = (0.7, 1.3)) # saturation thresholding (yellow lines) s_binary = s_select(image, thresh=(170, 255)) # Luminence thresholding (white lines) l_binary = l_select(image, thresh=(200, 255)) # R-channel thresholding r_binary = r_channel_threshold(image, thresh=(200, 255)) # G-channel thresholding g_binary = g_channel_threshold(image, thresh=(200, 255)) # Combination step combined = np.zeros_like(dir_binary) #combined[((gradx == 1) & (l_binary == 1) & (r_binary)) | ((mag_binary == 1) & (dir_binary == 1)) | (s_binary == 1)] = 1 combined[((r_binary == 1) & (g_binary == 1))| (( gradx == 1) & (dir_binary == 1)) | (s_binary == 1)] = 1 #plt.imshow(combined, cmap = 'gray') #plt.show() # Select area of interest # Perpective transform warped = get_warped_image(combined) #print(cv2.resize(warped_image, (10, 10))) # Get pixel count histogram histogram = np.sum(warped[warped.shape[0]//2:,:], axis=0).astype(np.int32) window_centroids = find_window_centroids(warped, window_width, window_height, margin) # If we found any window centers if len(window_centroids) > 0: # Points used to draw all the left and right windows l_points = np.zeros_like(warped) r_points = np.zeros_like(warped) # Go through each level and draw the windows for level in range(0,len(window_centroids)): # Window_mask is a function to draw window areas l_mask = window_mask(window_width,window_height,warped,window_centroids[level][0],level) r_mask = window_mask(window_width,window_height,warped,window_centroids[level][1],level) # Add graphic points from window mask here to total pixels found l_points[(l_points == 255) | ((l_mask == 1) ) ] = 255 r_points[(r_points == 255) | ((r_mask == 1) ) ] = 255 # Draw the results template = np.array(r_points+l_points,np.uint8) # add both left and right window pixels together zero_channel = np.zeros_like(template) # create a zero color channel template = np.array(cv2.merge((zero_channel,template,zero_channel)),np.uint8) # make window pixels green warpage= np.dstack((warped, warped, warped))*255 # making the original road pixels 3 color channels output = cv2.addWeighted(np.uint8(warpage), 1, template, 0.5, 0.0) # overlay the orignal road image with window results # If no window centers found, just display orginal road image else: output = np.array(cv2.merge((warped,warped,warped)),np.uint8) # Display the final results """ plt.imshow(output) plt.title('window fitting results') plt.show() """ ploty = [] leftx, rightx = [], [] for level, centroid in enumerate(window_centroids): leftx.append(centroid[0]) rightx.append(centroid[1]) ploty.append(warped.shape[0] - level*window_height) ploty = np.array(ploty) leftx = np.array(leftx) rightx = np.array(rightx) # Define conversions in x and y from pixels space to meters ym_per_pix = 30/720 # meters per pixel in y dimension xm_per_pix = 3.7/700 # meters per pixel in x dimension y_eval = np.max(ploty) # Fit new polynomials to x,y in world space left_fit_cr = np.polyfit(ploty*ym_per_pix, leftx*xm_per_pix, 2) right_fit_cr = np.polyfit(ploty*ym_per_pix, rightx*xm_per_pix, 2) # Calculate the new radii of curvature left_curverad = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0]) right_curverad = ((1 + (2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0]) # Now our radius of curvature is in meters #print(left_curverad, 'm', right_curverad, 'm') left_fit = np.polyfit(ploty, leftx, 2) left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2] right_fit = np.polyfit(ploty, rightx, 2) right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2] warp_zero = np.zeros_like(warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) # Recast the x and y points into usable format for cv2.fillPoly() pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))]) pts = np.hstack((pts_left, pts_right)) # Draw the lane onto the warped blank image cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0)) # Warp the blank back to original image space using inverse perspective matrix (Minv) newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0])) # Combine the result with the original image result = cv2.addWeighted(image, 1, newwarp, 0.3, 0) #cv2.imshow('title', warped) #plt.imshow( output) #cv2.waitKey(0) #plt.imshow(result) #plt.show() #quit() return result if __name__ == "__main__": # Calibration params img_size = (720, 1280) nx, ny = 9, 6 objP = np.zeros((nx*ny, 3), np.float32) objP[:,:2] = np.mgrid[0: nx, 0: ny].T.reshape(-1, 2) # calibrate camera print("Calibrating Camera ..") obj_points = [] img_points = [] for filename in os.listdir(CALIB_DATA_DIR): ret, corners = get_img_points(img_abs_path = os.path.join(CALIB_DATA_DIR, filename)) if ret: obj_points.append(objP) img_points.append(corners) # Get coefficients ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, img_size, None, None) if ret: print("Calibration: PASSED") """ image = mpimg.imread(os.path.join(CALIB_DATA_DIR, 'calibration1.jpg')) image = cv2.undistort(image, mtx, dist, None, mtx) plt.imshow(image) plt.title('sanity_check') plt.show() """ # Process images for filename in os.listdir(IMG_INPUT_DIR): sys.stdout.write('\r Processing : {}'.format(filename)) sys.stdout.flush() image = cv2.imread(os.path.join(IMG_INPUT_DIR, filename)) # undistort image image = cv2.undistort(image, mtx, dist, None, mtx) process_image(image) video_filename = "project_video.mp4" clip1 = VideoFileClip(video_filename) white_output = "output_{}".format(video_filename) white_clip = clip1.fl_image(process_image) white_clip.write_videofile(white_output, audio=False)
34.715347
158
0.654046
4a102686355f01e24a42730f62ab9bd096cac652
2,815
py
Python
cirq-core/cirq/contrib/paulistring/pauli_string_optimize.py
Nexuscompute/Cirq
640ef8f82d6a56ec95361388ce7976e096cca906
[ "Apache-2.0" ]
null
null
null
cirq-core/cirq/contrib/paulistring/pauli_string_optimize.py
Nexuscompute/Cirq
640ef8f82d6a56ec95361388ce7976e096cca906
[ "Apache-2.0" ]
4
2022-01-16T14:12:15.000Z
2022-02-24T03:58:46.000Z
cirq-core/cirq/contrib/paulistring/pauli_string_optimize.py
Nexuscompute/Cirq
640ef8f82d6a56ec95361388ce7976e096cca906
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import networkx from cirq import circuits, linalg from cirq.contrib import circuitdag from cirq.contrib.paulistring.pauli_string_dag import pauli_string_dag_from_circuit from cirq.contrib.paulistring.recombine import move_pauli_strings_into_circuit from cirq.contrib.paulistring.separate import convert_and_separate_circuit from cirq.ops import PauliStringGateOperation def pauli_string_optimized_circuit( circuit: circuits.Circuit, move_cliffords: bool = True, atol: float = 1e-8 ) -> circuits.Circuit: cl, cr = convert_and_separate_circuit(circuit, leave_cliffords=not move_cliffords, atol=atol) string_dag = pauli_string_dag_from_circuit(cl) # Merge and remove Pauli string phasors while True: before_len = len(string_dag.nodes()) merge_equal_strings(string_dag) remove_negligible_strings(string_dag) if len(string_dag.nodes()) >= before_len: break c_all = move_pauli_strings_into_circuit(string_dag, cr) assert_no_multi_qubit_pauli_strings(c_all) return c_all def assert_no_multi_qubit_pauli_strings(circuit: circuits.Circuit) -> None: for op in circuit.all_operations(): if isinstance(op, PauliStringGateOperation): assert len(op.pauli_string) == 1, 'Multi qubit Pauli string left over' def merge_equal_strings(string_dag: circuitdag.CircuitDag) -> None: for node in tuple(string_dag.nodes()): if node not in string_dag.nodes(): # Node was removed continue commuting_nodes = ( set(string_dag.nodes()) - set(networkx.dag.ancestors(string_dag, node)) - set(networkx.dag.descendants(string_dag, node)) - set([node]) ) for other_node in commuting_nodes: if node.val.pauli_string.equal_up_to_coefficient(other_node.val.pauli_string): string_dag.remove_node(other_node) node.val = node.val.merged_with(other_node.val) def remove_negligible_strings(string_dag: circuitdag.CircuitDag, atol=1e-8) -> None: for node in tuple(string_dag.nodes()): if linalg.all_near_zero_mod(node.val.exponent_relative, 2, atol=atol): string_dag.remove_node(node)
38.561644
97
0.728242
4a1026a3dcc69dc3d3616fbdc94627c1ba6847ce
1,470
py
Python
scripts/cleanup_datasets/remove_renamed_datasets_from_disk.py
igorhollaender/sirv_dashboard
85aec60b80ef6f561d89398e3da5963d3d0f2aa4
[ "CC-BY-3.0" ]
2
2018-10-14T16:42:39.000Z
2018-10-14T16:42:41.000Z
scripts/cleanup_datasets/remove_renamed_datasets_from_disk.py
igorhollaender/OBSOLETE_sirv_dashboard
85aec60b80ef6f561d89398e3da5963d3d0f2aa4
[ "CC-BY-3.0" ]
null
null
null
scripts/cleanup_datasets/remove_renamed_datasets_from_disk.py
igorhollaender/OBSOLETE_sirv_dashboard
85aec60b80ef6f561d89398e3da5963d3d0f2aa4
[ "CC-BY-3.0" ]
null
null
null
#!/usr/bin/env python """ Removes a dataset file ( which was first renamed by appending _purged to the file name ) from disk. Usage: python remove_renamed_datasets_from_disk.py renamed.log """ import os import sys assert sys.version_info[:2] >= ( 2, 4 ) def usage(prog) : print "usage: %s file" % prog print """ Removes a set of files from disk. The input file should contain a list of files to be deleted, one per line. The full path must be specified and must begin with /var/opt/galaxy. A log of files deleted is created in a file with the same name as that input but with .removed.log appended. """ def main(): if len(sys.argv) != 2 or sys.argv == "-h" or sys.argv == "--help" : usage(sys.argv[0]) sys.exit() infile = sys.argv[1] outfile = infile + ".removed.log" out = open( outfile, 'w' ) print >> out, "# The following renamed datasets have been removed from disk" i = 0 removed_files = 0 for i, line in enumerate( open( infile ) ): line = line.rstrip( '\r\n' ) if line and line.startswith( '/var/opt/galaxy' ): try: os.unlink( line ) print >> out, line removed_files += 1 except Exception, exc: print >> out, "# Error, exception " + str( exc ) + " caught attempting to remove " + line print >> out, "# Removed " + str( removed_files ) + " files" if __name__ == "__main__": main()
29.4
105
0.606122
4a10283533154e55905b5c45d4a14f88ff89e5a3
19,802
py
Python
modules/pytket-honeywell/pytket/extensions/honeywell/backends/api_wrappers.py
CQCL/pytket-extensions
45d36ff16636a194046c37e64060164611559d19
[ "Apache-2.0" ]
22
2021-03-02T15:17:22.000Z
2022-03-20T21:17:10.000Z
modules/pytket-honeywell/pytket/extensions/honeywell/backends/api_wrappers.py
CQCL/pytket-extensions
45d36ff16636a194046c37e64060164611559d19
[ "Apache-2.0" ]
132
2021-03-03T08:30:05.000Z
2022-03-31T21:11:58.000Z
modules/pytket-honeywell/pytket/extensions/honeywell/backends/api_wrappers.py
CQCL/pytket-extensions
45d36ff16636a194046c37e64060164611559d19
[ "Apache-2.0" ]
13
2021-03-05T17:01:19.000Z
2022-03-17T15:38:02.000Z
# -*- coding: utf-8 -*- """" Functions used to submit jobs with Honeywell Quantum Solutions API. Adapted from original file provided by Honeywell Quantum Solutions """ import datetime import time from http import HTTPStatus from typing import Optional, Dict, Any, Tuple import asyncio import json import getpass import jwt import requests from websockets import connect, exceptions # type: ignore import nest_asyncio # type: ignore from .config import HoneywellConfig from .credential_storage import CredentialStorage, MemoryStorage, PersistentStorage # This is necessary for use in Jupyter notebooks to allow for nested asyncio loops nest_asyncio.apply() class HQSAPIError(Exception): pass class _OverrideManager: def __init__( self, api_handler: "HoneywellQAPI", timeout: Optional[int] = None, retry_timeout: Optional[int] = None, ): self._timeout = timeout self._retry = retry_timeout self.api_handler = api_handler self._orig_timeout = api_handler.timeout self._orig_retry = api_handler.retry_timeout def __enter__(self) -> None: if self._timeout is not None: self.api_handler.timeout = self._timeout if self._retry is not None: self.api_handler.retry_timeout = self._retry def __exit__(self, exc_type, exc_value, traceback) -> None: # type: ignore self.api_handler.timeout = self._orig_timeout self.api_handler.retry_timeout = self._orig_retry class HoneywellQAPI: JOB_DONE = ["failed", "completed", "canceled"] DEFAULT_API_URL = "https://qapi.honeywell.com/" DEFAULT_TIME_SAFETY = ( 60 # Default safety factor (in seconds) to token expiration before a refresh ) def __init__( self, user_name: Optional[str] = None, token: Optional[str] = None, machine: Optional[str] = None, api_url: Optional[str] = None, api_version: int = 1, use_websocket: bool = True, time_safety: Optional[int] = None, login: bool = True, persistent_credential: bool = True, __pwd: Optional[str] = None, ): """Initialize and login to the Honeywell Quantum API interface All arguments are optional Arguments: user_name (str): User e-mail used to register token (str): Token used to refresh id token api_url (str): Url of the Quantum API: https://qapi.honeywell.com/ api_version (str): API version use_websocket (bool): Whether to default to using websockets to reduce traffic time_safety (int): seconds before token expiration within which to refresh tokens login (bool): attempt to login during initialiasation persistent_credential (bool): use keyring to store credentials (instead of memory) __pwd (str): password for the service. For debugging purposes only, do not store password in source code. """ self.config = HoneywellConfig.from_default_config_file() self.url = ( f"{api_url}v{api_version}/" if api_url else f"{self.DEFAULT_API_URL}v{api_version}/" ) self._cred_store: CredentialStorage = ( MemoryStorage() if not persistent_credential else PersistentStorage() ) self.user_name = user_name if user_name else self.config.username if self.user_name is not None and __pwd is not None: self._cred_store.save_login_credential(self.user_name, __pwd) refresh_token = token if token else self._cred_store.refresh_token if refresh_token is not None: self._cred_store.save_refresh_token(refresh_token) self.api_version = api_version self.machine = machine self.use_websocket = use_websocket self.time_safety_factor = ( time_safety if time_safety else self.DEFAULT_TIME_SAFETY ) self.ws_timeout = 180 self.retry_timeout = 5 self.timeout: Optional[int] = None # don't timeout by default if login: self.login() def override_timeouts( self, timeout: Optional[int] = None, retry_timeout: Optional[int] = None ) -> _OverrideManager: return _OverrideManager(self, timeout=timeout, retry_timeout=retry_timeout) def _request_tokens(self, body: dict) -> Tuple[Optional[int], Optional[Any]]: """Method to send login request to machine api and save tokens.""" try: # send request to login response = requests.post( f"{self.url}login", json.dumps(body), ) # reset body to delete credentials body = {} if response.status_code != HTTPStatus.OK: return response.status_code, response.json() else: print("***Successfully logged in***") self._cred_store.save_tokens( response.json()["id-token"], response.json()["refresh-token"] ) return response.status_code, None except requests.exceptions.RequestException as e: print(e) return None, None def _get_credentials(self) -> Tuple[str, str]: """Method to ask for user's credentials""" if self.config.username is not None: pwd = self._cred_store.login_credential(self.config.username) # type: ignore if pwd: self.user_name = self.config.username return self.user_name, pwd if not self.user_name: user_name = input("Enter your email: ") self.user_name = user_name pwd = self._cred_store.login_credential(self.user_name) if not pwd: pwd = getpass.getpass(prompt="Enter your password: ") self._cred_store.save_login_credential(self.user_name, pwd) return self.user_name, pwd def _authenticate( self, action: Optional[str] = None, __user_name: Optional[str] = None, __pwd: Optional[str] = None, ) -> None: """This method makes requests to refresh or get new id-token. If a token refresh fails due to token being expired, credentials get requested from user. The __user_name and __pwd parameters are there for debugging purposes only, do not include your credentials in source code. """ # login body body = {} if action == "refresh": body["refresh-token"] = self._cred_store.refresh_token else: # ask user for crendentials before making login request user_name: Optional[str] pwd: Optional[str] if __user_name and __pwd: user_name = __user_name pwd = __pwd else: user_name, pwd = self._get_credentials() body["email"] = user_name body["password"] = pwd # clear credentials user_name = None pwd = None # send login request to API status_code, message = self._request_tokens(body) body = {} if status_code != HTTPStatus.OK: # check if we got an error because refresh token has expired if status_code == HTTPStatus.BAD_REQUEST: if message is not None: if "Invalid Refresh Token" in message["error"]["text"]: # ask user for credentials to login again user_name, pwd = self._get_credentials() body["email"] = user_name body["password"] = pwd # send login request to API status_code, message = self._request_tokens(body) else: raise HQSAPIError("No message with BAD_REQUEST") if status_code != HTTPStatus.OK: raise HQSAPIError( "HTTP error while logging in: " f"{status_code} {'' if message is None else message}" ) def login(self) -> str: """This methods checks if we have a valid (non-expired) id-token and returns it, otherwise it gets a new one with refresh-token. If refresh-token doesn't exist, it asks user for credentials. """ # check if id_token exists id_token = self._cred_store.id_token if id_token is None: # authenticate against '/login' endpoint self._authenticate() # get id_token id_token = self._cred_store.id_token if id_token is None: raise HQSAPIError("Unable to retrieve id token.") # check id_token is not expired yet expiration_date = jwt.decode(id_token, verify=False)["exp"] if expiration_date < ( datetime.datetime.now().timestamp() - self.time_safety_factor ): print("Your id token is expired. Refreshing...") # get refresh_token refresh_token = self._cred_store.refresh_token if refresh_token is not None: self._authenticate("refresh") else: self._authenticate() # get id_token id_token = self._cred_store.id_token return id_token # type: ignore def delete_authentication(self) -> None: """Remove stored credentials and tokens""" if self.user_name: self._cred_store.delete_login_credential(self.user_name) self._cred_store.delete_tokens() def recent_jobs( self, start: Optional[str] = None, end: Optional[str] = None, days: Optional[int] = None, jobs: Optional[int] = None, ) -> Any: id_token = self.login() if start is not None and end is not None: res = requests.get( f"{self.url}metering?start={start}&end={end}", headers={"Authorization": id_token}, ) self._response_check(res, f"metering between {start} and {end}") return res.json() elif days is not None: res = requests.get( f"{self.url}metering?days={days}", headers={"Authorization": id_token} ) self._response_check(res, f"metering of last {days} days") return res.json() elif jobs is not None: res = requests.get( f"{self.url}metering?jobs={jobs}", headers={"Authorization": id_token} ) self._response_check(res, f"metering of last {jobs} jobs") return res.json() else: raise ValueError("Need more information to make a metering request") def submit_job( self, qasm_str: str, shots: Optional[int] = None, machine: Optional[str] = None, name: str = "job", ) -> str: """ Submits job to device and returns job ID. Args: qasm_str: OpenQASM file to run shots: number of repetitions of qasm_str machine: machine to run on name: name of job (for error handling) Returns: (str): id of job submitted """ try: if not machine and not self.machine: raise ValueError("Must provide valid machine name") # send job request body = { "machine": machine if machine else self.machine, "name": name, "language": "OPENQASM 2.0", "program": qasm_str, "priority": "normal", "count": shots, "options": None, } id_token = self.login() res = requests.post( f"{self.url}job", json.dumps(body), headers={"Authorization": id_token} ) self._response_check(res, "job submission") # extract job ID from response jr = res.json() job_id: str = str(jr["job"]) print( f"submitted {name} id={{job}}, submit date={{submit-date}}".format(**jr) ) except ConnectionError as e: raise e return job_id def _response_check(self, res: requests.Response, description: str) -> None: """Consolidate as much error-checking of response""" # check if token has expired or is generally unauthorized if res.status_code == HTTPStatus.UNAUTHORIZED: jr = res.json() raise HQSAPIError( ( f"Authorization failure attempting: {description}." "\n\nServer Response: {jr}" ) ) elif res.status_code != HTTPStatus.OK: jr = res.json() raise HQSAPIError( f"HTTP error attempting: {description}.\n\nServer Response: {jr}" ) def retrieve_job_status( self, job_id: str, use_websocket: Optional[bool] = None ) -> Optional[Dict]: """ Retrieves job status from device. Args: job_id: unique id of job use_websocket: use websocket to minimize interaction Returns: (dict): output from API """ job_url = f"{self.url}job/{job_id}" # Using the login wrapper we will automatically try to refresh token id_token = self.login() if use_websocket or (use_websocket is None and self.use_websocket): job_url += "?websocket=true" res = requests.get(job_url, headers={"Authorization": id_token}) jr: Optional[Dict] = None # Check for invalid responses, and raise an exception if so self._response_check(res, "job status") # if we successfully got status return the decoded details if res.status_code == HTTPStatus.OK: jr = res.json() return jr def retrieve_job( self, job_id: str, use_websocket: Optional[bool] = None ) -> Optional[Dict]: """ Retrieves job from device. Args: job_id: unique id of job use_websocket: use websocket to minimize interaction Returns: (dict): output from API """ jr = self.retrieve_job_status(job_id, use_websocket) if not jr: raise HQSAPIError(f"Unable to retrive job {job_id}") if "status" in jr and jr["status"] in self.JOB_DONE: return jr if "websocket" in jr: # wait for job completion using websocket jr = asyncio.get_event_loop().run_until_complete(self._wait_results(job_id)) else: # poll for job completion jr = self._poll_results(job_id) return jr def _poll_results(self, job_id: str) -> Optional[Dict]: jr = None start_time = time.time() while True: if self.timeout is not None and time.time() > (start_time + self.timeout): break self.login() try: jr = self.retrieve_job_status(job_id) # If we are failing to retrieve status of any kind, then fail out. if jr is None: break if "status" in jr and jr["status"] in self.JOB_DONE: return jr time.sleep(self.retry_timeout) except KeyboardInterrupt: raise RuntimeError("Keyboard Interrupted") return jr async def _wait_results(self, job_id: str) -> Optional[Dict]: start_time = time.time() while True: if self.timeout is not None and time.time() > (start_time + self.timeout): break self.login() jr = self.retrieve_job_status(job_id, True) if jr is None: return jr elif "status" in jr and jr["status"] in self.JOB_DONE: return jr else: task_token = jr["websocket"]["task_token"] execution_arn = jr["websocket"]["executionArn"] websocket_uri = self.url.replace("https://", "wss://ws.") async with connect(websocket_uri) as websocket: body = { "action": "OpenConnection", "task_token": task_token, "executionArn": execution_arn, } await websocket.send(json.dumps(body)) while True: try: res = await asyncio.wait_for( websocket.recv(), timeout=self.ws_timeout ) jr = json.loads(res) if not isinstance(jr, Dict): raise RuntimeError("Unable to decode response.") if "status" in jr and jr["status"] in self.JOB_DONE: return jr except ( asyncio.TimeoutError, exceptions.ConnectionClosed, ): try: # Try to keep the connection alive... pong = await websocket.ping() await asyncio.wait_for(pong, timeout=10) continue except asyncio.TimeoutError: # If we are failing, wait a little while, # then start from the top await asyncio.sleep(self.retry_timeout) break except KeyboardInterrupt: raise RuntimeError("Keyboard Interrupted") def run_job( self, qasm_str: str, shots: int, machine: str, name: str = "job" ) -> Optional[Dict]: """ Submits a job and waits to receives job result dictionary. Args: qasm_file: OpenQASM file to run name: name of job (for error handling) shots: number of repetitions of qasm_str machine: machine to run on Returns: jr: (dict) output from API """ job_id = self.submit_job( qasm_str=qasm_str, shots=shots, machine=machine, name=name ) jr = self.retrieve_job(job_id) return jr def status(self, machine: Optional[str] = None) -> str: """ Check status of machine. Args: (str): machine name """ id_token = self.login() res = requests.get( f"{self.url}machine/{machine if machine else self.machine}", headers={"Authorization": id_token}, ) self._response_check(res, "get machine status") jr = res.json() return str(jr["state"]) def cancel(self, job_id: str) -> dict: """ Cancels job. Args: job_id: job ID to cancel Returns: jr: (dict) output from API """ id_token = self.login() res = requests.post( f"{self.url}job/{job_id}/cancel", headers={"Authorization": id_token} ) self._response_check(res, "job cancel") jr = res.json() return jr # type: ignore
35.172291
89
0.551055
4a1028ebe509064e9d636e8e8da08896df084436
74,077
py
Python
scipy/stats/tests/test_distributions.py
jetuk/scipy
8a9310265464d81d51a56baf499336cf07acc8e5
[ "BSD-3-Clause" ]
null
null
null
scipy/stats/tests/test_distributions.py
jetuk/scipy
8a9310265464d81d51a56baf499336cf07acc8e5
[ "BSD-3-Clause" ]
null
null
null
scipy/stats/tests/test_distributions.py
jetuk/scipy
8a9310265464d81d51a56baf499336cf07acc8e5
[ "BSD-3-Clause" ]
1
2019-08-13T21:23:57.000Z
2019-08-13T21:23:57.000Z
""" Test functions for stats module """ from __future__ import division, print_function, absolute_import import warnings import re import sys from numpy.testing import (TestCase, run_module_suite, assert_equal, assert_array_equal, assert_almost_equal, assert_array_almost_equal, assert_allclose, assert_, assert_raises, rand, dec) from nose import SkipTest import numpy import numpy as np from numpy import typecodes, array from scipy.lib._version import NumpyVersion from scipy import special import scipy.stats as stats from scipy.stats._distn_infrastructure import argsreduce import scipy.stats.distributions from scipy.special import xlogy # python -OO strips docstrings DOCSTRINGS_STRIPPED = sys.flags.optimize > 1 # Generate test cases to test cdf and distribution consistency. # Note that this list does not include all distributions. dists = ['uniform','norm','lognorm','expon','beta', 'powerlaw','bradford','burr','fisk','cauchy','halfcauchy', 'foldcauchy','gamma','gengamma','loggamma', 'alpha','anglit','arcsine','betaprime', 'dgamma','exponweib','exponpow','frechet_l','frechet_r', 'gilbrat','f','ncf','chi2','chi','nakagami','genpareto', 'genextreme','genhalflogistic','pareto','lomax','halfnorm', 'halflogistic','fatiguelife','foldnorm','ncx2','t','nct', 'weibull_min','weibull_max','dweibull','maxwell','rayleigh', 'genlogistic', 'logistic','gumbel_l','gumbel_r','gompertz', 'hypsecant', 'laplace', 'reciprocal','triang','tukeylambda', 'vonmises', 'vonmises_line', 'pearson3'] def _assert_hasattr(a, b, msg=None): if msg is None: msg = '%s does not have attribute %s' % (a, b) assert_(hasattr(a, b), msg=msg) def test_api_regression(): # https://github.com/scipy/scipy/issues/3802 _assert_hasattr(scipy.stats.distributions, 'f_gen') # check function for test generator def check_distribution(dist, args, alpha): D,pval = stats.kstest(dist,'', args=args, N=1000) if (pval < alpha): D,pval = stats.kstest(dist,'',args=args, N=1000) # if (pval < alpha): # D,pval = stats.kstest(dist,'',args=args, N=1000) assert_(pval > alpha, msg="D = " + str(D) + "; pval = " + str(pval) + "; alpha = " + str(alpha) + "\nargs = " + str(args)) # nose test generator def test_all_distributions(): for dist in dists: distfunc = getattr(stats, dist) nargs = distfunc.numargs alpha = 0.01 if dist == 'fatiguelife': alpha = 0.001 if dist == 'frechet': args = tuple(2*rand(1))+(0,)+tuple(2*rand(2)) elif dist == 'triang': args = tuple(rand(nargs)) elif dist == 'reciprocal': vals = rand(nargs) vals[1] = vals[0] + 1.0 args = tuple(vals) elif dist == 'vonmises': yield check_distribution, dist, (10,), alpha yield check_distribution, dist, (101,), alpha args = tuple(1.0+rand(nargs)) else: args = tuple(1.0+rand(nargs)) yield check_distribution, dist, args, alpha def check_vonmises_pdf_periodic(k,l,s,x): vm = stats.vonmises(k,loc=l,scale=s) assert_almost_equal(vm.pdf(x),vm.pdf(x % (2*numpy.pi*s))) def check_vonmises_cdf_periodic(k,l,s,x): vm = stats.vonmises(k,loc=l,scale=s) assert_almost_equal(vm.cdf(x) % 1,vm.cdf(x % (2*numpy.pi*s)) % 1) def test_vonmises_pdf_periodic(): for k in [0.1, 1, 101]: for x in [0,1,numpy.pi,10,100]: yield check_vonmises_pdf_periodic, k, 0, 1, x yield check_vonmises_pdf_periodic, k, 1, 1, x yield check_vonmises_pdf_periodic, k, 0, 10, x yield check_vonmises_cdf_periodic, k, 0, 1, x yield check_vonmises_cdf_periodic, k, 1, 1, x yield check_vonmises_cdf_periodic, k, 0, 10, x def test_vonmises_line_support(): assert_equal(stats.vonmises_line.a, -np.pi) assert_equal(stats.vonmises_line.b, np.pi) class TestRandInt(TestCase): def test_rvs(self): vals = stats.randint.rvs(5,30,size=100) assert_(numpy.all(vals < 30) & numpy.all(vals >= 5)) assert_(len(vals) == 100) vals = stats.randint.rvs(5,30,size=(2,50)) assert_(numpy.shape(vals) == (2,50)) assert_(vals.dtype.char in typecodes['AllInteger']) val = stats.randint.rvs(15,46) assert_((val >= 15) & (val < 46)) assert_(isinstance(val, numpy.ScalarType), msg=repr(type(val))) val = stats.randint(15,46).rvs(3) assert_(val.dtype.char in typecodes['AllInteger']) def test_pdf(self): k = numpy.r_[0:36] out = numpy.where((k >= 5) & (k < 30), 1.0/(30-5), 0) vals = stats.randint.pmf(k,5,30) assert_array_almost_equal(vals,out) def test_cdf(self): x = numpy.r_[0:36:100j] k = numpy.floor(x) out = numpy.select([k >= 30,k >= 5],[1.0,(k-5.0+1)/(30-5.0)],0) vals = stats.randint.cdf(x,5,30) assert_array_almost_equal(vals, out, decimal=12) class TestBinom(TestCase): def test_rvs(self): vals = stats.binom.rvs(10, 0.75, size=(2, 50)) assert_(numpy.all(vals >= 0) & numpy.all(vals <= 10)) assert_(numpy.shape(vals) == (2, 50)) assert_(vals.dtype.char in typecodes['AllInteger']) val = stats.binom.rvs(10, 0.75) assert_(isinstance(val, int)) val = stats.binom(10, 0.75).rvs(3) assert_(isinstance(val, numpy.ndarray)) assert_(val.dtype.char in typecodes['AllInteger']) def test_pmf(self): # regression test for Ticket #1842 vals1 = stats.binom.pmf(100, 100,1) vals2 = stats.binom.pmf(0, 100,0) assert_allclose(vals1, 1.0, rtol=1e-15, atol=0) assert_allclose(vals2, 1.0, rtol=1e-15, atol=0) def test_entropy(self): # Basic entropy tests. b = stats.binom(2, 0.5) expected_p = np.array([0.25, 0.5, 0.25]) expected_h = -sum(xlogy(expected_p, expected_p)) h = b.entropy() assert_allclose(h, expected_h) b = stats.binom(2, 0.0) h = b.entropy() assert_equal(h, 0.0) b = stats.binom(2, 1.0) h = b.entropy() assert_equal(h, 0.0) class TestBernoulli(TestCase): def test_rvs(self): vals = stats.bernoulli.rvs(0.75, size=(2, 50)) assert_(numpy.all(vals >= 0) & numpy.all(vals <= 1)) assert_(numpy.shape(vals) == (2, 50)) assert_(vals.dtype.char in typecodes['AllInteger']) val = stats.bernoulli.rvs(0.75) assert_(isinstance(val, int)) val = stats.bernoulli(0.75).rvs(3) assert_(isinstance(val, numpy.ndarray)) assert_(val.dtype.char in typecodes['AllInteger']) def test_entropy(self): # Simple tests of entropy. b = stats.bernoulli(0.25) expected_h = -0.25*np.log(0.25) - 0.75*np.log(0.75) h = b.entropy() assert_allclose(h, expected_h) b = stats.bernoulli(0.0) h = b.entropy() assert_equal(h, 0.0) b = stats.bernoulli(1.0) h = b.entropy() assert_equal(h, 0.0) class TestNBinom(TestCase): def test_rvs(self): vals = stats.nbinom.rvs(10, 0.75, size=(2, 50)) assert_(numpy.all(vals >= 0)) assert_(numpy.shape(vals) == (2, 50)) assert_(vals.dtype.char in typecodes['AllInteger']) val = stats.nbinom.rvs(10, 0.75) assert_(isinstance(val, int)) val = stats.nbinom(10, 0.75).rvs(3) assert_(isinstance(val, numpy.ndarray)) assert_(val.dtype.char in typecodes['AllInteger']) def test_pmf(self): # regression test for ticket 1779 assert_allclose(np.exp(stats.nbinom.logpmf(700, 721, 0.52)), stats.nbinom.pmf(700, 721, 0.52)) class TestGeom(TestCase): def test_rvs(self): vals = stats.geom.rvs(0.75, size=(2, 50)) assert_(numpy.all(vals >= 0)) assert_(numpy.shape(vals) == (2, 50)) assert_(vals.dtype.char in typecodes['AllInteger']) val = stats.geom.rvs(0.75) assert_(isinstance(val, int)) val = stats.geom(0.75).rvs(3) assert_(isinstance(val, numpy.ndarray)) assert_(val.dtype.char in typecodes['AllInteger']) def test_pmf(self): vals = stats.geom.pmf([1,2,3],0.5) assert_array_almost_equal(vals,[0.5,0.25,0.125]) def test_logpmf(self): # regression test for ticket 1793 vals1 = np.log(stats.geom.pmf([1,2,3], 0.5)) vals2 = stats.geom.logpmf([1,2,3], 0.5) assert_allclose(vals1, vals2, rtol=1e-15, atol=0) def test_cdf_sf(self): vals = stats.geom.cdf([1, 2, 3], 0.5) vals_sf = stats.geom.sf([1, 2, 3], 0.5) expected = array([0.5, 0.75, 0.875]) assert_array_almost_equal(vals, expected) assert_array_almost_equal(vals_sf, 1-expected) def test_logcdf_logsf(self): vals = stats.geom.logcdf([1, 2, 3], 0.5) vals_sf = stats.geom.logsf([1, 2, 3], 0.5) expected = array([0.5, 0.75, 0.875]) assert_array_almost_equal(vals, np.log(expected)) assert_array_almost_equal(vals_sf, np.log1p(-expected)) def test_ppf(self): vals = stats.geom.ppf([0.5, 0.75, 0.875], 0.5) expected = array([1.0, 2.0, 3.0]) assert_array_almost_equal(vals, expected) class TestTruncnorm(TestCase): def test_ppf_ticket1131(self): vals = stats.truncnorm.ppf([-0.5,0,1e-4,0.5, 1-1e-4,1,2], -1., 1., loc=[3]*7, scale=2) expected = np.array([np.nan, 1, 1.00056419, 3, 4.99943581, 5, np.nan]) assert_array_almost_equal(vals, expected) def test_isf_ticket1131(self): vals = stats.truncnorm.isf([-0.5,0,1e-4,0.5, 1-1e-4,1,2], -1., 1., loc=[3]*7, scale=2) expected = np.array([np.nan, 5, 4.99943581, 3, 1.00056419, 1, np.nan]) assert_array_almost_equal(vals, expected) def test_gh_2477_small_values(self): # Check a case that worked in the original issue. low, high = -11, -10 x = stats.truncnorm.rvs(low, high, 0, 1, size=10) assert_(low < x.min() < x.max() < high) # Check a case that failed in the original issue. low, high = 10, 11 x = stats.truncnorm.rvs(low, high, 0, 1, size=10) assert_(low < x.min() < x.max() < high) def test_gh_2477_large_values(self): # Check a case that fails because of extreme tailness. raise SkipTest('truncnorm rvs is know to fail at extreme tails') low, high = 100, 101 x = stats.truncnorm.rvs(low, high, 0, 1, size=10) assert_(low < x.min() < x.max() < high) def test_gh_1489_trac_962_rvs(self): # Check the original example. low, high = 10, 15 x = stats.truncnorm.rvs(low, high, 0, 1, size=10) assert_(low < x.min() < x.max() < high) class TestHypergeom(TestCase): def test_rvs(self): vals = stats.hypergeom.rvs(20, 10, 3, size=(2, 50)) assert_(numpy.all(vals >= 0) & numpy.all(vals <= 3)) assert_(numpy.shape(vals) == (2, 50)) assert_(vals.dtype.char in typecodes['AllInteger']) val = stats.hypergeom.rvs(20, 3, 10) assert_(isinstance(val, int)) val = stats.hypergeom(20, 3, 10).rvs(3) assert_(isinstance(val, numpy.ndarray)) assert_(val.dtype.char in typecodes['AllInteger']) def test_precision(self): # comparison number from mpmath M = 2500 n = 50 N = 500 tot = M good = n hgpmf = stats.hypergeom.pmf(2, tot, good, N) assert_almost_equal(hgpmf, 0.0010114963068932233, 11) def test_cdf_above_one(self): # for some values of parameters, hypergeom cdf was >1, see gh-2238 assert_(0 <= stats.hypergeom.cdf(30, 13397950, 4363, 12390) <= 1.0) def test_precision2(self): # Test hypergeom precision for large numbers. See #1218. # Results compared with those from R. oranges = 9.9e4 pears = 1.1e5 fruits_eaten = np.array([3, 3.8, 3.9, 4, 4.1, 4.2, 5]) * 1e4 quantile = 2e4 res = [] for eaten in fruits_eaten: res.append(stats.hypergeom.sf(quantile, oranges + pears, oranges, eaten)) expected = np.array([0, 1.904153e-114, 2.752693e-66, 4.931217e-32, 8.265601e-11, 0.1237904, 1]) assert_allclose(res, expected, atol=0, rtol=5e-7) # Test with array_like first argument quantiles = [1.9e4, 2e4, 2.1e4, 2.15e4] res2 = stats.hypergeom.sf(quantiles, oranges + pears, oranges, 4.2e4) expected2 = [1, 0.1237904, 6.511452e-34, 3.277667e-69] assert_allclose(res2, expected2, atol=0, rtol=5e-7) def test_entropy(self): # Simple tests of entropy. hg = stats.hypergeom(4, 1, 1) h = hg.entropy() expected_p = np.array([0.75, 0.25]) expected_h = -np.sum(xlogy(expected_p, expected_p)) assert_allclose(h, expected_h) hg = stats.hypergeom(1, 1, 1) h = hg.entropy() assert_equal(h, 0.0) class TestLoggamma(TestCase): def test_stats(self): # The following precomputed values are from the table in section 2.2 # of "A Statistical Study of Log-Gamma Distribution", by Ping Shing # Chan (thesis, McMaster University, 1993). table = np.array([ # c, mean, var, skew, exc. kurt. 0.5, -1.9635, 4.9348, -1.5351, 4.0000, 1.0, -0.5772, 1.6449, -1.1395, 2.4000, 12.0, 2.4427, 0.0869, -0.2946, 0.1735, ]).reshape(-1, 5) for c, mean, var, skew, kurt in table: computed = stats.loggamma.stats(c, moments='msvk') assert_array_almost_equal(computed, [mean, var, skew, kurt], decimal=4) class TestLogser(TestCase): def test_rvs(self): vals = stats.logser.rvs(0.75, size=(2, 50)) assert_(numpy.all(vals >= 1)) assert_(numpy.shape(vals) == (2, 50)) assert_(vals.dtype.char in typecodes['AllInteger']) val = stats.logser.rvs(0.75) assert_(isinstance(val, int)) val = stats.logser(0.75).rvs(3) assert_(isinstance(val, numpy.ndarray)) assert_(val.dtype.char in typecodes['AllInteger']) class TestPareto(TestCase): def test_stats(self): # Check the stats() method with some simple values. Also check # that the calculations do not trigger RuntimeWarnings. with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) m, v, s, k = stats.pareto.stats(0.5, moments='mvsk') assert_equal(m, np.inf) assert_equal(v, np.inf) assert_equal(s, np.nan) assert_equal(k, np.nan) m, v, s, k = stats.pareto.stats(1.0, moments='mvsk') assert_equal(m, np.inf) assert_equal(v, np.inf) assert_equal(s, np.nan) assert_equal(k, np.nan) m, v, s, k = stats.pareto.stats(1.5, moments='mvsk') assert_equal(m, 3.0) assert_equal(v, np.inf) assert_equal(s, np.nan) assert_equal(k, np.nan) m, v, s, k = stats.pareto.stats(2.0, moments='mvsk') assert_equal(m, 2.0) assert_equal(v, np.inf) assert_equal(s, np.nan) assert_equal(k, np.nan) m, v, s, k = stats.pareto.stats(2.5, moments='mvsk') assert_allclose(m, 2.5 / 1.5) assert_allclose(v, 2.5 / (1.5*1.5*0.5)) assert_equal(s, np.nan) assert_equal(k, np.nan) m, v, s, k = stats.pareto.stats(3.0, moments='mvsk') assert_allclose(m, 1.5) assert_allclose(v, 0.75) assert_equal(s, np.nan) assert_equal(k, np.nan) m, v, s, k = stats.pareto.stats(3.5, moments='mvsk') assert_allclose(m, 3.5 / 2.5) assert_allclose(v, 3.5 / (2.5*2.5*1.5)) assert_allclose(s, (2*4.5/0.5)*np.sqrt(1.5/3.5)) assert_equal(k, np.nan) m, v, s, k = stats.pareto.stats(4.0, moments='mvsk') assert_allclose(m, 4.0 / 3.0) assert_allclose(v, 4.0 / 18.0) assert_allclose(s, 2*(1+4.0)/(4.0-3) * np.sqrt((4.0-2)/4.0)) assert_equal(k, np.nan) m, v, s, k = stats.pareto.stats(4.5, moments='mvsk') assert_allclose(m, 4.5 / 3.5) assert_allclose(v, 4.5 / (3.5*3.5*2.5)) assert_allclose(s, (2*5.5/1.5) * np.sqrt(2.5/4.5)) assert_allclose(k, 6*(4.5**3 + 4.5**2 - 6*4.5 - 2)/(4.5*1.5*0.5)) class TestPearson3(TestCase): def test_rvs(self): vals = stats.pearson3.rvs(0.1, size=(2, 50)) assert_(numpy.shape(vals) == (2, 50)) assert_(vals.dtype.char in typecodes['AllFloat']) val = stats.pearson3.rvs(0.5) assert_(isinstance(val, float)) val = stats.pearson3(0.5).rvs(3) assert_(isinstance(val, numpy.ndarray)) assert_(val.dtype.char in typecodes['AllFloat']) assert_(len(val) == 3) def test_pdf(self): vals = stats.pearson3.pdf(2, [0.0, 0.1, 0.2]) assert_allclose(vals, np.array([0.05399097, 0.05555481, 0.05670246]), atol=1e-6) vals = stats.pearson3.pdf(-3, 0.1) assert_allclose(vals, np.array([0.00313791]), atol=1e-6) vals = stats.pearson3.pdf([-3,-2,-1,0,1], 0.1) assert_allclose(vals, np.array([0.00313791, 0.05192304, 0.25028092, 0.39885918, 0.23413173]), atol=1e-6) def test_cdf(self): vals = stats.pearson3.cdf(2, [0.0, 0.1, 0.2]) assert_allclose(vals, np.array([0.97724987, 0.97462004, 0.97213626]), atol=1e-6) vals = stats.pearson3.cdf(-3, 0.1) assert_allclose(vals, [0.00082256], atol=1e-6) vals = stats.pearson3.cdf([-3,-2,-1,0,1], 0.1) assert_allclose(vals, [8.22563821e-04, 1.99860448e-02, 1.58550710e-01, 5.06649130e-01, 8.41442111e-01], atol=1e-6) class TestPoisson(TestCase): def test_rvs(self): vals = stats.poisson.rvs(0.5, size=(2, 50)) assert_(numpy.all(vals >= 0)) assert_(numpy.shape(vals) == (2, 50)) assert_(vals.dtype.char in typecodes['AllInteger']) val = stats.poisson.rvs(0.5) assert_(isinstance(val, int)) val = stats.poisson(0.5).rvs(3) assert_(isinstance(val, numpy.ndarray)) assert_(val.dtype.char in typecodes['AllInteger']) def test_stats(self): mu = 16.0 result = stats.poisson.stats(mu, moments='mvsk') assert_allclose(result, [mu, mu, np.sqrt(1.0/mu), 1.0/mu]) class TestZipf(TestCase): def test_rvs(self): vals = stats.zipf.rvs(1.5, size=(2, 50)) assert_(numpy.all(vals >= 1)) assert_(numpy.shape(vals) == (2, 50)) assert_(vals.dtype.char in typecodes['AllInteger']) val = stats.zipf.rvs(1.5) assert_(isinstance(val, int)) val = stats.zipf(1.5).rvs(3) assert_(isinstance(val, numpy.ndarray)) assert_(val.dtype.char in typecodes['AllInteger']) def test_moments(self): # n-th moment is finite iff a > n + 1 m, v = stats.zipf.stats(a=2.8) assert_(np.isfinite(m)) assert_equal(v, np.inf) s, k = stats.zipf.stats(a=4.8, moments='sk') assert_(not np.isfinite([s, k]).all()) class TestDLaplace(TestCase): def test_rvs(self): vals = stats.dlaplace.rvs(1.5, size=(2, 50)) assert_(numpy.shape(vals) == (2, 50)) assert_(vals.dtype.char in typecodes['AllInteger']) val = stats.dlaplace.rvs(1.5) assert_(isinstance(val, int)) val = stats.dlaplace(1.5).rvs(3) assert_(isinstance(val, numpy.ndarray)) assert_(val.dtype.char in typecodes['AllInteger']) assert_(stats.dlaplace.rvs(0.8) is not None) def test_stats(self): # compare the explicit formulas w/ direct summation using pmf a = 1. dl = stats.dlaplace(a) m, v, s, k = dl.stats('mvsk') N = 37 xx = np.arange(-N, N+1) pp = dl.pmf(xx) m2, m4 = np.sum(pp*xx**2), np.sum(pp*xx**4) assert_equal((m, s), (0,0)) assert_allclose((v, k), (m2, m4/m2**2 - 3.), atol=1e-14, rtol=1e-8) def test_stats2(self): a = np.log(2.) dl = stats.dlaplace(a) m, v, s, k = dl.stats('mvsk') assert_equal((m, s), (0.,0.)) assert_allclose((v, k), (4., 3.25)) class TestInvGamma(TestCase): @dec.skipif(NumpyVersion(np.__version__) < '1.7.0', "assert_* funcs broken with inf/nan") def test_invgamma_inf_gh_1866(self): # invgamma's moments are only finite for a>n # specific numbers checked w/ boost 1.54 with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) mvsk = stats.invgamma.stats(a=19.31, moments='mvsk') assert_allclose(mvsk, [0.05461496450, 0.0001723162534, 1.020362676, 2.055616582]) a = [1.1, 3.1, 5.6] mvsk = stats.invgamma.stats(a=a, moments='mvsk') expected = ([10., 0.476190476, 0.2173913043], # mmm [np.inf, 0.2061430632, 0.01312749422], # vvv [np.nan, 41.95235392, 2.919025532], # sss [np.nan, np.nan, 24.51923076]) # kkk for x, y in zip(mvsk, expected): assert_almost_equal(x, y) class TestF(TestCase): def test_f_moments(self): # n-th moment of F distributions is only finite for n < dfd / 2 m, v, s, k = stats.f.stats(11, 6.5, moments='mvsk') assert_(np.isfinite(m)) assert_(np.isfinite(v)) assert_(np.isfinite(s)) assert_(not np.isfinite(k)) def test_moments_warnings(self): # no warnings should be generated for dfd = 2, 4, 6, 8 (div by zero) with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) stats.f.stats(dfn=[11]*4, dfd=[2, 4, 6, 8], moments='mvsk') @dec.knownfailureif(True, 'f stats does not properly broadcast') def test_stats_broadcast(self): # stats do not fully broadcast just yet mv = stats.f.stats(dfn=11, dfd=[11, 12]) def test_rvgeneric_std(): # Regression test for #1191 assert_array_almost_equal(stats.t.std([5, 6]), [1.29099445, 1.22474487]) class TestRvDiscrete(TestCase): def test_rvs(self): states = [-1,0,1,2,3,4] probability = [0.0,0.3,0.4,0.0,0.3,0.0] samples = 1000 r = stats.rv_discrete(name='sample',values=(states,probability)) x = r.rvs(size=samples) assert_(isinstance(x, numpy.ndarray)) for s,p in zip(states,probability): assert_(abs(sum(x == s)/float(samples) - p) < 0.05) x = r.rvs() assert_(isinstance(x, int)) def test_entropy(self): # Basic tests of entropy. pvals = np.array([0.25, 0.45, 0.3]) p = stats.rv_discrete(values=([0, 1, 2], pvals)) expected_h = -sum(xlogy(pvals, pvals)) h = p.entropy() assert_allclose(h, expected_h) p = stats.rv_discrete(values=([0, 1, 2], [1.0, 0, 0])) h = p.entropy() assert_equal(h, 0.0) class TestExpon(TestCase): def test_zero(self): assert_equal(stats.expon.pdf(0),1) def test_tail(self): # Regression test for ticket 807 assert_equal(stats.expon.cdf(1e-18), 1e-18) assert_equal(stats.expon.isf(stats.expon.sf(40)), 40) class TestGenExpon(TestCase): def test_pdf_unity_area(self): from scipy.integrate import simps # PDF should integrate to one assert_almost_equal(simps(stats.genexpon.pdf(numpy.arange(0,10,0.01), 0.5, 0.5, 2.0), dx=0.01), 1, 1) def test_cdf_bounds(self): # CDF should always be positive cdf = stats.genexpon.cdf(numpy.arange(0, 10, 0.01), 0.5, 0.5, 2.0) assert_(numpy.all((0 <= cdf) & (cdf <= 1))) class TestExponpow(TestCase): def test_tail(self): assert_almost_equal(stats.exponpow.cdf(1e-10, 2.), 1e-20) assert_almost_equal(stats.exponpow.isf(stats.exponpow.sf(5, .8), .8), 5) class TestSkellam(TestCase): def test_pmf(self): # comparison to R k = numpy.arange(-10, 15) mu1, mu2 = 10, 5 skpmfR = numpy.array( [4.2254582961926893e-005, 1.1404838449648488e-004, 2.8979625801752660e-004, 6.9177078182101231e-004, 1.5480716105844708e-003, 3.2412274963433889e-003, 6.3373707175123292e-003, 1.1552351566696643e-002, 1.9606152375042644e-002, 3.0947164083410337e-002, 4.5401737566767360e-002, 6.1894328166820688e-002, 7.8424609500170578e-002, 9.2418812533573133e-002, 1.0139793148019728e-001, 1.0371927988298846e-001, 9.9076583077406091e-002, 8.8546660073089561e-002, 7.4187842052486810e-002, 5.8392772862200251e-002, 4.3268692953013159e-002, 3.0248159818374226e-002, 1.9991434305603021e-002, 1.2516877303301180e-002, 7.4389876226229707e-003]) assert_almost_equal(stats.skellam.pmf(k, mu1, mu2), skpmfR, decimal=15) def test_cdf(self): # comparison to R, only 5 decimals k = numpy.arange(-10, 15) mu1, mu2 = 10, 5 skcdfR = numpy.array( [6.4061475386192104e-005, 1.7810985988267694e-004, 4.6790611790020336e-004, 1.1596768997212152e-003, 2.7077485103056847e-003, 5.9489760066490718e-003, 1.2286346724161398e-002, 2.3838698290858034e-002, 4.3444850665900668e-002, 7.4392014749310995e-002, 1.1979375231607835e-001, 1.8168808048289900e-001, 2.6011268998306952e-001, 3.5253150251664261e-001, 4.5392943399683988e-001, 5.5764871387982828e-001, 6.5672529695723436e-001, 7.4527195703032389e-001, 8.1945979908281064e-001, 8.7785257194501087e-001, 9.2112126489802404e-001, 9.5136942471639818e-001, 9.7136085902200120e-001, 9.8387773632530240e-001, 9.9131672394792536e-001]) assert_almost_equal(stats.skellam.cdf(k, mu1, mu2), skcdfR, decimal=5) class TestLognorm(TestCase): def test_pdf(self): # Regression test for Ticket #1471: avoid nan with 0/0 situation with np.errstate(divide='ignore'): pdf = stats.lognorm.pdf([0, 0.5, 1], 1) assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228]) class TestBeta(TestCase): def test_logpdf(self): # Regression test for Ticket #1326: avoid nan with 0*log(0) situation logpdf = stats.beta.logpdf(0,1,0.5) assert_almost_equal(logpdf, -0.69314718056) logpdf = stats.beta.logpdf(0,0.5,1) assert_almost_equal(logpdf, np.inf) def test_logpdf_ticket_1866(self): alpha, beta = 267, 1472 x = np.array([0.2, 0.5, 0.6]) b = stats.beta(alpha, beta) assert_allclose(b.logpdf(x).sum(), -1201.699061824062) assert_allclose(b.pdf(x), np.exp(b.logpdf(x))) class TestBetaPrime(TestCase): def test_logpdf(self): alpha, beta = 267, 1472 x = np.array([0.2, 0.5, 0.6]) b = stats.betaprime(alpha, beta) assert_(np.isfinite(b.logpdf(x)).all()) assert_allclose(b.pdf(x), np.exp(b.logpdf(x))) class TestGamma(TestCase): def test_pdf(self): # a few test cases to compare with R pdf = stats.gamma.pdf(90, 394, scale=1./5) assert_almost_equal(pdf, 0.002312341) pdf = stats.gamma.pdf(3, 10, scale=1./5) assert_almost_equal(pdf, 0.1620358) def test_logpdf(self): # Regression test for Ticket #1326: cornercase avoid nan with 0*log(0) # situation logpdf = stats.gamma.logpdf(0,1) assert_almost_equal(logpdf, 0) class TestChi2(TestCase): # regression tests after precision improvements, ticket:1041, not verified def test_precision(self): assert_almost_equal(stats.chi2.pdf(1000, 1000), 8.919133934753128e-003, 14) assert_almost_equal(stats.chi2.pdf(100, 100), 0.028162503162596778, 14) class TestArrayArgument(TestCase): # test for ticket:992 def test_noexception(self): rvs = stats.norm.rvs(loc=(np.arange(5)), scale=np.ones(5), size=(10,5)) assert_equal(rvs.shape, (10,5)) class TestDocstring(TestCase): def test_docstrings(self): # See ticket #761 if stats.rayleigh.__doc__ is not None: self.assertTrue("rayleigh" in stats.rayleigh.__doc__.lower()) if stats.bernoulli.__doc__ is not None: self.assertTrue("bernoulli" in stats.bernoulli.__doc__.lower()) def test_no_name_arg(self): # If name is not given, construction shouldn't fail. See #1508. stats.rv_continuous() stats.rv_discrete() class TestEntropy(TestCase): def test_entropy_positive(self): # See ticket #497 pk = [0.5,0.2,0.3] qk = [0.1,0.25,0.65] eself = stats.entropy(pk,pk) edouble = stats.entropy(pk,qk) assert_(0.0 == eself) assert_(edouble >= 0.0) def test_entropy_base(self): pk = np.ones(16, float) S = stats.entropy(pk, base=2.) assert_(abs(S - 4.) < 1.e-5) qk = np.ones(16, float) qk[:8] = 2. S = stats.entropy(pk, qk) S2 = stats.entropy(pk, qk, base=2.) assert_(abs(S/S2 - np.log(2.)) < 1.e-5) def test_entropy_zero(self): # Test for PR-479 assert_almost_equal(stats.entropy([0, 1, 2]), 0.63651416829481278, decimal=12) def test_entropy_2d(self): pk = [[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]] qk = [[0.2, 0.1], [0.3, 0.6], [0.5, 0.3]] assert_array_almost_equal(stats.entropy(pk, qk), [0.1933259, 0.18609809]) @dec.skipif(NumpyVersion(np.__version__) < '1.7.0', "assert_* funcs broken with inf/nan") def test_entropy_2d_zero(self): pk = [[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]] qk = [[0.0, 0.1], [0.3, 0.6], [0.5, 0.3]] assert_array_almost_equal(stats.entropy(pk, qk), [np.inf, 0.18609809]) pk[0][0] = 0.0 assert_array_almost_equal(stats.entropy(pk, qk), [0.17403988, 0.18609809]) def TestArgsreduce(): a = array([1,3,2,1,2,3,3]) b,c = argsreduce(a > 1, a, 2) assert_array_equal(b, [3,2,2,3,3]) assert_array_equal(c, [2,2,2,2,2]) b,c = argsreduce(2 > 1, a, 2) assert_array_equal(b, a[0]) assert_array_equal(c, [2]) b,c = argsreduce(a > 0, a, 2) assert_array_equal(b, a) assert_array_equal(c, [2] * numpy.size(a)) class TestFitMethod(object): skip = ['ncf'] @dec.slow def test_fit(self): def check(func, dist, args, alpha): if dist in self.skip: raise SkipTest("%s fit known to fail" % dist) distfunc = getattr(stats, dist) with np.errstate(all='ignore'): res = distfunc.rvs(*args, **{'size':200}) vals = distfunc.fit(res) vals2 = distfunc.fit(res, optimizer='powell') # Only check the length of the return # FIXME: should check the actual results to see if we are 'close' # to what was created --- but what is 'close' enough if dist == 'frechet': assert_(len(vals) == len(args)) assert_(len(vals2) == len(args)) else: assert_(len(vals) == 2+len(args)) assert_(len(vals2) == 2+len(args)) for func, dist, args, alpha in test_all_distributions(): yield check, func, dist, args, alpha @dec.slow def test_fix_fit(self): def check(func, dist, args, alpha): # Not sure why 'ncf', and 'beta' are failing # frechet has different len(args) than distfunc.numargs if dist in self.skip + ['frechet']: raise SkipTest("%s fit known to fail" % dist) distfunc = getattr(stats, dist) with np.errstate(all='ignore'): res = distfunc.rvs(*args, **{'size':200}) vals = distfunc.fit(res,floc=0) vals2 = distfunc.fit(res,fscale=1) assert_(len(vals) == 2+len(args)) assert_(vals[-2] == 0) assert_(vals2[-1] == 1) assert_(len(vals2) == 2+len(args)) if len(args) > 0: vals3 = distfunc.fit(res, f0=args[0]) assert_(len(vals3) == 2+len(args)) assert_(vals3[0] == args[0]) if len(args) > 1: vals4 = distfunc.fit(res, f1=args[1]) assert_(len(vals4) == 2+len(args)) assert_(vals4[1] == args[1]) if len(args) > 2: vals5 = distfunc.fit(res, f2=args[2]) assert_(len(vals5) == 2+len(args)) assert_(vals5[2] == args[2]) for func, dist, args, alpha in test_all_distributions(): yield check, func, dist, args, alpha def test_fix_fit_2args_lognorm(self): # Regression test for #1551. np.random.seed(12345) with np.errstate(all='ignore'): x = stats.lognorm.rvs(0.25, 0., 20.0, size=20) assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)), [0.25888672, 0, 20], atol=1e-5) def test_fix_fit_norm(self): x = np.arange(1, 6) loc, scale = stats.norm.fit(x) assert_almost_equal(loc, 3) assert_almost_equal(scale, np.sqrt(2)) loc, scale = stats.norm.fit(x, floc=2) assert_equal(loc, 2) assert_equal(scale, np.sqrt(3)) loc, scale = stats.norm.fit(x, fscale=2) assert_almost_equal(loc, 3) assert_equal(scale, 2) def test_fix_fit_gamma(self): x = np.arange(1, 6) meanlog = np.log(x).mean() # A basic test of gamma.fit with floc=0. floc = 0 a, loc, scale = stats.gamma.fit(x, floc=floc) s = np.log(x.mean()) - meanlog assert_almost_equal(np.log(a) - special.digamma(a), s, decimal=5) assert_equal(loc, floc) assert_almost_equal(scale, x.mean()/a, decimal=8) # Regression tests for gh-2514. # The problem was that if `floc=0` was given, any other fixed # parameters were ignored. f0 = 1 floc = 0 a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc) assert_equal(a, f0) assert_equal(loc, floc) assert_almost_equal(scale, x.mean()/a, decimal=8) f0 = 2 floc = 0 a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc) assert_equal(a, f0) assert_equal(loc, floc) assert_almost_equal(scale, x.mean()/a, decimal=8) # loc and scale fixed. floc = 0 fscale = 2 a, loc, scale = stats.gamma.fit(x, floc=floc, fscale=fscale) assert_equal(loc, floc) assert_equal(scale, fscale) c = meanlog - np.log(fscale) assert_almost_equal(special.digamma(a), c) def test_fix_fit_beta(self): # Test beta.fit when both floc and fscale are given. def mlefunc(a, b, x): # Zeros of this function are critical points of # the maximum likelihood function. n = len(x) s1 = np.log(x).sum() s2 = np.log(1-x).sum() psiab = special.psi(a + b) func = [s1 - n * (-psiab + special.psi(a)), s2 - n * (-psiab + special.psi(b))] return func # Basic test with floc and fscale given. x = np.array([0.125, 0.25, 0.5]) a, b, loc, scale = stats.beta.fit(x, floc=0, fscale=1) assert_equal(loc, 0) assert_equal(scale, 1) assert_allclose(mlefunc(a, b, x), [0,0], atol=1e-6) # Basic test with f0, floc and fscale given. # This is also a regression test for gh-2514. x = np.array([0.125, 0.25, 0.5]) a, b, loc, scale = stats.beta.fit(x, f0=2, floc=0, fscale=1) assert_equal(a, 2) assert_equal(loc, 0) assert_equal(scale, 1) da, db = mlefunc(a, b, x) assert_allclose(db, 0, atol=1e-5) # Same floc and fscale values as above, but reverse the data # and fix b (f1). x2 = 1 - x a2, b2, loc2, scale2 = stats.beta.fit(x2, f1=2, floc=0, fscale=1) assert_equal(b2, 2) assert_equal(loc2, 0) assert_equal(scale2, 1) da, db = mlefunc(a2, b2, x2) assert_allclose(da, 0, atol=1e-5) # a2 of this test should equal b from above. assert_almost_equal(a2, b) # Check for detection of data out of bounds when floc and fscale # are given. assert_raises(ValueError, stats.beta.fit, x, floc=0.5, fscale=1) y = np.array([0, .5, 1]) assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1) assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1, f0=2) assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1, f1=2) # Check that attempting to fix all the parameters raises a ValueError. assert_raises(ValueError, stats.beta.fit, y, f0=0, f1=1, floc=2, fscale=3) class TestFrozen(TestCase): # Test that a frozen distribution gives the same results as the original object. # # Only tested for the normal distribution (with loc and scale specified) # and for the gamma distribution (with a shape parameter specified). def test_norm(self): dist = stats.norm frozen = stats.norm(loc=10.0, scale=3.0) result_f = frozen.pdf(20.0) result = dist.pdf(20.0, loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.cdf(20.0) result = dist.cdf(20.0, loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.ppf(0.25) result = dist.ppf(0.25, loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.isf(0.25) result = dist.isf(0.25, loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.sf(10.0) result = dist.sf(10.0, loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.median() result = dist.median(loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.mean() result = dist.mean(loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.var() result = dist.var(loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.std() result = dist.std(loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.entropy() result = dist.entropy(loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.moment(2) result = dist.moment(2,loc=10.0, scale=3.0) assert_equal(result_f, result) def test_gamma(self): a = 2.0 dist = stats.gamma frozen = stats.gamma(a) result_f = frozen.pdf(20.0) result = dist.pdf(20.0, a) assert_equal(result_f, result) result_f = frozen.cdf(20.0) result = dist.cdf(20.0, a) assert_equal(result_f, result) result_f = frozen.ppf(0.25) result = dist.ppf(0.25, a) assert_equal(result_f, result) result_f = frozen.isf(0.25) result = dist.isf(0.25, a) assert_equal(result_f, result) result_f = frozen.sf(10.0) result = dist.sf(10.0, a) assert_equal(result_f, result) result_f = frozen.median() result = dist.median(a) assert_equal(result_f, result) result_f = frozen.mean() result = dist.mean(a) assert_equal(result_f, result) result_f = frozen.var() result = dist.var(a) assert_equal(result_f, result) result_f = frozen.std() result = dist.std(a) assert_equal(result_f, result) result_f = frozen.entropy() result = dist.entropy(a) assert_equal(result_f, result) result_f = frozen.moment(2) result = dist.moment(2, a) assert_equal(result_f, result) def test_regression_ticket_1293(self): # Create a frozen distribution. frozen = stats.lognorm(1) # Call one of its methods that does not take any keyword arguments. m1 = frozen.moment(2) # Now call a method that takes a keyword argument. frozen.stats(moments='mvsk') # Call moment(2) again. # After calling stats(), the following was raising an exception. # So this test passes if the following does not raise an exception. m2 = frozen.moment(2) # The following should also be true, of course. But it is not # the focus of this test. assert_equal(m1, m2) def test_ab(self): # test that the support of a frozen distribution # (i) remains frozen even if it changes for the original one # (ii) is actually correct if the shape parameters are such that # the values of [a, b] are not the default [0, inf] # take a genpareto as an example where the support # depends on the value of the shape parameter: # for c > 0: a, b = 0, inf # for c < 0: a, b = 0, -1/c rv = stats.genpareto(c=-0.1) a, b = rv.dist.a, rv.dist.b assert_equal([a, b], [0., 10.]) stats.genpareto.pdf(0, c=0.1) # this changes genpareto.b assert_equal([rv.dist.a, rv.dist.b], [a, b]) rv1 = stats.genpareto(c=0.1) assert_(rv1.dist is not rv.dist) def test_rv_frozen_in_namespace(self): # Regression test for gh-3522 assert_(hasattr(stats.distributions, 'rv_frozen')) class TestExpect(TestCase): # Test for expect method. # # Uses normal distribution and beta distribution for finite bounds, and # hypergeom for discrete distribution with finite support def test_norm(self): v = stats.norm.expect(lambda x: (x-5)*(x-5), loc=5, scale=2) assert_almost_equal(v, 4, decimal=14) m = stats.norm.expect(lambda x: (x), loc=5, scale=2) assert_almost_equal(m, 5, decimal=14) lb = stats.norm.ppf(0.05, loc=5, scale=2) ub = stats.norm.ppf(0.95, loc=5, scale=2) prob90 = stats.norm.expect(lambda x: 1, loc=5, scale=2, lb=lb, ub=ub) assert_almost_equal(prob90, 0.9, decimal=14) prob90c = stats.norm.expect(lambda x: 1, loc=5, scale=2, lb=lb, ub=ub, conditional=True) assert_almost_equal(prob90c, 1., decimal=14) def test_beta(self): # case with finite support interval v = stats.beta.expect(lambda x: (x-19/3.)*(x-19/3.), args=(10,5), loc=5, scale=2) assert_almost_equal(v, 1./18., decimal=13) m = stats.beta.expect(lambda x: x, args=(10,5), loc=5., scale=2.) assert_almost_equal(m, 19/3., decimal=13) ub = stats.beta.ppf(0.95, 10, 10, loc=5, scale=2) lb = stats.beta.ppf(0.05, 10, 10, loc=5, scale=2) prob90 = stats.beta.expect(lambda x: 1., args=(10,10), loc=5., scale=2.,lb=lb, ub=ub, conditional=False) assert_almost_equal(prob90, 0.9, decimal=13) prob90c = stats.beta.expect(lambda x: 1, args=(10,10), loc=5, scale=2, lb=lb, ub=ub, conditional=True) assert_almost_equal(prob90c, 1., decimal=13) def test_hypergeom(self): # test case with finite bounds # without specifying bounds m_true, v_true = stats.hypergeom.stats(20, 10, 8, loc=5.) m = stats.hypergeom.expect(lambda x: x, args=(20, 10, 8), loc=5.) assert_almost_equal(m, m_true, decimal=13) v = stats.hypergeom.expect(lambda x: (x-9.)**2, args=(20, 10, 8), loc=5.) assert_almost_equal(v, v_true, decimal=14) # with bounds, bounds equal to shifted support v_bounds = stats.hypergeom.expect(lambda x: (x-9.)**2, args=(20, 10, 8), loc=5., lb=5, ub=13) assert_almost_equal(v_bounds, v_true, decimal=14) # drop boundary points prob_true = 1-stats.hypergeom.pmf([5, 13], 20, 10, 8, loc=5).sum() prob_bounds = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8), loc=5., lb=6, ub=12) assert_almost_equal(prob_bounds, prob_true, decimal=13) # conditional prob_bc = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8), loc=5., lb=6, ub=12, conditional=True) assert_almost_equal(prob_bc, 1, decimal=14) # check simple integral prob_b = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8), lb=0, ub=8) assert_almost_equal(prob_b, 1, decimal=13) def test_poisson(self): # poisson, use lower bound only prob_bounds = stats.poisson.expect(lambda x: 1, args=(2,), lb=3, conditional=False) prob_b_true = 1-stats.poisson.cdf(2,2) assert_almost_equal(prob_bounds, prob_b_true, decimal=14) prob_lb = stats.poisson.expect(lambda x: 1, args=(2,), lb=2, conditional=True) assert_almost_equal(prob_lb, 1, decimal=14) def test_genhalflogistic(self): # genhalflogistic, changes upper bound of support in _argcheck # regression test for gh-2622 halflog = stats.genhalflogistic # check consistency when calling expect twice with the same input res1 = halflog.expect(args=(1.5,)) halflog.expect(args=(0.5,)) res2 = halflog.expect(args=(1.5,)) assert_almost_equal(res1, res2, decimal=14) def test_rice_overflow(self): # rice.pdf(999, 0.74) was inf since special.i0 silentyly overflows # check that using i0e fixes it assert_(np.isfinite(stats.rice.pdf(999, 0.74))) assert_(np.isfinite(stats.rice.expect(lambda x: 1, args=(0.74,)))) assert_(np.isfinite(stats.rice.expect(lambda x: 2, args=(0.74,)))) assert_(np.isfinite(stats.rice.expect(lambda x: 3, args=(0.74,)))) class TestNct(TestCase): def test_nc_parameter(self): # Parameter values c<=0 were not enabled (gh-2402). # For negative values c and for c=0 results of rv.cdf(0) below were nan rv = stats.nct(5, 0) assert_equal(rv.cdf(0), 0.5) rv = stats.nct(5, -1) assert_almost_equal(rv.cdf(0), 0.841344746069, decimal=10) def test_broadcasting(self): res = stats.nct.pdf(5, np.arange(4,7)[:,None], np.linspace(0.1, 1, 4)) expected = array([[0.00321886, 0.00557466, 0.00918418, 0.01442997], [0.00217142, 0.00395366, 0.00683888, 0.01126276], [0.00153078, 0.00291093, 0.00525206, 0.00900815]]) assert_allclose(res, expected, rtol=1e-5) def text_variance_gh_issue_2401(self): # Computation of the variance of a non-central t-distribution resulted # in a TypeError: ufunc 'isinf' not supported for the input types, # and the inputs could not be safely coerced to any supported types # according to the casting rule 'safe' rv = stats.nct(4, 0) assert_equal(rv.var(), 2.0) def test_nct_inf_moments(self): # n-th moment of nct only exists for df > n m, v, s, k = stats.nct.stats(df=1.9, nc=0.3, moments='mvsk') assert_(np.isfinite(m)) assert_equal([v, s, k], [np.inf, np.nan, np.nan]) m, v, s, k = stats.nct.stats(df=3.1, nc=0.3, moments='mvsk') assert_(np.isfinite([m, v, s]).all()) assert_equal(k, np.nan) class TestRice(TestCase): def test_rice_zero_b(self): # rice distribution should work with b=0, cf gh-2164 x = [0.2, 1., 5.] assert_(np.isfinite(stats.rice.pdf(x, b=0.)).all()) assert_(np.isfinite(stats.rice.logpdf(x, b=0.)).all()) assert_(np.isfinite(stats.rice.cdf(x, b=0.)).all()) assert_(np.isfinite(stats.rice.logcdf(x, b=0.)).all()) q = [0.1, 0.1, 0.5, 0.9] assert_(np.isfinite(stats.rice.ppf(q, b=0.)).all()) mvsk = stats.rice.stats(0, moments='mvsk') assert_(np.isfinite(mvsk).all()) # furthermore, pdf is continuous as b\to 0 # rice.pdf(x, b\to 0) = x exp(-x^2/2) + O(b^2) # see e.g. Abramovich & Stegun 9.6.7 & 9.6.10 b = 1e-8 assert_allclose(stats.rice.pdf(x, 0), stats.rice.pdf(x, b), atol=b, rtol=0) def test_rice_rvs(self): rvs = stats.rice.rvs assert_equal(rvs(b=3.).size, 1) assert_equal(rvs(b=3., size=(3, 5)).shape, (3, 5)) class TestErlang(TestCase): def test_erlang_runtimewarning(self): # erlang should generate a RuntimeWarning if a non-integer # shape parameter is used. with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) # The non-integer shape parameter 1.3 should trigger a RuntimeWarning assert_raises(RuntimeWarning, stats.erlang.rvs, 1.3, loc=0, scale=1, size=4) # Calling the fit method with `f0` set to an integer should # *not* trigger a RuntimeWarning. It should return the same # values as gamma.fit(...). data = [0.5, 1.0, 2.0, 4.0] result_erlang = stats.erlang.fit(data, f0=1) result_gamma = stats.gamma.fit(data, f0=1) assert_allclose(result_erlang, result_gamma, rtol=1e-3) class TestExponWeib(TestCase): def test_pdf_logpdf(self): # Regression test for gh-3508. x = 0.1 a = 1.0 c = 100.0 p = stats.exponweib.pdf(x, a, c) logp = stats.exponweib.logpdf(x, a, c) # Expected values were computed with mpmath. assert_allclose([p, logp], [1.0000000000000054e-97, -223.35075402042244]) def test_a_is_1(self): # For issue gh-3508. # Check that when a=1, the pdf and logpdf methods of exponweib are the # same as those of weibull_min. x = np.logspace(-4, -1, 4) a = 1 c = 100 p = stats.exponweib.pdf(x, a, c) expected = stats.weibull_min.pdf(x, c) assert_allclose(p, expected) logp = stats.exponweib.logpdf(x, a, c) expected = stats.weibull_min.logpdf(x, c) assert_allclose(logp, expected) def test_a_is_1_c_is_1(self): # When a = 1 and c = 1, the distribution is exponential. x = np.logspace(-8, 1, 10) a = 1 c = 1 p = stats.exponweib.pdf(x, a, c) expected = stats.expon.pdf(x) assert_allclose(p, expected) logp = stats.exponweib.logpdf(x, a, c) expected = stats.expon.logpdf(x) assert_allclose(logp, expected) class TestRdist(TestCase): @dec.slow def test_rdist_cdf_gh1285(self): # check workaround in rdist._cdf for issue gh-1285. distfn = stats.rdist values = [0.001, 0.5, 0.999] assert_almost_equal(distfn.cdf(distfn.ppf(values, 541.0), 541.0), values, decimal=5) def test_540_567(): # test for nan returned in tickets 540, 567 assert_almost_equal(stats.norm.cdf(-1.7624320982),0.03899815971089126, decimal=10, err_msg='test_540_567') assert_almost_equal(stats.norm.cdf(-1.7624320983),0.038998159702449846, decimal=10, err_msg='test_540_567') assert_almost_equal(stats.norm.cdf(1.38629436112, loc=0.950273420309, scale=0.204423758009),0.98353464004309321, decimal=10, err_msg='test_540_567') def test_regression_ticket_1316(): # The following was raising an exception, because _construct_default_doc() # did not handle the default keyword extradoc=None. See ticket #1316. g = stats._continuous_distns.gamma_gen(name='gamma') def test_regression_ticket_1326(): # adjust to avoid nan with 0*log(0) assert_almost_equal(stats.chi2.pdf(0.0, 2), 0.5, 14) def test_regression_tukey_lambda(): # Make sure that Tukey-Lambda distribution correctly handles non-positive lambdas. x = np.linspace(-5.0, 5.0, 101) olderr = np.seterr(divide='ignore') try: for lam in [0.0, -1.0, -2.0, np.array([[-1.0], [0.0], [-2.0]])]: p = stats.tukeylambda.pdf(x, lam) assert_((p != 0.0).all()) assert_(~np.isnan(p).all()) lam = np.array([[-1.0], [0.0], [2.0]]) p = stats.tukeylambda.pdf(x, lam) finally: np.seterr(**olderr) assert_(~np.isnan(p).all()) assert_((p[0] != 0.0).all()) assert_((p[1] != 0.0).all()) assert_((p[2] != 0.0).any()) assert_((p[2] == 0.0).any()) @dec.skipif(DOCSTRINGS_STRIPPED) def test_regression_ticket_1421(): assert_('pdf(x, mu, loc=0, scale=1)' not in stats.poisson.__doc__) assert_('pmf(x,' in stats.poisson.__doc__) def test_nan_arguments_gh_issue_1362(): with np.errstate(invalid='ignore'): assert_(np.isnan(stats.t.logcdf(1, np.nan))) assert_(np.isnan(stats.t.cdf(1, np.nan))) assert_(np.isnan(stats.t.logsf(1, np.nan))) assert_(np.isnan(stats.t.sf(1, np.nan))) assert_(np.isnan(stats.t.pdf(1, np.nan))) assert_(np.isnan(stats.t.logpdf(1, np.nan))) assert_(np.isnan(stats.t.ppf(1, np.nan))) assert_(np.isnan(stats.t.isf(1, np.nan))) assert_(np.isnan(stats.bernoulli.logcdf(np.nan, 0.5))) assert_(np.isnan(stats.bernoulli.cdf(np.nan, 0.5))) assert_(np.isnan(stats.bernoulli.logsf(np.nan, 0.5))) assert_(np.isnan(stats.bernoulli.sf(np.nan, 0.5))) assert_(np.isnan(stats.bernoulli.pmf(np.nan, 0.5))) assert_(np.isnan(stats.bernoulli.logpmf(np.nan, 0.5))) assert_(np.isnan(stats.bernoulli.ppf(np.nan, 0.5))) assert_(np.isnan(stats.bernoulli.isf(np.nan, 0.5))) def test_frozen_fit_ticket_1536(): np.random.seed(5678) true = np.array([0.25, 0., 0.5]) x = stats.lognorm.rvs(true[0], true[1], true[2], size=100) olderr = np.seterr(divide='ignore') try: params = np.array(stats.lognorm.fit(x, floc=0.)) finally: np.seterr(**olderr) assert_almost_equal(params, true, decimal=2) params = np.array(stats.lognorm.fit(x, fscale=0.5, loc=0)) assert_almost_equal(params, true, decimal=2) params = np.array(stats.lognorm.fit(x, f0=0.25, loc=0)) assert_almost_equal(params, true, decimal=2) params = np.array(stats.lognorm.fit(x, f0=0.25, floc=0)) assert_almost_equal(params, true, decimal=2) np.random.seed(5678) loc = 1 floc = 0.9 x = stats.norm.rvs(loc, 2., size=100) params = np.array(stats.norm.fit(x, floc=floc)) expected = np.array([floc, np.sqrt(((x-floc)**2).mean())]) assert_almost_equal(params, expected, decimal=4) def test_regression_ticket_1530(): # Check the starting value works for Cauchy distribution fit. np.random.seed(654321) rvs = stats.cauchy.rvs(size=100) params = stats.cauchy.fit(rvs) expected = (0.045, 1.142) assert_almost_equal(params, expected, decimal=1) def test_tukeylambda_stats_ticket_1545(): # Some test for the variance and kurtosis of the Tukey Lambda distr. # See test_tukeylamdba_stats.py for more tests. mv = stats.tukeylambda.stats(0, moments='mvsk') # Known exact values: expected = [0, np.pi**2/3, 0, 1.2] assert_almost_equal(mv, expected, decimal=10) mv = stats.tukeylambda.stats(3.13, moments='mvsk') # 'expected' computed with mpmath. expected = [0, 0.0269220858861465102, 0, -0.898062386219224104] assert_almost_equal(mv, expected, decimal=10) mv = stats.tukeylambda.stats(0.14, moments='mvsk') # 'expected' computed with mpmath. expected = [0, 2.11029702221450250, 0, -0.02708377353223019456] assert_almost_equal(mv, expected, decimal=10) def test_poisson_logpmf_ticket_1436(): assert_(np.isfinite(stats.poisson.logpmf(1500, 200))) def test_powerlaw_stats(): """Test the powerlaw stats function. This unit test is also a regression test for ticket 1548. The exact values are: mean: mu = a / (a + 1) variance: sigma**2 = a / ((a + 2) * (a + 1) ** 2) skewness: One formula (see http://en.wikipedia.org/wiki/Skewness) is gamma_1 = (E[X**3] - 3*mu*E[X**2] + 2*mu**3) / sigma**3 A short calculation shows that E[X**k] is a / (a + k), so gamma_1 can be implemented as n = a/(a+3) - 3*(a/(a+1))*a/(a+2) + 2*(a/(a+1))**3 d = sqrt(a/((a+2)*(a+1)**2)) ** 3 gamma_1 = n/d Either by simplifying, or by a direct calculation of mu_3 / sigma**3, one gets the more concise formula: gamma_1 = -2.0 * ((a - 1) / (a + 3)) * sqrt((a + 2) / a) kurtosis: (See http://en.wikipedia.org/wiki/Kurtosis) The excess kurtosis is gamma_2 = mu_4 / sigma**4 - 3 A bit of calculus and algebra (sympy helps) shows that mu_4 = 3*a*(3*a**2 - a + 2) / ((a+1)**4 * (a+2) * (a+3) * (a+4)) so gamma_2 = 3*(3*a**2 - a + 2) * (a+2) / (a*(a+3)*(a+4)) - 3 which can be rearranged to gamma_2 = 6 * (a**3 - a**2 - 6*a + 2) / (a*(a+3)*(a+4)) """ cases = [(1.0, (0.5, 1./12, 0.0, -1.2)), (2.0, (2./3, 2./36, -0.56568542494924734, -0.6))] for a, exact_mvsk in cases: mvsk = stats.powerlaw.stats(a, moments="mvsk") assert_array_almost_equal(mvsk, exact_mvsk) def test_ksone_fit_freeze(): # Regression test for ticket #1638. d = np.array( [-0.18879233, 0.15734249, 0.18695107, 0.27908787, -0.248649, -0.2171497, 0.12233512, 0.15126419, 0.03119282, 0.4365294, 0.08930393, -0.23509903, 0.28231224, -0.09974875, -0.25196048, 0.11102028, 0.1427649, 0.10176452, 0.18754054, 0.25826724, 0.05988819, 0.0531668, 0.21906056, 0.32106729, 0.2117662, 0.10886442, 0.09375789, 0.24583286, -0.22968366, -0.07842391, -0.31195432, -0.21271196, 0.1114243, -0.13293002, 0.01331725, -0.04330977, -0.09485776, -0.28434547, 0.22245721, -0.18518199, -0.10943985, -0.35243174, 0.06897665, -0.03553363, -0.0701746, -0.06037974, 0.37670779, -0.21684405]) try: olderr = np.seterr(invalid='ignore') with warnings.catch_warnings(): warnings.simplefilter('ignore', UserWarning) warnings.simplefilter('ignore', RuntimeWarning) stats.ksone.fit(d) finally: np.seterr(**olderr) def test_norm_logcdf(): # Test precision of the logcdf of the normal distribution. # This precision was enhanced in ticket 1614. x = -np.asarray(list(range(0, 120, 4))) # Values from R expected = [-0.69314718, -10.36010149, -35.01343716, -75.41067300, -131.69539607, -203.91715537, -292.09872100, -396.25241451, -516.38564863, -652.50322759, -804.60844201, -972.70364403, -1156.79057310, -1356.87055173, -1572.94460885, -1805.01356068, -2053.07806561, -2317.13866238, -2597.19579746, -2893.24984493, -3205.30112136, -3533.34989701, -3877.39640444, -4237.44084522, -4613.48339520, -5005.52420869, -5413.56342187, -5837.60115548, -6277.63751711, -6733.67260303] olderr = np.seterr(divide='ignore') try: assert_allclose(stats.norm().logcdf(x), expected, atol=1e-8) finally: np.seterr(**olderr) def test_levy_cdf_ppf(): # Test levy.cdf, including small arguments. x = np.array([1000, 1.0, 0.5, 0.1, 0.01, 0.001]) # Expected values were calculated separately with mpmath. # E.g. # >>> mpmath.mp.dps = 100 # >>> x = mpmath.mp.mpf('0.01') # >>> cdf = mpmath.erfc(mpmath.sqrt(1/(2*x))) expected = np.array([0.9747728793699604, 0.3173105078629141, 0.1572992070502851, 0.0015654022580025495, 1.523970604832105e-23, 1.795832784800726e-219]) y = stats.levy.cdf(x) assert_allclose(y, expected, rtol=1e-10) # ppf(expected) should get us back to x. xx = stats.levy.ppf(expected) assert_allclose(xx, x, rtol=1e-13) def test_hypergeom_interval_1802(): # these two had endless loops assert_equal(stats.hypergeom.interval(.95, 187601, 43192, 757), (152.0, 197.0)) assert_equal(stats.hypergeom.interval(.945, 187601, 43192, 757), (152.0, 197.0)) # this was working also before assert_equal(stats.hypergeom.interval(.94, 187601, 43192, 757), (153.0, 196.0)) # degenerate case .a == .b assert_equal(stats.hypergeom.ppf(0.02, 100, 100, 8), 8) assert_equal(stats.hypergeom.ppf(1, 100, 100, 8), 8) def test_distribution_too_many_args(): # Check that a TypeError is raised when too many args are given to a method # Regression test for ticket 1815. x = np.linspace(0.1, 0.7, num=5) assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0) assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, loc=1.0) assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, 5) assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0, scale=0.5) assert_raises(TypeError, stats.gamma.rvs, 2., 3, loc=1.0, scale=0.5) assert_raises(TypeError, stats.gamma.cdf, x, 2., 3, loc=1.0, scale=0.5) assert_raises(TypeError, stats.gamma.ppf, x, 2., 3, loc=1.0, scale=0.5) assert_raises(TypeError, stats.gamma.stats, 2., 3, loc=1.0, scale=0.5) assert_raises(TypeError, stats.gamma.entropy, 2., 3, loc=1.0, scale=0.5) assert_raises(TypeError, stats.gamma.fit, x, 2., 3, loc=1.0, scale=0.5) # These should not give errors stats.gamma.pdf(x, 2, 3) # loc=3 stats.gamma.pdf(x, 2, 3, 4) # loc=3, scale=4 stats.gamma.stats(2., 3) stats.gamma.stats(2., 3, 4) stats.gamma.stats(2., 3, 4, 'mv') stats.gamma.rvs(2., 3, 4, 5) stats.gamma.fit(stats.gamma.rvs(2., size=7), 2.) # Also for a discrete distribution stats.geom.pmf(x, 2, loc=3) # no error, loc=3 assert_raises(TypeError, stats.geom.pmf, x, 2, 3, 4) assert_raises(TypeError, stats.geom.pmf, x, 2, 3, loc=4) # And for distributions with 0, 2 and 3 args respectively assert_raises(TypeError, stats.expon.pdf, x, 3, loc=1.0) assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, loc=1.0) assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, 0.1, 0.1) assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, loc=1.0) assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, 1.0, scale=0.5) stats.ncf.pdf(x, 3, 4, 5, 6, 1.0) # 3 args, plus loc/scale def test_ncx2_tails_ticket_955(): # Trac #955 -- check that the cdf computed by special functions # matches the integrated pdf a = stats.ncx2.cdf(np.arange(20, 25, 0.2), 2, 1.07458615e+02) b = stats.ncx2._cdfvec(np.arange(20, 25, 0.2), 2, 1.07458615e+02) assert_allclose(a, b, rtol=1e-3, atol=0) def test_foldnorm_zero(): # Parameter value c=0 was not enabled, see gh-2399. rv = stats.foldnorm(0, scale=1) assert_equal(rv.cdf(0), 0) # rv.cdf(0) previously resulted in: nan def test_stats_shapes_argcheck(): # stats method was failing for vector shapes if some of the values # were outside of the allowed range, see gh-2678 mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5) # 0 is not a legal `a` mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5) mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2) assert_equal(mv2_augmented, mv3) mv3 = stats.lognorm.stats([2, 2.4, -1]) # -1 is not a legal shape parameter mv2 = stats.lognorm.stats([2, 2.4]) mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2) assert_equal(mv2_augmented, mv3) # FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix. # stats method with multiple shape parameters is not properly vectorized # anyway, so some distributions may or may not fail. ## Test subclassing distributions w/ explicit shapes class _distr_gen(stats.rv_continuous): def _pdf(self, x, a): return 42 class _distr2_gen(stats.rv_continuous): def _cdf(self, x, a): return 42 * a + x class _distr3_gen(stats.rv_continuous): def _pdf(self, x, a, b): return a + b def _cdf(self, x, a): # Different # of shape params from _pdf, to be able to check that # inspection catches the inconsistency.""" return 42 * a + x class _distr6_gen(stats.rv_continuous): # Two shape parameters (both _pdf and _cdf defined, consistent shapes.) def _pdf(self, x, a, b): return a*x + b def _cdf(self, x, a, b): return 42 * a + x class TestSubclassingExplicitShapes(TestCase): # Construct a distribution w/ explicit shapes parameter and test it. def test_correct_shapes(self): dummy_distr = _distr_gen(name='dummy', shapes='a') assert_equal(dummy_distr.pdf(1, a=1), 42) def test_wrong_shapes_1(self): dummy_distr = _distr_gen(name='dummy', shapes='A') assert_raises(TypeError, dummy_distr.pdf, 1, **dict(a=1)) def test_wrong_shapes_2(self): dummy_distr = _distr_gen(name='dummy', shapes='a, b, c') dct = dict(a=1, b=2, c=3) assert_raises(TypeError, dummy_distr.pdf, 1, **dct) def test_shapes_string(self): # shapes must be a string dct = dict(name='dummy', shapes=42) assert_raises(TypeError, _distr_gen, **dct) def test_shapes_identifiers_1(self): # shapes must be a comma-separated list of valid python identifiers dct = dict(name='dummy', shapes='(!)') assert_raises(SyntaxError, _distr_gen, **dct) def test_shapes_identifiers_2(self): dct = dict(name='dummy', shapes='4chan') assert_raises(SyntaxError, _distr_gen, **dct) def test_shapes_identifiers_3(self): dct = dict(name='dummy', shapes='m(fti)') assert_raises(SyntaxError, _distr_gen, **dct) def test_shapes_identifiers_nodefaults(self): dct = dict(name='dummy', shapes='a=2') assert_raises(SyntaxError, _distr_gen, **dct) def test_shapes_args(self): dct = dict(name='dummy', shapes='*args') assert_raises(SyntaxError, _distr_gen, **dct) def test_shapes_kwargs(self): dct = dict(name='dummy', shapes='**kwargs') assert_raises(SyntaxError, _distr_gen, **dct) def test_shapes_keywords(self): # python keywords cannot be used for shape parameters dct = dict(name='dummy', shapes='a, b, c, lambda') assert_raises(SyntaxError, _distr_gen, **dct) def test_shapes_signature(self): # test explicit shapes which agree w/ the signature of _pdf class _dist_gen(stats.rv_continuous): def _pdf(self, x, a): return stats.norm._pdf(x) * a dist = _dist_gen(shapes='a') assert_equal(dist.pdf(0.5, a=2), stats.norm.pdf(0.5)*2) def test_shapes_signature_inconsistent(self): # test explicit shapes which do not agree w/ the signature of _pdf class _dist_gen(stats.rv_continuous): def _pdf(self, x, a): return stats.norm._pdf(x) * a dist = _dist_gen(shapes='a, b') assert_raises(TypeError, dist.pdf, 0.5, **dict(a=1, b=2)) def test_star_args(self): # test _pdf with only starargs # NB: **kwargs of pdf will never reach _pdf class _dist_gen(stats.rv_continuous): def _pdf(self, x, *args): extra_kwarg = args[0] return stats.norm._pdf(x) * extra_kwarg dist = _dist_gen(shapes='extra_kwarg') assert_equal(dist.pdf(0.5, extra_kwarg=33), stats.norm.pdf(0.5)*33) assert_equal(dist.pdf(0.5, 33), stats.norm.pdf(0.5)*33) assert_raises(TypeError, dist.pdf, 0.5, **dict(xxx=33)) def test_star_args_2(self): # test _pdf with named & starargs # NB: **kwargs of pdf will never reach _pdf class _dist_gen(stats.rv_continuous): def _pdf(self, x, offset, *args): extra_kwarg = args[0] return stats.norm._pdf(x) * extra_kwarg + offset dist = _dist_gen(shapes='offset, extra_kwarg') assert_equal(dist.pdf(0.5, offset=111, extra_kwarg=33), stats.norm.pdf(0.5)*33 + 111) assert_equal(dist.pdf(0.5, 111, 33), stats.norm.pdf(0.5)*33 + 111) def test_extra_kwarg(self): # **kwargs to _pdf are ignored. # this is a limitation of the framework (_pdf(x, *goodargs)) class _distr_gen(stats.rv_continuous): def _pdf(self, x, *args, **kwargs): # _pdf should handle *args, **kwargs itself. Here "handling" is # ignoring *args and looking for ``extra_kwarg`` and using that. extra_kwarg = kwargs.pop('extra_kwarg', 1) return stats.norm._pdf(x) * extra_kwarg dist = _distr_gen(shapes='extra_kwarg') assert_equal(dist.pdf(1, extra_kwarg=3), stats.norm.pdf(1)) def shapes_empty_string(self): # shapes='' is equivalent to shapes=None class _dist_gen(stats.rv_continuous): def _pdf(self, x): return stats.norm.pdf(x) dist = _dist_gen(shapes='') assert_equal(dist.pdf(0.5), stats.norm.pdf(0.5)) class TestSubclassingNoShapes(TestCase): # Construct a distribution w/o explicit shapes parameter and test it. def test_only__pdf(self): dummy_distr = _distr_gen(name='dummy') assert_equal(dummy_distr.pdf(1, a=1), 42) def test_only__cdf(self): # _pdf is determined from _cdf by taking numerical derivative dummy_distr = _distr2_gen(name='dummy') assert_almost_equal(dummy_distr.pdf(1, a=1), 1) @dec.skipif(DOCSTRINGS_STRIPPED) def test_signature_inspection(self): # check that _pdf signature inspection works correctly, and is used in # the class docstring dummy_distr = _distr_gen(name='dummy') assert_equal(dummy_distr.numargs, 1) assert_equal(dummy_distr.shapes, 'a') res = re.findall('logpdf\(x, a, loc=0, scale=1\)', dummy_distr.__doc__) assert_(len(res) == 1) @dec.skipif(DOCSTRINGS_STRIPPED) def test_signature_inspection_2args(self): # same for 2 shape params and both _pdf and _cdf defined dummy_distr = _distr6_gen(name='dummy') assert_equal(dummy_distr.numargs, 2) assert_equal(dummy_distr.shapes, 'a, b') res = re.findall('logpdf\(x, a, b, loc=0, scale=1\)', dummy_distr.__doc__) assert_(len(res) == 1) def test_signature_inspection_2args_incorrect_shapes(self): # both _pdf and _cdf defined, but shapes are inconsistent: raises try: _distr3_gen(name='dummy') except TypeError: pass else: raise AssertionError('TypeError not raised.') def test_defaults_raise(self): # default arguments should raise class _dist_gen(stats.rv_continuous): def _pdf(self, x, a=42): return 42 assert_raises(TypeError, _dist_gen, **dict(name='dummy')) def test_starargs_raise(self): # without explicit shapes, *args are not allowed class _dist_gen(stats.rv_continuous): def _pdf(self, x, a, *args): return 42 assert_raises(TypeError, _dist_gen, **dict(name='dummy')) def test_kwargs_raise(self): # without explicit shapes, **kwargs are not allowed class _dist_gen(stats.rv_continuous): def _pdf(self, x, a, **kwargs): return 42 assert_raises(TypeError, _dist_gen, **dict(name='dummy')) @dec.skipif(DOCSTRINGS_STRIPPED) def test_docstrings(): badones = [',\s*,', '\(\s*,', '^\s*:'] for distname in stats.__all__: dist = getattr(stats, distname) if isinstance(dist, (stats.rv_discrete, stats.rv_continuous)): for regex in badones: assert_(re.search(regex, dist.__doc__) is None) def test_infinite_input(): assert_almost_equal(stats.skellam.sf(np.inf, 10, 11), 0) assert_almost_equal(stats.ncx2._cdf(np.inf, 8, 0.1), 1) if __name__ == "__main__": run_module_suite()
37.48836
86
0.588928
4a10291c430e69e2696c7a5be61e579fe8f8b483
4,176
py
Python
glomeruli_segmentation/api_interface.py
theodore-evans/hubmap-kidney-segmentation
7842655d49080be28682a9cf0394bcbe53172ddc
[ "MIT" ]
null
null
null
glomeruli_segmentation/api_interface.py
theodore-evans/hubmap-kidney-segmentation
7842655d49080be28682a9cf0394bcbe53172ddc
[ "MIT" ]
null
null
null
glomeruli_segmentation/api_interface.py
theodore-evans/hubmap-kidney-segmentation
7842655d49080be28682a9cf0394bcbe53172ddc
[ "MIT" ]
null
null
null
from io import BytesIO from logging import Logger from typing import Tuple, Type, Union import desert from aiohttp import ClientSession, TCPConnector from marshmallow import EXCLUDE from PIL import Image from glomeruli_segmentation.aiohttp_hooks import get_logging_hooks from glomeruli_segmentation.data_classes import Rect, Tile, Wsi from glomeruli_segmentation.logging_tools import get_logger API_VERSION = "v0" class LoggingClientSession(ClientSession): def __init__(self, logger: dict, get_hooks: Tuple = get_logging_hooks, **kwargs): super().__init__(**kwargs) self.hooks = {"response": [get_hook(logger) for get_hook in get_hooks]} async def _request(self, method, str_or_url, **kwargs): r = await super()._request(method, str_or_url, **kwargs) for hook in self.hooks["response"]: await hook(r) return r # TODO: add methods for getting from /configuration and post/putting to /failure class ApiInterface: def __init__(self, api_url: str, job_id: str, headers: dict, logger: Logger = get_logger()): self.logger = logger self.api_url = api_url self.job_id = job_id self.headers = headers self.session: LoggingClientSession = None async def __aenter__(self): self.session = LoggingClientSession( connector=TCPConnector(keepalive_timeout=5, ssl=False, limit=10), headers=self.headers, logger=self.logger, ) await self.session.__aenter__() return self async def __aexit__(self, exc_type, exc_val, exc_tb): if self.session: return await self.session.__aexit__(exc_type, exc_val, exc_tb) async def check_alive(self) -> dict: """ check if API is alive """ url = f"{self.api_url}/alive" r = await self.session.get(url) return await r.json() async def get_input(self, key: str, input_type: Type) -> Union[Rect, Wsi]: """ fetch an input from API """ url = f"{self.api_url}/{API_VERSION}/{self.job_id}/inputs/{key}" r = await self.session.get(url) schema = desert.schema(input_type, meta={"unknown": EXCLUDE}) response = await r.json() return schema.load(response) async def post_output(self, key: str, data: dict) -> dict: """ post output data by key as defined in EAD """ url = f"{self.api_url}/{API_VERSION}/{self.job_id}/outputs/{key}" r = await self.session.post(url, json=data) return await r.json() async def post_items_to_collection(self, collection: dict, items: list) -> dict: """ add items to an existing output collection Parameters: items: list of data elements """ url = f"{self.api_url}/{API_VERSION}/{self.job_id}/collections/{collection['id']}/items" r = await self.session.post(url, json={"items": items}) items = await r.json() return items["items"] async def get_wsi_tile(self, slide: Wsi, rect: Rect) -> Tile: """ get a WSI tile on level 0 Parameters: wsi_slide: Wsi object with WSI id (and meta data) rectangle: Rectangle describing tile position """ x, y = rect.upper_left url = f"{self.api_url}/{API_VERSION}/{self.job_id}/regions/{slide.id}/level/{rect.level}/start/{x}/{y}/size/{rect.width}/{rect.height}" r = await self.session.get(url) content = await r.read() return Tile(image=Image.open(BytesIO(content)), rect=rect) async def put_finalize(self) -> dict: """ finalize job, such that no more data can be added and to inform EMPAIA infrastructure about job state """ url = f"{self.api_url}/{API_VERSION}/{self.job_id}/finalize" r = await self.session.put(url) return await r.json() async def put_failure(self, message: str) -> dict: url = f"{self.api_url}/{API_VERSION}/{self.job_id}/failure" r = await self.session.put(url, json={"user_message": message.replace('"', "'")}) return await r.json()
34.8
143
0.633142
4a10295b92dd20b77d763cfd6182b90950f823e4
1,599
py
Python
src/pipe/pipe.py
Ochmar/kivy_floppy_bird
0ef38ecc7b160e723dbb99cf6d71dba0024b0836
[ "MIT" ]
null
null
null
src/pipe/pipe.py
Ochmar/kivy_floppy_bird
0ef38ecc7b160e723dbb99cf6d71dba0024b0836
[ "MIT" ]
null
null
null
src/pipe/pipe.py
Ochmar/kivy_floppy_bird
0ef38ecc7b160e723dbb99cf6d71dba0024b0836
[ "MIT" ]
null
null
null
from kivy.uix.widget import Widget from kivy.properties import NumericProperty, ObjectProperty, ListProperty from kivy.uix.image import Image from kivy.clock import Clock class Pipe(Widget): GAP_SIZE = NumericProperty(100) CAP_SIZE = NumericProperty(20) pipe_center = NumericProperty(0) bottom_body_position = NumericProperty(0) bottom_cap_position = NumericProperty(0) top_body_position = NumericProperty(0) top_cap_position = NumericProperty(0) pipe_body_texture = ObjectProperty(None) bottom_pipe_tex_coords = ListProperty((0, 0, 1, 0, 1, 1, 0, 1)) top_pipe_tex_coords = ListProperty((0, 0, 1, 0, 1, 1, 0, 1)) def __init__(self, **kwargs): super(Pipe, self).__init__(**kwargs) self.pipe_body_texture = Image(source="assets/pipe_body.png").texture self.pipe_body_texture.wrap = 'repeat' def on_size(self, *args): bottom_body_size = self.bottom_cap_position - self.bottom_body_position self.bottom_pipe_tex_coords[5] = bottom_body_size / 20. self.bottom_pipe_tex_coords[7] = bottom_body_size / 20. top_body_size = self.top - self.top_body_position self.top_pipe_tex_coords[5] = top_body_size / 20. self.top_pipe_tex_coords[7] = top_body_size / 20. def on_pipe_center(self, *args): Clock.schedule_once(self.on_size, 0) @classmethod def pipe_factory(cls, *, pipe_center, size_hint, pos, size): pipe = cls() pipe.pipe_center = pipe_center pipe.size_hint = size pipe.pos = pos pipe.size = size return pipe
35.533333
79
0.693558
4a102a037ec43a6ba7dabf95381c352ed0fe2ce0
2,296
py
Python
src/GimelStudio/corenodes/blend/composite_node.py
iwoithe/Gimel-Studio
e2750576e72edee6f2f4c268045b81459df82d89
[ "Apache-2.0" ]
47
2020-05-22T09:10:05.000Z
2021-04-08T06:27:50.000Z
src/GimelStudio/corenodes/blend/composite_node.py
iwoithe/Gimel-Studio
e2750576e72edee6f2f4c268045b81459df82d89
[ "Apache-2.0" ]
24
2020-08-26T13:51:10.000Z
2021-04-18T01:41:51.000Z
src/GimelStudio/corenodes/blend/composite_node.py
iwoithe/Gimel-Studio
e2750576e72edee6f2f4c268045b81459df82d89
[ "Apache-2.0" ]
9
2020-08-16T14:27:14.000Z
2021-02-17T19:04:34.000Z
# THIS FILE IS A PART OF GIMEL STUDIO AND IS LICENSED UNDER THE SAME TERMS: # ---------------------------------------------------------------------------- # Gimel Studio Copyright 2019-2021 by Noah Rahm and contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- from PIL import Image, ImageOps from GimelStudio import api class CompositeNode(api.NodeBase): def __init__(self, _id): api.NodeBase.__init__(self, _id) @property def NodeMeta(self): meta_info = { "label": "Composite", "author": "Correct Syntax", "version": (1, 1, 0), "supported_app_version": (0, 5, 0), "category": "BLEND", "description": "Creates composite image by blending images using a transparency mask.", } return meta_info def NodeInitParams(self): p1 = api.RenderImageParam('Image 1') p2 = api.RenderImageParam('Image 2') p3 = api.RenderImageParam('Alpha Mask') self.NodeAddParam(p1) self.NodeAddParam(p2) self.NodeAddParam(p3) def NodeEvaluation(self, eval_info): image1 = eval_info.EvaluateParameter('Image 1') image2 = eval_info.EvaluateParameter('Image 2') mask = eval_info.EvaluateParameter('Alpha Mask') image = api.RenderImage() main_image = image1.GetImage() layer_image = ImageOps.fit(image2.GetImage(), main_image.size) mask_image = ImageOps.fit(mask.GetImage(), main_image.size).convert('RGBA') image.SetAsImage(Image.composite(main_image, layer_image, mask_image)) self.NodeSetThumb(image.GetImage()) return image api.RegisterNode(CompositeNode, "corenode_composite")
35.875
99
0.630662
4a102aaceb9253ea6edf5251bb0d6ce384f17c25
25,148
py
Python
analysis/webservice/algorithms_spark/TimeSeriesSpark.py
tloubrieu-jpl/incubator-sdap-nexus
5bf903f04f12eb27f25ea2aa738c617ca404a87b
[ "Apache-2.0" ]
1
2019-11-25T18:49:26.000Z
2019-11-25T18:49:26.000Z
analysis/webservice/algorithms_spark/TimeSeriesSpark.py
ifenty/incubator-sdap-nexus
3059c66f53d3f3d24c74d557c7632bdcc7f1eeec
[ "Apache-2.0" ]
null
null
null
analysis/webservice/algorithms_spark/TimeSeriesSpark.py
ifenty/incubator-sdap-nexus
3059c66f53d3f3d24c74d557c7632bdcc7f1eeec
[ "Apache-2.0" ]
null
null
null
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math import calendar import itertools import logging import traceback from cStringIO import StringIO from datetime import datetime import matplotlib.dates as mdates import matplotlib.pyplot as plt import numpy as np import pytz import shapely.geometry import shapely.wkt from backports.functools_lru_cache import lru_cache from nexustiles.nexustiles import NexusTileService from pytz import timezone from scipy import stats from webservice import Filtering as filtering from webservice.NexusHandler import nexus_handler, SparkHandler from webservice.webmodel import NexusResults, NoDataException, NexusProcessingException EPOCH = timezone('UTC').localize(datetime(1970, 1, 1)) ISO_8601 = '%Y-%m-%dT%H:%M:%S%z' @nexus_handler class TimeSeriesHandlerImpl(SparkHandler): name = "Time Series Spark" path = "/timeSeriesSpark" description = "Computes a time series plot between one or more datasets given an arbitrary geographical area and time range" params = { "ds": { "name": "Dataset", "type": "comma-delimited string", "description": "The dataset(s) Used to generate the Time Series. Required" }, "startTime": { "name": "Start Time", "type": "string", "description": "Starting time in format YYYY-MM-DDTHH:mm:ssZ or seconds since EPOCH. Required" }, "endTime": { "name": "End Time", "type": "string", "description": "Ending time in format YYYY-MM-DDTHH:mm:ssZ or seconds since EPOCH. Required" }, "b": { "name": "Bounding box", "type": "comma-delimited float", "description": "Minimum (Western) Longitude, Minimum (Southern) Latitude, " "Maximum (Eastern) Longitude, Maximum (Northern) Latitude. Required" }, "seasonalFilter": { "name": "Compute Seasonal Cycle Filter", "type": "boolean", "description": "Flag used to specify if the seasonal averages should be computed during " "Time Series computation. Optional (Default: False)" }, "lowPassFilter": { "name": "Compute Low Pass Filter", "type": "boolean", "description": "Flag used to specify if a low pass filter should be computed during " "Time Series computation. Optional (Default: True)" }, "spark": { "name": "Spark Configuration", "type": "comma-delimited value", "description": "Configuration used to launch in the Spark cluster. Value should be 3 elements separated by " "commas. 1) Spark Master 2) Number of Spark Executors 3) Number of Spark Partitions. Only " "Number of Spark Partitions is used by this function. Optional (Default: local,1,1)" } } singleton = True def __init__(self): SparkHandler.__init__(self) self.log = logging.getLogger(__name__) def parse_arguments(self, request): # Parse input arguments self.log.debug("Parsing arguments") try: ds = request.get_dataset() if type(ds) != list and type(ds) != tuple: ds = (ds,) except: raise NexusProcessingException( reason="'ds' argument is required. Must be comma-delimited string", code=400) # Do not allow time series on Climatology if next(iter([clim for clim in ds if 'CLIM' in clim]), False): raise NexusProcessingException(reason="Cannot compute time series on a climatology", code=400) try: bounding_polygon = request.get_bounding_polygon() request.get_min_lon = lambda: bounding_polygon.bounds[0] request.get_min_lat = lambda: bounding_polygon.bounds[1] request.get_max_lon = lambda: bounding_polygon.bounds[2] request.get_max_lat = lambda: bounding_polygon.bounds[3] except: try: west, south, east, north = request.get_min_lon(), request.get_min_lat(), \ request.get_max_lon(), request.get_max_lat() bounding_polygon = shapely.geometry.Polygon( [(west, south), (east, south), (east, north), (west, north), (west, south)]) except: raise NexusProcessingException( reason="'b' argument is required. Must be comma-delimited float formatted as " "Minimum (Western) Longitude, Minimum (Southern) Latitude, " "Maximum (Eastern) Longitude, Maximum (Northern) Latitude", code=400) try: start_time = request.get_start_datetime() except: raise NexusProcessingException( reason="'startTime' argument is required. Can be int value seconds from epoch or " "string format YYYY-MM-DDTHH:mm:ssZ", code=400) try: end_time = request.get_end_datetime() except: raise NexusProcessingException( reason="'endTime' argument is required. Can be int value seconds from epoch or " "string format YYYY-MM-DDTHH:mm:ssZ", code=400) if start_time > end_time: raise NexusProcessingException( reason="The starting time must be before the ending time. Received startTime: %s, endTime: %s" % ( request.get_start_datetime().strftime(ISO_8601), request.get_end_datetime().strftime(ISO_8601)), code=400) apply_seasonal_cycle_filter = request.get_apply_seasonal_cycle_filter(default=False) apply_low_pass_filter = request.get_apply_low_pass_filter() start_seconds_from_epoch = long((start_time - EPOCH).total_seconds()) end_seconds_from_epoch = long((end_time - EPOCH).total_seconds()) nparts_requested = request.get_nparts() return ds, bounding_polygon, start_seconds_from_epoch, end_seconds_from_epoch, apply_seasonal_cycle_filter, apply_low_pass_filter, nparts_requested def calc(self, request, **args): """ :param request: StatsComputeOptions :param args: dict :return: """ ds, bounding_polygon, start_seconds_from_epoch, end_seconds_from_epoch, apply_seasonal_cycle_filter, apply_low_pass_filter, nparts_requested = self.parse_arguments(request) resultsRaw = [] for shortName in ds: the_time = datetime.now() daysinrange = self._tile_service.find_days_in_range_asc(bounding_polygon.bounds[1], bounding_polygon.bounds[3], bounding_polygon.bounds[0], bounding_polygon.bounds[2], shortName, start_seconds_from_epoch, end_seconds_from_epoch) self.log.info("Finding days in range took %s for dataset %s" % (str(datetime.now() - the_time), shortName)) ndays = len(daysinrange) if ndays == 0: raise NoDataException(reason="No data found for selected timeframe") self.log.debug('Found {0} days in range'.format(ndays)) for i, d in enumerate(daysinrange): self.log.debug('{0}, {1}'.format(i, datetime.utcfromtimestamp(d))) spark_nparts = self._spark_nparts(nparts_requested) self.log.info('Using {} partitions'.format(spark_nparts)) the_time = datetime.now() results, meta = spark_driver(daysinrange, bounding_polygon, shortName, spark_nparts=spark_nparts, sc=self._sc) self.log.info( "Time series calculation took %s for dataset %s" % (str(datetime.now() - the_time), shortName)) if apply_seasonal_cycle_filter: the_time = datetime.now() for result in results: month = datetime.utcfromtimestamp(result['time']).month month_mean, month_max, month_min = self.calculate_monthly_average(month, bounding_polygon.wkt, shortName) seasonal_mean = result['mean'] - month_mean seasonal_min = result['min'] - month_min seasonal_max = result['max'] - month_max result['meanSeasonal'] = seasonal_mean result['minSeasonal'] = seasonal_min result['maxSeasonal'] = seasonal_max self.log.info( "Seasonal calculation took %s for dataset %s" % (str(datetime.now() - the_time), shortName)) the_time = datetime.now() filtering.applyAllFiltersOnField(results, 'mean', applySeasonal=False, applyLowPass=apply_low_pass_filter) filtering.applyAllFiltersOnField(results, 'max', applySeasonal=False, applyLowPass=apply_low_pass_filter) filtering.applyAllFiltersOnField(results, 'min', applySeasonal=False, applyLowPass=apply_low_pass_filter) if apply_seasonal_cycle_filter and apply_low_pass_filter: try: filtering.applyFiltersOnField(results, 'meanSeasonal', applySeasonal=False, applyLowPass=True, append="LowPass") filtering.applyFiltersOnField(results, 'minSeasonal', applySeasonal=False, applyLowPass=True, append="LowPass") filtering.applyFiltersOnField(results, 'maxSeasonal', applySeasonal=False, applyLowPass=True, append="LowPass") except Exception as e: # If it doesn't work log the error but ignore it tb = traceback.format_exc() self.log.warn("Error calculating SeasonalLowPass filter:\n%s" % tb) resultsRaw.append([results, meta]) self.log.info( "LowPass filter calculation took %s for dataset %s" % (str(datetime.now() - the_time), shortName)) the_time = datetime.now() self._create_nc_file_time1d(np.array(results), 'ts.nc', 'mean', fill=-9999.) self.log.info( "NetCDF generation took %s for dataset %s" % (str(datetime.now() - the_time), shortName)) the_time = datetime.now() results = self._mergeResults(resultsRaw) if len(ds) == 2: try: stats = TimeSeriesHandlerImpl.calculate_comparison_stats(results) except Exception: stats = {} tb = traceback.format_exc() self.log.warn("Error when calculating comparison stats:\n%s" % tb) else: stats = {} meta = [] for singleRes in resultsRaw: meta.append(singleRes[1]) res = TimeSeriesResults(results=results, meta=meta, stats=stats, computeOptions=None, minLat=bounding_polygon.bounds[1], maxLat=bounding_polygon.bounds[3], minLon=bounding_polygon.bounds[0], maxLon=bounding_polygon.bounds[2], ds=ds, startTime=start_seconds_from_epoch, endTime=end_seconds_from_epoch) self.log.info("Merging results and calculating comparisons took %s" % (str(datetime.now() - the_time))) return res @lru_cache() def calculate_monthly_average(self, month=None, bounding_polygon_wkt=None, ds=None): min_date, max_date = self.get_min_max_date(ds=ds) monthly_averages, monthly_counts = [], [] monthly_mins, monthly_maxes = [], [] bounding_polygon = shapely.wkt.loads(bounding_polygon_wkt) for year in range(min_date.year, max_date.year + 1): beginning_of_month = datetime(year, month, 1) end_of_month = datetime(year, month, calendar.monthrange(year, month)[1], 23, 59, 59) start = (pytz.UTC.localize(beginning_of_month) - EPOCH).total_seconds() end = (pytz.UTC.localize(end_of_month) - EPOCH).total_seconds() tile_stats = self._tile_service.find_tiles_in_polygon(bounding_polygon, ds, start, end, fl=('id,' 'tile_avg_val_d,tile_count_i,' 'tile_min_val_d,tile_max_val_d,' 'tile_min_lat,tile_max_lat,' 'tile_min_lon,tile_max_lon'), fetch_data=False) if len(tile_stats) == 0: continue # Split list into tiles on the border of the bounding box and tiles completely inside the bounding box. border_tiles, inner_tiles = [], [] for tile in tile_stats: inner_tiles.append(tile) if bounding_polygon.contains(shapely.geometry.box(tile.bbox.min_lon, tile.bbox.min_lat, tile.bbox.max_lon, tile.bbox.max_lat)) else border_tiles.append( tile) # We can use the stats of the inner tiles directly tile_means = [tile.tile_stats.mean for tile in inner_tiles] tile_mins = [tile.tile_stats.min for tile in inner_tiles] tile_maxes = [tile.tile_stats.max for tile in inner_tiles] tile_counts = [tile.tile_stats.count for tile in inner_tiles] # Border tiles need have the data loaded, masked, and stats recalculated border_tiles = list(self._tile_service.fetch_data_for_tiles(*border_tiles)) border_tiles = self._tile_service.mask_tiles_to_polygon(bounding_polygon, border_tiles) for tile in border_tiles: tile.update_stats() tile_means.append(tile.tile_stats.mean) tile_mins.append(tile.tile_stats.min) tile_maxes.append(tile.tile_stats.max) tile_counts.append(tile.tile_stats.count) tile_means = np.array(tile_means) tile_mins = np.array(tile_mins) tile_maxes = np.array(tile_maxes) tile_counts = np.array(tile_counts) sum_tile_counts = np.sum(tile_counts) * 1.0 monthly_averages += [np.average(tile_means, None, tile_counts / sum_tile_counts).item()] monthly_mins += [np.average(tile_mins, None, tile_counts / sum_tile_counts).item()] monthly_maxes += [np.average(tile_maxes, None, tile_counts / sum_tile_counts).item()] monthly_counts += [sum_tile_counts] count_sum = np.sum(monthly_counts) * 1.0 weights = np.array(monthly_counts) / count_sum return np.average(monthly_averages, None, weights).item(), \ np.average(monthly_averages, None, weights).item(), \ np.average(monthly_averages, None, weights).item() @lru_cache() def get_min_max_date(self, ds=None): min_date = pytz.timezone('UTC').localize( datetime.utcfromtimestamp(self._tile_service.get_min_time([], ds=ds))) max_date = pytz.timezone('UTC').localize( datetime.utcfromtimestamp(self._tile_service.get_max_time([], ds=ds))) return min_date.date(), max_date.date() @staticmethod def calculate_comparison_stats(results): xy = [[], []] for item in results: if len(item) == 2: xy[item[0]["ds"]].append(item[0]["mean"]) xy[item[1]["ds"]].append(item[1]["mean"]) slope, intercept, r_value, p_value, std_err = stats.linregress(xy[0], xy[1]) comparisonStats = { "slope": slope, "intercept": intercept, "r": r_value, "p": p_value, "err": std_err } return comparisonStats class TimeSeriesResults(NexusResults): LINE_PLOT = "line" SCATTER_PLOT = "scatter" __SERIES_COLORS = ['red', 'blue'] def toImage(self): type = self.computeOptions().get_plot_type() if type == TimeSeriesResults.LINE_PLOT or type == "default": return self.createLinePlot() elif type == TimeSeriesResults.SCATTER_PLOT: return self.createScatterPlot() else: raise Exception("Invalid or unsupported time series plot specified") def createScatterPlot(self): timeSeries = [] series0 = [] series1 = [] res = self.results() meta = self.meta() plotSeries = self.computeOptions().get_plot_series() if self.computeOptions is not None else None if plotSeries is None: plotSeries = "mean" for m in res: if len(m) == 2: timeSeries.append(datetime.fromtimestamp(m[0]["time"] / 1000)) series0.append(m[0][plotSeries]) series1.append(m[1][plotSeries]) title = ', '.join(set([m['title'] for m in meta])) sources = ', '.join(set([m['source'] for m in meta])) dateRange = "%s - %s" % (timeSeries[0].strftime('%b %Y'), timeSeries[-1].strftime('%b %Y')) fig, ax = plt.subplots() fig.set_size_inches(11.0, 8.5) ax.scatter(series0, series1, alpha=0.5) ax.set_xlabel(meta[0]['units']) ax.set_ylabel(meta[1]['units']) ax.set_title("%s\n%s\n%s" % (title, sources, dateRange)) par = np.polyfit(series0, series1, 1, full=True) slope = par[0][0] intercept = par[0][1] xl = [min(series0), max(series0)] yl = [slope * xx + intercept for xx in xl] plt.plot(xl, yl, '-r') # r = self.stats()["r"] # plt.text(0.5, 0.5, "r = foo") ax.grid(True) fig.tight_layout() sio = StringIO() plt.savefig(sio, format='png') return sio.getvalue() def createLinePlot(self): nseries = len(self.meta()) res = self.results() meta = self.meta() timeSeries = [datetime.fromtimestamp(m[0]["time"] / 1000) for m in res] means = [[np.nan] * len(res) for n in range(0, nseries)] plotSeries = self.computeOptions().get_plot_series() if self.computeOptions is not None else None if plotSeries is None: plotSeries = "mean" for n in range(0, len(res)): timeSlot = res[n] for seriesValues in timeSlot: means[seriesValues['ds']][n] = seriesValues[plotSeries] x = timeSeries fig, axMain = plt.subplots() fig.set_size_inches(11.0, 8.5) fig.autofmt_xdate() title = ', '.join(set([m['title'] for m in meta])) sources = ', '.join(set([m['source'] for m in meta])) dateRange = "%s - %s" % (timeSeries[0].strftime('%b %Y'), timeSeries[-1].strftime('%b %Y')) axMain.set_title("%s\n%s\n%s" % (title, sources, dateRange)) axMain.set_xlabel('Date') axMain.grid(True) axMain.xaxis.set_major_locator(mdates.YearLocator()) axMain.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) axMain.xaxis.set_minor_locator(mdates.MonthLocator()) axMain.format_xdata = mdates.DateFormatter('%Y-%m-%d') plots = [] for n in range(0, nseries): if n == 0: ax = axMain else: ax = ax.twinx() plots += ax.plot(x, means[n], color=self.__SERIES_COLORS[n], zorder=10, linewidth=3, label=meta[n]['title']) ax.set_ylabel(meta[n]['units']) labs = [l.get_label() for l in plots] axMain.legend(plots, labs, loc=0) sio = StringIO() plt.savefig(sio, format='png') return sio.getvalue() def spark_driver(daysinrange, bounding_polygon, ds, fill=-9999., spark_nparts=1, sc=None): nexus_tiles_spark = [(bounding_polygon.wkt, ds, list(daysinrange_part), fill) for daysinrange_part in np.array_split(daysinrange, spark_nparts)] # Launch Spark computations rdd = sc.parallelize(nexus_tiles_spark, spark_nparts) results = rdd.map(calc_average_on_day).collect() results = list(itertools.chain.from_iterable(results)) results = sorted(results, key=lambda entry: entry["time"]) return results, {} def calc_average_on_day(tile_in_spark): import shapely.wkt from datetime import datetime from pytz import timezone ISO_8601 = '%Y-%m-%dT%H:%M:%S%z' (bounding_wkt, dataset, timestamps, fill) = tile_in_spark if len(timestamps) == 0: return [] tile_service = NexusTileService() ds1_nexus_tiles = \ tile_service.get_tiles_bounded_by_polygon(shapely.wkt.loads(bounding_wkt), dataset, timestamps[0], timestamps[-1], rows=5000) tile_dict = {} for timeinseconds in timestamps: tile_dict[timeinseconds] = [] for i in range(len(ds1_nexus_tiles)): tile = ds1_nexus_tiles[i] tile_dict[tile.times[0]].append(i) stats_arr = [] for timeinseconds in timestamps: cur_tile_list = tile_dict[timeinseconds] if len(cur_tile_list) == 0: continue tile_data_agg = \ np.ma.array(data=np.hstack([ds1_nexus_tiles[i].data.data.flatten() for i in cur_tile_list if (ds1_nexus_tiles[i].times[0] == timeinseconds)]), mask=np.hstack([ds1_nexus_tiles[i].data.mask.flatten() for i in cur_tile_list if (ds1_nexus_tiles[i].times[0] == timeinseconds)])) lats_agg = np.hstack([np.repeat(ds1_nexus_tiles[i].latitudes, len(ds1_nexus_tiles[i].longitudes)) for i in cur_tile_list if (ds1_nexus_tiles[i].times[0] == timeinseconds)]) if (len(tile_data_agg) == 0) or tile_data_agg.mask.all(): continue else: data_min = np.ma.min(tile_data_agg) data_max = np.ma.max(tile_data_agg) daily_mean = \ np.ma.average(tile_data_agg, weights=np.cos(np.radians(lats_agg))).item() data_count = np.ma.count(tile_data_agg) data_std = np.ma.std(tile_data_agg) # Return Stats by day stat = { 'min': data_min, 'max': data_max, 'mean': daily_mean, 'cnt': data_count, 'std': data_std, 'time': int(timeinseconds), 'iso_time': datetime.utcfromtimestamp(int(timeinseconds)).replace(tzinfo=timezone('UTC')).strftime(ISO_8601) } stats_arr.append(stat) return stats_arr
43.965035
180
0.562589
4a102b1ac6c5d339c6ed016a53f757c9e9d82a9b
309
py
Python
italian_csv_type_prediction/features/feature.py
LucaCappelletti94/italian_csv_type_prediction
a6332c4fd5b29d3b52e9b940fe964c9fffa2b3b4
[ "MIT" ]
null
null
null
italian_csv_type_prediction/features/feature.py
LucaCappelletti94/italian_csv_type_prediction
a6332c4fd5b29d3b52e9b940fe964c9fffa2b3b4
[ "MIT" ]
1
2021-02-24T11:01:06.000Z
2021-02-24T11:01:06.000Z
italian_csv_type_prediction/features/feature.py
LucaCappelletti94/italian_csv_type_prediction
a6332c4fd5b29d3b52e9b940fe964c9fffa2b3b4
[ "MIT" ]
null
null
null
class Feature: """A text related feature.""" @property def name(self): """Return type identified by this predictor.""" return self.__class__.__name__[:-4] def score(self, value)->float: raise NotImplementedError("This method must be implemented in children classes.")
30.9
89
0.656958
4a102ce9001a95136a4bbcc87204cf7de7bed6bd
1,845
py
Python
pdx-base/usr/share/pdx/python/pdx-poweroff.py
hoopsurfer/pdxnew
8fd71916b6fbf1f020c409a206e34573784e528f
[ "Apache-2.0" ]
10
2020-01-29T16:11:30.000Z
2021-05-29T11:43:57.000Z
pdx-base/usr/share/pdx/python/pdx-poweroff.py
hoopsurfer/pdxnew
8fd71916b6fbf1f020c409a206e34573784e528f
[ "Apache-2.0" ]
2
2020-02-02T08:59:35.000Z
2020-09-12T20:42:06.000Z
pdx-base/usr/share/pdx/python/pdx-poweroff.py
hoopsurfer/pdxnew
8fd71916b6fbf1f020c409a206e34573784e528f
[ "Apache-2.0" ]
4
2020-02-13T21:15:55.000Z
2020-05-07T15:33:21.000Z
#!/user/bin/env python # pdx-poweroff.py - oneshot service so do your thing and exit # # We are in poweroff processing because shutdown has started for whatever reason. # This code can do any needed poweroff specific processing for power management. # The critical activity is a long press of the power button through GPIO18 # import RPi.GPIO as GPIO import time,os,sys print('pdx: poweroff service - service initializing') GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # Use traditional pin numbering GPIO.setup(17, GPIO.OUT) # Pi to Power MCU system active GPIO.setup(18, GPIO.OUT) # Pi to Power MCU soft button press GPIO.setup(4, GPIO.IN) # Power MCU to Pi on power button # disable the power button if it has not already been pressed if GPIO.input(4): # Power button was pressed and we can tell print('pdx: poweroff service - power button press detected') # poweroff initiated enable power control GPIO.output(17, GPIO.HIGH) # enable power control print('pdx: poweroff service - power control enabled') print('pdx: poweroff service - long press power button') GPIO.output(18, GPIO.HIGH) # long press soft power button time.sleep(3) # poweroff GPIO.output(18, GPIO.LOW) # release soft power button # wait for shutdown processing to take place time.sleep(3) # processing # poweroff initiated disable power control GPIO.output(17, GPIO.LOW) # disable power control print('pdx: poweroff service - power control disabled') # unmount SD card to clean up logs #print("pdx: poweroff service - unmounting SD card") #os.system("umount /dev/mmcblk0p1") # stash the current system clock setting into the RTC hardware #print("pdx: poweroff service - saving system clock to hardware clock") #os.system("/sbin/hwclock --systohc") GPIO.cleanup() print('pdx: poweroff service - service complete') sys.exit()
34.811321
81
0.746883
4a102d0cc2ac15e2bcd2c2bf8fcc400a592cc288
111,365
py
Python
tests/cache/tests.py
danhayden/django
49b470b9187b6be60e573fed08c8f4a87f133750
[ "BSD-3-Clause", "0BSD" ]
2
2021-12-17T07:27:44.000Z
2021-12-17T19:16:52.000Z
tests/cache/tests.py
danhayden/django
49b470b9187b6be60e573fed08c8f4a87f133750
[ "BSD-3-Clause", "0BSD" ]
6
2022-01-13T17:38:02.000Z
2022-03-15T15:24:12.000Z
tests/cache/tests.py
danhayden/django
49b470b9187b6be60e573fed08c8f4a87f133750
[ "BSD-3-Clause", "0BSD" ]
2
2020-01-01T18:36:17.000Z
2022-02-21T14:00:56.000Z
# Unit tests for cache framework # Uses whatever cache backend is set in the test settings file. import copy import io import os import pickle import re import shutil import sys import tempfile import threading import time import unittest from pathlib import Path from unittest import mock, skipIf from django.conf import settings from django.core import management, signals from django.core.cache import ( DEFAULT_CACHE_ALIAS, CacheHandler, CacheKeyWarning, InvalidCacheKey, cache, caches, ) from django.core.cache.backends.base import InvalidCacheBackendError from django.core.cache.backends.redis import RedisCacheClient from django.core.cache.utils import make_template_fragment_key from django.db import close_old_connections, connection, connections from django.db.backends.utils import CursorWrapper from django.http import ( HttpRequest, HttpResponse, HttpResponseNotModified, StreamingHttpResponse, ) from django.middleware.cache import ( CacheMiddleware, FetchFromCacheMiddleware, UpdateCacheMiddleware, ) from django.middleware.csrf import CsrfViewMiddleware from django.template import engines from django.template.context_processors import csrf from django.template.response import TemplateResponse from django.test import ( RequestFactory, SimpleTestCase, TestCase, TransactionTestCase, override_settings, ) from django.test.signals import setting_changed from django.test.utils import CaptureQueriesContext from django.utils import timezone, translation from django.utils.cache import ( get_cache_key, learn_cache_key, patch_cache_control, patch_vary_headers, ) from django.views.decorators.cache import cache_control, cache_page from .models import Poll, expensive_calculation # functions/classes for complex data type tests def f(): return 42 class C: def m(n): return 24 class Unpicklable: def __getstate__(self): raise pickle.PickleError() def empty_response(request): return HttpResponse() KEY_ERRORS_WITH_MEMCACHED_MSG = ( "Cache key contains characters that will cause errors if used with memcached: %r" ) @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", } } ) class DummyCacheTests(SimpleTestCase): # The Dummy cache backend doesn't really behave like a test backend, # so it has its own test case. def test_simple(self): "Dummy cache backend ignores cache set calls" cache.set("key", "value") self.assertIsNone(cache.get("key")) def test_add(self): "Add doesn't do anything in dummy cache backend" self.assertIs(cache.add("addkey1", "value"), True) self.assertIs(cache.add("addkey1", "newvalue"), True) self.assertIsNone(cache.get("addkey1")) def test_non_existent(self): "Nonexistent keys aren't found in the dummy cache backend" self.assertIsNone(cache.get("does_not_exist")) self.assertEqual(cache.get("does_not_exist", "bang!"), "bang!") def test_get_many(self): "get_many returns nothing for the dummy cache backend" cache.set_many({"a": "a", "b": "b", "c": "c", "d": "d"}) self.assertEqual(cache.get_many(["a", "c", "d"]), {}) self.assertEqual(cache.get_many(["a", "b", "e"]), {}) def test_get_many_invalid_key(self): msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces" with self.assertWarnsMessage(CacheKeyWarning, msg): cache.get_many(["key with spaces"]) def test_delete(self): "Cache deletion is transparently ignored on the dummy cache backend" cache.set_many({"key1": "spam", "key2": "eggs"}) self.assertIsNone(cache.get("key1")) self.assertIs(cache.delete("key1"), False) self.assertIsNone(cache.get("key1")) self.assertIsNone(cache.get("key2")) def test_has_key(self): "The has_key method doesn't ever return True for the dummy cache backend" cache.set("hello1", "goodbye1") self.assertIs(cache.has_key("hello1"), False) self.assertIs(cache.has_key("goodbye1"), False) def test_in(self): "The in operator doesn't ever return True for the dummy cache backend" cache.set("hello2", "goodbye2") self.assertNotIn("hello2", cache) self.assertNotIn("goodbye2", cache) def test_incr(self): "Dummy cache values can't be incremented" cache.set("answer", 42) with self.assertRaises(ValueError): cache.incr("answer") with self.assertRaises(ValueError): cache.incr("does_not_exist") with self.assertRaises(ValueError): cache.incr("does_not_exist", -1) def test_decr(self): "Dummy cache values can't be decremented" cache.set("answer", 42) with self.assertRaises(ValueError): cache.decr("answer") with self.assertRaises(ValueError): cache.decr("does_not_exist") with self.assertRaises(ValueError): cache.decr("does_not_exist", -1) def test_touch(self): """Dummy cache can't do touch().""" self.assertIs(cache.touch("whatever"), False) def test_data_types(self): "All data types are ignored equally by the dummy cache" tests = { "string": "this is a string", "int": 42, "bool": True, "list": [1, 2, 3, 4], "tuple": (1, 2, 3, 4), "dict": {"A": 1, "B": 2}, "function": f, "class": C, } for key, value in tests.items(): with self.subTest(key=key): cache.set(key, value) self.assertIsNone(cache.get(key)) def test_expiration(self): "Expiration has no effect on the dummy cache" cache.set("expire1", "very quickly", 1) cache.set("expire2", "very quickly", 1) cache.set("expire3", "very quickly", 1) time.sleep(2) self.assertIsNone(cache.get("expire1")) self.assertIs(cache.add("expire2", "newvalue"), True) self.assertIsNone(cache.get("expire2")) self.assertIs(cache.has_key("expire3"), False) def test_unicode(self): "Unicode values are ignored by the dummy cache" stuff = { "ascii": "ascii_value", "unicode_ascii": "Iñtërnâtiônàlizætiøn1", "Iñtërnâtiônàlizætiøn": "Iñtërnâtiônàlizætiøn2", "ascii2": {"x": 1}, } for (key, value) in stuff.items(): with self.subTest(key=key): cache.set(key, value) self.assertIsNone(cache.get(key)) def test_set_many(self): "set_many does nothing for the dummy cache backend" self.assertEqual(cache.set_many({"a": 1, "b": 2}), []) self.assertEqual(cache.set_many({"a": 1, "b": 2}, timeout=2, version="1"), []) def test_set_many_invalid_key(self): msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces" with self.assertWarnsMessage(CacheKeyWarning, msg): cache.set_many({"key with spaces": "foo"}) def test_delete_many(self): "delete_many does nothing for the dummy cache backend" cache.delete_many(["a", "b"]) def test_delete_many_invalid_key(self): msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces" with self.assertWarnsMessage(CacheKeyWarning, msg): cache.delete_many(["key with spaces"]) def test_clear(self): "clear does nothing for the dummy cache backend" cache.clear() def test_incr_version(self): "Dummy cache versions can't be incremented" cache.set("answer", 42) with self.assertRaises(ValueError): cache.incr_version("answer") with self.assertRaises(ValueError): cache.incr_version("does_not_exist") def test_decr_version(self): "Dummy cache versions can't be decremented" cache.set("answer", 42) with self.assertRaises(ValueError): cache.decr_version("answer") with self.assertRaises(ValueError): cache.decr_version("does_not_exist") def test_get_or_set(self): self.assertEqual(cache.get_or_set("mykey", "default"), "default") self.assertIsNone(cache.get_or_set("mykey", None)) def test_get_or_set_callable(self): def my_callable(): return "default" self.assertEqual(cache.get_or_set("mykey", my_callable), "default") self.assertEqual(cache.get_or_set("mykey", my_callable()), "default") def custom_key_func(key, key_prefix, version): "A customized cache key function" return "CUSTOM-" + "-".join([key_prefix, str(version), key]) _caches_setting_base = { "default": {}, "prefix": {"KEY_PREFIX": "cacheprefix{}".format(os.getpid())}, "v2": {"VERSION": 2}, "custom_key": {"KEY_FUNCTION": custom_key_func}, "custom_key2": {"KEY_FUNCTION": "cache.tests.custom_key_func"}, "cull": {"OPTIONS": {"MAX_ENTRIES": 30}}, "zero_cull": {"OPTIONS": {"CULL_FREQUENCY": 0, "MAX_ENTRIES": 30}}, } def caches_setting_for_tests(base=None, exclude=None, **params): # `base` is used to pull in the memcached config from the original settings, # `exclude` is a set of cache names denoting which `_caches_setting_base` keys # should be omitted. # `params` are test specific overrides and `_caches_settings_base` is the # base config for the tests. # This results in the following search order: # params -> _caches_setting_base -> base base = base or {} exclude = exclude or set() setting = {k: base.copy() for k in _caches_setting_base if k not in exclude} for key, cache_params in setting.items(): cache_params.update(_caches_setting_base[key]) cache_params.update(params) return setting class BaseCacheTests: # A common set of tests to apply to all cache backends factory = RequestFactory() # Some clients raise custom exceptions when .incr() or .decr() are called # with a non-integer value. incr_decr_type_error = TypeError def tearDown(self): cache.clear() def test_simple(self): # Simple cache set/get works cache.set("key", "value") self.assertEqual(cache.get("key"), "value") def test_default_used_when_none_is_set(self): """If None is cached, get() returns it instead of the default.""" cache.set("key_default_none", None) self.assertIsNone(cache.get("key_default_none", default="default")) def test_add(self): # A key can be added to a cache self.assertIs(cache.add("addkey1", "value"), True) self.assertIs(cache.add("addkey1", "newvalue"), False) self.assertEqual(cache.get("addkey1"), "value") def test_prefix(self): # Test for same cache key conflicts between shared backend cache.set("somekey", "value") # should not be set in the prefixed cache self.assertIs(caches["prefix"].has_key("somekey"), False) caches["prefix"].set("somekey", "value2") self.assertEqual(cache.get("somekey"), "value") self.assertEqual(caches["prefix"].get("somekey"), "value2") def test_non_existent(self): """Nonexistent cache keys return as None/default.""" self.assertIsNone(cache.get("does_not_exist")) self.assertEqual(cache.get("does_not_exist", "bang!"), "bang!") def test_get_many(self): # Multiple cache keys can be returned using get_many cache.set_many({"a": "a", "b": "b", "c": "c", "d": "d"}) self.assertEqual( cache.get_many(["a", "c", "d"]), {"a": "a", "c": "c", "d": "d"} ) self.assertEqual(cache.get_many(["a", "b", "e"]), {"a": "a", "b": "b"}) self.assertEqual(cache.get_many(iter(["a", "b", "e"])), {"a": "a", "b": "b"}) cache.set_many({"x": None, "y": 1}) self.assertEqual(cache.get_many(["x", "y"]), {"x": None, "y": 1}) def test_delete(self): # Cache keys can be deleted cache.set_many({"key1": "spam", "key2": "eggs"}) self.assertEqual(cache.get("key1"), "spam") self.assertIs(cache.delete("key1"), True) self.assertIsNone(cache.get("key1")) self.assertEqual(cache.get("key2"), "eggs") def test_delete_nonexistent(self): self.assertIs(cache.delete("nonexistent_key"), False) def test_has_key(self): # The cache can be inspected for cache keys cache.set("hello1", "goodbye1") self.assertIs(cache.has_key("hello1"), True) self.assertIs(cache.has_key("goodbye1"), False) cache.set("no_expiry", "here", None) self.assertIs(cache.has_key("no_expiry"), True) cache.set("null", None) self.assertIs(cache.has_key("null"), True) def test_in(self): # The in operator can be used to inspect cache contents cache.set("hello2", "goodbye2") self.assertIn("hello2", cache) self.assertNotIn("goodbye2", cache) cache.set("null", None) self.assertIn("null", cache) def test_incr(self): # Cache values can be incremented cache.set("answer", 41) self.assertEqual(cache.incr("answer"), 42) self.assertEqual(cache.get("answer"), 42) self.assertEqual(cache.incr("answer", 10), 52) self.assertEqual(cache.get("answer"), 52) self.assertEqual(cache.incr("answer", -10), 42) with self.assertRaises(ValueError): cache.incr("does_not_exist") with self.assertRaises(ValueError): cache.incr("does_not_exist", -1) cache.set("null", None) with self.assertRaises(self.incr_decr_type_error): cache.incr("null") def test_decr(self): # Cache values can be decremented cache.set("answer", 43) self.assertEqual(cache.decr("answer"), 42) self.assertEqual(cache.get("answer"), 42) self.assertEqual(cache.decr("answer", 10), 32) self.assertEqual(cache.get("answer"), 32) self.assertEqual(cache.decr("answer", -10), 42) with self.assertRaises(ValueError): cache.decr("does_not_exist") with self.assertRaises(ValueError): cache.incr("does_not_exist", -1) cache.set("null", None) with self.assertRaises(self.incr_decr_type_error): cache.decr("null") def test_close(self): self.assertTrue(hasattr(cache, "close")) cache.close() def test_data_types(self): # Many different data types can be cached tests = { "string": "this is a string", "int": 42, "bool": True, "list": [1, 2, 3, 4], "tuple": (1, 2, 3, 4), "dict": {"A": 1, "B": 2}, "function": f, "class": C, } for key, value in tests.items(): with self.subTest(key=key): cache.set(key, value) self.assertEqual(cache.get(key), value) def test_cache_read_for_model_instance(self): # Don't want fields with callable as default to be called on cache read expensive_calculation.num_runs = 0 Poll.objects.all().delete() my_poll = Poll.objects.create(question="Well?") self.assertEqual(Poll.objects.count(), 1) pub_date = my_poll.pub_date cache.set("question", my_poll) cached_poll = cache.get("question") self.assertEqual(cached_poll.pub_date, pub_date) # We only want the default expensive calculation run once self.assertEqual(expensive_calculation.num_runs, 1) def test_cache_write_for_model_instance_with_deferred(self): # Don't want fields with callable as default to be called on cache write expensive_calculation.num_runs = 0 Poll.objects.all().delete() Poll.objects.create(question="What?") self.assertEqual(expensive_calculation.num_runs, 1) defer_qs = Poll.objects.defer("question") self.assertEqual(defer_qs.count(), 1) self.assertEqual(expensive_calculation.num_runs, 1) cache.set("deferred_queryset", defer_qs) # cache set should not re-evaluate default functions self.assertEqual(expensive_calculation.num_runs, 1) def test_cache_read_for_model_instance_with_deferred(self): # Don't want fields with callable as default to be called on cache read expensive_calculation.num_runs = 0 Poll.objects.all().delete() Poll.objects.create(question="What?") self.assertEqual(expensive_calculation.num_runs, 1) defer_qs = Poll.objects.defer("question") self.assertEqual(defer_qs.count(), 1) cache.set("deferred_queryset", defer_qs) self.assertEqual(expensive_calculation.num_runs, 1) runs_before_cache_read = expensive_calculation.num_runs cache.get("deferred_queryset") # We only want the default expensive calculation run on creation and set self.assertEqual(expensive_calculation.num_runs, runs_before_cache_read) def test_expiration(self): # Cache values can be set to expire cache.set("expire1", "very quickly", 1) cache.set("expire2", "very quickly", 1) cache.set("expire3", "very quickly", 1) time.sleep(2) self.assertIsNone(cache.get("expire1")) self.assertIs(cache.add("expire2", "newvalue"), True) self.assertEqual(cache.get("expire2"), "newvalue") self.assertIs(cache.has_key("expire3"), False) def test_touch(self): # cache.touch() updates the timeout. cache.set("expire1", "very quickly", timeout=1) self.assertIs(cache.touch("expire1", timeout=4), True) time.sleep(2) self.assertIs(cache.has_key("expire1"), True) time.sleep(3) self.assertIs(cache.has_key("expire1"), False) # cache.touch() works without the timeout argument. cache.set("expire1", "very quickly", timeout=1) self.assertIs(cache.touch("expire1"), True) time.sleep(2) self.assertIs(cache.has_key("expire1"), True) self.assertIs(cache.touch("nonexistent"), False) def test_unicode(self): # Unicode values can be cached stuff = { "ascii": "ascii_value", "unicode_ascii": "Iñtërnâtiônàlizætiøn1", "Iñtërnâtiônàlizætiøn": "Iñtërnâtiônàlizætiøn2", "ascii2": {"x": 1}, } # Test `set` for (key, value) in stuff.items(): with self.subTest(key=key): cache.set(key, value) self.assertEqual(cache.get(key), value) # Test `add` for (key, value) in stuff.items(): with self.subTest(key=key): self.assertIs(cache.delete(key), True) self.assertIs(cache.add(key, value), True) self.assertEqual(cache.get(key), value) # Test `set_many` for (key, value) in stuff.items(): self.assertIs(cache.delete(key), True) cache.set_many(stuff) for (key, value) in stuff.items(): with self.subTest(key=key): self.assertEqual(cache.get(key), value) def test_binary_string(self): # Binary strings should be cacheable from zlib import compress, decompress value = "value_to_be_compressed" compressed_value = compress(value.encode()) # Test set cache.set("binary1", compressed_value) compressed_result = cache.get("binary1") self.assertEqual(compressed_value, compressed_result) self.assertEqual(value, decompress(compressed_result).decode()) # Test add self.assertIs(cache.add("binary1-add", compressed_value), True) compressed_result = cache.get("binary1-add") self.assertEqual(compressed_value, compressed_result) self.assertEqual(value, decompress(compressed_result).decode()) # Test set_many cache.set_many({"binary1-set_many": compressed_value}) compressed_result = cache.get("binary1-set_many") self.assertEqual(compressed_value, compressed_result) self.assertEqual(value, decompress(compressed_result).decode()) def test_set_many(self): # Multiple keys can be set using set_many cache.set_many({"key1": "spam", "key2": "eggs"}) self.assertEqual(cache.get("key1"), "spam") self.assertEqual(cache.get("key2"), "eggs") def test_set_many_returns_empty_list_on_success(self): """set_many() returns an empty list when all keys are inserted.""" failing_keys = cache.set_many({"key1": "spam", "key2": "eggs"}) self.assertEqual(failing_keys, []) def test_set_many_expiration(self): # set_many takes a second ``timeout`` parameter cache.set_many({"key1": "spam", "key2": "eggs"}, 1) time.sleep(2) self.assertIsNone(cache.get("key1")) self.assertIsNone(cache.get("key2")) def test_delete_many(self): # Multiple keys can be deleted using delete_many cache.set_many({"key1": "spam", "key2": "eggs", "key3": "ham"}) cache.delete_many(["key1", "key2"]) self.assertIsNone(cache.get("key1")) self.assertIsNone(cache.get("key2")) self.assertEqual(cache.get("key3"), "ham") def test_clear(self): # The cache can be emptied using clear cache.set_many({"key1": "spam", "key2": "eggs"}) cache.clear() self.assertIsNone(cache.get("key1")) self.assertIsNone(cache.get("key2")) def test_long_timeout(self): """ Follow memcached's convention where a timeout greater than 30 days is treated as an absolute expiration timestamp instead of a relative offset (#12399). """ cache.set("key1", "eggs", 60 * 60 * 24 * 30 + 1) # 30 days + 1 second self.assertEqual(cache.get("key1"), "eggs") self.assertIs(cache.add("key2", "ham", 60 * 60 * 24 * 30 + 1), True) self.assertEqual(cache.get("key2"), "ham") cache.set_many( {"key3": "sausage", "key4": "lobster bisque"}, 60 * 60 * 24 * 30 + 1 ) self.assertEqual(cache.get("key3"), "sausage") self.assertEqual(cache.get("key4"), "lobster bisque") def test_forever_timeout(self): """ Passing in None into timeout results in a value that is cached forever """ cache.set("key1", "eggs", None) self.assertEqual(cache.get("key1"), "eggs") self.assertIs(cache.add("key2", "ham", None), True) self.assertEqual(cache.get("key2"), "ham") self.assertIs(cache.add("key1", "new eggs", None), False) self.assertEqual(cache.get("key1"), "eggs") cache.set_many({"key3": "sausage", "key4": "lobster bisque"}, None) self.assertEqual(cache.get("key3"), "sausage") self.assertEqual(cache.get("key4"), "lobster bisque") cache.set("key5", "belgian fries", timeout=1) self.assertIs(cache.touch("key5", timeout=None), True) time.sleep(2) self.assertEqual(cache.get("key5"), "belgian fries") def test_zero_timeout(self): """ Passing in zero into timeout results in a value that is not cached """ cache.set("key1", "eggs", 0) self.assertIsNone(cache.get("key1")) self.assertIs(cache.add("key2", "ham", 0), True) self.assertIsNone(cache.get("key2")) cache.set_many({"key3": "sausage", "key4": "lobster bisque"}, 0) self.assertIsNone(cache.get("key3")) self.assertIsNone(cache.get("key4")) cache.set("key5", "belgian fries", timeout=5) self.assertIs(cache.touch("key5", timeout=0), True) self.assertIsNone(cache.get("key5")) def test_float_timeout(self): # Make sure a timeout given as a float doesn't crash anything. cache.set("key1", "spam", 100.2) self.assertEqual(cache.get("key1"), "spam") def _perform_cull_test(self, cull_cache_name, initial_count, final_count): try: cull_cache = caches[cull_cache_name] except InvalidCacheBackendError: self.skipTest("Culling isn't implemented.") # Create initial cache key entries. This will overflow the cache, # causing a cull. for i in range(1, initial_count): cull_cache.set("cull%d" % i, "value", 1000) count = 0 # Count how many keys are left in the cache. for i in range(1, initial_count): if cull_cache.has_key("cull%d" % i): count += 1 self.assertEqual(count, final_count) def test_cull(self): self._perform_cull_test("cull", 50, 29) def test_zero_cull(self): self._perform_cull_test("zero_cull", 50, 19) def test_cull_delete_when_store_empty(self): try: cull_cache = caches["cull"] except InvalidCacheBackendError: self.skipTest("Culling isn't implemented.") old_max_entries = cull_cache._max_entries # Force _cull to delete on first cached record. cull_cache._max_entries = -1 try: cull_cache.set("force_cull_delete", "value", 1000) self.assertIs(cull_cache.has_key("force_cull_delete"), True) finally: cull_cache._max_entries = old_max_entries def _perform_invalid_key_test(self, key, expected_warning, key_func=None): """ All the builtin backends should warn (except memcached that should error) on keys that would be refused by memcached. This encourages portable caching code without making it too difficult to use production backends with more liberal key rules. Refs #6447. """ # mimic custom ``make_key`` method being defined since the default will # never show the below warnings def func(key, *args): return key old_func = cache.key_func cache.key_func = key_func or func tests = [ ("add", [key, 1]), ("get", [key]), ("set", [key, 1]), ("incr", [key]), ("decr", [key]), ("touch", [key]), ("delete", [key]), ("get_many", [[key, "b"]]), ("set_many", [{key: 1, "b": 2}]), ("delete_many", [[key, "b"]]), ] try: for operation, args in tests: with self.subTest(operation=operation): with self.assertWarns(CacheKeyWarning) as cm: getattr(cache, operation)(*args) self.assertEqual(str(cm.warning), expected_warning) finally: cache.key_func = old_func def test_invalid_key_characters(self): # memcached doesn't allow whitespace or control characters in keys. key = "key with spaces and 清" self._perform_invalid_key_test(key, KEY_ERRORS_WITH_MEMCACHED_MSG % key) def test_invalid_key_length(self): # memcached limits key length to 250. key = ("a" * 250) + "清" expected_warning = ( "Cache key will cause errors if used with memcached: " "%r (longer than %s)" % (key, 250) ) self._perform_invalid_key_test(key, expected_warning) def test_invalid_with_version_key_length(self): # Custom make_key() that adds a version to the key and exceeds the # limit. def key_func(key, *args): return key + ":1" key = "a" * 249 expected_warning = ( "Cache key will cause errors if used with memcached: " "%r (longer than %s)" % (key_func(key), 250) ) self._perform_invalid_key_test(key, expected_warning, key_func=key_func) def test_cache_versioning_get_set(self): # set, using default version = 1 cache.set("answer1", 42) self.assertEqual(cache.get("answer1"), 42) self.assertEqual(cache.get("answer1", version=1), 42) self.assertIsNone(cache.get("answer1", version=2)) self.assertIsNone(caches["v2"].get("answer1")) self.assertEqual(caches["v2"].get("answer1", version=1), 42) self.assertIsNone(caches["v2"].get("answer1", version=2)) # set, default version = 1, but manually override version = 2 cache.set("answer2", 42, version=2) self.assertIsNone(cache.get("answer2")) self.assertIsNone(cache.get("answer2", version=1)) self.assertEqual(cache.get("answer2", version=2), 42) self.assertEqual(caches["v2"].get("answer2"), 42) self.assertIsNone(caches["v2"].get("answer2", version=1)) self.assertEqual(caches["v2"].get("answer2", version=2), 42) # v2 set, using default version = 2 caches["v2"].set("answer3", 42) self.assertIsNone(cache.get("answer3")) self.assertIsNone(cache.get("answer3", version=1)) self.assertEqual(cache.get("answer3", version=2), 42) self.assertEqual(caches["v2"].get("answer3"), 42) self.assertIsNone(caches["v2"].get("answer3", version=1)) self.assertEqual(caches["v2"].get("answer3", version=2), 42) # v2 set, default version = 2, but manually override version = 1 caches["v2"].set("answer4", 42, version=1) self.assertEqual(cache.get("answer4"), 42) self.assertEqual(cache.get("answer4", version=1), 42) self.assertIsNone(cache.get("answer4", version=2)) self.assertIsNone(caches["v2"].get("answer4")) self.assertEqual(caches["v2"].get("answer4", version=1), 42) self.assertIsNone(caches["v2"].get("answer4", version=2)) def test_cache_versioning_add(self): # add, default version = 1, but manually override version = 2 self.assertIs(cache.add("answer1", 42, version=2), True) self.assertIsNone(cache.get("answer1", version=1)) self.assertEqual(cache.get("answer1", version=2), 42) self.assertIs(cache.add("answer1", 37, version=2), False) self.assertIsNone(cache.get("answer1", version=1)) self.assertEqual(cache.get("answer1", version=2), 42) self.assertIs(cache.add("answer1", 37, version=1), True) self.assertEqual(cache.get("answer1", version=1), 37) self.assertEqual(cache.get("answer1", version=2), 42) # v2 add, using default version = 2 self.assertIs(caches["v2"].add("answer2", 42), True) self.assertIsNone(cache.get("answer2", version=1)) self.assertEqual(cache.get("answer2", version=2), 42) self.assertIs(caches["v2"].add("answer2", 37), False) self.assertIsNone(cache.get("answer2", version=1)) self.assertEqual(cache.get("answer2", version=2), 42) self.assertIs(caches["v2"].add("answer2", 37, version=1), True) self.assertEqual(cache.get("answer2", version=1), 37) self.assertEqual(cache.get("answer2", version=2), 42) # v2 add, default version = 2, but manually override version = 1 self.assertIs(caches["v2"].add("answer3", 42, version=1), True) self.assertEqual(cache.get("answer3", version=1), 42) self.assertIsNone(cache.get("answer3", version=2)) self.assertIs(caches["v2"].add("answer3", 37, version=1), False) self.assertEqual(cache.get("answer3", version=1), 42) self.assertIsNone(cache.get("answer3", version=2)) self.assertIs(caches["v2"].add("answer3", 37), True) self.assertEqual(cache.get("answer3", version=1), 42) self.assertEqual(cache.get("answer3", version=2), 37) def test_cache_versioning_has_key(self): cache.set("answer1", 42) # has_key self.assertIs(cache.has_key("answer1"), True) self.assertIs(cache.has_key("answer1", version=1), True) self.assertIs(cache.has_key("answer1", version=2), False) self.assertIs(caches["v2"].has_key("answer1"), False) self.assertIs(caches["v2"].has_key("answer1", version=1), True) self.assertIs(caches["v2"].has_key("answer1", version=2), False) def test_cache_versioning_delete(self): cache.set("answer1", 37, version=1) cache.set("answer1", 42, version=2) self.assertIs(cache.delete("answer1"), True) self.assertIsNone(cache.get("answer1", version=1)) self.assertEqual(cache.get("answer1", version=2), 42) cache.set("answer2", 37, version=1) cache.set("answer2", 42, version=2) self.assertIs(cache.delete("answer2", version=2), True) self.assertEqual(cache.get("answer2", version=1), 37) self.assertIsNone(cache.get("answer2", version=2)) cache.set("answer3", 37, version=1) cache.set("answer3", 42, version=2) self.assertIs(caches["v2"].delete("answer3"), True) self.assertEqual(cache.get("answer3", version=1), 37) self.assertIsNone(cache.get("answer3", version=2)) cache.set("answer4", 37, version=1) cache.set("answer4", 42, version=2) self.assertIs(caches["v2"].delete("answer4", version=1), True) self.assertIsNone(cache.get("answer4", version=1)) self.assertEqual(cache.get("answer4", version=2), 42) def test_cache_versioning_incr_decr(self): cache.set("answer1", 37, version=1) cache.set("answer1", 42, version=2) self.assertEqual(cache.incr("answer1"), 38) self.assertEqual(cache.get("answer1", version=1), 38) self.assertEqual(cache.get("answer1", version=2), 42) self.assertEqual(cache.decr("answer1"), 37) self.assertEqual(cache.get("answer1", version=1), 37) self.assertEqual(cache.get("answer1", version=2), 42) cache.set("answer2", 37, version=1) cache.set("answer2", 42, version=2) self.assertEqual(cache.incr("answer2", version=2), 43) self.assertEqual(cache.get("answer2", version=1), 37) self.assertEqual(cache.get("answer2", version=2), 43) self.assertEqual(cache.decr("answer2", version=2), 42) self.assertEqual(cache.get("answer2", version=1), 37) self.assertEqual(cache.get("answer2", version=2), 42) cache.set("answer3", 37, version=1) cache.set("answer3", 42, version=2) self.assertEqual(caches["v2"].incr("answer3"), 43) self.assertEqual(cache.get("answer3", version=1), 37) self.assertEqual(cache.get("answer3", version=2), 43) self.assertEqual(caches["v2"].decr("answer3"), 42) self.assertEqual(cache.get("answer3", version=1), 37) self.assertEqual(cache.get("answer3", version=2), 42) cache.set("answer4", 37, version=1) cache.set("answer4", 42, version=2) self.assertEqual(caches["v2"].incr("answer4", version=1), 38) self.assertEqual(cache.get("answer4", version=1), 38) self.assertEqual(cache.get("answer4", version=2), 42) self.assertEqual(caches["v2"].decr("answer4", version=1), 37) self.assertEqual(cache.get("answer4", version=1), 37) self.assertEqual(cache.get("answer4", version=2), 42) def test_cache_versioning_get_set_many(self): # set, using default version = 1 cache.set_many({"ford1": 37, "arthur1": 42}) self.assertEqual( cache.get_many(["ford1", "arthur1"]), {"ford1": 37, "arthur1": 42} ) self.assertEqual( cache.get_many(["ford1", "arthur1"], version=1), {"ford1": 37, "arthur1": 42}, ) self.assertEqual(cache.get_many(["ford1", "arthur1"], version=2), {}) self.assertEqual(caches["v2"].get_many(["ford1", "arthur1"]), {}) self.assertEqual( caches["v2"].get_many(["ford1", "arthur1"], version=1), {"ford1": 37, "arthur1": 42}, ) self.assertEqual(caches["v2"].get_many(["ford1", "arthur1"], version=2), {}) # set, default version = 1, but manually override version = 2 cache.set_many({"ford2": 37, "arthur2": 42}, version=2) self.assertEqual(cache.get_many(["ford2", "arthur2"]), {}) self.assertEqual(cache.get_many(["ford2", "arthur2"], version=1), {}) self.assertEqual( cache.get_many(["ford2", "arthur2"], version=2), {"ford2": 37, "arthur2": 42}, ) self.assertEqual( caches["v2"].get_many(["ford2", "arthur2"]), {"ford2": 37, "arthur2": 42} ) self.assertEqual(caches["v2"].get_many(["ford2", "arthur2"], version=1), {}) self.assertEqual( caches["v2"].get_many(["ford2", "arthur2"], version=2), {"ford2": 37, "arthur2": 42}, ) # v2 set, using default version = 2 caches["v2"].set_many({"ford3": 37, "arthur3": 42}) self.assertEqual(cache.get_many(["ford3", "arthur3"]), {}) self.assertEqual(cache.get_many(["ford3", "arthur3"], version=1), {}) self.assertEqual( cache.get_many(["ford3", "arthur3"], version=2), {"ford3": 37, "arthur3": 42}, ) self.assertEqual( caches["v2"].get_many(["ford3", "arthur3"]), {"ford3": 37, "arthur3": 42} ) self.assertEqual(caches["v2"].get_many(["ford3", "arthur3"], version=1), {}) self.assertEqual( caches["v2"].get_many(["ford3", "arthur3"], version=2), {"ford3": 37, "arthur3": 42}, ) # v2 set, default version = 2, but manually override version = 1 caches["v2"].set_many({"ford4": 37, "arthur4": 42}, version=1) self.assertEqual( cache.get_many(["ford4", "arthur4"]), {"ford4": 37, "arthur4": 42} ) self.assertEqual( cache.get_many(["ford4", "arthur4"], version=1), {"ford4": 37, "arthur4": 42}, ) self.assertEqual(cache.get_many(["ford4", "arthur4"], version=2), {}) self.assertEqual(caches["v2"].get_many(["ford4", "arthur4"]), {}) self.assertEqual( caches["v2"].get_many(["ford4", "arthur4"], version=1), {"ford4": 37, "arthur4": 42}, ) self.assertEqual(caches["v2"].get_many(["ford4", "arthur4"], version=2), {}) def test_incr_version(self): cache.set("answer", 42, version=2) self.assertIsNone(cache.get("answer")) self.assertIsNone(cache.get("answer", version=1)) self.assertEqual(cache.get("answer", version=2), 42) self.assertIsNone(cache.get("answer", version=3)) self.assertEqual(cache.incr_version("answer", version=2), 3) self.assertIsNone(cache.get("answer")) self.assertIsNone(cache.get("answer", version=1)) self.assertIsNone(cache.get("answer", version=2)) self.assertEqual(cache.get("answer", version=3), 42) caches["v2"].set("answer2", 42) self.assertEqual(caches["v2"].get("answer2"), 42) self.assertIsNone(caches["v2"].get("answer2", version=1)) self.assertEqual(caches["v2"].get("answer2", version=2), 42) self.assertIsNone(caches["v2"].get("answer2", version=3)) self.assertEqual(caches["v2"].incr_version("answer2"), 3) self.assertIsNone(caches["v2"].get("answer2")) self.assertIsNone(caches["v2"].get("answer2", version=1)) self.assertIsNone(caches["v2"].get("answer2", version=2)) self.assertEqual(caches["v2"].get("answer2", version=3), 42) with self.assertRaises(ValueError): cache.incr_version("does_not_exist") cache.set("null", None) self.assertEqual(cache.incr_version("null"), 2) def test_decr_version(self): cache.set("answer", 42, version=2) self.assertIsNone(cache.get("answer")) self.assertIsNone(cache.get("answer", version=1)) self.assertEqual(cache.get("answer", version=2), 42) self.assertEqual(cache.decr_version("answer", version=2), 1) self.assertEqual(cache.get("answer"), 42) self.assertEqual(cache.get("answer", version=1), 42) self.assertIsNone(cache.get("answer", version=2)) caches["v2"].set("answer2", 42) self.assertEqual(caches["v2"].get("answer2"), 42) self.assertIsNone(caches["v2"].get("answer2", version=1)) self.assertEqual(caches["v2"].get("answer2", version=2), 42) self.assertEqual(caches["v2"].decr_version("answer2"), 1) self.assertIsNone(caches["v2"].get("answer2")) self.assertEqual(caches["v2"].get("answer2", version=1), 42) self.assertIsNone(caches["v2"].get("answer2", version=2)) with self.assertRaises(ValueError): cache.decr_version("does_not_exist", version=2) cache.set("null", None, version=2) self.assertEqual(cache.decr_version("null", version=2), 1) def test_custom_key_func(self): # Two caches with different key functions aren't visible to each other cache.set("answer1", 42) self.assertEqual(cache.get("answer1"), 42) self.assertIsNone(caches["custom_key"].get("answer1")) self.assertIsNone(caches["custom_key2"].get("answer1")) caches["custom_key"].set("answer2", 42) self.assertIsNone(cache.get("answer2")) self.assertEqual(caches["custom_key"].get("answer2"), 42) self.assertEqual(caches["custom_key2"].get("answer2"), 42) @override_settings(CACHE_MIDDLEWARE_ALIAS=DEFAULT_CACHE_ALIAS) def test_cache_write_unpicklable_object(self): fetch_middleware = FetchFromCacheMiddleware(empty_response) request = self.factory.get("/cache/test") request._cache_update_cache = True get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNone(get_cache_data) content = "Testing cookie serialization." def get_response(req): response = HttpResponse(content) response.set_cookie("foo", "bar") return response update_middleware = UpdateCacheMiddleware(get_response) response = update_middleware(request) get_cache_data = fetch_middleware.process_request(request) self.assertIsNotNone(get_cache_data) self.assertEqual(get_cache_data.content, content.encode()) self.assertEqual(get_cache_data.cookies, response.cookies) UpdateCacheMiddleware(lambda req: get_cache_data)(request) get_cache_data = fetch_middleware.process_request(request) self.assertIsNotNone(get_cache_data) self.assertEqual(get_cache_data.content, content.encode()) self.assertEqual(get_cache_data.cookies, response.cookies) def test_add_fail_on_pickleerror(self): # Shouldn't fail silently if trying to cache an unpicklable type. with self.assertRaises(pickle.PickleError): cache.add("unpicklable", Unpicklable()) def test_set_fail_on_pickleerror(self): with self.assertRaises(pickle.PickleError): cache.set("unpicklable", Unpicklable()) def test_get_or_set(self): self.assertIsNone(cache.get("projector")) self.assertEqual(cache.get_or_set("projector", 42), 42) self.assertEqual(cache.get("projector"), 42) self.assertIsNone(cache.get_or_set("null", None)) # Previous get_or_set() stores None in the cache. self.assertIsNone(cache.get("null", "default")) def test_get_or_set_callable(self): def my_callable(): return "value" self.assertEqual(cache.get_or_set("mykey", my_callable), "value") self.assertEqual(cache.get_or_set("mykey", my_callable()), "value") self.assertIsNone(cache.get_or_set("null", lambda: None)) # Previous get_or_set() stores None in the cache. self.assertIsNone(cache.get("null", "default")) def test_get_or_set_version(self): msg = "get_or_set() missing 1 required positional argument: 'default'" self.assertEqual(cache.get_or_set("brian", 1979, version=2), 1979) with self.assertRaisesMessage(TypeError, msg): cache.get_or_set("brian") with self.assertRaisesMessage(TypeError, msg): cache.get_or_set("brian", version=1) self.assertIsNone(cache.get("brian", version=1)) self.assertEqual(cache.get_or_set("brian", 42, version=1), 42) self.assertEqual(cache.get_or_set("brian", 1979, version=2), 1979) self.assertIsNone(cache.get("brian", version=3)) def test_get_or_set_racing(self): with mock.patch( "%s.%s" % (settings.CACHES["default"]["BACKEND"], "add") ) as cache_add: # Simulate cache.add() failing to add a value. In that case, the # default value should be returned. cache_add.return_value = False self.assertEqual(cache.get_or_set("key", "default"), "default") @override_settings( CACHES=caches_setting_for_tests( BACKEND="django.core.cache.backends.db.DatabaseCache", # Spaces are used in the table name to ensure quoting/escaping is working LOCATION="test cache table", ) ) class DBCacheTests(BaseCacheTests, TransactionTestCase): available_apps = ["cache"] def setUp(self): # The super calls needs to happen first for the settings override. super().setUp() self.create_table() def tearDown(self): # The super call needs to happen first because it uses the database. super().tearDown() self.drop_table() def create_table(self): management.call_command("createcachetable", verbosity=0) def drop_table(self): with connection.cursor() as cursor: table_name = connection.ops.quote_name("test cache table") cursor.execute("DROP TABLE %s" % table_name) def test_get_many_num_queries(self): cache.set_many({"a": 1, "b": 2}) cache.set("expired", "expired", 0.01) with self.assertNumQueries(1): self.assertEqual(cache.get_many(["a", "b"]), {"a": 1, "b": 2}) time.sleep(0.02) with self.assertNumQueries(2): self.assertEqual(cache.get_many(["a", "b", "expired"]), {"a": 1, "b": 2}) def test_delete_many_num_queries(self): cache.set_many({"a": 1, "b": 2, "c": 3}) with self.assertNumQueries(1): cache.delete_many(["a", "b", "c"]) def test_cull_queries(self): old_max_entries = cache._max_entries # Force _cull to delete on first cached record. cache._max_entries = -1 with CaptureQueriesContext(connection) as captured_queries: try: cache.set("force_cull", "value", 1000) finally: cache._max_entries = old_max_entries num_count_queries = sum("COUNT" in query["sql"] for query in captured_queries) self.assertEqual(num_count_queries, 1) # Column names are quoted. for query in captured_queries: sql = query["sql"] if "expires" in sql: self.assertIn(connection.ops.quote_name("expires"), sql) if "cache_key" in sql: self.assertIn(connection.ops.quote_name("cache_key"), sql) def test_delete_cursor_rowcount(self): """ The rowcount attribute should not be checked on a closed cursor. """ class MockedCursorWrapper(CursorWrapper): is_closed = False def close(self): self.cursor.close() self.is_closed = True @property def rowcount(self): if self.is_closed: raise Exception("Cursor is closed.") return self.cursor.rowcount cache.set_many({"a": 1, "b": 2}) with mock.patch("django.db.backends.utils.CursorWrapper", MockedCursorWrapper): self.assertIs(cache.delete("a"), True) def test_zero_cull(self): self._perform_cull_test("zero_cull", 50, 18) def test_second_call_doesnt_crash(self): out = io.StringIO() management.call_command("createcachetable", stdout=out) self.assertEqual( out.getvalue(), "Cache table 'test cache table' already exists.\n" * len(settings.CACHES), ) @override_settings( CACHES=caches_setting_for_tests( BACKEND="django.core.cache.backends.db.DatabaseCache", # Use another table name to avoid the 'table already exists' message. LOCATION="createcachetable_dry_run_mode", ) ) def test_createcachetable_dry_run_mode(self): out = io.StringIO() management.call_command("createcachetable", dry_run=True, stdout=out) output = out.getvalue() self.assertTrue(output.startswith("CREATE TABLE")) def test_createcachetable_with_table_argument(self): """ Delete and recreate cache table with legacy behavior (explicitly specifying the table name). """ self.drop_table() out = io.StringIO() management.call_command( "createcachetable", "test cache table", verbosity=2, stdout=out, ) self.assertEqual(out.getvalue(), "Cache table 'test cache table' created.\n") def test_has_key_query_columns_quoted(self): with CaptureQueriesContext(connection) as captured_queries: cache.has_key("key") self.assertEqual(len(captured_queries), 1) sql = captured_queries[0]["sql"] # Column names are quoted. self.assertIn(connection.ops.quote_name("expires"), sql) self.assertIn(connection.ops.quote_name("cache_key"), sql) @override_settings(USE_TZ=True) class DBCacheWithTimeZoneTests(DBCacheTests): pass class DBCacheRouter: """A router that puts the cache table on the 'other' database.""" def db_for_read(self, model, **hints): if model._meta.app_label == "django_cache": return "other" return None def db_for_write(self, model, **hints): if model._meta.app_label == "django_cache": return "other" return None def allow_migrate(self, db, app_label, **hints): if app_label == "django_cache": return db == "other" return None @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.db.DatabaseCache", "LOCATION": "my_cache_table", }, }, ) class CreateCacheTableForDBCacheTests(TestCase): databases = {"default", "other"} @override_settings(DATABASE_ROUTERS=[DBCacheRouter()]) def test_createcachetable_observes_database_router(self): # cache table should not be created on 'default' with self.assertNumQueries(0, using="default"): management.call_command("createcachetable", database="default", verbosity=0) # cache table should be created on 'other' # Queries: # 1: check table doesn't already exist # 2: create savepoint (if transactional DDL is supported) # 3: create the table # 4: create the index # 5: release savepoint (if transactional DDL is supported) num = 5 if connections["other"].features.can_rollback_ddl else 3 with self.assertNumQueries(num, using="other"): management.call_command("createcachetable", database="other", verbosity=0) class PicklingSideEffect: def __init__(self, cache): self.cache = cache self.locked = False def __getstate__(self): self.locked = self.cache._lock.locked() return {} limit_locmem_entries = override_settings( CACHES=caches_setting_for_tests( BACKEND="django.core.cache.backends.locmem.LocMemCache", OPTIONS={"MAX_ENTRIES": 9}, ) ) @override_settings( CACHES=caches_setting_for_tests( BACKEND="django.core.cache.backends.locmem.LocMemCache", ) ) class LocMemCacheTests(BaseCacheTests, TestCase): def setUp(self): super().setUp() # LocMem requires a hack to make the other caches # share a data store with the 'normal' cache. caches["prefix"]._cache = cache._cache caches["prefix"]._expire_info = cache._expire_info caches["v2"]._cache = cache._cache caches["v2"]._expire_info = cache._expire_info caches["custom_key"]._cache = cache._cache caches["custom_key"]._expire_info = cache._expire_info caches["custom_key2"]._cache = cache._cache caches["custom_key2"]._expire_info = cache._expire_info @override_settings( CACHES={ "default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}, "other": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "other", }, } ) def test_multiple_caches(self): "Multiple locmem caches are isolated" cache.set("value", 42) self.assertEqual(caches["default"].get("value"), 42) self.assertIsNone(caches["other"].get("value")) def test_locking_on_pickle(self): """#20613/#18541 -- Ensures pickling is done outside of the lock.""" bad_obj = PicklingSideEffect(cache) cache.set("set", bad_obj) self.assertFalse(bad_obj.locked, "Cache was locked during pickling") self.assertIs(cache.add("add", bad_obj), True) self.assertFalse(bad_obj.locked, "Cache was locked during pickling") def test_incr_decr_timeout(self): """incr/decr does not modify expiry time (matches memcached behavior)""" key = "value" _key = cache.make_key(key) cache.set(key, 1, timeout=cache.default_timeout * 10) expire = cache._expire_info[_key] self.assertEqual(cache.incr(key), 2) self.assertEqual(expire, cache._expire_info[_key]) self.assertEqual(cache.decr(key), 1) self.assertEqual(expire, cache._expire_info[_key]) @limit_locmem_entries def test_lru_get(self): """get() moves cache keys.""" for key in range(9): cache.set(key, key, timeout=None) for key in range(6): self.assertEqual(cache.get(key), key) cache.set(9, 9, timeout=None) for key in range(6): self.assertEqual(cache.get(key), key) for key in range(6, 9): self.assertIsNone(cache.get(key)) self.assertEqual(cache.get(9), 9) @limit_locmem_entries def test_lru_set(self): """set() moves cache keys.""" for key in range(9): cache.set(key, key, timeout=None) for key in range(3, 9): cache.set(key, key, timeout=None) cache.set(9, 9, timeout=None) for key in range(3, 10): self.assertEqual(cache.get(key), key) for key in range(3): self.assertIsNone(cache.get(key)) @limit_locmem_entries def test_lru_incr(self): """incr() moves cache keys.""" for key in range(9): cache.set(key, key, timeout=None) for key in range(6): self.assertEqual(cache.incr(key), key + 1) cache.set(9, 9, timeout=None) for key in range(6): self.assertEqual(cache.get(key), key + 1) for key in range(6, 9): self.assertIsNone(cache.get(key)) self.assertEqual(cache.get(9), 9) # memcached and redis backends aren't guaranteed to be available. # To check the backends, the test settings file will need to contain at least # one cache backend setting that points at your cache server. configured_caches = {} for _cache_params in settings.CACHES.values(): configured_caches[_cache_params["BACKEND"]] = _cache_params PyLibMCCache_params = configured_caches.get( "django.core.cache.backends.memcached.PyLibMCCache" ) PyMemcacheCache_params = configured_caches.get( "django.core.cache.backends.memcached.PyMemcacheCache" ) # The memcached backends don't support cull-related options like `MAX_ENTRIES`. memcached_excluded_caches = {"cull", "zero_cull"} RedisCache_params = configured_caches.get("django.core.cache.backends.redis.RedisCache") # The redis backend does not support cull-related options like `MAX_ENTRIES`. redis_excluded_caches = {"cull", "zero_cull"} class BaseMemcachedTests(BaseCacheTests): # By default it's assumed that the client doesn't clean up connections # properly, in which case the backend must do so after each request. should_disconnect_on_close = True def test_location_multiple_servers(self): locations = [ ["server1.tld", "server2:11211"], "server1.tld;server2:11211", "server1.tld,server2:11211", ] for location in locations: with self.subTest(location=location): params = {"BACKEND": self.base_params["BACKEND"], "LOCATION": location} with self.settings(CACHES={"default": params}): self.assertEqual(cache._servers, ["server1.tld", "server2:11211"]) def _perform_invalid_key_test(self, key, expected_warning): """ While other backends merely warn, memcached should raise for an invalid key. """ msg = expected_warning.replace(key, cache.make_key(key)) tests = [ ("add", [key, 1]), ("get", [key]), ("set", [key, 1]), ("incr", [key]), ("decr", [key]), ("touch", [key]), ("delete", [key]), ("get_many", [[key, "b"]]), ("set_many", [{key: 1, "b": 2}]), ("delete_many", [[key, "b"]]), ] for operation, args in tests: with self.subTest(operation=operation): with self.assertRaises(InvalidCacheKey) as cm: getattr(cache, operation)(*args) self.assertEqual(str(cm.exception), msg) def test_invalid_with_version_key_length(self): # make_key() adds a version to the key and exceeds the limit. key = "a" * 248 expected_warning = ( "Cache key will cause errors if used with memcached: " "%r (longer than %s)" % (key, 250) ) self._perform_invalid_key_test(key, expected_warning) def test_default_never_expiring_timeout(self): # Regression test for #22845 with self.settings( CACHES=caches_setting_for_tests( base=self.base_params, exclude=memcached_excluded_caches, TIMEOUT=None ) ): cache.set("infinite_foo", "bar") self.assertEqual(cache.get("infinite_foo"), "bar") def test_default_far_future_timeout(self): # Regression test for #22845 with self.settings( CACHES=caches_setting_for_tests( base=self.base_params, exclude=memcached_excluded_caches, # 60*60*24*365, 1 year TIMEOUT=31536000, ) ): cache.set("future_foo", "bar") self.assertEqual(cache.get("future_foo"), "bar") def test_memcached_deletes_key_on_failed_set(self): # By default memcached allows objects up to 1MB. For the cache_db session # backend to always use the current session, memcached needs to delete # the old key if it fails to set. max_value_length = 2**20 cache.set("small_value", "a") self.assertEqual(cache.get("small_value"), "a") large_value = "a" * (max_value_length + 1) try: cache.set("small_value", large_value) except Exception: # Most clients (e.g. pymemcache or pylibmc) raise when the value is # too large. This test is primarily checking that the key was # deleted, so the return/exception behavior for the set() itself is # not important. pass # small_value should be deleted, or set if configured to accept larger values value = cache.get("small_value") self.assertTrue(value is None or value == large_value) def test_close(self): # For clients that don't manage their connections properly, the # connection is closed when the request is complete. signals.request_finished.disconnect(close_old_connections) try: with mock.patch.object( cache._class, "disconnect_all", autospec=True ) as mock_disconnect: signals.request_finished.send(self.__class__) self.assertIs(mock_disconnect.called, self.should_disconnect_on_close) finally: signals.request_finished.connect(close_old_connections) def test_set_many_returns_failing_keys(self): def fail_set_multi(mapping, *args, **kwargs): return mapping.keys() with mock.patch.object(cache._class, "set_multi", side_effect=fail_set_multi): failing_keys = cache.set_many({"key": "value"}) self.assertEqual(failing_keys, ["key"]) @unittest.skipUnless(PyLibMCCache_params, "PyLibMCCache backend not configured") @override_settings( CACHES=caches_setting_for_tests( base=PyLibMCCache_params, exclude=memcached_excluded_caches, ) ) class PyLibMCCacheTests(BaseMemcachedTests, TestCase): base_params = PyLibMCCache_params # libmemcached manages its own connections. should_disconnect_on_close = False @property def incr_decr_type_error(self): return cache._lib.ClientError @override_settings( CACHES=caches_setting_for_tests( base=PyLibMCCache_params, exclude=memcached_excluded_caches, OPTIONS={ "binary": True, "behaviors": {"tcp_nodelay": True}, }, ) ) def test_pylibmc_options(self): self.assertTrue(cache._cache.binary) self.assertEqual(cache._cache.behaviors["tcp_nodelay"], int(True)) def test_pylibmc_client_servers(self): backend = self.base_params["BACKEND"] tests = [ ("unix:/run/memcached/socket", "/run/memcached/socket"), ("/run/memcached/socket", "/run/memcached/socket"), ("localhost", "localhost"), ("localhost:11211", "localhost:11211"), ("[::1]", "[::1]"), ("[::1]:11211", "[::1]:11211"), ("127.0.0.1", "127.0.0.1"), ("127.0.0.1:11211", "127.0.0.1:11211"), ] for location, expected in tests: settings = {"default": {"BACKEND": backend, "LOCATION": location}} with self.subTest(location), self.settings(CACHES=settings): self.assertEqual(cache.client_servers, [expected]) @unittest.skipUnless(PyMemcacheCache_params, "PyMemcacheCache backend not configured") @override_settings( CACHES=caches_setting_for_tests( base=PyMemcacheCache_params, exclude=memcached_excluded_caches, ) ) class PyMemcacheCacheTests(BaseMemcachedTests, TestCase): base_params = PyMemcacheCache_params @property def incr_decr_type_error(self): return cache._lib.exceptions.MemcacheClientError def test_pymemcache_highest_pickle_version(self): self.assertEqual( cache._cache.default_kwargs["serde"]._serialize_func.keywords[ "pickle_version" ], pickle.HIGHEST_PROTOCOL, ) for cache_key in settings.CACHES: for client_key, client in caches[cache_key]._cache.clients.items(): with self.subTest(cache_key=cache_key, server=client_key): self.assertEqual( client.serde._serialize_func.keywords["pickle_version"], pickle.HIGHEST_PROTOCOL, ) @override_settings( CACHES=caches_setting_for_tests( base=PyMemcacheCache_params, exclude=memcached_excluded_caches, OPTIONS={"no_delay": True}, ) ) def test_pymemcache_options(self): self.assertIs(cache._cache.default_kwargs["no_delay"], True) @override_settings( CACHES=caches_setting_for_tests( BACKEND="django.core.cache.backends.filebased.FileBasedCache", ) ) class FileBasedCacheTests(BaseCacheTests, TestCase): """ Specific test cases for the file-based cache. """ def setUp(self): super().setUp() self.dirname = self.mkdtemp() # Caches location cannot be modified through override_settings / # modify_settings, hence settings are manipulated directly here and the # setting_changed signal is triggered manually. for cache_params in settings.CACHES.values(): cache_params["LOCATION"] = self.dirname setting_changed.send(self.__class__, setting="CACHES", enter=False) def tearDown(self): super().tearDown() # Call parent first, as cache.clear() may recreate cache base directory shutil.rmtree(self.dirname) def mkdtemp(self): return tempfile.mkdtemp() def test_ignores_non_cache_files(self): fname = os.path.join(self.dirname, "not-a-cache-file") with open(fname, "w"): os.utime(fname, None) cache.clear() self.assertTrue( os.path.exists(fname), "Expected cache.clear to ignore non cache files" ) os.remove(fname) def test_clear_does_not_remove_cache_dir(self): cache.clear() self.assertTrue( os.path.exists(self.dirname), "Expected cache.clear to keep the cache dir" ) def test_creates_cache_dir_if_nonexistent(self): os.rmdir(self.dirname) cache.set("foo", "bar") self.assertTrue(os.path.exists(self.dirname)) def test_get_ignores_enoent(self): cache.set("foo", "bar") os.unlink(cache._key_to_file("foo")) # Returns the default instead of erroring. self.assertEqual(cache.get("foo", "baz"), "baz") @skipIf( sys.platform == "win32", "Windows only partially supports umasks and chmod.", ) def test_cache_dir_permissions(self): os.rmdir(self.dirname) dir_path = Path(self.dirname) / "nested" / "filebasedcache" for cache_params in settings.CACHES.values(): cache_params["LOCATION"] = dir_path setting_changed.send(self.__class__, setting="CACHES", enter=False) cache.set("foo", "bar") self.assertIs(dir_path.exists(), True) tests = [ dir_path, dir_path.parent, dir_path.parent.parent, ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o700) def test_get_does_not_ignore_non_filenotfound_exceptions(self): with mock.patch("builtins.open", side_effect=OSError): with self.assertRaises(OSError): cache.get("foo") def test_empty_cache_file_considered_expired(self): cache_file = cache._key_to_file("foo") with open(cache_file, "wb") as fh: fh.write(b"") with open(cache_file, "rb") as fh: self.assertIs(cache._is_expired(fh), True) @unittest.skipUnless(RedisCache_params, "Redis backend not configured") @override_settings( CACHES=caches_setting_for_tests( base=RedisCache_params, exclude=redis_excluded_caches, ) ) class RedisCacheTests(BaseCacheTests, TestCase): def setUp(self): import redis super().setUp() self.lib = redis @property def incr_decr_type_error(self): return self.lib.ResponseError def test_cache_client_class(self): self.assertIs(cache._class, RedisCacheClient) self.assertIsInstance(cache._cache, RedisCacheClient) def test_get_backend_timeout_method(self): positive_timeout = 10 positive_backend_timeout = cache.get_backend_timeout(positive_timeout) self.assertEqual(positive_backend_timeout, positive_timeout) negative_timeout = -5 negative_backend_timeout = cache.get_backend_timeout(negative_timeout) self.assertEqual(negative_backend_timeout, 0) none_timeout = None none_backend_timeout = cache.get_backend_timeout(none_timeout) self.assertIsNone(none_backend_timeout) def test_get_connection_pool_index(self): pool_index = cache._cache._get_connection_pool_index(write=True) self.assertEqual(pool_index, 0) pool_index = cache._cache._get_connection_pool_index(write=False) if len(cache._cache._servers) == 1: self.assertEqual(pool_index, 0) else: self.assertGreater(pool_index, 0) self.assertLess(pool_index, len(cache._cache._servers)) def test_get_connection_pool(self): pool = cache._cache._get_connection_pool(write=True) self.assertIsInstance(pool, self.lib.ConnectionPool) pool = cache._cache._get_connection_pool(write=False) self.assertIsInstance(pool, self.lib.ConnectionPool) def test_get_client(self): self.assertIsInstance(cache._cache.get_client(), self.lib.Redis) def test_serializer_dumps(self): self.assertEqual(cache._cache._serializer.dumps(123), 123) self.assertIsInstance(cache._cache._serializer.dumps(True), bytes) self.assertIsInstance(cache._cache._serializer.dumps("abc"), bytes) @override_settings( CACHES=caches_setting_for_tests( base=RedisCache_params, exclude=redis_excluded_caches, OPTIONS={ "db": 5, "socket_timeout": 0.1, "retry_on_timeout": True, }, ) ) def test_redis_pool_options(self): pool = cache._cache._get_connection_pool(write=False) self.assertEqual(pool.connection_kwargs["db"], 5) self.assertEqual(pool.connection_kwargs["socket_timeout"], 0.1) self.assertIs(pool.connection_kwargs["retry_on_timeout"], True) class FileBasedCachePathLibTests(FileBasedCacheTests): def mkdtemp(self): tmp_dir = super().mkdtemp() return Path(tmp_dir) @override_settings( CACHES={ "default": { "BACKEND": "cache.liberal_backend.CacheClass", }, } ) class CustomCacheKeyValidationTests(SimpleTestCase): """ Tests for the ability to mixin a custom ``validate_key`` method to a custom cache backend that otherwise inherits from a builtin backend, and override the default key validation. Refs #6447. """ def test_custom_key_validation(self): # this key is both longer than 250 characters, and has spaces key = "some key with spaces" * 15 val = "a value" cache.set(key, val) self.assertEqual(cache.get(key), val) @override_settings( CACHES={ "default": { "BACKEND": "cache.closeable_cache.CacheClass", } } ) class CacheClosingTests(SimpleTestCase): def test_close(self): self.assertFalse(cache.closed) signals.request_finished.send(self.__class__) self.assertTrue(cache.closed) def test_close_only_initialized(self): with self.settings( CACHES={ "cache_1": { "BACKEND": "cache.closeable_cache.CacheClass", }, "cache_2": { "BACKEND": "cache.closeable_cache.CacheClass", }, } ): self.assertEqual(caches.all(initialized_only=True), []) signals.request_finished.send(self.__class__) self.assertEqual(caches.all(initialized_only=True), []) DEFAULT_MEMORY_CACHES_SETTINGS = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "unique-snowflake", } } NEVER_EXPIRING_CACHES_SETTINGS = copy.deepcopy(DEFAULT_MEMORY_CACHES_SETTINGS) NEVER_EXPIRING_CACHES_SETTINGS["default"]["TIMEOUT"] = None class DefaultNonExpiringCacheKeyTests(SimpleTestCase): """ Settings having Cache arguments with a TIMEOUT=None create Caches that will set non-expiring keys. """ def setUp(self): # The 5 minute (300 seconds) default expiration time for keys is # defined in the implementation of the initializer method of the # BaseCache type. self.DEFAULT_TIMEOUT = caches[DEFAULT_CACHE_ALIAS].default_timeout def tearDown(self): del self.DEFAULT_TIMEOUT def test_default_expiration_time_for_keys_is_5_minutes(self): """The default expiration time of a cache key is 5 minutes. This value is defined in django.core.cache.backends.base.BaseCache.__init__(). """ self.assertEqual(300, self.DEFAULT_TIMEOUT) def test_caches_with_unset_timeout_has_correct_default_timeout(self): """Caches that have the TIMEOUT parameter undefined in the default settings will use the default 5 minute timeout. """ cache = caches[DEFAULT_CACHE_ALIAS] self.assertEqual(self.DEFAULT_TIMEOUT, cache.default_timeout) @override_settings(CACHES=NEVER_EXPIRING_CACHES_SETTINGS) def test_caches_set_with_timeout_as_none_has_correct_default_timeout(self): """Memory caches that have the TIMEOUT parameter set to `None` in the default settings with have `None` as the default timeout. This means "no timeout". """ cache = caches[DEFAULT_CACHE_ALIAS] self.assertIsNone(cache.default_timeout) self.assertIsNone(cache.get_backend_timeout()) @override_settings(CACHES=DEFAULT_MEMORY_CACHES_SETTINGS) def test_caches_with_unset_timeout_set_expiring_key(self): """Memory caches that have the TIMEOUT parameter unset will set cache keys having the default 5 minute timeout. """ key = "my-key" value = "my-value" cache = caches[DEFAULT_CACHE_ALIAS] cache.set(key, value) cache_key = cache.make_key(key) self.assertIsNotNone(cache._expire_info[cache_key]) @override_settings(CACHES=NEVER_EXPIRING_CACHES_SETTINGS) def test_caches_set_with_timeout_as_none_set_non_expiring_key(self): """Memory caches that have the TIMEOUT parameter set to `None` will set a non expiring key by default. """ key = "another-key" value = "another-value" cache = caches[DEFAULT_CACHE_ALIAS] cache.set(key, value) cache_key = cache.make_key(key) self.assertIsNone(cache._expire_info[cache_key]) @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="settingsprefix", CACHE_MIDDLEWARE_SECONDS=1, CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, }, USE_I18N=False, ALLOWED_HOSTS=[".example.com"], ) class CacheUtils(SimpleTestCase): """TestCase for django.utils.cache functions.""" host = "www.example.com" path = "/cache/test/" factory = RequestFactory(HTTP_HOST=host) def tearDown(self): cache.clear() def _get_request_cache(self, method="GET", query_string=None, update_cache=None): request = self._get_request( self.host, self.path, method, query_string=query_string ) request._cache_update_cache = update_cache if update_cache else True return request def test_patch_vary_headers(self): headers = ( # Initial vary, new headers, resulting vary. (None, ("Accept-Encoding",), "Accept-Encoding"), ("Accept-Encoding", ("accept-encoding",), "Accept-Encoding"), ("Accept-Encoding", ("ACCEPT-ENCODING",), "Accept-Encoding"), ("Cookie", ("Accept-Encoding",), "Cookie, Accept-Encoding"), ( "Cookie, Accept-Encoding", ("Accept-Encoding",), "Cookie, Accept-Encoding", ), ( "Cookie, Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), (None, ("Accept-Encoding", "COOKIE"), "Accept-Encoding, COOKIE"), ( "Cookie, Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), ( "Cookie , Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), ("*", ("Accept-Language", "Cookie"), "*"), ("Accept-Language, Cookie", ("*",), "*"), ) for initial_vary, newheaders, resulting_vary in headers: with self.subTest(initial_vary=initial_vary, newheaders=newheaders): response = HttpResponse() if initial_vary is not None: response.headers["Vary"] = initial_vary patch_vary_headers(response, newheaders) self.assertEqual(response.headers["Vary"], resulting_vary) def test_get_cache_key(self): request = self.factory.get(self.path) response = HttpResponse() # Expect None if no headers have been set yet. self.assertIsNone(get_cache_key(request)) # Set headers to an empty list. learn_cache_key(request, response) self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e", ) # A specified key_prefix is taken into account. key_prefix = "localprefix" learn_cache_key(request, response, key_prefix=key_prefix) self.assertEqual( get_cache_key(request, key_prefix=key_prefix), "views.decorators.cache.cache_page.localprefix.GET." "18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e", ) def test_get_cache_key_with_query(self): request = self.factory.get(self.path, {"test": 1}) response = HttpResponse() # Expect None if no headers have been set yet. self.assertIsNone(get_cache_key(request)) # Set headers to an empty list. learn_cache_key(request, response) # The querystring is taken into account. self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "beaf87a9a99ee81c673ea2d67ccbec2a.d41d8cd98f00b204e9800998ecf8427e", ) def test_cache_key_varies_by_url(self): """ get_cache_key keys differ by fully-qualified URL instead of path """ request1 = self.factory.get(self.path, HTTP_HOST="sub-1.example.com") learn_cache_key(request1, HttpResponse()) request2 = self.factory.get(self.path, HTTP_HOST="sub-2.example.com") learn_cache_key(request2, HttpResponse()) self.assertNotEqual(get_cache_key(request1), get_cache_key(request2)) def test_learn_cache_key(self): request = self.factory.head(self.path) response = HttpResponse() response.headers["Vary"] = "Pony" # Make sure that the Vary header is added to the key hash learn_cache_key(request, response) self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e", ) def test_patch_cache_control(self): tests = ( # Initial Cache-Control, kwargs to patch_cache_control, expected # Cache-Control parts. (None, {"private": True}, {"private"}), ("", {"private": True}, {"private"}), # no-cache. ("", {"no_cache": "Set-Cookie"}, {"no-cache=Set-Cookie"}), ("", {"no-cache": "Set-Cookie"}, {"no-cache=Set-Cookie"}), ("no-cache=Set-Cookie", {"no_cache": True}, {"no-cache"}), ("no-cache=Set-Cookie,no-cache=Link", {"no_cache": True}, {"no-cache"}), ( "no-cache=Set-Cookie", {"no_cache": "Link"}, {"no-cache=Set-Cookie", "no-cache=Link"}, ), ( "no-cache=Set-Cookie,no-cache=Link", {"no_cache": "Custom"}, {"no-cache=Set-Cookie", "no-cache=Link", "no-cache=Custom"}, ), # Test whether private/public attributes are mutually exclusive ("private", {"private": True}, {"private"}), ("private", {"public": True}, {"public"}), ("public", {"public": True}, {"public"}), ("public", {"private": True}, {"private"}), ( "must-revalidate,max-age=60,private", {"public": True}, {"must-revalidate", "max-age=60", "public"}, ), ( "must-revalidate,max-age=60,public", {"private": True}, {"must-revalidate", "max-age=60", "private"}, ), ( "must-revalidate,max-age=60", {"public": True}, {"must-revalidate", "max-age=60", "public"}, ), ) cc_delim_re = re.compile(r"\s*,\s*") for initial_cc, newheaders, expected_cc in tests: with self.subTest(initial_cc=initial_cc, newheaders=newheaders): response = HttpResponse() if initial_cc is not None: response.headers["Cache-Control"] = initial_cc patch_cache_control(response, **newheaders) parts = set(cc_delim_re.split(response.headers["Cache-Control"])) self.assertEqual(parts, expected_cc) @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "KEY_PREFIX": "cacheprefix", }, }, ) class PrefixedCacheUtils(CacheUtils): pass @override_settings( CACHE_MIDDLEWARE_SECONDS=60, CACHE_MIDDLEWARE_KEY_PREFIX="test", CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, }, ) class CacheHEADTest(SimpleTestCase): path = "/cache/test/" factory = RequestFactory() def tearDown(self): cache.clear() def _set_cache(self, request, msg): return UpdateCacheMiddleware(lambda req: HttpResponse(msg))(request) def test_head_caches_correctly(self): test_content = "test content" request = self.factory.head(self.path) request._cache_update_cache = True self._set_cache(request, test_content) request = self.factory.head(self.path) request._cache_update_cache = True get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNotNone(get_cache_data) self.assertEqual(test_content.encode(), get_cache_data.content) def test_head_with_cached_get(self): test_content = "test content" request = self.factory.get(self.path) request._cache_update_cache = True self._set_cache(request, test_content) request = self.factory.head(self.path) get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNotNone(get_cache_data) self.assertEqual(test_content.encode(), get_cache_data.content) @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="settingsprefix", CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, }, LANGUAGES=[ ("en", "English"), ("es", "Spanish"), ], ) class CacheI18nTest(SimpleTestCase): path = "/cache/test/" factory = RequestFactory() def tearDown(self): cache.clear() @override_settings(USE_I18N=True, USE_TZ=False) def test_cache_key_i18n_translation(self): request = self.factory.get(self.path) lang = translation.get_language() response = HttpResponse() key = learn_cache_key(request, response) self.assertIn( lang, key, "Cache keys should include the language name when translation is active", ) key2 = get_cache_key(request) self.assertEqual(key, key2) def check_accept_language_vary(self, accept_language, vary, reference_key): request = self.factory.get(self.path) request.META["HTTP_ACCEPT_LANGUAGE"] = accept_language request.META["HTTP_ACCEPT_ENCODING"] = "gzip;q=1.0, identity; q=0.5, *;q=0" response = HttpResponse() response.headers["Vary"] = vary key = learn_cache_key(request, response) key2 = get_cache_key(request) self.assertEqual(key, reference_key) self.assertEqual(key2, reference_key) @override_settings(USE_I18N=True, USE_TZ=False) def test_cache_key_i18n_translation_accept_language(self): lang = translation.get_language() self.assertEqual(lang, "en") request = self.factory.get(self.path) request.META["HTTP_ACCEPT_ENCODING"] = "gzip;q=1.0, identity; q=0.5, *;q=0" response = HttpResponse() response.headers["Vary"] = "accept-encoding" key = learn_cache_key(request, response) self.assertIn( lang, key, "Cache keys should include the language name when translation is active", ) self.check_accept_language_vary( "en-us", "cookie, accept-language, accept-encoding", key ) self.check_accept_language_vary( "en-US", "cookie, accept-encoding, accept-language", key ) self.check_accept_language_vary( "en-US,en;q=0.8", "accept-encoding, accept-language, cookie", key ) self.check_accept_language_vary( "en-US,en;q=0.8,ko;q=0.6", "accept-language, cookie, accept-encoding", key ) self.check_accept_language_vary( "ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3 ", "accept-encoding, cookie, accept-language", key, ) self.check_accept_language_vary( "ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4", "accept-language, accept-encoding, cookie", key, ) self.check_accept_language_vary( "ko;q=1.0,en;q=0.5", "cookie, accept-language, accept-encoding", key ) self.check_accept_language_vary( "ko, en", "cookie, accept-encoding, accept-language", key ) self.check_accept_language_vary( "ko-KR, en-US", "accept-encoding, accept-language, cookie", key ) @override_settings(USE_I18N=False, USE_TZ=True) def test_cache_key_i18n_timezone(self): request = self.factory.get(self.path) tz = timezone.get_current_timezone_name() response = HttpResponse() key = learn_cache_key(request, response) self.assertIn( tz, key, "Cache keys should include the time zone name when time zones are active", ) key2 = get_cache_key(request) self.assertEqual(key, key2) @override_settings(USE_I18N=False) def test_cache_key_no_i18n(self): request = self.factory.get(self.path) lang = translation.get_language() tz = timezone.get_current_timezone_name() response = HttpResponse() key = learn_cache_key(request, response) self.assertNotIn( lang, key, "Cache keys shouldn't include the language name when i18n isn't active", ) self.assertNotIn( tz, key, "Cache keys shouldn't include the time zone name when i18n isn't active", ) @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="test", CACHE_MIDDLEWARE_SECONDS=60, USE_I18N=True, ) def test_middleware(self): def set_cache(request, lang, msg): def get_response(req): return HttpResponse(msg) translation.activate(lang) return UpdateCacheMiddleware(get_response)(request) # cache with non empty request.GET request = self.factory.get(self.path, {"foo": "bar", "other": "true"}) request._cache_update_cache = True get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) # first access, cache must return None self.assertIsNone(get_cache_data) content = "Check for cache with QUERY_STRING" def get_response(req): return HttpResponse(content) UpdateCacheMiddleware(get_response)(request) get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) # cache must return content self.assertIsNotNone(get_cache_data) self.assertEqual(get_cache_data.content, content.encode()) # different QUERY_STRING, cache must be empty request = self.factory.get(self.path, {"foo": "bar", "somethingelse": "true"}) request._cache_update_cache = True get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNone(get_cache_data) # i18n tests en_message = "Hello world!" es_message = "Hola mundo!" request = self.factory.get(self.path) request._cache_update_cache = True set_cache(request, "en", en_message) get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) # The cache can be recovered self.assertIsNotNone(get_cache_data) self.assertEqual(get_cache_data.content, en_message.encode()) # change the session language and set content request = self.factory.get(self.path) request._cache_update_cache = True set_cache(request, "es", es_message) # change again the language translation.activate("en") # retrieve the content from cache get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertEqual(get_cache_data.content, en_message.encode()) # change again the language translation.activate("es") get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertEqual(get_cache_data.content, es_message.encode()) # reset the language translation.deactivate() @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="test", CACHE_MIDDLEWARE_SECONDS=60, ) def test_middleware_doesnt_cache_streaming_response(self): request = self.factory.get(self.path) get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNone(get_cache_data) def get_stream_response(req): return StreamingHttpResponse(["Check for cache with streaming content."]) UpdateCacheMiddleware(get_stream_response)(request) get_cache_data = FetchFromCacheMiddleware(empty_response).process_request( request ) self.assertIsNone(get_cache_data) @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "KEY_PREFIX": "cacheprefix", }, }, ) class PrefixedCacheI18nTest(CacheI18nTest): pass def hello_world_view(request, value): return HttpResponse("Hello World %s" % value) def csrf_view(request): return HttpResponse(csrf(request)["csrf_token"]) @override_settings( CACHE_MIDDLEWARE_ALIAS="other", CACHE_MIDDLEWARE_KEY_PREFIX="middlewareprefix", CACHE_MIDDLEWARE_SECONDS=30, CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, "other": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "other", "TIMEOUT": "1", }, }, ) class CacheMiddlewareTest(SimpleTestCase): factory = RequestFactory() def setUp(self): self.default_cache = caches["default"] self.other_cache = caches["other"] def tearDown(self): self.default_cache.clear() self.other_cache.clear() super().tearDown() def test_constructor(self): """ The constructor is correctly distinguishing between usage of CacheMiddleware as Middleware vs. usage of CacheMiddleware as view decorator and setting attributes appropriately. """ # If only one argument is passed in construction, it's being used as # middleware. middleware = CacheMiddleware(empty_response) # Now test object attributes against values defined in setUp above self.assertEqual(middleware.cache_timeout, 30) self.assertEqual(middleware.key_prefix, "middlewareprefix") self.assertEqual(middleware.cache_alias, "other") self.assertEqual(middleware.cache, self.other_cache) # If more arguments are being passed in construction, it's being used # as a decorator. First, test with "defaults": as_view_decorator = CacheMiddleware( empty_response, cache_alias=None, key_prefix=None ) self.assertEqual( as_view_decorator.cache_timeout, 30 ) # Timeout value for 'default' cache, i.e. 30 self.assertEqual(as_view_decorator.key_prefix, "") # Value of DEFAULT_CACHE_ALIAS from django.core.cache self.assertEqual(as_view_decorator.cache_alias, "default") self.assertEqual(as_view_decorator.cache, self.default_cache) # Next, test with custom values: as_view_decorator_with_custom = CacheMiddleware( hello_world_view, cache_timeout=60, cache_alias="other", key_prefix="foo" ) self.assertEqual(as_view_decorator_with_custom.cache_timeout, 60) self.assertEqual(as_view_decorator_with_custom.key_prefix, "foo") self.assertEqual(as_view_decorator_with_custom.cache_alias, "other") self.assertEqual(as_view_decorator_with_custom.cache, self.other_cache) def test_update_cache_middleware_constructor(self): middleware = UpdateCacheMiddleware(empty_response) self.assertEqual(middleware.cache_timeout, 30) self.assertIsNone(middleware.page_timeout) self.assertEqual(middleware.key_prefix, "middlewareprefix") self.assertEqual(middleware.cache_alias, "other") self.assertEqual(middleware.cache, self.other_cache) def test_fetch_cache_middleware_constructor(self): middleware = FetchFromCacheMiddleware(empty_response) self.assertEqual(middleware.key_prefix, "middlewareprefix") self.assertEqual(middleware.cache_alias, "other") self.assertEqual(middleware.cache, self.other_cache) def test_middleware(self): middleware = CacheMiddleware(hello_world_view) prefix_middleware = CacheMiddleware(hello_world_view, key_prefix="prefix1") timeout_middleware = CacheMiddleware(hello_world_view, cache_timeout=1) request = self.factory.get("/view/") # Put the request through the request middleware result = middleware.process_request(request) self.assertIsNone(result) response = hello_world_view(request, "1") # Now put the response through the response middleware response = middleware.process_response(request, response) # Repeating the request should result in a cache hit result = middleware.process_request(request) self.assertIsNotNone(result) self.assertEqual(result.content, b"Hello World 1") # The same request through a different middleware won't hit result = prefix_middleware.process_request(request) self.assertIsNone(result) # The same request with a timeout _will_ hit result = timeout_middleware.process_request(request) self.assertIsNotNone(result) self.assertEqual(result.content, b"Hello World 1") def test_view_decorator(self): # decorate the same view with different cache decorators default_view = cache_page(3)(hello_world_view) default_with_prefix_view = cache_page(3, key_prefix="prefix1")(hello_world_view) explicit_default_view = cache_page(3, cache="default")(hello_world_view) explicit_default_with_prefix_view = cache_page( 3, cache="default", key_prefix="prefix1" )(hello_world_view) other_view = cache_page(1, cache="other")(hello_world_view) other_with_prefix_view = cache_page(1, cache="other", key_prefix="prefix2")( hello_world_view ) request = self.factory.get("/view/") # Request the view once response = default_view(request, "1") self.assertEqual(response.content, b"Hello World 1") # Request again -- hit the cache response = default_view(request, "2") self.assertEqual(response.content, b"Hello World 1") # Requesting the same view with the explicit cache should yield the same result response = explicit_default_view(request, "3") self.assertEqual(response.content, b"Hello World 1") # Requesting with a prefix will hit a different cache key response = explicit_default_with_prefix_view(request, "4") self.assertEqual(response.content, b"Hello World 4") # Hitting the same view again gives a cache hit response = explicit_default_with_prefix_view(request, "5") self.assertEqual(response.content, b"Hello World 4") # And going back to the implicit cache will hit the same cache response = default_with_prefix_view(request, "6") self.assertEqual(response.content, b"Hello World 4") # Requesting from an alternate cache won't hit cache response = other_view(request, "7") self.assertEqual(response.content, b"Hello World 7") # But a repeated hit will hit cache response = other_view(request, "8") self.assertEqual(response.content, b"Hello World 7") # And prefixing the alternate cache yields yet another cache entry response = other_with_prefix_view(request, "9") self.assertEqual(response.content, b"Hello World 9") # But if we wait a couple of seconds... time.sleep(2) # ... the default cache will still hit caches["default"] response = default_view(request, "11") self.assertEqual(response.content, b"Hello World 1") # ... the default cache with a prefix will still hit response = default_with_prefix_view(request, "12") self.assertEqual(response.content, b"Hello World 4") # ... the explicit default cache will still hit response = explicit_default_view(request, "13") self.assertEqual(response.content, b"Hello World 1") # ... the explicit default cache with a prefix will still hit response = explicit_default_with_prefix_view(request, "14") self.assertEqual(response.content, b"Hello World 4") # .. but a rapidly expiring cache won't hit response = other_view(request, "15") self.assertEqual(response.content, b"Hello World 15") # .. even if it has a prefix response = other_with_prefix_view(request, "16") self.assertEqual(response.content, b"Hello World 16") def test_cache_page_timeout(self): # Page timeout takes precedence over the "max-age" section of the # "Cache-Control". tests = [ (1, 3), # max_age < page_timeout. (3, 1), # max_age > page_timeout. ] for max_age, page_timeout in tests: with self.subTest(max_age=max_age, page_timeout=page_timeout): view = cache_page(timeout=page_timeout)( cache_control(max_age=max_age)(hello_world_view) ) request = self.factory.get("/view/") response = view(request, "1") self.assertEqual(response.content, b"Hello World 1") time.sleep(1) response = view(request, "2") self.assertEqual( response.content, b"Hello World 1" if page_timeout > max_age else b"Hello World 2", ) cache.clear() def test_cached_control_private_not_cached(self): """Responses with 'Cache-Control: private' are not cached.""" view_with_private_cache = cache_page(3)( cache_control(private=True)(hello_world_view) ) request = self.factory.get("/view/") response = view_with_private_cache(request, "1") self.assertEqual(response.content, b"Hello World 1") response = view_with_private_cache(request, "2") self.assertEqual(response.content, b"Hello World 2") def test_sensitive_cookie_not_cached(self): """ Django must prevent caching of responses that set a user-specific (and maybe security sensitive) cookie in response to a cookie-less request. """ request = self.factory.get("/view/") csrf_middleware = CsrfViewMiddleware(csrf_view) csrf_middleware.process_view(request, csrf_view, (), {}) cache_middleware = CacheMiddleware(csrf_middleware) self.assertIsNone(cache_middleware.process_request(request)) cache_middleware(request) # Inserting a CSRF cookie in a cookie-less request prevented caching. self.assertIsNone(cache_middleware.process_request(request)) def test_304_response_has_http_caching_headers_but_not_cached(self): original_view = mock.Mock(return_value=HttpResponseNotModified()) view = cache_page(2)(original_view) request = self.factory.get("/view/") # The view shouldn't be cached on the second call. view(request).close() response = view(request) response.close() self.assertEqual(original_view.call_count, 2) self.assertIsInstance(response, HttpResponseNotModified) self.assertIn("Cache-Control", response) self.assertIn("Expires", response) def test_per_thread(self): """The cache instance is different for each thread.""" thread_caches = [] middleware = CacheMiddleware(empty_response) def runner(): thread_caches.append(middleware.cache) for _ in range(2): thread = threading.Thread(target=runner) thread.start() thread.join() self.assertIsNot(thread_caches[0], thread_caches[1]) @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="settingsprefix", CACHE_MIDDLEWARE_SECONDS=1, CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, }, USE_I18N=False, ) class TestWithTemplateResponse(SimpleTestCase): """ Tests various headers w/ TemplateResponse. Most are probably redundant since they manipulate the same object anyway but the ETag header is 'special' because it relies on the content being complete (which is not necessarily always the case with a TemplateResponse) """ path = "/cache/test/" factory = RequestFactory() def tearDown(self): cache.clear() def test_patch_vary_headers(self): headers = ( # Initial vary, new headers, resulting vary. (None, ("Accept-Encoding",), "Accept-Encoding"), ("Accept-Encoding", ("accept-encoding",), "Accept-Encoding"), ("Accept-Encoding", ("ACCEPT-ENCODING",), "Accept-Encoding"), ("Cookie", ("Accept-Encoding",), "Cookie, Accept-Encoding"), ( "Cookie, Accept-Encoding", ("Accept-Encoding",), "Cookie, Accept-Encoding", ), ( "Cookie, Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), (None, ("Accept-Encoding", "COOKIE"), "Accept-Encoding, COOKIE"), ( "Cookie, Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), ( "Cookie , Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), ) for initial_vary, newheaders, resulting_vary in headers: with self.subTest(initial_vary=initial_vary, newheaders=newheaders): template = engines["django"].from_string("This is a test") response = TemplateResponse(HttpRequest(), template) if initial_vary is not None: response.headers["Vary"] = initial_vary patch_vary_headers(response, newheaders) self.assertEqual(response.headers["Vary"], resulting_vary) def test_get_cache_key(self): request = self.factory.get(self.path) template = engines["django"].from_string("This is a test") response = TemplateResponse(HttpRequest(), template) key_prefix = "localprefix" # Expect None if no headers have been set yet. self.assertIsNone(get_cache_key(request)) # Set headers to an empty list. learn_cache_key(request, response) self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e", ) # A specified key_prefix is taken into account. learn_cache_key(request, response, key_prefix=key_prefix) self.assertEqual( get_cache_key(request, key_prefix=key_prefix), "views.decorators.cache.cache_page.localprefix.GET." "58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e", ) def test_get_cache_key_with_query(self): request = self.factory.get(self.path, {"test": 1}) template = engines["django"].from_string("This is a test") response = TemplateResponse(HttpRequest(), template) # Expect None if no headers have been set yet. self.assertIsNone(get_cache_key(request)) # Set headers to an empty list. learn_cache_key(request, response) # The querystring is taken into account. self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "0f1c2d56633c943073c4569d9a9502fe.d41d8cd98f00b204e9800998ecf8427e", ) class TestMakeTemplateFragmentKey(SimpleTestCase): def test_without_vary_on(self): key = make_template_fragment_key("a.fragment") self.assertEqual( key, "template.cache.a.fragment.d41d8cd98f00b204e9800998ecf8427e" ) def test_with_one_vary_on(self): key = make_template_fragment_key("foo", ["abc"]) self.assertEqual(key, "template.cache.foo.493e283d571a73056196f1a68efd0f66") def test_with_many_vary_on(self): key = make_template_fragment_key("bar", ["abc", "def"]) self.assertEqual(key, "template.cache.bar.17c1a507a0cb58384f4c639067a93520") def test_proper_escaping(self): key = make_template_fragment_key("spam", ["abc:def%"]) self.assertEqual(key, "template.cache.spam.06c8ae8e8c430b69fb0a6443504153dc") def test_with_ints_vary_on(self): key = make_template_fragment_key("foo", [1, 2, 3, 4, 5]) self.assertEqual(key, "template.cache.foo.7ae8fd2e0d25d651c683bdeebdb29461") def test_with_unicode_vary_on(self): key = make_template_fragment_key("foo", ["42º", "😀"]) self.assertEqual(key, "template.cache.foo.7ced1c94e543668590ba39b3c08b0237") def test_long_vary_on(self): key = make_template_fragment_key("foo", ["x" * 10000]) self.assertEqual(key, "template.cache.foo.3670b349b5124aa56bdb50678b02b23a") class CacheHandlerTest(SimpleTestCase): def test_same_instance(self): """ Attempting to retrieve the same alias should yield the same instance. """ cache1 = caches["default"] cache2 = caches["default"] self.assertIs(cache1, cache2) def test_per_thread(self): """ Requesting the same alias from separate threads should yield separate instances. """ c = [] def runner(): c.append(caches["default"]) for x in range(2): t = threading.Thread(target=runner) t.start() t.join() self.assertIsNot(c[0], c[1]) def test_nonexistent_alias(self): msg = "The connection 'nonexistent' doesn't exist." with self.assertRaisesMessage(InvalidCacheBackendError, msg): caches["nonexistent"] def test_nonexistent_backend(self): test_caches = CacheHandler( { "invalid_backend": { "BACKEND": "django.nonexistent.NonexistentBackend", }, } ) msg = ( "Could not find backend 'django.nonexistent.NonexistentBackend': " "No module named 'django.nonexistent'" ) with self.assertRaisesMessage(InvalidCacheBackendError, msg): test_caches["invalid_backend"] def test_all(self): test_caches = CacheHandler( { "cache_1": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", }, "cache_2": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", }, } ) self.assertEqual(test_caches.all(initialized_only=True), []) cache_1 = test_caches["cache_1"] self.assertEqual(test_caches.all(initialized_only=True), [cache_1]) self.assertEqual(len(test_caches.all()), 2) # .all() initializes all caches. self.assertEqual(len(test_caches.all(initialized_only=True)), 2) self.assertEqual(test_caches.all(), test_caches.all(initialized_only=True))
38.099555
88
0.626085
4a102d3616f0c455be159f217c9ddd40b3d9710d
39,321
py
Python
get_together/views/events.py
thiagoferreiraw/GetTogether
0cfa2bcf0915dd03ed5e5b9fab641b058eee1ca3
[ "BSD-2-Clause" ]
null
null
null
get_together/views/events.py
thiagoferreiraw/GetTogether
0cfa2bcf0915dd03ed5e5b9fab641b058eee1ca3
[ "BSD-2-Clause" ]
null
null
null
get_together/views/events.py
thiagoferreiraw/GetTogether
0cfa2bcf0915dd03ed5e5b9fab641b058eee1ca3
[ "BSD-2-Clause" ]
null
null
null
from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib.sites.models import Site from django.utils import timezone from django.utils.datastructures import OrderedSet from django.core.mail import send_mail from django.template.loader import get_template, render_to_string from django.conf import settings from django.http import JsonResponse from events.models.events import ( Event, EventComment, CommonEvent, EventSeries, EventPhoto, Place, Attendee, update_event_searchable, delete_event_searchable, ) from events.models.speakers import Speaker, Talk, SpeakerRequest, Presentation from events.models.profiles import Team, Organization, UserProfile, Member, Sponsor from events.forms import ( TeamEventForm, NewTeamEventForm, DeleteEventForm, CancelEventForm, EventSeriesForm, DeleteEventSeriesForm, EventCommentForm, DeleteCommentForm, NewPlaceForm, UploadEventPhotoForm, RemoveEventPhotoForm, EventInviteEmailForm, EventInviteMemberForm, EventContactForm, SponsorForm, ChangeEventHostForm, ) from events import location from events.utils import verify_csrf from accounts.models import EmailRecord import simple_ga as ga import datetime import simplejson # Create your views here. def events_list(request, *args, **kwargs): if not request.user.is_authenticated: return redirect('all-events') events = Event.objects.filter(attendees=request.user.profile, end_time__gt=timezone.now(), status__gt=Event.CANCELED).order_by('start_time') geo_ip = location.get_geoip(request) context = { 'active': 'my', 'events_list': sorted(events, key=lambda event: location.event_distance_from(geo_ip.latlng, event)), } return render(request, 'get_together/events/list_events.html', context) def events_list_all(request, *args, **kwargs): events = Event.objects.filter(end_time__gt=timezone.now()).order_by('start_time') geo_ip = location.get_geoip(request) context = { 'active': 'all', 'events_list': sorted(events, key=lambda event: location.event_distance_from(geo_ip.latlng, event)), } return render(request, 'get_together/events/list_events.html', context) def show_event(request, event_id, event_slug): event = get_object_or_404(Event, id=event_id) comment_form = EventCommentForm() context = { 'team': event.team, 'event': event, 'comment_form': comment_form, 'sponsor_count': event.sponsors.count(), 'sponsor_list': event.sponsors.all(), 'is_attending': request.user.profile in event.attendees.all(), 'attendee_list': Attendee.objects.filter(event=event).order_by('-role', '-status'), 'attendee_count': Attendee.objects.filter(event=event, status=Attendee.YES).count(), 'presentation_list': event.presentations.filter(status=Presentation.ACCEPTED).order_by('start_time'), 'pending_presentations': event.presentations.filter(status=Presentation.PROPOSED).count(), 'can_edit_event': request.user.profile.can_edit_event(event), 'can_edit_team': request.user.profile.can_edit_team(event.team), 'is_in_team': request.user.profile.is_in_team(event.team), 'is_email_confirmed': request.user.account.is_email_confirmed, } return render(request, 'get_together/events/show_event.html', context) def show_series(request, series_id, series_slug): series = get_object_or_404(EventSeries, id=series_id) context = { 'team': series.team, 'series': series, 'instances': series.instances.all().order_by('-start_time'), 'can_edit_event': request.user.profile.can_create_event(series.team), } return render(request, 'get_together/events/show_series.html', context) @login_required def create_event_team_select(request): teams = request.user.profile.moderating if len(teams) == 0: return redirect('create-team') if len(teams) == 1: return redirect('create-event', team_id=teams[0].id) return render(request, 'get_together/events/create_event_team_select.html', {'teams': teams}) @login_required def create_event(request, team_id): team = get_object_or_404(Team, id=team_id) if not request.user.profile.can_create_event(team): messages.add_message(request, messages.WARNING, message=_('You can not create events for this team.')) return redirect('show-team-by-slug', team_slug=team.slug) new_event = Event(team=team, created_by=request.user.profile) if request.method == 'GET': initial = {} if 'common' in request.GET and request.GET['common'] != '': new_event.parent = CommonEvent.objects.get(id=request.GET['common']) initial['name'] = new_event.parent.name initial['summary'] = new_event.parent.summary initial['start_time'] = new_event.parent.start_time initial['end_time'] = new_event.parent.end_time form = NewTeamEventForm(instance=new_event, initial=initial) context = { 'event': new_event, 'team': team, 'event_form': form, } return render(request, 'get_together/events/create_event.html', context) elif request.method == 'POST': if 'common' in request.POST and request.POST['common'] != '': new_event.parent = CommonEvent.objects.get(id=request.POST['common']) form = NewTeamEventForm(request.POST, instance=new_event) if form.is_valid: new_event = form.save() Attendee.objects.create(event=new_event, user=request.user.profile, role=Attendee.HOST, status=Attendee.YES) if form.cleaned_data.get('recurrences', None): new_series = EventSeries.from_event(new_event, recurrences=form.cleaned_data['recurrences']) new_series.save() new_event.series = new_series new_event.save() messages.add_message(request, messages.SUCCESS, message=_('Your event has been scheduled! Next, find a place for your event.')) ga.add_event(request, action='new_event', category='activity', label=new_event.get_full_url()) return redirect('add-place', new_event.id) else: context = { 'event': new_event, 'team': team, 'event_form': form, } return render(request, 'get_together/events/create_event.html', context) else: return redirect('home') @login_required def manage_event_sponsors(request, event_id): event = get_object_or_404(Event, id=event_id) if not request.user.profile.can_edit_event(event): messages.add_message(request, messages.WARNING, message=_('You can not manage this event\'s sponsorss.')) return redirect(event.get_absolute_url()) team_sponsors = list(event.team.sponsors.all()) events_sponsors = list(Sponsor.objects.filter(events__team=event.team)) if request.method == 'POST': sponsor_form = SponsorForm(request.POST, request.FILES) if sponsor_form.is_valid(): new_sponsor = sponsor_form.save() event.sponsors.add(new_sponsor) event.team.sponsors.add(new_sponsor) messages.add_message(request, messages.SUCCESS, message=_('Your sponsor has been added to this event.')) return redirect('manage-event-sponsors', event.id) else: sponsor_form = SponsorForm() context = { 'event': event, 'sponsors': OrderedSet(events_sponsors + team_sponsors), 'sponsor_form': sponsor_form, 'can_edit_event': request.user.profile.can_edit_event(event), } return render(request, 'get_together/events/manage_event_sponsors.html', context) @login_required def sponsor_event(request, event_id): event = get_object_or_404(Event, id=event_id) sponsor = get_object_or_404(Sponsor, id=request.GET.get('sponsor', None)) if request.user.is_anonymous: return JsonResponse({'status': 'ERROR', 'message': _("You must be logged in manage event sponsors.")}) if not request.user.profile.can_edit_event(event): return JsonResponse({'status': 'ERROR', 'message': _("You can not manage this event's sponsors.")}) action = 'none' if request.GET.get('action', None) == 'add': if sponsor in event.sponsors.all(): return JsonResponse({'status': 'ERROR', 'message': _("Already sponsoring this event.")}) event.sponsors.add(sponsor) action = 'Added' if request.GET.get('action', None) == 'remove': if sponsor not in event.sponsors.all(): return JsonResponse({'status': 'ERROR', 'message': _("Not sponsoring this event.")}) event.sponsors.remove(sponsor) action = 'Removed' return JsonResponse({'status': 'OK', 'sponsor_id': sponsor.id, 'action': action}) @login_required def manage_attendees(request, event_id): event = get_object_or_404(Event, id=event_id) if not request.user.profile.can_edit_event(event): messages.add_message(request, messages.WARNING, message=_('You can not manage this event\'s attendees.')) return redirect(event.get_absolute_url()) attendees = Attendee.objects.filter(event=event).order_by('-actual', '-status', 'user__realname') attendee_choices = [(attendee.id, attendee.user) for attendee in attendees if attendee.user.user.account.is_email_confirmed] default_choices = [('all', 'Everyone (%s)' % len(attendee_choices)), ('hosts', 'Only Hosts')] if event.is_over: default_choices.append(('attended', 'Only Attended')) else: default_choices.append(('attending', 'Only Attending')) if request.method == 'POST': contact_form = EventContactForm(request.POST) contact_form.fields['to'].choices = default_choices + attendee_choices if contact_form.is_valid(): to = contact_form.cleaned_data['to'] body = contact_form.cleaned_data['body'] if to is not 'hosts' and not request.user.profile.can_edit_event(event): messages.add_message(request, messages.WARNING, message=_('You can not contact this events\'s attendees.')) return redirect(event.get_absolute_url()) if to == 'all': count = 0 for attendee in Attendee.objects.filter(event=event): if attendee.user.user.account.is_email_confirmed: contact_attendee(attendee, body, request.user.profile) count += 1 messages.add_message(request, messages.SUCCESS, message=_('Emailed %s attendees' % count)) elif to == 'hosts': count = 0 for attendee in Attendee.objects.filter(event=event, role=Attendee.HOST): if attendee.user.user.account.is_email_confirmed: contact_attendee(attendee, body, request.user.profile) count += 1 messages.add_message(request, messages.SUCCESS, message=_('Emailed %s attendees' % count)) elif to == 'attending': count = 0 for attendee in Attendee.objects.filter(event=event, status=Attendee.YES): if attendee.user.user.account.is_email_confirmed: contact_attendee(attendee, body, request.user.profile) count += 1 messages.add_message(request, messages.SUCCESS, message=_('Emailed %s attendees' % count)) elif to == 'attended': count = 0 for attendee in Attendee.objects.filter(event=event, actual=Attendee.YES): if attendee.user.user.account.is_email_confirmed: contact_attendee(attendee, body, request.user.profile) count += 1 messages.add_message(request, messages.SUCCESS, message=_('Emailed %s attendees' % count)) else: try: attendee = Attendee.objects.get(id=to) contact_attendee(attendee, body, request.user.profile) messages.add_message(request, messages.SUCCESS, message=_('Emailed %s' % attendee.user)) except Member.DoesNotExist: messages.add_message(request, messages.ERROR, message=_('Error sending message: Unknown user (%s)'%to)) pass return redirect('manage-attendees', event.id) else: messages.add_message(request, messages.ERROR, message=_('Error sending message: %s' % contact_form.errors)) else: contact_form = EventContactForm() contact_form.fields['to'].choices = default_choices + attendee_choices context = { 'event': event, 'attendees': attendees, 'contact_form': contact_form, 'can_edit_event': request.user.profile.can_edit_event(event), } return render(request, 'get_together/events/manage_attendees.html', context) @login_required def invite_attendees(request, event_id): event = get_object_or_404(Event, id=event_id) attendee_userids = [attendee.user.id for attendee in Attendee.objects.filter(event=event)] members = Member.objects.filter(team=event.team, ).order_by('user__realname') member_choices = [(member.id, member.user) for member in members if member.user.user.account.is_email_confirmed and member.user.id not in attendee_userids] default_choices = [('all', 'All Members (%s)' % len(member_choices))] if request.method == 'POST' and request.POST.get('form', None) == 'email': email_form = EventInviteEmailForm(request.POST) if email_form.is_valid(): to = email_form.cleaned_data['emails'] for email in to: invite_attendee(email, event, request.user) messages.add_message(request, messages.SUCCESS, message=_('Sent %s invites' % len(to))) return redirect(event.get_absolute_url()) team_form = EventInviteMemberForm() team_form.fields['member'].choices = default_choices + member_choices elif request.method == 'POST' and request.POST.get('form', None) == 'team': team_form = EventInviteMemberForm(request.POST) team_form.fields['member'].choices = default_choices + member_choices if team_form.is_valid(): to = team_form.cleaned_data['member'] if to == 'all': for (member_id, user) in member_choices: try: attendee = Attendee.objects.get(event=event, user=user) except: # No attendee record found, so send the invite invite_attendee(user.user, event, request.user) messages.add_message(request, messages.SUCCESS, message=_('Sent %s invites' % len(member_choices))) return redirect(event.get_absolute_url()) else: member = get_object_or_404(Member, id=to) try: attendee = Attendee.objects.get(event=event, user=member.user) except: # No attendee record found, so send the invite invite_attendee(member.user.user, event, request.user) messages.add_message(request, messages.SUCCESS, message=_('Invited %s' % member.user)) return redirect(event.get_absolute_url()) email_form = EventInviteEmailForm() else: email_form = EventInviteEmailForm() team_form = EventInviteMemberForm() team_form.fields['member'].choices = default_choices + member_choices context = { 'event': event, 'email_form': email_form, 'team_form': team_form, 'member_choice_count': len(member_choices), 'can_edit_team': request.user.profile.can_edit_team(event.team), 'is_email_confirmed': request.user.account.is_email_confirmed, } return render(request, 'get_together/events/invite_attendees.html', context) def invite_attendee(email, event, sender): context = { 'sender': sender.profile, 'team': event.team, 'event': event, 'site': Site.objects.get(id=1), } recipient = None if type(email) == User: recipient = email email = recipient.email email_subject = 'Invitation to attend: %s' % event.name email_body_text = render_to_string('get_together/emails/events/attendee_invite.txt', context) email_body_html = render_to_string('get_together/emails/events/attendee_invite.html', context) email_recipients = [email] email_from = getattr(settings, 'DEFAULT_FROM_EMAIL', 'noreply@gettogether.community') success = send_mail( from_email=email_from, html_message=email_body_html, message=email_body_text, recipient_list=email_recipients, subject=email_subject, fail_silently=True, ) EmailRecord.objects.create( sender=sender, recipient=recipient, email=email, subject=email_subject, body=email_body_text, ok=success ) def contact_attendee(attendee, body, sender): context = { 'sender': sender, 'event': attendee.event, 'body': body, 'site': Site.objects.get(id=1), } email_subject = 'A message about: %s' % attendee.event.name email_body_text = render_to_string('get_together/emails/events/attendee_contact.txt', context) email_body_html = render_to_string('get_together/emails/events/attendee_contact.html', context) email_recipients = [attendee.user.user.email] email_from = getattr(settings, 'DEFAULT_FROM_EMAIL', 'noreply@gettogether.community') success = send_mail( from_email=email_from, html_message=email_body_html, message=email_body_text, recipient_list=email_recipients, subject=email_subject, fail_silently=True, ) EmailRecord.objects.create( sender=sender.user, recipient=attendee.user.user, email=attendee.user.user.email, subject=email_subject, body=email_body_text, ok=success ) @verify_csrf(token_key='csrftoken') def attend_event(request, event_id): event = get_object_or_404(Event, id=event_id) if request.user.is_anonymous: messages.add_message(request, messages.WARNING, message=_("You must be logged in to say you're attending.")) return redirect(event.get_absolute_url()) if event.is_over: messages.add_message(request, messages.WARNING, message=_("You can not change your status on an event that has ended.")) return redirect(event.get_absolute_url()) if event.status == event.CANCELED: messages.add_message(request, messages.WARNING, message=_("This event has been canceled.")) return redirect(event.get_absolute_url()) try: attendee = Attendee.objects.get(event=event, user=request.user.profile) except: attendee = Attendee(event=event, user=request.user.profile, role=Attendee.NORMAL) attendee.status = Attendee.YES if request.GET.get('response', None) == 'maybe': attendee.status = Attendee.MAYBE if request.GET.get('response', None) == 'no': attendee.status = Attendee.NO attendee.joined_date = timezone.now() attendee.save() if attendee.status == Attendee.YES: messages.add_message(request, messages.SUCCESS, message=_("We'll see you there!")) return redirect(event.get_absolute_url()) def attended_event(request, event_id): event = get_object_or_404(Event, id=event_id) attendee = get_object_or_404(Attendee, id=request.GET.get('attendee', None)) if request.user.is_anonymous: return JsonResponse({'status': 'ERROR', 'message': _("You must be logged in mark an attendee's actual status.")}) if not event.is_over: return JsonResponse({'status': 'ERROR', 'message': _("You can not set an attendee's actual status until the event is over")}) if request.GET.get('response', None) == 'yes': attendee.actual = Attendee.YES if request.GET.get('response', None) == 'no': attendee.actual = Attendee.NO attendee.save() return JsonResponse({'status': 'OK', 'attendee_id': attendee.id, 'actual': attendee.actual_name}) def comment_event(request, event_id): event = Event.objects.get(id=event_id) if not event.enable_comments: messages.add_message(request, messages.WARNING, message=_('This event does not allow comments.')) return redirect(event.get_absolute_url()) if request.user.is_anonymous: messages.add_message(request, messages.WARNING, message=_("You must be logged in to comment.")) return redirect(event.get_absolute_url()) if request.method == 'POST': new_comment = EventComment(author=request.user.profile, event=event) comment_form = EventCommentForm(request.POST, instance=new_comment) if comment_form.is_valid(): new_comment = comment_form.save() send_comment_emails(new_comment) return redirect(event.get_absolute_url()+'#comment-%s'%new_comment.id) return redirect(event.get_absolute_url()) def edit_comment(request, comment_id): comment = get_object_or_404(EventComment, id=comment_id) if not request.user.profile.can_edit_event(comment.event) and request.user.profile.id != comment.author.id: messages.add_message(request, messages.WARNING, message=_("You can not edit a comment that is not yours.")) return redirect(comment.event.get_absolute_url()) if request.method == 'POST': comment_form = EventCommentForm(request.POST, instance=comment) if comment_form.is_valid(): comment_form.save() return redirect(comment.event.get_absolute_url()+'#comment-%s'%comment.id) else: messages.add_message(request, messages.ERROR, message=_("Error updating comment.")) return redirect(comment.event.get_absolute_url()) @login_required def delete_comment(request, comment_id): comment = get_object_or_404(EventComment, id=comment_id) event = comment.event if not request.user.profile.can_edit_event(comment.event) and request.user.profile.id != comment.author.id: messages.add_message(request, messages.WARNING, message=_('You can not make delete this comment.')) return redirect(event.get_absolute_url()+"#comment-"+comment_id) if request.method == 'GET': form = DeleteCommentForm() context = { 'comment': comment, 'event': event, 'delete_form': form, } return render(request, 'get_together/events/delete_comment.html', context) elif request.method == 'POST': form = DeleteCommentForm(request.POST) if form.is_valid() and form.cleaned_data['confirm']: comment.delete() return redirect(event.get_absolute_url()) else: context = { 'comment': comment, 'event': event, 'delete_form': form, } return render(request, 'get_together/events/delete_comment.html', context) else: return redirect def send_comment_emails(comment): context = { 'comment': comment, 'site': Site.objects.get(id=1), } email_subject = 'New comment on: %s' % comment.event.name email_body_text = render_to_string('get_together/emails/events/event_comment.txt', context) email_body_html = render_to_string('get_together/emails/events/event_comment.html', context) email_from = getattr(settings, 'DEFAULT_FROM_EMAIL', 'noreply@gettogether.community') for attendee in comment.event.attendees.filter(user__account__is_email_confirmed=True): success = send_mail( from_email=email_from, html_message=email_body_html, message=email_body_text, recipient_list=[attendee.user.email], subject=email_subject, fail_silently=True, ) EmailRecord.objects.create( sender=comment.author.user, recipient=attendee.user, email=attendee.user.email, subject=email_subject, body=email_body_text, ok=success ) @login_required def add_event_photo(request, event_id): event = get_object_or_404(Event, id=event_id) if not request.user.profile.is_in_team(event.team): messages.add_message(request, messages.WARNING, message=_('You can not add photos this event.')) return redirect(event.get_absolute_url()) if not event.enable_photos: messages.add_message(request, messages.WARNING, message=_('This event does not allow uploading photos.')) return redirect(event.get_absolute_url()) if request.method == 'GET': form = UploadEventPhotoForm() context = { 'event': event, 'photo_form': form, } return render(request, 'get_together/events/add_photo.html', context) elif request.method == 'POST': new_photo = EventPhoto(event=event, uploader=request.user.profile) form = UploadEventPhotoForm(request.POST, request.FILES, instance=new_photo) if form.is_valid(): form.save() return redirect(event.get_absolute_url()) else: context = { 'event': event, 'photo_form': form, } return render(request, 'get_together/events/add_photo.html', context) else: return redirect('home') @login_required def remove_event_photo(request, photo_id): photo = get_object_or_404(EventPhoto, id=photo_id) event = photo.event if not request.user.profile.can_edit_event(event) and photo.uploader != request.user.profile: messages.add_message(request, messages.WARNING, message=_('You can not make changes to this photo.')) return redirect(event.get_absolute_url()) if request.method == 'GET': form = RemoveEventPhotoForm() context = { 'photo': photo, 'event': event, 'remove_form': form, } return render(request, 'get_together/events/remove_photo.html', context) elif request.method == 'POST': form = RemoveEventPhotoForm(request.POST) if form.is_valid() and form.cleaned_data['confirm']: photo.delete() return redirect(event.get_absolute_url()) else: return redirect('home') @login_required def add_place_to_event(request, event_id): event = get_object_or_404(Event, id=event_id) if not request.user.profile.can_edit_event(event): messages.add_message(request, messages.WARNING, message=_('You can not make changes to this event.')) return redirect(event.get_absolute_url()) if request.method == 'GET': form = NewPlaceForm() context = { 'event': event, 'place_form': form, } return render(request, 'get_together/places/create_place.html', context) elif request.method == 'POST': form = NewPlaceForm(request.POST) if form.is_valid: if request.POST.get('id', None): form.instance.id = request.POST.get('id') new_place = form.save() event.place = new_place event.save() if event.series is not None and event.series.place is None: event.series.place = new_place; event.series.save() return redirect(event.get_absolute_url()) else: context = { 'event': event, 'place_form': form, } return render(request, 'get_together/places/create_place.html', context) else: return redirect('home') @login_required def add_place_to_series(request, series_id): series = get_object_or_404(EventSeries, id=series_id) if not request.user.profile.can_edit_series(series): messages.add_message(request, messages.WARNING, message=_('You can not make changes to this event.')) return redirect(series.get_absolute_url()) if request.method == 'GET': form = NewPlaceForm() context = { 'series': series, 'place_form': form, } return render(request, 'get_together/places/add_place_to_series.html', context) elif request.method == 'POST': form = NewPlaceForm(request.POST) if form.is_valid: if request.POST.get('id', None): form.instance.id = request.POST.get('id') new_place = form.save() series.place = new_place series.save() return redirect('show-series', series.id, series.slug) else: context = { 'series': series, 'place_form': form, } return render(request, 'get_together/places/add_place_to_series.html', context) else: return redirect('home') @login_required def edit_event(request, event_id): event = get_object_or_404(Event, id=event_id) if not request.user.profile.can_edit_event(event): messages.add_message(request, messages.WARNING, message=_('You can not make changes to this event.')) return redirect(event.get_absolute_url()) if request.method == 'GET': form = TeamEventForm(instance=event) if event.series is not None: form.initial['recurrences'] = event.series.recurrences context = { 'team': event.team, 'event': event, 'event_form': form, } return render(request, 'get_together/events/edit_event.html', context) elif request.method == 'POST': form = TeamEventForm(request.POST,instance=event) if form.is_valid: new_event = form.save() if form.cleaned_data.get('recurrences', None): if event.series is not None: event.series.recurrences = form.cleaned_data['recurrences'] event.series.save() else: new_series = EventSeries.from_event(new_event, recurrences=form.cleaned_data['recurrences']) new_series.save() new_event.series = new_series new_event.save() else: if event.series is not None: old_series = event.series event.series = None event.save() if old_series.instances.count() < 1: old_series.delete() else: event.save() return redirect(new_event.get_absolute_url()) else: context = { 'team': event.team, 'event': event, 'event_form': form, } return render(request, 'get_together/events/edit_event.html', context) else: return redirect('home') @login_required def change_event_host(request, event_id): event = get_object_or_404(Event, id=event_id) if not request.user.profile.can_edit_event(event): messages.add_message(request, messages.WARNING, message=_('You can not change this event\'s host')) return redirect(event.get_absolute_url()) if request.method == 'GET': form = ChangeEventHostForm(instance=event) form.fields['team'].queryset = Team.objects.filter(member__user=request.user.profile, member__role__gte=Member.MODERATOR).order_by('name') context = { 'event': event, 'change_form': form, } return render(request, 'get_together/events/change_team.html', context) elif request.method == 'POST': form = ChangeEventHostForm(request.POST, instance=event) form.fields['team'].queryset = Team.objects.filter(member__user=request.user.profile, member__role__gte=Member.MODERATOR).order_by('name') if form.is_valid(): new_event = form.save() messages.add_message(request, messages.SUCCESS, message=_('Your event host has been changed.')) return redirect(new_event.get_absolute_url()) else: context = { 'event': event, 'change_form': form, } return render(request, 'get_together/orgs/request_to_join.html', context) else: return redirect('home') @login_required def delete_event(request, event_id): event = get_object_or_404(Event, id=event_id) if not request.user.profile.can_edit_event(event): messages.add_message(request, messages.WARNING, message=_('You can not make changes to this event.')) return redirect(event.get_absolute_url()) if request.method == 'GET': form = DeleteEventForm() context = { 'team': event.team, 'event': event, 'delete_form': form, } return render(request, 'get_together/events/delete_event.html', context) elif request.method == 'POST': form = DeleteEventForm(request.POST) if form.is_valid() and form.cleaned_data['confirm']: team_slug = event.team.slug delete_event_searchable(event) event.delete() return redirect('show-team-by-slug', team_slug) else: context = { 'team': event.team, 'event': event, 'delete_form': form, } return render(request, 'get_together/events/delete_event.html', context) else: return redirect('home') @login_required def cancel_event(request, event_id): event = get_object_or_404(Event, id=event_id) if not request.user.profile.can_edit_event(event): messages.add_message(request, messages.WARNING, message=_('You can not make changes to this event.')) return redirect(event.get_absolute_url()) if request.method == 'GET': form = CancelEventForm() context = { 'team': event.team, 'event': event, 'cancel_form': form, } return render(request, 'get_together/events/cancel_event.html', context) elif request.method == 'POST': form = CancelEventForm(request.POST) if form.is_valid() and form.cleaned_data['confirm']: event.status = Event.CANCELED event.save() send_cancellation_emails(event, form.cleaned_data['reason'], request.user) return redirect(event.get_absolute_url()) else: context = { 'team': event.team, 'event': event, 'cancel_form': form, } return render(request, 'get_together/events/cancel_event.html', context) else: return redirect('home') def send_cancellation_emails(event, reason, canceled_by): context = { 'event': event, 'reason': reason, 'by': canceled_by.profile, 'site': Site.objects.get(id=1), } email_subject = 'Event canceled: %s' % event.name email_body_text = render_to_string('get_together/emails/events/event_canceled.txt', context) email_body_html = render_to_string('get_together/emails/events/event_canceled.html', context) email_from = getattr(settings, 'DEFAULT_FROM_EMAIL', 'noreply@gettogether.community') for attendee in event.attendees.filter(user__account__is_email_confirmed=True): success = send_mail( from_email=email_from, html_message=email_body_html, message=email_body_text, recipient_list=[attendee.user.email], subject=email_subject, fail_silently=True, ) EmailRecord.objects.create( sender=canceled_by, recipient=attendee.user, email=attendee.user.email, subject=email_subject, body=email_body_text, ok=success ) @login_required def restore_event(request, event_id): event = get_object_or_404(Event, id=event_id) if not request.user.profile.can_edit_event(event): messages.add_message(request, messages.WARNING, message=_('You can not make changes to this event.')) return redirect(event.get_absolute_url()) event.status = Event.CONFIRMED event.save() return redirect(event.get_absolute_url()) @login_required def edit_series(request, series_id): series = get_object_or_404(EventSeries, id=series_id) if not request.user.profile.can_edit_series(series): messages.add_message(request, messages.WARNING, message=_('You can not make changes to this event.')) return redirect(series.get_absolute_url()) if request.method == 'GET': form = EventSeriesForm(instance=series) context = { 'team': series.team, 'series': series, 'series_form': form, } return render(request, 'get_together/events/edit_series.html', context) elif request.method == 'POST': form = EventSeriesForm(request.POST,instance=series) if form.is_valid: new_series = form.save() return redirect(new_series.get_absolute_url()) else: context = { 'team': event.team, 'series': series, 'series_form': form, } return render(request, 'get_together/events/edit_series.html', context) else: return redirect('home') @login_required def delete_series(request, series_id): series = get_object_or_404(EventSeries, id=series_id) if not request.user.profile.can_edit_series(series): messages.add_message(request, messages.WARNING, message=_('You can not make changes to this event.')) return redirect(series.get_absolute_url()) if request.method == 'GET': form = DeleteEventSeriesForm() context = { 'team': series.team, 'series': series, 'delete_form': form, } return render(request, 'get_together/events/delete_series.html', context) elif request.method == 'POST': form = DeleteEventSeriesForm(request.POST) if form.is_valid() and form.cleaned_data['confirm']: team_slug = series.team.slug series.delete() return redirect('show-team-by-slug', team_slug) else: context = { 'team': series.team, 'series': series, 'delete_form': form, } return render(request, 'get_together/events/delete_series.html', context) else: return redirect('home')
40.789419
159
0.643091
4a102d71d0b862c8bd7a54f36b0f0722b30a51eb
4,361
py
Python
src/planning/settings/base.py
stuttup/planning
0932a6af171a616ad3de50c343aed417ee25a222
[ "MIT" ]
null
null
null
src/planning/settings/base.py
stuttup/planning
0932a6af171a616ad3de50c343aed417ee25a222
[ "MIT" ]
null
null
null
src/planning/settings/base.py
stuttup/planning
0932a6af171a616ad3de50c343aed417ee25a222
[ "MIT" ]
null
null
null
""" Django settings for planning project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from django.core.urlresolvers import reverse_lazy from os.path import dirname, join, exists # Build paths inside the project like this: join(BASE_DIR, "directory") BASE_DIR = dirname(dirname(dirname(__file__))) STATICFILES_DIRS = [join(BASE_DIR, 'static')] MEDIA_ROOT = join(BASE_DIR, 'media') MEDIA_URL = "/media/" BOWER_COMPONENTS_ROOT = join(BASE_DIR, 'components') # Use Django templates using the new Django 1.8 TEMPLATES settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ join(BASE_DIR, 'templates'), # insert more TEMPLATE_DIRS here ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this # list if you haven't customized them: 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Use 12factor inspired environment variables or from a file import environ env = environ.Env() # Ideally move env file should be outside the git repo # i.e. BASE_DIR.parent.parent env_file = join(dirname(__file__), 'local.env') if exists(env_file): environ.Env.read_env(str(env_file)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ SECRET_KEY = env('SECRET_KEY') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.auth', 'django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authtools', 'crispy_forms', 'easy_thumbnails', 'profiles', 'accounts', 'djangobower', 'rooms', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'planning.urls' WSGI_APPLICATION = 'planning.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { # Raises ImproperlyConfigured exception if DATABASE_URL not in # os.environ 'default': env.db(), } # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'fr' TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/dev/howto/static-files/ STATIC_URL = '/static/' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'djangobower.finders.BowerFinder', ] ALLOWED_HOSTS = [] # Crispy Form Theme - Bootstrap 3 CRISPY_TEMPLATE_PACK = 'bootstrap3' # For Bootstrap 3, change error alert to 'danger' from django.contrib import messages MESSAGE_TAGS = { messages.ERROR: 'danger' } # Authentication Settings AUTH_USER_MODEL = 'authtools.User' LOGIN_REDIRECT_URL = reverse_lazy("profiles:show_self") LOGIN_URL = reverse_lazy("accounts:login") THUMBNAIL_EXTENSION = 'png' # Or any extn for your thumbnails # Bower dependancies BOWER_INSTALLED_APPS = ( 'jquery', 'fullcalendar', 'fullcalendar-scheduler', )
27.601266
74
0.711534
4a102e9c827376b727a4ac2009a82650bb7e9875
2,554
py
Python
backend/pyrogram/raw/types/update_message_poll_vote.py
appheap/social-media-analyzer
0f9da098bfb0b4f9eb38e0244aa3a168cf97d51c
[ "Apache-2.0" ]
5
2021-09-11T22:01:15.000Z
2022-03-16T21:33:42.000Z
backend/pyrogram/raw/types/update_message_poll_vote.py
iamatlasss/social-media-analyzer
429d1d2bbd8bfce80c50c5f8edda58f87ace668d
[ "Apache-2.0" ]
null
null
null
backend/pyrogram/raw/types/update_message_poll_vote.py
iamatlasss/social-media-analyzer
429d1d2bbd8bfce80c50c5f8edda58f87ace668d
[ "Apache-2.0" ]
3
2022-01-18T11:06:22.000Z
2022-02-26T13:39:28.000Z
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2021 Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pyrogram is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. from io import BytesIO from pyrogram.raw.core.primitives import Int, Long, Int128, Int256, Bool, Bytes, String, Double, Vector from pyrogram.raw.core import TLObject from pyrogram import raw from typing import List, Union, Any # # # # # # # # # # # # # # # # # # # # # # # # # !!! WARNING !!! # # This is a generated file! # # All changes made in this file will be lost! # # # # # # # # # # # # # # # # # # # # # # # # # class UpdateMessagePollVote(TLObject): # type: ignore """This object is a constructor of the base type :obj:`~pyrogram.raw.base.Update`. Details: - Layer: ``123`` - ID: ``0x42f88f2c`` Parameters: poll_id: ``int`` ``64-bit`` user_id: ``int`` ``32-bit`` options: List of ``bytes`` """ __slots__: List[str] = ["poll_id", "user_id", "options"] ID = 0x42f88f2c QUALNAME = "types.UpdateMessagePollVote" def __init__(self, *, poll_id: int, user_id: int, options: List[bytes]) -> None: self.poll_id = poll_id # long self.user_id = user_id # int self.options = options # Vector<bytes> @staticmethod def read(data: BytesIO, *args: Any) -> "UpdateMessagePollVote": # No flags poll_id = Long.read(data) user_id = Int.read(data) options = TLObject.read(data, Bytes) return UpdateMessagePollVote(poll_id=poll_id, user_id=user_id, options=options) def write(self) -> bytes: data = BytesIO() data.write(Int(self.ID, False)) # No flags data.write(Long(self.poll_id)) data.write(Int(self.user_id)) data.write(Vector(self.options, Bytes)) return data.getvalue()
31.530864
103
0.629601
4a102eb7d56be9c99be1a0ab70fd7a608b0c12ed
21,492
py
Python
test/oscprob3nu_plot.py
mbustama/NuOscProbExact
76c816e75a995fbeeb98b0249a7b9e03769aa12b
[ "MIT" ]
14
2019-04-30T01:40:45.000Z
2022-03-23T05:00:13.000Z
test/oscprob3nu_plot.py
mbustama/NuOscProbExact
76c816e75a995fbeeb98b0249a7b9e03769aa12b
[ "MIT" ]
1
2022-03-11T14:33:03.000Z
2022-03-11T14:33:03.000Z
test/oscprob3nu_plot.py
mbustama/NuOscProbExact
76c816e75a995fbeeb98b0249a7b9e03769aa12b
[ "MIT" ]
9
2019-04-30T16:47:25.000Z
2022-03-23T05:00:19.000Z
# -*- coding: utf-8 -*- r"""Routines to plot three-neutrino flavor-transition probabilities. This module contains contains routines to plot three-neutrino oscillation probabilities vs. the neutrino baseline and energy. These routines are used by run_testsuite.py to produce a suite of test plots. Routine listings ---------------- * plot_probability_3nu_vs_baseline - Plot probabilities vs. baseline * plot_probability_3nu_vs_energy - Plot probabilities vs. energy Created: 2019/04/17 17:14 Last modified: 2019/04/22 18:01 """ __version__ = "1.0" __author__ = "Mauricio Bustamante" __email__ = "mbustamante@gmail.com" from numpy import * import numpy as np from pylab import * from matplotlib import * import matplotlib as mpl import sys sys.path.append('../src') sys.path.append('../test') import oscprob3nu import hamiltonians3nu from globaldefs import * def plot_probability_3nu_vs_baseline( case, energy=1.e-1, log10_l_min=0.0, log10_l_max=3.0, log10_l_npts=6000, plot_prob_ee=True, plot_prob_em=True, plot_prob_et=True, plot_prob_me=False, plot_prob_mm=False, plot_prob_mt=False, plot_prob_te=False, plot_prob_tm=False, plot_prob_tt=False, output_filename='prob_vs_baseline', output_format='pdf', output_path='../fig/', legend_loc='center left', legend_ncol=1): r"""Generates and saves a plot of 3nu probabilities vs. baseline. Generates a plot of three-neutrino oscillation probabilities vs. baseline, for a fixed neutrino energy. The probabilities to be plotted are turned on and off via the flags plot_prob_ee, plot_prob_em, etc. (At least one of them must be True.) The parameter 'case' selects between 'vacuum', 'matter', 'nsi', and 'liv' (see below). The plot is saved with the provided name and file format under the specified path. Parameters ---------- case : str Not optional. Must be one of the following: 'vacuum', 'matter', 'nsi', or 'liv'. In each case, the probabilities are computed using the default parameter values pulled from globaldefs. energy : float, optional Neutrino energy [GeV]. log10_l_min : float, optional Log10 of the minimum baseline [km]. log10_l_max : float, optional Log10 of the maximum baseline [km]. log10_l_npts : int, optional Number of baseline values at which to compute the probabilities. plot_prob_ee : bool, optional True to plot Pee, False otherwise. plot_prob_em : bool, optional True to plot Pem, False otherwise. plot_prob_et : bool, optional True to plot Pet, False otherwise. plot_prob_me : bool, optional True to plot Pme, False otherwise. plot_prob_mm : bool, optional True to plot Pmm, False otherwise. plot_prob_mt : bool, optional True to plot Pmt, False otherwise. plot_prob_te : bool, optional True to plot Pte, False otherwise. plot_prob_tm : bool, optional True to plot Ptm, False otherwise. plot_prob_tt : bool, optional True to plot Ptt, False otherwise. output_filename : str, optional File name of plot to save (without the file extension). output_format : str, optional File extension of the plot to save (e.g., 'pdf', 'png', 'jpg'). output_path : str, optional File path where to save the plot. legend_loc : str, optional Location of the legend in the plot. Must be one of the allowed values of the plot routine of matplotlib. legend_ncol : int, optional Number of columns to include in the legend box. Must be at least 1. Returns ------- None The plot is generated and saved. """ if (not plot_prob_ee) and (not plot_prob_em) and (not plot_prob_et) \ and (not plot_prob_me) and (not plot_prob_mm) and (not plot_prob_mt) \ and (not plot_prob_te) and (not plot_prob_tm) and (not plot_prob_tt): quit() # Baselines, L log10_l_val = np.linspace(log10_l_min, log10_l_max, log10_l_npts) l_val =[10.**x for x in log10_l_val] h_vacuum_energy_independent = \ hamiltonians3nu.hamiltonian_3nu_vacuum_energy_independent( S12_NO_BF, S23_NO_BF, S13_NO_BF, DCP_NO_BF, D21_NO_BF, D31_NO_BF) if (case.lower() == 'vacuum'): hamiltonian = np.multiply(1./energy/1.e9, h_vacuum_energy_independent) label_case = r'Vacuum' elif (case.lower() == 'matter'): hamiltonian = hamiltonians3nu.hamiltonian_3nu_matter( \ h_vacuum_energy_independent, energy*1.e9, VCC_EARTH_CRUST) label_case = r'Matter' elif (case.lower() == 'nsi'): hamiltonian = hamiltonians3nu.hamiltonian_3nu_nsi( \ h_vacuum_energy_independent, energy*1.e9, VCC_EARTH_CRUST, EPS_3) label_case = r'NSI' elif (case.lower() == 'liv'): hamiltonian = hamiltonians3nu.hamiltonian_3nu_liv( \ h_vacuum_energy_independent, energy*1.e9, SXI12, SXI23, SXI13, DXICP, B1, B2, B3, LAMBDA) label_case = r'CPT-odd LIV' # Each element of prob: [Pee, Pem, Pet, Pme, Pmm, Pmt, Pte, Ptm, Ptt] prob = [oscprob3nu.probabilities_3nu( hamiltonian, l*CONV_KM_TO_INV_EV) \ for l in l_val] prob_ee = [x[0] for x in prob] prob_em = [x[1] for x in prob] prob_et = [x[2] for x in prob] prob_me = [x[3] for x in prob] prob_mm = [x[4] for x in prob] prob_mt = [x[5] for x in prob] prob_te = [x[6] for x in prob] prob_tm = [x[7] for x in prob] prob_tt = [x[8] for x in prob] # Formatting mpl.rcParams['xtick.labelsize']=26 mpl.rcParams['ytick.labelsize']=26 mpl.rcParams['legend.fontsize']=26 mpl.rcParams['legend.borderpad']=0.4 mpl.rcParams['axes.labelpad']=10 mpl.rcParams['ps.fonttype']=42 mpl.rcParams['pdf.fonttype']=42 fig = plt.figure(figsize=[9,9]) ax = fig.add_subplot(1,1,1) ax.set_xlabel(r'Baseline $L$ [km]', fontsize=25) ax.set_ylabel(r'Three-neutrino probability', fontsize=25) yaxis_minor_locator = mpl.ticker.MultipleLocator(0.1) ax.yaxis.set_minor_locator(yaxis_minor_locator) ax.tick_params('both', length=10, width=2, which='major') ax.tick_params('both', length=5, width=1, which='minor') ax.tick_params(axis='both', which='major', pad=10, direction='in') ax.tick_params(axis='both', which='minor', pad=10, direction='in') ax.tick_params(axis='x', which='minor', bottom=True) ax.tick_params(axis='x', which='minor', top=True) ax.tick_params(axis='y', which='minor', left=True) ax.tick_params(axis='y', which='minor', right=True) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.set_xlim([10.**log10_l_min, 10.**log10_l_max]) ax.set_xscale('log') ax.set_ylim([0.0, 1.0]) # Plot if (plot_prob_ee): ax.plot(l_val, prob_ee, label=r'$P_{\nu_e \to \nu_e}$', color='C0', zorder=1) if (plot_prob_em): ax.plot(l_val, prob_em, label=r'$P_{\nu_e \to \nu_\mu}$', color='C1', zorder=1) if (plot_prob_et): ax.plot(l_val, prob_et, label=r'$P_{\nu_e \to \nu_\tau}$', color='C2', zorder=1) if (plot_prob_me): ax.plot(l_val, prob_me, label=r'$P_{\nu_\mu \to \nu_e}$', color='C3', zorder=1) if (plot_prob_mm): ax.plot(l_val, prob_mm, label=r'$P_{\nu_\mu \to \nu_\mu}$', color='C4', zorder=1) if (plot_prob_mt): ax.plot(l_val, prob_mt, label=r'$P_{\nu_\mu \to \nu_\tau}$', color='C5', zorder=1) if (plot_prob_te): ax.plot(l_val, prob_te, label=r'$P_{\nu_\tau \to \nu_e}$', color='C6', zorder=1) if (plot_prob_tm): ax.plot(l_val, prob_tm, label=r'$P_{\nu_\tau \to \nu_\mu}$', color='C7', zorder=1) if (plot_prob_tt): ax.plot(l_val, prob_tt, label=r'$P_{\nu_\tau \to \nu_\tau}$', color='C8', zorder=1) # Legend ax.legend(loc=legend_loc, frameon=False, ncol=legend_ncol) # Annotations ax.annotate( label_case, xy = (0.05, 0.86), \ xycoords='axes fraction', color='k', fontsize=25, horizontalalignment='left', rotation=0, zorder=2 ) ax.annotate( r'$\log_{10}(E/{\rm GeV}) = $' + \ str(int(log10(energy)*100.)/100.), xy = (0.05, 0.80), xycoords='axes fraction', color='k', fontsize=25, horizontalalignment='left', rotation=0, zorder=2 ) pylab.savefig(output_path+output_filename+'.'+output_format, bbox_inches='tight', dpi=100) plt.close() return def plot_probability_3nu_vs_energy( case, baseline=1.3e3, log10_energy_min=-1.0, log10_energy_max=1.0, log10_energy_npts=200, plot_prob_ee=True, plot_prob_em=True, plot_prob_et=True, plot_prob_me=False, plot_prob_mm=False, plot_prob_mt=False, plot_prob_te=False, plot_prob_tm=False, plot_prob_tt=False, output_filename='prob_vs_energy', output_format='pdf', output_path='../fig/', legend_loc='center right', legend_ncol=1): r"""Generates and saves a plot of 3nu probabilities vs. energy. Generates a plot of three-neutrino oscillation probabilities vs. energy, for a fixed neutrino baseline. The probabilities to be plotted are turned on and off via the flags plot_prob_ee, plot_prob_em, etc. (At least one of them must be True.) The parameter 'case' selects between 'vacuum', 'matter', 'nsi', and 'liv' (see below). The plot is saved with the provided name and file format under the specified path. Parameters ---------- case : str Not optional. Must be one of the following: 'vacuum', 'matter', 'nsi', or 'liv'. In each case, the probabilities are computed using the default parameter values pulled from globaldefs. baseline : float, optional Neutrino baseline [km]. log10_energy_min : float, optional Log10 of the minimum energy [GeV]. log10_energy_max : float, optional Log10 of the maximum energy [GeV]. log10_energy_npts : int, optional Number of energy values at which to compute the probabilities. plot_prob_ee : bool, optional True to plot Pee, False otherwise. plot_prob_em : bool, optional True to plot Pem, False otherwise. plot_prob_et : bool, optional True to plot Pet, False otherwise. plot_prob_me : bool, optional True to plot Pme, False otherwise. plot_prob_mm : bool, optional True to plot Pmm, False otherwise. plot_prob_mt : bool, optional True to plot Pmt, False otherwise. plot_prob_te : bool, optional True to plot Pte, False otherwise. plot_prob_tm : bool, optional True to plot Ptm, False otherwise. plot_prob_tt : bool, optional True to plot Ptt, False otherwise. output_filename : str, optional File name of plot to save (without the file extension). output_format : str, optional File extension of the plot to save (e.g., 'pdf', 'png', 'jpg'). output_path : str, optional File path where to save the plot. legend_loc : str, optional Location of the legend in the plot. Must be one of the allowed values of the plot routine of matplotlib. legend_ncol : int, optional Number of columns to include in the legend box. Must be at least 1. Returns ------- None The plot is generated and saved. """ if (not plot_prob_ee) and (not plot_prob_em) and (not plot_prob_et) \ and (not plot_prob_me) and (not plot_prob_mm) and (not plot_prob_mt) \ and (not plot_prob_te) and (not plot_prob_tm) and (not plot_prob_tt): quit() baseline = baseline*CONV_KM_TO_INV_EV # [eV^{-1}] # Neutrino energies log10_energy_val = np.linspace( log10_energy_min, log10_energy_max, log10_energy_npts) energy_val =[10.**x for x in log10_energy_val] h_vacuum_energy_independent = \ hamiltonians3nu.hamiltonian_3nu_vacuum_energy_independent( S12_NO_BF, S23_NO_BF, S13_NO_BF, DCP_NO_BF, D21_NO_BF, D31_NO_BF) if (case.lower() == 'vacuum'): prob = [oscprob3nu.probabilities_3nu( \ np.multiply(1./energy/1.e9, h_vacuum_energy_independent), baseline) \ for energy in energy_val] label_case = r'Vacuum' elif (case.lower() == 'matter'): prob = [oscprob3nu.probabilities_3nu( \ hamiltonians3nu.hamiltonian_3nu_matter( \ h_vacuum_energy_independent, energy*1.e9, VCC_EARTH_CRUST), baseline) \ for energy in energy_val] label_case = r'Matter' elif (case.lower() == 'nsi'): prob = [oscprob3nu.probabilities_3nu( \ hamiltonians3nu.hamiltonian_3nu_nsi( \ h_vacuum_energy_independent, energy*1.e9, VCC_EARTH_CRUST, EPS_3), baseline) \ for energy in energy_val] label_case = r'NSI' elif (case.lower() == 'liv'): prob = [oscprob3nu.probabilities_3nu( \ hamiltonians3nu.hamiltonian_3nu_liv( \ h_vacuum_energy_independent, energy*1.e9, SXI12, SXI23, SXI13, DXICP, B1, B2, B3, LAMBDA), baseline) \ for energy in energy_val] label_case = r'CPT-odd LIV' # Each element of prob: [Pee, Pem, Pet, Pme, Pmm, Pmt, Pte, Ptm, Ptt] prob_ee = [x[0] for x in prob] prob_em = [x[1] for x in prob] prob_et = [x[2] for x in prob] prob_me = [x[3] for x in prob] prob_mm = [x[4] for x in prob] prob_mt = [x[5] for x in prob] prob_te = [x[6] for x in prob] prob_tm = [x[7] for x in prob] prob_tt = [x[8] for x in prob] # Formatting mpl.rcParams['xtick.labelsize']=26 mpl.rcParams['ytick.labelsize']=26 mpl.rcParams['legend.fontsize']=26 mpl.rcParams['legend.borderpad']=0.4 mpl.rcParams['axes.labelpad']=10 mpl.rcParams['ps.fonttype']=42 mpl.rcParams['pdf.fonttype']=42 fig = plt.figure(figsize=[9,9]) ax = fig.add_subplot(1,1,1) ax.set_xlabel(r'Neutrino energy $E$ [GeV]', fontsize=25) ax.set_ylabel(r'Three-neutrino probability', fontsize=25) yaxis_minor_locator = mpl.ticker.MultipleLocator(0.1) ax.yaxis.set_minor_locator(yaxis_minor_locator) ax.tick_params('both', length=10, width=2, which='major') ax.tick_params('both', length=5, width=1, which='minor') ax.tick_params(axis='both', which='major', pad=10, direction='in') ax.tick_params(axis='both', which='minor', pad=10, direction='in') ax.tick_params(axis='x', which='minor', bottom=True) ax.tick_params(axis='x', which='minor', top=True) ax.tick_params(axis='y', which='minor', left=True) ax.tick_params(axis='y', which='minor', right=True) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.set_xlim([10.**log10_energy_min, 10.**log10_energy_max]) ax.set_xscale('log') ax.set_ylim([0.0, 1.0]) # Plot if (plot_prob_ee): ax.plot(energy_val, prob_ee, label=r'$P_{\nu_e \to \nu_e}$', color='C0', zorder=1) if (plot_prob_em): ax.plot(energy_val, prob_em, label=r'$P_{\nu_e \to \nu_\mu}$', color='C1', zorder=1) if (plot_prob_et): ax.plot(energy_val, prob_et, label=r'$P_{\nu_e \to \nu_\tau}$', color='C2', zorder=1) if (plot_prob_me): ax.plot(energy_val, prob_me, label=r'$P_{\nu_\mu \to \nu_e}$', color='C3', zorder=1) if (plot_prob_mm): ax.plot(energy_val, prob_mm, label=r'$P_{\nu_\mu \to \nu_\mu}$', color='C4', zorder=1) if (plot_prob_mt): ax.plot(energy_val, prob_mt, label=r'$P_{\nu_\mu \to \nu_\tau}$', color='C5', zorder=1) if (plot_prob_te): ax.plot(energy_val, prob_te, label=r'$P_{\nu_\tau \to \nu_e}$', color='C6', zorder=1) if (plot_prob_tm): ax.plot(energy_val, prob_tm, label=r'$P_{\nu_\tau \to \nu_\mu}$', color='C7', zorder=1) if (plot_prob_tt): ax.plot(energy_val, prob_tt, label=r'$P_{\nu_\tau \to \nu_\tau}$', color='C8', zorder=1) # Legend ax.legend(loc=legend_loc, frameon=False, ncol=legend_ncol) # Annotations ax.annotate( label_case, xy = (0.05, 0.86), \ xycoords='axes fraction', color='k', fontsize=25, horizontalalignment='left', rotation=0, zorder=2 ) ax.annotate( r'$\log_{10}(L/{\rm km}) = $' + \ str(int(log10(baseline/CONV_KM_TO_INV_EV)*100.)/100.), xy = (0.05, 0.80), xycoords='axes fraction', color='k', fontsize=25, horizontalalignment='left', rotation=0, zorder=2 ) pylab.savefig(output_path+output_filename+'.'+output_format, bbox_inches='tight', dpi=100) plt.close() return def plot_probability_3nu_vacuum_vs_l_std(output_format='pdf'): # Best-fit values of mixing parameters, normal ordering, from 1708.01186 s12 = sqrt(3.21e-1) s23 = sqrt(4.30e-1) s13 = sqrt(2.155e-2) dCP = 1.4*np.pi # [rad] D21 = 7.56e-5 # [eV^2] D31 = 2.55e-3 # [eV^2] # Neutrino energy, E energy_nu = 1.e6 # [eV] # Baselines, L log10_l_min = 0.0 # [km] log10_l_max = log10(5.e2) # [km] log10_l_npts = 6000 log10_l_val = np.linspace(log10_l_min, log10_l_max, log10_l_npts) l_val =[10.**x for x in log10_l_val] U = pmns_mixing_matrix(s12, s23, s13, dCP) # Pee, Pem, Pet, Pme, Pmm, Pmt, Pte, Ptm, Ptt lst_prob = [probabilities_3nu_std( U, D21, D31, energy_nu, l/CONV_KM_TO_INV_EV) \ for l in l_val] lst_prob_ee = [x[0] for x in lst_prob] lst_prob_em = [x[1] for x in lst_prob] lst_prob_et = [x[2] for x in lst_prob] # Plot mpl.rcParams['xtick.labelsize']=26 mpl.rcParams['ytick.labelsize']=26 mpl.rcParams['legend.fontsize']=26 mpl.rcParams['legend.borderpad']=0.4 mpl.rcParams['axes.labelpad']=10 mpl.rcParams['ps.fonttype']=42 mpl.rcParams['pdf.fonttype']=42 fig = plt.figure(figsize=[9,9]) ax = fig.add_subplot(1,1,1) ax.set_xlabel(r'Baseline $L$ [km]', fontsize=25) ax.set_ylabel(r'Probability in vacuum ($E = 1$ MeV)', fontsize=25) yaxis_minor_locator = mpl.ticker.MultipleLocator(0.1) ax.yaxis.set_minor_locator(yaxis_minor_locator) ax.tick_params('both', length=10, width=2, which='major') ax.tick_params('both', length=5, width=1, which='minor') ax.tick_params(axis='both', which='major', pad=10, direction='in') ax.tick_params(axis='both', which='minor', pad=10, direction='in') ax.tick_params(axis='x', which='minor', bottom=True) ax.tick_params(axis='x', which='minor', top=True) ax.tick_params(axis='y', which='minor', left=True) ax.tick_params(axis='y', which='minor', right=True) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.set_xlim([10.**log10_l_min, 10.**log10_l_max]) ax.set_xscale('log') ax.set_ylim([0.0, 1.0]) # Plot ax.plot(l_val, lst_prob_ee, label=r'$P_{\nu_e \to \nu_e}$', color='C0', zorder=1) ax.plot(l_val, lst_prob_em, label=r'$P_{\nu_e \to \nu_\mu}$', color='C1', zorder=1) ax.plot(l_val, lst_prob_et, label=r'$P_{\nu_e \to \nu_\tau}$', color='C2', zorder=1) # Legend ax.legend(loc='center left', frameon=False, ncol=1) pylab.savefig('prob_3nu_vacuum_std_vs_l.'+output_format, bbox_inches='tight', dpi=300) return
38.724324
81
0.582217
4a102f2ef68dd46f3302b11915681d4ede4009a8
8,170
py
Python
nectar/theanoutil/model.py
Y0mingZhang/nectar
ca2bebdfedf46dfee9a2cb2d1bc82ad5c0871c93
[ "MIT" ]
null
null
null
nectar/theanoutil/model.py
Y0mingZhang/nectar
ca2bebdfedf46dfee9a2cb2d1bc82ad5c0871c93
[ "MIT" ]
null
null
null
nectar/theanoutil/model.py
Y0mingZhang/nectar
ca2bebdfedf46dfee9a2cb2d1bc82ad5c0871c93
[ "MIT" ]
null
null
null
"""Standard utilties for a theano model.""" import collections import numbers import numpy as np import pickle import random import sys import theano import time from tkinter import TclError from . import __init__ as ntu from .. import log, secs_to_str class TheanoModel(object): """A generic theano model. This class handles some standard boilerplate. Current features include: Basic training loop Saving and reloading of model An implementing subclass must override the following methods: self.__init__(*args, **kwargs) self.init_params() self.setup_theano_funcs() self.get_metrics(example) self.train_one(example, lr) self.evaluate(dataset) A basic self.__init__() routine is provided here, just as an example. Most users should override __init__() to perform additional functionality. See these methods for more details. """ def __init__(self): """A minimal example of what functions must be called during initialization. Implementing subclasses should override this method, but maintain the basic functionality presented here. """ # self.params, self.params_list, and self.param_names are required by self.create_matrix() self.params = {} self.param_list = [] self.param_names = [] # Initialize parameters self.init_params() # If desired, set up grad norm caches for momentum, AdaGrad, etc. here. # It must be after params are initialized but before theano functionss are created. # self.velocities = nt.create_grad_cache(self.param_list) # Set up theano functions self.theano_funcs = {} self.setup_theano_funcs() def init_params(self): """Initialize parameters with repeated calls to self.create_matrix().""" raise NotImplementedError def setup_theano_funcs(self): """Create theano.function objects for this model in self.theano_funcs.""" raise NotImplementedError def get_metrics(self, example): """Get accuracy metrics on a single example. Args: example: An example (possibly batch) lr: Current learning rate Returns: dictionary mapping metric_name to (value, weight); |weight| is used to compute weighted average over dataset. """ raise NotImplementedError def train_one(self, example, lr): """Run training on a single example. Args: example: An example (possibly batch) lr: Current learning rate Returns: dictionary mapping metric_name to (value, weight); |weight| is used to compute weighted average over dataset. """ raise NotImplementedError def create_matrix(self, name, shape, weight_scale, value=None): """A helper method that creates a parameter matrix.""" if value: pass elif shape: value = weight_scale * np.random.uniform(-1.0, 1.0, shape).astype( theano.config.floatX) else: # None means it's a scalar dtype = np.dtype(theano.config.floatX) value = dtype.type(weight_scale * np.random.uniform(-1.0, 1.0)) mat = theano.shared(name=name, value=value) self.params[name] = mat self.param_list.append(mat) self.param_names.append(name) def train(self, train_data, lr_init, epochs, dev_data=None, rng_seed=0, plot_metric=None, plot_outfile=None): """Train the model. Args: train_data: A list of training examples lr_init: Initial learning rate epochs: An integer number of epochs to train, or a list of integers, where we halve the learning rate after each period. dev_data: A list of dev examples, evaluate loss on this each epoch. rng_seed: Random seed for shuffling the dataset at each epoch. plot_metric: If True, plot a learning for the given metric. plot_outfile: If provided, save learning curve to file. """ random.seed(rng_seed) train_data = list(train_data) lr = lr_init if isinstance(epochs, numbers.Number): lr_changes = [] num_epochs = epochs else: lr_changes = set([sum(epochs[:i]) for i in range(1, len(epochs))]) num_epochs = sum(epochs) num_epochs_digits = len(str(num_epochs)) train_plot_list = [] dev_plot_list = [] str_len_dict = collections.defaultdict(int) len_time = 0 for epoch in range(num_epochs): t0 = time.time() random.shuffle(train_data) if epoch in lr_changes: lr *= 0.5 train_metric_list = [] for ex in train_data: cur_metrics = self.train_one(ex, lr) train_metric_list.append(cur_metrics) if dev_data: dev_metric_list = [self.get_metrics(ex) for ex in dev_data] else: dev_metric_list = [] t1 = time.time() # Compute the averaged metrics train_metrics = aggregate_metrics(train_metric_list) dev_metrics = aggregate_metrics(dev_metric_list) if plot_metric: train_plot_list.append(train_metrics[plot_metric]) if dev_metrics: dev_plot_list.append(dev_metrics[plot_metric]) # Some formatting to make things align in columns train_str = format_epoch_str('train', train_metrics, str_len_dict) dev_str = format_epoch_str('dev', dev_metrics, str_len_dict) metric_str = ', '.join(x for x in [train_str, dev_str] if x) time_str = secs_to_str(t1 - t0) len_time = max(len(time_str), len_time) log('Epoch %s: %s [lr = %.1e] [took %s]' % ( str(epoch+1).rjust(num_epochs_digits), metric_str, lr, time_str.rjust(len_time))) if plot_metric: plot_data = [('%s on train data' % plot_metric, train_plot_list)] if dev_plot_list: plot_data.append(('%s on dev data' % plot_metric, dev_plot_list)) try: ntu.plot_learning_curve(plot_data, outfile=plot_outfile) except TclError: print('Encoutered error while plotting learning curve', file=sys.stderr) def evaluate(self, dataset): """Evaluate the model.""" metrics_list = [self.get_metrics(ex) for ex in dataset] return aggregate_metrics(metrics_list) def save(self, filename): # Save tf = self.theano_funcs params = self.params param_list = self.param_list # Don't pickle theano functions self.theano_funcs = None # CPU/GPU portability self.params = {k: v.get_value() for k, v in params.items()} self.param_list = None # Any other things to do before saving saved = self._prepare_save() with open(filename, 'wb') as f: pickle.dump(self, f) # Restore self.theano_funcs = tf self.params = params self.param_list = param_list self._after_save(saved) def _prepare_save(self): """Any additional things before calling pickle.dump().""" pass def _after_save(self, saved): """Any additional things after calling pickle.dump().""" pass @classmethod def load(cls, filename): with open(filename, 'rb') as f: model = pickle.load(f) # Recreate theano shared variables params = model.params model.params = {} model.param_list = [] for name in model.param_names: value = params[name] mat = theano.shared(name=name, value=value) model.params[name] = mat model.param_list.append(mat) model._after_load() # Recompile theano functions model.theano_funcs = {} model.setup_theano_funcs() return model def _after_load(self): """Any additional things after calling pickle.load().""" pass def aggregate_metrics(metric_list): metrics = collections.OrderedDict() if metric_list: keys = list(metric_list[0].keys()) for k in keys: numer = sum(x[k][0] * x[k][1] for x in metric_list) denom = sum(x[k][1] for x in metric_list) metrics[k] = float(numer) / denom return metrics def format_epoch_str(name, metrics, str_len_dict): if not metrics: return '' toks = [] for k in metrics: val_str = '%.4f' % metrics[k] len_key = '%s:%s' % (name, k) str_len_dict[len_key] = max(str_len_dict[len_key], len(val_str)) cur_str = '%s=%s' % (k, val_str.rjust(str_len_dict[len_key])) toks.append(cur_str) return '%s(%s)' % (name, ', '.join(toks))
32.165354
94
0.673929
4a103193f94515ec2f023399574112431af531a2
2,089
py
Python
certbot-dns-cloudxns/setup.py
singhdeepu/certificateprovider
ed2168aaa8c8a7e1bef449e60167b53d501d173a
[ "Apache-2.0" ]
null
null
null
certbot-dns-cloudxns/setup.py
singhdeepu/certificateprovider
ed2168aaa8c8a7e1bef449e60167b53d501d173a
[ "Apache-2.0" ]
808
2018-11-09T05:14:26.000Z
2021-08-03T05:26:10.000Z
certbot-dns-cloudxns/setup.py
singhdeepu/certificateprovider
ed2168aaa8c8a7e1bef449e60167b53d501d173a
[ "Apache-2.0" ]
null
null
null
import sys from setuptools import setup from setuptools import find_packages version = '0.21.0.dev0' # Please update tox.ini when modifying dependency version requirements install_requires = [ 'acme=={0}'.format(version), 'certbot=={0}'.format(version), 'dns-lexicon', 'mock', # For pkg_resources. >=1.0 so pip resolves it to a version cryptography # will tolerate; see #2599: 'setuptools>=1.0', 'zope.interface', ] docs_extras = [ 'Sphinx>=1.0', # autodoc_member_order = 'bysource', autodoc_default_flags 'sphinx_rtd_theme', ] setup( name='certbot-dns-cloudxns', version=version, description="CloudXNS DNS Authenticator plugin for Certbot", url='https://github.com/certbot/certbot', author="Certbot Project", author_email='client-dev@letsencrypt.org', license='Apache License 2.0', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Plugins', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Security', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Networking', 'Topic :: System :: Systems Administration', 'Topic :: Utilities', ], packages=find_packages(), include_package_data=True, install_requires=install_requires, extras_require={ 'docs': docs_extras, }, entry_points={ 'certbot.plugins': [ 'dns-cloudxns = certbot_dns_cloudxns.dns_cloudxns:Authenticator', ], }, test_suite='certbot_dns_cloudxns', )
30.275362
78
0.624222
4a103194f3f86c61093a0498b29d52e41aee3003
3,231
py
Python
certbot-compatibility-test/certbot_compatibility_test/configurators/nginx/common.py
lpmitchell/certbot
fe0c0dc3ae6c25c6087e51717a223f38a9b23d2f
[ "Apache-2.0" ]
null
null
null
certbot-compatibility-test/certbot_compatibility_test/configurators/nginx/common.py
lpmitchell/certbot
fe0c0dc3ae6c25c6087e51717a223f38a9b23d2f
[ "Apache-2.0" ]
null
null
null
certbot-compatibility-test/certbot_compatibility_test/configurators/nginx/common.py
lpmitchell/certbot
fe0c0dc3ae6c25c6087e51717a223f38a9b23d2f
[ "Apache-2.0" ]
1
2022-03-31T07:54:20.000Z
2022-03-31T07:54:20.000Z
"""Provides a common base for Nginx proxies""" import os import shutil import subprocess from typing import Set from typing import Tuple from certbot_compatibility_test import errors from certbot_compatibility_test import util from certbot_compatibility_test.configurators import common as configurators_common from certbot_nginx._internal import configurator from certbot_nginx._internal import constants from certbot import configuration class Proxy(configurators_common.Proxy): """A common base for Nginx test configurators""" def load_config(self) -> str: """Loads the next configuration for the plugin to test""" config = super().load_config() self._all_names, self._test_names = _get_names(config) server_root = _get_server_root(config) # XXX: Deleting all of this is kind of scary unless the test # instances really each have a complete configuration! shutil.rmtree("/etc/nginx") shutil.copytree(server_root, "/etc/nginx", symlinks=True) self._prepare_configurator() try: subprocess.check_call("service nginx reload".split()) except errors.Error: raise errors.Error( "Nginx failed to load {0} before tests started".format( config)) return config def _prepare_configurator(self) -> None: """Prepares the Nginx plugin for testing""" for k in constants.CLI_DEFAULTS: setattr(self.le_config, "nginx_" + k, constants.os_constant(k)) conf = configuration.NamespaceConfig(self.le_config) self._configurator = configurator.NginxConfigurator(config=conf, name="nginx") self._configurator.prepare() def cleanup_from_tests(self) -> None: """Performs any necessary cleanup from running plugin tests""" def _get_server_root(config: str) -> str: """Returns the server root directory in config""" subdirs = [ name for name in os.listdir(config) if os.path.isdir(os.path.join(config, name))] if len(subdirs) != 1: raise errors.Error("Malformed configuration directory {0}".format(config)) return os.path.join(config, subdirs[0].rstrip()) def _get_names(config: str) -> Tuple[Set[str], Set[str]]: """Returns all and testable domain names in config""" all_names: Set[str] = set() for root, _dirs, files in os.walk(config): for this_file in files: update_names = _get_server_names(root, this_file) all_names.update(update_names) non_ip_names = set(n for n in all_names if not util.IP_REGEX.match(n)) return all_names, non_ip_names def _get_server_names(root: str, filename: str) -> Set[str]: """Returns all names in a config file path""" all_names = set() with open(os.path.join(root, filename)) as f: for line in f: if line.strip().startswith("server_name"): names = line.partition("server_name")[2].rpartition(";")[0] for n in names.split(): # Filter out wildcards in both all_names and test_names if not n.startswith("*."): all_names.add(n) return all_names
35.505495
86
0.662953
4a10322dfd2f6b2d7093c0438917071792e81daf
101,029
py
Python
macmini-liz/anode/src/main/python/anode/plugin/plugin.py
ggear/asystem
c949a1624812eab5b063681f46a88ccc9527266e
[ "Apache-2.0" ]
4
2019-03-26T13:57:54.000Z
2021-11-04T04:55:49.000Z
macmini-liz/anode/src/main/python/anode/plugin/plugin.py
ggear/asystem
c949a1624812eab5b063681f46a88ccc9527266e
[ "Apache-2.0" ]
1
2021-04-03T01:10:11.000Z
2021-04-03T01:10:11.000Z
macmini-liz/anode/src/main/python/anode/plugin/plugin.py
ggear/asystem
c949a1624812eab5b063681f46a88ccc9527266e
[ "Apache-2.0" ]
2
2019-04-02T19:20:34.000Z
2019-08-13T16:39:52.000Z
from __future__ import print_function import sys sys.path.append('./main/python') import HTMLParser import StringIO import abc import base64 import calendar import datetime import decimal import io import json import logging import numbers import operator import os.path import re import shutil import time import urllib from StringIO import StringIO from collections import deque from decimal import Decimal from functools import reduce from importlib import import_module from uuid import getnode as get_mac import avro import avro.io import avro.schema import avro.schema import dill import matplotlib import matplotlib.pyplot as plot import numpy import pandas import treq import xmltodict from avro.io import AvroTypeException from cycler import cycler from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from sklearn.externals import joblib from twisted.internet.task import Clock from twisted_s3 import auth import anode import anode.plugin from anode.application import * # noinspection PyTypeChecker,PyUnboundLocalVariable class Plugin(object): def poll(self): if self.has_poll: log_timer = anode.Log(logging.DEBUG).start() self._poll() log_timer.log("Plugin", "timer", lambda: "[{}]".format(self.name), context=self.poll) def push(self, content, targets=None): if self.has_push: log_timer = anode.Log(logging.DEBUG).start() self._push(content, targets) log_timer.log("Plugin", "timer", lambda: "[{}]".format(self.name), context=self.push) def repeat(self, force=False): log_timer = anode.Log(logging.DEBUG).start() for datum_metric in self.datums: for datum_type in self.datums[datum_metric]: for datum_unit in self.datums[datum_metric][datum_type]: for datum_bin in self.datums[datum_metric][datum_type][datum_unit]: datums = self.datums[datum_metric][datum_type][datum_unit][datum_bin] if DATUM_QUEUE_LAST in datums and DATUM_QUEUE_HISTORY in datums: datum = datums[DATUM_QUEUE_LAST] if datum["data_temporal"] != "derived": datum_bin_timestamp = self.get_time() if force and "history_partition_seconds" in self.config and self.config["history_partition_seconds"] > 0: datum_bin_timestamp = self.get_time_period(datum_bin_timestamp, Plugin.get_seconds( self.config["history_partition_seconds"], "second")) if force or ((24 * 60 * 60) > (datum_bin_timestamp - datum["bin_timestamp"]) >= ( self.config["repeat_seconds"] - 5)): def expired_max_min(max_or_min): if max_or_min in self.datums[datum_metric][datum_type][datum_unit][datum_bin]: if force or datums[max_or_min]["bin_timestamp"] < \ self.get_time_period(self.get_time(), Plugin.get_seconds(datums[max_or_min]["bin_width"], datums[max_or_min]["bin_unit"])): return True return False datum_value = datum["data_value"] if force and "history_partition_seconds" in self.config and self.config[ "history_partition_seconds"] > 0 and \ Plugin.get_seconds(datum["bin_width"], datum["bin_unit"]) == \ Plugin.get_seconds(self.config["history_partition_seconds"], "second"): if datum["data_type"] == "integral": datum_value = 0 if datum_value is not None: self.datum_push( datum["data_metric"], "forecast" if datum["data_temporal"] == "forecast" else "repeat", datum["data_type"], datum_value, datum["data_unit"], datum["data_scale"], datum["data_timestamp"], datum_bin_timestamp, datum["bin_width"], datum["bin_unit"], data_string=datum["data_string"] if "data_string" in datum else None, data_derived_max=expired_max_min(DATUM_QUEUE_MAX), data_derived_min=expired_max_min(DATUM_QUEUE_MIN), data_derived_force=force, data_push_force=True ) self.publish() log_timer.log("Plugin", "timer", lambda: "[{}]".format(self.name), context=self.repeat) def publish(self): metric_name = "anode__" + self.name + "__" time_now = self.get_time() metrics_count = sum(len(units) for metrics in self.datums.values() for types in metrics.values() for units in types.values()) self.datum_push( metric_name + "metrics", "current", "point", self.datum_value(metrics_count), "scalar", 1, time_now, time_now, self.config["poll_seconds"], "second", data_bound_lower=0, data_transient=True ) datums_buffer_count = sum(len(bins[DATUM_QUEUE_BUFFER]) for metrics in self.datums.values() for types in metrics.values() for units in types.values() for bins in units.values()) self.datum_push( metric_name + "buffer", "current", "point", self.datum_value(0 if metrics_count == 0 else (float(datums_buffer_count) / (self.datums_buffer_batch * metrics_count) * 100)), "_P25", 1, time_now, time_now, self.config["poll_seconds"], "second", data_bound_upper=100, data_bound_lower=0, data_transient=True ) datums_count = sum(0 if DATUM_QUEUE_HISTORY not in bins else ( sum(len(partitions["data_df"].index) for partitions in bins[DATUM_QUEUE_HISTORY].values())) for metrics in self.datums.values() for types in metrics.values() for units in types.values() for bins in units.values()) self.datum_push( metric_name + "history", "current", "point", self.datum_value(0 if ("history_ticks" not in self.config or self.config["history_ticks"] < 1) else ( float(datums_count) / self.config["history_ticks"] * 100)), "_P25", 1, time_now, time_now, self.config["poll_seconds"], "second", data_bound_upper=100, data_bound_lower=0, data_transient=True ) partitions_count_max = 0 if len(self.datums) == 0 else (max(0 if DATUM_QUEUE_HISTORY not in bins else ( len(bins[DATUM_QUEUE_HISTORY])) for metrics in self.datums.values() for types in metrics.values() for units in types.values() for bins in units.values())) self.datum_push( metric_name + "partitions", "current", "point", self.datum_value(0 if ("history_partitions" not in self.config or self.config["history_partitions"] < 1) else ( float(partitions_count_max) / self.config["history_partitions"] * 100)), "_P25", 1, time_now, time_now, self.config["poll_seconds"], "second", data_bound_upper=100, data_bound_lower=0, data_transient=True ) self.datum_push( metric_name + "up_Dtime", "current", "point", self.datum_value((time_now - self.time_boot) / Decimal(24 * 60 * 60), factor=100), "d", 100, time_now, time_now, self.config["poll_seconds"], "second", data_bound_lower=0, data_transient=True ) self.datum_push( metric_name + "last_Dseen", "current", "point", self.datum_value(self.time_seen), "scalar", 1, time_now, time_now, self.config["poll_seconds"], "second", data_transient=True ) publish_service = self.config["publish_service"] if "publish_service" in self.config else None publish_batch_datum_topic = "dev/" if "SNAPSHOT" in APP_VERSION \ else "" + self.config["publish_batch_datum_topic"] if "publish_batch_datum_topic" in self.config else None datums_publish_len_sum = 0 for datum_metric in self.datums: for datum_type in self.datums[datum_metric]: for datum_unit in self.datums[datum_metric][datum_type]: for datum_bin in self.datums[datum_metric][datum_type][datum_unit]: datums_publish = self.datums[datum_metric][datum_type][datum_unit][datum_bin][DATUM_QUEUE_PUBLISH] datums_publish_len = len(datums_publish) datums_publish_len_sum += datums_publish_len if publish_service is not None and publish_batch_datum_topic is not None: if publish_service.isConnected(): for index in xrange(datums_publish_len): datum_avro = datums_publish.popleft() anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] publishing datum [{}] datum [{}] of [{}]".format( self.name, self.datum_tostring(self.datum_avro_to_dict(datum_avro)[0]), index + 1, datums_publish_len)) publish_service.publishMessage(publish_batch_datum_topic + PUBLISH_BATCH_TOPIC, datum_avro, datums_publish, 1, False, lambda failure, message, queue: ( anode.Log(logging.WARN).log("Plugin", "state", lambda: "[{}] publish failed datum [{}] with reason {}".format( self.name, self.datum_tostring(self.datum_avro_to_dict(datum_avro)[0]), str(failure).replace("\n", ""))), queue.appendleft(message))) elif publish_service is None: datums_publish.clear() self.datum_push( metric_name + "queue", "current", "point", self.datum_value(len(datums_publish)), "datums", 1, time_now, time_now, self.config["poll_seconds"], "second", data_bound_lower=0, data_transient=True ) anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] batch publish queue length is [{}] datums" .format(self.name, datums_publish_len_sum)) def datum_push(self, data_metric, data_temporal, data_type, data_value, data_unit, data_scale, data_timestamp, bin_timestamp, bin_width, bin_unit, asystem_version=None, data_version=None, data_string=None, data_bound_upper=None, data_bound_lower=None, data_derived_max=False, data_derived_min=False, data_derived_period=1, data_derived_unit="day", data_derived_force=False, data_push_force=False, data_transient=False): log_timer = anode.Log(logging.DEBUG).start() if data_value is not None: datum_dict = { "asystem_version": APP_VERSION_COMPACT if asystem_version is None else Plugin.datum_version_encode(asystem_version), "data_version": 0 if data_version is None else Plugin.datum_version_encode(data_version, 1000), "data_source": self.name, "data_metric": data_metric, "data_temporal": data_temporal, "data_type": data_type, "data_value": data_value, "data_unit": data_unit, "data_scale": data_scale, "data_string": data_string, "data_timestamp": data_timestamp, "bin_timestamp": bin_timestamp, "bin_width": bin_width, "bin_unit": bin_unit } if data_bound_upper is not None and data_value > Decimal(data_bound_upper * data_scale): datum_dict["data_value"] = data_bound_upper * data_scale anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] upperbounded datum [{}]".format(self.name, self.datum_tostring(datum_dict))) if data_bound_lower is not None and data_value < Decimal(data_bound_lower * data_scale): datum_dict["data_value"] = data_bound_lower * data_scale anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] lowerbounded datum [{}]".format(self.name, self.datum_tostring(datum_dict))) try: datum_avro = self.datum_dict_to_avro(datum_dict)[0] except AvroTypeException as exception: anode.Log(logging.ERROR).log("Plugin", "error", lambda: "[{}] error serialising Avro object [{}]".format(self.name, datum_dict)) return if datum_dict["data_metric"] not in self.datums: self.datums[datum_dict["data_metric"]] = {} if datum_dict["data_type"] not in self.datums[datum_dict["data_metric"]]: self.datums[datum_dict["data_metric"]][datum_dict["data_type"]] = {} if datum_dict["data_unit"] not in self.datums[datum_dict["data_metric"]][datum_dict["data_type"]]: self.datums[datum_dict["data_metric"]][datum_dict["data_type"]][datum_dict["data_unit"]] = {} if str(datum_dict["bin_width"]) + datum_dict["bin_unit"] not in \ self.datums[datum_dict["data_metric"]][datum_dict["data_type"]][datum_dict["data_unit"]]: self.datums[datum_dict["data_metric"]][datum_dict["data_type"]][datum_dict["data_unit"]] \ [str(datum_dict["bin_width"]) + datum_dict["bin_unit"]] = { DATUM_QUEUE_PUBLISH: deque(maxlen=(None if "publish_ticks" not in self.config or self.config["publish_ticks"] < 1 else self.config["publish_ticks"])), DATUM_QUEUE_BUFFER: deque()} if not data_transient: self.datums[datum_dict["data_metric"]][datum_dict["data_type"]][datum_dict["data_unit"]][ str(datum_dict["bin_width"]) + datum_dict["bin_unit"]][DATUM_QUEUE_HISTORY] = {} datums_deref = self.datums[datum_dict["data_metric"]][datum_dict["data_type"]][datum_dict["data_unit"]][ str(datum_dict["bin_width"]) + datum_dict["bin_unit"]] if DATUM_QUEUE_LAST not in datums_deref or datums_deref[DATUM_QUEUE_LAST]["data_value"] != datum_dict["data_value"] or \ datums_deref[DATUM_QUEUE_LAST]["data_unit"] != datum_dict["data_unit"] or \ datums_deref[DATUM_QUEUE_LAST]["data_scale"] != datum_dict["data_scale"] or \ ("data_string" in datums_deref[DATUM_QUEUE_LAST] and datums_deref[DATUM_QUEUE_LAST]["data_string"] != datum_dict["data_string"]) or \ ("repeat_partition" in self.config and self.config["repeat_partition"] and self.get_time_period(datums_deref[DATUM_QUEUE_LAST]["bin_timestamp"], self.config["history_partition_seconds"]) != self.get_time_period(datum_dict["bin_timestamp"], self.config["history_partition_seconds"])) or data_push_force: self.time_seen = self.get_time() datums_deref[DATUM_QUEUE_LAST] = datum_dict bin_timestamp_derived = self.get_time_period(datum_dict["bin_timestamp"], Plugin.get_seconds(data_derived_period, data_derived_unit)) if not data_transient: if data_derived_max: if DATUM_QUEUE_MAX not in datums_deref or datums_deref[DATUM_QUEUE_MAX]["bin_timestamp"] < bin_timestamp_derived \ or datums_deref[DATUM_QUEUE_MAX]["data_value"] < datum_dict["data_value"] or data_derived_force: datums_deref[DATUM_QUEUE_MAX] = datum_dict.copy() datums_deref[DATUM_QUEUE_MAX]["bin_type"] = "high" datums_deref[DATUM_QUEUE_MAX]["bin_timestamp"] = bin_timestamp_derived datums_deref[DATUM_QUEUE_MAX]["bin_width"] = data_derived_period datums_deref[DATUM_QUEUE_MAX]["bin_unit"] = data_derived_unit anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] selected high [{}]".format( self.name, self.datum_tostring(datums_deref[DATUM_QUEUE_MAX]))) self.datum_push(data_metric, "derived", "high", datum_dict["data_value"], data_unit, data_scale, datum_dict["data_timestamp"], datums_deref[DATUM_QUEUE_MAX]["bin_timestamp"], datum_dict["bin_width"] if datum_dict["data_type"] == "integral" else data_derived_period, datum_dict["bin_unit"] if datum_dict["data_type"] == "integral" else data_derived_unit, asystem_version=asystem_version, data_version=data_version, data_derived_force=data_derived_force, data_push_force=data_push_force, data_transient=data_transient) if data_derived_min: if DATUM_QUEUE_MIN not in datums_deref or datums_deref[DATUM_QUEUE_MIN]["bin_timestamp"] < bin_timestamp_derived \ or datums_deref[DATUM_QUEUE_MIN]["data_value"] > datum_dict["data_value"] or data_derived_force: datums_deref[DATUM_QUEUE_MIN] = datum_dict.copy() datums_deref[DATUM_QUEUE_MIN]["bin_type"] = "low" datums_deref[DATUM_QUEUE_MIN]["bin_timestamp"] = bin_timestamp_derived datums_deref[DATUM_QUEUE_MIN]["bin_width"] = data_derived_period datums_deref[DATUM_QUEUE_MIN]["bin_unit"] = data_derived_unit anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] deleted low [{}]".format(self.name, self.datum_tostring( datums_deref[DATUM_QUEUE_MIN]))) self.datum_push(data_metric, "derived", "low", datum_dict["data_value"], data_unit, data_scale, datum_dict["data_timestamp"], datums_deref[DATUM_QUEUE_MIN]["bin_timestamp"], datum_dict["bin_width"] if datum_dict["data_type"] == "integral" else data_derived_period, datum_dict["bin_unit"] if datum_dict["data_type"] == "integral" else data_derived_unit, asystem_version=asystem_version, data_version=data_version, data_derived_force=data_derived_force, data_push_force=data_push_force, data_transient=data_transient) if not datum_dict["data_temporal"] == "derived" and "publish_batch_datum_topic" in self.config: datums_deref[DATUM_QUEUE_PUBLISH].append(datum_avro) if "history_ticks" in self.config and self.config["history_ticks"] > 0 and \ "history_partitions" in self.config and self.config["history_partitions"] > 0 and \ "history_partition_seconds" in self.config and self.config["history_partition_seconds"] > 0: bin_timestamp_partition = self.get_time_period(datum_dict["bin_timestamp"], self.config["history_partition_seconds"]) if len(datums_deref[DATUM_QUEUE_BUFFER]) == self.datums_buffer_batch or bin_timestamp_partition \ not in datums_deref[DATUM_QUEUE_HISTORY]: self.datum_merge_buffer_history(datums_deref[DATUM_QUEUE_BUFFER], datums_deref[DATUM_QUEUE_HISTORY]) datums_deref[DATUM_QUEUE_BUFFER].append(datum_dict) anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] saved datum [{}]".format(self.name, self.datum_tostring(datum_dict))) anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] pushed datum [{}]".format(self.name, self.datum_tostring(datum_dict))) self.anode.push_datums({"dict": [datum_dict]}) if not datum_dict["data_metric"].startswith("anode") and \ datum_dict["data_type"] != "low" and \ datum_dict["data_type"] != "high" and \ datum_dict["bin_unit"] != "all_Dtime": publish_service = self.config["publish_service"] if "publish_service" in self.config else None topic_prefix = "dev/" if "SNAPSHOT" in APP_VERSION else "" publish_push_data_topic = (topic_prefix + self.config["publish_push_data_topic"]) \ if "publish_push_data_topic" in self.config else None publish_push_metadata_topic = (topic_prefix + self.config["publish_push_metadata_topic"]) \ if "publish_push_metadata_topic" in self.config else None if publish_service is not None and publish_push_data_topic is not None and publish_push_metadata_topic is not None: if publish_service.isConnected(): datum_dict_decoded = Plugin.datum_decode(datum_dict) datum_id = Plugin.datum_encode_id(datum_dict) datum_guid = Plugin.datum_encode_guid(datum_dict) datum_name = Plugin.datum_decode_label(datum_dict_decoded) datum_data_topic = "{}/sensor/anode/{}/state".format(publish_push_data_topic, datum_id) if datum_guid in PUBLISH_METADATA_CACHE and PUBLISH_METADATA_CACHE[datum_guid] != datum_id: anode.Log(logging.ERROR).log("Plugin", "error", lambda: "[{}] attempting to publish datum with GUID [{}] and ID [{}] " "when previously published with ID [{}]".format( self.name, datum_guid, datum_id, PUBLISH_METADATA_CACHE[datum_guid])) if datum_guid not in PUBLISH_METADATA_CACHE: datum_metadata_topic = "{}/sensor/anode/{}/config".format(publish_push_metadata_topic, datum_id) datum_metadata = { "unique_id": datum_id, "name": datum_name, "value_template": "{{value_json.value}}", "unit_of_measurement": datum_dict_decoded["data_unit"], "device": { "name": "ANode", "model": "ASystem", "manufacturer": "Jane and Graham", "identifiers": ID_HEX, "connections": [["mac", ID_HEX_STRING]], "sw_version": APP_MODEL_VERSION }, "qos": 1, "state_topic": datum_data_topic } publish_service.publishMessage(datum_metadata_topic, json.dumps(datum_metadata), None, 1, True, lambda failure, message, queue: ( anode.Log(logging.WARN).log("Plugin", "state", lambda: "[{}] publish failed datum metadata [{}] with reason {}".format( self.name, datum_metadata, str(failure).replace("\n", ""))), None)) PUBLISH_METADATA_CACHE[datum_guid] = datum_id datum_data = {"value": float(int(datum_dict["data_value"]) / Decimal(datum_dict["data_scale"]))} publish_service.publishMessage(datum_data_topic, json.dumps(datum_data), None, 1, False, lambda failure, message, queue: ( anode.Log(logging.WARN).log("Plugin", "state", lambda: "[{}] publish failed datum data [{}] with reason {}".format( self.name, datum_data, str(failure).replace("\n", ""))), None)) else: anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] dropped datum [{}]".format(self.name, self.datum_tostring(datum_dict))) log_timer.log("Plugin", "timer", lambda: "[{}]".format(self.name), context=self.datum_push) def datum_merge_buffer_history(self, datums_buffer, datums_history): log_timer = anode.Log(logging.DEBUG).start() if "history_ticks" in self.config and self.config["history_ticks"] > 0 and \ "history_partitions" in self.config and self.config["history_partitions"] > 0 and \ "history_partition_seconds" in self.config and self.config["history_partition_seconds"] > 0: bin_timestamp_partition_max = None if len(datums_buffer) > 0: datums_buffer_partition = {} for datum in datums_buffer: bin_timestamp_partition = self.get_time_period(datum["bin_timestamp"], self.config["history_partition_seconds"]) bin_timestamp_partition_max = bin_timestamp_partition if \ (bin_timestamp_partition_max is None or bin_timestamp_partition_max < bin_timestamp_partition) else \ bin_timestamp_partition_max if bin_timestamp_partition not in datums_buffer_partition: datums_buffer_partition[bin_timestamp_partition] = [] datums_buffer_partition[bin_timestamp_partition].append(datum) for bin_timestamp_partition, datums in datums_buffer_partition.iteritems(): datums_df = self.datums_dict_to_df(datums_buffer) if len(datums_df) != 1: raise ValueError("Assertion error merging mixed datum types when there should not be any!") datums_df = datums_df[0] if bin_timestamp_partition not in datums_history: datums_history[bin_timestamp_partition] = datums_df else: datums_history[bin_timestamp_partition]["data_df"] = pandas.concat( [datums_history[bin_timestamp_partition]["data_df"], datums_df["data_df"]], ignore_index=True) anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] merged buffer partition [{}]".format(self.name, bin_timestamp_partition)) datums_buffer.clear() if len(datums_history) > 0 and bin_timestamp_partition_max is not None: bin_timestamp_partition_lower = bin_timestamp_partition_max - \ (self.config["history_partitions"] - 1) * self.config["history_partition_seconds"] for bin_timestamp_partition_del in datums_history.keys(): if bin_timestamp_partition_del < bin_timestamp_partition_lower: del datums_history[bin_timestamp_partition_del] anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] purged expired partition [{}]".format(self.name, bin_timestamp_partition_del)) while len(datums_history) > self.config["history_partitions"] or \ sum(len(datums_df_cached["data_df"].index) for datums_df_cached in datums_history.itervalues()) > \ self.config["history_ticks"]: bin_timestamp_partition_del = min(datums_history.keys()) del datums_history[bin_timestamp_partition_del] anode.Log(logging.DEBUG).log("Plugin", "state", lambda: "[{}] purged upperbounded partition [{}]".format(self.name, bin_timestamp_partition_del)) log_timer.log("Plugin", "timer", lambda: "[{}] partitions [{}]".format(self.name, len(datums_history)), context=self.datum_merge_buffer_history) def datum_merge_history(self, datums_history, datum_filter): log_timer = anode.Log(logging.DEBUG).start() datums = [] if "history_ticks" in self.config and self.config["history_ticks"] > 0 and \ "history_partitions" in self.config and self.config["history_partitions"] > 0 and \ "history_partition_seconds" in self.config and self.config["history_partition_seconds"] > 0: datums_partitions = [] if "partitions" in datum_filter: datum_filter_partitions = 0 if not min(datum_filter["partitions"]).isdigit() else int(min(datum_filter["partitions"])) if datum_filter_partitions > 0 and len(datums_history) > 0: for datums_partition in sorted(datums_history.iterkeys())[( (len(datums_history) - datum_filter_partitions) if len(datums_history) > datum_filter_partitions else 0):]: datums_partitions.append(datums_history[datums_partition]["data_df"]) else: datums_partition_lower = DATUM_TIMESTAMP_MIN if "start" not in datum_filter else \ (self.get_time_period(int(min(datum_filter["start"])), self.config["history_partition_seconds"])) datums_partition_upper = DATUM_TIMESTAMP_MAX if "finish" not in datum_filter else \ (self.get_time_period(int(max(datum_filter["finish"])), self.config["history_partition_seconds"])) for datums_partition in sorted(datums_history.keys()): if datums_partition_upper >= datums_partition >= datums_partition_lower: datums_partitions.append(datums_history[datums_partition]["data_df"]) if len(datums_partitions) > 0: datums_partition_metadata = datums_history.itervalues().next().copy() if len(datums_partitions) == 1: datums_partition_metadata["data_df"] = datums_partitions[0].copy(deep=False) else: datums_partition_metadata["data_df"] = pandas.concat(datums_partitions, ignore_index=True) datums_partition_metadata["data_df"] = Plugin.datums_df_resample( Plugin.datums_df_filter(Plugin.datums_df_reindex(datums_partition_metadata["data_df"]), datum_filter), datum_filter) datums.append(datums_partition_metadata) log_timer.log("Plugin", "timer", lambda: "[{}]".format(self.name), context=self.datum_merge_history) return datums @staticmethod def datum_encode(datum_dict): datum_dict_encoded = datum_dict.copy() for field in ("data_source", "data_metric", "data_temporal", "data_type", "data_unit", "bin_unit"): datum_dict_encoded[field] = Plugin.datum_field_encode(datum_dict_encoded[field]) return datum_dict_encoded @staticmethod def datum_decode(datum_dict): datum_dict_decoded = datum_dict.copy() for field in ("data_source", "data_metric", "data_temporal", "data_type", "data_unit", "bin_unit"): datum_dict_decoded[field] = Plugin.datum_field_decode(datum_dict_decoded[field]) return datum_dict_decoded @staticmethod def datum_encode_id(datum_dict): datum_metric_tokens = datum_dict["data_metric"].split("__") datum_name = datum_metric_tokens[2] if len(datum_metric_tokens) > 1 else datum_dict["data_metric"] datum_domain = datum_metric_tokens[0] if len(datum_metric_tokens) > 1 else "" datum_group = datum_metric_tokens[1] if len(datum_metric_tokens) > 1 else "" datum_location = datum_metric_tokens[2].split("-")[0].title() if len(datum_metric_tokens) > 1 else "" datum_location = (datum_location if datum_location in DATUM_LOCATIONS else DATUM_LOCATION_DEFAULT).lower() return "__".join([ "anode", datum_name, datum_domain, datum_group, datum_location ]) @staticmethod def datum_encode_guid(datum_dict): return "_".join([ datum_dict["data_metric"], datum_dict["data_type"], datum_dict["data_unit"], datum_dict["bin_unit"], str(datum_dict["bin_width"])]) @staticmethod def datum_decode_label(datum_dict_decoded): datum_name = datum_dict_decoded["data_metric"].split(".")[2] datum_domain = datum_dict_decoded["data_metric"].split(".")[0] return (" ".join([ datum_name, datum_domain ])).replace("-", " ").title() @staticmethod def datum_tostring(datum_dict): datum_dict = Plugin.datum_decode(datum_dict) return "{}.{}.{}.{}{}.{}={}{}{}".format( datum_dict["data_source"], datum_dict["data_metric"], datum_dict["data_type"], datum_dict["bin_width"], datum_dict["bin_timestamp"], datum_dict["bin_unit"], int(datum_dict["data_value"]) / Decimal(datum_dict["data_scale"]), datum_dict["data_unit"], datum_dict["data_string"] if datum_dict["data_string"] is not None else "" ) def datum_get(self, datum_scope, data_metric, data_type, data_unit, bin_width, bin_unit, data_derived_period=None, data_derived_unit="day"): if data_metric in self.datums and data_type in self.datums[data_metric] and data_unit in self.datums[data_metric][data_type] and \ (str(bin_width) + bin_unit) in self.datums[data_metric][data_type][data_unit] and \ datum_scope in self.datums[data_metric][data_type][data_unit][str(bin_width) + bin_unit]: datum_dict = self.datums[data_metric][data_type][data_unit][str(bin_width) + bin_unit][datum_scope] return datum_dict if (data_derived_period is None or datum_dict["bin_timestamp"] == self.get_time_period(self.get_time(), Plugin.get_seconds(data_derived_period, data_derived_unit))) else None return None def datums_filter_get(self, datums_filtered, datum_filter): log_timer = anode.Log(logging.DEBUG).start() for datum_metric in self.datums: if Plugin.is_filtered(datum_filter, "metrics", datum_metric): for datum_type in self.datums[datum_metric]: if Plugin.is_filtered(datum_filter, "types", datum_type): for datum_unit in self.datums[datum_metric][datum_type]: if Plugin.is_filtered(datum_filter, "units", datum_unit, exact_match=True): for datum_bin in self.datums[datum_metric][datum_type][datum_unit]: if Plugin.is_filtered(datum_filter, "bins", datum_bin): datum_scopes = [DATUM_QUEUE_LAST] if "scope" not in datum_filter else datum_filter["scope"] for datum_scope in datum_scopes: if datum_scope in self.datums[datum_metric][datum_type][datum_unit][datum_bin]: datums = [] if datum_scope == DATUM_QUEUE_LAST: datums_format = "dict" datums = [self.datums[datum_metric][datum_type][datum_unit][datum_bin][datum_scope]] elif datum_scope == DATUM_QUEUE_HISTORY: self.datum_merge_buffer_history( self.datums[datum_metric][datum_type][datum_unit][datum_bin] [DATUM_QUEUE_BUFFER], self.datums[datum_metric][datum_type][datum_unit][datum_bin] [DATUM_QUEUE_HISTORY]) datums_format = "df" datums = self.datum_merge_history( self.datums[datum_metric][datum_type][datum_unit][datum_bin][DATUM_QUEUE_HISTORY], datum_filter) elif datum_scope == DATUM_QUEUE_PUBLISH: datums_format = "avro" datums = self.datums[datum_metric][datum_type][datum_unit][datum_bin][datum_scope] if datums_format not in datums_filtered: datums_filtered[datums_format] = [] datums_filtered[datums_format].extend(datums) log_timer.log("Plugin", "timer", lambda: "[{}]".format(self.name), context=self.datums_filter_get) return datums_filtered @staticmethod def datums_filter(datums_filtered, datum_filter, datums): log_timer = anode.Log(logging.DEBUG).start() for datum in Plugin.datum_to_format(datums, "dict")["dict"]: if Plugin.is_filtered(datum_filter, "metrics", datum["data_metric"]): if Plugin.is_filtered(datum_filter, "types", datum["data_type"]): if Plugin.is_filtered(datum_filter, "units", datum["data_unit"], exact_match=True): if Plugin.is_filtered(datum_filter, "bins", str(datum["bin_width"]) + datum["bin_unit"]): if "dict" not in datums_filtered: datums_filtered["dict"] = [] datums_filtered["dict"].append(datum) log_timer.log("Plugin", "timer", lambda: "[*]", context=Plugin.datums_filter) return datums_filtered @staticmethod def is_filtered(datum_filter, datum_filter_field, datum_field, exact_match=False): if datum_filter_field not in datum_filter: return True for datum_filter_field_value in datum_filter[datum_filter_field]: datum_filter_field_value = Plugin.datum_field_encode(datum_filter_field_value) if exact_match and datum_field == datum_filter_field_value or not exact_match and \ datum_field.find(datum_filter_field_value) != -1: return True return False @staticmethod def datums_sort(datums): return sorted(datums, key=lambda datum: ( "aaaaa" if datum["data_unit"] == "_P24" else "bbbbb" if datum["data_unit"] == "W" else "ccccc" if datum["data_unit"] == "Wh" else "ddddd" if datum["data_unit"] == "ms" else "eeeee" if datum["data_unit"] == "MB_P2Fs" else "eeeee" if datum["data_unit"] == "KB_P2Fs" else "fffff" if datum["data_unit"] == "_P25" else "zzzzz" + datum["data_unit"], datum["data_metric"], "aaaaa" if datum["data_type"] == "point" else "bbbbb" if datum["data_type"] == "mean" else "ccccc" if datum["data_type"] == "integral" else "ddddd" if datum["data_type"] == "low" else "eeeee" if datum["data_type"] == "high" else datum["data_type"], "aaaaa" if datum["bin_unit"] == "second" else "bbbbb" if datum["bin_unit"] == "minute" else "ccccc" if datum["bin_unit"] == "hour" else "ddddd" if datum["bin_unit"] == "day_Dtime" else "eeeee" if datum["bin_unit"] == "night_Dtime" else "fffff" if datum["bin_unit"] == "day" else "ggggg" if datum["bin_unit"] == "month" else "hhhhh" if datum["bin_unit"] == "year" else "iiiii", datum["bin_width"])) @staticmethod def datum_dict_to_avro(datum_dict): avro_writer = io.BytesIO() avro.io.DatumWriter(DATUM_SCHEMA_AVRO).write(datum_dict, avro.io.BinaryEncoder(avro_writer)) return [avro_writer.getvalue()] @staticmethod def datum_dict_to_json(datum_dict): datum_dict = Plugin.datum_decode(datum_dict) return [json.dumps(datum_dict, separators=(',', ':'))] @staticmethod def datum_dict_to_csv(datum_dict): datum_dict = datum_dict.copy() if datum_dict["data_unit"] not in DATUM_SCHEMA_TO_ASCII: DATUM_SCHEMA_TO_ASCII[datum_dict["data_unit"]] = urllib.quote_plus(datum_dict["data_unit"]) datum_dict["data_unit"] = DATUM_SCHEMA_TO_ASCII[datum_dict["data_unit"]] if datum_dict["bin_unit"] not in DATUM_SCHEMA_TO_ASCII: DATUM_SCHEMA_TO_ASCII[datum_dict["bin_unit"]] = urllib.quote_plus(datum_dict["bin_unit"]) datum_dict["bin_unit"] = DATUM_SCHEMA_TO_ASCII[datum_dict["bin_unit"]] return [','.join(str(datum_dict[datum_field]) for datum_field in DATUM_SCHEMA_MODEL.iterkeys())] @staticmethod def datum_dict_to_df(datum_dict): return Plugin.datums_dict_to_df([datum_dict]) @staticmethod def datum_df_to_dict(datum_df): datums_dict_df = Plugin.datums_df_unindex(datum_df["data_df"].copy(deep=False)) datums_dict = datums_dict_df.to_dict(orient="records") for datum_dict in datums_dict: # datum_dict["data_value"] = numpy.asscalar(datum_dict["data_value"]) # datum_dict["bin_timestamp"] = numpy.asscalar(datum_dict["bin_timestamp"]) # datum_dict["data_timestamp"] = numpy.asscalar(datum_dict["data_timestamp"]) datum_dict.update(datum_df) del datum_dict["data_df"] return datums_dict @staticmethod def datum_avro_to_dict(datum_avro): return [{datum_key.encode("utf-8"): (datum_value.encode("utf-8") if isinstance(datum_value, unicode) else datum_value) for datum_key, datum_value in avro.io.DatumReader(DATUM_SCHEMA_AVRO).read(avro.io.BinaryDecoder(io.BytesIO(datum_avro))).items()}] # noinspection PyUnusedLocal @staticmethod def datum_to_format(datums, datum_format, off_thread=False): log_timer = anode.Log(logging.DEBUG).start() count = 0 count_sum = sum(len(datums_values) for datums_values in datums.values()) if "dict" in datums and len(datums["dict"]) > 0: datums["dict"] = Plugin.datums_sort(datums["dict"]) log_timer.log("Plugin", "timer", lambda: "[*] count and sort for [{}] dict datums".format(len(datums["dict"])) if "dict" in datums else 0, context=Plugin.datum_to_format, off_thread=off_thread) log_timer = anode.Log(logging.DEBUG).start() datums_formatted = {datum_format: []} datum_to_format_iterate = False for datums_format, datums_value in datums.iteritems(): datums_format_function = None if datums_format == "dict": if datum_format == "avro": datums_format_function = Plugin.datum_dict_to_avro elif datum_format == "json": datums_format_function = Plugin.datum_dict_to_json elif datum_format == "csv": datums_format_function = Plugin.datum_dict_to_csv elif datum_format == "df": datums_format_function = Plugin.datum_dict_to_df elif datum_format != "dict": raise ValueError("Unknown datum format conversion [{}] to [{}]".format(datums_format, datum_format)) elif datums_format == "df" and datum_format == "dict": datums_format_function = Plugin.datum_df_to_dict elif datums_format != datum_format: datum_to_format_iterate = datum_format != "dict" if datums_format == "avro": datums_format_function = Plugin.datum_avro_to_dict else: raise ValueError("Unknown datum format conversion [{}] to [{}]".format(datums_format, datum_format)) if "dict" if datum_to_format_iterate else datum_format not in datums_formatted: datums_formatted["dict" if datum_to_format_iterate else datum_format] = [] if datums_format_function is None: datums_formatted["dict" if datum_to_format_iterate else datum_format].extend(datums_value) count += len(datums_value) else: for datum in datums_value: datums_formatted["dict" if datum_to_format_iterate else datum_format].extend(datums_format_function(datum)) count += 1 if count % SERIALISATION_BATCH == 0 or count == count_sum: if off_thread and count < count_sum: log_timer.pause() time.sleep(SERIALISATION_BATCH_SLEEP) log_timer.start() log_timer.log("Plugin", "timer", lambda: "[*] {} to {} for [{}] datums".format(",".join(datums.keys()), datum_format, count), context=Plugin.datum_to_format, off_thread=off_thread) return datums_formatted if not datum_to_format_iterate else Plugin.datum_to_format(datums_formatted, datum_format, off_thread) # noinspection PyArgumentList @staticmethod def datums_csv_to_dict(datums_csv): datums_dict = {"dict": []} for datum_dict in datums_csv: datum_dict["data_value"] = long(datum_dict["data_value"]) datum_dict["data_unit"] = HTMLParser.HTMLParser().unescape(datum_dict["data_unit"]) if datum_dict["data_unit"] not in DATUM_SCHEMA_FROM_ASCII: DATUM_SCHEMA_FROM_ASCII[datum_dict["data_unit"]] = \ urllib.unquote_plus(datum_dict["data_unit"].encode("utf-8")).decode("utf-8") datum_dict["data_scale"] = float(datum_dict["data_scale"]) datum_dict["data_timestamp"] = long(datum_dict["data_timestamp"]) datum_dict["bin_timestamp"] = long(datum_dict["bin_timestamp"]) datum_dict["bin_width"] = int(datum_dict["bin_width"]) if datum_dict["bin_unit"] not in DATUM_SCHEMA_FROM_ASCII: DATUM_SCHEMA_FROM_ASCII[datum_dict["bin_unit"]] = \ urllib.unquote_plus(datum_dict["bin_unit"].encode("utf-8")).decode("utf-8") datums_dict["dict"].append(datum_dict) return datums_dict @staticmethod def datums_dict_to_json(datums_dict, off_thread=False): log_timer = anode.Log(logging.DEBUG).start() count = 0 datums_json_fragments = [] for datum_dict in datums_dict: datums_json_fragments.append(Plugin.datum_dict_to_json(datum_dict)[0]) count += 1 if count % SERIALISATION_BATCH == 0 or count == len(datums_dict): datums_json_fragments = [",".join(datums_json_fragments)] if off_thread and count < len(datums_dict): log_timer.pause() time.sleep(SERIALISATION_BATCH_SLEEP) log_timer.start() datums_json = "".join(["[", "" if len(datums_json_fragments) == 0 else datums_json_fragments[0], "]"]) log_timer.log("Plugin", "timer", lambda: "[*]", context=Plugin.datums_dict_to_json, off_thread=off_thread) return datums_json @staticmethod def datums_dict_to_df(datums_dict, off_thread=False): log_timer = anode.Log(logging.DEBUG).start() datums_df = [] datums_data = {} datums_metadata = {} for datum_dict in datums_dict: datum_id = "_".join([datum_dict["data_metric"], datum_dict["data_type"], str(datum_dict["bin_width"]) + datum_dict["bin_unit"]]) if datum_id not in datums_metadata: datum_metadata = datum_dict.copy() del datum_metadata["bin_timestamp"] del datum_metadata["data_timestamp"] del datum_metadata["data_value"] datums_metadata[datum_id] = datum_metadata datums_data[datum_id] = [] datums_data[datum_id].append({"bin_timestamp": datum_dict["bin_timestamp"], "data_timestamp": datum_dict["data_timestamp"], "data_value": datum_dict["data_value"]}) for datum_id, datum_metadata in datums_metadata.iteritems(): datum_metadata["data_df"] = pandas.DataFrame(datums_data[datum_id]) datums_df.append(datum_metadata) log_timer.log("Plugin", "timer", lambda: "[*]", context=Plugin.datums_dict_to_df, off_thread=off_thread) return datums_df @staticmethod def datums_df_to_csv(datums_df, off_thread=False): log_timer = anode.Log(logging.DEBUG).start() datums_csv = datums_df.to_csv(index=False) log_timer.log("Plugin", "timer", lambda: "[*]", context=Plugin.datums_df_to_csv, off_thread=off_thread) return datums_csv @staticmethod def datums_df_to_svg(datums_df, off_thread=False): log_timer = anode.Log(logging.DEBUG).start() datums_plot_font_size = 14 datums_plot_alpha = 0.7 datums_plot_colour = "white" datums_plot_colour_foreground = "0.5" datums_plot_colour_background = "black" datums_plot_colour_lines = \ ["yellow", "lime", "red", "orange", "dodgerblue", "coral", "magenta", "aliceblue", "cyan", "darkgreen", "maroon"] datums_plot_title = datums_df.title if hasattr(datums_df, "title") else None datums_plot_buffer = StringIO() datums_df = Plugin.datums_df_reindex(datums_df) datums_points = len(datums_df.index) datums_axes_x_range = ((datums_df.index[-1] - datums_df.index[0]).total_seconds()) if datums_points > 0 else 0 if datums_points == 0 or datums_axes_x_range == 0: return SVG_EMPTY datums_figure = Figure() datums_axes = datums_figure.add_subplot(111) datums_axes.set_prop_cycle(cycler("color", datums_plot_colour_lines)) for column in datums_df: datums_axes.plot(datums_df.index, datums_df[column]) datums_axes.margins(0, 0, tight=True) datums_axes.minorticks_off() if datums_axes_x_range <= (10 + 2): datums_axes.xaxis.set_major_locator(matplotlib.dates.SecondLocator(interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M:%S")) elif datums_axes_x_range <= (60 + 2): datums_axes.xaxis.set_major_locator(matplotlib.dates.SecondLocator(bysecond=[0, 10, 20, 30, 40, 50], interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M:%S")) if datums_axes_x_range <= (60 * 2 + 2): datums_axes.xaxis.set_major_locator(matplotlib.dates.MinuteLocator(interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M")) if datums_axes_x_range <= (60 * 10 + 2): datums_axes.xaxis.set_major_locator( matplotlib.dates.MinuteLocator(byminute=[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55], interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M")) elif datums_axes_x_range <= (60 * 60 + 2): datums_axes.xaxis.set_major_locator(matplotlib.dates.MinuteLocator(byminute=[0, 10, 20, 30, 40, 50], interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M")) elif datums_axes_x_range <= (60 * 60 * 4 + 2): datums_axes.xaxis.set_major_locator(matplotlib.dates.MinuteLocator(byminute=[0, 30], interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M")) elif datums_axes_x_range <= (60 * 60 * 8 + 2): datums_axes.xaxis.set_major_locator(matplotlib.dates.HourLocator(interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M")) elif datums_axes_x_range <= (60 * 60 * 16 + 2): datums_axes.xaxis.set_major_locator( matplotlib.dates.HourLocator(byhour=[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22], interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M")) elif datums_axes_x_range <= (60 * 60 * 24 + 2): datums_axes.xaxis.set_major_locator(matplotlib.dates.HourLocator(byhour=[0, 4, 8, 12, 16, 20], interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M")) elif datums_axes_x_range <= (60 * 60 * 24 * 3 + 2): datums_axes.xaxis.set_major_locator(matplotlib.dates.HourLocator(byhour=[0, 8, 16], interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M")) elif datums_axes_x_range <= (60 * 60 * 24 * 14 + 2): datums_axes.xaxis.set_major_locator(matplotlib.dates.DayLocator(interval=1)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%a")) else: datums_axes.xaxis.set_major_locator(matplotlib.dates.DayLocator(interval=3)) datums_axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%a")) datums_axes.xaxis.label.set_visible(False) datums_axes.xaxis.label.set_color(datums_plot_colour) datums_axes.tick_params(axis="x", colors=datums_plot_colour) datums_axes.yaxis.tick_right() datums_axes.yaxis.label.set_color(datums_plot_colour) datums_axes.yaxis.grid(b=True, which="major", color=datums_plot_colour_foreground, linestyle='--') datums_axes.tick_params(axis="y", colors=datums_plot_colour) datums_axes.spines["bottom"].set_color(datums_plot_colour) datums_axes.spines["top"].set_color(datums_plot_colour) datums_axes.spines["left"].set_color(datums_plot_colour) datums_axes.spines["right"].set_color(datums_plot_colour) datums_axes.patch.set_facecolor(datums_plot_colour_background) if datums_plot_title is not None and (len(max(datums_df.columns.values, key=len)) + len(datums_plot_title)) > 40: datums_plot_legend = datums_axes.legend(loc="lower left", ncol=1) else: datums_plot_legend = datums_axes.legend(loc="upper left", ncol=1) if datums_plot_legend is not None: for datums_plot_legend_text in datums_plot_legend.get_texts(): datums_plot_legend_text.set_fontsize(datums_plot_font_size) datums_plot_legend_text.set_color(datums_plot_colour) datums_plot_legend.get_frame().set_alpha(datums_plot_alpha) datums_plot_legend.get_frame().set_edgecolor(datums_plot_colour_foreground) datums_plot_legend.get_frame().set_facecolor(datums_plot_colour_background) datums_figure.subplots_adjust(left=0, right=0.9, top=0.9725, bottom=0.08) datums_canvas = FigureCanvas(datums_figure) datums_canvas.draw() if datums_plot_title is not None: datums_axes.text(0.98, 0.975, datums_plot_title, horizontalalignment="right", verticalalignment="top", transform=datums_axes.transAxes, color=datums_plot_colour, fontsize=datums_plot_font_size, bbox=dict(facecolor=datums_plot_colour_background, edgecolor=datums_plot_colour_background, alpha=datums_plot_alpha, boxstyle="round,pad=0.2")) datums_axes_x_labels = [tick.get_text() for tick in datums_axes.get_xticklabels()] if len(datums_axes_x_labels) > 1: datums_axes_x_labels[0] = u"" datums_axes.set_xticklabels(datums_axes_x_labels) datums_axes.set_ylim([datums_axes.get_ylim()[0] * 0.9, datums_axes.get_ylim()[1] * 1.15]) datums_figure.set_size_inches(6, 3.35) datums_canvas.print_figure(datums_plot_buffer, facecolor=datums_plot_colour_background, format="svg") datums_figure.clf() plot.close() del datums_canvas del datums_figure del datums_df datums_plot_buffer.seek(0) log_timer.log("Plugin", "timer", lambda: "[*]", context=Plugin.datums_df_to_svg, off_thread=off_thread) return datums_plot_buffer.buf @staticmethod def datums_df_to_df(datums_df, datum_options=None, off_thread=False): log_timer = anode.Log(logging.DEBUG).start() datums_df_df = [] if len(datums_df) > 0: log_timer_input = anode.Log(logging.DEBUG).start() datums_df_groups = {} for datums_df_dict in datums_df: datums_df_dict_decoded = Plugin.datum_decode(datums_df_dict) if datums_df_dict_decoded["data_unit"] not in DATUM_SCHEMA_TO_ASCII: DATUM_SCHEMA_TO_ASCII[datums_df_dict_decoded["data_unit"]] = urllib.quote_plus(datums_df_dict_decoded["data_unit"]) if datums_df_dict["bin_unit"] not in DATUM_SCHEMA_TO_ASCII: DATUM_SCHEMA_TO_ASCII[datums_df_dict_decoded["bin_unit"]] = urllib.quote_plus(datums_df_dict_decoded["bin_unit"]) datum_name = "&".join( ["metrics=" + datums_df_dict_decoded["data_metric"], "types=" + datums_df_dict_decoded["data_type"], "bins=" + str(datums_df_dict_decoded["bin_width"]) + DATUM_SCHEMA_TO_ASCII[datums_df_dict_decoded["bin_unit"]], "unit=" + DATUM_SCHEMA_TO_ASCII[datums_df_dict_decoded["data_unit"]], "scale=" + str(datums_df_dict_decoded["data_scale"]), "temporal=" + datums_df_dict_decoded["data_temporal"], "source=" + datums_df_dict_decoded["data_source"], "anode_id=" + ID_BASE64 ] ).decode("utf-8") if datum_name not in datums_df_groups: datums_df_groups[datum_name] = datums_df_dict.copy() datums_df_groups[datum_name]["data_df"] = [datums_df_dict["data_df"]] else: datums_df_groups[datum_name]["data_df"].append(datums_df_dict["data_df"]) log_timer_input.log("Plugin", "timer", lambda: "[*] input [{}] dataframes and [{}] datums".format( len(datums_df), sum(len(datums_df_value["data_df"].index) for datums_df_value in datums_df)), context=Plugin.datums_df_to_df, off_thread=off_thread) log_timer_intermediate = anode.Log(logging.DEBUG).start() datums_df_groups_concat = {} datums_df_groups_concat_data = [] for datum_name, datums_df_dict in datums_df_groups.iteritems(): datums_df_dict_df = pandas.concat(datums_df_dict["data_df"]) datums_df_dict_df = Plugin.datums_df_reindex(datums_df_dict_df) datums_df_dict_df["data_value"] = (datums_df_dict_df["data_value"] / datums_df_dict["data_scale"]).astype( numpy.dtype(decimal.Decimal)) datums_df_dict_df.rename( columns={"data_timestamp": "data_timestamp@" + datum_name, "data_value": "data_value_scaled@" + datum_name}, inplace=True) datums_df_groups_concat_data.append("data_value_scaled@" + datum_name) datums_df_groups_concat[datum_name] = datums_df_dict_df datum_df = pandas.concat(datums_df_groups_concat.values(), axis=1, join="outer") log_timer_intermediate.log("Plugin", "timer", lambda: "[*] intermediate [{}] dataframes and [{}] datums".format( len(datums_df_groups_concat), sum(len(datums_df_groups_concat_df.index) for datums_df_groups_concat_df in datums_df_groups_concat.values())), context=Plugin.datums_df_to_df, off_thread=off_thread) log_timer_output = anode.Log(logging.DEBUG).start() datum_df = Plugin.datums_df_unindex( Plugin.datums_df_fill( Plugin.datums_df_resample(datum_df, datum_options), datums_df_groups_concat_data, datum_options)) if "print" in datum_options and datum_options["print"][0] == "pretty": datum_df = Plugin.datums_df_metadata_pretty(Plugin.datums_df_data_pretty(datum_df)) datums_df_df.append(datum_df) log_timer_output.log("Plugin", "timer", lambda: "[*] output [{}] dataframes and [{}] datums".format( len(datums_df_df), sum(response_df[response_df_column].count() for response_df in datums_df_df for response_df_column in response_df if response_df_column.startswith("data_value"))), context=Plugin.datums_df_to_df, off_thread=off_thread) log_timer.log("Plugin", "timer", lambda: "[*]", context=Plugin.datums_df_to_df, off_thread=off_thread) return datums_df_df @staticmethod def datums_to_format(datums, datum_format, datum_options, off_thread=False): log_timer = anode.Log(logging.DEBUG).start() datums_count = 0 for datums_format, datums_value in datums.iteritems(): if datums_format == "df": datums_count += sum(len(datums_value_df["data_df"].index) for datums_value_df in datums_value) else: datums_count += len(datums_value) if datum_format == "json" or datum_format == "dict": datums_formatted = Plugin.datum_to_format(datums, "dict", off_thread)["dict"] if datum_format == "json": datums_formatted = Plugin.datums_dict_to_json(datums_formatted, off_thread) elif datum_format == "csv" or datum_format == "svg" or datum_format == "df": datums_formatted = Plugin.datums_df_to_df(Plugin.datum_to_format(datums, "df", off_thread)["df"], datum_options, off_thread=off_thread) if datum_format == "csv": datums_formatted = Plugin.datums_df_to_csv(datums_formatted[0], off_thread) if len(datums_formatted) > 0 else "" elif datum_format == "svg": datums_formatted = Plugin.datums_df_to_svg(datums_formatted[0], off_thread) if len(datums_formatted) > 0 else SVG_EMPTY else: raise ValueError("Unknown datum format [{}]".format(datum_format)) log_timer.log("Plugin", "timer", lambda: "[*] {} to {} for [{}] datums".format(",".join(datums.keys()), datum_format, datums_count), context=Plugin.datums_to_format, off_thread=off_thread) return datums_formatted @staticmethod def datums_df_title(datum_df, datum_df_title=None): if datum_df_title is not None: datum_df.title = datum_df_title return datum_df_title if datum_df_title is not None else (datum_df.title if hasattr(datum_df, "title") else None) @staticmethod def datums_df_reindex(datum_df): datum_df_title = Plugin.datums_df_title(datum_df) if "Time" in datum_df: datum_df["bin_timestamp"] = pandas.to_datetime(datum_df["Time"]) datum_df["bin_timestamp"] = (datum_df['bin_timestamp'] - datetime.datetime(1970, 1, 1)).dt.total_seconds() del datum_df["Time"] if "bin_timestamp" in datum_df: datum_df = datum_df[~datum_df["bin_timestamp"].duplicated(keep="first")] datum_df.set_index("bin_timestamp", inplace=True) datum_df.index = pandas.to_datetime(datum_df.index, unit="s") Plugin.datums_df_title(datum_df, datum_df_title) return datum_df @staticmethod def datums_df_unindex(datum_df): datum_df_title = Plugin.datums_df_title(datum_df) if "bin_timestamp" not in datum_df: datum_df.index = datum_df.index.astype(numpy.int64) // 10 ** 9 datum_df.index.name = "bin_timestamp" datum_df.reset_index(inplace=True) datum_df.reindex(sorted(datum_df.columns), axis=1) Plugin.datums_df_title(datum_df, datum_df_title) return datum_df @staticmethod def datums_df_filter(datum_df, datum_options): datum_df_title = Plugin.datums_df_title(datum_df) if datum_options is not None: datum_df = Plugin.datums_df_reindex(datum_df) if "start" in datum_options: datum_df = datum_df[datum_df.index >= pandas.to_datetime(datum_options["start"], unit="s")[0]] if "finish" in datum_options: datum_df = datum_df[datum_df.index <= pandas.to_datetime(datum_options["finish"], unit="s")[0]] Plugin.datums_df_title(datum_df, datum_df_title) return datum_df @staticmethod def datums_df_resample(datum_df, datum_options): datum_df_title = Plugin.datums_df_title(datum_df) if datum_options is not None: if "period" in datum_options: datum_df = getattr(datum_df.resample(str(datum_options["period"][0]) + "S"), "max" if "method" not in datum_options else datum_options["method"][0])() Plugin.datums_df_title(datum_df, datum_df_title) return datum_df @staticmethod def datums_df_fill(datum_df, datum_df_columns, datum_options): datum_df_title = Plugin.datums_df_title(datum_df) if datum_options is not None: if "fill" in datum_options: if datum_options["fill"][0] == "linear": try: datum_df[datum_df_columns] = datum_df[datum_df_columns].interpolate(method="time") except TypeError as type_error: anode.Log(logging.WARN).log("Plugin", "state", lambda: "[plugin] could not interpolate data frame column [{}]".format( type_error)) if datum_options["fill"][0] == "linear" or datum_options["fill"][0] == "forwardback": datum_df[datum_df_columns] = datum_df[datum_df_columns].fillna(method="ffill").fillna(method="bfill") if datum_options["fill"][0] == "linear" or datum_options["fill"][0] == "zeros": datum_df[datum_df_columns] = datum_df[datum_df_columns].fillna(0) Plugin.datums_df_title(datum_df, datum_df_title) return datum_df @staticmethod def datums_df_data_pretty(datum_df): datum_df_title = Plugin.datums_df_title(datum_df) timestamps = [] if "Time" in datum_df: timestamps.append("Time") if "bin_timestamp" in datum_df: timestamps.append("bin_timestamp") for timestamp in timestamps: datum_df[timestamp] = datum_df[timestamp].apply( lambda epoch: datetime.datetime.fromtimestamp(epoch).strftime("%Y-%m-%d %H:%M:%S")) Plugin.datums_df_title(datum_df, datum_df_title) return datum_df @staticmethod def datums_df_metadata_pretty(datum_df): datum_df_columns_deletes = [] datum_df_columns_renames = {} datum_df_columns_renames_order = {} datum_df_columns_renames_tokens = {} datum_df_columns_renames_tokens_unit = set() datum_df_columns_renames_tokens_metric0 = set() datum_df_columns_renames_tokens_metric2 = set() datum_df_columns_renames_tokens_metric2_type = set() datum_df_columns_renames_tokens_metric3_type = set() for datum_df_column in datum_df.columns: if datum_df_column == "bin_timestamp": datum_df_columns_renames[datum_df_column] = "Time" datum_df_columns_renames_order[datum_df_column] = "0" elif datum_df_column.startswith("data_value"): datum_df_column_tokens_all = datum_df_column.split("data_value_scaled@")[1].split("&") datum_df_column_tokens_metric = datum_df_column_tokens_all[0].split("=")[1] datum_df_column_tokens_subset = datum_df_column_tokens_metric.split(".") datum_df_column_tokens_subset.append(datum_df_column_tokens_all[1].split("=")[1]) datum_df_columns_renames_tokens_unit.add( urllib.unquote_plus(datum_df_column_tokens_all[3].split("=")[1].encode("utf-8")).decode("utf-8")) datum_df_columns_renames_tokens_metric0.add(datum_df_column_tokens_subset[0]) datum_df_columns_renames_tokens_metric2.add(datum_df_column_tokens_subset[2]) datum_df_columns_renames_tokens_metric2_type.add( "".join([datum_df_column_tokens_subset[2], datum_df_column_tokens_subset[3]])) datum_df_columns_renames_tokens_metric3_type.add("".join(datum_df_column_tokens_subset[0:4])) datum_df_column_tokens_subset.append("".join(["(", " ".join( [re.search(r"\d+", datum_df_column_tokens_all[2].split("=")[1]).group(), datum_df_column_tokens_all[2].split("=")[1].replace( re.search(r"\d+", datum_df_column_tokens_all[2].split("=")[1]).group(), "").title()]), ")"])) datum_df_columns_renames_order[datum_df_column] = \ (str(DATUM_SCHEMA_METRICS[datum_df_column_tokens_metric]) + datum_df_column_tokens_all[2]) \ if datum_df_column_tokens_all[0].split("=")[1] in DATUM_SCHEMA_METRICS else datum_df_column_tokens_metric datum_df_columns_renames_tokens[datum_df_column] = datum_df_column_tokens_subset elif datum_df_column.startswith("data_timestamp"): datum_df_columns_deletes.append(datum_df_column) for datum_df_columns_delete in datum_df_columns_deletes: del datum_df[datum_df_columns_delete] for datum_df_columns_renames_token in datum_df_columns_renames_tokens: datum_df_columns_renames_token_subset = [] if len(datum_df_columns_renames_tokens_metric0) > 1: datum_df_columns_renames_token_subset.append(datum_df_columns_renames_tokens[datum_df_columns_renames_token][0].title()) if len(datum_df_columns_renames_tokens_metric2) == len(datum_df_columns_renames_tokens): datum_df_columns_renames_token_subset.append(datum_df_columns_renames_tokens[datum_df_columns_renames_token][2].title()) else: datum_df_columns_renames_tokens_metric2_type_str = datum_df_columns_renames_tokens[datum_df_columns_renames_token][ 2].title() if \ (datum_df_columns_renames_tokens[datum_df_columns_renames_token][3] == "point" or datum_df_columns_renames_tokens[datum_df_columns_renames_token][3] == "integral") else " ".join( [datum_df_columns_renames_tokens[datum_df_columns_renames_token][2].title(), datum_df_columns_renames_tokens[datum_df_columns_renames_token][3].title()]) if len(datum_df_columns_renames_tokens_metric2_type) == len(datum_df_columns_renames_tokens): datum_df_columns_renames_token_subset.append(datum_df_columns_renames_tokens_metric2_type_str) elif len(datum_df_columns_renames_tokens_metric3_type) == len(datum_df_columns_renames_tokens): datum_df_columns_renames_token_subset.append( " ".join([datum_df_columns_renames_tokens[datum_df_columns_renames_token][1].title(), datum_df_columns_renames_tokens_metric2_type_str])) else: datum_df_columns_renames_token_subset.append( " ".join([datum_df_columns_renames_tokens[datum_df_columns_renames_token][1].title(), datum_df_columns_renames_tokens_metric2_type_str, datum_df_columns_renames_tokens[datum_df_columns_renames_token][4]])) datum_df_columns_renames[datum_df_columns_renames_token] = " ".join(datum_df_columns_renames_token_subset) if len(datum_df_columns_renames) == 2: for datum_df_column_old, datum_df_column_new in datum_df_columns_renames.iteritems(): if datum_df_column_old.startswith("data_value_scaled@"): datum_df_columns_renames[datum_df_column_old] = \ " ".join([datum_df_column_new, datum_df_columns_renames_tokens[datum_df_column_old][4]]) for datum_df_columns_rename in datum_df_columns_renames: datum_df_columns_renames[datum_df_columns_rename] = datum_df_columns_renames[datum_df_columns_rename]. \ replace("-", " ").replace("1 All Time", "All Time") datum_df.rename(columns=datum_df_columns_renames, inplace=True) datum_df_columns_reorder = [] for datum_df_column_old in sorted(datum_df_columns_renames_order, key=lambda datum_df_column_sort: (datum_df_columns_renames_order[datum_df_column_sort])): datum_df_columns_reorder.append(datum_df_columns_renames[datum_df_column_old]) datum_df = datum_df[datum_df_columns_reorder] Plugin.datums_df_title(datum_df, (" & ".join(datum_df_columns_renames_tokens_metric0).title() + " (" + ", ".join(datum_df_columns_renames_tokens_unit) + ")").replace("-", " ")) return datum_df def datum_value(self, data, keys=None, default=None, factor=1): # noinspection PyBroadException try: value = data if keys is None else reduce(operator.getitem, keys, data) if isinstance(value, basestring) and not value: value = None if value is None: value = default anode.Log(logging.WARN).log("Plugin", "state", lambda: "[{}] setting value {} to default [{}] from response [{}]".format( self.name, keys, default, data)) return value if not isinstance(value, numbers.Number) else int(value * factor) except Exception as exception: anode.Log(logging.ERROR).log("Plugin", "error", lambda: "[{}] setting value {} to default [{}] from response [{}] due to error [{}]".format( self.name, keys, default, data, exception), exception) return None if default is None else int(default * factor) def datums_store(self): log_timer = anode.Log(logging.INFO).start() for datum_metric in self.datums: for datum_type in self.datums[datum_metric]: for datum_unit in self.datums[datum_metric][datum_type]: for datum_bin in self.datums[datum_metric][datum_type][datum_unit]: if DATUM_QUEUE_HISTORY in self.datums[datum_metric][datum_type][datum_unit][datum_bin]: self.datum_merge_buffer_history( self.datums[datum_metric][datum_type][datum_unit][datum_bin][DATUM_QUEUE_BUFFER], self.datums[datum_metric][datum_type][datum_unit][datum_bin][DATUM_QUEUE_HISTORY]) else: self.datums[datum_metric][datum_type][datum_unit][datum_bin][DATUM_QUEUE_BUFFER].clear() if len(self.datums) > 0: self.pickled_put(os.path.join(self.config["db_dir"], "anode"), os.path.join( "asystem", "anode", self.name, "model/pickle/pandas/none/amodel_version=" + APP_VERSION, "amodel_model=" + APP_MODEL_VERSION, self.name + ".pkl"), self.datums, True) metrics_count = sum(len(units) for metrics in self.datums.values() for types in metrics.values() for units in types.values()) datums_count = sum(0 if DATUM_QUEUE_HISTORY not in bins else ( sum(len(partitions["data_df"].index) for partitions in bins[DATUM_QUEUE_HISTORY].values())) for metrics in self.datums.values() for types in metrics.values() for units in types.values() for bins in units.values()) log_timer.log("Plugin", "timer", lambda: "[{}] state stored [{}] metrics and [{}] datums".format(self.name, metrics_count, datums_count), context=self.datums_store) def datums_load(self): log_timer = anode.Log(logging.INFO).start() metrics_count = 0 datums_pickled = self.pickled_get(os.path.join(self.config["db_dir"], "anode"), name=self.name, cache=False) model_version = int(APP_MODEL_VERSION) while model_version >= 1000 and self.name in datums_pickled and str(model_version) not in datums_pickled[self.name]: model_version -= 1 self.datums = datums_pickled[self.name][str(model_version)][1] \ if self.name in datums_pickled and str(model_version) in datums_pickled[self.name] else {} metrics_count = sum(len(units) for metrics in self.datums.values() for types in metrics.values() for units in types.values()) for datum_metric in self.datums: for datum_type in self.datums[datum_metric]: for datum_unit in self.datums[datum_metric][datum_type]: for datum_bin in self.datums[datum_metric][datum_type][datum_unit]: self.datums[datum_metric][datum_type][datum_unit][datum_bin][DATUM_QUEUE_BUFFER].clear() datums_count = sum(0 if DATUM_QUEUE_HISTORY not in bins else ( sum(len(partitions["data_df"].index) for partitions in bins[DATUM_QUEUE_HISTORY].values())) for metrics in self.datums.values() for types in metrics.values() for units in types.values() for bins in units.values()) log_timer.log("Plugin", "timer", lambda: "[{}] state loaded [{}] metrics and [{}] datums from [{}]".format( self.name, metrics_count, datums_count, ( self.name + "-" + APP_MODEL_VERSION + "-" + datums_pickled[self.name][APP_MODEL_VERSION][ 0]) if self.name in datums_pickled and APP_MODEL_VERSION in datums_pickled[ self.name] else ""), context=self.datums_store) def get_time(self): return calendar.timegm(time.gmtime()) if not self.is_clock else ( (1 if self.reactor.seconds() == 0 else int(self.reactor.seconds())) + self.get_time_period(self.time_boot, 24 * 60 * 60)) def get_time_period(self, timestamp, period): return period if period > timestamp else \ ((timestamp + self.time_tmz_offset) - (timestamp + self.time_tmz_offset) % period - self.time_tmz_offset) def pickled_status(self, store, path, model_lower=None, model_upper=None): log_timer = anode.Log(logging.INFO).start() path_dirty = False path_filtered = True pickle_metadata = re.search(PICKLE_PATH_REGEX, path) if pickle_metadata is not None: if (model_lower is None or model_lower <= pickle_metadata.group(4)) and \ (model_upper is None or model_upper >= pickle_metadata.group(4)): path_filtered = False pickle_cache = self.pickled_get(store, name=pickle_metadata.group(1), model=pickle_metadata.group(4)) path_dirty = pickle_metadata.group(3).endswith("-SNAPSHOT") or \ pickle_metadata.group(1) not in pickle_cache or \ pickle_metadata.group(4) not in pickle_cache[pickle_metadata.group(1)] or \ Plugin.compare_version(pickle_metadata.group(3), pickle_cache[pickle_metadata.group(1)][pickle_metadata.group(4)][0]) > 0 log_timer.log("Plugin", "timer", lambda: "[{}] status pickled [{}filtered, {}dirty] [{}]".format( self.name, "" if path_filtered else "not ", "" if path_dirty else "not ", path), context=self.pickled_status) return path_filtered, path_dirty def pickled_put(self, store, path, library, pickle=False): log_timer = anode.Log(logging.INFO).start() pickle_path = None pickle_metadata = re.search(PICKLE_PATH_REGEX, path) if pickle_metadata is not None: pickle_path = os.path.join(store, pickle_metadata.group(1), "model/pickle", pickle_metadata.group(2), "none/amodel_version=" + pickle_metadata.group(3), "amodel_model=" + pickle_metadata.group(4), pickle_metadata.group(1) + ".pkl") not os.path.exists(os.path.dirname(pickle_path)) and os.makedirs(os.path.dirname(pickle_path)) if pickle: if pickle_metadata.group(2) == "pandas": pandas.to_pickle(library, pickle_path) else: raise Exception("Unknown pickle write format [{}]".format(pickle_metadata[0])) else: with open(pickle_path, "wb") as pickle_file: pickle_file.write(library) self.pickled_get(store, path=path, warm=True) log_timer.log("Plugin", "timer", lambda: "[{}] put pickled [{}] to [{}]".format(self.name, "-".join( "" if pickle_metadata is None else pickle_metadata.group(3, 2, 1)), "" if pickle_path is None else ("file://" + pickle_path)), context=self.pickled_put) return pickle_path def pickled_get(self, store, path=None, name=None, model=None, warm=False, cache=True, flush=False): log_timer = anode.Log(logging.INFO).start() if flush and os.path.isdir(store): shutil.rmtree(store) os.makedirs(store) if cache: if store not in PICKLES_CACHE: PICKLES_CACHE[store] = {} pickle_cache = PICKLES_CACHE[store] else: pickle_cache = {} if path is not None: pickle_metadata = re.search(PICKLE_PATH_REGEX, path) if pickle_metadata is not None: name = pickle_metadata.group(1) model = pickle_metadata.group(4) if not cache or warm: pickle_metadata_cache = {} for root_dir, parent_dirs, file_names in os.walk(store): for file_name in file_names: file_path = os.path.join(root_dir, file_name) pickle_metadata = re.search(PICKLE_PATH_REGEX, file_path) if pickle_metadata is not None: if (name is None or name == pickle_metadata.group(1)) and (model is None or model == pickle_metadata.group(4)): if APP_VERSION.endswith("-SNAPSHOT") or not pickle_metadata.group(3).endswith("-SNAPSHOT"): if pickle_metadata.group(1) not in pickle_metadata_cache: pickle_metadata_cache[pickle_metadata.group(1)] = {} if pickle_metadata.group(4) not in pickle_metadata_cache[pickle_metadata.group(1)]: pickle_metadata_cache[pickle_metadata.group(1)][pickle_metadata.group(4)] = {} pickle_metadata_cache[pickle_metadata.group(1)][pickle_metadata.group(4)][pickle_metadata.group(3)] = \ (pickle_metadata.group(2), file_path) for pickle_name in pickle_metadata_cache: for pickle_model in pickle_metadata_cache[pickle_name]: pickle_version = sorted(pickle_metadata_cache[pickle_name][pickle_model].keys(), cmp=Plugin.compare_version)[-1] pickle_metadata = pickle_metadata_cache[pickle_name][pickle_model][pickle_version] pickle_cache[pickle_name] = pickle_cache[pickle_name] if pickle_name in pickle_cache else {} if pickle_metadata[0] == "pandas": pickle_cache[pickle_name][pickle_model] = (pickle_version, pandas.read_pickle(pickle_metadata[1])) elif pickle_metadata[0] == "joblib": unpickled = joblib.load(pickle_metadata[1]) unpickled['execute'] = dill.load(StringIO(unpickled['execute'].getvalue())) pickle_cache[pickle_name][pickle_model] = (pickle_version, unpickled) else: raise Exception("Unknown pickle read format [{}]".format(pickle_metadata[0])) anode.Log(logging.INFO).log("Plugin", "timer", lambda: "[{}] read pickled [{}] using [{}]".format( self.name, pickle_name + "-" + pickle_model + "-" + pickle_version, pickle_metadata[0])) pickle_cache = pickle_cache if name is None else ({name: pickle_cache[name]} if name in pickle_cache else {name: {}}) pickle_cache = pickle_cache if model is None else ({name: {model: pickle_cache[name][model]}} if (name in pickle_cache and model in pickle_cache[name]) else {name: {}}) pickle = pickle_cache[name] if name in pickle_cache else {} log_timer.log("Plugin", "timer", lambda: "[{}] got pickled [{}]".format(self.name, ", ".join( [name + "-{}-{}".format(model, pickle[model][0]) for model in pickle.keys()])), context=self.pickled_get) return pickle_cache @staticmethod def compare_version(this, that): if this is not None and that is not None and \ (this.endswith("-SNAPSHOT") or that.endswith("-SNAPSHOT")) and \ this.replace("-SNAPSHOT", "") == that.replace("-SNAPSHOT", ""): return 0 if this == that else (1 if that.endswith("-SNAPSHOT") else -1) else: return 0 if this == that else (1 if this > that else -1) @staticmethod def datum_field_swap(field): return "" if field is None else "".join([ESCAPE_SWAPS.get(field_char, field_char) for field_char in field]) @staticmethod def datum_version_encode(version, base=100000000): return (-1 if version.endswith("-SNAPSHOT") else 1) * ((int(re.sub("[^0-9]", "", version)) - base + 1) if ( int(re.sub("[^0-9]", "", version)) >= base) else int(re.sub("[^0-9]", "", version))) @staticmethod def datum_field_encode(field): field_encoded = urllib.quote_plus(Plugin.datum_field_swap(field)) for escaped, unescaped in ESCAPE_SEQUENCES.iteritems(): field_encoded = field_encoded.replace(unescaped, escaped) return field_encoded @staticmethod def datum_field_decode(field): fields_decoded = field.split("__") for index, field in enumerate(fields_decoded): for escaped, unescaped in ESCAPE_SEQUENCES.iteritems(): fields_decoded[index] = fields_decoded[index].replace(escaped, unescaped) field_decoded = urllib.unquote_plus(Plugin.datum_field_swap("_".join(fields_decoded))) return field_decoded if isinstance(field_decoded, unicode) else field_decoded @staticmethod def get_seconds(scalar, unit): if unit == "second": return scalar elif unit == "minute": return scalar * 60 elif unit == "hour": return scalar * 60 * 60 elif unit == "day": return scalar * 60 * 60 * 24 elif unit == "day_Dtime": return scalar * 60 * 60 * 24 elif unit == "night_Dtime": return scalar * 60 * 60 * 24 elif unit == "month": return scalar * 60 * 60 * 24 * 30.42 elif unit == "year": return scalar * 60 * 60 * 24 * 365 elif unit == "all_Dtime": return scalar * -1 else: raise Exception("Unknown time unit [{}]".format(unit)) @staticmethod def get(parent, plugin_name, config, reactor): plugin = getattr(import_module("anode.plugin") if hasattr(anode.plugin, plugin_name.title()) else import_module("anode.plugin." + plugin_name), plugin_name.title())(parent, plugin_name, config, reactor) anode.Log(logging.INFO).log("Plugin", "state", lambda: "[{}] initialised".format(plugin_name)) return plugin __metaclass__ = abc.ABCMeta def __init__(self, parent, name, config, reactor): self.has_poll = getattr(self, "_poll", None) is not None self.has_push = getattr(self, "_push", None) is not None self.is_clock = isinstance(reactor, Clock) self.anode = parent self.name = name self.config = config self.reactor = reactor self.datums = {} self.time_seen = None self.time_boot = calendar.timegm(time.gmtime()) time_local = time.localtime() self.time_tmz_offset = calendar.timegm(time_local) - calendar.timegm(time.gmtime(time.mktime(time_local))) self.datums_buffer_batch = BUFFER_BATCH_DEFAULT if ("buffer_ticks" not in self.config or self.config["buffer_ticks"] < 1) \ else self.config["buffer_ticks"] self.datums_load() PICKLE_PATH_REGEX = ".*/[a-zA-z]*/([a-zA-z]*)/model/pickle/([a-zA-z]*)/none/" \ "amodel_version=([1-9][0-9]\.[0-9]{3}.[0-9]{4}.*)/amodel_model=([1-9][0-9]{3})/.*\.pkl" ID_BYTE = '{s:0^12}'.format(s=format(get_mac(), "x")).decode("hex") ID_HEX = ID_BYTE.encode("hex").upper() ID_HEX_STRING = ':'.join(a + b for a, b in zip(ID_HEX[::2], ID_HEX[1::2])) ID_BASE64 = base64.b64encode(str(ID_BYTE)) SVG_EMPTY = """<?xml version="1.0" encoding="utf-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> </svg>""" ESCAPE_SWAPS = { "_": ".", ".": "_" } ESCAPE_SEQUENCES = { "__": "_", "_X": ".", "_D": "-", "_P": "%" } HTTP_TIMEOUT = 10 BUFFER_BATCH_DEFAULT = 60 SERIALISATION_BATCH = 1000 SERIALISATION_BATCH_SLEEP = 0.3 DATUM_TIMESTAMP_MIN = -2211753600 DATUM_TIMESTAMP_MAX = 32500915200 DATUM_QUEUE_MIN = "min" DATUM_QUEUE_MAX = "max" DATUM_QUEUE_LAST = "last" DATUM_QUEUE_PUBLISH = "publish" DATUM_QUEUE_BUFFER = "buffer" DATUM_QUEUE_HISTORY = "history" DATUM_LOCATION_DEFAULT = "Home" DATUM_LOCATIONS = { "Ada", "Dining", "Edwin", "Kitchen", "Laundry", "Lounge", "Office", "Pantry", "Parents", "Ensuite", "Bathroom", "Utility", "Shed", "Basement", "Deck", "Roof", } PICKLES_CACHE = {} DATUM_SCHEMA_TO_ASCII = {} DATUM_SCHEMA_FROM_ASCII = {} DATUM_SCHEMA_FILE = open(os.path.dirname(__file__) + "/../web/js/metadata/datum.avsc", "rb").read() DATUM_SCHEMA_JSON = json.loads(DATUM_SCHEMA_FILE) DATUM_SCHEMA_AVRO = avro.schema.parse(DATUM_SCHEMA_FILE) DATUM_SCHEMA_MODEL = {DATUM_SCHEMA_JSON["fields"][i]["name"].encode("utf-8"): i * 10 for i in range(len(DATUM_SCHEMA_JSON["fields"]))} DATUM_SCHEMA_METRICS = {Plugin.datum_field_decode(DATUM_SCHEMA_JSON["fields"][4]["type"]["symbols"][i].encode("utf-8")): i * 10 for i in range(len(DATUM_SCHEMA_JSON["fields"][4]["type"]["symbols"]))} PUBLISH_METADATA_CACHE = {} PUBLISH_BATCH_TOPIC = "/anode_version=" + APP_VERSION + "/anode_id=" + ID_HEX class ModelPull(Plugin): def poll(self): self.http_get(self.config["model_pull_region"], self.config["model_pull_bucket"], "/", "list-type=2&max-keys=1000000&prefix=asystem", self.list_models) def http_get(self, region, bucket, path, params, callback): host = bucket + ".s3-" + region + ".amazonaws.com" url = "http://" + host + path + "?" + params payload = auth.compute_hashed_payload(b"") timestamp = datetime.datetime.utcnow() headers = {"host": host, "x-amz-content-sha256": payload, "x-amz-date": timestamp.strftime(auth.ISO8601_FMT)} headers["Authorization"] = auth.compute_auth_header(headers, "GET", timestamp, region, bucket, path, params, payload, self.config["profile"]["AWS_ACCESS_KEY"], self.config["profile"]["AWS_SECRET_KEY"]) connection_pool = self.config["pool"] if "pool" in self.config else None treq.get(url, headers=headers, timeout=HTTP_TIMEOUT, pool=connection_pool).addCallbacks( lambda response, url=url, callback=callback: self.http_response(response, url, callback), errback=lambda error, url=url: anode.Log(logging.ERROR).log("Plugin", "error", lambda: "[{}] error processing HTTP GET [{}] with [{}]".format( self.name, url, error.getErrorMessage()))) def http_response(self, response, url, callback): if response.code == 200: treq.content(response).addCallbacks(callback, callbackKeywords={"url": url}) else: anode.Log(logging.ERROR).log("Plugin", "error", lambda: "[{}] error processing HTTP response [{}] with [{}]".format(self.name, url, response.code)) def list_models(self, content, url): log_timer = anode.Log(logging.DEBUG).start() try: for key_remote in xmltodict.parse(content)["ListBucketResult"]["Contents"]: path_remote = "s3://" + self.config["model_pull_bucket"] + "/" + key_remote["Key"].encode("utf-8") path_status = self.pickled_status(os.path.join(self.config["db_dir"], "amodel"), path_remote) if not path_status[0] and path_status[1]: self.http_get(self.config["model_pull_region"], self.config["model_pull_bucket"], "/" + path_remote.replace("s3://" + self.config["model_pull_bucket"] + "/", ""), "", self.pull_model) elif not path_status[0]: self.verified_model(path_remote) except Exception as exception: anode.Log(logging.ERROR).log("Plugin", "error", lambda: "[{}] error [{}] processing response:\n{}" .format(self.name, exception, content), exception) log_timer.log("Plugin", "timer", lambda: "[{}]".format(self.name), context=self.list_models) def pull_model(self, content, url): log_timer = anode.Log(logging.DEBUG).start() try: path_remote = url[:-1] self.pickled_put(os.path.join(self.config["db_dir"], "amodel"), path_remote, content) self.verified_model(path_remote) except Exception as exception: anode.Log(logging.ERROR).log("Plugin", "error", lambda: "[{}] error [{}] processing binary response of length [{}]" .format(self.name, exception, len(content)), exception) log_timer.log("Plugin", "timer", lambda: "[{}]".format(self.name), context=self.pull_model) def verified_model(self, path=None): anode.Log(logging.INFO).log("Plugin", "state", lambda: "[{}] verified model [{}]".format(self.name, path)) def __init__(self, parent, name, config, reactor): super(ModelPull, self).__init__(parent, name, config, reactor) self.pickled_get(os.path.join(self.config["db_dir"], "amodel"), flush=True)
61.867116
140
0.585515
4a10330f9d8ea805a53cae3ced9e32910ab976fc
1,298
py
Python
biobakery_workflows/scripts/remove_if_exists.py
tkuntz-hsph/biobakery_workflows
e861705d939354178362fd5b26e59dcc696489d2
[ "MIT" ]
47
2020-08-18T20:51:02.000Z
2022-03-21T19:43:13.000Z
biobakery_workflows/scripts/remove_if_exists.py
tkuntz-hsph/biobakery_workflows
e861705d939354178362fd5b26e59dcc696489d2
[ "MIT" ]
18
2020-06-12T21:26:46.000Z
2022-03-19T08:24:55.000Z
biobakery_workflows/scripts/remove_if_exists.py
tkuntz-hsph/biobakery_workflows
e861705d939354178362fd5b26e59dcc696489d2
[ "MIT" ]
15
2020-07-24T16:41:46.000Z
2022-02-22T09:02:01.000Z
#!/usr/bin/env python """ This script will remove a file if it exists. It will report error messages from trying to remove the file. """ import sys import shutil try: import argparse except ImportError: sys.exit("Please upgrade to at least python v2.7") import os def parse_arguments(args): """ Parse the arguments from the user""" parser=argparse.ArgumentParser(description="Remove file if it exists.") parser.add_argument('file',help="File (or folder) to remove") parser.add_argument('--is-folder',help="Indicate if input is a folder", action="store_true") return parser.parse_args() def main(): # parse arguments args = parse_arguments(sys.argv) # check if the file exists if os.path.isfile(args.file): # if it exists, then try to remove # Report error messages if unable to remove file that exists try: os.unlink(args.file) except EnvironmentError: sys.exit("ERROR: Unable to remove file: " + args.file) if os.path.isdir(args.file) and args.is_folder: try: shutil.rmtree(args.file) except EnvironmentError: sys.exit("ERROR: Unable to remove folder: " + args.file) if __name__ == "__main__": main()
27.617021
96
0.642527
4a10349ed4dec2af6df81ee777ad8422925930e9
1,254
py
Python
1. Algorithmic Toolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers.py
vishweshwartyagi/Data-Structures-and-Algorithms-UCSD
de942b3a0eb2bf56f949f47c297fad713aa81489
[ "MIT" ]
null
null
null
1. Algorithmic Toolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers.py
vishweshwartyagi/Data-Structures-and-Algorithms-UCSD
de942b3a0eb2bf56f949f47c297fad713aa81489
[ "MIT" ]
null
null
null
1. Algorithmic Toolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers.py
vishweshwartyagi/Data-Structures-and-Algorithms-UCSD
de942b3a0eb2bf56f949f47c297fad713aa81489
[ "MIT" ]
null
null
null
# Uses python3 from sys import stdin def fibonacci_sum_squares_naive(n): if n <= 1: return n previous = 0 current = 1 sum = 1 for _ in range(n - 1): previous, current = current, previous + current sum += current * current return sum % 10 def mat_mul(A, B, q): assert(len(A[0]) == len(B)) m = len(A) n = len(A[0]) p = len(B[0]) prod = [] for i in range(0, m): row = [] for j in range(0, p): val = 0 for k in range(0, n): val += (A[i][k]%q)*(B[k][j]%q) val %= q row.append(val) prod.append(row) return prod def mat_pow_fast(A, p, q): if p == 1: return A sub_problem = mat_pow_fast(A, p//2, q) result = mat_mul(sub_problem, sub_problem, q) if p%2 == 1: result = mat_mul(result, A, q) return result def get_fib_modulo(n, q): if n <= 1: return n A = [[1, 1], [1, 0]] return mat_pow_fast(A, n-1, q)[0][0] if __name__ == '__main__': # n = int(stdin.read()) n = int(input()) # print(fibonacci_sum_squares_naive(n)) print((get_fib_modulo(n+1, 10) * get_fib_modulo(n, 10)) % 10)
19
65
0.49362
4a1034aa06543aae909aa89e3607c39cf2e87ca0
6,811
py
Python
hvac/api/secrets_engines/consul.py
leongyh/hvac
4697d5ec097809def0e0bacd166f6db520db7d94
[ "Apache-2.0" ]
1
2020-12-14T04:01:10.000Z
2020-12-14T04:01:10.000Z
hvac/api/secrets_engines/consul.py
TerryHowe/hvac
a6b7f904bfaba3c1133ccc7fa5a0cff0d29340c7
[ "Apache-2.0" ]
null
null
null
hvac/api/secrets_engines/consul.py
TerryHowe/hvac
a6b7f904bfaba3c1133ccc7fa5a0cff0d29340c7
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """Consul methods module.""" from hvac import exceptions, utils from hvac.api.vault_api_base import VaultApiBase DEFAULT_MOUNT_POINT = "consul" class Consul(VaultApiBase): """Copnsul Secrets Engine (API). Reference: https://www.vaultproject.io/api/secret/consul/index.html """ def configure_access(self, address, token, scheme=None, mount_point=DEFAULT_MOUNT_POINT): """This endpoint configures the access information for Consul. This access information is used so that Vault can communicate with Consul and generate Consul tokens. :param address: Specifies the address of the Consul instance, provided as "host:port" like "127.0.0.1:8500". :type address: str | unicode :param token: Specifies the Consul ACL token to use. This must be a management type token. :type token: str | unicode :param scheme: Specifies the URL scheme to use. :type scheme: str | unicode :param mount_point: Specifies the place where the secrets engine will be accessible (default: consul). :type mount_point: str | unicode :return: The response of the request. :rtype: requests.Response """ params = { "address": address, "token": token, } params.update( utils.remove_nones({ "scheme": scheme, }) ) api_path = utils.format_url("/v1/{}/config/access", mount_point) return self._adapter.post( url=api_path, json=params, ) def create_or_update_role(self, name, policy=None, policies=None, token_type=None, local=None, ttl=None, max_ttl=None, mount_point=DEFAULT_MOUNT_POINT): """This endpoint creates or updates the Consul role definition. If the role does not exist, it will be created. If the role already exists, it will receive updated attributes. :param name: Specifies the name of an existing role against which to create this Consul credential. :type name: str | unicode :param token_type: Specifies the type of token to create when using this role. Valid values are "client" or "management". :type token_type: str | unicode :param policy: Specifies the base64 encoded ACL policy. The ACL format can be found in the Consul ACL documentation (https://www.consul.io/docs/internals/acl.html). This is required unless the token_type is management. :type policy: str | unicode :param policies: The list of policies to assign to the generated token. This is only available in Consul 1.4 and greater. :type policies: list :param local: Indicates that the token should not be replicated globally and instead be local to the current datacenter. Only available in Consul 1.4 and greater. :type local: bool :param ttl: Specifies the TTL for this role. This is provided as a string duration with a time suffix like "30s" or "1h" or as seconds. If not provided, the default Vault TTL is used. :type ttl: str | unicode :param max_ttl: Specifies the max TTL for this role. This is provided as a string duration with a time suffix like "30s" or "1h" or as seconds. If not provided, the default Vault Max TTL is used. :type max_ttl: str | unicode :param mount_point: Specifies the place where the secrets engine will be accessible (default: consul). :type mount_point: str | unicode :return: The response of the request. :rtype: requests.Response """ api_path = utils.format_url("/v1/{}/roles/{}", mount_point, name) if not policy and token_type != "management": error_msg = 'policy must be specified unless token_type is management' raise exceptions.ParamValidationError(error_msg) params = utils.remove_nones({ "token_type": token_type, "policy": policy, "policies": policies, "local": local, "ttl": ttl, "max_ttl": max_ttl }) return self._adapter.post( url=api_path, json=params, ) def read_role(self, name, mount_point=DEFAULT_MOUNT_POINT): """This endpoint queries for information about a Consul role with the given name. If no role exists with that name, a 404 is returned. :param name: Specifies the name of the role to query. :type name: str | unicode :param mount_point: Specifies the place where the secrets engine will be accessible (default: consul). :type mount_point: str | unicode :return: The response of the request. :rtype: requests.Response """ api_path = utils.format_url("/v1/{}/roles/{}", mount_point, name) return self._adapter.get( url=api_path, ) def list_roles(self, mount_point=DEFAULT_MOUNT_POINT): """This endpoint lists all existing roles in the secrets engine. :return: The response of the request. :rtype: requests.Response """ api_path = utils.format_url("/v1/{}/roles", mount_point) return self._adapter.list( url=api_path, ) def delete_role(self, name, mount_point=DEFAULT_MOUNT_POINT): """This endpoint deletes a Consul role with the given name. Even if the role does not exist, this endpoint will still return a successful response. :param name: Specifies the name of the role to delete. :type name: str | unicode :param mount_point: Specifies the place where the secrets engine will be accessible (default: consul). :type mount_point: str | unicode :return: The response of the request. :rtype: requests.Response """ api_path = utils.format_url("/v1/{}/roles/{}", mount_point, name) return self._adapter.delete( url=api_path, ) def generate_credentials(self, name, mount_point=DEFAULT_MOUNT_POINT): """This endpoint generates a dynamic Consul token based on the given role definition. :param name: Specifies the name of an existing role against which to create this Consul credential. :type name: str | unicode :param mount_point: Specifies the place where the secrets engine will be accessible (default: consul). :type mount_point: str | unicode :return: The response of the request. :rtype: requests.Response """ api_path = utils.format_url("/v1/{}/creds/{}", mount_point, name) return self._adapter.get( url=api_path, )
42.04321
122
0.641316
4a103526a51a8ad88b3c9f227139ecefef9f419e
5,100
py
Python
src/lcd16x2.py
dooley-ch/microbit-grove
e25213de74d982b8ab49412e6f8b2dbe205ca932
[ "MIT" ]
null
null
null
src/lcd16x2.py
dooley-ch/microbit-grove
e25213de74d982b8ab49412e6f8b2dbe205ca932
[ "MIT" ]
null
null
null
src/lcd16x2.py
dooley-ch/microbit-grove
e25213de74d982b8ab49412e6f8b2dbe205ca932
[ "MIT" ]
null
null
null
# ------------------------------------------------------------------------------------------ # Copyright James A. Dooley 2021. # # Distributed under the MIT License. # (See accompanying file license.md file or copy at http://opensource.org/licenses/MIT) # # ------------------------------------------------------------------------------------------ # Note: While the LCD does work, it does not perform very well without an external power # source from microbit import i2c, sleep, display, button_b from utime import sleep_us _DEFAULT_ADDRESS = 0x3E # commands _LCD_CLEARDISPLAY = 0x01 _LCD_RETURNHOME = 0x02 _LCD_ENTRYMODESET = 0x04 _LCD_DISPLAYCONTROL = 0x08 _LCD_CURSORSHIFT = 0x10 _LCD_FUNCTIONSET = 0x20 _LCD_SETCGRAMADDR = 0x40 _LCD_SETDDRAMADDR = 0x80 # Function set flags _LCD_2LINE = 0x08 # flags for display on/off control _LCD_DISPLAYON = 0x04 _LCD_DISPLAYOFF = 0x00 _LCD_CURSORON = 0x02 _LCD_CURSOROFF = 0x00 _LCD_BLINKON = 0x01 _LCD_BLINKOFF = 0x00 # flags for display/cursor shift _LCD_DISPLAYMOVE = 0x08 _LCD_MOVERIGHT = 0x04 _LCD_MOVELEFT = 0x00 # flags for display entry mode # _LCD_ENTRYRIGHT = 0x00 _LCD_ENTRYLEFT = 0x02 _LCD_ENTRYSHIFTINCREMENT = 0x01 _LCD_ENTRYSHIFTDECREMENT = 0x00 class Lcd16x2(): def __init__(self): self._device_address = _DEFAULT_ADDRESS self._display_function = _LCD_DISPLAYON | _LCD_2LINE sleep_us(50000) self.command(_LCD_FUNCTIONSET | self._display_function) sleep_us(4500) self.command(_LCD_FUNCTIONSET | self._display_function) sleep_us(150) self.command(_LCD_FUNCTIONSET | self._display_function) self._display_control = _LCD_DISPLAYON | _LCD_CURSOROFF | _LCD_BLINKOFF self.display(True) self.clear() self._display_mode = _LCD_ENTRYLEFT | _LCD_ENTRYSHIFTDECREMENT self.command(_LCD_ENTRYMODESET | self._display_mode) def _write_register(self, address, data): i2c.write(self._device_address, bytearray([address, data])) def command(self, value): assert value >= 0 and value < 256 self._write_register(_LCD_SETDDRAMADDR, value) def write_character(self, value): assert value >= 0 and value < 256 self._write_register(_LCD_SETCGRAMADDR, value) def write(self, value): value = str(value) for char in value: self.write_character(ord(char)) sleep_us(200) def set_cursor(self, col, row): col = (col | 0x80) if row == 0 else (col | 0xc0) self.command(col) def display(self, state): if state: self._display_control |= _LCD_DISPLAYON self.command(0x08 | self._display_control) else: self._display_control &= ~_LCD_DISPLAYON self.command(0x08 | self._display_control) def clear(self): self.command(_LCD_CLEARDISPLAY) sleep_us(2000) def home(self): self.command(_LCD_CLEARDISPLAY) sleep_us(2000) def autoscroll(self): self._display_mode |= _LCD_ENTRYSHIFTINCREMENT self.command(_LCD_ENTRYMODESET | self._display_mode) def no_autoscroll(self): self._display_mode &= ~_LCD_ENTRYSHIFTINCREMENT self.command(_LCD_ENTRYMODESET | self._display_mode); def blink(self): self._display_control |= _LCD_BLINKON self.command(_LCD_DISPLAYCONTROL | self._display_control); def no_blink(self): self._display_control &= ~_LCD_BLINKON self.command(_LCD_DISPLAYCONTROL | self._display_control); sleep_us(2000) def cursor(self): self._display_control |= _LCD_CURSORON self.command(_LCD_DISPLAYCONTROL | self._display_control); def no_cursor(self): self._display_control &= ~_LCD_CURSORON self.command(_LCD_DISPLAYCONTROL | self._display_control); sleep_us(2000) def scroll_display_left(self): self.command(_LCD_CURSORSHIFT | _LCD_DISPLAYMOVE | _LCD_MOVELEFT); sleep_us(2000) def scroll_display_right(self): self.command(_LCD_CURSORSHIFT | _LCD_DISPLAYMOVE | _LCD_MOVERIGHT); sleep_us(2000) def left_to_right(self): self._display_mode |= _LCD_ENTRYLEFT; self.command(_LCD_ENTRYMODESET | self._display_mode); def right_to_left(self): self._display_mode &= ~_LCD_ENTRYLEFT; self.command(_LCD_ENTRYMODESET | self._display_mode); def main(): board = Lcd16x2() display.clear() display.show('>') while True: if button_b.was_pressed(): display.clear() break board.clear() board.write('Hello World') board.set_cursor(0, 1) for i in range(20): board.set_cursor(0, 1) board.write(str(i)) sleep(500) sleep(1000) if __name__ == '__main__': main()
29.479769
92
0.622941
4a103532642f5a3aaebbe39ea6373ce2230e0455
5,185
py
Python
equatorial_UVW.py
jgagneastro/jg_kinematics
cd1469ab342240d15b01b75ca038d545dbaf227a
[ "MIT" ]
1
2018-12-04T21:54:07.000Z
2018-12-04T21:54:07.000Z
equatorial_UVW.py
jgagneastro/jg_kinematics
cd1469ab342240d15b01b75ca038d545dbaf227a
[ "MIT" ]
null
null
null
equatorial_UVW.py
jgagneastro/jg_kinematics
cd1469ab342240d15b01b75ca038d545dbaf227a
[ "MIT" ]
null
null
null
import numpy as np #Numpy maths #Initiate some global constants #1 AU/yr to km/s divided by 1000 kappa = 0.004743717361 #Not using "from astropy import units as u; kappa=u.au.to(u.km)/u.year.to(u.s)" because astropy defines one year as exactly 365.25 days instead of 365 days #Galactic Coordinates matrix TGAL = (np.array([[-0.0548755604, -0.8734370902, -0.4838350155], [0.4941094279, -0.4448296300, 0.7469822445], [-0.8676661490, -0.1980763734, 0.4559837762]])) def equatorial_UVW(ra, dec, pmra, pmdec, rv, dist, pmra_error=None, pmdec_error=None, rv_error=None, dist_error=None): """ Transforms equatorial coordinates (ra, dec), proper motion (pmra, pmdec), radial velocity and distance to space velocities UVW. All inputs must be numpy arrays of the same dimension. param ra: Right ascension (degrees) param dec: Declination (degrees) param pmra: Proper motion in right ascension (milliarcsecond per year). Must include the cos(delta) term param pmdec: Proper motion in declination (milliarcsecond per year) param rv: Radial velocity (kilometers per second) param dist: Distance (parsec) param ra_error: Error on right ascension (degrees) param dec_error: Error on declination (degrees) param pmra_error: Error on proper motion in right ascension (milliarcsecond per year) param pmdec_error: Error on proper motion in declination (milliarcsecond per year) param rv_error: Error on radial velocity (kilometers per second) param dist_error: Error on distance (parsec) output (U, V, W): Tuple containing Space velocities UVW (kilometers per second) output (U, V, W, EU, EV, EW): Tuple containing Space velocities UVW and their measurement errors, used if any measurement errors are given as inputs (kilometers per second) """ #Verify keywords num_stars = np.size(ra) if np.size(dec) != num_stars or np.size(pmra) != num_stars or np.size(pmdec) != num_stars or np.size(dist) != num_stars: raise ValueError('ra, dec, pmra, pmdec, rv and distance must all be numpy arrays of the same size !') if pmra_error is not None and np.size(pmra_error) != num_stars: raise ValueError('pmra_error must be a numpy array of the same size as ra !') if pmdec_error is not None and np.size(pmdec_error) != num_stars: raise ValueError('pmdec_error must be a numpy array of the same size as ra !') if rv_error is not None and np.size(rv_error) != num_stars: raise ValueError('rv_error must be a numpy array of the same size as ra !') if dist_error is not None and np.size(dist_error) != num_stars: raise ValueError('dist_error must be a numpy array of the same size as ra !') #Compute elements of the T matrix cos_ra = np.cos(np.radians(ra)) cos_dec = np.cos(np.radians(dec)) sin_ra = np.sin(np.radians(ra)) sin_dec = np.sin(np.radians(dec)) T1 = TGAL[0, 0]*cos_ra*cos_dec + TGAL[0, 1]*sin_ra*cos_dec + TGAL[0, 2]*sin_dec T2 = -TGAL[0, 0]*sin_ra + TGAL[0, 1]*cos_ra T3 = -TGAL[0, 0]*cos_ra*sin_dec - TGAL[0, 1]*sin_ra*sin_dec + TGAL[0, 2]*cos_dec T4 = TGAL[1, 0]*cos_ra*cos_dec + TGAL[1, 1]*sin_ra*cos_dec + TGAL[1, 2]*sin_dec T5 = -TGAL[1, 0]*sin_ra + TGAL[1, 1]*cos_ra T6 = -TGAL[1, 0]*cos_ra*sin_dec - TGAL[1, 1]*sin_ra*sin_dec + TGAL[1, 2]*cos_dec T7 = TGAL[2, 0]*cos_ra*cos_dec + TGAL[2, 1]*sin_ra*cos_dec + TGAL[2, 2]*sin_dec T8 = -TGAL[2, 0]*sin_ra + TGAL[2, 1]*cos_ra T9 = -TGAL[2, 0]*cos_ra*sin_dec - TGAL[2, 1]*sin_ra*sin_dec + TGAL[2, 2]*cos_dec #Calculate UVW reduced_dist = kappa*dist U = T1*rv + T2*pmra*reduced_dist + T3*pmdec*reduced_dist V = T4*rv + T5*pmra*reduced_dist + T6*pmdec*reduced_dist W = T7*rv + T8*pmra*reduced_dist + T9*pmdec*reduced_dist #Return only (U, V, W) tuple if no errors are set if pmra_error is None and pmdec_error is None and rv_error is None and dist_error is None: return (U, V, W) #Propagate errors if they are specified if pmra_error is None: pmra_error = np.zeros(num_stars) if pmdec_error is None: pmdec_error = np.zeros(num_stars) if rv_error is None: rv_error = np.zeros(num_stars) if dist_error is None: dist_error = np.zeros(num_stars) reduced_dist_error = kappa*dist_error #Calculate derivatives T23_pm = np.sqrt((T2*pmra)**2+(T3*pmdec)**2) T23_pm_error = np.sqrt((T2*pmra_error)**2+(T3*pmdec_error)**2) EU_rv = T1 * rv_error EU_pm = T23_pm_error * reduced_dist EU_dist = T23_pm * reduced_dist_error EU_dist_pm = T23_pm_error * reduced_dist_error T56_pm = np.sqrt((T5*pmra)**2+(T6*pmdec)**2) T56_pm_error = np.sqrt((T5*pmra_error)**2+(T6*pmdec_error)**2) EV_rv = T4 * rv_error EV_pm = T56_pm_error * reduced_dist EV_dist = T56_pm * reduced_dist_error EV_dist_pm = T56_pm_error * reduced_dist_error T89_pm = np.sqrt((T8*pmra)**2+(T9*pmdec)**2) T89_pm_error = np.sqrt((T8*pmra_error)**2+(T9*pmdec_error)**2) EW_rv = T7 * rv_error EW_pm = T89_pm_error * reduced_dist EW_dist = T89_pm * reduced_dist_error EW_dist_pm = T89_pm_error * reduced_dist_error #Calculate error bars EU = np.sqrt(EU_rv**2 + EU_pm**2 + EU_dist**2 + EU_dist_pm**2) EV = np.sqrt(EV_rv**2 + EV_pm**2 + EV_dist**2 + EV_dist_pm**2) EW = np.sqrt(EW_rv**2 + EW_pm**2 + EW_dist**2 + EW_dist_pm**2) #Return measurements and error bars return (U, V, W, EU, EV, EW)
46.294643
183
0.724204
4a103602e3067486420afe003535c56a8147050c
11,253
py
Python
tests/test_commands.py
Gobot1234/steam
ffcd3a6c4d531fbf174f359f0b66d9a9525d62cb
[ "MIT" ]
79
2020-02-26T19:20:07.000Z
2022-03-24T11:12:57.000Z
tests/test_commands.py
Gobot1234/steam
ffcd3a6c4d531fbf174f359f0b66d9a9525d62cb
[ "MIT" ]
34
2020-04-26T01:55:31.000Z
2022-03-15T17:38:34.000Z
tests/test_commands.py
Gobot1234/steam
ffcd3a6c4d531fbf174f359f0b66d9a9525d62cb
[ "MIT" ]
14
2020-07-15T14:50:14.000Z
2022-01-26T21:51:30.000Z
import contextlib import traceback from copy import copy from io import StringIO from typing import Any, Generator, Optional, TypeVar, Union import pytest from typing_extensions import TypeAlias import steam from steam.ext import commands from tests.mocks import GROUP_MESSAGE CE = TypeVar("CE", bound=commands.CommandError) T = TypeVar("T") IsInstanceable: TypeAlias = "Union[type[T], tuple[type[T], ...]]" SomeCoolType = int UserTypes = Union[steam.User, int, str] FAILS: "list[Exception]" = [] @pytest.mark.asyncio async def test_commands(): with pytest.raises(TypeError): @commands.command def not_valid(_): ... with pytest.raises(TypeError): @commands.command(name=123) async def _123(_) -> None: ... with pytest.raises(TypeError): @commands.command(aliases=[1, 2, 3]) async def _123(_) -> None: ... with pytest.raises(steam.ClientException): @commands.command async def not_valid() -> None: ... class MyCog(commands.Cog): with pytest.raises(steam.ClientException): @commands.command async def not_even_close() -> None: # noqa ... bot = TheTestBot() class MyCog(commands.Cog): @commands.command async def not_valid(self) -> None: ... with pytest.raises(steam.ClientException): bot.add_cog(MyCog()) def test_annotations() -> None: @commands.command async def some_cool_command(_, cool_type: SomeCoolType) -> None: ... assert some_cool_command.clean_params.popitem()[1].annotation is SomeCoolType # should be evaluated @commands.command async def get_an_user(_, user: "UserTypes") -> None: ... assert get_an_user.clean_params.popitem()[1].annotation == UserTypes class CustomConverter(commands.Converter[tuple]): async def convert(self, ctx: commands.Context, argument: str) -> tuple: ... @pytest.mark.parametrize( "param_type, expected", [ (None, TypeError), (str, TypeError), (int, int), (CustomConverter, CustomConverter), ("None", TypeError), ("str", TypeError), ("int", int), ], ) def test_greedy(param_type: Union[type, str], expected: type) -> None: global param_type_ # hack to make typing.get_type_hints work with locals param_type_ = param_type if issubclass(expected, Exception): with pytest.raises(expected): @commands.command async def greedy(_, param: commands.Greedy[param_type_]) -> None: ... else: @commands.command async def greedy(_, param: commands.Greedy[param_type_]) -> None: ... assert greedy.params["param"].annotation.converter is expected class TheTestBot(commands.Bot): def __init__(self) -> None: super().__init__(command_prefix="") self.MESSAGE = GROUP_MESSAGE self.to_finish: "list[str]" = [] @contextlib.asynccontextmanager async def raises_command_error( self, expected_errors: "IsInstanceable[type[CE]]", content: str ) -> "contextlib.AbstractAsyncContextManager[None]": expected_errors = (expected_errors,) if not isinstance(expected_errors, tuple) else expected_errors async def on_command_error(ctx: commands.Context, error: CE) -> None: error = error.__class__ if isinstance(error, Exception) else error if ctx.message.content == content: if error not in expected_errors: raise error self.to_finish.remove(content) async def on_command_completion(ctx: commands.Context) -> None: if ctx.message.content == content: self.to_finish.remove(content) self.add_listener(on_command_error) self.add_listener(on_command_completion) yield @contextlib.asynccontextmanager async def returns_command_completion(self, content: str) -> "contextlib.AbstractAsyncContextManager[None]": async def on_command_error(ctx: commands.Context, error: CE) -> None: if ctx.message.content == content: raise error async def on_command_completion(ctx: commands.Context) -> None: if ctx.message.content == content: self.to_finish.remove(content) self.add_listener(on_command_error) self.add_listener(on_command_completion) yield async def process_commands( self, arguments: Optional[str] = None, exception: Optional["type[CE]"] = None, command: Optional[commands.Command] = None, ) -> None: command = command or list(self.__commands__.values())[-1] message = copy(self.MESSAGE) message.content = message.clean_content = f"{command.qualified_name} {arguments or ''}".strip() self.to_finish.append(message.content) if exception is not None: async with self.raises_command_error(exception, message.content): await super().process_commands(message) else: async with self.returns_command_completion(message.content): await super().process_commands(message) async def on_error(self, event: str, error: Exception, *args: Any, **kwargs: Any) -> None: FAILS.append(error) def __del__(self): if self.to_finish: FAILS.append( Exception(f"{len(self.to_finish)} commands still being processed: {', '.join(self.to_finish)}") ) @pytest.mark.asyncio @pytest.mark.parametrize( "input, excepted_exception", [ ("", commands.MissingRequiredArgument), ("1234", None), ("1234 1234", None), ("string", commands.BadArgument), ], ) async def test_positional_or_keyword_commands( input: str, excepted_exception: Optional["type[commands.CommandError]"] ) -> None: bot = TheTestBot() @bot.command async def test_positional(_, number: int) -> None: assert isinstance(number, int) assert len(str(number)) == 4 await bot.process_commands(input, excepted_exception) @pytest.mark.asyncio @pytest.mark.parametrize( "input, expected_exception", [ ("", None), ("1234", None), ("1234 1234", None), ("1234 1234 1234 1234 1234", None), ("string", commands.BadArgument), ], ) async def test_variadic_commands(input: str, expected_exception: commands.CommandError) -> None: bot = TheTestBot() @bot.command async def test_var(_, *numbers: int) -> None: assert isinstance(numbers, tuple) for number in numbers: assert isinstance(number, int) assert len(str(number)) == 4 await bot.process_commands(input, expected_exception) @pytest.mark.asyncio async def test_positional_only_commands(): bot = TheTestBot() @bot.command async def test_consume_rest_int(_, *, number: int) -> None: assert isinstance(number, int) inputs = [ ("", commands.MissingRequiredArgument), ("1234", None), ("123412341234", None), ("string", commands.BadArgument), ] for args, excepted_exception in inputs: await bot.process_commands(args, excepted_exception) @bot.command async def test_consume_rest_str(_, *, string: str) -> None: assert isinstance(string, str) assert len(string.split()) == 3 inputs = [ ("", commands.MissingRequiredArgument), ("string string string", None), ("1234 1234 1234", None), ] for args, excepted_exception in inputs: await bot.process_commands(args, excepted_exception) @bot.group async def test_sub(_) -> None: pass inputs = [ ("", None), ("string string string", None), ("1234123412134", None), ("string", None), ] for args, excepted_exception in inputs: await bot.process_commands(args, excepted_exception) @test_sub.command async def sub(_, *, string: str) -> None: assert string == "cool string string string" inputs = [ ("", commands.MissingRequiredArgument), ("cool string string string", None), ] for args, excepted_exception in inputs: await bot.process_commands(args, excepted_exception, command=sub) @pytest.mark.asyncio async def test_group_commands() -> None: bot = TheTestBot() @contextlib.contextmanager def writes_to_console(msg: str) -> Generator[None, None, None]: stdout = StringIO() with contextlib.redirect_stdout(stdout): yield assert msg == stdout.getvalue().strip() @bot.group async def parent(_) -> None: print("In parent") @parent.group async def child(_) -> None: print("In child") @child.command async def grand_child(_) -> None: print("In grand child") @parent.group async def other_child(_) -> None: print("In other child") assert bot.get_command("parent") is parent with writes_to_console("In parent"): await bot.process_commands(command=parent) assert bot.get_command("child") is None assert bot.get_command("parent child") is child with writes_to_console("In child"): await bot.process_commands(command=child) assert bot.get_command("grand_child") is None assert bot.get_command("child grand_child") is None assert bot.get_command("parent child grand_child") is grand_child with writes_to_console("In grand child"): await bot.process_commands(command=grand_child) assert bot.get_command("other_child") is None assert bot.get_command("parent other_child") is other_child with writes_to_console("In other child"): await bot.process_commands(command=other_child) called_image_converter = False called_command_converter = False @commands.converter_for(commands.Command) def command_converter(argument: str) -> None: global called_command_converter called_command_converter = True class ImageConverter(commands.Converter[steam.Image]): async def convert(self, ctx: commands.Context, argument: str) -> None: global called_image_converter called_image_converter = True @pytest.mark.asyncio async def test_converters() -> None: bot = TheTestBot() @bot.command async def source(_, command: commands.Command): ... assert command_converter.converter_for == commands.Command assert commands.Command in bot.converters await bot.process_commands("not a command", None) assert called_command_converter @bot.command async def set_avatar(_, image: steam.Image): ... assert ImageConverter.converter_for is steam.Image assert steam.Image in bot.converters await bot.process_commands("https://not_an_image.com", None) assert called_image_converter def teardown_module(_) -> None: for error in FAILS: traceback.print_exception(error.__class__, error, error.__traceback__) if FAILS: pytest.fail("failed to finish tests")
28.560914
111
0.64445
4a103648a367a8f44cb00908c0b56beb2aa894c8
2,017
py
Python
collection/launcher.py
L0adinggg/Braised-vegetables
d979bb0affd6257178f5b22e675d6350ece41b44
[ "CC0-1.0" ]
20
2021-06-02T03:20:34.000Z
2021-11-10T03:29:25.000Z
collection/launcher.py
L0adinggg/Braised-vegetables
d979bb0affd6257178f5b22e675d6350ece41b44
[ "CC0-1.0" ]
null
null
null
collection/launcher.py
L0adinggg/Braised-vegetables
d979bb0affd6257178f5b22e675d6350ece41b44
[ "CC0-1.0" ]
2
2022-03-17T04:06:47.000Z
2022-03-17T06:17:04.000Z
#!/usr/bin/python3 # coding: utf-8 import queue import simplejson import threading import subprocess import requests import warnings warnings.filterwarnings(action='ignore') urls_queue = queue.Queue() tclose=0 def opt2File(paths): try: f = open('crawl_result.txt','a') f.write(paths + '\n') finally: f.close() def opt2File2(subdomains): try: f = open('sub_domains.txt','a') f.write(subdomains + '\n') finally: f.close() def request0(): while tclose==0 or urls_queue.empty() == False: if(urls_queue.qsize()==0): continue print(urls_queue.qsize()) req =urls_queue.get() proxies = { 'http': 'http://127.0.0.1:7777', 'https': 'http://127.0.0.1:7777', } urls0 =req['url'] headers0 =req['headers'] method0=req['method'] data0=req['data'] try: if(method0=='GET'): a = requests.get(urls0, headers=headers0, proxies=proxies,timeout=30,verify=False) opt2File(urls0) elif(method0=='POST'): a = requests.post(urls0, headers=headers0,data=data0, proxies=proxies,timeout=30,verify=False) opt2File(urls0) except: continue return def main(data1): target = data1 cmd = ["./crawlergo.exe", "-c", "C:/Users/Administrator/Desktop/Win_x64_823063_chrome-win/chrome-win/chrome.exe","-t", "20","-f","smart","--fuzz-path", "--output-mode", "json", target] rsp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = rsp.communicate() try: result = simplejson.loads(output.decode().split("--[Mission Complete]--")[1]) except: return req_list = result["req_list"] sub_domain = result["sub_domain_list"] print(data1) print("[crawl ok]") for subd in sub_domain: opt2File2(subd) for req in req_list: urls_queue.put(req) print("[scanning]") if __name__ == '__main__': file = open("targets.txt") t = threading.Thread(target=request0) t.start() for text in file.readlines(): data1 = text.strip('\n') main(data1) tclose=1
23.729412
186
0.650471
4a1038cb2f56ce8aa6f61ec4c863614a3d27c93e
1,320
py
Python
assignments/03_days/days.py
charlesb107/biosystems-analytics-2020
38d61c2db203626777db384ca720695723d61e8f
[ "MIT" ]
null
null
null
assignments/03_days/days.py
charlesb107/biosystems-analytics-2020
38d61c2db203626777db384ca720695723d61e8f
[ "MIT" ]
null
null
null
assignments/03_days/days.py
charlesb107/biosystems-analytics-2020
38d61c2db203626777db384ca720695723d61e8f
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """ Author : charlesb107 Date : 2020-02-17 Purpose: Repeat the days of the week Reference: Tiny Python Projects (Book)/Biosystems Analytics (BE534), Spring 2020 """ import argparse import os import sys # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='What to do on each day', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('day', metavar='str', nargs='+', help='Days of the week') return parser.parse_args() # -------------------------------------------------- def main(): args = get_args() todo = { 'Monday' : 'On Mondays I never go to work', 'Tuesday' : 'On Tuesdays I stay at home', 'Wednesday' : 'On Wednesdays I never feel inclined', 'Thursday' : "On Thursdays, it's a holiday", 'Friday' : 'And Fridays I detest', 'Saturday' : "Oh, it's much too late on a Saturday", 'Sunday' : 'And Sunday is the day of rest'} for day in args.day: print(todo.get(day, f'Can\'t find "{day}"')) #--------------------------------------------------- if __name__ == '__main__': main()
25.882353
80
0.520455
4a10395677bb4896012a15f4307c081c65ba0db1
1,479
py
Python
app/core/tools/integrals.py
Matexer/BSPR
a503a8795cb0f4cebe2eedd148aa00aea75b570e
[ "MIT" ]
null
null
null
app/core/tools/integrals.py
Matexer/BSPR
a503a8795cb0f4cebe2eedd148aa00aea75b570e
[ "MIT" ]
null
null
null
app/core/tools/integrals.py
Matexer/BSPR
a503a8795cb0f4cebe2eedd148aa00aea75b570e
[ "MIT" ]
null
null
null
import numpy as np class Integrals: @staticmethod def rect(prep_p_sur, smp_time): return smp_time * sum(prep_p_sur) @staticmethod def trapeze(prep_p_sur, smp_time): if len(prep_p_sur) < 2: return prep_p_sur[0] * smp_time A = (prep_p_sur[0] + prep_p_sur[-1]) / 2 return smp_time * (sum(prep_p_sur[1:-1]) + A) @staticmethod def simpson(prep_p_sur, smp_time): if len(prep_p_sur) < 2: return prep_p_sur[0] * smp_time h_smp_time = smp_time / 2 x = [h_smp_time * i for i in range(2 * len(prep_p_sur) - 1)] y = [prep_p_sur[0]] total_sum = 0 for val in prep_p_sur[1:]: y.append((val + y[-1]) / 2) y.append(val) for v in range(len(prep_p_sur) - 1): j = 2 * v y_1 = y[j] y_2 = y[j + 1] y_3 = y[j + 2] f_1 = [x[j] ** 2, x[j], 1] f_2 = [x[j + 1] ** 2, x[j + 1], 1] f_3 = [x[j + 2] ** 2, x[j + 2], 1] f_m = np.array([f_1, f_2, f_3]) y_m = np.array([y_1, y_2, y_3]) f_r = np.linalg.inv(f_m) para = f_r @ y_m a = para[0] b = para[1] c = para[2] x_p = x[j] x_k = x[j + 2] P = a * ((x_k ** 3) - (x_p ** 3)) / 3 + b * ((x_k ** 2) - (x_p ** 2)) / 2 + c * (x_k - x_p) total_sum += P return total_sum
25.5
103
0.441515
4a1039a00afcb8202e0a77c3558e4bf3c77500ec
1,323
py
Python
aalh_iit_jdoylewitgencollection/merge-description-columns.py
johndewees/iitmigration
4dadfbecda719d6e7d60af076a231aedec3c862f
[ "Unlicense" ]
null
null
null
aalh_iit_jdoylewitgencollection/merge-description-columns.py
johndewees/iitmigration
4dadfbecda719d6e7d60af076a231aedec3c862f
[ "Unlicense" ]
null
null
null
aalh_iit_jdoylewitgencollection/merge-description-columns.py
johndewees/iitmigration
4dadfbecda719d6e7d60af076a231aedec3c862f
[ "Unlicense" ]
null
null
null
from openpyxl import load_workbook filename = 'aalh_iit_jdoylewitgencollection.xlsx' wb = load_workbook(filename) ws = wb['Metadata Template'] minimumcol = 8 maximumcol = 8 minimumrow = 7 maximumrow = 203 iterationrow = 7 targetcol = 46 linkstring = 'Terms associated with the photograph are: ' for row in ws.iter_rows(min_row=minimumrow, min_col=minimumcol, max_row=maximumrow, max_col=maximumcol): for cell in row: print(iterationrow) iitdescription = ws.cell(row=iterationrow, column=minimumcol).value print(iitdescription) keywords = ws.cell(row=iterationrow, column=targetcol).value print(keywords) if iitdescription == None: descriptionmerged = linkstring + keywords descriptionfinal = descriptionmerged.replace("&#39;", "'") ws.cell(row=iterationrow, column=minimumcol).value = descriptionfinal else: descriptionmerged = iitdescription + ' ' + linkstring + keywords descriptionfinal = descriptionmerged.replace("&#39;", "'") ws.cell(row=iterationrow, column=minimumcol).value = descriptionfinal print(ws.cell(row=iterationrow, column=minimumcol).value) iterationrow = iterationrow + 1 wb.save('aalh_iit_jdoylewitgencollection.xlsx')
40.090909
105
0.684807
4a1039eabafb7111bfb00e642c818ac7c4d16733
1,007
py
Python
env/lib/python3.6/site-packages/dipy/tracking/tests/test_learning.py
Raniac/NEURO-LEARN
3c3acc55de8ba741e673063378e6cbaf10b64c7a
[ "Apache-2.0" ]
8
2019-05-29T09:38:30.000Z
2021-01-20T03:36:59.000Z
env/lib/python3.6/site-packages/dipy/tracking/tests/test_learning.py
Raniac/neurolearn_dev
3c3acc55de8ba741e673063378e6cbaf10b64c7a
[ "Apache-2.0" ]
12
2021-03-09T03:01:16.000Z
2022-03-11T23:59:36.000Z
env/lib/python3.6/site-packages/dipy/tracking/tests/test_learning.py
Raniac/NEURO-LEARN
3c3acc55de8ba741e673063378e6cbaf10b64c7a
[ "Apache-2.0" ]
1
2020-07-17T12:49:49.000Z
2020-07-17T12:49:49.000Z
""" Testing track_metrics module """ import numpy as np from dipy.testing import assert_true, assert_false from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_equal, assert_almost_equal) from dipy.tracking import metrics as tm from dipy.tracking import distances as td from dipy.tracking import learning as tl def test_det_corr_tracks(): A = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) B = np.array([[1, 0, 0], [2, 0, 0], [3, 0, 0]]) C = np.array([[0, 0, -1], [0, 0, -2], [0, 0, -3]]) bundle1 = [A, B, C] bundle2 = [B, A] indices = [0, 1] print(A) print(B) print(C) arr = tl.detect_corresponding_tracks(indices, bundle1, bundle2) print(arr) assert_array_equal(arr, np.array([[0, 1], [1, 0]])) indices2 = [0, 1] arr2 = tl.detect_corresponding_tracks_plus(indices, bundle1, indices2, bundle2) print(arr2) assert_array_equal(arr, arr2)
29.617647
73
0.602781
4a103a118e1c971902cf6bf85399180a06392ffd
411
py
Python
polylexis/wsgi.py
heitorchang/polylexis
22589560fb015cffb6419308349c5518a5c38551
[ "MIT" ]
null
null
null
polylexis/wsgi.py
heitorchang/polylexis
22589560fb015cffb6419308349c5518a5c38551
[ "MIT" ]
null
null
null
polylexis/wsgi.py
heitorchang/polylexis
22589560fb015cffb6419308349c5518a5c38551
[ "MIT" ]
null
null
null
""" WSGI config for polylexis project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'polylexis.settings') application = get_wsgi_application()
24.176471
79
0.756691
4a103b325b9af15f0acd6a82f419f608c8be3f48
3,322
py
Python
product_analysis/ebike_analysis/ebike_specs.py
STNichols/product_analysis
cba20f17d7f30da534ccd2c3fc14bdeb9564d25b
[ "BSD-2-Clause" ]
null
null
null
product_analysis/ebike_analysis/ebike_specs.py
STNichols/product_analysis
cba20f17d7f30da534ccd2c3fc14bdeb9564d25b
[ "BSD-2-Clause" ]
1
2020-06-13T23:39:27.000Z
2020-06-13T23:39:27.000Z
product_analysis/ebike_analysis/ebike_specs.py
STNichols/product_analysis
cba20f17d7f30da534ccd2c3fc14bdeb9564d25b
[ "BSD-2-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Tue May 12 13:11:23 2020 @author: Sean """ import re import numpy as np import pandas as pd from ..utilities.web_browsing import make_soup base_url = "https://electricbikereview.com/category/bikes/" all_specs = { "make":{ "num":False }, "model":{ "num":False }, "price":{ "num":True, "units":"$" }, "total_weight":{ "num":True, "units":"lbs" }, "motor_nominal_output":{ "num":True, "units":"W" }, "estimated_min_range":{ "num":True, "units":"miles" }, "estimated_max_range":{ "num":True, "units":"miles" }, "battery_watt_hours":{ "num":True, "units":"wh" }, } def generate_url(base, page): """""" if page == 1: return base else: return base + "page/" + str(page) + "/" def find_numbers(val): """""" return [float(re.sub("\$|\,","",i)) for i in val.split() if re.sub("\.|\$|\,","",i).isdigit()] def find_products(soup): """""" pattern = "href=\"(.*?)\"" results = soup.find_all(href=re.compile("https://"), title=re.compile("Review")) if results is not None: urls = [] for r in results: rs = str(r) if "post-thumb-small" in rs: url = re.search(pattern, rs).group(1) urls.append(url) return urls return [] def find_specs(url, index=0): """""" # Generate the dataframe for this product product = pd.DataFrame(np.nan, index=[index], columns=all_specs) soup = make_soup(url) print(url) spec_results = soup.find_all("h4") for spec_name, dets in all_specs.items(): spec = spec_name.replace("_","").lower() for sr in spec_results: srs = str(sr).replace(" ","").lower() if spec in srs: spec_str = str(sr.next_sibling) spec_val = re.sub( "<span>|\n|\t|</span>", "", spec_str).replace(" ","") if dets['num']: numbers = find_numbers(spec_val) if numbers: spec_val = numbers[0] else: print(spec_name) print(spec_val) spec_val = np.nan product[spec_name] = spec_val break return product def compile_product_specs(n_pages=1, pages=None): """""" all_products = [] if pages is not None: pages_to_search = pages else: pages_to_search = range(n_pages) for pgi in pages_to_search: pg_num = pgi + 1 soup = make_soup(generate_url(base_url, pg_num)) urls_for_page = find_products(soup) all_products.extend(urls_for_page) full_specs = pd.DataFrame(columns=all_specs) for pi, product in enumerate(all_products): full_specs = full_specs.append(find_specs(product, index=pi)) full_specs['url'] = all_products return full_specs
25.751938
77
0.484648
4a103b51d00b6618eb6cf61270c1608a750915ec
967
py
Python
treasurySS/migrations/0003_data.py
uktrade/fadmin2
0f774400fb816c9ca30e30b25ae542135966e185
[ "MIT" ]
3
2020-01-05T16:46:42.000Z
2021-08-02T08:08:39.000Z
treasurySS/migrations/0003_data.py
uktrade/fadmin2
0f774400fb816c9ca30e30b25ae542135966e185
[ "MIT" ]
30
2019-11-28T15:16:35.000Z
2021-08-16T14:49:58.000Z
treasurySS/migrations/0003_data.py
uktrade/fadmin2
0f774400fb816c9ca30e30b25ae542135966e185
[ "MIT" ]
null
null
null
# Generated by Django 3.2.4 on 2021-07-29 08:49 from django.db import migrations def create_organizations(apps, schema_editor): OrganizationCode = apps.get_model("treasurySS", "OrganizationCode") Segment = apps.get_model("treasurySS", "Segment") organization_obj = OrganizationCode.objects.create( organization_code = "UKT013", organization_alias = "UK TRADE & INVESTMENT", active=True, ) Segment.objects.all().update(organization=organization_obj) organization_obj = OrganizationCode.objects.create( organization_code = "TRA013", organization_alias = "TRADE REMEDIES AUTHORITY (TRA)", active=True, ) Segment.objects.filter(segment_code="S013A007").update(organization=organization_obj) class Migration(migrations.Migration): dependencies = [ ('treasurySS', '0002_auto_20210729_0846'), ] operations = [ migrations.RunPython(create_organizations), ]
31.193548
89
0.703206
4a103d11a39917fbbc4402c9e4a2d20c31a0b897
97
py
Python
Chapter_1/misc/new_test.py
aquib-sh/C_Programming_Exercises
6753164dd8e4f090751db5f988eb27f1bc7363f8
[ "CC0-1.0" ]
null
null
null
Chapter_1/misc/new_test.py
aquib-sh/C_Programming_Exercises
6753164dd8e4f090751db5f988eb27f1bc7363f8
[ "CC0-1.0" ]
null
null
null
Chapter_1/misc/new_test.py
aquib-sh/C_Programming_Exercises
6753164dd8e4f090751db5f988eb27f1bc7363f8
[ "CC0-1.0" ]
null
null
null
while True: try: got = input() print(got) except EOFError: break
13.857143
21
0.484536
4a103dc50cc62cf19625f100631d54e2b40ae601
518
py
Python
array/1701_average_waiting_time/1701_average_waiting_time.py
zdyxry/LeetCode
33371285d0f3302158230f46e8b1b63b9f4639c4
[ "Xnet", "X11" ]
6
2019-09-16T01:50:44.000Z
2020-09-17T08:52:25.000Z
array/1701_average_waiting_time/1701_average_waiting_time.py
zdyxry/LeetCode
33371285d0f3302158230f46e8b1b63b9f4639c4
[ "Xnet", "X11" ]
null
null
null
array/1701_average_waiting_time/1701_average_waiting_time.py
zdyxry/LeetCode
33371285d0f3302158230f46e8b1b63b9f4639c4
[ "Xnet", "X11" ]
4
2020-02-07T12:43:16.000Z
2021-04-11T06:38:55.000Z
from typing import List class Solution: def averageWaitingTime(self, customers: List[List[int]]) -> float: cur = customers[0][0] total = 0 for c in customers: if cur >= c[0]: cur = cur + c[1] total += cur - c[0] else: cur = c[0] + c[1] total += c[1] return float(total) / len(customers) customers = [[1,2],[2,5],[4,3]] res = Solution().averageWaitingTime(customers) print(res)
24.666667
70
0.482625
4a103e8e4b061031a7b0e38b7a21f41596712267
4,204
py
Python
tests/clvm/coin_store.py
Storch-Network/chialite
587fc53e8ef452e07c6f3f266f58962d065feb5c
[ "Apache-2.0" ]
2
2021-06-29T14:05:41.000Z
2021-07-15T19:28:26.000Z
tests/clvm/coin_store.py
Storch-Network/chialite
587fc53e8ef452e07c6f3f266f58962d065feb5c
[ "Apache-2.0" ]
31
2021-06-26T23:11:46.000Z
2022-03-29T00:12:30.000Z
tests/clvm/coin_store.py
Storch-Network/chialite
587fc53e8ef452e07c6f3f266f58962d065feb5c
[ "Apache-2.0" ]
null
null
null
from collections import defaultdict from dataclasses import dataclass, replace from typing import Dict, Iterator, Set from chialite.full_node.mempool_check_conditions import mempool_check_conditions_dict from chialite.types.blockchain_format.coin import Coin from chialite.types.blockchain_format.sized_bytes import bytes32 from chialite.types.coin_record import CoinRecord from chialite.types.spend_bundle import SpendBundle from chialite.util.condition_tools import ( conditions_dict_for_solution, coin_announcement_names_for_conditions_dict, puzzle_announcement_names_for_conditions_dict, ) from chialite.util.ints import uint32, uint64 class BadSpendBundleError(Exception): pass @dataclass class CoinTimestamp: seconds: int height: int class CoinStore: def __init__(self): self._db: Dict[bytes32, CoinRecord] = dict() self._ph_index = defaultdict(list) def farm_coin(self, puzzle_hash: bytes32, birthday: CoinTimestamp, amount: int = 1024) -> Coin: parent = birthday.height.to_bytes(32, "big") coin = Coin(parent, puzzle_hash, uint64(amount)) self._add_coin_entry(coin, birthday) return coin def validate_spend_bundle( self, spend_bundle: SpendBundle, now: CoinTimestamp, max_cost: int, ) -> int: # this should use blockchain consensus code coin_announcements: Set[bytes32] = set() puzzle_announcements: Set[bytes32] = set() conditions_dicts = [] for coin_solution in spend_bundle.coin_solutions: err, conditions_dict, cost = conditions_dict_for_solution( coin_solution.puzzle_reveal, coin_solution.solution, max_cost ) if conditions_dict is None: raise BadSpendBundleError(f"clvm validation failure {err}") conditions_dicts.append(conditions_dict) coin_announcements.update( coin_announcement_names_for_conditions_dict(conditions_dict, coin_solution.coin.name()) ) puzzle_announcements.update( puzzle_announcement_names_for_conditions_dict(conditions_dict, coin_solution.coin.puzzle_hash) ) for coin_solution, conditions_dict in zip(spend_bundle.coin_solutions, conditions_dicts): prev_transaction_block_height = now.height timestamp = now.seconds coin_record = self._db[coin_solution.coin.name()] err = mempool_check_conditions_dict( coin_record, coin_announcements, puzzle_announcements, conditions_dict, uint32(prev_transaction_block_height), uint64(timestamp), ) if err is not None: raise BadSpendBundleError(f"condition validation failure {err}") return 0 def update_coin_store_for_spend_bundle(self, spend_bundle: SpendBundle, now: CoinTimestamp, max_cost: int): err = self.validate_spend_bundle(spend_bundle, now, max_cost) if err != 0: raise BadSpendBundleError(f"validation failure {err}") for spent_coin in spend_bundle.removals(): coin_name = spent_coin.name() coin_record = self._db[coin_name] self._db[coin_name] = replace(coin_record, spent_block_index=now.height, spent=True) for new_coin in spend_bundle.additions(): self._add_coin_entry(new_coin, now) def coins_for_puzzle_hash(self, puzzle_hash: bytes32) -> Iterator[Coin]: for coin_name in self._ph_index[puzzle_hash]: coin_entry = self._db[coin_name] assert coin_entry.coin.puzzle_hash == puzzle_hash yield coin_entry.coin def all_coins(self) -> Iterator[Coin]: for coin_entry in self._db.values(): yield coin_entry.coin def _add_coin_entry(self, coin: Coin, birthday: CoinTimestamp) -> None: name = coin.name() assert name not in self._db self._db[name] = CoinRecord(coin, uint32(birthday.height), uint32(0), False, False, uint64(birthday.seconds)) self._ph_index[coin.puzzle_hash].append(name)
38.925926
117
0.682207
4a1041663ade8650287aee98ca4620160a1e51a5
1,517
py
Python
utils.py
jeccec51/WordPrediction
53607414bd8f44a3fd0d2c2ec6f0d3f0fc7bbba3
[ "BSD-2-Clause" ]
1
2020-11-21T07:12:55.000Z
2020-11-21T07:12:55.000Z
utils.py
jeccec51/WordPrediction
53607414bd8f44a3fd0d2c2ec6f0d3f0fc7bbba3
[ "BSD-2-Clause" ]
null
null
null
utils.py
jeccec51/WordPrediction
53607414bd8f44a3fd0d2c2ec6f0d3f0fc7bbba3
[ "BSD-2-Clause" ]
null
null
null
import re from collections import Counter def preprocess(text): # Replace punctuation with tokens so we can use them in our model text = text.lower() text = text.replace('.', ' <PERIOD> ') text = text.replace(',', ' <COMMA> ') text = text.replace('"', ' <QUOTATION_MARK> ') text = text.replace(';', ' <SEMICOLON> ') text = text.replace('!', ' <EXCLAMATION_MARK> ') text = text.replace('?', ' <QUESTION_MARK> ') text = text.replace('(', ' <LEFT_PAREN> ') text = text.replace(')', ' <RIGHT_PAREN> ') text = text.replace('--', ' <HYPHENS> ') text = text.replace('?', ' <QUESTION_MARK> ') # text = text.replace('\n', ' <NEW_LINE> ') text = text.replace(':', ' <COLON> ') words = text.split() # Remove all words with 5 or fewer occurences word_counts = Counter(words) trimmed_words = [word for word in words if word_counts[word] > 5] return trimmed_words def create_lookup_tables(words): """ Create lookup tables for vocabulary :param words: Input list of words :return: Two dictionaries, vocab_to_int, int_to_vocab """ word_counts = Counter(words) # sorting the words from most to least frequent in text occurrence sorted_vocab = sorted(word_counts, key=word_counts.get, reverse=True) # create int_to_vocab dictionaries int_to_vocab = {ii: word for ii, word in enumerate(sorted_vocab)} vocab_to_int = {word: ii for ii, word in int_to_vocab.items()} return vocab_to_int, int_to_vocab
33.711111
73
0.644034
4a1041b3af332d5688b2676e560580c5c3893d8b
292
py
Python
tests/__main__.py
CaioRuizz/DevOps_Curso_Ftt
ca71114b003eed9dc2551d4c7ce5b1d3af56c5dd
[ "MIT" ]
null
null
null
tests/__main__.py
CaioRuizz/DevOps_Curso_Ftt
ca71114b003eed9dc2551d4c7ce5b1d3af56c5dd
[ "MIT" ]
null
null
null
tests/__main__.py
CaioRuizz/DevOps_Curso_Ftt
ca71114b003eed9dc2551d4c7ce5b1d3af56c5dd
[ "MIT" ]
null
null
null
import unittest import sys if __name__ == "__main__": test_suite = unittest.defaultTestLoader.discover('./tests', '*_test.py') test_runner = unittest.TextTestRunner(resultclass=unittest.TextTestResult) result = test_runner.run(test_suite) sys.exit(not result.wasSuccessful())
36.5
78
0.756849
4a1042cc3e50c8920ec2fdee597e68c3aa8e8d12
20,318
py
Python
mapclientplugins/cimconverterstep/SurfaceExtractor.py
HiiKevin/mapclientplugins.cimconverterstep
66a2ebc5482b9eb3f3c58ab6fb7cec9531ef6140
[ "Apache-2.0" ]
null
null
null
mapclientplugins/cimconverterstep/SurfaceExtractor.py
HiiKevin/mapclientplugins.cimconverterstep
66a2ebc5482b9eb3f3c58ab6fb7cec9531ef6140
[ "Apache-2.0" ]
null
null
null
mapclientplugins/cimconverterstep/SurfaceExtractor.py
HiiKevin/mapclientplugins.cimconverterstep
66a2ebc5482b9eb3f3c58ab6fb7cec9531ef6140
[ "Apache-2.0" ]
1
2022-01-17T04:05:45.000Z
2022-01-17T04:05:45.000Z
from datetime import time import numpy as np import csv import os import glob import natsort import pandas as pd import re import warnings import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D, art3d class Subdivision_Surface(): ''' This class create a surface from the control mesh, based on Catmull Clark subdivision surface method ... Attributes ---------- etPos : array-like Matrix containing model after subdivision matrix : array-like Subdivision matrix (from coarse mesh to 3D model) numNodes : int Number of nodes (coarse mesh) numElements : int Number of elements ETIndices : array-like Faces (subdivided model) control_mesh : array-like Coarse mesh faceCM : array-like Coarse mesh connections faceCMsorted : array-like Faces (coarse mesh/template) etVertexStartEnd : array-like Start and End indices CMStartEnd : array-like Start and End indices SurfaceStartEnd : array-like Start and End indices Methods ------- Plot(SurfaceType,time_frame = 0) Plots the points of the model at a specified time frame on a 3d axis for visualisation. PlotCM(SurfaceType,time_frame = 0) Plots the points of the coarse mesh at a specified time frame on a 3d axis for visualisation. ''' etPos = None # model after subdivision matrix = None # subdivision matrix (from coarse mesh to 3D model) numNodes = 388 # number of nodes (coarse mesh) numElements = 187; # number of elements ETIndices = None # Faces (subdivided model) control_mesh = None # Coarse mesh faceCM = None # Coarse mesh connections faceCMsorted = None # Faces (coarse mesh/template) def __init__(self,type,FilePath): """ Inputs ------ type: str initialisation type FilePath: path-like directory where the model folder(s) are stored """ dir_path=os.path.dirname(os.path.realpath(__file__)) # load in matrices from text self.matrix = np.loadtxt(dir_path+'\\subdivision_matrix.txt') self.ETIndices = np.loadtxt(dir_path+'\\ETIndices.txt') self.faceCM = np.loadtxt(dir_path+'\\ETIndices_control_mesh.txt') # initialise matrix indices self.CMStartEnd = np.array([[1,96], # LV [97,211], # RV [212,354] # Epi ])-1 # convert indexing from 1 index to 0 index self.etVertexStartEnd = np.array([[1,1500], # LV (vertices 1 to 1500 belong to the LV chamber...) [1501,2165], # RVS [2166,3224], # RVFW [3225,5582], # Epi [5583,5631], # Mitral valve [5632,5656], # Aortic valve [5657,5697], # Tricuspid valve [5698,5730], # Pulmonary valve [5731,5810] # RV insert ])-1 # convert indexing from 1 index to 0 index self.SurfaceStartEnd = np.array([[1,3072], # LV (vertices 1 to 3072 belong to the LV chamber...) [3073,4480], # RVS [4481,6752], # RVFW [6753,11616], # Epi [11617,11664], # Mitral valve [11665,11688], # Aortic valve [11689,11728], # Tricuspid valve [11729,11760] # Pulmonary valve ])-1 # convert indexing from 1 index to 0 index if type == 'InitFromControlMesh': self.control_mesh[:,:,1] = np.loadtxt(FilePath); self.etPos[:,:,1] = np.matmul(self.matrix,self.control_mesh) elif type =='InitFromCIM': if len(glob.glob(os.path.abspath(FilePath)+"\\*model\\*")) > 0: # ensure model folder(s) exists # extract .model files and sort numerically files = glob.glob(os.path.abspath(FilePath)+"\\*model\\*.model") files = natsort.natsorted(files) # read each model file and store data for i in range(0,len(files)): P = ReadFromCIMRVLVModel(os.path.join(os.path.abspath(FilePath),files[i])) if self.control_mesh is not None: self.control_mesh=np.concatenate((self.control_mesh, np.array([[P.XParameters,P.YParameters,P.ZParameters]]).T),axis=2) else: self.control_mesh=np.array([[P.XParameters,P.YParameters,P.ZParameters]]).T # initialise matrix on first time if self.etPos is not None: self.etPos=np.concatenate((self.etPos,np.matmul(self.matrix,self.control_mesh[:,:,i])[:,:,np.newaxis]),axis=2) else: self.etPos = np.matmul(self.matrix,self.control_mesh[:,:,i])[:,:,np.newaxis] # initialise matrix on first time else: raise Exception('No CIM model folder found') else: raise Exception('please select your initialisation: InitFromCIM if you are dealing with CIM data or InitFromControlMesh if you only have a coarse mesh') def Plot(self,SurfaceType,time_frame = 0): """Plots the points of the model at a specified time frame on a 3d axis for visualisation. Inputs ------ SurfaceType: str Type of surface that is to be plotted time_frame: int, optional Index of which time frame is to be plotted (default is 0) """ if SurfaceType=='endo': faces_lv=self.ETIndices[range(self.SurfaceStartEnd[0,0],self.SurfaceStartEnd[0,1]+1),:] faces_rv=self.ETIndices[range(self.SurfaceStartEnd[1,0],self.SurfaceStartEnd[2,1]+1),:] x,y,z=self.etPos[:,:,time_frame].T ax = plt.figure().add_subplot(projection='3d') ax.set_box_aspect((np.max(x)-np.min(x), np.max(y)-np.min(y), np.max(z)-np.min(z))) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.title('Endocardium at t = '+str(time_frame)) ax.plot_trisurf(x, y, z, triangles=faces_lv-1,color='green', alpha=0.75,edgecolors='black',linewidth=0.2) ax.plot_trisurf(x, y, z, triangles=faces_rv-1,color='blue', alpha=0.75,edgecolors='black',linewidth=0.2) plt.show() if SurfaceType=='LV': faces_lv=self.ETIndices[range(self.SurfaceStartEnd[0,0],self.SurfaceStartEnd[0,1]+1),:] x,y,z=self.etPos[:,:,time_frame].T ax = plt.figure().add_subplot(projection='3d') ax.set_box_aspect((np.max(x)-np.min(x), np.max(y)-np.min(y), np.max(z)-np.min(z))) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.title('LV at t = '+str(time_frame)) ax.plot_trisurf(x, y, z, triangles=faces_lv-1,color='green', alpha=0.75,edgecolors='black',linewidth=0.2) plt.show() if SurfaceType=='RV': faces_rv=self.ETIndices[range(self.SurfaceStartEnd[1,0],self.SurfaceStartEnd[2,1]+1),:] x,y,z=self.etPos[:,:,time_frame].T ax = plt.figure().add_subplot(projection='3d') ax.set_box_aspect((np.max(x)-np.min(x), np.max(y)-np.min(y), np.max(z)-np.min(z))) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.title('RV at t = '+str(time_frame)) ax.plot_trisurf(x, y, z, triangles=faces_rv-1,color='blue', alpha=0.75,edgecolors='black',linewidth=0.2) plt.show() if SurfaceType=='epi': faces_epi=self.ETIndices[range(self.SurfaceStartEnd[3,0],self.SurfaceStartEnd[3,1]+1),:] x,y,z=self.etPos[:,:,time_frame].T ax = plt.figure().add_subplot(projection='3d') ax.set_box_aspect((np.max(x)-np.min(x), np.max(y)-np.min(y), np.max(z)-np.min(z))) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.title('Epicardium at t = '+str(time_frame)) ax.plot_trisurf(x, y, z, triangles=faces_epi-1,color='red', alpha=0.75,edgecolors='black',linewidth=0.2) plt.show() if SurfaceType=='all': faces_lv=self.ETIndices[range(self.SurfaceStartEnd[0,0],self.SurfaceStartEnd[0,1]+1),:] faces_rv=self.ETIndices[range(self.SurfaceStartEnd[1,0],self.SurfaceStartEnd[2,1]+1),:] faces_epi=self.ETIndices[range(self.SurfaceStartEnd[3,0],self.SurfaceStartEnd[3,1]+1),:] x,y,z=self.etPos[:,:,time_frame].T ax = plt.figure().add_subplot(projection='3d') ax.set_box_aspect((np.max(x)-np.min(x), np.max(y)-np.min(y), np.max(z)-np.min(z))) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.title('Biventricular model at t = '+str(time_frame)) ax.plot_trisurf(x, y, z, triangles=faces_lv-1,color='green', alpha=0.9,edgecolors='black',linewidth=0.2) ax.plot_trisurf(x, y, z, triangles=faces_rv-1,color='blue', alpha=0.9,edgecolors='black',linewidth=0.2) ax.plot_trisurf(x, y, z, triangles=faces_epi-1,color='red', alpha=0.4,edgecolors='black',linewidth=0.2) plt.show() def PlotCM(self,SurfaceType,time_frame = 0): """Plots the points of the coarse mesh at a specified time frame on a 3d axis for visualisation. Inputs ------ SurfaceType: str Type of surface that is to be plotted time_frame: int, optional Index of which time frame is to be plotted (default is 0) """ if SurfaceType=='all': faces_lv=self.faceCM[range(self.CMStartEnd[0,0],self.CMStartEnd[0,1]+1),:] faces_rv=self.faceCM[range(self.CMStartEnd[1,0],self.CMStartEnd[1,1]+1),:] faces_epi=self.faceCM[range(self.CMStartEnd[2,0],self.CMStartEnd[2,1]+1),:] v=self.control_mesh[:,:,time_frame].T ax = plt.figure().add_subplot(projection='3d') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_xlim3d(min(v[0,:])-1, max(v[0,:])+1) ax.set_ylim3d(min(v[1,:])-1, max(v[1,:])+1) ax.set_zlim3d(min(v[2,:])-1, max(v[2,:])+1) plt.title('Coarse Mesh at t = '+str(time_frame)) pc1 = art3d.Poly3DCollection(v[:,(faces_lv-1).astype(int).T].T, facecolors='green', edgecolor="black",alpha=0.2) pc2 = art3d.Poly3DCollection(v[:,(faces_rv-1).astype(int).T].T, facecolors='blue', edgecolor="black",alpha=0.2) pc3 = art3d.Poly3DCollection(v[:,(faces_epi-1).astype(int).T].T, facecolors='red', edgecolor="black",alpha=0.2) ax.add_collection(pc1) ax.add_collection(pc2) ax.add_collection(pc3) plt.show() if SurfaceType=='LV': faces_lv=self.faceCM[range(self.CMStartEnd[0,0],self.CMStartEnd[0,1]+1),:] v=self.control_mesh[:,:,time_frame].T ax = plt.figure().add_subplot(projection='3d') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_xlim3d(min(v[0,:])-1, max(v[0,:])+1) ax.set_ylim3d(min(v[1,:])-1, max(v[1,:])+1) ax.set_zlim3d(min(v[2,:])-1, max(v[2,:])+1) plt.title('Coarse LV at t = '+str(time_frame)) pc = art3d.Poly3DCollection(v[:,(faces_lv-1).astype(int).T].T, facecolors='green', edgecolor="black",alpha=0.2) ax.add_collection(pc) plt.show() if SurfaceType=='RV': faces_rv=self.faceCM[range(self.CMStartEnd[1,0],self.CMStartEnd[1,1]+1),:] v=self.control_mesh[:,:,time_frame].T ax = plt.figure().add_subplot(projection='3d') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_xlim3d(min(v[0,:])-1, max(v[0,:])+1) ax.set_ylim3d(min(v[1,:])-1, max(v[1,:])+1) ax.set_zlim3d(min(v[2,:])-1, max(v[2,:])+1) plt.title('Coarse RV at t = '+str(time_frame)) pc = art3d.Poly3DCollection(v[:,(faces_rv-1).astype(int).T].T, facecolors='blue', edgecolor="black",alpha=0.2) ax.add_collection(pc) plt.show() if SurfaceType=='endo': faces_endo=self.faceCM[range(self.CMStartEnd[0,0],self.CMStartEnd[1,1]+1),:] v=self.control_mesh[:,:,time_frame].T ax = plt.figure().add_subplot(projection='3d') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_xlim3d(min(v[0,:])-1, max(v[0,:])+1) ax.set_ylim3d(min(v[1,:])-1, max(v[1,:])+1) ax.set_zlim3d(min(v[2,:])-1, max(v[2,:])+1) plt.title('Coarse endocardium at t = '+str(time_frame)) pc = art3d.Poly3DCollection(v[:,(faces_endo-1).astype(int).T].T, facecolors='red', edgecolor="black",alpha=0.2) ax.add_collection(pc) plt.show() if SurfaceType=='epi': faces_epi=self.faceCM[range(self.CMStartEnd[2,0],self.CMStartEnd[2,1]+1),:] v=self.control_mesh[:,:,time_frame].T ax = plt.figure().add_subplot(projection='3d') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_xlim3d(min(v[0,:])-1, max(v[0,:])+1) ax.set_ylim3d(min(v[1,:])-1, max(v[1,:])+1) ax.set_zlim3d(min(v[2,:])-1, max(v[2,:])+1) plt.title('Coarse epicardium at t = '+str(time_frame)) pc = art3d.Poly3DCollection(v[:,(faces_epi-1).astype(int).T].T, facecolors='red', edgecolor="black",alpha=0.2) ax.add_collection(pc) plt.show() class ReadFromCIMRVLVModel(): ''' This class creates an RVLV model by reading from from a CIM RVLV file ... Attributes ---------- ScaleFactor : float Scale factor ModelToMagnetTransform : array-like Model to magnet transform matrix XParameters : array-like X coordinates YParameters : array-like Y coordinates ZParameters : array-like Z coordinates ''' def __init__(self,cim_file): """ Inputs ------ cim_file: path-like directory of CIM (.model) file to be read """ # initialise dictionary for parameter types params = ['scaleFactor'.casefold(), 'ModelToMagnetTransform:ScaleFactor'.casefold(), 'ModelToMagnetTransform'.casefold(),'XParameters'.casefold(), 'YParameters'.casefold(),'ZParameters'.casefold()] df=pd.DataFrame({"type": pd.Series(['scalar','scalar','invIJK','vector','vector','vector'],index=params), "value": pd.Series([[],[],[],[],[],[]], index=params) }) # ensure files can be read assert os.path.isfile(cim_file), 'Cannot read file ' + cim_file # read each .model file with open(cim_file, "r") as file: line = file.readline() while len(line) != 0: line=line.rstrip() # skip empty line if len(line) == 0: line = file.readline() continue # ignore this one if line == 'ModelToMagnetTransform:': line = file.readline() continue # remove last if line[-1] == ':': line=line[0:-1] # find which parameter it is assert line.casefold() in df.index, 'unhandled parameter type '+line param=line.casefold() if df['type'][param] == 'scalar': df['value'][param].append(float(file.readline().rstrip())) elif df['type'][param] == 'vector': nelmt=int(file.readline().rstrip()) for i in range(0,nelmt): df['value'][param].append(float(file.readline().rstrip())) elif df['type'][param] == 'invIJK': for i in range(0,4): data=[float(i) for i in re.findall('([0-9e.\-]+)i\s+([0-9e.\-]+)j\s+([0-9e.\-]+)k',file.readline().rstrip())[0]] df['value'][param].append(data) else: warnings.warn('Unknown parameter type of.' + param + 'Skip.\n',) continue line=file.readline() file.close() # store data in appropriate arrays self.scaleFactor=df['value']['scaleFactor'.casefold()] self.ModelToMagnetTransform=np.array(df['value']['ModelToMagnetTransform'.casefold()]).T self.XParameters=np.array(df['value']['XParameters'.casefold()]) self.YParameters=np.array(df['value']['YParameters'.casefold()]) self.ZParameters=np.array(df['value']['ZParameters'.casefold()]) def main(): """This script reads the cardiohance_082 .model files to create a Subdivision_Surface model and writes the xyz coordinates of the model to csv files in the OutputPath. """ FilePath = '.\\input\\cardiohance_082' OutputPath = '.\\output_python' model = Subdivision_Surface('InitFromCIM',FilePath) time_frame = np.shape(model.etPos)[2] # write to csv (disabled for debugging) if False: for i in range(time_frame): LVendo = model.etPos[range(model.etVertexStartEnd[0,0],model.etVertexStartEnd[0,1]+1),:,i] RV_S = model.etPos[range(model.etVertexStartEnd[1,0],model.etVertexStartEnd[1,1]+1),:,i] RV_FW = model.etPos[range(model.etVertexStartEnd[2,0],model.etVertexStartEnd[2,1]+1),:,i] Epi = model.etPos[range(model.etVertexStartEnd[3,0],model.etVertexStartEnd[3,1]+1),:,i] MV = model.etPos[range(model.etVertexStartEnd[4,0],model.etVertexStartEnd[4,1]+1),:,i] AV = model.etPos[range(model.etVertexStartEnd[5,0],model.etVertexStartEnd[5,1]+1),:,i] TV = model.etPos[range(model.etVertexStartEnd[6,0],model.etVertexStartEnd[6,1]+1),:,i] PV = model.etPos[range(model.etVertexStartEnd[7,0],model.etVertexStartEnd[7,1]+1),:,i] np.savetxt(os.path.abspath(OutputPath)+'\\'+'LVendo_'+str(i+1)+'.csv',LVendo,delimiter=',') np.savetxt(os.path.abspath(OutputPath)+'\\'+'RV_septum_'+str(i+1)+'.csv',RV_S,delimiter=',') np.savetxt(os.path.abspath(OutputPath)+'\\'+'RV_freewall_'+str(i+1)+'.csv',RV_FW,delimiter=',') np.savetxt(os.path.abspath(OutputPath)+'\\'+'Epi_'+str(i+1)+'.csv',Epi,delimiter=',') np.savetxt(os.path.abspath(OutputPath)+'\\'+'MV_'+str(i+1)+'.csv',MV[:-1,:],delimiter=',') np.savetxt(os.path.abspath(OutputPath)+'\\'+'AV_'+str(i+1)+'.csv',AV[:-1,:],delimiter=',') np.savetxt(os.path.abspath(OutputPath)+'\\'+'TV_'+str(i+1)+'.csv',TV[:-1,:],delimiter=',') np.savetxt(os.path.abspath(OutputPath)+'\\'+'PV_'+str(i+1)+'.csv',PV[:-1,:],delimiter=',') if __name__ == "__main__": main()
50.542289
164
0.538783
4a1044acbfe38f26f5164aeaffff4e3a888ea775
953
py
Python
tweet_builder.py
hundvalp/puppy-pills
50e691c6a6882ff1d1d7c9fd13cbd663862c7e9c
[ "MIT" ]
null
null
null
tweet_builder.py
hundvalp/puppy-pills
50e691c6a6882ff1d1d7c9fd13cbd663862c7e9c
[ "MIT" ]
null
null
null
tweet_builder.py
hundvalp/puppy-pills
50e691c6a6882ff1d1d7c9fd13cbd663862c7e9c
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- class TweetBuilder(object): """Constructs tweets to specific users""" def __init__(self, mention_users): """Create a new tweet builder which will mention the given users""" super(TweetBuilder, self).__init__() # Convert lists to a space separated string if not isinstance(mention_users, str): mention_users = ' '.join(mention_users) # Ensure that the mention users string contains an @ before all usernames mention_users = ' '.join(mention_users.split()) # Remove multiple consecutive spaces mention_users = '@' + mention_users.replace('@', '').replace(' ', ' @') # The prefix of each tweet is the users to mention self.tweet_prefix = mention_users + ' ' def create_tweet(self, message): """Creates a tweet which mentions the builder's mention users with the given message""" return self.tweet_prefix + message
39.708333
95
0.654774
4a1044ed5e788d2e53d28a30dbe18165a2afbd9a
21,410
py
Python
solartf/core/block.py
solarfresh/solartf
69a5f2ed9990f71e7e19054c4e6e1206396f24e3
[ "Apache-2.0" ]
null
null
null
solartf/core/block.py
solarfresh/solartf
69a5f2ed9990f71e7e19054c4e6e1206396f24e3
[ "Apache-2.0" ]
null
null
null
solartf/core/block.py
solarfresh/solartf
69a5f2ed9990f71e7e19054c4e6e1206396f24e3
[ "Apache-2.0" ]
null
null
null
from tensorflow.keras import backend as K from tensorflow.keras.initializers import RandomNormal from tensorflow.keras import layers from tensorflow.keras.regularizers import l2 from . import activation as solar_activation from . import layer as solartf_layers from .util import (get_filter_nb_by_depth,) class Conv2DBlock(layers.Layer): def __init__(self, filters, kernel_size=3, strides=1, padding='same', use_bias=False, batch_normalization=True, normalize_axis=0, normalize_epsilon=1e-3, normalize_momentum=0.999, activation=None, **kwargs): super(Conv2DBlock, self).__init__(**kwargs) self.filters = filters self.kernel_size = kernel_size self.strides = strides self.padding = padding self.use_bias = use_bias self.batch_normalization = batch_normalization self.normalize_axis = normalize_axis self.normalize_epsilon = normalize_epsilon self.normalize_momentum = normalize_momentum self.activation = activation self.conv = layers.Conv2D(filters=self.filters, kernel_size=self.kernel_size, strides=self.strides, padding=self.padding, use_bias=self.use_bias) if self.batch_normalization is not None: self.batch_normalization_layer = layers.BatchNormalization( axis=self.normalize_axis, epsilon=self.normalize_epsilon, momentum=self.normalize_momentum ) if self.activation is not None: self.activation_layer = layers.Activation(activation) def build(self, input_shape): self.input_spec = layers.InputSpec(shape=input_shape) def call(self, x, *args, **kwargs): x = self.conv(x) if self.batch_normalization is not None: x = self.batch_normalization_layer(x) if self.activation is not None: x = self.activation_layer(x) return x def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'use_bias': self.use_bias, 'batch_normalization': self.batch_normalization, 'normalize_axis': self.normalize_axis, 'normalize_epsilon': self.normalize_epsilon, 'normalize_momentum': self.normalize_momentum, 'activation': self.activation } base_config = super(Conv2DBlock, self).get_config() base_config.update(config) return base_config class DepthwiseConv2DBlock(layers.Layer): def __init__(self, kernel_size=3, strides=1, padding='same', use_bias=False, batch_normalization=True, normalize_axis=0, normalize_epsilon=1e-3, normalize_momentum=0.999, activation=None, **kwargs): super(DepthwiseConv2DBlock, self).__init__(**kwargs) self.kernel_size = kernel_size self.strides = strides self.padding = padding self.use_bias = use_bias self.batch_normalization = batch_normalization self.normalize_axis = normalize_axis self.normalize_epsilon = normalize_epsilon self.normalize_momentum = normalize_momentum self.activation = activation self.conv = layers.DepthwiseConv2D( kernel_size=self.kernel_size, strides=self.strides, padding=self.padding, use_bias=self.use_bias) if self.batch_normalization is not None: self.batch_normalization_layer = layers.BatchNormalization( axis=self.normalize_axis, epsilon=self.normalize_epsilon, momentum=self.normalize_momentum ) if self.activation is not None: self.activation_layer = layers.Activation(activation) def build(self, input_shape): self.input_spec = layers.InputSpec(shape=input_shape) def call(self, x, *args, **kwargs): x = self.conv(x) if self.batch_normalization is not None: x = self.batch_normalization_layer(x) if self.activation is not None: x = self.activation_layer(x) return x def get_config(self): config = { 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'use_bias': self.use_bias, 'batch_normalization': self.batch_normalization, 'normalize_axis': self.normalize_axis, 'normalize_epsilon': self.normalize_epsilon, 'normalize_momentum': self.normalize_momentum, 'activation': self.activation } base_config = super(DepthwiseConv2DBlock, self).get_config() base_config.update(config) return base_config class DownsampleBlock(layers.Layer): def __init__(self, filters, kernel_initializer=None, kernel_size=(3, 3), strides=(2, 2), padding="same", gamma_initializer=None, use_bias=False, activation=None, **kwargs): super(DownsampleBlock, self).__init__(**kwargs) self.filters = filters self.kernel_size = kernel_size self.strides = strides self.padding = padding self.use_bias= use_bias self.activation = activation self.kernel_initializer = RandomNormal(mean=0.0, stddev=0.02) \ if kernel_initializer is None else kernel_initializer self.gamma_initializer = RandomNormal(mean=0.0, stddev=0.02) \ if gamma_initializer is None else gamma_initializer self.conv = layers.Conv2D( self.filters, self.kernel_size, strides=self.strides, kernel_initializer=self.kernel_initializer, padding=self.padding, use_bias=self.use_bias, ) self.inst_norm = solartf_layers.InstanceNormalization(gamma_initializer=self.gamma_initializer) def build(self, input_shape): self.input_spec = layers.InputSpec(shape=input_shape) def call(self, x, *args, **kwargs): x = self.conv(x) x = self.inst_norm(x) if self.activation is not None: x = self.activation(x) return x def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'use_bias': self.use_bias, 'activation': self.activation, 'kernel_initializer': self.kernel_initializer, 'gamma_initializer': self.gamma_initializer, } base_config = super(DownsampleBlock, self).get_config() base_config.update(config) return base_config class InvertedResBlock(layers.Layer): def __init__(self, infilters, expansion, filters, kernel_size, strides, se_ratio=None, **kwargs): super(InvertedResBlock, self).__init__(**kwargs) self.channel_axis = 1 if K.image_data_format() == 'channels_first' else -1 self.infilters = infilters self.expansion = expansion self.filters = filters self.kernel_size= kernel_size self.strides = strides self.se_ratio = se_ratio self.conv_expand = Conv2DBlock( filters=get_filter_nb_by_depth(self.infilters * self.expansion), kernel_size=1, padding='same', use_bias=False, normalize_axis=self.channel_axis, normalize_epsilon=1e-3, normalize_momentum=0.999, activation='relu' ) if self.strides == 2: self.zero_padding = solartf_layers.CorrectZeroPadding( kernel_size=self.kernel_size, ) self.depthwise_conv = DepthwiseConv2DBlock( kernel_size=self.kernel_size, strides=self.strides, padding='same', use_bias=False, normalize_axis=self.channel_axis, normalize_epsilon=1e-3, normalize_momentum=0.999, activation='relu' ) self.conv_out = Conv2DBlock( filters=self.filters, kernel_size=1, padding='same', use_bias=False, normalize_axis=self.channel_axis, normalize_epsilon=1e-3, normalize_momentum=0.999, activation=None ) if self.se_ratio: self.se_block = SEBlock( filters=get_filter_nb_by_depth(self.infilters * self.expansion), se_ratio=self.se_ratio ) def build(self, input_shape): self.input_spec = layers.InputSpec(shape=input_shape) def call(self, x, *args, **kwargs): shortcut = x x = self.conv_expand(x) # todo: it would make FPN wrong, and will be fixed in the future # if self.strides == 2: # x = self.zero_padding(x) x = self.depthwise_conv(x) if self.se_ratio: x = self.se_block(x) x = self.conv_out(x) if self.strides == 1 and self.infilters == self.filters: x = layers.add([shortcut, x]) return x def get_config(self): config = { 'channel_axis': self.channel_axis, 'infilters': self.infilters, 'expansion': self.expansion, 'filters': self.filters, 'kernel_size': self.kernel_size, 'stride': self.strides, 'se_ratio': self.se_ratio } base_config = super(InvertedResBlock, self).get_config() base_config.update(config) return base_config class ResNetBlock(layers.Layer): def __init__(self, num_filters_in=16, num_filters_out=32, kernel_size=3, kernel_initializer='he_normal', kernel_regularizer=l2(1e-4), stage_index=0, block_index=0, **kwargs): super(ResNetBlock, self).__init__(**kwargs) self.num_filters_in = num_filters_in self.num_filters_out = num_filters_out self.kernel_size = kernel_size self.kernel_initializer = kernel_initializer self.kernel_regularizer = kernel_regularizer # todo: to correct activation functions self.activation_in = layers.Activation('relu') self.activation_middle = layers.Activation('relu') self.activation_out = layers.Activation('relu') self.normalization_in = layers.BatchNormalization() self.normalization_middle = layers.BatchNormalization() self.normalization_out = layers.BatchNormalization() self.stage_index = stage_index self.block_index = block_index self.conv_in = layers.Conv2D(self.num_filters_in, kernel_size=1, strides=1, padding='same', kernel_initializer=self.kernel_initializer, kernel_regularizer=self.kernel_regularizer) self.conv_middle = layers.Conv2D( self.num_filters_in, kernel_size=self.kernel_size, strides=1, padding='same', kernel_initializer=self.kernel_initializer, kernel_regularizer=self.kernel_regularizer) self.conv_in_downsample = layers.Conv2D( self.num_filters_in, kernel_size=1, strides=2, padding='same', kernel_initializer=self.kernel_initializer, kernel_regularizer=self.kernel_regularizer) self.conv_out = layers.Conv2D(self.num_filters_out, kernel_size=1, strides=1, padding='same', kernel_initializer=self.kernel_initializer, kernel_regularizer=self.kernel_regularizer) self.conv_shortcut_out = layers.Conv2D( self.num_filters_out, kernel_size=1, strides=1, padding='same', kernel_initializer=self.kernel_initializer, kernel_regularizer=self.kernel_regularizer) self.conv_out_downsample = layers.Conv2D( self.num_filters_out, kernel_size=1, strides=2, padding='same', kernel_initializer=self.kernel_initializer, kernel_regularizer=self.kernel_regularizer) def build(self, input_shape): self.input_spec = layers.InputSpec(shape=input_shape) def call(self, x, *args, **kwargs): activation = self.activation_in normalization = self.normalization_in conv = self.conv_in if self.stage_index == 0: if self.block_index == 0: activation = None normalization = None else: if self.block_index == 0: conv = self.conv_in_downsample # bottleneck residual unit y = self._resnet_conv(inputs=x, conv=conv, activation=activation, normalization=normalization,) y = self._resnet_conv(inputs=y, conv=self.conv_middle, activation=self.activation_middle, normalization=self.normalization_middle,) y = self._resnet_conv(inputs=y, conv=self.conv_out, activation=self.activation_out, normalization=self.normalization_out,) if self.block_index == 0: # linear projection residual shortcut connection to match # changed dims x = self._resnet_conv( inputs=x, conv=self.conv_out_downsample if self.stage_index > 0 else self.conv_shortcut_out, activation=None, normalization=None) return layers.add([x, y]) def get_config(self): config = { 'num_filters_in': self.self.num_filters_in, 'num_filters_out': self.num_filters_out, 'kernel_size': self.kernel_size, 'stage_index': self.stage_index, 'block_index': self.block_index } base_config = super(ResNetBlock, self).get_config() base_config.update(config) return base_config def _resnet_conv(self, inputs, conv, normalization=None, activation=None): x = inputs if normalization is not None: x = normalization(x) if activation is not None: x = activation(x) x = conv(x) return x class ResidualBlock(layers.Layer): def __init__(self, filters, kernel_size=(3, 3), kernel_initializer=None, gamma_initializer=None, use_bias=False, activation=None, **kwargs): super(ResidualBlock, self).__init__(**kwargs) self.filters = filters self.kernel_size = kernel_size self.use_bias= use_bias self.activation = activation self.kernel_initializer = RandomNormal(mean=0.0, stddev=0.02) \ if kernel_initializer is None else kernel_initializer self.gamma_initializer = RandomNormal(mean=0.0, stddev=0.02) \ if gamma_initializer is None else gamma_initializer self.reflect_padding = solartf_layers.ReflectionPadding2D() self.conv = layers.Conv2D( self.filters, self.kernel_size, strides=(1, 1), kernel_initializer=self.kernel_initializer, padding='valid', use_bias=self.use_bias, ) self.inst_norm = solartf_layers.InstanceNormalization(gamma_initializer=self.gamma_initializer) def build(self, input_shape): self.input_spec = layers.InputSpec(shape=input_shape) def call(self, x, *args, **kwargs): input_tensor = x for _ in range(2): x = self.reflect_padding(x) x = self.conv(x) x = self.inst_norm(x) if self.activation is not None: x = self.activation(x) x = layers.add([input_tensor, x]) return x def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'use_bias': self.use_bias, 'activation': self.activation, 'kernel_initializer': self.kernel_initializer, 'gamma_initializer': self.gamma_initializer, } base_config = super(ResidualBlock, self).get_config() base_config.update(config) return base_config class SEBlock(layers.Layer): def __init__(self, filters, se_ratio, **kwargs): super(SEBlock, self).__init__(**kwargs) self.filters = filters self.se_ratio = se_ratio self.global_pool = layers.GlobalAveragePooling2D() if K.image_data_format() == 'channels_first': self.reshape = layers.Reshape((self.filters, 1, 1)) else: self.reshape = layers.Reshape((1, 1, self.filters)) self.conv_in = layers.Conv2D( filters=get_filter_nb_by_depth(self.filters * self.se_ratio), kernel_size=1, padding='same', ) self.activation_relu = layers.ReLU() self.conv_out = layers.Conv2D( filters=self.filters, kernel_size=1, padding='same', ) self.activation_hard_sigmoid = solar_activation.HardSigmoid() def build(self, input_shape): self.input_spec = layers.InputSpec(shape=input_shape) def call(self, inputs, *args, **kwargs): x = self.global_pool(inputs) x = self.reshape(x) x = self.conv_in(x) x = self.activation_relu(x) x = self.conv_out(x) x = self.activation_hard_sigmoid(x) return layers.multiply([inputs, x]) def get_config(self): config = { } base_config = super(SEBlock, self).get_config() base_config.update(config) return base_config class UpsampleBlock(layers.Layer): def __init__(self, filters, kernel_size=(3, 3), strides=(2, 2), padding="same", kernel_initializer=None, gamma_initializer=None, use_bias=False, activation=None, **kwargs): super(UpsampleBlock, self).__init__(**kwargs) self.filters = filters self.kernel_size = kernel_size self.strides = strides self.padding = padding self.use_bias= use_bias self.activation = activation self.kernel_initializer = RandomNormal(mean=0.0, stddev=0.02) \ if kernel_initializer is None else kernel_initializer self.gamma_initializer = RandomNormal(mean=0.0, stddev=0.02) \ if gamma_initializer is None else gamma_initializer self.invert_conv = layers.Conv2DTranspose( self.filters, self.kernel_size, strides=self.strides, kernel_initializer=self.kernel_initializer, padding=self.padding, use_bias=self.use_bias, ) self.inst_norm = solartf_layers.InstanceNormalization(gamma_initializer=self.gamma_initializer) def build(self, input_shape): self.input_spec = layers.InputSpec(shape=input_shape) def call(self, x, *args, **kwargs): x = self.invert_conv(x) x = self.inst_norm(x) if self.activation is not None: x = self.activation(x) return x def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'use_bias': self.use_bias, 'activation': self.activation, 'kernel_initializer': self.kernel_initializer, 'gamma_initializer': self.gamma_initializer, } base_config = super(UpsampleBlock, self).get_config() base_config.update(config) return base_config
34.98366
103
0.572303
4a104512a0315071dc7d0af7d39bb216d720ad4a
8,416
py
Python
sdk/python/pulumi_gcp/logging/folder_sink.py
23doors/pulumi-gcp
ded01b199f95b164884266ea3e6f8206c8231270
[ "ECL-2.0", "Apache-2.0" ]
1
2019-12-20T22:08:20.000Z
2019-12-20T22:08:20.000Z
sdk/python/pulumi_gcp/logging/folder_sink.py
pellizzetti/pulumi-gcp
fad74dd55a0cf7723f73046bb0e6fcbfd948ba84
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/python/pulumi_gcp/logging/folder_sink.py
pellizzetti/pulumi-gcp
fad74dd55a0cf7723f73046bb0e6fcbfd948ba84
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class FolderSink(pulumi.CustomResource): bigquery_options: pulumi.Output[dict] """ Options that affect sinks exporting data to BigQuery. Structure documented below. * `usePartitionedTables` (`bool`) """ destination: pulumi.Output[str] """ The destination of the sink (or, in other words, where logs are written to). Can be a Cloud Storage bucket, a PubSub topic, or a BigQuery dataset. Examples: The writer associated with the sink must have access to write to the above resource. """ filter: pulumi.Output[str] """ The filter to apply when exporting logs. Only log entries that match the filter are exported. See [Advanced Log Filters](https://cloud.google.com/logging/docs/view/advanced_filters) for information on how to write a filter. """ folder: pulumi.Output[str] """ The folder to be exported to the sink. Note that either [FOLDER_ID] or "folders/[FOLDER_ID]" is accepted. """ include_children: pulumi.Output[bool] """ Whether or not to include children folders in the sink export. If true, logs associated with child projects are also exported; otherwise only logs relating to the provided folder are included. """ name: pulumi.Output[str] """ The name of the logging sink. """ writer_identity: pulumi.Output[str] """ The identity associated with this sink. This identity must be granted write access to the configured `destination`. """ def __init__(__self__, resource_name, opts=None, bigquery_options=None, destination=None, filter=None, folder=None, include_children=None, name=None, __props__=None, __name__=None, __opts__=None): """ Create a FolderSink resource with the given unique name, props, and options. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[dict] bigquery_options: Options that affect sinks exporting data to BigQuery. Structure documented below. :param pulumi.Input[str] destination: The destination of the sink (or, in other words, where logs are written to). Can be a Cloud Storage bucket, a PubSub topic, or a BigQuery dataset. Examples: The writer associated with the sink must have access to write to the above resource. :param pulumi.Input[str] filter: The filter to apply when exporting logs. Only log entries that match the filter are exported. See [Advanced Log Filters](https://cloud.google.com/logging/docs/view/advanced_filters) for information on how to write a filter. :param pulumi.Input[str] folder: The folder to be exported to the sink. Note that either [FOLDER_ID] or "folders/[FOLDER_ID]" is accepted. :param pulumi.Input[bool] include_children: Whether or not to include children folders in the sink export. If true, logs associated with child projects are also exported; otherwise only logs relating to the provided folder are included. :param pulumi.Input[str] name: The name of the logging sink. The **bigquery_options** object supports the following: * `usePartitionedTables` (`pulumi.Input[bool]`) > This content is derived from https://github.com/terraform-providers/terraform-provider-google/blob/master/website/docs/r/logging_folder_sink.html.markdown. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['bigquery_options'] = bigquery_options if destination is None: raise TypeError("Missing required property 'destination'") __props__['destination'] = destination __props__['filter'] = filter if folder is None: raise TypeError("Missing required property 'folder'") __props__['folder'] = folder __props__['include_children'] = include_children __props__['name'] = name __props__['writer_identity'] = None super(FolderSink, __self__).__init__( 'gcp:logging/folderSink:FolderSink', resource_name, __props__, opts) @staticmethod def get(resource_name, id, opts=None, bigquery_options=None, destination=None, filter=None, folder=None, include_children=None, name=None, writer_identity=None): """ Get an existing FolderSink resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param str id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[dict] bigquery_options: Options that affect sinks exporting data to BigQuery. Structure documented below. :param pulumi.Input[str] destination: The destination of the sink (or, in other words, where logs are written to). Can be a Cloud Storage bucket, a PubSub topic, or a BigQuery dataset. Examples: The writer associated with the sink must have access to write to the above resource. :param pulumi.Input[str] filter: The filter to apply when exporting logs. Only log entries that match the filter are exported. See [Advanced Log Filters](https://cloud.google.com/logging/docs/view/advanced_filters) for information on how to write a filter. :param pulumi.Input[str] folder: The folder to be exported to the sink. Note that either [FOLDER_ID] or "folders/[FOLDER_ID]" is accepted. :param pulumi.Input[bool] include_children: Whether or not to include children folders in the sink export. If true, logs associated with child projects are also exported; otherwise only logs relating to the provided folder are included. :param pulumi.Input[str] name: The name of the logging sink. :param pulumi.Input[str] writer_identity: The identity associated with this sink. This identity must be granted write access to the configured `destination`. The **bigquery_options** object supports the following: * `usePartitionedTables` (`pulumi.Input[bool]`) > This content is derived from https://github.com/terraform-providers/terraform-provider-google/blob/master/website/docs/r/logging_folder_sink.html.markdown. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["bigquery_options"] = bigquery_options __props__["destination"] = destination __props__["filter"] = filter __props__["folder"] = folder __props__["include_children"] = include_children __props__["name"] = name __props__["writer_identity"] = writer_identity return FolderSink(resource_name, opts=opts, __props__=__props__) def translate_output_property(self, prop): return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
53.948718
200
0.683341
4a1045bf2cfebffff6d30bc1fdbbacdfa74f3d17
5,493
py
Python
offb_posctl/scripts/GPM_test.py
SensenLiu/aggrecup
0c381ee259b388684205c1fa5fc41265a7e849b3
[ "MIT" ]
null
null
null
offb_posctl/scripts/GPM_test.py
SensenLiu/aggrecup
0c381ee259b388684205c1fa5fc41265a7e849b3
[ "MIT" ]
null
null
null
offb_posctl/scripts/GPM_test.py
SensenLiu/aggrecup
0c381ee259b388684205c1fa5fc41265a7e849b3
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # coding=utf-8 import socket from scipy.optimize import minimize import numpy as np import time from numba import jit, float64 import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import datetime # global variable start >>> n = 7 t0 = 0 tf = 2 discretized_point_persecond = 50 pointnumber = tf * discretized_point_persecond # 离散点数 currentupdateflag = False # 是否计算控制量 k = np.array([50, 50]) c = np.array([0, 0]) # air drag effect in x & z co = 0.5 * (tf - t0) g = 9.8 px_ini = -3 pz_ini = 0 vx_ini = 0 vz_ini = 0 va_ini = 0 # absolute velocity of plane # ini = np.array([[px_ini], [pz_ini], [vx_ini], [vz_ini], [va_ini]]) state_get_flag = False # global variable start >>> # D matrix D = np.loadtxt(open("../data/D.csv", "rb"), delimiter=",", skiprows=0) # array # Gauss weights omega = np.loadtxt(open("../data/omega.csv", "rb"), delimiter=",", skiprows=0) # array # Lagrange coefficient of x L1 = np.loadtxt(open("../data/L1.csv", "rb"), delimiter=",", skiprows=0) # array # Lagrange coefficient of u L2 = np.loadtxt(open("../data/L2.csv", "rb"), delimiter=",", skiprows=0) # array # Objective @jit(float64(float64[:]), nopython=True) def J(x): X1 = x[0: n] X2 = x[n: 2 * n] U1 = x[5 * n: 6 * n] U2 = x[6 * n: 7 * n] return co * 0.5 * np.dot(omega, ( 0.5 * (U1 - 9.8) ** 2 + 0.5 * U2 ** 2 + k[0] * (X1 + 3) ** 2 + k[1] * (X1 * U2 + X2) ** 2)) # the derivative of objective function J @jit(float64[:](float64[:]), nopython=True) def fast_jac(x): h = 1e-11 N = x.shape[0] jac = np.zeros_like(x) f_0 = J(x) for i in range(N): x_d = np.copy(x) x_d[i] += h f_d = J(x_d) jac[i] = (f_d - f_0) / h return jac # Constraint @jit(float64[:](float64[:]), nopython=True) def mycon(x): global px_ini, pz_ini, vx_ini, vz_ini, va_ini X1 = x[0: n] X2 = x[n: 2 * n] X3 = x[2 * n: 3 * n] X4 = x[3 * n: 4 * n] X5 = x[4 * n: 5 * n] U1 = x[5 * n: 6 * n] U2 = x[6 * n: 7 * n] print('===================????', px_ini) Ceq1 = np.dot(D, np.append(px_ini, X1)) - co * X3 Ceq2 = np.dot(D, np.append(pz_ini, X2)) - co * X4 Ceq3 = np.dot(D, np.append(vx_ini, X3)) - co * (g * U2 - c[0] * X5) Ceq4 = np.dot(D, np.append(vz_ini, X4)) - co * (U1 - g - c[1] * X5) Ceq5 = np.dot(D, np.append(va_ini, X5)) - co * (g * U2 - c[0] * X5) return np.hstack((Ceq1, Ceq2, Ceq3, Ceq4, Ceq5)) def do_process(result): global tau x = result.x.reshape(7, n) print('===================!!!!', px_ini) ini = np.array([[px_ini], [pz_ini], [vx_ini], [vz_ini], [va_ini]]) # print('ini.{}'.format(ini)) poly_x = np.dot(np.hstack((ini, x[0:5, :])), L1) # 拟合出的x的系数矩阵 poly_u = np.dot(x[5:7, :], L2) # 拟合出的u的系数矩阵 # 将数据代入系数矩阵求x和u x1 = np.polyval(poly_x[0], tau) x2 = np.polyval(poly_x[1], tau) x3 = np.polyval(poly_x[2], tau) x4 = np.polyval(poly_x[3], tau) x5 = np.polyval(poly_x[4], tau) u1 = np.polyval(poly_u[0], tau) u2 = np.polyval(poly_u[1], tau) return np.vstack((x1, x2, x3, x4, u1, u2)) def parse(data): # 解析收到的client的px等数据 global state_get_flag if len(data) > 6: # 判断是否包含至少包头 for i in range(len(data)): if data[i:i + 3].decode() == 'LEN': Length = int(data[i + 3:i + 6].decode()) # print('data:{}'.format(data)) # print('time now:{}'.format(time.time())) if len(data[i:]) >= (Length + 6): # 消息包含包头+state msg = eval(data[i + 6:i + 6 + Length].decode()) # 直到处理完,最新msg print('msg:{}'.format(msg)) if len(msg) == 6: state_get_flag = True if len(data[i + 6+Length:]) < Length + 6: # 剩下的不够一条消息的长度 break else: break try: return data[Length + i + 6:], msg # 返回剩余不能构成一帧数据的data except: print('----data:{}----'.format(data)) return b'' else: return b'' pass def main(): global currentupdateflag, discretized_point_persecond, tau, state_get_flag, msg global px_ini, pz_ini, vx_ini, vz_ini, va_ini constraint = [dict(type='eq', fun=mycon)] tau = np.linspace(-1, 1, pointnumber) # t = 0.5 * (tf - t0) * tau + 0.5 * (tf + t0) # while True: state_get_flag = True if state_get_flag: px_ini = -3.5 pz_ini = 0.0 vx_ini = -0.1 vz_ini = 0 va_ini = 0 print('px_ini:{}; pz_ini:{}; vx_ini:{}; vz_ini:{}; va_ini:{};'.format(px_ini, pz_ini, vx_ini, vz_ini, va_ini)) start = time.time() # core calculate code result = minimize(J, np.zeros((7 * n)), method='SLSQP', tol=1e-4, constraints=constraint, jac=fast_jac) print(result) res = do_process(result) # print(res) # core calculate code end = time.time() running_time = end - start print('time cost : %.5f sec' % running_time) ## core part 1 >>>> time_now = time.time() thrust_pitch_x1234 = [res[4, 0:20].tolist(), res[5, 0:20].tolist(), res[0, 0:20].tolist(), res[1, 0:20].tolist(), res[2, 0:20].tolist(), res[3, 0:20].tolist(), time_now] plt.plot(tau*(tf-t0)/2.0+(tf+t0), res[0, 0:100]) plt.show() if __name__ == '__main__': # 主函数 main()
30.687151
121
0.532132
4a1045ec4252fa814150d3bae82056091352db45
3,773
py
Python
parser.py
misaelnieto/tracey
bb6c1cd88130fc903561b5122ee2320deb8d9f6c
[ "Apache-2.0" ]
null
null
null
parser.py
misaelnieto/tracey
bb6c1cd88130fc903561b5122ee2320deb8d9f6c
[ "Apache-2.0" ]
null
null
null
parser.py
misaelnieto/tracey
bb6c1cd88130fc903561b5122ee2320deb8d9f6c
[ "Apache-2.0" ]
null
null
null
#!/bin/env python3 class DevsimData(object): """ Simple object contains the coordinates Should probably be replace with numpy's dtype and loadtxt """ def __init__(self, filename): self.filename = filename self.regions = {} self.name = None self.coordinates = None with open(filename, 'r') as fp: line = fp.readline().strip() if line.startswith('begin_device'): _, n = line.split() self.name = n.strip('"') line = fp.readline().strip() while line != 'end_device': if line.startswith('begin_coordinates'): self.coordinates = [] line = fp.readline().strip() while line != 'end_coordinates': self.coordinates.append([float(i) for i in line.strip().split()]) line = fp.readline().strip() elif line.startswith('begin_region'): _, rname, rmaterial = line.split() rname = rname.strip('"') self.regions[rname] = { 'material': rmaterial.strip('"'), 'nodes': [], 'node_solutions': {}, 'edges': [], 'edge_solutions': {}, } line = fp.readline().strip() while line != 'end_region': if line.startswith('begin_nodes'): line = fp.readline().strip() while line != 'end_nodes': self.regions[rname]['nodes'].append(int(line.strip())) line = fp.readline().strip() elif line.startswith('begin_edges'): line = fp.readline().strip() while line != 'end_edges': self.regions[rname]['edges'].append( [int(e) for e in line.split()] ) line = fp.readline().strip() elif line.startswith('begin_node_solution'): _, sname = line.split() sname = sname.strip('"') self.regions[rname]['node_solutions'][sname] = [] line = fp.readline().strip() while line != 'end_node_solution': self.regions[rname]['node_solutions'][sname].append(float(line.strip())) line = fp.readline().strip() elif line.startswith('begin_edge_solution'): _, sname = line.split() sname = sname.strip('"') self.regions[rname]['edge_solutions'][sname] = [] line = fp.readline().strip() while line != 'end_edge_solution': self.regions[rname]['edge_solutions'][sname].append(float(line.strip())) line = fp.readline().strip() line = fp.readline().strip() line = fp.readline().strip() def __str__(self): return 'DevsimData "{}" ({} regions)'.format(self.name, len(self.regions)) if __name__ == '__main__': d = DevsimData('../resistor.dat') print(d)
49.644737
108
0.401802
4a10466ead3a43189a6138b2fde341af0e5edce2
3,053
py
Python
src/oci/identity_data_plane/models/authenticate_user_result.py
LaudateCorpus1/oci-python-sdk
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/oci/identity_data_plane/models/authenticate_user_result.py
LaudateCorpus1/oci-python-sdk
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/oci/identity_data_plane/models/authenticate_user_result.py
LaudateCorpus1/oci-python-sdk
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class AuthenticateUserResult(object): """ See ValidAuthenticateUserResult, BadUserStateAuthenticateUserResult, UserNotFoundAuthenticateUserResult, TenantNotFoundAuthenticateUserResult """ def __init__(self, **kwargs): """ Initializes a new AuthenticateUserResult object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param tenant_input: The value to assign to the tenant_input property of this AuthenticateUserResult. :type tenant_input: str :param user_input: The value to assign to the user_input property of this AuthenticateUserResult. :type user_input: str """ self.swagger_types = { 'tenant_input': 'str', 'user_input': 'str' } self.attribute_map = { 'tenant_input': 'tenantInput', 'user_input': 'userInput' } self._tenant_input = None self._user_input = None @property def tenant_input(self): """ **[Required]** Gets the tenant_input of this AuthenticateUserResult. The tenant name. :return: The tenant_input of this AuthenticateUserResult. :rtype: str """ return self._tenant_input @tenant_input.setter def tenant_input(self, tenant_input): """ Sets the tenant_input of this AuthenticateUserResult. The tenant name. :param tenant_input: The tenant_input of this AuthenticateUserResult. :type: str """ self._tenant_input = tenant_input @property def user_input(self): """ **[Required]** Gets the user_input of this AuthenticateUserResult. The user name. :return: The user_input of this AuthenticateUserResult. :rtype: str """ return self._user_input @user_input.setter def user_input(self, user_input): """ Sets the user_input of this AuthenticateUserResult. The user name. :param user_input: The user_input of this AuthenticateUserResult. :type: str """ self._user_input = user_input def __repr__(self): return formatted_flat_dict(self) def __eq__(self, other): if other is None: return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
29.931373
245
0.657714
4a10470e1f69e3ab4601f894a6ac2b68f0561075
4,776
py
Python
homework2/replay_buffer.py
IrohXu/NYU_Deep_Reinforcement_Learning
bb8025464b430687c7604e627eefb2908317cfa7
[ "MIT" ]
null
null
null
homework2/replay_buffer.py
IrohXu/NYU_Deep_Reinforcement_Learning
bb8025464b430687c7604e627eefb2908317cfa7
[ "MIT" ]
null
null
null
homework2/replay_buffer.py
IrohXu/NYU_Deep_Reinforcement_Learning
bb8025464b430687c7604e627eefb2908317cfa7
[ "MIT" ]
null
null
null
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import utils from segment_tree import SumSegmentTree, MinSegmentTree class ReplayBuffer(object): def __init__(self, obs_shape, capacity, device): self.capacity = capacity self.device = device self.obses = np.empty((capacity, *obs_shape), dtype=np.uint8) self.next_obses = np.empty((capacity, *obs_shape), dtype=np.uint8) self.actions = np.empty((capacity, 1), dtype=np.int64) self.rewards = np.empty((capacity, 1), dtype=np.float32) self.not_dones = np.empty((capacity, 1), dtype=np.float32) self.idx = 0 self.full = False def __len__(self): return self.capacity if self.full else self.idx def add(self, obs, action, reward, next_obs, done): np.copyto(self.obses[self.idx], obs) np.copyto(self.actions[self.idx], action) np.copyto(self.rewards[self.idx], reward) np.copyto(self.next_obses[self.idx], next_obs) np.copyto(self.not_dones[self.idx], not done) self.idx = (self.idx + 1) % self.capacity self.full = self.full or self.idx == 0 def fetch(self, idxs, discount, n): assert idxs.max() + n <= len(self) obses = self.obses[idxs] next_obses = self.next_obses[idxs + n - 1] obses = torch.as_tensor(obses, device=self.device).float() next_obses = torch.as_tensor(next_obses, device=self.device).float() actions = torch.as_tensor(self.actions[idxs], device=self.device) rewards = np.zeros((idxs.shape[0], 1), dtype=np.float32) not_dones = np.ones((idxs.shape[0], 1), dtype=np.float32) for i in range(n): rewards += (discount**i) * not_dones * np.sign( self.rewards[idxs + i]) not_dones = np.minimum(not_dones, self.not_dones[idxs + i]) rewards = torch.as_tensor(rewards, device=self.device) not_dones = torch.as_tensor(not_dones, device=self.device) return obses, actions, rewards, next_obses, not_dones def sample_idxs(self, batch_size, n): last_idx = (self.capacity if self.full else self.idx) - (n - 1) idxs = np.random.randint(0, last_idx, size=batch_size) return idxs def sample_multistep(self, batch_size, discount, n): assert n <= self.idx or self.full idxs = self.sample_idxs(batch_size, n) return self.fetch(idxs, discount, n) class PrioritizedReplayBuffer(ReplayBuffer): def __init__(self, obs_shape, capacity, alpha, device): super().__init__(obs_shape, capacity, device) assert alpha >= 0 self.alpha = alpha tree_capacity = 1 while tree_capacity < capacity: tree_capacity *= 2 self.sum_tree = SumSegmentTree(tree_capacity) self.min_tree = MinSegmentTree(tree_capacity) self.max_priority = 1.0 def add(self, obs, action, reward, next_obs, done): super().add(obs, action, reward, next_obs, done) self.sum_tree[self.idx] = self.max_priority**self.alpha self.min_tree[self.idx] = self.max_priority**self.alpha def sample_idxs(self, batch_size, n): idxs = [] p_total = self.sum_tree.sum(0, len(self) - n - 1) every_range_len = p_total / batch_size for i in range(batch_size): while True: mass = np.random.rand() * every_range_len + i * every_range_len idx = self.sum_tree.find_prefixsum_idx(mass) if idx + n <= len(self): idxs.append(idx) break return np.array(idxs) def sample_multistep(self, batch_size, beta, discount, n): assert n <= self.idx or self.full assert beta > 0 idxs = self.sample_idxs(batch_size, n) weights = [] p_min = self.min_tree.min() / self.sum_tree.sum() max_weight = (p_min * len(self))**(-beta) for idx in idxs: p_sample = self.sum_tree[idx] / self.sum_tree.sum() weight = (p_sample * len(self))**(-beta) weights.append(weight / max_weight) weights = torch.as_tensor(np.array(weights), device=self.device).unsqueeze(dim=1) sample = self.fetch(idxs, discount, n) return tuple(list(sample) + [weights, idxs]) def update_priorities(self, idxs, prios): assert idxs.shape[0] == prios.shape[0] for idx, prio in zip(idxs, prios): assert prio > 0 assert 0 <= idx < len(self) self.sum_tree[idx] = prio**self.alpha self.min_tree[idx] = prio**self.alpha self.max_priority = max(self.max_priority, prio)
34.608696
79
0.609925
4a1047d99fe50e2345f1feba1295e7cb2f2f7814
10,363
py
Python
misc/train.py
RyanC1681/RCAI1122
c9683110b58c255a7a78d880ff73df7ff2329405
[ "Apache-2.0" ]
18
2020-10-16T00:38:55.000Z
2022-03-03T06:01:49.000Z
misc/train.py
RyanC1681/RCAI1122
c9683110b58c255a7a78d880ff73df7ff2329405
[ "Apache-2.0" ]
20
2020-07-23T03:50:50.000Z
2021-11-09T04:00:26.000Z
misc/train.py
RyanC1681/RCAI1122
c9683110b58c255a7a78d880ff73df7ff2329405
[ "Apache-2.0" ]
140
2019-11-20T22:46:02.000Z
2022-03-29T13:26:17.000Z
from keras.models import load_model import numpy as np import cv2 from pathlib import Path import os import glob import h5py from keras import __version__ as keras_version from typing import List import tensorflow as tf try: from model import nvidia_model, simple_model except: from .model import nvidia_model, simple_model import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split def load_vehicle_states(dir: Path, regex="/*.npy") -> np.ndarray: file_paths = sorted(glob.glob((dir.as_posix() + regex)), key=os.path.getmtime) states = [] for fpath in file_paths: state = np.load(fpath, allow_pickle=True) states.append(state) return np.array(states) def load_images(image_dir: Path, regex="/*.png") -> List: file_paths = sorted(glob.glob((image_dir.as_posix() + regex)), key=os.path.getmtime) images = [] for fpath in file_paths: image = cv2.imread(fpath) images.append(image) return images def load_depth_images(dir, regex="/*.npy") -> List: file_paths = sorted(glob.glob((dir.as_posix() + regex)), key=os.path.getmtime) images = [] for fpath in file_paths: image = np.load(fpath) images.append(image) return images def load_data(): rgb_images = load_images(Path("../data/output_oct_10/front_rgb/"), regex="/frame_*") vehicle_states = load_vehicle_states(dir=Path("../data/output_oct_10/vehicle_state")) # depth_images = load_depth_images(dir=Path("../data/output_oct_10/front_depth")) X = rgb_images y = np.array(vehicle_states)[:, -1] return X, y def plot_steering_hist(steerings: np.ndarray): fig, ax = plt.subplots(1, 1, figsize=(10, 7)) ax.grid(True) ax.set(title="Ensemble - Distribution of steering angles") count, bins, _ = ax.hist(steerings, bins=25, histtype='bar') plt.show() def fliph_image(img): """ Returns a horizontally flipped image """ return cv2.flip(img, 1) def blur_image(img, f_size=5): """ Applies Gaussir Blur to smoothen the image. This in effect performs anti-aliasing on the provided image """ img = cv2.GaussianBlur(img, (f_size, f_size), 0) img = np.clip(img, 0, 255) return img.astype(np.uint8) def translate_image(img, st_angle, low_x_range, high_x_range, low_y_range, high_y_range, delta_st_angle_per_px): """ Shifts the image right, left, up or down. When performing a lateral shift, a delta proportional to the pixel shifts is added to the current steering angle """ rows, cols = (img.shape[0], img.shape[1]) translation_x = np.random.randint(low_x_range, high_x_range) translation_y = np.random.randint(low_y_range, high_y_range) st_angle += translation_x * delta_st_angle_per_px translation_matrix = np.float32([[1, 0, translation_x], [0, 1, translation_y]]) img = cv2.warpAffine(img, translation_matrix, (cols, rows)) return img, st_angle def change_image_lightness(img, low, high): """ Applies an offset in [low, high] interval to change the 'L' component of the supplied image in HSL format The returned image in converted back to RGB """ # Convert to HSL (HLS in OpenCV!!) hls = cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_RGB2HLS) hls = hls.astype(int) # Add an offset to light component offset = np.random.randint(low, high=high) # Since the format is HLS and NOT HSL, it is the second component (index 1) that is modified # hls[:,:,1] += offset hls[:, :, 1] = offset # Make sure our lightness component is in the interval [0, 255] np.clip(hls, 0, 255) # Convert back to uint hls = hls.astype(np.uint8) # Make sure we return image in RGB format return cv2.cvtColor(hls, cv2.COLOR_HLS2RGB) def change_image_brightness(img, low, high): """ Applies an offset in [low, high] interval to change the 'V' component of the supplied image in HSV format The returned image in converted back to RGB """ # Convert to HSV hsv = cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_RGB2HSV) hsv = hsv.astype(int) # Adding the offset to the v component offset = np.random.randint(low, high=high) hsv[:, :, 2] += offset # Make sure our lightness component is in the interval [0, 255] np.clip(hsv, 0, 255) # Convert back to uint hsv = hsv.astype(np.uint8) # Make sure we return image in RGB format return cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) def add_random_shadow(img, w_low=0.6, w_high=0.85): """ Overlays supplied image with a random shadow poligon The weight range (i.e. darkness) of the shadow can be configured via the interval [w_low, w_high) """ cols, rows = (img.shape[0], img.shape[1]) top_y = np.random.random_sample() * rows bottom_y = np.random.random_sample() * rows bottom_y_right = bottom_y + np.random.random_sample() * (rows - bottom_y) top_y_right = top_y + np.random.random_sample() * (rows - top_y) if np.random.random_sample() <= 0.5: bottom_y_right = bottom_y - np.random.random_sample() * (bottom_y) top_y_right = top_y - np.random.random_sample() * (top_y) poly = np.asarray([[[top_y, 0], [bottom_y, cols], [bottom_y_right, cols], [top_y_right, 0]]], dtype=np.int32) mask_weight = np.random.uniform(w_low, w_high) origin_weight = 1 - mask_weight mask = np.copy(img).astype(np.int32) cv2.fillPoly(mask, poly, (0, 0, 0)) # masked_image = cv2.bitwise_and(img, mask) return cv2.addWeighted(img.astype(np.int32), origin_weight, mask, mask_weight, 0).astype(np.uint8) def shift_horizon(img, h_s=0.2): img = img.astype(np.float32) # randomly shift horizon height = img.shape[0] width = img.shape[1] horizon = h_s * height / 3 v_shift = np.random.randint(-height / 8, height / 8) pts1 = np.float32([[0, horizon], [width, horizon], [0, height], [width, height]]) pts2 = np.float32([[0, horizon + v_shift], [width, horizon + v_shift], [0, height], [width, height]]) M = cv2.getPerspectiveTransform(pts1, pts2) img = cv2.warpPerspective(img, M, (width, height), borderMode=cv2.BORDER_REPLICATE) return img.astype(np.uint8) def change_image_brightness_rgb(img, s_low=0.2, s_high=0.75): """ Changes the image brightness by multiplying all RGB values by the same scalacar in [s_low, s_high). Returns the brightness adjusted image in RGB format. """ img = img.astype(np.float32) s = np.random.uniform(s_low, s_high) img[:, :, :] *= s np.clip(img, 0, 255) return img.astype(np.uint8) def augment_image(img, st_angle, p=1.0): """ Augment a given image, by applying a series of transformations, with a probability p. The steering angle may also be modified. Returns the tuple (augmented_image, new_steering_angle) """ aug_img = img # if np.random.random_sample() <= 1.0: # Reduce aliasing via blurring # aug_img = blur_image(aug_img) if np.random.random_sample() <= 0.5: # Horizontally flip image aug_img = fliph_image(aug_img) st_angle = -st_angle if np.random.random_sample() <= 0.5: aug_img = change_image_brightness_rgb(aug_img) if np.random.random_sample() <= 0.5: aug_img = add_random_shadow(aug_img, w_low=0.45) if np.random.random_sample() <= 0.5: # Shift the image left/right, up/down and modify the steering angle accordingly aug_img, st_angle = translate_image(aug_img, st_angle, -60, 61, -20, 21, 0.35 / 100.0) return aug_img, st_angle def generate_images(X, y, batch_size, shuffle=True, aug_likelihood=0.5, data_aug_pct=0.8): num_images, width, height, channel = np.shape(X) assert num_images == len(y), f"Dimension mismatch: Got {num_images} X but {len(y)} y" batch = np.zeros((batch_size, width, height, channel), dtype=np.float32) steering_angles = np.zeros(batch_size) while True: k = 0 while k < batch_size: idx = np.random.randint(0, num_images) image = X[idx] steering_angle = y[idx] img, st_angle = None, None if np.random.random_sample() <= data_aug_pct: img, st_angle = augment_image(img=image, st_angle=steering_angle, p=aug_likelihood) else: img, st_angle = image, steering_angle batch[k] = img steering_angles[k] = st_angle k += 1 yield batch, np.clip(steering_angles, -1, 1) def show_images(imgs, labels, cols=5, fig_size=(15, 5)): rows = len(imgs) // cols fig, axes = plt.subplots(rows, cols, figsize=fig_size) for r in range(rows): for c in range(cols): ax = axes[r, c] img = imgs[cols * r + c] lb = labels[cols * r + c] ax.imshow(img.astype(np.uint8)) ax.axis('on') ax.set_aspect('equal') ax.set(title=lb) fig.tight_layout() plt.show() def show_sample_images(X, y): gen = generate_images(X=X, y=y, batch_size=20) b, s = next(gen) show_images(b[0:20], s[0:20]) def plot_results(hist, metrics, xlb, ylb, title, leg, fsize=(10, 5)): fig, ax = plt.subplots(1, 1, figsize=fsize) for m in metrics: ax.plot(hist.history[m]) ax.set(xlabel=xlb, ylabel=ylb, title=title) ax.set_yscale('log') ax.legend(leg, loc='upper left') plt.show() def generate_train_test_split(X, y, test_size): return train_test_split(X, y, test_size=test_size) def tf_setup(): gpus = tf.config.list_physical_devices('GPU') if gpus: try: # Currently, memory growth needs to be the same across GPUs for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) logical_gpus = tf.config.experimental.list_logical_devices('GPU') print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs") except RuntimeError as e: # Memory growth must be set before GPUs have been initialized print(e) if __name__ == "__main__": tf_setup() X, y = load_data() print("Data Loaded") # batch_size = 20 X_train, X_test, y_train, y_test = generate_train_test_split(X, y, test_size=0.33) show_sample_images(X_train, y_train)
32.794304
116
0.655505
4a10485a1e7ad7385a598dcbd4b4ed63c75940c7
2,042
py
Python
main.py
RhnSaxena/KonfHub
09efc83556880469710f05209c6190b8c99e3d97
[ "MIT" ]
null
null
null
main.py
RhnSaxena/KonfHub
09efc83556880469710f05209c6190b8c99e3d97
[ "MIT" ]
null
null
null
main.py
RhnSaxena/KonfHub
09efc83556880469710f05209c6190b8c99e3d97
[ "MIT" ]
null
null
null
import json import config from source.requestUtil import requestGet from source.readable import createReadableDict from source.replicas import createDict, findExactReplicas, findSimilar from source.fileWriter import writeToJSONFile, writeToTXT def driver(): # Perform the GET operation on the link # and receive response response = requestGet(config.link) # Create a dict in readable format. readableData = createReadableDict(response) # Write the readable dict to .json file writeToJSONFile( "./{folder}/{file}.{extension}".format( folder=config.folder, file=config.readableFileName, extension="json" ), readableData, ) # Write the readable dict to .txt file writeToTXT( "./{folder}/{file}.{extension}".format( folder=config.folder, file=config.readableFileName, extension="txt" ), readableData, ) print("The events have been printed in readable format.") # Create Dictionary for the events, # and write it to .json file eventDict = createDict(response) writeToJSONFile( "./{folder}/{file}.{extension}".format( folder=config.folder, file=config.eventsFileName, extension="json" ), eventDict, ) print("The events have been printed.") # Find duplicates events, # and write it to .json file duplicatesDict = findExactReplicas(eventDict) writeToJSONFile( "./{folder}/{file}.{extension}".format( folder=config.folder, file=config.exactDuplicatesFileName, extension="json" ), duplicatesDict, ) print("The duplicates events have been printed.") # Find similar events, # and write it to .json file similarDict = findSimilar(eventDict) writeToJSONFile( "./{folder}/{file}.{extension}".format( folder=config.folder, file=config.similarEventsFileName, extension="json" ), similarDict, ) print("The similar events have been printed.") driver()
30.029412
87
0.660627
4a1048a0aaf7dc7e8e4422085370e34328979564
2,506
py
Python
neuroConstruct/pythonScripts/RunTestsLEMS.py
OpenSourceBrain/L5bPyrCellHayEtAl2011
23d938d8c4ba1fb83cdd99810ac324ae4f58bd7c
[ "MIT" ]
4
2020-06-15T13:10:23.000Z
2022-02-17T18:20:05.000Z
neuroConstruct/pythonScripts/RunTestsLEMS.py
OpenSourceBrain/L5bPyrCellHayEtAl2011
23d938d8c4ba1fb83cdd99810ac324ae4f58bd7c
[ "MIT" ]
null
null
null
neuroConstruct/pythonScripts/RunTestsLEMS.py
OpenSourceBrain/L5bPyrCellHayEtAl2011
23d938d8c4ba1fb83cdd99810ac324ae4f58bd7c
[ "MIT" ]
1
2022-02-17T11:23:37.000Z
2022-02-17T11:23:37.000Z
# # # File to test current configuration of project # # Author: Padraig Gleeson # # This file has been developed as part of the neuroConstruct project # This work has been funded by the Wellcome Trust # # import sys import os try: from java.io import File except ImportError: print "Note: this file should be run using nC.bat -python XXX.py' or 'nC.sh -python XXX.py'" print "See http://www.neuroconstruct.org/docs/python.html for more details" quit() sys.path.append(os.environ["NC_HOME"]+"/pythonNeuroML/nCUtils") import ncutils as nc # Many useful functions such as SimManager.runMultipleSims found here projFile = File("../L5bPyrCellHayEtAl2011.ncx") ############## Main settings ################## simConfigs = [] simConfigs.append("TestNeuroML") simDt = 0.001 simulators = ["NEURON", "LEMS"] varTimestepNeuron = False varTimestepTolerance = 0.0001 plotSims = True plotVoltageOnly = True runInBackground = True analyseSims = True verbose = True ############################################# def testAll(argv=None): if argv is None: argv = sys.argv print "Loading project from "+ projFile.getCanonicalPath() simManager = nc.SimulationManager(projFile, verbose = verbose, numConcurrentSims = 2) simManager.runMultipleSims(simConfigs = simConfigs, simDt = simDt, simulators = simulators, runInBackground = runInBackground, varTimestepNeuron = varTimestepNeuron, varTimestepTolerance = varTimestepTolerance) simManager.reloadSims(plotVoltageOnly = plotVoltageOnly, analyseSims = analyseSims) # These were discovered using ../../NEURON/test.py WITH DT = 0.001 times = [306.303, 320.052, 334.602, 349.882, 365.473, 381.181, 396.932] spikeTimesToCheck = {'CG_TestCML_0': times} spikeTimeAccuracy = 0.1 report = simManager.checkSims(spikeTimesToCheck = spikeTimesToCheck, spikeTimeAccuracy = spikeTimeAccuracy) print report return report if __name__ == "__main__": testAll()
27.538462
97
0.557861
4a1048d610ce8c0fec2c04e456a510c421edb520
860
py
Python
tests/test_basic.py
saksham219/scvelo
41fb2a90ae6a71577cf2c55b80e1ade4407891b7
[ "BSD-3-Clause" ]
null
null
null
tests/test_basic.py
saksham219/scvelo
41fb2a90ae6a71577cf2c55b80e1ade4407891b7
[ "BSD-3-Clause" ]
null
null
null
tests/test_basic.py
saksham219/scvelo
41fb2a90ae6a71577cf2c55b80e1ade4407891b7
[ "BSD-3-Clause" ]
null
null
null
import scvelo as scv import numpy as np def test_einsum(): from scvelo.tools.utils import prod_sum_obs, prod_sum_var, norm Ms, Mu = np.random.rand(5, 4), np.random.rand(5, 4) assert np.allclose(prod_sum_obs(Ms, Mu), np.sum(Ms * Mu, 0)) assert np.allclose(prod_sum_var(Ms, Mu), np.sum(Ms * Mu, 1)) assert np.allclose(norm(Ms), np.linalg.norm(Ms, axis=1)) # def test_velocity_graph(): # adata = scv.datasets.toy_data(n_obs=500) # scv.pp.recipe_velocity(adata, n_top_genes=300) # scv.tl.velocity(adata) # # scv.tl.velocity_graph(adata) # graph = adata.uns['velocity_graph'] + adata.uns['velocity_graph_neg'] # graph.setdiag(0) # graph.eliminate_zeros() # # T = scv.tl.transition_matrix(adata) # T.setdiag(0) # T.eliminate_zeros() # # assert np.allclose((T > 0).toarray(), (graph > 0).toarray())
30.714286
75
0.661628
4a1048e5c89539832b9a87bd683699939a79ba5d
1,733
py
Python
bureau/assignments/views.py
clairempr/bureau
c9fd114e637829b4e9ff643459d15602cc2efc2f
[ "Apache-2.0" ]
1
2019-02-15T09:05:35.000Z
2019-02-15T09:05:35.000Z
bureau/assignments/views.py
clairempr/bureau
c9fd114e637829b4e9ff643459d15602cc2efc2f
[ "Apache-2.0" ]
null
null
null
bureau/assignments/views.py
clairempr/bureau
c9fd114e637829b4e9ff643459d15602cc2efc2f
[ "Apache-2.0" ]
null
null
null
from django.views.generic import ListView from assignments.models import Assignment from places.models import Place class AssignmentListView(ListView): model = Assignment queryset = Assignment.objects.all() ordering = ['start_date', 'positions__title', 'employee__last_name', 'employee__first_name'] template_name = "assignments/assignment_list.html" def get_place(self): # If place is in kwargs and it's the pk of a Place, return the Place # otherwise return None place_pk = self.kwargs.get('place') if place_pk: try: return Place.objects.get(pk=place_pk) except Place.DoesNotExist: pass return None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Put the specified Place object in the view context. If there wasn't one, it will be None context['place'] = self.get_place() return context def get_queryset(self): # If a place is specified, only return assignments in that exact place, not places in that place place = self.get_place() if place: queryset = Assignment.objects.in_place(place=place, exact=True) else: queryset = self.queryset return queryset.order_by(*self.ordering) assignment_list_view = AssignmentListView.as_view() class BureauHeadquartersAssignmentListView(AssignmentListView): def get_queryset(self): # Return Bureau Headquarters assignments only return Assignment.objects.filter(bureau_headquarters=True).order_by(*self.ordering) bureau_headquarters_assignment_list_view = BureauHeadquartersAssignmentListView.as_view()
32.698113
104
0.691864
4a104972b02fe1199013f78dd4348a37afde5a22
16,120
py
Python
homeassistant/components/homekit/type_media_players.py
twrecked/core
d3ae8a938cdea9b6e0d443c91c37ac3dbbd459ab
[ "Apache-2.0" ]
2
2021-09-13T21:44:02.000Z
2021-12-17T21:20:51.000Z
homeassistant/components/homekit/type_media_players.py
twrecked/core
d3ae8a938cdea9b6e0d443c91c37ac3dbbd459ab
[ "Apache-2.0" ]
5
2021-02-08T20:55:25.000Z
2022-03-12T00:51:18.000Z
homeassistant/components/homekit/type_media_players.py
twrecked/core
d3ae8a938cdea9b6e0d443c91c37ac3dbbd459ab
[ "Apache-2.0" ]
2
2020-11-04T07:40:01.000Z
2021-09-13T21:44:03.000Z
"""Class to hold all media player accessories.""" import logging from pyhap.const import CATEGORY_SWITCH, CATEGORY_TELEVISION from homeassistant.components.media_player import ( ATTR_INPUT_SOURCE, ATTR_INPUT_SOURCE_LIST, ATTR_MEDIA_VOLUME_LEVEL, ATTR_MEDIA_VOLUME_MUTED, DOMAIN, SERVICE_SELECT_SOURCE, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_SELECT_SOURCE, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_PLAY, SERVICE_MEDIA_PLAY_PAUSE, SERVICE_MEDIA_STOP, SERVICE_TURN_OFF, SERVICE_TURN_ON, SERVICE_VOLUME_DOWN, SERVICE_VOLUME_MUTE, SERVICE_VOLUME_SET, SERVICE_VOLUME_UP, STATE_OFF, STATE_PAUSED, STATE_PLAYING, STATE_STANDBY, STATE_UNKNOWN, ) from homeassistant.core import callback from .accessories import TYPES, HomeAccessory from .const import ( CHAR_ACTIVE, CHAR_ACTIVE_IDENTIFIER, CHAR_CONFIGURED_NAME, CHAR_CURRENT_VISIBILITY_STATE, CHAR_IDENTIFIER, CHAR_INPUT_SOURCE_TYPE, CHAR_IS_CONFIGURED, CHAR_MUTE, CHAR_NAME, CHAR_ON, CHAR_REMOTE_KEY, CHAR_SLEEP_DISCOVER_MODE, CHAR_VOLUME, CHAR_VOLUME_CONTROL_TYPE, CHAR_VOLUME_SELECTOR, CONF_FEATURE_LIST, FEATURE_ON_OFF, FEATURE_PLAY_PAUSE, FEATURE_PLAY_STOP, FEATURE_TOGGLE_MUTE, SERV_INPUT_SOURCE, SERV_SWITCH, SERV_TELEVISION, SERV_TELEVISION_SPEAKER, ) from .util import get_media_player_features _LOGGER = logging.getLogger(__name__) MEDIA_PLAYER_KEYS = { # 0: "Rewind", # 1: "FastForward", # 2: "NextTrack", # 3: "PreviousTrack", # 4: "ArrowUp", # 5: "ArrowDown", # 6: "ArrowLeft", # 7: "ArrowRight", # 8: "Select", # 9: "Back", # 10: "Exit", 11: SERVICE_MEDIA_PLAY_PAUSE, # 15: "Information", } # Names may not contain special characters # or emjoi (/ is a special character for Apple) MODE_FRIENDLY_NAME = { FEATURE_ON_OFF: "Power", FEATURE_PLAY_PAUSE: "Play-Pause", FEATURE_PLAY_STOP: "Play-Stop", FEATURE_TOGGLE_MUTE: "Mute", } MEDIA_PLAYER_OFF_STATES = ( STATE_OFF, STATE_UNKNOWN, STATE_STANDBY, "None", ) @TYPES.register("MediaPlayer") class MediaPlayer(HomeAccessory): """Generate a Media Player accessory.""" def __init__(self, *args): """Initialize a Switch accessory object.""" super().__init__(*args, category=CATEGORY_SWITCH) state = self.hass.states.get(self.entity_id) self.chars = { FEATURE_ON_OFF: None, FEATURE_PLAY_PAUSE: None, FEATURE_PLAY_STOP: None, FEATURE_TOGGLE_MUTE: None, } feature_list = self.config.get( CONF_FEATURE_LIST, get_media_player_features(state) ) if FEATURE_ON_OFF in feature_list: name = self.generate_service_name(FEATURE_ON_OFF) serv_on_off = self.add_preload_service(SERV_SWITCH, CHAR_NAME) serv_on_off.configure_char(CHAR_NAME, value=name) self.chars[FEATURE_ON_OFF] = serv_on_off.configure_char( CHAR_ON, value=False, setter_callback=self.set_on_off ) if FEATURE_PLAY_PAUSE in feature_list: name = self.generate_service_name(FEATURE_PLAY_PAUSE) serv_play_pause = self.add_preload_service(SERV_SWITCH, CHAR_NAME) serv_play_pause.configure_char(CHAR_NAME, value=name) self.chars[FEATURE_PLAY_PAUSE] = serv_play_pause.configure_char( CHAR_ON, value=False, setter_callback=self.set_play_pause ) if FEATURE_PLAY_STOP in feature_list: name = self.generate_service_name(FEATURE_PLAY_STOP) serv_play_stop = self.add_preload_service(SERV_SWITCH, CHAR_NAME) serv_play_stop.configure_char(CHAR_NAME, value=name) self.chars[FEATURE_PLAY_STOP] = serv_play_stop.configure_char( CHAR_ON, value=False, setter_callback=self.set_play_stop ) if FEATURE_TOGGLE_MUTE in feature_list: name = self.generate_service_name(FEATURE_TOGGLE_MUTE) serv_toggle_mute = self.add_preload_service(SERV_SWITCH, CHAR_NAME) serv_toggle_mute.configure_char(CHAR_NAME, value=name) self.chars[FEATURE_TOGGLE_MUTE] = serv_toggle_mute.configure_char( CHAR_ON, value=False, setter_callback=self.set_toggle_mute ) self.async_update_state(state) def generate_service_name(self, mode): """Generate name for individual service.""" return f"{self.display_name} {MODE_FRIENDLY_NAME[mode]}" def set_on_off(self, value): """Move switch state to value if call came from HomeKit.""" _LOGGER.debug('%s: Set switch state for "on_off" to %s', self.entity_id, value) service = SERVICE_TURN_ON if value else SERVICE_TURN_OFF params = {ATTR_ENTITY_ID: self.entity_id} self.call_service(DOMAIN, service, params) def set_play_pause(self, value): """Move switch state to value if call came from HomeKit.""" _LOGGER.debug( '%s: Set switch state for "play_pause" to %s', self.entity_id, value ) service = SERVICE_MEDIA_PLAY if value else SERVICE_MEDIA_PAUSE params = {ATTR_ENTITY_ID: self.entity_id} self.call_service(DOMAIN, service, params) def set_play_stop(self, value): """Move switch state to value if call came from HomeKit.""" _LOGGER.debug( '%s: Set switch state for "play_stop" to %s', self.entity_id, value ) service = SERVICE_MEDIA_PLAY if value else SERVICE_MEDIA_STOP params = {ATTR_ENTITY_ID: self.entity_id} self.call_service(DOMAIN, service, params) def set_toggle_mute(self, value): """Move switch state to value if call came from HomeKit.""" _LOGGER.debug( '%s: Set switch state for "toggle_mute" to %s', self.entity_id, value ) params = {ATTR_ENTITY_ID: self.entity_id, ATTR_MEDIA_VOLUME_MUTED: value} self.call_service(DOMAIN, SERVICE_VOLUME_MUTE, params) @callback def async_update_state(self, new_state): """Update switch state after state changed.""" current_state = new_state.state if self.chars[FEATURE_ON_OFF]: hk_state = current_state not in MEDIA_PLAYER_OFF_STATES _LOGGER.debug( '%s: Set current state for "on_off" to %s', self.entity_id, hk_state ) if self.chars[FEATURE_ON_OFF].value != hk_state: self.chars[FEATURE_ON_OFF].set_value(hk_state) if self.chars[FEATURE_PLAY_PAUSE]: hk_state = current_state == STATE_PLAYING _LOGGER.debug( '%s: Set current state for "play_pause" to %s', self.entity_id, hk_state, ) if self.chars[FEATURE_PLAY_PAUSE].value != hk_state: self.chars[FEATURE_PLAY_PAUSE].set_value(hk_state) if self.chars[FEATURE_PLAY_STOP]: hk_state = current_state == STATE_PLAYING _LOGGER.debug( '%s: Set current state for "play_stop" to %s', self.entity_id, hk_state, ) if self.chars[FEATURE_PLAY_STOP].value != hk_state: self.chars[FEATURE_PLAY_STOP].set_value(hk_state) if self.chars[FEATURE_TOGGLE_MUTE]: current_state = bool(new_state.attributes.get(ATTR_MEDIA_VOLUME_MUTED)) _LOGGER.debug( '%s: Set current state for "toggle_mute" to %s', self.entity_id, current_state, ) if self.chars[FEATURE_TOGGLE_MUTE].value != current_state: self.chars[FEATURE_TOGGLE_MUTE].set_value(current_state) @TYPES.register("TelevisionMediaPlayer") class TelevisionMediaPlayer(HomeAccessory): """Generate a Television Media Player accessory.""" def __init__(self, *args): """Initialize a Switch accessory object.""" super().__init__(*args, category=CATEGORY_TELEVISION) state = self.hass.states.get(self.entity_id) self.support_select_source = False self.sources = [] # Add additional characteristics if volume or input selection supported self.chars_tv = [] self.chars_speaker = [] features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) if features & (SUPPORT_PLAY | SUPPORT_PAUSE): self.chars_tv.append(CHAR_REMOTE_KEY) if features & SUPPORT_VOLUME_MUTE or features & SUPPORT_VOLUME_STEP: self.chars_speaker.extend( (CHAR_NAME, CHAR_ACTIVE, CHAR_VOLUME_CONTROL_TYPE, CHAR_VOLUME_SELECTOR) ) if features & SUPPORT_VOLUME_SET: self.chars_speaker.append(CHAR_VOLUME) source_list = state.attributes.get(ATTR_INPUT_SOURCE_LIST, []) if source_list and features & SUPPORT_SELECT_SOURCE: self.support_select_source = True serv_tv = self.add_preload_service(SERV_TELEVISION, self.chars_tv) self.set_primary_service(serv_tv) serv_tv.configure_char(CHAR_CONFIGURED_NAME, value=self.display_name) serv_tv.configure_char(CHAR_SLEEP_DISCOVER_MODE, value=True) self.char_active = serv_tv.configure_char( CHAR_ACTIVE, setter_callback=self.set_on_off ) if CHAR_REMOTE_KEY in self.chars_tv: self.char_remote_key = serv_tv.configure_char( CHAR_REMOTE_KEY, setter_callback=self.set_remote_key ) if CHAR_VOLUME_SELECTOR in self.chars_speaker: serv_speaker = self.add_preload_service( SERV_TELEVISION_SPEAKER, self.chars_speaker ) serv_tv.add_linked_service(serv_speaker) name = f"{self.display_name} Volume" serv_speaker.configure_char(CHAR_NAME, value=name) serv_speaker.configure_char(CHAR_ACTIVE, value=1) self.char_mute = serv_speaker.configure_char( CHAR_MUTE, value=False, setter_callback=self.set_mute ) volume_control_type = 1 if CHAR_VOLUME in self.chars_speaker else 2 serv_speaker.configure_char( CHAR_VOLUME_CONTROL_TYPE, value=volume_control_type ) self.char_volume_selector = serv_speaker.configure_char( CHAR_VOLUME_SELECTOR, setter_callback=self.set_volume_step ) if CHAR_VOLUME in self.chars_speaker: self.char_volume = serv_speaker.configure_char( CHAR_VOLUME, setter_callback=self.set_volume ) if self.support_select_source: self.sources = source_list self.char_input_source = serv_tv.configure_char( CHAR_ACTIVE_IDENTIFIER, setter_callback=self.set_input_source ) for index, source in enumerate(self.sources): serv_input = self.add_preload_service( SERV_INPUT_SOURCE, [CHAR_IDENTIFIER, CHAR_NAME] ) serv_tv.add_linked_service(serv_input) serv_input.configure_char(CHAR_CONFIGURED_NAME, value=source) serv_input.configure_char(CHAR_NAME, value=source) serv_input.configure_char(CHAR_IDENTIFIER, value=index) serv_input.configure_char(CHAR_IS_CONFIGURED, value=True) input_type = 3 if "hdmi" in source.lower() else 0 serv_input.configure_char(CHAR_INPUT_SOURCE_TYPE, value=input_type) serv_input.configure_char(CHAR_CURRENT_VISIBILITY_STATE, value=False) _LOGGER.debug("%s: Added source %s.", self.entity_id, source) self.async_update_state(state) def set_on_off(self, value): """Move switch state to value if call came from HomeKit.""" _LOGGER.debug('%s: Set switch state for "on_off" to %s', self.entity_id, value) service = SERVICE_TURN_ON if value else SERVICE_TURN_OFF params = {ATTR_ENTITY_ID: self.entity_id} self.call_service(DOMAIN, service, params) def set_mute(self, value): """Move switch state to value if call came from HomeKit.""" _LOGGER.debug( '%s: Set switch state for "toggle_mute" to %s', self.entity_id, value ) params = {ATTR_ENTITY_ID: self.entity_id, ATTR_MEDIA_VOLUME_MUTED: value} self.call_service(DOMAIN, SERVICE_VOLUME_MUTE, params) def set_volume(self, value): """Send volume step value if call came from HomeKit.""" _LOGGER.debug("%s: Set volume to %s", self.entity_id, value) params = {ATTR_ENTITY_ID: self.entity_id, ATTR_MEDIA_VOLUME_LEVEL: value} self.call_service(DOMAIN, SERVICE_VOLUME_SET, params) def set_volume_step(self, value): """Send volume step value if call came from HomeKit.""" _LOGGER.debug("%s: Step volume by %s", self.entity_id, value) service = SERVICE_VOLUME_DOWN if value else SERVICE_VOLUME_UP params = {ATTR_ENTITY_ID: self.entity_id} self.call_service(DOMAIN, service, params) def set_input_source(self, value): """Send input set value if call came from HomeKit.""" _LOGGER.debug("%s: Set current input to %s", self.entity_id, value) source = self.sources[value] params = {ATTR_ENTITY_ID: self.entity_id, ATTR_INPUT_SOURCE: source} self.call_service(DOMAIN, SERVICE_SELECT_SOURCE, params) def set_remote_key(self, value): """Send remote key value if call came from HomeKit.""" _LOGGER.debug("%s: Set remote key to %s", self.entity_id, value) service = MEDIA_PLAYER_KEYS.get(value) if service: # Handle Play Pause if service == SERVICE_MEDIA_PLAY_PAUSE: state = self.hass.states.get(self.entity_id).state if state in (STATE_PLAYING, STATE_PAUSED): service = ( SERVICE_MEDIA_PLAY if state == STATE_PAUSED else SERVICE_MEDIA_PAUSE ) params = {ATTR_ENTITY_ID: self.entity_id} self.call_service(DOMAIN, service, params) @callback def async_update_state(self, new_state): """Update Television state after state changed.""" current_state = new_state.state # Power state television hk_state = 0 if current_state not in MEDIA_PLAYER_OFF_STATES: hk_state = 1 _LOGGER.debug("%s: Set current active state to %s", self.entity_id, hk_state) if self.char_active.value != hk_state: self.char_active.set_value(hk_state) # Set mute state if CHAR_VOLUME_SELECTOR in self.chars_speaker: current_mute_state = bool(new_state.attributes.get(ATTR_MEDIA_VOLUME_MUTED)) _LOGGER.debug( "%s: Set current mute state to %s", self.entity_id, current_mute_state, ) if self.char_mute.value != current_mute_state: self.char_mute.set_value(current_mute_state) # Set active input if self.support_select_source and self.sources: source_name = new_state.attributes.get(ATTR_INPUT_SOURCE) _LOGGER.debug("%s: Set current input to %s", self.entity_id, source_name) if source_name in self.sources: index = self.sources.index(source_name) if self.char_input_source.value != index: self.char_input_source.set_value(index) else: _LOGGER.warning( "%s: Sources out of sync. Restart Home Assistant", self.entity_id, ) if self.char_input_source.value != 0: self.char_input_source.set_value(0)
38.75
88
0.649132
4a104a1e2413b328cbeb4d1ad5165b75f352a2f4
1,780
py
Python
Dynamic Programming/Candies.py
adgarciaar/HackerRankExercises
0d71dafcc437bac200034faf8be1c2794775b05d
[ "MIT" ]
null
null
null
Dynamic Programming/Candies.py
adgarciaar/HackerRankExercises
0d71dafcc437bac200034faf8be1c2794775b05d
[ "MIT" ]
null
null
null
Dynamic Programming/Candies.py
adgarciaar/HackerRankExercises
0d71dafcc437bac200034faf8be1c2794775b05d
[ "MIT" ]
null
null
null
#!/bin/python3 import math import os import random import re import sys def candiesAux(n, arr, i, direction, previousInAuxArray): numberCandies = None if(direction == 0): # left to right if( arr[i-1] < arr[i] ): numberCandies = previousInAuxArray + 1 else: if( i+1 < n ): if( arr[i+1] < arr[i] ): numberCandies = 2 else: numberCandies = 1 else: numberCandies = 1 else: # right to left if( arr[i+1] < arr[i] ): numberCandies = previousInAuxArray + 1 else: if( i-1 >= 0 ): if( arr[i-1] < arr[i] ): numberCandies = 2 else: numberCandies = 1 else: numberCandies = 1 return numberCandies # Complete the candies function below. def candies(n, arr): i = 1 auxArrayLR = [ 1 for i in range( len(arr) ) ] while( i < len(arr) ): auxArrayLR[i] = candiesAux(n, arr, i, 0, auxArrayLR[i-1]) i += 1 j = len(arr)-2 auxArrayRL = [ 1 for i in range( len(arr) ) ] while( j >= 0 ): auxArrayRL[j] = candiesAux(n, arr, j, 1, auxArrayRL[j+1]) j -= 1 i = 0 numberCandies = 0 while( i < len(arr) ): numberCandies += max( auxArrayLR[i], auxArrayRL[i] ) i += 1 #print(auxArray) return numberCandies if __name__ == '__main__': #fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) arr = [] for _ in range(n): arr_item = int(input()) arr.append(arr_item) result = candies(n, arr) #fptr.write(str(result) + '\n') print(str(result) + '\n') #fptr.close()
23.421053
65
0.493258
4a104add6b9d0f7fa1a86d845f64e6e6ffdd5295
18,085
py
Python
src/poke_env/environment/pokemon.py
BrunoMNDantas/poke-env
1e7ac23619ebd869d47862a1b9edd12525eabdac
[ "MIT" ]
null
null
null
src/poke_env/environment/pokemon.py
BrunoMNDantas/poke-env
1e7ac23619ebd869d47862a1b9edd12525eabdac
[ "MIT" ]
3
2022-03-05T14:22:08.000Z
2022-03-29T10:36:47.000Z
src/poke_env/environment/pokemon.py
darrenswhite/poke-env
1116d7ef765fdf1048083801adfa528df3f7215e
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Set from typing import Tuple from typing import Union from poke_env.data import POKEDEX from poke_env.environment.effect import Effect from poke_env.environment.pokemon_gender import PokemonGender from poke_env.environment.pokemon_type import PokemonType from poke_env.environment.move import Move from poke_env.environment.status import Status from poke_env.environment.z_crystal import Z_CRYSTAL from poke_env.utils import to_id_str class Pokemon: __slots__ = ( "_ability", "_active", "_active", "_base_stats", "_boosts", "_current_hp", "_effects", "_gender", "_heightm", "_item", "_last_details", "_last_request", "_level", "_max_hp", "_moves", "_must_recharge", "_possible_abilities", "_preparing", "_shiny", "_species", "_status", "_type_1", "_type_2", "_weightkg", ) def __init__( self, *, species: Optional[str] = None, request_pokemon: Optional[Dict[str, Any]] = None, details: Optional[str] = None, ) -> None: # Species related attributes self._base_stats: Dict[str, int] self._heightm: int self._possible_abilities: List[str] self._species: str = "" self._type_1: PokemonType self._type_2: Optional[PokemonType] = None self._weightkg: int # Individual related attributes self._ability: Optional[str] = None self._active: bool self._gender: Optional[PokemonGender] = None self._level: int = 100 self._max_hp: int = 0 self._moves: Dict[str, Move] = {} self._shiny: Optional[bool] = False # Battle related attributes self._active: bool = False self._boosts: Dict[str, int] = { "accuracy": 0, "atk": 0, "def": 0, "evasion": 0, "spa": 0, "spd": 0, "spe": 0, } self._current_hp: int = 0 self._effects: Set[Effect] = set() self._item: Optional[str] = None self._last_request: dict = {} self._last_details: str = "" self._must_recharge = False self._preparing = False self._status: Optional[Status] = None if request_pokemon: self._update_from_request(request_pokemon) elif details: self._update_from_details(details) elif species: self._update_from_pokedex(species) def __repr__(self) -> str: return self.__str__() def __str__(self) -> str: return ( f"{self._species} (pokemon object) " f"[Active: {self._active}, Status: {self._status}]" ) def _add_move(self, move_id: str, use: bool = False) -> None: """Store the move if applicable.""" id_ = Move.retrieve_id(move_id) if not Move.should_be_stored(id_): return if id_ not in self._moves: move = Move(move_id=id_) self._moves[id_] = move if use: self._moves[id_].use() def _boost(self, stat, amount): self._boosts[stat] += int(amount) if self._boosts[stat] > 6: self._boosts[stat] = 6 elif self._boosts[stat] < -6: self._boosts[stat] = -6 def _clear_boosts(self): for stat in self._boosts: self._boosts[stat] = 0 def _clear_effects(self): self._effects = set() def _clear_negative_boosts(self): for stat, value in self._boosts.items(): if value < 0: self._boosts[stat] = 0 def _clear_positive_boosts(self): for stat, value in self._boosts.items(): if value > 0: self._boosts[stat] = 0 def _copy_boosts(self, mon): self._boosts = dict(mon._boosts.items()) def _cure_status(self, status=None): if status and Status[status.upper()] == self._status: self._status = None elif status is None and not self.fainted: self._status = None def _damage(self, hp_status): self._set_hp_status(hp_status) def _end_effect(self, effect): effect = Effect.from_showdown_message(effect) if effect in self._effects: self._effects.remove(effect) def _end_item(self, item): self._item = None def _faint(self): self._current_hp = 0 self.status = Status.FNT def _forme_change(self, species): species = species.split(",")[0] self._update_from_pokedex(species, store_species=False) def _heal(self, hp_status): self._set_hp_status(hp_status) def _invert_boosts(self): self._boosts = {k: -v for k, v in self._boosts.items()} def _mega_evolve(self, stone): species_id_str = to_id_str(self.species) mega_species = ( species_id_str + "mega" if not species_id_str.endswith("mega") else species_id_str ) if mega_species in POKEDEX: self._update_from_pokedex(mega_species, store_species=False) elif stone[-1] in "XY": mega_species = mega_species + stone[-1].lower() self._update_from_pokedex(mega_species, store_species=False) def _moved(self, move): self._must_recharge = False self._preparing = False self._add_move(move, use=True) def _prepare(self, move, target): self._preparing = (move, target) def _primal(self): species_id_str = to_id_str(self._species) primal_species = ( species_id_str + "primal" if not species_id_str.endswith("primal") else species_id_str ) self._update_from_pokedex(primal_species, store_species=False) def _set_boost(self, stat, amount): assert abs(int(amount)) <= 6 self._boosts[stat] = int(amount) def _set_hp(self, hp_status): self._set_hp_status(hp_status) def _set_hp_status(self, hp_status): if hp_status == "0 fnt": self._faint() return if " " in hp_status: hp, status = hp_status.split(" ") self.status = Status[status.upper()] else: hp = hp_status hp = "".join([c for c in hp if c in "0123456789/"]).split("/") self._current_hp, self._max_hp = hp self._current_hp = int(self._current_hp) self._max_hp = int(self._max_hp) def _start_effect(self, effect): effect = Effect.from_showdown_message(effect) self._effects.add(effect) def _swap_boosts(self): self._boosts["atk"], self._boosts["spa"] = ( self._boosts["spa"], self._boosts["atk"], ) def _switch_in(self, details=None): self._active = True if details: self._update_from_details(details) def _switch_out(self): self._active = False self._clear_boosts() self._clear_effects() self._must_recharge = False self._preparing = False def _transform(self, into): current_hp = self.current_hp self._update_from_pokedex(into.species, store_species=False) self._current_hp = int(current_hp) self._boosts = into.boosts.copy() def _update_from_pokedex(self, species: str, store_species: bool = True) -> None: species = to_id_str(species) dex_entry = POKEDEX[species] if store_species: self._species = species self._base_stats = dex_entry["baseStats"] self._type_1 = PokemonType.from_name(dex_entry["types"][0]) if len(dex_entry["types"]) == 1: self._type_2 = None else: self._type_2 = PokemonType.from_name(dex_entry["types"][1]) self._possible_abilities = dex_entry["abilities"] self._heightm = dex_entry["heightm"] self._weightkg = dex_entry["weightkg"] def _update_from_details(self, details: str) -> None: if details == self._last_details: return else: self._last_details = details if ", shiny" in details: self._shiny = True details = details.replace(", shiny", "") else: self._shiny = False split_details = details.split(", ") gender = None level = None if len(split_details) == 3: species, level, gender = split_details elif len(split_details) == 2: if split_details[1].startswith("L"): species, level = split_details else: species, gender = split_details else: species = to_id_str(split_details[0]) if gender: self._gender = PokemonGender.from_request_details(gender) else: self._gender = PokemonGender.NEUTRAL if level: self._level = int(level[1:]) else: self._level = 100 if species != self._species: self._update_from_pokedex(species) def _update_from_request(self, request_pokemon: Dict[str, Any]) -> None: self._active = request_pokemon["active"] if request_pokemon == self._last_request: return if "ability" in request_pokemon: self._ability = request_pokemon["ability"] elif "baseAbility" in request_pokemon: self._ability = request_pokemon["baseAbility"] self._last_request = request_pokemon condition = request_pokemon["condition"] self._set_hp_status(condition) self._item = request_pokemon["item"] details = request_pokemon["details"] self._update_from_details(details) for move in request_pokemon["moves"]: self._add_move(move) if len(self._moves) > 4: self._moves = {} for move in request_pokemon["moves"]: self._add_move(move) def _used_z_move(self): self._item = None def _was_illusionned(self): self._current_hp = None self._max_hp = None self._status = None self._switch_out() def damage_multiplier(self, type_or_move: Union[PokemonType, Move]) -> float: """ Returns the damage multiplier associated with a given type or move on this pokemon. This method is a shortcut for PokemonType.damage_multiplier with relevant types. :param type_or_move: The type or move of interest. :type type_or_move: PokemonType or Move :return: The damage multiplier associated with given type on the pokemon. :rtype: float """ if isinstance(type_or_move, Move): type_or_move = type_or_move.type if isinstance(type_or_move, PokemonType): return type_or_move.damage_multiplier(self._type_1, self._type_2) # This can happen with special moves, which do not necessarily have a type return 1 @property def ability(self) -> Optional[str]: """ :return: The pokemon's ability. None if unknown. :rtype: str, optional """ return self._ability @ability.setter def ability(self, ability: Optional[str]): self._ability = ability @property def active(self) -> Optional[bool]: """ :return: Boolean indicating whether the pokemon is active. :rtype: bool """ return self._active @property def available_z_moves(self) -> List[Move]: """ Caution: this property is not properly tested yet. :return: The set of moves that pokemon can use as z-moves. :rtype: List[Move] """ if isinstance(self.item, str) and self.item.endswith("iumz"): # pyre-ignore type_, move = Z_CRYSTAL[self.item] # pyre-ignore if type_: return [ move for move_id, move in self._moves.items() if move.type == type_ and move.can_z_move ] elif move in self._moves: return [self._moves[move]] return [] @property def base_stats(self) -> Dict[str, int]: """ :return: The pokemon's base stats. :rtype: Dict[str, int] """ return self._base_stats @property def boosts(self) -> Dict[str, int]: """ :return: The pokemon's boosts. :rtype: Dict[str, int] """ return self._boosts @property def current_hp(self) -> int: """ :return: The pokemon's current hp. For your pokemons, this is the actual value. For opponent's pokemon, this value depends on showdown information: it can be on a scale from 0 to 100 or on a pixel scale. :rtype: int """ return self._current_hp @property def current_hp_fraction(self) -> float: """ :return: The pokemon's current remaining hp fraction. :rtype: float """ if self.current_hp: return self.current_hp / self.max_hp return 0 @property def effects(self) -> Set[Effect]: """ :return: The effects currently affecting the pokemon. :rtype: Set[Effect] """ return self._effects @property def fainted(self) -> bool: """ :return: Wheter the pokemon has fainted. :rtype: bool """ return Status.FNT == self._status @property def gender(self) -> Optional[PokemonGender]: """ :return: The pokemon's gender. :rtype: PokemonGender, optional """ return self._gender @property def height(self) -> float: """ :return: The pokemon's height, in meters. :rtype: float """ return self._heightm @property def is_dynamaxed(self) -> bool: """ :return: Whether the pokemon is currently dynamaxed :rtype: bool """ return Effect.DYNAMAX in self.effects @property def item(self) -> Optional[str]: """ :return: The pokemon's item. :rtype: Optional[str] """ return self._item @item.setter def item(self, item: str): self._item = item @property def level(self) -> int: """ :return: The pokemon's level. :rtype: int """ return self._level @property def max_hp(self) -> int: """ :return: The pokemon's max hp. For your pokemons, this is the actual value. For opponent's pokemon, this value depends on showdown information: it can be on a scale from 0 to 100 or on a pixel scale. :rtype: int """ return self._max_hp @property def moves(self) -> Dict[str, Move]: """ :return: A dictionary of the pokemon's known moves. :rtype: Dict[str, Move] """ return self._moves @property def must_recharge(self) -> bool: """ :return: A boolean indicating whether the pokemon must recharge. :rtype: bool """ return self._must_recharge @must_recharge.setter def must_recharge(self, value) -> None: self._must_recharge = value @property def pokeball(self) -> Optional[str]: """ :return: The pokeball in which is the pokemon. :rtype: Optional[str] """ return self._last_request.get("pokeball", None) @property def possible_abilities(self) -> List[str]: """ :return: The list of possible abilities for this pokemon. :rtype: List[str] """ return self._possible_abilities @property def preparing(self) -> bool: """ :return: Whether this pokemon is preparing a multi-turn move. :rtype: bool """ return self._preparing @property def shiny(self) -> bool: """ :return: Whether this pokemon is shiny. :rtype: bool """ return bool(self._shiny) @property def species(self) -> str: """ :return: The pokemon's species. :rtype: Optional[str] """ return self._species @property def stats(self) -> Dict[str, Optional[int]]: """ :return: The pokemon's stats, as a dictionary. :rtype: Dict[str, Optional[int]] """ return self._last_request.get( "stats", {"atk": None, "def": None, "spa": None, "spd": None, "spe": None} ) @property def status(self) -> Optional[Status]: """ :return: The pokemon's status. :rtype: Optional[Status] """ return self._status @status.setter def status(self, status): if isinstance(status, str): status = Status[status.upper()] self._status = status @property def type_1(self) -> PokemonType: """ :return: The pokemon's first type. :rtype: PokemonType """ return self._type_1 @property def type_2(self) -> Optional[PokemonType]: """ :return: The pokemon's second type. :rtype: Optional[PokemonType] """ return self._type_2 @property def types(self) -> Tuple[PokemonType, Optional[PokemonType]]: """ :return: The pokemon's types, as a tuple. :rtype: Tuple[PokemonType, Optional[PokemonType]] """ return self.type_1, self._type_2 @property def weight(self) -> float: """ :return: The pokemon's weight, in kilograms. :rtype: float """ return self._weightkg
28.302034
88
0.572795
4a104b81000c52b9ed674f2eccfc682d72b81fd4
1,078
py
Python
Desafio 59.py
MoomenEltelbany/PythonDesafios
aa2f44d3104cf3607f58dc42c2f8fc8023f128de
[ "MIT" ]
null
null
null
Desafio 59.py
MoomenEltelbany/PythonDesafios
aa2f44d3104cf3607f58dc42c2f8fc8023f128de
[ "MIT" ]
null
null
null
Desafio 59.py
MoomenEltelbany/PythonDesafios
aa2f44d3104cf3607f58dc42c2f8fc8023f128de
[ "MIT" ]
null
null
null
num1 = int(input('Digite o primeiro número: ')) num2 = int(input('Digite o segundo número: ')) opcao = 0 while opcao != 5: opcao = int(input('''Solicite a sua escolha: [ 1 ] Somar [ 2 ] Multiplicar [ 3 ] Maior [ 4 ] Novo números [ 5 ] Sair do Programa ''')) if opcao == 1: soma = num1 + num2 print(f'A soma entre {num1} e {num2} é {soma}.') print('-=' * 20) elif opcao == 2: mult = num1 * num2 print(f'A multiplicação emtre {num1} e {num2} é {mult}.') print('-=' * 20) elif opcao == 3: if num1 > num2: print(f'O {num1} maior do {num2}') print('-=' * 20) elif num2 > num1: print(f'O {num2} maior do {num1}') print('-=' * 20) else: print(f'Os dois números são iguais.') print('-=' * 20) elif opcao == 4: num1 = int(input(f'Digite o primeiro número novamente.')) num2 = int(input(f'Digite o segundo número novamente.')) elif opcao == 5: break print(f'FIM!!!')
30.8
65
0.499072
4a104b93cd86febbcb517e5d4db7fc9200a24e0e
487
py
Python
functions/decorators/failsafe.py
kashifali-m398/advanced_python
988f407e986403b3238c9d1ea30b7d6fddf88c84
[ "MIT" ]
1
2021-01-04T18:33:08.000Z
2021-01-04T18:33:08.000Z
functions/decorators/failsafe.py
kashifali-m398/advanced_python
988f407e986403b3238c9d1ea30b7d6fddf88c84
[ "MIT" ]
null
null
null
functions/decorators/failsafe.py
kashifali-m398/advanced_python
988f407e986403b3238c9d1ea30b7d6fddf88c84
[ "MIT" ]
null
null
null
class Failsafe: ''' Catches I/O errors. ''' def __init__(self, func): self.function = func def __call__(self, *args): try: self.function(*args) except IOError: print('An I/O error was caught when opening file "{}"'.format(args[0])) @Failsafe def risky_fileopen(filename): open(filename) print('SUCCESS:', filename) risky_fileopen('failsafe.py') risky_fileopen('doesnotexist')
18.037037
84
0.570842
4a104b96b91a47c07a2242d935e7222e65b9efb1
352
py
Python
aliyun/api/rest/Ram20140214ListUserPoliciesRequest.py
francisar/rds_manager
458298669bf7d1990a85648b466b88f905256690
[ "MIT" ]
14
2015-11-30T02:35:18.000Z
2019-05-14T11:49:24.000Z
aliyun/api/rest/Ram20140214ListUserPoliciesRequest.py
francisar/rds_manager
458298669bf7d1990a85648b466b88f905256690
[ "MIT" ]
2
2015-11-30T02:51:40.000Z
2017-03-16T01:51:45.000Z
aliyun/api/rest/Ram20140214ListUserPoliciesRequest.py
francisar/rds_manager
458298669bf7d1990a85648b466b88f905256690
[ "MIT" ]
12
2016-01-04T06:48:17.000Z
2020-11-07T14:08:25.000Z
''' Created by auto_sdk on 2015.06.23 ''' from aliyun.api.base import RestApi class Ram20140214ListUserPoliciesRequest(RestApi): def __init__(self,domain='ram.aliyuncs.com',port=80): RestApi.__init__(self,domain, port) self.AccountSpace = None self.UserName = None def getapiname(self): return 'ram.aliyuncs.com.ListUserPolicies.2014-02-14'
27.076923
55
0.767045
4a104bfa1b905dbec9f041916018d49157800e15
327
py
Python
tql/ml/optimizer/__init__.py
Jie-Yuan/1_DataMining
f5338388b4f883233f350d4fb9c5903180883430
[ "Apache-2.0" ]
14
2019-06-25T13:46:32.000Z
2020-10-27T02:04:59.000Z
tql/ml/optimizer/__init__.py
Jie-Yuan/2_DataMining
f5338388b4f883233f350d4fb9c5903180883430
[ "Apache-2.0" ]
null
null
null
tql/ml/optimizer/__init__.py
Jie-Yuan/2_DataMining
f5338388b4f883233f350d4fb9c5903180883430
[ "Apache-2.0" ]
7
2019-06-25T13:26:16.000Z
2020-10-27T02:05:03.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Project : tql-Python. # @File : __init__.py # @Time : 2020/9/8 2:55 下午 # @Author : yuanjie # @Email : yuanjie@xiaomi.com # @Software : PyCharm # @Description : from .F1Optimizer import F1Optimizer from .BaseOptimizer import BaseOptimizer
25.153846
40
0.605505
4a104d0a8bcaea1ca12561a24cde974d81f59308
43,065
py
Python
salt/utils/vmware.py
cournape/salt
39bcb8671a9dd04409923c0d34d15652b9fc3c06
[ "Apache-2.0" ]
null
null
null
salt/utils/vmware.py
cournape/salt
39bcb8671a9dd04409923c0d34d15652b9fc3c06
[ "Apache-2.0" ]
null
null
null
salt/utils/vmware.py
cournape/salt
39bcb8671a9dd04409923c0d34d15652b9fc3c06
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- ''' Connection library for VMware .. versionadded:: 2015.8.2 This is a base library used by a number of VMware services such as VMware ESX, ESXi, and vCenter servers. :codeauthor: Nitin Madhok <nmadhok@clemson.edu> :codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstaley.com> Dependencies ~~~~~~~~~~~~ - pyVmomi Python Module - ESXCLI: This dependency is only needed to use the ``esxcli`` function. No other functions in this module rely on ESXCLI. pyVmomi ------- PyVmomi can be installed via pip: .. code-block:: bash pip install pyVmomi .. note:: Version 6.0 of pyVmomi has some problems with SSL error handling on certain versions of Python. If using version 6.0 of pyVmomi, Python 2.6, Python 2.7.9, or newer must be present. This is due to an upstream dependency in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the version of Python is not in the supported range, you will need to install an earlier version of pyVmomi. See `Issue #29537`_ for more information. .. _Issue #29537: https://github.com/saltstack/salt/issues/29537 Based on the note above, to install an earlier version of pyVmomi than the version currently listed in PyPi, run the following: .. code-block:: bash pip install pyVmomi==5.5.0.2014.1.1 The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file was developed against. ESXCLI ------ This dependency is only needed to use the ``esxcli`` function. At the time of this writing, no other functions in this module rely on ESXCLI. The ESXCLI package is also referred to as the VMware vSphere CLI, or vCLI. VMware provides vCLI package installation instructions for `vSphere 5.5`_ and `vSphere 6.0`_. .. _vSphere 5.5: http://pubs.vmware.com/vsphere-55/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html .. _vSphere 6.0: http://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html Once all of the required dependencies are in place and the vCLI package is installed, you can check to see if you can connect to your ESXi host or vCenter server by running the following command: .. code-block:: bash esxcli -s <host-location> -u <username> -p <password> system syslog config get If the connection was successful, ESXCLI was successfully installed on your system. You should see output related to the ESXi host's syslog configuration. ''' # Import Python Libs from __future__ import absolute_import import atexit import logging import time from salt.ext.six.moves.http_client import BadStatusLine # pylint: disable=E0611 # Import Salt Libs import salt.exceptions import salt.modules.cmdmod import salt.utils # Import Third Party Libs try: from pyVim.connect import GetSi, SmartConnect, Disconnect, GetStub from pyVmomi import vim, vmodl HAS_PYVMOMI = True except ImportError: HAS_PYVMOMI = False try: import gssapi import base64 HAS_GSSAPI = True except ImportError: HAS_GSSAPI = False # Get Logging Started log = logging.getLogger(__name__) def __virtual__(): ''' Only load if PyVmomi is installed. ''' if HAS_PYVMOMI: return True else: return False, 'Missing dependency: The salt.utils.vmware module requires pyVmomi.' def esxcli(host, user, pwd, cmd, protocol=None, port=None, esxi_host=None): ''' Shell out and call the specified esxcli commmand, parse the result and return something sane. :param host: ESXi or vCenter host to connect to :param user: User to connect as, usually root :param pwd: Password to connect with :param port: TCP port :param cmd: esxcli command and arguments :param esxi_host: If `host` is a vCenter host, then esxi_host is the ESXi machine on which to execute this command :return: Dictionary ''' esx_cmd = salt.utils.which('esxcli') if not esx_cmd: log.error('Missing dependency: The salt.utils.vmware.esxcli function requires ESXCLI.') return False # Set default port and protocol if none are provided. if port is None: port = 443 if protocol is None: protocol = 'https' if not esxi_host: # Then we are connecting directly to an ESXi server, # 'host' points at that server, and esxi_host is a reference to the # ESXi instance we are manipulating esx_cmd += ' -s {0} -u {1} -p \'{2}\' ' \ '--protocol={3} --portnumber={4} {5}'.format(host, user, pwd, protocol, port, cmd) else: esx_cmd += ' -s {0} -h {1} -u {2} -p \'{3}\' ' \ '--protocol={4} --portnumber={5} {6}'.format(host, esxi_host, user, pwd, protocol, port, cmd) ret = salt.modules.cmdmod.run_all(esx_cmd, output_loglevel='quiet') return ret def _get_service_instance(host, username, password, protocol, port, mechanism, principal, domain): ''' Internal method to authenticate with a vCenter server or ESX/ESXi host and return the service instance object. ''' log.trace('Retrieving new service instance') token = None if mechanism == 'userpass': if username is None: raise salt.exceptions.CommandExecutionError( 'Login mechanism userpass was specified but the mandatory ' 'parameter \'username\' is missing') if password is None: raise salt.exceptions.CommandExecutionError( 'Login mechanism userpass was specified but the mandatory ' 'parameter \'password\' is missing') elif mechanism == 'sspi': if principal is not None and domain is not None: try: token = get_gssapi_token(principal, host, domain) except Exception as exc: raise salt.exceptions.VMwareConnectionError(str(exc)) else: err_msg = 'Login mechanism \'{0}\' was specified but the' \ ' mandatory parameters are missing'.format(mechanism) raise salt.exceptions.CommandExecutionError(err_msg) else: raise salt.exceptions.CommandExecutionError( 'Unsupported mechanism: \'{0}\''.format(mechanism)) try: log.trace('Connecting using the \'{0}\' mechanism, with username ' '\'{1}\''.format(mechanism, username)) service_instance = SmartConnect( host=host, user=username, pwd=password, protocol=protocol, port=port, b64token=token, mechanism=mechanism) except TypeError as exc: if 'unexpected keyword argument' in exc.message: log.error('Initial connect to the VMware endpoint failed with {0}'.format(exc.message)) log.error('This may mean that a version of PyVmomi EARLIER than 6.0.0.2016.6 is installed.') log.error('We recommend updating to that version or later.') raise except Exception as exc: default_msg = 'Could not connect to host \'{0}\'. ' \ 'Please check the debug log for more information.'.format(host) try: if (isinstance(exc, vim.fault.HostConnectFault) and '[SSL: CERTIFICATE_VERIFY_FAILED]' in exc.msg) or \ '[SSL: CERTIFICATE_VERIFY_FAILED]' in str(exc): import ssl service_instance = SmartConnect( host=host, user=username, pwd=password, protocol=protocol, port=port, sslContext=ssl._create_unverified_context(), b64token=token, mechanism=mechanism) else: err_msg = exc.msg if hasattr(exc, 'msg') else default_msg log.trace(exc) raise salt.exceptions.VMwareConnectionError(err_msg) except Exception as exc: if 'certificate verify failed' in str(exc): import ssl context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE try: service_instance = SmartConnect( host=host, user=username, pwd=password, protocol=protocol, port=port, sslContext=context, b64token=token, mechanism=mechanism ) except Exception as exc: err_msg = exc.msg if hasattr(exc, 'msg') else str(exc) log.trace(err_msg) raise salt.exceptions.VMwareConnectionError( 'Could not connect to host \'{0}\': ' '{1}'.format(host, err_msg)) else: err_msg = exc.msg if hasattr(exc, 'msg') else default_msg log.trace(exc) raise salt.exceptions.VMwareConnectionError(err_msg) atexit.register(Disconnect, service_instance) return service_instance def get_datastore_ref(si, datastore_name): ''' Get a reference to a VMware datastore for the purposes of adding/removing disks si ServiceInstance for the vSphere or ESXi server (see get_service_instance) datastore_name Name of the datastore ''' inventory = get_inventory(si) container = inventory.viewManager.CreateContainerView(inventory.rootFolder, [vim.Datastore], True) for item in container.view: if item.name == datastore_name: return item return None def get_service_instance(host, username=None, password=None, protocol=None, port=None, mechanism='userpass', principal=None, domain=None): ''' Authenticate with a vCenter server or ESX/ESXi host and return the service instance object. host The location of the vCenter server or ESX/ESXi host. username The username used to login to the vCenter server or ESX/ESXi host. Required if mechanism is ``userpass`` password The password used to login to the vCenter server or ESX/ESXi host. Required if mechanism is ``userpass`` protocol Optionally set to alternate protocol if the vCenter server or ESX/ESXi host is not using the default protocol. Default protocol is ``https``. port Optionally set to alternate port if the vCenter server or ESX/ESXi host is not using the default port. Default port is ``443``. mechanism pyVmomi connection mechanism. Can either be ``userpass`` or ``sspi``. Default mechanism is ``userpass``. principal Kerberos service principal. Required if mechanism is ``sspi`` domain Kerberos user domain. Required if mechanism is ``sspi`` ''' if protocol is None: protocol = 'https' if port is None: port = 443 service_instance = GetSi() if service_instance: stub = GetStub() if salt.utils.is_proxy() or (hasattr(stub, 'host') and stub.host != ':'.join([host, str(port)])): # Proxies will fork and mess up the cached service instance. # If this is a proxy or we are connecting to a different host # invalidate the service instance to avoid a potential memory leak # and reconnect Disconnect(service_instance) service_instance = None else: return service_instance if not service_instance: service_instance = _get_service_instance(host, username, password, protocol, port, mechanism, principal, domain) # Test if data can actually be retrieved or connection has gone stale log.trace('Checking connection is still authenticated') try: service_instance.CurrentTime() except vim.fault.NotAuthenticated: log.trace('Session no longer authenticating. Reconnecting') Disconnect(service_instance) service_instance = _get_service_instance(host, username, password, protocol, port, mechanism, principal, domain) return service_instance def get_service_instance_from_managed_object(mo_ref, name='<unnamed>'): ''' Retrieves the service instance from a managed object. me_ref Reference to a managed object (of type vim.ManagedEntity). name Name of managed object. This field is optional. ''' if not name: name = mo_ref.name log.trace('[{0}] Retrieving service instance from managed object' ''.format(name)) si = vim.ServiceInstance('ServiceInstance') si._stub = mo_ref._stub return si def disconnect(service_instance): ''' Function that disconnects from the vCenter server or ESXi host service_instance The Service Instance from which to obtain managed object references. ''' log.trace('Disconnecting') try: Disconnect(service_instance) except vim.fault.VimFault as exc: raise salt.exceptions.VMwareApiError(exc.msg) except vmodl.RuntimeFault as exc: raise salt.exceptions.VMwareRuntimeError(exc.msg) def is_connection_to_a_vcenter(service_instance): ''' Function that returns True if the connection is made to a vCenter Server and False if the connection is made to an ESXi host service_instance The Service Instance from which to obtain managed object references. ''' api_type = service_instance.content.about.apiType log.trace('api_type = {0}'.format(api_type)) if api_type == 'VirtualCenter': return True elif api_type == 'HostAgent': return False else: raise salt.exceptions.VMwareApiError( 'Unexpected api type \'{0}\' . Supported types: ' '\'VirtualCenter/HostAgent\''.format(api_type)) def _get_dvs(service_instance, dvs_name): ''' Return a reference to a Distributed Virtual Switch object. :param service_instance: PyVmomi service instance :param dvs_name: Name of DVS to return :return: A PyVmomi DVS object ''' switches = list_dvs(service_instance) if dvs_name in switches: inventory = get_inventory(service_instance) container = inventory.viewManager.CreateContainerView(inventory.rootFolder, [vim.DistributedVirtualSwitch], True) for item in container.view: if item.name == dvs_name: return item return None def _get_pnics(host_reference): ''' Helper function that returns a list of PhysicalNics and their information. ''' return host_reference.config.network.pnic def _get_vnics(host_reference): ''' Helper function that returns a list of VirtualNics and their information. ''' return host_reference.config.network.vnic def _get_vnic_manager(host_reference): ''' Helper function that returns a list of Virtual NicManagers and their information. ''' return host_reference.configManager.virtualNicManager def _get_dvs_portgroup(dvs, portgroup_name): ''' Return a portgroup object corresponding to the portgroup name on the dvs :param dvs: DVS object :param portgroup_name: Name of portgroup to return :return: Portgroup object ''' for portgroup in dvs.portgroup: if portgroup.name == portgroup_name: return portgroup return None def _get_dvs_uplink_portgroup(dvs, portgroup_name): ''' Return a portgroup object corresponding to the portgroup name on the dvs :param dvs: DVS object :param portgroup_name: Name of portgroup to return :return: Portgroup object ''' for portgroup in dvs.portgroup: if portgroup.name == portgroup_name: return portgroup return None def get_gssapi_token(principal, host, domain): ''' Get the gssapi token for Kerberos connection principal The service principal host Host url where we would like to authenticate domain Kerberos user domain ''' if not HAS_GSSAPI: raise ImportError('The gssapi library is not imported.') service = '{0}/{1}@{2}'.format(principal, host, domain) log.debug('Retrieving gsspi token for service {0}'.format(service)) service_name = gssapi.Name(service, gssapi.C_NT_USER_NAME) ctx = gssapi.InitContext(service_name) in_token = None while not ctx.established: out_token = ctx.step(in_token) if out_token: encoded_token = base64.b64encode(out_token) return encoded_token if ctx.established: break if not in_token: raise salt.exceptions.CommandExecutionError( 'Can\'t receive token, no response from server') raise salt.exceptions.CommandExecutionError( 'Context established, but didn\'t receive token') def get_hardware_grains(service_instance): ''' Return hardware info for standard minion grains if the service_instance is a HostAgent type service_instance The service instance object to get hardware info for .. versionadded:: 2016.11.0 ''' hw_grain_data = {} if get_inventory(service_instance).about.apiType == 'HostAgent': view = service_instance.content.viewManager.CreateContainerView(service_instance.RetrieveContent().rootFolder, [vim.HostSystem], True) if view: if view.view: if len(view.view) > 0: hw_grain_data['manufacturer'] = view.view[0].hardware.systemInfo.vendor hw_grain_data['productname'] = view.view[0].hardware.systemInfo.model for _data in view.view[0].hardware.systemInfo.otherIdentifyingInfo: if _data.identifierType.key == 'ServiceTag': hw_grain_data['serialnumber'] = _data.identifierValue hw_grain_data['osfullname'] = view.view[0].summary.config.product.fullName hw_grain_data['osmanufacturer'] = view.view[0].summary.config.product.vendor hw_grain_data['osrelease'] = view.view[0].summary.config.product.version hw_grain_data['osbuild'] = view.view[0].summary.config.product.build hw_grain_data['os_family'] = view.view[0].summary.config.product.name hw_grain_data['os'] = view.view[0].summary.config.product.name hw_grain_data['mem_total'] = view.view[0].hardware.memorySize /1024/1024 hw_grain_data['biosversion'] = view.view[0].hardware.biosInfo.biosVersion hw_grain_data['biosreleasedate'] = view.view[0].hardware.biosInfo.releaseDate.date().strftime('%m/%d/%Y') hw_grain_data['cpu_model'] = view.view[0].hardware.cpuPkg[0].description hw_grain_data['kernel'] = view.view[0].summary.config.product.productLineId hw_grain_data['num_cpu_sockets'] = view.view[0].hardware.cpuInfo.numCpuPackages hw_grain_data['num_cpu_cores'] = view.view[0].hardware.cpuInfo.numCpuCores hw_grain_data['num_cpus'] = hw_grain_data['num_cpu_sockets'] * hw_grain_data['num_cpu_cores'] hw_grain_data['ip_interfaces'] = {} hw_grain_data['ip4_interfaces'] = {} hw_grain_data['ip6_interfaces'] = {} hw_grain_data['hwaddr_interfaces'] = {} for _vnic in view.view[0].configManager.networkSystem.networkConfig.vnic: hw_grain_data['ip_interfaces'][_vnic.device] = [] hw_grain_data['ip4_interfaces'][_vnic.device] = [] hw_grain_data['ip6_interfaces'][_vnic.device] = [] hw_grain_data['ip_interfaces'][_vnic.device].append(_vnic.spec.ip.ipAddress) hw_grain_data['ip4_interfaces'][_vnic.device].append(_vnic.spec.ip.ipAddress) if _vnic.spec.ip.ipV6Config: hw_grain_data['ip6_interfaces'][_vnic.device].append(_vnic.spec.ip.ipV6Config.ipV6Address) hw_grain_data['hwaddr_interfaces'][_vnic.device] = _vnic.spec.mac hw_grain_data['host'] = view.view[0].configManager.networkSystem.dnsConfig.hostName hw_grain_data['domain'] = view.view[0].configManager.networkSystem.dnsConfig.domainName hw_grain_data['fqdn'] = '{0}{1}{2}'.format( view.view[0].configManager.networkSystem.dnsConfig.hostName, ('.' if view.view[0].configManager.networkSystem.dnsConfig.domainName else ''), view.view[0].configManager.networkSystem.dnsConfig.domainName) for _pnic in view.view[0].configManager.networkSystem.networkInfo.pnic: hw_grain_data['hwaddr_interfaces'][_pnic.device] = _pnic.mac hw_grain_data['timezone'] = view.view[0].configManager.dateTimeSystem.dateTimeInfo.timeZone.name view = None return hw_grain_data def get_inventory(service_instance): ''' Return the inventory of a Service Instance Object. service_instance The Service Instance Object for which to obtain inventory. ''' return service_instance.RetrieveContent() def get_root_folder(service_instance): ''' Returns the root folder of a vCenter. service_instance The Service Instance Object for which to obtain the root folder. ''' try: log.trace('Retrieving root folder') return service_instance.RetrieveContent().rootFolder except vim.fault.VimFault as exc: raise salt.exceptions.VMwareApiError(exc.msg) except vmodl.RuntimeFault as exc: raise salt.exceptions.VMwareRuntimeError(exc.msg) def get_content(service_instance, obj_type, property_list=None, container_ref=None, traversal_spec=None, local_properties=False): ''' Returns the content of the specified type of object for a Service Instance. For more information, please see: http://pubs.vmware.com/vsphere-50/index.jsp?topic=%2Fcom.vmware.wssdk.pg.doc_50%2FPG_Ch5_PropertyCollector.7.6.html service_instance The Service Instance from which to obtain content. obj_type The type of content to obtain. property_list An optional list of object properties to used to return even more filtered content results. container_ref An optional reference to the managed object to search under. Can either be an object of type Folder, Datacenter, ComputeResource, Resource Pool or HostSystem. If not specified, default behaviour is to search under the inventory rootFolder. traversal_spec An optional TraversalSpec to be used instead of the standard ``Traverse All`` spec. local_properties Flag specifying whether the properties to be retrieved are local to the container. If that is the case, the traversal spec needs to be None. ''' # Start at the rootFolder if container starting point not specified if not container_ref: container_ref = service_instance.content.rootFolder # By default, the object reference used as the starting poing for the filter # is the container_ref passed in the function obj_ref = container_ref local_traversal_spec = False if not traversal_spec and not local_properties: local_traversal_spec = True # We don't have a specific traversal spec override so we are going to # get everything using a container view obj_ref = service_instance.content.viewManager.CreateContainerView( container_ref, [obj_type], True) # Create 'Traverse All' traversal spec to determine the path for # collection traversal_spec = vmodl.query.PropertyCollector.TraversalSpec( name='traverseEntities', path='view', skip=False, type=vim.view.ContainerView ) # Create property spec to determine properties to be retrieved property_spec = vmodl.query.PropertyCollector.PropertySpec( type=obj_type, all=True if not property_list else False, pathSet=property_list ) # Create object spec to navigate content obj_spec = vmodl.query.PropertyCollector.ObjectSpec( obj=obj_ref, skip=True if not local_properties else False, selectSet=[traversal_spec] if not local_properties else None ) # Create a filter spec and specify object, property spec in it filter_spec = vmodl.query.PropertyCollector.FilterSpec( objectSet=[obj_spec], propSet=[property_spec], reportMissingObjectsInResults=False ) # Retrieve the contents content = service_instance.content.propertyCollector.RetrieveContents([filter_spec]) # Destroy the object view if local_traversal_spec: obj_ref.Destroy() return content def get_mor_by_property(service_instance, object_type, property_value, property_name='name', container_ref=None): ''' Returns the first managed object reference having the specified property value. service_instance The Service Instance from which to obtain managed object references. object_type The type of content for which to obtain managed object references. property_value The name of the property for which to obtain the managed object reference. property_name An object property used to return the specified object reference results. Defaults to ``name``. container_ref An optional reference to the managed object to search under. Can either be an object of type Folder, Datacenter, ComputeResource, Resource Pool or HostSystem. If not specified, default behaviour is to search under the inventory rootFolder. ''' # Get list of all managed object references with specified property object_list = get_mors_with_properties(service_instance, object_type, property_list=[property_name], container_ref=container_ref) for obj in object_list: obj_id = str(obj.get('object', '')).strip('\'"') if obj[property_name] == property_value or property_value == obj_id: return obj['object'] return None def get_mors_with_properties(service_instance, object_type, property_list=None, container_ref=None, traversal_spec=None, local_properties=False): ''' Returns a list containing properties and managed object references for the managed object. service_instance The Service Instance from which to obtain managed object references. object_type The type of content for which to obtain managed object references. property_list An optional list of object properties used to return even more filtered managed object reference results. container_ref An optional reference to the managed object to search under. Can either be an object of type Folder, Datacenter, ComputeResource, Resource Pool or HostSystem. If not specified, default behaviour is to search under the inventory rootFolder. traversal_spec An optional TraversalSpec to be used instead of the standard ``Traverse All`` spec local_properties Flag specigying whether the properties to be retrieved are local to the container. If that is the case, the traversal spec needs to be None. ''' # Get all the content content_args = [service_instance, object_type] content_kwargs = {'property_list': property_list, 'container_ref': container_ref, 'traversal_spec': traversal_spec, 'local_properties': local_properties} try: content = get_content(*content_args, **content_kwargs) except BadStatusLine: content = get_content(*content_args, **content_kwargs) object_list = [] for obj in content: properties = {} for prop in obj.propSet: properties[prop.name] = prop.val properties['object'] = obj.obj object_list.append(properties) log.trace('Retrieved {0} objects'.format(len(object_list))) return object_list def get_properties_of_managed_object(mo_ref, properties): ''' Returns specific properties of a managed object, retrieved in an optimally. mo_ref The managed object reference. properties List of properties of the managed object to retrieve. ''' service_instance = get_service_instance_from_managed_object(mo_ref) log.trace('Retrieving name of {0}'''.format(type(mo_ref).__name__)) try: items = get_mors_with_properties(service_instance, type(mo_ref), container_ref=mo_ref, property_list=['name'], local_properties=True) mo_name = items[0]['name'] except vmodl.query.InvalidProperty: mo_name = '<unnamed>' log.trace('Retrieving properties \'{0}\' of {1} \'{2}\'' ''.format(properties, type(mo_ref).__name__, mo_name)) items = get_mors_with_properties(service_instance, type(mo_ref), container_ref=mo_ref, property_list=properties, local_properties=True) if not items: raise salt.exceptions.VMwareApiError( 'Properties of managed object \'{0}\' weren\'t ' 'retrieved'.format(mo_name)) return items[0] def get_managed_object_name(mo_ref): ''' Returns the name of a managed object. If the name wasn't found, it returns None. mo_ref The managed object reference. ''' props = get_properties_of_managed_object(mo_ref, ['name']) return props.get('name') def get_network_adapter_type(adapter_type): ''' Return the network adapter type. adpater_type The adapter type from which to obtain the network adapter type. ''' if adapter_type == "vmxnet": return vim.vm.device.VirtualVmxnet() elif adapter_type == "vmxnet2": return vim.vm.device.VirtualVmxnet2() elif adapter_type == "vmxnet3": return vim.vm.device.VirtualVmxnet3() elif adapter_type == "e1000": return vim.vm.device.VirtualE1000() elif adapter_type == "e1000e": return vim.vm.device.VirtualE1000e() def list_objects(service_instance, vim_object, properties=None): ''' Returns a simple list of objects from a given service instance. service_instance The Service Instance for which to obtain a list of objects. object_type The type of content for which to obtain information. properties An optional list of object properties used to return reference results. If not provided, defaults to ``name``. ''' if properties is None: properties = ['name'] items = [] item_list = get_mors_with_properties(service_instance, vim_object, properties) for item in item_list: items.append(item['name']) return items def list_datacenters(service_instance): ''' Returns a list of datacenters associated with a given service instance. service_instance The Service Instance Object from which to obtain datacenters. ''' return list_objects(service_instance, vim.Datacenter) def get_datacenter(service_instance, datacenter_name): ''' Returns a vim.Datacenter managed object. service_instance The Service Instance Object from which to obtain datacenter. datacenter_name The datacenter name ''' items = [i['object'] for i in get_mors_with_properties(service_instance, vim.Datacenter, property_list=['name']) if i['name'] == datacenter_name] if not items: raise salt.exceptions.VMwareObjectRetrievalError( 'Datacenter \'{0}\' was not found'.format(datacenter_name)) return items[0] def create_datacenter(service_instance, datacenter_name): ''' Creates a datacenter. .. versionadded:: Nitrogen service_instance The Service Instance Object datacenter_name The datacenter name ''' root_folder = get_root_folder(service_instance) log.trace('Creating datacenter \'{0}\''.format(datacenter_name)) try: dc_obj = root_folder.CreateDatacenter(datacenter_name) except vim.fault.VimFault as exc: raise salt.exceptions.VMwareApiError(exc.msg) except vmodl.RuntimeFault as exc: raise salt.exceptions.VMwareRuntimeError(exc.msg) return dc_obj def get_cluster(dc_ref, cluster): ''' Returns a cluster in a datacenter. dc_ref The datacenter reference cluster The cluster to be retrieved ''' dc_name = get_managed_object_name(dc_ref) log.trace('Retrieving cluster \'{0}\' from datacenter \'{1}\'' ''.format(cluster, dc_name)) si = get_service_instance_from_managed_object(dc_ref, name=dc_name) traversal_spec = vmodl.query.PropertyCollector.TraversalSpec( path='hostFolder', skip=True, type=vim.Datacenter, selectSet=[vmodl.query.PropertyCollector.TraversalSpec( path='childEntity', skip=False, type=vim.Folder)]) items = [i['object'] for i in get_mors_with_properties(si, vim.ClusterComputeResource, container_ref=dc_ref, property_list=['name'], traversal_spec=traversal_spec) if i['name'] == cluster] if not items: raise salt.exceptions.VMwareObjectRetrievalError( 'Cluster \'{0}\' was not found in datacenter ' '\'{1}\''. format(cluster, dc_name)) return items[0] def create_cluster(dc_ref, cluster_name, cluster_spec): ''' Creates a cluster in a datacenter. dc_ref The parent datacenter reference. cluster_name The cluster name. cluster_spec The cluster spec (vim.ClusterConfigSpecEx). Defaults to None. ''' dc_name = get_managed_object_name(dc_ref) log.trace('Creating cluster \'{0}\' in datacenter \'{1}\'' ''.format(cluster_name, dc_name)) try: dc_ref.hostFolder.CreateClusterEx(cluster_name, cluster_spec) except vim.fault.VimFault as exc: raise salt.exceptions.VMwareApiError(exc.msg) except vmodl.RuntimeFault as exc: raise salt.exceptions.VMwareRuntimeError(exc.msg) def update_cluster(cluster_ref, cluster_spec): ''' Updates a cluster in a datacenter. cluster_ref The cluster reference. cluster_spec The cluster spec (vim.ClusterConfigSpecEx). Defaults to None. ''' cluster_name = get_managed_object_name(cluster_ref) log.trace('Updating cluster \'{0}\''.format(cluster_name)) try: task = cluster_ref.ReconfigureComputeResource_Task(cluster_spec, modify=True) except vim.fault.VimFault as exc: raise salt.exceptions.VMwareApiError(exc.msg) except vmodl.RuntimeFault as exc: raise salt.exceptions.VMwareRuntimeError(exc.msg) wait_for_task(task, cluster_name, 'ClusterUpdateTask') def list_clusters(service_instance): ''' Returns a list of clusters associated with a given service instance. service_instance The Service Instance Object from which to obtain clusters. ''' return list_objects(service_instance, vim.ClusterComputeResource) def list_datastore_clusters(service_instance): ''' Returns a list of datastore clusters associated with a given service instance. service_instance The Service Instance Object from which to obtain datastore clusters. ''' return list_objects(service_instance, vim.StoragePod) def list_datastores(service_instance): ''' Returns a list of datastores associated with a given service instance. service_instance The Service Instance Object from which to obtain datastores. ''' return list_objects(service_instance, vim.Datastore) def list_hosts(service_instance): ''' Returns a list of hosts associated with a given service instance. service_instance The Service Instance Object from which to obtain hosts. ''' return list_objects(service_instance, vim.HostSystem) def list_resourcepools(service_instance): ''' Returns a list of resource pools associated with a given service instance. service_instance The Service Instance Object from which to obtain resource pools. ''' return list_objects(service_instance, vim.ResourcePool) def list_networks(service_instance): ''' Returns a list of networks associated with a given service instance. service_instance The Service Instance Object from which to obtain networks. ''' return list_objects(service_instance, vim.Network) def list_vms(service_instance): ''' Returns a list of VMs associated with a given service instance. service_instance The Service Instance Object from which to obtain VMs. ''' return list_objects(service_instance, vim.VirtualMachine) def list_folders(service_instance): ''' Returns a list of folders associated with a given service instance. service_instance The Service Instance Object from which to obtain folders. ''' return list_objects(service_instance, vim.Folder) def list_dvs(service_instance): ''' Returns a list of distributed virtual switches associated with a given service instance. service_instance The Service Instance Object from which to obtain distributed virtual switches. ''' return list_objects(service_instance, vim.DistributedVirtualSwitch) def list_vapps(service_instance): ''' Returns a list of vApps associated with a given service instance. service_instance The Service Instance Object from which to obtain vApps. ''' return list_objects(service_instance, vim.VirtualApp) def list_portgroups(service_instance): ''' Returns a list of distributed virtual portgroups associated with a given service instance. service_instance The Service Instance Object from which to obtain distributed virtual switches. ''' return list_objects(service_instance, vim.dvs.DistributedVirtualPortgroup) def wait_for_task(task, instance_name, task_type, sleep_seconds=1, log_level='debug'): ''' Waits for a task to be completed. task The task to wait for. instance_name The name of the ESXi host, vCenter Server, or Virtual Machine that the task is being run on. task_type The type of task being performed. Useful information for debugging purposes. sleep_seconds The number of seconds to wait before querying the task again. Defaults to ``1`` second. log_level The level at which to log task information. Default is ``debug``, but ``info`` is also supported. ''' time_counter = 0 start_time = time.time() log.trace('task = {0}, task_type = {1}'.format(task, task.__class__.__name__)) try: task_info = task.info except vim.fault.VimFault as exc: raise salt.exceptions.VMwareApiError(exc.msg) except vmodl.RuntimeFault as exc: raise salt.exceptions.VMwareRuntimeError(exc.msg) while task_info.state == 'running' or task_info.state == 'queued': if time_counter % sleep_seconds == 0: msg = '[ {0} ] Waiting for {1} task to finish [{2} s]'.format( instance_name, task_type, time_counter) if log_level == 'info': log.info(msg) else: log.debug(msg) time.sleep(1.0 - ((time.time() - start_time) % 1.0)) time_counter += 1 try: task_info = task.info except vim.fault.VimFault as exc: raise salt.exceptions.VMwareApiError(exc.msg) except vmodl.RuntimeFault as exc: raise salt.exceptions.VMwareRuntimeError(exc.msg) if task_info.state == 'success': msg = '[ {0} ] Successfully completed {1} task in {2} seconds'.format( instance_name, task_type, time_counter) if log_level == 'info': log.info(msg) else: log.debug(msg) # task is in a successful state return task_info.result else: # task is in an error state try: raise task_info.error except vim.fault.VimFault as exc: raise salt.exceptions.VMwareApiError(exc.msg) except vmodl.fault.SystemError as exc: raise salt.exceptions.VMwareSystemError(exc.msg)
36.007525
133
0.630698
4a104d2d8718e90031699e6e582547c7755b70ce
2,737
py
Python
tests/test_autobib.py
HDembinski/autobib
f4fa004a4496f912acbf251d3092271c45b2fcb3
[ "MIT" ]
5
2021-05-09T12:39:04.000Z
2021-08-25T11:35:39.000Z
tests/test_autobib.py
HDembinski/autobib
f4fa004a4496f912acbf251d3092271c45b2fcb3
[ "MIT" ]
2
2021-05-13T11:34:25.000Z
2021-05-13T11:35:45.000Z
tests/test_autobib.py
HDembinski/autobib
f4fa004a4496f912acbf251d3092271c45b2fcb3
[ "MIT" ]
null
null
null
import subprocess as subp import shutil from pathlib import Path from autobib.util import find_in_path, get_bib_keys import pytest cwd = Path(__file__).parent test_document_path = cwd / "data" @pytest.mark.skipif(not find_in_path("latex"), reason="requires latex") def test_autobib(tmpdir): for fn in ("main.tex", "bar.bib", "foo.bib"): shutil.copy(test_document_path / fn, tmpdir / fn) subp.run(["latex", "main.tex"], cwd=tmpdir) p = subp.run(["bibtex", "main"], cwd=tmpdir) assert p.returncode == 0 with open(tmpdir / "main.bib") as f: assert get_bib_keys(f.read()) == { "2020Univ....6..102M", "Vanthieghem:2021akb", "PierreAuger:2021qsd", } # "Dembinski:2018ihc" is not in main.bib, because it is in foo.bib # "Baur:2019cpv" is not in main.bib, because it is in bar.bib assert subp.run(["bibtex", "foobarbaz"], cwd=tmpdir).returncode != 0 @pytest.mark.skipif(not find_in_path("latex"), reason="requires latex") def test_autobib_updated_key(tmpdir): # test renamed key Abe:1993xy -> CDF:1993wpv tex = r"""\documentclass{article} \begin{document} \cite{Abe:1993xy} \bibliographystyle{plain} \bibliography{main} \end{document} """ with (tmpdir / "main.tex").open("w") as f: f.write(tex) subp.run(["latex", "main.tex"], cwd=tmpdir) assert (tmpdir / "main.aux").exists() p = subp.run(["bibtex", "main"], cwd=tmpdir, stdout=subp.PIPE) with open(tmpdir / "main.bib") as f: assert get_bib_keys(f.read()) == {"CDF:1993wpv"} with open(tmpdir / "main.tex.bak") as f: assert f.read() == tex with open(tmpdir / "main.tex") as f: assert f.read() == tex.replace("Abe:1993xy", "CDF:1993wpv") assert ( b"""autobib: Updating keys in LaTeX files autobib: Abe:1993xy -> CDF:1993wpv """ in p.stdout ) @pytest.mark.skipif(not find_in_path("latex"), reason="requires latex") def test_autobib_backup_failure(tmpdir): tex = r"""\documentclass{article} \begin{document} \cite{Abe:1993xy} \bibliographystyle{plain} \bibliography{main} \end{document} """ with (tmpdir / "main.tex").open("w") as f: f.write(tex) subp.run(["latex", "main.tex"], cwd=tmpdir) assert (tmpdir / "main.aux").exists() with (tmpdir / "main.aux").open() as f: aux = f.read() p = subp.run(["bibtex", "main"], cwd=tmpdir) assert p.returncode == 0 assert (tmpdir / "main.tex.bak").exists() for i in range(3): with open(tmpdir / "main.aux", "w") as f: f.write(aux) p = subp.run(["bibtex", "main"], cwd=tmpdir) assert (tmpdir / f"main.tex.bak.{i}").exists() assert p.returncode == 0
28.510417
74
0.618926
4a104dca866ad6fc4108087b2047f2320270a293
1,128
py
Python
app.py
DheerajKumar97/Drug-Review-Sentiment-Analysis-RNN-Bidirectional-lstm--Flask-Deployment
6eff5dd7ab7ff833f9bfad04a65af6c79b19a1f6
[ "MIT" ]
5
2020-10-27T07:25:16.000Z
2021-09-09T09:56:01.000Z
app.py
DheerajKumar97/Drug-Review-Sentiment-Analysis-RNN-Bidirectional-lstm--Flask-Deployment
6eff5dd7ab7ff833f9bfad04a65af6c79b19a1f6
[ "MIT" ]
null
null
null
app.py
DheerajKumar97/Drug-Review-Sentiment-Analysis-RNN-Bidirectional-lstm--Flask-Deployment
6eff5dd7ab7ff833f9bfad04a65af6c79b19a1f6
[ "MIT" ]
null
null
null
from flask import Flask,render_template,url_for,request import numpy as np import pickle import pandas as pd from keras.models import load_model from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from keras.models import model_from_json from numpy import array app=Flask(__name__) model = load_model("rnn_model.h5") with open('tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle) @app.route('/') def home(): return render_template('home.html') @app.route('/predict',methods=['POST']) def predict(): max_length = 200 if request.method == 'POST': review = request.form['review'] data = [review] tokenizer.fit_on_texts(data) enc = tokenizer.texts_to_sequences(data) enc=pad_sequences(enc, maxlen=max_length, padding='post') my_prediction = model.predict(array([enc][0]))[0][0] class1 = model.predict_classes(array([enc][0]))[0][0] return render_template('result.html',prediction = class1) if __name__ == '__main__': app.run(debug=True)
26.232558
65
0.702128
4a104e6460757188d16c755155c80f0400838954
2,389
py
Python
envs/d4rl/d4rl_content/gym_minigrid/fourroom_controller.py
AliengirlLiv/babyai
51421ee11538bf110c5b2d0c84a15f783d854e7d
[ "MIT" ]
2
2022-02-24T08:47:48.000Z
2022-03-23T09:44:22.000Z
envs/d4rl/d4rl_content/gym_minigrid/fourroom_controller.py
AliengirlLiv/babyai
51421ee11538bf110c5b2d0c84a15f783d854e7d
[ "MIT" ]
null
null
null
envs/d4rl/d4rl_content/gym_minigrid/fourroom_controller.py
AliengirlLiv/babyai
51421ee11538bf110c5b2d0c84a15f783d854e7d
[ "MIT" ]
1
2021-12-27T19:03:38.000Z
2021-12-27T19:03:38.000Z
import numpy as np import random from envs.d4rl.d4rl_content.pointmaze import q_iteration from envs.d4rl.d4rl_content.pointmaze.gridcraft import grid_env from envs.d4rl.d4rl_content.pointmaze.gridcraft import grid_spec MAZE = \ "###################\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOOOOOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "####O#########O####\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "#OOOOOOOOOOOOOOOOO#\\"+\ "#OOOOOOOO#OOOOOOOO#\\"+\ "###################\\" # NLUDR -> RDLU TRANSLATE_DIRECTION = { 0: None, 1: 3,#3, 2: 1,#1, 3: 2,#2, 4: 0,#0, } RIGHT = 1 LEFT = 0 FORWARD = 2 class FourRoomController(object): def __init__(self): self.env = grid_env.GridEnv(grid_spec.spec_from_string(MAZE)) self.reset_locations = list(zip(*np.where(self.env.gs.spec == grid_spec.EMPTY))) def sample_target(self): return random.choice(self.reset_locations) def set_target(self, target): self.target = target self.env.gs[target] = grid_spec.REWARD self.q_values = q_iteration.q_iteration(env=self.env, num_itrs=32, discount=0.99) self.env.gs[target] = grid_spec.EMPTY def get_action(self, pos, orientation): if tuple(pos) == tuple(self.target): done = True else: done = False env_pos_idx = self.env.gs.xy_to_idx(pos) qvalues = self.q_values[env_pos_idx] direction = TRANSLATE_DIRECTION[np.argmax(qvalues)] #tgt_pos, _ = self.env.step_stateless(env_pos_idx, np.argmax(qvalues)) #tgt_pos = self.env.gs.idx_to_xy(tgt_pos) #print('\tcmd_dir:', direction, np.argmax(qvalues), qvalues, tgt_pos) #infos = {} #infos['tgt_pos'] = tgt_pos if orientation == direction or direction == None: return FORWARD, done else: return get_turn(orientation, direction), done #RDLU TURN_DIRS = [ [None, RIGHT, RIGHT, LEFT], #R [LEFT, None, RIGHT, RIGHT], #D [RIGHT, LEFT, None, RIGHT], #L [RIGHT, RIGHT, LEFT, None], #U ] def get_turn(ori, tgt_ori): return TURN_DIRS[ori][tgt_ori]
28.105882
89
0.614483
4a10503783da86c5b736f1472232b4a05ef7490a
7,753
py
Python
InApp.py
LHoBiz/ols_engine
9bdbd827f7be17aee95d416255a7f483472c4315
[ "MIT" ]
1
2022-01-05T07:38:06.000Z
2022-01-05T07:38:06.000Z
InApp.py
LHoBiz/ols_engine
9bdbd827f7be17aee95d416255a7f483472c4315
[ "MIT" ]
null
null
null
InApp.py
LHoBiz/ols_engine
9bdbd827f7be17aee95d416255a7f483472c4315
[ "MIT" ]
null
null
null
# -*- coding: cp1252 -*- import sys import os import math import OLSDims import EnvSettings from osgeo import osr import mdl ip = mdl.Data() f=ip.f AppOLS = OLSDims.AppDim.AppOLS AppOLSNAME=OLSDims.AppDim.AppOLSNAME AppOLSDIMS=OLSDims.AppDim.AppOLSDIMS NRunwayInfo=ip.NRunwayInfo SRunwayInfo=ip.SRunwayInfo NIns = ip.NIns if NIns == 'Y': NPrc=ip.NPrc if NPrc != 'N': NBLDist=ip.NBLDist CN = ip.CN DayOnly = ip.CN CL=ip.CL RED=ip.RED MTOW5700kg = ip.MTOW5700kg RPT = ip.RPT SIns = ip.SIns if SIns == 'Y': SPrc=ip.SPrc if SPrc != 'N': SBLDist=ip.SBLDist RPT = ip.RPT RWY_WID=ip.RWY_WID RSW=ip.RSW CodeNo = range(len(AppOLS)) Surfaces = range(len(AppOLS[0])) NE=ip.NE SE=ip.SE NTE=ip.NTE NTN=ip.NTN STE=ip.STE STN=ip.STN ARP=ip.ARP SE=ip.SE NE=ip.NE zone=ip.zone KML_NAME=ip.KML_NAME completeName=ip.completeName RwyLen = math.sqrt((NTE-STE)*(NTE-STE) + (NTN-STN)*(NTN-STN)) def NInApp(ApOls,accur): E1 = NE E2 = SE ns = 'n' Surf = 'NorthInnerAppoach' InnerApp(E1,E2,ns,Surf,accur,ApOls) def SInApp(ApOls,accur): E1 = SE E2 = NE ns = 's' Surf = 'SouthInnerApproach' InnerApp(E1,E2,ns,Surf,accur,ApOls) def InnerApp(E1,E2,ns,Surf,accur,ApOls): if accur >= 200: x = accur/100 elif accur>=100 and accur< 200: x = accur / 20 elif accur >=50 and accur< 100: x = accur / 15 elif accur >0 and accur< 50: x = accur / 10 ## accur = x s = [] Square = [] count = 0 ct = 0 I = range(int(1+math.ceil((ApOls[4][0])/accur))) J = range(int(1+math.ceil((ApOls[4][2])/accur))) for i in I: U = [] T = [] L=[] for j in J: par = ApOls[4][1] + ApOls[4][2] - accur*j perp = ApOls[4][0]/2 - i*accur Z= (E1-RED)+(par - ApOls[3][1])*ApOls[4][3] if par > ApOls[3][1]: if perp <= 0: perp = 0 if par <= ApOls[3][1]: par = ApOls[3][1] if perp <= 0: perp = 0 Z= (E1-RED) L.append([par,perp,Z]) if perp == 0: T.append(i) if par == ApOls[3][1]: U.append(j) s.append(L) if len(U) > 0: J = range(U[0]+1) if len(T) > 0: I = range(T[0]+1) F = [1,-1] for n in range(2): f.write( '<Folder>\n') f.write( '<ScreenOverlay>\n') f.write( '<name>Runway: Code '+str(int(CN))+CL+NRunwayInfo+'</name>\n') f.write( '<visibility>0</visibility>\n') f.write('<overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/>\n') f.write('<screenXY x="25" y="95" xunits="pixels" yunits="pixels"/>\n') f.write('<rotationXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>\n') f.write('<size x="0" y="0" xunits="pixels" yunits="pixels"/>\n') f.write('<styleUrl>#KMLStyler</styleUrl>\n') f.write('<ExtendedData>\n') f.write('<SchemaData schemaUrl="#NewFeatureType">\n') f.write('<SimpleData name="Surface">Dimensions</SimpleData>\n') f.write('<SimpleData name="'+AppOLSNAME[2]+'">-</SimpleData>\n') for b in range(len(AppOLSDIMS[2])): f.write('<SimpleData name="'+AppOLSDIMS[2][b]+'">'+str(ApOls[2][b])+'</SimpleData>\n') f.write('</SchemaData>\n') f.write('</ExtendedData>\n') f.write('</ScreenOverlay>\n') OlsSurf = Surf+str(n+1) f.write( '<name>'+OlsSurf+'</name>\n') hero = [] if n == 0 or n == 1: I = range(len(s)) if n == 2 or n == 3: I = range(len(t)) for i in I: if n == 0 or n == 1: bip = range(len(s[i])) if n == 2 or n == 3: bip = range(len(t[i])) for j in bip: if i < max(I): if n == 0 or n == 1: bap = (len(s[i+1])-1) if n == 2 or n == 3: bap = (len(t[i+1])-1) if j < bap: xxx=[] if n == 0: #adjacent to runway right xx =[ [s[i][j][0]*F[1], s[i][j][1]*F[0], s[i][j][2]], [s[i][j+1][0]*F[1], s[i][j+1][1]*F[0], s[i][j+1][2]], [s[i+1][j+1][0]*F[1],s[i+1][j+1][1]*F[0], s[i+1][j+1][2]], [s[i+1][j][0]*F[1], s[i+1][j][1]*F[0], s[i+1][j][2]], [s[i][j][0]*F[1], s[i][j][1]*F[0], s[i][j][2]] ] if n == 1: #adjacent to runway left xx =[ [s[i][j][0]*F[1], s[i][j][1]*F[1], s[i][j][2]], [s[i][j+1][0]*F[1], s[i][j+1][1]*F[1], s[i][j+1][2]], [s[i+1][j+1][0]*F[1],s[i+1][j+1][1]*F[1], s[i+1][j+1][2]], [s[i+1][j][0]*F[1], s[i+1][j][1]*F[1], s[i+1][j][2]], [s[i][j][0]*F[1], s[i][j][1]*F[1], s[i][j][2]] ] f.write( "<Placemark>\n") f.write( "<name>n="+str(n)+" i="+str(i)+" j="+str(j)+"</name>\n") f.write( "<styleUrl>#m_ylw-pushpin</styleUrl>\n") ##extended data H = [] for h in range(len(xx)): e = RED+xx[h][2] Utm = mdl.toUTM(NTE,NTN,STE,STN,ARP,SE,NE,xx[h][0],xx[h][1],e,ns) Wgs = list(mdl.U_W(Utm[0],Utm[1],zone, e)) H.append(Wgs[2]) Hn = min(H) Hm = max(H) f.write( "<ExtendedData>") f.write( '<SchemaData schemaUrl="#S_t1_ISDDDDDDDDSSS">') f.write( '<SimpleData name="Surface">'+OlsSurf+'</SimpleData>') f.write( '<SimpleData name="Z-min">'+str(Hn)+'</SimpleData>') f.write( '<SimpleData name="Z-max">'+str(Hm)+'</SimpleData>') f.write( '</SchemaData>') f.write( "</ExtendedData>") ##extended data f.write( "<Polygon>\n") f.write( "<altitudeMode>absolute</altitudeMode>\n") f.write( "<outerBoundaryIs>\n") f.write( "<LinearRing>\n") f.write( "<coordinates>\n") for h in range(len(xx)): e = RED+xx[h][2] Utm = mdl.toUTM(NTE,NTN,STE,STN,ARP,SE,NE,xx[h][0],xx[h][1],e,ns) Wgs = list(mdl.U_W(Utm[0],Utm[1],zone, e)) f.write(str(Wgs[0])+","+str(Wgs[1])+","+str(Wgs[2])) f.write( "\n") f.write( "</coordinates>\n") f.write( "</LinearRing>\n") f.write( "</outerBoundaryIs>\n" ) f.write( "</Polygon>\n" ) f.write( "</Placemark>\n") f.write( '</Folder>\n') f.write( '\n') f.write( '\n') f.write( '\n') f.write( '\n') f.write( '\n') f.write( '\n') f.write( '\n')
34.30531
98
0.402554
4a10521b6b4c4eb6dfff3e7e4d661dc62a5ce115
7,835
py
Python
bot.py
ARBNonay32/DnD_CascenE
b09d4633aa1401d722517fc94dc1ed40560908eb
[ "MIT" ]
null
null
null
bot.py
ARBNonay32/DnD_CascenE
b09d4633aa1401d722517fc94dc1ed40560908eb
[ "MIT" ]
null
null
null
bot.py
ARBNonay32/DnD_CascenE
b09d4633aa1401d722517fc94dc1ed40560908eb
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import nest_asyncio nest_asyncio.apply() import os, ssl if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)): ssl._create_default_https_context = ssl._create_unverified_context #import discord from discord.ext import commands import cv2 from dotenv import load_dotenv import discord load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') bot = commands.Bot(command_prefix='&') players = [] gmap = "" oldgmap = "" gwidth = 0 gheight = 0 @bot.command() async def ping(ctx): await ctx.channel.send("pong") @bot.command() async def game_map(ctx, width: int, height: int): global gwidth global gheight global gmap gwidth = width*2 + 1 gheight = height*2 + 1 gmap = ""; if width > 70: temp = height height = width width = temp if ((width + 1) * height) > 1980: await ctx.channel.send("Given dimensions are too large, map area must be smaller than 1980 units") else: width = width*2 for i in range(height): for j in range(width): if j == 0 or j == width - 1: gmap += "|" elif i == 0: gmap += "‾" elif i == height - 1: gmap += "_" else: gmap += " " gmap += "\n" await ctx.channel.send("```" + gmap + "```") @bot.command() async def build(ctx, tlx: int, tly: int, brx: int, bry: int): global gwidth global gheight global gmap global oldgmap chArray = list(gmap) if tlx>brx: temp = tlx tlx = brx brx = temp if tly>bry: temp = tly tly = bry bry = temp oldgmap = gmap for k in range(abs(tly - bry)): for l in range(abs(tlx - brx)*2): if l == 0 or l == abs(tlx - brx)*2 - 1: chArray[((tly + k)*gwidth + l + tlx*2)] = "‖" elif k == abs(tly - bry) - 1: chArray[((tly + k)*gwidth + l + tlx*2)] = "‗" elif k == 0: chArray[((tly + k)*gwidth + l + tlx*2)] = "˭" #await ctx.channel.send(str((tly + k)*gwidth) + " " + str(l) + " " + str(tlx)) gmap = "".join(chArray) await ctx.channel.send("```" + gmap + "```") @bot.command() async def build_spec(ctx, tlx: int, tly: int, brx: int, bry: int, char: str): global gwidth global gheight global gmap global oldgmap chArray = list(gmap) if tlx>brx: temp = tlx tlx = brx brx = temp if tly>bry: temp = tly tly = bry bry = temp oldgmap = gmap for k in range(abs(tly - bry)): for l in range(abs(tlx - brx)*2): if l == 0 or l == abs(tlx - brx)*2 - 1: chArray[((tly + k)*gwidth + l + tlx*2 + 1)] = char elif k == abs(tly - bry) - 1: chArray[((tly + k)*gwidth + l + tlx*2 + 1)] = char elif k == 0: chArray[((tly + k)*gwidth + l + tlx*2 + 1)] = char #await ctx.channel.send(str((tly + k)*gwidth) + " " + str(l) + " " + str(tlx)) gmap = "".join(chArray) await ctx.channel.send("```" + gmap + "```") @bot.command() async def save_as(ctx, filename: str): try: global gmap global gwidth global gheight f = open("_".join(["userFile",filename]), "w", encoding="utf-8") f.write("\t".join([str(gwidth), str(gheight), gmap])) f.close() await ctx.channel.send("```File Written```") except Exception as e: await ctx.channel.send(f"```Error when writing file '{filename}' with the following error:\n {str(e)}"[0:1996]+"```") @bot.command() async def load_map(ctx, filename: str): try: global gmap global gwidth global gheight f = open("_".join(["userFile",filename]), "r", encoding="utf-8") temp = f.read() tgwidth, tgheight, gmap = temp.split("\t") gwidth = int(tgwidth) gheight = int(tgheight) await ctx.channel.send("```" + gmap + "```") except Exception as e: await ctx.channel.send(f"```Error when reading file '{filename}':\n {str(e)}"[0:1996]+"```") @bot.command() async def listplayers(ctx): for player in players: await ctx.channel.send(player[0]) @bot.command() async def print(ctx, arg): await ctx.channel.send(arg) @bot.command() async def add_player(ctx, name, xpos: int, ypos: int): global players global gmap global gwidth global gheight global oldgmap oldgmap = gmap xpos = xpos*2 valid = True if xpos < 0 or xpos > gwidth - 1 or ypos < 0 or ypos > gheight - 1: await ctx.channel.send("Your character would be out of bounds at these coordinates") valid = False listMap = list(gmap) if listMap[ypos * gwidth + xpos] != " ": await ctx.channel.send("Your character would be inside a wall or something at these coordinates") valid = False if len(name) > 1: listMap[ypos * gwidth + xpos] = name[0] else: listMap[ypos * gwidth + xpos] = name if valid: players.append((name, xpos, ypos)) gmap = "".join(listMap) await ctx.channel.send("```" + gmap + "```") @bot.command() async def move(ctx, name, newx: int, newy: int): newx = newx*2 global gmap global oldgmap listMap = list(gmap) old = None oldgmap = gmap valid = True if newx < 0 or newx > gwidth - 1 or newy < 0 or newy > gheight - 1: await ctx.channel.send("Your character would be out of bounds at these coordinates") valid = False if listMap[newy * gwidth + newx] != " ": await ctx.channel.send("Your character would be inside a wall or something at these coordinates") valid = False for player in players: if player[0] == name: old = player players.remove(old) if old == None: await ctx.channel.send("This player does not exist. Check your spelling or use &listplayers.") return listMap[old[2] * gwidth + old[1]] = " " if len(name) > 1: listMap[newy * gwidth + newx] = name[0] else: listMap[newy * gwidth + newx] = name if valid: players.append((name, newx, newy)) gmap = "".join(listMap) await ctx.channel.send("```" + gmap + "```") @bot.command() async def line(ctx, x0: int, y0: int, x1: int, y1: int, char: str): global gwidth global gheight global gmap global oldgmap #start oldgmap = gmap points = []; dx = x1 - x0 dy = y1 - y0 N = max(abs(dx), abs(dy)*2); #may move *2 to l in points loop for step in range(N+1): t = 0 if (N == 0): t = 0.0 else: t = step / N vx = round(x0 + t * dx) vy = round(y0 + t * dy) pxy = (vx, vy) points.append(pxy) chArray = list(gmap) for pr in points: chArray[(pr[1]*gwidth + pr[0]*2 + 1)] = char gmap = "".join(chArray) await ctx.channel.send("```" + gmap + "```") @bot.command() async def picture(ctx, pip_w: int, pip_h: int): background = cv2.imread('picture1.png') overlay = cv2.imread('lucas.png') wb, hb, ht = background.shape w, h, t = overlay.shape resized_image = cv2.resize(overlay, (h//10, w//10)) h1, w1 = resized_image.shape[:2] background[pip_h:pip_h+h1,pip_w:pip_w+w1] = resized_image # make it PIP cv2.imwrite('combined.png', background) await ctx.channel.send(file=discord.File('combined.png')) @bot.command() async def repeat(ctx, arg): await ctx.channel.send(arg) @bot.command() async def undo(ctx): global gmap global oldgmap gmap = oldgmap await ctx.channel.send("```" + gmap + "```") bot.run(TOKEN)
24.561129
119
0.555329
4a1052aac6c7ee3c8b6e37dda72f4cca84cc717a
13,397
py
Python
python/example_code/s3/file_transfer/demo_file_transfer.py
AllanFly120/aws-doc-sdk-examples
380d46c4af7192d8bc73b2ea941f92f60500cf2d
[ "Apache-2.0" ]
1
2020-03-09T17:23:38.000Z
2020-03-09T17:23:38.000Z
python/example_code/s3/file_transfer/demo_file_transfer.py
AllanFly120/aws-doc-sdk-examples
380d46c4af7192d8bc73b2ea941f92f60500cf2d
[ "Apache-2.0" ]
null
null
null
python/example_code/s3/file_transfer/demo_file_transfer.py
AllanFly120/aws-doc-sdk-examples
380d46c4af7192d8bc73b2ea941f92f60500cf2d
[ "Apache-2.0" ]
1
2020-01-27T20:42:30.000Z
2020-01-27T20:42:30.000Z
# # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # This file is licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. # # """ Demonstration manager for the Amazon S3 file transfer example. The demonstration collects information from the user and runs various upload and download scenarios to show how to use Boto 3 managed transfers. TransferDemoManager Handle user interactions like collecting user input and reporting transfer results. """ import hashlib import os import platform import shutil import time import boto3 from boto3.s3.transfer import TransferConfig from botocore.exceptions import ClientError from botocore.exceptions import ParamValidationError from botocore.exceptions import NoCredentialsError import file_transfer MB = 1024 * 1024 # These configuration attributes affect both uploads and downloads. CONFIG_ATTRS = ('multipart_threshold', 'multipart_chunksize', 'max_concurrency', 'use_threads') # These configuration attributes affect only downloads. DOWNLOAD_CONFIG_ATTRS = ('max_io_queue', 'io_chunksize', 'num_download_attempts') class TransferDemoManager: """ Manages the demonstration. Collects user input from a command line, reports transfer results, maintains a list of artifacts created during the demonstration, and cleans them up after the demonstration is completed. """ def __init__(self): self._s3 = boto3.resource('s3') self._chore_list = [] self._create_file_cmd = None self._size_multiplier = 0 self.file_size_mb = 30 self.demo_folder = None self.demo_bucket = None self._setup_platform_specific() self._terminal_width = shutil.get_terminal_size(fallback=(80, 80))[0] def collect_user_info(self): """ Collect local folder and Amazon S3 bucket name from the user. These locations are used to store files during the demonstration. """ while not self.demo_folder: self.demo_folder = input( "Which file folder do you want to use to store " "demonstration files? ") if not os.path.isdir(self.demo_folder): print(f"{self.demo_folder} isn't a folder!") self.demo_folder = None while not self.demo_bucket: self.demo_bucket = input( "Which Amazon S3 bucket do you want to use to store " "demonstration files? ") try: self._s3.meta.client.head_bucket(Bucket=self.demo_bucket) except ParamValidationError as err: print(err) self.demo_bucket = None except ClientError as err: print(err) print( f"Either {self.demo_bucket} doesn't exist or you don't " f"have access to it.") self.demo_bucket = None def demo(self, question, upload_func, download_func, upload_args=None, download_args=None): """Run a demonstration. Ask the user if they want to run this specific demonstration. If they say yes, create a file on the local path, upload it using the specified upload function, then download it using the specified download function. """ if download_args is None: download_args = {} if upload_args is None: upload_args = {} question = question.format(self.file_size_mb) answer = input(f"{question} (y/n)") if answer.lower() == 'y': local_file_path, object_key, download_file_path = \ self._create_demo_file() file_transfer.TransferConfig = \ self._config_wrapper(TransferConfig, CONFIG_ATTRS) self._report_transfer_params('Uploading', local_file_path, object_key, **upload_args) start_time = time.perf_counter() thread_info = upload_func(local_file_path, self.demo_bucket, object_key, self.file_size_mb, **upload_args) end_time = time.perf_counter() self._report_transfer_result(thread_info, end_time - start_time) file_transfer.TransferConfig = \ self._config_wrapper(TransferConfig, CONFIG_ATTRS + DOWNLOAD_CONFIG_ATTRS) self._report_transfer_params('Downloading', object_key, download_file_path, **download_args) start_time = time.perf_counter() thread_info = download_func(self.demo_bucket, object_key, download_file_path, self.file_size_mb, **download_args) end_time = time.perf_counter() self._report_transfer_result(thread_info, end_time - start_time) def last_name_set(self): """Get the name set used for the last demo.""" return self._chore_list[-1] def cleanup(self): """ Remove files from the demo folder, and uploaded objects from the Amazon S3 bucket. """ print('-' * self._terminal_width) for local_file_path, s3_object_key, downloaded_file_path \ in self._chore_list: print(f"Removing {local_file_path}") try: os.remove(local_file_path) except FileNotFoundError as err: print(err) print(f"Removing {downloaded_file_path}") try: os.remove(downloaded_file_path) except FileNotFoundError as err: print(err) if self.demo_bucket: print(f"Removing {self.demo_bucket}:{s3_object_key}") try: self._s3.Bucket(self.demo_bucket).Object( s3_object_key).delete() except ClientError as err: print(err) def _setup_platform_specific(self): """Set up platform-specific command used to create a large file.""" if platform.system() == "Windows": self._create_file_cmd = "fsutil file createnew {} {}" self._size_multiplier = MB elif platform.system() == "Linux" or platform.system() == "Darwin": self._create_file_cmd = f"dd if=/dev/urandom of={{}} " \ f"bs={MB} count={{}}" self._size_multiplier = 1 else: raise EnvironmentError( f"Demo of platform {platform.system()} isn't supported.") def _create_demo_file(self): """ Create a file in the demo folder specified by the user. Store the local path, object name, and download path for later cleanup. Only the local file is created by this method. The Amazon S3 object and download file are created later during the demonstration. Returns: A tuple that contains the local file path, object name, and download file path. """ file_name_template = "TestFile{}-{}.demo" local_suffix = "local" object_suffix = "s3object" download_suffix = "downloaded" file_tag = len(self._chore_list) + 1 local_file_path = os.path.join( self.demo_folder, file_name_template.format(file_tag, local_suffix)) s3_object_key = file_name_template.format(file_tag, object_suffix) downloaded_file_path = os.path.join( self.demo_folder, file_name_template.format(file_tag, download_suffix)) filled_cmd = self._create_file_cmd.format( local_file_path, self.file_size_mb * self._size_multiplier) print(f"Creating file of size {self.file_size_mb} MB " f"in {self.demo_folder} by running:") print(f"{'':4}{filled_cmd}") os.system(filled_cmd) chore = (local_file_path, s3_object_key, downloaded_file_path) self._chore_list.append(chore) return chore def _report_transfer_params(self, verb, source_name, dest_name, **kwargs): """Report configuration and extra arguments used for a file transfer.""" print('-' * self._terminal_width) print(f'{verb} {source_name} ({self.file_size_mb} MB) to {dest_name}') if kwargs: print('With extra args:') for arg, value in kwargs.items(): print(f'{"":4}{arg:<20}: {value}') @staticmethod def ask_user(question): """ Ask the user a yes or no question. Returns: True when the user answers 'y' or 'Y'; otherwise, False. """ answer = input(f"{question} (y/n) ") return answer.lower() == 'y' @staticmethod def _config_wrapper(func, config_attrs): def wrapper(*args, **kwargs): config = func(*args, **kwargs) print('With configuration:') for attr in config_attrs: print(f'{"":4}{attr:<20}: {getattr(config, attr)}') return config return wrapper @staticmethod def _report_transfer_result(thread_info, elapsed): """Report the result of a transfer, including per-thread data.""" print(f"\nUsed {len(thread_info)} threads.") for ident, byte_count in thread_info.items(): print(f"{'':4}Thread {ident} copied {byte_count} bytes.") print(f"Your transfer took {elapsed:.2f} seconds.") def main(): """ Run the demonstration script for s3_file_transfer. """ demo_manager = TransferDemoManager() demo_manager.collect_user_info() # Upload and download with default configuration. Because the file is 30 MB # and the default multipart_threshold is 8 MB, both upload and download are # multipart transfers. demo_manager.demo( "Do you want to upload and download a {} MB file " "using the default configuration?", file_transfer.upload_with_default_configuration, file_transfer.download_with_default_configuration) # Upload and download with multipart_threshold set higher than the size of # the file. This causes the transfer manager to use standard transfers # instead of multipart transfers. demo_manager.demo( "Do you want to upload and download a {} MB file " "as a standard (not multipart) transfer?", file_transfer.upload_with_high_threshold, file_transfer.download_with_high_threshold) # Upload with specific chunk size and additional metadata. # Download with a single thread. demo_manager.demo( "Do you want to upload a {} MB file with a smaller chunk size and " "then download the same file using a single thread?", file_transfer.upload_with_chunksize_and_meta, file_transfer.download_with_single_thread, upload_args={ 'metadata': { 'upload_type': 'chunky', 'favorite_color': 'aqua', 'size': 'medium'}}) # Upload using server-side encryption with customer-provided # encryption keys. # Generate a 256-bit key from a passphrase. sse_key = hashlib.sha256('demo_passphrase'.encode('utf-8')).digest() demo_manager.demo( "Do you want to upload and download a {} MB file using " "server-side encryption?", file_transfer.upload_with_sse, file_transfer.download_with_sse, upload_args={'sse_key': sse_key}, download_args={'sse_key': sse_key}) # Download without specifying an encryption key to show that the # encryption key must be included to download an encrypted object. if demo_manager.ask_user("Do you want to try to download the encrypted " "object without sending the required key?"): try: local_file_path, object_key, download_file_path = \ demo_manager.last_name_set() file_transfer.download_with_default_configuration( demo_manager.demo_bucket, object_key, download_file_path, demo_manager.file_size_mb) except ClientError as err: print("Got expected error when trying to download an encrypted " "object without specifying encryption info:") print(f"{'':4}{err}") # Remove all created and downloaded files, remove all objects from # S3 storage. if demo_manager.ask_user( "Demonstration complete. Do you want to remove local files " "and S3 objects?"): demo_manager.cleanup() if __name__ == '__main__': try: main() except NoCredentialsError as error: print(error) print("To run this example, you must have valid credentials in " "a shared credential file or set in environment variables.")
39.058309
81
0.623871
4a1053654f4f34eb5af21add8424debd753f6fcd
3,942
py
Python
oarepo_communities/api.py
oarepo/oarepo-communities
eb05dbdd5caf29e8741df5213456220d8f359cfa
[ "MIT" ]
null
null
null
oarepo_communities/api.py
oarepo/oarepo-communities
eb05dbdd5caf29e8741df5213456220d8f359cfa
[ "MIT" ]
24
2021-02-01T17:30:33.000Z
2022-02-08T09:54:22.000Z
oarepo_communities/api.py
oarepo/oarepo-communities
eb05dbdd5caf29e8741df5213456220d8f359cfa
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright (C) 2021 CESNET. # # OARepo-Communities is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """OArepo module that adds support for communities""" import sqlalchemy from flask import current_app from invenio_accounts.models import Role from invenio_accounts.proxies import current_datastore from invenio_db import db from invenio_records.api import RecordBase from oarepo_communities.errors import OARepoCommunityCreateError from oarepo_communities.models import OARepoCommunityModel from oarepo_communities.proxies import current_oarepo_communities from oarepo_communities.signals import before_community_insert, after_community_insert class OARepoCommunity(RecordBase): model_cls = OARepoCommunityModel @classmethod def create(cls, data, title, ctype='other', id_=None, **kwargs): """Create a new Community instance and store it in the database.""" with db.session.begin_nested(): comm = cls(data) comm.model = cls.model_cls( id=id_, title=title, type=ctype, json=comm) before_community_insert.send( current_app._get_current_object(), community=comm.model ) cls._create_community_roles(comm.model) db.session.add(comm.model) after_community_insert.send( current_app._get_current_object(), community=comm.model ) return comm.model @classmethod def _create_community_roles(cls, community): community.roles = [] for role in current_oarepo_communities.roles: role_kwargs = current_oarepo_communities.role_name_factory(community, role) role = current_datastore.find_or_create_role(str(role_kwargs['name'])) if not role: raise OARepoCommunityCreateError(community) role.description = role_kwargs['description'] current_datastore.put(role) community.roles.append(role) # Allow actions on community roles based on policy rules @classmethod def get_community(cls, id_, with_deleted=False, **kwargs): """Retrieve the community by its id. Raise a database exception if the community does not exist. :param id_: community ID. :param with_deleted: If `True` then it includes deleted communities. :returns: The :class:`OARepoCommunityModel` instance or None if not found. """ with db.session.no_autoflush: query = cls.model_cls.query.filter_by(id=id_) if not with_deleted: query = query.filter(cls.model_cls.json != None) # noqa try: obj = query.one() except sqlalchemy.orm.exc.NoResultFound: return None return cls(obj.json, model=obj).model @classmethod def get_role(cls, community: OARepoCommunityModel, role_name: str) -> Role: """Retrieve the community Invenio Role for a given role short name.""" kwargs = current_oarepo_communities.role_name_factory(community, role_name) return current_datastore.find_role(kwargs['name']) @classmethod def get_communities(cls, ids, with_deleted=False): """Retrieve multiple communities by id. :param ids: List of community IDs. :param with_deleted: If `True` then it includes deleted communities. :returns: A list of :class:`OARepoCommunityModel` instances. """ with db.session.no_autoflush: query = cls.model_cls.query.filter(cls.model_cls.id.in_(ids)) if not with_deleted: query = query.filter(cls.model_cls.json != None) # noqa return [cls(obj.json, model=obj).model for obj in query.all()]
36.841121
87
0.660832
4a105453151158fe7f108cff9a1eaa8a0e0fcef0
3,995
py
Python
source/process_global_variables.py
WuphonsReach/BeggarsDiplomacy
e6b7f3790e28f458eca0a42250a6bbf41bef8d30
[ "MIT" ]
14
2018-09-20T23:01:27.000Z
2021-05-25T11:05:09.000Z
source/process_global_variables.py
WuphonsReach/BeggarsDiplomacy
e6b7f3790e28f458eca0a42250a6bbf41bef8d30
[ "MIT" ]
44
2018-09-15T03:05:50.000Z
2022-03-22T02:46:24.000Z
source/process_global_variables.py
WuphonsReach/BeggarsDiplomacy
e6b7f3790e28f458eca0a42250a6bbf41bef8d30
[ "MIT" ]
13
2018-10-02T11:45:24.000Z
2021-08-22T18:41:44.000Z
#import string #import types from module_info import * from module_triggers import * from module_dialogs import * from module_simple_triggers import * from module_presentations import * from module_variables import * from process_common import * from process_operations import * #------------------------------------------------------- def compile_all_global_vars(variable_list,variable_uses, triggers, sentences, game_menus, mission_templates, scripts, simple_triggers): temp_list = [] list_type = type(temp_list) for varb in reserved_variables: try: add_variable(varb, variable_list, variable_uses) except: print "Error in variable:" print variable for trigger in triggers: try: compile_global_vars(trigger[3], variable_list,variable_uses), compile_global_vars(trigger[4], variable_list,variable_uses), except: print "Error in trigger:" print trigger for scene_prop in scene_props: try: sp_triggers = scene_prop[4] for sp_trigger in sp_triggers: compile_global_vars(sp_trigger[1], variable_list,variable_uses) except: print "Error in scene prop:" print scene_prop for sentence in sentences: try: compile_global_vars(sentence[2], variable_list,variable_uses), compile_global_vars(sentence[5], variable_list,variable_uses), except: print "Error in dialog line:" print sentence for game_menu in game_menus: try: compile_global_vars(game_menu[4], variable_list,variable_uses) menu_items = game_menu[5] for menu_item in menu_items: compile_global_vars(menu_item[1], variable_list,variable_uses) compile_global_vars(menu_item[3], variable_list,variable_uses) except: print "Error in game menu:" print game_menu for mission_template in mission_templates: try: mt_triggers = mission_template[5] for mt_trigger in mt_triggers: compile_global_vars(mt_trigger[3], variable_list,variable_uses) compile_global_vars(mt_trigger[4], variable_list,variable_uses) except: print "Error in mission template:" print mission_template for presentation in presentations: try: prsnt_triggers = presentation[3] for prsnt_trigger in prsnt_triggers: compile_global_vars(prsnt_trigger[1], variable_list,variable_uses) except: print "Error in presentation:" print presentation for i_script in xrange(len(scripts)): try: func = scripts[i_script] if (type(func[1]) == list_type): compile_global_vars(func[1], variable_list,variable_uses) else: compile_global_vars(func[2], variable_list,variable_uses) except: print "Error in script:" print func for simple_trigger in simple_triggers: try: compile_global_vars(simple_trigger[1] , variable_list,variable_uses) except: print "Error in simple trigger:" print simple_trigger print "Compiling all global variables..." ##diplomacy start+ #Import global-variable-saving code # ##OLD: # #variable_uses = [] #variables = load_variables(export_dir, variable_uses) #compile_all_global_vars(variables, variable_uses,triggers, dialogs, game_menus, mission_templates, scripts, simple_triggers) #save_variables(export_dir, variables,variable_uses) # ##NEW: # #MORDACHAI - Preserve previous global variable order, for save-game compatibility... variables = [] variable_uses = [] try: file = open("variables.txt","r") var_list = file.readlines() file.close() for v in var_list: vv = string.strip(v) if vv: variables.append(vv) variable_uses.append(0) except: print "Variables.txt not found. No attempt to maintain save game compatibility will be made for this build." compile_all_global_vars(variables, variable_uses, triggers, dialogs, game_menus, mission_templates, scripts, simple_triggers) save_variables(export_dir, variables, variable_uses) ##diplomacy end+
29.813433
135
0.717647
4a1055e910f2b5dff285720613a9b37ce29fb75e
4,090
py
Python
RsaEncryptionOaepSha256String/RsaEncryptionOaepSha256.py
likloadm/cross_platform_crypto
e828c9c9504c022d3882d174f7a8fd424aa19991
[ "Unlicense" ]
15
2020-11-14T09:50:50.000Z
2022-03-13T16:39:19.000Z
RsaEncryptionOaepSha256String/RsaEncryptionOaepSha256.py
likloadm/cross_platform_crypto
e828c9c9504c022d3882d174f7a8fd424aa19991
[ "Unlicense" ]
1
2021-04-26T07:42:27.000Z
2021-07-06T07:39:17.000Z
RsaEncryptionOaepSha256String/RsaEncryptionOaepSha256.py
likloadm/cross_platform_crypto
e828c9c9504c022d3882d174f7a8fd424aa19991
[ "Unlicense" ]
6
2021-11-03T11:28:36.000Z
2022-03-16T13:03:20.000Z
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from Crypto.Hash import SHA256 import base64 def base64Encoding(input): dataBase64 = base64.b64encode(input) dataBase64P = dataBase64.decode("UTF-8") return dataBase64P def base64Decoding(input): return base64.decodebytes(input.encode("ascii")) def rsaEncryptionOaepSha256ToBase64(publicKeyPem, message): rsaPublicKey = RSA.import_key(publicKeyPem) plaintext = message.encode("ascii") cipher = PKCS1_OAEP.new(rsaPublicKey, SHA256) ciphertext = cipher.encrypt(plaintext) return base64Encoding(ciphertext) def rsaDecryptionOaepSha256FromBase64(privateKeyPem, ciphertextBase64): rsaPrivateKey = RSA.import_key(privateKeyPem) ciphertextBytes = base64Decoding(ciphertextBase64) cipher = PKCS1_OAEP.new(rsaPrivateKey, SHA256) try: message = cipher.decrypt(ciphertextBytes) messageP = message.decode("UTF-8") return messageP except (ValueError): return "" def loadRsaPrivateKeyPem(): return """-----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDwSZYlRn86zPi9 e1RTZL7QzgE/36zjbeCMyOhf6o/WIKeVxFwVbG2FAY3YJZIxnBH+9j1XS6f+ewjG FlJY4f2IrOpS1kPiO3fmOo5N4nc8JKvjwmKtUM0t63uFFPfs69+7mKJ4w3tk2mSN 4gb8J9P9BCXtH6Q78SdOYvdCMspA1X8eERsdLb/jjHs8+gepKqQ6+XwZbSq0vf2B MtaAB7zTX/Dk+ZxDfwIobShPaB0mYmojE2YAQeRq1gYdwwO1dEGk6E5J2toWPpKY /IcSYsGKyFqrsmbw0880r1BwRDer4RFrkzp4zvY+kX3eDanlyMqDLPN+ghXT1lv8 snZpbaBDAgMBAAECggEBAIVxmHzjBc11/73bPB2EGaSEg5UhdzZm0wncmZCLB453 XBqEjk8nhDsVfdzIIMSEVEowHijYz1c4pMq9osXR26eHwCp47AI73H5zjowadPVl uEAot/xgn1IdMN/boURmSj44qiI/DcwYrTdOi2qGA+jD4PwrUl4nsxiJRZ/x7PjL hMzRbvDxQ4/Q4ThYXwoEGiIBBK/iB3Z5eR7lFa8E5yAaxM2QP9PENBr/OqkGXLWV qA/YTxs3gAvkUjMhlScOi7PMwRX9HsrAeLKbLuC1KJv1p2THUtZbOHqrAF/uwHaj ygUblFaa/BTckTN7PKSVIhp7OihbD04bSRrh+nOilcECgYEA/8atV5DmNxFrxF1P ODDjdJPNb9pzNrDF03TiFBZWS4Q+2JazyLGjZzhg5Vv9RJ7VcIjPAbMy2Cy5BUff EFE+8ryKVWfdpPxpPYOwHCJSw4Bqqdj0Pmp/xw928ebrnUoCzdkUqYYpRWx0T7YV RoA9RiBfQiVHhuJBSDPYJPoP34kCgYEA8H9wLE5L8raUn4NYYRuUVMa+1k4Q1N3X Bixm5cccc/Ja4LVvrnWqmFOmfFgpVd8BcTGaPSsqfA4j/oEQp7tmjZqggVFqiM2m J2YEv18cY/5kiDUVYR7VWSkpqVOkgiX3lK3UkIngnVMGGFnoIBlfBFF9uo02rZpC 5o5zebaDImsCgYAE9d5wv0+nq7/STBj4NwKCRUeLrsnjOqRriG3GA/TifAsX+jw8 XS2VF+PRLuqHhSkQiKazGr2Wsa9Y6d7qmxjEbmGkbGJBC+AioEYvFX9TaU8oQhvi hgA6ZRNid58EKuZJBbe/3ek4/nR3A0oAVwZZMNGIH972P7cSZmb/uJXMOQKBgQCs FaQAL+4sN/TUxrkAkylqF+QJmEZ26l2nrzHZjMWROYNJcsn8/XkaEhD4vGSnazCu /B0vU6nMppmezF9Mhc112YSrw8QFK5GOc3NGNBoueqMYy1MG8Xcbm1aSMKVv8xba rh+BZQbxy6x61CpCfaT9hAoA6HaNdeoU6y05lBz1DQKBgAbYiIk56QZHeoZKiZxy 4eicQS0sVKKRb24ZUd+04cNSTfeIuuXZrYJ48Jbr0fzjIM3EfHvLgh9rAZ+aHe/L 84Ig17KiExe+qyYHjut/SC0wODDtzM/jtrpqyYa5JoEpPIaUSgPuTH/WhO3cDsx6 3PIW4/CddNs8mCSBOqTnoaxh -----END PRIVATE KEY----- """ def loadRsaPublicKeyPem(): return """-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8EmWJUZ/Osz4vXtUU2S+ 0M4BP9+s423gjMjoX+qP1iCnlcRcFWxthQGN2CWSMZwR/vY9V0un/nsIxhZSWOH9 iKzqUtZD4jt35jqOTeJ3PCSr48JirVDNLet7hRT37Ovfu5iieMN7ZNpkjeIG/CfT /QQl7R+kO/EnTmL3QjLKQNV/HhEbHS2/44x7PPoHqSqkOvl8GW0qtL39gTLWgAe8 01/w5PmcQ38CKG0oT2gdJmJqIxNmAEHkatYGHcMDtXRBpOhOSdraFj6SmPyHEmLB ishaq7Jm8NPPNK9QcEQ3q+ERa5M6eM72PpF93g2p5cjKgyzzfoIV09Zb/LJ2aW2g QwIDAQAB -----END PUBLIC KEY-----""" print("RSA 2048 encryption OAEP SHA-256 string") dataToEncrypt = "The quick brown fox jumps over the lazy dog" print("dataToEncrypt: " + dataToEncrypt) print("\n* * * encrypt the plaintext with the RSA public key * * *") publicRsaKeyPem = loadRsaPublicKeyPem() print("used public key:\n" + publicRsaKeyPem) ciphertextBase64 = rsaEncryptionOaepSha256ToBase64(publicRsaKeyPem, dataToEncrypt) print("\nciphertextBase64: " + ciphertextBase64) print("\n* * * decrypt the ciphertext with the RSA private key * * *") ciphertextReceivedBase64 = ciphertextBase64; privateRsaKeyPem = loadRsaPrivateKeyPem() print("used private key:\n" + privateRsaKeyPem) decryptedtext = rsaDecryptionOaepSha256FromBase64(privateRsaKeyPem, ciphertextReceivedBase64) print("\ndecryptedtext: " + decryptedtext)
44.456522
94
0.839609
4a10568d86aff60ddd208382f4b54a4e1e0cb9e5
7,853
py
Python
tensorflow_graphics/geometry/deformation_energy/tests/as_conformal_as_possible_test.py
jackd/graphics
736b99a3306e302674a9b7599e3e2857b85fdb74
[ "Apache-2.0" ]
null
null
null
tensorflow_graphics/geometry/deformation_energy/tests/as_conformal_as_possible_test.py
jackd/graphics
736b99a3306e302674a9b7599e3e2857b85fdb74
[ "Apache-2.0" ]
null
null
null
tensorflow_graphics/geometry/deformation_energy/tests/as_conformal_as_possible_test.py
jackd/graphics
736b99a3306e302674a9b7599e3e2857b85fdb74
[ "Apache-2.0" ]
1
2020-04-11T10:37:36.000Z
2020-04-11T10:37:36.000Z
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for as_conformal_as_possible.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.deformation_energy import as_conformal_as_possible from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.util import test_case class AsConformalAsPossibleTest(test_case.TestCase): def test_energy_identity(self): """Checks that energy evaluated between the rest pose and itself is zero.""" number_vertices = np.random.randint(3, 10) batch_size = np.random.randint(3) batch_shape = np.random.randint(1, 10, size=(batch_size)).tolist() vertices_rest_pose = np.random.uniform(size=(number_vertices, 3)) vertices_deformed_pose = tf.broadcast_to( vertices_rest_pose, shape=batch_shape + [number_vertices, 3]) quaternions = quaternion.from_euler( np.zeros(shape=batch_shape + [number_vertices, 3])) num_edges = int(round(number_vertices / 2)) edges = np.zeros(shape=(num_edges, 2), dtype=np.int32) edges[..., 0] = np.linspace( 0, number_vertices / 2 - 1, num_edges, dtype=np.int32) edges[..., 1] = np.linspace( number_vertices / 2, number_vertices - 1, num_edges, dtype=np.int32) energy = as_conformal_as_possible.energy( vertices_rest_pose=vertices_rest_pose, vertices_deformed_pose=vertices_deformed_pose, quaternions=quaternions, edges=edges, conformal_energy=False) self.assertAllClose(energy, tf.zeros_like(energy)) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_energy_jacobian_random(self): """Checks the correctness of the jacobian of energy.""" number_vertices = np.random.randint(3, 10) batch_size = np.random.randint(3) batch_shape = np.random.randint(1, 10, size=(batch_size)).tolist() vertices_rest_pose_init = np.random.uniform(size=(number_vertices, 3)) vertices_deformed_pose_init = np.random.uniform(size=batch_shape + [number_vertices, 3]) quaternions_init = np.random.uniform(size=batch_shape + [number_vertices, 4]) num_edges = int(round(number_vertices / 2)) edges = np.zeros(shape=(num_edges, 2), dtype=np.int32) edges[..., 0] = np.linspace( 0, number_vertices / 2 - 1, num_edges, dtype=np.int32) edges[..., 1] = np.linspace( number_vertices / 2, number_vertices - 1, num_edges, dtype=np.int32) def conformal_energy(vertices_rest_pose, vertices_deformed_pose, quaternions): return as_conformal_as_possible.energy( vertices_rest_pose=vertices_rest_pose, vertices_deformed_pose=vertices_deformed_pose, quaternions=quaternions, edges=edges, conformal_energy=True) def nonconformal_energy(vertices_rest_pose, vertices_deformed_pose, quaternions): return as_conformal_as_possible.energy( vertices_rest_pose=vertices_rest_pose, vertices_deformed_pose=vertices_deformed_pose, quaternions=quaternions, edges=edges, conformal_energy=False) with self.subTest(name="conformal"): self.assert_jacobian_is_correct_fn(conformal_energy, [ vertices_rest_pose_init, vertices_deformed_pose_init, quaternions_init ]) with self.subTest(name="non_conformal"): self.assert_jacobian_is_correct_fn(nonconformal_energy, [ vertices_rest_pose_init, vertices_deformed_pose_init, quaternions_init ]) @parameterized.parameters( ((1, 3), (1, 3), (1, 4), (1, 2), (1,), (1,)), ((1, 3), (None, 1, 3), (None, 1, 4), (1, 2), (1,), (1,)), ((1, 3), (2, None, 1, 3), (2, None, 1, 4), (1, 2), (1,), (1,)), ) def test_energy_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( as_conformal_as_possible.energy, shapes, [tf.float32, tf.float32, tf.float32, tf.int32, tf.float32, tf.float32]) def test_energy_preset(self): """Checks that energy returns the expected value.""" vertices_rest_pose = np.array(((1.0, 0.0, 0.0), (-1.0, 0.0, 0.0))) vertices_deformed_pose = 2.0 * vertices_rest_pose quaternions = quaternion.from_euler( np.zeros(shape=vertices_deformed_pose.shape)) edges = ((0, 1),) all_weights_1_energy = as_conformal_as_possible.energy( vertices_rest_pose, vertices_deformed_pose, quaternions, edges) all_weights_1_gt = 4.0 vertex_weights = np.array((2.0, 1.0)) vertex_weights_energy = as_conformal_as_possible.energy( vertices_rest_pose=vertices_rest_pose, vertices_deformed_pose=vertices_deformed_pose, quaternions=quaternions, edges=edges, vertex_weight=vertex_weights) vertex_weights_gt = 10.0 edge_weights = np.array((2.0,)) edge_weights_energy = as_conformal_as_possible.energy( vertices_rest_pose=vertices_rest_pose, vertices_deformed_pose=vertices_deformed_pose, quaternions=quaternions, edges=edges, edge_weight=edge_weights) edge_weights_gt = 16.0 with self.subTest(name="all_weights_1"): self.assertAllClose(all_weights_1_energy, all_weights_1_gt) with self.subTest(name="vertex_weights"): self.assertAllClose(vertex_weights_energy, vertex_weights_gt) with self.subTest(name="edge_weights"): self.assertAllClose(edge_weights_energy, edge_weights_gt) @parameterized.parameters( ("vertices_rest_pose must have exactly 3 dimensions in axis", (1, 2), (1, 3), (1, 4), (1, 2), (1,), (1,)), ("vertices_rest_pose must have a rank of 2", (2, 1, 2), (1, 3), (1, 4), (1, 2), (1,), (1,)), ("vertices_deformed_pose must have exactly 3 dimensions in axis", (1, 3), (1, 2), (1, 4), (1, 2), (1,), (1,)), ("must have the same number of dimensions", (1, 3), (2, 3), (1, 4), (1, 2), (1,), (1,)), ("quaternions must have exactly 4 dimensions in axis", (1, 3), (1, 3), (1, 5), (1, 2), (1,), (1,)), ("must have the same number of dimensions", (1, 3), (1, 3), (2, 4), (1, 2), (1,), (1,)), ("Not all batch dimensions are identical", (1, 3), (1, 3), (2, 1, 4), (1, 2), (1,), (1,)), ("edges must have exactly 2 dimensions in axis", (1, 3), (1, 3), (1, 4), (1, 3), (1,), (1,)), ("edges must have a rank of 2", (1, 3), (1, 3), (1, 4), (2, 1, 2), (1,), (1,)), ("must have the same number of dimensions", (1, 3), (1, 3), (1, 4), (1, 2), (2,), (1,)), ("must have the same number of dimensions", (1, 3), (1, 3), (1, 4), (1, 2), (1,), (2,)), ) # pyformat: disable def test_energy_raised(self, error_msg, *shapes): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised( as_conformal_as_possible.energy, error_msg, shapes, [tf.float32, tf.float32, tf.float32, tf.int32, tf.float32, tf.float32]) if __name__ == "__main__": test_case.main()
42.912568
84
0.663823
4a1056b38fda05e8c12a1c4fca5d13db0a01eca6
3,402
py
Python
main.py
PotatoHD1/KlainMakklasky
898e5dc25d4eb4112a669afdb2456260ee240fb0
[ "MIT" ]
1
2021-04-12T08:15:08.000Z
2021-04-12T08:15:08.000Z
main.py
PotatoHD1/KlainMakklasky
898e5dc25d4eb4112a669afdb2456260ee240fb0
[ "MIT" ]
null
null
null
main.py
PotatoHD1/KlainMakklasky
898e5dc25d4eb4112a669afdb2456260ee240fb0
[ "MIT" ]
null
null
null
import collections import pandas as pd import random def F4(table, inp, res): temp = dict(table) for k in res: table = dict(temp) for i in inp: f = F1(bin(i + 16)[3:]) if i in k[0]: table[f] -= 1 if all([i > 0 for i in table.values()]): return False return True def F2(a): newlist = [] for i in a: if i not in newlist: newlist.append(i) return newlist ALPHABET = \ "0123456789abcdefghijklmnopqrstuvwxyz" def encode(n): try: return ALPHABET[n] except IndexError: raise Exception("cannot encode: %s" % n) def dec_to_base(dec=0, base=16): if dec < base: return encode(dec) else: return dec_to_base(dec // base, base) + encode(dec % base) def F(a, b): count = 0 k = 0 for j in range(len(a)): # if a[j] != b[j] and not (a[j] == "-" or b[j] == "-"): if a[j] != b[j]: count += 1 k = j if count == 1: a = a[:k] + "-" + a[k + 1:] return a return "" def F1(a): mas = "abcd" res = "" for i in range(len(a)): if a[i] == "1": res += mas[i] elif a[i] == "0": res += "¬" + mas[i] return res inp = [0, 1, 4, 5, 9, 10, 11, 12, 13, 14] a = [[], [], [], [], []] res = [] used = set() gened = set() for i in inp: f = str(bin(i + 16)[3:]) unsorted = dict(collections.Counter(f)) if "1" not in unsorted: unsorted['1'] = 0 a[unsorted['1']].append(([i], f)) print(a) for o in range(3): b = [[], [], [], []] for i in range(5 - o): for m, j in a[i]: if i < 5 - o - 1: for l, k in a[i + 1]: if f := F(j, k): used.add(j) used.add(k) if f not in gened: unsorted = dict(collections.Counter(f)) if "1" not in unsorted: unsorted['1'] = 0 tmp = list(m) tmp[0:0] = l gened.add(f) b[unsorted['1']].append((tmp, f)) if j not in used: res.append((m, j)) a = b print(a) print(res) for i in range(len(res)): res[i] = (res[i][0], F1(res[i][1])) print(res) result = set() for l in range(2 ** len(res)): table = {} inp1 = [] res1 = [] for i in range(len(res)): if str(bin(l + 2 ** len(res)))[3:][i] == "1": res1.append(res[i]) for i in inp: f = F1(bin(i + 16)[3:]) table[f] = 0 for k in res1: if i in k[0]: # print(k[0]) table[f] += 1 temp = "" for k in res1: temp += k[1] + "V" temp = temp[:-1] # print(inp1) if all([i > 0 for i in table.values()]) and F4(table, inp, res1) and temp not in result: result.add(temp) print(temp, [i for i in range(len(res)) if str(bin(l + 2 ** len(res)))[3:][i] == "1"]) print(result) # for i in inp: # f = F1(bin(i + 16)[3:]) # table[f] = [0] * len(res) # for j, k in enumerate(res): # if i in k[0]: # table[f][j] = 1 # df = pd.DataFrame(data=table, index=[i[1] for i in res]) # df.to_excel("output.xlsx")
24.3
94
0.423868
4a1056c96214cb38d86a8593d5de26ccd86eb2a5
2,390
py
Python
src/python/coref/models/entity/TitleModel.py
nmonath/coref_tools
542659170897ad05f7612639cb918886859ae9d6
[ "Apache-2.0" ]
null
null
null
src/python/coref/models/entity/TitleModel.py
nmonath/coref_tools
542659170897ad05f7612639cb918886859ae9d6
[ "Apache-2.0" ]
null
null
null
src/python/coref/models/entity/TitleModel.py
nmonath/coref_tools
542659170897ad05f7612639cb918886859ae9d6
[ "Apache-2.0" ]
null
null
null
""" Copyright (C) 2018 University of Massachusetts Amherst. This file is part of "coref_tools" http://github.com/nmonath/coref_tools Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from torch.nn import Module from coref.util.dist import _fast_norm_diff class TitleModel(Module): def __init__(self, config, vocab): """ Construct a router model :param config: the config to use :param vocab: the vocab to use :param ft: a fasttext loaded model """ super(TitleModel, self).__init__() self.config = config self.vocab = vocab self.dim = 1 def norm_diff_min_avg(self, entity): """Norm of difference between min and average title emedding.""" avg_emb = entity['tea'] # title embedding avg bb_emb = entity['tbb'] if type(avg_emb) == set or type(bb_emb) == set: return 0.0 else: return _fast_norm_diff(bb_emb[0], avg_emb) def norm_diff_max_avg(self, entity): """Norm of difference between max and average title emedding.""" avg_emb = entity['tea'] # title embedding avg bb_emb = entity['tbb'] if type(avg_emb) == set or type(bb_emb) == set: return 0.0 else: return _fast_norm_diff(bb_emb[1], avg_emb) def norm_diff_max_min(self, entity): """Norm of difference between min and max title emedding.""" bb_emb = entity['tbb'] if type(bb_emb) == set: return 0.0 else: return _fast_norm_diff(bb_emb[0], bb_emb[1]) def emb(self, entity): """ :param routee: :param dest: :return: Some kind of vector, you choose """ fv = [] # fv.append(self.norm_diff_max_avg(entity)) # fv.append(self.norm_diff_min_avg(entity)) fv.append(self.norm_diff_max_min(entity)) return fv
33.194444
72
0.641423
4a1056e2eeac6344989c69776f621fd3ea9d4699
347
py
Python
cd2vec/python/my_test/func4.py
Kirili4ik/code2vec
4867647eb68ec3708fb77d3500d4f3fc48331374
[ "MIT" ]
2
2020-08-11T13:33:02.000Z
2020-10-27T05:07:05.000Z
cd2vec/python/my_test/func4.py
Kirili4ik/code2vec
4867647eb68ec3708fb77d3500d4f3fc48331374
[ "MIT" ]
2
2020-12-03T13:15:55.000Z
2022-02-10T02:06:22.000Z
cd2vec/python/my_test/func4.py
Kirili4ik/code2vec
4867647eb68ec3708fb77d3500d4f3fc48331374
[ "MIT" ]
2
2021-04-08T14:51:01.000Z
2021-09-22T07:57:37.000Z
def plotting(): ts_fare_diff = log_ts_fare - log_ts_fare.shift() ts_fare_diff.dropna(inplace = True)t1 = plot_line(ts_fare_diff.index,ts_fare_diff['fare_amount'], 'blue','Differenced log series') lay = plot_layout('Differenced log series') fig = go.Figure(data = [t1],layout=lay) py.iplot(fig)stationary_test(ts_fare_diff)
34.7
98
0.723343
4a105713da4ee2e0d6bd9e405ac25d6faa27802e
3,346
py
Python
hw3/china.py
dgketchum/csci547
bbba91c1cd09f672342b11280f79e551968a0037
[ "Apache-2.0" ]
null
null
null
hw3/china.py
dgketchum/csci547
bbba91c1cd09f672342b11280f79e551968a0037
[ "Apache-2.0" ]
null
null
null
hw3/china.py
dgketchum/csci547
bbba91c1cd09f672342b11280f79e551968a0037
[ "Apache-2.0" ]
null
null
null
# ============================================================================================= # Copyright 2018 dgketchum # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================================= import os print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.metrics import pairwise_distances_argmin from sklearn.datasets import load_sample_image from sklearn.utils import shuffle from time import time n_colors = 64 # Load the Summer Palace photo china = load_sample_image("china.jpg") # Convert to floats instead of the default 8 bits integer coding. Dividing by # 255 is important so that plt.imshow behaves works well on float data (need to # be in the range [0-1]) china = np.array(china, dtype=np.float64) / 255 # Load Image and transform to a 2D numpy array. w, h, d = original_shape = tuple(china.shape) assert d == 3 image_array = np.reshape(china, (w * h, d)) print("Fitting model on a small sub-sample of the data") t0 = time() image_array_sample = shuffle(image_array, random_state=0)[:1000] kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array_sample) print("done in %0.3fs." % (time() - t0)) # Get labels for all points print("Predicting color indices on the full image (k-means)") t0 = time() labels = kmeans.predict(image_array) print("done in %0.3fs." % (time() - t0)) codebook_random = shuffle(image_array, random_state=0)[:n_colors + 1] print("Predicting color indices on the full image (random)") t0 = time() labels_random = pairwise_distances_argmin(codebook_random, image_array, axis=0) print("done in %0.3fs." % (time() - t0)) def recreate_image(codebook, labels, w, h): """Recreate the (compressed) image from the code book & labels""" d = codebook.shape[1] image = np.zeros((w, h, d)) label_idx = 0 for i in range(w): for j in range(h): image[i][j] = codebook[labels[label_idx]] label_idx += 1 return image # Display all results, alongside original image plt.figure(1) plt.clf() ax = plt.axes([0, 0, 1, 1]) plt.axis('off') plt.title('Original image (96,615 colors)') plt.imshow(china) plt.figure(2) plt.clf() ax = plt.axes([0, 0, 1, 1]) plt.axis('off') plt.title('Quantized image (64 colors, K-Means)') plt.imshow(recreate_image(kmeans.cluster_centers_, labels, w, h)) plt.figure(3) plt.clf() ax = plt.axes([0, 0, 1, 1]) plt.axis('off') plt.title('Quantized image (64 colors, Random)') plt.imshow(recreate_image(codebook_random, labels_random, w, h)) plt.show() if __name__ == '__main__': home = os.path.expanduser('~') # ========================= EOF ================================================================
32.173077
96
0.639868
4a1057b6fdeba601577f38260adc6c6bc812b7d6
2,503
py
Python
TrackerDash/templates/logpage.py
wedgieedward/TrackerDash
53c3ecc7b9124740f05847dbd235b068601c621e
[ "Beerware" ]
null
null
null
TrackerDash/templates/logpage.py
wedgieedward/TrackerDash
53c3ecc7b9124740f05847dbd235b068601c621e
[ "Beerware" ]
2
2015-04-08T23:20:35.000Z
2015-04-08T23:21:57.000Z
TrackerDash/templates/logpage.py
wedgieedward/TrackerDash
53c3ecc7b9124740f05847dbd235b068601c621e
[ "Beerware" ]
null
null
null
from twisted.web.template import XMLFile, renderer, XMLString from twisted.python.filepath import FilePath from TrackerDash.templates.basewebpage import BasePage class LogPage(BasePage): """ LogPage """ DEFAULT_TAG = XMLString('<span class="label label-default"> Log </span>') INFO_TAG = XMLString('<span class="label label-info">Info</span>') DEBUG_TAG = XMLString('<span class="label label-warning">Debug</span>') PRIMARY_TAG = XMLString('<span class="label label-primary">Primary</span>') SUCCESS_TAG = XMLString('<span class="label label-success">Success</span>') DANGER_TAG = XMLString('<span class="label label-danger">Danger</span>') def __init__(self, log_file, title): self.log_file = log_file self.title = title super(LogPage, self).__init__() @renderer def content(self, request, tag): """ get the content for the configuration page """ log_content = XMLFile(FilePath("TrackerDash/snippets/logs.xml")) return log_content.load() @renderer def auto_refresh(self, request, tag): """ render the auto refresh meta tag """ return "" @renderer def get_title(self, request, tag): """ """ return self.title @renderer def get_log_lines(self, request, tag): """ render the log lines """ for log_line in self.get_log_file_contents(): log_type = self.get_log_label(log_line) yield tag.clone().fillSlots( log_line=log_line, log_label=log_type.load()) def get_log_file_contents(self): """ open the log file, return an list of all the log lines in reverse order """ log_file = open(self.log_file, 'r') lines = log_file.readlines() # TODO remove this when log rotation is properly implemented lines = lines[-100:] # Get the last 100 lines log_file.close() lines.reverse() # Put them in a displayable order return lines def get_log_label(self, log_line): """ """ label = self.DEFAULT_TAG if "INFO" in log_line: label = self.INFO_TAG elif "DEBUG" in log_line: label = self.DEBUG_TAG elif "200" in log_line or "304" in log_line: label = self.SUCCESS_TAG elif "404" in log_line or "500" in log_line: label = self.DANGER_TAG return label
31.683544
79
0.609668
4a1057f3f0f57643fd54c4aa7a355978ea31169c
1,490
py
Python
util/syn_gen.py
yangop8/Noah-GED
31c6a737321c227d25c787625b3fe1cc2846f51e
[ "MIT" ]
5
2021-09-01T15:53:30.000Z
2022-03-26T13:37:24.000Z
util/syn_gen.py
yangop8/Noah-GED
31c6a737321c227d25c787625b3fe1cc2846f51e
[ "MIT" ]
1
2021-10-12T13:16:38.000Z
2021-10-12T13:16:38.000Z
util/syn_gen.py
yangop8/Noah-GED
31c6a737321c227d25c787625b3fe1cc2846f51e
[ "MIT" ]
1
2021-12-21T11:53:36.000Z
2021-12-21T11:53:36.000Z
import networkx as nx import random import os data_path = '/home/yanglei/GraphEditDistance/Syn/test/' if not os.path.exists(data_path): os.makedirs(data_path) nodes = 100 for i in range(2000): G = nx.fast_gnp_random_graph(nodes,0.2) nx.write_gexf(G,data_path+str(i)+'_1.gexf') edge_num = nx.number_of_edges(G) rm_edge = random.randint(0,edge_num-1) edge_list = list(G.edges()) rm_start = edge_list[rm_edge][0] rm_end = edge_list[rm_edge][1] G.remove_edge(rm_start, rm_end) add_start = random.randint(0,nodes-2) add_end = random.randint(add_start+1,nodes-1) while ((add_start,add_end) in G.edges()): add_start = random.randint(0, nodes-2) add_end = random.randint(add_start+1, nodes-1) G.add_edge(add_start,add_end) nx.write_gexf(G,data_path+str(i)+'_2.gexf') rm_edge = random.randint(0, edge_num - 1) edge_list = list(G.edges()) while (edge_list[rm_edge][0] == add_start and edge_list[rm_edge][1] == add_end): rm_edge = random.randint(0, edge_num - 1) G.remove_edge(edge_list[rm_edge][0], edge_list[rm_edge][1]) add_start = random.randint(0, nodes-2) add_end = random.randint(add_start + 1, nodes-1) while ((add_start, add_end) in G.edges() or (add_start == rm_start and add_end == rm_end)): add_start = random.randint(0, nodes-2) add_end = random.randint(add_start + 1, nodes-1) G.add_edge(add_start, add_end) nx.write_gexf(G,data_path+str(i)+'_3.gexf')
38.205128
95
0.679195
4a105871116583bf46b7c172518ce031100a958e
4,098
py
Python
ARCHIVE/mozlz4a.py
nodiscc/toolbox
84c0a917369fc2d0efd471c8606725ac407c2c9f
[ "Unlicense", "MIT" ]
10
2017-05-27T16:59:00.000Z
2022-03-28T02:30:55.000Z
ARCHIVE/mozlz4a.py
nodiscc/toolbox
84c0a917369fc2d0efd471c8606725ac407c2c9f
[ "Unlicense", "MIT" ]
null
null
null
ARCHIVE/mozlz4a.py
nodiscc/toolbox
84c0a917369fc2d0efd471c8606725ac407c2c9f
[ "Unlicense", "MIT" ]
2
2018-03-03T18:40:25.000Z
2018-03-05T06:09:47.000Z
#!/usr/bin/env python # #Description: Decompressor/compressor for files in Mozilla's "mozLz4" format # Firefox uses this file format to compress e. g. bookmark backups (*.jsonlz4). # # This file format is in fact just plain LZ4 data with a custom header (magic number [8 bytes] and # uncompressed file size [4 bytes, little endian]). # # This Python 3 script requires the LZ4 bindings for Python, see: https://pypi.python.org/pypi/lz4 # # Source: https://gist.github.com/Tblue/62ff47bef7f894e92ed5 # Requires python3-lz4 # Run as: # python3 mozlz4a.py -d search.json.mozlz4 search.json # cat search.json | json_reformat | tee search.json # (json_reformat is part of the yajl-tools package) # python3 mozlz4a.py search.json search.json.mozlz4 # # Copyright (c) 2015, Tilman Blumenbach # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted # provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions # and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, this list of # conditions and the following disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import lz4 import sys from argparse import ArgumentParser class MozLz4aError(Exception): pass class InvalidHeader(MozLz4aError): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg def decompress(file_obj): if file_obj.read(8) != b"mozLz40\0": raise InvalidHeader("Invalid magic number") return lz4.decompress(file_obj.read()) def compress(file_obj): compressed = lz4.compress(file_obj.read()) return b"mozLz40\0" + compressed if __name__ == "__main__": argparser = ArgumentParser(description="MozLz4a compression/decompression utility") argparser.add_argument( "-d", "--decompress", "--uncompress", action="store_true", help="Decompress the input file instead of compressing it." ) argparser.add_argument( "in_file", help="Path to input file." ) argparser.add_argument( "out_file", help="Path to output file." ) parsed_args = argparser.parse_args() try: in_file = open(parsed_args.in_file, "rb") except IOError as e: print("Could not open input file `%s' for reading: %s" % (parsed_args.in_file, e), file=sys.stderr) sys.exit(2) try: out_file = open(parsed_args.out_file, "wb") except IOError as e: print("Could not open output file `%s' for writing: %s" % (parsed_args.out_file, e), file=sys.stderr) sys.exit(3) try: if parsed_args.decompress: data = decompress(in_file) else: data = compress(in_file) except Exception as e: print("Could not compress/decompress file `%s': %s" % (parsed_args.in_file, e), file=sys.stderr) sys.exit(4) try: out_file.write(data) except IOError as e: print("Could not write to output file `%s': %s" % (parsed_args.out_file, e), file=sys.stderr) sys.exit(5) finally: out_file.close()
35.327586
109
0.695705
4a10599c9bd064d5e27114757131f1c9a6619736
543
py
Python
rogal/__main__.py
kosciak/ecs-rogal
d553104e0ea350d11272d274a900419620b9389e
[ "MIT" ]
4
2021-01-23T13:25:46.000Z
2021-03-19T03:08:05.000Z
rogal/__main__.py
kosciak/ecs-rogal
d553104e0ea350d11272d274a900419620b9389e
[ "MIT" ]
null
null
null
rogal/__main__.py
kosciak/ecs-rogal
d553104e0ea350d11272d274a900419620b9389e
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import argparse from . import main if __name__ == "__main__": parser = argparse.ArgumentParser() # parser.add_argument( # 'wrapper', # nargs='?', # choices=sorted(main.WRAPPERS.keys()), # default='tcod', # ) for wrapper in sorted(main.WRAPPERS.keys()): parser.add_argument( f'--{wrapper}', const=wrapper, action='store_const', dest='wrapper', ) args = parser.parse_args() wrapper = args.wrapper or 'tcod' main.run(wrapper)
19.392857
80
0.585635
4a1059fdc99a880d7a8f4ba6f1b8e52c4672c814
1,283
py
Python
imlib/image/objects.py
noisysky/imlib
625193be4a586d9040a48df9d51dbdd3a17c7d06
[ "MIT" ]
null
null
null
imlib/image/objects.py
noisysky/imlib
625193be4a586d9040a48df9d51dbdd3a17c7d06
[ "MIT" ]
6
2020-04-17T12:02:56.000Z
2020-05-12T15:20:18.000Z
imlib/image/objects.py
noisysky/imlib
625193be4a586d9040a48df9d51dbdd3a17c7d06
[ "MIT" ]
4
2020-02-05T18:53:30.000Z
2022-02-21T18:50:14.000Z
import numpy as np from skimage.measure import label def get_largest_non_zero_object(label_image): """ In a labelled (each object assigned an int) numpy array. Return the largest object with a value >= 1. :param label_image: Output of skimage.measure.label :return: Boolean numpy array or largest object """ return label_image == np.argmax(np.bincount(label_image.flat)[1:]) + 1 def keep_n_largest_objects(numpy_array, n=1, connectivity=None): """ Given an input binary numpy array, return a "clean" array with only the n largest connected components remaining Inspired by stackoverflow.com/questions/47540926 TODO: optimise :param numpy_array: Binary numpy array :param n: How many objects to keep :param connectivity: Labelling connectivity (see skimage.measure.label) :return: "Clean" numpy array with n largest objects """ labels = label(numpy_array, connectivity=connectivity) assert labels.max() != 0 # assume at least 1 CC n_largest_objects = get_largest_non_zero_object(labels) if n > 1: i = 1 while i < n: labels[n_largest_objects] = 0 n_largest_objects += get_largest_non_zero_object(labels) i += 1 return n_largest_objects
32.075
75
0.696804
4a105a4c4aaa37aee07d4029794be791db13d82a
3,888
py
Python
Tests/uninitialized_local_variable_rule_test.py
colobot/colobot-lint
30921edb55b49dbda27d645357e24d6d22f5c48f
[ "BSD-3-Clause" ]
7
2015-08-28T14:26:51.000Z
2020-05-18T01:37:27.000Z
Tests/uninitialized_local_variable_rule_test.py
piotrdz/colobot-lint
30921edb55b49dbda27d645357e24d6d22f5c48f
[ "BSD-3-Clause" ]
7
2015-07-31T20:54:10.000Z
2015-08-24T22:26:55.000Z
Tests/uninitialized_local_variable_rule_test.py
piotrdz/colobot-lint
30921edb55b49dbda27d645357e24d6d22f5c48f
[ "BSD-3-Clause" ]
2
2015-09-09T15:11:28.000Z
2018-11-14T20:34:35.000Z
import test_support class UnintializedLocalVariableRuleTest(test_support.TestBase): def setUp(self): self.set_default_rules_selection(['UninitializedLocalVariableRule']) self.set_default_error_id('uninitialized local variable') self.set_default_error_severity('error') def test_function_with_builtin_variables_initialized(self): self.assert_colobot_lint_result( source_file_lines = [ 'void Foo()', '{', ' int x = 0, y = 1;', ' bool z = true;', '}' ], expected_errors = []) def test_function_with_one_builtin_variable_uninitialized(self): self.assert_colobot_lint_result( source_file_lines = [ 'void Foo()', '{', ' int x, y = 1;', ' bool z = true;', '}' ], expected_errors = [ { 'msg': "Local variable 'x' is uninitialized", 'line': '3' } ]) def test_function_with_pod_type_uninitialized(self): self.assert_colobot_lint_result( source_file_lines = [ 'struct Bar { int x; };', 'void Foo()', '{', ' Bar bar;', ' bool z = true;', '}' ], expected_errors = [ { 'msg': "Local variable 'bar' is uninitialized", 'line': '4' } ]) def test_function_with_non_pod_types_uninitialized(self): self.assert_colobot_lint_result( source_file_lines = [ 'struct Baz { int x; Baz() : x(0) {} };', 'struct Bar { int x = 0; };', 'void Foo()', '{', ' Bar bar;', ' Baz baz;', '}' ], expected_errors = []) def test_ignore_function_parameters(self): self.assert_colobot_lint_result( source_file_lines = [ 'void Foo(int x, int y, int z);', 'void Bar(int x, int y, int z) {}', ], expected_errors = []) def test_ignore_pod_types_with_no_data_members(self): self.assert_colobot_lint_result( source_file_lines = [ 'struct PodWithoutData {};', 'struct DerivedPodWithoutData : PodWithoutData {};', '', 'void Foo()', '{', ' PodWithoutData pod1;', ' DerivedPodWithoutData pod2;', '}' ], expected_errors = []) def test_dont_report_uninitialized_variables_in_old_style_functions(self): self.assert_colobot_lint_result( source_file_lines = [ 'void Bar(int &x, int &y, int& z);', 'void Foo()', '{', ' int x, y, z;', ' float a, b, c;', ' const char* str;', '', ' Bar(x, y, z);', ' a = b = c = 10.0f;', ' str = "123";', '}' ], expected_errors = [ { 'id': 'old style function', 'severity': 'warning', 'msg': "Function 'Foo' seems to be written in legacy C style: " + "it has uninitialized POD type variables declared far from their point of use ('x', 'y', 'z', 'a'... and 3 more)", 'line': '2' } ], rules_selection = ['OldStyleFunctionRule', 'UninitializedLocalVariableRule'])
34.40708
141
0.434928
4a105b96ca8818b95ecb626a22f89bf5982988c4
2,079
py
Python
scripts/eval/evaluate_loss.py
galberding/FleckDetect
787a3306261754a15f32e69ca57599f81cb378fa
[ "Apache-2.0" ]
null
null
null
scripts/eval/evaluate_loss.py
galberding/FleckDetect
787a3306261754a15f32e69ca57599f81cb378fa
[ "Apache-2.0" ]
1
2022-03-12T00:10:08.000Z
2022-03-12T00:10:08.000Z
scripts/eval/evaluate_loss.py
galberding/FleckDetect
787a3306261754a15f32e69ca57599f81cb378fa
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python """ Short script used to extract the minimal loss value and plot values from csv files. """ import argparse import sys import numpy as np import matplotlib.pyplot as plt def parse_loss_csv(filename): iterations = [] losses = [] min_loss = sys.maxsize min_index = -1 index = 0 with open(filename, 'r') as lossfile: first_line = True for line in lossfile: if first_line: first_line = False continue iterations.append(float(line[0:12].strip())) losses.append(float(line[12:25].strip())) if losses[index] < min_loss: min_loss = losses[index] min_index = index index += 1 return np.array(iterations), np.array(losses), min_loss, min_index def det_best_model(filelist, vis=False): for filename in filelist: loss_type = filename.replace('loss_', '').replace('.csv', '') iterations, losses, min_loss, min_index = parse_loss_csv(filename) if min_index > -1: print (loss_type, ': lowest loss', min_loss, 'at iteration', iterations[min_index]) if vis: plt.plot(iterations, losses, '-', label=loss_type) else: print (loss_type, ': no lowest loss available!') if vis: plt.legend() plt.show() def main(): # initialize argument parser parser = argparse.ArgumentParser( description='Process a list of loss tables by evaluting the iteration with the lowest loss optionally visualizing them as graphs.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # add arguments parser.add_argument('filelist', nargs='+', help='list of csv files to evaluate') parser.add_argument('-v', '--visual', action='store_true', help='if the losses should be plotted') # parse arguments args = parser.parse_args() det_best_model(args.filelist, vis=args.visual) if __name__ == "__main__": main()
28.479452
139
0.611833
4a105bcaff9650e687a442f45fed5955a561b9e1
5,762
py
Python
xharvest/handlers/main.py
vyscond/py-xharvest
10cb6a78ddd86d2b0cf73f1eaaf47d97e839fbe8
[ "MIT" ]
null
null
null
xharvest/handlers/main.py
vyscond/py-xharvest
10cb6a78ddd86d2b0cf73f1eaaf47d97e839fbe8
[ "MIT" ]
21
2020-04-26T18:22:24.000Z
2020-08-09T23:23:20.000Z
xharvest/handlers/main.py
vyscond/py-xharvest
10cb6a78ddd86d2b0cf73f1eaaf47d97e839fbe8
[ "MIT" ]
null
null
null
from datetime import datetime from gi.repository import Gtk from gi.repository import Gdk from xharvest.data import get_img_path from xharvest.auth import AuthenticationManager from xharvest.threads import GtkThread from xharvest.threads import gtk_thread_cb from xharvest.models import Shortcuts from xharvest.handlers.base import Handler from xharvest.handlers.timeentries import TimeEntriesHandler from xharvest.handlers.week import WeekHandler from xharvest.handlers.main_headerbar import MainHeaderBarHandler from xharvest.handlers.settings import SettingsHandler from xharvest.handlers.timeentry import TimeEntryFormHandler from xharvest.handlers.login import LoginHandler from xharvest.tray import MainAppIndicator class MainWindowHandler(Handler): MASK_BOOTING = Gdk.WindowState.WITHDRAWN | Gdk.WindowState.FOCUSED def bind_data(self): # You need to attach Headerbar before the Window is shown self.get_root_widget().set_titlebar( MainHeaderBarHandler().get_root_widget()) # Most reused Widgets self.spin = self.builder.get_object("spinner") self.box = self.builder.get_object("box") self.vp_week = self.builder.get_object("viewport_week") self.viewport = self.builder.get_object("viewport_time_entries") self.evbox_new_timeentry = self.get_widget("evbox_new_timeentry") # Attaching fixed widgets self.vp_week.add(WeekHandler().get_root_widget()) self.viewport.add(TimeEntriesHandler().get_root_widget()) self.get_root_widget().set_icon_from_file(get_img_path("xharvest.png")) if AuthenticationManager().is_user_authenticated(): self.fetch_base_data() self.app_ind = MainAppIndicator([ ('item', 'Show', self.on_show), ('item', 'Quit', lambda m: Gtk.main_quit()), ]) def bind_signals(self): self.get_root_widget().connect("delete-event", self.on_quit) self.time_entries.connect( "time_entries_were_rendered", lambda gobj: self.spin.stop() ) self.time_entries.connect( "data_update_bgn", lambda gobj: self.spin.start() ) self.auth_flow.connect("user_authenticated", self.on_user_authenticated) self.auth_flow.connect("user_signout", self.on_user_signout) self.bind_accel_groups() def bind_accel_groups(self): self.ag_1 = self.preferences.get_accel_group( Shortcuts.SHOW_TIME_ENTRY_FORM, self.on_show_time_entry_form_kb, ) self.ag_2 = self.preferences.get_accel_group( Shortcuts.SHOW_TODAYS_ENTRIES, self.on_back_to_today_kb, ) # self.ag_3 = self.preferences.get_accel_group( # Shortcuts.SHOW_TIME_SUMMARY, # self.on_show_time_summary_kb, # ) # Re-attaching self.get_root_widget().add_accel_group(self.ag_1) self.get_root_widget().add_accel_group(self.ag_2) # self.get_root_widget().add_accel_group(self.ag_3) # ----------------------------------------------------------------[Helpers] def fetch_base_data(self): ''' Description: Yes. We are blocking on purpose to avoid user trying interacting with some part of the UI and see no reaction. We will slowly move the parts to be more and more asynchronous. ''' self.user.sync_data() self.assignments.sync_data() self.time_entries.emit('data_update_bgn') GtkThread( target=self.time_entries.sync_data, target_cb=gtk_thread_cb( lambda t: self.time_entries.emit('data_update_end') ), ).start() # -------------------------------------------------------[Standard Signals] def on_evbox_new_timeentry_button_press_event(self, ev_box, ev_btn): if self.assignments.data: w = TimeEntryFormHandler().get_root_widget() w.set_relative_to(ev_box) w.popup() def on_evbox_show_settings_button_press_event(self, ev_box, gdk_ev_btn): if self.user.data: w = SettingsHandler().get_root_widget() w.set_relative_to(ev_box) w.show_all() w.popup() # FIXME show/hide is breaking the main window def on_show(self, *args): self.get_root_widget().deiconify() self.get_root_widget().present() def on_quit(self, *args): if self.preferences.get_minimize_to_tray_icon(): self.get_root_widget().hide() return True else: Gtk.main_quit() # ----------------------------------------------------------[Model Signals] def on_show_time_entry_form_kb(self, *args): self.on_evbox_new_timeentry_button_press_event( self.evbox_new_timeentry, None, ) def on_back_to_today_kb(self, *args): self.week.set_selected_date(datetime.now()) self.week.emit("selected_date_changed") self.time_entries.date_obj = self.week.get_selected_date() self.time_entries.emit('data_update_bgn') GtkThread( target=self.time_entries.sync_data, target_cb=gtk_thread_cb( lambda t: self.time_entries.emit('data_update_end') ), ).start() def on_user_authenticated(self, gobj): self.fetch_base_data() self.get_root_widget().show() def on_user_signout(self, gobj): self.get_root_widget().hide() # LoginHandler().get_root_widget().show_all() LoginHandler().get_root_widget().present()
38.15894
80
0.634675
4a105c84c5e46f611ef6884abba0e2b90ba66ef1
5,279
py
Python
src/freemoovr/geometry/rectangle.py
loopbio/FreemooVR
5d22951f869621dda27fb10c501253c02374c3a7
[ "Zlib" ]
1
2021-05-20T06:55:09.000Z
2021-05-20T06:55:09.000Z
src/freemoovr/geometry/rectangle.py
loopbio/FreemooVR
5d22951f869621dda27fb10c501253c02374c3a7
[ "Zlib" ]
3
2016-08-05T12:56:12.000Z
2016-08-09T14:20:09.000Z
src/freemoovr/geometry/rectangle.py
loopbio/FreemooVR
5d22951f869621dda27fb10c501253c02374c3a7
[ "Zlib" ]
null
null
null
from freemoovr.geometry.common import ModelBase, point_dict_to_vec import numpy as np class PlanarRectangle(ModelBase): def __init__(self, lowerleft=None, upperleft=None, lowerright=None): self.left_lower_corner = point_dict_to_vec(lowerleft) self.left_upper_corner = point_dict_to_vec(upperleft) self.right_lower_corner = point_dict_to_vec(lowerright) # keep in sync with DisplaySurfaceGeometry.cpp self._left_lower_corner = np.array((self.left_lower_corner.x, self.left_lower_corner.y, self.left_lower_corner.z), dtype=np.float) self._left_upper_corner = np.array((self.left_upper_corner.x, self.left_upper_corner.y, self.left_upper_corner.z), dtype=np.float) self._right_lower_corner = np.array((self.right_lower_corner.x, self.right_lower_corner.y, self.right_lower_corner.z), dtype=np.float) self._dir_u = self._right_lower_corner - self._left_lower_corner self._dir_v = self._left_upper_corner - self._left_lower_corner self.center_arr = self._left_lower_corner + 0.5 * self._dir_u + 0.5 * self._dir_v self._normal = np.cross(self._dir_u, self._dir_v) super(PlanarRectangle, self).__init__() def __repr__(self): return '<PlanarRectangle(lowerleft=%r,upperleft=%r,lowerright=%r)>' % ( self._left_lower_corner[:, 0].tolist(), self._left_upper_corner[:, 0].tolist(), self._right_lower_corner[:, 0].tolist(), ) def to_geom_dict(self): return dict( lowerleft=self.left_lower_corner.to_dict(), upperleft=self.left_upper_corner.to_dict(), lowerright=self.right_lower_corner.to_dict(), model="planar_rectangle") def texcoord2worldcoord(self, tc): # Parse inputs tc = np.array(tc, copy=False) assert tc.ndim == 2 assert tc.shape[1] == 2 tex_u, tex_v = tc.T # keep in sync with DisplaySurfaceGeometry.cpp result = (self._left_lower_corner[:, np.newaxis] + self._dir_u[:, np.newaxis] * tex_u[np.newaxis] + self._dir_v[:, np.newaxis] * tex_v[np.newaxis]) return result.T def worldcoord2texcoord(self, wc): # Parse inputs wc = np.array(wc, copy=False) assert wc.ndim == 2 assert wc.shape[1] == 3 wc = wc.T x, y, z = wc x0 = x - self.left_lower_corner.x y0 = y - self.left_lower_corner.y z0 = z - self.left_lower_corner.z wc = np.vstack((x0, y0, z0)) u = np.dot(self._dir_u, wc) v = np.dot(self._dir_v, wc) result = np.vstack((u, v)) return result.T def worldcoord2normal(self, wc): wc = np.array(wc, copy=False) assert wc.ndim == 2 assert wc.shape[1] == 3 N = wc.shape[0] one_sz = np.ones((1, N)) bad = np.isnan(wc[:, 0]) result = (self._normal[:, np.newaxis] * one_sz).T result[bad] = np.nan return result def get_relative_distance_to_first_surface(self, a, b): # See ModelBase.get_relative_distance_to_first_surface for docstring a = np.array(a, copy=False) assert a.ndim == 2 assert a.shape[1] == 3 inshape = a.shape b = np.array(b, copy=False) assert b.ndim == 2 assert b.shape[1] == 3 assert b.shape == inshape # See http://en.wikipedia.org/wiki/Line-plane_intersection # especially the "Algebraic form" section. # Create variables according to wikipedia notation linked above l = b - a l0 = a n = self._normal p0 = np.array([self.left_lower_corner.x, self.left_lower_corner.y, self.left_lower_corner.z], dtype=np.float) # Now, do the math... old_settings = np.seterr(invalid='ignore', divide='ignore') # we expect some nans below d = np.dot((p0 - l0), n) / np.dot(l, n) d[np.isinf(d)] = np.nan # don't let infinity in d[d < 0] = np.nan # don't look backwards, either np.seterr(**old_settings) return d get_relative_distance_to_first_surface.__doc__ = ModelBase.get_relative_distance_to_first_surface.__doc__ def get_first_surface(self, a, b): # See ModelBase.get_first_surface for docstring d = self.get_relative_distance_to_first_surface(a, b) a = np.array(a, copy=False) assert a.ndim == 2 assert a.shape[1] == 3 inshape = a.shape b = np.array(b, copy=False) assert b.ndim == 2 assert b.shape[1] == 3 assert b.shape == inshape l = b - a l0 = a d = d[:, np.newaxis] pt = d * l + l0 return pt get_first_surface.__doc__ = ModelBase.get_first_surface.__doc__
36.916084
109
0.562796
4a105c894f01b68f1d2a372c617dc8bd30471954
4,239
py
Python
gcalcli/utils.py
shaicoleman/gcalcli
96f7cf45e4f8180923ec27776e932cba954f08ce
[ "MIT" ]
null
null
null
gcalcli/utils.py
shaicoleman/gcalcli
96f7cf45e4f8180923ec27776e932cba954f08ce
[ "MIT" ]
1
2020-06-18T16:11:47.000Z
2020-06-18T16:11:47.000Z
gcalcli/utils.py
shaicoleman/gcalcli
96f7cf45e4f8180923ec27776e932cba954f08ce
[ "MIT" ]
null
null
null
import calendar import time import locale import re from dateutil.tz import tzlocal from dateutil.parser import parse as dateutil_parse from datetime import datetime, timedelta from parsedatetime.parsedatetime import Calendar locale.setlocale(locale.LC_ALL, '') fuzzy_date_parse = Calendar().parse fuzzy_datetime_parse = Calendar().parseDT REMINDER_REGEX = r'^(\d+)([wdhm]?)(?:\s+(popup|email|sms))?$' DURATION_REGEX = re.compile( r'^((?P<days>[\.\d]+?)(?:d|day|days))?[ :]*' r'((?P<hours>[\.\d]+?)(?:h|hour|hours))?[ :]*' r'((?P<minutes>[\.\d]+?)(?:m|min|mins|minute|minutes))?[ :]*' r'((?P<seconds>[\.\d]+?)(?:s|sec|secs|second|seconds))?$' ) def parse_reminder(rem): match = re.match(REMINDER_REGEX, rem) if not match: # Allow argparse to generate a message when parsing options return None n = int(match.group(1)) t = match.group(2) m = match.group(3) if t == 'w': n = n * 7 * 24 * 60 elif t == 'd': n = n * 24 * 60 elif t == 'h': n = n * 60 if not m: m = 'popup' return n, m def set_locale(new_locale): try: locale.setlocale(locale.LC_ALL, new_locale) except locale.Error as exc: raise ValueError( 'Error: ' + str(exc) + '!\n Check supported locales of your system.\n') def get_times_from_duration(when, duration=0, allday=False): try: start = get_time_from_str(when) except Exception: raise ValueError('Date and time is invalid: %s\n' % (when)) if allday: try: stop = start + timedelta(days=float(duration)) except Exception: raise ValueError( 'Duration time (days) is invalid: %s\n' % (duration)) start = start.date().isoformat() stop = stop.date().isoformat() else: try: stop = start + get_timedelta_from_str(duration) except Exception: raise ValueError( 'Duration time is invalid: %s\n' % (duration)) start = start.isoformat() stop = stop.isoformat() return start, stop def get_time_from_str(when): """Convert a string to a time: first uses the dateutil parser, falls back on fuzzy matching with parsedatetime """ zero_oclock_today = datetime.now(tzlocal()).replace( hour=0, minute=0, second=0, microsecond=0) try: event_time = dateutil_parse(when, default=zero_oclock_today) except ValueError: struct, result = fuzzy_date_parse(when) if not result: raise ValueError('Date and time is invalid: %s' % (when)) event_time = datetime.fromtimestamp(time.mktime(struct), tzlocal()) return event_time def get_timedelta_from_str(delta): """ Parse a time string a timedelta object. Formats: - number -> duration in minutes - "1:10" -> hour and minutes - "1d 1h 1m" -> days, hours, minutes Based on https://stackoverflow.com/a/51916936/12880 """ parsed_delta = None try: parsed_delta = timedelta(minutes=float(delta)) except ValueError: pass if parsed_delta is None: parts = DURATION_REGEX.match(delta) if parts is not None: try: time_params = {name: float(param) for name, param in parts.groupdict().items() if param} parsed_delta = timedelta(**time_params) except ValueError: pass if parsed_delta is None: dt, result = fuzzy_datetime_parse(delta, sourceTime=datetime.min) if result: parsed_delta = dt - datetime.min if parsed_delta is None: raise ValueError('Duration is invalid: %s' % (delta)) return parsed_delta def days_since_epoch(dt): __DAYS_IN_SECONDS__ = 24 * 60 * 60 return calendar.timegm(dt.timetuple()) / __DAYS_IN_SECONDS__ def agenda_time_fmt(dt, military): hour_min_fmt = '%H:%M' if military else '%I:%M' ampm = '' if military else dt.strftime('%p').lower() return dt.strftime(hour_min_fmt).lstrip('0') + ampm
29.034247
77
0.588818
4a105e0ded4ab89c3f6a7f84b1aebaa7b0db390a
2,810
py
Python
docs_src/source/conf.py
seeq12/seeq-udf-ui
96a7151abc46ad18b6faae78be27a420ddbd1a48
[ "Apache-2.0" ]
null
null
null
docs_src/source/conf.py
seeq12/seeq-udf-ui
96a7151abc46ad18b6faae78be27a420ddbd1a48
[ "Apache-2.0" ]
5
2022-03-01T00:32:22.000Z
2022-03-23T21:14:15.000Z
docs_src/source/conf.py
seeq12/seeq-udf-ui
96a7151abc46ad18b6faae78be27a420ddbd1a48
[ "Apache-2.0" ]
null
null
null
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath('../..')) from seeq.addons import udf_ui # -- Project information ----------------------------------------------------- project = 'seeq-udf-ui' copyright = '2022, Seeq Corporation' author = 'Ehsan Shahidi' # The full version, including alpha/beta/rc tags version = udf_ui.__version__ release = udf_ui.__version__ # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.intersphinx', 'sphinx.ext.githubpages', 'sphinx.ext.viewcode', 'myst_parser' ] napoleon_google_docstring = False napoleon_numpy_docstring = True # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. # language = 'python' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # # html_theme = 'sphinxdoc' html_theme = 'sphinx_rtd_theme' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] html_favicon = '_static/seeq-favicon.ico' html_logo = '_static/Seeq_logo_darkBlue_sm.png' # # These paths are either relative to html_static_path # # or fully qualified paths (eg. https://...) # html_css_files = ['css/style.css'] # # html_style = 'css/style.css'
33.452381
79
0.690747
4a105ea1cb5adf3df6c1cfeb86c3bfdae1d17417
1,645
py
Python
panda/models/user_proxy.py
newsapps/panda
7553fd8cbc9c9c92a1b8be2e073141ec1b2ef903
[ "MIT" ]
4
2015-07-28T19:01:03.000Z
2018-12-21T01:57:03.000Z
panda/models/user_proxy.py
NUKnightLab/panda
c8b81151cad9f23ecd439e4354e86cca1eb49bb1
[ "MIT" ]
null
null
null
panda/models/user_proxy.py
NUKnightLab/panda
c8b81151cad9f23ecd439e4354e86cca1eb49bb1
[ "MIT" ]
null
null
null
#!/usr/bin/env python from django.contrib.auth.models import User from django.conf import settings from panda import solr class UserProxy(User): """ User Django's ProxyModel concept to track changes to the User model without overriding it. This way related datasets can be updated when user details change. Inspired by: http://stackoverflow.com/questions/1817244/override-default-user-model-method http://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed """ __original_first_name = None __original_last_name = None __original_email = None class Meta: proxy = True app_label = 'panda' verbose_name = 'User' verbose_name_plural = 'Users' def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.__original_first_name = self.first_name self.__original_last_name = self.last_name self.__original_email = self.email def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) if self.first_name != self.__original_first_name or \ self.last_name != self.__original_last_name or \ self.email != self.__original_email: if self.datasets.count(): for dataset in self.datasets.all(): dataset.update_full_text(commit=False) solr.commit(settings.SOLR_DATASETS_CORE) self.__original_first_name = self.first_name self.__original_last_name = self.last_name self.__original_email = self.email
32.9
106
0.662006
4a105efd8b20263e48319c151d4f0958952d4e34
297
py
Python
accounts/forms.py
arkarhtethan/django-library-management-system
f505b85f9609e62e30d4459f8028a6b5418fbf7d
[ "MIT" ]
1
2022-01-17T06:28:44.000Z
2022-01-17T06:28:44.000Z
accounts/forms.py
arkarhtethan/django-library-management-system
f505b85f9609e62e30d4459f8028a6b5418fbf7d
[ "MIT" ]
10
2020-06-05T22:48:54.000Z
2022-03-11T23:57:22.000Z
accounts/forms.py
arkarhtethan/django-library-management-system
f505b85f9609e62e30d4459f8028a6b5418fbf7d
[ "MIT" ]
1
2020-06-05T11:23:57.000Z
2020-06-05T11:23:57.000Z
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class SignUpForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email', 'password1', 'password2')
22.846154
64
0.713805
4a105f5a34532cf85e46526dddc4b28f3788c7cd
13,663
py
Python
models/egan_model.py
shiming-chen/CDE-GAN
6d67dfee5087fdd91791a33a7f73bb5914678ff0
[ "MIT" ]
9
2020-09-08T07:53:55.000Z
2022-01-17T12:23:59.000Z
models/egan_model.py
shiming-chen/CDE-GAN
6d67dfee5087fdd91791a33a7f73bb5914678ff0
[ "MIT" ]
2
2020-09-08T07:53:03.000Z
2021-03-23T01:29:21.000Z
models/egan_model.py
shiming-chen/CDE-GAN
6d67dfee5087fdd91791a33a7f73bb5914678ff0
[ "MIT" ]
1
2021-12-21T09:04:38.000Z
2021-12-21T09:04:38.000Z
"""Model class template This module provides a template for users to implement custom models. You can specify '--model template' to use this model. The class name should be consistent with both the filename and its model option. The filename should be <model>_dataset.py The class name should be <Model>Dataset.py It implements a simple image-to-image translation baseline based on regression loss. Given input-output pairs (data_A, data_B), it learns a network netG that can minimize the following L1 loss: min_<netG> ||netG(data_A) - data_B||_1 You need to implement the following functions: <modify_commandline_options>: Add model-specific options and rewrite default values for existing options. <__init__>: Initialize this model class. <set_input>: Unpack input data and perform data pre-processing. <forward>: Run forward pass. This will be called by both <optimize_parameters> and <test>. <optimize_parameters>: Update network weights; it will be called in every training iteration. """ import torch import numpy as np from .base_model import BaseModel from . import networks from util.util import prepare_z_y, one_hot, visualize_imgs from torch.distributions import Categorical from collections import OrderedDict from TTUR import fid from util.inception import get_inception_score from inception_pytorch import inception_utils import torch.nn as nn import copy import math import pdb class EGANModel(BaseModel): @staticmethod def modify_commandline_options(parser, is_train=True): """Add new model-specific options and rewrite default values for existing options. Parameters: parser -- the option parser is_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: the modified parser. """ #parser.set_defaults(dataset_mode='aligned') # You can rewrite default values for this model. For example, this model usually uses aligned dataset as its dataset if is_train: parser.add_argument('--g_loss_mode', nargs='*', default=['nsgan','lsgan','vanilla'], help='lsgan | nsgan | vanilla | wgan | hinge | rsgan') parser.add_argument('--d_loss_mode', type=str, default='lsgan', help='lsgan | nsgan | vanilla | wgan | hinge | rsgan') parser.add_argument('--which_D', type=str, default='S', help='Standard(S) | Relativistic_average (Ra)') parser.add_argument('--lambda_f', type=float, default=0.1, help='the hyperparameter that balance Fq and Fd') parser.add_argument('--candi_num', type=int, default=2, help='# of survived candidatures in each evolutinary iteration.') parser.add_argument('--eval_size', type=int, default=64, help='batch size during each evaluation.') return parser def __init__(self, opt): """Initialize this model class. Parameters: opt -- training/test options A few things can be done here. - (required) call the initialization function of BaseModel - define loss function, visualization images, model names, and optimizers """ BaseModel.__init__(self, opt) # call the initialization method of BaseModel self.opt = opt if opt.d_loss_mode == 'wgan' and not opt.use_gp: raise NotImplementedError('using wgan on D must be with use_gp = True.') self.loss_names = ['G_real', 'G_fake', 'D_real', 'D_fake', 'D_gp', 'G', 'D'] self.visual_names = ['real_visual', 'gen_visual'] if self.isTrain: # only defined during training time self.model_names = ['G', 'D'] else: self.model_names = ['G'] if self.opt.cgan: probs = np.ones(self.opt.cat_num)/self.opt.cat_num self.CatDis = Categorical(torch.tensor(probs)) # define networks self.netG = networks.define_G(opt.z_dim, opt.output_nc, opt.ngf, opt.netG, opt.g_norm, opt.cgan, opt.cat_num, not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids) if self.isTrain: # define a discriminator; conditional GANs need to take both input and output images; Therefore, #channels for D is input_nc + output_nc self.netD = networks.define_D(opt.input_nc, opt.ndf, opt.netD, opt.d_norm, opt.cgan, opt.cat_num, opt.init_type, opt.init_gain, self.gpu_ids) if self.isTrain: # only defined during training time # define G mutations self.G_mutations = [] for g_loss in opt.g_loss_mode: self.G_mutations.append(networks.GANLoss(g_loss, 'G', opt.which_D).to(self.device)) # define loss functions self.criterionD = networks.GANLoss(opt.d_loss_mode, 'D', opt.which_D).to(self.device) # initialize optimizers self.optimizer_G = torch.optim.Adam(self.netG.parameters(), lr=opt.lr_g, betas=(opt.beta1, opt.beta2)) self.optimizer_D = torch.optim.Adam(self.netD.parameters(), lr=opt.lr_d, betas=(opt.beta1, opt.beta2)) self.optimizers.append(self.optimizer_G) self.optimizers.append(self.optimizer_D) # Evolutinoary candidatures setting (init) self.G_candis = [] self.optG_candis = [] for i in range(opt.candi_num): self.G_candis.append(copy.deepcopy(self.netG.state_dict())) self.optG_candis.append(copy.deepcopy(self.optimizer_G.state_dict())) # visulize settings self.N =int(np.trunc(np.sqrt(min(opt.batch_size, 64)))) if self.opt.z_type == 'Gaussian': self.z_fixed = torch.randn(self.N*self.N, opt.z_dim, 1, 1, device=self.device) elif self.opt.z_type == 'Uniform': self.z_fixed = torch.rand(self.N*self.N, opt.z_dim, 1, 1, device=self.device)*2. - 1. if self.opt.cgan: yf = self.CatDis.sample([self.N*self.N]) self.y_fixed = one_hot(yf, [self.N*self.N, self.opt.cat_num]) # the # of image for each evluation self.eval_size = max(math.ceil((opt.batch_size * opt.D_iters) / opt.candi_num), opt.eval_size) def set_input(self, input): """input: a dictionary that contains the data itself and its metadata information.""" self.input_imgs = input['image'].to(self.device) if self.opt.cgan: self.input_targets = input['target'].to(self.device) def forward(self, batch_size = None): bs = self.opt.batch_size if batch_size is None else batch_size if self.opt.z_type == 'Gaussian': z = torch.randn(bs, self.opt.z_dim, 1, 1, device=self.device) elif self.opt.z_type == 'Uniform': z = torch.rand(bs, self.opt.z_dim, 1, 1, device=self.device)*2. - 1. # Fake images if not self.opt.cgan: gen_imgs = self.netG(z) y_ = None else: y = self.CatDis.sample([bs]) y_ = one_hot(y, [bs, self.opt.cat_num]) gen_imgs = self.netG(z, self.y_) return gen_imgs, y_ def backward_G(self, criterionG): # pass D if not self.opt.cgan: self.fake_out = self.netD(self.gen_imgs) else: self.fake_out = self.netD(self.gen_imgs, self.y_) self.loss_G_fake, self.loss_G_real = criterionG(self.fake_out, self.real_out) self.loss_G = self.loss_G_fake + self.loss_G_real self.loss_G.backward() def backward_D(self): # pass D if not self.opt.cgan: self.fake_out = self.netD(self.gen_imgs) self.real_out = self.netD(self.real_imgs) else: self.fake_out = self.netD(self.gen_imgs, self.y_) self.real_out = self.netD(self.real_imgs, self.targets) self.loss_D_fake, self.loss_D_real = self.criterionD(self.fake_out, self.real_out) if self.opt.use_gp is True: self.loss_D_gp = networks.cal_gradient_penalty(self.netD, self.real_imgs, self.gen_imgs, self.device, type='mixed', constant=1.0, lambda_gp=10.0)[0] else: self.loss_D_gp = 0. self.loss_D = self.loss_D_fake + self.loss_D_real + self.loss_D_gp self.loss_D.backward() def optimize_parameters(self, iters=None): for i in range(self.opt.D_iters + 1): self.real_imgs = self.input_imgs[i*self.opt.batch_size:(i+1)*self.opt.batch_size,:,:,:] if self.opt.cgan: self.targets = self.input_target[i*self.opt.batch_size:(i+1)*self.opt.batch_size,:] # update G if i == 0: self.Fitness, self.evalimgs, self.evaly, self.sel_mut = self.Evo_G() self.evalimgs = torch.cat(self.evalimgs, dim=0) self.evaly = torch.cat(self.evaly, dim=0) if self.opt.cgan else None shuffle_ids = torch.randperm(self.evalimgs.size()[0]) self.evalimgs = self.evalimgs[shuffle_ids] self.evaly = self.evaly[shuffle_ids] if self.opt.cgan else None # update D else: self.set_requires_grad(self.netD, True) self.optimizer_D.zero_grad() self.gen_imgs = self.evalimgs[(i-1)*self.opt.batch_size: i*self.opt.batch_size].detach() self.y_ = self.evaly[(i-1)*self.opt.batch_size: i*self.opt.batch_size] if self.opt.cgan else None self.backward_D() self.optimizer_D.step() def Evo_G(self): eval_imgs = self.input_imgs[-self.eval_size:,:,:,:] eval_targets = self.input_target[-self.eval_size:,:] if self.opt.cgan else None # define real images pass D self.real_out = self.netD(self.real_imgs) if not self.opt.cgan else self.netD(self.real_imgs, self.targets) F_list = np.zeros(self.opt.candi_num) Fit_list = [] G_list = [] optG_list = [] evalimg_list = [] evaly_list = [] selected_mutation = [] count = 0 # variation-evluation-selection for i in range(self.opt.candi_num): for j, criterionG in enumerate(self.G_mutations): # Variation self.netG.load_state_dict(self.G_candis[i]) self.optimizer_G.load_state_dict(self.optG_candis[i]) self.optimizer_G.zero_grad() self.gen_imgs, self.y_ = self.forward() self.set_requires_grad(self.netD, False) self.backward_G(criterionG) self.optimizer_G.step() # Evaluation with torch.no_grad(): eval_fake_imgs, eval_fake_y = self.forward(batch_size=self.eval_size) Fq, Fd = self.fitness_score(eval_fake_imgs, eval_fake_y, eval_imgs, eval_targets) F = Fq + self.opt.lambda_f * Fd #pdb.set_trace() #print('Fq:',Fq,'Fd:',self.opt.lambda_f*Fd) # Selection if count < self.opt.candi_num: F_list[count] = F Fit_list.append([Fq, Fd, F]) G_list.append(copy.deepcopy(self.netG.state_dict())) optG_list.append(copy.deepcopy(self.optimizer_G.state_dict())) evalimg_list.append(eval_fake_imgs) evaly_list.append(eval_fake_y) selected_mutation.append(self.opt.g_loss_mode[j]) else: fit_com = F - F_list if max(fit_com) > 0: ids_replace = np.where(fit_com==max(fit_com))[0][0] F_list[ids_replace] = F Fit_list[ids_replace] = [Fq, Fd, F] G_list[ids_replace] = copy.deepcopy(self.netG.state_dict()) optG_list[ids_replace] = copy.deepcopy(self.optimizer_G.state_dict()) evalimg_list[ids_replace] = eval_fake_imgs evaly_list[ids_replace] = eval_fake_y selected_mutation[ids_replace] = self.opt.g_loss_mode[j] count += 1 self.G_candis = copy.deepcopy(G_list) self.optG_candis = copy.deepcopy(optG_list) return np.array(Fit_list), evalimg_list, evaly_list, selected_mutation def fitness_score(self, eval_fake_imgs, eval_fake_y, eval_real_imgs, eval_real_y): self.set_requires_grad(self.netD, True) eval_fake = self.netD(eval_fake_imgs) if not self.opt.cgan else self.netD(eval_fake_imgs, eval_fake_y) eval_real = self.netD(eval_real_imgs) if not self.opt.cgan else self.netD(eval_real_imgs, eval_real_y) # Quality fitness score Fq = nn.Sigmoid()(eval_fake).data.mean().cpu().numpy() # Diversity fitness score eval_D_fake, eval_D_real = self.criterionD(eval_fake, eval_real) eval_D = eval_D_fake + eval_D_real gradients = torch.autograd.grad(outputs=eval_D, inputs=self.netD.parameters(), grad_outputs=torch.ones(eval_D.size()).to(self.device), create_graph=True, retain_graph=True, only_inputs=True) with torch.no_grad(): for i, grad in enumerate(gradients): grad = grad.view(-1) allgrad = grad if i == 0 else torch.cat([allgrad,grad]) Fd = -torch.log(torch.norm(allgrad)).data.cpu().numpy() return Fq, Fd
49.147482
170
0.616629
4a105f9a8494e298740f0e1d1c2d8342fb96e1b0
8,647
py
Python
google-cloud-recaptcha_enterprise/synth.py
pradeepbhadani/google-cloud-ruby
765eac0f1a5277cb113293bf2fd271e1495a12f5
[ "Apache-2.0" ]
null
null
null
google-cloud-recaptcha_enterprise/synth.py
pradeepbhadani/google-cloud-ruby
765eac0f1a5277cb113293bf2fd271e1495a12f5
[ "Apache-2.0" ]
null
null
null
google-cloud-recaptcha_enterprise/synth.py
pradeepbhadani/google-cloud-ruby
765eac0f1a5277cb113293bf2fd271e1495a12f5
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This script is used to synthesize generated parts of this library.""" import synthtool as s import synthtool.gcp as gcp import synthtool.languages.ruby as ruby import logging import os import re from subprocess import call logging.basicConfig(level=logging.DEBUG) gapic = gcp.GAPICGenerator() v1beta1_library = gapic.ruby_library( 'recaptchaenterprise', 'v1beta1', artman_output_name='google-cloud-ruby/google-cloud-recaptchaenterprise', config_path='artman_recaptchaenterprise_v1beta1.yaml' ) s.copy(v1beta1_library / 'lib') s.copy(v1beta1_library / 'test') s.copy(v1beta1_library / 'README.md') s.copy(v1beta1_library / 'LICENSE') s.copy(v1beta1_library / '.gitignore') s.copy(v1beta1_library / '.yardopts') s.copy(v1beta1_library / 'google-cloud-recaptcha_enterprise.gemspec', merge=ruby.merge_gemspec) # Copy common templates templates = gcp.CommonTemplates().ruby_library() s.copy(templates) # Update gemspec to reflect Ruby 2.4 ruby.update_gemspec('google-cloud-recaptcha_enterprise.gemspec') # Update README to reflect Ruby 2.4 s.replace( 'README.md', 'Ruby 2.3', 'Ruby 2.4' ) # Support for service_address s.replace( [ 'lib/google/cloud/recaptcha_enterprise.rb', 'lib/google/cloud/recaptcha_enterprise/v*.rb', 'lib/google/cloud/recaptcha_enterprise/v*/*_client.rb' ], '\n(\\s+)#(\\s+)@param exception_transformer', '\n\\1#\\2@param service_address [String]\n' + '\\1#\\2 Override for the service hostname, or `nil` to leave as the default.\n' + '\\1#\\2@param service_port [Integer]\n' + '\\1#\\2 Override for the service port, or `nil` to leave as the default.\n' + '\\1#\\2@param exception_transformer' ) s.replace( [ 'lib/google/cloud/recaptcha_enterprise/v*.rb', 'lib/google/cloud/recaptcha_enterprise/v*/*_client.rb' ], '\n(\\s+)metadata: nil,\n\\s+exception_transformer: nil,\n', '\n\\1metadata: nil,\n\\1service_address: nil,\n\\1service_port: nil,\n\\1exception_transformer: nil,\n' ) s.replace( [ 'lib/google/cloud/recaptcha_enterprise/v*.rb', 'lib/google/cloud/recaptcha_enterprise/v*/*_client.rb' ], ',\n(\\s+)lib_name: lib_name,\n\\s+lib_version: lib_version', ',\n\\1lib_name: lib_name,\n\\1service_address: service_address,\n\\1service_port: service_port,\n\\1lib_version: lib_version' ) s.replace( 'lib/google/cloud/recaptcha_enterprise/v*/*_client.rb', 'service_path = self\\.class::SERVICE_ADDRESS', 'service_path = service_address || self.class::SERVICE_ADDRESS' ) s.replace( 'lib/google/cloud/recaptcha_enterprise/v*/*_client.rb', 'port = self\\.class::DEFAULT_SERVICE_PORT', 'port = service_port || self.class::DEFAULT_SERVICE_PORT' ) # https://github.com/googleapis/gapic-generator/issues/2180 s.replace( 'google-cloud-recaptcha_enterprise.gemspec', '\n gem\\.add_dependency "google-gax", "~> 1\\.[\\d\\.]+"\n\n', '\n gem.add_dependency "google-gax", "~> 1.8"\n gem.add_dependency "grpc-google-iam-v1", "~> 0.6.9"\n\n') # https://github.com/googleapis/gapic-generator/issues/2242 def escape_braces(match): expr = re.compile('^([^`]*(`[^`]*`[^`]*)*)([^`#\\$\\\\])\\{([\\w,]+)\\}') content = match.group(0) while True: content, count = expr.subn('\\1\\3\\\\\\\\{\\4}', content) if count == 0: return content s.replace( 'lib/google/cloud/**/*.rb', '\n(\\s+)#[^\n]*[^\n#\\$\\\\]\\{[\\w,]+\\}', escape_braces) # https://github.com/googleapis/gapic-generator/issues/2243 s.replace( 'lib/google/cloud/recaptcha_enterprise/*/*_client.rb', '(\n\\s+class \\w+Client\n)(\\s+)(attr_reader :\\w+_stub)', '\\1\\2# @private\n\\2\\3') # https://github.com/googleapis/gapic-generator/issues/2279 s.replace( 'lib/**/*.rb', '\\A(((#[^\n]*)?\n)*# (Copyright \\d+|Generated by the protocol buffer compiler)[^\n]+\n(#[^\n]*\n)*\n)([^\n])', '\\1\n\\6') # https://github.com/googleapis/gapic-generator/issues/2323 s.replace( [ 'lib/**/*.rb', 'README.md' ], 'https://github\\.com/GoogleCloudPlatform/google-cloud-ruby', 'https://github.com/googleapis/google-cloud-ruby' ) s.replace( [ 'lib/**/*.rb', 'README.md' ], 'https://googlecloudplatform\\.github\\.io/google-cloud-ruby', 'https://googleapis.github.io/google-cloud-ruby' ) os.rename( 'lib/google/cloud/recaptcha_enterprise/v1beta1/recaptcha_enterprise_service_v1_beta1_client_config.json', 'lib/google/cloud/recaptcha_enterprise/v1beta1/recaptcha_enterprise_client_config.json' ) os.rename( 'lib/google/cloud/recaptcha_enterprise/v1beta1/recaptcha_enterprise_service_v1_beta1_client.rb', 'lib/google/cloud/recaptcha_enterprise/v1beta1/recaptcha_enterprise_client.rb' ) os.rename( 'test/google/cloud/recaptcha_enterprise/v1beta1/recaptcha_enterprise_service_v1_beta1_client_test.rb', 'test/google/cloud/recaptcha_enterprise/v1beta1/recaptcha_enterprise_client_test.rb' ) s.replace( 'lib/**/*.rb', '_service_v1_beta1', '' ) s.replace( 'lib/**/*.rb', 'ServiceV1Beta1', '' ) s.replace( 'lib/**/*.rb', '"google.cloud.recaptchaenterprise.v1beta1.RecaptchaEnterprise"', '"google.cloud.recaptchaenterprise.v1beta1.RecaptchaEnterpriseServiceV1Beta1"' ) s.replace( 'lib/**/credentials.rb', 'RECAPTCHAENTERPRISE_', 'RECAPTCHA_ENTERPRISE_' ) s.replace( 'test/**/*.rb', '_service_v1_beta1', '' ) s.replace( 'test/**/*.rb', 'ServiceV1Beta1', '' ) # Require the helpers file s.replace( f'lib/google/cloud/recaptcha_enterprise/v1beta1.rb', f'require "google/cloud/recaptcha_enterprise/v1beta1/recaptcha_enterprise_client"', '\n'.join([ f'require "google/cloud/recaptcha_enterprise/v1beta1/recaptcha_enterprise_client"', f'require "google/cloud/recaptcha_enterprise/v1beta1/helpers"' ]) ) s.replace( 'google-cloud-recaptcha_enterprise.gemspec', '"README.md", "LICENSE"', '"README.md", "AUTHENTICATION.md", "LICENSE"' ) s.replace( '.yardopts', 'README.md\n', 'README.md\nAUTHENTICATION.md\nLICENSE\n' ) # https://github.com/googleapis/google-cloud-ruby/issues/3058 s.replace( 'google-cloud-recaptcha_enterprise.gemspec', '\nGem::Specification.new do', 'require File.expand_path("../lib/google/cloud/recaptcha_enterprise/version", __FILE__)\n\nGem::Specification.new do' ) s.replace( 'google-cloud-recaptcha_enterprise.gemspec', '(gem.version\s+=\s+).\d+.\d+.\d.*$', '\\1Google::Cloud::RecaptchaEnterprise::VERSION' ) s.replace( 'lib/google/cloud/recaptcha_enterprise/v1beta1/*_client.rb', '(require \".*credentials\"\n)\n', '\\1require "google/cloud/recaptcha_enterprise/version"\n\n' ) s.replace( 'lib/google/cloud/recaptcha_enterprise/v1beta1/*_client.rb', 'Gem.loaded_specs\[.*\]\.version\.version', 'Google::Cloud::RecaptchaEnterprise::VERSION' ) # Fix links for devsite migration for file in ['lib/**/*.rb', '*.md']: s.replace( file, 'https://googleapis.github.io/google-cloud-ruby/#/docs/google-cloud-logging/latest/google/cloud/logging/logger', 'https://googleapis.dev/ruby/google-cloud-logging/latest' ) s.replace( '*.md', 'https://googleapis.github.io/google-cloud-ruby/#/docs/.*/authentication', 'https://googleapis.dev/ruby/google-cloud-recaptcha_enterprise/latest/file.AUTHENTICATION.html' ) s.replace( 'lib/**/*.rb', 'https://googleapis.github.io/google-cloud-ruby/#/docs/.*/authentication', 'https://googleapis.dev/ruby/google-cloud-recaptcha_enterprise/latest/file.AUTHENTICATION.html' ) s.replace( 'README.md', 'github.io/google-cloud-ruby/#/docs/google-cloud-recaptcha_enterprise/latest/.*$', 'dev/ruby/google-cloud-recaptcha_enterprise/latest' ) s.replace( 'README.md', 'https://cloud.google.com/recaptchaenterprise', 'https://cloud.google.com/recaptcha-enterprise' ) # Generate the helper methods call('bundle update && bundle exec rake generate_partials', shell=True)
32.753788
130
0.683821
4a105f9f496ffbbc59e57e75c45afe70028d2868
4,238
py
Python
model/resnet.py
venuc13/CIFARConfidenceSet
f9505d753c77465e005db83600ccc00a996e2930
[ "Apache-2.0" ]
null
null
null
model/resnet.py
venuc13/CIFARConfidenceSet
f9505d753c77465e005db83600ccc00a996e2930
[ "Apache-2.0" ]
null
null
null
model/resnet.py
venuc13/CIFARConfidenceSet
f9505d753c77465e005db83600ccc00a996e2930
[ "Apache-2.0" ]
null
null
null
'''ResNet in PyTorch. For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 ''' import torch import torch.nn as nn import torch.nn.functional as F class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d( in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion*planes: self.shortcut = nn.Sequential( nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(self.expansion*planes) ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) out += self.shortcut(x) out = F.relu(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(self.expansion*planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion*planes: self.shortcut = nn.Sequential( nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(self.expansion*planes) ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = F.relu(self.bn2(self.conv2(out))) out = self.bn3(self.conv3(out)) out += self.shortcut(x) out = F.relu(out) return out class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(ResNet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) self.linear = nn.Linear(512*block.expansion, num_classes) def _make_layer(self, block, planes, num_blocks, stride): strides = [stride] + [1]*(num_blocks-1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion return nn.Sequential(*layers) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.layer1(out) out = self.layer2(out) out = self.layer3(out) out = self.layer4(out) out = F.avg_pool2d(out, 4) out = out.view(out.size(0), -1) out = self.linear(out) return out def resnet18(): return ResNet(BasicBlock, [2, 2, 2, 2]) def resnet34(): return ResNet(BasicBlock, [3, 4, 6, 3]) def resnet50(): return ResNet(Bottleneck, [3, 4, 6, 3]) def resnet101(): return ResNet(Bottleneck, [3, 4, 23, 3]) def resnet152(): return ResNet(Bottleneck, [3, 8, 36, 3])
33.904
84
0.577159
4a1060ac497dceea673991e85b49ec33716319d8
1,689
py
Python
packages/tencent-cloud-sdk-core/tencent/cloud/core/__init__.py
nobody-night/tencent-cloud-sdk-python
4b02c49c587da002c96fff6cadbd0cf6dbae40f9
[ "MIT" ]
3
2020-07-31T13:29:20.000Z
2021-04-07T09:06:39.000Z
packages/tencent-cloud-sdk-core/tencent/cloud/core/__init__.py
nobody-night/tencent-cloud-sdk-python
4b02c49c587da002c96fff6cadbd0cf6dbae40f9
[ "MIT" ]
null
null
null
packages/tencent-cloud-sdk-core/tencent/cloud/core/__init__.py
nobody-night/tencent-cloud-sdk-python
4b02c49c587da002c96fff6cadbd0cf6dbae40f9
[ "MIT" ]
1
2020-02-06T16:54:56.000Z
2020-02-06T16:54:56.000Z
# tencent.cloud.core.__init__ is python-3.6 source file # MIT License # # Copyright (c) 2021 Handle. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ''' This package implements the core functions of the Tencent Cloud SDK. Packages for the Tencent Cloud SDK must rely on the package to operate. Raises: RuntimeError: Current Python runtime version is less than 3.6 ''' import sys # Check if the current Python runtime version is less than 3.6 if sys.version_info.major < 3: raise RuntimeError('runtime version is lower than 3.6') if (sys.version_info.major == 3 and sys.version_info.minor < 6 ): raise RuntimeError('runtime version is lower than 3.6')
38.386364
80
0.762581
4a10613321f7530b95af7ad4035e7d5677eed42a
61,248
py
Python
srctools/dmx.py
TeamSpen210/srctools
0ccea9bc9e00236dd452518af8a7b4ac31e23150
[ "MIT" ]
29
2016-06-12T17:35:50.000Z
2022-03-25T08:37:56.000Z
srctools/dmx.py
TeamSpen210/srctools
0ccea9bc9e00236dd452518af8a7b4ac31e23150
[ "MIT" ]
8
2020-09-22T00:22:35.000Z
2021-12-04T00:53:07.000Z
srctools/dmx.py
TeamSpen210/srctools
0ccea9bc9e00236dd452518af8a7b4ac31e23150
[ "MIT" ]
12
2018-09-03T10:39:46.000Z
2022-01-18T13:21:22.000Z
"""Handles DataModel eXchange trees, in both binary and text (keyvalues2) format. As an extension, optionally all strings may become full UTF-8, marked by a new set of 'unicode_XXX' encoding formats. """ import struct import sys from enum import Enum from typing import ( Union, NamedTuple, TypeVar, Generic, NewType, KeysView, Dict, Tuple, Callable, IO, List, Optional, Type, MutableMapping, Iterator, Set, Mapping, Any, ValuesView, ) from struct import Struct, pack import io import re from uuid import UUID, uuid4 as get_uuid from srctools import binformat, bool_as_int, BOOL_LOOKUP, Matrix, Angle from srctools.tokenizer import Py_Tokenizer as Tokenizer, Token class ValueType(Enum): """The type of value an element has.""" ELEMENT = 'element' # Another attribute INTEGER = INT = 'int' FLOAT = 'float' BOOL = 'bool' STRING = STR = 'string' BINARY = BIN = VOID = 'binary' # IE "void *", binary blob. TIME = 'time' # Seconds COLOR = COLOUR = 'color' VEC2 = 'vector2' VEC3 = 'vector3' VEC4 = 'vector4' ANGLE = 'qangle' QUATERNION = 'quaternion' MATRIX = 'vmatrix' # type -> enum index. VAL_TYPE_TO_IND = { ValueType.ELEMENT: 1, ValueType.INT: 2, ValueType.FLOAT: 3, ValueType.BOOL: 4, ValueType.STRING: 5, ValueType.BINARY: 6, ValueType.TIME: 7, ValueType.COLOR: 8, ValueType.VEC2: 9, ValueType.VEC3: 10, ValueType.VEC4: 11, ValueType.ANGLE: 12, ValueType.QUATERNION: 13, ValueType.MATRIX: 14, } # INT_ARRAY is INT + ARRAY_OFFSET = 15, and so on. ARRAY_OFFSET = 14 IND_TO_VALTYPE = { ind: val_type for val_type, ind in VAL_TYPE_TO_IND.items() } # For parsing, set this initially to check one is set. _UNSET_UUID = get_uuid() _UNSET = object() # Argument sentinel # Element type used to indicate binary "stub" elements... STUB = '<StubElement>' class Vec2(NamedTuple): """A 2-dimensional vector.""" x: float y: float def __repr__(self) -> str: return f'({self[0]:.6g} {self[1]:.6g})' class Vec3(NamedTuple): """A 3-dimensional vector.""" x: float y: float z: float def __repr__(self) -> str: return f'({self[0]:.6g} {self[1]:.6g} {self[2]:.6g})' class Vec4(NamedTuple): """A 4-dimensional vector.""" x: float y: float z: float w: float def __repr__(self) -> str: return f'({self[0]:.6g} {self[1]:.6g} {self[2]:.6g} {self[3]:.6g})' class Quaternion(NamedTuple): """A quaternion used to represent rotations.""" x: float y: float z: float w: float # def __repr__(self) -> str: # return f'({self[0]} {self[1]:.6g} {self[2]:.6g} {self[3]:.6g})' class Color(NamedTuple): """An RGB color.""" r: int g: int b: int a: int def __repr__(self) -> str: return f'{self[0]} {self[1]} {self[2]} {self[3]}' class AngleTup(NamedTuple): """A pitch-yaw-roll angle.""" pitch: float yaw: float roll: float Time = NewType('Time', float) Value = Union[ int, float, bool, str, bytes, Color, Time, Vec2, Vec3, Vec4, AngleTup, Quaternion, Matrix, Optional['Element'], ] ValueT = TypeVar( 'ValueT', int, float, bool, str, bytes, Color, Time, Vec2, Vec3, Vec4, AngleTup, Quaternion, Matrix, Optional['Element'], ) # [from, to] -> conversion. # Implementation at the end of the file. TYPE_CONVERT: Dict[Tuple[ValueType, ValueType], Callable[[Value], Value]] # Take valid types, convert to the value. CONVERSIONS: Dict[ValueType, Callable[[object], Value]] # And type -> size, excluding str/bytes. SIZES: Dict[ValueType, int] def parse_vector(text: str, count: int) -> List[float]: """Parse a space-delimited vector.""" parts = text.split() if len(parts) != count: raise ValueError(f'{text!r} is not a {count}-dimensional vector!') return list(map(float, parts)) def _get_converters() -> Tuple[dict, dict, dict]: type_conv = {} convert = {} sizes = {} ns = globals() def unchanged(x): """No change means no conversion needed.""" return x for from_typ in ValueType: for to_typ in ValueType: if from_typ is to_typ: type_conv[from_typ, to_typ] = unchanged else: func = f'_conv_{from_typ.name.casefold()}_to_{to_typ.name.casefold()}' try: type_conv[from_typ, to_typ] = ns.pop(func) except KeyError: if ( (from_typ is ValueType.STRING or to_typ is ValueType.STRING) and from_typ is not ValueType.ELEMENT and to_typ is not ValueType.ELEMENT ): raise ValueError(func + ' must exist!') # Special cases, variable size. if from_typ is not ValueType.STRING and from_typ is not ValueType.BINARY: sizes[from_typ] = ns['_struct_' + from_typ.name.casefold()].size convert[from_typ] = ns.pop(f'_conv_{from_typ.name.casefold()}') return type_conv, convert, sizes def _make_val_prop(val_type: ValueType, typ: type) -> property: """Build the properties for each type.""" def setter(self, value): self._write_val(val_type, value) def getter(self): return self._read_val(val_type) if val_type.name[0].casefold() in 'aeiou': desc = f'an {val_type.name.lower()}.' else: desc = f'a {val_type.name.lower()}.' getter.__doc__ = 'Return the value as ' + desc setter.__doc__ = 'Convert the value to ' + desc getter.__annotations__['return'] = typ setter.__annotations__['value'] = typ return property( fget=getter, fset=setter, doc='Access the value as ' + desc, ) class _ValProps: """Properties which read/write as the various kinds of value types.""" def _read_val(self, newtype: ValueType) -> Value: """Convert to the desired type.""" raise NotImplementedError def _write_val(self, newtype: ValueType, value: Value) -> None: """Set to the desired type.""" raise NotImplementedError val_int = _make_val_prop(ValueType.INT, int) val_str = val_string = _make_val_prop(ValueType.STRING, str) val_bin = val_binary = val_bytes = _make_val_prop(ValueType.BINARY, bytes) val_float = _make_val_prop(ValueType.FLOAT, float) val_time = _make_val_prop(ValueType.TIME, Time) val_bool = _make_val_prop(ValueType.BOOL, bool) val_colour = val_color = _make_val_prop(ValueType.COLOR, Color) val_vec2 = _make_val_prop(ValueType.VEC2, Vec2) val_vec3 = _make_val_prop(ValueType.VEC3, Vec3) val_vec4 = _make_val_prop(ValueType.VEC4, Vec4) val_quat = val_quaternion = _make_val_prop(ValueType.QUATERNION, Quaternion) val_ang = val_angle = _make_val_prop(ValueType.ANGLE, AngleTup) val_mat = val_matrix = _make_val_prop(ValueType.MATRIX, Matrix) val_compound = val_elem = val = _make_val_prop(ValueType.ELEMENT, Optional['Element']) del _make_val_prop # Uses private parts of Attribute only. # noinspection PyProtectedMember class AttrMember(_ValProps): """A proxy for individual indexes/keys, allowing having .val attributes.""" def __init__(self, owner, index) -> None: """Internal use only.""" self.owner = owner self.index = index def _read_val(self, newtype: ValueType) -> Value: if isinstance(self.owner._value, (list, dict)): value = self.owner._value[self.index] else: value = self.owner._value try: func = TYPE_CONVERT[self.owner._typ, newtype] except KeyError: raise ValueError(f'Cannot convert ({value}) to {newtype} type!') return func(value) def _write_val(self, newtype: ValueType, value: object) -> None: if newtype != self.owner._typ: raise ValueError('Cannot change type of array.') convert = CONVERSIONS[newtype](value) if isinstance(self.owner._value, (list, dict)): self.owner._value[self.index] = convert else: self.owner._value = convert class Attribute(Generic[ValueT], _ValProps): """A single attribute of an element.""" __slots__ = ['name', '_typ', '_value'] name: str _typ: ValueType _value: Union[ValueT, List[ValueT]] def __init__(self, name, type, value) -> None: """For internal use only.""" self.name = name self._typ = type self._value = value @property def type(self) -> ValueType: """Return the current type of the attribute.""" return self._typ @property def is_array(self) -> bool: """Check if this is an array, or a singular value.""" return isinstance(self._value, list) @classmethod def array(cls, name, val_type) -> 'Attribute': """Create an attribute with an array of a specified type.""" return Attribute(name, val_type, []) @classmethod def int(cls, name, value) -> 'Attribute[int]': """Create an attribute with an integer value.""" return Attribute(name, ValueType.INT, value) @classmethod def float(cls, name, value) -> 'Attribute[float]': """Create an attribute with a float value.""" return Attribute(name, ValueType.FLOAT, value) @classmethod def time(cls, name, value) -> 'Attribute[Time]': """Create an attribute with a 'time' value. This is effectively a float, and only available in binary v3+.""" return Attribute(name, ValueType.TIME, Time(value)) @classmethod def bool(cls, name, value) -> 'Attribute[bool]': """Create an attribute with a boolean value.""" return Attribute(name, ValueType.BOOL, value) @classmethod def string(cls, name, value) -> 'Attribute[str]': """Create an attribute with a string value.""" return Attribute(name, ValueType.STRING, value) @classmethod def binary(cls, name, value) -> 'Attribute[bytes]': """Create an attribute with binary data.""" return Attribute(name, ValueType.BINARY, value) @classmethod def vec2(cls, name, x=0.0, y=0.0) -> 'Attribute[Vec2]': """Create an attribute with a 2D vector.""" if isinstance(x, (int, float)): x_ = float(x) else: it = iter(x) x_ = float(next(it, 0.0)) y = float(next(it, y)) return Attribute(name, ValueType.VEC2, Vec2(x_, y)) @classmethod def vec3(cls, name, x=0.0, y=0.0, z=0.0) -> 'Attribute[Vec3]': """Create an attribute with a 3D vector.""" if isinstance(x, (int, float)): x_ = float(x) else: it = iter(x) x_ = float(next(it, 0.0)) y = float(next(it, y)) z = float(next(it, z)) return Attribute(name, ValueType.VEC3, Vec3(x_, y, z)) @classmethod def vec4(cls, name, x=0.0, y=0.0, z=0.0, w=0.0) -> 'Attribute[Vec4]': """Create an attribute with a 4D vector.""" if isinstance(x, (int, float)): x_ = float(x) else: it = iter(x) x_ = float(next(it, 0.0)) y = float(next(it, y)) z = float(next(it, z)) w = float(next(it, w)) return Attribute(name, ValueType.VEC4, Vec4(x_, y, z, w)) @classmethod def color(cls, name, r=0, g=0, b=0, a=255) -> 'Attribute[Color]': """Create an attribute with a color.""" if isinstance(r, int): r_ = r else: it = iter(r) r_ = int(next(it, 0)) g = int(next(it, g)) b = int(next(it, b)) a = int(next(it, a)) return Attribute(name, ValueType.COLOR, Color(r_, g, b, a)) @classmethod def angle(cls, name, pitch=0.0, yaw=0.0, roll=0.0) -> 'Attribute[AngleTup]': """Create an attribute with an Euler angle.""" if isinstance(pitch, (int, float)): pitch_ = float(pitch) else: it = iter(pitch) pitch_ = float(next(it, 0.0)) yaw = float(next(it, yaw)) roll = float(next(it, roll)) return Attribute(name, ValueType.ANGLE, AngleTup(pitch_, yaw, roll)) @classmethod def quaternion(cls, name: str, x=0.0, y=0.0, z=0.0, w=1.0) -> 'Attribute[Quaternion]': """Create an attribute with a quaternion rotation.""" if isinstance(x, (int, float)): x_ = float(x) else: it = iter(x) x_ = float(next(it, 0.0)) y = float(next(it, y)) z = float(next(it, z)) w = float(next(it, w)) return Attribute(name, ValueType.QUATERNION, Quaternion(x_, y, z, w)) def _read_val(self, newtype: ValueType) -> Value: """Convert to the desired type.""" if isinstance(self._value, list): raise ValueError('Cannot read value of array elements!') if isinstance(self._value, dict): raise ValueError('Cannot read value of compound elements!') try: func = TYPE_CONVERT[self._typ, newtype] except KeyError: raise ValueError( f'Cannot convert ({self._value!r}) to {newtype} type!') return func(self._value) def _write_val(self, newtype: ValueType, value: Value) -> None: """Change the type of the atribute.""" self._typ = newtype self._value = CONVERSIONS[newtype](value) # type: ignore # This changes the generic... def __repr__(self) -> str: return f'<{self._typ.name} Attr {self.name!r}: {self._value!r}>' def __getitem__(self, item): """Read values in an array element.""" if not isinstance(self._value, list): raise ValueError('Cannot index singular elements.') _ = self._value[item] # Raise IndexError/KeyError if not present. return AttrMember(self, item) def __setitem__(self, ind, value): """Set a specific array element to a value.""" if not isinstance(self._value, list): raise ValueError('Cannot index singular elements.') [val_type, result] = deduce_type_single(value) if val_type is not self._typ: # Try converting. try: func = TYPE_CONVERT[self._typ, val_type] except KeyError: raise ValueError( f'Cannot convert ({val_type}) to {self._typ} type!') self._value[ind] = func(result) else: self._value[ind] = result def __delitem__(self, item): """Remove the specified array index.""" if not isinstance(self._value, list): raise ValueError('Cannot index singular elements.') del self._value[item] def __len__(self): """Return the number of values in the array, if this is one.""" if isinstance(self._value, list): return len(self._value) raise ValueError('Singular elements have no length!') def __iter__(self): """Yield each of the elements in an array.""" if isinstance(self._value, list): return iter(self._value) else: return iter((self._value, )) def append(self, value) -> None: """Append an item to the array. If not already an array, it is converted to one holding the existing value. """ if not isinstance(self._value, list): self._value = [self._value] [val_type, result] = deduce_type_single(value) if val_type is not self._typ: # Try converting. try: func = TYPE_CONVERT[self._typ, val_type] except KeyError: raise ValueError( f'Cannot convert ({val_type}) to {self._typ} type!') self._value.append(func(result)) else: self._value.append(result) class Element(MutableMapping[str, Attribute]): """An element in a DMX tree.""" __slots__ = ['type', 'name', 'uuid', '_members'] name: str type: str uuid: UUID _members: Dict[str, Attribute] def __init__(self, name: str, type: str, uuid: UUID=None) -> None: self.name = name self.type = type self._members = {} if uuid is None: self.uuid = get_uuid() else: self.uuid = uuid @classmethod def parse(cls, file: IO[bytes], unicode=False) -> Tuple['Element', str, int]: """Parse a DMX file encoded in binary or KV2 (text). The return value is the tree, format name and version. If unicode is set to True, strings will be treated as UTF8 instead of safe ASCII. """ # The format header is: # <!-- dmx encoding [encoding] [version] format [format] [version] --> header = bytearray(file.read(4)) if header != b'<!--': raise ValueError('The file is not a DMX file.') # Read until the -->, or we arbitrarily hit 1kb (assume it's corrupt) for i in range(1024): header.extend(file.read(1)) if header.endswith(b'-->'): break else: raise ValueError('Unterminated DMX heading comment!') match = re.match( br'<!--\s*dmx\s+encoding\s+(unicode_)?(\S+)\s+([0-9]+)\s+' br'format\s+(\S+)\s+([0-9]+)\s*-->', header, ) if match is not None: unicode_flag, enc_name, enc_vers_by, fmt_name_by, fmt_vers_by = match.groups() if unicode_flag: unicode = True enc_vers = int(enc_vers_by.decode('ascii')) fmt_name = fmt_name_by.decode('ascii') fmt_vers = int(fmt_vers_by.decode('ascii')) else: # Try a "legacy" header, no version. match = re.match(br'<!--\s*DMXVersion\s+([a-z0-9]+)_v[a-z0-9]*\s*-->', header) if match is None: raise ValueError(f'Invalid DMX header {bytes(header)!r}!') enc_name = match.group(0) if enc_name == b'sfm': enc_name = b'binary' unicode = False enc_vers = 0 fmt_name = '' fmt_vers = 0 if enc_name == b'keyvalues2': result = cls.parse_kv2( io.TextIOWrapper(file, encoding='utf8' if unicode else 'ascii'), enc_vers, ) elif enc_name == b'binary': result = cls.parse_bin(file, enc_vers, unicode) else: raise ValueError(f'Unknown DMX encoding {repr(enc_name)[2:-1]}!') return result, fmt_name, fmt_vers @classmethod def parse_bin(cls, file, version, unicode=False): """Parse the core binary data in a DMX file. The <!-- --> format comment line should have already be read. If unicode is set to True, strings will be treated as UTF8 instead of safe ASCII. """ # There should be a newline and null byte after the comment. newline = file.read(2) if newline != b'\n\0': raise ValueError('No newline after comment!') encoding = 'utf8' if unicode else 'ascii' # First, we read the string "dictionary". if version >= 5: stringdb_size = stringdb_ind = '<i' elif version >= 4: stringdb_size = '<i' stringdb_ind = '<h' elif version >= 2: stringdb_size = stringdb_ind = '<h' else: stringdb_size = stringdb_ind = None if stringdb_size is not None: [string_count] = binformat.struct_read(stringdb_size, file) stringdb = binformat.read_nullstr_array(file, string_count, encoding) else: stringdb = None stubs: Dict[UUID, Element] = {} [element_count] = binformat.struct_read('<i', file) elements: List[Element] = [None] * element_count for i in range(element_count): if stringdb is not None: [ind] = binformat.struct_read(stringdb_ind, file) el_type = stringdb[ind] else: el_type = binformat.read_nullstr(file) if version >= 4: [ind] = binformat.struct_read(stringdb_ind, file) name = stringdb[ind] else: name = binformat.read_nullstr(file, encoding=encoding) uuid = UUID(bytes_le=file.read(16)) elements[i] = Element(name, el_type, uuid) # Now, the attributes in the elements. for i in range(element_count): elem = elements[i] [attr_count] = binformat.struct_read('<i', file) for attr_i in range(attr_count): if stringdb is not None: [ind] = binformat.struct_read(stringdb_ind, file) name = stringdb[ind] else: name = binformat.read_nullstr(file, encoding=encoding) [attr_type_data] = binformat.struct_read('<B', file) array_size: Optional[int] if attr_type_data >= ARRAY_OFFSET: attr_type_data -= ARRAY_OFFSET [array_size] = binformat.struct_read('<i', file) else: array_size = None attr_type = IND_TO_VALTYPE[attr_type_data] if attr_type is ValueType.TIME and version < 3: # It's elementid in these versions ??? raise ValueError('Time attribute added in version 3!') elif attr_type is ValueType.ELEMENT: if array_size is not None: array = [] attr = Attribute(name, attr_type, array) for _ in range(array_size): [ind] = binformat.struct_read('<i', file) if ind == -1: child_elem = None elif ind == -2: # Stub element, just with a UUID. [uuid_str] = binformat.read_nullstr(file) uuid = UUID(uuid_str) try: child_elem = stubs[uuid] except KeyError: child_elem = stubs[uuid] = Element('', 'StubElement', uuid) else: child_elem = elements[ind] array.append(child_elem) else: [ind] = binformat.struct_read('<i', file) if ind == -1: child_elem = None elif ind == -2: # Stub element, just with a UUID. [uuid_str] = binformat.read_nullstr(file) uuid = UUID(uuid_str) try: child_elem = stubs[uuid] except KeyError: child_elem = stubs[uuid] = Element('', 'StubElement', uuid) else: child_elem = elements[ind] attr = Attribute(name, ValueType.ELEMENT, child_elem) elif attr_type is ValueType.STRING: if array_size is not None: # Arrays are always raw ASCII in the file. attr = Attribute( name, attr_type, binformat.read_nullstr_array(file, array_size), ) else: # Single string. if stringdb is not None and version >= 4: [ind] = binformat.struct_read(stringdb_ind, file) value = stringdb[ind] else: # Raw value. value = binformat.read_nullstr(file, encoding=encoding) attr = Attribute(name, attr_type, value) elif attr_type is ValueType.BINARY: # Binary blobs. if array_size is not None: array = [] attr = Attribute(name, attr_type, array) for _ in range(array_size): [size] = binformat.struct_read('<i', file) array.append(file.read(size)) else: [size] = binformat.struct_read('<i', file) attr = Attribute(name, attr_type, file.read(size)) else: # All other types are fixed-length. size = SIZES[attr_type] conv = TYPE_CONVERT[ValueType.BINARY, attr_type] if array_size is not None: attr = Attribute(name, attr_type, [ conv(file.read(size)) for _ in range(array_size) ]) else: attr = Attribute(name, attr_type, conv(file.read(size))) elem._members[name.casefold()] = attr return elements[0] @classmethod def parse_kv2(cls, file, version): """Parse a DMX file encoded in KeyValues2. The <!-- --> format comment line should have already be read. """ # We apply UUID lookups after everything's parsed. id_to_elem: Dict[UUID, Element] = {} # Locations in arrays which are UUIDs (and need setting). # This is a (attr, index, uuid, line_num) tuple. fixups: List[Tuple[Attribute, Optional[int], UUID, int]] = [] elements = [] tok = Tokenizer(file) for token, tok_value in tok: if token is Token.STRING: elem_name = tok_value elif token is Token.NEWLINE: continue else: raise tok.error(token) elements.append(cls._parse_kv2_element(tok, id_to_elem, fixups, '', elem_name)) for attr, index, uuid, line_num in fixups: try: elem = id_to_elem[uuid] except KeyError: tok.line_num = line_num raise tok.error('UUID {} not found!', uuid) if index is None: attr._value = elem else: attr._value[index] = elem return elements[0] @classmethod def _parse_kv2_element(cls, tok, id_to_elem, fixups, name, typ_name): """Parse a compound element.""" elem: Element = cls(name, typ_name, _UNSET_UUID) for attr_name in tok.block(name): orig_typ_name = tok.expect(Token.STRING) typ_name = orig_typ_name.casefold() # The UUID is a special element name/type combo. if attr_name == 'id': if typ_name != 'elementid': raise tok.error( 'Element ID attribute must be ' '"elementid" type, not "{}"!', typ_name ) uuid_str = tok.expect(Token.STRING) if elem.uuid is not _UNSET_UUID: raise tok.error('Duplicate UUID definition!') try: elem.uuid = UUID(uuid_str) except ValueError: raise tok.error('Invalid UUID "{}"!', uuid_str) id_to_elem[elem.uuid] = elem continue elif attr_name == 'name': # This is also special. if typ_name != 'string': raise tok.error( 'Element name attribute must be ' '"string" type, not "{}"!', typ_name ) elem.name = tok.expect(Token.STRING) continue if typ_name.endswith('_array'): is_array = True typ_name = typ_name[:-6] else: is_array = False try: attr_type = ValueType(typ_name) except ValueError: # It's an inline compound element. elem._members[attr_name.casefold()] = Attribute( attr_name, ValueType.ELEMENT, cls._parse_kv2_element(tok, id_to_elem, fixups, attr_name, orig_typ_name), ) continue if is_array: array = [] attr = Attribute(attr_name, attr_type, array) tok.expect(Token.BRACK_OPEN) for tok_typ, tok_value in tok: if tok_typ is Token.BRACK_CLOSE: break elif tok_typ is Token.STRING: if attr_type is ValueType.ELEMENT: if tok_value == 'element': # UUID reference. uuid_str = tok.expect(Token.STRING) if uuid_str: try: uuid = UUID(uuid_str) except ValueError: raise tok.error('Invalid UUID "{}"!', uuid_str) fixups.append((attr, len(array), uuid, tok.line_num)) # If UUID is present, this None will be # overwritten after. Otherwise, this stays None. array.append(None) else: # Inline compound array.append(cls._parse_kv2_element(tok, id_to_elem, fixups, attr_name, tok_value)) else: # Other value try: array.append(TYPE_CONVERT[ValueType.STRING, attr_type](tok_value)) except ValueError: raise tok.error('"{}" is not a valid {}!', tok_value, attr_type.name) # Skip over the trailing comma if present. next_tok, tok_value = tok() while next_tok is Token.NEWLINE: next_tok, tok_value = tok() if next_tok is not Token.COMMA: tok.push_back(next_tok, tok_value) elif tok_typ is not Token.NEWLINE: raise tok.error(tok_typ) else: raise tok.error('Unterminated array!') elif attr_type is ValueType.ELEMENT: # This is a reference to another element. uuid_str = tok.expect(Token.STRING) attr = Attribute(attr_name, attr_type, None) if uuid_str: try: uuid = UUID(uuid_str) except ValueError: raise tok.error('Invalid UUID "{}"!', uuid_str) fixups.append((attr, None, uuid, tok.line_num)) # If UUID is present, the None value will be overwritten after. # Otherwise, this stays None. else: # Single element. unparsed = tok.expect(Token.STRING) value = TYPE_CONVERT[ValueType.STRING, attr_type](unparsed) attr = Attribute(attr_name, attr_type, value) elem._members[attr_name.casefold()] = attr if elem.uuid is _UNSET_UUID: # No UUID set, just generate one. elem.uuid = get_uuid() return elem def export_binary( self, file: IO[bytes], version: int = 5, fmt_name: str = 'dmx', fmt_ver: int = 1, unicode: str='ascii', ) -> None: """Write out a DMX tree, using the binary format. The version must be a number from 0-5. The format name and version can be anything, to indicate which application should read the file. Unicode controls whether Unicode characters are permitted: - 'ascii' (the default) raises an error if any value is non-ASCII. This ensures no encoding issues occur when read by the game. - 'format' changes the encoding format to 'unicode_binary', allowing the file to be rejected if the game tries to read it and this module's parser to automatically switch to Unicode. - 'silent' outputs UTF8 without any marker, meaning it could be parsed incorrectly by the game or other utilties. This must be parsed with unicode=True to succeed. """ if not (0 <= version <= 5): raise ValueError(f'Invalid version: {version} is not within range 0-5!') # Write the header, and determine which string DB variant to use. if version == 0: # "legacy" header. file.write( b'<!-- DMXVersion %b_v2 -->\n\0' % (fmt_name.encode('ascii'), ) ) else: file.write(b'<!-- dmx encoding %sbinary %i format %b %i -->\n\0' % ( b'unicode_' if unicode == 'format' else b'', version, fmt_name.encode('ascii'), fmt_ver, )) if version >= 5: stringdb_size = stringdb_ind = '<i' elif version >= 4: stringdb_size = '<i' stringdb_ind = '<h' elif version >= 2: stringdb_size = stringdb_ind = '<h' else: stringdb_size = stringdb_ind = None encoding = 'utf8' if unicode != 'ascii' else 'ascii' # First, iterate the tree to collect the elements, and strings (v2+). elements: List[Element] = [self] elem_to_ind: Dict[UUID, int] = {self.uuid: 0} # Valve "bug" - the name attribute is in the database, despite having a # special location in the file format. used_strings: Set[str] = {"name"} # Use the fact that list iteration will continue through appended # items. for elem in elements: if stringdb_ind is not None: used_strings.add(elem.type) if version >= 4: used_strings.add(elem.name) for attr in elem.values(): if stringdb_ind is not None: used_strings.add(attr.name) if attr.type is ValueType.TIME and version < 3: raise ValueError('TIME attributes are not permitted before binary v3!') elif attr.type is ValueType.ELEMENT: for subelem in attr: if subelem is not None and subelem.type != STUB and subelem.uuid not in elem_to_ind: elem_to_ind[subelem.uuid] = len(elements) elements.append(subelem) # Only non-array strings get added to the DB. elif version >= 4 and attr.type is ValueType.STRING and not attr.is_array: used_strings.add(attr.val_str) string_list = sorted(used_strings) string_to_ind = { text: ind for ind, text in enumerate(string_list) } if stringdb_size is not None: file.write(pack(stringdb_size, len(string_list))) for text in string_list: file.write(text.encode(encoding) + b'\0') file.write(pack('<i', len(elements))) for elem in elements: if stringdb_ind is not None: file.write(pack(stringdb_ind, string_to_ind[elem.type])) else: file.write(elem.type.encode(encoding) + b'\0') if version >= 4: file.write(pack(stringdb_ind, string_to_ind[elem.name])) else: file.write(elem.name.encode(encoding) + b'\0') file.write(elem.uuid.bytes_le) # Now, write out all attributes. for elem in elements: file.write(pack('<i', len(elem))) for attr in elem.values(): if stringdb_ind is not None: file.write(pack(stringdb_ind, string_to_ind[attr.name])) else: file.write(attr.name.encode(encoding) + b'\0') typ_ind = VAL_TYPE_TO_IND[attr.type] if attr.is_array: typ_ind += ARRAY_OFFSET file.write(pack('B', typ_ind)) if attr.is_array: file.write(pack('<i', len(attr))) if attr.type is ValueType.STRING: # Scalar strings after v4 use the DB. if version >= 4 and not attr.is_array: file.write(pack(stringdb_ind, string_to_ind[attr.val_str])) else: for text in attr: file.write(text.encode(encoding) + b'\0') elif attr.type is ValueType.BINARY: for data in attr: file.write(pack('<i', len(data))) file.write(data) elif attr.type is ValueType.ELEMENT: for subelem in attr: if subelem is None: elm_ind = -1 file.write(pack('<i', -1)) elif subelem.type == STUB: elm_ind = -2 file.write(pack('<i', -2)) else: file.write(pack('<i', elem_to_ind[subelem.uuid])) else: conv_func = TYPE_CONVERT[attr.type, ValueType.BINARY] for any_data in attr: try: file.write(conv_func(any_data)) except struct.error: raise ValueError(f'Cannot convert {attr.type}({any_data}) to binary!') def export_kv2( self, file: IO[bytes], fmt_name: str = 'dmx', fmt_ver: int = 1, *, flat: bool = False, unicode: str='ascii', cull_uuid: bool = False, ) -> None: """Write out a DMX tree, using the text-based KeyValues2 format. The format name and version can be anything, to indicate which application should read the file. * If flat is enabled, elements will all be placed at the toplevel, so they don't nest inside each other. * If cull_uuid is enabled, UUIDs are only written for self-referential elements. When parsed by this or Valve's parser, new ones will simply be generated. * unicode controls whether Unicode characters are permitted: - 'ascii' (the default) raises an error if any value is non-ASCII. This ensures no encoding issues occur when read by the game. - 'format' changes the encoding format to 'unicode_keyvalues2', allowing the file to be rejected if the game tries to read it and this module's parser to automatically switch to Unicode. - 'silent' outputs UTF8 without any marker, meaning it could be parsed incorrectly by the game or other utilties. This must be parsed with unicode=True to succeed. """ file.write(b'<!-- dmx encoding %skeyvalues2 1 format %b %i -->\r\n' % ( b'unicode_' if unicode == 'format' else b'', fmt_name.encode('ascii'), fmt_ver, )) # First, iterate through to find all "root" elements. # Those are added with UUIDS, and are put at the end of the file. # If `flat` is enabled, all elements are like that. Otherwise, # it's only self and any used multiple times. elements: List[Element] = [self] use_count: Dict[UUID, int] = {self.uuid: 1} # Use the fact that list iteration will continue through appended items. for elem in elements: for attr in elem.values(): if attr.type is not ValueType.ELEMENT: continue for subelem in attr: if subelem is None or subelem.type == STUB: continue if subelem.uuid not in use_count: use_count[subelem.uuid] = 1 elements.append(subelem) else: use_count[subelem.uuid] += 1 if flat: roots = set(use_count) else: roots = {uuid for uuid, count in use_count.items() if count > 1} # We're always a root! roots.add(self.uuid) encoding = 'utf8' if unicode != 'ascii' else 'ascii' for elem in elements: if flat or elem.uuid in roots: if elem is not self: file.write(b'\r\n') elem._export_kv2(file, b'', roots, encoding, cull_uuid) file.write(b'\r\n') def _export_kv2( self, file: IO[bytes], indent: bytes, roots: Set[UUID], encoding: str, cull_uuid: bool, ) -> None: """Export a single element to the file. @param indent: The tabs to prepend each line with. @param roots: The set of all elements exported at toplevel, and so needs to be referenced by UUID instead of inline. """ indent_child = indent + b'\t' file.write(b'"%b"\r\n%b{\r\n' % (self.type.encode('ascii'), indent)) if not cull_uuid or self.uuid in roots: file.write(b'%b"id" "elementid" "%b"\r\n' % (indent_child, str(self.uuid).encode('ascii'))) file.write(b'%b"name" "string" "%b"\r\n' % (indent_child, self.name.encode(encoding))) for attr in self.values(): file.write(b'%b"%b" ' % ( indent_child, attr.name.encode(encoding), )) if attr.is_array: file.write(b'"%b_array"\r\n%b[\r\n' % (attr.type.value.encode(encoding), indent_child)) indent_arr = indent + b'\t\t' for i, child in enumerate(attr): file.write(indent_arr) if isinstance(child, Element): if child.uuid in roots: file.write(b'"element" "%b"' % str(child.uuid).encode('ascii')) else: child._export_kv2(file, indent_arr, roots, encoding, cull_uuid) else: str_value = TYPE_CONVERT[attr.type, ValueType.STRING](child).encode(encoding) file.write(b'"%b"' % (str_value, )) if i == len(attr) - 1: file.write(b'\r\n') else: file.write(b',\r\n') file.write(b'%b]\r\n' % (indent_child, )) elif isinstance(attr._value, Element): if attr.val_elem.uuid in roots: file.write(b'"element" "%b"\r\n' % str(attr.val_elem.uuid).encode('ascii')) else: attr.val_elem._export_kv2(file, indent_child, roots, encoding, cull_uuid) file.write(b'\r\n') else: file.write(b'"%b" "%b"\r\n' % ( attr.type.value.encode(encoding), attr.val_str.encode(encoding), )) file.write(indent + b'}') def __repr__(self) -> str: if self.type and self.name: return f'<{self.type}({self.name!r}): {self._members!r}>' elif self.name: return f'<Element {self.name!r}: {self._members!r}>' else: return f'<Element: {self._members!r}>' def __len__(self) -> int: return len(self._members) def __iter__(self) -> Iterator[str]: return iter(self._members.keys()) def keys(self) -> KeysView[str]: """Return a view of the valid (casefolded) keys for this element.""" return self._members.keys() def values(self) -> ValuesView[Attribute]: """Return a view of the attributes for this element.""" return self._members.values() def __getitem__(self, name: str) -> Attribute: return self._members[name.casefold()] def __delitem__(self, name: str) -> None: """Remove the specified attribute.""" del self._members[name.casefold()] def __setitem__(self, name: str, value: Union[Attribute, ValueT]) -> None: """Set a specific value, by deducing the type. This means this cannot produce certain types like Time. Use an Attribute constructor for that, or set the val_* property of an existing attribute. """ if isinstance(value, Attribute): value.name = name self._members[name.casefold()] = value return val_type, result = deduce_type(value) self._members[name.casefold()] = Attribute(name, val_type, result) def clear(self) -> None: """Remove all attributes from the element.""" self._members.clear() def pop(self, name: str, default: Union[Attribute, Value, object] = _UNSET) -> Attribute: """Remove the specified attribute and return it. If not found, an attribute is created from the default if specified, or KeyError is raised otherwise. """ key = name.casefold() try: attr = self._members.pop(key) except KeyError: if default is _UNSET: raise if isinstance(default, Attribute): return default else: typ, val = deduce_type(default) return Attribute(name, typ, val) else: return attr def popitem(self) -> Tuple[str, Attribute]: """Remove and return a (name, attr) pair as a 2-tuple, or raise KeyError.""" key, attr = self._members.popitem() return (attr.name, attr) def update(*args: Any, **kwds: Union[Attribute, Value]) -> None: """Update from a mapping/iterable, and keyword args. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v """ if len(args) not in (1, 2): raise TypeError(f'Expected 1-2 positional args, not {len(args)}!') self: Element = args[0] if len(args) == 2: other = args[1] if isinstance(other, Mapping): for key in other: self[key] = other[key] elif hasattr(other, "keys"): for key in other.keys(): self[key] = other[key] else: for attr in other: if isinstance(attr, Attribute): self._members[attr.name.casefold()] = attr else: key, value = attr self[key] = value for key, value in kwds.items(): self[key] = value def setdefault(self, name: str, default: Union[Attribute, Value] = None) -> Attribute: """Return the specified attribute name. If it does not exist, set it using the default and return that. """ key = name.casefold() try: return self._members[key] except KeyError: if not isinstance(default, Attribute): typ, val = deduce_type(default) default = Attribute(name, typ, val) self._members[key] = default return default _NUMBERS = {int, float, bool} _ANGLES = {Angle, AngleTup} # Python types to their matching ValueType. TYPE_TO_VALTYPE: Dict[type, ValueType] = { Element: ValueType.ELEMENT, int: ValueType.INT, float: ValueType.FLOAT, bool: ValueType.BOOL, str: ValueType.STRING, bytes: ValueType.BINARY, # Time: ValueType.TIME, Color: ValueType.COLOR, Vec2: ValueType.VEC2, Vec3: ValueType.VEC3, Vec4: ValueType.VEC4, AngleTup: ValueType.ANGLE, Quaternion: ValueType.QUATERNION, Matrix: ValueType.MATRIX, } def deduce_type(value): """Convert Python objects to an appropriate ValueType.""" if isinstance(value, list): # Array. return deduce_type_array(value) else: # Single value. return deduce_type_single(value) def deduce_type_array(value: list): """Convert a Python list to an appropriate ValueType.""" if len(value) == 0: raise TypeError('Cannot deduce type for empty list!') types = set(map(type, value)) if len(types) > 1: if types <= _NUMBERS: # Allow mixing numerics, casting to the largest subset. if float in types: return ValueType.FLOAT, list(map(float, value)) if int in types: return ValueType.INTEGER, list(map(int, value)) if bool in types: return ValueType.BOOL, list(map(bool, value)) raise AssertionError('No numbers?', value) elif types == _ANGLES: return ValueType.ANGLE, list(map(AngleTup._make, value)) # Else, fall through and try iterables. else: [val_actual_type] = types if val_actual_type is Matrix: return ValueType.MATRIX, [mat.copy() for mat in value] if val_actual_type is Angle: return ValueType.ANGLE, [AngleTup._make(ang) for ang in value] elif val_actual_type is Color: return ValueType.COLOR, [ Color(int(r), int(g), int(b), int(a)) for r, g, b, a in value ] try: # Match to one of the types directly. val_type = TYPE_TO_VALTYPE[val_actual_type] except KeyError: pass else: # NamedTuple, ensure they're a float. if issubclass(val_actual_type, tuple): return val_type, [ tuple.__new__(val_actual_type, map(float, val)) for val in value ] else: return val_type, value.copy() # Deduce each type in the array, check they're the same. val_type, first = deduce_type_single(value[0]) result = [first] for val in value[1:]: sec_type, sec_val = deduce_type_single(val) if sec_type is not val_type: raise TypeError( 'Arrays must have the same types, or be all numeric. ' f'Got {val_type.name} and {sec_type.name}.' ) result.append(sec_val) return val_type, result def deduce_type_single(value): if isinstance(value, Matrix): return ValueType.MATRIX, value.copy() if isinstance(value, Angle): # Mutable version of values we use. return ValueType.ANGLE, AngleTup._make(value) elif isinstance(value, Color): [r, g, b, a] = value return ValueType.COLOR, Color(int(r), int(g), int(b), int(a)) try: # Match to one of the types directly. val_type = TYPE_TO_VALTYPE[type(value)] except KeyError: # Try iterables. pass else: # NamedTuple, ensure they're a float. if isinstance(value, tuple): return val_type, tuple.__new__(type(value), map(float, value)) else: # No change needed. return val_type, value try: it = iter(value) except TypeError: # Nope, not an iterable. So not valid. raise TypeError(f'Could not deduce value type for {type(value)}.') from None # Now determine the length. try: x = float(next(it)) except StopIteration: raise TypeError(f'Could not deduce vector type for zero-length iterable {type(value)}.') from None try: y = float(next(it)) except StopIteration: raise TypeError(f'Could not deduce vector type for one-long iterable {type(value)}.') from None try: z = float(next(it)) except StopIteration: return ValueType.VEC2, Vec2(x, y) try: w = float(next(it)) except StopIteration: return ValueType.VEC3, Vec3(x, y, z) try: next(it) except StopIteration: return ValueType.VEC4, Vec4(x, y, z, w) else: raise TypeError(f'Could not deduce vector type for 5+ long iterable {type(value)}.') from None # All the type converter functions. # Assign to globals, then _get_converters() will find and store these funcs, # removing them from globals. # Conversion to/from strings and binary are required for all types. _conv_string_to_float = float _conv_string_to_integer = int _conv_string_to_time = float _conv_string_to_bool = lambda val: BOOL_LOOKUP[val.casefold()] _conv_string_to_vec2 = lambda text: Vec2._make(parse_vector(text, 2)) _conv_string_to_vec3 = lambda text: Vec3._make(parse_vector(text, 3)) _conv_string_to_vec4 = lambda text: Vec4._make(parse_vector(text, 4)) _conv_string_to_color = lambda text: Color._make(parse_vector(text, 4)) _conv_string_to_angle = lambda text: AngleTup._make(parse_vector(text, 3)) _conv_string_to_quaternion = lambda text: Quaternion._make(parse_vector(text, 4)) _conv_integer_to_string = str _conv_integer_to_float = float _conv_integer_to_time = float _conv_integer_to_bool = bool _conv_integer_to_vec2 = lambda n: Vec2(n, n) _conv_integer_to_vec3 = lambda n: Vec3(n, n, n) _conv_integer_to_vec4 = lambda n: Vec4(n, n, n, n) def _conv_integer_to_color(val: int) -> Color: val = max(0, min(val, 255)) return Color(val, val, val, 255) def _fmt_float(x: float) -> str: """Format floats appropriately, with 6 decimal points but no trailing zeros.""" res = format(x, '.6f').rstrip('0') if res.endswith('.'): return res[:-1] return res _conv_float_to_string = _fmt_float _conv_float_to_integer = int _conv_float_to_bool = bool _conv_float_to_time = float _conv_float_to_vec2 = lambda n: Vec2(n, n) _conv_float_to_vec3 = lambda n: Vec3(n, n, n) _conv_float_to_vec4 = lambda n: Vec4(n, n, n, n) _conv_bool_to_integer = int _conv_bool_to_float = int _conv_bool_to_string = bool_as_int _conv_time_to_integer = int _conv_time_to_float = float _conv_time_to_bool = lambda t: t > 0 _conv_time_to_string = str _conv_vec2_to_string = lambda v: f'{_fmt_float(v.x)} {_fmt_float(v.y)}' _conv_vec2_to_bool = lambda v: bool(v.x or v.y) _conv_vec2_to_vec3 = lambda v: Vec3(v.x, v.y, 0.0) _conv_vec2_to_vec4 = lambda v: Vec4(v.x, v.y, 0.0, 0.0) _conv_vec3_to_string = lambda v: f'{_fmt_float(v.x)} {_fmt_float(v.y)} {_fmt_float(v.z)}' _conv_vec3_to_bool = lambda v: bool(v.x or v.y or v.z) _conv_vec3_to_vec2 = lambda v: Vec2(v.x, v.y) _conv_vec3_to_vec4 = lambda v: Vec4(v.x, v.y, v.z, 0.0) _conv_vec3_to_angle = lambda v: AngleTup(v.x, v.y, v.z) _conv_vec3_to_color = lambda v: Color(int(v.x), int(v.y), int(v.z), 255) _conv_vec4_to_string = lambda v: f'{_fmt_float(v.x)} {_fmt_float(v.y)} {_fmt_float(v.z)} {_fmt_float(v.w)}' _conv_vec4_to_bool = lambda v: bool(v.x or v.y or v.z or v.w) _conv_vec4_to_vec3 = lambda v: Vec3(v.x, v.y, v.z) _conv_vec4_to_vec2 = lambda v: Vec2(v.x, v.y) _conv_vec4_to_quaternion = lambda v: Quaternion(v.x, v.y, v.z, v.w) _conv_vec4_to_color = lambda v: Color(int(v.x), int(v.y), int(v.z), int(v.w)) _conv_matrix_to_angle = lambda mat: AngleTup._make(mat.to_angle()) _conv_angle_to_string = lambda a: f'{_fmt_float(a.pitch)} {_fmt_float(a.yaw)} {_fmt_float(a.roll)}' _conv_angle_to_matrix = lambda ang: Matrix.from_angle(Angle(ang)) _conv_angle_to_vec3 = lambda ang: Vec3(ang.pitch, ang.yaw, ang.roll) _conv_color_to_string = lambda col: f'{col.r} {col.g} {col.b} {col.a}' _conv_color_to_vec3 = lambda col: Vec3(col.r, col.g, col.b) _conv_color_to_vec4 = lambda col: Vec4(col.r, col.g, col.b, col.a) _conv_quaternion_to_string = lambda quat: f'{_fmt_float(quat.x)} {_fmt_float(quat.y)} {_fmt_float(quat.z)} {_fmt_float(quat.w)}' _conv_quaternion_to_vec4 = lambda quat: Vec4(quat.x, quat.y, quat.z, quat.w) # Binary conversions. _conv_string_to_binary = bytes.fromhex if sys.version_info >= (3, 8, 0): def _conv_binary_to_string(byt: bytes) -> str: """Format each byte, seperated by spaces.""" return byt.hex(' ', 1).upper() else: def _conv_binary_to_string(byt: bytes) -> str: """The parameters for bytes.hex aren't available, do it ourselves.""" return ' '.join([format(x, '02X') for x in byt]) def _binconv_basic(name: str, fmt: str): """Converter functions for a type with a single value.""" shape = Struct(fmt) def unpack(byt): [val] = shape.unpack(byt) return val ns = globals() ns['_struct_' + name] = shape ns[f'_conv_{name}_to_binary'] = shape.pack ns[f'_conv_binary_to_{name}'] = unpack def _binconv_ntup(name: str, fmt: str, Tup: Type[tuple]): """Converter functions for a type matching a namedtuple.""" shape = Struct(fmt) ns = globals() ns['_struct_' + name] = shape ns[f'_conv_{name}_to_binary'] = lambda val: shape.pack(*val) ns[f'_conv_binary_to_{name}'] = lambda byt: Tup._make(shape.unpack(byt)) _binconv_basic('integer', '<i') _binconv_basic('float', '<f') _binconv_basic('bool', '<?') _binconv_ntup('color', '<4B', Color) _binconv_ntup('angle', '<3f', AngleTup) _binconv_ntup('quaternion', '<4f', Quaternion) _binconv_ntup('vec2', '<2f', Vec2) _binconv_ntup('vec3', '<3f', Vec3) _binconv_ntup('vec4', '<4f', Vec4) _struct_time = Struct('<i') def _conv_time_to_binary(tim: Time) -> bytes: """Time is written as a fixed point integer.""" return _struct_time.pack(int(round(tim * 10000.0))) def _conv_binary_to_time(byt: bytes) -> Time: [num] = _struct_time.unpack(byt) return Time(num / 10000.0) _struct_matrix = Struct('<16f') def _conv_matrix_to_binary(mat): """We only set the 3x3 part.""" return _struct_matrix.pack( mat[0, 0], mat[0, 1], mat[0, 2], 0.0, mat[1, 0], mat[1, 1], mat[1, 2], 0.0, mat[2, 0], mat[2, 1], mat[2, 2], 0.0, 0.0, 0.0, 0.0, 1.0, ) def _conv_binary_to_matrix(byt): """We only set the 3x3 part.""" data = _struct_matrix.unpack(byt) mat = Matrix() mat[0, 0], mat[0, 1], mat[0, 2] = data[0:3] mat[1, 0], mat[1, 1], mat[1, 2] = data[4:7] mat[2, 0], mat[2, 1], mat[2, 2] = data[8:11] return mat def _conv_string_to_matrix(text: str) -> Matrix: data = parse_vector(text, 16) mat = Matrix() mat[0, 0], mat[0, 1], mat[0, 2] = data[0:3] mat[1, 0], mat[1, 1], mat[1, 2] = data[4:7] mat[2, 0], mat[2, 1], mat[2, 2] = data[8:11] return mat def _conv_matrix_to_string(mat: Matrix) -> str: return ( f'{mat[0, 0]} {mat[0, 1]} {mat[0, 2]} 0.0\n' f'{mat[1, 0]} {mat[1, 1]} {mat[1, 2]} 0.0\n' f'{mat[2, 0]} {mat[2, 1]} {mat[2, 2]} 0.0\n' '0.0 0.0 0.0 1.0' ) # Element ID _struct_element = Struct('<i') # Property setter implementations: _conv_integer = int _conv_string = str _conv_binary = bytes _conv_float = float _conv_time = float _conv_bool = bool def _converter_ntup(typ): """Common logic for named-tuple members.""" def _convert(value) -> typ: if isinstance(value, typ): return value else: return typ._make(value) return _convert _conv_color = _converter_ntup(Color) _conv_vec2 = _converter_ntup(Vec2) _conv_vec3 = _converter_ntup(Vec3) _conv_vec4 = _converter_ntup(Vec4) _conv_quaternion = _converter_ntup(Quaternion) del _converter_ntup def _conv_angle(value) -> AngleTup: if isinstance(value, AngleTup): return value elif isinstance(value, Matrix): return AngleTup._make(value.to_angle()) else: return AngleTup._make(value) def _conv_matrix(value) -> Matrix: if isinstance(value, AngleTup): value = Matrix.from_angle(Angle(*value)) elif isinstance(value, Angle): value = Matrix.from_angle(value) elif not isinstance(value, Matrix): raise ValueError('Matrix attributes must be set to a matrix.') return value.copy() def _conv_element(value) -> Element: if not isinstance(value, Element): raise ValueError('Element arrays must contain elements!') return value # Gather up all these functions, add to the dicts. TYPE_CONVERT, CONVERSIONS, SIZES = _get_converters()
37.621622
128
0.556622
4a1063a24b6461ef3609c112f94ed92a4179a45f
865
py
Python
tests/area_attention/test_multi_head_area_attention.py
mikomel/area-attention
06f219e9067b473da33a1c4b087778641012e8c8
[ "MIT" ]
8
2020-11-26T03:02:34.000Z
2022-02-04T08:41:10.000Z
tests/area_attention/test_multi_head_area_attention.py
mikomel/area-attention
06f219e9067b473da33a1c4b087778641012e8c8
[ "MIT" ]
null
null
null
tests/area_attention/test_multi_head_area_attention.py
mikomel/area-attention
06f219e9067b473da33a1c4b087778641012e8c8
[ "MIT" ]
1
2021-12-23T06:18:11.000Z
2021-12-23T06:18:11.000Z
import pytest import torch from area_attention import AreaAttention, MultiHeadAreaAttention area_attention = AreaAttention( key_query_size=32, area_key_mode='max', area_value_mode='mean', max_area_height=2, max_area_width=2, memory_height=4, memory_width=4, dropout_rate=0.2, top_k_areas=0 ) @pytest.mark.parametrize('num_heads', [1, 2, 4]) def test_forward(num_heads): multi_head_area_attention = MultiHeadAreaAttention( area_attention=area_attention, num_heads=num_heads, key_query_size=32, key_query_size_hidden=32, value_size=64, value_size_hidden=64 ) q = torch.rand(4, 8, 32) k = torch.rand(4, 16, 32) v = torch.rand(4, 16, 64) output = multi_head_area_attention(q, k, v) assert output.shape == (4, 8, 64) assert output.isfinite().all()
23.378378
64
0.677457
4a1063e1c85cfa49cd421ea140d4635841c82fd4
18,031
py
Python
rally/common/db/sqlalchemy/api.py
ewhseo/rally
37e5475b7785e987173e118e89dbab357cd64b66
[ "Apache-2.0" ]
null
null
null
rally/common/db/sqlalchemy/api.py
ewhseo/rally
37e5475b7785e987173e118e89dbab357cd64b66
[ "Apache-2.0" ]
null
null
null
rally/common/db/sqlalchemy/api.py
ewhseo/rally
37e5475b7785e987173e118e89dbab357cd64b66
[ "Apache-2.0" ]
null
null
null
# Copyright 2013: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ SQLAlchemy implementation for DB.API """ import os import alembic from alembic import config as alembic_config import alembic.migration as alembic_migration from oslo_config import cfg from oslo_db import exception as db_exc from oslo_db.sqlalchemy import session as db_session from oslo_utils import timeutils import sqlalchemy as sa from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm import load_only as sa_loadonly from rally.common.db import api as db_api from rally.common.db.sqlalchemy import models from rally.common.i18n import _ from rally import exceptions CONF = cfg.CONF _FACADE = None INITIAL_REVISION_UUID = "ca3626f62937" def _create_facade_lazily(): global _FACADE if _FACADE is None: _FACADE = db_session.EngineFacade.from_config(CONF) return _FACADE def get_engine(): facade = _create_facade_lazily() return facade.get_engine() def get_session(**kwargs): facade = _create_facade_lazily() return facade.get_session(**kwargs) def get_backend(): """The backend is this module itself.""" return Connection() def _alembic_config(): path = os.path.join(os.path.dirname(__file__), "alembic.ini") config = alembic_config.Config(path) return config def fix_deployment(fn): # NOTE(ikhudoshyn): Remove this once new deployment model # get adopted. # New DB schema for Deployment was introduced in # https://github.com/openstack/rally/ # commit/433cf080ea02f448df1ce33c620c8b30910338cd # yet old one is used over the codebase. # This decorator restores attributes that are missing from # the new model. """Restore old deployment model's attributes This decorator restores deployment properties "admin" and "users" moved into "credentials" attribute of DB model. """ def fix(o): if isinstance(o, list): return [fix(deployment) for deployment in o] else: if not o.get("admin"): o["admin"] = o["credentials"][0][1]["admin"] if not o.get("users"): o["users"] = o["credentials"][0][1]["users"] return o def wrapper(*args, **kwargs): deployment = fn(*args, **kwargs) return fix(deployment) return wrapper class Connection(object): def engine_reset(self): global _FACADE _FACADE = None def schema_cleanup(self): models.drop_db() def schema_revision(self, config=None, engine=None): """Current database revision. :param config: Instance of alembic config :param engine: Instance of DB engine :returns: Database revision :rtype: string """ engine = engine or get_engine() with engine.connect() as conn: context = alembic_migration.MigrationContext.configure(conn) return context.get_current_revision() def schema_upgrade(self, revision=None, config=None, engine=None): """Used for upgrading database. :param revision: Desired database version :type revision: string :param config: Instance of alembic config :param engine: Instance of DB engine """ revision = revision or "head" config = config or _alembic_config() engine = engine or get_engine() if self.schema_revision() is None: self.schema_stamp(INITIAL_REVISION_UUID, config=config) alembic.command.upgrade(config, revision or "head") def schema_create(self, config=None, engine=None): """Create database schema from models description. Can be used for initial installation instead of upgrade('head'). :param config: Instance of alembic config :param engine: Instance of DB engine """ engine = engine or get_engine() # NOTE(viktors): If we will use metadata.create_all() for non empty db # schema, it will only add the new tables, but leave # existing as is. So we should avoid of this situation. if self.schema_revision(engine=engine) is not None: raise db_exc.DbMigrationError("DB schema is already under version" " control. Use upgrade() instead") models.BASE.metadata.create_all(engine) self.schema_stamp("head", config=config) def schema_downgrade(self, revision, config=None): """Used for downgrading database. :param revision: Desired database revision :type revision: string :param config: Instance of alembic config """ config = config or _alembic_config() return alembic.command.downgrade(config, revision) def schema_stamp(self, revision, config=None): """Stamps database with provided revision. Don't run any migrations. :param revision: Should match one from repository or head - to stamp database with most recent revision :type revision: string :param config: Instance of alembic config """ config = config or _alembic_config() return alembic.command.stamp(config, revision=revision) def model_query(self, model, session=None): """The helper method to create query. :param model: The instance of :class:`rally.common.db.sqlalchemy.models.RallyBase` to request it. :param session: Reuse the session object or get new one if it is None. :returns: The query object. :raises Exception: when the model is not a sublcass of :class:`rally.common.db.sqlalchemy.models.RallyBase`. """ session = session or get_session() query = session.query(model) def issubclassof_rally_base(obj): return isinstance(obj, type) and issubclass(obj, models.RallyBase) if not issubclassof_rally_base(model): raise Exception(_("The model should be a subclass of RallyBase")) return query def _task_get(self, uuid, load_only=None, session=None): pre_query = self.model_query(models.Task, session=session) if load_only: pre_query = pre_query.options(sa_loadonly(load_only)) task = pre_query.filter_by(uuid=uuid).first() if not task: raise exceptions.TaskNotFound(uuid=uuid) return task @db_api.serialize def task_get(self, uuid): return self._task_get(uuid) @db_api.serialize def task_get_detailed(self, uuid): return (self.model_query(models.Task). options(sa.orm.joinedload("results")). filter_by(uuid=uuid).first()) @db_api.serialize def task_get_status(self, uuid): return self._task_get(uuid, load_only="status").status @db_api.serialize def task_get_detailed_last(self): return (self.model_query(models.Task). options(sa.orm.joinedload("results")). order_by(models.Task.id.desc()).first()) @db_api.serialize def task_create(self, values): task = models.Task() task.update(values) task.save() return task @db_api.serialize def task_update(self, uuid, values): session = get_session() values.pop("uuid", None) with session.begin(): task = self._task_get(uuid, session=session) task.update(values) return task def task_update_status(self, uuid, statuses, status_value): session = get_session() query = ( session.query(models.Task).filter( models.Task.uuid == uuid, models.Task.status.in_( statuses)). update({"status": status_value}, synchronize_session=False) ) if not query: status = " or ".join(statuses) msg = _("Task with uuid='%(uuid)s' and in statuses:'" "%(statuses)s' not found.'") % {"uuid": uuid, "statuses": status} raise exceptions.RallyException(msg) return query @db_api.serialize def task_list(self, status=None, deployment=None): query = self.model_query(models.Task) filters = {} if status is not None: filters["status"] = status if deployment is not None: filters["deployment_uuid"] = self.deployment_get( deployment)["uuid"] if filters: query = query.filter_by(**filters) return query.all() def task_delete(self, uuid, status=None): session = get_session() with session.begin(): query = base_query = (self.model_query(models.Task). filter_by(uuid=uuid)) if status is not None: query = base_query.filter_by(status=status) (self.model_query(models.TaskResult).filter_by(task_uuid=uuid). delete(synchronize_session=False)) count = query.delete(synchronize_session=False) if not count: if status is not None: task = base_query.first() if task: raise exceptions.TaskInvalidStatus(uuid=uuid, require=status, actual=task.status) raise exceptions.TaskNotFound(uuid=uuid) @db_api.serialize def task_result_create(self, task_uuid, key, data): result = models.TaskResult() result.update({"task_uuid": task_uuid, "key": key, "data": data}) result.save() return result @db_api.serialize def task_result_get_all_by_uuid(self, uuid): return (self.model_query(models.TaskResult). filter_by(task_uuid=uuid).all()) def _deployment_get(self, deployment, session=None): stored_deployment = self.model_query( models.Deployment, session=session).filter_by(name=deployment).first() if not stored_deployment: stored_deployment = self.model_query( models.Deployment, session=session).filter_by(uuid=deployment).first() if not stored_deployment: raise exceptions.DeploymentNotFound(deployment=deployment) return stored_deployment @fix_deployment @db_api.serialize def deployment_create(self, values): deployment = models.Deployment() try: # TODO(rpromyshlennikov): remove after credentials refactoring values.setdefault( "credentials", [ ["openstack", {"admin": values.get("admin"), "users": values.get("users", [])}] ] ) deployment.update(values) deployment.save() except db_exc.DBDuplicateEntry: raise exceptions.DeploymentNameExists(deployment=values["name"]) return deployment def deployment_delete(self, uuid): session = get_session() with session.begin(): count = (self.model_query(models.Resource, session=session). filter_by(deployment_uuid=uuid).count()) if count: raise exceptions.DeploymentIsBusy(uuid=uuid) count = (self.model_query(models.Deployment, session=session). filter_by(uuid=uuid).delete(synchronize_session=False)) if not count: raise exceptions.DeploymentNotFound(deployment=uuid) @fix_deployment @db_api.serialize def deployment_get(self, deployment): return self._deployment_get(deployment) @fix_deployment @db_api.serialize def deployment_update(self, deployment, values): session = get_session() values.pop("uuid", None) with session.begin(): dpl = self._deployment_get(deployment, session=session) # TODO(rpromyshlennikov): remove after credentials refactoring values.setdefault( "credentials", [ ["openstack", {"admin": values.get("admin"), "users": values.get("users", [])}] ] ) dpl.update(values) return dpl @fix_deployment @db_api.serialize def deployment_list(self, status=None, parent_uuid=None, name=None): query = (self.model_query(models.Deployment). filter_by(parent_uuid=parent_uuid)) if name: query = query.filter_by(name=name) if status: query = query.filter_by(status=status) return query.all() @db_api.serialize def resource_create(self, values): resource = models.Resource() resource.update(values) resource.save() return resource @db_api.serialize def resource_get_all(self, deployment_uuid, provider_name=None, type=None): query = (self.model_query(models.Resource). filter_by(deployment_uuid=deployment_uuid)) if provider_name is not None: query = query.filter_by(provider_name=provider_name) if type is not None: query = query.filter_by(type=type) return query.all() def resource_delete(self, id): count = (self.model_query(models.Resource). filter_by(id=id).delete(synchronize_session=False)) if not count: raise exceptions.ResourceNotFound(id=id) @db_api.serialize def verification_create(self, deployment_uuid): verification = models.Verification() verification.update({"deployment_uuid": deployment_uuid}) verification.save() return verification @db_api.serialize def verification_get(self, verification_uuid, session=None): return self._verification_get(verification_uuid, session) def _verification_get(self, verification_uuid, session=None): verification = (self.model_query(models.Verification, session=session). filter_by(uuid=verification_uuid).first()) if not verification: raise exceptions.NotFoundException( "Can't find any verification with following UUID '%s'." % verification_uuid) return verification @db_api.serialize def verification_update(self, verification_uuid, values): session = get_session() with session.begin(): verification = self._verification_get(verification_uuid, session=session) verification.update(values) return verification @db_api.serialize def verification_list(self, status=None): query = self.model_query(models.Verification) if status is not None: query = query.filter_by(status=status) return query.all() def verification_delete(self, verification_uuid): count = (self.model_query(models.Verification). filter_by(id=verification_uuid). delete(synchronize_session=False)) if not count: raise exceptions.NotFoundException( "Can't find any verification with following UUID '%s'." % verification_uuid) @db_api.serialize def verification_result_create(self, verification_uuid, data): result = models.VerificationResult() result.update({"verification_uuid": verification_uuid, "data": data}) result.save() return result @db_api.serialize def verification_result_get(self, verification_uuid): result = (self.model_query(models.VerificationResult). filter_by(verification_uuid=verification_uuid).first()) if not result: raise exceptions.NotFoundException( "No results for following UUID '%s'." % verification_uuid) return result @db_api.serialize def register_worker(self, values): try: worker = models.Worker() worker.update(values) worker.update({"updated_at": timeutils.utcnow()}) worker.save() return worker except db_exc.DBDuplicateEntry: raise exceptions.WorkerAlreadyRegistered( worker=values["hostname"]) @db_api.serialize def get_worker(self, hostname): try: return (self.model_query(models.Worker). filter_by(hostname=hostname).one()) except NoResultFound: raise exceptions.WorkerNotFound(worker=hostname) def unregister_worker(self, hostname): count = (self.model_query(models.Worker). filter_by(hostname=hostname).delete()) if count == 0: raise exceptions.WorkerNotFound(worker=hostname) def update_worker(self, hostname): count = (self.model_query(models.Worker). filter_by(hostname=hostname). update({"updated_at": timeutils.utcnow()})) if count == 0: raise exceptions.WorkerNotFound(worker=hostname)
34.741811
79
0.615828
4a1064744f3c459c03eb09ea55e06674a1a41bf9
430
py
Python
app/tests/utils/utils.py
nubilfi/fastapi-starter-kit
99a326099c3446584dd0ef18b123c42ba360d364
[ "MIT" ]
null
null
null
app/tests/utils/utils.py
nubilfi/fastapi-starter-kit
99a326099c3446584dd0ef18b123c42ba360d364
[ "MIT" ]
1
2021-03-17T08:24:12.000Z
2021-03-17T08:24:12.000Z
app/tests/utils/utils.py
nubilfi/fastapi-starter-kit
99a326099c3446584dd0ef18b123c42ba360d364
[ "MIT" ]
null
null
null
""" Just a utils function """ import random import string def random_lower_string() -> str: """generate random lowercase str""" return "".join(random.choices(string.ascii_lowercase, k=32)) def random_email() -> str: """generate a random email""" return f"{random_lower_string()}@{random_lower_string()}.com" def random_username() -> str: """generate a random username""" return random_lower_string()
20.47619
65
0.686047
4a1064b76d1c8c75368d950c82e0ea5412c63761
636
py
Python
move.py
jpgualdarrama/pokescrape
dcfed3fc7b887c2c7c4720ef414247aa79dc749b
[ "MIT" ]
21
2015-03-28T15:30:05.000Z
2020-08-03T12:27:27.000Z
move.py
jpgualdarrama/pokescrape
dcfed3fc7b887c2c7c4720ef414247aa79dc749b
[ "MIT" ]
1
2015-04-28T22:19:51.000Z
2015-04-29T00:37:57.000Z
move.py
jpgualdarrama/pokescrape
dcfed3fc7b887c2c7c4720ef414247aa79dc749b
[ "MIT" ]
3
2016-12-08T18:55:53.000Z
2020-01-30T03:04:49.000Z
from pk import * class Move: def __init__(self): self.name = 'None' self.type = 0 self.pp = 0 self.power = 0 self.accuracy = 0 self.category = 0 self.damage = 0 self.description = 'None' def __str__(self): return ('Name: %s' % self.name + '\nType: %i (%s)' % (self.type, PkIType[self.type]) + '\nPP: %i' % self.pp + '\nPower: %i' % self.power + '\nAccuracy: %i' % self.accuracy + '\nCategory: %i (%s)' % (self.category, PkIMoveCategory[self.category]) + '\nDamage: %i (%s)' % (self.damage, PkIMoveDamae[self.damage]) + '\nDescription: %s' % self.description) moves = [Move()] moves_map = {}
24.461538
76
0.59434