hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
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
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
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
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
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
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
f735d895095411701d85cb27b09f83cd7ccb48b3
2,603
py
Python
python/dask_cudf/setup.py
dominicshanshan/cudf
bfbdcb14164c737820a0a8a6334c92039d5e6621
[ "Apache-2.0" ]
null
null
null
python/dask_cudf/setup.py
dominicshanshan/cudf
bfbdcb14164c737820a0a8a6334c92039d5e6621
[ "Apache-2.0" ]
1
2021-03-10T20:28:23.000Z
2021-03-25T15:58:47.000Z
python/dask_cudf/setup.py
vyasr/cudf
9617fcd452a66bdeb9c2275216e866b78f997508
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2019-2021, NVIDIA CORPORATION. import os import re import shutil from setuptools import find_packages, setup import versioneer install_requires = [ "cudf", "dask==2021.4.0", "distributed>=2.22.0,<=2021.4.0", "fsspec>=0.6.0", "numpy", "pandas>=1.0,<1.3.0dev0", ] extras_require = { "test": [ "numpy", "pandas>=1.0,<1.3.0dev0", "pytest", "numba>=0.49.0,!=0.51.0", "dask==2021.4.0", "distributed>=2.22.0,<=2021.4.0", ] } def get_cuda_version_from_header(cuda_include_dir, delimeter=""): cuda_version = None with open( os.path.join(cuda_include_dir, "cuda.h"), "r", encoding="utf-8" ) as f: for line in f.readlines(): if re.search(r"#define CUDA_VERSION ", line) is not None: cuda_version = line break if cuda_version is None: raise TypeError("CUDA_VERSION not found in cuda.h") cuda_version = int(cuda_version.split()[2]) return "%d%s%d" % ( cuda_version // 1000, delimeter, (cuda_version % 1000) // 10, ) CUDA_HOME = os.environ.get("CUDA_HOME", False) if not CUDA_HOME: path_to_cuda_gdb = shutil.which("cuda-gdb") if path_to_cuda_gdb is None: raise OSError( "Could not locate CUDA. " "Please set the environment variable " "CUDA_HOME to the path to the CUDA installation " "and try again." ) CUDA_HOME = os.path.dirname(os.path.dirname(path_to_cuda_gdb)) if not os.path.isdir(CUDA_HOME): raise OSError(f"Invalid CUDA_HOME: directory does not exist: {CUDA_HOME}") cuda_include_dir = os.path.join(CUDA_HOME, "include") cupy_package_name = "cupy-cuda" + get_cuda_version_from_header( cuda_include_dir ) install_requires.append(cupy_package_name) setup( name="dask-cudf", version=versioneer.get_version(), description="Utilities for Dask and cuDF interactions", url="https://github.com/rapidsai/cudf", author="NVIDIA Corporation", license="Apache 2.0", classifiers=[ "Intended Audience :: Developers", "Topic :: Database", "Topic :: Scientific/Engineering", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], packages=find_packages(exclude=["tests", "tests.*"]), cmdclass=versioneer.get_cmdclass(), install_requires=install_requires, extras_require=extras_require, )
26.835052
78
0.623511
import os import re import shutil from setuptools import find_packages, setup import versioneer install_requires = [ "cudf", "dask==2021.4.0", "distributed>=2.22.0,<=2021.4.0", "fsspec>=0.6.0", "numpy", "pandas>=1.0,<1.3.0dev0", ] extras_require = { "test": [ "numpy", "pandas>=1.0,<1.3.0dev0", "pytest", "numba>=0.49.0,!=0.51.0", "dask==2021.4.0", "distributed>=2.22.0,<=2021.4.0", ] } def get_cuda_version_from_header(cuda_include_dir, delimeter=""): cuda_version = None with open( os.path.join(cuda_include_dir, "cuda.h"), "r", encoding="utf-8" ) as f: for line in f.readlines(): if re.search(r"#define CUDA_VERSION ", line) is not None: cuda_version = line break if cuda_version is None: raise TypeError("CUDA_VERSION not found in cuda.h") cuda_version = int(cuda_version.split()[2]) return "%d%s%d" % ( cuda_version // 1000, delimeter, (cuda_version % 1000) // 10, ) CUDA_HOME = os.environ.get("CUDA_HOME", False) if not CUDA_HOME: path_to_cuda_gdb = shutil.which("cuda-gdb") if path_to_cuda_gdb is None: raise OSError( "Could not locate CUDA. " "Please set the environment variable " "CUDA_HOME to the path to the CUDA installation " "and try again." ) CUDA_HOME = os.path.dirname(os.path.dirname(path_to_cuda_gdb)) if not os.path.isdir(CUDA_HOME): raise OSError(f"Invalid CUDA_HOME: directory does not exist: {CUDA_HOME}") cuda_include_dir = os.path.join(CUDA_HOME, "include") cupy_package_name = "cupy-cuda" + get_cuda_version_from_header( cuda_include_dir ) install_requires.append(cupy_package_name) setup( name="dask-cudf", version=versioneer.get_version(), description="Utilities for Dask and cuDF interactions", url="https://github.com/rapidsai/cudf", author="NVIDIA Corporation", license="Apache 2.0", classifiers=[ "Intended Audience :: Developers", "Topic :: Database", "Topic :: Scientific/Engineering", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], packages=find_packages(exclude=["tests", "tests.*"]), cmdclass=versioneer.get_cmdclass(), install_requires=install_requires, extras_require=extras_require, )
true
true
f735d9417c94a77fd8ca0384ef7cbaaf9998e431
2,717
py
Python
venv/Lib/site-packages/nbformat/v4/tests/test_convert.py
ajayiagbebaku/NFL-Model
afcc67a85ca7138c58c3334d45988ada2da158ed
[ "MIT" ]
603
2020-12-23T13:49:32.000Z
2022-03-31T23:38:03.000Z
venv/Lib/site-packages/nbformat/v4/tests/test_convert.py
ajayiagbebaku/NFL-Model
afcc67a85ca7138c58c3334d45988ada2da158ed
[ "MIT" ]
387
2020-12-15T14:54:04.000Z
2022-03-31T07:00:21.000Z
venv/Lib/site-packages/nbformat/v4/tests/test_convert.py
ajayiagbebaku/NFL-Model
afcc67a85ca7138c58c3334d45988ada2da158ed
[ "MIT" ]
35
2021-03-26T03:12:04.000Z
2022-03-23T10:15:10.000Z
# -*- coding: utf-8 -*- import os import io import copy from unittest import mock from nbformat import validate from .. import convert from ..nbjson import reads from . import nbexamples from nbformat.v3.tests import nbexamples as v3examples from nbformat import v3, v4 def test_upgrade_notebook(): nb03 = copy.deepcopy(v3examples.nb0) validate(nb03) nb04 = convert.upgrade(nb03) validate(nb04) def test_downgrade_notebook(): nb04 = copy.deepcopy(nbexamples.nb0) validate(nb04) nb03 = convert.downgrade(nb04) validate(nb03) def test_upgrade_heading(): # Fake the uuid generation for ids cell_ids = ['cell-1', 'cell-2', 'cell-3'] with mock.patch('nbformat.v4.convert.random_cell_id', side_effect=cell_ids): with mock.patch('nbformat.v4.nbbase.random_cell_id', side_effect=cell_ids): v3h = v3.new_heading_cell v4m = v4.new_markdown_cell for v3cell, expected in [ ( v3h(source='foo', level=1), v4m(source='# foo'), ), ( v3h(source='foo\nbar\nmulti-line\n', level=4), v4m(source='#### foo bar multi-line'), ), ( v3h(source=u'ünìcö∂e–cønvërsioñ', level=4), v4m(source=u'#### ünìcö∂e–cønvërsioñ'), ), ]: upgraded = convert.upgrade_cell(v3cell) assert upgraded == expected def test_downgrade_heading(): v3h = v3.new_heading_cell v4m = v4.new_markdown_cell v3m = lambda source: v3.new_text_cell('markdown', source) for v4cell, expected in [ ( v4m(source='# foo'), v3h(source='foo', level=1), ), ( v4m(source='#foo'), v3h(source='foo', level=1), ), ( v4m(source='#\tfoo'), v3h(source='foo', level=1), ), ( v4m(source='# \t foo'), v3h(source='foo', level=1), ), ( v4m(source='# foo\nbar'), v3m(source='# foo\nbar'), ), ]: downgraded = convert.downgrade_cell(v4cell) assert downgraded == expected def test_upgrade_v4_to_4_dot_5(): here = os.path.dirname(__file__) with io.open(os.path.join(here, os.pardir, os.pardir, 'tests', "test4.ipynb"), encoding='utf-8') as f: nb = reads(f.read()) assert nb['nbformat_minor'] == 0 validate(nb) assert nb.cells[0].get('id') is None nb_up = convert.upgrade(nb) assert nb_up['nbformat_minor'] == 5 validate(nb_up) assert nb_up.cells[0]['id'] is not None
29.532609
106
0.552448
import os import io import copy from unittest import mock from nbformat import validate from .. import convert from ..nbjson import reads from . import nbexamples from nbformat.v3.tests import nbexamples as v3examples from nbformat import v3, v4 def test_upgrade_notebook(): nb03 = copy.deepcopy(v3examples.nb0) validate(nb03) nb04 = convert.upgrade(nb03) validate(nb04) def test_downgrade_notebook(): nb04 = copy.deepcopy(nbexamples.nb0) validate(nb04) nb03 = convert.downgrade(nb04) validate(nb03) def test_upgrade_heading(): cell_ids = ['cell-1', 'cell-2', 'cell-3'] with mock.patch('nbformat.v4.convert.random_cell_id', side_effect=cell_ids): with mock.patch('nbformat.v4.nbbase.random_cell_id', side_effect=cell_ids): v3h = v3.new_heading_cell v4m = v4.new_markdown_cell for v3cell, expected in [ ( v3h(source='foo', level=1), v4m(source='# foo'), ), ( v3h(source='foo\nbar\nmulti-line\n', level=4), v4m(source='#### foo bar multi-line'), ), ( v3h(source=u'ünìcö∂e–cønvërsioñ', level=4), v4m(source=u'#### ünìcö∂e–cønvërsioñ'), ), ]: upgraded = convert.upgrade_cell(v3cell) assert upgraded == expected def test_downgrade_heading(): v3h = v3.new_heading_cell v4m = v4.new_markdown_cell v3m = lambda source: v3.new_text_cell('markdown', source) for v4cell, expected in [ ( v4m(source='# foo'), v3h(source='foo', level=1), ), ( v4m(source='#foo'), v3h(source='foo', level=1), ), ( v4m(source='#\tfoo'), v3h(source='foo', level=1), ), ( v4m(source='# \t foo'), v3h(source='foo', level=1), ), ( v4m(source='# foo\nbar'), v3m(source='# foo\nbar'), ), ]: downgraded = convert.downgrade_cell(v4cell) assert downgraded == expected def test_upgrade_v4_to_4_dot_5(): here = os.path.dirname(__file__) with io.open(os.path.join(here, os.pardir, os.pardir, 'tests', "test4.ipynb"), encoding='utf-8') as f: nb = reads(f.read()) assert nb['nbformat_minor'] == 0 validate(nb) assert nb.cells[0].get('id') is None nb_up = convert.upgrade(nb) assert nb_up['nbformat_minor'] == 5 validate(nb_up) assert nb_up.cells[0]['id'] is not None
true
true
f735d97c51df40ed12b2c8c8b79166d319cf9203
4,720
py
Python
Memory_RNN.py
dhingratul/RNN
9e1ac582dbf8251769817b34fc9d791fa8c20376
[ "MIT" ]
null
null
null
Memory_RNN.py
dhingratul/RNN
9e1ac582dbf8251769817b34fc9d791fa8c20376
[ "MIT" ]
null
null
null
Memory_RNN.py
dhingratul/RNN
9e1ac582dbf8251769817b34fc9d791fa8c20376
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 24 11:28:50 2017 @author: dhingratul """ from __future__ import print_function, division import numpy as np import tensorflow as tf import helpers # hyperparams num_epochs = 10000 total_series_length = 100 truncated_backprop_length = 5 state_size = 4 # Number of neurons in the hidden layer num_classes = 2 # Data is binary, 0 / 1 = Two Classes batch_size = 8 num_batches = total_series_length//batch_size//truncated_backprop_length # Step 1 - Data Generation # Generate integers and corresponding binary numbers randomly selected in a # range of 10,000. The data points are zero padded so as to make a constant # lenght of 100 shift_batch = 0 def generateData(shift_batch): vector_size = 100 batches = helpers.random_sequences(length_from=3, length_to=8, vocab_lower=0, vocab_upper=2, batch_size=vector_size) batch = next(batches) x, _ = helpers.batch(batch) if shift_batch == 0: # Learning the same sequence y = x else: y_inter2 = helpers.shifter(batch, shift_batch) y, _ = helpers.batch(y_inter2) return x, y # Step 2 - Build the Model batchX_placeholder = tf.placeholder( tf.float32, [batch_size, truncated_backprop_length]) batchY_placeholder = tf.placeholder( tf.int32, [batch_size, truncated_backprop_length]) init_state = tf.placeholder(tf.float32, [batch_size, state_size]) # Randomly initialize weights W = tf.Variable(np.random.rand(state_size+1, state_size), dtype=tf.float32) b = tf.Variable(np.zeros((1, state_size)), dtype=tf.float32) W2 = tf.Variable(np.random.rand(state_size, num_classes), dtype=tf.float32) b2 = tf.Variable(np.zeros((1, num_classes)), dtype=tf.float32) # Unpack columns inputs_series = tf.unstack(batchX_placeholder, axis=1) labels_series = tf.unstack(batchY_placeholder, axis=1) # Forward pass # State placeholder current_state = init_state # series of states through time states_series = [] # For each set of inputs, forward pass through the network to get new state # values and store all states in memory for current_input in inputs_series: current_input = tf.reshape(current_input, [batch_size, 1]) # Concatenate state and input data input_and_state_concatenated = tf.concat( axis=1, values=[current_input, current_state]) next_state = tf.tanh(tf.matmul(input_and_state_concatenated, W) + b) # Store the state in memory states_series.append(next_state) # Set current state to next one current_state = next_state # Calculate loss logits_series = [tf.matmul(state, W2) + b2 for state in states_series] # Softmax Non-linearity predictions_series = [tf.nn.softmax(logits) for logits in logits_series] # Measure loss, calculate softmax again on logits, then compute cross entropy losses = [tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels) for logits, labels in zip(logits_series, labels_series)] # Average Loss total_loss = tf.reduce_mean(losses) # Use adagrad for minimization train_step = tf.train.AdagradOptimizer(0.2).minimize(total_loss) # Step 3 Training the network with tf.Session() as sess: y = np.zeros([batch_size]) sess.run(tf.global_variables_initializer()) loss_list = [] for epoch_idx in range(num_epochs): # Generate new data at every epoch x, y = generateData(shift_batch) while (len(y) > 8 or len(y) < 8): x, y = generateData(shift_batch) # Empty hidden state _current_state = np.zeros((batch_size, state_size)) print("epoch", epoch_idx) for batch_idx in range(num_batches): # layers unrolled to a limited number of time-steps: # truncated length start_idx = batch_idx * truncated_backprop_length end_idx = start_idx + truncated_backprop_length batchX = x[:, start_idx:end_idx] batchY = y[:, start_idx:end_idx] # Run the computation graph, give it the values _total_loss, _train_step, _current_state, _predictions_series = \ sess.run( [total_loss, train_step, current_state, predictions_series], feed_dict={ batchX_placeholder: batchX, batchY_placeholder: batchY, init_state: _current_state }) # print(batchX, batchY) loss_list.append(_total_loss) if batch_idx % 100 == 0: print("Loss", _total_loss)
37.165354
77
0.670763
from __future__ import print_function, division import numpy as np import tensorflow as tf import helpers num_epochs = 10000 total_series_length = 100 truncated_backprop_length = 5 state_size = 4 num_classes = 2 batch_size = 8 num_batches = total_series_length//batch_size//truncated_backprop_length shift_batch = 0 def generateData(shift_batch): vector_size = 100 batches = helpers.random_sequences(length_from=3, length_to=8, vocab_lower=0, vocab_upper=2, batch_size=vector_size) batch = next(batches) x, _ = helpers.batch(batch) if shift_batch == 0: y = x else: y_inter2 = helpers.shifter(batch, shift_batch) y, _ = helpers.batch(y_inter2) return x, y batchX_placeholder = tf.placeholder( tf.float32, [batch_size, truncated_backprop_length]) batchY_placeholder = tf.placeholder( tf.int32, [batch_size, truncated_backprop_length]) init_state = tf.placeholder(tf.float32, [batch_size, state_size]) W = tf.Variable(np.random.rand(state_size+1, state_size), dtype=tf.float32) b = tf.Variable(np.zeros((1, state_size)), dtype=tf.float32) W2 = tf.Variable(np.random.rand(state_size, num_classes), dtype=tf.float32) b2 = tf.Variable(np.zeros((1, num_classes)), dtype=tf.float32) inputs_series = tf.unstack(batchX_placeholder, axis=1) labels_series = tf.unstack(batchY_placeholder, axis=1) current_state = init_state states_series = [] for current_input in inputs_series: current_input = tf.reshape(current_input, [batch_size, 1]) input_and_state_concatenated = tf.concat( axis=1, values=[current_input, current_state]) next_state = tf.tanh(tf.matmul(input_and_state_concatenated, W) + b) states_series.append(next_state) current_state = next_state logits_series = [tf.matmul(state, W2) + b2 for state in states_series] predictions_series = [tf.nn.softmax(logits) for logits in logits_series] losses = [tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels) for logits, labels in zip(logits_series, labels_series)] total_loss = tf.reduce_mean(losses) train_step = tf.train.AdagradOptimizer(0.2).minimize(total_loss) with tf.Session() as sess: y = np.zeros([batch_size]) sess.run(tf.global_variables_initializer()) loss_list = [] for epoch_idx in range(num_epochs): x, y = generateData(shift_batch) while (len(y) > 8 or len(y) < 8): x, y = generateData(shift_batch) _current_state = np.zeros((batch_size, state_size)) print("epoch", epoch_idx) for batch_idx in range(num_batches): start_idx = batch_idx * truncated_backprop_length end_idx = start_idx + truncated_backprop_length batchX = x[:, start_idx:end_idx] batchY = y[:, start_idx:end_idx] _total_loss, _train_step, _current_state, _predictions_series = \ sess.run( [total_loss, train_step, current_state, predictions_series], feed_dict={ batchX_placeholder: batchX, batchY_placeholder: batchY, init_state: _current_state }) loss_list.append(_total_loss) if batch_idx % 100 == 0: print("Loss", _total_loss)
true
true
f735d995a995275b81d6509ee58d925327c4d02a
2,246
py
Python
fewshot/data/compress_tiered_imagenet.py
ashok-arjun/few-shot-ssl-public
f7577d80b7491e0f27234a2e9c0113782365c2e1
[ "MIT" ]
497
2018-03-02T00:50:53.000Z
2022-03-22T06:30:59.000Z
fewshot/data/compress_tiered_imagenet.py
eleniTriantafillou/few-shot-ssl-public
3cf522031aa40b4ffb61e4693d0b48fdd5669276
[ "MIT" ]
20
2018-03-19T06:15:30.000Z
2021-11-20T07:21:38.000Z
fewshot/data/compress_tiered_imagenet.py
eleniTriantafillou/few-shot-ssl-public
3cf522031aa40b4ffb61e4693d0b48fdd5669276
[ "MIT" ]
108
2018-03-02T06:56:13.000Z
2021-12-23T03:40:43.000Z
# Copyright (c) 2018 Mengye Ren, Eleni Triantafillou, Sachin Ravi, Jake Snell, # Kevin Swersky, Joshua B. Tenenbaum, Hugo Larochelle, Richars S. Zemel. # # 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. # ============================================================================= import cv2 import numpy as np import six import sys import pickle as pkl from tqdm import tqdm def compress(path, output): with np.load(path, mmap_mode="r") as data: images = data["images"] array = [] for ii in tqdm(six.moves.xrange(images.shape[0]), desc='compress'): im = images[ii] im_str = cv2.imencode('.png', im)[1] array.append(im_str) with open(output, 'wb') as f: pkl.dump(array, f, protocol=pkl.HIGHEST_PROTOCOL) def decompress(path, output): with open(output, 'rb') as f: array = pkl.load(f) images = np.zeros([len(array), 84, 84, 3], dtype=np.uint8) for ii, item in tqdm(enumerate(array), desc='decompress'): im = cv2.imdecode(item, 1) images[ii] = im np.savez(path, images=images) def main(): if sys.argv[1] == 'compress': compress(sys.argv[2], sys.argv[3]) elif sys.argv[1] == 'decompress': decompress(sys.argv[2], sys.argv[3]) if __name__ == '__main__': main()
36.225806
80
0.691897
import cv2 import numpy as np import six import sys import pickle as pkl from tqdm import tqdm def compress(path, output): with np.load(path, mmap_mode="r") as data: images = data["images"] array = [] for ii in tqdm(six.moves.xrange(images.shape[0]), desc='compress'): im = images[ii] im_str = cv2.imencode('.png', im)[1] array.append(im_str) with open(output, 'wb') as f: pkl.dump(array, f, protocol=pkl.HIGHEST_PROTOCOL) def decompress(path, output): with open(output, 'rb') as f: array = pkl.load(f) images = np.zeros([len(array), 84, 84, 3], dtype=np.uint8) for ii, item in tqdm(enumerate(array), desc='decompress'): im = cv2.imdecode(item, 1) images[ii] = im np.savez(path, images=images) def main(): if sys.argv[1] == 'compress': compress(sys.argv[2], sys.argv[3]) elif sys.argv[1] == 'decompress': decompress(sys.argv[2], sys.argv[3]) if __name__ == '__main__': main()
true
true
f735db37f7d3724fd60e352c1e02af97aa1e9569
444
py
Python
tests/transform/preprocessing/test_instance_unit_norm_scaler.py
selimfirat/pysad
dff2ff38258eb8a85c9d34cf5f0b876fc1dc9ede
[ "BSD-3-Clause" ]
155
2020-08-17T12:52:38.000Z
2022-03-19T02:59:26.000Z
tests/transform/preprocessing/test_instance_unit_norm_scaler.py
shubhsoni/pysad
dff2ff38258eb8a85c9d34cf5f0b876fc1dc9ede
[ "BSD-3-Clause" ]
2
2020-10-22T09:50:28.000Z
2021-02-15T02:01:44.000Z
tests/transform/preprocessing/test_instance_unit_norm_scaler.py
shubhsoni/pysad
dff2ff38258eb8a85c9d34cf5f0b876fc1dc9ede
[ "BSD-3-Clause" ]
14
2020-10-09T17:08:23.000Z
2022-03-25T11:30:12.000Z
def test_instance_unit_norm_scaler(): import numpy as np from pysad.transform.preprocessing import InstanceUnitNormScaler X = np.random.rand(100, 25) scaler = InstanceUnitNormScaler() scaled_X = scaler.fit_transform(X) assert np.all(np.isclose(np.linalg.norm(scaled_X, axis=1), 1.0)) scaler = scaler.fit(X) scaled_X = scaler.transform(X) assert np.all(np.isclose(np.linalg.norm(scaled_X, axis=1), 1.0))
27.75
68
0.709459
def test_instance_unit_norm_scaler(): import numpy as np from pysad.transform.preprocessing import InstanceUnitNormScaler X = np.random.rand(100, 25) scaler = InstanceUnitNormScaler() scaled_X = scaler.fit_transform(X) assert np.all(np.isclose(np.linalg.norm(scaled_X, axis=1), 1.0)) scaler = scaler.fit(X) scaled_X = scaler.transform(X) assert np.all(np.isclose(np.linalg.norm(scaled_X, axis=1), 1.0))
true
true
f735dc85333b263fc7bc9284960f4d6199a4a30e
815
py
Python
irfca_blog/urls.py
abhishekadhikari23/irfca_blog
2e14a52857304e17117177f1b1bc6f01c2b8d6e5
[ "MIT" ]
null
null
null
irfca_blog/urls.py
abhishekadhikari23/irfca_blog
2e14a52857304e17117177f1b1bc6f01c2b8d6e5
[ "MIT" ]
null
null
null
irfca_blog/urls.py
abhishekadhikari23/irfca_blog
2e14a52857304e17117177f1b1bc6f01c2b8d6e5
[ "MIT" ]
null
null
null
"""irfca_blog URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home' ), ]
33.958333
77
0.704294
from django.contrib import admin from django.urls import path from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home' ), ]
true
true
f735ddf7c597a5a4b3a06b755753649d01e3fa15
5,892
py
Python
oteltrace/contrib/django/conf.py
ocelotl/opentelemetry-auto-instr-python-1
f5c47bd1ee492ffde298794f283031c22891f60b
[ "BSD-3-Clause" ]
2
2020-03-04T17:33:22.000Z
2021-01-20T14:20:10.000Z
oteltrace/contrib/django/conf.py
ocelotl/opentelemetry-auto-instr-python-1
f5c47bd1ee492ffde298794f283031c22891f60b
[ "BSD-3-Clause" ]
4
2019-11-25T00:11:16.000Z
2021-05-13T20:43:50.000Z
oteltrace/contrib/django/conf.py
ocelotl/opentelemetry-auto-instr-python-1
f5c47bd1ee492ffde298794f283031c22891f60b
[ "BSD-3-Clause" ]
3
2020-02-05T14:54:25.000Z
2020-03-23T02:51:27.000Z
# Copyright 2019, OpenTelemetry Authors # # 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. """ Settings for OpenTelemetry tracer are all namespaced in the OPENTELEMETRY_TRACE setting. For example your project's `settings.py` file might look like this: OPENTELEMETRY_TRACE = { 'TRACER': 'myapp.tracer', } This module provides the `setting` object, that is used to access OpenTelemetry settings, checking for user settings first, then falling back to the defaults. """ from __future__ import unicode_literals import os import importlib from django.conf import settings as django_settings from ...internal.logger import get_logger log = get_logger(__name__) # List of available settings with their defaults DEFAULTS = { 'AGENT_HOSTNAME': 'localhost', 'AGENT_PORT': 8126, 'AUTO_INSTRUMENT': True, 'INSTRUMENT_CACHE': True, 'INSTRUMENT_DATABASE': True, 'INSTRUMENT_TEMPLATE': True, 'DEFAULT_DATABASE_PREFIX': '', 'DEFAULT_SERVICE': 'django', 'DEFAULT_CACHE_SERVICE': '', 'ENABLED': True, 'DISTRIBUTED_TRACING': True, 'ANALYTICS_ENABLED': None, 'ANALYTICS_SAMPLE_RATE': True, 'TRACE_QUERY_STRING': None, 'TAGS': {}, 'TRACER': 'oteltrace.tracer', } # List of settings that may be in string import notation. IMPORT_STRINGS = ( 'TRACER', ) # List of settings that have been removed REMOVED_SETTINGS = () def import_from_string(val, setting_name): """ Attempt to import a class from a string representation. """ try: # Nod to tastypie's use of importlib. parts = val.split('.') module_path, class_name = '.'.join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) as e: msg = 'Could not import "{}" for setting "{}". {}: {}.'.format( val, setting_name, e.__class__.__name__, e, ) raise ImportError(msg) class OpenTelemetrySettings(object): """ A settings object, that allows OpenTelemetry settings to be accessed as properties. For example: from oteltrace.contrib.django.conf import settings tracer = settings.TRACER Any setting with string import paths will be automatically resolved and return the class, rather than the string literal. """ def __init__(self, user_settings=None, defaults=None, import_strings=None): if user_settings: self._user_settings = self.__check_user_settings(user_settings) self.defaults = defaults or DEFAULTS if os.environ.get('OPENTELEMETRY_ENV'): self.defaults['TAGS'].update({'env': os.environ.get('OPENTELEMETRY_ENV')}) if os.environ.get('OPENTELEMETRY_SERVICE_NAME'): self.defaults['DEFAULT_SERVICE'] = os.environ.get('OPENTELEMETRY_SERVICE_NAME') host = os.environ.get('OTEL_AGENT_HOST', os.environ.get('OPENTELEMETRY_TRACE_AGENT_HOSTNAME')) if host: self.defaults['AGENT_HOSTNAME'] = host port = os.environ.get('OTEL_TRACE_AGENT_PORT', os.environ.get('OPENTELEMETRY_TRACE_AGENT_PORT')) if port: # if the agent port is a string, the underlying library that creates the socket # stops working try: port = int(port) except ValueError: log.warning('OTEL_TRACE_AGENT_PORT is not an integer value; default to 8126') else: self.defaults['AGENT_PORT'] = port self.import_strings = import_strings or IMPORT_STRINGS @property def user_settings(self): if not hasattr(self, '_user_settings'): self._user_settings = getattr(django_settings, 'OPENTELEMETRY_TRACE', {}) # TODO[manu]: prevents docs import errors; provide a better implementation if 'ENABLED' not in self._user_settings: self._user_settings['ENABLED'] = not django_settings.DEBUG return self._user_settings def __getattr__(self, attr): if attr not in self.defaults: raise AttributeError('Invalid setting: "{}"'.format(attr)) try: # Check if present in user settings val = self.user_settings[attr] except KeyError: # Otherwise, fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if attr in self.import_strings: val = import_from_string(val, attr) # Cache the result setattr(self, attr, val) return val def __check_user_settings(self, user_settings): SETTINGS_DOC = 'http://pypi.datadoghq.com/trace/docs/#module-oteltrace.contrib.django' for setting in REMOVED_SETTINGS: if setting in user_settings: raise RuntimeError( 'The "{}" setting has been removed, check "{}".'.format(setting, SETTINGS_DOC) ) return user_settings settings = OpenTelemetrySettings(None, DEFAULTS, IMPORT_STRINGS) def reload_settings(*args, **kwargs): """ Triggers a reload when Django emits the reloading signal """ global settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'OPENTELEMETRY_TRACE': settings = OpenTelemetrySettings(value, DEFAULTS, IMPORT_STRINGS)
33.101124
104
0.667006
from __future__ import unicode_literals import os import importlib from django.conf import settings as django_settings from ...internal.logger import get_logger log = get_logger(__name__) DEFAULTS = { 'AGENT_HOSTNAME': 'localhost', 'AGENT_PORT': 8126, 'AUTO_INSTRUMENT': True, 'INSTRUMENT_CACHE': True, 'INSTRUMENT_DATABASE': True, 'INSTRUMENT_TEMPLATE': True, 'DEFAULT_DATABASE_PREFIX': '', 'DEFAULT_SERVICE': 'django', 'DEFAULT_CACHE_SERVICE': '', 'ENABLED': True, 'DISTRIBUTED_TRACING': True, 'ANALYTICS_ENABLED': None, 'ANALYTICS_SAMPLE_RATE': True, 'TRACE_QUERY_STRING': None, 'TAGS': {}, 'TRACER': 'oteltrace.tracer', } IMPORT_STRINGS = ( 'TRACER', ) REMOVED_SETTINGS = () def import_from_string(val, setting_name): try: parts = val.split('.') module_path, class_name = '.'.join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) as e: msg = 'Could not import "{}" for setting "{}". {}: {}.'.format( val, setting_name, e.__class__.__name__, e, ) raise ImportError(msg) class OpenTelemetrySettings(object): def __init__(self, user_settings=None, defaults=None, import_strings=None): if user_settings: self._user_settings = self.__check_user_settings(user_settings) self.defaults = defaults or DEFAULTS if os.environ.get('OPENTELEMETRY_ENV'): self.defaults['TAGS'].update({'env': os.environ.get('OPENTELEMETRY_ENV')}) if os.environ.get('OPENTELEMETRY_SERVICE_NAME'): self.defaults['DEFAULT_SERVICE'] = os.environ.get('OPENTELEMETRY_SERVICE_NAME') host = os.environ.get('OTEL_AGENT_HOST', os.environ.get('OPENTELEMETRY_TRACE_AGENT_HOSTNAME')) if host: self.defaults['AGENT_HOSTNAME'] = host port = os.environ.get('OTEL_TRACE_AGENT_PORT', os.environ.get('OPENTELEMETRY_TRACE_AGENT_PORT')) if port: # if the agent port is a string, the underlying library that creates the socket # stops working try: port = int(port) except ValueError: log.warning('OTEL_TRACE_AGENT_PORT is not an integer value; default to 8126') else: self.defaults['AGENT_PORT'] = port self.import_strings = import_strings or IMPORT_STRINGS @property def user_settings(self): if not hasattr(self, '_user_settings'): self._user_settings = getattr(django_settings, 'OPENTELEMETRY_TRACE', {}) # TODO[manu]: prevents docs import errors; provide a better implementation if 'ENABLED' not in self._user_settings: self._user_settings['ENABLED'] = not django_settings.DEBUG return self._user_settings def __getattr__(self, attr): if attr not in self.defaults: raise AttributeError('Invalid setting: "{}"'.format(attr)) try: # Check if present in user settings val = self.user_settings[attr] except KeyError: # Otherwise, fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if attr in self.import_strings: val = import_from_string(val, attr) # Cache the result setattr(self, attr, val) return val def __check_user_settings(self, user_settings): SETTINGS_DOC = 'http://pypi.datadoghq.com/trace/docs/ for setting in REMOVED_SETTINGS: if setting in user_settings: raise RuntimeError( 'The "{}" setting has been removed, check "{}".'.format(setting, SETTINGS_DOC) ) return user_settings settings = OpenTelemetrySettings(None, DEFAULTS, IMPORT_STRINGS) def reload_settings(*args, **kwargs): global settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'OPENTELEMETRY_TRACE': settings = OpenTelemetrySettings(value, DEFAULTS, IMPORT_STRINGS)
true
true
f735e01c64e62313be6f9983c47ef6c910fb9043
3,904
py
Python
app/recipe/views.py
jhgutsol1290/recipe-app-api
1c2ca015a05b0309f80b074e4df08e5180a1cbe7
[ "MIT" ]
null
null
null
app/recipe/views.py
jhgutsol1290/recipe-app-api
1c2ca015a05b0309f80b074e4df08e5180a1cbe7
[ "MIT" ]
null
null
null
app/recipe/views.py
jhgutsol1290/recipe-app-api
1c2ca015a05b0309f80b074e4df08e5180a1cbe7
[ "MIT" ]
null
null
null
from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets, mixins, status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from core.models import Tag, Ingredient, Recipe from recipe import serializers class BaseRecipeAttrViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): """ Base viewset fro user owned recipe attr. We can create this class to avoid writting repetitve code, and then we can inherit from this class when needed. Awesome!!! """ authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): """ Return objects for the current auth user only, this can be done in queryset, but is recommended to be done here """ assigned_only = bool( int(self.request.query_params.get('assigned_only', 0)) ) queryset = self.queryset if assigned_only: queryset = queryset.filter(recipe__isnull=False) return queryset.filter( user=self.request.user ).order_by('-name').distinct() def perform_create(self, serializer): """ Create a new ingredient with the user, You override perform_create methos and pass the user from request """ serializer.save(user=self.request.user) class TagViewSet(BaseRecipeAttrViewSet): """Manage tags in database""" queryset = Tag.objects.all() serializer_class = serializers.TagSerializer class IngredientViewSet(BaseRecipeAttrViewSet): """Manage ingredients in db""" queryset = Ingredient.objects.all() serializer_class = serializers.IngredientSerializer class RecipeViewSet(viewsets.ModelViewSet): """Manage recipes in db""" serializer_class = serializers.RecipeSerializer queryset = Recipe.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def _params_to_ints(self, qs): """Convert a list of string ids to a loist of integers""" return [int(str_id) for str_id in qs.split(',')] def get_queryset(self): """Retrieve recipies for the auth user""" tags = self.request.query_params.get('tags') ingredients = self.request.query_params.get('ingredients') queryset = self.queryset if tags: tag_ids = self._params_to_ints(tags) queryset = queryset.filter(tags__id__in=tag_ids) if ingredients: ingredient_ids = self._params_to_ints(ingredients) queryset = queryset.filter(ingredients__id__in=ingredient_ids) return queryset.filter(user=self.request.user) def get_serializer_class(self): """Return appropiate serializer class""" if self.action == 'retrieve': return serializers.RecipeDetailSerializer elif self.action == 'upload_image': return serializers.RecipeImageSerializer return self.serializer_class def perform_create(self, serializer): """Create a new recipe""" serializer.save(user=self.request.user) @action(methods=['POST'], detail=True, url_path='upload-image') def upload_image(self, request, pk=None): """Upload an image to a recipe""" recipe = self.get_object() serializer = self.get_serializer( recipe, data=request.data ) if serializer.is_valid(): serializer.save() return Response( serializer.data, status=status.HTTP_200_OK ) return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST )
33.655172
74
0.660092
from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets, mixins, status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from core.models import Tag, Ingredient, Recipe from recipe import serializers class BaseRecipeAttrViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): assigned_only = bool( int(self.request.query_params.get('assigned_only', 0)) ) queryset = self.queryset if assigned_only: queryset = queryset.filter(recipe__isnull=False) return queryset.filter( user=self.request.user ).order_by('-name').distinct() def perform_create(self, serializer): serializer.save(user=self.request.user) class TagViewSet(BaseRecipeAttrViewSet): queryset = Tag.objects.all() serializer_class = serializers.TagSerializer class IngredientViewSet(BaseRecipeAttrViewSet): queryset = Ingredient.objects.all() serializer_class = serializers.IngredientSerializer class RecipeViewSet(viewsets.ModelViewSet): serializer_class = serializers.RecipeSerializer queryset = Recipe.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def _params_to_ints(self, qs): return [int(str_id) for str_id in qs.split(',')] def get_queryset(self): tags = self.request.query_params.get('tags') ingredients = self.request.query_params.get('ingredients') queryset = self.queryset if tags: tag_ids = self._params_to_ints(tags) queryset = queryset.filter(tags__id__in=tag_ids) if ingredients: ingredient_ids = self._params_to_ints(ingredients) queryset = queryset.filter(ingredients__id__in=ingredient_ids) return queryset.filter(user=self.request.user) def get_serializer_class(self): if self.action == 'retrieve': return serializers.RecipeDetailSerializer elif self.action == 'upload_image': return serializers.RecipeImageSerializer return self.serializer_class def perform_create(self, serializer): serializer.save(user=self.request.user) @action(methods=['POST'], detail=True, url_path='upload-image') def upload_image(self, request, pk=None): recipe = self.get_object() serializer = self.get_serializer( recipe, data=request.data ) if serializer.is_valid(): serializer.save() return Response( serializer.data, status=status.HTTP_200_OK ) return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST )
true
true
f735e065a680a895d5a324a0b9b4e185811f440e
1,040
py
Python
test_sample.py
corganhejijun/frontal-trans
1509babf2447a53a772703b09cb6a2daec6968a7
[ "MIT" ]
6
2019-10-07T07:34:28.000Z
2020-11-17T13:04:37.000Z
test_sample.py
corganhejijun/frontal-trans
1509babf2447a53a772703b09cb6a2daec6968a7
[ "MIT" ]
3
2019-09-18T09:56:36.000Z
2020-11-25T09:54:06.000Z
test_sample.py
corganhejijun/frontal-trans
1509babf2447a53a772703b09cb6a2daec6968a7
[ "MIT" ]
3
2019-11-01T04:39:07.000Z
2021-04-21T08:19:19.000Z
# -*- coding: utf-8 -*- import os import cv2 from scipy import misc from PIL import Image sample_path = 'datasets/celeb_train/lfw_trans' dest_path = sample_path + "/../dest" middleSize = 64 imgSize = 256 kernel_size = (5, 5) sigma = 5 if not os.path.exists(dest_path): os.mkdir(dest_path) fileList = os.listdir(sample_path) for index, file in enumerate(fileList): imgPath = os.path.join(sample_path, file) if os.path.isdir(imgPath): continue print("procesing " + file + " " + str(index+1) + '/' + str(len(fileList))) img = cv2.cvtColor(cv2.imread(imgPath), cv2.COLOR_BGR2RGB) img = misc.imresize(img, (middleSize, middleSize), interp='bilinear') img = misc.imresize(img, (imgSize, imgSize), interp='bilinear') img = cv2.GaussianBlur(img, kernel_size, sigma) combineImg = Image.new('RGB', (img.shape[0]*2, img.shape[0])) combineImg.paste(Image.fromarray(img), (0,0)) combineImg.paste(Image.fromarray(img), (img.shape[0]+1,0)) misc.imsave(os.path.join(dest_path, file), combineImg)
33.548387
78
0.683654
import os import cv2 from scipy import misc from PIL import Image sample_path = 'datasets/celeb_train/lfw_trans' dest_path = sample_path + "/../dest" middleSize = 64 imgSize = 256 kernel_size = (5, 5) sigma = 5 if not os.path.exists(dest_path): os.mkdir(dest_path) fileList = os.listdir(sample_path) for index, file in enumerate(fileList): imgPath = os.path.join(sample_path, file) if os.path.isdir(imgPath): continue print("procesing " + file + " " + str(index+1) + '/' + str(len(fileList))) img = cv2.cvtColor(cv2.imread(imgPath), cv2.COLOR_BGR2RGB) img = misc.imresize(img, (middleSize, middleSize), interp='bilinear') img = misc.imresize(img, (imgSize, imgSize), interp='bilinear') img = cv2.GaussianBlur(img, kernel_size, sigma) combineImg = Image.new('RGB', (img.shape[0]*2, img.shape[0])) combineImg.paste(Image.fromarray(img), (0,0)) combineImg.paste(Image.fromarray(img), (img.shape[0]+1,0)) misc.imsave(os.path.join(dest_path, file), combineImg)
true
true
f735e0b0bfb2b3d775aacd5ba8c56eb9fc4ac69b
3,506
py
Python
gmn/src/d1_gmn/app/node_registry.py
DataONEorg/d1_python
dfab267c3adea913ab0e0073ed9dc1ee50b5b8eb
[ "Apache-2.0" ]
15
2016-10-28T13:56:52.000Z
2022-01-31T19:07:49.000Z
gmn/src/d1_gmn/app/node_registry.py
DataONEorg/d1_python
dfab267c3adea913ab0e0073ed9dc1ee50b5b8eb
[ "Apache-2.0" ]
56
2017-03-16T03:52:32.000Z
2022-03-12T01:05:28.000Z
gmn/src/d1_gmn/app/node_registry.py
DataONEorg/d1_python
dfab267c3adea913ab0e0073ed9dc1ee50b5b8eb
[ "Apache-2.0" ]
11
2016-05-31T16:22:02.000Z
2020-10-05T14:37:10.000Z
# This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2019 DataONE # # 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. """Node Registry cache. - Retrieve, hold and update a cache of the Node Registry for the DataONE environment in which this MN is registered. - Query the Node Registry. """ import logging import d1_common.xml import d1_client.cnclient import django.conf import django.core.cache log = logging.getLogger(__name__) def get_cn_subjects(): cn_subjects = django.core.cache.cache.get("cn_subjects") if cn_subjects is not None: return cn_subjects if django.conf.settings.STAND_ALONE: log.info("Running in stand-alone mode. Skipping node registry download.") set_empty_cn_subjects_cache() else: log.info("Running in environment: {}".format(django.conf.settings.DATAONE_ROOT)) set_cn_subjects_for_environment() return django.core.cache.cache.get("cn_subjects") def set_empty_cn_subjects_cache(): django.core.cache.cache.set("cn_subjects", set()) log.info("CN Subjects set to empty list") def set_cn_subjects_for_environment(): # Attempt to get a list of trusted subjects from the DataONE root for the # environment of which this MN is a member. try: cn_subjects = get_cn_subjects_from_dataone_root() except Exception as e: log.warning( "Unable to get CN Subjects from the DataONE environment. " "If this server is being used for testing, see the STAND_ALONE setting. " 'error="{}" env="{}"'.format(str(e), django.conf.settings.DATAONE_ROOT) ) cn_subjects = [] else: log.info( "CN Subjects successfully retrieved from the DataONE environment: {}".format( ", ".join(cn_subjects) ) ) django.core.cache.cache.set("cn_subjects", set(cn_subjects)) def get_cn_subjects_string(): return ", ".join(sorted(list(get_cn_subjects()))) def get_cn_subjects_from_dataone_root(): nodes = download_node_registry() cn_subjects = set() for node in nodes.node: try: services = node.services.service except AttributeError: pass else: for service in services: if service.name == "CNCore": for subject in node.subject: cn_subjects.add(d1_common.xml.get_req_val(subject)) break return cn_subjects def download_node_registry(): log.info( "Downloading node registry from environment: {}".format( django.conf.settings.DATAONE_ROOT ) ) client = create_root_cn_client() return client.listNodes() def create_root_cn_client(): return d1_client.cnclient.CoordinatingNodeClient(django.conf.settings.DATAONE_ROOT)
31.303571
89
0.684541
import logging import d1_common.xml import d1_client.cnclient import django.conf import django.core.cache log = logging.getLogger(__name__) def get_cn_subjects(): cn_subjects = django.core.cache.cache.get("cn_subjects") if cn_subjects is not None: return cn_subjects if django.conf.settings.STAND_ALONE: log.info("Running in stand-alone mode. Skipping node registry download.") set_empty_cn_subjects_cache() else: log.info("Running in environment: {}".format(django.conf.settings.DATAONE_ROOT)) set_cn_subjects_for_environment() return django.core.cache.cache.get("cn_subjects") def set_empty_cn_subjects_cache(): django.core.cache.cache.set("cn_subjects", set()) log.info("CN Subjects set to empty list") def set_cn_subjects_for_environment(): try: cn_subjects = get_cn_subjects_from_dataone_root() except Exception as e: log.warning( "Unable to get CN Subjects from the DataONE environment. " "If this server is being used for testing, see the STAND_ALONE setting. " 'error="{}" env="{}"'.format(str(e), django.conf.settings.DATAONE_ROOT) ) cn_subjects = [] else: log.info( "CN Subjects successfully retrieved from the DataONE environment: {}".format( ", ".join(cn_subjects) ) ) django.core.cache.cache.set("cn_subjects", set(cn_subjects)) def get_cn_subjects_string(): return ", ".join(sorted(list(get_cn_subjects()))) def get_cn_subjects_from_dataone_root(): nodes = download_node_registry() cn_subjects = set() for node in nodes.node: try: services = node.services.service except AttributeError: pass else: for service in services: if service.name == "CNCore": for subject in node.subject: cn_subjects.add(d1_common.xml.get_req_val(subject)) break return cn_subjects def download_node_registry(): log.info( "Downloading node registry from environment: {}".format( django.conf.settings.DATAONE_ROOT ) ) client = create_root_cn_client() return client.listNodes() def create_root_cn_client(): return d1_client.cnclient.CoordinatingNodeClient(django.conf.settings.DATAONE_ROOT)
true
true
f735e13bab66faf531dc0c6b42371e197f6d91a6
3,037
py
Python
freezeyt/cli.py
encukou/freezeyt
f0783bb3e001f181ce33718b0cbd2ddbd0e56af0
[ "MIT" ]
7
2020-09-23T15:27:09.000Z
2022-03-20T19:31:41.000Z
freezeyt/cli.py
encukou/freezeyt
f0783bb3e001f181ce33718b0cbd2ddbd0e56af0
[ "MIT" ]
160
2020-07-06T17:58:35.000Z
2022-03-30T13:06:07.000Z
freezeyt/cli.py
encukou/freezeyt
f0783bb3e001f181ce33718b0cbd2ddbd0e56af0
[ "MIT" ]
10
2020-07-06T18:05:10.000Z
2022-03-12T21:20:11.000Z
import sys import click import yaml from freezeyt.freezer import freeze from freezeyt.util import import_variable_from_module @click.command() @click.argument('module_name') @click.argument('dest_path', required=False) @click.option('--prefix', help='URL where we want to deploy our static site ' + '(the application root)') @click.option('--extra-page', 'extra_pages', multiple=True, help="URLs of a page to freeze even if it's not linked from " + "the application. May be repeated.") @click.option('-c', '--config', 'config_file', type=click.File(), help='Path to configuration YAML file') @click.option('-C', '--import-config', 'config_var', help='Python variable with configuration') @click.option('--progress', 'progress', type=click.Choice(['none', 'bar', 'log']), help='Select how to display progress') def main( module_name, dest_path, prefix, extra_pages, config_file, config_var, progress, ): """ MODULE_NAME Name of the Python web app module which will be frozen. DEST_PATH Absolute or relative path to the directory to which the files will be frozen. Example use: python -m freezeyt demo_app build --prefix 'http://localhost:8000/' --extra-page /extra/ python -m freezeyt demo_app build -c config.yaml """ if config_file and config_var: raise click.UsageError( "Can't pass configuration both in a file and in a variable." ) elif config_file != None: config = yaml.safe_load(config_file) if not isinstance(config, dict): raise SyntaxError( f'File {config_file.name} is not a YAML dictionary.' ) elif config_var is not None: config = import_variable_from_module(config_var) else: config = {} if extra_pages: config.setdefault('extra_pages', []).extend(extra_pages) if prefix != None: config['prefix'] = prefix if 'output' in config: if dest_path is not None: raise click.UsageError( 'DEST_PATH argument is not needed if output is configured from file' ) else: if dest_path is None: raise click.UsageError('DEST_PATH argument is required') config['output'] = {'type': 'dir', 'dir': dest_path} if progress is None: if sys.stdout.isatty(): progress = 'bar' else: progress = 'log' if progress == 'bar': config.setdefault( 'plugins', []).append('freezeyt.progressbar:ProgressBarPlugin') if progress in ('log', 'bar'): # The 'log' plugin is activated both with --progress=log and # --progress=bar. config.setdefault( 'plugins', []).append('freezeyt.progressbar:LogPlugin') app = import_variable_from_module( module_name, default_variable_name='app', ) freeze(app, config)
31.309278
96
0.609812
import sys import click import yaml from freezeyt.freezer import freeze from freezeyt.util import import_variable_from_module @click.command() @click.argument('module_name') @click.argument('dest_path', required=False) @click.option('--prefix', help='URL where we want to deploy our static site ' + '(the application root)') @click.option('--extra-page', 'extra_pages', multiple=True, help="URLs of a page to freeze even if it's not linked from " + "the application. May be repeated.") @click.option('-c', '--config', 'config_file', type=click.File(), help='Path to configuration YAML file') @click.option('-C', '--import-config', 'config_var', help='Python variable with configuration') @click.option('--progress', 'progress', type=click.Choice(['none', 'bar', 'log']), help='Select how to display progress') def main( module_name, dest_path, prefix, extra_pages, config_file, config_var, progress, ): if config_file and config_var: raise click.UsageError( "Can't pass configuration both in a file and in a variable." ) elif config_file != None: config = yaml.safe_load(config_file) if not isinstance(config, dict): raise SyntaxError( f'File {config_file.name} is not a YAML dictionary.' ) elif config_var is not None: config = import_variable_from_module(config_var) else: config = {} if extra_pages: config.setdefault('extra_pages', []).extend(extra_pages) if prefix != None: config['prefix'] = prefix if 'output' in config: if dest_path is not None: raise click.UsageError( 'DEST_PATH argument is not needed if output is configured from file' ) else: if dest_path is None: raise click.UsageError('DEST_PATH argument is required') config['output'] = {'type': 'dir', 'dir': dest_path} if progress is None: if sys.stdout.isatty(): progress = 'bar' else: progress = 'log' if progress == 'bar': config.setdefault( 'plugins', []).append('freezeyt.progressbar:ProgressBarPlugin') if progress in ('log', 'bar'): config.setdefault( 'plugins', []).append('freezeyt.progressbar:LogPlugin') app = import_variable_from_module( module_name, default_variable_name='app', ) freeze(app, config)
true
true
f735e15ae6ba7a49fa2a7da756be5fc32bfde867
227
py
Python
learn-to-code-with-python/17-Dictionaries-the-Basics/the-in-and-not-in-operators-on-a-dictionary.py
MaciejZurek/python_practicing
0a426f2aed151573e1f8678e0239ff596d92bbde
[ "MIT" ]
null
null
null
learn-to-code-with-python/17-Dictionaries-the-Basics/the-in-and-not-in-operators-on-a-dictionary.py
MaciejZurek/python_practicing
0a426f2aed151573e1f8678e0239ff596d92bbde
[ "MIT" ]
null
null
null
learn-to-code-with-python/17-Dictionaries-the-Basics/the-in-and-not-in-operators-on-a-dictionary.py
MaciejZurek/python_practicing
0a426f2aed151573e1f8678e0239ff596d92bbde
[ "MIT" ]
null
null
null
pokemon = { "Fire": ["Charmander", "Charmeleon", "Charizard"], "Water": ["Squirtle", "Warturtle", "Blastiose"], "Grass": ["Bulbasaur", "Venusaur", "Ivysaur"] } print("Fire" in pokemon) print("Electric" in pokemon)
25.222222
54
0.61674
pokemon = { "Fire": ["Charmander", "Charmeleon", "Charizard"], "Water": ["Squirtle", "Warturtle", "Blastiose"], "Grass": ["Bulbasaur", "Venusaur", "Ivysaur"] } print("Fire" in pokemon) print("Electric" in pokemon)
true
true
f735e2a9e13dbd62de2c29ea355c89e45b70252a
2,380
py
Python
amime/modules/anime/TV-SHOW/KATEGORI/MAHOU SHOUJO/ktgr_action3.py
Myudi422/ccgnime_req
a0f7596ba101204539b4120dffa08912b6560efe
[ "MIT" ]
null
null
null
amime/modules/anime/TV-SHOW/KATEGORI/MAHOU SHOUJO/ktgr_action3.py
Myudi422/ccgnime_req
a0f7596ba101204539b4120dffa08912b6560efe
[ "MIT" ]
null
null
null
amime/modules/anime/TV-SHOW/KATEGORI/MAHOU SHOUJO/ktgr_action3.py
Myudi422/ccgnime_req
a0f7596ba101204539b4120dffa08912b6560efe
[ "MIT" ]
null
null
null
import httpx from anilist.types import Anime from pyrogram import filters from pyrogram.types import CallbackQuery from pyromod.helpers import ikb from pyromod.nav import Pagination from amime.amime import Amime @Amime.on_callback_query(filters.regex(r"^tv_mahousj3 anime (?P<page>\d+)")) async def anime_suggestions(bot: Amime, callback: CallbackQuery): page = int(callback.matches[0]["page"]) message = callback.message lang = callback._lang keyboard = [] async with httpx.AsyncClient(http2=True) as client: response = await client.post( url="https://graphql.anilist.co", json=dict( query=""" query($per_page: Int) { Page(page: 4, perPage: $per_page) { media(type: ANIME, format: TV, sort: TRENDING_DESC, status: FINISHED, genre: "mahou shoujo") { id title { romaji english native } siteUrl } } } """, variables=dict( perPage=100, ), ), headers={ "Content-Type": "application/json", "Accept": "application/json", }, ) data = response.json() await client.aclose() if data["data"]: items = data["data"]["Page"]["media"] suggestions = [ Anime(id=item["id"], title=item["title"], url=item["siteUrl"]) for item in items ] layout = Pagination( suggestions, item_data=lambda i, pg: f"menu {i.id}", item_title=lambda i, pg: i.title.romaji, page_data=lambda pg: f"tv_mahousj3 anime {pg}", ) lines = layout.create(page, lines=8) if len(lines) > 0: keyboard += lines keyboard.append([(lang.Prev, "tv_mahousj2 anime 1"), (lang.Next, "tv_mahousj4 anime 1")]) keyboard.append([(lang.back_button, "ktgr-finish")]) await message.edit_text( lang.suggestions_text, reply_markup=ikb(keyboard), )
32.162162
118
0.485714
import httpx from anilist.types import Anime from pyrogram import filters from pyrogram.types import CallbackQuery from pyromod.helpers import ikb from pyromod.nav import Pagination from amime.amime import Amime @Amime.on_callback_query(filters.regex(r"^tv_mahousj3 anime (?P<page>\d+)")) async def anime_suggestions(bot: Amime, callback: CallbackQuery): page = int(callback.matches[0]["page"]) message = callback.message lang = callback._lang keyboard = [] async with httpx.AsyncClient(http2=True) as client: response = await client.post( url="https://graphql.anilist.co", json=dict( query=""" query($per_page: Int) { Page(page: 4, perPage: $per_page) { media(type: ANIME, format: TV, sort: TRENDING_DESC, status: FINISHED, genre: "mahou shoujo") { id title { romaji english native } siteUrl } } } """, variables=dict( perPage=100, ), ), headers={ "Content-Type": "application/json", "Accept": "application/json", }, ) data = response.json() await client.aclose() if data["data"]: items = data["data"]["Page"]["media"] suggestions = [ Anime(id=item["id"], title=item["title"], url=item["siteUrl"]) for item in items ] layout = Pagination( suggestions, item_data=lambda i, pg: f"menu {i.id}", item_title=lambda i, pg: i.title.romaji, page_data=lambda pg: f"tv_mahousj3 anime {pg}", ) lines = layout.create(page, lines=8) if len(lines) > 0: keyboard += lines keyboard.append([(lang.Prev, "tv_mahousj2 anime 1"), (lang.Next, "tv_mahousj4 anime 1")]) keyboard.append([(lang.back_button, "ktgr-finish")]) await message.edit_text( lang.suggestions_text, reply_markup=ikb(keyboard), )
true
true
f735e2aea9b9012219f860b604255299c65e9e32
593
py
Python
test_ucf101.py
mental689/pytorch-c3d
578bf43a2628decc50fd554437668d5490f6e77d
[ "Apache-2.0" ]
3
2019-03-15T17:42:26.000Z
2021-11-18T04:17:16.000Z
test_ucf101.py
mental689/pytorch-c3d
578bf43a2628decc50fd554437668d5490f6e77d
[ "Apache-2.0" ]
null
null
null
test_ucf101.py
mental689/pytorch-c3d
578bf43a2628decc50fd554437668d5490f6e77d
[ "Apache-2.0" ]
1
2019-03-15T17:42:38.000Z
2019-03-15T17:42:38.000Z
# coding: utf-8 from network.trainer import * video_train_list = '/media/tuananhn/903a7d3c-0ce5-444b-ad39-384fcda231ed/UCF101/video-caffe/examples/c3d_ucf101/c3d_ucf101_train_split1.txt' video_test_list = '/media/tuananhn/903a7d3c-0ce5-444b-ad39-384fcda231ed/UCF101/video-caffe/examples/c3d_ucf101/c3d_ucf101_test_split1.txt' trainer = UCFClipTrainer(video_train_list, video_test_list, batch_size=1) trainer.load(path='static/models/model_000008.pt') val_loss, top1, top5 = trainer.test() print('Epoch 0/10: Top-1 accuracy {:.2f} %, Top-5 accuracy: {:.2f} %'.format(top1.item(), top5.item()))
65.888889
140
0.789207
from network.trainer import * video_train_list = '/media/tuananhn/903a7d3c-0ce5-444b-ad39-384fcda231ed/UCF101/video-caffe/examples/c3d_ucf101/c3d_ucf101_train_split1.txt' video_test_list = '/media/tuananhn/903a7d3c-0ce5-444b-ad39-384fcda231ed/UCF101/video-caffe/examples/c3d_ucf101/c3d_ucf101_test_split1.txt' trainer = UCFClipTrainer(video_train_list, video_test_list, batch_size=1) trainer.load(path='static/models/model_000008.pt') val_loss, top1, top5 = trainer.test() print('Epoch 0/10: Top-1 accuracy {:.2f} %, Top-5 accuracy: {:.2f} %'.format(top1.item(), top5.item()))
true
true
f735e312a81e88978793ec77d681c3348d55b18e
14,779
py
Python
niapy/algorithms/modified/saba.py
altaregos/NiaPy
74f1b2827778d9086603f4a8cb523f6b5537212a
[ "MIT" ]
202
2018-02-06T12:13:42.000Z
2022-03-18T16:33:20.000Z
niapy/algorithms/modified/saba.py
altaregos/NiaPy
74f1b2827778d9086603f4a8cb523f6b5537212a
[ "MIT" ]
262
2018-02-06T14:49:15.000Z
2022-03-25T19:49:46.000Z
niapy/algorithms/modified/saba.py
altaregos/NiaPy
74f1b2827778d9086603f4a8cb523f6b5537212a
[ "MIT" ]
136
2018-02-06T16:55:32.000Z
2022-03-05T17:49:52.000Z
# encoding=utf8 import logging import numpy as np from niapy.algorithms.algorithm import Algorithm logging.basicConfig() logger = logging.getLogger('niapy.algorithms.modified') logger.setLevel('INFO') __all__ = ['AdaptiveBatAlgorithm', 'SelfAdaptiveBatAlgorithm'] class AdaptiveBatAlgorithm(Algorithm): r"""Implementation of Adaptive bat algorithm. Algorithm: Adaptive bat algorithm Date: April 2019 Authors: Klemen Berkovič License: MIT Attributes: Name (List[str]): List of strings representing algorithm name. epsilon (float): Scaling factor. alpha (float): Constant for updating loudness. pulse_rate (float): Pulse rate. min_frequency (float): Minimum frequency. max_frequency (float): Maximum frequency. See Also: * :class:`niapy.algorithms.Algorithm` """ Name = ['AdaptiveBatAlgorithm', 'ABA'] @staticmethod def info(): r"""Get basic information about the algorithm. Returns: str: Basic information. See Also: * :func:`niapy.algorithms.Algorithm.info` """ return r"""TODO""" def __init__(self, population_size=100, starting_loudness=0.5, epsilon=0.001, alpha=1.0, pulse_rate=0.5, min_frequency=0.0, max_frequency=2.0, *args, **kwargs): """Initialize AdaptiveBatAlgorithm. Args: population_size (Optional[int]): Population size. starting_loudness (Optional[float]): Starting loudness. epsilon (Optional[float]): Scaling factor. alpha (Optional[float]): Constant for updating loudness. pulse_rate (Optional[float]): Pulse rate. min_frequency (Optional[float]): Minimum frequency. max_frequency (Optional[float]): Maximum frequency. See Also: * :func:`niapy.algorithms.Algorithm.__init__` """ super().__init__(population_size, *args, **kwargs) self.starting_loudness = starting_loudness self.epsilon = epsilon self.alpha = alpha self.pulse_rate = pulse_rate self.min_frequency = min_frequency self.max_frequency = max_frequency def set_parameters(self, population_size=100, starting_loudness=0.5, epsilon=0.001, alpha=1.0, pulse_rate=0.5, min_frequency=0.0, max_frequency=2.0, **kwargs): r"""Set the parameters of the algorithm. Args: population_size (Optional[int]): Population size. starting_loudness (Optional[float]): Starting loudness. epsilon (Optional[float]): Scaling factor. alpha (Optional[float]): Constant for updating loudness. pulse_rate (Optional[float]): Pulse rate. min_frequency (Optional[float]): Minimum frequency. max_frequency (Optional[float]): Maximum frequency. See Also: * :func:`niapy.algorithms.Algorithm.set_parameters` """ super().set_parameters(population_size=population_size, **kwargs) self.starting_loudness = starting_loudness self.epsilon = epsilon self.alpha = alpha self.pulse_rate = pulse_rate self.min_frequency = min_frequency self.max_frequency = max_frequency def get_parameters(self): r"""Get algorithm parameters. Returns: Dict[str, Any]: Arguments values. See Also: * :func:`niapy.algorithms.algorithm.Algorithm.get_parameters` """ d = super().get_parameters() d.update({ 'starting_loudness': self.starting_loudness, 'epsilon': self.epsilon, 'alpha': self.alpha, 'pulse_rate': self.pulse_rate, 'min_frequency': self.min_frequency, 'max_frequency': self.max_frequency }) return d def init_population(self, task): r"""Initialize the starting population. Args: task (Task): Optimization task Returns: Tuple[numpy.ndarray, numpy.ndarray[float], Dict[str, Any]]: 1. New population. 2. New population fitness/function values. 3. Additional arguments: * loudness (float): Loudness. * velocities (numpy.ndarray[float]): Velocity. See Also: * :func:`niapy.algorithms.Algorithm.init_population` """ population, fitness, d = super().init_population(task) loudness = np.full(self.population_size, self.starting_loudness) velocities = np.zeros((self.population_size, task.dimension)) d.update({'loudness': loudness, 'velocities': velocities}) return population, fitness, d def local_search(self, best, loudness, task, **kwargs): r"""Improve the best solution according to the Yang (2010). Args: best (numpy.ndarray): Global best individual. loudness (float): Loudness. task (Task): Optimization task. Returns: numpy.ndarray: New solution based on global best individual. """ return task.repair(best + self.epsilon * loudness * self.normal(0, 1, task.dimension), rng=self.rng) def update_loudness(self, loudness): r"""Update loudness when the prey is found. Args: loudness (float): Loudness. Returns: float: New loudness. """ new_loudness = loudness * self.alpha return new_loudness if new_loudness > 1e-13 else self.starting_loudness def run_iteration(self, task, population, population_fitness, best_x, best_fitness, **params): r"""Core function of Bat Algorithm. Args: task (Task): Optimization task. population (numpy.ndarray): Current population population_fitness (numpy.ndarray[float]): Current population fitness/function values best_x (numpy.ndarray): Current best individual best_fitness (float): Current best individual function/fitness value params (Dict[str, Any]): Additional algorithm arguments Returns: Tuple[numpy.ndarray, numpy.ndarray[float], Dict[str, Any]]: 1. New population 2. New population fitness/function values 3. Additional arguments: * loudness (numpy.ndarray[float]): Loudness. * velocities (numpy.ndarray[float]): Velocities. """ loudness = params.pop('loudness') velocities = params.pop('velocities') for i in range(self.population_size): frequency = self.min_frequency + (self.max_frequency - self.min_frequency) * self.random() velocities[i] += (population[i] - best_x) * frequency if self.random() > self.pulse_rate: solution = self.local_search(best=best_x, loudness=loudness[i], task=task, i=i, Sol=population) else: solution = task.repair(population[i] + velocities[i], rng=self.rng) new_fitness = task.eval(solution) if (new_fitness <= population_fitness[i]) and (self.random() < loudness[i]): population[i], population_fitness[i] = solution, new_fitness if new_fitness <= best_fitness: best_x, best_fitness, loudness[i] = solution.copy(), new_fitness, self.update_loudness(loudness[i]) return population, population_fitness, best_x, best_fitness, {'loudness': loudness, 'velocities': velocities} class SelfAdaptiveBatAlgorithm(AdaptiveBatAlgorithm): r"""Implementation of Hybrid bat algorithm. Algorithm: Self Adaptive Bat Algorithm Date: April 2019 Author: Klemen Berkovič License: MIT Reference paper: Fister Jr., Iztok and Fister, Dusan and Yang, Xin-She. "A Hybrid Bat Algorithm". Elektrotehniški vestnik, 2013. 1-7. Attributes: Name (List[str]): List of strings representing algorithm name. A_l (Optional[float]): Lower limit of loudness. A_u (Optional[float]): Upper limit of loudness. r_l (Optional[float]): Lower limit of pulse rate. r_u (Optional[float]): Upper limit of pulse rate. tao_1 (Optional[float]): Learning rate for loudness. tao_2 (Optional[float]): Learning rate for pulse rate. See Also: * :class:`niapy.algorithms.basic.BatAlgorithm` """ Name = ['SelfAdaptiveBatAlgorithm', 'SABA'] @staticmethod def info(): r"""Get basic information about the algorithm. Returns: str: Basic information. See Also: * :func:`niapy.algorithms.Algorithm.info` """ return r"""Fister Jr., Iztok and Fister, Dusan and Yang, Xin-She. "A Hybrid Bat Algorithm". Elektrotehniški vestnik, 2013. 1-7.""" def __init__(self, min_loudness=0.9, max_loudness=1.0, min_pulse_rate=0.001, max_pulse_rate=0.1, tao_1=0.1, tao_2=0.1, *args, **kwargs): """Initialize SelfAdaptiveBatAlgorithm. Args: min_loudness (Optional[float]): Lower limit of loudness. max_loudness (Optional[float]): Upper limit of loudness. min_pulse_rate (Optional[float]): Lower limit of pulse rate. max_pulse_rate (Optional[float]): Upper limit of pulse rate. tao_1 (Optional[float]): Learning rate for loudness. tao_2 (Optional[float]): Learning rate for pulse rate. See Also: * :func:`niapy.algorithms.modified.AdaptiveBatAlgorithm.__init__` """ super().__init__(*args, **kwargs) self.min_loudness = min_loudness self.max_loudness = max_loudness self.min_pulse_rate = min_pulse_rate self.max_pulse_rate = max_pulse_rate self.tao_1 = tao_1 self.tao_2 = tao_2 def set_parameters(self, min_loudness=0.9, max_loudness=1.0, min_pulse_rate=0.001, max_pulse_rate=0.1, tao_1=0.1, tao_2=0.1, **kwargs): r"""Set core parameters of HybridBatAlgorithm algorithm. Args: min_loudness (Optional[float]): Lower limit of loudness. max_loudness (Optional[float]): Upper limit of loudness. min_pulse_rate (Optional[float]): Lower limit of pulse rate. max_pulse_rate (Optional[float]): Upper limit of pulse rate. tao_1 (Optional[float]): Learning rate for loudness. tao_2 (Optional[float]): Learning rate for pulse rate. See Also: * :func:`niapy.algorithms.modified.AdaptiveBatAlgorithm.set_parameters` """ super().set_parameters(**kwargs) self.min_loudness = min_loudness self.max_loudness = max_loudness self.min_pulse_rate = min_pulse_rate self.max_pulse_rate = max_pulse_rate self.tao_1 = tao_1 self.tao_2 = tao_2 def get_parameters(self): r"""Get parameters of the algorithm. Returns: Dict[str, Any]: Parameters of the algorithm. See Also: * :func:`niapy.algorithms.modified.AdaptiveBatAlgorithm.get_parameters` """ d = AdaptiveBatAlgorithm.get_parameters(self) d.update({ 'min_loudness': self.min_loudness, 'max_loudness': self.max_loudness, 'min_pulse_rate': self.min_pulse_rate, 'max_pulse_rate': self.max_pulse_rate, 'tao_1': self.tao_1, 'tao_2': self.tao_2 }) return d def init_population(self, task): population, fitness, d = super().init_population(task) pulse_rates = np.full(self.population_size, self.pulse_rate) d.update({'pulse_rates': pulse_rates}) return population, fitness, d def self_adaptation(self, loudness, pulse_rate): r"""Adaptation step. Args: loudness (float): Current loudness. pulse_rate (float): Current pulse rate. Returns: Tuple[float, float]: 1. New loudness. 2. Nwq pulse rate. """ return self.min_loudness + self.random() * ( self.max_loudness - self.min_loudness) if self.random() < self.tao_1 else loudness, self.min_pulse_rate + self.random() * ( self.max_pulse_rate - self.min_pulse_rate) if self.random() < self.tao_2 else pulse_rate def run_iteration(self, task, population, population_fitness, best_x, best_fitness, **params): r"""Core function of Bat Algorithm. Args: task (Task): Optimization task. population (numpy.ndarray): Current population population_fitness (numpy.ndarray[float]): Current population fitness/function values best_x (numpy.ndarray): Current best individual best_fitness (float): Current best individual function/fitness value params (Dict[str, Any]): Additional algorithm arguments Returns: Tuple[numpy.ndarray, numpy.ndarray[float], Dict[str, Any]]: 1. New population 2. New population fitness/function values 3. Additional arguments: * loudness (numpy.ndarray[float]): Loudness. * pulse_rates (numpy.ndarray[float]): Pulse rate. * velocities (numpy.ndarray[float]): Velocities. """ loudness = params.pop('loudness') pulse_rates = params.pop('pulse_rates') velocities = params.pop('velocities') for i in range(self.population_size): loudness[i], pulse_rates[i] = self.self_adaptation(loudness[i], pulse_rates[i]) frequency = self.min_frequency + (self.max_frequency - self.min_frequency) * self.random() velocities[i] += (population[i] - best_x) * frequency if self.random() > pulse_rates[i]: solution = self.local_search(best=best_x, loudness=loudness[i], task=task, i=i, population=population) else: solution = task.repair(population[i] + velocities[i], rng=self.rng) new_fitness = task.eval(solution) if (new_fitness <= population_fitness[i]) and (self.random() < (self.min_loudness - loudness[i]) / self.starting_loudness): population[i], population_fitness[i] = solution, new_fitness if new_fitness <= best_fitness: best_x, best_fitness = solution.copy(), new_fitness return population, population_fitness, best_x, best_fitness, {'loudness': loudness, 'pulse_rates': pulse_rates, 'velocities': velocities}
37.41519
145
0.619528
import logging import numpy as np from niapy.algorithms.algorithm import Algorithm logging.basicConfig() logger = logging.getLogger('niapy.algorithms.modified') logger.setLevel('INFO') __all__ = ['AdaptiveBatAlgorithm', 'SelfAdaptiveBatAlgorithm'] class AdaptiveBatAlgorithm(Algorithm): Name = ['AdaptiveBatAlgorithm', 'ABA'] @staticmethod def info(): return r"""TODO""" def __init__(self, population_size=100, starting_loudness=0.5, epsilon=0.001, alpha=1.0, pulse_rate=0.5, min_frequency=0.0, max_frequency=2.0, *args, **kwargs): super().__init__(population_size, *args, **kwargs) self.starting_loudness = starting_loudness self.epsilon = epsilon self.alpha = alpha self.pulse_rate = pulse_rate self.min_frequency = min_frequency self.max_frequency = max_frequency def set_parameters(self, population_size=100, starting_loudness=0.5, epsilon=0.001, alpha=1.0, pulse_rate=0.5, min_frequency=0.0, max_frequency=2.0, **kwargs): super().set_parameters(population_size=population_size, **kwargs) self.starting_loudness = starting_loudness self.epsilon = epsilon self.alpha = alpha self.pulse_rate = pulse_rate self.min_frequency = min_frequency self.max_frequency = max_frequency def get_parameters(self): d = super().get_parameters() d.update({ 'starting_loudness': self.starting_loudness, 'epsilon': self.epsilon, 'alpha': self.alpha, 'pulse_rate': self.pulse_rate, 'min_frequency': self.min_frequency, 'max_frequency': self.max_frequency }) return d def init_population(self, task): population, fitness, d = super().init_population(task) loudness = np.full(self.population_size, self.starting_loudness) velocities = np.zeros((self.population_size, task.dimension)) d.update({'loudness': loudness, 'velocities': velocities}) return population, fitness, d def local_search(self, best, loudness, task, **kwargs): return task.repair(best + self.epsilon * loudness * self.normal(0, 1, task.dimension), rng=self.rng) def update_loudness(self, loudness): new_loudness = loudness * self.alpha return new_loudness if new_loudness > 1e-13 else self.starting_loudness def run_iteration(self, task, population, population_fitness, best_x, best_fitness, **params): loudness = params.pop('loudness') velocities = params.pop('velocities') for i in range(self.population_size): frequency = self.min_frequency + (self.max_frequency - self.min_frequency) * self.random() velocities[i] += (population[i] - best_x) * frequency if self.random() > self.pulse_rate: solution = self.local_search(best=best_x, loudness=loudness[i], task=task, i=i, Sol=population) else: solution = task.repair(population[i] + velocities[i], rng=self.rng) new_fitness = task.eval(solution) if (new_fitness <= population_fitness[i]) and (self.random() < loudness[i]): population[i], population_fitness[i] = solution, new_fitness if new_fitness <= best_fitness: best_x, best_fitness, loudness[i] = solution.copy(), new_fitness, self.update_loudness(loudness[i]) return population, population_fitness, best_x, best_fitness, {'loudness': loudness, 'velocities': velocities} class SelfAdaptiveBatAlgorithm(AdaptiveBatAlgorithm): Name = ['SelfAdaptiveBatAlgorithm', 'SABA'] @staticmethod def info(): return r"""Fister Jr., Iztok and Fister, Dusan and Yang, Xin-She. "A Hybrid Bat Algorithm". Elektrotehniški vestnik, 2013. 1-7.""" def __init__(self, min_loudness=0.9, max_loudness=1.0, min_pulse_rate=0.001, max_pulse_rate=0.1, tao_1=0.1, tao_2=0.1, *args, **kwargs): super().__init__(*args, **kwargs) self.min_loudness = min_loudness self.max_loudness = max_loudness self.min_pulse_rate = min_pulse_rate self.max_pulse_rate = max_pulse_rate self.tao_1 = tao_1 self.tao_2 = tao_2 def set_parameters(self, min_loudness=0.9, max_loudness=1.0, min_pulse_rate=0.001, max_pulse_rate=0.1, tao_1=0.1, tao_2=0.1, **kwargs): super().set_parameters(**kwargs) self.min_loudness = min_loudness self.max_loudness = max_loudness self.min_pulse_rate = min_pulse_rate self.max_pulse_rate = max_pulse_rate self.tao_1 = tao_1 self.tao_2 = tao_2 def get_parameters(self): d = AdaptiveBatAlgorithm.get_parameters(self) d.update({ 'min_loudness': self.min_loudness, 'max_loudness': self.max_loudness, 'min_pulse_rate': self.min_pulse_rate, 'max_pulse_rate': self.max_pulse_rate, 'tao_1': self.tao_1, 'tao_2': self.tao_2 }) return d def init_population(self, task): population, fitness, d = super().init_population(task) pulse_rates = np.full(self.population_size, self.pulse_rate) d.update({'pulse_rates': pulse_rates}) return population, fitness, d def self_adaptation(self, loudness, pulse_rate): return self.min_loudness + self.random() * ( self.max_loudness - self.min_loudness) if self.random() < self.tao_1 else loudness, self.min_pulse_rate + self.random() * ( self.max_pulse_rate - self.min_pulse_rate) if self.random() < self.tao_2 else pulse_rate def run_iteration(self, task, population, population_fitness, best_x, best_fitness, **params): loudness = params.pop('loudness') pulse_rates = params.pop('pulse_rates') velocities = params.pop('velocities') for i in range(self.population_size): loudness[i], pulse_rates[i] = self.self_adaptation(loudness[i], pulse_rates[i]) frequency = self.min_frequency + (self.max_frequency - self.min_frequency) * self.random() velocities[i] += (population[i] - best_x) * frequency if self.random() > pulse_rates[i]: solution = self.local_search(best=best_x, loudness=loudness[i], task=task, i=i, population=population) else: solution = task.repair(population[i] + velocities[i], rng=self.rng) new_fitness = task.eval(solution) if (new_fitness <= population_fitness[i]) and (self.random() < (self.min_loudness - loudness[i]) / self.starting_loudness): population[i], population_fitness[i] = solution, new_fitness if new_fitness <= best_fitness: best_x, best_fitness = solution.copy(), new_fitness return population, population_fitness, best_x, best_fitness, {'loudness': loudness, 'pulse_rates': pulse_rates, 'velocities': velocities}
true
true
f735e42af71bfc4069df8d626b6ce697fcedc245
1,726
py
Python
ml-project/extract_face_yusril.py
YusrilHasanuddin/bangkit-capstone-CAP0166
51742f7af47fa285154793a6ea74de1d78d945b3
[ "MIT" ]
2
2021-07-20T17:31:29.000Z
2021-12-27T06:42:42.000Z
ml-project/extract_face_yusril.py
YusrilHasanuddin/bangkit-capstone-CAP0166
51742f7af47fa285154793a6ea74de1d78d945b3
[ "MIT" ]
26
2021-05-02T14:05:27.000Z
2021-06-06T14:22:35.000Z
ml-project/extract_face_yusril.py
YusrilHasanuddin/bangkit-capstone-CAP0166
51742f7af47fa285154793a6ea74de1d78d945b3
[ "MIT" ]
3
2021-05-23T06:13:14.000Z
2021-06-09T11:04:29.000Z
import sys import os import traceback from PIL import Image from facenet_pytorch import MTCNN import matplotlib.image as mpimg import numpy as np def detect_faces(image_path): mtcnn = MTCNN(margin=20, keep_all=True, post_process=False, device='cuda:0') image = image_path image = mpimg.imread(image) image = Image.fromarray(image) faces = mtcnn(image) count = 0 for face in faces: face = face.permute(1, 2, 0).int().numpy() # cv2.imwrite(os.path.join( # path_folder, "face" + str(count) + ".jpg"),face) face = Image.fromarray((face).astype(np.uint8)) face.save(os.path.join(path_folder, "face" + str(count) + ".jpg")) count = count + 1 if __name__ == "__main__": fcount = 0 while os.path.exists("ExtractedFaceFolder" + str(fcount)) == True: fcount = fcount + 1 if os.path.exists("ExtractedFaceFolder" + str(fcount)) == False: break else: continue os.mkdir("ExtractedFaceFolder" + str(fcount)) path_folder = "ExtractedFaceFolder" + str(fcount) if len(sys.argv) < 2: print("Usage: python detect_extract_save.py 'image path'") sys.exit() if os.path.isdir(sys.argv[1]): for image in os.listdir(sys.argv[1]): try: print("Processing.....",os.path.abspath( os.path.join(sys.argv[1],image))) detect_faces(os.path.abspath( os.path.join(sys.argv[1],image)),False) except Exception: print("Could not process ",os.path.abspath( os.path.join(sys.argv[1],image))) else: detect_faces(sys.argv[1])
31.962963
74
0.584009
import sys import os import traceback from PIL import Image from facenet_pytorch import MTCNN import matplotlib.image as mpimg import numpy as np def detect_faces(image_path): mtcnn = MTCNN(margin=20, keep_all=True, post_process=False, device='cuda:0') image = image_path image = mpimg.imread(image) image = Image.fromarray(image) faces = mtcnn(image) count = 0 for face in faces: face = face.permute(1, 2, 0).int().numpy() face = Image.fromarray((face).astype(np.uint8)) face.save(os.path.join(path_folder, "face" + str(count) + ".jpg")) count = count + 1 if __name__ == "__main__": fcount = 0 while os.path.exists("ExtractedFaceFolder" + str(fcount)) == True: fcount = fcount + 1 if os.path.exists("ExtractedFaceFolder" + str(fcount)) == False: break else: continue os.mkdir("ExtractedFaceFolder" + str(fcount)) path_folder = "ExtractedFaceFolder" + str(fcount) if len(sys.argv) < 2: print("Usage: python detect_extract_save.py 'image path'") sys.exit() if os.path.isdir(sys.argv[1]): for image in os.listdir(sys.argv[1]): try: print("Processing.....",os.path.abspath( os.path.join(sys.argv[1],image))) detect_faces(os.path.abspath( os.path.join(sys.argv[1],image)),False) except Exception: print("Could not process ",os.path.abspath( os.path.join(sys.argv[1],image))) else: detect_faces(sys.argv[1])
true
true
f735e441dcf5ae886a87accea2eb267ceb2901ee
358
py
Python
nms_stack/nms_cli/nms_stack/roles/ansible-role-glusterfs/molecule/default/tests/test_default.py
kkkkv/tgnms
a3b8fd8a69b647a614f9856933f05e50a4affadf
[ "MIT" ]
12
2021-04-06T06:27:18.000Z
2022-03-18T10:52:29.000Z
nms_stack/nms_cli/nms_stack/roles/ansible-role-glusterfs/molecule/default/tests/test_default.py
kkkkv/tgnms
a3b8fd8a69b647a614f9856933f05e50a4affadf
[ "MIT" ]
6
2022-01-04T13:32:16.000Z
2022-03-28T21:13:59.000Z
nms_stack/nms_cli/nms_stack/roles/ansible-role-glusterfs/molecule/default/tests/test_default.py
kkkkv/tgnms
a3b8fd8a69b647a614f9856933f05e50a4affadf
[ "MIT" ]
7
2021-09-27T13:14:42.000Z
2022-03-28T16:24:15.000Z
# Copyright (c) 2014-present, Facebook, Inc. import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_hosts_file(host): f = host.file('/etc/hosts') assert f.exists assert f.user == 'root' assert f.group == 'root'
22.375
63
0.717877
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_hosts_file(host): f = host.file('/etc/hosts') assert f.exists assert f.user == 'root' assert f.group == 'root'
true
true
f735e520bdc3adc6f904a5797629bf0a08ce182c
1,653
py
Python
homeassistant/components/asuswrt/__init__.py
MrDelik/core
93a66cc357b226389967668441000498a10453bb
[ "Apache-2.0" ]
3
2020-11-27T06:26:27.000Z
2020-12-09T14:55:16.000Z
homeassistant/components/asuswrt/__init__.py
MrDelik/core
93a66cc357b226389967668441000498a10453bb
[ "Apache-2.0" ]
25
2021-11-24T06:24:10.000Z
2022-03-31T06:23:06.000Z
homeassistant/components/asuswrt/__init__.py
MrDelik/core
93a66cc357b226389967668441000498a10453bb
[ "Apache-2.0" ]
3
2022-01-02T18:49:54.000Z
2022-01-25T02:03:54.000Z
"""Support for ASUSWRT devices.""" from homeassistant.config_entries import ConfigEntry from homeassistant.const import EVENT_HOMEASSISTANT_STOP, Platform from homeassistant.core import HomeAssistant from .const import DATA_ASUSWRT, DOMAIN from .router import AsusWrtRouter PLATFORMS = [Platform.DEVICE_TRACKER, Platform.SENSOR] async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up AsusWrt platform.""" router = AsusWrtRouter(hass, entry) await router.setup() router.async_on_close(entry.add_update_listener(update_listener)) async def async_close_connection(event): """Close AsusWrt connection on HA Stop.""" await router.close() entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_close_connection) ) hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {DATA_ASUSWRT: router} hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): router = hass.data[DOMAIN][entry.entry_id][DATA_ASUSWRT] await router.close() hass.data[DOMAIN].pop(entry.entry_id) return unload_ok async def update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Update when config_entry options update.""" router = hass.data[DOMAIN][entry.entry_id][DATA_ASUSWRT] if router.update_options(entry.options): await hass.config_entries.async_reload(entry.entry_id)
31.788462
87
0.745312
from homeassistant.config_entries import ConfigEntry from homeassistant.const import EVENT_HOMEASSISTANT_STOP, Platform from homeassistant.core import HomeAssistant from .const import DATA_ASUSWRT, DOMAIN from .router import AsusWrtRouter PLATFORMS = [Platform.DEVICE_TRACKER, Platform.SENSOR] async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: router = AsusWrtRouter(hass, entry) await router.setup() router.async_on_close(entry.add_update_listener(update_listener)) async def async_close_connection(event): await router.close() entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_close_connection) ) hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {DATA_ASUSWRT: router} hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): router = hass.data[DOMAIN][entry.entry_id][DATA_ASUSWRT] await router.close() hass.data[DOMAIN].pop(entry.entry_id) return unload_ok async def update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: router = hass.data[DOMAIN][entry.entry_id][DATA_ASUSWRT] if router.update_options(entry.options): await hass.config_entries.async_reload(entry.entry_id)
true
true
f735e533e4d7419d51f09dc7c83e8618f578b234
6,225
py
Python
isimip_publisher/tests/test_commands.py
ISI-MIP/isimip-publisher
d54f7325931df91c98e40c924eac085351fc5813
[ "MIT" ]
null
null
null
isimip_publisher/tests/test_commands.py
ISI-MIP/isimip-publisher
d54f7325931df91c98e40c924eac085351fc5813
[ "MIT" ]
44
2019-12-04T10:47:13.000Z
2021-03-29T16:43:06.000Z
isimip_publisher/tests/test_commands.py
ISI-MIP/isimip-publisher
d54f7325931df91c98e40c924eac085351fc5813
[ "MIT" ]
1
2019-12-04T09:09:26.000Z
2019-12-04T09:09:26.000Z
import os import shutil from pathlib import Path import pytest from dotenv import load_dotenv from isimip_publisher.utils.database import (Dataset, Resource, init_database_session) @pytest.fixture(scope='session') def setup(): load_dotenv(Path().cwd() / '.env') base_dir = Path(__file__).parent.parent.parent test_dir = base_dir / 'testing' shutil.rmtree(test_dir / 'work', ignore_errors=True) shutil.rmtree(test_dir / 'public', ignore_errors=True) shutil.rmtree(test_dir / 'archive', ignore_errors=True) session = init_database_session(os.getenv('DATABASE')) for resource in session.query(Resource): session.delete(resource) session.commit() for dataset in session.query(Dataset): for file in dataset.files: session.delete(file) session.delete(dataset) session.commit() def test_empty(setup, script_runner): response = script_runner.run('isimip-publisher') assert not response.stderr assert response.returncode == 0 def test_help(setup, script_runner): response = script_runner.run('isimip-publisher', '--help') assert response.success, response.stderr assert response.stdout assert not response.stderr def test_list_remote(setup, script_runner): response = script_runner.run('isimip-publisher', 'list_remote', 'round/product/sector') assert response.success, response.stderr assert response.stdout assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_match_remote(setup, script_runner): response = script_runner.run('isimip-publisher', 'match_remote', 'round/product/sector') assert response.success, response.stderr assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_fetch_files(setup, script_runner): response = script_runner.run('isimip-publisher', 'fetch_files', 'round/product/sector') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('fetch_files') def test_list_local(setup, script_runner): response = script_runner.run('isimip-publisher', 'list_local', 'round/product/sector') assert response.success, response.stderr assert response.stdout assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_match_local(setup, script_runner): response = script_runner.run('isimip-publisher', 'match_local', 'round/product/sector') assert response.success, response.stderr assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_write_jsons(setup, script_runner): response = script_runner.run('isimip-publisher', 'write_jsons', 'round/product/sector') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('write_jsons') def test_insert_datasets(setup, script_runner): response = script_runner.run('isimip-publisher', 'insert_datasets', 'round/product/sector') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('insert_datasets') def test_publish_datasets(setup, script_runner): response = script_runner.run('isimip-publisher', 'publish_datasets', 'round/product/sector') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('publish_datasets') def test_list_public(setup, script_runner): response = script_runner.run('isimip-publisher', 'list_public', 'round/product/sector') assert response.success, response.stderr assert response.stdout assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_match_public(setup, script_runner): response = script_runner.run('isimip-publisher', 'match_public', 'round/product/sector') assert response.success, response.stderr assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_link_files(setup, script_runner): response = script_runner.run('isimip-publisher', 'link_files', 'round/product/sector/model', 'round/product/sector2/model') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('link_files') def test_link_datasets(setup, script_runner): response = script_runner.run('isimip-publisher', 'link_datasets', 'round/product/sector/model', 'round/product/sector2/model') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('link_datasets') def test_insert_doi(setup, script_runner): response = script_runner.run('isimip-publisher', 'insert_doi', 'testing/resources/test.json') assert response.success, response.stderr assert not response.stdout assert not response.stderr def test_update_doi(setup, script_runner): response = script_runner.run('isimip-publisher', 'update_doi', 'testing/resources/test1.json') assert response.success, response.stderr assert not response.stdout assert not response.stderr def test_update_index(setup, script_runner): response = script_runner.run('isimip-publisher', 'update_index', 'round/product/sector/model') assert response.success, response.stderr assert not response.stdout assert not response.stderr def test_check(setup, script_runner): response = script_runner.run('isimip-publisher', 'check', 'round/product/sector/model') assert response.success, response.stderr assert not response.stdout assert not response.stderr def test_archive_datasets(setup, script_runner): response = script_runner.run('isimip-publisher', 'archive_datasets', 'round/product/sector/model2') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('archive_datasets') def test_clean(setup, script_runner): response = script_runner.run('isimip-publisher', 'clean', 'round/product/sector/model') assert response.success, response.stderr assert not response.stdout assert not response.stderr
35.571429
130
0.744418
import os import shutil from pathlib import Path import pytest from dotenv import load_dotenv from isimip_publisher.utils.database import (Dataset, Resource, init_database_session) @pytest.fixture(scope='session') def setup(): load_dotenv(Path().cwd() / '.env') base_dir = Path(__file__).parent.parent.parent test_dir = base_dir / 'testing' shutil.rmtree(test_dir / 'work', ignore_errors=True) shutil.rmtree(test_dir / 'public', ignore_errors=True) shutil.rmtree(test_dir / 'archive', ignore_errors=True) session = init_database_session(os.getenv('DATABASE')) for resource in session.query(Resource): session.delete(resource) session.commit() for dataset in session.query(Dataset): for file in dataset.files: session.delete(file) session.delete(dataset) session.commit() def test_empty(setup, script_runner): response = script_runner.run('isimip-publisher') assert not response.stderr assert response.returncode == 0 def test_help(setup, script_runner): response = script_runner.run('isimip-publisher', '--help') assert response.success, response.stderr assert response.stdout assert not response.stderr def test_list_remote(setup, script_runner): response = script_runner.run('isimip-publisher', 'list_remote', 'round/product/sector') assert response.success, response.stderr assert response.stdout assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_match_remote(setup, script_runner): response = script_runner.run('isimip-publisher', 'match_remote', 'round/product/sector') assert response.success, response.stderr assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_fetch_files(setup, script_runner): response = script_runner.run('isimip-publisher', 'fetch_files', 'round/product/sector') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('fetch_files') def test_list_local(setup, script_runner): response = script_runner.run('isimip-publisher', 'list_local', 'round/product/sector') assert response.success, response.stderr assert response.stdout assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_match_local(setup, script_runner): response = script_runner.run('isimip-publisher', 'match_local', 'round/product/sector') assert response.success, response.stderr assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_write_jsons(setup, script_runner): response = script_runner.run('isimip-publisher', 'write_jsons', 'round/product/sector') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('write_jsons') def test_insert_datasets(setup, script_runner): response = script_runner.run('isimip-publisher', 'insert_datasets', 'round/product/sector') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('insert_datasets') def test_publish_datasets(setup, script_runner): response = script_runner.run('isimip-publisher', 'publish_datasets', 'round/product/sector') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('publish_datasets') def test_list_public(setup, script_runner): response = script_runner.run('isimip-publisher', 'list_public', 'round/product/sector') assert response.success, response.stderr assert response.stdout assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_match_public(setup, script_runner): response = script_runner.run('isimip-publisher', 'match_public', 'round/product/sector') assert response.success, response.stderr assert not response.stderr assert len(response.stdout.splitlines()) == 12 def test_link_files(setup, script_runner): response = script_runner.run('isimip-publisher', 'link_files', 'round/product/sector/model', 'round/product/sector2/model') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('link_files') def test_link_datasets(setup, script_runner): response = script_runner.run('isimip-publisher', 'link_datasets', 'round/product/sector/model', 'round/product/sector2/model') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('link_datasets') def test_insert_doi(setup, script_runner): response = script_runner.run('isimip-publisher', 'insert_doi', 'testing/resources/test.json') assert response.success, response.stderr assert not response.stdout assert not response.stderr def test_update_doi(setup, script_runner): response = script_runner.run('isimip-publisher', 'update_doi', 'testing/resources/test1.json') assert response.success, response.stderr assert not response.stdout assert not response.stderr def test_update_index(setup, script_runner): response = script_runner.run('isimip-publisher', 'update_index', 'round/product/sector/model') assert response.success, response.stderr assert not response.stdout assert not response.stderr def test_check(setup, script_runner): response = script_runner.run('isimip-publisher', 'check', 'round/product/sector/model') assert response.success, response.stderr assert not response.stdout assert not response.stderr def test_archive_datasets(setup, script_runner): response = script_runner.run('isimip-publisher', 'archive_datasets', 'round/product/sector/model2') assert response.success, response.stderr assert not response.stdout assert response.stderr.strip().startswith('archive_datasets') def test_clean(setup, script_runner): response = script_runner.run('isimip-publisher', 'clean', 'round/product/sector/model') assert response.success, response.stderr assert not response.stdout assert not response.stderr
true
true
f735e5b4e2f72c64bab1404d35d76c84bea5704e
1,404
py
Python
pyweb/cli.py
gera2ld/pyhttpd
c7bbfd8ba22f09da1200a4d570ce128d83e5f82c
[ "MIT" ]
2
2015-08-25T10:30:25.000Z
2017-05-01T10:12:59.000Z
pyweb/cli.py
gera2ld/pyweb
c7bbfd8ba22f09da1200a4d570ce128d83e5f82c
[ "MIT" ]
null
null
null
pyweb/cli.py
gera2ld/pyweb
c7bbfd8ba22f09da1200a4d570ce128d83e5f82c
[ "MIT" ]
1
2015-05-07T01:41:00.000Z
2015-05-07T01:41:00.000Z
# -*- coding: utf-8 -*- """Console script for pyweb.""" import os import sys import platform import click from . import __version__ from .server import HTTPDaemon from .utils import logger @click.command() @click.option('-b', '--bind', default=':4000', help='the address to bind, default as `:4000`') @click.option('-r', '--root', default='.', help='the root directory of documents') def main(bind, root): """Start a web server with pyweb.""" logger.info( 'HTTP Server v%s/%s %s - by Gerald', __version__, platform.python_implementation(), platform.python_version()) server = HTTPDaemon({ 'bind': bind, 'match': None, 'handler': [ 'proxy', { 'handler': 'fcgi', 'options': { 'fcgi_ext': '.php', 'fcgi_target': ['127.0.0.1:9000'], 'index': [ 'index.php', ], }, }, 'file', 'dir', ], 'gzip': [ 'text/html', 'text/css', 'application/javascript', ], 'options': { 'root': root, 'index': [ 'index.html', ], }, }) server.serve() return 0 if __name__ == "__main__": sys.exit(main()) # pragma: no cover
25.527273
94
0.458689
import os import sys import platform import click from . import __version__ from .server import HTTPDaemon from .utils import logger @click.command() @click.option('-b', '--bind', default=':4000', help='the address to bind, default as `:4000`') @click.option('-r', '--root', default='.', help='the root directory of documents') def main(bind, root): logger.info( 'HTTP Server v%s/%s %s - by Gerald', __version__, platform.python_implementation(), platform.python_version()) server = HTTPDaemon({ 'bind': bind, 'match': None, 'handler': [ 'proxy', { 'handler': 'fcgi', 'options': { 'fcgi_ext': '.php', 'fcgi_target': ['127.0.0.1:9000'], 'index': [ 'index.php', ], }, }, 'file', 'dir', ], 'gzip': [ 'text/html', 'text/css', 'application/javascript', ], 'options': { 'root': root, 'index': [ 'index.html', ], }, }) server.serve() return 0 if __name__ == "__main__": sys.exit(main())
true
true
f735e5ce1ca1a10327b8aa4b68252afb05835453
34,509
py
Python
pelicun/model.py
13273781142/pelicun1
1177f069a083a25eb53ae7a9ddfa6c814660a423
[ "BSD-3-Clause" ]
20
2019-03-01T21:51:15.000Z
2022-02-25T11:51:13.000Z
pelicun/model.py
13273781142/pelicun1
1177f069a083a25eb53ae7a9ddfa6c814660a423
[ "BSD-3-Clause" ]
7
2018-12-04T18:55:39.000Z
2021-09-26T00:20:34.000Z
pelicun/model.py
13273781142/pelicun1
1177f069a083a25eb53ae7a9ddfa6c814660a423
[ "BSD-3-Clause" ]
14
2018-10-26T21:48:44.000Z
2022-02-28T01:53:40.000Z
# -*- coding: utf-8 -*- # # Copyright (c) 2018 Leland Stanford Junior University # Copyright (c) 2018 The Regents of the University of California # # This file is part of pelicun. # # 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. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # 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. # # You should have received a copy of the BSD 3-Clause License along with # pelicun. If not, see <http://www.opensource.org/licenses/>. # # Contributors: # Adam Zsarnóczay """ This module has classes and methods that define and access the model used for loss assessment. .. rubric:: Contents .. autosummary:: prep_constant_median_DV prep_bounded_linear_median_DV prep_bounded_multilinear_median_DV FragilityFunction ConsequenceFunction DamageState DamageStateGroup PerformanceGroup FragilityGroup """ from .base import * class FragilityFunction(object): """ Describes the relationship between asset response and damage. Asset response is characterized by a Demand value that represents an engineering demand parameter (EDP). Only a scalar EDP is supported currently. The damage is characterized by a set of DamageStateGroup (DSG) objects. For each DSG, the corresponding EDP limit (i.e. the EDP at which the asset is assumed to experience damage described by the DSG) is considered uncertain; hence, it is described by a random variable. The random variables that describe EDP limits for the set of DSGs are not necessarily independent. We assume that the EDP limit will be approximated by a probability distribution for each DSG and these variables together form a multivariate distribution. Following common practice, the correlation between variables is assumed perfect by default, but the framework allows the users to explore other, more realistic options. Parameters ---------- EDP_limit: list of RandomVariable A list of correlated random variables where each variable corresponds to an EDP limit that triggers a damage state. The number of list elements shall be equal to the number of DSGs handled by the Fragility Function (FF) and they shall be in ascending order of damage severity. """ def __init__(self, EDP_limit): self._EDP_limit = EDP_limit self._EDP_tags = [EDP_lim_i.name for EDP_lim_i in EDP_limit] def P_exc(self, EDP, DSG_ID): """ Return the probability of damage state exceedance. Calculate the probability of exceeding the damage corresponding to the DSG identified by the DSG_ID conditioned on a particular EDP value. Parameters ---------- EDP: float scalar or ndarray Single EDP or numpy array of EDP values. DSG_ID: int Identifies the conditioning DSG. The DSG numbering is 1-based, because zero typically corresponds to the undamaged state. Returns ------- P_exc: float scalar or ndarray DSG exceedance probability at the given EDP point(s). """ EDP = np.asarray(EDP, dtype=np.float64) nvals = EDP.size # The exceedance probability corresponding to no damage is 1. # Although this is trivial, returning 1 for DSG_ID=0 makes using P_exc # more convenient. if DSG_ID == 0: P_exc = np.ones(EDP.size) else: # prepare the limits for the density calculation ndims = len(self._EDP_limit) limit_list = np.full((ndims, nvals), -np.inf, dtype=np.float64) limit_list[DSG_ID - 1:] = EDP limit_list[:DSG_ID - 1] = None P_exc = 1.0 - self._EDP_limit[0].RV_set.orthotope_density( lower=limit_list, var_subset = self._EDP_tags) # if EDP was a scalar, make sure that the result is also a scalar if EDP.size == 1: return P_exc[0] else: return P_exc def DSG_given_EDP(self, EDP, force_resampling=False): """ Given an EDP, get a damage level based on the fragility function. The damage is evaluated by sampling the joint distribution of fragilities corresponding to all possible damage levels and checking which damage level the given EDP falls into. This approach allows for efficient damage state evaluation for a large number of EDP realizations. Parameters ---------- EDP: float scalar or ndarray or Series Single EDP, or numpy array or pandas Series of EDP values. force_resampling: bool, optional, default: False If True, the probability distribution is resampled before evaluating the damage for each EDP. This is not recommended if the fragility functions are correlated with other sources of uncertainty because those variables will also be resampled in this case. If False, which is the default approach, we assume that the random variable has already been sampled and the number of samples greater or equal to the number of EDP values. Returns ------- DSG_ID: Series Identifies the damage that corresponds to the given EDP. A DSG_ID of 0 means no damage. """ # get the number of samples needed nsamples = EDP.size # if there are no samples or resampling is forced, then sample the # distribution first # TODO: force_resampling is probably not needed # if force_resampling or (self._EDP_limit.samples is None): # self._EDP_limit.sample_distribution(sample_size=nsamples) # # # if the number of samples is not sufficiently large, raise an error # if self._EDP_limit.samples.shape[0] < nsamples: # raise ValueError( # 'Damage evaluation requires at least as many samples of the ' # 'joint distribution defined by the fragility functions as ' # 'many EDP values are provided to the DSG_given_EDP function. ' # 'You might want to consider setting force_resampling to True ' # 'or sampling the distribution before calling the DSG_given_EDP ' # 'function.') #samples = pd.DataFrame(self._EDP_limit.samples) samples = pd.DataFrame(dict([(lim_i.name, lim_i.samples) for lim_i in self._EDP_limit])) if type(EDP) not in [pd.Series, pd.DataFrame]: EDP = pd.Series(EDP, name='EDP') #nstates = samples.columns.values.size nstates = samples.shape[1] samples = samples.loc[EDP.index,:] # sort columns sample_cols = samples.columns samples = samples[sample_cols[np.argsort(sample_cols)]] # check for EDP exceedance EXC = samples.sub(EDP, axis=0) < 0. DSG_ID = pd.Series(np.zeros(len(samples.index)), name='DSG_ID', index=samples.index, dtype=np.int) for s in range(nstates): DSG_ID[EXC.iloc[:,s]] = s + 1 return DSG_ID def prep_constant_median_DV(median): """ Returns a constant median Decision Variable (DV) function. Parameters ---------- median: float The median DV for a consequence function with fixed median. Returns ------- f: callable A function that returns the constant median DV for all component quantities. """ def f(quantity): return median return f def prep_bounded_linear_median_DV(median_max, median_min, quantity_lower, quantity_upper): """ Returns a bounded linear median Decision Variable (DV) function. The median DV equals the min and max values when the quantity is outside of the prescribed quantity bounds. When the quantity is within the bounds, the returned median is calculated by a linear function with a negative slope between max and min values. Parameters ---------- median_max: float, optional median_min: float, optional Minimum and maximum limits that define the bounded_linear median DV function. quantity_lower: float, optional quantity_upper: float, optional Lower and upper bounds of component quantity that define the bounded_linear median DV function. Returns ------- f: callable A function that returns the median DV given the quantity of damaged components. """ def f(quantity): if quantity is None: raise ValueError( 'A bounded linear median Decision Variable function called ' 'without specifying the quantity of damaged components') q_array = np.asarray(quantity, dtype=np.float64) # calculate the median consequence given the quantity of damaged # components output = np.interp(q_array, [quantity_lower, quantity_upper], [median_max, median_min]) return output return f def prep_bounded_multilinear_median_DV(medians, quantities): """ Returns a bounded multilinear median Decision Variable (DV) function. The median DV equals the min and max values when the quantity is outside of the prescribed quantity bounds. When the quantity is within the bounds, the returned median is calculated by linear interpolation. Parameters ---------- medians: ndarray Series of values that define the y coordinates of the multilinear DV function. quantities: ndarray Series of values that define the component quantities corresponding to the series of medians and serving as the x coordinates of the multilinear DV function. Returns ------- f: callable A function that returns the median DV given the quantity of damaged components. """ def f(quantity): if quantity is None: raise ValueError( 'A bounded linear median Decision Variable function called ' 'without specifying the quantity of damaged components') q_array = np.asarray(quantity, dtype=np.float64) # calculate the median consequence given the quantity of damaged # components output = np.interp(q_array, quantities, medians) return output return f class ConsequenceFunction(object): """ Describes the relationship between damage and a decision variable. Indicates the distribution of a quantified Decision Variable (DV) conditioned on a component, an element, or the system reaching a given damage state (DS). DV can be reconstruction cost, repair time, casualties, injuries, etc. Its distribution might depend on the quantity of damaged components. Parameters ---------- DV_median: callable Describes the median DV as an f(quantity) function of the total quantity of damaged components. Use the prep_constant_median_DV, and prep_bounded_linear_median_DV helper functions to conveniently prescribe the typical FEMA P-58 functions. DV_distribution: RandomVariable A random variable that characterizes the uncertainty in the DV. The distribution shall be normalized by the median DV (i.e. the RV is expected to have a unit median). Truncation can be used to prescribe lower and upper limits for the DV, such as the (0,1) domain needed for red tag evaluation. """ def __init__(self, DV_median, DV_distribution): self._DV_median = DV_median self._DV_distribution = DV_distribution def median(self, quantity=None): """ Return the value of the median DV. The median DV corresponds to the component damage state (DS). If the damage consequence depends on the quantity of damaged components, the total quantity of damaged components shall be specified through the quantity parameter. Parameters ---------- quantity: float scalar or ndarray, optional Total quantity of damaged components that determines the magnitude of median DV. Not needed for consequence functions with a fixed median DV. Returns ------- median: float scalar or ndarray A single scalar for fixed median; a scalar or an array depending on the shape of the quantity parameter for bounded_linear median. """ return self._DV_median(quantity) def sample_unit_DV(self, quantity=None, sample_size=1, force_resampling=False): """ Sample the decision variable quantity per component unit. The Unit Decision Variable (UDV) corresponds to the component Damage State (DS). It shall be multiplied by the quantity of damaged components to get the total DV that corresponds to the quantity of the damaged components in the asset. If the DV depends on the total quantity of damaged components, that value shall be specified through the quantity parameter. Parameters ---------- quantity: float scalar, ndarray or Series, optional, default: None Total quantity of damaged components that determines the magnitude of median DV. Not needed for consequence functions with a fixed median DV. sample_size: int, optional, default: 1 Number of samples drawn from the DV distribution. The default value yields one sample. If quantity is an array with more than one element, the sample_size parameter is ignored. force_resampling: bool, optional, default: False If True, the DV distribution (and the corresponding RV if there are correlations) is resampled even if there are samples already available. This is not recommended if the DV distribution is correlated with other sources of uncertainty because those variables will also be resampled in this case. If False, which is the default approach, we assume that the random variable has already been sampled and the number of samples is greater or equal to the number of samples requested. Returns ------- unit_DV: float scalar or ndarray Unit DV samples. """ # get the median DV conditioned on the provided quantities median = self.median(quantity=np.asarray(quantity)) # if the distribution is None, then there is no uncertainty in the DV # and the median values are the samples if self._DV_distribution is None: return median else: # if there are more than one quantities defined, infer the number of # samples from the number of quantities if quantity is not None: if type(quantity) not in [pd.Series, pd.DataFrame]: quantity = pd.Series(quantity, name='QNT') if quantity.size > 1: sample_size = quantity.size elif sample_size > 1: quantity = pd.Series(np.ones(sample_size) * quantity.values, name='QNT') # if there are no samples or resampling is forced, then sample the # distribution first # TODO: force_resampling is probably not needed # if (force_resampling or # (self._DV_distribution.samples is None)): # self._DV_distribution.sample_distribution(sample_size=sample_size) # # if the number of samples is not sufficiently large, raise an error # if self._DV_distribution.samples.shape[0] < sample_size: # raise ValueError( # 'Consequence evaluation requires at least as many samples of ' # 'the Decision Variable distribution as many samples are ' # 'requested or as many quantity values are provided to the ' # 'sample_unit_DV function. You might want to consider setting ' # 'force_resampling to True or sampling the distribution before ' # 'calling the sample_unit_DV function.') # get the samples if quantity is not None: samples = pd.Series(self._DV_distribution.samples).loc[quantity.index] else: samples = pd.Series(self._DV_distribution.samples).iloc[:sample_size] samples = samples * median return samples class DamageState(object): """ Characterizes one type of damage that corresponds to a particular DSG. The occurrence of damage is evaluated at the DSG. The DS describes one of the possibly several types of damages that belong to the same DSG and the consequences of such damage. Parameters ---------- ID:int weight: float, optional, default: 1.0 Describes the probability of DS occurrence, conditioned on the damage being in the DSG linked to this DS. This information is only used for DSGs with multiple DS corresponding to them. The weights of the set of DS shall sum up to 1.0 if they are mutually exclusive. When the set of DS occur simultaneously, the sum of weights typically exceeds 1.0. description: str, optional Provides a short description of the damage state. affected_area: float, optional, default: 0. Defines the area over which life safety hazards from this DS exist. repair_cost_CF: ConsequenceFunction, optional A consequence function that describes the cost necessary to restore the component to its pre-disaster condition. reconstruction_time_CF: ConsequenceFunction, optional A consequence function that describes the time, necessary to repair the damaged component to its pre-disaster condition. injuries_CF_set: ConsequenceFunction array, optional A set of consequence functions; each describes the number of people expected to experience injury of a particular severity when the component is in this DS. Any number of injury-levels can be considered. red_tag_CF: ConsequenceFunction, optional A consequence function that describes the proportion of components (within a Performance Group) that needs to be damaged to trigger an unsafe placard (i.e. red tag) for the building during post-disaster inspection. """ def __init__(self, ID, weight=1.0, description='', repair_cost_CF=None, reconstruction_time_CF=None, injuries_CF_set=None, affected_area=0., red_tag_CF=None): self._ID = int(ID) self._weight = float(weight) self._description = description self._repair_cost_CF = repair_cost_CF self._reconstruction_time_CF = reconstruction_time_CF self._injuries_CF_set = injuries_CF_set self._affected_area = affected_area self._red_tag_CF = red_tag_CF @property def description(self): """ Return the damage description. """ return self._description @property def weight(self): """ Return the weight of DS among the set of damage states in the DSG. """ return self._weight def unit_repair_cost(self, quantity=None, sample_size=1, **kwargs): """ Sample the repair cost distribution and return the unit repair costs. The unit repair costs shall be multiplied by the quantity of damaged components to get the total repair costs for the components in this DS. Parameters ---------- quantity: float scalar, ndarray or Series, optional, default: None Total quantity of damaged components that determines the median repair cost. Not used for repair cost models with fixed median. sample_size: int, optional, default: 1 Number of samples drawn from the repair cost distribution. The default value yields one sample. Returns ------- unit_repair_cost: float scalar or ndarray Unit repair cost samples. """ output = None if self._repair_cost_CF is not None: output = self._repair_cost_CF.sample_unit_DV(quantity=quantity, sample_size=sample_size, **kwargs) return output def unit_reconstruction_time(self, quantity=None, sample_size=1, **kwargs): """ Sample the reconstruction time distribution and return the unit reconstruction times. The unit reconstruction times shall be multiplied by the quantity of damaged components to get the total reconstruction time for the components in this DS. Parameters ---------- quantity: float scalar, ndarray or Series, optional, default: None Total quantity of damaged components that determines the magnitude of median reconstruction time. Not used for reconstruction time models with fixed median. sample_size: int, optional, default: 1 Number of samples drawn from the reconstruction time distribution. The default value yields one sample. Returns ------- unit_reconstruction_time: float scalar or ndarray Unit reconstruction time samples. """ output = None if self._reconstruction_time_CF is not None: output = self._reconstruction_time_CF.sample_unit_DV( quantity=quantity, sample_size=sample_size, **kwargs) return output def red_tag_dmg_limit(self, sample_size=1, **kwargs): """ Sample the red tag consequence function and return the proportion of components that needs to be damaged to trigger a red tag. The red tag consequence function is assumed to have a fixed median value that does not depend on the quantity of damaged components. Parameters ---------- sample_size: int, optional, default: 1 Number of samples drawn from the red tag consequence distribution. The default value yields one sample. Returns ------- red_tag_trigger: float scalar or ndarray Samples of damaged component proportions that trigger a red tag. """ output = None if self._red_tag_CF is not None: output = self._red_tag_CF.sample_unit_DV(sample_size=sample_size, **kwargs) return output def unit_injuries(self, severity_level=0, sample_size=1, **kwargs): """ Sample the injury consequence function that corresponds to the specified level of severity and return the injuries per component unit. The injury consequence function is assumed to have a fixed median value that does not depend on the quantity of damaged components (i.e. the number of injuries per component unit does not change with the quantity of components.) Parameters ---------- severity_level: int, optional, default: 1 Identifies which injury consequence to sample. The indexing of severity levels is zero-based. sample_size: int, optional, default: 1 Number of samples drawn from the injury consequence distribution. The default value yields one sample. Returns ------- unit_injuries: float scalar or ndarray Unit injury samples. """ output = None if len(self._injuries_CF_set) > severity_level: CF = self._injuries_CF_set[severity_level] if CF is not None: output = CF.sample_unit_DV(sample_size=sample_size, **kwargs) return output class DamageStateGroup(object): """ A set of similar component damages that are controlled by the same EDP. Damages are described in detail by the set of Damage State objects. Damages in a DSG are assumed to occur at the same EDP magnitude. A Damage State Group (DSG) might have only a single DS in the simplest case. Parameters ---------- ID: int DS_set: DamageState array DS_set_kind: {'single', 'mutually_exclusive', 'simultaneous'} Specifies the relationship among the DS in the set. When only one DS is defined, use the 'single' option to improve calculation efficiency. When multiple DS are present, the 'mutually_exclusive' option assumes that the occurrence of one DS precludes the occurrence of another DS. In such a case, the weights of the DS in the set shall sum up to 1.0. In a 'simultaneous' case the DS are independent and unrelated. Hence, they can occur at the same time and at least one of them has to occur. """ def __init__(self, ID, DS_set, DS_set_kind): self._ID = ID self._DS_set = DS_set self._DS_set_kind = DS_set_kind class PerformanceGroup(object): """ A group of similar components that experience the same demands. FEMA P-58: Performance Groups (PGs) are a sub-categorization of fragility groups. A performance group is a subset of fragility group components that are subjected to the same demands (e.g. story drift, floor acceleration, etc.). In buildings, most performance groups shall be organized by story level. There is no need to separate performance groups by direction, because the direction of components within a group can be specified during definition, and it will be taken into consideration in the analysis. Parameters ---------- ID: int location: int Identifies the location of the components that belong to the PG. In a building, location shall typically refer to the story of the building. The location assigned to each PG shall be in agreement with the locations assigned to the Demand objects. quantity: RandomVariable Specifies the quantity of components that belong to this PG. Uncertainty in component quantities is considered by assigning a random variable to this property. fragility_functions: FragilityFunction list Each fragility function describes the probability that the damage in a subset of components will meet or exceed the damages described by each damage state group in the DSG_set. Each is a multi-dimensional function if there is more than one DSG. The number of functions shall match the number of subsets defined by the `csg_weights` parameter. DSG_set: DamageStateGroup array A set of sequential Damage State Groups that describe the plausible set of damage states of the components in the FG. csg_weights: float ndarray, optional, default: [1.0] Identifies subgroups of components within a PG, each of which have perfectly correlated behavior. Correlation between the damage and consequences among subgroups is controlled by the `correlation` parameter of the FragilityGroup that the PG belongs to. Note that if the components are assumed to have perfectly correlated behavior at the PG level, assigning several subgroups to the PG is unnecessary. This input shall be a list of weights that are applied to the quantity of components to define the amount of components in each subgroup. The sum of assigned weights shall be 1.0. directions: int ndarray, optional, default: [0] Identifies the direction of each subgroup of components within the PG. The number of directions shall be identical to the number of csg_weights assigned. In buildings, directions typically correspond to the orientation of components in plane. Hence, using 0 or 1 to identify 'X' or 'Y' is recommended. These directions shall be in agreement with the directions assigned to Demand objects. """ def __init__(self, ID, location, quantity, fragility_functions, DSG_set, csg_weights=[1.0], direction=0): self._ID = ID self._location = location self._quantity = quantity if type(fragility_functions) == FragilityFunction: self._FF_set = [fragility_functions,] else: self._FF_set = fragility_functions self._DSG_set = DSG_set self._csg_weights = csg_weights self._direction = direction def P_exc(self, EDP, DSG_ID): """ This is a convenience function that provides a shortcut to fragility_function.P_exc(). It calculates the exceedance probability of a given DSG conditioned on the provided EDP value(s). The fragility functions assigned to the first subset are used for this calculation because P_exc shall be identical among subsets. Parameters ---------- EDP: float scalar or ndarray Single EDP or numpy array of EDP values. DSG_ID: int Identifies the DSG of interest. Returns ------- P_exc: float scalar or ndarray Exceedance probability of the given DSG at the EDP point(s). """ return self._FF_set[0].P_exc(EDP, DSG_ID) class FragilityGroup(object): """ Groups a set of similar components from a loss-assessment perspective. Characterizes a set of structural or non-structural components that have similar construction characteristics, similar potential modes of damage, similar probability of incurring those modes of damage, and similar potential consequences resulting from their damage. Parameters ---------- ID: int demand_type: {'PID', 'PFA', 'PSD', 'PSA', 'ePGA', 'PGD'} The type of Engineering Demand Parameter (EDP) that controls the damage of the components in the FG. See Demand for acronym descriptions. performance_groups: PerformanceGroup array A list of performance groups that contain the components characterized by the FG. directional: bool, optional, default: True Determines whether the components in the FG are sensitive to the directionality of the EDP. correlation: bool, optional, default: True Determines whether the components within a Performance Group (PG) will have correlated or uncorrelated damage. Correlated damage means that all components will have the same damage state. In the uncorrelated case, each component in the performance group will have its damage state evaluated independently. Correlated damage reduces the required computational effort for the calculation. Incorrect correlation modeling will only slightly affect the mean estimates, but might significantly change the dispersion of results. demand_location_offset: int, optional, default: 0 Indicates if the location for the demand shall be different from the location of the components. Damage to components of the ceiling, for example, is controlled by demands on the floor above the one that the components belong to. This can be indicated by setting the demand_location_offset to 1 for such an FG. incomplete: bool, optional, default: False Indicates that the FG information is not complete and corresponding results shall be treated with caution. name: str, optional, default: '' Provides a short description of the fragility group. description: str, optional, default: '' Provides a detailed description of the fragility group. """ def __init__(self, ID, demand_type, performance_groups, directional=True, correlation=True, demand_location_offset=0, incomplete=False, name='', description='', unit="ea"): self._ID = ID self._demand_type = demand_type self._performance_groups = performance_groups self._directional = directional self._correlation = correlation self._demand_location_offset = demand_location_offset self._incomplete = incomplete self._name = name self._description = description self._unit = unit @property def description(self): """ Return the fragility group description. """ return self._description @property def name(self): """ Return the name of the fragility group. """ return self._name
40.598824
86
0.663131
from .base import * class FragilityFunction(object): def __init__(self, EDP_limit): self._EDP_limit = EDP_limit self._EDP_tags = [EDP_lim_i.name for EDP_lim_i in EDP_limit] def P_exc(self, EDP, DSG_ID): EDP = np.asarray(EDP, dtype=np.float64) nvals = EDP.size if DSG_ID == 0: P_exc = np.ones(EDP.size) else: ndims = len(self._EDP_limit) limit_list = np.full((ndims, nvals), -np.inf, dtype=np.float64) limit_list[DSG_ID - 1:] = EDP limit_list[:DSG_ID - 1] = None P_exc = 1.0 - self._EDP_limit[0].RV_set.orthotope_density( lower=limit_list, var_subset = self._EDP_tags) if EDP.size == 1: return P_exc[0] else: return P_exc def DSG_given_EDP(self, EDP, force_resampling=False): nsamples = EDP.size samples = pd.DataFrame(dict([(lim_i.name, lim_i.samples) for lim_i in self._EDP_limit])) if type(EDP) not in [pd.Series, pd.DataFrame]: EDP = pd.Series(EDP, name='EDP') nstates = samples.shape[1] samples = samples.loc[EDP.index,:] sample_cols = samples.columns samples = samples[sample_cols[np.argsort(sample_cols)]] EXC = samples.sub(EDP, axis=0) < 0. DSG_ID = pd.Series(np.zeros(len(samples.index)), name='DSG_ID', index=samples.index, dtype=np.int) for s in range(nstates): DSG_ID[EXC.iloc[:,s]] = s + 1 return DSG_ID def prep_constant_median_DV(median): def f(quantity): return median return f def prep_bounded_linear_median_DV(median_max, median_min, quantity_lower, quantity_upper): def f(quantity): if quantity is None: raise ValueError( 'A bounded linear median Decision Variable function called ' 'without specifying the quantity of damaged components') q_array = np.asarray(quantity, dtype=np.float64) output = np.interp(q_array, [quantity_lower, quantity_upper], [median_max, median_min]) return output return f def prep_bounded_multilinear_median_DV(medians, quantities): def f(quantity): if quantity is None: raise ValueError( 'A bounded linear median Decision Variable function called ' 'without specifying the quantity of damaged components') q_array = np.asarray(quantity, dtype=np.float64) output = np.interp(q_array, quantities, medians) return output return f class ConsequenceFunction(object): def __init__(self, DV_median, DV_distribution): self._DV_median = DV_median self._DV_distribution = DV_distribution def median(self, quantity=None): return self._DV_median(quantity) def sample_unit_DV(self, quantity=None, sample_size=1, force_resampling=False): median = self.median(quantity=np.asarray(quantity)) if self._DV_distribution is None: return median else: if quantity is not None: if type(quantity) not in [pd.Series, pd.DataFrame]: quantity = pd.Series(quantity, name='QNT') if quantity.size > 1: sample_size = quantity.size elif sample_size > 1: quantity = pd.Series(np.ones(sample_size) * quantity.values, name='QNT') if quantity is not None: samples = pd.Series(self._DV_distribution.samples).loc[quantity.index] else: samples = pd.Series(self._DV_distribution.samples).iloc[:sample_size] samples = samples * median return samples class DamageState(object): def __init__(self, ID, weight=1.0, description='', repair_cost_CF=None, reconstruction_time_CF=None, injuries_CF_set=None, affected_area=0., red_tag_CF=None): self._ID = int(ID) self._weight = float(weight) self._description = description self._repair_cost_CF = repair_cost_CF self._reconstruction_time_CF = reconstruction_time_CF self._injuries_CF_set = injuries_CF_set self._affected_area = affected_area self._red_tag_CF = red_tag_CF @property def description(self): return self._description @property def weight(self): return self._weight def unit_repair_cost(self, quantity=None, sample_size=1, **kwargs): output = None if self._repair_cost_CF is not None: output = self._repair_cost_CF.sample_unit_DV(quantity=quantity, sample_size=sample_size, **kwargs) return output def unit_reconstruction_time(self, quantity=None, sample_size=1, **kwargs): output = None if self._reconstruction_time_CF is not None: output = self._reconstruction_time_CF.sample_unit_DV( quantity=quantity, sample_size=sample_size, **kwargs) return output def red_tag_dmg_limit(self, sample_size=1, **kwargs): output = None if self._red_tag_CF is not None: output = self._red_tag_CF.sample_unit_DV(sample_size=sample_size, **kwargs) return output def unit_injuries(self, severity_level=0, sample_size=1, **kwargs): output = None if len(self._injuries_CF_set) > severity_level: CF = self._injuries_CF_set[severity_level] if CF is not None: output = CF.sample_unit_DV(sample_size=sample_size, **kwargs) return output class DamageStateGroup(object): def __init__(self, ID, DS_set, DS_set_kind): self._ID = ID self._DS_set = DS_set self._DS_set_kind = DS_set_kind class PerformanceGroup(object): def __init__(self, ID, location, quantity, fragility_functions, DSG_set, csg_weights=[1.0], direction=0): self._ID = ID self._location = location self._quantity = quantity if type(fragility_functions) == FragilityFunction: self._FF_set = [fragility_functions,] else: self._FF_set = fragility_functions self._DSG_set = DSG_set self._csg_weights = csg_weights self._direction = direction def P_exc(self, EDP, DSG_ID): return self._FF_set[0].P_exc(EDP, DSG_ID) class FragilityGroup(object): def __init__(self, ID, demand_type, performance_groups, directional=True, correlation=True, demand_location_offset=0, incomplete=False, name='', description='', unit="ea"): self._ID = ID self._demand_type = demand_type self._performance_groups = performance_groups self._directional = directional self._correlation = correlation self._demand_location_offset = demand_location_offset self._incomplete = incomplete self._name = name self._description = description self._unit = unit @property def description(self): return self._description @property def name(self): return self._name
true
true
f735e7a4939d5cc1f3c6d92e39265e3f54d99be0
2,093
py
Python
old_game/spells/base.py
jwvhewitt/dmeternal
bb09f2d497daf9b40dd8cfee10c55be55fb7c3cb
[ "Apache-2.0" ]
53
2015-07-03T21:25:36.000Z
2022-02-18T23:08:38.000Z
old_game/spells/base.py
jwvhewitt/dmeternal
bb09f2d497daf9b40dd8cfee10c55be55fb7c3cb
[ "Apache-2.0" ]
5
2015-07-03T21:27:12.000Z
2016-12-08T14:40:38.000Z
old_game/spells/base.py
jwvhewitt/dmeternal
bb09f2d497daf9b40dd8cfee10c55be55fb7c3cb
[ "Apache-2.0" ]
14
2016-02-02T06:49:51.000Z
2022-02-24T13:24:35.000Z
from .. import invocations # Enumerate some constants for the six spell colors. SOLAR, EARTH, WATER, FIRE, AIR, LUNAR = list(range( 6)) class Spell( invocations.Invocation ): def __init__( self, name, desc, fx, rank=1, gems=dict(), mpfudge=0, com_tar=None, exp_tar=None, ai_tar=None, shot_anim=None ): self.name=name self.desc = desc self.fx = fx self.rank = rank self.gems = gems self.mpfudge = mpfudge self.com_tar = com_tar self.exp_tar = exp_tar self.ai_tar = ai_tar self.shot_anim = shot_anim def mp_cost( self ): """Return spell invocation cost.""" return max( (1 + sum( self.gems.values() )) * (self.rank * 2 - 1 ) + self.mpfudge, 1 ) def gems_needed( self ): """Return total number of spell gems needed.""" return self.rank + 1 def can_be_invoked( self, chara, in_combat=False ): if in_combat: return self.com_tar and chara.current_mp() >= self.mp_cost() else: return self.exp_tar and chara.current_mp() >= self.mp_cost() def can_be_learned( self, chara, right_now=True ): if right_now: ok = self.gems_needed() <= ( chara.total_spell_gems() - chara.spell_gems_used() ) and self.rank <= (chara.rank() + 1) // 2 if ok: for k,v in self.gems.items(): if v > chara.spell_gems_of_color(k) - chara.spell_gems_of_color_used(k): ok = False break else: ok = self.gems_needed() <= chara.total_spell_gems() and self.rank <= (chara.rank() + 1) // 2 if ok: for k,v in self.gems.items(): if v > chara.spell_gems_of_color(k): ok = False break return ok def pay_invocation_price( self, chara ): chara.mp_damage += self.mp_cost() def menu_str( self ): return "{0} [{1}MP]".format( self.name, self.mp_cost() ) def __str__( self ): return self.name
36.086207
134
0.557573
from .. import invocations SOLAR, EARTH, WATER, FIRE, AIR, LUNAR = list(range( 6)) class Spell( invocations.Invocation ): def __init__( self, name, desc, fx, rank=1, gems=dict(), mpfudge=0, com_tar=None, exp_tar=None, ai_tar=None, shot_anim=None ): self.name=name self.desc = desc self.fx = fx self.rank = rank self.gems = gems self.mpfudge = mpfudge self.com_tar = com_tar self.exp_tar = exp_tar self.ai_tar = ai_tar self.shot_anim = shot_anim def mp_cost( self ): return max( (1 + sum( self.gems.values() )) * (self.rank * 2 - 1 ) + self.mpfudge, 1 ) def gems_needed( self ): return self.rank + 1 def can_be_invoked( self, chara, in_combat=False ): if in_combat: return self.com_tar and chara.current_mp() >= self.mp_cost() else: return self.exp_tar and chara.current_mp() >= self.mp_cost() def can_be_learned( self, chara, right_now=True ): if right_now: ok = self.gems_needed() <= ( chara.total_spell_gems() - chara.spell_gems_used() ) and self.rank <= (chara.rank() + 1) // 2 if ok: for k,v in self.gems.items(): if v > chara.spell_gems_of_color(k) - chara.spell_gems_of_color_used(k): ok = False break else: ok = self.gems_needed() <= chara.total_spell_gems() and self.rank <= (chara.rank() + 1) // 2 if ok: for k,v in self.gems.items(): if v > chara.spell_gems_of_color(k): ok = False break return ok def pay_invocation_price( self, chara ): chara.mp_damage += self.mp_cost() def menu_str( self ): return "{0} [{1}MP]".format( self.name, self.mp_cost() ) def __str__( self ): return self.name
true
true
f735e7b770f1da0d8886b0e78f5cda6a16931206
24,389
py
Python
release/scripts/startup/bl_ui/space_topbar.py
vlobanov/blender
5c58740a08ef369435b48093b91fa7075fef8383
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
release/scripts/startup/bl_ui/space_topbar.py
vlobanov/blender
5c58740a08ef369435b48093b91fa7075fef8383
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
release/scripts/startup/bl_ui/space_topbar.py
vlobanov/blender
5c58740a08ef369435b48093b91fa7075fef8383
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2019-09-13T15:29:14.000Z
2019-09-13T15:29:14.000Z
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> import bpy from bpy.types import Header, Menu, Panel class TOPBAR_HT_upper_bar(Header): bl_space_type = 'TOPBAR' def draw(self, context): region = context.region if region.alignment == 'RIGHT': self.draw_right(context) else: self.draw_left(context) def draw_left(self, context): layout = self.layout window = context.window screen = context.screen TOPBAR_MT_editor_menus.draw_collapsible(context, layout) layout.separator() if not screen.show_fullscreen: layout.template_ID_tabs( window, "workspace", new="workspace.add", menu="TOPBAR_MT_workspace_menu", ) else: layout.operator( "screen.back_to_previous", icon='SCREEN_BACK', text="Back to Previous", ) def draw_right(self, context): layout = self.layout window = context.window screen = context.screen scene = window.scene # If statusbar is hidden, still show messages at the top if not screen.show_statusbar: layout.template_reports_banner() layout.template_running_jobs() # Active workspace view-layer is retrieved through window, not through workspace. layout.template_ID(window, "scene", new="scene.new", unlink="scene.delete") row = layout.row(align=True) row.template_search( window, "view_layer", scene, "view_layers", new="scene.view_layer_add", unlink="scene.view_layer_remove") class TOPBAR_PT_gpencil_layers(Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'HEADER' bl_label = "Layers" bl_ui_units_x = 14 @classmethod def poll(cls, context): if context.gpencil_data is None: return False ob = context.object if ob is not None and ob.type == 'GPENCIL': return True return False def draw(self, context): layout = self.layout gpd = context.gpencil_data # Grease Pencil data... if (gpd is None) or (not gpd.layers): layout.operator("gpencil.layer_add", text="New Layer") else: self.draw_layers(context, layout, gpd) def draw_layers(self, context, layout, gpd): row = layout.row() col = row.column() layer_rows = 10 col.template_list("GPENCIL_UL_layer", "", gpd, "layers", gpd.layers, "active_index", rows=layer_rows, sort_reverse=True, sort_lock=True) gpl = context.active_gpencil_layer if gpl: srow = col.row(align=True) srow.prop(gpl, "blend_mode", text="Blend") srow = col.row(align=True) srow.prop(gpl, "opacity", text="Opacity", slider=True) srow.prop(gpl, "mask_layer", text="", icon='MOD_MASK' if gpl.mask_layer else 'LAYER_ACTIVE') srow = col.row(align=True) srow.prop(gpl, "use_solo_mode", text="Show Only On Keyframed") col = row.column() sub = col.column(align=True) sub.operator("gpencil.layer_add", icon='ADD', text="") sub.operator("gpencil.layer_remove", icon='REMOVE', text="") gpl = context.active_gpencil_layer if gpl: sub.menu("GPENCIL_MT_layer_context_menu", icon='DOWNARROW_HLT', text="") if len(gpd.layers) > 1: col.separator() sub = col.column(align=True) sub.operator("gpencil.layer_move", icon='TRIA_UP', text="").type = 'UP' sub.operator("gpencil.layer_move", icon='TRIA_DOWN', text="").type = 'DOWN' col.separator() sub = col.column(align=True) sub.operator("gpencil.layer_isolate", icon='LOCKED', text="").affect_visibility = False sub.operator("gpencil.layer_isolate", icon='HIDE_OFF', text="").affect_visibility = True class TOPBAR_MT_editor_menus(Menu): bl_idname = "TOPBAR_MT_editor_menus" bl_label = "" def draw(self, context): layout = self.layout if context.area.show_menus: layout.menu("TOPBAR_MT_app", text="", icon='BLENDER') else: layout.menu("TOPBAR_MT_app", text="Blender") layout.menu("TOPBAR_MT_file") layout.menu("TOPBAR_MT_edit") layout.menu("TOPBAR_MT_render") layout.menu("TOPBAR_MT_window") layout.menu("TOPBAR_MT_help") class TOPBAR_MT_app(Menu): bl_label = "Blender" def draw(self, _context): layout = self.layout layout.operator("wm.splash") layout.separator() layout.menu("TOPBAR_MT_app_support") layout.separator() layout.menu("TOPBAR_MT_app_about") layout.separator() layout.operator("preferences.app_template_install", text="Install Application Template...") class TOPBAR_MT_file(Menu): bl_label = "File" def draw(self, context): layout = self.layout layout.operator_context = 'INVOKE_AREA' layout.menu("TOPBAR_MT_file_new", text="New", icon='FILE_NEW') layout.operator("wm.open_mainfile", text="Open...", icon='FILE_FOLDER') layout.menu("TOPBAR_MT_file_open_recent") layout.operator("wm.revert_mainfile") layout.menu("TOPBAR_MT_file_recover") layout.separator() layout.operator_context = 'EXEC_AREA' if context.blend_data.is_saved else 'INVOKE_AREA' layout.operator("wm.save_mainfile", text="Save", icon='FILE_TICK') layout.operator_context = 'INVOKE_AREA' layout.operator("wm.save_as_mainfile", text="Save As...") layout.operator_context = 'INVOKE_AREA' layout.operator("wm.save_as_mainfile", text="Save Copy...").copy = True layout.separator() layout.operator_context = 'INVOKE_AREA' layout.operator("wm.link", text="Link...", icon='LINK_BLEND') layout.operator("wm.append", text="Append...", icon='APPEND_BLEND') layout.menu("TOPBAR_MT_file_previews") layout.separator() layout.menu("TOPBAR_MT_file_import", icon='IMPORT') layout.menu("TOPBAR_MT_file_export", icon='EXPORT') layout.separator() layout.menu("TOPBAR_MT_file_external_data") layout.separator() layout.menu("TOPBAR_MT_file_defaults") layout.separator() layout.operator("wm.quit_blender", text="Quit", icon='QUIT') class TOPBAR_MT_file_new(Menu): bl_label = "New File" @staticmethod def app_template_paths(): import os template_paths = bpy.utils.app_template_paths() # expand template paths app_templates = [] for path in template_paths: for d in os.listdir(path): if d.startswith(("__", ".")): continue template = os.path.join(path, d) if os.path.isdir(template): # template_paths_expand.append(template) app_templates.append(d) return sorted(app_templates) @staticmethod def draw_ex(layout, _context, *, use_splash=False, use_more=False): layout.operator_context = 'INVOKE_DEFAULT' # Limit number of templates in splash screen, spill over into more menu. paths = TOPBAR_MT_file_new.app_template_paths() splash_limit = 5 if use_splash: icon = 'FILE_NEW' show_more = len(paths) > (splash_limit - 1) if show_more: paths = paths[:splash_limit - 2] elif use_more: icon = 'FILE_NEW' paths = paths[splash_limit - 2:] show_more = False else: icon = 'NONE' show_more = False # Draw application templates. if not use_more: props = layout.operator("wm.read_homefile", text="General", icon=icon) props.app_template = "" for d in paths: props = layout.operator( "wm.read_homefile", text=bpy.path.display_name(d), icon=icon, ) props.app_template = d layout.operator_context = 'EXEC_DEFAULT' if show_more: layout.menu("TOPBAR_MT_templates_more", text="...") def draw(self, context): TOPBAR_MT_file_new.draw_ex(self.layout, context) class TOPBAR_MT_file_recover(Menu): bl_label = "Recover" def draw(self, _context): layout = self.layout layout.operator("wm.recover_last_session", text="Last Session") layout.operator("wm.recover_auto_save", text="Auto Save...") class TOPBAR_MT_file_defaults(Menu): bl_label = "Defaults" def draw(self, context): layout = self.layout prefs = context.preferences layout.operator_context = 'INVOKE_AREA' if any(bpy.utils.app_template_paths()): app_template = prefs.app_template else: app_template = None if app_template: layout.label(text=bpy.path.display_name(app_template, has_ext=False)) layout.operator("wm.save_homefile") props = layout.operator("wm.read_factory_settings") if app_template: props.app_template = app_template class TOPBAR_MT_app_about(Menu): bl_label = "About" def draw(self, _context): layout = self.layout layout.operator( "wm.url_open", text="Release Notes", icon='URL', ).url = "https://www.blender.org/download/releases/%d-%d/" % bpy.app.version[:2] layout.separator() layout.operator( "wm.url_open", text="Blender Website", icon='URL', ).url = "https://www.blender.org/" layout.operator( "wm.url_open", text="Credits", icon='URL', ).url = "https://www.blender.org/about/credits/" layout.separator() layout.operator( "wm.url_open", text="License", icon='URL', ).url = "https://www.blender.org/about/license/" class TOPBAR_MT_app_support(Menu): bl_label = "Support Blender" def draw(self, _context): layout = self.layout layout.operator( "wm.url_open", text="Development Fund", icon='FUND', ).url = "https://fund.blender.org" layout.separator() layout.operator( "wm.url_open", text="Blender Store", icon='URL', ).url = "https://store.blender.org" class TOPBAR_MT_templates_more(Menu): bl_label = "Templates" def draw(self, context): bpy.types.TOPBAR_MT_file_new.draw_ex(self.layout, context, use_more=True) class TOPBAR_MT_file_import(Menu): bl_idname = "TOPBAR_MT_file_import" bl_label = "Import" def draw(self, _context): if bpy.app.build_options.collada: self.layout.operator("wm.collada_import", text="Collada (Default) (.dae)") if bpy.app.build_options.alembic: self.layout.operator("wm.alembic_import", text="Alembic (.abc)") class TOPBAR_MT_file_export(Menu): bl_idname = "TOPBAR_MT_file_export" bl_label = "Export" def draw(self, _context): if bpy.app.build_options.collada: self.layout.operator("wm.collada_export", text="Collada (Default) (.dae)") if bpy.app.build_options.alembic: self.layout.operator("wm.alembic_export", text="Alembic (.abc)") class TOPBAR_MT_file_external_data(Menu): bl_label = "External Data" def draw(self, _context): layout = self.layout icon = 'CHECKBOX_HLT' if bpy.data.use_autopack else 'CHECKBOX_DEHLT' layout.operator("file.autopack_toggle", icon=icon) layout.separator() pack_all = layout.row() pack_all.operator("file.pack_all") pack_all.active = not bpy.data.use_autopack unpack_all = layout.row() unpack_all.operator("file.unpack_all") unpack_all.active = not bpy.data.use_autopack layout.separator() layout.operator("file.make_paths_relative") layout.operator("file.make_paths_absolute") layout.operator("file.report_missing_files") layout.operator("file.find_missing_files") class TOPBAR_MT_file_previews(Menu): bl_label = "Data Previews" def draw(self, _context): layout = self.layout layout.operator("wm.previews_ensure") layout.operator("wm.previews_batch_generate") layout.separator() layout.operator("wm.previews_clear") layout.operator("wm.previews_batch_clear") class TOPBAR_MT_render(Menu): bl_label = "Render" def draw(self, context): layout = self.layout rd = context.scene.render layout.operator("render.render", text="Render Image", icon='RENDER_STILL').use_viewport = True props = layout.operator("render.render", text="Render Animation", icon='RENDER_ANIMATION') props.animation = True props.use_viewport = True layout.separator() layout.operator("sound.mixdown", text="Render Audio...") layout.separator() layout.operator("render.view_show", text="View Render") layout.operator("render.play_rendered_anim", text="View Animation") layout.prop_menu_enum(rd, "display_mode", text="Display Mode") layout.separator() layout.prop(rd, "use_lock_interface", text="Lock Interface") class TOPBAR_MT_edit(Menu): bl_label = "Edit" def draw(self, context): layout = self.layout layout.operator("ed.undo") layout.operator("ed.redo") layout.separator() layout.operator("ed.undo_history", text="Undo History...") layout.separator() layout.operator("screen.repeat_last") layout.operator("screen.repeat_history", text="Repeat History...") layout.separator() layout.operator("screen.redo_last", text="Adjust Last Operation...") layout.separator() layout.operator("wm.search_menu", text="Operator Search...", icon='VIEWZOOM') layout.separator() # Mainly to expose shortcut since this depends on the context. props = layout.operator("wm.call_panel", text="Rename Active Item...") props.name = "TOPBAR_PT_name" props.keep_open = False layout.separator() # Should move elsewhere (impacts outliner & 3D view). tool_settings = context.tool_settings layout.prop(tool_settings, "lock_object_mode") layout.separator() layout.operator("screen.userpref_show", text="Preferences...", icon='PREFERENCES') class TOPBAR_MT_window(Menu): bl_label = "Window" def draw(self, context): import sys layout = self.layout layout.operator("wm.window_new") layout.operator("wm.window_new_main") layout.separator() layout.operator("wm.window_fullscreen_toggle", icon='FULLSCREEN_ENTER') layout.separator() layout.operator("screen.workspace_cycle", text="Next Workspace").direction = 'NEXT' layout.operator("screen.workspace_cycle", text="Previous Workspace").direction = 'PREV' layout.separator() layout.prop(context.screen, "show_statusbar") layout.separator() layout.operator("screen.screenshot") if sys.platform[:3] == "win": layout.separator() layout.operator("wm.console_toggle", icon='CONSOLE') if context.scene.render.use_multiview: layout.separator() layout.operator("wm.set_stereo_3d") class TOPBAR_MT_help(Menu): bl_label = "Help" def draw(self, context): # If 'url_prefill_from_blender' becomes slow it could be made into a separate operator # to avoid constructing the bug report just to show this menu. from bl_ui_utils.bug_report_url import url_prefill_from_blender layout = self.layout show_developer = context.preferences.view.show_developer_ui if bpy.app.version_cycle in {'rc', 'release'}: manual_version = '%d.%d' % bpy.app.version[:2] else: manual_version = 'dev' layout.operator( "wm.url_open", text="Manual", icon='HELP', ).url = "https://docs.blender.org/manual/en/" + manual_version + "/" layout.operator( "wm.url_open", text="Tutorials", icon='URL', ).url = "https://www.blender.org/tutorials" layout.operator( "wm.url_open", text="Support", icon='URL', ).url = "https://www.blender.org/support" layout.separator() layout.operator( "wm.url_open", text="User Communities", icon='URL', ).url = "https://www.blender.org/community/" layout.operator( "wm.url_open", text="Developer Community", icon='URL', ).url = "https://devtalk.blender.org" layout.separator() layout.operator( "wm.url_open", text="Python API Reference", icon='URL', ).url = bpy.types.WM_OT_doc_view._prefix if show_developer: layout.operator( "wm.url_open", text="Developer Documentation", icon='URL', ).url = "https://wiki.blender.org/wiki/Main_Page" layout.operator("wm.operator_cheat_sheet", icon='TEXT') layout.separator() layout.operator( "wm.url_open", text="Report a Bug", icon='URL', ).url = url_prefill_from_blender() layout.separator() layout.operator("wm.sysinfo") class TOPBAR_MT_file_context_menu(Menu): bl_label = "File Context Menu" def draw(self, _context): layout = self.layout layout.operator_context = 'INVOKE_AREA' layout.menu("TOPBAR_MT_file_new", text="New", icon='FILE_NEW') layout.operator("wm.open_mainfile", text="Open...", icon='FILE_FOLDER') layout.separator() layout.operator("wm.link", text="Link...", icon='LINK_BLEND') layout.operator("wm.append", text="Append...", icon='APPEND_BLEND') layout.separator() layout.menu("TOPBAR_MT_file_import", icon='IMPORT') layout.menu("TOPBAR_MT_file_export", icon='EXPORT') layout.separator() layout.operator("screen.userpref_show", text="Preferences...", icon='PREFERENCES') class TOPBAR_MT_workspace_menu(Menu): bl_label = "Workspace" def draw(self, _context): layout = self.layout layout.operator("workspace.duplicate", text="Duplicate", icon='DUPLICATE') if len(bpy.data.workspaces) > 1: layout.operator("workspace.delete", text="Delete", icon='REMOVE') layout.separator() layout.operator("workspace.reorder_to_front", text="Reorder to Front", icon='TRIA_LEFT_BAR') layout.operator("workspace.reorder_to_back", text="Reorder to Back", icon='TRIA_RIGHT_BAR') layout.separator() # For key binding discoverability. props = layout.operator("screen.workspace_cycle", text="Previous Workspace") props.direction = 'PREV' props = layout.operator("screen.workspace_cycle", text="Next Workspace") props.direction = 'NEXT' # Grease Pencil Object - Primitive curve class TOPBAR_PT_gpencil_primitive(Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'HEADER' bl_label = "Primitives" def draw(self, context): settings = context.tool_settings.gpencil_sculpt layout = self.layout # Curve layout.template_curve_mapping(settings, "thickness_primitive_curve", brush=True) # Grease Pencil Fill class TOPBAR_PT_gpencil_fill(Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'HEADER' bl_label = "Advanced" def draw(self, context): paint = context.tool_settings.gpencil_paint brush = paint.brush gp_settings = brush.gpencil_settings layout = self.layout # Fill row = layout.row(align=True) row.prop(gp_settings, "fill_factor", text="Resolution") if gp_settings.fill_draw_mode != 'STROKE': row = layout.row(align=True) row.prop(gp_settings, "show_fill", text="Ignore Transparent Strokes") row = layout.row(align=True) row.prop(gp_settings, "fill_threshold", text="Threshold") # Only a popover class TOPBAR_PT_name(Panel): bl_space_type = 'TOPBAR' # dummy bl_region_type = 'HEADER' bl_label = "Rename Active Item" bl_ui_units_x = 14 def draw(self, context): layout = self.layout # Edit first editable button in popup def row_with_icon(layout, icon): row = layout.row() row.activate_init = True row.label(icon=icon) return row mode = context.mode scene = context.scene space = context.space_data space_type = None if (space is None) else space.type found = False if space_type == 'SEQUENCE_EDITOR': layout.label(text="Sequence Strip Name") item = getattr(scene.sequence_editor, "active_strip") if item: row = row_with_icon(layout, 'SEQUENCE') row.prop(item, "name", text="") found = True elif space_type == 'NODE_EDITOR': layout.label(text="Node Label") item = context.active_node if item: row = row_with_icon(layout, 'NODE') row.prop(item, "label", text="") found = True else: if mode == 'POSE' or (mode == 'WEIGHT_PAINT' and context.pose_object): layout.label(text="Bone Name") item = context.active_pose_bone if item: row = row_with_icon(layout, 'BONE_DATA') row.prop(item, "name", text="") found = True elif mode == 'EDIT_ARMATURE': layout.label(text="Bone Name") item = context.active_bone if item: row = row_with_icon(layout, 'BONE_DATA') row.prop(item, "name", text="") found = True else: layout.label(text="Object Name") item = context.object if item: row = row_with_icon(layout, 'OBJECT_DATA') row.prop(item, "name", text="") found = True if not found: row = row_with_icon(layout, 'ERROR') row.label(text="No active item") classes = ( TOPBAR_HT_upper_bar, TOPBAR_MT_file_context_menu, TOPBAR_MT_workspace_menu, TOPBAR_MT_editor_menus, TOPBAR_MT_app, TOPBAR_MT_app_about, TOPBAR_MT_app_support, TOPBAR_MT_file, TOPBAR_MT_file_new, TOPBAR_MT_file_recover, TOPBAR_MT_file_defaults, TOPBAR_MT_templates_more, TOPBAR_MT_file_import, TOPBAR_MT_file_export, TOPBAR_MT_file_external_data, TOPBAR_MT_file_previews, TOPBAR_MT_edit, TOPBAR_MT_render, TOPBAR_MT_window, TOPBAR_MT_help, TOPBAR_PT_gpencil_layers, TOPBAR_PT_gpencil_primitive, TOPBAR_PT_gpencil_fill, TOPBAR_PT_name, ) if __name__ == "__main__": # only for live edit. from bpy.utils import register_class for cls in classes: register_class(cls)
30.334577
104
0.613801
f, context): layout = self.layout window = context.window screen = context.screen TOPBAR_MT_editor_menus.draw_collapsible(context, layout) layout.separator() if not screen.show_fullscreen: layout.template_ID_tabs( window, "workspace", new="workspace.add", menu="TOPBAR_MT_workspace_menu", ) else: layout.operator( "screen.back_to_previous", icon='SCREEN_BACK', text="Back to Previous", ) def draw_right(self, context): layout = self.layout window = context.window screen = context.screen scene = window.scene if not screen.show_statusbar: layout.template_reports_banner() layout.template_running_jobs() layout.template_ID(window, "scene", new="scene.new", unlink="scene.delete") row = layout.row(align=True) row.template_search( window, "view_layer", scene, "view_layers", new="scene.view_layer_add", unlink="scene.view_layer_remove") class TOPBAR_PT_gpencil_layers(Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'HEADER' bl_label = "Layers" bl_ui_units_x = 14 @classmethod def poll(cls, context): if context.gpencil_data is None: return False ob = context.object if ob is not None and ob.type == 'GPENCIL': return True return False def draw(self, context): layout = self.layout gpd = context.gpencil_data if (gpd is None) or (not gpd.layers): layout.operator("gpencil.layer_add", text="New Layer") else: self.draw_layers(context, layout, gpd) def draw_layers(self, context, layout, gpd): row = layout.row() col = row.column() layer_rows = 10 col.template_list("GPENCIL_UL_layer", "", gpd, "layers", gpd.layers, "active_index", rows=layer_rows, sort_reverse=True, sort_lock=True) gpl = context.active_gpencil_layer if gpl: srow = col.row(align=True) srow.prop(gpl, "blend_mode", text="Blend") srow = col.row(align=True) srow.prop(gpl, "opacity", text="Opacity", slider=True) srow.prop(gpl, "mask_layer", text="", icon='MOD_MASK' if gpl.mask_layer else 'LAYER_ACTIVE') srow = col.row(align=True) srow.prop(gpl, "use_solo_mode", text="Show Only On Keyframed") col = row.column() sub = col.column(align=True) sub.operator("gpencil.layer_add", icon='ADD', text="") sub.operator("gpencil.layer_remove", icon='REMOVE', text="") gpl = context.active_gpencil_layer if gpl: sub.menu("GPENCIL_MT_layer_context_menu", icon='DOWNARROW_HLT', text="") if len(gpd.layers) > 1: col.separator() sub = col.column(align=True) sub.operator("gpencil.layer_move", icon='TRIA_UP', text="").type = 'UP' sub.operator("gpencil.layer_move", icon='TRIA_DOWN', text="").type = 'DOWN' col.separator() sub = col.column(align=True) sub.operator("gpencil.layer_isolate", icon='LOCKED', text="").affect_visibility = False sub.operator("gpencil.layer_isolate", icon='HIDE_OFF', text="").affect_visibility = True class TOPBAR_MT_editor_menus(Menu): bl_idname = "TOPBAR_MT_editor_menus" bl_label = "" def draw(self, context): layout = self.layout if context.area.show_menus: layout.menu("TOPBAR_MT_app", text="", icon='BLENDER') else: layout.menu("TOPBAR_MT_app", text="Blender") layout.menu("TOPBAR_MT_file") layout.menu("TOPBAR_MT_edit") layout.menu("TOPBAR_MT_render") layout.menu("TOPBAR_MT_window") layout.menu("TOPBAR_MT_help") class TOPBAR_MT_app(Menu): bl_label = "Blender" def draw(self, _context): layout = self.layout layout.operator("wm.splash") layout.separator() layout.menu("TOPBAR_MT_app_support") layout.separator() layout.menu("TOPBAR_MT_app_about") layout.separator() layout.operator("preferences.app_template_install", text="Install Application Template...") class TOPBAR_MT_file(Menu): bl_label = "File" def draw(self, context): layout = self.layout layout.operator_context = 'INVOKE_AREA' layout.menu("TOPBAR_MT_file_new", text="New", icon='FILE_NEW') layout.operator("wm.open_mainfile", text="Open...", icon='FILE_FOLDER') layout.menu("TOPBAR_MT_file_open_recent") layout.operator("wm.revert_mainfile") layout.menu("TOPBAR_MT_file_recover") layout.separator() layout.operator_context = 'EXEC_AREA' if context.blend_data.is_saved else 'INVOKE_AREA' layout.operator("wm.save_mainfile", text="Save", icon='FILE_TICK') layout.operator_context = 'INVOKE_AREA' layout.operator("wm.save_as_mainfile", text="Save As...") layout.operator_context = 'INVOKE_AREA' layout.operator("wm.save_as_mainfile", text="Save Copy...").copy = True layout.separator() layout.operator_context = 'INVOKE_AREA' layout.operator("wm.link", text="Link...", icon='LINK_BLEND') layout.operator("wm.append", text="Append...", icon='APPEND_BLEND') layout.menu("TOPBAR_MT_file_previews") layout.separator() layout.menu("TOPBAR_MT_file_import", icon='IMPORT') layout.menu("TOPBAR_MT_file_export", icon='EXPORT') layout.separator() layout.menu("TOPBAR_MT_file_external_data") layout.separator() layout.menu("TOPBAR_MT_file_defaults") layout.separator() layout.operator("wm.quit_blender", text="Quit", icon='QUIT') class TOPBAR_MT_file_new(Menu): bl_label = "New File" @staticmethod def app_template_paths(): import os template_paths = bpy.utils.app_template_paths() app_templates = [] for path in template_paths: for d in os.listdir(path): if d.startswith(("__", ".")): continue template = os.path.join(path, d) if os.path.isdir(template): app_templates.append(d) return sorted(app_templates) @staticmethod def draw_ex(layout, _context, *, use_splash=False, use_more=False): layout.operator_context = 'INVOKE_DEFAULT' paths = TOPBAR_MT_file_new.app_template_paths() splash_limit = 5 if use_splash: icon = 'FILE_NEW' show_more = len(paths) > (splash_limit - 1) if show_more: paths = paths[:splash_limit - 2] elif use_more: icon = 'FILE_NEW' paths = paths[splash_limit - 2:] show_more = False else: icon = 'NONE' show_more = False if not use_more: props = layout.operator("wm.read_homefile", text="General", icon=icon) props.app_template = "" for d in paths: props = layout.operator( "wm.read_homefile", text=bpy.path.display_name(d), icon=icon, ) props.app_template = d layout.operator_context = 'EXEC_DEFAULT' if show_more: layout.menu("TOPBAR_MT_templates_more", text="...") def draw(self, context): TOPBAR_MT_file_new.draw_ex(self.layout, context) class TOPBAR_MT_file_recover(Menu): bl_label = "Recover" def draw(self, _context): layout = self.layout layout.operator("wm.recover_last_session", text="Last Session") layout.operator("wm.recover_auto_save", text="Auto Save...") class TOPBAR_MT_file_defaults(Menu): bl_label = "Defaults" def draw(self, context): layout = self.layout prefs = context.preferences layout.operator_context = 'INVOKE_AREA' if any(bpy.utils.app_template_paths()): app_template = prefs.app_template else: app_template = None if app_template: layout.label(text=bpy.path.display_name(app_template, has_ext=False)) layout.operator("wm.save_homefile") props = layout.operator("wm.read_factory_settings") if app_template: props.app_template = app_template class TOPBAR_MT_app_about(Menu): bl_label = "About" def draw(self, _context): layout = self.layout layout.operator( "wm.url_open", text="Release Notes", icon='URL', ).url = "https://www.blender.org/download/releases/%d-%d/" % bpy.app.version[:2] layout.separator() layout.operator( "wm.url_open", text="Blender Website", icon='URL', ).url = "https://www.blender.org/" layout.operator( "wm.url_open", text="Credits", icon='URL', ).url = "https://www.blender.org/about/credits/" layout.separator() layout.operator( "wm.url_open", text="License", icon='URL', ).url = "https://www.blender.org/about/license/" class TOPBAR_MT_app_support(Menu): bl_label = "Support Blender" def draw(self, _context): layout = self.layout layout.operator( "wm.url_open", text="Development Fund", icon='FUND', ).url = "https://fund.blender.org" layout.separator() layout.operator( "wm.url_open", text="Blender Store", icon='URL', ).url = "https://store.blender.org" class TOPBAR_MT_templates_more(Menu): bl_label = "Templates" def draw(self, context): bpy.types.TOPBAR_MT_file_new.draw_ex(self.layout, context, use_more=True) class TOPBAR_MT_file_import(Menu): bl_idname = "TOPBAR_MT_file_import" bl_label = "Import" def draw(self, _context): if bpy.app.build_options.collada: self.layout.operator("wm.collada_import", text="Collada (Default) (.dae)") if bpy.app.build_options.alembic: self.layout.operator("wm.alembic_import", text="Alembic (.abc)") class TOPBAR_MT_file_export(Menu): bl_idname = "TOPBAR_MT_file_export" bl_label = "Export" def draw(self, _context): if bpy.app.build_options.collada: self.layout.operator("wm.collada_export", text="Collada (Default) (.dae)") if bpy.app.build_options.alembic: self.layout.operator("wm.alembic_export", text="Alembic (.abc)") class TOPBAR_MT_file_external_data(Menu): bl_label = "External Data" def draw(self, _context): layout = self.layout icon = 'CHECKBOX_HLT' if bpy.data.use_autopack else 'CHECKBOX_DEHLT' layout.operator("file.autopack_toggle", icon=icon) layout.separator() pack_all = layout.row() pack_all.operator("file.pack_all") pack_all.active = not bpy.data.use_autopack unpack_all = layout.row() unpack_all.operator("file.unpack_all") unpack_all.active = not bpy.data.use_autopack layout.separator() layout.operator("file.make_paths_relative") layout.operator("file.make_paths_absolute") layout.operator("file.report_missing_files") layout.operator("file.find_missing_files") class TOPBAR_MT_file_previews(Menu): bl_label = "Data Previews" def draw(self, _context): layout = self.layout layout.operator("wm.previews_ensure") layout.operator("wm.previews_batch_generate") layout.separator() layout.operator("wm.previews_clear") layout.operator("wm.previews_batch_clear") class TOPBAR_MT_render(Menu): bl_label = "Render" def draw(self, context): layout = self.layout rd = context.scene.render layout.operator("render.render", text="Render Image", icon='RENDER_STILL').use_viewport = True props = layout.operator("render.render", text="Render Animation", icon='RENDER_ANIMATION') props.animation = True props.use_viewport = True layout.separator() layout.operator("sound.mixdown", text="Render Audio...") layout.separator() layout.operator("render.view_show", text="View Render") layout.operator("render.play_rendered_anim", text="View Animation") layout.prop_menu_enum(rd, "display_mode", text="Display Mode") layout.separator() layout.prop(rd, "use_lock_interface", text="Lock Interface") class TOPBAR_MT_edit(Menu): bl_label = "Edit" def draw(self, context): layout = self.layout layout.operator("ed.undo") layout.operator("ed.redo") layout.separator() layout.operator("ed.undo_history", text="Undo History...") layout.separator() layout.operator("screen.repeat_last") layout.operator("screen.repeat_history", text="Repeat History...") layout.separator() layout.operator("screen.redo_last", text="Adjust Last Operation...") layout.separator() layout.operator("wm.search_menu", text="Operator Search...", icon='VIEWZOOM') layout.separator() props = layout.operator("wm.call_panel", text="Rename Active Item...") props.name = "TOPBAR_PT_name" props.keep_open = False layout.separator() tool_settings = context.tool_settings layout.prop(tool_settings, "lock_object_mode") layout.separator() layout.operator("screen.userpref_show", text="Preferences...", icon='PREFERENCES') class TOPBAR_MT_window(Menu): bl_label = "Window" def draw(self, context): import sys layout = self.layout layout.operator("wm.window_new") layout.operator("wm.window_new_main") layout.separator() layout.operator("wm.window_fullscreen_toggle", icon='FULLSCREEN_ENTER') layout.separator() layout.operator("screen.workspace_cycle", text="Next Workspace").direction = 'NEXT' layout.operator("screen.workspace_cycle", text="Previous Workspace").direction = 'PREV' layout.separator() layout.prop(context.screen, "show_statusbar") layout.separator() layout.operator("screen.screenshot") if sys.platform[:3] == "win": layout.separator() layout.operator("wm.console_toggle", icon='CONSOLE') if context.scene.render.use_multiview: layout.separator() layout.operator("wm.set_stereo_3d") class TOPBAR_MT_help(Menu): bl_label = "Help" def draw(self, context): from bl_ui_utils.bug_report_url import url_prefill_from_blender layout = self.layout show_developer = context.preferences.view.show_developer_ui if bpy.app.version_cycle in {'rc', 'release'}: manual_version = '%d.%d' % bpy.app.version[:2] else: manual_version = 'dev' layout.operator( "wm.url_open", text="Manual", icon='HELP', ).url = "https://docs.blender.org/manual/en/" + manual_version + "/" layout.operator( "wm.url_open", text="Tutorials", icon='URL', ).url = "https://www.blender.org/tutorials" layout.operator( "wm.url_open", text="Support", icon='URL', ).url = "https://www.blender.org/support" layout.separator() layout.operator( "wm.url_open", text="User Communities", icon='URL', ).url = "https://www.blender.org/community/" layout.operator( "wm.url_open", text="Developer Community", icon='URL', ).url = "https://devtalk.blender.org" layout.separator() layout.operator( "wm.url_open", text="Python API Reference", icon='URL', ).url = bpy.types.WM_OT_doc_view._prefix if show_developer: layout.operator( "wm.url_open", text="Developer Documentation", icon='URL', ).url = "https://wiki.blender.org/wiki/Main_Page" layout.operator("wm.operator_cheat_sheet", icon='TEXT') layout.separator() layout.operator( "wm.url_open", text="Report a Bug", icon='URL', ).url = url_prefill_from_blender() layout.separator() layout.operator("wm.sysinfo") class TOPBAR_MT_file_context_menu(Menu): bl_label = "File Context Menu" def draw(self, _context): layout = self.layout layout.operator_context = 'INVOKE_AREA' layout.menu("TOPBAR_MT_file_new", text="New", icon='FILE_NEW') layout.operator("wm.open_mainfile", text="Open...", icon='FILE_FOLDER') layout.separator() layout.operator("wm.link", text="Link...", icon='LINK_BLEND') layout.operator("wm.append", text="Append...", icon='APPEND_BLEND') layout.separator() layout.menu("TOPBAR_MT_file_import", icon='IMPORT') layout.menu("TOPBAR_MT_file_export", icon='EXPORT') layout.separator() layout.operator("screen.userpref_show", text="Preferences...", icon='PREFERENCES') class TOPBAR_MT_workspace_menu(Menu): bl_label = "Workspace" def draw(self, _context): layout = self.layout layout.operator("workspace.duplicate", text="Duplicate", icon='DUPLICATE') if len(bpy.data.workspaces) > 1: layout.operator("workspace.delete", text="Delete", icon='REMOVE') layout.separator() layout.operator("workspace.reorder_to_front", text="Reorder to Front", icon='TRIA_LEFT_BAR') layout.operator("workspace.reorder_to_back", text="Reorder to Back", icon='TRIA_RIGHT_BAR') layout.separator() props = layout.operator("screen.workspace_cycle", text="Previous Workspace") props.direction = 'PREV' props = layout.operator("screen.workspace_cycle", text="Next Workspace") props.direction = 'NEXT' class TOPBAR_PT_gpencil_primitive(Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'HEADER' bl_label = "Primitives" def draw(self, context): settings = context.tool_settings.gpencil_sculpt layout = self.layout layout.template_curve_mapping(settings, "thickness_primitive_curve", brush=True) class TOPBAR_PT_gpencil_fill(Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'HEADER' bl_label = "Advanced" def draw(self, context): paint = context.tool_settings.gpencil_paint brush = paint.brush gp_settings = brush.gpencil_settings layout = self.layout row = layout.row(align=True) row.prop(gp_settings, "fill_factor", text="Resolution") if gp_settings.fill_draw_mode != 'STROKE': row = layout.row(align=True) row.prop(gp_settings, "show_fill", text="Ignore Transparent Strokes") row = layout.row(align=True) row.prop(gp_settings, "fill_threshold", text="Threshold") class TOPBAR_PT_name(Panel): bl_space_type = 'TOPBAR' bl_region_type = 'HEADER' bl_label = "Rename Active Item" bl_ui_units_x = 14 def draw(self, context): layout = self.layout def row_with_icon(layout, icon): row = layout.row() row.activate_init = True row.label(icon=icon) return row mode = context.mode scene = context.scene space = context.space_data space_type = None if (space is None) else space.type found = False if space_type == 'SEQUENCE_EDITOR': layout.label(text="Sequence Strip Name") item = getattr(scene.sequence_editor, "active_strip") if item: row = row_with_icon(layout, 'SEQUENCE') row.prop(item, "name", text="") found = True elif space_type == 'NODE_EDITOR': layout.label(text="Node Label") item = context.active_node if item: row = row_with_icon(layout, 'NODE') row.prop(item, "label", text="") found = True else: if mode == 'POSE' or (mode == 'WEIGHT_PAINT' and context.pose_object): layout.label(text="Bone Name") item = context.active_pose_bone if item: row = row_with_icon(layout, 'BONE_DATA') row.prop(item, "name", text="") found = True elif mode == 'EDIT_ARMATURE': layout.label(text="Bone Name") item = context.active_bone if item: row = row_with_icon(layout, 'BONE_DATA') row.prop(item, "name", text="") found = True else: layout.label(text="Object Name") item = context.object if item: row = row_with_icon(layout, 'OBJECT_DATA') row.prop(item, "name", text="") found = True if not found: row = row_with_icon(layout, 'ERROR') row.label(text="No active item") classes = ( TOPBAR_HT_upper_bar, TOPBAR_MT_file_context_menu, TOPBAR_MT_workspace_menu, TOPBAR_MT_editor_menus, TOPBAR_MT_app, TOPBAR_MT_app_about, TOPBAR_MT_app_support, TOPBAR_MT_file, TOPBAR_MT_file_new, TOPBAR_MT_file_recover, TOPBAR_MT_file_defaults, TOPBAR_MT_templates_more, TOPBAR_MT_file_import, TOPBAR_MT_file_export, TOPBAR_MT_file_external_data, TOPBAR_MT_file_previews, TOPBAR_MT_edit, TOPBAR_MT_render, TOPBAR_MT_window, TOPBAR_MT_help, TOPBAR_PT_gpencil_layers, TOPBAR_PT_gpencil_primitive, TOPBAR_PT_gpencil_fill, TOPBAR_PT_name, ) if __name__ == "__main__": from bpy.utils import register_class for cls in classes: register_class(cls)
true
true
f735e8029c232fc98daab344aa931b6c8667ee1a
5,397
py
Python
example_unity_socket.py
sailab-code/SAILenv
e202be04de468a58e58ae858693245f5556c3597
[ "MIT" ]
null
null
null
example_unity_socket.py
sailab-code/SAILenv
e202be04de468a58e58ae858693245f5556c3597
[ "MIT" ]
1
2021-02-25T16:47:39.000Z
2021-04-22T08:08:53.000Z
example_unity_socket.py
sailab-code/SAILenv
e202be04de468a58e58ae858693245f5556c3597
[ "MIT" ]
2
2021-05-01T12:42:53.000Z
2021-07-10T06:46:44.000Z
# # Copyright (C) 2020 Enrico Meloni, Luca Pasqualini, Matteo Tiezzi # University of Siena - Artificial Intelligence Laboratory - SAILab # # # SAILenv is licensed under a MIT license. # # You should have received a copy of the license along with this # work. If not, see <https://en.wikipedia.org/wiki/MIT_License>. # Import packages import time import numpy as np import cv2 import tkinter as tk from PIL import Image, ImageTk # Import src from sailenv.agent import Agent frames: int = 1000 def decode_image(array: np.ndarray): """ Decode the given numpy array with OpenCV. :param array: the numpy array to decode :return: the decoded image that can be displayed """ image = cv2.cvtColor(array, cv2.COLOR_RGB2BGR) return image def draw_flow_lines(current_frame, optical_flow, line_step=16, line_color=(0, 255, 0)): frame_with_lines = current_frame.copy() line_color = (line_color[2], line_color[1], line_color[0]) for y in range(0, optical_flow.shape[0], line_step): for x in range(0, optical_flow.shape[1], line_step): fx, fy = optical_flow[y, x] cv2.line(frame_with_lines, (x, y), (int(x + fx), int(y + fy)), line_color) cv2.circle(frame_with_lines, (x, y), 1, line_color, -1) return frame_with_lines def draw_flow_map(optical_flow): hsv = np.zeros((optical_flow.shape[0], optical_flow.shape[1], 3), dtype=np.uint8) hsv[..., 1] = 255 mag, ang = cv2.cartToPolar(optical_flow[..., 0], optical_flow[..., 1]) hsv[..., 0] = ang * 180 / np.pi / 2 hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) frame_flow_map = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) return frame_flow_map def create_windows(agent: Agent): windows = {} for view, is_active in agent.active_frames.items(): if is_active: window = tk.Tk() window.geometry(f"{agent.width}x{agent.height}") windows[view] = window # host = "bronte.diism.unisi.it" host = "127.0.0.1" # host = "eliza.diism.unisi.it" if __name__ == '__main__': print("Generating agent...") agent = Agent(depth_frame_active=True, flow_frame_active=True, object_frame_active=True, main_frame_active=True, category_frame_active=True, width=256, height=192, host=host, port=8085, use_gzip=False) print("Registering agent on server...") agent.register() print(f"Agent registered with ID: {agent.id}") last_unity_time: float = 0.0 print(f"Available scenes: {agent.scenes}") scene = agent.scenes[0] print(f"Changing scene to {scene}") agent.change_scene(scene) print(f"Available categories: {agent.categories}") # print(agent.get_resolution()) try: print("Press ESC to close") while True: start_real_time = time.time() start_unity_time = last_unity_time start_get = time.time() frame = agent.get_frame() step_get = time.time() - start_get print(f"get frame in seconds: {step_get}, fps: {1/step_get}") if frame["main"] is not None: main_img = cv2.cvtColor(frame["main"], cv2.COLOR_RGB2BGR) cv2.imshow("PBR", main_img) if frame["category"] is not None: start_get_cat = time.time() # cat_img = np.zeros((agent.height * agent.width, 3), dtype=np.uint8) # Extract values and keys k = np.array(list(agent.cat_colors.keys())) v = np.array(list(agent.cat_colors.values())) mapping_ar = np.zeros((np.maximum(np.max(k)+1, 256), 3), dtype=v.dtype) mapping_ar[k] = v out = mapping_ar[frame["category"]] # for idx, sup in enumerate(frame["category"]): # try: # color = agent.cat_colors[sup] # cat_img[idx] = color # except KeyError: # #print(f"key error on color get: {sup}") # cat_img[idx] = [0,0,0] cat_img = np.reshape(out, (agent.height, agent.width, 3)) cat_img = cat_img.astype(np.uint8) # unity stores the image as left to right, bottom to top # while CV2 reads it left to right, top to bottom # a flip up-down solves the problem # cat_img = np.flipud(cat_img) step_get_cat = time.time() - start_get_cat print(f"Plot category in : {step_get_cat}") cv2.imshow("Category", cat_img) if frame["object"] is not None: obj_img = decode_image(frame["object"]) cv2.imshow("Object ID", obj_img) if frame["flow"] is not None: flow = frame["flow"] flow_img = draw_flow_map(flow) cv2.imshow("Optical Flow", flow_img) if frame["depth"] is not None: depth = frame["depth"] cv2.imshow("Depth", depth) key = cv2.waitKey(1) # print(f"FPS: {1/(time.time() - start_real_time)}") if key == 27: # ESC Pressed break finally: print(f"Closing agent {agent.id}") agent.delete()
32.512048
106
0.576987
import time import numpy as np import cv2 import tkinter as tk from PIL import Image, ImageTk from sailenv.agent import Agent frames: int = 1000 def decode_image(array: np.ndarray): image = cv2.cvtColor(array, cv2.COLOR_RGB2BGR) return image def draw_flow_lines(current_frame, optical_flow, line_step=16, line_color=(0, 255, 0)): frame_with_lines = current_frame.copy() line_color = (line_color[2], line_color[1], line_color[0]) for y in range(0, optical_flow.shape[0], line_step): for x in range(0, optical_flow.shape[1], line_step): fx, fy = optical_flow[y, x] cv2.line(frame_with_lines, (x, y), (int(x + fx), int(y + fy)), line_color) cv2.circle(frame_with_lines, (x, y), 1, line_color, -1) return frame_with_lines def draw_flow_map(optical_flow): hsv = np.zeros((optical_flow.shape[0], optical_flow.shape[1], 3), dtype=np.uint8) hsv[..., 1] = 255 mag, ang = cv2.cartToPolar(optical_flow[..., 0], optical_flow[..., 1]) hsv[..., 0] = ang * 180 / np.pi / 2 hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) frame_flow_map = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) return frame_flow_map def create_windows(agent: Agent): windows = {} for view, is_active in agent.active_frames.items(): if is_active: window = tk.Tk() window.geometry(f"{agent.width}x{agent.height}") windows[view] = window host = "127.0.0.1" if __name__ == '__main__': print("Generating agent...") agent = Agent(depth_frame_active=True, flow_frame_active=True, object_frame_active=True, main_frame_active=True, category_frame_active=True, width=256, height=192, host=host, port=8085, use_gzip=False) print("Registering agent on server...") agent.register() print(f"Agent registered with ID: {agent.id}") last_unity_time: float = 0.0 print(f"Available scenes: {agent.scenes}") scene = agent.scenes[0] print(f"Changing scene to {scene}") agent.change_scene(scene) print(f"Available categories: {agent.categories}") try: print("Press ESC to close") while True: start_real_time = time.time() start_unity_time = last_unity_time start_get = time.time() frame = agent.get_frame() step_get = time.time() - start_get print(f"get frame in seconds: {step_get}, fps: {1/step_get}") if frame["main"] is not None: main_img = cv2.cvtColor(frame["main"], cv2.COLOR_RGB2BGR) cv2.imshow("PBR", main_img) if frame["category"] is not None: start_get_cat = time.time() k = np.array(list(agent.cat_colors.keys())) v = np.array(list(agent.cat_colors.values())) mapping_ar = np.zeros((np.maximum(np.max(k)+1, 256), 3), dtype=v.dtype) mapping_ar[k] = v out = mapping_ar[frame["category"]] mg = np.reshape(out, (agent.height, agent.width, 3)) cat_img = cat_img.astype(np.uint8) step_get_cat = time.time() - start_get_cat print(f"Plot category in : {step_get_cat}") cv2.imshow("Category", cat_img) if frame["object"] is not None: obj_img = decode_image(frame["object"]) cv2.imshow("Object ID", obj_img) if frame["flow"] is not None: flow = frame["flow"] flow_img = draw_flow_map(flow) cv2.imshow("Optical Flow", flow_img) if frame["depth"] is not None: depth = frame["depth"] cv2.imshow("Depth", depth) key = cv2.waitKey(1) if key == 27: break finally: print(f"Closing agent {agent.id}") agent.delete()
true
true
f735e9ed972bd701f8c000f77a88cedb63fe8f5b
14,425
py
Python
src/AzureFunctions/ComputeGradient/AzureUtilities.py
georgeAccnt-GH/Azure2019
5c9774b644d3ea15590d72d3de9363df72abf7ab
[ "MIT" ]
2
2020-09-18T09:18:06.000Z
2021-01-10T05:26:53.000Z
src/AzureFunctions/ComputeGradient/AzureUtilities.py
georgeAccnt-GH/Azure2019
5c9774b644d3ea15590d72d3de9363df72abf7ab
[ "MIT" ]
1
2021-04-16T06:21:14.000Z
2021-04-16T16:29:43.000Z
src/AzureFunctions/ComputeGradient/AzureUtilities.py
georgeAccnt-GH/Azure2019
5c9774b644d3ea15590d72d3de9363df72abf7ab
[ "MIT" ]
1
2020-01-23T21:45:49.000Z
2020-01-23T21:45:49.000Z
import numpy as np import segyio import subprocess import os, h5py from scipy import interpolate from devito import Eq, Operator from azure.storage.blob import BlockBlobService, PublicAccess blob_service = BlockBlobService(account_name='', account_key='') #################################################################################################### # array put and get def convert_to_string(t): if len(t) == 1: return str(t[0]) elif len(t) == 2: return str(t[0]) + 'S' + str(t[1]) else: return str(t[0]) + 'S' + str(t[1]) + 'S' + str(t[2]) def convert_int_from_string(s): s_split = s.split('S') ndim = len(s_split) if ndim==1: n = int(s_split[0]) elif ndim==2: n1 = int(s_split[0]) n2 = int(s_split[1]) n = (n1, n2) else: n1 = int(s_split[0]) n2 = int(s_split[1]) n3 = int(s_split[2]) n = (n1, n2, n3) return n def convert_float_from_string(s): s_split = s.split('S') ndim = len(s_split) d1 = float(s_split[0]) d2 = float(s_split[1]) if ndim==2: d = (d1, d2) else: d3 = float(s_split[2]) d = (d1, d2, d3) return d # write array def array_put(blob, container, blob_name, index=0, count=None, validate_content=False): shape_str = convert_to_string(blob.shape) meta = {'dtype':str(blob.dtype), 'shape': shape_str} blob_service.create_blob_from_bytes( container, blob_name, blob.tostring(), # blob index = index, # start index in array of bytes count = count, # number of bytes to upload metadata = meta, # Name-value pairs validate_content = validate_content ) # put array def array_get(container, blob_name, start_range=None, end_range=None, validate_content=False): binary_blob = blob_service.get_blob_to_bytes( container, blob_name, start_range=start_range, end_range=end_range, validate_content=validate_content ) try: meta = binary_blob.metadata shape = convert_int_from_string(meta['shape']) x = np.fromstring(binary_blob.content, dtype=meta['dtype']) return x.reshape(shape) except: x = np.fromstring(binary_blob.content, dtype='float32') return x #################################################################################################### # model put and get # write model def model_put(model_blob, origin, spacing, container, blob_name, index=0, count=None, validate_content=False): shape_str = convert_to_string(model_blob.shape) origin_str = convert_to_string(origin) spacing_str = convert_to_string(spacing) meta = {'dtype':str(model_blob.dtype), 'shape': shape_str, 'origin': origin_str, 'spacing': spacing_str} blob_service.create_blob_from_bytes( container, blob_name, model_blob.tostring(), # blob index = index, # start index in array of bytes count = count, # number of bytes to upload metadata = meta, # Name-value pairs validate_content = validate_content ) # read model def model_get(container, blob_name, start_range=None, end_range=None, validate_content=False): binary_blob = blob_service.get_blob_to_bytes( container, blob_name, start_range=start_range, end_range=end_range, validate_content=validate_content ) meta = binary_blob.metadata shape = convert_int_from_string(meta['shape']) origin = convert_float_from_string(meta['origin']) spacing = convert_float_from_string(meta['spacing']) x = np.fromstring(binary_blob.content, dtype=meta['dtype']) return x.reshape(shape), origin, spacing def model_read(filename): h5f = h5py.File(filename, 'r') m = h5f['m'][:] o = h5f['origin'][:] d = h5f['spacing'][:] h5f.close() return m, o, d def model_write(m, origin, spacing, filename): h5f = h5py.File(filename, 'w') h5f.create_dataset('m', data=m) h5f.create_dataset('origin', data=origin) h5f.create_dataset('spacing', data=spacing) h5f.close() #################################################################################################### # segy read def segy_get(container, path, filename, ndims=2, keepFile=False): # copy from s3 to local volume subprocess.run(['az', 'storage', 'blob', 'download', '--container-name', container, '--name', path + filename, '--file', os.getcwd() + '/' + filename, '--output', 'table']) argout = segy_read(filename, ndims=ndims) if keepFile is False: subprocess.run(['rm', '-f', filename]) return argout def segy_read(filename, ndims=2): with segyio.open(filename, "r", ignore_geometry=True) as segyfile: segyfile.mmap() # Assume input data is for single common shot gather sourceX = segyfile.attributes(segyio.TraceField.SourceX)[0] sourceY = segyfile.attributes(segyio.TraceField.SourceY)[0] sourceZ = segyfile.attributes(segyio.TraceField.SourceSurfaceElevation)[0] groupX = segyfile.attributes(segyio.TraceField.GroupX)[:] groupY = segyfile.attributes(segyio.TraceField.GroupY)[:] groupZ = segyfile.attributes(segyio.TraceField.ReceiverGroupElevation)[:] dt = segyio.dt(segyfile)/1e3 # Apply scaling elevScalar = segyfile.attributes(segyio.TraceField.ElevationScalar)[0] coordScalar = segyfile.attributes(segyio.TraceField.SourceGroupScalar)[0] if coordScalar < 0.: sourceX = sourceX / np.abs(coordScalar) sourceY = sourceY / np.abs(coordScalar) sourceZ = sourceZ / np.abs(elevScalar) groupX = groupX / np.abs(coordScalar) groupY = groupY / np.abs(coordScalar) elif coordScalar > 0.: sourceX = sourceX * np.abs(coordScalar) sourceY = sourceY * np.abs(coordScalar) sourceZ = sourceZ * np.abs(elevScalar) groupX = groupX * np.abs(coordScalar) groupY = groupY * np.abs(coordScalar) if elevScalar < 0.: groupZ = groupZ / np.abs(elevScalar) elif elevScalar > 0.: groupZ = groupZ * np.abs(elevScalar) nrec = len(groupX) nt = len(segyfile.trace[0]) # Extract data data = np.zeros(shape=(nt, nrec), dtype='float32') for i in range(nrec): data[:,i] = segyfile.trace[i] tmax = (nt-1)*dt if ndims == 2: return data, sourceX, sourceZ, groupX, groupZ, tmax, dt, nt else: return data, sourceX, sourceY, sourceZ, groupX, groupY, groupZ, tmax, dt, nt def segy_model_read(filename): with segyio.open(filename, "r", ignore_geometry=True) as segyfile: segyfile.mmap() # Assume input data is for single common shot gather sourceX = segyfile.attributes(segyio.TraceField.SourceX) dx = segyio.dt(segyfile)/1e3 # Apply scaling coordScalar = segyfile.attributes(segyio.TraceField.SourceGroupScalar)[0] if coordScalar < 0.: sourceX = sourceX / np.abs(coordScalar) elif coordScalar > 0.: sourceX = sourceX * np.abs(coordScalar) nx = len(sourceX) nz = len(segyfile.trace[0]) # Extract data data = np.zeros(shape=(nx, nz), dtype='float32') for i in range(nx): data[i,:] = segyfile.trace[i] return data, sourceX, dx def segy_put(data, sourceX, sourceZ, groupX, groupZ, dt, container, path, filename, sourceY=None, groupY=None, elevScalar=-1000, coordScalar=-1000, keepFile=False): # Write segy file segy_write(data, sourceX, sourceZ, groupX, groupZ, dt, filename, sourceY=None, groupY=None, elevScalar=-1000, coordScalar=-1000) # copy from local volume to s3 status = subprocess.run(['az', 'storage', 'blob', 'upload', '--container-name', container, '--file', filename, '--name', path+filename]) if keepFile is False: subprocess.run(['rm', '-f', filename]) return status def segy_write(data, sourceX, sourceZ, groupX, groupZ, dt, filename, sourceY=None, groupY=None, elevScalar=-1000, coordScalar=-1000): nt = data.shape[0] nsrc = 1 nxrec = len(groupX) if sourceY is None and groupY is None: sourceY = np.zeros(1, dtype='int') groupY = np.zeros(nxrec, dtype='int') nyrec = len(groupY) # Create spec object spec = segyio.spec() spec.ilines = np.arange(nxrec) # dummy trace count spec.xlines = np.zeros(1, dtype='int') # assume coordinates are already vectorized for 3D spec.samples = range(nt) spec.format=1 spec.sorting=1 with segyio.create(filename, spec) as segyfile: for i in range(nxrec): segyfile.header[i] = { segyio.su.tracl : i+1, segyio.su.tracr : i+1, segyio.su.fldr : 1, segyio.su.tracf : i+1, segyio.su.sx : int(np.round(sourceX[0] * np.abs(coordScalar))), segyio.su.sy : int(np.round(sourceY[0] * np.abs(coordScalar))), segyio.su.selev: int(np.round(sourceZ[0] * np.abs(elevScalar))), segyio.su.gx : int(np.round(groupX[i] * np.abs(coordScalar))), segyio.su.gy : int(np.round(groupY[i] * np.abs(coordScalar))), segyio.su.gelev : int(np.round(groupZ[i] * np.abs(elevScalar))), segyio.su.dt : int(dt*1e3), segyio.su.scalel : int(elevScalar), segyio.su.scalco : int(coordScalar) } segyfile.trace[i] = data[:, i] segyfile.dt=int(dt*1e3) #################################################################################################### # Auxiliary modeling functions # Add/subtract devito data w/ MPI def add_rec(d1, d2): eq = Eq(d1, d1 + d2) op = Operator([eq]) op() return d1 def sub_rec(d1, d2): eq = Eq(d1, d1 - d2) op = Operator([eq],subs={d2.indices[-1]: d1.indices[-1]}) op() return d1 # Create 3D receiver grid from 1D x and y receiver vectors def create_3D_grid(xrec, yrec, zrec): nxrec = len(xrec) nyrec = len(yrec) nrec_total = nxrec * nyrec rec = np.zeros(shape=(nrec_total, 3), dtype='float32') count = 0 for j in range(nxrec): for k in range(nyrec): rec[count, 0] = xrec[j] rec[count, 1] = yrec[k] rec[count, 2] = zrec count += 1 return rec def restrict_model_to_receiver_grid(sx, gx, m, spacing, origin, sy=None, gy=None, buffer_size=500, numpy_coords=True): # Model parameters shape = m.shape ndim = len(shape) if ndim == 2: domain_size = ((shape[0] - 1) * spacing[0], (shape[1] - 1) * spacing[1]) else: domain_size = ((shape[0] - 1) * spacing[0], (shape[1] - 1) * spacing[1], \ (shape[2] - 1) * spacing[2]) # Scan for minimum/maximum source/receiver coordinates min_x = np.min([np.min(sx), np.min(gx)]) max_x = np.max([np.max(sx), np.max(gx)]) if sy is not None and gy is not None: min_y = np.min([np.min(sy), np.min(gy)]) max_y = np.max([np.max(sy), np.max(gy)]) # Add buffer zone if possible min_x = np.max([origin[0], min_x - buffer_size]) max_x = np.min([origin[0] + domain_size[0], max_x + buffer_size]) #print("min_x: ", min_x) #print("max_x: ", max_x) if ndim == 3: min_y = np.max([origin[1], min_y - buffer_size]) max_y = np.min([origin[1] + domain_size[1], max_y + buffer_size]) #print("min_y: ", min_y) #print("max_y: ", max_y) # Extract model part nx_min = int(min_x / spacing[0]) nx_max = int(max_x / spacing[0]) #print("nx_min: ", nx_min) #print("nx_max: ", nx_max) ox = nx_min * spacing[0] oz = origin[-1] if ndim == 3: ny_min = int(min_y / spacing[1]) ny_max = int(max_y / spacing[1]) #print("ny_min: ", ny_min) #print("ny_max: ", ny_max) oy = ny_min * spacing[1] # Extract relevant part of model n_orig = shape #print("Original shape: ", n_orig) if ndim == 2: m = m[nx_min:nx_max+1, :] origin = (ox, oz) else: m = m[nx_min:nx_max+1, ny_min:ny_max+1, :] origin = (ox, oy, oz) shape = m.shape #print("New shape: ", shape) return m, shape, origin def extent_gradient(shape_full, origin_full, shape_sub, origin_sub, spacing, g): nz = shape_full[-1] ndim = len(shape_full) nx_left = int((origin_sub[0] - origin_full[0]) / spacing[0]) nx_right = shape_full[0] - shape_sub[0] - nx_left if ndim == 3: ny_left = int((origin_sub[1] - origin_full[1]) / spacing[1]) ny_right = shape_full[1] - shape_sub[1] - ny_left if ndim == 2: block1 = np.zeros(shape=(nx_left, nz), dtype='float32') block2 = np.zeros(shape=(nx_right, nz), dtype='float32') g = np.concatenate((block1, g, block2), axis=0) else: block1 = np.zeros(shape=(nx_left, shape_sub[1], nz), dtype='float32') block2 = np.zeros(shape=(nx_right, shape_sub[1], nz), dtype='float32') g = np.concatenate((block1, g, block2), axis=0) del block1, block2 block3 = np.zeros(shape=(shape_full[0], ny_left, nz), dtype='float32') block4 = np.zeros(shape=(shape_full[0], ny_right, nz), dtype='float32') g = np.concatenate((block3, g, block4), axis=1) return g #################################################################################################### # Auxiliary AWS functions def resample(data, t0, tn, nt_prev, nt_new): time_prev = np.linspace(start=t0, stop=tn, num=nt_prev) time_new = np.linspace(start=t0, stop=tn, num=nt_new) d_resamp = np.zeros(shape=(len(time_new), data.shape[1]), dtype='float32') for i in range(data.shape[1]): tck = interpolate.splrep(time_prev, data[:, i], k=3) d_resamp[:, i] = interpolate.splev(time_new, tck) return d_resamp # Get chunk size of gradient def get_chunk_size(g_size, num_chunks): average_size = int(g_size/num_chunks) num_residuals = g_size % num_chunks chunk_size = np.ones(num_chunks, dtype='int')*average_size if num_residuals > 0: for j in range(num_residuals): chunk_size[j] += 1 return chunk_size
33.941176
164
0.590017
import numpy as np import segyio import subprocess import os, h5py from scipy import interpolate from devito import Eq, Operator from azure.storage.blob import BlockBlobService, PublicAccess blob_service = BlockBlobService(account_name='', account_key='')
true
true
f735ea24e6fd85bb1e3da23800a0230330cffa36
419
py
Python
Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/install/cmd/shutdown/tasking_dsz.py
bidhata/EquationGroupLeaks
1ff4bc115cb2bd5bf2ed6bf769af44392926830c
[ "Unlicense" ]
9
2019-11-22T04:58:40.000Z
2022-02-26T16:47:28.000Z
Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/install/cmd/shutdown/tasking_dsz.py
bidhata/EquationGroupLeaks
1ff4bc115cb2bd5bf2ed6bf769af44392926830c
[ "Unlicense" ]
null
null
null
Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/install/cmd/shutdown/tasking_dsz.py
bidhata/EquationGroupLeaks
1ff4bc115cb2bd5bf2ed6bf769af44392926830c
[ "Unlicense" ]
8
2017-09-27T10:31:18.000Z
2022-01-08T10:30:46.000Z
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: tasking_dsz.py import mcl.framework import mcl.tasking class dsz: INTERFACE = 16842801 PFAM = 4159 PROVIDER_ANY = 4159 PROVIDER = 16846911 RPC_INFO_SHUTDOWN = mcl.tasking.RpcInfo(mcl.framework.DSZ, [INTERFACE, PROVIDER_ANY, 0])
29.928571
92
0.720764
import mcl.framework import mcl.tasking class dsz: INTERFACE = 16842801 PFAM = 4159 PROVIDER_ANY = 4159 PROVIDER = 16846911 RPC_INFO_SHUTDOWN = mcl.tasking.RpcInfo(mcl.framework.DSZ, [INTERFACE, PROVIDER_ANY, 0])
true
true
f735ea3e98c2932b4eebe3ab870b9d47c441fccc
1,673
py
Python
src/test/testcases/testIstepInvalid.py
madscientist159/sbe
63aa1d2be90d345001937953370c3f4e1536e513
[ "Apache-2.0" ]
null
null
null
src/test/testcases/testIstepInvalid.py
madscientist159/sbe
63aa1d2be90d345001937953370c3f4e1536e513
[ "Apache-2.0" ]
null
null
null
src/test/testcases/testIstepInvalid.py
madscientist159/sbe
63aa1d2be90d345001937953370c3f4e1536e513
[ "Apache-2.0" ]
null
null
null
# IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/test/testcases/testIstepInvalid.py $ # # OpenPOWER sbe Project # # Contributors Listed Below - COPYRIGHT 2015,2016 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG import sys sys.path.append("targets/p9_nimbus/sbeTest" ) import testUtil err = False #from testWrite import * TESTDATA = [0,0,0,3, 0,0,0xA1,0x01, 0,0x02,0x00,0x1] EXPDATA = [0xc0,0xde,0xa1,0x01, 0x00,0x02,0x00,0x0A, 0x00,0x0,0x0,0x03]; # MAIN Test Run Starts Here... #------------------------------------------------- def main( ): testUtil.runCycles( 10000000 ) testUtil.writeUsFifo( TESTDATA ) testUtil.writeEot( ) testUtil.runCycles( 10000000 ) testUtil.readDsFifo( EXPDATA ) testUtil.readEot( ) #------------------------------------------------- # Calling all test code #------------------------------------------------- main() if err: print ("\nTest Suite completed with error(s)") #sys.exit(1) else: print ("\nTest Suite completed with no errors") #sys.exit(0);
27.883333
69
0.641363
import sys sys.path.append("targets/p9_nimbus/sbeTest" ) import testUtil err = False TESTDATA = [0,0,0,3, 0,0,0xA1,0x01, 0,0x02,0x00,0x1] EXPDATA = [0xc0,0xde,0xa1,0x01, 0x00,0x02,0x00,0x0A, 0x00,0x0,0x0,0x03]; def main( ): testUtil.runCycles( 10000000 ) testUtil.writeUsFifo( TESTDATA ) testUtil.writeEot( ) testUtil.runCycles( 10000000 ) testUtil.readDsFifo( EXPDATA ) testUtil.readEot( ) main() if err: print ("\nTest Suite completed with error(s)") else: print ("\nTest Suite completed with no errors")
true
true
f735ebe8c181c4ca65d623419c429c65ce0e1e7a
1,160
py
Python
users/tests/test_forms.py
EaguaireSama/CodePanda
ebc7ca9246df6463430f04d4b08124ef2ba2c3f6
[ "MIT" ]
1
2021-04-17T18:32:51.000Z
2021-04-17T18:32:51.000Z
users/tests/test_forms.py
EaguaireSama/CodePanda
ebc7ca9246df6463430f04d4b08124ef2ba2c3f6
[ "MIT" ]
null
null
null
users/tests/test_forms.py
EaguaireSama/CodePanda
ebc7ca9246df6463430f04d4b08124ef2ba2c3f6
[ "MIT" ]
3
2021-04-10T15:20:46.000Z
2021-04-11T12:04:57.000Z
from django.test import TestCase from django.contrib.auth.models import User from users.forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm class TestForms(TestCase): def test_user_register_form_valid(self): form = UserRegisterForm( data = { 'username' :"user2", 'email' : "user2@email.com", 'password1' : "user2password", 'password2' : "user2password" } ) self.assertTrue(form.is_valid()) def test_user_register_form_invalid(self): form = UserRegisterForm( data = { 'username' :"user2", 'email' : "", 'password1' : "user1password", 'password2' : "user2password" } ) self.assertFalse(form.is_valid()) def test_user_update_form_valid(self): form = UserUpdateForm( data = { 'username' :"user2", 'email' : "user2@email.com" } ) self.assertTrue(form.is_valid()) def test_user_update_form_invalid(self): form = UserUpdateForm( data = { 'username' :"user2", 'email' : "" } ) self.assertFalse(form.is_valid()) def test_user_profile_update_form_invalid(self): form = UserUpdateForm( data = { 'image' :"" } ) self.assertFalse(form.is_valid())
21.481481
76
0.672414
from django.test import TestCase from django.contrib.auth.models import User from users.forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm class TestForms(TestCase): def test_user_register_form_valid(self): form = UserRegisterForm( data = { 'username' :"user2", 'email' : "user2@email.com", 'password1' : "user2password", 'password2' : "user2password" } ) self.assertTrue(form.is_valid()) def test_user_register_form_invalid(self): form = UserRegisterForm( data = { 'username' :"user2", 'email' : "", 'password1' : "user1password", 'password2' : "user2password" } ) self.assertFalse(form.is_valid()) def test_user_update_form_valid(self): form = UserUpdateForm( data = { 'username' :"user2", 'email' : "user2@email.com" } ) self.assertTrue(form.is_valid()) def test_user_update_form_invalid(self): form = UserUpdateForm( data = { 'username' :"user2", 'email' : "" } ) self.assertFalse(form.is_valid()) def test_user_profile_update_form_invalid(self): form = UserUpdateForm( data = { 'image' :"" } ) self.assertFalse(form.is_valid())
true
true
f735ec17ddf645bf613f2789c946c6c81183fceb
1,696
py
Python
payment/views.py
caioaraujo/bakery_payments_api_v2
ade365bd2aa9561182be982286caa72923f36e13
[ "MIT" ]
4
2019-06-01T23:51:20.000Z
2021-02-24T11:23:31.000Z
payment/views.py
caioaraujo/bakery_payments_api_v2
ade365bd2aa9561182be982286caa72923f36e13
[ "MIT" ]
8
2020-06-13T23:10:46.000Z
2022-02-28T13:58:02.000Z
payment/views.py
caioaraujo/bakery_payments_api_v2
ade365bd2aa9561182be982286caa72923f36e13
[ "MIT" ]
1
2022-03-22T04:54:35.000Z
2022-03-22T04:54:35.000Z
from django.utils.translation import ugettext as _ from rest_framework.generics import GenericAPIView from rest_framework.response import Response from .serializers import PaymentInputSerializer, PaymentPatchSerializer, PaymentResponseSerializer from .services import PaymentService class PaymentView(GenericAPIView): serializer_class = PaymentInputSerializer def __init__(self, **kwargs): super().__init__(**kwargs) self.service = PaymentService() def post(self, request): """ Record a new payment. """ params = request.data.copy() data = self.service.insert(params) serializer = PaymentResponseSerializer(data) result = {'detail': _('Payment recorded successfully!'), 'data': serializer.data} return Response(result) class PaymentViewId(GenericAPIView): serializer_class = PaymentPatchSerializer def __init__(self, **kwargs): super().__init__(**kwargs) self.service = PaymentService() def patch(self, request, payment_id): """ Update payment value. If payment value reach zero, the flag is_paid will be set to true. It will raise an error if: - Payment is already paid; - Expiration date has already passed; - Value is higher than amount available for payment; - Branch has no balance. """ params = dict( value=request.data.get('value'), id=payment_id ) data = self.service.pay(params) serializer = PaymentResponseSerializer(data) result = {'detail': _('Payment changed successfully!'), 'data': serializer.data} return Response(result)
30.836364
98
0.668632
from django.utils.translation import ugettext as _ from rest_framework.generics import GenericAPIView from rest_framework.response import Response from .serializers import PaymentInputSerializer, PaymentPatchSerializer, PaymentResponseSerializer from .services import PaymentService class PaymentView(GenericAPIView): serializer_class = PaymentInputSerializer def __init__(self, **kwargs): super().__init__(**kwargs) self.service = PaymentService() def post(self, request): params = request.data.copy() data = self.service.insert(params) serializer = PaymentResponseSerializer(data) result = {'detail': _('Payment recorded successfully!'), 'data': serializer.data} return Response(result) class PaymentViewId(GenericAPIView): serializer_class = PaymentPatchSerializer def __init__(self, **kwargs): super().__init__(**kwargs) self.service = PaymentService() def patch(self, request, payment_id): params = dict( value=request.data.get('value'), id=payment_id ) data = self.service.pay(params) serializer = PaymentResponseSerializer(data) result = {'detail': _('Payment changed successfully!'), 'data': serializer.data} return Response(result)
true
true
f735ec7fb88fb24ceaca3d1817d3585bcfaba514
10,306
py
Python
CBGM/mpisupport.py
catsmith/CBGM
4fb85c6a0c67b6d790c94aa8d17284b66fc6206a
[ "MIT" ]
8
2019-11-12T14:06:18.000Z
2021-10-31T03:10:36.000Z
CBGM/mpisupport.py
catsmith/CBGM
4fb85c6a0c67b6d790c94aa8d17284b66fc6206a
[ "MIT" ]
1
2018-11-27T18:04:27.000Z
2018-11-27T18:08:27.000Z
CBGM/mpisupport.py
catsmith/CBGM
4fb85c6a0c67b6d790c94aa8d17284b66fc6206a
[ "MIT" ]
2
2020-01-06T12:04:27.000Z
2021-07-14T17:03:13.000Z
""" OpenMPI support wrapper """ import threading import queue import logging import time import resource logger = logging.getLogger() try: from mpi4py import MPI except ImportError: logger.warning("MPI support unavailable") def is_parent(): return MPI.COMM_WORLD.Get_rank() == 0 CHILD_RETRY_HELLO = 60 class MpiParent(object): mpicomm = None mpi_queue = queue.Queue() mpi_child_threads = [] mpi_child_status = {} mpi_child_meminfo = {} mpi_child_timeout = 3600 mpi_child_ready_timeout = 30 mpi_parent_status = "" # WARNING - this operates as a singleton class - always using the # latest instance created. latest_instance = None def __init__(self): logger.debug("Initialising MpiParent") self.__class__.latest_instance = self self.mpi_run() @classmethod def mpi_wait(cls, *, stop=True): """ Wait for all work to be done, then tell things to stop. Make sure you've put things in the queue before calling this... or it will all just exit and move on. """ if cls.mpicomm is None: # We haven't launched any MPI workers - we need to launch the local # management threads, so that the remote MPI processes will quit. cls._mpi_init() # When the queue is done, we can continue. cls.update_parent_stats("Waiting for work to finish") # This waits for an empty queue AND task_done to have been called # for each item. cls.mpi_queue.join() if not stop: # Nothing more to do for now return cls.update_parent_stats("Telling children to exit") for _ in cls.mpi_child_threads: cls.mpi_queue.put(None) # Clean up the threads, in case we run out cls.update_parent_stats("Waiting for threads to exit") running_threads = [t for t in cls.mpi_child_threads] while running_threads: t = running_threads.pop(0) t.join(0.1) if t.is_alive(): running_threads.append(t) else: cls.update_parent_stats("Thread {} joined - waiting for {} more" .format(t, len(running_threads))) # Set the list as empty, so it'll be re-made if more work is required. cls.mpi_child_threads = [] cls.update_parent_stats("Work done") # We need to let threads, remote MPI processes etc. all clean up # properly - and a second seems to be ample time for this. time.sleep(1) @classmethod def show_stats(cls): child_stats = '\n\t'.join(['{} ({}): {}'.format(k, cls.mpi_child_meminfo.get(k, "-"), cls.mpi_child_status[k]) for k in sorted(cls.mpi_child_status.keys())]) logger.info("Status:\n\tParent: %s\n\tQueue: %s\n\t%s", cls.mpi_parent_status, cls.mpi_queue.qsize(), child_stats) @classmethod def update_parent_stats(cls, msg): logger.debug(msg) cls.mpi_parent_status = msg @classmethod def mpi_manage_child(cls, child): """ Manage communications with the specified MPI child """ logger.info("Child manager {} starting".format(child)) def stat(child, status, meminfo=None): cls.mpi_child_status[child] = "[{}]: {}".format(time.ctime(), status) if meminfo: cls.mpi_child_meminfo[child] = meminfo logger.debug("Child {}: {}".format(child, status)) waiting_for_results = False while True: # Wait for the child to be ready start = time.time() abort = False while not cls.mpicomm.Iprobe(source=child): time.sleep(0.1) if time.time() - start > cls.mpi_child_ready_timeout: logger.error("Child {} took too long to be ready. Aborting.".format(child)) stat(child, "child not ready") abort = True break if not abort: ready = cls.mpicomm.recv(source=child) if ready is not True: stat(child, "unexpected response ({}...)".format(str(ready[:30]))) abort = True if abort: time.sleep(5) continue # wait for something to do stat(child, "waiting for queue") args = cls.mpi_queue.get() # send it to the remote child stat(child, "sending data to child") cls.mpicomm.send(args, dest=child) if args is None: # That's the call to quit stat(child, "quitting") return stat(child, "waiting for results ({})".format(args)) # get the results back start = time.time() while True: while not cls.mpicomm.Iprobe(source=child): time.sleep(1) if time.time() - start > cls.mpi_child_timeout: logger.error("Child {} took too long to return. Aborting.".format(child)) stat(child, "timeout - task returned to the queue") # Put it back on the queue for someone else to do cls.mpi_queue.put(args) cls.mpi_queue.task_done() time.sleep(5) return data = cls.mpicomm.recv(source=child) if data is True: # This is just a "hello" stat(child, "recv hello ({})".format(time.ctime())) continue # This must be real data back... break ret, meminfo = data stat(child, "sent results back", meminfo) # process the result by handing it to the latest_instance's # mpi_handle_result method. cls.latest_instance.mpi_handle_result(args, ret) cls.mpi_queue.task_done() stat(child, "task done") def mpi_handle_result(self, args, ret): """ Handle an MPI result @param args: original args sent to the child @param ret: response from the child """ raise NotImplemented @classmethod def mpi_run(cls): """ Top-level MPI parent method. """ return cls._mpi_init() @classmethod def _mpi_init(cls): """ Start up the MPI management threads etc. """ cls.mpicomm = MPI.COMM_WORLD rank = cls.mpicomm.Get_rank() assert rank == 0 # parent if cls.mpi_child_threads: logger.debug("We've already got child processes - so just using them") return logger.info("MPI-enabled version with {} processors available" .format(cls.mpicomm.size)) assert cls.mpicomm.size > 1, "Please run this under MPI with more than one processor" for child in range(1, cls.mpicomm.size): t = threading.Thread(target=cls.mpi_manage_child, args=(child,), daemon=True) t.start() cls.mpi_child_threads.append(t) t = threading.Thread(target=cls.stats_thread, daemon=True) t.start() @classmethod def stats_thread(cls): while True: cls.show_stats() time.sleep(60) def mpi_child(fn): """ An MPI child wrapper that will call the supplied function in a child context - reading its arguments from mpicomm.recv(source=0). """ rank = MPI.COMM_WORLD.Get_rank() logger.debug("Child {} (remote) starting".format(rank)) while True: # A little sleep to let everything start... time.sleep(3) # Send ready logger.debug("Child {} (remote) sending hello".format(rank)) try: MPI.COMM_WORLD.send(True, dest=0) except Exception: # Sometimes we see messages like this: # [bb2a3c26][[4455,1],95][btl_tcp_endpoint.c:818:mca_btl_tcp_endpoint_complete_connect] connect() to 169.254.95.120 failed: Connection refused (111) # That seems to kill the process... and we're lost. logger.warning("Error saying hello", exc_info=True) time.sleep(5) continue else: logger.debug("Child {} (remote) sent hello".format(rank)) start = time.time() retry = False # child - wait to be given a data structure while not MPI.COMM_WORLD.Iprobe(source=0): if time.time() - start > CHILD_RETRY_HELLO: retry = True break time.sleep(1) if retry: logger.debug("Child {} (remote) heard nothing from parent - will send another hello".format(rank)) continue try: args = MPI.COMM_WORLD.recv(source=0) except EOFError: logger.exception("Child {} error receiving instructions - carrying on".format(rank)) continue if args is None: logger.info("Child {} (remote) exiting - no args received".format(rank)) break logger.debug("Child {} (remote) received data".format(rank)) ret = fn(*args) mem_raw = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss mem_size = resource.getpagesize() mem_bytes = mem_raw * mem_size meminfo = "{:.2f} MB".format(mem_bytes / 1024 ** 2) if ret is None: # Nothing was generated MPI.COMM_WORLD.send((None, meminfo), dest=0) logger.info("Child {} (remote) aborted job".format(rank)) else: logger.debug("Child {} (remote) sending results back".format(rank)) MPI.COMM_WORLD.send((ret, meminfo), dest=0) logger.debug("Child {} (remote) completed job".format(rank)) # Show leaking objects... uncomment this to track them... # tracker.print_diff()
33.570033
160
0.555016
import threading import queue import logging import time import resource logger = logging.getLogger() try: from mpi4py import MPI except ImportError: logger.warning("MPI support unavailable") def is_parent(): return MPI.COMM_WORLD.Get_rank() == 0 CHILD_RETRY_HELLO = 60 class MpiParent(object): mpicomm = None mpi_queue = queue.Queue() mpi_child_threads = [] mpi_child_status = {} mpi_child_meminfo = {} mpi_child_timeout = 3600 mpi_child_ready_timeout = 30 mpi_parent_status = "" latest_instance = None def __init__(self): logger.debug("Initialising MpiParent") self.__class__.latest_instance = self self.mpi_run() @classmethod def mpi_wait(cls, *, stop=True): if cls.mpicomm is None: # management threads, so that the remote MPI processes will quit. cls._mpi_init() # When the queue is done, we can continue. cls.update_parent_stats("Waiting for work to finish") # This waits for an empty queue AND task_done to have been called # for each item. cls.mpi_queue.join() if not stop: # Nothing more to do for now return cls.update_parent_stats("Telling children to exit") for _ in cls.mpi_child_threads: cls.mpi_queue.put(None) # Clean up the threads, in case we run out cls.update_parent_stats("Waiting for threads to exit") running_threads = [t for t in cls.mpi_child_threads] while running_threads: t = running_threads.pop(0) t.join(0.1) if t.is_alive(): running_threads.append(t) else: cls.update_parent_stats("Thread {} joined - waiting for {} more" .format(t, len(running_threads))) # Set the list as empty, so it'll be re-made if more work is required. cls.mpi_child_threads = [] cls.update_parent_stats("Work done") time.sleep(1) @classmethod def show_stats(cls): child_stats = '\n\t'.join(['{} ({}): {}'.format(k, cls.mpi_child_meminfo.get(k, "-"), cls.mpi_child_status[k]) for k in sorted(cls.mpi_child_status.keys())]) logger.info("Status:\n\tParent: %s\n\tQueue: %s\n\t%s", cls.mpi_parent_status, cls.mpi_queue.qsize(), child_stats) @classmethod def update_parent_stats(cls, msg): logger.debug(msg) cls.mpi_parent_status = msg @classmethod def mpi_manage_child(cls, child): logger.info("Child manager {} starting".format(child)) def stat(child, status, meminfo=None): cls.mpi_child_status[child] = "[{}]: {}".format(time.ctime(), status) if meminfo: cls.mpi_child_meminfo[child] = meminfo logger.debug("Child {}: {}".format(child, status)) waiting_for_results = False while True: start = time.time() abort = False while not cls.mpicomm.Iprobe(source=child): time.sleep(0.1) if time.time() - start > cls.mpi_child_ready_timeout: logger.error("Child {} took too long to be ready. Aborting.".format(child)) stat(child, "child not ready") abort = True break if not abort: ready = cls.mpicomm.recv(source=child) if ready is not True: stat(child, "unexpected response ({}...)".format(str(ready[:30]))) abort = True if abort: time.sleep(5) continue stat(child, "waiting for queue") args = cls.mpi_queue.get() stat(child, "sending data to child") cls.mpicomm.send(args, dest=child) if args is None: stat(child, "quitting") return stat(child, "waiting for results ({})".format(args)) # get the results back start = time.time() while True: while not cls.mpicomm.Iprobe(source=child): time.sleep(1) if time.time() - start > cls.mpi_child_timeout: logger.error("Child {} took too long to return. Aborting.".format(child)) stat(child, "timeout - task returned to the queue") # Put it back on the queue for someone else to do cls.mpi_queue.put(args) cls.mpi_queue.task_done() time.sleep(5) return data = cls.mpicomm.recv(source=child) if data is True: # This is just a "hello" stat(child, "recv hello ({})".format(time.ctime())) continue # This must be real data back... break ret, meminfo = data stat(child, "sent results back", meminfo) # process the result by handing it to the latest_instance's cls.latest_instance.mpi_handle_result(args, ret) cls.mpi_queue.task_done() stat(child, "task done") def mpi_handle_result(self, args, ret): raise NotImplemented @classmethod def mpi_run(cls): return cls._mpi_init() @classmethod def _mpi_init(cls): cls.mpicomm = MPI.COMM_WORLD rank = cls.mpicomm.Get_rank() assert rank == 0 if cls.mpi_child_threads: logger.debug("We've already got child processes - so just using them") return logger.info("MPI-enabled version with {} processors available" .format(cls.mpicomm.size)) assert cls.mpicomm.size > 1, "Please run this under MPI with more than one processor" for child in range(1, cls.mpicomm.size): t = threading.Thread(target=cls.mpi_manage_child, args=(child,), daemon=True) t.start() cls.mpi_child_threads.append(t) t = threading.Thread(target=cls.stats_thread, daemon=True) t.start() @classmethod def stats_thread(cls): while True: cls.show_stats() time.sleep(60) def mpi_child(fn): rank = MPI.COMM_WORLD.Get_rank() logger.debug("Child {} (remote) starting".format(rank)) while True: # A little sleep to let everything start... time.sleep(3) # Send ready logger.debug("Child {} (remote) sending hello".format(rank)) try: MPI.COMM_WORLD.send(True, dest=0) except Exception: # Sometimes we see messages like this: # [bb2a3c26][[4455,1],95][btl_tcp_endpoint.c:818:mca_btl_tcp_endpoint_complete_connect] connect() to 169.254.95.120 failed: Connection refused (111) # That seems to kill the process... and we're lost. logger.warning("Error saying hello", exc_info=True) time.sleep(5) continue else: logger.debug("Child {} (remote) sent hello".format(rank)) start = time.time() retry = False while not MPI.COMM_WORLD.Iprobe(source=0): if time.time() - start > CHILD_RETRY_HELLO: retry = True break time.sleep(1) if retry: logger.debug("Child {} (remote) heard nothing from parent - will send another hello".format(rank)) continue try: args = MPI.COMM_WORLD.recv(source=0) except EOFError: logger.exception("Child {} error receiving instructions - carrying on".format(rank)) continue if args is None: logger.info("Child {} (remote) exiting - no args received".format(rank)) break logger.debug("Child {} (remote) received data".format(rank)) ret = fn(*args) mem_raw = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss mem_size = resource.getpagesize() mem_bytes = mem_raw * mem_size meminfo = "{:.2f} MB".format(mem_bytes / 1024 ** 2) if ret is None: MPI.COMM_WORLD.send((None, meminfo), dest=0) logger.info("Child {} (remote) aborted job".format(rank)) else: logger.debug("Child {} (remote) sending results back".format(rank)) MPI.COMM_WORLD.send((ret, meminfo), dest=0) logger.debug("Child {} (remote) completed job".format(rank))
true
true
f735ecc745344aa1dc9776c189e320d619c7fee5
8,205
py
Python
sphinx/source/conf.py
menefotto/Kats
3fc8a3f819502d45736734eabb3601f42a6b7759
[ "MIT" ]
1
2021-06-22T03:40:33.000Z
2021-06-22T03:40:33.000Z
sphinx/source/conf.py
menefotto/Kats
3fc8a3f819502d45736734eabb3601f42a6b7759
[ "MIT" ]
null
null
null
sphinx/source/conf.py
menefotto/Kats
3fc8a3f819502d45736734eabb3601f42a6b7759
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # fmt: off # # Kats documentation build configuration file. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # 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. sys.path.insert(0, os.path.abspath("..")) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # 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.napoleon", "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.coverage", "sphinx.ext.viewcode", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = u"Kats" copyright = u"2021, Facebook Inc." author = u"Facebook Inc." # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "0.0.1" # The full version, including alpha/beta/rc tags. release = "0.0.1" # 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 = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- 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 = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # 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 = [] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyright = False # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "Katsdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, "Kats.tex", u"Kats Documentation", u"Facebook Inc.", "manual") ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, "kats", u"Kats Documentation", [author], 1)] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "Kats", u"Kats Documentation", author, "Kats", "Toolkit to analyze time series data.", "Miscellaneous", ) ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {"https://docs.python.org/": None} # -- Autodocs Configuration ------------------------------------------- # Turns on conditional imports via TYPE_CHECKING flag; # Used for sphinx_autodoc_typehints set_type_checking_flag = True # Mock SQLAlchemy base; otherwise have issues with trying to register same # class (with same table) multiple times through autodocs # Also mock Pandas to avoid circular imports due to TYPE_CHECKING = True autodoc_mock_imports = [ "__test_modules__", ]
32.30315
79
0.709324
import os import sys sys.path.insert(0, os.path.abspath("..")) extensions = [ "sphinx.ext.napoleon", "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.coverage", "sphinx.ext.viewcode", ] templates_path = ["_templates"] source_suffix = ".rst" master_doc = "index" project = u"Kats" copyright = u"2021, Facebook Inc." author = u"Facebook Inc." # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "0.0.1" # The full version, including alpha/beta/rc tags. release = "0.0.1" # 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 = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- 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 = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # 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 = [] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyright = False # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "Katsdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, "Kats.tex", u"Kats Documentation", u"Facebook Inc.", "manual") ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, "kats", u"Kats Documentation", [author], 1)] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "Kats", u"Kats Documentation", author, "Kats", "Toolkit to analyze time series data.", "Miscellaneous", ) ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {"https://docs.python.org/": None} # -- Autodocs Configuration ------------------------------------------- # Turns on conditional imports via TYPE_CHECKING flag; # Used for sphinx_autodoc_typehints set_type_checking_flag = True # Mock SQLAlchemy base; otherwise have issues with trying to register same # class (with same table) multiple times through autodocs # Also mock Pandas to avoid circular imports due to TYPE_CHECKING = True autodoc_mock_imports = [ "__test_modules__", ]
true
true
f735eda6a7910c11a095f6cddcd4998435bc09a3
5,473
py
Python
docs/conf.py
webbhuset/pipeline
5e838c9a1b25f4dd72060202b7730ae3c71ea024
[ "MIT" ]
null
null
null
docs/conf.py
webbhuset/pipeline
5e838c9a1b25f4dd72060202b7730ae3c71ea024
[ "MIT" ]
null
null
null
docs/conf.py
webbhuset/pipeline
5e838c9a1b25f4dd72060202b7730ae3c71ea024
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- 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('.')) #from recommonmark.parser import CommonMarkParser from sphinx.highlighting import lexers from pygments.lexers.web import PhpLexer # -- Project information ----------------------------------------------------- project = u'Pipeline' copyright = u'2018, Webbhuset AB' author = u'Webbhuset AB' # The short X.Y version version = u'' # The full version, including alpha/beta/rc tags release = u'' # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst'] #source_parsers = { # '.md': CommonMarkParser #} # The master toctree document. master_doc = 'index' # 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 = None # 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 = [u'_build', 'Thumbs.db', '.DS_Store', 'README.rst'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None # -- 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 = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = { 'collapse_navigation': False } # 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'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'Pipelinedoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'Pipeline.tex', u'Pipeline Documentation', u'Webbhuset AB', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'whaskell', u'Pipeline Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'Pipeline', u'Pipeline Documentation', author, 'Pipeline', 'One line description of project.', 'Miscellaneous'), ] # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] lexers["php"] = PhpLexer(startinline=True, linenos=1) lexers["php-annotations"] = PhpLexer(startinline=True, linenos=1)
29.583784
79
0.661612
from sphinx.highlighting import lexers from pygments.lexers.web import PhpLexer project = u'Pipeline' copyright = u'2018, Webbhuset AB' author = u'Webbhuset AB' version = u'' release = u'' extensions = [ ] templates_path = ['_templates'] source_suffix = ['.rst'] master_doc = 'index' language = None exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store', 'README.rst'] pygments_style = None html_theme = 'sphinx_rtd_theme' html_theme_options = { 'collapse_navigation': False } html_static_path = ['_static'] # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'Pipelinedoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'Pipeline.tex', u'Pipeline Documentation', u'Webbhuset AB', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'whaskell', u'Pipeline Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'Pipeline', u'Pipeline Documentation', author, 'Pipeline', 'One line description of project.', 'Miscellaneous'), ] # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] lexers["php"] = PhpLexer(startinline=True, linenos=1) lexers["php-annotations"] = PhpLexer(startinline=True, linenos=1)
true
true
f735ee0c9e1e28a8ec6d114097af7d6120e0d6fe
1,839
py
Python
game_data.py
EthanRiley/Arkon
fe1dff2bdc8e783aae6d6b9ed975f792ab8f926a
[ "MIT" ]
3
2016-03-11T19:17:17.000Z
2016-03-12T13:49:01.000Z
game_data.py
EthanRiley/Arkon
fe1dff2bdc8e783aae6d6b9ed975f792ab8f926a
[ "MIT" ]
null
null
null
game_data.py
EthanRiley/Arkon
fe1dff2bdc8e783aae6d6b9ed975f792ab8f926a
[ "MIT" ]
null
null
null
import pygame, os, re, pygame.freetype from pygame.locals import * pygame.init() class resource_handler(object): def get_data_from_folder(self, data_dir, extension, iterfunc): data = [] for file in os.listdir(data_dir): if extension in file: data.append({ 'name': file, 'data': iterfunc(os.path.join(data_dir, file))}) return data def __init__(self, data_dir, extension, iterfunc): self.__data = self.get_data_from_folder(data_dir, extension, iterfunc); def get_data(self, name): for data in self.__data: if re.match(name, data['name']): return data['data'] raise KeyError def get_data_dict(self, names): data = {} for name in names: data[name] = self.get_data(name) return data def get_data_array(self, name): out = [] for data in self.__data: if re.match(name, data['name']): out.append(data['data']) return out def get_name(self, data): for data in self.__data: if data['data'] == data: return data['name'] def get_image(file): image = pygame.image.load(file) image.convert() return image def image_data(data_dir): return resource_handler(data_dir, '.png', get_image) def sound_data(data_dir): return resource_handler(data_dir, '.ogg', pygame.mixer.Sound) def font_data(data_dir): return resource_handler(data_dir,'.ttf', pygame.freetype.Font) class game_data(object): def __init__(self, data_dir): self.sprites = image_data(os.path.join(data_dir, "sprites")) self.backgrounds = image_data(os.path.join(data_dir, "backgrounds")) #self.sounds = sound_data(os.path.join(data_dir, "sounds"))
27.863636
79
0.612289
import pygame, os, re, pygame.freetype from pygame.locals import * pygame.init() class resource_handler(object): def get_data_from_folder(self, data_dir, extension, iterfunc): data = [] for file in os.listdir(data_dir): if extension in file: data.append({ 'name': file, 'data': iterfunc(os.path.join(data_dir, file))}) return data def __init__(self, data_dir, extension, iterfunc): self.__data = self.get_data_from_folder(data_dir, extension, iterfunc); def get_data(self, name): for data in self.__data: if re.match(name, data['name']): return data['data'] raise KeyError def get_data_dict(self, names): data = {} for name in names: data[name] = self.get_data(name) return data def get_data_array(self, name): out = [] for data in self.__data: if re.match(name, data['name']): out.append(data['data']) return out def get_name(self, data): for data in self.__data: if data['data'] == data: return data['name'] def get_image(file): image = pygame.image.load(file) image.convert() return image def image_data(data_dir): return resource_handler(data_dir, '.png', get_image) def sound_data(data_dir): return resource_handler(data_dir, '.ogg', pygame.mixer.Sound) def font_data(data_dir): return resource_handler(data_dir,'.ttf', pygame.freetype.Font) class game_data(object): def __init__(self, data_dir): self.sprites = image_data(os.path.join(data_dir, "sprites")) self.backgrounds = image_data(os.path.join(data_dir, "backgrounds"))
true
true
f735eecbca65eada9d6d39cba7d9783bdfd16701
2,886
py
Python
plugins/modules/memsource_project.py
rooftopcellist/ansible-collection-memsource
e9b506e0da091461baac531e0921815369dfca29
[ "Apache-2.0" ]
null
null
null
plugins/modules/memsource_project.py
rooftopcellist/ansible-collection-memsource
e9b506e0da091461baac531e0921815369dfca29
[ "Apache-2.0" ]
null
null
null
plugins/modules/memsource_project.py
rooftopcellist/ansible-collection-memsource
e9b506e0da091461baac531e0921815369dfca29
[ "Apache-2.0" ]
1
2021-10-05T23:27:10.000Z
2021-10-05T23:27:10.000Z
#!/usr/bin/env python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = """ module: memsource_project short_description: Manage a Memsource project version_added: 0.0.1 description: - Manage a Memsource project author: 'Yanis Guenane (@Spredzy)' options: uid: description: - UID of the project type: str name: description: - A dict of filters to apply required: false default: {} type: dict template_id: description: - A dict of filters to apply required: false default: {} type: dict purge_on_delete: description: - Whether to purge the content of the project on delete type: bool extends_documentation_fragment: - community.memsource.memsource requirements: [memsource] """ EXAMPLES = """ - name: Create project from template id community.memsource.memsource_project: name: My Project template_id: 12345 - name: Retrieve project information community.memsource.memsource_project: uid: uid - name: Delete project community.memsource.memsource_project: uid: uid state: absent """ RETURN = """ project: returned: on success description: > Project's up to date information type: dict """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.memsource.plugins.module_utils.memsource import ( get_action, get_default_argspec, get_memsource_client, ) def main(): argument_spec = get_default_argspec() argument_spec.update( dict( uid=dict(type="str"), name=dict(type="str"), template_id=dict(type="int"), purge_on_delete=dict(type="bool"), state=dict(type="str", default="present", choices=["absent", "present"]), ), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) _memsource = get_memsource_client(module.params) _action = get_action(module.params) _result = {} project = {} if _action == "create": if module.params.get("template_id"): project = _memsource.create_project_from_template( module.params.get("name"), module.params.get("template_id") ) else: pass _result.update({"changed": True}) elif _action == "read": project = _memsource.get_project_by_id(module.params["uid"]) elif _action == "update": pass else: res = _memsource.delete_project( module.params["uid"], purge=module.params.get("purge_on_delete", False), do_not_fail_on_404=True, ) if res.status_code == 204: _result.update({"changed": True}) _result.update({"project": project}) module.exit_json(**_result) if __name__ == "__main__": main()
23.655738
85
0.651421
from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = """ module: memsource_project short_description: Manage a Memsource project version_added: 0.0.1 description: - Manage a Memsource project author: 'Yanis Guenane (@Spredzy)' options: uid: description: - UID of the project type: str name: description: - A dict of filters to apply required: false default: {} type: dict template_id: description: - A dict of filters to apply required: false default: {} type: dict purge_on_delete: description: - Whether to purge the content of the project on delete type: bool extends_documentation_fragment: - community.memsource.memsource requirements: [memsource] """ EXAMPLES = """ - name: Create project from template id community.memsource.memsource_project: name: My Project template_id: 12345 - name: Retrieve project information community.memsource.memsource_project: uid: uid - name: Delete project community.memsource.memsource_project: uid: uid state: absent """ RETURN = """ project: returned: on success description: > Project's up to date information type: dict """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.memsource.plugins.module_utils.memsource import ( get_action, get_default_argspec, get_memsource_client, ) def main(): argument_spec = get_default_argspec() argument_spec.update( dict( uid=dict(type="str"), name=dict(type="str"), template_id=dict(type="int"), purge_on_delete=dict(type="bool"), state=dict(type="str", default="present", choices=["absent", "present"]), ), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) _memsource = get_memsource_client(module.params) _action = get_action(module.params) _result = {} project = {} if _action == "create": if module.params.get("template_id"): project = _memsource.create_project_from_template( module.params.get("name"), module.params.get("template_id") ) else: pass _result.update({"changed": True}) elif _action == "read": project = _memsource.get_project_by_id(module.params["uid"]) elif _action == "update": pass else: res = _memsource.delete_project( module.params["uid"], purge=module.params.get("purge_on_delete", False), do_not_fail_on_404=True, ) if res.status_code == 204: _result.update({"changed": True}) _result.update({"project": project}) module.exit_json(**_result) if __name__ == "__main__": main()
true
true
f735ef00c592ff18ce03fb7b24d9baccd2ae3d16
389
py
Python
bardo2/wsgi.py
Manzanero/bardo2-web
cfacb9ec321030ce0cafb62a1a7bcdb28726a99c
[ "MIT" ]
null
null
null
bardo2/wsgi.py
Manzanero/bardo2-web
cfacb9ec321030ce0cafb62a1a7bcdb28726a99c
[ "MIT" ]
null
null
null
bardo2/wsgi.py
Manzanero/bardo2-web
cfacb9ec321030ce0cafb62a1a7bcdb28726a99c
[ "MIT" ]
null
null
null
""" WSGI config for bardo2 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/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bardo2.settings') application = get_wsgi_application()
22.882353
78
0.784062
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bardo2.settings') application = get_wsgi_application()
true
true
f735ef49a6a7ff21aed43a74d854d9b11e62da8b
2,537
py
Python
treat.py
TwinIsland/img2java
6b6788daa0a97acb1e455ead9d7bd09d7d881ab2
[ "MIT" ]
null
null
null
treat.py
TwinIsland/img2java
6b6788daa0a97acb1e455ead9d7bd09d7d881ab2
[ "MIT" ]
null
null
null
treat.py
TwinIsland/img2java
6b6788daa0a97acb1e455ead9d7bd09d7d881ab2
[ "MIT" ]
null
null
null
from matplotlib import pyplot as plt import numpy as np import cv2 from scipy import stats import translate from skimage import transform ##################################### imgData = cv2.imread('van.jpg',0) compressRate = 0.4 ##################################### imgData = np.array(imgData) shape = imgData.shape pas = p = 'unknown' def twoWayTreat(): global imgData imgData = stats.zscore(imgData) for raw in range(shape[0]): for col in range(shape[1]): if imgData[raw][col] < 0: imgData[raw][col] = 0 else: imgData[raw][col] = 255 def debugImg(): global imgData plt.imshow(imgData) plt.show() def getCode(): code = '' for this_line_index in range(len(imgData)-1): lineLib = [] this_line = imgData[this_line_index] newTurn = False for this_line_data_index in range(len(this_line)-1): if this_line[this_line_data_index] == 255: begin_draw = this_line_data_index newTurn = True if this_line[this_line_data_index] == 0 and newTurn: end_draw = this_line_data_index lineLib.append([begin_draw,end_draw]) newTurn = False for i in lineLib: code = code + translate.getCode([i[0],this_line_index,i[1],this_line_index]) + '\n' return code def compressImg(): global imgData,compressRate imgData = transform.rescale(imgData, [compressRate,compressRate]) def passivate(): count = 0 global imgData shape = imgData.shape lineLenght = shape[1] for lineIndex in range(shape[0]-1): for numberIndex in range(0,lineLenght-6): thisFive = list(imgData[lineIndex,numberIndex:numberIndex+5]) if thisFive == [0,255,255,255,255]: count += 1 thisFive[0] =255 imgData[lineIndex,numberIndex:numberIndex+5] = thisFive return 'passivate rate: ' + str(count/(shape[0]*shape[1])) + '%' twoWayTreat() compressImg() pas = passivate() debugImg() p = getCode() translate.setSize(imgData.shape) with open('draw.java','w') as f: f.write(translate.upper_code) f.write(p) f.write(translate.lower_code) try: print('==================') print('compressRate: ' + str(compressRate)) print('passivateRate: ' + str(pas)) print('size: ' + str(imgData.shape)) print('==================') except Exception: print('cannot print out the post-info!') f.close()
25.626263
95
0.589279
from matplotlib import pyplot as plt import numpy as np import cv2 from scipy import stats import translate from skimage import transform count = 0 global imgData shape = imgData.shape lineLenght = shape[1] for lineIndex in range(shape[0]-1): for numberIndex in range(0,lineLenght-6): thisFive = list(imgData[lineIndex,numberIndex:numberIndex+5]) if thisFive == [0,255,255,255,255]: count += 1 thisFive[0] =255 imgData[lineIndex,numberIndex:numberIndex+5] = thisFive return 'passivate rate: ' + str(count/(shape[0]*shape[1])) + '%' twoWayTreat() compressImg() pas = passivate() debugImg() p = getCode() translate.setSize(imgData.shape) with open('draw.java','w') as f: f.write(translate.upper_code) f.write(p) f.write(translate.lower_code) try: print('==================') print('compressRate: ' + str(compressRate)) print('passivateRate: ' + str(pas)) print('size: ' + str(imgData.shape)) print('==================') except Exception: print('cannot print out the post-info!') f.close()
true
true
f735ef8bb7eef76ac42f0236481b16ad8040fb74
1,811
py
Python
tests/test_locate_trace.py
hover2pi/hotsoss
82d8316d97096416d7f175516a80953e99fb6f44
[ "MIT" ]
2
2019-12-06T17:40:30.000Z
2020-06-25T09:04:04.000Z
tests/test_locate_trace.py
hover2pi/hotsoss
82d8316d97096416d7f175516a80953e99fb6f44
[ "MIT" ]
2
2021-11-15T17:49:23.000Z
2022-02-08T17:15:09.000Z
tests/test_locate_trace.py
hover2pi/hotsoss
82d8316d97096416d7f175516a80953e99fb6f44
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `locate_trace` module.""" import unittest import numpy as np from hotsoss import locate_trace as lt def test_simulate_frame(): """Test the simulate_frame function""" # CLEAR and plot test assert lt.simulate_frame(plot=True).shape == (256, 2048) # F277W test assert lt.simulate_frame(filt='F277W').shape == (256, 2048) def test_isolate_signal(): """Test isolate_signal function""" # Make frame for testing frame = lt.simulate_frame() # CLEAR and plot assert len(lt.isolate_signal(500, frame, plot=True)) == 2 # F277W and radius assert len(lt.isolate_signal(500, frame, filt='F277W', radius=20)) == 2 def test_order_masks(): """Test order_masks function""" # Make frame for testing frame = lt.simulate_frame() # Test plot and defaults assert len(lt.order_masks(frame, plot=True)) == 2 # Test save and subarray assert len(lt.order_masks(frame, subarray='SUBSTRIP96', save=True)) == 2 def test_trace_polynomial(): """Test trace_polynomial function""" # No order specified assert len(lt.trace_polynomial(order=None, evaluate=False)) == 2 # Single order assert len(lt.trace_polynomial(order=1, evaluate=False)) == 5 # Test evaluate assert len(lt.trace_polynomial(order=1, evaluate=True)) == 2048 def test_trace_wavelengths(): """Test trace_wavelengths function""" # No order specified assert len(lt.trace_wavelengths(order=None)) == 2 # Single order assert len(lt.trace_wavelengths(order=1)) == 2048 def test_wavelength_bins(): """Test wavelength_bins works""" # Default values for two orders assert len(lt.wavelength_bins()) == 2 # Generate assert len(lt.wavelength_bins(save=True)) == 2
24.472973
76
0.677526
import unittest import numpy as np from hotsoss import locate_trace as lt def test_simulate_frame(): assert lt.simulate_frame(plot=True).shape == (256, 2048) assert lt.simulate_frame(filt='F277W').shape == (256, 2048) def test_isolate_signal(): frame = lt.simulate_frame() assert len(lt.isolate_signal(500, frame, plot=True)) == 2 assert len(lt.isolate_signal(500, frame, filt='F277W', radius=20)) == 2 def test_order_masks(): frame = lt.simulate_frame() assert len(lt.order_masks(frame, plot=True)) == 2 assert len(lt.order_masks(frame, subarray='SUBSTRIP96', save=True)) == 2 def test_trace_polynomial(): assert len(lt.trace_polynomial(order=None, evaluate=False)) == 2 assert len(lt.trace_polynomial(order=1, evaluate=False)) == 5 assert len(lt.trace_polynomial(order=1, evaluate=True)) == 2048 def test_trace_wavelengths(): assert len(lt.trace_wavelengths(order=None)) == 2 assert len(lt.trace_wavelengths(order=1)) == 2048 def test_wavelength_bins(): assert len(lt.wavelength_bins()) == 2 assert len(lt.wavelength_bins(save=True)) == 2
true
true
f735efd81dd59271b71383463bdf088ddbe47517
1,656
py
Python
userbot/plugins/confuse.py
justteen/BUZZ-USERBOT
55651cce150e1d04d2c61efb2565ef9f46b42933
[ "BSL-1.0" ]
null
null
null
userbot/plugins/confuse.py
justteen/BUZZ-USERBOT
55651cce150e1d04d2c61efb2565ef9f46b42933
[ "BSL-1.0" ]
null
null
null
userbot/plugins/confuse.py
justteen/BUZZ-USERBOT
55651cce150e1d04d2c61efb2565ef9f46b42933
[ "BSL-1.0" ]
null
null
null
"""Emoji Available Commands: .adi""" import asyncio from telethon import events @borg.on(events.NewMessage(pattern=r"\.(.*)", outgoing=True)) async def _(event): if event.fwd_from: return animation_interval = 0.3 animation_ttl = range(0, 15) input_str = event.pattern_match.group(1) if input_str == "adi": await event.edit(input_str) animation_chars = [ "⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬛⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬛⬛⬛⬜⬜\n⬜⬜⬛⬜⬛⬜⬜\n⬜⬜⬛⬛⬛⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬛⬛⬛⬛⬛⬛⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬛⬛⬛⬛⬛⬛", "⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛", "⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬛⬛⬛⬛⬛⬛⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬛⬛⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬛⬛⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬛⬛⬛⬛⬛⬛", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬛⬛⬛⬛⬛⬛⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬛⬛⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬛⬛⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬛⬛⬛⬛⬛⬛", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬛⬛⬛⬛⬛\n⬛⬜⬜⬜⬛\n⬛⬜⬛⬜⬛\n⬛⬜⬜⬜⬛\n⬛⬛⬛⬛⬛", "⬜⬜⬜\n⬜⬛⬜\n⬜⬜⬜", "[👉🔴👈](https://t.me/black_lightning_channel)", ] for i in animation_ttl: await asyncio.sleep(animation_interval) await event.edit(animation_chars[i % 15])
33.12
93
0.278986
import asyncio from telethon import events @borg.on(events.NewMessage(pattern=r"\.(.*)", outgoing=True)) async def _(event): if event.fwd_from: return animation_interval = 0.3 animation_ttl = range(0, 15) input_str = event.pattern_match.group(1) if input_str == "adi": await event.edit(input_str) animation_chars = [ "⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬛⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬛⬛⬛⬜⬜\n⬜⬜⬛⬜⬛⬜⬜\n⬜⬜⬛⬛⬛⬜⬜\n⬜⬜⬜⬜⬜⬜⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬛⬛⬛⬛⬛⬛⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬛⬛⬛⬛⬛⬛", "⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛", "⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛⬜", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬛⬛⬛⬛⬛⬛⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬛⬛⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬛⬛⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬛⬛⬛⬛⬛⬛", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬛⬛⬛⬛⬛⬛⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬜⬛⬛⬛⬜⬛\n⬛⬜⬛⬜⬛⬜⬛\n⬛⬜⬛⬛⬛⬜⬛\n⬛⬜⬜⬜⬜⬜⬛\n⬛⬛⬛⬛⬛⬛⬛", "⬜⬜⬜⬜⬜⬜⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬜⬛⬜⬛⬜\n⬜⬛⬜⬜⬜⬛⬜\n⬜⬛⬛⬛⬛⬛⬜\n⬜⬜⬜⬜⬜⬜⬜", "⬛⬛⬛⬛⬛\n⬛⬜⬜⬜⬛\n⬛⬜⬛⬜⬛\n⬛⬜⬜⬜⬛\n⬛⬛⬛⬛⬛", "⬜⬜⬜\n⬜⬛⬜\n⬜⬜⬜", "[👉🔴👈](https://t.me/black_lightning_channel)", ] for i in animation_ttl: await asyncio.sleep(animation_interval) await event.edit(animation_chars[i % 15])
true
true
f735f1cc42cde14539830514433b678241a88a6b
1,357
py
Python
tests/cloudformation/checks/resource/aws/test_RDSMultiAZEnabled.py
pmalkki/checkov
b6cdf386dd976fe27c16fed6d550756a678a5d7b
[ "Apache-2.0" ]
4,013
2019-12-09T13:16:54.000Z
2022-03-31T14:31:01.000Z
tests/cloudformation/checks/resource/aws/test_RDSMultiAZEnabled.py
pmalkki/checkov
b6cdf386dd976fe27c16fed6d550756a678a5d7b
[ "Apache-2.0" ]
1,258
2019-12-17T09:55:51.000Z
2022-03-31T19:17:17.000Z
tests/cloudformation/checks/resource/aws/test_RDSMultiAZEnabled.py
pmalkki/checkov
b6cdf386dd976fe27c16fed6d550756a678a5d7b
[ "Apache-2.0" ]
638
2019-12-19T08:57:38.000Z
2022-03-30T21:38:37.000Z
import os import unittest from checkov.cloudformation.checks.resource.aws.RDSMultiAZEnabled import check from checkov.cloudformation.runner import Runner from checkov.runner_filter import RunnerFilter class TestRDSMultiAZEnabled(unittest.TestCase): def test_summary(self): runner = Runner() current_dir = os.path.dirname(os.path.realpath(__file__)) test_files_dir = current_dir + "/example_RDSMultiAZEnabled" report = runner.run(root_folder=test_files_dir, runner_filter=RunnerFilter(checks=[check.id])) summary = report.get_summary() passing_resources = { "AWS::RDS::DBInstance.MyDBEnabled", } failing_resources = { "AWS::RDS::DBInstance.MyDBDefault", "AWS::RDS::DBInstance.MyDBDisabled", } passed_check_resources = set([c.resource for c in report.passed_checks]) failed_check_resources = set([c.resource for c in report.failed_checks]) self.assertEqual(summary['passed'], 1) self.assertEqual(summary['failed'], 2) self.assertEqual(summary['skipped'], 0) self.assertEqual(summary['parsing_errors'], 0) self.assertEqual(passing_resources, passed_check_resources) self.assertEqual(failing_resources, failed_check_resources) if __name__ == '__main__': unittest.main()
33.097561
102
0.696389
import os import unittest from checkov.cloudformation.checks.resource.aws.RDSMultiAZEnabled import check from checkov.cloudformation.runner import Runner from checkov.runner_filter import RunnerFilter class TestRDSMultiAZEnabled(unittest.TestCase): def test_summary(self): runner = Runner() current_dir = os.path.dirname(os.path.realpath(__file__)) test_files_dir = current_dir + "/example_RDSMultiAZEnabled" report = runner.run(root_folder=test_files_dir, runner_filter=RunnerFilter(checks=[check.id])) summary = report.get_summary() passing_resources = { "AWS::RDS::DBInstance.MyDBEnabled", } failing_resources = { "AWS::RDS::DBInstance.MyDBDefault", "AWS::RDS::DBInstance.MyDBDisabled", } passed_check_resources = set([c.resource for c in report.passed_checks]) failed_check_resources = set([c.resource for c in report.failed_checks]) self.assertEqual(summary['passed'], 1) self.assertEqual(summary['failed'], 2) self.assertEqual(summary['skipped'], 0) self.assertEqual(summary['parsing_errors'], 0) self.assertEqual(passing_resources, passed_check_resources) self.assertEqual(failing_resources, failed_check_resources) if __name__ == '__main__': unittest.main()
true
true
f735f341c87bd4f4fdcc65b249d937ef404bd09f
56,071
py
Python
www/tests/issues.py
alan0526/brython
440571d5e124b85ad2822ca84dd12e46fd3e1737
[ "BSD-3-Clause" ]
1
2022-02-15T09:11:51.000Z
2022-02-15T09:11:51.000Z
www/tests/issues.py
alan0526/brython
440571d5e124b85ad2822ca84dd12e46fd3e1737
[ "BSD-3-Clause" ]
null
null
null
www/tests/issues.py
alan0526/brython
440571d5e124b85ad2822ca84dd12e46fd3e1737
[ "BSD-3-Clause" ]
1
2022-02-27T17:45:52.000Z
2022-02-27T17:45:52.000Z
from tester import assertRaises # issue 5 assert(isinstance(__debug__, bool)) # issue #6 : unknown encoding: windows-1250 s = "Dziś jeść ryby" b = s.encode('windows-1250') assert b == b'Dzi\x9c je\x9c\xe6 ryby' assert b.decode('windows-1250') == "Dziś jeść ryby" # issue #7 : attribute set on module is not available from inside the module import inject_name_in_module inject_name_in_module.xxx = 123 assert inject_name_in_module.xxx == 123 # XXX temporarily comment next line #assert inject_name_in_module.yyy() == 246 # issue #15 in PierreQuentel/brython class a(object): def __init__(self): self.x = 9 a.__init__ class b(a): def __init__(s): super().__init__() assert s.x == 9 z = b() # issue 12 x = {'a': 1} assert 'a' in x class ToDir: def init(self): pass instanceToDir = ToDir() dictToDir = ({k: getattr(instanceToDir, k) for k in dir(instanceToDir) if '__' not in k}) castdictToDir={str(k): getattr(instanceToDir, k) for k in dir(instanceToDir) if '__' not in k} assert 'init' in castdictToDir, \ 'init not in castdictToDir: %s' % list(dictToDir.keys()) assert castdictToDir["init"] == instanceToDir.init , \ 'init not init method: %s' % castdictToDir["init"] assert 'init' in dictToDir, \ 'init not in dictToDir: %s' % list(dictToDir.keys()) assert dictToDir["init"] == instanceToDir.init , \ 'init not init method: %s' % dictToDir["init"] # issue 32 assert 5 < 10 < 5 * 10 < 100 # issue 16 : isolate Python Namespacing i = 5 def foo(): def bar(): return i res = [] for i in range(5): res.append(bar()) return res assert foo() == [0, 1, 2, 3, 4] # issue 82 : Ellipsis literal (...) missing def f(): ... # issue 83 import sys assert sys.version_info > (3, 0, 0) assert sys.version_info >= (3, 0, 0) assert not sys.version_info == (3, 0, 0) assert sys.version_info != (3, 0, 0) assert not sys.version_info < (3, 0, 0) assert not sys.version_info <= (3, 0, 0) # issue #100 class A: if True: def aaa(self, x): return x class B(A): if True: def aaa(self, x): return super().aaa(x) b = B() assert b.aaa(0) == 0 # issue 108 def funcattrs(**kwds): def decorate(func): func.__dict__.update(kwds) return func return decorate class C(object): @funcattrs(abc=1, xyz="haha") @funcattrs(booh=42) def foo(self): return 42 assert C().foo() == 42 assert C.foo.abc == 1 assert C.foo.xyz == "haha" assert C.foo.booh == 42 # issue 121 def recur(change_namespace=0): if change_namespace: x = 2 return else: x = 1 def nested(): return x recur(change_namespace=1) return nested() assert recur() == 1 #issue 131 import time target = time.struct_time([1970, 1, 1, 0, 0, 0, 3, 1, 0]) assert time.gmtime(0).args == target.args target = time.struct_time([1970, 1, 1, 0, 1, 40, 3, 1, 0]) assert time.gmtime(100).args == target.args target = time.struct_time([2001, 9, 9, 1, 46, 40, 6, 252, 0]) assert time.gmtime(1000000000).args == target.args try: time.asctime(1) except TypeError: pass except: ValueError("Should have raised TypeError") try: time.asctime((1, 2, 3, 4)) except TypeError: pass except: ValueError("Should have raised TypeError") assert time.asctime(time.gmtime(0)) == 'Thu Jan 1 00:00:00 1970' tup = tuple(time.gmtime(0).args) assert time.asctime(tup) == 'Thu Jan 1 00:00:00 1970' # issue 137 codeobj = compile("3 + 4", "<example>", "eval") assert eval(codeobj) == 7 x = 7 codeobj = compile("x + 4", "<example>", "eval") assert eval(codeobj) == 11 # traceback objects import types try: raise ValueError except ValueError: tb = sys.exc_info()[2] assert isinstance(tb, types.TracebackType) # repr of type(None) assert repr(type(None)) == "<class 'NoneType'>" # nonlocal def f(): def g(): nonlocal t return t t = 1 return g assert f()() == 1 def f(): k = 1 def g(): def r(): nonlocal k return k + 1 return r() return g() assert f() == 2 # hashable objects class X: def __hash__(self): return hash(1.0) def __eq__(self, other): return other == 1 a = {1: 'a', X(): 'b'} assert a == {1: 'b'} assert X() in a assert a[X()] == 'b' class X: def __hash__(self): return hash('u') a = {'u': 'a', X(): 'b'} assert set(a.values()) == {'a', 'b'} assert not X() in a b = {'u': 'a'} assert not X() in b class X: def __hash__(self): return hash('u') def __eq__(self, other): return other == 'u' a = {'u': 'a', X(): 'b'} assert a == {'u': 'b'} assert X() in a assert a[X()] == 'b' # issue 176 x = [1, 2, 3] assert sum(-y for y in x) == -6 # issue 186 source = [0, 1, 2, 3] total = sum(source.pop() for _ in range(len(source))) assert total == 6, "expected 6 but instead was %d" % total # issue 177 ModuleType = type(sys) foo = ModuleType("foo", "foodoc") assert foo.__name__ == "foo" assert foo.__doc__ == "foodoc" # issue 203 def f(z): z += 1 return z x = 1.0 assert x != f(x) # issue 207 for x in range(0x7ffffff0, 0x8000000f): assert x & x == x, "%s & %s == %s" % (hex(x), hex(x), hex(x & x)) assert x | x == x, "%s | %s == %s" % (hex(x), hex(x), hex(x | x)) for x in range(0x17ffffff0, 0x17fffffff): assert x & x == x, "%s & %s == %s" % (hex(x), hex(x), hex(x & x)) assert x | x == x, "%s | %s == %s" % (hex(x), hex(x), hex(x | x)) # issue 208 a = 5 assert globals().get('a') == 5 # not an official issue class Cmp: def __init__(self,arg): self.arg = arg def __repr__(self): return '<Cmp %s>' % self.arg def __eq__(self, other): return self.arg == other a = Cmp(1) b = Cmp(1) assert a == b assert not (a != b) # bug with property setter class Test: @property def clicked(self): return self.func @clicked.setter def clicked(self, callback): self.func = callback t = Test() t.clicked = lambda x: x+7 #"clicked" assert t.clicked(7) == 14 # issue 249 x = [a.strip() for a in [ " foo ", " bar ", ]] assert x == ['foo', 'bar'] # issue 250 assert 2 ** 3 ** 4 == 2417851639229258349412352 # issue 258 a = [1, 2, 3] b, *c = a assert c == [2, 3] # issue 261 (__slots__) class A: __slots__ = 'x', A.x a = A() a.x = 9 assert a.x == 9 try: a.y = 0 except AttributeError: pass except: raise # issue 274 import base64 b = bytearray(b'<Z\x00N') b64 = base64.b64encode( b ) assert b64 == b'PFoATg==' buf = bytearray(b'EZ\x86\xdd\xabN\x86\xdd\xabNE[\x86\xdd\xabN\x86\xdd\xabN') b64 = base64.b64encode( buf ) assert b64 == b'RVqG3atOht2rTkVbht2rTobdq04=' # issue 279 x = 0 if False: x += 2 x += 3 for n in range(2): x += 1 x += 1 assert x == 4 # issue 280 for n in range(5): pass assert n == 4 #issue 297 assert type((1,) * 2) == tuple # issue 298 n = 1 for n in range(n): pass assert n == 0 # issue 301 t = 1, 2 assertRaises(AttributeError, getattr, t, "__setitem__") # issue 307 x = 1 assertRaises(AttributeError, setattr, x, '__add__', 1) assertRaises(AttributeError, setattr, x, 'y', 1) # issue 310 assert 4 in range(5) assert 4 in range(0, 5, 2) assert not 1 in range(0, 5, 2) assert 1 in range(10, 0, -1) assert 10 in range(10, 0, -1) assert not 1 in range(10, 0, -2) assert not 0 in range(10, 0, -2) # issue 316 class Test(): def __pos__(self): return 'plus' def __neg__(self): return 'minus' def __invert__(self): return 'invert' a = Test() assert +a == 'plus' assert -a == 'minus' assert ~a == 'invert' for x in 1, 1.2, 1 + 2j, 2 ** 54: assert +x == x assert -True == -1 # issue 317 assert eval("-1") == -1 # issue 322 a = 0000 b = int(00) c = 000 + 1 d = 0000 * 10 assert a == 0 assert b == 0 assert c == 1 assert d == 0 # unpacking in target list for a, *b in [[1, 2, 3]]: assert a == 1 assert b == [2, 3] # issue 327 def f(): a += 1 assertRaises(UnboundLocalError, f) def f(): a = a + 1 assertRaises(UnboundLocalError, f) a = 3 def plus(): print(a) a = 7 assertRaises(UnboundLocalError, plus) def plus(): global axd print(axd) assertRaises(NameError, plus) def f(): for i in 1, 2: if i == 2: x = a else: a = 1 return x assert f() == 1 def f(): for i in 1, 2: if i == 2: a += 1 else: a = 1 return a assert f() == 2 # issue 335 def f(): "hello"("3") assertRaises(TypeError, f) # issue 342 try: from .spam import eggs except SystemError as ie: assert str(ie) == \ "Parent module '' not loaded, cannot perform relative import" # issue 343 a76gf = 0 def f(): a76gf = 1 def g(): nonlocal a76gf a76gf = a76gf + 1 return a76gf assert g() == 2 f() # issue 344 def f(): a2fx = 1 def g(): nonlocal a2fx a2fx = 2 g() assert a2fx == 2 f() # issue 347 from abc import ABCMeta, abstractmethod class interface(metaclass=ABCMeta): @abstractmethod def test(self): return class implementation(interface): def test(self): return i = implementation() assert isinstance(i, implementation) assert isinstance(i, interface) # classes with abstract methods can't be instanciated class A(metaclass=ABCMeta): @abstractmethod def foo(self): pass assertRaises(TypeError, A) # same for subclasses class B(A): pass assertRaises(TypeError, B) # class C overrides foo so it has no abstract method, it can have instances class C(A): def foo(self): return 42 assert C().foo() == 42 # issue 348 x, y = y, x = 2, 3 assert x, y == (3, 2) # issue 355 class kk: def __init__(self, enum): pass lambda enum: enum def foo(enum): pass # issue 360 assert "André".isidentifier() # issue 363 a = float('nan') b = 1 c = a - b # issue 371 assert (not 'x' in ['x', 'y'] and 2 == 1) == False # issue 375 def f(): "test" %3 assertRaises(TypeError, f) # issues 387 and 388 class A(): pass class B(): pass a1 = A() a2 = A() assert hash(A) != hash(B) assert hash(A) != hash(a1) assert hash(A) != hash(a2) class A(): pass class B(): pass d = {A: "class A"} def test(): d[B] assertRaises(KeyError, test) # issue 389 gen = (n * n for n in range(10)) assert list(gen) == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] assert list(gen) == [] # issue 391 def f(): ["a"] + 5 assertRaises(TypeError, f) # sum with booleans assert sum([True, False]) == 1 assert 1.2 + True == 2.2 # issue #392 class A: def __init__(self): self.b = [1 for n in range(10)] self.b[3] = 0 eval = A() assert [c for c in range(10) if eval.b[c] == 0] == [3] # restore original "eval" eval = __builtins__.eval # issue 394 import base64 b = b"\x7F\x7B\xED\x96" b64 = base64.b64encode(b) assert b64 == b"f3vtlg==" newb = base64.b64decode(b64) assert newb == b e = base64.b64encode(b'data to encode') assert e == b"ZGF0YSB0byBlbmNvZGU=" assert base64.b64decode(e, validate=True) == b'data to encode' # issue 412 assert not True and not False or True assert False and not False or True assert False and not False or not False assert False and not True or True assert False and not True or not False assert not True and not True or True assert not True and not True or not False assert not True and not False or True assert not True and not False or not False # set attribute __doc__ of a function def test(): """original text""" pass assert test.__doc__ == """original text""" test.__doc__ = "new text" assert test.__doc__ == "new text" # issue 443 class Pepe: def __getitem__(self, arg): return arg pepe = Pepe() assert pepe[0:1] == slice(0, 1) assert pepe[1, 0, 0:10:2] == (1, 0, slice(0, 10, 2)) assert pepe[0, 0:10:1] == (0, slice(0, 10, 1)) assert pepe[0, 0] == (0, 0) assert pepe[0, :] == (0, slice(None, None, None)) assert pepe[0, 1, 1, 1, 2, 3, 4, :] == \ (0, 1, 1, 1, 2, 3, 4, slice(None, None, None)) # issue 448 d = {0 : [1]} d[0] += [2] assert d == {0: [1, 2]} # issue 449 a = [[1]] a[0] += [2] assert a == [[1, 2]] # issue 450 assert True == True assert True != False assert False == False assert not (True == None) assert True != None # issue 465 class A: def __init__(self, value): self.value = value def __enter__(self): return self def __exit__(self, *args): pass def __str__(self): return str(self.value) a = A(1) with a as x: assert str(x) == "1" with A(2) as x: assert str(x) == "2" with A(3): pass # ternary is an expression a = eval('1 if 3 == 4 else 0') assert a == 0 # issue 480 def test(throw=True): pass test(throw=False) # issue 485 class Test: pass a = Test() b = Test() d = {a: 1, b: 2} assert d[a] == 1 assert d[b] == 2 # issue 481 flag = False def extend_instance(obj, cls): """ Apply mixins to a class instance after creation (thanks http://stackoverflow.com/questions/8544983/dynamically-mixin-a-base-class-to-an-instance-in-python) """ base_cls = obj.__class__ base_cls_name = obj.__class__.__name__ obj.__class__ = type("Extended"+base_cls_name, (cls,base_cls),{}) class Mixin(object): def __setattr__(self, name, value): if not name.startswith('_'): #print("Mixin setting", name, "to", value, super().__setattr__) super().__setattr__(name,value) else: super().__setattr__(name,value) class Test: def __init__(self): self._dct={} def __setattr__(self, name, value): global flag if not name.startswith('_'): self._dct[name] = value flag = True else: super().__setattr__(name, value) def __getattr__(self): if not name.startswith('_'): return self._dct[name] else: return getattr(self, name) t = Test() extend_instance(t, Mixin) t.c = 20 assert flag # bug in comprehensions a = [1, 2] b = [3, 4] odd = [x for x in a + b if x % 2] assert odd == [1, 3] # issue 506 class TestRound: def __round__(self, n=None): if n is None: return 10 else: return n tr = TestRound() assert type(round(3.0)) == int, \ "Round called without second argument should return int" assert type(round(3.1111, 3)) == float, \ "Round called without second argument should return same type as first arg" assert type(round(3.0, 0)) == float, \ "Round called without second argument should return same type as first arg" assert round(3.1111, 3) == 3.111 assert type(round(0, 3)) == int, \ "Round called without second argument should return same type as first arg" assert round(tr, 3) == 3, \ "Round called on obj with __round__ method should use it" assert round(tr) == 10, \ "Round called on obj with __round__ method should use it" # Bankers rounding (issue #513) assert round(-9.5) == -10 assert round(-0.5) == 0 assert round(2.5) == 2 assert round(9.5) == 10 assert round(100.5) == 100 # issue 523 borders_distance = [(-5, 0), (4, 0), (0, -3), (0, 4)] mx, my = min(borders_distance, key=lambda m: abs(m[0] + m[1])) assert (mx, my) == (0, -3) # issue 500 order = [] try: order.append('try') except KeyError as exc: order.append('except') else: order.append('else') finally: order.append('finally') assert order == ['try', 'else', 'finally'] # issue 542 def test(*args): return args a01 = [0, 1] assert test(*a01, 2, 3) == (0, 1, 2, 3) args = a01 + [2, 3] assert test(*args) == (0, 1, 2, 3) def test(**kw): return kw d1 = {'x': 2} d2 = {'y': 3} assert test(u=1, **d1, **d2) == {'u': 1, 'x': 2, 'y': 3} # issue 545 k = 3 nb = 0 for k in range(k): nb += 1 assert nb == 3 # issue 547 a = (1,) b = a a += (2,) assert b == (1,) # issue 549 a = 5.0 a **= 2 assert a == 25.0 a //= 25 assert a == 1.0 # issue 550 assert True & False is False assert True | False is True assert True ^ False is True # issue 551 y = -1; assert y == -1 # issue 553 sxz = 'abc' assert [sxz for sxz in sxz] == ['a', 'b', 'c'] assert {sxz for sxz in sxz} == {'a', 'b', 'c'} assert {sxz: sxz for sxz in sxz} == {'a': 'a', 'b': 'b', 'c': 'c'} g = (sxz for sxz in sxz) assert list(g) == ['a', 'b', 'c'] # issue 554 nbcalls = 0 def f(): global nbcalls nbcalls += 1 def g(unused_arg=f()): pass assert nbcalls == 1 # issue 499 data = [1, 2, 3] data = (item for item in data) assert list(data) == [1, 2, 3] # issue 557 from math import sin, log class N: def __float__(self): return 42.0 num = N() assert sin(num) == -0.9165215479156338 assert log(num) == 3.7376696182833684 # issue 560 class Base: @classmethod def test(cls): return cls class Derived(Base): def __init__(self): pass assert Derived.test() == Derived d = Derived() assert d.test() == Derived # issue 563 assert str(False + False) == '0' assert False + True == 1 assert True + True == 2 # issue 572: sort should be stable words = ["Bed", "Axe", "Cat", "Court", "Axle", "Beer"] words.sort() words.sort(key=len, reverse=True) assert words == ['Court', 'Axle', 'Beer', 'Axe', 'Bed', 'Cat'] # chained comparisons x = 0 def impure(): global x x += 1 return x assert 0 < impure() <= 1 # issue 576 class Patched: def method(self, first="patched1", second="patched2"): return(first, second) class Patcher: def __init__(self): Patched.method = self.method # monkey patches with instantiated method def method(self, first="patcher1", second="patcher2"): return(first, second) Patched.method = Patcher.method # monkey patches with non instantiated method assert ("tester1", "patcher2") == Patched().method("tester1") Patcher() assert ("tester1", "patcher2") == Patched().method("tester1"), \ "instead returns %s %s" % Patched().method() # issue 578 try: raise 1 except TypeError: pass class A: pass try: raise A() except TypeError: pass def test(): return IOError() try: raise test() except IOError: pass # issue 582 def nothing(): a = lambda: 1 \ or 2 return a() assert nothing() == 1 # issue 584 try: from __future__ import non_existing_feature except SyntaxError: pass # issue 501 class Test: def __iter__(self): self._blocking = True yield self def test_yield(): b = yield from Test() return b test = [] for b in test_yield(): test.append(b) assert test[0]._blocking is True # issue 588 def yoba(a, b): return a + b assertRaises(TypeError, yoba, 1, 2, 3) # issue 592 assert pow(97, 1351, 723) == 385 # issue 595 assert float(True) == 1.0 # issue 598 class A(object): __slots__ = "attr" def __init__(self, attr=0): self.attr = attr a = A() # issue 600 class A: def __eq__(self, other): return True class B(A): def __eq__(self, other): return False # check that B.__eq__ is used because B is a subclass of A assert A() != B() a = A() b = B() assert a != b assert b != a # issue 604 class StopCompares: def __eq__(self, other): return 1 / 0 checkfirst = list([1, StopCompares()]) assert(1 in checkfirst) # issue 615 class A: spam = 5 assertRaises(TypeError, A, 5) try: class A(spam="foo"): pass raise AssertionError("should have raised TypeError") except TypeError: pass # issue 619 from browser.html import H2 class _ElementMixIn: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._sargs = [] self._kargs = {} def mytest(self): self._sargs.append(5) def mytest2(self): self._kargs[5] = '5' kls = type('h2', (_ElementMixIn, H2,), {}) x = kls() x.mytest() assert x._sargs == [5] x.mytest2() assert x._kargs[5] == '5' # issue 649 class test: def test(self): return 1 assert test().test() == 1 # issue 658 kk = [i for i in [ 1, # 1st quadrant 2 ]] assert kk == [1, 2] kk = (i for i in [ 1, # a comment 2 ]) assert list(kk) == [1, 2] # issue 663 a = {} a[5] = b = 0 assert a[5] == 0 # issue 659 class A: def x(self): pass assert A().x.__name__ == "x" assert A.x.__name__ == "x" # issue 669 assert 0.1 is 0.1 assert not(1 is 1.0) # issue 673 class A: __z = 7 def __init__(self): self.__x = 20 a = A() assert a._A__x == 20 assert a._A__z == 7 class Mapping: def __init__(self, iterable): self.items_list = [] self.__update(iterable) def update(self, iterable): for item in iterable: self.items_list.append(item) __update = update # private copy of original update() method class MappingSubclass(Mapping): def update(self, keys, values): # provides new signature for update() # but does not break __init__() for item in zip(keys, values): self.items_list.append(item) mapping = Mapping(range(3)) mapping.update(range(7, 10)) assert mapping.items_list == [0, 1, 2, 7, 8, 9] map2 = MappingSubclass(range(3)) map2.update(['a', 'b'], [8, 9]) assert map2.items_list == [0, 1, 2, ('a', 8), ('b', 9)] class B: def __print(self, name): return name assert B()._B__print('ok') == 'ok' # issue 680 class A: def __getattribute__(self, name): return super().__getattribute__(name) def test(self): return 'test !' assert A().test() == "test !" # issue 681 found = [x for x in ['a', 'b', 'c'] if x and not x.startswith('-')][-1] assert found == 'c' assert [0, 1][-1] == 1 assert {-1: 'a'}[-1] == 'a' # issue 691 class C(object): pass c1 = C() c1.x = 42 assert c1.__dict__['x'] == 42 c1.__dict__.clear() assert c1.__dict__ == {} class C(object): pass c2 = C() c2.x = 42 c2.__dict__ = dict() assert c2.__dict__ == {} try: c2.__dict__ = 6 except TypeError: pass # issue 699 def members(obj): for m in dir(obj): getattr(obj, m) members(int) class Foo: def foo(self): pass members(Foo) # issue 701 assert type((1, 2, 3)[:0]) == tuple assert type((1, 2, 3)[1:2:-1]) == tuple assert type((1, 2, 3)[0:2]) == tuple # generalised unpacking for function calls def f(*args, **kw): return args, kw res = f(3, *[1, 8], 5, y=2, **{'a': 0}, **{'z': 3}) assert res[0] == (3, 1, 8, 5) assert res[1] == {'y': 2, 'a': 0, 'z': 3} # issue 702 def f(): return try: f > 5 raise Exception("should have raised TypeError") except TypeError: pass try: min <= 'a' raise Exception("should have raised TypeError") except TypeError: pass import random try: random.random < 1 raise Exception("should have raised TypeError") except TypeError: pass class A: pass try: A < 'x' raise Exception("should have raised TypeError") except TypeError: pass # issue 729 head, *tail = 1, 2, 3 assert tail == [2, 3] # issue 743 def test(msg = 'a', e_type: int = 10): pass # issue 751 class Z: pass try: (10, Z()) <= (10, Z()) raise Exception("should have raised TypeError") except TypeError: pass try: a = [100, 100, 100, 100, 100, 70, 100, 100, 70, 70, 100, 70, 70, 70, 100, 70, 70, 100, 70, 70, 70, 70, 100, 70, 70, 70, 70, 70, 100, 70, 70, 70, 100, 70, 70, 70, 70, 70, 70, 100] b = [(v, Z()) for v in a] sorted(b, reverse=True) raise Exception("should have raised TypeError") except TypeError: pass # issue 753 # cf. https://github.com/mziccard/node-timsort/issues/14 a = [1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 0.5, 0.5, 1.0, 0.5, 1.0, 0.5, 0.5, 0.5, 0.6, 1.0] a.sort() for i in range(len(a) - 1): assert a[i] <= a[i + 1] # issue 755 assert '{}'.format(int) == "<class 'int'>" class C: pass assert '{}'.format(C) == "<class '__main__.C'>" import javascript assert javascript.jsobj2pyobj(javascript.NULL) is None undef = javascript.jsobj2pyobj(javascript.UNDEFINED) assert not undef # issue 760 class A(object): def __str__(self): return "an A" class B(A): def __repr__(self): return '<B>()' b = B() assert str(b) == "an A" # issue 761 class A: def __str__(self): return 'an A' assert '{0}'.format(A()) == 'an A' # issue 776 def f(): d = { a: b for k in keys if k not in ( "name", ) # comment } # issue 778 import os assertRaises(NotImplementedError, os.listdir) # issue 780 def g(): print(xtr) # should crash, of course def f(): xtr = 42 g() assertRaises(NameError, f) # issue 781 # can't call strings assertRaises(TypeError, 'a') assertRaises(TypeError, 'a', 1) assertRaises(TypeError, 'a', {'x': 1}) # can't call lists t = [1, 2] assertRaises(TypeError, t) assertRaises(TypeError, t, 1) assertRaises(TypeError, t, {'x': 1}) # can't call dicts d = {1: 'a'} assertRaises(TypeError,d) assertRaises(TypeError, d, 1) assertRaises(TypeError, d, {'x': 1}) # issue 782 class Greetings: default = None def hello(self): return "Hello!" _func_body = """\ def {name}(): if {obj} is None: {obj} = {init} return {obj}.{name}() """ def_str = _func_body.format(obj='Greetings.default', init='Greetings()', name="hello") exec(def_str, globals()) assert hello() == "Hello!" # issue 801 class L: def __init__(self): self._called = 0 def get_list(self): self._called += 1 return [0] l = L() for i in l.get_list(): pass assert l._called == 1 # issue 808 class A: pass class B(object): def __init__(self, *args, **kwargs): self.res = None def __setattr__(self, *args, **kwargs): res = None if len(args) == 2 and hasattr(self, args[0]): old = getattr(self, args[0]) new = args[1] res = super(B, self).__setattr__(*args, **kwargs) else: res = super(B, self).__setattr__(*args, **kwargs) return res class C(B,A): pass c = C() """ import ipaddress assert repr(ipaddress.ip_address('192.168.0.1')) == "IPv4Address('192.168.0.1')" assert repr(ipaddress.ip_address('2001:db8::')) == "IPv6Address('2001:db8::')" """ # issue 811 try: exec("a + b = 1") raise Exception("should have raised SyntaxError") except SyntaxError: pass # issue 813 class A: def __radd__(self, other): return 99 def __rmul__(self, other): return 100 assert [5] + A() == 99 assert [6] * A() == 100 # issue reported on the Google Group # https://groups.google.com/forum/?fromgroups=#!topic/brython/U6cmUP9Q6Y8 class ndarray: def __getitem__(self, val): return val t = ndarray() assert slice(1, 5, None) == slice(1, 5, None) assert t[1:5, 7] == (slice(1, 5, None), 7) # test attribute __code__.co_code of functions def f(): print(10) assert f.__code__.co_code.startswith("function f") # Regression introduced in 6888c6d67b3d5b44905a09fa427a84bef2c7b304 class A: pass global_x = None def target(x=None): global global_x global_x = x obj_dict = A().__dict__ obj_dict['target_key'] = target obj_dict['target_key'](x='hello') assert global_x == 'hello' # issue 835 x = 0 class A: assert x == 0 def x(self): pass assert callable(x) # issue 836 def f(): if False: wxc = 0 else: print(wxc) assertRaises(UnboundLocalError, f) def g(): if False: vbn = 0 print(vbn) assertRaises(UnboundLocalError, f) # issue 838 import sys assert type(random) == type(sys) # issue 843 try: raise FileNotFoundError() except FloatingPointError: assert False except FileNotFoundError: assert sys.exc_info()[0] == FileNotFoundError # Test exception raising with and without parens for # custom and builtin exception types class CustomException(Exception): pass try: raise Exception() except Exception: pass try: raise Exception except Exception: pass try: raise CustomException() except CustomException: pass try: raise CustomException except CustomException: pass # Make sure that accessing tb.tb_next doesn't lead to an infinite loop try: raise Exception() except: (_, _, tb) = sys.exc_info() while tb: tb = tb.tb_next # PEP 448 assert dict(**{'x': 1}, y=2, **{'z': 3}) == {"x": 1, "y": 2, "z": 3} try: d = dict(**{'x': 1}, y=2, **{'z': 3, 'x': 9}) raise Exception("should have raised TypeError") except TypeError: pass r = range(2) t = *r, *range(2), 4 assert t == (0, 1, 0, 1, 4) t = [*range(4), 4] assert t == [0, 1, 2, 3, 4] assert {*range(4), 4} == {0, 1, 2, 3, 4} assert {*[0, 1], 2} == {0, 1, 2} assert {*(0, 1), 2} == {0, 1, 2} assert {4, *t} == {0, 1, 2, 3, 4} assert {'x': 1, **{'y': 2, 'z': 3}} == {'x': 1, 'y': 2, 'z': 3} assert {'x': 1, **{'x': 2}} == {'x': 2} assert {**{'x': 2}, 'x': 1} == {'x': 1} assertRaises(SyntaxError, exec, "d = {'x': 1, *[1]}") assertRaises(SyntaxError, exec, "d = {'x', **{'y': 1}}") assertRaises(SyntaxError, exec, "d = {*[1], 'x': 2}") assertRaises(SyntaxError, exec, "d = {**{'x': 1}, 2}") assertRaises(SyntaxError, exec, "t = *range(4)") # issue 909 t1 = [*[1]] assert t1 == [1] t2 = [*(1, 2)] assert t2 == [1, 2] # issue 854 class A(object): def __init__(self): self.x = 0 def f(): pass class B(A): pass assert 'f' in dir(A) assert 'f' in dir(B) assert 'x' in dir(A()) assert 'x' in dir(B()) # issue 869 class A(object): def __init__(self): self.value = 0 def __iadd__(self, val): self.value += val return self.value class B(object): def __init__(self): self.a = A() b = B() b.a += 10 assert b.a == 10 # issue 873 str(globals()) # issue 883 for _ in range(2): for _ in range(2): pass # issue 900 "".format(**globals()) # issue 901 : _jsre's SRE_Pattern lacking methods: .sub(), .subn(), .split(), and .fullmatch() import _jsre as re regex = re.compile('a|b') # These methods work! assert regex.match('ab') is not None assert regex.search(' ab') is not None assert regex.findall('ab') == ['a', 'b'] def switch(m): return 'a' if m.group(0) == 'b' else 'b' # Missing: .sub() assert regex.sub(switch, 'ba') == 'ab' # Missing: .fullmatch() # assert regex.fullmatch('b') is not None # Missing: .split() #assert regex.split('cacbca', maxsplit=2) == ['c', 'c', 'ca'] # Missing: .subn() #assert regex.subn(switch, 'ba') == ('ab', 2) # Broken: .finditer() #assert [m.group(0) for m in regex.finditer('ab')] == ['a', 'b'] # issue 923 v = 1 del v try: print(v) raise Exception("should have raised NameError") except NameError: pass hello = {"a": 1, "b": 2} del(hello["a"]) # with parenthesis assert len(hello) == 1 # issue 925 class A(): def __lt__(self, other): return 1 def __gt__(self, other): return 2 assert (1 < A()) == 2 assert (A() < 1) == 1 # issue 936 assert not (2 == "2") assert 2 != "2" assert not ("2" == 2) assert "2" != 2 try: 2 <= "2" except TypeError as exc: assert "<=" in exc.args[0] # issue 939 class A: def __bool__(self): raise TypeError("Not a bool!") try: if A(): pass raise Exception("should have raised TypeError") except TypeError as exc: assert exc.args[0] == "Not a bool!" try: bool(A()) raise Exception("should have raised TypeError") except TypeError as exc: assert exc.args[0] == "Not a bool!" # issue 940 assertRaises(SyntaxError, lambda: exec('a.foo = x += 3', {'a': A(), 'x': 10})) assertRaises(SyntaxError, lambda: exec('x = a.foo += 3', {'a': A(), 'x': 10})) # issue 944 src = """def f(): pass f(): """ assertRaises(SyntaxError, exec, src) # issue 948 try: exec("a = +25, b = 25") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "cannot assign to operator" # issue 949 class A(object): def __getattr__(self, name): return 'A-%s' % name try: A.foo raise Exception("should have raised AttributeError") except AttributeError: pass # issue 951 class A(object): pass a = A() a.__dict__['_x'] = {1: 2} a._x[3] = 4 assert len(a._x) == 2 # issue 952 try: exec("x += 1, y = 2") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0].startswith("invalid syntax") # issue 953 adk = 4 def f(): if False: adk = 1 else: print(adk) assertRaises(UnboundLocalError, f) # issue 959 try: exec("x + x += 10") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "cannot assign to operator" # issue 965 assertRaises(SyntaxError, exec, "if:x=2") assertRaises(SyntaxError, exec, "while:x=2") assertRaises(SyntaxError, exec, "for x in:x") # issue 973 try: exec("x = 400 - a, y = 400 - b") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "cannot assign to operator" # issue 975 l = [1, 2, 3] try: l[:,:] raise Exception("should have raised TypeError") except TypeError: pass def f(): global x985 print(x985) def g(): global x985 x985 = 1 assertRaises(NameError, f) # issue 1024 assert [x for x in range(10) if x % 2 if x % 3] == [1, 5, 7] result = [] for x, in [(1,), (2,), (3,)]: result.append(x) assert result == [1, 2, 3] assert [x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False)] == [True] def test_yield_in_comprehensions(self): # Check yield in comprehensions def g2(): [x for x in [(yield 1)]] # issue 1026 assertRaises(SyntaxError, exec, "x += y += 5") # augmented assignment to a global variable def f(): global xaz25 xaz25 += 1 xaz25 = 8 f() assert xaz25 == 9 # issue 1048 class Foo: bar = 1 foo = Foo() assertRaises(AttributeError, delattr, foo, 'bar') class C: def __init__(self): self._x = None self.count = 0 def getx(self): return self._x def setx(self, value): self._x = value def delx(self): self.count += 1 del self._x x = property(getx, setx, delx, "I'm the 'x' property.") c = C() delattr(c, "x") assert c.count == 1 # setting __defaults__ to functions (issue #1053) def ftrk(x, y=5): return x + y assert ftrk(1) == 6 ftrk.__defaults__ = (4, 1) assert ftrk(1) == 2 assert ftrk() == 5 ftrk.__defaults__ = () assertRaises(TypeError, ftrk) ftrk.__defaults__ = (4, 1) assert ftrk(1) == 2 assert ftrk() == 5 ftrk.__defaults__ = None assertRaises(TypeError, ftrk) def g(): def h(x, y): return x + y h.__defaults__ = (3,) return h assert g()(1) == 4 class A: def ftrk2(self, x): return x + 1 a = A() assert a.ftrk2(2) == 3 A.ftrk2.__defaults__ = (2,) assert a.ftrk2() == 3, a.ftrk2() class B: def __new__(cls, a): obj = object.__new__(cls) obj.a = a return obj def show(self): return self.a b = B(2) assert b.show() == 2 B.__new__.__defaults__ = (8,) b2 = B() assert b2.show() == 8 # issue 1059 import os try: issues_py_dir = os.path.dirname(__file__) z_txt_path = os.path.join(issues_py_dir, "z.txt") except NameError: z_txt_path = "z.txt" with open(z_txt_path, encoding="utf-8") as f: t = [line for line in f] assert len(t) == 3 with open(z_txt_path, encoding="utf-8") as f: assert f.readlines() == t # issue 1063 class A(object): pass y = [1, 2, 3] x = A() t = [] for x.foo in y: t.append(x.foo) assert t == y # issue 1062 assertRaises(SyntaxError, exec, "x[]") assertRaises(SyntaxError, exec, "x{}") # issue 1068 class Class(): def method(self): assert "__class__" not in Class.method.__code__.co_varnames return __class__.__name__ assert Class().method() == "Class" def f(): print(__class__) assertRaises(NameError, f) # issue 1085 expected = [ (0, 10, 1), (0, 10, 1), (0, 1, 1), (0, 1, 1), (1, 10, 1), (1, 10, 1), (1, 1, 1), (1, 1, 1) ] tmp = (None, 1) for i in range(8): target = slice( tmp[bool(i & 4)], tmp[bool(i & 2)], tmp[bool(i & 1)] ) assert target.indices(10) == expected[i] test_pool = [((85, None, None), 9, (9, 9, 1)), ((-32, None, None), 84, (52, 84, 1)), ((None, -40, None), 97, (0, 57, 1)), ((-89, None, -5), 86, (-1, -1, -5)), ((-92, -10, None), 0, (0, 0, 1)), ((99, None, None), 22, (22, 22, 1)), ((-85, -90, 8), 60, (0, 0, 8)), ((76, None, -9), 10, (9, -1, -9)), ((None, None, 8), 54, (0, 54, 8)), ((None, -86, None), 71, (0, 0, 1)), ((None, -83, None), 4, (0, 0, 1)), ((-78, None, -7), 27, (-1, -1, -7)), ((None, 3, None), 71, (0, 3, 1)), ((91, None, 3), 15, (15, 15, 3)), ((None, None, 2), 35, (0, 35, 2)), ((None, None, None), 46, (0, 46, 1)), ((None, 94, None), 64, (0, 64, 1)), ((6, None, 2), 57, (6, 57, 2)), ((43, None, 9), 70, (43, 70, 9)), ((83, None, None), 93, (83, 93, 1)), ((None, None, -7), 37, (36, -1, -7)), ((None, -27, None), 70, (0, 43, 1)), ((None, -22, None), 89, (0, 67, 1)), ((-79, -39, 9), 20, (0, 0, 9)), ((None, 83, None), 89, (0, 83, 1)), ((96, None, None), 8, (8, 8, 1)), ((None, -37, None), 35, (0, 0, 1)), ((None, -62, -2), 78, (77, 16, -2)), ((-31, -37, 3), 9, (0, 0, 3)), ((None, None, None), 92, (0, 92, 1)), ((35, 54, None), 10, (10, 10, 1)), ((-55, None, 7), 55, (0, 55, 7)), ((None, None, 7), 97, (0, 97, 7)), ((None, 92, None), 70, (0, 70, 1)), ((None, -37, None), 57, (0, 20, 1)), ((None, None, None), 71, (0, 71, 1)), ((-98, -76, -7), 10, (-1, -1, -7)), ((-90, 44, None), 66, (0, 44, 1)), ((None, None, 2), 16, (0, 16, 2)), ((61, -54, None), 35, (35, 0, 1)), ((4, -12, None), 36, (4, 24, 1)), ((None, 78, -7), 92, (91, 78, -7)), ((-48, None, 2), 47, (0, 47, 2)), ((-16, 55, None), 8, (0, 8, 1)), ((None, None, 1), 6, (0, 6, 1)), ((-73, None, None), 67, (0, 67, 1)), ((65, None, -1), 30, (29, -1, -1)), ((12, None, None), 61, (12, 61, 1)), ((33, None, None), 31, (31, 31, 1)), ((None, None, -3), 96, (95, -1, -3)), ((None, None, None), 15, (0, 15, 1)), ((19, -65, 8), 39, (19, 0, 8)), ((85, -4, 9), 40, (40, 36, 9)), ((-82, None, None), 6, (0, 6, 1)), ((29, None, 6), 94, (29, 94, 6)), ((None, 14, -2), 63, (62, 14, -2)), ((None, 15, 6), 30, (0, 15, 6)), ((None, None, None), 22, (0, 22, 1)), ((None, None, 1), 88, (0, 88, 1)), ((87, -7, None), 47, (47, 40, 1)), ((None, -12, 8), 68, (0, 56, 8)), ((-70, None, 8), 1, (0, 1, 8)), ((-21, None, 1), 24, (3, 24, 1)), ((None, None, None), 54, (0, 54, 1)), ((None, None, 9), 28, (0, 28, 9)), ((31, -25, None), 13, (13, 0, 1)), ((16, 33, None), 63, (16, 33, 1)), ((None, 86, 3), 58, (0, 58, 3)), ((None, -63, -1), 68, (67, 5, -1)), ((None, 7, -3), 76, (75, 7, -3)), ((92, 24, 7), 76, (76, 24, 7)), ((3, 65, None), 78, (3, 65, 1)), ((None, None, -9), 45, (44, -1, -9)), ((None, 85, None), 21, (0, 21, 1)), ((77, None, 1), 33, (33, 33, 1)), ((None, None, None), 81, (0, 81, 1)), ((-2, 50, 6), 52, (50, 50, 6)), ((-39, 6, 2), 89, (50, 6, 2)), ((None, -26, None), 15, (0, 0, 1)), ((66, None, -1), 98, (66, -1, -1)), ((None, None, None), 37, (0, 37, 1)), ((3, -48, None), 14, (3, 0, 1)), ((None, 84, None), 12, (0, 12, 1)), ((79, 87, -2), 72, (71, 71, -2)), ((None, -97, -7), 68, (67, -1, -7)), ((None, 62, None), 86, (0, 62, 1)), ((-54, None, 3), 71, (17, 71, 3)), ((77, None, None), 78, (77, 78, 1)), ((None, None, -7), 87, (86, -1, -7)), ((None, None, None), 59, (0, 59, 1)), ((None, -24, None), 15, (0, 0, 1)), ((None, None, 7), 72, (0, 72, 7)), ((None, None, 2), 79, (0, 79, 2)), ((-50, None, None), 4, (0, 4, 1)), ((None, -97, -5), 68, (67, -1, -5)), ((22, None, None), 67, (22, 67, 1)), ((-72, None, -2), 93, (21, -1, -2)), ((8, None, -6), 88, (8, -1, -6)), ((-53, 31, -6), 0, (-1, -1, -6)), ((None, None, None), 0, (0, 0, 1))] for args, cut, res in test_pool: test = slice(*args) res_test = test.indices(cut) assert res == res_test, \ '{test}.indices({cut}) should be {res}, not {res_test}'.format(**locals()) # too many positional arguments def f(a, b, *, x=3): print(a, b, x) assertRaises(TypeError, f, 1, 2, 3) # issue 1122 class A(Exception): pass class B(object): def __getattr__(self, attr): raise A() ok = False try: b = B() b.attr except A: ok = True except: pass assert(ok) # issue 1125 from typing import Union row = Union[int, str] def do() -> None: a: row = 4 do() # issue 1133 try: set except NameError: from sets import Set as set if False: set = list assert set([1, 2]) == {1, 2} # issue 1209 assertRaises(SyntaxError, exec, "x:+=1") # issue 1210 assertRaises(SyntaxError, exec, r"\\") assertRaises(SyntaxError, exec, r"\\\n") assertRaises(SyntaxError, exec, "def f():\n \\\\") assertRaises(SyntaxError, exec, "def f():\n \\\\\n") # issue 1229 class A: def __str__(self): return "real str" a = A() assert str(a) == "real str" a.__str__ = lambda : "fake str" assert str(a) == "real str" # issue 1233 for x1233 in range(0): pass assertRaises(NameError, exec, "x1233") # issue 1243 assertRaises(SyntaxError, exec, """for i in range(1): f(), = 0""") # issue 1247 assertRaises(SyntaxError, exec, """def f(): return x += 1""") # issue 1248 def f(): x += 1 # issue 1251 assertRaises(SyntaxError, eval, '\\\n') # issue 1253 assertRaises(UnboundLocalError, exec, """x = 1 def f(): (((((x))))) += 1 f() """) # issue 1254 assertRaises(SyntaxError, exec, """def f(): print('hi') f(*)""") assertRaises(SyntaxError, exec, """def f(): print('hi') f(*, 1)""") assertRaises(SyntaxError, exec, """def f(x, **): print('hi') f(7)""") assertRaises(SyntaxError, exec, """def f(x, *): print('hi') f(7)""") # issue 1264 class TestDescriptor: counter = 0 def __set_name__(self, owner, name): TestDescriptor.counter += 1 class TestObject: my_descriptor = TestDescriptor() assert TestDescriptor.counter == 1 # issue 1273 lambda x, y, *, k=20: x+y+k lambda *args: args l6 = lambda x, y, *, k=20: x+y+k assert l6(3, 4) == 27 assert l6(3, 4, k=1) == 8 assertRaises(TypeError, l6, 1, 2, 3) l16 = lambda *, b,: b assertRaises(TypeError, l16, 10) assert l16(b=2) == 2 assertRaises(TypeError, l16, 5) l19 = lambda a, *, b,: a + b assert l19(8, b=10) == 18 assertRaises(TypeError, l19, 5) l22 = lambda *, b, **kwds,: b assertRaises(TypeError, l22, 1) assert l22(b=2) == 2 l24 = lambda a, *, b, **kwds,: (a + b, kwds) assert l24(1, b=2, c=24) == (3, {'c': 24}) # issue 1276 class A: pass x = A() x.a = 1 try: exec("(x.a < 2) += 100") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "'comparison' is an illegal expression for augmented assignment" try: exec("(x.a * 2) += 100") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "'operator' is an illegal expression for augmented assignment" # issue 1278 import textwrap assert textwrap.wrap('1234 123', width=5) == ['1234', '123'] assert textwrap.wrap('12345 123', width=5) == ['12345', '123'] assert textwrap.wrap('123456 123', width=5, break_long_words=False) == \ ['123456', '123'] # issue 1286 assertRaises(ZeroDivisionError, tuple, (1/0 for n in range(10))) def zde1(): {1 / 0 for n in range(10)} assertRaises(ZeroDivisionError, zde1) def zde2(): sum(1 / 0 for n in range(10)) assertRaises(ZeroDivisionError, zde2) def zde3(): [1 / 0 for n in range(10)] assertRaises(ZeroDivisionError, zde3) def zde4(): {n: 1 / 0 for n in range(10)} assertRaises(ZeroDivisionError, zde4) try: [1/0 for n in range(10)] raise AssertionError(f"should have raised ZeroDivisionError") except ZeroDivisionError: pass try: list(1/0 for n in range(10)) raise AssertionError(f"should have raised ZeroDivisionError") except ZeroDivisionError: pass try: {1/0 for n in range(10)} raise AssertionError(f"should have raised ZeroDivisionError") except ZeroDivisionError: pass try: {n: 1/0 for n in range(10)} raise AssertionError(f"should have raised ZeroDivisionError") except ZeroDivisionError: pass assertRaises(NameError, tuple, (d999['missing key'] for n in range(10))) # continuation lines inside comprehensions [n for \ n in range(10)] # change definition of range def range(n): return 'abc' t = [] for i in range(10): t.append(i) assert t == ['a', 'b', 'c'] # reset range to builtins range = __builtins__.range assert list(range(3)) == [0, 1, 2] # issue 1292 assertRaises(SyntaxError, exec, "for in range(1):\n pass") # issue 1297 assertRaises(SyntaxError, exec, "for i in range = 10") # ternary x = 1 if True is not None else 2, 3, 4 assert x == (1, 3, 4) # issue 1323 try: exit() raise AssertionError("should have raised SystemExit") except SystemExit: pass # issue 1331 assert [*{*['a', 'b', 'a']}] == ['a', 'b'] assert [*{'a': 1, 'b': 2}] == ['a', 'b'] # issue 1366 class A(object): def __str__(self): return "A __str__ output." class B(A): def __str__(self): return super().__str__() + " (from B)" x = A() assert str(x) == "A __str__ output." y = B() assert str(y) == "A __str__ output. (from B)" # issue 1445 ge = (*((i, i*2) for i in range(3)),) assert list(ge) == [(0, 0), (1, 2), (2, 4)] assert [*((i, i*2) for i in range(3))] == [(0, 0), (1, 2), (2, 4)] def matrix(s, types=None, char='|'): ds = ([j.strip() for j in i.split(char)] for i in s.strip().splitlines() if not i.strip().startswith('#')) if not types: yield from ds elif isinstance(types, (list, tuple)): for i in ds: yield [k(v or k()) for k, v in zip(types, i)] else: for i in ds: yield [types(v or types()) for v in i] m = [*matrix(''' #l | r 1 | 2 3 | 4 ''', (int, int))] assert m == [[1, 2], [3, 4]] # issue 1448 class Property: def __set_name__(self, owner, name): assert owner.__name__ == "Cat" class Cat: name = Property() def test(self): pass # issue 1461 def todict(obj): # dict if isinstance(obj, dict): return {k: todict(v) for k, v in obj.items()} # slot objects elif hasattr(obj, '__slots__'): return {k: todict(getattr(obj, k)) for k in obj.__slots__} # brython issue # something iterable, like tuples or lists elif hasattr(obj, "__iter__") and not isinstance(obj, str): return type(obj)(todict(v) for v in obj) # simple classes elif hasattr(obj, "__dict__"): return {k: todict(v) for k, v in obj.__dict__.items() if not callable(v) and not k.startswith('_')} # finally simple type else: return obj class Cat: __slots__ = ('name', 'age', 'breed') def __init__(self, name='', age=0, breed='test'): self.name = name self.age = age self.breed = breed def __repr__(self): return self.__class__.__name__ + '(' + ', '.join(f'{k}={getattr(self, k, None)!r}' for k in self.__slots__) + ')' assert str(todict(Cat(Cat()))) == \ "{'name': {'name': '', 'age': 0, 'breed': 'test'}, 'age': 0, 'breed': 'test'}" # issue 1472 try: exec(""" myvar = 1 result.append(myvar) def main_func(): nonlocal myvar myvar = 3 result.append(myvar) result.append("hello") main_func() result.append(myvar) """) raise AssertionError("should have raised SyntaxError") except SyntaxError as e: assert e.args[0] == "no binding for nonlocal 'myvar' found" result = [] exec(""" def f(): myvar = 1 result.append(myvar) def main_func(): nonlocal myvar myvar = 3 result.append(myvar) result.append("hello") main_func() result.append(myvar) f() """) assert result == [1, 3, 'hello', 3] result = [] exec(""" def f(): myvar = 1 result.append(myvar) def main_func(): global myvar myvar = 3 result.append(myvar) result.append("hello") main_func() result.append(myvar) f() """) assert result == [1, 3, 'hello', 1] result = [] def f(): exec(""" myvar = 1 result.append(myvar) def main_func(): global myvar myvar = 3 result.append(myvar) main_func() result.append(myvar) """) f() assert result == [1, 3, 3] # issue 1496 try: exec("not x = 1") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "cannot assign to operator" pass # issue 1501 class B: pass b = B() (a := b).c = 7 assert a.c == 7 try: exec("(a := b) = 1") raise Exception("should have raised SyntaxError") except SyntaxError: pass # issue 1509 funs = [(lambda i=i: i) for i in range(3)] t = [] for f in funs: t.append(f()) assert t == [0, 1, 2] # issue 1515 try: range[0, 8] raise Exception("should have raised TypeError") except TypeError as exc: assert exc.args[0] == "'type' object is not subscriptable" # issue 1529 assertRaises(SyntaxError, exec, "for x in in range(1):\n pass") # issue 1531 try: exec("x =* -1") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "can't use starred expression here" # issue 1538 def g(x): if isinstance(x, int): return x return [g(y) for y in x] assert g([1, [3, 4]]) == [1, [3, 4]] # issue 1562 t = *['a', 'b'], assert t == ('a', 'b') s = *"cde", assert s == ('c', 'd', 'e') try: exec('t = *["a", "b"]') raise Exception("should have raised SyntaxError") except SyntaxError: pass try: exec('s = *"abcd"') raise Exception("should have raised SyntaxError") except SyntaxError: pass spam = ['spam'] x = *spam[0], assert x == ('s', 'p', 'a', 'm') class Spam: def __neg__(self): return 'spam' try: exec('x = *-Spam()') raise Exception("should have raised SyntaxError") except SyntaxError: pass x = *-Spam(), assert x == ('s', 'p', 'a', 'm') x = 1, *'two' assert x == (1, 't', 'w', 'o') y = *b'abc', assert y == (97, 98, 99) z = [*'spam'] assert z == ['s', 'p', 'a', 'm'] # issue 1582 assert max([1, 2, 3], key=None) == 3 assert min([1, 2, 3], key=None) == 1 # issue 1596 x = 0 y = 0 def f(): x = 1 y = 1 class C: assert x == 0 # local to a class, unbound : search at module level assert y == 1 # not local, unbound : search in all enclosing scopes x = 2 f() # issue 1608 class Test(): def __enter__(self): return (42, 43) def __exit__(self, type, value, traceback): pass with Test() as (a, b): assert type(a) == int assert b == 43 # issue 1618 assert repr(list[0]) == 'list[0]' # issue 1621 english = ["one", "two", "three"] español = ["uno", "dos", "tres"] zip_iter = zip(english, español) eng, esp = next(zip_iter) assert eng == "one" assert esp == "uno" rest = [] for eng, esp in zip_iter: rest.append([eng, esp]) assert rest == [["two", "dos"], ["three", "tres"]] # issue 1632 def add_seen_k(k, f=lambda x: 0): def inner(z): return k return inner a = add_seen_k(3) assert a(4) == 3 # issue 1638 def fib_gen(): yield from [0, 1] a = fib_gen() next(a) for x, y in zip(a, fib_gen()): yield x + y fg = fib_gen() t = [next(fg) for _ in range(7)] assert t == [0, 1, 1, 2, 3, 5, 8] # issue 1652 try: ()[0] raise Exception("should have raised IndexError") except IndexError as exc: assert exc.args[0] == "tuple index out of range" # issue 1661 class A(): pass o = A() o.x = 1 t = [] def f(): for o.x in range(5): t.append(o.x) f() assert t == [0, 1, 2, 3, 4] class A(): pass t = [] def f(): o = A() o.x = 1 for o.x in range(5): t.append(o.x) f() assert t == [0, 1, 2, 3, 4] t = [] def f(): d = {} d['x'] = 1 for d['x'] in range(5): t.append(d['x']) f() assert t == [0, 1, 2, 3, 4] t = [] def f(): d = [1] for d[0] in range(5): t.append(d[0]) f() assert t == [0, 1, 2, 3, 4] # issue 1664 x = 0 def f(): global x x -= -1 assert x == 1 f() # issue 1665 def foo(a, b): c = 10 return foo.__code__.co_varnames assert foo(1, 2) == ('a', 'b', 'c') # issue 1671 def f(): global x1671 try: print(x1671) raise Exception("should have raised NameError") except NameError: pass # issue 1685 assertRaises(TypeError, int.__str__) assertRaises(TypeError, int.__str__, 1, 2) assert int.__str__('a') == "'a'" assert int.__str__(int) == "<class 'int'>" assertRaises(TypeError, int.__repr__, 'x') assert int.__repr__(7) == '7' assertRaises(TypeError, float.__str__) assertRaises(TypeError, float.__str__, 1.1, 2.2) assert float.__str__('a') == "'a'" assert float.__str__(int) == "<class 'int'>" assertRaises(TypeError, float.__repr__, 'x') assertRaises(TypeError, float.__repr__, 7) assert float.__repr__(7.6) == '7.6' # issue 1688 def f(a1688): pass try: for a1688 in a1688.b: pass raise Exception("should have raised NameError") except NameError: pass # issue 1699 assertRaises(IndentationError, exec, 'def f():') # issue 1703 def get_foobar(): global foobar return foobar global foobar foobar = 'foobar' assert get_foobar() == "foobar" # issue 1723 try: type() raise Exception('should have raised TypeError') except TypeError: pass # issue 1729 assertRaises(SyntaxError, exec, '''for i in range(0): if True: f() += 1''') # issue 1767 assertRaises(TypeError, chr, '') assertRaises(TypeError, chr, 'a') # issue 1814 er = IndexError('hello') assert str(er) == 'hello' assert repr(er) == "IndexError('hello')" er = IndexError() assert str(er) == '' assert repr(er) == 'IndexError()' # issue 1812 assertRaises(ValueError, exec, "list(zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True))") assertRaises(ValueError, exec, "list(zip(range(5), ['fee', 'fi', 'fo', 'fum'], strict=True))") # issue 1816 assertRaises(SyntaxError, exec, '@x = 123') # issue 1821 class MyRepr: def __init__(self): self.__repr__ = lambda: "obj" def __repr__(self): return "class" my_repr = MyRepr() assert str(my_repr.__repr__()) == 'obj' assert str(my_repr) == 'class' assert str(MyRepr.__repr__(my_repr)) == 'class' assert str(MyRepr().__repr__()) == 'obj' # issue 1826 assertRaises(SyntaxError, exec, """x, if y > 4: pass""") assertRaises(SyntaxError, exec, """async def f(): await x = 1""") # issue 1827 class Vector2: def __init__(self, a, b): self.x, self.y = a, b def clone(self): return Vector2(self.x, self.y) def __imul__(self, k): res = self.clone() res.x *= k res.y *= k return res vector = Vector2(1.5, 3.7) vector *= 25.7 assert (vector.x, vector.y) == (38.55, 95.09) # issue 1830 def foo(constructor: bool): assert constructor is True foo(constructor=True) # issue 1854 assert 0 != int # issue 1857 lines = ["789/", "456*", "123-", "0.=+"] ((x for x in line) for line in lines) # issue 1860 try: try: raise ValueError("inner") except Exception as e: raise ValueError("outer") from e except Exception as e: assert repr(e.__context__) == "ValueError('inner')" # issue 1875 assertRaises(SyntaxError, exec, "(a, b = b, a)") # issue 1886 try: exec("[i := i for i in range(5)]") except SyntaxError as exc: assert "cannot rebind" in exc.args[0] # ========================================== # Finally, report that all tests have passed # ========================================== print('passed all tests')
18.389964
115
0.57709
from tester import assertRaises assert(isinstance(__debug__, bool)) 'windows-1250') assert b == b'Dzi\x9c je\x9c\xe6 ryby' assert b.decode('windows-1250') == "Dziś jeść ryby" inject_name_in_module.xxx == 123 init__(self): self.x = 9 a.__init__ class b(a): def __init__(s): super().__init__() assert s.x == 9 z = b() x = {'a': 1} assert 'a' in x class ToDir: def init(self): pass instanceToDir = ToDir() dictToDir = ({k: getattr(instanceToDir, k) for k in dir(instanceToDir) if '__' not in k}) castdictToDir={str(k): getattr(instanceToDir, k) for k in dir(instanceToDir) if '__' not in k} assert 'init' in castdictToDir, \ 'init not in castdictToDir: %s' % list(dictToDir.keys()) assert castdictToDir["init"] == instanceToDir.init , \ 'init not init method: %s' % castdictToDir["init"] assert 'init' in dictToDir, \ 'init not in dictToDir: %s' % list(dictToDir.keys()) assert dictToDir["init"] == instanceToDir.init , \ 'init not init method: %s' % dictToDir["init"] assert 5 < 10 < 5 * 10 < 100 i = 5 def foo(): def bar(): return i res = [] for i in range(5): res.append(bar()) return res assert foo() == [0, 1, 2, 3, 4] def f(): ... import sys assert sys.version_info > (3, 0, 0) assert sys.version_info >= (3, 0, 0) assert not sys.version_info == (3, 0, 0) assert sys.version_info != (3, 0, 0) assert not sys.version_info < (3, 0, 0) assert not sys.version_info <= (3, 0, 0) ss A: if True: def aaa(self, x): return x class B(A): if True: def aaa(self, x): return super().aaa(x) b = B() assert b.aaa(0) == 0 def funcattrs(**kwds): def decorate(func): func.__dict__.update(kwds) return func return decorate class C(object): @funcattrs(abc=1, xyz="haha") @funcattrs(booh=42) def foo(self): return 42 assert C().foo() == 42 assert C.foo.abc == 1 assert C.foo.xyz == "haha" assert C.foo.booh == 42 def recur(change_namespace=0): if change_namespace: x = 2 return else: x = 1 def nested(): return x recur(change_namespace=1) return nested() assert recur() == 1 import time target = time.struct_time([1970, 1, 1, 0, 0, 0, 3, 1, 0]) assert time.gmtime(0).args == target.args target = time.struct_time([1970, 1, 1, 0, 1, 40, 3, 1, 0]) assert time.gmtime(100).args == target.args target = time.struct_time([2001, 9, 9, 1, 46, 40, 6, 252, 0]) assert time.gmtime(1000000000).args == target.args try: time.asctime(1) except TypeError: pass except: ValueError("Should have raised TypeError") try: time.asctime((1, 2, 3, 4)) except TypeError: pass except: ValueError("Should have raised TypeError") assert time.asctime(time.gmtime(0)) == 'Thu Jan 1 00:00:00 1970' tup = tuple(time.gmtime(0).args) assert time.asctime(tup) == 'Thu Jan 1 00:00:00 1970' codeobj = compile("3 + 4", "<example>", "eval") assert eval(codeobj) == 7 x = 7 codeobj = compile("x + 4", "<example>", "eval") assert eval(codeobj) == 11 import types try: raise ValueError except ValueError: tb = sys.exc_info()[2] assert isinstance(tb, types.TracebackType) assert repr(type(None)) == "<class 'NoneType'>" def f(): def g(): nonlocal t return t t = 1 return g assert f()() == 1 def f(): k = 1 def g(): def r(): nonlocal k return k + 1 return r() return g() assert f() == 2 class X: def __hash__(self): return hash(1.0) def __eq__(self, other): return other == 1 a = {1: 'a', X(): 'b'} assert a == {1: 'b'} assert X() in a assert a[X()] == 'b' class X: def __hash__(self): return hash('u') a = {'u': 'a', X(): 'b'} assert set(a.values()) == {'a', 'b'} assert not X() in a b = {'u': 'a'} assert not X() in b class X: def __hash__(self): return hash('u') def __eq__(self, other): return other == 'u' a = {'u': 'a', X(): 'b'} assert a == {'u': 'b'} assert X() in a assert a[X()] == 'b' x = [1, 2, 3] assert sum(-y for y in x) == -6 source = [0, 1, 2, 3] total = sum(source.pop() for _ in range(len(source))) assert total == 6, "expected 6 but instead was %d" % total ModuleType = type(sys) foo = ModuleType("foo", "foodoc") assert foo.__name__ == "foo" assert foo.__doc__ == "foodoc" def f(z): z += 1 return z x = 1.0 assert x != f(x) for x in range(0x7ffffff0, 0x8000000f): assert x & x == x, "%s & %s == %s" % (hex(x), hex(x), hex(x & x)) assert x | x == x, "%s | %s == %s" % (hex(x), hex(x), hex(x | x)) for x in range(0x17ffffff0, 0x17fffffff): assert x & x == x, "%s & %s == %s" % (hex(x), hex(x), hex(x & x)) assert x | x == x, "%s | %s == %s" % (hex(x), hex(x), hex(x | x)) a = 5 assert globals().get('a') == 5 class Cmp: def __init__(self,arg): self.arg = arg def __repr__(self): return '<Cmp %s>' % self.arg def __eq__(self, other): return self.arg == other a = Cmp(1) b = Cmp(1) assert a == b assert not (a != b) class Test: @property def clicked(self): return self.func @clicked.setter def clicked(self, callback): self.func = callback t = Test() t.clicked = lambda x: x+7 assert t.clicked(7) == 14 x = [a.strip() for a in [ " foo ", " bar ", ]] assert x == ['foo', 'bar'] assert 2 ** 3 ** 4 == 2417851639229258349412352 a = [1, 2, 3] b, *c = a assert c == [2, 3] class A: __slots__ = 'x', A.x a = A() a.x = 9 assert a.x == 9 try: a.y = 0 except AttributeError: pass except: raise import base64 b = bytearray(b'<Z\x00N') b64 = base64.b64encode( b ) assert b64 == b'PFoATg==' buf = bytearray(b'EZ\x86\xdd\xabN\x86\xdd\xabNE[\x86\xdd\xabN\x86\xdd\xabN') b64 = base64.b64encode( buf ) assert b64 == b'RVqG3atOht2rTkVbht2rTobdq04=' x = 0 if False: x += 2 x += 3 for n in range(2): x += 1 x += 1 assert x == 4 for n in range(5): pass assert n == 4 assert type((1,) * 2) == tuple n = 1 for n in range(n): pass assert n == 0 t = 1, 2 assertRaises(AttributeError, getattr, t, "__setitem__") x = 1 assertRaises(AttributeError, setattr, x, '__add__', 1) assertRaises(AttributeError, setattr, x, 'y', 1) assert 4 in range(5) assert 4 in range(0, 5, 2) assert not 1 in range(0, 5, 2) assert 1 in range(10, 0, -1) assert 10 in range(10, 0, -1) assert not 1 in range(10, 0, -2) assert not 0 in range(10, 0, -2) class Test(): def __pos__(self): return 'plus' def __neg__(self): return 'minus' def __invert__(self): return 'invert' a = Test() assert +a == 'plus' assert -a == 'minus' assert ~a == 'invert' for x in 1, 1.2, 1 + 2j, 2 ** 54: assert +x == x assert -True == -1 assert eval("-1") == -1 a = 0000 b = int(00) c = 000 + 1 d = 0000 * 10 assert a == 0 assert b == 0 assert c == 1 assert d == 0 for a, *b in [[1, 2, 3]]: assert a == 1 assert b == [2, 3] def f(): a += 1 assertRaises(UnboundLocalError, f) def f(): a = a + 1 assertRaises(UnboundLocalError, f) a = 3 def plus(): print(a) a = 7 assertRaises(UnboundLocalError, plus) def plus(): global axd print(axd) assertRaises(NameError, plus) def f(): for i in 1, 2: if i == 2: x = a else: a = 1 return x assert f() == 1 def f(): for i in 1, 2: if i == 2: a += 1 else: a = 1 return a assert f() == 2 def f(): "hello"("3") assertRaises(TypeError, f) try: from .spam import eggs except SystemError as ie: assert str(ie) == \ "Parent module '' not loaded, cannot perform relative import" a76gf = 0 def f(): a76gf = 1 def g(): nonlocal a76gf a76gf = a76gf + 1 return a76gf assert g() == 2 f() def f(): a2fx = 1 def g(): nonlocal a2fx a2fx = 2 g() assert a2fx == 2 f() from abc import ABCMeta, abstractmethod class interface(metaclass=ABCMeta): @abstractmethod def test(self): return class implementation(interface): def test(self): return i = implementation() assert isinstance(i, implementation) assert isinstance(i, interface) class A(metaclass=ABCMeta): @abstractmethod def foo(self): pass assertRaises(TypeError, A) # same for subclasses class B(A): pass assertRaises(TypeError, B) # class C overrides foo so it has no abstract method, it can have instances class C(A): def foo(self): return 42 assert C().foo() == 42 # issue 348 x, y = y, x = 2, 3 assert x, y == (3, 2) # issue 355 class kk: def __init__(self, enum): pass lambda enum: enum def foo(enum): pass # issue 360 assert "André".isidentifier() # issue 363 a = float('nan') b = 1 c = a - b # issue 371 assert (not 'x' in ['x', 'y'] and 2 == 1) == False # issue 375 def f(): "test" %3 assertRaises(TypeError, f) # issues 387 and 388 class A(): pass class B(): pass a1 = A() a2 = A() assert hash(A) != hash(B) assert hash(A) != hash(a1) assert hash(A) != hash(a2) class A(): pass class B(): pass d = {A: "class A"} def test(): d[B] assertRaises(KeyError, test) # issue 389 gen = (n * n for n in range(10)) assert list(gen) == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] assert list(gen) == [] # issue 391 def f(): ["a"] + 5 assertRaises(TypeError, f) # sum with booleans assert sum([True, False]) == 1 assert 1.2 + True == 2.2 # issue #392 class A: def __init__(self): self.b = [1 for n in range(10)] self.b[3] = 0 eval = A() assert [c for c in range(10) if eval.b[c] == 0] == [3] # restore original "eval" eval = __builtins__.eval # issue 394 import base64 b = b"\x7F\x7B\xED\x96" b64 = base64.b64encode(b) assert b64 == b"f3vtlg==" newb = base64.b64decode(b64) assert newb == b e = base64.b64encode(b'data to encode') assert e == b"ZGF0YSB0byBlbmNvZGU=" assert base64.b64decode(e, validate=True) == b'data to encode' # issue 412 assert not True and not False or True assert False and not False or True assert False and not False or not False assert False and not True or True assert False and not True or not False assert not True and not True or True assert not True and not True or not False assert not True and not False or True assert not True and not False or not False # set attribute __doc__ of a function def test(): pass assert test.__doc__ == """original text""" test.__doc__ = "new text" assert test.__doc__ == "new text" # issue 443 class Pepe: def __getitem__(self, arg): return arg pepe = Pepe() assert pepe[0:1] == slice(0, 1) assert pepe[1, 0, 0:10:2] == (1, 0, slice(0, 10, 2)) assert pepe[0, 0:10:1] == (0, slice(0, 10, 1)) assert pepe[0, 0] == (0, 0) assert pepe[0, :] == (0, slice(None, None, None)) assert pepe[0, 1, 1, 1, 2, 3, 4, :] == \ (0, 1, 1, 1, 2, 3, 4, slice(None, None, None)) # issue 448 d = {0 : [1]} d[0] += [2] assert d == {0: [1, 2]} # issue 449 a = [[1]] a[0] += [2] assert a == [[1, 2]] # issue 450 assert True == True assert True != False assert False == False assert not (True == None) assert True != None # issue 465 class A: def __init__(self, value): self.value = value def __enter__(self): return self def __exit__(self, *args): pass def __str__(self): return str(self.value) a = A(1) with a as x: assert str(x) == "1" with A(2) as x: assert str(x) == "2" with A(3): pass # ternary is an expression a = eval('1 if 3 == 4 else 0') assert a == 0 # issue 480 def test(throw=True): pass test(throw=False) # issue 485 class Test: pass a = Test() b = Test() d = {a: 1, b: 2} assert d[a] == 1 assert d[b] == 2 # issue 481 flag = False def extend_instance(obj, cls): base_cls = obj.__class__ base_cls_name = obj.__class__.__name__ obj.__class__ = type("Extended"+base_cls_name, (cls,base_cls),{}) class Mixin(object): def __setattr__(self, name, value): if not name.startswith('_'): #print("Mixin setting", name, "to", value, super().__setattr__) super().__setattr__(name,value) else: super().__setattr__(name,value) class Test: def __init__(self): self._dct={} def __setattr__(self, name, value): global flag if not name.startswith('_'): self._dct[name] = value flag = True else: super().__setattr__(name, value) def __getattr__(self): if not name.startswith('_'): return self._dct[name] else: return getattr(self, name) t = Test() extend_instance(t, Mixin) t.c = 20 assert flag # bug in comprehensions a = [1, 2] b = [3, 4] odd = [x for x in a + b if x % 2] assert odd == [1, 3] # issue 506 class TestRound: def __round__(self, n=None): if n is None: return 10 else: return n tr = TestRound() assert type(round(3.0)) == int, \ "Round called without second argument should return int" assert type(round(3.1111, 3)) == float, \ "Round called without second argument should return same type as first arg" assert type(round(3.0, 0)) == float, \ "Round called without second argument should return same type as first arg" assert round(3.1111, 3) == 3.111 assert type(round(0, 3)) == int, \ "Round called without second argument should return same type as first arg" assert round(tr, 3) == 3, \ "Round called on obj with __round__ method should use it" assert round(tr) == 10, \ "Round called on obj with __round__ method should use it" # Bankers rounding (issue #513) assert round(-9.5) == -10 assert round(-0.5) == 0 assert round(2.5) == 2 assert round(9.5) == 10 assert round(100.5) == 100 # issue 523 borders_distance = [(-5, 0), (4, 0), (0, -3), (0, 4)] mx, my = min(borders_distance, key=lambda m: abs(m[0] + m[1])) assert (mx, my) == (0, -3) # issue 500 order = [] try: order.append('try') except KeyError as exc: order.append('except') else: order.append('else') finally: order.append('finally') assert order == ['try', 'else', 'finally'] # issue 542 def test(*args): return args a01 = [0, 1] assert test(*a01, 2, 3) == (0, 1, 2, 3) args = a01 + [2, 3] assert test(*args) == (0, 1, 2, 3) def test(**kw): return kw d1 = {'x': 2} d2 = {'y': 3} assert test(u=1, **d1, **d2) == {'u': 1, 'x': 2, 'y': 3} # issue 545 k = 3 nb = 0 for k in range(k): nb += 1 assert nb == 3 # issue 547 a = (1,) b = a a += (2,) assert b == (1,) # issue 549 a = 5.0 a **= 2 assert a == 25.0 a //= 25 assert a == 1.0 # issue 550 assert True & False is False assert True | False is True assert True ^ False is True # issue 551 y = -1; assert y == -1 # issue 553 sxz = 'abc' assert [sxz for sxz in sxz] == ['a', 'b', 'c'] assert {sxz for sxz in sxz} == {'a', 'b', 'c'} assert {sxz: sxz for sxz in sxz} == {'a': 'a', 'b': 'b', 'c': 'c'} g = (sxz for sxz in sxz) assert list(g) == ['a', 'b', 'c'] # issue 554 nbcalls = 0 def f(): global nbcalls nbcalls += 1 def g(unused_arg=f()): pass assert nbcalls == 1 # issue 499 data = [1, 2, 3] data = (item for item in data) assert list(data) == [1, 2, 3] # issue 557 from math import sin, log class N: def __float__(self): return 42.0 num = N() assert sin(num) == -0.9165215479156338 assert log(num) == 3.7376696182833684 # issue 560 class Base: @classmethod def test(cls): return cls class Derived(Base): def __init__(self): pass assert Derived.test() == Derived d = Derived() assert d.test() == Derived # issue 563 assert str(False + False) == '0' assert False + True == 1 assert True + True == 2 # issue 572: sort should be stable words = ["Bed", "Axe", "Cat", "Court", "Axle", "Beer"] words.sort() words.sort(key=len, reverse=True) assert words == ['Court', 'Axle', 'Beer', 'Axe', 'Bed', 'Cat'] # chained comparisons x = 0 def impure(): global x x += 1 return x assert 0 < impure() <= 1 # issue 576 class Patched: def method(self, first="patched1", second="patched2"): return(first, second) class Patcher: def __init__(self): Patched.method = self.method # monkey patches with instantiated method def method(self, first="patcher1", second="patcher2"): return(first, second) Patched.method = Patcher.method # monkey patches with non instantiated method assert ("tester1", "patcher2") == Patched().method("tester1") Patcher() assert ("tester1", "patcher2") == Patched().method("tester1"), \ "instead returns %s %s" % Patched().method() # issue 578 try: raise 1 except TypeError: pass class A: pass try: raise A() except TypeError: pass def test(): return IOError() try: raise test() except IOError: pass # issue 582 def nothing(): a = lambda: 1 \ or 2 return a() assert nothing() == 1 # issue 584 try: from __future__ import non_existing_feature except SyntaxError: pass # issue 501 class Test: def __iter__(self): self._blocking = True yield self def test_yield(): b = yield from Test() return b test = [] for b in test_yield(): test.append(b) assert test[0]._blocking is True # issue 588 def yoba(a, b): return a + b assertRaises(TypeError, yoba, 1, 2, 3) # issue 592 assert pow(97, 1351, 723) == 385 # issue 595 assert float(True) == 1.0 # issue 598 class A(object): __slots__ = "attr" def __init__(self, attr=0): self.attr = attr a = A() # issue 600 class A: def __eq__(self, other): return True class B(A): def __eq__(self, other): return False # check that B.__eq__ is used because B is a subclass of A assert A() != B() a = A() b = B() assert a != b assert b != a # issue 604 class StopCompares: def __eq__(self, other): return 1 / 0 checkfirst = list([1, StopCompares()]) assert(1 in checkfirst) # issue 615 class A: spam = 5 assertRaises(TypeError, A, 5) try: class A(spam="foo"): pass raise AssertionError("should have raised TypeError") except TypeError: pass # issue 619 from browser.html import H2 class _ElementMixIn: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._sargs = [] self._kargs = {} def mytest(self): self._sargs.append(5) def mytest2(self): self._kargs[5] = '5' kls = type('h2', (_ElementMixIn, H2,), {}) x = kls() x.mytest() assert x._sargs == [5] x.mytest2() assert x._kargs[5] == '5' # issue 649 class test: def test(self): return 1 assert test().test() == 1 # issue 658 kk = [i for i in [ 1, # 1st quadrant 2 ]] assert kk == [1, 2] kk = (i for i in [ 1, # a comment 2 ]) assert list(kk) == [1, 2] # issue 663 a = {} a[5] = b = 0 assert a[5] == 0 # issue 659 class A: def x(self): pass assert A().x.__name__ == "x" assert A.x.__name__ == "x" # issue 669 assert 0.1 is 0.1 assert not(1 is 1.0) # issue 673 class A: __z = 7 def __init__(self): self.__x = 20 a = A() assert a._A__x == 20 assert a._A__z == 7 class Mapping: def __init__(self, iterable): self.items_list = [] self.__update(iterable) def update(self, iterable): for item in iterable: self.items_list.append(item) __update = update # private copy of original update() method class MappingSubclass(Mapping): def update(self, keys, values): # provides new signature for update() # but does not break __init__() for item in zip(keys, values): self.items_list.append(item) mapping = Mapping(range(3)) mapping.update(range(7, 10)) assert mapping.items_list == [0, 1, 2, 7, 8, 9] map2 = MappingSubclass(range(3)) map2.update(['a', 'b'], [8, 9]) assert map2.items_list == [0, 1, 2, ('a', 8), ('b', 9)] class B: def __print(self, name): return name assert B()._B__print('ok') == 'ok' # issue 680 class A: def __getattribute__(self, name): return super().__getattribute__(name) def test(self): return 'test !' assert A().test() == "test !" # issue 681 found = [x for x in ['a', 'b', 'c'] if x and not x.startswith('-')][-1] assert found == 'c' assert [0, 1][-1] == 1 assert {-1: 'a'}[-1] == 'a' # issue 691 class C(object): pass c1 = C() c1.x = 42 assert c1.__dict__['x'] == 42 c1.__dict__.clear() assert c1.__dict__ == {} class C(object): pass c2 = C() c2.x = 42 c2.__dict__ = dict() assert c2.__dict__ == {} try: c2.__dict__ = 6 except TypeError: pass # issue 699 def members(obj): for m in dir(obj): getattr(obj, m) members(int) class Foo: def foo(self): pass members(Foo) # issue 701 assert type((1, 2, 3)[:0]) == tuple assert type((1, 2, 3)[1:2:-1]) == tuple assert type((1, 2, 3)[0:2]) == tuple # generalised unpacking for function calls def f(*args, **kw): return args, kw res = f(3, *[1, 8], 5, y=2, **{'a': 0}, **{'z': 3}) assert res[0] == (3, 1, 8, 5) assert res[1] == {'y': 2, 'a': 0, 'z': 3} # issue 702 def f(): return try: f > 5 raise Exception("should have raised TypeError") except TypeError: pass try: min <= 'a' raise Exception("should have raised TypeError") except TypeError: pass import random try: random.random < 1 raise Exception("should have raised TypeError") except TypeError: pass class A: pass try: A < 'x' raise Exception("should have raised TypeError") except TypeError: pass # issue 729 head, *tail = 1, 2, 3 assert tail == [2, 3] # issue 743 def test(msg = 'a', e_type: int = 10): pass # issue 751 class Z: pass try: (10, Z()) <= (10, Z()) raise Exception("should have raised TypeError") except TypeError: pass try: a = [100, 100, 100, 100, 100, 70, 100, 100, 70, 70, 100, 70, 70, 70, 100, 70, 70, 100, 70, 70, 70, 70, 100, 70, 70, 70, 70, 70, 100, 70, 70, 70, 100, 70, 70, 70, 70, 70, 70, 100] b = [(v, Z()) for v in a] sorted(b, reverse=True) raise Exception("should have raised TypeError") except TypeError: pass # issue 753 # cf. https://github.com/mziccard/node-timsort/issues/14 a = [1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 0.5, 0.5, 1.0, 0.5, 1.0, 0.5, 0.5, 0.5, 0.6, 1.0] a.sort() for i in range(len(a) - 1): assert a[i] <= a[i + 1] # issue 755 assert '{}'.format(int) == "<class 'int'>" class C: pass assert '{}'.format(C) == "<class '__main__.C'>" import javascript assert javascript.jsobj2pyobj(javascript.NULL) is None undef = javascript.jsobj2pyobj(javascript.UNDEFINED) assert not undef # issue 760 class A(object): def __str__(self): return "an A" class B(A): def __repr__(self): return '<B>()' b = B() assert str(b) == "an A" # issue 761 class A: def __str__(self): return 'an A' assert '{0}'.format(A()) == 'an A' # issue 776 def f(): d = { a: b for k in keys if k not in ( "name", ) # comment } # issue 778 import os assertRaises(NotImplementedError, os.listdir) # issue 780 def g(): print(xtr) # should crash, of course def f(): xtr = 42 g() assertRaises(NameError, f) # issue 781 # can't call strings assertRaises(TypeError, 'a') assertRaises(TypeError, 'a', 1) assertRaises(TypeError, 'a', {'x': 1}) t = [1, 2] assertRaises(TypeError, t) assertRaises(TypeError, t, 1) assertRaises(TypeError, t, {'x': 1}) # can't call dicts d = {1: 'a'} assertRaises(TypeError,d) assertRaises(TypeError, d, 1) assertRaises(TypeError, d, {'x': 1}) class Greetings: default = None def hello(self): return "Hello!" _func_body = """\ def {name}(): if {obj} is None: {obj} = {init} return {obj}.{name}() """ def_str = _func_body.format(obj='Greetings.default', init='Greetings()', name="hello") exec(def_str, globals()) assert hello() == "Hello!" class L: def __init__(self): self._called = 0 def get_list(self): self._called += 1 return [0] l = L() for i in l.get_list(): pass assert l._called == 1 class A: pass class B(object): def __init__(self, *args, **kwargs): self.res = None def __setattr__(self, *args, **kwargs): res = None if len(args) == 2 and hasattr(self, args[0]): old = getattr(self, args[0]) new = args[1] res = super(B, self).__setattr__(*args, **kwargs) else: res = super(B, self).__setattr__(*args, **kwargs) return res class C(B,A): pass c = C() try: exec("a + b = 1") raise Exception("should have raised SyntaxError") except SyntaxError: pass class A: def __radd__(self, other): return 99 def __rmul__(self, other): return 100 assert [5] + A() == 99 assert [6] * A() == 100 titem__(self, val): return val t = ndarray() assert slice(1, 5, None) == slice(1, 5, None) assert t[1:5, 7] == (slice(1, 5, None), 7) def f(): print(10) assert f.__code__.co_code.startswith("function f") class A: pass global_x = None def target(x=None): global global_x global_x = x obj_dict = A().__dict__ obj_dict['target_key'] = target obj_dict['target_key'](x='hello') assert global_x == 'hello' x = 0 class A: assert x == 0 def x(self): pass assert callable(x) def f(): if False: wxc = 0 else: print(wxc) assertRaises(UnboundLocalError, f) def g(): if False: vbn = 0 print(vbn) assertRaises(UnboundLocalError, f) import sys assert type(random) == type(sys) try: raise FileNotFoundError() except FloatingPointError: assert False except FileNotFoundError: assert sys.exc_info()[0] == FileNotFoundError class CustomException(Exception): pass try: raise Exception() except Exception: pass try: raise Exception except Exception: pass try: raise CustomException() except CustomException: pass try: raise CustomException except CustomException: pass try: raise Exception() except: (_, _, tb) = sys.exc_info() while tb: tb = tb.tb_next # PEP 448 assert dict(**{'x': 1}, y=2, **{'z': 3}) == {"x": 1, "y": 2, "z": 3} try: d = dict(**{'x': 1}, y=2, **{'z': 3, 'x': 9}) raise Exception("should have raised TypeError") except TypeError: pass r = range(2) t = *r, *range(2), 4 assert t == (0, 1, 0, 1, 4) t = [*range(4), 4] assert t == [0, 1, 2, 3, 4] assert {*range(4), 4} == {0, 1, 2, 3, 4} assert {*[0, 1], 2} == {0, 1, 2} assert {*(0, 1), 2} == {0, 1, 2} assert {4, *t} == {0, 1, 2, 3, 4} assert {'x': 1, **{'y': 2, 'z': 3}} == {'x': 1, 'y': 2, 'z': 3} assert {'x': 1, **{'x': 2}} == {'x': 2} assert {**{'x': 2}, 'x': 1} == {'x': 1} assertRaises(SyntaxError, exec, "d = {'x': 1, *[1]}") assertRaises(SyntaxError, exec, "d = {'x', **{'y': 1}}") assertRaises(SyntaxError, exec, "d = {*[1], 'x': 2}") assertRaises(SyntaxError, exec, "d = {**{'x': 1}, 2}") assertRaises(SyntaxError, exec, "t = *range(4)") # issue 909 t1 = [*[1]] assert t1 == [1] t2 = [*(1, 2)] assert t2 == [1, 2] # issue 854 class A(object): def __init__(self): self.x = 0 def f(): pass class B(A): pass assert 'f' in dir(A) assert 'f' in dir(B) assert 'x' in dir(A()) assert 'x' in dir(B()) # issue 869 class A(object): def __init__(self): self.value = 0 def __iadd__(self, val): self.value += val return self.value class B(object): def __init__(self): self.a = A() b = B() b.a += 10 assert b.a == 10 # issue 873 str(globals()) # issue 883 for _ in range(2): for _ in range(2): pass # issue 900 "".format(**globals()) # issue 901 : _jsre's SRE_Pattern lacking methods: .sub(), .subn(), .split(), and .fullmatch() import _jsre as re regex = re.compile('a|b') assert regex.match('ab') is not None assert regex.search(' ab') is not None assert regex.findall('ab') == ['a', 'b'] def switch(m): return 'a' if m.group(0) == 'b' else 'b' assert regex.sub(switch, 'ba') == 'ab' v = 1 del v try: print(v) raise Exception("should have raised NameError") except NameError: pass hello = {"a": 1, "b": 2} del(hello["a"]) assert len(hello) == 1 class A(): def __lt__(self, other): return 1 def __gt__(self, other): return 2 assert (1 < A()) == 2 assert (A() < 1) == 1 assert not (2 == "2") assert 2 != "2" assert not ("2" == 2) assert "2" != 2 try: 2 <= "2" except TypeError as exc: assert "<=" in exc.args[0] class A: def __bool__(self): raise TypeError("Not a bool!") try: if A(): pass raise Exception("should have raised TypeError") except TypeError as exc: assert exc.args[0] == "Not a bool!" try: bool(A()) raise Exception("should have raised TypeError") except TypeError as exc: assert exc.args[0] == "Not a bool!" assertRaises(SyntaxError, lambda: exec('a.foo = x += 3', {'a': A(), 'x': 10})) assertRaises(SyntaxError, lambda: exec('x = a.foo += 3', {'a': A(), 'x': 10})) src = """def f(): pass f(): """ assertRaises(SyntaxError, exec, src) try: exec("a = +25, b = 25") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "cannot assign to operator" class A(object): def __getattr__(self, name): return 'A-%s' % name try: A.foo raise Exception("should have raised AttributeError") except AttributeError: pass class A(object): pass a = A() a.__dict__['_x'] = {1: 2} a._x[3] = 4 assert len(a._x) == 2 try: exec("x += 1, y = 2") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0].startswith("invalid syntax") adk = 4 def f(): if False: adk = 1 else: print(adk) assertRaises(UnboundLocalError, f) try: exec("x + x += 10") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "cannot assign to operator" assertRaises(SyntaxError, exec, "if:x=2") assertRaises(SyntaxError, exec, "while:x=2") assertRaises(SyntaxError, exec, "for x in:x") try: exec("x = 400 - a, y = 400 - b") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "cannot assign to operator" l = [1, 2, 3] try: l[:,:] raise Exception("should have raised TypeError") except TypeError: pass def f(): global x985 print(x985) def g(): global x985 x985 = 1 assertRaises(NameError, f) assert [x for x in range(10) if x % 2 if x % 3] == [1, 5, 7] result = [] for x, in [(1,), (2,), (3,)]: result.append(x) assert result == [1, 2, 3] assert [x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False)] == [True] def test_yield_in_comprehensions(self): def g2(): [x for x in [(yield 1)]] assertRaises(SyntaxError, exec, "x += y += 5") def f(): global xaz25 xaz25 += 1 xaz25 = 8 f() assert xaz25 == 9 class Foo: bar = 1 foo = Foo() assertRaises(AttributeError, delattr, foo, 'bar') class C: def __init__(self): self._x = None self.count = 0 def getx(self): return self._x def setx(self, value): self._x = value def delx(self): self.count += 1 del self._x x = property(getx, setx, delx, "I'm the 'x' property.") c = C() delattr(c, "x") assert c.count == 1 # setting __defaults__ to functions (issue #1053) def ftrk(x, y=5): return x + y assert ftrk(1) == 6 ftrk.__defaults__ = (4, 1) assert ftrk(1) == 2 assert ftrk() == 5 ftrk.__defaults__ = () assertRaises(TypeError, ftrk) ftrk.__defaults__ = (4, 1) assert ftrk(1) == 2 assert ftrk() == 5 ftrk.__defaults__ = None assertRaises(TypeError, ftrk) def g(): def h(x, y): return x + y h.__defaults__ = (3,) return h assert g()(1) == 4 class A: def ftrk2(self, x): return x + 1 a = A() assert a.ftrk2(2) == 3 A.ftrk2.__defaults__ = (2,) assert a.ftrk2() == 3, a.ftrk2() class B: def __new__(cls, a): obj = object.__new__(cls) obj.a = a return obj def show(self): return self.a b = B(2) assert b.show() == 2 B.__new__.__defaults__ = (8,) b2 = B() assert b2.show() == 8 # issue 1059 import os try: issues_py_dir = os.path.dirname(__file__) z_txt_path = os.path.join(issues_py_dir, "z.txt") except NameError: z_txt_path = "z.txt" with open(z_txt_path, encoding="utf-8") as f: t = [line for line in f] assert len(t) == 3 with open(z_txt_path, encoding="utf-8") as f: assert f.readlines() == t # issue 1063 class A(object): pass y = [1, 2, 3] x = A() t = [] for x.foo in y: t.append(x.foo) assert t == y # issue 1062 assertRaises(SyntaxError, exec, "x[]") assertRaises(SyntaxError, exec, "x{}") # issue 1068 class Class(): def method(self): assert "__class__" not in Class.method.__code__.co_varnames return __class__.__name__ assert Class().method() == "Class" def f(): print(__class__) assertRaises(NameError, f) # issue 1085 expected = [ (0, 10, 1), (0, 10, 1), (0, 1, 1), (0, 1, 1), (1, 10, 1), (1, 10, 1), (1, 1, 1), (1, 1, 1) ] tmp = (None, 1) for i in range(8): target = slice( tmp[bool(i & 4)], tmp[bool(i & 2)], tmp[bool(i & 1)] ) assert target.indices(10) == expected[i] test_pool = [((85, None, None), 9, (9, 9, 1)), ((-32, None, None), 84, (52, 84, 1)), ((None, -40, None), 97, (0, 57, 1)), ((-89, None, -5), 86, (-1, -1, -5)), ((-92, -10, None), 0, (0, 0, 1)), ((99, None, None), 22, (22, 22, 1)), ((-85, -90, 8), 60, (0, 0, 8)), ((76, None, -9), 10, (9, -1, -9)), ((None, None, 8), 54, (0, 54, 8)), ((None, -86, None), 71, (0, 0, 1)), ((None, -83, None), 4, (0, 0, 1)), ((-78, None, -7), 27, (-1, -1, -7)), ((None, 3, None), 71, (0, 3, 1)), ((91, None, 3), 15, (15, 15, 3)), ((None, None, 2), 35, (0, 35, 2)), ((None, None, None), 46, (0, 46, 1)), ((None, 94, None), 64, (0, 64, 1)), ((6, None, 2), 57, (6, 57, 2)), ((43, None, 9), 70, (43, 70, 9)), ((83, None, None), 93, (83, 93, 1)), ((None, None, -7), 37, (36, -1, -7)), ((None, -27, None), 70, (0, 43, 1)), ((None, -22, None), 89, (0, 67, 1)), ((-79, -39, 9), 20, (0, 0, 9)), ((None, 83, None), 89, (0, 83, 1)), ((96, None, None), 8, (8, 8, 1)), ((None, -37, None), 35, (0, 0, 1)), ((None, -62, -2), 78, (77, 16, -2)), ((-31, -37, 3), 9, (0, 0, 3)), ((None, None, None), 92, (0, 92, 1)), ((35, 54, None), 10, (10, 10, 1)), ((-55, None, 7), 55, (0, 55, 7)), ((None, None, 7), 97, (0, 97, 7)), ((None, 92, None), 70, (0, 70, 1)), ((None, -37, None), 57, (0, 20, 1)), ((None, None, None), 71, (0, 71, 1)), ((-98, -76, -7), 10, (-1, -1, -7)), ((-90, 44, None), 66, (0, 44, 1)), ((None, None, 2), 16, (0, 16, 2)), ((61, -54, None), 35, (35, 0, 1)), ((4, -12, None), 36, (4, 24, 1)), ((None, 78, -7), 92, (91, 78, -7)), ((-48, None, 2), 47, (0, 47, 2)), ((-16, 55, None), 8, (0, 8, 1)), ((None, None, 1), 6, (0, 6, 1)), ((-73, None, None), 67, (0, 67, 1)), ((65, None, -1), 30, (29, -1, -1)), ((12, None, None), 61, (12, 61, 1)), ((33, None, None), 31, (31, 31, 1)), ((None, None, -3), 96, (95, -1, -3)), ((None, None, None), 15, (0, 15, 1)), ((19, -65, 8), 39, (19, 0, 8)), ((85, -4, 9), 40, (40, 36, 9)), ((-82, None, None), 6, (0, 6, 1)), ((29, None, 6), 94, (29, 94, 6)), ((None, 14, -2), 63, (62, 14, -2)), ((None, 15, 6), 30, (0, 15, 6)), ((None, None, None), 22, (0, 22, 1)), ((None, None, 1), 88, (0, 88, 1)), ((87, -7, None), 47, (47, 40, 1)), ((None, -12, 8), 68, (0, 56, 8)), ((-70, None, 8), 1, (0, 1, 8)), ((-21, None, 1), 24, (3, 24, 1)), ((None, None, None), 54, (0, 54, 1)), ((None, None, 9), 28, (0, 28, 9)), ((31, -25, None), 13, (13, 0, 1)), ((16, 33, None), 63, (16, 33, 1)), ((None, 86, 3), 58, (0, 58, 3)), ((None, -63, -1), 68, (67, 5, -1)), ((None, 7, -3), 76, (75, 7, -3)), ((92, 24, 7), 76, (76, 24, 7)), ((3, 65, None), 78, (3, 65, 1)), ((None, None, -9), 45, (44, -1, -9)), ((None, 85, None), 21, (0, 21, 1)), ((77, None, 1), 33, (33, 33, 1)), ((None, None, None), 81, (0, 81, 1)), ((-2, 50, 6), 52, (50, 50, 6)), ((-39, 6, 2), 89, (50, 6, 2)), ((None, -26, None), 15, (0, 0, 1)), ((66, None, -1), 98, (66, -1, -1)), ((None, None, None), 37, (0, 37, 1)), ((3, -48, None), 14, (3, 0, 1)), ((None, 84, None), 12, (0, 12, 1)), ((79, 87, -2), 72, (71, 71, -2)), ((None, -97, -7), 68, (67, -1, -7)), ((None, 62, None), 86, (0, 62, 1)), ((-54, None, 3), 71, (17, 71, 3)), ((77, None, None), 78, (77, 78, 1)), ((None, None, -7), 87, (86, -1, -7)), ((None, None, None), 59, (0, 59, 1)), ((None, -24, None), 15, (0, 0, 1)), ((None, None, 7), 72, (0, 72, 7)), ((None, None, 2), 79, (0, 79, 2)), ((-50, None, None), 4, (0, 4, 1)), ((None, -97, -5), 68, (67, -1, -5)), ((22, None, None), 67, (22, 67, 1)), ((-72, None, -2), 93, (21, -1, -2)), ((8, None, -6), 88, (8, -1, -6)), ((-53, 31, -6), 0, (-1, -1, -6)), ((None, None, None), 0, (0, 0, 1))] for args, cut, res in test_pool: test = slice(*args) res_test = test.indices(cut) assert res == res_test, \ '{test}.indices({cut}) should be {res}, not {res_test}'.format(**locals()) # too many positional arguments def f(a, b, *, x=3): print(a, b, x) assertRaises(TypeError, f, 1, 2, 3) # issue 1122 class A(Exception): pass class B(object): def __getattr__(self, attr): raise A() ok = False try: b = B() b.attr except A: ok = True except: pass assert(ok) # issue 1125 from typing import Union row = Union[int, str] def do() -> None: a: row = 4 do() # issue 1133 try: set except NameError: from sets import Set as set if False: set = list assert set([1, 2]) == {1, 2} # issue 1209 assertRaises(SyntaxError, exec, "x:+=1") # issue 1210 assertRaises(SyntaxError, exec, r"\\") assertRaises(SyntaxError, exec, r"\\\n") assertRaises(SyntaxError, exec, "def f():\n \\\\") assertRaises(SyntaxError, exec, "def f():\n \\\\\n") # issue 1229 class A: def __str__(self): return "real str" a = A() assert str(a) == "real str" a.__str__ = lambda : "fake str" assert str(a) == "real str" # issue 1233 for x1233 in range(0): pass assertRaises(NameError, exec, "x1233") # issue 1243 assertRaises(SyntaxError, exec, """for i in range(1): f(), = 0""") # issue 1247 assertRaises(SyntaxError, exec, """def f(): return x += 1""") # issue 1248 def f(): x += 1 # issue 1251 assertRaises(SyntaxError, eval, '\\\n') # issue 1253 assertRaises(UnboundLocalError, exec, """x = 1 def f(): (((((x))))) += 1 f() """) # issue 1254 assertRaises(SyntaxError, exec, """def f(): print('hi') f(*)""") assertRaises(SyntaxError, exec, """def f(): print('hi') f(*, 1)""") assertRaises(SyntaxError, exec, """def f(x, **): print('hi') f(7)""") assertRaises(SyntaxError, exec, """def f(x, *): print('hi') f(7)""") # issue 1264 class TestDescriptor: counter = 0 def __set_name__(self, owner, name): TestDescriptor.counter += 1 class TestObject: my_descriptor = TestDescriptor() assert TestDescriptor.counter == 1 # issue 1273 lambda x, y, *, k=20: x+y+k lambda *args: args l6 = lambda x, y, *, k=20: x+y+k assert l6(3, 4) == 27 assert l6(3, 4, k=1) == 8 assertRaises(TypeError, l6, 1, 2, 3) l16 = lambda *, b,: b assertRaises(TypeError, l16, 10) assert l16(b=2) == 2 assertRaises(TypeError, l16, 5) l19 = lambda a, *, b,: a + b assert l19(8, b=10) == 18 assertRaises(TypeError, l19, 5) l22 = lambda *, b, **kwds,: b assertRaises(TypeError, l22, 1) assert l22(b=2) == 2 l24 = lambda a, *, b, **kwds,: (a + b, kwds) assert l24(1, b=2, c=24) == (3, {'c': 24}) # issue 1276 class A: pass x = A() x.a = 1 try: exec("(x.a < 2) += 100") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "'comparison' is an illegal expression for augmented assignment" try: exec("(x.a * 2) += 100") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "'operator' is an illegal expression for augmented assignment" # issue 1278 import textwrap assert textwrap.wrap('1234 123', width=5) == ['1234', '123'] assert textwrap.wrap('12345 123', width=5) == ['12345', '123'] assert textwrap.wrap('123456 123', width=5, break_long_words=False) == \ ['123456', '123'] # issue 1286 assertRaises(ZeroDivisionError, tuple, (1/0 for n in range(10))) def zde1(): {1 / 0 for n in range(10)} assertRaises(ZeroDivisionError, zde1) def zde2(): sum(1 / 0 for n in range(10)) assertRaises(ZeroDivisionError, zde2) def zde3(): [1 / 0 for n in range(10)] assertRaises(ZeroDivisionError, zde3) def zde4(): {n: 1 / 0 for n in range(10)} assertRaises(ZeroDivisionError, zde4) try: [1/0 for n in range(10)] raise AssertionError(f"should have raised ZeroDivisionError") except ZeroDivisionError: pass try: list(1/0 for n in range(10)) raise AssertionError(f"should have raised ZeroDivisionError") except ZeroDivisionError: pass try: {1/0 for n in range(10)} raise AssertionError(f"should have raised ZeroDivisionError") except ZeroDivisionError: pass try: {n: 1/0 for n in range(10)} raise AssertionError(f"should have raised ZeroDivisionError") except ZeroDivisionError: pass assertRaises(NameError, tuple, (d999['missing key'] for n in range(10))) # continuation lines inside comprehensions [n for \ n in range(10)] # change definition of range def range(n): return 'abc' t = [] for i in range(10): t.append(i) assert t == ['a', 'b', 'c'] # reset range to builtins range = __builtins__.range assert list(range(3)) == [0, 1, 2] # issue 1292 assertRaises(SyntaxError, exec, "for in range(1):\n pass") # issue 1297 assertRaises(SyntaxError, exec, "for i in range = 10") # ternary x = 1 if True is not None else 2, 3, 4 assert x == (1, 3, 4) # issue 1323 try: exit() raise AssertionError("should have raised SystemExit") except SystemExit: pass # issue 1331 assert [*{*['a', 'b', 'a']}] == ['a', 'b'] assert [*{'a': 1, 'b': 2}] == ['a', 'b'] # issue 1366 class A(object): def __str__(self): return "A __str__ output." class B(A): def __str__(self): return super().__str__() + " (from B)" x = A() assert str(x) == "A __str__ output." y = B() assert str(y) == "A __str__ output. (from B)" # issue 1445 ge = (*((i, i*2) for i in range(3)),) assert list(ge) == [(0, 0), (1, 2), (2, 4)] assert [*((i, i*2) for i in range(3))] == [(0, 0), (1, 2), (2, 4)] def matrix(s, types=None, char='|'): ds = ([j.strip() for j in i.split(char)] for i in s.strip().splitlines() if not i.strip().startswith(' if not types: yield from ds elif isinstance(types, (list, tuple)): for i in ds: yield [k(v or k()) for k, v in zip(types, i)] else: for i in ds: yield [types(v or types()) for v in i] m = [*matrix(''' #l | r 1 | 2 3 | 4 ''', (int, int))] assert m == [[1, 2], [3, 4]] # issue 1448 class Property: def __set_name__(self, owner, name): assert owner.__name__ == "Cat" class Cat: name = Property() def test(self): pass # issue 1461 def todict(obj): # dict if isinstance(obj, dict): return {k: todict(v) for k, v in obj.items()} # slot objects elif hasattr(obj, '__slots__'): return {k: todict(getattr(obj, k)) for k in obj.__slots__} # brython issue # something iterable, like tuples or lists elif hasattr(obj, "__iter__") and not isinstance(obj, str): return type(obj)(todict(v) for v in obj) # simple classes elif hasattr(obj, "__dict__"): return {k: todict(v) for k, v in obj.__dict__.items() if not callable(v) and not k.startswith('_')} # finally simple type else: return obj class Cat: __slots__ = ('name', 'age', 'breed') def __init__(self, name='', age=0, breed='test'): self.name = name self.age = age self.breed = breed def __repr__(self): return self.__class__.__name__ + '(' + ', '.join(f'{k}={getattr(self, k, None)!r}' for k in self.__slots__) + ')' assert str(todict(Cat(Cat()))) == \ "{'name': {'name': '', 'age': 0, 'breed': 'test'}, 'age': 0, 'breed': 'test'}" # issue 1472 try: exec(""" myvar = 1 result.append(myvar) def main_func(): nonlocal myvar myvar = 3 result.append(myvar) result.append("hello") main_func() result.append(myvar) """) raise AssertionError("should have raised SyntaxError") except SyntaxError as e: assert e.args[0] == "no binding for nonlocal 'myvar' found" result = [] exec(""" def f(): myvar = 1 result.append(myvar) def main_func(): nonlocal myvar myvar = 3 result.append(myvar) result.append("hello") main_func() result.append(myvar) f() """) assert result == [1, 3, 'hello', 3] result = [] exec(""" def f(): myvar = 1 result.append(myvar) def main_func(): global myvar myvar = 3 result.append(myvar) result.append("hello") main_func() result.append(myvar) f() """) assert result == [1, 3, 'hello', 1] result = [] def f(): exec(""" myvar = 1 result.append(myvar) def main_func(): global myvar myvar = 3 result.append(myvar) main_func() result.append(myvar) """) f() assert result == [1, 3, 3] # issue 1496 try: exec("not x = 1") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "cannot assign to operator" pass # issue 1501 class B: pass b = B() (a := b).c = 7 assert a.c == 7 try: exec("(a := b) = 1") raise Exception("should have raised SyntaxError") except SyntaxError: pass # issue 1509 funs = [(lambda i=i: i) for i in range(3)] t = [] for f in funs: t.append(f()) assert t == [0, 1, 2] # issue 1515 try: range[0, 8] raise Exception("should have raised TypeError") except TypeError as exc: assert exc.args[0] == "'type' object is not subscriptable" # issue 1529 assertRaises(SyntaxError, exec, "for x in in range(1):\n pass") # issue 1531 try: exec("x =* -1") raise Exception("should have raised SyntaxError") except SyntaxError as exc: assert exc.args[0] == "can't use starred expression here" def g(x): if isinstance(x, int): return x return [g(y) for y in x] assert g([1, [3, 4]]) == [1, [3, 4]] t = *['a', 'b'], assert t == ('a', 'b') s = *"cde", assert s == ('c', 'd', 'e') try: exec('t = *["a", "b"]') raise Exception("should have raised SyntaxError") except SyntaxError: pass try: exec('s = *"abcd"') raise Exception("should have raised SyntaxError") except SyntaxError: pass spam = ['spam'] x = *spam[0], assert x == ('s', 'p', 'a', 'm') class Spam: def __neg__(self): return 'spam' try: exec('x = *-Spam()') raise Exception("should have raised SyntaxError") except SyntaxError: pass x = *-Spam(), assert x == ('s', 'p', 'a', 'm') x = 1, *'two' assert x == (1, 't', 'w', 'o') y = *b'abc', assert y == (97, 98, 99) z = [*'spam'] assert z == ['s', 'p', 'a', 'm'] assert max([1, 2, 3], key=None) == 3 assert min([1, 2, 3], key=None) == 1 x = 0 y = 0 def f(): x = 1 y = 1 class C: assert x == 0 assert y == 1 x = 2 f() class Test(): def __enter__(self): return (42, 43) def __exit__(self, type, value, traceback): pass with Test() as (a, b): assert type(a) == int assert b == 43 assert repr(list[0]) == 'list[0]' english = ["one", "two", "three"] español = ["uno", "dos", "tres"] zip_iter = zip(english, español) eng, esp = next(zip_iter) assert eng == "one" assert esp == "uno" rest = [] for eng, esp in zip_iter: rest.append([eng, esp]) assert rest == [["two", "dos"], ["three", "tres"]] def add_seen_k(k, f=lambda x: 0): def inner(z): return k return inner a = add_seen_k(3) assert a(4) == 3 def fib_gen(): yield from [0, 1] a = fib_gen() next(a) for x, y in zip(a, fib_gen()): yield x + y fg = fib_gen() t = [next(fg) for _ in range(7)] assert t == [0, 1, 1, 2, 3, 5, 8] try: ()[0] raise Exception("should have raised IndexError") except IndexError as exc: assert exc.args[0] == "tuple index out of range" class A(): pass o = A() o.x = 1 t = [] def f(): for o.x in range(5): t.append(o.x) f() assert t == [0, 1, 2, 3, 4] class A(): pass t = [] def f(): o = A() o.x = 1 for o.x in range(5): t.append(o.x) f() assert t == [0, 1, 2, 3, 4] t = [] def f(): d = {} d['x'] = 1 for d['x'] in range(5): t.append(d['x']) f() assert t == [0, 1, 2, 3, 4] t = [] def f(): d = [1] for d[0] in range(5): t.append(d[0]) f() assert t == [0, 1, 2, 3, 4] x = 0 def f(): global x x -= -1 assert x == 1 f() def foo(a, b): c = 10 return foo.__code__.co_varnames assert foo(1, 2) == ('a', 'b', 'c') def f(): global x1671 try: print(x1671) raise Exception("should have raised NameError") except NameError: pass assertRaises(TypeError, int.__str__) assertRaises(TypeError, int.__str__, 1, 2) assert int.__str__('a') == "'a'" assert int.__str__(int) == "<class 'int'>" assertRaises(TypeError, int.__repr__, 'x') assert int.__repr__(7) == '7' assertRaises(TypeError, float.__str__) assertRaises(TypeError, float.__str__, 1.1, 2.2) assert float.__str__('a') == "'a'" assert float.__str__(int) == "<class 'int'>" assertRaises(TypeError, float.__repr__, 'x') assertRaises(TypeError, float.__repr__, 7) assert float.__repr__(7.6) == '7.6' def f(a1688): pass try: for a1688 in a1688.b: pass raise Exception("should have raised NameError") except NameError: pass assertRaises(IndentationError, exec, 'def f():') def get_foobar(): global foobar return foobar global foobar foobar = 'foobar' assert get_foobar() == "foobar" try: type() raise Exception('should have raised TypeError') except TypeError: pass assertRaises(SyntaxError, exec, '''for i in range(0): if True: f() += 1''') assertRaises(TypeError, chr, '') assertRaises(TypeError, chr, 'a') er = IndexError('hello') assert str(er) == 'hello' assert repr(er) == "IndexError('hello')" er = IndexError() assert str(er) == '' assert repr(er) == 'IndexError()' assertRaises(ValueError, exec, "list(zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True))") assertRaises(ValueError, exec, "list(zip(range(5), ['fee', 'fi', 'fo', 'fum'], strict=True))") assertRaises(SyntaxError, exec, '@x = 123') class MyRepr: def __init__(self): self.__repr__ = lambda: "obj" def __repr__(self): return "class" my_repr = MyRepr() assert str(my_repr.__repr__()) == 'obj' assert str(my_repr) == 'class' assert str(MyRepr.__repr__(my_repr)) == 'class' assert str(MyRepr().__repr__()) == 'obj' assertRaises(SyntaxError, exec, """x, if y > 4: pass""") assertRaises(SyntaxError, exec, """async def f(): await x = 1""") class Vector2: def __init__(self, a, b): self.x, self.y = a, b def clone(self): return Vector2(self.x, self.y) def __imul__(self, k): res = self.clone() res.x *= k res.y *= k return res vector = Vector2(1.5, 3.7) vector *= 25.7 assert (vector.x, vector.y) == (38.55, 95.09) def foo(constructor: bool): assert constructor is True foo(constructor=True) assert 0 != int lines = ["789/", "456*", "123-", "0.=+"] ((x for x in line) for line in lines) try: try: raise ValueError("inner") except Exception as e: raise ValueError("outer") from e except Exception as e: assert repr(e.__context__) == "ValueError('inner')" assertRaises(SyntaxError, exec, "(a, b = b, a)") try: exec("[i := i for i in range(5)]") except SyntaxError as exc: assert "cannot rebind" in exc.args[0] print('passed all tests')
true
true
f735f3e677422c352df9ec6eb83935b0d6721318
61
py
Python
pyranet/__init__.py
accasio/3DPyraNet
19f8d453ac5d089b5c5514ea744d895e6f8aee14
[ "MIT" ]
null
null
null
pyranet/__init__.py
accasio/3DPyraNet
19f8d453ac5d089b5c5514ea744d895e6f8aee14
[ "MIT" ]
null
null
null
pyranet/__init__.py
accasio/3DPyraNet
19f8d453ac5d089b5c5514ea744d895e6f8aee14
[ "MIT" ]
3
2019-09-11T10:01:29.000Z
2019-10-04T09:12:17.000Z
from . import layers from . import models from . import keras
20.333333
20
0.770492
from . import layers from . import models from . import keras
true
true
f735f482decbd6a9a885af3d4a25a4218a16a2f5
3,167
py
Python
aps/util/edit_region_mask.py
kmunve/APS
4c2f254ede83a3a311cbedc90c76db9ee367a000
[ "MIT" ]
null
null
null
aps/util/edit_region_mask.py
kmunve/APS
4c2f254ede83a3a311cbedc90c76db9ee367a000
[ "MIT" ]
1
2018-12-14T14:47:13.000Z
2018-12-14T14:47:13.000Z
aps/util/edit_region_mask.py
kmunve/APS
4c2f254ede83a3a311cbedc90c76db9ee367a000
[ "MIT" ]
null
null
null
from pathlib import Path import os import numpy as np import netCDF4 import matplotlib.pyplot as plt from aps.util.nc_index_by_coordinate import tunnel_fast # Creates the mask over the small regions of 20x20 km size def create_small_regions_mask(): p = Path(os.path.dirname(os.path.abspath(__file__))).parent nc_file = p / 'data' / 'terrain_parameters' / 'VarslingsOmr_2017.nc' nc = netCDF4.Dataset(nc_file, "a") # removes inconsistencies wrt fill_value in VarslingsOmr_2017 vr = nc.variables["VarslingsOmr_2017"] regions = vr[:] regions[regions == 0] = 65536 regions[regions == 65535] = 65536 vr[:] = regions # create mask based on dictionary with small regions to monitor regions_small = regions regions_small[regions > 3000] = 65536 # extend in each direction from center in km ext_x, ext_y = 10, 10 # dict over smaller region with Id and coordinates of center-point # VarslingsOmr have Id in range 3000-3999 - LokalOmr in 4000-4999 s_reg = {"Hemsedal": {"Id": 4001, "Lat": 60.95, "Lon": 8.28}, "Tyin": {"Id": 4002, "Lat": 61.255, "Lon": 8.2}, "Kattfjordeidet": {"Id": 4003, "Lat": 69.65, "Lon": 18.5}, "Lavangsdalen": {"Id": 4004, "Lat": 69.46, "Lon": 19.24}} for key in s_reg: y, x = get_xgeo_indicies(s_reg[key]['Lat'], s_reg[key]['Lon']) regions_small[y - ext_y : y + ext_y + 1, x - ext_x : x + ext_x + 1] = s_reg[key]['Id'] # set up new netCDF variable and attributes lr = nc.createVariable('LokalOmr_2018', np.int32, ('y', 'x')) lr.units = vr.units lr.long_name = 'Mindre test omraader' lr.missing_value = vr.missing_value lr.coordinates = vr.coordinates lr.grid_mapping = vr.grid_mapping lr.esri_pe_string = vr.esri_pe_string lr[:] = regions_small nc.close() print('Dataset is closed!') def add_lat_lon(): p = Path(os.path.dirname(os.path.abspath(__file__))).parent nc_file = p / 'data' / 'terrain_parameters' / 'VarslingsOmr_2017.nc' nc = netCDF4.Dataset(nc_file, "a") nc_ref = netCDF4.Dataset(r"\\hdata\grid\metdata\prognosis\meps\det\archive\2018\meps_det_pp_1km_20180127T00Z.nc", "r") lat_ref = nc_ref.variables['lat'] lon_ref = nc_ref.variables['lon'] lat = nc.createVariable('lat', np.float64, ('y', 'x')) lat.units = lat_ref.units lat.standard_name = lat_ref.standard_name lat.long_name = lat_ref.long_name lon = nc.createVariable('lon', np.float64, ('y', 'x')) lon.units = lon_ref.units lon.standard_name = lon_ref.standard_name lon.long_name = lon_ref.long_name nc.close() nc_ref.close() def get_xgeo_indicies(lat, lon): # region mask is flipped up-down with regard to MET-data in netCDF files y_max = 1550 nc = netCDF4.Dataset(r"\\hdata\grid\metdata\prognosis\meps\det\archive\2018\meps_det_pp_1km_20180127T00Z.nc", "r") y, x = tunnel_fast(nc.variables['lat'], nc.variables['lon'], lat, lon) return y_max-y, x if __name__ == "__main__": print("BLING BLING") #y, x = get_xgeo_indicies(60.95, 8.28); print(y, x) #create_small_regions_mask() add_lat_lon()
33.691489
122
0.663088
from pathlib import Path import os import numpy as np import netCDF4 import matplotlib.pyplot as plt from aps.util.nc_index_by_coordinate import tunnel_fast def create_small_regions_mask(): p = Path(os.path.dirname(os.path.abspath(__file__))).parent nc_file = p / 'data' / 'terrain_parameters' / 'VarslingsOmr_2017.nc' nc = netCDF4.Dataset(nc_file, "a") vr = nc.variables["VarslingsOmr_2017"] regions = vr[:] regions[regions == 0] = 65536 regions[regions == 65535] = 65536 vr[:] = regions regions_small = regions regions_small[regions > 3000] = 65536 ext_x, ext_y = 10, 10 s_reg = {"Hemsedal": {"Id": 4001, "Lat": 60.95, "Lon": 8.28}, "Tyin": {"Id": 4002, "Lat": 61.255, "Lon": 8.2}, "Kattfjordeidet": {"Id": 4003, "Lat": 69.65, "Lon": 18.5}, "Lavangsdalen": {"Id": 4004, "Lat": 69.46, "Lon": 19.24}} for key in s_reg: y, x = get_xgeo_indicies(s_reg[key]['Lat'], s_reg[key]['Lon']) regions_small[y - ext_y : y + ext_y + 1, x - ext_x : x + ext_x + 1] = s_reg[key]['Id'] lr = nc.createVariable('LokalOmr_2018', np.int32, ('y', 'x')) lr.units = vr.units lr.long_name = 'Mindre test omraader' lr.missing_value = vr.missing_value lr.coordinates = vr.coordinates lr.grid_mapping = vr.grid_mapping lr.esri_pe_string = vr.esri_pe_string lr[:] = regions_small nc.close() print('Dataset is closed!') def add_lat_lon(): p = Path(os.path.dirname(os.path.abspath(__file__))).parent nc_file = p / 'data' / 'terrain_parameters' / 'VarslingsOmr_2017.nc' nc = netCDF4.Dataset(nc_file, "a") nc_ref = netCDF4.Dataset(r"\\hdata\grid\metdata\prognosis\meps\det\archive\2018\meps_det_pp_1km_20180127T00Z.nc", "r") lat_ref = nc_ref.variables['lat'] lon_ref = nc_ref.variables['lon'] lat = nc.createVariable('lat', np.float64, ('y', 'x')) lat.units = lat_ref.units lat.standard_name = lat_ref.standard_name lat.long_name = lat_ref.long_name lon = nc.createVariable('lon', np.float64, ('y', 'x')) lon.units = lon_ref.units lon.standard_name = lon_ref.standard_name lon.long_name = lon_ref.long_name nc.close() nc_ref.close() def get_xgeo_indicies(lat, lon): y_max = 1550 nc = netCDF4.Dataset(r"\\hdata\grid\metdata\prognosis\meps\det\archive\2018\meps_det_pp_1km_20180127T00Z.nc", "r") y, x = tunnel_fast(nc.variables['lat'], nc.variables['lon'], lat, lon) return y_max-y, x if __name__ == "__main__": print("BLING BLING") add_lat_lon()
true
true
f735f5f927d84cdc60937cb689e5e363a0be9c54
505
py
Python
sqrtrading/wsgi.py
alexbid/sqrtrading
1dadf3e42e9b747134861572b44f81cb8222c2f2
[ "MIT" ]
null
null
null
sqrtrading/wsgi.py
alexbid/sqrtrading
1dadf3e42e9b747134861572b44f81cb8222c2f2
[ "MIT" ]
null
null
null
sqrtrading/wsgi.py
alexbid/sqrtrading
1dadf3e42e9b747134861572b44f81cb8222c2f2
[ "MIT" ]
null
null
null
""" WSGI config for sqrtrading 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/1.10/howto/deployment/wsgi/ """ import os import sys addPath = os.path.realpath(__file__).replace('sqrtrading/wsgi.py','') sys.path.append(addPath) from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sqrtrading.settings") application = get_wsgi_application()
24.047619
78
0.782178
import os import sys addPath = os.path.realpath(__file__).replace('sqrtrading/wsgi.py','') sys.path.append(addPath) from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sqrtrading.settings") application = get_wsgi_application()
true
true
f735f5fbd64d2154b36d035f777107f689429cdb
611
py
Python
test/python/LIM2Metrics/py3/base/common/Prototype/Prototype.py
sagodiz/SonarQube-plug-in
4f8e111baecc4c9f9eaa5cd3d7ebeb1e365ace2c
[ "BSD-4-Clause" ]
20
2015-06-16T17:39:10.000Z
2022-03-20T22:39:40.000Z
test/python/LIM2Metrics/py3/base/common/Prototype/Prototype.py
sagodiz/SonarQube-plug-in
4f8e111baecc4c9f9eaa5cd3d7ebeb1e365ace2c
[ "BSD-4-Clause" ]
29
2015-12-29T19:07:22.000Z
2022-03-22T10:39:02.000Z
test/python/LIM2Metrics/py3/base/common/Prototype/Prototype.py
sagodiz/SonarQube-plug-in
4f8e111baecc4c9f9eaa5cd3d7ebeb1e365ace2c
[ "BSD-4-Clause" ]
12
2015-08-28T01:22:18.000Z
2021-09-25T08:17:31.000Z
import copy # # Prototype Class # class Cookie: def __init__(self, name): self.name = name def clone(self): return copy.deepcopy(self) # # Concrete Prototypes to clone # class CoconutCookie(Cookie): def __init__(self): Cookie.__init__(self, 'Coconut') # # Client Class # class CookieMachine: def __init__(self, cookie): self.cookie = cookie def make_cookie(self): return self.cookie.clone() if __name__ == '__main__': prot = CoconutCookie() cm = CookieMachine(prot) for i in range(10): temp_cookie = cm.make_cookie()
16.972222
40
0.630115
import copy class Cookie: def __init__(self, name): self.name = name def clone(self): return copy.deepcopy(self) class CoconutCookie(Cookie): def __init__(self): Cookie.__init__(self, 'Coconut') class CookieMachine: def __init__(self, cookie): self.cookie = cookie def make_cookie(self): return self.cookie.clone() if __name__ == '__main__': prot = CoconutCookie() cm = CookieMachine(prot) for i in range(10): temp_cookie = cm.make_cookie()
true
true
f735f6a1ba518112d8f3c4b8d18cb45e36f1179b
8,475
py
Python
.ci/ci_lib.py
ossys/mitogen
8654af738b007fc659a77fe88c7da8cb0b5d51cd
[ "BSD-3-Clause" ]
null
null
null
.ci/ci_lib.py
ossys/mitogen
8654af738b007fc659a77fe88c7da8cb0b5d51cd
[ "BSD-3-Clause" ]
3
2021-03-26T00:43:30.000Z
2022-03-29T22:03:58.000Z
deploy/mitogen/.ci/ci_lib.py
voloshanenko/smsgateway
a1509c7b98d844bc483a47173223062e6e1c2bc6
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
from __future__ import absolute_import from __future__ import print_function import atexit import os import shlex import shutil import subprocess import sys import tempfile try: import urlparse except ImportError: import urllib.parse as urlparse os.chdir( os.path.join( os.path.dirname(__file__), '..' ) ) # # check_output() monkeypatch cutpasted from testlib.py # def subprocess__check_output(*popenargs, **kwargs): # Missing from 2.6. process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, _ = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise subprocess.CalledProcessError(retcode, cmd) return output if not hasattr(subprocess, 'check_output'): subprocess.check_output = subprocess__check_output # ------------------ def have_apt(): proc = subprocess.Popen('apt --help >/dev/null 2>/dev/null', shell=True) return proc.wait() == 0 def have_brew(): proc = subprocess.Popen('brew help >/dev/null 2>/dev/null', shell=True) return proc.wait() == 0 def have_docker(): proc = subprocess.Popen('docker info >/dev/null 2>/dev/null', shell=True) return proc.wait() == 0 # ----------------- # Force line buffering on stdout. sys.stdout = os.fdopen(1, 'w', 1) # Force stdout FD 1 to be a pipe, so tools like pip don't spam progress bars. if 'TRAVIS_HOME' in os.environ: proc = subprocess.Popen( args=['stdbuf', '-oL', 'cat'], stdin=subprocess.PIPE ) os.dup2(proc.stdin.fileno(), 1) os.dup2(proc.stdin.fileno(), 2) def cleanup_travis_junk(stdout=sys.stdout, stderr=sys.stderr, proc=proc): stdout.close() stderr.close() proc.terminate() atexit.register(cleanup_travis_junk) # ----------------- def _argv(s, *args): if args: s %= args return shlex.split(s) def run(s, *args, **kwargs): argv = ['/usr/bin/time', '--'] + _argv(s, *args) print('Running: %s' % (argv,)) try: ret = subprocess.check_call(argv, **kwargs) print('Finished running: %s' % (argv,)) except Exception: print('Exception occurred while running: %s' % (argv,)) raise return ret def run_batches(batches): combine = lambda batch: 'set -x; ' + (' && '.join( '( %s; )' % (cmd,) for cmd in batch )) procs = [ subprocess.Popen(combine(batch), shell=True) for batch in batches ] assert [proc.wait() for proc in procs] == [0] * len(procs) def get_output(s, *args, **kwargs): argv = _argv(s, *args) print('Running: %s' % (argv,)) return subprocess.check_output(argv, **kwargs) def exists_in_path(progname): return any(os.path.exists(os.path.join(dirname, progname)) for dirname in os.environ['PATH'].split(os.pathsep)) class TempDir(object): def __init__(self): self.path = tempfile.mkdtemp(prefix='mitogen_ci_lib') atexit.register(self.destroy) def destroy(self, rmtree=shutil.rmtree): rmtree(self.path) class Fold(object): def __init__(self, name): self.name = name def __enter__(self): print('travis_fold:start:%s' % (self.name)) def __exit__(self, _1, _2, _3): print('') print('travis_fold:end:%s' % (self.name)) os.environ.setdefault('ANSIBLE_STRATEGY', os.environ.get('STRATEGY', 'mitogen_linear')) ANSIBLE_VERSION = os.environ.get('VER', '2.6.2') GIT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) DISTRO = os.environ.get('DISTRO', 'debian') DISTROS = os.environ.get('DISTROS', 'debian centos6 centos7').split() TARGET_COUNT = int(os.environ.get('TARGET_COUNT', '2')) BASE_PORT = 2200 TMP = TempDir().path # We copy this out of the way to avoid random stuff modifying perms in the Git # tree (like git pull). src_key_file = os.path.join(GIT_ROOT, 'tests/data/docker/mitogen__has_sudo_pubkey.key') key_file = os.path.join(TMP, 'mitogen__has_sudo_pubkey.key') shutil.copyfile(src_key_file, key_file) os.chmod(key_file, int('0600', 8)) os.environ['PYTHONDONTWRITEBYTECODE'] = 'x' os.environ['PYTHONPATH'] = '%s:%s' % ( os.environ.get('PYTHONPATH', ''), GIT_ROOT ) def get_docker_hostname(): url = os.environ.get('DOCKER_HOST') if url in (None, 'http+docker://localunixsocket'): return 'localhost' parsed = urlparse.urlparse(url) return parsed.netloc.partition(':')[0] def image_for_distro(distro): return 'mitogen/%s-test' % (distro.partition('-')[0],) def make_containers(name_prefix='', port_offset=0): docker_hostname = get_docker_hostname() firstbit = lambda s: (s+'-').split('-')[0] secondbit = lambda s: (s+'-').split('-')[1] i = 1 lst = [] for distro in DISTROS: distro, star, count = distro.partition('*') if star: count = int(count) else: count = 1 for x in range(count): lst.append({ "distro": firstbit(distro), "name": name_prefix + ("target-%s-%s" % (distro, i)), "hostname": docker_hostname, "port": BASE_PORT + i + port_offset, "python_path": ( '/usr/bin/python3' if secondbit(distro) == 'py3' else '/usr/bin/python' ) }) i += 1 return lst # ssh removed from here because 'linear' strategy relies on processes that hang # around after the Ansible run completes INTERESTING_COMMS = ('python', 'sudo', 'su', 'doas') def proc_is_docker(pid): try: fp = open('/proc/%s/cgroup' % (pid,), 'r') except IOError: return False try: return 'docker' in fp.read() finally: fp.close() def get_interesting_procs(container_name=None): args = ['ps', 'ax', '-oppid=', '-opid=', '-ocomm=', '-ocommand='] if container_name is not None: args = ['docker', 'exec', container_name] + args out = [] for line in subprocess__check_output(args).decode().splitlines(): ppid, pid, comm, rest = line.split(None, 3) if ( ( any(comm.startswith(s) for s in INTERESTING_COMMS) or 'mitogen:' in rest ) and ( container_name is not None or (not proc_is_docker(pid)) ) ): out.append((int(pid), line)) return sorted(out) def start_containers(containers): if os.environ.get('KEEP'): return run_batches([ [ "docker rm -f %(name)s || true" % container, "docker run " "--rm " # "--cpuset-cpus 0,1 " "--detach " "--privileged " "--cap-add=SYS_PTRACE " "--publish 0.0.0.0:%(port)s:22/tcp " "--hostname=%(name)s " "--name=%(name)s " "mitogen/%(distro)s-test " % container ] for container in containers ]) for container in containers: container['interesting'] = get_interesting_procs(container['name']) return containers def verify_procs(hostname, old, new): oldpids = set(pid for pid, _ in old) if any(pid not in oldpids for pid, _ in new): print('%r had stray processes running:' % (hostname,)) for pid, line in new: if pid not in oldpids: print('New process:', line) print() return False return True def check_stray_processes(old, containers=None): ok = True new = get_interesting_procs() if old is not None: ok &= verify_procs('test host machine', old, new) for container in containers or (): ok &= verify_procs( container['name'], container['interesting'], get_interesting_procs(container['name']) ) assert ok, 'stray processes were found' def dump_file(path): print() print('--- %s ---' % (path,)) print() with open(path, 'r') as fp: print(fp.read().rstrip()) print('---') print() # SSH passes these through to the container when run interactively, causing # stdout to get messed up with libc warnings. os.environ.pop('LANG', None) os.environ.pop('LC_ALL', None)
25.298507
79
0.584307
from __future__ import absolute_import from __future__ import print_function import atexit import os import shlex import shutil import subprocess import sys import tempfile try: import urlparse except ImportError: import urllib.parse as urlparse os.chdir( os.path.join( os.path.dirname(__file__), '..' ) ) def subprocess__check_output(*popenargs, **kwargs): process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, _ = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise subprocess.CalledProcessError(retcode, cmd) return output if not hasattr(subprocess, 'check_output'): subprocess.check_output = subprocess__check_output def have_apt(): proc = subprocess.Popen('apt --help >/dev/null 2>/dev/null', shell=True) return proc.wait() == 0 def have_brew(): proc = subprocess.Popen('brew help >/dev/null 2>/dev/null', shell=True) return proc.wait() == 0 def have_docker(): proc = subprocess.Popen('docker info >/dev/null 2>/dev/null', shell=True) return proc.wait() == 0 sys.stdout = os.fdopen(1, 'w', 1) if 'TRAVIS_HOME' in os.environ: proc = subprocess.Popen( args=['stdbuf', '-oL', 'cat'], stdin=subprocess.PIPE ) os.dup2(proc.stdin.fileno(), 1) os.dup2(proc.stdin.fileno(), 2) def cleanup_travis_junk(stdout=sys.stdout, stderr=sys.stderr, proc=proc): stdout.close() stderr.close() proc.terminate() atexit.register(cleanup_travis_junk) # ----------------- def _argv(s, *args): if args: s %= args return shlex.split(s) def run(s, *args, **kwargs): argv = ['/usr/bin/time', '--'] + _argv(s, *args) print('Running: %s' % (argv,)) try: ret = subprocess.check_call(argv, **kwargs) print('Finished running: %s' % (argv,)) except Exception: print('Exception occurred while running: %s' % (argv,)) raise return ret def run_batches(batches): combine = lambda batch: 'set -x; ' + (' && '.join( '( %s; )' % (cmd,) for cmd in batch )) procs = [ subprocess.Popen(combine(batch), shell=True) for batch in batches ] assert [proc.wait() for proc in procs] == [0] * len(procs) def get_output(s, *args, **kwargs): argv = _argv(s, *args) print('Running: %s' % (argv,)) return subprocess.check_output(argv, **kwargs) def exists_in_path(progname): return any(os.path.exists(os.path.join(dirname, progname)) for dirname in os.environ['PATH'].split(os.pathsep)) class TempDir(object): def __init__(self): self.path = tempfile.mkdtemp(prefix='mitogen_ci_lib') atexit.register(self.destroy) def destroy(self, rmtree=shutil.rmtree): rmtree(self.path) class Fold(object): def __init__(self, name): self.name = name def __enter__(self): print('travis_fold:start:%s' % (self.name)) def __exit__(self, _1, _2, _3): print('') print('travis_fold:end:%s' % (self.name)) os.environ.setdefault('ANSIBLE_STRATEGY', os.environ.get('STRATEGY', 'mitogen_linear')) ANSIBLE_VERSION = os.environ.get('VER', '2.6.2') GIT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) DISTRO = os.environ.get('DISTRO', 'debian') DISTROS = os.environ.get('DISTROS', 'debian centos6 centos7').split() TARGET_COUNT = int(os.environ.get('TARGET_COUNT', '2')) BASE_PORT = 2200 TMP = TempDir().path # We copy this out of the way to avoid random stuff modifying perms in the Git # tree (like git pull). src_key_file = os.path.join(GIT_ROOT, 'tests/data/docker/mitogen__has_sudo_pubkey.key') key_file = os.path.join(TMP, 'mitogen__has_sudo_pubkey.key') shutil.copyfile(src_key_file, key_file) os.chmod(key_file, int('0600', 8)) os.environ['PYTHONDONTWRITEBYTECODE'] = 'x' os.environ['PYTHONPATH'] = '%s:%s' % ( os.environ.get('PYTHONPATH', ''), GIT_ROOT ) def get_docker_hostname(): url = os.environ.get('DOCKER_HOST') if url in (None, 'http+docker://localunixsocket'): return 'localhost' parsed = urlparse.urlparse(url) return parsed.netloc.partition(':')[0] def image_for_distro(distro): return 'mitogen/%s-test' % (distro.partition('-')[0],) def make_containers(name_prefix='', port_offset=0): docker_hostname = get_docker_hostname() firstbit = lambda s: (s+'-').split('-')[0] secondbit = lambda s: (s+'-').split('-')[1] i = 1 lst = [] for distro in DISTROS: distro, star, count = distro.partition('*') if star: count = int(count) else: count = 1 for x in range(count): lst.append({ "distro": firstbit(distro), "name": name_prefix + ("target-%s-%s" % (distro, i)), "hostname": docker_hostname, "port": BASE_PORT + i + port_offset, "python_path": ( '/usr/bin/python3' if secondbit(distro) == 'py3' else '/usr/bin/python' ) }) i += 1 return lst # ssh removed from here because 'linear' strategy relies on processes that hang # around after the Ansible run completes INTERESTING_COMMS = ('python', 'sudo', 'su', 'doas') def proc_is_docker(pid): try: fp = open('/proc/%s/cgroup' % (pid,), 'r') except IOError: return False try: return 'docker' in fp.read() finally: fp.close() def get_interesting_procs(container_name=None): args = ['ps', 'ax', '-oppid=', '-opid=', '-ocomm=', '-ocommand='] if container_name is not None: args = ['docker', 'exec', container_name] + args out = [] for line in subprocess__check_output(args).decode().splitlines(): ppid, pid, comm, rest = line.split(None, 3) if ( ( any(comm.startswith(s) for s in INTERESTING_COMMS) or 'mitogen:' in rest ) and ( container_name is not None or (not proc_is_docker(pid)) ) ): out.append((int(pid), line)) return sorted(out) def start_containers(containers): if os.environ.get('KEEP'): return run_batches([ [ "docker rm -f %(name)s || true" % container, "docker run " "--rm " # "--cpuset-cpus 0,1 " "--detach " "--privileged " "--cap-add=SYS_PTRACE " "--publish 0.0.0.0:%(port)s:22/tcp " "--hostname=%(name)s " "--name=%(name)s " "mitogen/%(distro)s-test " % container ] for container in containers ]) for container in containers: container['interesting'] = get_interesting_procs(container['name']) return containers def verify_procs(hostname, old, new): oldpids = set(pid for pid, _ in old) if any(pid not in oldpids for pid, _ in new): print('%r had stray processes running:' % (hostname,)) for pid, line in new: if pid not in oldpids: print('New process:', line) print() return False return True def check_stray_processes(old, containers=None): ok = True new = get_interesting_procs() if old is not None: ok &= verify_procs('test host machine', old, new) for container in containers or (): ok &= verify_procs( container['name'], container['interesting'], get_interesting_procs(container['name']) ) assert ok, 'stray processes were found' def dump_file(path): print() print('--- %s ---' % (path,)) print() with open(path, 'r') as fp: print(fp.read().rstrip()) print('---') print() # SSH passes these through to the container when run interactively, causing # stdout to get messed up with libc warnings. os.environ.pop('LANG', None) os.environ.pop('LC_ALL', None)
true
true
f735f6cd5e14c234a77f347166f09b45b4e9ba7e
3,327
py
Python
src/game_management/phases.py
kesslermaximilian/JustOneBot
1d7f861bc92fe6bc89e2061d8c22eb802db54d30
[ "MIT" ]
1
2021-05-23T09:29:02.000Z
2021-05-23T09:29:02.000Z
src/game_management/phases.py
nonchris/JustOneBot
4396dc042542938643932128892b19dc3802f394
[ "MIT" ]
1
2021-05-27T21:13:04.000Z
2021-05-27T21:13:04.000Z
src/game_management/phases.py
nonchris/JustOneBot
4396dc042542938643932128892b19dc3802f394
[ "MIT" ]
3
2021-05-23T16:59:39.000Z
2021-05-27T21:09:33.000Z
from game_management.game import Game from game_management.tools import Phase from log_setup import logger """ This file is outdated and not used in the project. Due to circular import issues, this class is now declared (and documented) in game.py """ class PhaseHandler: def __init__(self, game: Game): self.game = game # A dictionary containing the corresponding jobs of the game for each Phase of the game. self.task_dictionary = { Phase.initialised: None, Phase.preparation: game.preparation, Phase.wait_for_admin: game.wait_for_admin, Phase.show_word: game.show_word, Phase.wait_collect_hints: None, # There is no task in this phase Phase.show_all_hints_to_players: game.show_all_hints_to_players, Phase.wait_for_hints_reviewed: game.wait_for_hints_reviewed, Phase.compute_valid_hints: game.compute_valid_hints, Phase.inform_admin_to_reenter: game.inform_admin_to_reenter, Phase.remove_role_from_guesser: game.remove_role_from_guesser, Phase.show_valid_hints: game.show_valid_hints, Phase.wait_for_guess: game.wait_for_guess, # future: Phase.show_guess Phase.show_summary: game.show_summary, Phase.stopping: game.stopping, Phase.stopped: None, # There is no task in this phase Phase.wait_for_play_again_in_closed_mode: game.wait_for_play_again_in_closed_mode, # Phase.wait_for_play_again_in_open_mode: game.wait_for_play_again_in_open_mode # future Phase.wait_for_stop_game_after_timeout: game.wait_for_stop_game_after_timeout, Phase.clear_messages: game.clear_messages } def cancel_all(self): for phase in self.task_dictionary.keys(): if int(phase) < 1000: self.task_dictionary[phase].cancel() def advance_to_phase(self, phase: Phase): if phase.value >= 1000: logger.error(f'{self.game.game_prefix()}Tried to advance to Phase {phase}, but phase number is too high. ' f'Aborting phase advance') return if self.game.phase > phase: logger.error(f'{self.game.game_prefix()}Tried to advance to Phase {phase}, but game is already ' f'in phase {self.game.phase}, cannot go back in time. Aborting phase start.') return elif self.game.phase == phase: logger.warn(f'{self.game.game_prefix()}Tried to advance to Phase {phase}, but game is already ' f'in that phase.' f'Cannot start phase a second time.') return else: # Start the new phase self.game.phase = phase self.cancel_all() if self.task_dictionary[phase]: self.task_dictionary[phase].start() def start_task(self, phase: Phase, *kwargs): if self.task_dictionary[phase].is_running(): logger.error(f'{self.game.game_prefix}Task {phase} is already running, cannot start it twice. ' f'Aborting task start.') return else: self.task_dictionary[phase].start(*kwargs) logger.info(f'Started task {phase}')
45.575342
118
0.640517
from game_management.game import Game from game_management.tools import Phase from log_setup import logger class PhaseHandler: def __init__(self, game: Game): self.game = game self.task_dictionary = { Phase.initialised: None, Phase.preparation: game.preparation, Phase.wait_for_admin: game.wait_for_admin, Phase.show_word: game.show_word, Phase.wait_collect_hints: None, Phase.show_all_hints_to_players: game.show_all_hints_to_players, Phase.wait_for_hints_reviewed: game.wait_for_hints_reviewed, Phase.compute_valid_hints: game.compute_valid_hints, Phase.inform_admin_to_reenter: game.inform_admin_to_reenter, Phase.remove_role_from_guesser: game.remove_role_from_guesser, Phase.show_valid_hints: game.show_valid_hints, Phase.wait_for_guess: game.wait_for_guess, Phase.show_summary: game.show_summary, Phase.stopping: game.stopping, Phase.stopped: None, Phase.wait_for_play_again_in_closed_mode: game.wait_for_play_again_in_closed_mode, Phase.wait_for_stop_game_after_timeout: game.wait_for_stop_game_after_timeout, Phase.clear_messages: game.clear_messages } def cancel_all(self): for phase in self.task_dictionary.keys(): if int(phase) < 1000: self.task_dictionary[phase].cancel() def advance_to_phase(self, phase: Phase): if phase.value >= 1000: logger.error(f'{self.game.game_prefix()}Tried to advance to Phase {phase}, but phase number is too high. ' f'Aborting phase advance') return if self.game.phase > phase: logger.error(f'{self.game.game_prefix()}Tried to advance to Phase {phase}, but game is already ' f'in phase {self.game.phase}, cannot go back in time. Aborting phase start.') return elif self.game.phase == phase: logger.warn(f'{self.game.game_prefix()}Tried to advance to Phase {phase}, but game is already ' f'in that phase.' f'Cannot start phase a second time.') return else: self.game.phase = phase self.cancel_all() if self.task_dictionary[phase]: self.task_dictionary[phase].start() def start_task(self, phase: Phase, *kwargs): if self.task_dictionary[phase].is_running(): logger.error(f'{self.game.game_prefix}Task {phase} is already running, cannot start it twice. ' f'Aborting task start.') return else: self.task_dictionary[phase].start(*kwargs) logger.info(f'Started task {phase}')
true
true
f735f71c29215f16bd0045a36820d4e8c5cdd059
3,347
py
Python
procedure/problem/efficiency_performance/mo_nats.py
MinhTuDo/MD-MOENAS
edd6ec8c3f89cfbe9674873425c5056e72899edb
[ "MIT" ]
3
2021-12-10T02:07:38.000Z
2021-12-10T15:07:49.000Z
procedure/problem/efficiency_performance/mo_nats.py
ELO-Lab/MD-MOENAS
edd6ec8c3f89cfbe9674873425c5056e72899edb
[ "MIT" ]
null
null
null
procedure/problem/efficiency_performance/mo_nats.py
ELO-Lab/MD-MOENAS
edd6ec8c3f89cfbe9674873425c5056e72899edb
[ "MIT" ]
null
null
null
from procedure.problem.base import nats as base import numpy as np class EfficiencyAccuracyNATS(base.NATS): def __init__(self, efficiency, **kwargs): super().__init__(n_obj=2, **kwargs) self.msg += efficiency + '={:.3f}, ' + 'valid-error' + '={:.3f}' self.efficiency = efficiency def _calc_F(self, genotype, **kwargs): accuracy, latency, _, runtime = self.api.simulate_train_eval( genotype, self.dataset, iepoch=self.epoch, hp=self.api.full_train_epochs ) idx = self.api.query_index_by_arch(genotype) cost_info = self.api.get_cost_info(idx, self.dataset, hp=self.api.full_train_epochs) params, flops = cost_info['params'], cost_info['flops'] efficiency = eval(self.efficiency) error = 100 - accuracy F = [efficiency, error] return F, runtime def _convert_to_pf_space(self, X): F = [] dataset = self.pf_dict['dataset'] for x in X: genotype = self._decode(x) idx = self.api.query_index_by_arch(genotype) efficiency = self.api.get_cost_info( idx, dataset, hp=self.api.full_train_epochs )[self.efficiency] acc = self.api.get_more_info( idx, dataset, hp=self.api.full_train_epochs, is_random=False )['test-accuracy'] err = 100 - acc f = [efficiency, err] F += [np.column_stack(f)] F = np.row_stack(F) return F class MDEfficiencyAccuracyNATS(base.NATS): def __init__(self, efficiency, **kwargs): super().__init__(n_obj=2, **kwargs) self.msg += 'avg-' + efficiency + '={:.3f}, avg-val-err={:.3f}' self.efficiency = efficiency def _calc_F(self, genotype, **kwargs): idx = self.api.query_index_by_arch(genotype) efficiency = []; runtime = []; accuracy = [] for dts in self.dataset: _accuracy, latency, _, _runtime = self.api.simulate_train_eval( genotype, dataset=dts, iepoch=self.epoch, hp=self.api.full_train_epochs ) idx = self.api.query_index_by_arch(genotype) cost_info = self.api.get_cost_info(idx, dts, hp=self.api.full_train_epochs) params, flops = cost_info['params'], cost_info['flops'] _efficiency = eval(self.efficiency) efficiency += [_efficiency] runtime += [_runtime] accuracy += [_accuracy] efficiency = np.mean(efficiency) runtime = sum(runtime) accuracy = np.mean(accuracy) err = 100 - accuracy F = [efficiency, err] return F, runtime def _convert_to_pf_space(self, X): F = [] dataset = self.pf_dict['dataset'] for x in X: genotype = self._decode(x) idx = self.api.query_index_by_arch(genotype) efficiency = self.api.get_cost_info(idx, dataset, hp=self.api.full_train_epochs)[self.efficiency] acc = \ self.api.get_more_info(idx, dataset, hp=self.api.full_train_epochs, is_random=False)['test-accuracy'] err = 100 - acc f = [efficiency, err] F += [np.column_stack(f)] F = np.row_stack(F) return F
34.505155
117
0.579026
from procedure.problem.base import nats as base import numpy as np class EfficiencyAccuracyNATS(base.NATS): def __init__(self, efficiency, **kwargs): super().__init__(n_obj=2, **kwargs) self.msg += efficiency + '={:.3f}, ' + 'valid-error' + '={:.3f}' self.efficiency = efficiency def _calc_F(self, genotype, **kwargs): accuracy, latency, _, runtime = self.api.simulate_train_eval( genotype, self.dataset, iepoch=self.epoch, hp=self.api.full_train_epochs ) idx = self.api.query_index_by_arch(genotype) cost_info = self.api.get_cost_info(idx, self.dataset, hp=self.api.full_train_epochs) params, flops = cost_info['params'], cost_info['flops'] efficiency = eval(self.efficiency) error = 100 - accuracy F = [efficiency, error] return F, runtime def _convert_to_pf_space(self, X): F = [] dataset = self.pf_dict['dataset'] for x in X: genotype = self._decode(x) idx = self.api.query_index_by_arch(genotype) efficiency = self.api.get_cost_info( idx, dataset, hp=self.api.full_train_epochs )[self.efficiency] acc = self.api.get_more_info( idx, dataset, hp=self.api.full_train_epochs, is_random=False )['test-accuracy'] err = 100 - acc f = [efficiency, err] F += [np.column_stack(f)] F = np.row_stack(F) return F class MDEfficiencyAccuracyNATS(base.NATS): def __init__(self, efficiency, **kwargs): super().__init__(n_obj=2, **kwargs) self.msg += 'avg-' + efficiency + '={:.3f}, avg-val-err={:.3f}' self.efficiency = efficiency def _calc_F(self, genotype, **kwargs): idx = self.api.query_index_by_arch(genotype) efficiency = []; runtime = []; accuracy = [] for dts in self.dataset: _accuracy, latency, _, _runtime = self.api.simulate_train_eval( genotype, dataset=dts, iepoch=self.epoch, hp=self.api.full_train_epochs ) idx = self.api.query_index_by_arch(genotype) cost_info = self.api.get_cost_info(idx, dts, hp=self.api.full_train_epochs) params, flops = cost_info['params'], cost_info['flops'] _efficiency = eval(self.efficiency) efficiency += [_efficiency] runtime += [_runtime] accuracy += [_accuracy] efficiency = np.mean(efficiency) runtime = sum(runtime) accuracy = np.mean(accuracy) err = 100 - accuracy F = [efficiency, err] return F, runtime def _convert_to_pf_space(self, X): F = [] dataset = self.pf_dict['dataset'] for x in X: genotype = self._decode(x) idx = self.api.query_index_by_arch(genotype) efficiency = self.api.get_cost_info(idx, dataset, hp=self.api.full_train_epochs)[self.efficiency] acc = \ self.api.get_more_info(idx, dataset, hp=self.api.full_train_epochs, is_random=False)['test-accuracy'] err = 100 - acc f = [efficiency, err] F += [np.column_stack(f)] F = np.row_stack(F) return F
true
true
f735f82e3b5af400f3030e9e85e6e6684e925602
720
py
Python
poky-dunfell/meta/lib/oeqa/runtime/cases/gstreamer.py
lacie-life/YoctoPi
3412e78468a9b84da50bb1aadb12b459001a3712
[ "MIT" ]
14
2021-11-04T07:47:37.000Z
2022-03-21T10:10:30.000Z
poky-dunfell/meta/lib/oeqa/runtime/cases/gstreamer.py
lacie-life/YoctoPi
3412e78468a9b84da50bb1aadb12b459001a3712
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
poky-dunfell/meta/lib/oeqa/runtime/cases/gstreamer.py
lacie-life/YoctoPi
3412e78468a9b84da50bb1aadb12b459001a3712
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
# # SPDX-License-Identifier: MIT # from oeqa.runtime.case import OERuntimeTestCase from oeqa.runtime.decorator.package import OEHasPackage class GstreamerCliTest(OERuntimeTestCase): @OEHasPackage(['gstreamer1.0']) def test_gst_inspect_can_list_all_plugins(self): status, output = self.target.run('gst-inspect-1.0') self.assertEqual(status, 0, 'gst-inspect-1.0 does not appear to be running.') @OEHasPackage(['gstreamer1.0']) def test_gst_launch_can_create_video_pipeline(self): status, output = self.target.run('gst-launch-1.0 -v fakesrc silent=false num-buffers=3 ! fakesink silent=false') self.assertEqual(status, 0, 'gst-launch-1.0 does not appear to be running.')
37.894737
120
0.733333
from oeqa.runtime.case import OERuntimeTestCase from oeqa.runtime.decorator.package import OEHasPackage class GstreamerCliTest(OERuntimeTestCase): @OEHasPackage(['gstreamer1.0']) def test_gst_inspect_can_list_all_plugins(self): status, output = self.target.run('gst-inspect-1.0') self.assertEqual(status, 0, 'gst-inspect-1.0 does not appear to be running.') @OEHasPackage(['gstreamer1.0']) def test_gst_launch_can_create_video_pipeline(self): status, output = self.target.run('gst-launch-1.0 -v fakesrc silent=false num-buffers=3 ! fakesink silent=false') self.assertEqual(status, 0, 'gst-launch-1.0 does not appear to be running.')
true
true
f735f8c3575a57fd39b5854bb669d4259fcfaded
277
py
Python
core/admin.py
NarminSH/e-commerce-sellshop-project
a753038c8265473021e21f75b6b095bdc25f43d6
[ "MIT" ]
null
null
null
core/admin.py
NarminSH/e-commerce-sellshop-project
a753038c8265473021e21f75b6b095bdc25f43d6
[ "MIT" ]
null
null
null
core/admin.py
NarminSH/e-commerce-sellshop-project
a753038c8265473021e21f75b6b095bdc25f43d6
[ "MIT" ]
null
null
null
from django.contrib import admin from core.models import Contact, Slider @admin.register(Contact) class ContactAdmin(admin.ModelAdmin): list_display = ('name', 'email') list_filter = ('name', 'email') search_fields = ('name', 'email') admin.site.register(Slider)
25.181818
39
0.718412
from django.contrib import admin from core.models import Contact, Slider @admin.register(Contact) class ContactAdmin(admin.ModelAdmin): list_display = ('name', 'email') list_filter = ('name', 'email') search_fields = ('name', 'email') admin.site.register(Slider)
true
true
f735f8fc14c7fe9404c2a5d90d59491063b15f84
1,539
py
Python
pygna/cli.py
Gee-3/pygna
61f2128e918e423fef73d810e0c3af5761933096
[ "MIT" ]
32
2019-07-11T22:58:14.000Z
2022-03-04T19:34:55.000Z
pygna/cli.py
Gee-3/pygna
61f2128e918e423fef73d810e0c3af5761933096
[ "MIT" ]
3
2021-05-24T14:03:13.000Z
2022-01-07T03:47:32.000Z
pygna/cli.py
Gee-3/pygna
61f2128e918e423fef73d810e0c3af5761933096
[ "MIT" ]
5
2019-07-24T09:38:07.000Z
2021-12-30T09:20:20.000Z
import logging import argh import pygna.command as cmd import pygna.painter as paint import pygna.utils as utils import pygna.block_model as bm import pygna.degree_model as dm """ autodoc """ logging.basicConfig(level=logging.INFO) def main(): argh.dispatch_commands([ # network summary and graph file cmd.network_summary, cmd.network_graphml, cmd.get_connected_components, # geneset network topology analyses cmd.test_topology_total_degree, cmd.test_topology_internal_degree, cmd.test_topology_module, cmd.test_topology_sp, cmd.test_topology_rwr, cmd.test_diffusion_hotnet, # comparison analysis cmd.test_association_sp, cmd.test_association_rwr, # building functions cmd.build_distance_matrix, cmd.build_rwr_diffusion, # paint paint.paint_datasets_stats, paint.paint_comparison_matrix, paint.plot_adjacency, paint.paint_volcano_plot, paint.paint_summary_gnt, # utils utils.convert_gmt, utils.geneset_from_table, utils.convert_csv, utils.generate_group_gmt, # simulations bm.generate_gnt_sbm, bm.generate_gna_sbm, dm.generate_hdn_network, bm.generate_sbm_network, bm.generate_sbm2_network, dm.hdn_add_partial, dm.hdn_add_extended, dm.hdn_add_branching, ], ) if __name__ == "__main__": """ MAIN """ main()
23.676923
43
0.654321
import logging import argh import pygna.command as cmd import pygna.painter as paint import pygna.utils as utils import pygna.block_model as bm import pygna.degree_model as dm logging.basicConfig(level=logging.INFO) def main(): argh.dispatch_commands([ cmd.network_summary, cmd.network_graphml, cmd.get_connected_components, cmd.test_topology_total_degree, cmd.test_topology_internal_degree, cmd.test_topology_module, cmd.test_topology_sp, cmd.test_topology_rwr, cmd.test_diffusion_hotnet, cmd.test_association_sp, cmd.test_association_rwr, cmd.build_distance_matrix, cmd.build_rwr_diffusion, paint.paint_datasets_stats, paint.paint_comparison_matrix, paint.plot_adjacency, paint.paint_volcano_plot, paint.paint_summary_gnt, utils.convert_gmt, utils.geneset_from_table, utils.convert_csv, utils.generate_group_gmt, bm.generate_gnt_sbm, bm.generate_gna_sbm, dm.generate_hdn_network, bm.generate_sbm_network, bm.generate_sbm2_network, dm.hdn_add_partial, dm.hdn_add_extended, dm.hdn_add_branching, ], ) if __name__ == "__main__": main()
true
true
f735f9986c5d76bff5fadb7e320bf1356ecee3fd
16,822
py
Python
Step2_Training_MIL/train_MIL_classification_trained_cnn_models.py
Gaskell-1206/MSI_vs_MSS_Classification
be6fd8a6961624367b2bb0e1299219e940f6f418
[ "MIT" ]
null
null
null
Step2_Training_MIL/train_MIL_classification_trained_cnn_models.py
Gaskell-1206/MSI_vs_MSS_Classification
be6fd8a6961624367b2bb0e1299219e940f6f418
[ "MIT" ]
null
null
null
Step2_Training_MIL/train_MIL_classification_trained_cnn_models.py
Gaskell-1206/MSI_vs_MSS_Classification
be6fd8a6961624367b2bb0e1299219e940f6f418
[ "MIT" ]
null
null
null
# Run MIL classification use pretrained CNN models # Reference: 1.Campanella, G. et al. Clinical-grade computational pathology using weakly supervised # deep learning on whole slide images. Nat Med 25, 1301–1309 (2019). # doi:10.1038/s41591-019-0508-1. Available from http://www.nature.com/articles/s41591-019-0508-1 # The source codes of the referenced paper available at https://github.com/MSKCC-Computational-Pathology/MIL-nature-medicine-2019 # This code was modified by Shengjia Chen for our work. import argparse import os import random import sys from pathlib import Path from types import SimpleNamespace from typing import Callable, Optional, Union from urllib.error import HTTPError import glob import numpy as np import pandas as pd import pytorch_lightning as pl import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from PIL import Image from pytorch_lightning.callbacks import (EarlyStopping, LearningRateMonitor, ModelCheckpoint) from pytorch_lightning.lite import LightningLite from pytorch_lightning.loops import Loop from skimage import io from sklearn.preprocessing import LabelEncoder from torch.utils.data import DataLoader, Dataset from torch.utils.tensorboard import SummaryWriter from torchvision import transforms from tqdm import tqdm sys.path.append('/gpfs/scratch/sc9295/digPath/MSI_vs_MSS_Classification/Step1_Training_MSI_MSS') from train_tile_level_classification import MSI_MSS_Module from sklearn.metrics import (auc, confusion_matrix, f1_score, roc_auc_score, roc_curve) best_acc = 0 def inference(loader, model): model.eval() probs = torch.FloatTensor(len(loader.dataset)) with torch.no_grad(): for i, input in enumerate(loader): # print( # 'Inference\tEpoch: [{}/{}]\tBatch: [{}/{}]'.format(run+1, args.nepochs, i+1, len(loader))) output = F.softmax(model(input), dim=1) probs[i*args.batch_size:i*args.batch_size + input.size(0)] = output.detach()[:, 1].clone() return probs.cpu().numpy() def train(run, loader, model, criterion, optimizer): model.train() running_loss = 0. for i, (input, target) in enumerate(loader): input = input.cuda() target = target.cuda() output = model(input) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() running_loss += loss.item()*input.size(0) return running_loss/len(loader.dataset) def calc_err(pred, real): pred = np.array(pred) real = np.array(real) pos = np.equal(pred, real) neq = np.not_equal(pred, real) acc = float(pos.sum())/pred.shape[0] err = float(neq.sum())/pred.shape[0] fpr = float(np.logical_and(pred == 1, neq).sum())/(real == 0).sum() fnr = float(np.logical_and(pred == 0, neq).sum())/(real == 1).sum() return acc, err, fpr, fnr def group_argtopk(groups, data, k=1): # groups in slide, data is prob of each tile k = min(k,len(data)) order = np.lexsort((data, groups)) groups = groups[order] data = data[order] index = np.empty(len(groups), 'bool') index[-k:] = True index[:-k] = groups[k:] != groups[:-k] return list(order[index]) # output top prob tile index in each slide def group_max(groups, data, nmax): out = np.empty(nmax) out[:] = np.nan order = np.lexsort((data, groups)) groups = groups[order] data = data[order] index = np.empty(len(groups), 'bool') index[-1] = True index[:-1] = groups[1:] != groups[:-1] out[groups[index]] = data[index] return out class MILdataset(Dataset): def __init__(self, libraryfile_dir='', root_dir='', dataset_mode='Train', transform=None, subset_rate=None): libraryfile_path = os.path.join( libraryfile_dir, f'CRC_DX_{dataset_mode}_ALL.csv') lib = pd.read_csv(libraryfile_path) lib = lib if subset_rate is None else lib.sample( frac=subset_rate, random_state=2022) lib = lib.sort_values(['subject_id'], ignore_index=True) lib.to_csv(os.path.join(libraryfile_dir, f'{dataset_mode}_temporary.csv')) slides = [] for i, name in enumerate(lib['subject_id'].unique()): # sys.stdout.write( # 'Slides: [{}/{}]\r'.format(i+1, len(lib['subject_id'].unique()))) # sys.stdout.flush() slides.append(name) # Flatten grid grid = [] slideIDX = [] for i, g in enumerate(lib['subject_id'].unique()): tiles = lib[lib['subject_id'] == g]['slice_id'] grid.extend(tiles) slideIDX.extend([i]*len(tiles)) # print('Number of tiles: {}'.format(len(grid))) self.dataframe = self.load_data_and_get_class(lib) self.slidenames = list(lib['subject_id'].values) self.slides = slides self.targets = self.dataframe['Class'] self.grid = grid self.slideIDX = slideIDX self.transform = transform self.root_dir = root_dir self.dset = f"CRC_DX_{dataset_mode}" def setmode(self, mode): self.mode = mode def maketraindata(self, idxs): self.t_data = [(self.slideIDX[x], self.grid[x], self.targets[x]) for x in idxs] def shuffletraindata(self): self.t_data = random.sample(self.t_data, len(self.t_data)) def load_data_and_get_class(self, df): df.loc[df['label'] == 'MSI', 'Class'] = 1 df.loc[df['label'] == 'MSS', 'Class'] = 0 return df def __getitem__(self, index): if self.mode == 1: slideIDX = self.slideIDX[index] tile_id = self.grid[index] slide_id = self.slides[slideIDX] img_name = "blk-{}-{}.png".format(tile_id, slide_id) target = self.targets[index] label = 'CRC_DX_MSIMUT' if target == 1 else 'CRC_DX_MSS' img_path = os.path.join(self.root_dir, self.dset, label, img_name) img = io.imread(img_path) if self.transform is not None: img = self.transform(img) return img elif self.mode == 2: slideIDX, tile_id, target = self.t_data[index] slide_id = self.slides[slideIDX] label = 'CRC_DX_MSIMUT' if target == 1 else 'CRC_DX_MSS' img_name = "blk-{}-{}.png".format(tile_id, slide_id) img_path = os.path.join(self.root_dir, self.dset, label, img_name) img = io.imread(img_path) if self.transform is not None: img = self.transform(img) return img, target def __len__(self): if self.mode == 1: return len(self.grid) elif self.mode == 2: return len(self.t_data) class Lite(LightningLite): def run(self, args): global best_acc print(args) self.seed_everything(2022) model_name = args.model_name sample_rate = args.sample_rate ckpt_path = os.path.join(args.model_path, f'{args.model_name}_bs{args.batch_size}_lr{args.learning_rate}') ckpt_file_path = glob.glob(os.path.join(ckpt_path,'*.ckpt'))[0] model = MSI_MSS_Module.load_from_checkpoint(ckpt_file_path) optimizer = torch.optim.AdamW( model.parameters(), lr=args.learning_rate, weight_decay=1e-4) if args.weights == 0.5: criterion = nn.CrossEntropyLoss() else: w = torch.Tensor([1-args.weights, args.weights]) criterion = nn.CrossEntropyLoss(w) # Scale model and optimizers model, optimizer = self.setup(model, optimizer, move_to_device=True) DATA_MEANS = [0.485, 0.456, 0.406] DATA_STD = [0.229, 0.224, 0.225] train_transform = transforms.Compose([ transforms.ToPILImage(), transforms.ToTensor(), transforms.RandomHorizontalFlip(), transforms.Normalize(DATA_MEANS, DATA_STD)]) test_transform = transforms.Compose([ transforms.ToPILImage(), transforms.ToTensor(), transforms.Normalize(DATA_MEANS, DATA_STD)]) train_dataset = MILdataset( args.lib_dir, args.root_dir, 'Train', transform=train_transform, subset_rate=sample_rate) val_dataset = MILdataset( args.lib_dir, args.root_dir, 'Val', transform=test_transform, subset_rate=sample_rate) test_dataset = MILdataset( args.lib_dir, args.root_dir, 'Test', transform=test_transform, subset_rate=sample_rate) train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) val_dataloader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) test_dataloader = DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) train_dataloader, val_dataloader, test_dataloader = self.setup_dataloaders( train_dataloader, val_dataloader, test_dataloader, move_to_device=True) # open output file version_name = f'MIL_{model_name}_bs{args.batch_size}_lr{args.learning_rate}_w{args.weights}_k{args.k}_output' # logger output_path = os.path.join(args.output_path,version_name) writer = SummaryWriter(output_path) for epoch in tqdm(range(args.nepochs)): train_dataset.setmode(1) # print("train_set_len:", len(train_dataloader.dataset)) probs = inference(train_dataloader, model) # return the indices of topk tile(s) in each slides topk = group_argtopk( np.array(train_dataset.slideIDX), probs, args.k) train_dataset.maketraindata(topk) train_dataset.shuffletraindata() train_dataset.setmode(2) model.train() running_loss = 0. for i, (input, target) in enumerate(train_dataloader): output = model(input) loss = criterion(output, target.long()) optimizer.zero_grad() self.backward(loss) optimizer.step() running_loss += loss.item()*input.size(0) train_loss = running_loss/len(train_dataloader.dataset) print( 'Training\tEpoch: [{}/{}]\tLoss: {}'.format(epoch+1, args.nepochs, train_loss)) writer.add_scalar('train_loss', train_loss, epoch+1) # Validation if (epoch+1) % args.test_every == 0: val_dataset.setmode(1) probs = inference(val_dataloader, model) maxs = group_max(np.array(val_dataset.slideIDX), probs, len(val_dataset.targets)) pred = [1 if x >= 0.5 else 0 for x in probs] val_acc, err, fpr, fnr = calc_err(pred, val_dataset.targets) print('Validation\tEpoch: [{}/{}]\t ACC: {}\tError: {}\tFPR: {}\tFNR: {}'.format( epoch+1, args.nepochs, val_acc, err, fpr, fnr)) writer.add_scalar('val_acc', val_acc, epoch+1) writer.add_scalar('fpr', fpr, epoch+1) writer.add_scalar('fnr', fnr, epoch+1) # Save best model err = (fpr+fnr)/2. if 1-err >= best_acc: best_acc = 1-err obj = { 'epoch': epoch+1, 'state_dict': model.state_dict(), 'best_acc': best_acc, 'optimizer': optimizer.state_dict() } torch.save(obj, os.path.join(output_path, 'checkpoint_best.pth')) # test ch = torch.load(os.path.join(output_path,'checkpoint_best.pth')) # load params model.load_state_dict(ch['state_dict']) model = model.cuda() cudnn.benchmark = True train_dataset.setmode(1) val_dataset.setmode(1) test_dataset.setmode(1) # Train probs = inference(train_dataloader, model) maxs = group_max(np.array(train_dataset.slideIDX), probs, len(train_dataset.targets)) fp = open(os.path.join(output_path, f'Train_{version_name}.csv'), 'w') fp.write('slides,tiles,target,prediction,probability\n') for slides, tiles, target, prob in zip(train_dataset.slidenames, train_dataset.grid, train_dataset.targets, probs): fp.write('{},{},{},{},{}\n'.format(slides, tiles, target, int(prob>=0.5), prob)) fp.close() # Val probs = inference(val_dataloader, model) maxs = group_max(np.array(val_dataset.slideIDX), probs, len(val_dataset.targets)) fp = open(os.path.join(output_path, f'Val_{version_name}.csv'), 'w') fp.write('slides,tiles,target,prediction,probability\n') for slides, tiles, target, prob in zip(val_dataset.slidenames, val_dataset.grid, val_dataset.targets, probs): fp.write('{},{},{},{},{}\n'.format(slides, tiles, target, int(prob>=0.5), prob)) fp.close() # Test probs = inference(test_dataloader, model) maxs = group_max(np.array(test_dataset.slideIDX), probs, len(test_dataset.targets)) fp = open(os.path.join(output_path, f'Test_{version_name}.csv'), 'w') fp.write('slides,tiles,target,prediction,probability\n') for slides, tiles, target, prob in zip(test_dataset.slidenames, test_dataset.grid, test_dataset.targets, probs): fp.write('{},{},{},{},{}\n'.format(slides, tiles, target, int(prob>=0.5), prob)) fp.close() pred = [1 if x >= 0.5 else 0 for x in probs] test_acc, err, fnr, fpr = calc_err(pred, test_dataset.targets) test_f1_score = f1_score(test_dataset.targets, pred, average='binary') try: test_auroc_score = roc_auc_score(test_dataset.targets, probs) writer.add_scalar("test_auroc_score", test_auroc_score) except ValueError: writer.add_scalar('test_auroc_score', .0) writer.add_scalar('test_f1_score', test_f1_score) writer.add_scalar('test_acc', test_acc) def main(args): Lite(devices="auto", accelerator="auto").run(args) if __name__ == "__main__": parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "--root_dir", type=Path, required=True, help="root directory of dataset", ) parser.add_argument( "--lib_dir", type=Path, required=True, help="root directory of libraryfile", ) parser.add_argument( "--model_path", type=Path, required=True, help="root directory of pretrained models", ) parser.add_argument( "--output_path", type=Path, required=True, help="output directory", ) parser.add_argument( "--model_name", default='alexnet', choices=('resnet18', 'resnet34', 'alexnet', 'vgg', 'squeezenet', 'densenet', 'inception'), type=str, help="model use for train", ) parser.add_argument( "--sample_rate", default=1, type=float, help="undersample rate", ) parser.add_argument( "--batch_size", default=128, type=int, help="batch size", ) parser.add_argument( "--learning_rate", default=1e-3, type=float, help="learning rate", ) parser.add_argument( "--num_workers", default=0, type=int, required=True, help="number of workers", ) parser.add_argument( "--nepochs", default=50, type=int, help="training epoch", ) parser.add_argument( '--test_every', default=1, type=int, help='test on val every (default: 10)') parser.add_argument( "--weights", default=0.5, type=float, help="unbalanced positive class weight (default: 0.5, balanced classes)", ) parser.add_argument( "--k", default=1, type=int, help="top k tiles are assumed to be of the same class as the slide (default: 1, standard MIL)", ) args = parser.parse_args() main(args)
37.63311
140
0.603495
import argparse import os import random import sys from pathlib import Path from types import SimpleNamespace from typing import Callable, Optional, Union from urllib.error import HTTPError import glob import numpy as np import pandas as pd import pytorch_lightning as pl import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from PIL import Image from pytorch_lightning.callbacks import (EarlyStopping, LearningRateMonitor, ModelCheckpoint) from pytorch_lightning.lite import LightningLite from pytorch_lightning.loops import Loop from skimage import io from sklearn.preprocessing import LabelEncoder from torch.utils.data import DataLoader, Dataset from torch.utils.tensorboard import SummaryWriter from torchvision import transforms from tqdm import tqdm sys.path.append('/gpfs/scratch/sc9295/digPath/MSI_vs_MSS_Classification/Step1_Training_MSI_MSS') from train_tile_level_classification import MSI_MSS_Module from sklearn.metrics import (auc, confusion_matrix, f1_score, roc_auc_score, roc_curve) best_acc = 0 def inference(loader, model): model.eval() probs = torch.FloatTensor(len(loader.dataset)) with torch.no_grad(): for i, input in enumerate(loader): output = F.softmax(model(input), dim=1) probs[i*args.batch_size:i*args.batch_size + input.size(0)] = output.detach()[:, 1].clone() return probs.cpu().numpy() def train(run, loader, model, criterion, optimizer): model.train() running_loss = 0. for i, (input, target) in enumerate(loader): input = input.cuda() target = target.cuda() output = model(input) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() running_loss += loss.item()*input.size(0) return running_loss/len(loader.dataset) def calc_err(pred, real): pred = np.array(pred) real = np.array(real) pos = np.equal(pred, real) neq = np.not_equal(pred, real) acc = float(pos.sum())/pred.shape[0] err = float(neq.sum())/pred.shape[0] fpr = float(np.logical_and(pred == 1, neq).sum())/(real == 0).sum() fnr = float(np.logical_and(pred == 0, neq).sum())/(real == 1).sum() return acc, err, fpr, fnr def group_argtopk(groups, data, k=1): k = min(k,len(data)) order = np.lexsort((data, groups)) groups = groups[order] data = data[order] index = np.empty(len(groups), 'bool') index[-k:] = True index[:-k] = groups[k:] != groups[:-k] return list(order[index]) def group_max(groups, data, nmax): out = np.empty(nmax) out[:] = np.nan order = np.lexsort((data, groups)) groups = groups[order] data = data[order] index = np.empty(len(groups), 'bool') index[-1] = True index[:-1] = groups[1:] != groups[:-1] out[groups[index]] = data[index] return out class MILdataset(Dataset): def __init__(self, libraryfile_dir='', root_dir='', dataset_mode='Train', transform=None, subset_rate=None): libraryfile_path = os.path.join( libraryfile_dir, f'CRC_DX_{dataset_mode}_ALL.csv') lib = pd.read_csv(libraryfile_path) lib = lib if subset_rate is None else lib.sample( frac=subset_rate, random_state=2022) lib = lib.sort_values(['subject_id'], ignore_index=True) lib.to_csv(os.path.join(libraryfile_dir, f'{dataset_mode}_temporary.csv')) slides = [] for i, name in enumerate(lib['subject_id'].unique()): slides.append(name) grid = [] slideIDX = [] for i, g in enumerate(lib['subject_id'].unique()): tiles = lib[lib['subject_id'] == g]['slice_id'] grid.extend(tiles) slideIDX.extend([i]*len(tiles)) self.dataframe = self.load_data_and_get_class(lib) self.slidenames = list(lib['subject_id'].values) self.slides = slides self.targets = self.dataframe['Class'] self.grid = grid self.slideIDX = slideIDX self.transform = transform self.root_dir = root_dir self.dset = f"CRC_DX_{dataset_mode}" def setmode(self, mode): self.mode = mode def maketraindata(self, idxs): self.t_data = [(self.slideIDX[x], self.grid[x], self.targets[x]) for x in idxs] def shuffletraindata(self): self.t_data = random.sample(self.t_data, len(self.t_data)) def load_data_and_get_class(self, df): df.loc[df['label'] == 'MSI', 'Class'] = 1 df.loc[df['label'] == 'MSS', 'Class'] = 0 return df def __getitem__(self, index): if self.mode == 1: slideIDX = self.slideIDX[index] tile_id = self.grid[index] slide_id = self.slides[slideIDX] img_name = "blk-{}-{}.png".format(tile_id, slide_id) target = self.targets[index] label = 'CRC_DX_MSIMUT' if target == 1 else 'CRC_DX_MSS' img_path = os.path.join(self.root_dir, self.dset, label, img_name) img = io.imread(img_path) if self.transform is not None: img = self.transform(img) return img elif self.mode == 2: slideIDX, tile_id, target = self.t_data[index] slide_id = self.slides[slideIDX] label = 'CRC_DX_MSIMUT' if target == 1 else 'CRC_DX_MSS' img_name = "blk-{}-{}.png".format(tile_id, slide_id) img_path = os.path.join(self.root_dir, self.dset, label, img_name) img = io.imread(img_path) if self.transform is not None: img = self.transform(img) return img, target def __len__(self): if self.mode == 1: return len(self.grid) elif self.mode == 2: return len(self.t_data) class Lite(LightningLite): def run(self, args): global best_acc print(args) self.seed_everything(2022) model_name = args.model_name sample_rate = args.sample_rate ckpt_path = os.path.join(args.model_path, f'{args.model_name}_bs{args.batch_size}_lr{args.learning_rate}') ckpt_file_path = glob.glob(os.path.join(ckpt_path,'*.ckpt'))[0] model = MSI_MSS_Module.load_from_checkpoint(ckpt_file_path) optimizer = torch.optim.AdamW( model.parameters(), lr=args.learning_rate, weight_decay=1e-4) if args.weights == 0.5: criterion = nn.CrossEntropyLoss() else: w = torch.Tensor([1-args.weights, args.weights]) criterion = nn.CrossEntropyLoss(w) model, optimizer = self.setup(model, optimizer, move_to_device=True) DATA_MEANS = [0.485, 0.456, 0.406] DATA_STD = [0.229, 0.224, 0.225] train_transform = transforms.Compose([ transforms.ToPILImage(), transforms.ToTensor(), transforms.RandomHorizontalFlip(), transforms.Normalize(DATA_MEANS, DATA_STD)]) test_transform = transforms.Compose([ transforms.ToPILImage(), transforms.ToTensor(), transforms.Normalize(DATA_MEANS, DATA_STD)]) train_dataset = MILdataset( args.lib_dir, args.root_dir, 'Train', transform=train_transform, subset_rate=sample_rate) val_dataset = MILdataset( args.lib_dir, args.root_dir, 'Val', transform=test_transform, subset_rate=sample_rate) test_dataset = MILdataset( args.lib_dir, args.root_dir, 'Test', transform=test_transform, subset_rate=sample_rate) train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) val_dataloader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) test_dataloader = DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) train_dataloader, val_dataloader, test_dataloader = self.setup_dataloaders( train_dataloader, val_dataloader, test_dataloader, move_to_device=True) version_name = f'MIL_{model_name}_bs{args.batch_size}_lr{args.learning_rate}_w{args.weights}_k{args.k}_output' output_path = os.path.join(args.output_path,version_name) writer = SummaryWriter(output_path) for epoch in tqdm(range(args.nepochs)): train_dataset.setmode(1) probs = inference(train_dataloader, model) topk = group_argtopk( np.array(train_dataset.slideIDX), probs, args.k) train_dataset.maketraindata(topk) train_dataset.shuffletraindata() train_dataset.setmode(2) model.train() running_loss = 0. for i, (input, target) in enumerate(train_dataloader): output = model(input) loss = criterion(output, target.long()) optimizer.zero_grad() self.backward(loss) optimizer.step() running_loss += loss.item()*input.size(0) train_loss = running_loss/len(train_dataloader.dataset) print( 'Training\tEpoch: [{}/{}]\tLoss: {}'.format(epoch+1, args.nepochs, train_loss)) writer.add_scalar('train_loss', train_loss, epoch+1) if (epoch+1) % args.test_every == 0: val_dataset.setmode(1) probs = inference(val_dataloader, model) maxs = group_max(np.array(val_dataset.slideIDX), probs, len(val_dataset.targets)) pred = [1 if x >= 0.5 else 0 for x in probs] val_acc, err, fpr, fnr = calc_err(pred, val_dataset.targets) print('Validation\tEpoch: [{}/{}]\t ACC: {}\tError: {}\tFPR: {}\tFNR: {}'.format( epoch+1, args.nepochs, val_acc, err, fpr, fnr)) writer.add_scalar('val_acc', val_acc, epoch+1) writer.add_scalar('fpr', fpr, epoch+1) writer.add_scalar('fnr', fnr, epoch+1) err = (fpr+fnr)/2. if 1-err >= best_acc: best_acc = 1-err obj = { 'epoch': epoch+1, 'state_dict': model.state_dict(), 'best_acc': best_acc, 'optimizer': optimizer.state_dict() } torch.save(obj, os.path.join(output_path, 'checkpoint_best.pth')) ch = torch.load(os.path.join(output_path,'checkpoint_best.pth')) model.load_state_dict(ch['state_dict']) model = model.cuda() cudnn.benchmark = True train_dataset.setmode(1) val_dataset.setmode(1) test_dataset.setmode(1) probs = inference(train_dataloader, model) maxs = group_max(np.array(train_dataset.slideIDX), probs, len(train_dataset.targets)) fp = open(os.path.join(output_path, f'Train_{version_name}.csv'), 'w') fp.write('slides,tiles,target,prediction,probability\n') for slides, tiles, target, prob in zip(train_dataset.slidenames, train_dataset.grid, train_dataset.targets, probs): fp.write('{},{},{},{},{}\n'.format(slides, tiles, target, int(prob>=0.5), prob)) fp.close() probs = inference(val_dataloader, model) maxs = group_max(np.array(val_dataset.slideIDX), probs, len(val_dataset.targets)) fp = open(os.path.join(output_path, f'Val_{version_name}.csv'), 'w') fp.write('slides,tiles,target,prediction,probability\n') for slides, tiles, target, prob in zip(val_dataset.slidenames, val_dataset.grid, val_dataset.targets, probs): fp.write('{},{},{},{},{}\n'.format(slides, tiles, target, int(prob>=0.5), prob)) fp.close() probs = inference(test_dataloader, model) maxs = group_max(np.array(test_dataset.slideIDX), probs, len(test_dataset.targets)) fp = open(os.path.join(output_path, f'Test_{version_name}.csv'), 'w') fp.write('slides,tiles,target,prediction,probability\n') for slides, tiles, target, prob in zip(test_dataset.slidenames, test_dataset.grid, test_dataset.targets, probs): fp.write('{},{},{},{},{}\n'.format(slides, tiles, target, int(prob>=0.5), prob)) fp.close() pred = [1 if x >= 0.5 else 0 for x in probs] test_acc, err, fnr, fpr = calc_err(pred, test_dataset.targets) test_f1_score = f1_score(test_dataset.targets, pred, average='binary') try: test_auroc_score = roc_auc_score(test_dataset.targets, probs) writer.add_scalar("test_auroc_score", test_auroc_score) except ValueError: writer.add_scalar('test_auroc_score', .0) writer.add_scalar('test_f1_score', test_f1_score) writer.add_scalar('test_acc', test_acc) def main(args): Lite(devices="auto", accelerator="auto").run(args) if __name__ == "__main__": parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "--root_dir", type=Path, required=True, help="root directory of dataset", ) parser.add_argument( "--lib_dir", type=Path, required=True, help="root directory of libraryfile", ) parser.add_argument( "--model_path", type=Path, required=True, help="root directory of pretrained models", ) parser.add_argument( "--output_path", type=Path, required=True, help="output directory", ) parser.add_argument( "--model_name", default='alexnet', choices=('resnet18', 'resnet34', 'alexnet', 'vgg', 'squeezenet', 'densenet', 'inception'), type=str, help="model use for train", ) parser.add_argument( "--sample_rate", default=1, type=float, help="undersample rate", ) parser.add_argument( "--batch_size", default=128, type=int, help="batch size", ) parser.add_argument( "--learning_rate", default=1e-3, type=float, help="learning rate", ) parser.add_argument( "--num_workers", default=0, type=int, required=True, help="number of workers", ) parser.add_argument( "--nepochs", default=50, type=int, help="training epoch", ) parser.add_argument( '--test_every', default=1, type=int, help='test on val every (default: 10)') parser.add_argument( "--weights", default=0.5, type=float, help="unbalanced positive class weight (default: 0.5, balanced classes)", ) parser.add_argument( "--k", default=1, type=int, help="top k tiles are assumed to be of the same class as the slide (default: 1, standard MIL)", ) args = parser.parse_args() main(args)
true
true
f735f9f96a2b5bb581f1d6e28479603b2104d7a6
1,907
py
Python
scripts/generate_thumbnail.py
ardtieboy/Gruyaert
ebfc2979504d0fec0c34187fe98033c5c8fbea15
[ "CC-BY-3.0" ]
null
null
null
scripts/generate_thumbnail.py
ardtieboy/Gruyaert
ebfc2979504d0fec0c34187fe98033c5c8fbea15
[ "CC-BY-3.0" ]
null
null
null
scripts/generate_thumbnail.py
ardtieboy/Gruyaert
ebfc2979504d0fec0c34187fe98033c5c8fbea15
[ "CC-BY-3.0" ]
null
null
null
import os from PIL import Image import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-f', '--folder_path', type=str, help='folder with images which need a thumbnail', required=True) args = parser.parse_args() folder_path = args.folder_path + "/" print("Observed this: " + folder_path) size = [512, 512] def get_thumbnail(folder, filename, box, fit=True): img = Image.open(folder + filename) if img: # preresize image with factor 2, 4, 8 and fast algorithm factor = 1 while img.size[0] / factor > 2 * box[0] and img.size[1] * 2 / factor > 2 * box[1]: factor *= 2 if factor > 1: img.thumbnail((img.size[0] / factor, img.size[1] / factor), Image.NEAREST) # calculate the cropping box and get the cropped part if fit: x1 = y1 = 0 x2, y2 = img.size wRatio = 1.0 * x2 / box[0] hRatio = 1.0 * y2 / box[1] if hRatio > wRatio: y1 = int(y2 / 2 - box[1] * wRatio / 2) y2 = int(y2 / 2 + box[1] * wRatio / 2) else: x1 = int(x2 / 2 - box[0] * hRatio / 2) x2 = int(x2 / 2 + box[0] * hRatio / 2) img = img.crop((x1, y1, x2, y2)) # Resize the image with best quality algorithm ANTI-ALIAS img.thumbnail(box, Image.ANTIALIAS) output = folder + filename + "_thumbnail.jpg" img.save(output, "JPEG") return output for infile in os.listdir(folder_path): print("Removing old thumbnail entries") if "thumbnail" in infile: print("Removing " + infile) os.remove(folder_path + infile) for infile in os.listdir(folder_path): print(folder_path + infile) try: print(get_thumbnail(folder_path, infile, (512, 512))) except: print("Could not open " + infile)
34.672727
117
0.576822
import os from PIL import Image import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-f', '--folder_path', type=str, help='folder with images which need a thumbnail', required=True) args = parser.parse_args() folder_path = args.folder_path + "/" print("Observed this: " + folder_path) size = [512, 512] def get_thumbnail(folder, filename, box, fit=True): img = Image.open(folder + filename) if img: factor = 1 while img.size[0] / factor > 2 * box[0] and img.size[1] * 2 / factor > 2 * box[1]: factor *= 2 if factor > 1: img.thumbnail((img.size[0] / factor, img.size[1] / factor), Image.NEAREST) if fit: x1 = y1 = 0 x2, y2 = img.size wRatio = 1.0 * x2 / box[0] hRatio = 1.0 * y2 / box[1] if hRatio > wRatio: y1 = int(y2 / 2 - box[1] * wRatio / 2) y2 = int(y2 / 2 + box[1] * wRatio / 2) else: x1 = int(x2 / 2 - box[0] * hRatio / 2) x2 = int(x2 / 2 + box[0] * hRatio / 2) img = img.crop((x1, y1, x2, y2)) img.thumbnail(box, Image.ANTIALIAS) output = folder + filename + "_thumbnail.jpg" img.save(output, "JPEG") return output for infile in os.listdir(folder_path): print("Removing old thumbnail entries") if "thumbnail" in infile: print("Removing " + infile) os.remove(folder_path + infile) for infile in os.listdir(folder_path): print(folder_path + infile) try: print(get_thumbnail(folder_path, infile, (512, 512))) except: print("Could not open " + infile)
true
true
f735fabc28e42dba49575f3d3bcf92895802488f
1,422
py
Python
examples/np.py
krooken/dd
dda262e6f4582c7f0c77c56a3f3bdfccc2847b7a
[ "BSD-3-Clause" ]
90
2018-08-28T01:03:38.000Z
2022-03-28T19:36:37.000Z
examples/np.py
krooken/dd
dda262e6f4582c7f0c77c56a3f3bdfccc2847b7a
[ "BSD-3-Clause" ]
54
2018-07-25T00:10:57.000Z
2022-02-08T16:15:35.000Z
examples/np.py
krooken/dd
dda262e6f4582c7f0c77c56a3f3bdfccc2847b7a
[ "BSD-3-Clause" ]
21
2018-11-16T22:45:56.000Z
2021-12-31T02:03:54.000Z
"""How the variable order in a BDD affects the number of nodes. Reference ========= Randal Bryant "On the complexity of VLSI implementations and graph representations of Boolean functions with application to integer multiplication" TOC, 1991 https://doi.org/10.1109/12.73590 """ from dd import autoref as _bdd def comparing_two_variable_orders(): n = 6 # declare variables vrs = ['x{i}'.format(i=i) for i in range(2 * n)] bdd = _bdd.BDD() bdd.declare(*vrs) # equality constraints cause difficulties with BDD size expr_1 = r' /\ '.join( " x{i} <=> x{j} ".format(i=i, j=(i + n + 1) % (2*n)) for i in range(n)) u = bdd.add_expr(expr_1) expr_2 = r' /\ '.join( " x{i} <=> x{j} ".format(i=2 * i, j=(2 * i + 1)) for i in range(n)) v = bdd.add_expr(expr_2) bdd.collect_garbage() # an order that yields a small BDD for `expr` good_order = ['x{i}'.format(i=i - 1) for i in [1, 7, 3, 9, 5, 11, 2, 8, 4, 10, 6, 12]] # an order that yields a large BDD for `expr` bad_order = list(vrs) # plot _bdd.reorder(bdd, list_to_dict(good_order)) bdd.dump('good.pdf') _bdd.reorder(bdd, list_to_dict(bad_order)) bdd.dump('bad.pdf') def list_to_dict(c): return {var: level for level, var in enumerate(c)} def prime(s): return s + "'" if __name__ == '__main__': comparing_two_variable_orders()
26.830189
79
0.606892
from dd import autoref as _bdd def comparing_two_variable_orders(): n = 6 vrs = ['x{i}'.format(i=i) for i in range(2 * n)] bdd = _bdd.BDD() bdd.declare(*vrs) expr_1 = r' /\ '.join( " x{i} <=> x{j} ".format(i=i, j=(i + n + 1) % (2*n)) for i in range(n)) u = bdd.add_expr(expr_1) expr_2 = r' /\ '.join( " x{i} <=> x{j} ".format(i=2 * i, j=(2 * i + 1)) for i in range(n)) v = bdd.add_expr(expr_2) bdd.collect_garbage() good_order = ['x{i}'.format(i=i - 1) for i in [1, 7, 3, 9, 5, 11, 2, 8, 4, 10, 6, 12]] bad_order = list(vrs) _bdd.reorder(bdd, list_to_dict(good_order)) bdd.dump('good.pdf') _bdd.reorder(bdd, list_to_dict(bad_order)) bdd.dump('bad.pdf') def list_to_dict(c): return {var: level for level, var in enumerate(c)} def prime(s): return s + "'" if __name__ == '__main__': comparing_two_variable_orders()
true
true
f735fb673f5ace9c6c08a1fafb4cdaf48e3d9e85
129,146
py
Python
scipy/stats/_distn_infrastructure.py
siddhantwahal/scipy
411fbbda0f942fcce3e4b314efb11c4553baaa7c
[ "BSD-3-Clause" ]
1
2020-07-22T17:29:25.000Z
2020-07-22T17:29:25.000Z
scipy/stats/_distn_infrastructure.py
siddhantwahal/scipy
411fbbda0f942fcce3e4b314efb11c4553baaa7c
[ "BSD-3-Clause" ]
null
null
null
scipy/stats/_distn_infrastructure.py
siddhantwahal/scipy
411fbbda0f942fcce3e4b314efb11c4553baaa7c
[ "BSD-3-Clause" ]
null
null
null
# # Author: Travis Oliphant 2002-2011 with contributions from # SciPy Developers 2004-2011 # from scipy._lib._util import getfullargspec_no_self as _getfullargspec import sys import keyword import re import types import warnings import inspect from itertools import zip_longest from scipy._lib import doccer from ._distr_params import distcont, distdiscrete from scipy._lib._util import check_random_state from scipy._lib._util import _valarray as valarray from scipy.special import (comb, chndtr, entr, rel_entr, xlogy, ive) # for root finding for continuous distribution ppf, and max likelihood estimation from scipy import optimize # for functions of continuous distributions (e.g. moments, entropy, cdf) from scipy import integrate # to approximate the pdf of a continuous distribution given its cdf from scipy.misc import derivative from numpy import (arange, putmask, ravel, ones, shape, ndarray, zeros, floor, logical_and, log, sqrt, place, argmax, vectorize, asarray, nan, inf, isinf, NINF, empty) import numpy as np from ._constants import _XMAX # These are the docstring parts used for substitution in specific # distribution docstrings docheaders = {'methods': """\nMethods\n-------\n""", 'notes': """\nNotes\n-----\n""", 'examples': """\nExamples\n--------\n"""} _doc_rvs = """\ rvs(%(shapes)s, loc=0, scale=1, size=1, random_state=None) Random variates. """ _doc_pdf = """\ pdf(x, %(shapes)s, loc=0, scale=1) Probability density function. """ _doc_logpdf = """\ logpdf(x, %(shapes)s, loc=0, scale=1) Log of the probability density function. """ _doc_pmf = """\ pmf(k, %(shapes)s, loc=0, scale=1) Probability mass function. """ _doc_logpmf = """\ logpmf(k, %(shapes)s, loc=0, scale=1) Log of the probability mass function. """ _doc_cdf = """\ cdf(x, %(shapes)s, loc=0, scale=1) Cumulative distribution function. """ _doc_logcdf = """\ logcdf(x, %(shapes)s, loc=0, scale=1) Log of the cumulative distribution function. """ _doc_sf = """\ sf(x, %(shapes)s, loc=0, scale=1) Survival function (also defined as ``1 - cdf``, but `sf` is sometimes more accurate). """ _doc_logsf = """\ logsf(x, %(shapes)s, loc=0, scale=1) Log of the survival function. """ _doc_ppf = """\ ppf(q, %(shapes)s, loc=0, scale=1) Percent point function (inverse of ``cdf`` --- percentiles). """ _doc_isf = """\ isf(q, %(shapes)s, loc=0, scale=1) Inverse survival function (inverse of ``sf``). """ _doc_moment = """\ moment(n, %(shapes)s, loc=0, scale=1) Non-central moment of order n """ _doc_stats = """\ stats(%(shapes)s, loc=0, scale=1, moments='mv') Mean('m'), variance('v'), skew('s'), and/or kurtosis('k'). """ _doc_entropy = """\ entropy(%(shapes)s, loc=0, scale=1) (Differential) entropy of the RV. """ _doc_fit = """\ fit(data) Parameter estimates for generic data. See `scipy.stats.rv_continuous.fit <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.fit.html#scipy.stats.rv_continuous.fit>`__ for detailed documentation of the keyword arguments. """ _doc_expect = """\ expect(func, args=(%(shapes_)s), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds) Expected value of a function (of one argument) with respect to the distribution. """ _doc_expect_discrete = """\ expect(func, args=(%(shapes_)s), loc=0, lb=None, ub=None, conditional=False) Expected value of a function (of one argument) with respect to the distribution. """ _doc_median = """\ median(%(shapes)s, loc=0, scale=1) Median of the distribution. """ _doc_mean = """\ mean(%(shapes)s, loc=0, scale=1) Mean of the distribution. """ _doc_var = """\ var(%(shapes)s, loc=0, scale=1) Variance of the distribution. """ _doc_std = """\ std(%(shapes)s, loc=0, scale=1) Standard deviation of the distribution. """ _doc_interval = """\ interval(alpha, %(shapes)s, loc=0, scale=1) Endpoints of the range that contains alpha percent of the distribution """ _doc_allmethods = ''.join([docheaders['methods'], _doc_rvs, _doc_pdf, _doc_logpdf, _doc_cdf, _doc_logcdf, _doc_sf, _doc_logsf, _doc_ppf, _doc_isf, _doc_moment, _doc_stats, _doc_entropy, _doc_fit, _doc_expect, _doc_median, _doc_mean, _doc_var, _doc_std, _doc_interval]) _doc_default_longsummary = """\ As an instance of the `rv_continuous` class, `%(name)s` object inherits from it a collection of generic methods (see below for the full list), and completes them with details specific for this particular distribution. """ _doc_default_frozen_note = """ Alternatively, the object may be called (as a function) to fix the shape, location, and scale parameters returning a "frozen" continuous RV object: rv = %(name)s(%(shapes)s, loc=0, scale=1) - Frozen RV object with the same methods but holding the given shape, location, and scale fixed. """ _doc_default_example = """\ Examples -------- >>> from scipy.stats import %(name)s >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) Calculate a few first moments: %(set_vals_stmt)s >>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk') Display the probability density function (``pdf``): >>> x = np.linspace(%(name)s.ppf(0.01, %(shapes)s), ... %(name)s.ppf(0.99, %(shapes)s), 100) >>> ax.plot(x, %(name)s.pdf(x, %(shapes)s), ... 'r-', lw=5, alpha=0.6, label='%(name)s pdf') Alternatively, the distribution object can be called (as a function) to fix the shape, location and scale parameters. This returns a "frozen" RV object holding the given parameters fixed. Freeze the distribution and display the frozen ``pdf``: >>> rv = %(name)s(%(shapes)s) >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') Check accuracy of ``cdf`` and ``ppf``: >>> vals = %(name)s.ppf([0.001, 0.5, 0.999], %(shapes)s) >>> np.allclose([0.001, 0.5, 0.999], %(name)s.cdf(vals, %(shapes)s)) True Generate random numbers: >>> r = %(name)s.rvs(%(shapes)s, size=1000) And compare the histogram: >>> ax.hist(r, density=True, histtype='stepfilled', alpha=0.2) >>> ax.legend(loc='best', frameon=False) >>> plt.show() """ _doc_default_locscale = """\ The probability density above is defined in the "standardized" form. To shift and/or scale the distribution use the ``loc`` and ``scale`` parameters. Specifically, ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with ``y = (x - loc) / scale``. """ _doc_default = ''.join([_doc_default_longsummary, _doc_allmethods, '\n', _doc_default_example]) _doc_default_before_notes = ''.join([_doc_default_longsummary, _doc_allmethods]) docdict = { 'rvs': _doc_rvs, 'pdf': _doc_pdf, 'logpdf': _doc_logpdf, 'cdf': _doc_cdf, 'logcdf': _doc_logcdf, 'sf': _doc_sf, 'logsf': _doc_logsf, 'ppf': _doc_ppf, 'isf': _doc_isf, 'stats': _doc_stats, 'entropy': _doc_entropy, 'fit': _doc_fit, 'moment': _doc_moment, 'expect': _doc_expect, 'interval': _doc_interval, 'mean': _doc_mean, 'std': _doc_std, 'var': _doc_var, 'median': _doc_median, 'allmethods': _doc_allmethods, 'longsummary': _doc_default_longsummary, 'frozennote': _doc_default_frozen_note, 'example': _doc_default_example, 'default': _doc_default, 'before_notes': _doc_default_before_notes, 'after_notes': _doc_default_locscale } # Reuse common content between continuous and discrete docs, change some # minor bits. docdict_discrete = docdict.copy() docdict_discrete['pmf'] = _doc_pmf docdict_discrete['logpmf'] = _doc_logpmf docdict_discrete['expect'] = _doc_expect_discrete _doc_disc_methods = ['rvs', 'pmf', 'logpmf', 'cdf', 'logcdf', 'sf', 'logsf', 'ppf', 'isf', 'stats', 'entropy', 'expect', 'median', 'mean', 'var', 'std', 'interval'] for obj in _doc_disc_methods: docdict_discrete[obj] = docdict_discrete[obj].replace(', scale=1', '') _doc_disc_methods_err_varname = ['cdf', 'logcdf', 'sf', 'logsf'] for obj in _doc_disc_methods_err_varname: docdict_discrete[obj] = docdict_discrete[obj].replace('(x, ', '(k, ') docdict_discrete.pop('pdf') docdict_discrete.pop('logpdf') _doc_allmethods = ''.join([docdict_discrete[obj] for obj in _doc_disc_methods]) docdict_discrete['allmethods'] = docheaders['methods'] + _doc_allmethods docdict_discrete['longsummary'] = _doc_default_longsummary.replace( 'rv_continuous', 'rv_discrete') _doc_default_frozen_note = """ Alternatively, the object may be called (as a function) to fix the shape and location parameters returning a "frozen" discrete RV object: rv = %(name)s(%(shapes)s, loc=0) - Frozen RV object with the same methods but holding the given shape and location fixed. """ docdict_discrete['frozennote'] = _doc_default_frozen_note _doc_default_discrete_example = """\ Examples -------- >>> from scipy.stats import %(name)s >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) Calculate a few first moments: %(set_vals_stmt)s >>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk') Display the probability mass function (``pmf``): >>> x = np.arange(%(name)s.ppf(0.01, %(shapes)s), ... %(name)s.ppf(0.99, %(shapes)s)) >>> ax.plot(x, %(name)s.pmf(x, %(shapes)s), 'bo', ms=8, label='%(name)s pmf') >>> ax.vlines(x, 0, %(name)s.pmf(x, %(shapes)s), colors='b', lw=5, alpha=0.5) Alternatively, the distribution object can be called (as a function) to fix the shape and location. This returns a "frozen" RV object holding the given parameters fixed. Freeze the distribution and display the frozen ``pmf``: >>> rv = %(name)s(%(shapes)s) >>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1, ... label='frozen pmf') >>> ax.legend(loc='best', frameon=False) >>> plt.show() Check accuracy of ``cdf`` and ``ppf``: >>> prob = %(name)s.cdf(x, %(shapes)s) >>> np.allclose(x, %(name)s.ppf(prob, %(shapes)s)) True Generate random numbers: >>> r = %(name)s.rvs(%(shapes)s, size=1000) """ _doc_default_discrete_locscale = """\ The probability mass function above is defined in the "standardized" form. To shift distribution use the ``loc`` parameter. Specifically, ``%(name)s.pmf(k, %(shapes)s, loc)`` is identically equivalent to ``%(name)s.pmf(k - loc, %(shapes)s)``. """ docdict_discrete['example'] = _doc_default_discrete_example docdict_discrete['after_notes'] = _doc_default_discrete_locscale _doc_default_before_notes = ''.join([docdict_discrete['longsummary'], docdict_discrete['allmethods']]) docdict_discrete['before_notes'] = _doc_default_before_notes _doc_default_disc = ''.join([docdict_discrete['longsummary'], docdict_discrete['allmethods'], docdict_discrete['frozennote'], docdict_discrete['example']]) docdict_discrete['default'] = _doc_default_disc # clean up all the separate docstring elements, we do not need them anymore for obj in [s for s in dir() if s.startswith('_doc_')]: exec('del ' + obj) del obj def _moment(data, n, mu=None): if mu is None: mu = data.mean() return ((data - mu)**n).mean() def _moment_from_stats(n, mu, mu2, g1, g2, moment_func, args): if (n == 0): return 1.0 elif (n == 1): if mu is None: val = moment_func(1, *args) else: val = mu elif (n == 2): if mu2 is None or mu is None: val = moment_func(2, *args) else: val = mu2 + mu*mu elif (n == 3): if g1 is None or mu2 is None or mu is None: val = moment_func(3, *args) else: mu3 = g1 * np.power(mu2, 1.5) # 3rd central moment val = mu3+3*mu*mu2+mu*mu*mu # 3rd non-central moment elif (n == 4): if g1 is None or g2 is None or mu2 is None or mu is None: val = moment_func(4, *args) else: mu4 = (g2+3.0)*(mu2**2.0) # 4th central moment mu3 = g1*np.power(mu2, 1.5) # 3rd central moment val = mu4+4*mu*mu3+6*mu*mu*mu2+mu*mu*mu*mu else: val = moment_func(n, *args) return val def _skew(data): """ skew is third central moment / variance**(1.5) """ data = np.ravel(data) mu = data.mean() m2 = ((data - mu)**2).mean() m3 = ((data - mu)**3).mean() return m3 / np.power(m2, 1.5) def _kurtosis(data): """ kurtosis is fourth central moment / variance**2 - 3 """ data = np.ravel(data) mu = data.mean() m2 = ((data - mu)**2).mean() m4 = ((data - mu)**4).mean() return m4 / m2**2 - 3 # Frozen RV class class rv_frozen(object): def __init__(self, dist, *args, **kwds): self.args = args self.kwds = kwds # create a new instance self.dist = dist.__class__(**dist._updated_ctor_param()) shapes, _, _ = self.dist._parse_args(*args, **kwds) self.a, self.b = self.dist._get_support(*shapes) @property def random_state(self): return self.dist._random_state @random_state.setter def random_state(self, seed): self.dist._random_state = check_random_state(seed) def pdf(self, x): # raises AttributeError in frozen discrete distribution return self.dist.pdf(x, *self.args, **self.kwds) def logpdf(self, x): return self.dist.logpdf(x, *self.args, **self.kwds) def cdf(self, x): return self.dist.cdf(x, *self.args, **self.kwds) def logcdf(self, x): return self.dist.logcdf(x, *self.args, **self.kwds) def ppf(self, q): return self.dist.ppf(q, *self.args, **self.kwds) def isf(self, q): return self.dist.isf(q, *self.args, **self.kwds) def rvs(self, size=None, random_state=None): kwds = self.kwds.copy() kwds.update({'size': size, 'random_state': random_state}) return self.dist.rvs(*self.args, **kwds) def sf(self, x): return self.dist.sf(x, *self.args, **self.kwds) def logsf(self, x): return self.dist.logsf(x, *self.args, **self.kwds) def stats(self, moments='mv'): kwds = self.kwds.copy() kwds.update({'moments': moments}) return self.dist.stats(*self.args, **kwds) def median(self): return self.dist.median(*self.args, **self.kwds) def mean(self): return self.dist.mean(*self.args, **self.kwds) def var(self): return self.dist.var(*self.args, **self.kwds) def std(self): return self.dist.std(*self.args, **self.kwds) def moment(self, n): return self.dist.moment(n, *self.args, **self.kwds) def entropy(self): return self.dist.entropy(*self.args, **self.kwds) def pmf(self, k): return self.dist.pmf(k, *self.args, **self.kwds) def logpmf(self, k): return self.dist.logpmf(k, *self.args, **self.kwds) def interval(self, alpha): return self.dist.interval(alpha, *self.args, **self.kwds) def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds): # expect method only accepts shape parameters as positional args # hence convert self.args, self.kwds, also loc/scale # See the .expect method docstrings for the meaning of # other parameters. a, loc, scale = self.dist._parse_args(*self.args, **self.kwds) if isinstance(self.dist, rv_discrete): return self.dist.expect(func, a, loc, lb, ub, conditional, **kwds) else: return self.dist.expect(func, a, loc, scale, lb, ub, conditional, **kwds) def support(self): return self.dist.support(*self.args, **self.kwds) # This should be rewritten def argsreduce(cond, *args): """Return the sequence of ravel(args[i]) where ravel(condition) is True in 1D. Examples -------- >>> import numpy as np >>> rand = np.random.random_sample >>> A = rand((4, 5)) >>> B = 2 >>> C = rand((1, 5)) >>> cond = np.ones(A.shape) >>> [A1, B1, C1] = argsreduce(cond, A, B, C) >>> B1.shape (20,) >>> cond[2,:] = 0 >>> [A2, B2, C2] = argsreduce(cond, A, B, C) >>> B2.shape (15,) """ newargs = np.atleast_1d(*args) if not isinstance(newargs, list): newargs = [newargs, ] expand_arr = (cond == cond) return [np.extract(cond, arr1 * expand_arr) for arr1 in newargs] parse_arg_template = """ def _parse_args(self, %(shape_arg_str)s %(locscale_in)s): return (%(shape_arg_str)s), %(locscale_out)s def _parse_args_rvs(self, %(shape_arg_str)s %(locscale_in)s, size=None): return self._argcheck_rvs(%(shape_arg_str)s %(locscale_out)s, size=size) def _parse_args_stats(self, %(shape_arg_str)s %(locscale_in)s, moments='mv'): return (%(shape_arg_str)s), %(locscale_out)s, moments """ # Both the continuous and discrete distributions depend on ncx2. # The function name ncx2 is an abbreviation for noncentral chi squared. def _ncx2_log_pdf(x, df, nc): # We use (xs**2 + ns**2)/2 = (xs - ns)**2/2 + xs*ns, and include the # factor of exp(-xs*ns) into the ive function to improve numerical # stability at large values of xs. See also `rice.pdf`. df2 = df/2.0 - 1.0 xs, ns = np.sqrt(x), np.sqrt(nc) res = xlogy(df2/2.0, x/nc) - 0.5*(xs - ns)**2 res += np.log(ive(df2, xs*ns) / 2.0) return res def _ncx2_pdf(x, df, nc): return np.exp(_ncx2_log_pdf(x, df, nc)) def _ncx2_cdf(x, df, nc): return chndtr(x, df, nc) class rv_generic(object): """Class which encapsulates common functionality between rv_discrete and rv_continuous. """ def __init__(self, seed=None): super(rv_generic, self).__init__() # figure out if _stats signature has 'moments' keyword sig = _getfullargspec(self._stats) self._stats_has_moments = ((sig.varkw is not None) or ('moments' in sig.args) or ('moments' in sig.kwonlyargs)) self._random_state = check_random_state(seed) # For historical reasons, `size` was made an attribute that was read # inside _rvs(). The code is being changed so that 'size' is an argument # to self._rvs(). However some external (non-SciPy) distributions have not # been updated. Maintain backwards compatibility by checking if # the self._rvs() signature has the 'size' keyword, or a **kwarg, # and if not set self._size inside self.rvs() before calling self._rvs(). argspec = inspect.getfullargspec(self._rvs) self._rvs_uses_size_attribute = (argspec.varkw is None and 'size' not in argspec.args and 'size' not in argspec.kwonlyargs) # Warn on first use only self._rvs_size_warned = False @property def random_state(self): """ Get or set the RandomState object for generating random variates. This can be either None, int, a RandomState instance, or a np.random.Generator instance. If None (or np.random), use the RandomState singleton used by np.random. If already a RandomState or Generator instance, use it. If an int, use a new RandomState instance seeded with seed. """ return self._random_state @random_state.setter def random_state(self, seed): self._random_state = check_random_state(seed) def __getstate__(self): return self._updated_ctor_param(), self._random_state def __setstate__(self, state): ctor_param, r = state self.__init__(**ctor_param) self._random_state = r return self def _construct_argparser( self, meths_to_inspect, locscale_in, locscale_out): """Construct the parser for the shape arguments. Generates the argument-parsing functions dynamically and attaches them to the instance. Is supposed to be called in __init__ of a class for each distribution. If self.shapes is a non-empty string, interprets it as a comma-separated list of shape parameters. Otherwise inspects the call signatures of `meths_to_inspect` and constructs the argument-parsing functions from these. In this case also sets `shapes` and `numargs`. """ if self.shapes: # sanitize the user-supplied shapes if not isinstance(self.shapes, str): raise TypeError('shapes must be a string.') shapes = self.shapes.replace(',', ' ').split() for field in shapes: if keyword.iskeyword(field): raise SyntaxError('keywords cannot be used as shapes.') if not re.match('^[_a-zA-Z][_a-zA-Z0-9]*$', field): raise SyntaxError( 'shapes must be valid python identifiers') else: # find out the call signatures (_pdf, _cdf etc), deduce shape # arguments. Generic methods only have 'self, x', any further args # are shapes. shapes_list = [] for meth in meths_to_inspect: shapes_args = _getfullargspec(meth) # NB: does not contain self args = shapes_args.args[1:] # peel off 'x', too if args: shapes_list.append(args) # *args or **kwargs are not allowed w/automatic shapes if shapes_args.varargs is not None: raise TypeError( '*args are not allowed w/out explicit shapes') if shapes_args.varkw is not None: raise TypeError( '**kwds are not allowed w/out explicit shapes') if shapes_args.kwonlyargs: raise TypeError( 'kwonly args are not allowed w/out explicit shapes') if shapes_args.defaults is not None: raise TypeError('defaults are not allowed for shapes') if shapes_list: shapes = shapes_list[0] # make sure the signatures are consistent for item in shapes_list: if item != shapes: raise TypeError('Shape arguments are inconsistent.') else: shapes = [] # have the arguments, construct the method from template shapes_str = ', '.join(shapes) + ', ' if shapes else '' # NB: not None dct = dict(shape_arg_str=shapes_str, locscale_in=locscale_in, locscale_out=locscale_out, ) ns = {} exec(parse_arg_template % dct, ns) # NB: attach to the instance, not class for name in ['_parse_args', '_parse_args_stats', '_parse_args_rvs']: setattr(self, name, types.MethodType(ns[name], self)) self.shapes = ', '.join(shapes) if shapes else None if not hasattr(self, 'numargs'): # allows more general subclassing with *args self.numargs = len(shapes) def _construct_doc(self, docdict, shapes_vals=None): """Construct the instance docstring with string substitutions.""" tempdict = docdict.copy() tempdict['name'] = self.name or 'distname' tempdict['shapes'] = self.shapes or '' if shapes_vals is None: shapes_vals = () vals = ', '.join('%.3g' % val for val in shapes_vals) tempdict['vals'] = vals tempdict['shapes_'] = self.shapes or '' if self.shapes and self.numargs == 1: tempdict['shapes_'] += ',' if self.shapes: tempdict['set_vals_stmt'] = '>>> %s = %s' % (self.shapes, vals) else: tempdict['set_vals_stmt'] = '' if self.shapes is None: # remove shapes from call parameters if there are none for item in ['default', 'before_notes']: tempdict[item] = tempdict[item].replace( "\n%(shapes)s : array_like\n shape parameters", "") for i in range(2): if self.shapes is None: # necessary because we use %(shapes)s in two forms (w w/o ", ") self.__doc__ = self.__doc__.replace("%(shapes)s, ", "") try: self.__doc__ = doccer.docformat(self.__doc__, tempdict) except TypeError as e: raise Exception("Unable to construct docstring for distribution \"%s\": %s" % (self.name, repr(e))) # correct for empty shapes self.__doc__ = self.__doc__.replace('(, ', '(').replace(', )', ')') def _construct_default_doc(self, longname=None, extradoc=None, docdict=None, discrete='continuous'): """Construct instance docstring from the default template.""" if longname is None: longname = 'A' if extradoc is None: extradoc = '' if extradoc.startswith('\n\n'): extradoc = extradoc[2:] self.__doc__ = ''.join(['%s %s random variable.' % (longname, discrete), '\n\n%(before_notes)s\n', docheaders['notes'], extradoc, '\n%(example)s']) self._construct_doc(docdict) def freeze(self, *args, **kwds): """Freeze the distribution for the given arguments. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution. Should include all the non-optional arguments, may include ``loc`` and ``scale``. Returns ------- rv_frozen : rv_frozen instance The frozen distribution. """ return rv_frozen(self, *args, **kwds) def __call__(self, *args, **kwds): return self.freeze(*args, **kwds) __call__.__doc__ = freeze.__doc__ # The actual calculation functions (no basic checking need be done) # If these are defined, the others won't be looked at. # Otherwise, the other set can be defined. def _stats(self, *args, **kwds): return None, None, None, None # Noncentral moments (also known as the moment about the origin). # Expressed in LaTeX, munp would be $\mu'_{n}$, i.e. "mu-sub-n-prime". # The primed mu is a widely used notation for the noncentral moment. def _munp(self, n, *args): # Silence floating point warnings from integration. with np.errstate(all='ignore'): vals = self.generic_moment(n, *args) return vals def _argcheck_rvs(self, *args, **kwargs): # Handle broadcasting and size validation of the rvs method. # Subclasses should not have to override this method. # The rule is that if `size` is not None, then `size` gives the # shape of the result (integer values of `size` are treated as # tuples with length 1; i.e. `size=3` is the same as `size=(3,)`.) # # `args` is expected to contain the shape parameters (if any), the # location and the scale in a flat tuple (e.g. if there are two # shape parameters `a` and `b`, `args` will be `(a, b, loc, scale)`). # The only keyword argument expected is 'size'. size = kwargs.get('size', None) all_bcast = np.broadcast_arrays(*args) def squeeze_left(a): while a.ndim > 0 and a.shape[0] == 1: a = a[0] return a # Eliminate trivial leading dimensions. In the convention # used by numpy's random variate generators, trivial leading # dimensions are effectively ignored. In other words, when `size` # is given, trivial leading dimensions of the broadcast parameters # in excess of the number of dimensions in size are ignored, e.g. # >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]], size=3) # array([ 1.00104267, 3.00422496, 4.99799278]) # If `size` is not given, the exact broadcast shape is preserved: # >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]]) # array([[[[ 1.00862899, 3.00061431, 4.99867122]]]]) # all_bcast = [squeeze_left(a) for a in all_bcast] bcast_shape = all_bcast[0].shape bcast_ndim = all_bcast[0].ndim if size is None: size_ = bcast_shape else: size_ = tuple(np.atleast_1d(size)) # Check compatibility of size_ with the broadcast shape of all # the parameters. This check is intended to be consistent with # how the numpy random variate generators (e.g. np.random.normal, # np.random.beta) handle their arguments. The rule is that, if size # is given, it determines the shape of the output. Broadcasting # can't change the output size. # This is the standard broadcasting convention of extending the # shape with fewer dimensions with enough dimensions of length 1 # so that the two shapes have the same number of dimensions. ndiff = bcast_ndim - len(size_) if ndiff < 0: bcast_shape = (1,)*(-ndiff) + bcast_shape elif ndiff > 0: size_ = (1,)*ndiff + size_ # This compatibility test is not standard. In "regular" broadcasting, # two shapes are compatible if for each dimension, the lengths are the # same or one of the lengths is 1. Here, the length of a dimension in # size_ must not be less than the corresponding length in bcast_shape. ok = all([bcdim == 1 or bcdim == szdim for (bcdim, szdim) in zip(bcast_shape, size_)]) if not ok: raise ValueError("size does not match the broadcast shape of " "the parameters. %s, %s, %s" % (size, size_, bcast_shape)) param_bcast = all_bcast[:-2] loc_bcast = all_bcast[-2] scale_bcast = all_bcast[-1] return param_bcast, loc_bcast, scale_bcast, size_ ## These are the methods you must define (standard form functions) ## NB: generic _pdf, _logpdf, _cdf are different for ## rv_continuous and rv_discrete hence are defined in there def _argcheck(self, *args): """Default check for correct values on args and keywords. Returns condition array of 1's where arguments are correct and 0's where they are not. """ cond = 1 for arg in args: cond = logical_and(cond, (asarray(arg) > 0)) return cond def _get_support(self, *args, **kwargs): """Return the support of the (unscaled, unshifted) distribution. *Must* be overridden by distributions which have support dependent upon the shape parameters of the distribution. Any such override *must not* set or change any of the class members, as these members are shared amongst all instances of the distribution. Parameters ---------- arg1, arg2, ... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). Returns ------- a, b : numeric (float, or int or +/-np.inf) end-points of the distribution's support for the specified shape parameters. """ return self.a, self.b def _support_mask(self, x, *args): a, b = self._get_support(*args) with np.errstate(invalid='ignore'): return (a <= x) & (x <= b) def _open_support_mask(self, x, *args): a, b = self._get_support(*args) with np.errstate(invalid='ignore'): return (a < x) & (x < b) def _rvs(self, *args, size=None, random_state=None): # This method must handle size being a tuple, and it must # properly broadcast *args and size. size might be # an empty tuple, which means a scalar random variate is to be # generated. ## Use basic inverse cdf algorithm for RV generation as default. U = random_state.uniform(size=size) Y = self._ppf(U, *args) return Y def _logcdf(self, x, *args): with np.errstate(divide='ignore'): return log(self._cdf(x, *args)) def _sf(self, x, *args): return 1.0-self._cdf(x, *args) def _logsf(self, x, *args): with np.errstate(divide='ignore'): return log(self._sf(x, *args)) def _ppf(self, q, *args): return self._ppfvec(q, *args) def _isf(self, q, *args): return self._ppf(1.0-q, *args) # use correct _ppf for subclasses # These are actually called, and should not be overwritten if you # want to keep error checking. def rvs(self, *args, **kwds): """ Random variates of given type. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). scale : array_like, optional Scale parameter (default=1). size : int or tuple of ints, optional Defining number of random variates (default is 1). random_state : {None, int, `~np.random.RandomState`, `~np.random.Generator`}, optional If `seed` is `None` the `~np.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with seed. If `seed` is already a ``RandomState`` or ``Generator`` instance, then that object is used. Default is None. Returns ------- rvs : ndarray or scalar Random variates of given `size`. """ discrete = kwds.pop('discrete', None) rndm = kwds.pop('random_state', None) args, loc, scale, size = self._parse_args_rvs(*args, **kwds) cond = logical_and(self._argcheck(*args), (scale >= 0)) if not np.all(cond): raise ValueError("Domain error in arguments.") if np.all(scale == 0): return loc*ones(size, 'd') # extra gymnastics needed for a custom random_state if rndm is not None: random_state_saved = self._random_state random_state = check_random_state(rndm) else: random_state = self._random_state # Maintain backwards compatibility by setting self._size # for distributions that still need it. if self._rvs_uses_size_attribute: if not self._rvs_size_warned: warnings.warn( f'The signature of {self._rvs} does not contain ' f'a "size" keyword. Such signatures are deprecated.', np.VisibleDeprecationWarning) self._rvs_size_warned = True self._size = size self._random_state = random_state vals = self._rvs(*args) else: vals = self._rvs(*args, size=size, random_state=random_state) vals = vals * scale + loc # do not forget to restore the _random_state if rndm is not None: self._random_state = random_state_saved # Cast to int if discrete if discrete: if size == (): vals = int(vals) else: vals = vals.astype(int) return vals def stats(self, *args, **kwds): """ Some statistics of the given RV. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional (continuous RVs only) scale parameter (default=1) moments : str, optional composed of letters ['mvsk'] defining which moments to compute: 'm' = mean, 'v' = variance, 's' = (Fisher's) skew, 'k' = (Fisher's) kurtosis. (default is 'mv') Returns ------- stats : sequence of requested moments. """ args, loc, scale, moments = self._parse_args_stats(*args, **kwds) # scale = 1 by construction for discrete RVs loc, scale = map(asarray, (loc, scale)) args = tuple(map(asarray, args)) cond = self._argcheck(*args) & (scale > 0) & (loc == loc) output = [] default = valarray(shape(cond), self.badvalue) # Use only entries that are valid in calculation if np.any(cond): goodargs = argsreduce(cond, *(args+(scale, loc))) scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] if self._stats_has_moments: mu, mu2, g1, g2 = self._stats(*goodargs, **{'moments': moments}) else: mu, mu2, g1, g2 = self._stats(*goodargs) if g1 is None: mu3 = None else: if mu2 is None: mu2 = self._munp(2, *goodargs) if g2 is None: # (mu2**1.5) breaks down for nan and inf mu3 = g1 * np.power(mu2, 1.5) if 'm' in moments: if mu is None: mu = self._munp(1, *goodargs) out0 = default.copy() place(out0, cond, mu * scale + loc) output.append(out0) if 'v' in moments: if mu2 is None: mu2p = self._munp(2, *goodargs) if mu is None: mu = self._munp(1, *goodargs) # if mean is inf then var is also inf with np.errstate(invalid='ignore'): mu2 = np.where(np.isfinite(mu), mu2p - mu**2, np.inf) out0 = default.copy() place(out0, cond, mu2 * scale * scale) output.append(out0) if 's' in moments: if g1 is None: mu3p = self._munp(3, *goodargs) if mu is None: mu = self._munp(1, *goodargs) if mu2 is None: mu2p = self._munp(2, *goodargs) mu2 = mu2p - mu * mu with np.errstate(invalid='ignore'): mu3 = (-mu*mu - 3*mu2)*mu + mu3p g1 = mu3 / np.power(mu2, 1.5) out0 = default.copy() place(out0, cond, g1) output.append(out0) if 'k' in moments: if g2 is None: mu4p = self._munp(4, *goodargs) if mu is None: mu = self._munp(1, *goodargs) if mu2 is None: mu2p = self._munp(2, *goodargs) mu2 = mu2p - mu * mu if mu3 is None: mu3p = self._munp(3, *goodargs) with np.errstate(invalid='ignore'): mu3 = (-mu * mu - 3 * mu2) * mu + mu3p with np.errstate(invalid='ignore'): mu4 = ((-mu**2 - 6*mu2) * mu - 4*mu3)*mu + mu4p g2 = mu4 / mu2**2.0 - 3.0 out0 = default.copy() place(out0, cond, g2) output.append(out0) else: # no valid args output = [default.copy() for _ in moments] if len(output) == 1: return output[0] else: return tuple(output) def entropy(self, *args, **kwds): """ Differential entropy of the RV. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). scale : array_like, optional (continuous distributions only). Scale parameter (default=1). Notes ----- Entropy is defined base `e`: >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5))) >>> np.allclose(drv.entropy(), np.log(2.0)) True """ args, loc, scale = self._parse_args(*args, **kwds) # NB: for discrete distributions scale=1 by construction in _parse_args loc, scale = map(asarray, (loc, scale)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) output = zeros(shape(cond0), 'd') place(output, (1-cond0), self.badvalue) goodargs = argsreduce(cond0, scale, *args) goodscale = goodargs[0] goodargs = goodargs[1:] place(output, cond0, self.vecentropy(*goodargs) + log(goodscale)) return output def moment(self, n, *args, **kwds): """ n-th order non-central moment of distribution. Parameters ---------- n : int, n >= 1 Order of moment. arg1, arg2, arg3,... : float The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) """ args, loc, scale = self._parse_args(*args, **kwds) if not (self._argcheck(*args) and (scale > 0)): return nan if (floor(n) != n): raise ValueError("Moment must be an integer.") if (n < 0): raise ValueError("Moment must be positive.") mu, mu2, g1, g2 = None, None, None, None if (n > 0) and (n < 5): if self._stats_has_moments: mdict = {'moments': {1: 'm', 2: 'v', 3: 'vs', 4: 'vk'}[n]} else: mdict = {} mu, mu2, g1, g2 = self._stats(*args, **mdict) val = _moment_from_stats(n, mu, mu2, g1, g2, self._munp, args) # Convert to transformed X = L + S*Y # E[X^n] = E[(L+S*Y)^n] = L^n sum(comb(n, k)*(S/L)^k E[Y^k], k=0...n) if loc == 0: return scale**n * val else: result = 0 fac = float(scale) / float(loc) for k in range(n): valk = _moment_from_stats(k, mu, mu2, g1, g2, self._munp, args) result += comb(n, k, exact=True)*(fac**k) * valk result += fac**n * val return result * loc**n def median(self, *args, **kwds): """ Median of the distribution. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional Location parameter, Default is 0. scale : array_like, optional Scale parameter, Default is 1. Returns ------- median : float The median of the distribution. See Also -------- rv_discrete.ppf Inverse of the CDF """ return self.ppf(0.5, *args, **kwds) def mean(self, *args, **kwds): """ Mean of the distribution. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- mean : float the mean of the distribution """ kwds['moments'] = 'm' res = self.stats(*args, **kwds) if isinstance(res, ndarray) and res.ndim == 0: return res[()] return res def var(self, *args, **kwds): """ Variance of the distribution. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- var : float the variance of the distribution """ kwds['moments'] = 'v' res = self.stats(*args, **kwds) if isinstance(res, ndarray) and res.ndim == 0: return res[()] return res def std(self, *args, **kwds): """ Standard deviation of the distribution. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- std : float standard deviation of the distribution """ kwds['moments'] = 'v' res = sqrt(self.stats(*args, **kwds)) return res def interval(self, alpha, *args, **kwds): """ Confidence interval with equal areas around the median. Parameters ---------- alpha : array_like of float Probability that an rv will be drawn from the returned range. Each value should be in the range [0, 1]. arg1, arg2, ... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional location parameter, Default is 0. scale : array_like, optional scale parameter, Default is 1. Returns ------- a, b : ndarray of float end-points of range that contain ``100 * alpha %`` of the rv's possible values. """ alpha = asarray(alpha) if np.any((alpha > 1) | (alpha < 0)): raise ValueError("alpha must be between 0 and 1 inclusive") q1 = (1.0-alpha)/2 q2 = (1.0+alpha)/2 a = self.ppf(q1, *args, **kwds) b = self.ppf(q2, *args, **kwds) return a, b def support(self, *args, **kwargs): """ Return the support of the distribution. Parameters ---------- arg1, arg2, ... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional location parameter, Default is 0. scale : array_like, optional scale parameter, Default is 1. Returns ------- a, b : float end-points of the distribution's support. """ args, loc, scale = self._parse_args(*args, **kwargs) _a, _b = self._get_support(*args) return _a * scale + loc, _b * scale + loc def _get_fixed_fit_value(kwds, names): """ Given names such as `['f0', 'fa', 'fix_a']`, check that there is at most one non-None value in `kwds` associaed with those names. Return that value, or None if none of the names occur in `kwds`. As a side effect, all occurrences of those names in `kwds` are removed. """ vals = [(name, kwds.pop(name)) for name in names if name in kwds] if len(vals) > 1: repeated = [name for name, val in vals] raise ValueError("fit method got multiple keyword arguments to " "specify the same fixed parameter: " + ', '.join(repeated)) return vals[0][1] if vals else None ## continuous random variables: implement maybe later ## ## hf --- Hazard Function (PDF / SF) ## chf --- Cumulative hazard function (-log(SF)) ## psf --- Probability sparsity function (reciprocal of the pdf) in ## units of percent-point-function (as a function of q). ## Also, the derivative of the percent-point function. class rv_continuous(rv_generic): """ A generic continuous random variable class meant for subclassing. `rv_continuous` is a base class to construct specific distribution classes and instances for continuous random variables. It cannot be used directly as a distribution. Parameters ---------- momtype : int, optional The type of generic moment calculation to use: 0 for pdf, 1 (default) for ppf. a : float, optional Lower bound of the support of the distribution, default is minus infinity. b : float, optional Upper bound of the support of the distribution, default is plus infinity. xtol : float, optional The tolerance for fixed point calculation for generic ppf. badvalue : float, optional The value in a result arrays that indicates a value that for which some argument restriction is violated, default is np.nan. name : str, optional The name of the instance. This string is used to construct the default example for distributions. longname : str, optional This string is used as part of the first line of the docstring returned when a subclass has no docstring of its own. Note: `longname` exists for backwards compatibility, do not use for new subclasses. shapes : str, optional The shape of the distribution. For example ``"m, n"`` for a distribution that takes two integers as the two shape arguments for all its methods. If not provided, shape parameters will be inferred from the signature of the private methods, ``_pdf`` and ``_cdf`` of the instance. extradoc : str, optional, deprecated This string is used as the last part of the docstring returned when a subclass has no docstring of its own. Note: `extradoc` exists for backwards compatibility, do not use for new subclasses. seed : {None, int, `~np.random.RandomState`, `~np.random.Generator`}, optional This parameter defines the object to use for drawing random variates. If `seed` is `None` the `~np.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with seed. If `seed` is already a ``RandomState`` or ``Generator`` instance, then that object is used. Default is None. Methods ------- rvs pdf logpdf cdf logcdf sf logsf ppf isf moment stats entropy expect median mean std var interval __call__ fit fit_loc_scale nnlf support Notes ----- Public methods of an instance of a distribution class (e.g., ``pdf``, ``cdf``) check their arguments and pass valid arguments to private, computational methods (``_pdf``, ``_cdf``). For ``pdf(x)``, ``x`` is valid if it is within the support of the distribution. Whether a shape parameter is valid is decided by an ``_argcheck`` method (which defaults to checking that its arguments are strictly positive.) **Subclassing** New random variables can be defined by subclassing the `rv_continuous` class and re-defining at least the ``_pdf`` or the ``_cdf`` method (normalized to location 0 and scale 1). If positive argument checking is not correct for your RV then you will also need to re-define the ``_argcheck`` method. For most of the scipy.stats distributions, the support interval doesn't depend on the shape parameters. ``x`` being in the support interval is equivalent to ``self.a <= x <= self.b``. If either of the endpoints of the support do depend on the shape parameters, then i) the distribution must implement the ``_get_support`` method; and ii) those dependent endpoints must be omitted from the distribution's call to the ``rv_continuous`` initializer. Correct, but potentially slow defaults exist for the remaining methods but for speed and/or accuracy you can over-ride:: _logpdf, _cdf, _logcdf, _ppf, _rvs, _isf, _sf, _logsf The default method ``_rvs`` relies on the inverse of the cdf, ``_ppf``, applied to a uniform random variate. In order to generate random variates efficiently, either the default ``_ppf`` needs to be overwritten (e.g. if the inverse cdf can expressed in an explicit form) or a sampling method needs to be implemented in a custom ``_rvs`` method. If possible, you should override ``_isf``, ``_sf`` or ``_logsf``. The main reason would be to improve numerical accuracy: for example, the survival function ``_sf`` is computed as ``1 - _cdf`` which can result in loss of precision if ``_cdf(x)`` is close to one. **Methods that can be overwritten by subclasses** :: _rvs _pdf _cdf _sf _ppf _isf _stats _munp _entropy _argcheck _get_support There are additional (internal and private) generic methods that can be useful for cross-checking and for debugging, but might work in all cases when directly called. A note on ``shapes``: subclasses need not specify them explicitly. In this case, `shapes` will be automatically deduced from the signatures of the overridden methods (`pdf`, `cdf` etc). If, for some reason, you prefer to avoid relying on introspection, you can specify ``shapes`` explicitly as an argument to the instance constructor. **Frozen Distributions** Normally, you must provide shape parameters (and, optionally, location and scale parameters to each call of a method of a distribution. Alternatively, the object may be called (as a function) to fix the shape, location, and scale parameters returning a "frozen" continuous RV object: rv = generic(<shape(s)>, loc=0, scale=1) `rv_frozen` object with the same methods but holding the given shape, location, and scale fixed **Statistics** Statistics are computed using numerical integration by default. For speed you can redefine this using ``_stats``: - take shape parameters and return mu, mu2, g1, g2 - If you can't compute one of these, return it as None - Can also be defined with a keyword argument ``moments``, which is a string composed of "m", "v", "s", and/or "k". Only the components appearing in string should be computed and returned in the order "m", "v", "s", or "k" with missing values returned as None. Alternatively, you can override ``_munp``, which takes ``n`` and shape parameters and returns the n-th non-central moment of the distribution. Examples -------- To create a new Gaussian distribution, we would do the following: >>> from scipy.stats import rv_continuous >>> class gaussian_gen(rv_continuous): ... "Gaussian distribution" ... def _pdf(self, x): ... return np.exp(-x**2 / 2.) / np.sqrt(2.0 * np.pi) >>> gaussian = gaussian_gen(name='gaussian') ``scipy.stats`` distributions are *instances*, so here we subclass `rv_continuous` and create an instance. With this, we now have a fully functional distribution with all relevant methods automagically generated by the framework. Note that above we defined a standard normal distribution, with zero mean and unit variance. Shifting and scaling of the distribution can be done by using ``loc`` and ``scale`` parameters: ``gaussian.pdf(x, loc, scale)`` essentially computes ``y = (x - loc) / scale`` and ``gaussian._pdf(y) / scale``. """ def __init__(self, momtype=1, a=None, b=None, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None, seed=None): super(rv_continuous, self).__init__(seed) # save the ctor parameters, cf generic freeze self._ctor_param = dict( momtype=momtype, a=a, b=b, xtol=xtol, badvalue=badvalue, name=name, longname=longname, shapes=shapes, extradoc=extradoc, seed=seed) if badvalue is None: badvalue = nan if name is None: name = 'Distribution' self.badvalue = badvalue self.name = name self.a = a self.b = b if a is None: self.a = -inf if b is None: self.b = inf self.xtol = xtol self.moment_type = momtype self.shapes = shapes self._construct_argparser(meths_to_inspect=[self._pdf, self._cdf], locscale_in='loc=0, scale=1', locscale_out='loc, scale') # nin correction self._ppfvec = vectorize(self._ppf_single, otypes='d') self._ppfvec.nin = self.numargs + 1 self.vecentropy = vectorize(self._entropy, otypes='d') self._cdfvec = vectorize(self._cdf_single, otypes='d') self._cdfvec.nin = self.numargs + 1 self.extradoc = extradoc if momtype == 0: self.generic_moment = vectorize(self._mom0_sc, otypes='d') else: self.generic_moment = vectorize(self._mom1_sc, otypes='d') # Because of the *args argument of _mom0_sc, vectorize cannot count the # number of arguments correctly. self.generic_moment.nin = self.numargs + 1 if longname is None: if name[0] in ['aeiouAEIOU']: hstr = "An " else: hstr = "A " longname = hstr + name if sys.flags.optimize < 2: # Skip adding docstrings if interpreter is run with -OO if self.__doc__ is None: self._construct_default_doc(longname=longname, extradoc=extradoc, docdict=docdict, discrete='continuous') else: dct = dict(distcont) self._construct_doc(docdict, dct.get(self.name)) def _updated_ctor_param(self): """ Return the current version of _ctor_param, possibly updated by user. Used by freezing and pickling. Keep this in sync with the signature of __init__. """ dct = self._ctor_param.copy() dct['a'] = self.a dct['b'] = self.b dct['xtol'] = self.xtol dct['badvalue'] = self.badvalue dct['name'] = self.name dct['shapes'] = self.shapes dct['extradoc'] = self.extradoc return dct def _ppf_to_solve(self, x, q, *args): return self.cdf(*(x, )+args)-q def _ppf_single(self, q, *args): factor = 10. left, right = self._get_support(*args) if np.isinf(left): left = min(-factor, right) while self._ppf_to_solve(left, q, *args) > 0.: left, right = left * factor, left # left is now such that cdf(left) <= q # if right has changed, then cdf(right) > q if np.isinf(right): right = max(factor, left) while self._ppf_to_solve(right, q, *args) < 0.: left, right = right, right * factor # right is now such that cdf(right) >= q return optimize.brentq(self._ppf_to_solve, left, right, args=(q,)+args, xtol=self.xtol) # moment from definition def _mom_integ0(self, x, m, *args): return x**m * self.pdf(x, *args) def _mom0_sc(self, m, *args): _a, _b = self._get_support(*args) return integrate.quad(self._mom_integ0, _a, _b, args=(m,)+args)[0] # moment calculated using ppf def _mom_integ1(self, q, m, *args): return (self.ppf(q, *args))**m def _mom1_sc(self, m, *args): return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0] def _pdf(self, x, *args): return derivative(self._cdf, x, dx=1e-5, args=args, order=5) ## Could also define any of these def _logpdf(self, x, *args): return log(self._pdf(x, *args)) def _cdf_single(self, x, *args): _a, _b = self._get_support(*args) return integrate.quad(self._pdf, _a, x, args=args)[0] def _cdf(self, x, *args): return self._cdfvec(x, *args) ## generic _argcheck, _logcdf, _sf, _logsf, _ppf, _isf, _rvs are defined ## in rv_generic def pdf(self, x, *args, **kwds): """ Probability density function at x of the given RV. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- pdf : ndarray Probability density function evaluated at x """ args, loc, scale = self._parse_args(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._support_mask(x, *args) & (scale > 0) cond = cond0 & cond1 output = zeros(shape(cond), dtyp) putmask(output, (1-cond0)+np.isnan(x), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args+(scale,))) scale, goodargs = goodargs[-1], goodargs[:-1] place(output, cond, self._pdf(*goodargs) / scale) if output.ndim == 0: return output[()] return output def logpdf(self, x, *args, **kwds): """ Log of the probability density function at x of the given RV. This uses a more numerically accurate calculation if available. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- logpdf : array_like Log of the probability density function evaluated at x """ args, loc, scale = self._parse_args(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._support_mask(x, *args) & (scale > 0) cond = cond0 & cond1 output = empty(shape(cond), dtyp) output.fill(NINF) putmask(output, (1-cond0)+np.isnan(x), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args+(scale,))) scale, goodargs = goodargs[-1], goodargs[:-1] place(output, cond, self._logpdf(*goodargs) - log(scale)) if output.ndim == 0: return output[()] return output def cdf(self, x, *args, **kwds): """ Cumulative distribution function of the given RV. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- cdf : ndarray Cumulative distribution function evaluated at `x` """ args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = (x >= np.asarray(_b)) & cond0 cond = cond0 & cond1 output = zeros(shape(cond), dtyp) place(output, (1-cond0)+np.isnan(x), self.badvalue) place(output, cond2, 1.0) if np.any(cond): # call only if at least 1 entry goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._cdf(*goodargs)) if output.ndim == 0: return output[()] return output def logcdf(self, x, *args, **kwds): """ Log of the cumulative distribution function at x of the given RV. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- logcdf : array_like Log of the cumulative distribution function evaluated at x """ args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = (x >= _b) & cond0 cond = cond0 & cond1 output = empty(shape(cond), dtyp) output.fill(NINF) place(output, (1-cond0)*(cond1 == cond1)+np.isnan(x), self.badvalue) place(output, cond2, 0.0) if np.any(cond): # call only if at least 1 entry goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._logcdf(*goodargs)) if output.ndim == 0: return output[()] return output def sf(self, x, *args, **kwds): """ Survival function (1 - `cdf`) at x of the given RV. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- sf : array_like Survival function evaluated at x """ args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = cond0 & (x <= _a) cond = cond0 & cond1 output = zeros(shape(cond), dtyp) place(output, (1-cond0)+np.isnan(x), self.badvalue) place(output, cond2, 1.0) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._sf(*goodargs)) if output.ndim == 0: return output[()] return output def logsf(self, x, *args, **kwds): """ Log of the survival function of the given RV. Returns the log of the "survival function," defined as (1 - `cdf`), evaluated at `x`. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- logsf : ndarray Log of the survival function evaluated at `x`. """ args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = cond0 & (x <= _a) cond = cond0 & cond1 output = empty(shape(cond), dtyp) output.fill(NINF) place(output, (1-cond0)+np.isnan(x), self.badvalue) place(output, cond2, 0.0) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._logsf(*goodargs)) if output.ndim == 0: return output[()] return output def ppf(self, q, *args, **kwds): """ Percent point function (inverse of `cdf`) at q of the given RV. Parameters ---------- q : array_like lower tail probability arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- x : array_like quantile corresponding to the lower tail probability q. """ args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) q, loc, scale = map(asarray, (q, loc, scale)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) cond1 = (0 < q) & (q < 1) cond2 = cond0 & (q == 0) cond3 = cond0 & (q == 1) cond = cond0 & cond1 output = valarray(shape(cond), value=self.badvalue) lower_bound = _a * scale + loc upper_bound = _b * scale + loc place(output, cond2, argsreduce(cond2, lower_bound)[0]) place(output, cond3, argsreduce(cond3, upper_bound)[0]) if np.any(cond): # call only if at least 1 entry goodargs = argsreduce(cond, *((q,)+args+(scale, loc))) scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] place(output, cond, self._ppf(*goodargs) * scale + loc) if output.ndim == 0: return output[()] return output def isf(self, q, *args, **kwds): """ Inverse survival function (inverse of `sf`) at q of the given RV. Parameters ---------- q : array_like upper tail probability arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- x : ndarray or scalar Quantile corresponding to the upper tail probability q. """ args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) q, loc, scale = map(asarray, (q, loc, scale)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) cond1 = (0 < q) & (q < 1) cond2 = cond0 & (q == 1) cond3 = cond0 & (q == 0) cond = cond0 & cond1 output = valarray(shape(cond), value=self.badvalue) lower_bound = _a * scale + loc upper_bound = _b * scale + loc place(output, cond2, argsreduce(cond2, lower_bound)[0]) place(output, cond3, argsreduce(cond3, upper_bound)[0]) if np.any(cond): goodargs = argsreduce(cond, *((q,)+args+(scale, loc))) scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] place(output, cond, self._isf(*goodargs) * scale + loc) if output.ndim == 0: return output[()] return output def _nnlf(self, x, *args): return -np.sum(self._logpdf(x, *args), axis=0) def _unpack_loc_scale(self, theta): try: loc = theta[-2] scale = theta[-1] args = tuple(theta[:-2]) except IndexError: raise ValueError("Not enough input arguments.") return loc, scale, args def nnlf(self, theta, x): '''Return negative loglikelihood function. Notes ----- This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the parameters (including loc and scale). ''' loc, scale, args = self._unpack_loc_scale(theta) if not self._argcheck(*args) or scale <= 0: return inf x = asarray((x-loc) / scale) n_log_scale = len(x) * log(scale) if np.any(~self._support_mask(x, *args)): return inf return self._nnlf(x, *args) + n_log_scale def _nnlf_and_penalty(self, x, args): cond0 = ~self._support_mask(x, *args) n_bad = np.count_nonzero(cond0, axis=0) if n_bad > 0: x = argsreduce(~cond0, x)[0] logpdf = self._logpdf(x, *args) finite_logpdf = np.isfinite(logpdf) n_bad += np.sum(~finite_logpdf, axis=0) if n_bad > 0: penalty = n_bad * log(_XMAX) * 100 return -np.sum(logpdf[finite_logpdf], axis=0) + penalty return -np.sum(logpdf, axis=0) def _penalized_nnlf(self, theta, x): ''' Return penalized negative loglikelihood function, i.e., - sum (log pdf(x, theta), axis=0) + penalty where theta are the parameters (including loc and scale) ''' loc, scale, args = self._unpack_loc_scale(theta) if not self._argcheck(*args) or scale <= 0: return inf x = asarray((x-loc) / scale) n_log_scale = len(x) * log(scale) return self._nnlf_and_penalty(x, args) + n_log_scale # return starting point for fit (shape arguments + loc + scale) def _fitstart(self, data, args=None): if args is None: args = (1.0,)*self.numargs loc, scale = self._fit_loc_scale_support(data, *args) return args + (loc, scale) def _reduce_func(self, args, kwds): """ Return the (possibly reduced) function to optimize in order to find MLE estimates for the .fit method. """ # Convert fixed shape parameters to the standard numeric form: e.g. for # stats.beta, shapes='a, b'. To fix `a`, the caller can give a value # for `f0`, `fa` or 'fix_a'. The following converts the latter two # into the first (numeric) form. if self.shapes: shapes = self.shapes.replace(',', ' ').split() for j, s in enumerate(shapes): key = 'f' + str(j) names = [key, 'f' + s, 'fix_' + s] val = _get_fixed_fit_value(kwds, names) if val is not None: kwds[key] = val args = list(args) Nargs = len(args) fixedn = [] names = ['f%d' % n for n in range(Nargs - 2)] + ['floc', 'fscale'] x0 = [] for n, key in enumerate(names): if key in kwds: fixedn.append(n) args[n] = kwds.pop(key) else: x0.append(args[n]) if len(fixedn) == 0: func = self._penalized_nnlf restore = None else: if len(fixedn) == Nargs: raise ValueError( "All parameters fixed. There is nothing to optimize.") def restore(args, theta): # Replace with theta for all numbers not in fixedn # This allows the non-fixed values to vary, but # we still call self.nnlf with all parameters. i = 0 for n in range(Nargs): if n not in fixedn: args[n] = theta[i] i += 1 return args def func(theta, x): newtheta = restore(args[:], theta) return self._penalized_nnlf(newtheta, x) return x0, func, restore, args def fit(self, data, *args, **kwds): """ Return MLEs for shape (if applicable), location, and scale parameters from data. MLE stands for Maximum Likelihood Estimate. Starting estimates for the fit are given by input arguments; for any arguments not provided with starting estimates, ``self._fitstart(data)`` is called to generate such. One can hold some parameters fixed to specific values by passing in keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters) and ``floc`` and ``fscale`` (for location and scale parameters, respectively). Parameters ---------- data : array_like Data to use in calculating the MLEs. arg1, arg2, arg3,... : floats, optional Starting value(s) for any shape-characterizing arguments (those not provided will be determined by a call to ``_fitstart(data)``). No default value. kwds : floats, optional - `loc`: initial guess of the distribution's location parameter. - `scale`: initial guess of the distribution's scale parameter. Special keyword arguments are recognized as holding certain parameters fixed: - f0...fn : hold respective shape parameters fixed. Alternatively, shape parameters to fix can be specified by name. For example, if ``self.shapes == "a, b"``, ``fa`` and ``fix_a`` are equivalent to ``f0``, and ``fb`` and ``fix_b`` are equivalent to ``f1``. - floc : hold location parameter fixed to specified value. - fscale : hold scale parameter fixed to specified value. - optimizer : The optimizer to use. The optimizer must take ``func``, and starting position as the first two arguments, plus ``args`` (for extra arguments to pass to the function to be optimized) and ``disp=0`` to suppress output as keyword arguments. Returns ------- mle_tuple : tuple of floats MLEs for any shape parameters (if applicable), followed by those for location and scale. For most random variables, shape statistics will be returned, but there are exceptions (e.g. ``norm``). Notes ----- This fit is computed by maximizing a log-likelihood function, with penalty applied for samples outside of range of the distribution. The returned answer is not guaranteed to be the globally optimal MLE, it may only be locally optimal, or the optimization may fail altogether. If the data contain any of np.nan, np.inf, or -np.inf, the fit routine will throw a RuntimeError. Examples -------- Generate some data to fit: draw random variates from the `beta` distribution >>> from scipy.stats import beta >>> a, b = 1., 2. >>> x = beta.rvs(a, b, size=1000) Now we can fit all four parameters (``a``, ``b``, ``loc`` and ``scale``): >>> a1, b1, loc1, scale1 = beta.fit(x) We can also use some prior knowledge about the dataset: let's keep ``loc`` and ``scale`` fixed: >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1) >>> loc1, scale1 (0, 1) We can also keep shape parameters fixed by using ``f``-keywords. To keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or, equivalently, ``fa=1``: >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1) >>> a1 1 Not all distributions return estimates for the shape parameters. ``norm`` for example just returns estimates for location and scale: >>> from scipy.stats import norm >>> x = norm.rvs(a, b, size=1000, random_state=123) >>> loc1, scale1 = norm.fit(x) >>> loc1, scale1 (0.92087172783841631, 2.0015750750324668) """ Narg = len(args) if Narg > self.numargs: raise TypeError("Too many input arguments.") if not np.isfinite(data).all(): raise RuntimeError("The data contains non-finite values.") start = [None]*2 if (Narg < self.numargs) or not ('loc' in kwds and 'scale' in kwds): # get distribution specific starting locations start = self._fitstart(data) args += start[Narg:-2] loc = kwds.pop('loc', start[-2]) scale = kwds.pop('scale', start[-1]) args += (loc, scale) x0, func, restore, args = self._reduce_func(args, kwds) optimizer = kwds.pop('optimizer', optimize.fmin) # convert string to function in scipy.optimize if not callable(optimizer) and isinstance(optimizer, str): if not optimizer.startswith('fmin_'): optimizer = "fmin_"+optimizer if optimizer == 'fmin_': optimizer = 'fmin' try: optimizer = getattr(optimize, optimizer) except AttributeError: raise ValueError("%s is not a valid optimizer" % optimizer) # by now kwds must be empty, since everybody took what they needed if kwds: raise TypeError("Unknown arguments: %s." % kwds) vals = optimizer(func, x0, args=(ravel(data),), disp=0) if restore is not None: vals = restore(args, vals) vals = tuple(vals) return vals def _fit_loc_scale_support(self, data, *args): """ Estimate loc and scale parameters from data accounting for support. Parameters ---------- data : array_like Data to fit. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). Returns ------- Lhat : float Estimated location parameter for the data. Shat : float Estimated scale parameter for the data. """ data = np.asarray(data) # Estimate location and scale according to the method of moments. loc_hat, scale_hat = self.fit_loc_scale(data, *args) # Compute the support according to the shape parameters. self._argcheck(*args) _a, _b = self._get_support(*args) a, b = _a, _b support_width = b - a # If the support is empty then return the moment-based estimates. if support_width <= 0: return loc_hat, scale_hat # Compute the proposed support according to the loc and scale # estimates. a_hat = loc_hat + a * scale_hat b_hat = loc_hat + b * scale_hat # Use the moment-based estimates if they are compatible with the data. data_a = np.min(data) data_b = np.max(data) if a_hat < data_a and data_b < b_hat: return loc_hat, scale_hat # Otherwise find other estimates that are compatible with the data. data_width = data_b - data_a rel_margin = 0.1 margin = data_width * rel_margin # For a finite interval, both the location and scale # should have interesting values. if support_width < np.inf: loc_hat = (data_a - a) - margin scale_hat = (data_width + 2 * margin) / support_width return loc_hat, scale_hat # For a one-sided interval, use only an interesting location parameter. if a > -np.inf: return (data_a - a) - margin, 1 elif b < np.inf: return (data_b - b) + margin, 1 else: raise RuntimeError def fit_loc_scale(self, data, *args): """ Estimate loc and scale parameters from data using 1st and 2nd moments. Parameters ---------- data : array_like Data to fit. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). Returns ------- Lhat : float Estimated location parameter for the data. Shat : float Estimated scale parameter for the data. """ mu, mu2 = self.stats(*args, **{'moments': 'mv'}) tmp = asarray(data) muhat = tmp.mean() mu2hat = tmp.var() Shat = sqrt(mu2hat / mu2) Lhat = muhat - Shat*mu if not np.isfinite(Lhat): Lhat = 0 if not (np.isfinite(Shat) and (0 < Shat)): Shat = 1 return Lhat, Shat def _entropy(self, *args): def integ(x): val = self._pdf(x, *args) return entr(val) # upper limit is often inf, so suppress warnings when integrating _a, _b = self._get_support(*args) with np.errstate(over='ignore'): h = integrate.quad(integ, _a, _b)[0] if not np.isnan(h): return h else: # try with different limits if integration problems low, upp = self.ppf([1e-10, 1. - 1e-10], *args) if np.isinf(_b): upper = upp else: upper = _b if np.isinf(_a): lower = low else: lower = _a return integrate.quad(integ, lower, upper)[0] def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds): """Calculate expected value of a function with respect to the distribution by numerical integration. The expected value of a function ``f(x)`` with respect to a distribution ``dist`` is defined as:: ub E[f(x)] = Integral(f(x) * dist.pdf(x)), lb where ``ub`` and ``lb`` are arguments and ``x`` has the ``dist.pdf(x)`` distribution. If the bounds ``lb`` and ``ub`` correspond to the support of the distribution, e.g. ``[-inf, inf]`` in the default case, then the integral is the unrestricted expectation of ``f(x)``. Also, the function ``f(x)`` may be defined such that ``f(x)`` is ``0`` outside a finite interval in which case the expectation is calculated within the finite range ``[lb, ub]``. Parameters ---------- func : callable, optional Function for which integral is calculated. Takes only one argument. The default is the identity mapping f(x) = x. args : tuple, optional Shape parameters of the distribution. loc : float, optional Location parameter (default=0). scale : float, optional Scale parameter (default=1). lb, ub : scalar, optional Lower and upper bound for integration. Default is set to the support of the distribution. conditional : bool, optional If True, the integral is corrected by the conditional probability of the integration interval. The return value is the expectation of the function, conditional on being in the given interval. Default is False. Additional keyword arguments are passed to the integration routine. Returns ------- expect : float The calculated expected value. Notes ----- The integration behavior of this function is inherited from `scipy.integrate.quad`. Neither this function nor `scipy.integrate.quad` can verify whether the integral exists or is finite. For example ``cauchy(0).mean()`` returns ``np.nan`` and ``cauchy(0).expect()`` returns ``0.0``. The function is not vectorized. Examples -------- To understand the effect of the bounds of integration consider >>> from scipy.stats import expon >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0) 0.6321205588285578 This is close to >>> expon(1).cdf(2.0) - expon(1).cdf(0.0) 0.6321205588285577 If ``conditional=True`` >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0, conditional=True) 1.0000000000000002 The slight deviation from 1 is due to numerical integration. """ lockwds = {'loc': loc, 'scale': scale} self._argcheck(*args) _a, _b = self._get_support(*args) if func is None: def fun(x, *args): return x * self.pdf(x, *args, **lockwds) else: def fun(x, *args): return func(x) * self.pdf(x, *args, **lockwds) if lb is None: lb = loc + _a * scale if ub is None: ub = loc + _b * scale if conditional: invfac = (self.sf(lb, *args, **lockwds) - self.sf(ub, *args, **lockwds)) else: invfac = 1.0 kwds['args'] = args # Silence floating point warnings from integration. with np.errstate(all='ignore'): vals = integrate.quad(fun, lb, ub, **kwds)[0] / invfac return vals # Helpers for the discrete distributions def _drv2_moment(self, n, *args): """Non-central moment of discrete distribution.""" def fun(x): return np.power(x, n) * self._pmf(x, *args) _a, _b = self._get_support(*args) return _expect(fun, _a, _b, self.ppf(0.5, *args), self.inc) def _drv2_ppfsingle(self, q, *args): # Use basic bisection algorithm _a, _b = self._get_support(*args) b = _b a = _a if isinf(b): # Be sure ending point is > q b = int(max(100*q, 10)) while 1: if b >= _b: qb = 1.0 break qb = self._cdf(b, *args) if (qb < q): b += 10 else: break else: qb = 1.0 if isinf(a): # be sure starting point < q a = int(min(-100*q, -10)) while 1: if a <= _a: qb = 0.0 break qa = self._cdf(a, *args) if (qa > q): a -= 10 else: break else: qa = self._cdf(a, *args) while 1: if (qa == q): return a if (qb == q): return b if b <= a+1: if qa > q: return a else: return b c = int((a+b)/2.0) qc = self._cdf(c, *args) if (qc < q): if a != c: a = c else: raise RuntimeError('updating stopped, endless loop') qa = qc elif (qc > q): if b != c: b = c else: raise RuntimeError('updating stopped, endless loop') qb = qc else: return c def entropy(pk, qk=None, base=None, axis=0): """Calculate the entropy of a distribution for given probability values. If only probabilities `pk` are given, the entropy is calculated as ``S = -sum(pk * log(pk), axis=axis)``. If `qk` is not None, then compute the Kullback-Leibler divergence ``S = sum(pk * log(pk / qk), axis=axis)``. This routine will normalize `pk` and `qk` if they don't sum to 1. Parameters ---------- pk : sequence Defines the (discrete) distribution. ``pk[i]`` is the (possibly unnormalized) probability of event ``i``. qk : sequence, optional Sequence against which the relative entropy is computed. Should be in the same format as `pk`. base : float, optional The logarithmic base to use, defaults to ``e`` (natural logarithm). axis: int, optional The axis along which the entropy is calculated. Default is 0. Returns ------- S : float The calculated entropy. Examples -------- >>> from scipy.stats import entropy Bernoulli trial with different p. The outcome of a fair coin is the most uncertain: >>> entropy([1/2, 1/2], base=2) 1.0 The outcome of a biased coin is less uncertain: >>> entropy([9/10, 1/10], base=2) 0.46899559358928117 Relative entropy: >>> entropy([1/2, 1/2], qk=[9/10, 1/10]) 0.5108256237659907 """ pk = asarray(pk) pk = 1.0*pk / np.sum(pk, axis=axis, keepdims=True) if qk is None: vec = entr(pk) else: qk = asarray(qk) if qk.shape != pk.shape: raise ValueError("qk and pk must have same shape.") qk = 1.0*qk / np.sum(qk, axis=axis, keepdims=True) vec = rel_entr(pk, qk) S = np.sum(vec, axis=axis) if base is not None: S /= log(base) return S # Must over-ride one of _pmf or _cdf or pass in # x_k, p(x_k) lists in initialization class rv_discrete(rv_generic): """ A generic discrete random variable class meant for subclassing. `rv_discrete` is a base class to construct specific distribution classes and instances for discrete random variables. It can also be used to construct an arbitrary distribution defined by a list of support points and corresponding probabilities. Parameters ---------- a : float, optional Lower bound of the support of the distribution, default: 0 b : float, optional Upper bound of the support of the distribution, default: plus infinity moment_tol : float, optional The tolerance for the generic calculation of moments. values : tuple of two array_like, optional ``(xk, pk)`` where ``xk`` are integers and ``pk`` are the non-zero probabilities between 0 and 1 with ``sum(pk) = 1``. ``xk`` and ``pk`` must have the same shape. inc : integer, optional Increment for the support of the distribution. Default is 1. (other values have not been tested) badvalue : float, optional The value in a result arrays that indicates a value that for which some argument restriction is violated, default is np.nan. name : str, optional The name of the instance. This string is used to construct the default example for distributions. longname : str, optional This string is used as part of the first line of the docstring returned when a subclass has no docstring of its own. Note: `longname` exists for backwards compatibility, do not use for new subclasses. shapes : str, optional The shape of the distribution. For example "m, n" for a distribution that takes two integers as the two shape arguments for all its methods If not provided, shape parameters will be inferred from the signatures of the private methods, ``_pmf`` and ``_cdf`` of the instance. extradoc : str, optional This string is used as the last part of the docstring returned when a subclass has no docstring of its own. Note: `extradoc` exists for backwards compatibility, do not use for new subclasses. seed : {None, int, `~np.random.RandomState`, `~np.random.Generator`}, optional This parameter defines the object to use for drawing random variates. If `seed` is `None` the `~np.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with seed. If `seed` is already a ``RandomState`` or ``Generator`` instance, then that object is used. Default is None. Methods ------- rvs pmf logpmf cdf logcdf sf logsf ppf isf moment stats entropy expect median mean std var interval __call__ support Notes ----- This class is similar to `rv_continuous`. Whether a shape parameter is valid is decided by an ``_argcheck`` method (which defaults to checking that its arguments are strictly positive.) The main differences are: - the support of the distribution is a set of integers - instead of the probability density function, ``pdf`` (and the corresponding private ``_pdf``), this class defines the *probability mass function*, `pmf` (and the corresponding private ``_pmf``.) - scale parameter is not defined. To create a new discrete distribution, we would do the following: >>> from scipy.stats import rv_discrete >>> class poisson_gen(rv_discrete): ... "Poisson distribution" ... def _pmf(self, k, mu): ... return exp(-mu) * mu**k / factorial(k) and create an instance:: >>> poisson = poisson_gen(name="poisson") Note that above we defined the Poisson distribution in the standard form. Shifting the distribution can be done by providing the ``loc`` parameter to the methods of the instance. For example, ``poisson.pmf(x, mu, loc)`` delegates the work to ``poisson._pmf(x-loc, mu)``. **Discrete distributions from a list of probabilities** Alternatively, you can construct an arbitrary discrete rv defined on a finite set of values ``xk`` with ``Prob{X=xk} = pk`` by using the ``values`` keyword argument to the `rv_discrete` constructor. Examples -------- Custom made discrete distribution: >>> from scipy import stats >>> xk = np.arange(7) >>> pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2) >>> custm = stats.rv_discrete(name='custm', values=(xk, pk)) >>> >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) >>> ax.plot(xk, custm.pmf(xk), 'ro', ms=12, mec='r') >>> ax.vlines(xk, 0, custm.pmf(xk), colors='r', lw=4) >>> plt.show() Random number generation: >>> R = custm.rvs(size=100) """ def __new__(cls, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-8, values=None, inc=1, longname=None, shapes=None, extradoc=None, seed=None): if values is not None: # dispatch to a subclass return super(rv_discrete, cls).__new__(rv_sample) else: # business as usual return super(rv_discrete, cls).__new__(cls) def __init__(self, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-8, values=None, inc=1, longname=None, shapes=None, extradoc=None, seed=None): super(rv_discrete, self).__init__(seed) # cf generic freeze self._ctor_param = dict( a=a, b=b, name=name, badvalue=badvalue, moment_tol=moment_tol, values=values, inc=inc, longname=longname, shapes=shapes, extradoc=extradoc, seed=seed) if badvalue is None: badvalue = nan self.badvalue = badvalue self.a = a self.b = b self.moment_tol = moment_tol self.inc = inc self._cdfvec = vectorize(self._cdf_single, otypes='d') self.vecentropy = vectorize(self._entropy) self.shapes = shapes if values is not None: raise ValueError("rv_discrete.__init__(..., values != None, ...)") self._construct_argparser(meths_to_inspect=[self._pmf, self._cdf], locscale_in='loc=0', # scale=1 for discrete RVs locscale_out='loc, 1') # nin correction needs to be after we know numargs # correct nin for generic moment vectorization _vec_generic_moment = vectorize(_drv2_moment, otypes='d') _vec_generic_moment.nin = self.numargs + 2 self.generic_moment = types.MethodType(_vec_generic_moment, self) # correct nin for ppf vectorization _vppf = vectorize(_drv2_ppfsingle, otypes='d') _vppf.nin = self.numargs + 2 self._ppfvec = types.MethodType(_vppf, self) # now that self.numargs is defined, we can adjust nin self._cdfvec.nin = self.numargs + 1 self._construct_docstrings(name, longname, extradoc) def _construct_docstrings(self, name, longname, extradoc): if name is None: name = 'Distribution' self.name = name self.extradoc = extradoc # generate docstring for subclass instances if longname is None: if name[0] in ['aeiouAEIOU']: hstr = "An " else: hstr = "A " longname = hstr + name if sys.flags.optimize < 2: # Skip adding docstrings if interpreter is run with -OO if self.__doc__ is None: self._construct_default_doc(longname=longname, extradoc=extradoc, docdict=docdict_discrete, discrete='discrete') else: dct = dict(distdiscrete) self._construct_doc(docdict_discrete, dct.get(self.name)) # discrete RV do not have the scale parameter, remove it self.__doc__ = self.__doc__.replace( '\n scale : array_like, ' 'optional\n scale parameter (default=1)', '') def _updated_ctor_param(self): """ Return the current version of _ctor_param, possibly updated by user. Used by freezing and pickling. Keep this in sync with the signature of __init__. """ dct = self._ctor_param.copy() dct['a'] = self.a dct['b'] = self.b dct['badvalue'] = self.badvalue dct['moment_tol'] = self.moment_tol dct['inc'] = self.inc dct['name'] = self.name dct['shapes'] = self.shapes dct['extradoc'] = self.extradoc return dct def _nonzero(self, k, *args): return floor(k) == k def _pmf(self, k, *args): return self._cdf(k, *args) - self._cdf(k-1, *args) def _logpmf(self, k, *args): return log(self._pmf(k, *args)) def _cdf_single(self, k, *args): _a, _b = self._get_support(*args) m = arange(int(_a), k+1) return np.sum(self._pmf(m, *args), axis=0) def _cdf(self, x, *args): k = floor(x) return self._cdfvec(k, *args) # generic _logcdf, _sf, _logsf, _ppf, _isf, _rvs defined in rv_generic def rvs(self, *args, **kwargs): """ Random variates of given type. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). size : int or tuple of ints, optional Defining number of random variates (Default is 1). Note that `size` has to be given as keyword, not as positional argument. random_state : {None, int, `~np.random.RandomState`, `~np.random.Generator`}, optional This parameter defines the object to use for drawing random variates. If `random_state` is `None` the `~np.random.RandomState` singleton is used. If `random_state` is an int, a new ``RandomState`` instance is used, seeded with random_state. If `random_state` is already a ``RandomState`` or ``Generator`` instance, then that object is used. Default is None. Returns ------- rvs : ndarray or scalar Random variates of given `size`. """ kwargs['discrete'] = True return super(rv_discrete, self).rvs(*args, **kwargs) def pmf(self, k, *args, **kwds): """ Probability mass function at k of the given RV. Parameters ---------- k : array_like Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional Location parameter (default=0). Returns ------- pmf : array_like Probability mass function evaluated at k """ args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k <= _b) & self._nonzero(k, *args) cond = cond0 & cond1 output = zeros(shape(cond), 'd') place(output, (1-cond0) + np.isnan(k), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, np.clip(self._pmf(*goodargs), 0, 1)) if output.ndim == 0: return output[()] return output def logpmf(self, k, *args, **kwds): """ Log of the probability mass function at k of the given RV. Parameters ---------- k : array_like Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter. Default is 0. Returns ------- logpmf : array_like Log of the probability mass function evaluated at k. """ args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k <= _b) & self._nonzero(k, *args) cond = cond0 & cond1 output = empty(shape(cond), 'd') output.fill(NINF) place(output, (1-cond0) + np.isnan(k), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, self._logpmf(*goodargs)) if output.ndim == 0: return output[()] return output def cdf(self, k, *args, **kwds): """ Cumulative distribution function of the given RV. Parameters ---------- k : array_like, int Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- cdf : ndarray Cumulative distribution function evaluated at `k`. """ args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k >= _b) cond = cond0 & cond1 output = zeros(shape(cond), 'd') place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2*(cond0 == cond0), 1.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, np.clip(self._cdf(*goodargs), 0, 1)) if output.ndim == 0: return output[()] return output def logcdf(self, k, *args, **kwds): """ Log of the cumulative distribution function at k of the given RV. Parameters ---------- k : array_like, int Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- logcdf : array_like Log of the cumulative distribution function evaluated at k. """ args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k >= _b) cond = cond0 & cond1 output = empty(shape(cond), 'd') output.fill(NINF) place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2*(cond0 == cond0), 0.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, self._logcdf(*goodargs)) if output.ndim == 0: return output[()] return output def sf(self, k, *args, **kwds): """ Survival function (1 - `cdf`) at k of the given RV. Parameters ---------- k : array_like Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- sf : array_like Survival function evaluated at k. """ args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray(k-loc) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k < _a) & cond0 cond = cond0 & cond1 output = zeros(shape(cond), 'd') place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2, 1.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, np.clip(self._sf(*goodargs), 0, 1)) if output.ndim == 0: return output[()] return output def logsf(self, k, *args, **kwds): """ Log of the survival function of the given RV. Returns the log of the "survival function," defined as 1 - `cdf`, evaluated at `k`. Parameters ---------- k : array_like Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- logsf : ndarray Log of the survival function evaluated at `k`. """ args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray(k-loc) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k < _a) & cond0 cond = cond0 & cond1 output = empty(shape(cond), 'd') output.fill(NINF) place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2, 0.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, self._logsf(*goodargs)) if output.ndim == 0: return output[()] return output def ppf(self, q, *args, **kwds): """ Percent point function (inverse of `cdf`) at q of the given RV. Parameters ---------- q : array_like Lower tail probability. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- k : array_like Quantile corresponding to the lower tail probability, q. """ args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) q, loc = map(asarray, (q, loc)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (loc == loc) cond1 = (q > 0) & (q < 1) cond2 = (q == 1) & cond0 cond = cond0 & cond1 output = valarray(shape(cond), value=self.badvalue, typecode='d') # output type 'd' to handle nin and inf place(output, (q == 0)*(cond == cond), _a-1 + loc) place(output, cond2, _b + loc) if np.any(cond): goodargs = argsreduce(cond, *((q,)+args+(loc,))) loc, goodargs = goodargs[-1], goodargs[:-1] place(output, cond, self._ppf(*goodargs) + loc) if output.ndim == 0: return output[()] return output def isf(self, q, *args, **kwds): """ Inverse survival function (inverse of `sf`) at q of the given RV. Parameters ---------- q : array_like Upper tail probability. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- k : ndarray or scalar Quantile corresponding to the upper tail probability, q. """ args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) q, loc = map(asarray, (q, loc)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (loc == loc) cond1 = (q > 0) & (q < 1) cond2 = (q == 1) & cond0 cond = cond0 & cond1 # same problem as with ppf; copied from ppf and changed output = valarray(shape(cond), value=self.badvalue, typecode='d') # output type 'd' to handle nin and inf place(output, (q == 0)*(cond == cond), _b) place(output, cond2, _a-1) # call place only if at least 1 valid argument if np.any(cond): goodargs = argsreduce(cond, *((q,)+args+(loc,))) loc, goodargs = goodargs[-1], goodargs[:-1] # PB same as ticket 766 place(output, cond, self._isf(*goodargs) + loc) if output.ndim == 0: return output[()] return output def _entropy(self, *args): if hasattr(self, 'pk'): return entropy(self.pk) else: _a, _b = self._get_support(*args) return _expect(lambda x: entr(self.pmf(x, *args)), _a, _b, self.ppf(0.5, *args), self.inc) def expect(self, func=None, args=(), loc=0, lb=None, ub=None, conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32): """ Calculate expected value of a function with respect to the distribution for discrete distribution by numerical summation. Parameters ---------- func : callable, optional Function for which the expectation value is calculated. Takes only one argument. The default is the identity mapping f(k) = k. args : tuple, optional Shape parameters of the distribution. loc : float, optional Location parameter. Default is 0. lb, ub : int, optional Lower and upper bound for the summation, default is set to the support of the distribution, inclusive (``ul <= k <= ub``). conditional : bool, optional If true then the expectation is corrected by the conditional probability of the summation interval. The return value is the expectation of the function, `func`, conditional on being in the given interval (k such that ``ul <= k <= ub``). Default is False. maxcount : int, optional Maximal number of terms to evaluate (to avoid an endless loop for an infinite sum). Default is 1000. tolerance : float, optional Absolute tolerance for the summation. Default is 1e-10. chunksize : int, optional Iterate over the support of a distributions in chunks of this size. Default is 32. Returns ------- expect : float Expected value. Notes ----- For heavy-tailed distributions, the expected value may or may not exist, depending on the function, `func`. If it does exist, but the sum converges slowly, the accuracy of the result may be rather low. For instance, for ``zipf(4)``, accuracy for mean, variance in example is only 1e-5. increasing `maxcount` and/or `chunksize` may improve the result, but may also make zipf very slow. The function is not vectorized. """ if func is None: def fun(x): # loc and args from outer scope return (x+loc)*self._pmf(x, *args) else: def fun(x): # loc and args from outer scope return func(x+loc)*self._pmf(x, *args) # used pmf because _pmf does not check support in randint and there # might be problems(?) with correct self.a, self.b at this stage maybe # not anymore, seems to work now with _pmf self._argcheck(*args) # (re)generate scalar self.a and self.b _a, _b = self._get_support(*args) if lb is None: lb = _a else: lb = lb - loc # convert bound for standardized distribution if ub is None: ub = _b else: ub = ub - loc # convert bound for standardized distribution if conditional: invfac = self.sf(lb-1, *args) - self.sf(ub, *args) else: invfac = 1.0 # iterate over the support, starting from the median x0 = self.ppf(0.5, *args) res = _expect(fun, lb, ub, x0, self.inc, maxcount, tolerance, chunksize) return res / invfac def _expect(fun, lb, ub, x0, inc, maxcount=1000, tolerance=1e-10, chunksize=32): """Helper for computing the expectation value of `fun`.""" # short-circuit if the support size is small enough if (ub - lb) <= chunksize: supp = np.arange(lb, ub+1, inc) vals = fun(supp) return np.sum(vals) # otherwise, iterate starting from x0 if x0 < lb: x0 = lb if x0 > ub: x0 = ub count, tot = 0, 0. # iterate over [x0, ub] inclusive for x in _iter_chunked(x0, ub+1, chunksize=chunksize, inc=inc): count += x.size delta = np.sum(fun(x)) tot += delta if abs(delta) < tolerance * x.size: break if count > maxcount: warnings.warn('expect(): sum did not converge', RuntimeWarning) return tot # iterate over [lb, x0) for x in _iter_chunked(x0-1, lb-1, chunksize=chunksize, inc=-inc): count += x.size delta = np.sum(fun(x)) tot += delta if abs(delta) < tolerance * x.size: break if count > maxcount: warnings.warn('expect(): sum did not converge', RuntimeWarning) break return tot def _iter_chunked(x0, x1, chunksize=4, inc=1): """Iterate from x0 to x1 in chunks of chunksize and steps inc. x0 must be finite, x1 need not be. In the latter case, the iterator is infinite. Handles both x0 < x1 and x0 > x1. In the latter case, iterates downwards (make sure to set inc < 0.) >>> [x for x in _iter_chunked(2, 5, inc=2)] [array([2, 4])] >>> [x for x in _iter_chunked(2, 11, inc=2)] [array([2, 4, 6, 8]), array([10])] >>> [x for x in _iter_chunked(2, -5, inc=-2)] [array([ 2, 0, -2, -4])] >>> [x for x in _iter_chunked(2, -9, inc=-2)] [array([ 2, 0, -2, -4]), array([-6, -8])] """ if inc == 0: raise ValueError('Cannot increment by zero.') if chunksize <= 0: raise ValueError('Chunk size must be positive; got %s.' % chunksize) s = 1 if inc > 0 else -1 stepsize = abs(chunksize * inc) x = x0 while (x - x1) * inc < 0: delta = min(stepsize, abs(x - x1)) step = delta * s supp = np.arange(x, x + step, inc) x += step yield supp class rv_sample(rv_discrete): """A 'sample' discrete distribution defined by the support and values. The ctor ignores most of the arguments, only needs the `values` argument. """ def __init__(self, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-8, values=None, inc=1, longname=None, shapes=None, extradoc=None, seed=None): super(rv_discrete, self).__init__(seed) if values is None: raise ValueError("rv_sample.__init__(..., values=None,...)") # cf generic freeze self._ctor_param = dict( a=a, b=b, name=name, badvalue=badvalue, moment_tol=moment_tol, values=values, inc=inc, longname=longname, shapes=shapes, extradoc=extradoc, seed=seed) if badvalue is None: badvalue = nan self.badvalue = badvalue self.moment_tol = moment_tol self.inc = inc self.shapes = shapes self.vecentropy = self._entropy xk, pk = values if np.shape(xk) != np.shape(pk): raise ValueError("xk and pk must have the same shape.") if np.less(pk, 0.0).any(): raise ValueError("All elements of pk must be non-negative.") if not np.allclose(np.sum(pk), 1): raise ValueError("The sum of provided pk is not 1.") indx = np.argsort(np.ravel(xk)) self.xk = np.take(np.ravel(xk), indx, 0) self.pk = np.take(np.ravel(pk), indx, 0) self.a = self.xk[0] self.b = self.xk[-1] self.qvals = np.cumsum(self.pk, axis=0) self.shapes = ' ' # bypass inspection self._construct_argparser(meths_to_inspect=[self._pmf], locscale_in='loc=0', # scale=1 for discrete RVs locscale_out='loc, 1') self._construct_docstrings(name, longname, extradoc) def _get_support(self, *args): """Return the support of the (unscaled, unshifted) distribution. Parameters ---------- arg1, arg2, ... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). Returns ------- a, b : numeric (float, or int or +/-np.inf) end-points of the distribution's support. """ return self.a, self.b def _pmf(self, x): return np.select([x == k for k in self.xk], [np.broadcast_arrays(p, x)[0] for p in self.pk], 0) def _cdf(self, x): xx, xxk = np.broadcast_arrays(x[:, None], self.xk) indx = np.argmax(xxk > xx, axis=-1) - 1 return self.qvals[indx] def _ppf(self, q): qq, sqq = np.broadcast_arrays(q[..., None], self.qvals) indx = argmax(sqq >= qq, axis=-1) return self.xk[indx] def _rvs(self, size=None, random_state=None): # Need to define it explicitly, otherwise .rvs() with size=None # fails due to explicit broadcasting in _ppf U = random_state.uniform(size=size) if size is None: U = np.array(U, ndmin=1) Y = self._ppf(U)[0] else: Y = self._ppf(U) return Y def _entropy(self): return entropy(self.pk) def generic_moment(self, n): n = asarray(n) return np.sum(self.xk**n[np.newaxis, ...] * self.pk, axis=0) def _check_shape(argshape, size): """ This is a utility function used by `_rvs()` in the class geninvgauss_gen. It compares the tuple argshape to the tuple size. Parameters ---------- argshape : tuple of integers Shape of the arguments. size : tuple of integers or integer Size argument of rvs(). Returns ------- The function returns two tuples, scalar_shape and bc. scalar_shape : tuple Shape to which the 1-d array of random variates returned by _rvs_scalar() is converted when it is copied into the output array of _rvs(). bc : tuple of booleans bc is an tuple the same length as size. bc[j] is True if the data associated with that index is generated in one call of _rvs_scalar(). """ scalar_shape = [] bc = [] for argdim, sizedim in zip_longest(argshape[::-1], size[::-1], fillvalue=1): if sizedim > argdim or (argdim == sizedim == 1): scalar_shape.append(sizedim) bc.append(True) else: bc.append(False) return tuple(scalar_shape[::-1]), tuple(bc[::-1]) def get_distribution_names(namespace_pairs, rv_base_class): """ Collect names of statistical distributions and their generators. Parameters ---------- namespace_pairs : sequence A snapshot of (name, value) pairs in the namespace of a module. rv_base_class : class The base class of random variable generator classes in a module. Returns ------- distn_names : list of strings Names of the statistical distributions. distn_gen_names : list of strings Names of the generators of the statistical distributions. Note that these are not simply the names of the statistical distributions, with a _gen suffix added. """ distn_names = [] distn_gen_names = [] for name, value in namespace_pairs: if name.startswith('_'): continue if name.endswith('_gen') and issubclass(value, rv_base_class): distn_gen_names.append(name) if isinstance(value, rv_base_class): distn_names.append(name) return distn_names, distn_gen_names
35.247271
195
0.569743
from scipy._lib._util import getfullargspec_no_self as _getfullargspec import sys import keyword import re import types import warnings import inspect from itertools import zip_longest from scipy._lib import doccer from ._distr_params import distcont, distdiscrete from scipy._lib._util import check_random_state from scipy._lib._util import _valarray as valarray from scipy.special import (comb, chndtr, entr, rel_entr, xlogy, ive) from scipy import optimize from scipy import integrate from scipy.misc import derivative from numpy import (arange, putmask, ravel, ones, shape, ndarray, zeros, floor, logical_and, log, sqrt, place, argmax, vectorize, asarray, nan, inf, isinf, NINF, empty) import numpy as np from ._constants import _XMAX docheaders = {'methods': """\nMethods\n-------\n""", 'notes': """\nNotes\n-----\n""", 'examples': """\nExamples\n--------\n"""} _doc_rvs = """\ rvs(%(shapes)s, loc=0, scale=1, size=1, random_state=None) Random variates. """ _doc_pdf = """\ pdf(x, %(shapes)s, loc=0, scale=1) Probability density function. """ _doc_logpdf = """\ logpdf(x, %(shapes)s, loc=0, scale=1) Log of the probability density function. """ _doc_pmf = """\ pmf(k, %(shapes)s, loc=0, scale=1) Probability mass function. """ _doc_logpmf = """\ logpmf(k, %(shapes)s, loc=0, scale=1) Log of the probability mass function. """ _doc_cdf = """\ cdf(x, %(shapes)s, loc=0, scale=1) Cumulative distribution function. """ _doc_logcdf = """\ logcdf(x, %(shapes)s, loc=0, scale=1) Log of the cumulative distribution function. """ _doc_sf = """\ sf(x, %(shapes)s, loc=0, scale=1) Survival function (also defined as ``1 - cdf``, but `sf` is sometimes more accurate). """ _doc_logsf = """\ logsf(x, %(shapes)s, loc=0, scale=1) Log of the survival function. """ _doc_ppf = """\ ppf(q, %(shapes)s, loc=0, scale=1) Percent point function (inverse of ``cdf`` --- percentiles). """ _doc_isf = """\ isf(q, %(shapes)s, loc=0, scale=1) Inverse survival function (inverse of ``sf``). """ _doc_moment = """\ moment(n, %(shapes)s, loc=0, scale=1) Non-central moment of order n """ _doc_stats = """\ stats(%(shapes)s, loc=0, scale=1, moments='mv') Mean('m'), variance('v'), skew('s'), and/or kurtosis('k'). """ _doc_entropy = """\ entropy(%(shapes)s, loc=0, scale=1) (Differential) entropy of the RV. """ _doc_fit = """\ fit(data) Parameter estimates for generic data. See `scipy.stats.rv_continuous.fit <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.fit.html#scipy.stats.rv_continuous.fit>`__ for detailed documentation of the keyword arguments. """ _doc_expect = """\ expect(func, args=(%(shapes_)s), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds) Expected value of a function (of one argument) with respect to the distribution. """ _doc_expect_discrete = """\ expect(func, args=(%(shapes_)s), loc=0, lb=None, ub=None, conditional=False) Expected value of a function (of one argument) with respect to the distribution. """ _doc_median = """\ median(%(shapes)s, loc=0, scale=1) Median of the distribution. """ _doc_mean = """\ mean(%(shapes)s, loc=0, scale=1) Mean of the distribution. """ _doc_var = """\ var(%(shapes)s, loc=0, scale=1) Variance of the distribution. """ _doc_std = """\ std(%(shapes)s, loc=0, scale=1) Standard deviation of the distribution. """ _doc_interval = """\ interval(alpha, %(shapes)s, loc=0, scale=1) Endpoints of the range that contains alpha percent of the distribution """ _doc_allmethods = ''.join([docheaders['methods'], _doc_rvs, _doc_pdf, _doc_logpdf, _doc_cdf, _doc_logcdf, _doc_sf, _doc_logsf, _doc_ppf, _doc_isf, _doc_moment, _doc_stats, _doc_entropy, _doc_fit, _doc_expect, _doc_median, _doc_mean, _doc_var, _doc_std, _doc_interval]) _doc_default_longsummary = """\ As an instance of the `rv_continuous` class, `%(name)s` object inherits from it a collection of generic methods (see below for the full list), and completes them with details specific for this particular distribution. """ _doc_default_frozen_note = """ Alternatively, the object may be called (as a function) to fix the shape, location, and scale parameters returning a "frozen" continuous RV object: rv = %(name)s(%(shapes)s, loc=0, scale=1) - Frozen RV object with the same methods but holding the given shape, location, and scale fixed. """ _doc_default_example = """\ Examples -------- >>> from scipy.stats import %(name)s >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) Calculate a few first moments: %(set_vals_stmt)s >>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk') Display the probability density function (``pdf``): >>> x = np.linspace(%(name)s.ppf(0.01, %(shapes)s), ... %(name)s.ppf(0.99, %(shapes)s), 100) >>> ax.plot(x, %(name)s.pdf(x, %(shapes)s), ... 'r-', lw=5, alpha=0.6, label='%(name)s pdf') Alternatively, the distribution object can be called (as a function) to fix the shape, location and scale parameters. This returns a "frozen" RV object holding the given parameters fixed. Freeze the distribution and display the frozen ``pdf``: >>> rv = %(name)s(%(shapes)s) >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') Check accuracy of ``cdf`` and ``ppf``: >>> vals = %(name)s.ppf([0.001, 0.5, 0.999], %(shapes)s) >>> np.allclose([0.001, 0.5, 0.999], %(name)s.cdf(vals, %(shapes)s)) True Generate random numbers: >>> r = %(name)s.rvs(%(shapes)s, size=1000) And compare the histogram: >>> ax.hist(r, density=True, histtype='stepfilled', alpha=0.2) >>> ax.legend(loc='best', frameon=False) >>> plt.show() """ _doc_default_locscale = """\ The probability density above is defined in the "standardized" form. To shift and/or scale the distribution use the ``loc`` and ``scale`` parameters. Specifically, ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with ``y = (x - loc) / scale``. """ _doc_default = ''.join([_doc_default_longsummary, _doc_allmethods, '\n', _doc_default_example]) _doc_default_before_notes = ''.join([_doc_default_longsummary, _doc_allmethods]) docdict = { 'rvs': _doc_rvs, 'pdf': _doc_pdf, 'logpdf': _doc_logpdf, 'cdf': _doc_cdf, 'logcdf': _doc_logcdf, 'sf': _doc_sf, 'logsf': _doc_logsf, 'ppf': _doc_ppf, 'isf': _doc_isf, 'stats': _doc_stats, 'entropy': _doc_entropy, 'fit': _doc_fit, 'moment': _doc_moment, 'expect': _doc_expect, 'interval': _doc_interval, 'mean': _doc_mean, 'std': _doc_std, 'var': _doc_var, 'median': _doc_median, 'allmethods': _doc_allmethods, 'longsummary': _doc_default_longsummary, 'frozennote': _doc_default_frozen_note, 'example': _doc_default_example, 'default': _doc_default, 'before_notes': _doc_default_before_notes, 'after_notes': _doc_default_locscale } docdict_discrete = docdict.copy() docdict_discrete['pmf'] = _doc_pmf docdict_discrete['logpmf'] = _doc_logpmf docdict_discrete['expect'] = _doc_expect_discrete _doc_disc_methods = ['rvs', 'pmf', 'logpmf', 'cdf', 'logcdf', 'sf', 'logsf', 'ppf', 'isf', 'stats', 'entropy', 'expect', 'median', 'mean', 'var', 'std', 'interval'] for obj in _doc_disc_methods: docdict_discrete[obj] = docdict_discrete[obj].replace(', scale=1', '') _doc_disc_methods_err_varname = ['cdf', 'logcdf', 'sf', 'logsf'] for obj in _doc_disc_methods_err_varname: docdict_discrete[obj] = docdict_discrete[obj].replace('(x, ', '(k, ') docdict_discrete.pop('pdf') docdict_discrete.pop('logpdf') _doc_allmethods = ''.join([docdict_discrete[obj] for obj in _doc_disc_methods]) docdict_discrete['allmethods'] = docheaders['methods'] + _doc_allmethods docdict_discrete['longsummary'] = _doc_default_longsummary.replace( 'rv_continuous', 'rv_discrete') _doc_default_frozen_note = """ Alternatively, the object may be called (as a function) to fix the shape and location parameters returning a "frozen" discrete RV object: rv = %(name)s(%(shapes)s, loc=0) - Frozen RV object with the same methods but holding the given shape and location fixed. """ docdict_discrete['frozennote'] = _doc_default_frozen_note _doc_default_discrete_example = """\ Examples -------- >>> from scipy.stats import %(name)s >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) Calculate a few first moments: %(set_vals_stmt)s >>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk') Display the probability mass function (``pmf``): >>> x = np.arange(%(name)s.ppf(0.01, %(shapes)s), ... %(name)s.ppf(0.99, %(shapes)s)) >>> ax.plot(x, %(name)s.pmf(x, %(shapes)s), 'bo', ms=8, label='%(name)s pmf') >>> ax.vlines(x, 0, %(name)s.pmf(x, %(shapes)s), colors='b', lw=5, alpha=0.5) Alternatively, the distribution object can be called (as a function) to fix the shape and location. This returns a "frozen" RV object holding the given parameters fixed. Freeze the distribution and display the frozen ``pmf``: >>> rv = %(name)s(%(shapes)s) >>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1, ... label='frozen pmf') >>> ax.legend(loc='best', frameon=False) >>> plt.show() Check accuracy of ``cdf`` and ``ppf``: >>> prob = %(name)s.cdf(x, %(shapes)s) >>> np.allclose(x, %(name)s.ppf(prob, %(shapes)s)) True Generate random numbers: >>> r = %(name)s.rvs(%(shapes)s, size=1000) """ _doc_default_discrete_locscale = """\ The probability mass function above is defined in the "standardized" form. To shift distribution use the ``loc`` parameter. Specifically, ``%(name)s.pmf(k, %(shapes)s, loc)`` is identically equivalent to ``%(name)s.pmf(k - loc, %(shapes)s)``. """ docdict_discrete['example'] = _doc_default_discrete_example docdict_discrete['after_notes'] = _doc_default_discrete_locscale _doc_default_before_notes = ''.join([docdict_discrete['longsummary'], docdict_discrete['allmethods']]) docdict_discrete['before_notes'] = _doc_default_before_notes _doc_default_disc = ''.join([docdict_discrete['longsummary'], docdict_discrete['allmethods'], docdict_discrete['frozennote'], docdict_discrete['example']]) docdict_discrete['default'] = _doc_default_disc for obj in [s for s in dir() if s.startswith('_doc_')]: exec('del ' + obj) del obj def _moment(data, n, mu=None): if mu is None: mu = data.mean() return ((data - mu)**n).mean() def _moment_from_stats(n, mu, mu2, g1, g2, moment_func, args): if (n == 0): return 1.0 elif (n == 1): if mu is None: val = moment_func(1, *args) else: val = mu elif (n == 2): if mu2 is None or mu is None: val = moment_func(2, *args) else: val = mu2 + mu*mu elif (n == 3): if g1 is None or mu2 is None or mu is None: val = moment_func(3, *args) else: mu3 = g1 * np.power(mu2, 1.5) val = mu3+3*mu*mu2+mu*mu*mu elif (n == 4): if g1 is None or g2 is None or mu2 is None or mu is None: val = moment_func(4, *args) else: mu4 = (g2+3.0)*(mu2**2.0) mu3 = g1*np.power(mu2, 1.5) val = mu4+4*mu*mu3+6*mu*mu*mu2+mu*mu*mu*mu else: val = moment_func(n, *args) return val def _skew(data): data = np.ravel(data) mu = data.mean() m2 = ((data - mu)**2).mean() m3 = ((data - mu)**3).mean() return m3 / np.power(m2, 1.5) def _kurtosis(data): data = np.ravel(data) mu = data.mean() m2 = ((data - mu)**2).mean() m4 = ((data - mu)**4).mean() return m4 / m2**2 - 3 class rv_frozen(object): def __init__(self, dist, *args, **kwds): self.args = args self.kwds = kwds self.dist = dist.__class__(**dist._updated_ctor_param()) shapes, _, _ = self.dist._parse_args(*args, **kwds) self.a, self.b = self.dist._get_support(*shapes) @property def random_state(self): return self.dist._random_state @random_state.setter def random_state(self, seed): self.dist._random_state = check_random_state(seed) def pdf(self, x): return self.dist.pdf(x, *self.args, **self.kwds) def logpdf(self, x): return self.dist.logpdf(x, *self.args, **self.kwds) def cdf(self, x): return self.dist.cdf(x, *self.args, **self.kwds) def logcdf(self, x): return self.dist.logcdf(x, *self.args, **self.kwds) def ppf(self, q): return self.dist.ppf(q, *self.args, **self.kwds) def isf(self, q): return self.dist.isf(q, *self.args, **self.kwds) def rvs(self, size=None, random_state=None): kwds = self.kwds.copy() kwds.update({'size': size, 'random_state': random_state}) return self.dist.rvs(*self.args, **kwds) def sf(self, x): return self.dist.sf(x, *self.args, **self.kwds) def logsf(self, x): return self.dist.logsf(x, *self.args, **self.kwds) def stats(self, moments='mv'): kwds = self.kwds.copy() kwds.update({'moments': moments}) return self.dist.stats(*self.args, **kwds) def median(self): return self.dist.median(*self.args, **self.kwds) def mean(self): return self.dist.mean(*self.args, **self.kwds) def var(self): return self.dist.var(*self.args, **self.kwds) def std(self): return self.dist.std(*self.args, **self.kwds) def moment(self, n): return self.dist.moment(n, *self.args, **self.kwds) def entropy(self): return self.dist.entropy(*self.args, **self.kwds) def pmf(self, k): return self.dist.pmf(k, *self.args, **self.kwds) def logpmf(self, k): return self.dist.logpmf(k, *self.args, **self.kwds) def interval(self, alpha): return self.dist.interval(alpha, *self.args, **self.kwds) def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds): a, loc, scale = self.dist._parse_args(*self.args, **self.kwds) if isinstance(self.dist, rv_discrete): return self.dist.expect(func, a, loc, lb, ub, conditional, **kwds) else: return self.dist.expect(func, a, loc, scale, lb, ub, conditional, **kwds) def support(self): return self.dist.support(*self.args, **self.kwds) def argsreduce(cond, *args): newargs = np.atleast_1d(*args) if not isinstance(newargs, list): newargs = [newargs, ] expand_arr = (cond == cond) return [np.extract(cond, arr1 * expand_arr) for arr1 in newargs] parse_arg_template = """ def _parse_args(self, %(shape_arg_str)s %(locscale_in)s): return (%(shape_arg_str)s), %(locscale_out)s def _parse_args_rvs(self, %(shape_arg_str)s %(locscale_in)s, size=None): return self._argcheck_rvs(%(shape_arg_str)s %(locscale_out)s, size=size) def _parse_args_stats(self, %(shape_arg_str)s %(locscale_in)s, moments='mv'): return (%(shape_arg_str)s), %(locscale_out)s, moments """ def _ncx2_log_pdf(x, df, nc): df2 = df/2.0 - 1.0 xs, ns = np.sqrt(x), np.sqrt(nc) res = xlogy(df2/2.0, x/nc) - 0.5*(xs - ns)**2 res += np.log(ive(df2, xs*ns) / 2.0) return res def _ncx2_pdf(x, df, nc): return np.exp(_ncx2_log_pdf(x, df, nc)) def _ncx2_cdf(x, df, nc): return chndtr(x, df, nc) class rv_generic(object): def __init__(self, seed=None): super(rv_generic, self).__init__() sig = _getfullargspec(self._stats) self._stats_has_moments = ((sig.varkw is not None) or ('moments' in sig.args) or ('moments' in sig.kwonlyargs)) self._random_state = check_random_state(seed) argspec = inspect.getfullargspec(self._rvs) self._rvs_uses_size_attribute = (argspec.varkw is None and 'size' not in argspec.args and 'size' not in argspec.kwonlyargs) self._rvs_size_warned = False @property def random_state(self): return self._random_state @random_state.setter def random_state(self, seed): self._random_state = check_random_state(seed) def __getstate__(self): return self._updated_ctor_param(), self._random_state def __setstate__(self, state): ctor_param, r = state self.__init__(**ctor_param) self._random_state = r return self def _construct_argparser( self, meths_to_inspect, locscale_in, locscale_out): if self.shapes: if not isinstance(self.shapes, str): raise TypeError('shapes must be a string.') shapes = self.shapes.replace(',', ' ').split() for field in shapes: if keyword.iskeyword(field): raise SyntaxError('keywords cannot be used as shapes.') if not re.match('^[_a-zA-Z][_a-zA-Z0-9]*$', field): raise SyntaxError( 'shapes must be valid python identifiers') else: shapes_list = [] for meth in meths_to_inspect: shapes_args = _getfullargspec(meth) args = shapes_args.args[1:] if args: shapes_list.append(args) if shapes_args.varargs is not None: raise TypeError( '*args are not allowed w/out explicit shapes') if shapes_args.varkw is not None: raise TypeError( '**kwds are not allowed w/out explicit shapes') if shapes_args.kwonlyargs: raise TypeError( 'kwonly args are not allowed w/out explicit shapes') if shapes_args.defaults is not None: raise TypeError('defaults are not allowed for shapes') if shapes_list: shapes = shapes_list[0] for item in shapes_list: if item != shapes: raise TypeError('Shape arguments are inconsistent.') else: shapes = [] shapes_str = ', '.join(shapes) + ', ' if shapes else '' dct = dict(shape_arg_str=shapes_str, locscale_in=locscale_in, locscale_out=locscale_out, ) ns = {} exec(parse_arg_template % dct, ns) for name in ['_parse_args', '_parse_args_stats', '_parse_args_rvs']: setattr(self, name, types.MethodType(ns[name], self)) self.shapes = ', '.join(shapes) if shapes else None if not hasattr(self, 'numargs'): self.numargs = len(shapes) def _construct_doc(self, docdict, shapes_vals=None): tempdict = docdict.copy() tempdict['name'] = self.name or 'distname' tempdict['shapes'] = self.shapes or '' if shapes_vals is None: shapes_vals = () vals = ', '.join('%.3g' % val for val in shapes_vals) tempdict['vals'] = vals tempdict['shapes_'] = self.shapes or '' if self.shapes and self.numargs == 1: tempdict['shapes_'] += ',' if self.shapes: tempdict['set_vals_stmt'] = '>>> %s = %s' % (self.shapes, vals) else: tempdict['set_vals_stmt'] = '' if self.shapes is None: for item in ['default', 'before_notes']: tempdict[item] = tempdict[item].replace( "\n%(shapes)s : array_like\n shape parameters", "") for i in range(2): if self.shapes is None: self.__doc__ = self.__doc__.replace("%(shapes)s, ", "") try: self.__doc__ = doccer.docformat(self.__doc__, tempdict) except TypeError as e: raise Exception("Unable to construct docstring for distribution \"%s\": %s" % (self.name, repr(e))) self.__doc__ = self.__doc__.replace('(, ', '(').replace(', )', ')') def _construct_default_doc(self, longname=None, extradoc=None, docdict=None, discrete='continuous'): if longname is None: longname = 'A' if extradoc is None: extradoc = '' if extradoc.startswith('\n\n'): extradoc = extradoc[2:] self.__doc__ = ''.join(['%s %s random variable.' % (longname, discrete), '\n\n%(before_notes)s\n', docheaders['notes'], extradoc, '\n%(example)s']) self._construct_doc(docdict) def freeze(self, *args, **kwds): return rv_frozen(self, *args, **kwds) def __call__(self, *args, **kwds): return self.freeze(*args, **kwds) __call__.__doc__ = freeze.__doc__ # Otherwise, the other set can be defined. def _stats(self, *args, **kwds): return None, None, None, None # Noncentral moments (also known as the moment about the origin). # Expressed in LaTeX, munp would be $\mu'_{n}$, i.e. "mu-sub-n-prime". def _munp(self, n, *args): with np.errstate(all='ignore'): vals = self.generic_moment(n, *args) return vals def _argcheck_rvs(self, *args, **kwargs): size = kwargs.get('size', None) all_bcast = np.broadcast_arrays(*args) def squeeze_left(a): while a.ndim > 0 and a.shape[0] == 1: a = a[0] return a # dimensions are effectively ignored. In other words, when `size` # is given, trivial leading dimensions of the broadcast parameters # in excess of the number of dimensions in size are ignored, e.g. # >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]], size=3) # array([ 1.00104267, 3.00422496, 4.99799278]) # If `size` is not given, the exact broadcast shape is preserved: # >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]]) # array([[[[ 1.00862899, 3.00061431, 4.99867122]]]]) # all_bcast = [squeeze_left(a) for a in all_bcast] bcast_shape = all_bcast[0].shape bcast_ndim = all_bcast[0].ndim if size is None: size_ = bcast_shape else: size_ = tuple(np.atleast_1d(size)) # Check compatibility of size_ with the broadcast shape of all # the parameters. This check is intended to be consistent with # how the numpy random variate generators (e.g. np.random.normal, # np.random.beta) handle their arguments. The rule is that, if size # is given, it determines the shape of the output. Broadcasting # can't change the output size. ndiff = bcast_ndim - len(size_) if ndiff < 0: bcast_shape = (1,)*(-ndiff) + bcast_shape elif ndiff > 0: size_ = (1,)*ndiff + size_ ok = all([bcdim == 1 or bcdim == szdim for (bcdim, szdim) in zip(bcast_shape, size_)]) if not ok: raise ValueError("size does not match the broadcast shape of " "the parameters. %s, %s, %s" % (size, size_, bcast_shape)) param_bcast = all_bcast[:-2] loc_bcast = all_bcast[-2] scale_bcast = all_bcast[-1] return param_bcast, loc_bcast, scale_bcast, size_ t_support(self, *args, **kwargs): return self.a, self.b def _support_mask(self, x, *args): a, b = self._get_support(*args) with np.errstate(invalid='ignore'): return (a <= x) & (x <= b) def _open_support_mask(self, x, *args): a, b = self._get_support(*args) with np.errstate(invalid='ignore'): return (a < x) & (x < b) def _rvs(self, *args, size=None, random_state=None): ppf(U, *args) return Y def _logcdf(self, x, *args): with np.errstate(divide='ignore'): return log(self._cdf(x, *args)) def _sf(self, x, *args): return 1.0-self._cdf(x, *args) def _logsf(self, x, *args): with np.errstate(divide='ignore'): return log(self._sf(x, *args)) def _ppf(self, q, *args): return self._ppfvec(q, *args) def _isf(self, q, *args): return self._ppf(1.0-q, *args) def rvs(self, *args, **kwds): discrete = kwds.pop('discrete', None) rndm = kwds.pop('random_state', None) args, loc, scale, size = self._parse_args_rvs(*args, **kwds) cond = logical_and(self._argcheck(*args), (scale >= 0)) if not np.all(cond): raise ValueError("Domain error in arguments.") if np.all(scale == 0): return loc*ones(size, 'd') if rndm is not None: random_state_saved = self._random_state random_state = check_random_state(rndm) else: random_state = self._random_state if self._rvs_uses_size_attribute: if not self._rvs_size_warned: warnings.warn( f'The signature of {self._rvs} does not contain ' f'a "size" keyword. Such signatures are deprecated.', np.VisibleDeprecationWarning) self._rvs_size_warned = True self._size = size self._random_state = random_state vals = self._rvs(*args) else: vals = self._rvs(*args, size=size, random_state=random_state) vals = vals * scale + loc if rndm is not None: self._random_state = random_state_saved if discrete: if size == (): vals = int(vals) else: vals = vals.astype(int) return vals def stats(self, *args, **kwds): args, loc, scale, moments = self._parse_args_stats(*args, **kwds) loc, scale = map(asarray, (loc, scale)) args = tuple(map(asarray, args)) cond = self._argcheck(*args) & (scale > 0) & (loc == loc) output = [] default = valarray(shape(cond), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *(args+(scale, loc))) scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] if self._stats_has_moments: mu, mu2, g1, g2 = self._stats(*goodargs, **{'moments': moments}) else: mu, mu2, g1, g2 = self._stats(*goodargs) if g1 is None: mu3 = None else: if mu2 is None: mu2 = self._munp(2, *goodargs) if g2 is None: mu3 = g1 * np.power(mu2, 1.5) if 'm' in moments: if mu is None: mu = self._munp(1, *goodargs) out0 = default.copy() place(out0, cond, mu * scale + loc) output.append(out0) if 'v' in moments: if mu2 is None: mu2p = self._munp(2, *goodargs) if mu is None: mu = self._munp(1, *goodargs) with np.errstate(invalid='ignore'): mu2 = np.where(np.isfinite(mu), mu2p - mu**2, np.inf) out0 = default.copy() place(out0, cond, mu2 * scale * scale) output.append(out0) if 's' in moments: if g1 is None: mu3p = self._munp(3, *goodargs) if mu is None: mu = self._munp(1, *goodargs) if mu2 is None: mu2p = self._munp(2, *goodargs) mu2 = mu2p - mu * mu with np.errstate(invalid='ignore'): mu3 = (-mu*mu - 3*mu2)*mu + mu3p g1 = mu3 / np.power(mu2, 1.5) out0 = default.copy() place(out0, cond, g1) output.append(out0) if 'k' in moments: if g2 is None: mu4p = self._munp(4, *goodargs) if mu is None: mu = self._munp(1, *goodargs) if mu2 is None: mu2p = self._munp(2, *goodargs) mu2 = mu2p - mu * mu if mu3 is None: mu3p = self._munp(3, *goodargs) with np.errstate(invalid='ignore'): mu3 = (-mu * mu - 3 * mu2) * mu + mu3p with np.errstate(invalid='ignore'): mu4 = ((-mu**2 - 6*mu2) * mu - 4*mu3)*mu + mu4p g2 = mu4 / mu2**2.0 - 3.0 out0 = default.copy() place(out0, cond, g2) output.append(out0) else: output = [default.copy() for _ in moments] if len(output) == 1: return output[0] else: return tuple(output) def entropy(self, *args, **kwds): args, loc, scale = self._parse_args(*args, **kwds) loc, scale = map(asarray, (loc, scale)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) output = zeros(shape(cond0), 'd') place(output, (1-cond0), self.badvalue) goodargs = argsreduce(cond0, scale, *args) goodscale = goodargs[0] goodargs = goodargs[1:] place(output, cond0, self.vecentropy(*goodargs) + log(goodscale)) return output def moment(self, n, *args, **kwds): args, loc, scale = self._parse_args(*args, **kwds) if not (self._argcheck(*args) and (scale > 0)): return nan if (floor(n) != n): raise ValueError("Moment must be an integer.") if (n < 0): raise ValueError("Moment must be positive.") mu, mu2, g1, g2 = None, None, None, None if (n > 0) and (n < 5): if self._stats_has_moments: mdict = {'moments': {1: 'm', 2: 'v', 3: 'vs', 4: 'vk'}[n]} else: mdict = {} mu, mu2, g1, g2 = self._stats(*args, **mdict) val = _moment_from_stats(n, mu, mu2, g1, g2, self._munp, args) if loc == 0: return scale**n * val else: result = 0 fac = float(scale) / float(loc) for k in range(n): valk = _moment_from_stats(k, mu, mu2, g1, g2, self._munp, args) result += comb(n, k, exact=True)*(fac**k) * valk result += fac**n * val return result * loc**n def median(self, *args, **kwds): return self.ppf(0.5, *args, **kwds) def mean(self, *args, **kwds): kwds['moments'] = 'm' res = self.stats(*args, **kwds) if isinstance(res, ndarray) and res.ndim == 0: return res[()] return res def var(self, *args, **kwds): kwds['moments'] = 'v' res = self.stats(*args, **kwds) if isinstance(res, ndarray) and res.ndim == 0: return res[()] return res def std(self, *args, **kwds): kwds['moments'] = 'v' res = sqrt(self.stats(*args, **kwds)) return res def interval(self, alpha, *args, **kwds): alpha = asarray(alpha) if np.any((alpha > 1) | (alpha < 0)): raise ValueError("alpha must be between 0 and 1 inclusive") q1 = (1.0-alpha)/2 q2 = (1.0+alpha)/2 a = self.ppf(q1, *args, **kwds) b = self.ppf(q2, *args, **kwds) return a, b def support(self, *args, **kwargs): args, loc, scale = self._parse_args(*args, **kwargs) _a, _b = self._get_support(*args) return _a * scale + loc, _b * scale + loc def _get_fixed_fit_value(kwds, names): vals = [(name, kwds.pop(name)) for name in names if name in kwds] if len(vals) > 1: repeated = [name for name, val in vals] raise ValueError("fit method got multiple keyword arguments to " "specify the same fixed parameter: " + ', '.join(repeated)) return vals[0][1] if vals else None b=b, xtol=xtol, badvalue=badvalue, name=name, longname=longname, shapes=shapes, extradoc=extradoc, seed=seed) if badvalue is None: badvalue = nan if name is None: name = 'Distribution' self.badvalue = badvalue self.name = name self.a = a self.b = b if a is None: self.a = -inf if b is None: self.b = inf self.xtol = xtol self.moment_type = momtype self.shapes = shapes self._construct_argparser(meths_to_inspect=[self._pdf, self._cdf], locscale_in='loc=0, scale=1', locscale_out='loc, scale') self._ppfvec = vectorize(self._ppf_single, otypes='d') self._ppfvec.nin = self.numargs + 1 self.vecentropy = vectorize(self._entropy, otypes='d') self._cdfvec = vectorize(self._cdf_single, otypes='d') self._cdfvec.nin = self.numargs + 1 self.extradoc = extradoc if momtype == 0: self.generic_moment = vectorize(self._mom0_sc, otypes='d') else: self.generic_moment = vectorize(self._mom1_sc, otypes='d') self.generic_moment.nin = self.numargs + 1 if longname is None: if name[0] in ['aeiouAEIOU']: hstr = "An " else: hstr = "A " longname = hstr + name if sys.flags.optimize < 2: if self.__doc__ is None: self._construct_default_doc(longname=longname, extradoc=extradoc, docdict=docdict, discrete='continuous') else: dct = dict(distcont) self._construct_doc(docdict, dct.get(self.name)) def _updated_ctor_param(self): dct = self._ctor_param.copy() dct['a'] = self.a dct['b'] = self.b dct['xtol'] = self.xtol dct['badvalue'] = self.badvalue dct['name'] = self.name dct['shapes'] = self.shapes dct['extradoc'] = self.extradoc return dct def _ppf_to_solve(self, x, q, *args): return self.cdf(*(x, )+args)-q def _ppf_single(self, q, *args): factor = 10. left, right = self._get_support(*args) if np.isinf(left): left = min(-factor, right) while self._ppf_to_solve(left, q, *args) > 0.: left, right = left * factor, left if np.isinf(right): right = max(factor, left) while self._ppf_to_solve(right, q, *args) < 0.: left, right = right, right * factor return optimize.brentq(self._ppf_to_solve, left, right, args=(q,)+args, xtol=self.xtol) def _mom_integ0(self, x, m, *args): return x**m * self.pdf(x, *args) def _mom0_sc(self, m, *args): _a, _b = self._get_support(*args) return integrate.quad(self._mom_integ0, _a, _b, args=(m,)+args)[0] def _mom_integ1(self, q, m, *args): return (self.ppf(q, *args))**m def _mom1_sc(self, m, *args): return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0] def _pdf(self, x, *args): return derivative(self._cdf, x, dx=1e-5, args=args, order=5) : return log(self._pdf(x, *args)) def _cdf_single(self, x, *args): _a, _b = self._get_support(*args) return integrate.quad(self._pdf, _a, x, args=args)[0] def _cdf(self, x, *args): return self._cdfvec(x, *args) s(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._support_mask(x, *args) & (scale > 0) cond = cond0 & cond1 output = zeros(shape(cond), dtyp) putmask(output, (1-cond0)+np.isnan(x), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args+(scale,))) scale, goodargs = goodargs[-1], goodargs[:-1] place(output, cond, self._pdf(*goodargs) / scale) if output.ndim == 0: return output[()] return output def logpdf(self, x, *args, **kwds): args, loc, scale = self._parse_args(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._support_mask(x, *args) & (scale > 0) cond = cond0 & cond1 output = empty(shape(cond), dtyp) output.fill(NINF) putmask(output, (1-cond0)+np.isnan(x), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args+(scale,))) scale, goodargs = goodargs[-1], goodargs[:-1] place(output, cond, self._logpdf(*goodargs) - log(scale)) if output.ndim == 0: return output[()] return output def cdf(self, x, *args, **kwds): args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = (x >= np.asarray(_b)) & cond0 cond = cond0 & cond1 output = zeros(shape(cond), dtyp) place(output, (1-cond0)+np.isnan(x), self.badvalue) place(output, cond2, 1.0) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._cdf(*goodargs)) if output.ndim == 0: return output[()] return output def logcdf(self, x, *args, **kwds): args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = (x >= _b) & cond0 cond = cond0 & cond1 output = empty(shape(cond), dtyp) output.fill(NINF) place(output, (1-cond0)*(cond1 == cond1)+np.isnan(x), self.badvalue) place(output, cond2, 0.0) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._logcdf(*goodargs)) if output.ndim == 0: return output[()] return output def sf(self, x, *args, **kwds): args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = cond0 & (x <= _a) cond = cond0 & cond1 output = zeros(shape(cond), dtyp) place(output, (1-cond0)+np.isnan(x), self.badvalue) place(output, cond2, 1.0) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._sf(*goodargs)) if output.ndim == 0: return output[()] return output def logsf(self, x, *args, **kwds): args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = cond0 & (x <= _a) cond = cond0 & cond1 output = empty(shape(cond), dtyp) output.fill(NINF) place(output, (1-cond0)+np.isnan(x), self.badvalue) place(output, cond2, 0.0) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._logsf(*goodargs)) if output.ndim == 0: return output[()] return output def ppf(self, q, *args, **kwds): args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) q, loc, scale = map(asarray, (q, loc, scale)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) cond1 = (0 < q) & (q < 1) cond2 = cond0 & (q == 0) cond3 = cond0 & (q == 1) cond = cond0 & cond1 output = valarray(shape(cond), value=self.badvalue) lower_bound = _a * scale + loc upper_bound = _b * scale + loc place(output, cond2, argsreduce(cond2, lower_bound)[0]) place(output, cond3, argsreduce(cond3, upper_bound)[0]) if np.any(cond): goodargs = argsreduce(cond, *((q,)+args+(scale, loc))) scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] place(output, cond, self._ppf(*goodargs) * scale + loc) if output.ndim == 0: return output[()] return output def isf(self, q, *args, **kwds): args, loc, scale = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) q, loc, scale = map(asarray, (q, loc, scale)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) cond1 = (0 < q) & (q < 1) cond2 = cond0 & (q == 1) cond3 = cond0 & (q == 0) cond = cond0 & cond1 output = valarray(shape(cond), value=self.badvalue) lower_bound = _a * scale + loc upper_bound = _b * scale + loc place(output, cond2, argsreduce(cond2, lower_bound)[0]) place(output, cond3, argsreduce(cond3, upper_bound)[0]) if np.any(cond): goodargs = argsreduce(cond, *((q,)+args+(scale, loc))) scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] place(output, cond, self._isf(*goodargs) * scale + loc) if output.ndim == 0: return output[()] return output def _nnlf(self, x, *args): return -np.sum(self._logpdf(x, *args), axis=0) def _unpack_loc_scale(self, theta): try: loc = theta[-2] scale = theta[-1] args = tuple(theta[:-2]) except IndexError: raise ValueError("Not enough input arguments.") return loc, scale, args def nnlf(self, theta, x): loc, scale, args = self._unpack_loc_scale(theta) if not self._argcheck(*args) or scale <= 0: return inf x = asarray((x-loc) / scale) n_log_scale = len(x) * log(scale) if np.any(~self._support_mask(x, *args)): return inf return self._nnlf(x, *args) + n_log_scale def _nnlf_and_penalty(self, x, args): cond0 = ~self._support_mask(x, *args) n_bad = np.count_nonzero(cond0, axis=0) if n_bad > 0: x = argsreduce(~cond0, x)[0] logpdf = self._logpdf(x, *args) finite_logpdf = np.isfinite(logpdf) n_bad += np.sum(~finite_logpdf, axis=0) if n_bad > 0: penalty = n_bad * log(_XMAX) * 100 return -np.sum(logpdf[finite_logpdf], axis=0) + penalty return -np.sum(logpdf, axis=0) def _penalized_nnlf(self, theta, x): loc, scale, args = self._unpack_loc_scale(theta) if not self._argcheck(*args) or scale <= 0: return inf x = asarray((x-loc) / scale) n_log_scale = len(x) * log(scale) return self._nnlf_and_penalty(x, args) + n_log_scale def _fitstart(self, data, args=None): if args is None: args = (1.0,)*self.numargs loc, scale = self._fit_loc_scale_support(data, *args) return args + (loc, scale) def _reduce_func(self, args, kwds): if self.shapes: shapes = self.shapes.replace(',', ' ').split() for j, s in enumerate(shapes): key = 'f' + str(j) names = [key, 'f' + s, 'fix_' + s] val = _get_fixed_fit_value(kwds, names) if val is not None: kwds[key] = val args = list(args) Nargs = len(args) fixedn = [] names = ['f%d' % n for n in range(Nargs - 2)] + ['floc', 'fscale'] x0 = [] for n, key in enumerate(names): if key in kwds: fixedn.append(n) args[n] = kwds.pop(key) else: x0.append(args[n]) if len(fixedn) == 0: func = self._penalized_nnlf restore = None else: if len(fixedn) == Nargs: raise ValueError( "All parameters fixed. There is nothing to optimize.") def restore(args, theta): i = 0 for n in range(Nargs): if n not in fixedn: args[n] = theta[i] i += 1 return args def func(theta, x): newtheta = restore(args[:], theta) return self._penalized_nnlf(newtheta, x) return x0, func, restore, args def fit(self, data, *args, **kwds): Narg = len(args) if Narg > self.numargs: raise TypeError("Too many input arguments.") if not np.isfinite(data).all(): raise RuntimeError("The data contains non-finite values.") start = [None]*2 if (Narg < self.numargs) or not ('loc' in kwds and 'scale' in kwds): start = self._fitstart(data) args += start[Narg:-2] loc = kwds.pop('loc', start[-2]) scale = kwds.pop('scale', start[-1]) args += (loc, scale) x0, func, restore, args = self._reduce_func(args, kwds) optimizer = kwds.pop('optimizer', optimize.fmin) if not callable(optimizer) and isinstance(optimizer, str): if not optimizer.startswith('fmin_'): optimizer = "fmin_"+optimizer if optimizer == 'fmin_': optimizer = 'fmin' try: optimizer = getattr(optimize, optimizer) except AttributeError: raise ValueError("%s is not a valid optimizer" % optimizer) if kwds: raise TypeError("Unknown arguments: %s." % kwds) vals = optimizer(func, x0, args=(ravel(data),), disp=0) if restore is not None: vals = restore(args, vals) vals = tuple(vals) return vals def _fit_loc_scale_support(self, data, *args): data = np.asarray(data) loc_hat, scale_hat = self.fit_loc_scale(data, *args) self._argcheck(*args) _a, _b = self._get_support(*args) a, b = _a, _b support_width = b - a if support_width <= 0: return loc_hat, scale_hat a_hat = loc_hat + a * scale_hat b_hat = loc_hat + b * scale_hat data_a = np.min(data) data_b = np.max(data) if a_hat < data_a and data_b < b_hat: return loc_hat, scale_hat data_width = data_b - data_a rel_margin = 0.1 margin = data_width * rel_margin if support_width < np.inf: loc_hat = (data_a - a) - margin scale_hat = (data_width + 2 * margin) / support_width return loc_hat, scale_hat if a > -np.inf: return (data_a - a) - margin, 1 elif b < np.inf: return (data_b - b) + margin, 1 else: raise RuntimeError def fit_loc_scale(self, data, *args): mu, mu2 = self.stats(*args, **{'moments': 'mv'}) tmp = asarray(data) muhat = tmp.mean() mu2hat = tmp.var() Shat = sqrt(mu2hat / mu2) Lhat = muhat - Shat*mu if not np.isfinite(Lhat): Lhat = 0 if not (np.isfinite(Shat) and (0 < Shat)): Shat = 1 return Lhat, Shat def _entropy(self, *args): def integ(x): val = self._pdf(x, *args) return entr(val) _a, _b = self._get_support(*args) with np.errstate(over='ignore'): h = integrate.quad(integ, _a, _b)[0] if not np.isnan(h): return h else: low, upp = self.ppf([1e-10, 1. - 1e-10], *args) if np.isinf(_b): upper = upp else: upper = _b if np.isinf(_a): lower = low else: lower = _a return integrate.quad(integ, lower, upper)[0] def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds): lockwds = {'loc': loc, 'scale': scale} self._argcheck(*args) _a, _b = self._get_support(*args) if func is None: def fun(x, *args): return x * self.pdf(x, *args, **lockwds) else: def fun(x, *args): return func(x) * self.pdf(x, *args, **lockwds) if lb is None: lb = loc + _a * scale if ub is None: ub = loc + _b * scale if conditional: invfac = (self.sf(lb, *args, **lockwds) - self.sf(ub, *args, **lockwds)) else: invfac = 1.0 kwds['args'] = args with np.errstate(all='ignore'): vals = integrate.quad(fun, lb, ub, **kwds)[0] / invfac return vals def _drv2_moment(self, n, *args): def fun(x): return np.power(x, n) * self._pmf(x, *args) _a, _b = self._get_support(*args) return _expect(fun, _a, _b, self.ppf(0.5, *args), self.inc) def _drv2_ppfsingle(self, q, *args): _a, _b = self._get_support(*args) b = _b a = _a if isinf(b): b = int(max(100*q, 10)) while 1: if b >= _b: qb = 1.0 break qb = self._cdf(b, *args) if (qb < q): b += 10 else: break else: qb = 1.0 if isinf(a): a = int(min(-100*q, -10)) while 1: if a <= _a: qb = 0.0 break qa = self._cdf(a, *args) if (qa > q): a -= 10 else: break else: qa = self._cdf(a, *args) while 1: if (qa == q): return a if (qb == q): return b if b <= a+1: if qa > q: return a else: return b c = int((a+b)/2.0) qc = self._cdf(c, *args) if (qc < q): if a != c: a = c else: raise RuntimeError('updating stopped, endless loop') qa = qc elif (qc > q): if b != c: b = c else: raise RuntimeError('updating stopped, endless loop') qb = qc else: return c def entropy(pk, qk=None, base=None, axis=0): pk = asarray(pk) pk = 1.0*pk / np.sum(pk, axis=axis, keepdims=True) if qk is None: vec = entr(pk) else: qk = asarray(qk) if qk.shape != pk.shape: raise ValueError("qk and pk must have same shape.") qk = 1.0*qk / np.sum(qk, axis=axis, keepdims=True) vec = rel_entr(pk, qk) S = np.sum(vec, axis=axis) if base is not None: S /= log(base) return S class rv_discrete(rv_generic): def __new__(cls, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-8, values=None, inc=1, longname=None, shapes=None, extradoc=None, seed=None): if values is not None: return super(rv_discrete, cls).__new__(rv_sample) else: return super(rv_discrete, cls).__new__(cls) def __init__(self, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-8, values=None, inc=1, longname=None, shapes=None, extradoc=None, seed=None): super(rv_discrete, self).__init__(seed) self._ctor_param = dict( a=a, b=b, name=name, badvalue=badvalue, moment_tol=moment_tol, values=values, inc=inc, longname=longname, shapes=shapes, extradoc=extradoc, seed=seed) if badvalue is None: badvalue = nan self.badvalue = badvalue self.a = a self.b = b self.moment_tol = moment_tol self.inc = inc self._cdfvec = vectorize(self._cdf_single, otypes='d') self.vecentropy = vectorize(self._entropy) self.shapes = shapes if values is not None: raise ValueError("rv_discrete.__init__(..., values != None, ...)") self._construct_argparser(meths_to_inspect=[self._pmf, self._cdf], locscale_in='loc=0', locscale_out='loc, 1') _vec_generic_moment = vectorize(_drv2_moment, otypes='d') _vec_generic_moment.nin = self.numargs + 2 self.generic_moment = types.MethodType(_vec_generic_moment, self) _vppf = vectorize(_drv2_ppfsingle, otypes='d') _vppf.nin = self.numargs + 2 self._ppfvec = types.MethodType(_vppf, self) self._cdfvec.nin = self.numargs + 1 self._construct_docstrings(name, longname, extradoc) def _construct_docstrings(self, name, longname, extradoc): if name is None: name = 'Distribution' self.name = name self.extradoc = extradoc if longname is None: if name[0] in ['aeiouAEIOU']: hstr = "An " else: hstr = "A " longname = hstr + name if sys.flags.optimize < 2: if self.__doc__ is None: self._construct_default_doc(longname=longname, extradoc=extradoc, docdict=docdict_discrete, discrete='discrete') else: dct = dict(distdiscrete) self._construct_doc(docdict_discrete, dct.get(self.name)) self.__doc__ = self.__doc__.replace( '\n scale : array_like, ' 'optional\n scale parameter (default=1)', '') def _updated_ctor_param(self): dct = self._ctor_param.copy() dct['a'] = self.a dct['b'] = self.b dct['badvalue'] = self.badvalue dct['moment_tol'] = self.moment_tol dct['inc'] = self.inc dct['name'] = self.name dct['shapes'] = self.shapes dct['extradoc'] = self.extradoc return dct def _nonzero(self, k, *args): return floor(k) == k def _pmf(self, k, *args): return self._cdf(k, *args) - self._cdf(k-1, *args) def _logpmf(self, k, *args): return log(self._pmf(k, *args)) def _cdf_single(self, k, *args): _a, _b = self._get_support(*args) m = arange(int(_a), k+1) return np.sum(self._pmf(m, *args), axis=0) def _cdf(self, x, *args): k = floor(x) return self._cdfvec(k, *args) def rvs(self, *args, **kwargs): kwargs['discrete'] = True return super(rv_discrete, self).rvs(*args, **kwargs) def pmf(self, k, *args, **kwds): args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k <= _b) & self._nonzero(k, *args) cond = cond0 & cond1 output = zeros(shape(cond), 'd') place(output, (1-cond0) + np.isnan(k), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, np.clip(self._pmf(*goodargs), 0, 1)) if output.ndim == 0: return output[()] return output def logpmf(self, k, *args, **kwds): args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k <= _b) & self._nonzero(k, *args) cond = cond0 & cond1 output = empty(shape(cond), 'd') output.fill(NINF) place(output, (1-cond0) + np.isnan(k), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, self._logpmf(*goodargs)) if output.ndim == 0: return output[()] return output def cdf(self, k, *args, **kwds): args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k >= _b) cond = cond0 & cond1 output = zeros(shape(cond), 'd') place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2*(cond0 == cond0), 1.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, np.clip(self._cdf(*goodargs), 0, 1)) if output.ndim == 0: return output[()] return output def logcdf(self, k, *args, **kwds): args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k >= _b) cond = cond0 & cond1 output = empty(shape(cond), 'd') output.fill(NINF) place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2*(cond0 == cond0), 0.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, self._logcdf(*goodargs)) if output.ndim == 0: return output[()] return output def sf(self, k, *args, **kwds): args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray(k-loc) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k < _a) & cond0 cond = cond0 & cond1 output = zeros(shape(cond), 'd') place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2, 1.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, np.clip(self._sf(*goodargs), 0, 1)) if output.ndim == 0: return output[()] return output def logsf(self, k, *args, **kwds): args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) k = asarray(k-loc) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k < _a) & cond0 cond = cond0 & cond1 output = empty(shape(cond), 'd') output.fill(NINF) place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2, 0.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, self._logsf(*goodargs)) if output.ndim == 0: return output[()] return output def ppf(self, q, *args, **kwds): args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) q, loc = map(asarray, (q, loc)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (loc == loc) cond1 = (q > 0) & (q < 1) cond2 = (q == 1) & cond0 cond = cond0 & cond1 output = valarray(shape(cond), value=self.badvalue, typecode='d') place(output, (q == 0)*(cond == cond), _a-1 + loc) place(output, cond2, _b + loc) if np.any(cond): goodargs = argsreduce(cond, *((q,)+args+(loc,))) loc, goodargs = goodargs[-1], goodargs[:-1] place(output, cond, self._ppf(*goodargs) + loc) if output.ndim == 0: return output[()] return output def isf(self, q, *args, **kwds): args, loc, _ = self._parse_args(*args, **kwds) _a, _b = self._get_support(*args) q, loc = map(asarray, (q, loc)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (loc == loc) cond1 = (q > 0) & (q < 1) cond2 = (q == 1) & cond0 cond = cond0 & cond1 output = valarray(shape(cond), value=self.badvalue, typecode='d') place(output, (q == 0)*(cond == cond), _b) place(output, cond2, _a-1) if np.any(cond): goodargs = argsreduce(cond, *((q,)+args+(loc,))) loc, goodargs = goodargs[-1], goodargs[:-1] place(output, cond, self._isf(*goodargs) + loc) if output.ndim == 0: return output[()] return output def _entropy(self, *args): if hasattr(self, 'pk'): return entropy(self.pk) else: _a, _b = self._get_support(*args) return _expect(lambda x: entr(self.pmf(x, *args)), _a, _b, self.ppf(0.5, *args), self.inc) def expect(self, func=None, args=(), loc=0, lb=None, ub=None, conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32): if func is None: def fun(x): return (x+loc)*self._pmf(x, *args) else: def fun(x): return func(x+loc)*self._pmf(x, *args) self._argcheck(*args) _a, _b = self._get_support(*args) if lb is None: lb = _a else: lb = lb - loc if ub is None: ub = _b else: ub = ub - loc if conditional: invfac = self.sf(lb-1, *args) - self.sf(ub, *args) else: invfac = 1.0 x0 = self.ppf(0.5, *args) res = _expect(fun, lb, ub, x0, self.inc, maxcount, tolerance, chunksize) return res / invfac def _expect(fun, lb, ub, x0, inc, maxcount=1000, tolerance=1e-10, chunksize=32): if (ub - lb) <= chunksize: supp = np.arange(lb, ub+1, inc) vals = fun(supp) return np.sum(vals) if x0 < lb: x0 = lb if x0 > ub: x0 = ub count, tot = 0, 0. for x in _iter_chunked(x0, ub+1, chunksize=chunksize, inc=inc): count += x.size delta = np.sum(fun(x)) tot += delta if abs(delta) < tolerance * x.size: break if count > maxcount: warnings.warn('expect(): sum did not converge', RuntimeWarning) return tot for x in _iter_chunked(x0-1, lb-1, chunksize=chunksize, inc=-inc): count += x.size delta = np.sum(fun(x)) tot += delta if abs(delta) < tolerance * x.size: break if count > maxcount: warnings.warn('expect(): sum did not converge', RuntimeWarning) break return tot def _iter_chunked(x0, x1, chunksize=4, inc=1): if inc == 0: raise ValueError('Cannot increment by zero.') if chunksize <= 0: raise ValueError('Chunk size must be positive; got %s.' % chunksize) s = 1 if inc > 0 else -1 stepsize = abs(chunksize * inc) x = x0 while (x - x1) * inc < 0: delta = min(stepsize, abs(x - x1)) step = delta * s supp = np.arange(x, x + step, inc) x += step yield supp class rv_sample(rv_discrete): def __init__(self, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-8, values=None, inc=1, longname=None, shapes=None, extradoc=None, seed=None): super(rv_discrete, self).__init__(seed) if values is None: raise ValueError("rv_sample.__init__(..., values=None,...)") self._ctor_param = dict( a=a, b=b, name=name, badvalue=badvalue, moment_tol=moment_tol, values=values, inc=inc, longname=longname, shapes=shapes, extradoc=extradoc, seed=seed) if badvalue is None: badvalue = nan self.badvalue = badvalue self.moment_tol = moment_tol self.inc = inc self.shapes = shapes self.vecentropy = self._entropy xk, pk = values if np.shape(xk) != np.shape(pk): raise ValueError("xk and pk must have the same shape.") if np.less(pk, 0.0).any(): raise ValueError("All elements of pk must be non-negative.") if not np.allclose(np.sum(pk), 1): raise ValueError("The sum of provided pk is not 1.") indx = np.argsort(np.ravel(xk)) self.xk = np.take(np.ravel(xk), indx, 0) self.pk = np.take(np.ravel(pk), indx, 0) self.a = self.xk[0] self.b = self.xk[-1] self.qvals = np.cumsum(self.pk, axis=0) self.shapes = ' ' self._construct_argparser(meths_to_inspect=[self._pmf], locscale_in='loc=0', locscale_out='loc, 1') self._construct_docstrings(name, longname, extradoc) def _get_support(self, *args): return self.a, self.b def _pmf(self, x): return np.select([x == k for k in self.xk], [np.broadcast_arrays(p, x)[0] for p in self.pk], 0) def _cdf(self, x): xx, xxk = np.broadcast_arrays(x[:, None], self.xk) indx = np.argmax(xxk > xx, axis=-1) - 1 return self.qvals[indx] def _ppf(self, q): qq, sqq = np.broadcast_arrays(q[..., None], self.qvals) indx = argmax(sqq >= qq, axis=-1) return self.xk[indx] def _rvs(self, size=None, random_state=None): U = random_state.uniform(size=size) if size is None: U = np.array(U, ndmin=1) Y = self._ppf(U)[0] else: Y = self._ppf(U) return Y def _entropy(self): return entropy(self.pk) def generic_moment(self, n): n = asarray(n) return np.sum(self.xk**n[np.newaxis, ...] * self.pk, axis=0) def _check_shape(argshape, size): scalar_shape = [] bc = [] for argdim, sizedim in zip_longest(argshape[::-1], size[::-1], fillvalue=1): if sizedim > argdim or (argdim == sizedim == 1): scalar_shape.append(sizedim) bc.append(True) else: bc.append(False) return tuple(scalar_shape[::-1]), tuple(bc[::-1]) def get_distribution_names(namespace_pairs, rv_base_class): distn_names = [] distn_gen_names = [] for name, value in namespace_pairs: if name.startswith('_'): continue if name.endswith('_gen') and issubclass(value, rv_base_class): distn_gen_names.append(name) if isinstance(value, rv_base_class): distn_names.append(name) return distn_names, distn_gen_names
true
true
f735fbda2f7247a6884a2e835b13932d3b859e30
5,851
py
Python
PaddleOCR/ppocr/utils/save_load.py
TangJiamin/Ultra_light_OCR_No.23
594aa286dc2f88614141838ce45c164647226cdb
[ "Apache-2.0" ]
null
null
null
PaddleOCR/ppocr/utils/save_load.py
TangJiamin/Ultra_light_OCR_No.23
594aa286dc2f88614141838ce45c164647226cdb
[ "Apache-2.0" ]
null
null
null
PaddleOCR/ppocr/utils/save_load.py
TangJiamin/Ultra_light_OCR_No.23
594aa286dc2f88614141838ce45c164647226cdb
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # 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 __future__ import absolute_import from __future__ import division from __future__ import print_function import errno import os import pickle import six import paddle __all__ = ['init_model', 'save_model', 'load_dygraph_pretrain'] def _mkdir_if_not_exist(path, logger): """ mkdir if not exists, ignore the exception when multiprocess mkdir together """ if not os.path.exists(path): try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(path): logger.warning( 'be happy if some process has already created {}'.format( path)) else: raise OSError('Failed to mkdir {}'.format(path)) def load_dygraph_pretrain(model, logger, path=None, load_static_weights=False): if not (os.path.isdir(path) or os.path.exists(path + '.pdparams')): raise ValueError("Model pretrain path {} does not " "exists.".format(path)) if load_static_weights: pre_state_dict = paddle.static.load_program_state(path) param_state_dict = {} model_dict = model.state_dict() for key in model_dict.keys(): weight_name = model_dict[key].name weight_name = weight_name.replace('binarize', '').replace( 'thresh', '') # for DB if weight_name in pre_state_dict.keys(): # logger.info('Load weight: {}, shape: {}'.format( # weight_name, pre_state_dict[weight_name].shape)) if 'encoder_rnn' in key: # delete axis which is 1 pre_state_dict[weight_name] = pre_state_dict[ weight_name].squeeze() # change axis if len(pre_state_dict[weight_name].shape) > 1: pre_state_dict[weight_name] = pre_state_dict[ weight_name].transpose((1, 0)) param_state_dict[key] = pre_state_dict[weight_name] else: param_state_dict[key] = model_dict[key] model.set_state_dict(param_state_dict) return param_state_dict = paddle.load(path + '.pdparams') model.set_state_dict(param_state_dict) return def init_model(config, model, logger, optimizer=None, lr_scheduler=None): """ load model from checkpoint or pretrained_model """ gloabl_config = config['Global'] checkpoints = gloabl_config.get('checkpoints') pretrained_model = gloabl_config.get('pretrained_model') best_model_dict = {} if checkpoints: assert os.path.exists(checkpoints + ".pdparams"), \ "Given dir {}.pdparams not exist.".format(checkpoints) assert os.path.exists(checkpoints + ".pdopt"), \ "Given dir {}.pdopt not exist.".format(checkpoints) para_dict = paddle.load(checkpoints + '.pdparams') opti_dict = paddle.load(checkpoints + '.pdopt') model.set_state_dict(para_dict) if optimizer is not None: optimizer.set_state_dict(opti_dict) if os.path.exists(checkpoints + '.states'): with open(checkpoints + '.states', 'rb') as f: states_dict = pickle.load(f) if six.PY2 else pickle.load( f, encoding='latin1') best_model_dict = states_dict.get('best_model_dict', {}) if 'epoch' in states_dict: best_model_dict['start_epoch'] = states_dict['epoch'] + 1 logger.info("resume from {}".format(checkpoints)) elif pretrained_model: load_static_weights = gloabl_config.get('load_static_weights', False) if not isinstance(pretrained_model, list): pretrained_model = [pretrained_model] if not isinstance(load_static_weights, list): load_static_weights = [load_static_weights] * len(pretrained_model) for idx, pretrained in enumerate(pretrained_model): load_static = load_static_weights[idx] load_dygraph_pretrain( model, logger, path=pretrained, load_static_weights=load_static) logger.info("load pretrained model from {}".format( pretrained_model)) else: logger.info('train from scratch') return best_model_dict def save_model(net, optimizer, model_path, logger, is_best=False, prefix='ppocr', **kwargs): """ save model to the target path """ _mkdir_if_not_exist(model_path, logger) model_prefix = os.path.join(model_path, prefix) paddle.save(net.state_dict(), model_prefix + '.pdparams') paddle.save(optimizer.state_dict(), model_prefix + '.pdopt') # save metric and config with open(model_prefix + '.states', 'wb') as f: pickle.dump(kwargs, f, protocol=2) if is_best: logger.info('save best model is to {}'.format(model_prefix)) else: logger.info("save model in {}".format(model_prefix))
40.075342
81
0.609981
from __future__ import absolute_import from __future__ import division from __future__ import print_function import errno import os import pickle import six import paddle __all__ = ['init_model', 'save_model', 'load_dygraph_pretrain'] def _mkdir_if_not_exist(path, logger): if not os.path.exists(path): try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(path): logger.warning( 'be happy if some process has already created {}'.format( path)) else: raise OSError('Failed to mkdir {}'.format(path)) def load_dygraph_pretrain(model, logger, path=None, load_static_weights=False): if not (os.path.isdir(path) or os.path.exists(path + '.pdparams')): raise ValueError("Model pretrain path {} does not " "exists.".format(path)) if load_static_weights: pre_state_dict = paddle.static.load_program_state(path) param_state_dict = {} model_dict = model.state_dict() for key in model_dict.keys(): weight_name = model_dict[key].name weight_name = weight_name.replace('binarize', '').replace( 'thresh', '') if weight_name in pre_state_dict.keys(): if 'encoder_rnn' in key: pre_state_dict[weight_name] = pre_state_dict[ weight_name].squeeze() if len(pre_state_dict[weight_name].shape) > 1: pre_state_dict[weight_name] = pre_state_dict[ weight_name].transpose((1, 0)) param_state_dict[key] = pre_state_dict[weight_name] else: param_state_dict[key] = model_dict[key] model.set_state_dict(param_state_dict) return param_state_dict = paddle.load(path + '.pdparams') model.set_state_dict(param_state_dict) return def init_model(config, model, logger, optimizer=None, lr_scheduler=None): gloabl_config = config['Global'] checkpoints = gloabl_config.get('checkpoints') pretrained_model = gloabl_config.get('pretrained_model') best_model_dict = {} if checkpoints: assert os.path.exists(checkpoints + ".pdparams"), \ "Given dir {}.pdparams not exist.".format(checkpoints) assert os.path.exists(checkpoints + ".pdopt"), \ "Given dir {}.pdopt not exist.".format(checkpoints) para_dict = paddle.load(checkpoints + '.pdparams') opti_dict = paddle.load(checkpoints + '.pdopt') model.set_state_dict(para_dict) if optimizer is not None: optimizer.set_state_dict(opti_dict) if os.path.exists(checkpoints + '.states'): with open(checkpoints + '.states', 'rb') as f: states_dict = pickle.load(f) if six.PY2 else pickle.load( f, encoding='latin1') best_model_dict = states_dict.get('best_model_dict', {}) if 'epoch' in states_dict: best_model_dict['start_epoch'] = states_dict['epoch'] + 1 logger.info("resume from {}".format(checkpoints)) elif pretrained_model: load_static_weights = gloabl_config.get('load_static_weights', False) if not isinstance(pretrained_model, list): pretrained_model = [pretrained_model] if not isinstance(load_static_weights, list): load_static_weights = [load_static_weights] * len(pretrained_model) for idx, pretrained in enumerate(pretrained_model): load_static = load_static_weights[idx] load_dygraph_pretrain( model, logger, path=pretrained, load_static_weights=load_static) logger.info("load pretrained model from {}".format( pretrained_model)) else: logger.info('train from scratch') return best_model_dict def save_model(net, optimizer, model_path, logger, is_best=False, prefix='ppocr', **kwargs): _mkdir_if_not_exist(model_path, logger) model_prefix = os.path.join(model_path, prefix) paddle.save(net.state_dict(), model_prefix + '.pdparams') paddle.save(optimizer.state_dict(), model_prefix + '.pdopt') with open(model_prefix + '.states', 'wb') as f: pickle.dump(kwargs, f, protocol=2) if is_best: logger.info('save best model is to {}'.format(model_prefix)) else: logger.info("save model in {}".format(model_prefix))
true
true
f735fbfbdbb3d26fc668de600ffcb5cd87869617
6,314
py
Python
python/federatedml/linear_model/logistic_regression/homo_logistic_regression/homo_lr_base.py
QuantumA/FATE
89a3dd593252128c1bf86fb1014b25a629bdb31a
[ "Apache-2.0" ]
3,787
2019-08-30T04:55:10.000Z
2022-03-31T23:30:07.000Z
python/federatedml/linear_model/logistic_regression/homo_logistic_regression/homo_lr_base.py
JavaGreenHands/FATE
ea1e94b6be50c70c354d1861093187e523af32f2
[ "Apache-2.0" ]
1,439
2019-08-29T16:35:52.000Z
2022-03-31T11:55:31.000Z
python/federatedml/linear_model/logistic_regression/homo_logistic_regression/homo_lr_base.py
JavaGreenHands/FATE
ea1e94b6be50c70c354d1861093187e523af32f2
[ "Apache-2.0" ]
1,179
2019-08-29T16:18:32.000Z
2022-03-31T12:55:38.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 The FATE Authors. 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. import functools from federatedml.linear_model.linear_model_weight import LinearModelWeights from federatedml.linear_model.logistic_regression.base_logistic_regression import BaseLogisticRegression from federatedml.optim import activation from federatedml.optim.optimizer import optimizer_factory from federatedml.param.logistic_regression_param import HomoLogisticParam from federatedml.protobuf.generated import lr_model_meta_pb2 from federatedml.secureprotol import PaillierEncrypt, FakeEncrypt from federatedml.util.classify_label_checker import ClassifyLabelChecker from federatedml.util.homo_label_encoder import HomoLabelEncoderClient, HomoLabelEncoderArbiter from federatedml.statistic import data_overview from federatedml.transfer_variable.transfer_class.homo_lr_transfer_variable import HomoLRTransferVariable from federatedml.util import LOGGER from federatedml.util import consts from federatedml.util import fate_operator class HomoLRBase(BaseLogisticRegression): def __init__(self): super(HomoLRBase, self).__init__() self.model_name = 'HomoLogisticRegression' self.model_param_name = 'HomoLogisticRegressionParam' self.model_meta_name = 'HomoLogisticRegressionMeta' self.mode = consts.HOMO self.model_param = HomoLogisticParam() self.aggregator = None def _init_model(self, params): super(HomoLRBase, self)._init_model(params) self.re_encrypt_batches = params.re_encrypt_batches if params.encrypt_param.method == consts.PAILLIER: self.cipher_operator = PaillierEncrypt() else: self.cipher_operator = FakeEncrypt() self.transfer_variable = HomoLRTransferVariable() # self.aggregator.register_aggregator(self.transfer_variable) self.optimizer = optimizer_factory(params) self.aggregate_iters = params.aggregate_iters self.use_proximal = params.use_proximal self.mu = params.mu @property def use_loss(self): if self.model_param.early_stop == 'weight_diff': return False return True def _client_check_data(self, data_instances): self._abnormal_detection(data_instances) self.check_abnormal_values(data_instances) self.init_schema(data_instances) num_classes, classes_ = ClassifyLabelChecker.validate_label(data_instances) aligned_label, new_label_mapping = HomoLabelEncoderClient().label_alignment(classes_) if len(aligned_label) > 2: raise ValueError("Homo LR support binary classification only now") elif len(aligned_label) <= 1: raise ValueError("Number of classes should be equal to 2") def _server_check_data(self): HomoLabelEncoderArbiter().label_alignment() def classify(self, predict_wx, threshold): """ convert a probability table into a predicted class table. """ # predict_wx = self.compute_wx(data_instances, self.model_weights.coef_, self.model_weights.intercept_) def predict(x): prob = activation.sigmoid(x) pred_label = 1 if prob > threshold else 0 return prob, pred_label predict_table = predict_wx.mapValues(predict) return predict_table def _init_model_variables(self, data_instances): model_shape = data_overview.get_features_shape(data_instances) LOGGER.info("Initialized model shape is {}".format(model_shape)) w = self.initializer.init_model(model_shape, init_params=self.init_param_obj, data_instance=data_instances) model_weights = LinearModelWeights(w, fit_intercept=self.fit_intercept) return model_weights def _compute_loss(self, data_instances, prev_round_weights): f = functools.partial(self.gradient_operator.compute_loss, coef=self.model_weights.coef_, intercept=self.model_weights.intercept_) loss = data_instances.applyPartitions(f).reduce(fate_operator.reduce_add) if self.use_proximal: # use additional proximal term loss_norm = self.optimizer.loss_norm(self.model_weights, prev_round_weights) else: loss_norm = self.optimizer.loss_norm(self.model_weights) if loss_norm is not None: loss += loss_norm loss /= data_instances.count() self.callback_loss(self.n_iter_, loss) self.loss_history.append(loss) return loss def _get_meta(self): meta_protobuf_obj = lr_model_meta_pb2.LRModelMeta(penalty=self.model_param.penalty, tol=self.model_param.tol, alpha=self.alpha, optimizer=self.model_param.optimizer, batch_size=self.batch_size, learning_rate=self.model_param.learning_rate, max_iter=self.max_iter, early_stop=self.model_param.early_stop, fit_intercept=self.fit_intercept, re_encrypt_batches=self.re_encrypt_batches, need_one_vs_rest=self.need_one_vs_rest) return meta_protobuf_obj
45.1
111
0.660437
import functools from federatedml.linear_model.linear_model_weight import LinearModelWeights from federatedml.linear_model.logistic_regression.base_logistic_regression import BaseLogisticRegression from federatedml.optim import activation from federatedml.optim.optimizer import optimizer_factory from federatedml.param.logistic_regression_param import HomoLogisticParam from federatedml.protobuf.generated import lr_model_meta_pb2 from federatedml.secureprotol import PaillierEncrypt, FakeEncrypt from federatedml.util.classify_label_checker import ClassifyLabelChecker from federatedml.util.homo_label_encoder import HomoLabelEncoderClient, HomoLabelEncoderArbiter from federatedml.statistic import data_overview from federatedml.transfer_variable.transfer_class.homo_lr_transfer_variable import HomoLRTransferVariable from federatedml.util import LOGGER from federatedml.util import consts from federatedml.util import fate_operator class HomoLRBase(BaseLogisticRegression): def __init__(self): super(HomoLRBase, self).__init__() self.model_name = 'HomoLogisticRegression' self.model_param_name = 'HomoLogisticRegressionParam' self.model_meta_name = 'HomoLogisticRegressionMeta' self.mode = consts.HOMO self.model_param = HomoLogisticParam() self.aggregator = None def _init_model(self, params): super(HomoLRBase, self)._init_model(params) self.re_encrypt_batches = params.re_encrypt_batches if params.encrypt_param.method == consts.PAILLIER: self.cipher_operator = PaillierEncrypt() else: self.cipher_operator = FakeEncrypt() self.transfer_variable = HomoLRTransferVariable() self.optimizer = optimizer_factory(params) self.aggregate_iters = params.aggregate_iters self.use_proximal = params.use_proximal self.mu = params.mu @property def use_loss(self): if self.model_param.early_stop == 'weight_diff': return False return True def _client_check_data(self, data_instances): self._abnormal_detection(data_instances) self.check_abnormal_values(data_instances) self.init_schema(data_instances) num_classes, classes_ = ClassifyLabelChecker.validate_label(data_instances) aligned_label, new_label_mapping = HomoLabelEncoderClient().label_alignment(classes_) if len(aligned_label) > 2: raise ValueError("Homo LR support binary classification only now") elif len(aligned_label) <= 1: raise ValueError("Number of classes should be equal to 2") def _server_check_data(self): HomoLabelEncoderArbiter().label_alignment() def classify(self, predict_wx, threshold): def predict(x): prob = activation.sigmoid(x) pred_label = 1 if prob > threshold else 0 return prob, pred_label predict_table = predict_wx.mapValues(predict) return predict_table def _init_model_variables(self, data_instances): model_shape = data_overview.get_features_shape(data_instances) LOGGER.info("Initialized model shape is {}".format(model_shape)) w = self.initializer.init_model(model_shape, init_params=self.init_param_obj, data_instance=data_instances) model_weights = LinearModelWeights(w, fit_intercept=self.fit_intercept) return model_weights def _compute_loss(self, data_instances, prev_round_weights): f = functools.partial(self.gradient_operator.compute_loss, coef=self.model_weights.coef_, intercept=self.model_weights.intercept_) loss = data_instances.applyPartitions(f).reduce(fate_operator.reduce_add) if self.use_proximal: loss_norm = self.optimizer.loss_norm(self.model_weights, prev_round_weights) else: loss_norm = self.optimizer.loss_norm(self.model_weights) if loss_norm is not None: loss += loss_norm loss /= data_instances.count() self.callback_loss(self.n_iter_, loss) self.loss_history.append(loss) return loss def _get_meta(self): meta_protobuf_obj = lr_model_meta_pb2.LRModelMeta(penalty=self.model_param.penalty, tol=self.model_param.tol, alpha=self.alpha, optimizer=self.model_param.optimizer, batch_size=self.batch_size, learning_rate=self.model_param.learning_rate, max_iter=self.max_iter, early_stop=self.model_param.early_stop, fit_intercept=self.fit_intercept, re_encrypt_batches=self.re_encrypt_batches, need_one_vs_rest=self.need_one_vs_rest) return meta_protobuf_obj
true
true
f735fc09c6875e47f9827a68f0d28372cc8084db
7,598
py
Python
draw_card/genshin_handle.py
dialogueX/nonebot_plugin_gamedraw
60e969a43709eeb9a61d1a96b9f52b44ddb7dc73
[ "MIT" ]
1
2021-11-15T03:38:20.000Z
2021-11-15T03:38:20.000Z
draw_card/genshin_handle.py
dialogueX/nonebot_plugin_gamedraw
60e969a43709eeb9a61d1a96b9f52b44ddb7dc73
[ "MIT" ]
null
null
null
draw_card/genshin_handle.py
dialogueX/nonebot_plugin_gamedraw
60e969a43709eeb9a61d1a96b9f52b44ddb7dc73
[ "MIT" ]
null
null
null
import os from nonebot.adapters.cqhttp import MessageSegment, Message import nonebot import random from .update_game_info import update_info from .util import generate_img, init_star_rst, BaseData, set_list, get_star, init_up_char from .config import GENSHIN_FIVE_P, GENSHIN_FOUR_P, GENSHIN_G_FIVE_P, GENSHIN_G_FOUR_P, GENSHIN_THREE_P, I72_ADD, \ DRAW_PATH, GENSHIN_FLAG from dataclasses import dataclass from .init_card_pool import init_game_pool from .announcement import GenshinAnnouncement try: import ujson as json except ModuleNotFoundError: import json driver: nonebot.Driver = nonebot.get_driver() announcement = GenshinAnnouncement() genshin_five = {} genshin_count = {} genshin_pl_count = {} ALL_CHAR = [] ALL_ARMS = [] UP_CHAR = [] UP_ARMS = [] _CURRENT_CHAR_POOL_TITLE = '' _CURRENT_ARMS_POOL_TITLE = '' POOL_IMG = '' @dataclass class GenshinChar(BaseData): pass async def genshin_draw(user_id: int, count: int, pool_name: str): # 0 1 2 cnlist = ['★★★★★', '★★★★', '★★★'] char_list, five_list, five_index_list, char_dict, star_list = _format_card_information(count, user_id, pool_name) temp = '' title = '' up_type = [] up_list = [] if pool_name == 'char' and _CURRENT_CHAR_POOL_TITLE: up_type = UP_CHAR title = _CURRENT_CHAR_POOL_TITLE elif pool_name == 'arms' and _CURRENT_ARMS_POOL_TITLE: up_type = UP_ARMS title = _CURRENT_ARMS_POOL_TITLE tmp = '' if up_type: for x in up_type: for operator in x.operators: up_list.append(operator) if x.star == 5: tmp += f'五星UP:{" ".join(x.operators)} \n' elif x.star == 4: tmp += f'四星UP:{" ".join(x.operators)}' rst = init_star_rst(star_list, cnlist, five_list, five_index_list, up_list) pool_info = f'当前up池:{title}\n{tmp}' if title else '' if count > 90: char_list = set_list(char_list) return pool_info + '\n' + MessageSegment.image("base64://" + await generate_img(char_list, 'genshin', star_list)) + '\n' + rst[:-1] + \ temp[:-1] + f'\n距离保底发还剩 {90 - genshin_count[user_id] if genshin_count.get(user_id) else "^"} 抽' \ + "\n【五星:0.6%,四星:5.1%\n第72抽开始五星概率每抽加0.585%】" async def update_genshin_info(): global ALL_CHAR, ALL_ARMS url = 'https://wiki.biligame.com/ys/角色筛选' data, code = await update_info(url, 'genshin') if code == 200: ALL_CHAR = init_game_pool('genshin', data, GenshinChar) url = 'https://wiki.biligame.com/ys/武器图鉴' data, code = await update_info(url, 'genshin_arms', ['头像', '名称', '类型', '稀有度.alt', '获取途径', '初始基础属性1', '初始基础属性2', '攻击力(MAX)', '副属性(MAX)', '技能']) if code == 200: ALL_ARMS = init_game_pool('genshin_arms', data, GenshinChar) await _genshin_init_up_char() async def init_genshin_data(): global ALL_CHAR, ALL_ARMS if GENSHIN_FLAG: if not os.path.exists(DRAW_PATH + 'genshin.json') or not os.path.exists(DRAW_PATH + 'genshin_arms.json'): await update_genshin_info() else: with open(DRAW_PATH + 'genshin.json', 'r', encoding='utf8') as f: genshin_dict = json.load(f) with open(DRAW_PATH + 'genshin_arms.json', 'r', encoding='utf8') as f: genshin_ARMS_dict = json.load(f) ALL_CHAR = init_game_pool('genshin', genshin_dict, GenshinChar) ALL_ARMS = init_game_pool('genshin_arms', genshin_ARMS_dict, GenshinChar) await _genshin_init_up_char() # 抽取卡池 def _get_genshin_card(mode: int = 1, pool_name: str = '', add: float = 0.0): global ALL_ARMS, ALL_CHAR, UP_ARMS, UP_CHAR, _CURRENT_ARMS_POOL_TITLE, _CURRENT_CHAR_POOL_TITLE if mode == 1: star = get_star([5, 4, 3], [GENSHIN_FIVE_P + add, GENSHIN_FOUR_P, GENSHIN_THREE_P]) elif mode == 2: star = get_star([5, 4], [GENSHIN_G_FIVE_P + add, GENSHIN_G_FOUR_P]) else: star = 5 if pool_name == 'char': data_lst = UP_CHAR flag = _CURRENT_CHAR_POOL_TITLE itype_all_lst = ALL_CHAR + [x for x in ALL_ARMS if x.star == star and x.star < 5] elif pool_name == 'arms': data_lst = UP_ARMS flag = _CURRENT_ARMS_POOL_TITLE itype_all_lst = ALL_ARMS + [x for x in ALL_CHAR if x.star == star and x.star < 5] else: data_lst = '' flag = '' itype_all_lst = '' all_lst = ALL_ARMS + ALL_CHAR # 是否UP if flag and star > 3 and pool_name: # 获取up角色列表 up_char_lst = [x.operators for x in data_lst if x.star == star][0] # 成功获取up角色 if random.random() < 0.5: up_char_name = random.choice(up_char_lst) acquire_char = [x for x in all_lst if x.name == up_char_name][0] else: # 无up all_char_lst = [x for x in itype_all_lst if x.star == star and x.name not in up_char_lst and not x.limited] acquire_char = random.choice(all_char_lst) else: chars = [x for x in all_lst if x.star == star and not x.limited] acquire_char = random.choice(chars) return acquire_char, 5 - star def _format_card_information(_count: int, user_id, pool_name): char_list = [] star_list = [0, 0, 0] five_index_list = [] five_list = [] five_dict = {} add = 0.0 if genshin_count.get(user_id) and _count <= 90: f_count = genshin_count[user_id] else: f_count = 0 if genshin_pl_count.get(user_id) and _count <= 90: count = genshin_pl_count[user_id] else: count = 0 for i in range(_count): count += 1 f_count += 1 # 十连保底 if count == 10 and f_count != 90: if f_count >= 72: add += I72_ADD char, code = _get_genshin_card(2, pool_name, add=add) count = 0 # 大保底 elif f_count == 90: char, code = _get_genshin_card(3, pool_name) else: if f_count >= 72: add += I72_ADD char, code = _get_genshin_card(pool_name=pool_name, add=add) if code == 1: count = 0 star_list[code] += 1 if code == 0: if _count <= 90: genshin_five[user_id] = f_count add = 0.0 f_count = 0 five_list.append(char.name) five_index_list.append(i) try: five_dict[char.name] += 1 except KeyError: five_dict[char.name] = 1 char_list.append(char) if _count <= 90: genshin_count[user_id] = f_count genshin_pl_count[user_id] = count return char_list, five_list, five_index_list, five_dict, star_list def reset_count(user_id: int): genshin_count[user_id] = 0 genshin_pl_count[user_id] = 0 # 获取up和概率 async def _genshin_init_up_char(): global _CURRENT_CHAR_POOL_TITLE, _CURRENT_ARMS_POOL_TITLE, UP_CHAR, UP_ARMS, POOL_IMG _CURRENT_CHAR_POOL_TITLE, _CURRENT_ARMS_POOL_TITLE, POOL_IMG, UP_CHAR, UP_ARMS = await init_up_char(announcement) async def reload_genshin_pool(): await _genshin_init_up_char() return Message(f'当前UP池子:{_CURRENT_CHAR_POOL_TITLE} & {_CURRENT_ARMS_POOL_TITLE} {POOL_IMG}')
35.504673
140
0.595815
import os from nonebot.adapters.cqhttp import MessageSegment, Message import nonebot import random from .update_game_info import update_info from .util import generate_img, init_star_rst, BaseData, set_list, get_star, init_up_char from .config import GENSHIN_FIVE_P, GENSHIN_FOUR_P, GENSHIN_G_FIVE_P, GENSHIN_G_FOUR_P, GENSHIN_THREE_P, I72_ADD, \ DRAW_PATH, GENSHIN_FLAG from dataclasses import dataclass from .init_card_pool import init_game_pool from .announcement import GenshinAnnouncement try: import ujson as json except ModuleNotFoundError: import json driver: nonebot.Driver = nonebot.get_driver() announcement = GenshinAnnouncement() genshin_five = {} genshin_count = {} genshin_pl_count = {} ALL_CHAR = [] ALL_ARMS = [] UP_CHAR = [] UP_ARMS = [] _CURRENT_CHAR_POOL_TITLE = '' _CURRENT_ARMS_POOL_TITLE = '' POOL_IMG = '' @dataclass class GenshinChar(BaseData): pass async def genshin_draw(user_id: int, count: int, pool_name: str): cnlist = ['★★★★★', '★★★★', '★★★'] char_list, five_list, five_index_list, char_dict, star_list = _format_card_information(count, user_id, pool_name) temp = '' title = '' up_type = [] up_list = [] if pool_name == 'char' and _CURRENT_CHAR_POOL_TITLE: up_type = UP_CHAR title = _CURRENT_CHAR_POOL_TITLE elif pool_name == 'arms' and _CURRENT_ARMS_POOL_TITLE: up_type = UP_ARMS title = _CURRENT_ARMS_POOL_TITLE tmp = '' if up_type: for x in up_type: for operator in x.operators: up_list.append(operator) if x.star == 5: tmp += f'五星UP:{" ".join(x.operators)} \n' elif x.star == 4: tmp += f'四星UP:{" ".join(x.operators)}' rst = init_star_rst(star_list, cnlist, five_list, five_index_list, up_list) pool_info = f'当前up池:{title}\n{tmp}' if title else '' if count > 90: char_list = set_list(char_list) return pool_info + '\n' + MessageSegment.image("base64://" + await generate_img(char_list, 'genshin', star_list)) + '\n' + rst[:-1] + \ temp[:-1] + f'\n距离保底发还剩 {90 - genshin_count[user_id] if genshin_count.get(user_id) else "^"} 抽' \ + "\n【五星:0.6%,四星:5.1%\n第72抽开始五星概率每抽加0.585%】" async def update_genshin_info(): global ALL_CHAR, ALL_ARMS url = 'https://wiki.biligame.com/ys/角色筛选' data, code = await update_info(url, 'genshin') if code == 200: ALL_CHAR = init_game_pool('genshin', data, GenshinChar) url = 'https://wiki.biligame.com/ys/武器图鉴' data, code = await update_info(url, 'genshin_arms', ['头像', '名称', '类型', '稀有度.alt', '获取途径', '初始基础属性1', '初始基础属性2', '攻击力(MAX)', '副属性(MAX)', '技能']) if code == 200: ALL_ARMS = init_game_pool('genshin_arms', data, GenshinChar) await _genshin_init_up_char() async def init_genshin_data(): global ALL_CHAR, ALL_ARMS if GENSHIN_FLAG: if not os.path.exists(DRAW_PATH + 'genshin.json') or not os.path.exists(DRAW_PATH + 'genshin_arms.json'): await update_genshin_info() else: with open(DRAW_PATH + 'genshin.json', 'r', encoding='utf8') as f: genshin_dict = json.load(f) with open(DRAW_PATH + 'genshin_arms.json', 'r', encoding='utf8') as f: genshin_ARMS_dict = json.load(f) ALL_CHAR = init_game_pool('genshin', genshin_dict, GenshinChar) ALL_ARMS = init_game_pool('genshin_arms', genshin_ARMS_dict, GenshinChar) await _genshin_init_up_char() def _get_genshin_card(mode: int = 1, pool_name: str = '', add: float = 0.0): global ALL_ARMS, ALL_CHAR, UP_ARMS, UP_CHAR, _CURRENT_ARMS_POOL_TITLE, _CURRENT_CHAR_POOL_TITLE if mode == 1: star = get_star([5, 4, 3], [GENSHIN_FIVE_P + add, GENSHIN_FOUR_P, GENSHIN_THREE_P]) elif mode == 2: star = get_star([5, 4], [GENSHIN_G_FIVE_P + add, GENSHIN_G_FOUR_P]) else: star = 5 if pool_name == 'char': data_lst = UP_CHAR flag = _CURRENT_CHAR_POOL_TITLE itype_all_lst = ALL_CHAR + [x for x in ALL_ARMS if x.star == star and x.star < 5] elif pool_name == 'arms': data_lst = UP_ARMS flag = _CURRENT_ARMS_POOL_TITLE itype_all_lst = ALL_ARMS + [x for x in ALL_CHAR if x.star == star and x.star < 5] else: data_lst = '' flag = '' itype_all_lst = '' all_lst = ALL_ARMS + ALL_CHAR if flag and star > 3 and pool_name: up_char_lst = [x.operators for x in data_lst if x.star == star][0] if random.random() < 0.5: up_char_name = random.choice(up_char_lst) acquire_char = [x for x in all_lst if x.name == up_char_name][0] else: all_char_lst = [x for x in itype_all_lst if x.star == star and x.name not in up_char_lst and not x.limited] acquire_char = random.choice(all_char_lst) else: chars = [x for x in all_lst if x.star == star and not x.limited] acquire_char = random.choice(chars) return acquire_char, 5 - star def _format_card_information(_count: int, user_id, pool_name): char_list = [] star_list = [0, 0, 0] five_index_list = [] five_list = [] five_dict = {} add = 0.0 if genshin_count.get(user_id) and _count <= 90: f_count = genshin_count[user_id] else: f_count = 0 if genshin_pl_count.get(user_id) and _count <= 90: count = genshin_pl_count[user_id] else: count = 0 for i in range(_count): count += 1 f_count += 1 if count == 10 and f_count != 90: if f_count >= 72: add += I72_ADD char, code = _get_genshin_card(2, pool_name, add=add) count = 0 elif f_count == 90: char, code = _get_genshin_card(3, pool_name) else: if f_count >= 72: add += I72_ADD char, code = _get_genshin_card(pool_name=pool_name, add=add) if code == 1: count = 0 star_list[code] += 1 if code == 0: if _count <= 90: genshin_five[user_id] = f_count add = 0.0 f_count = 0 five_list.append(char.name) five_index_list.append(i) try: five_dict[char.name] += 1 except KeyError: five_dict[char.name] = 1 char_list.append(char) if _count <= 90: genshin_count[user_id] = f_count genshin_pl_count[user_id] = count return char_list, five_list, five_index_list, five_dict, star_list def reset_count(user_id: int): genshin_count[user_id] = 0 genshin_pl_count[user_id] = 0 async def _genshin_init_up_char(): global _CURRENT_CHAR_POOL_TITLE, _CURRENT_ARMS_POOL_TITLE, UP_CHAR, UP_ARMS, POOL_IMG _CURRENT_CHAR_POOL_TITLE, _CURRENT_ARMS_POOL_TITLE, POOL_IMG, UP_CHAR, UP_ARMS = await init_up_char(announcement) async def reload_genshin_pool(): await _genshin_init_up_char() return Message(f'当前UP池子:{_CURRENT_CHAR_POOL_TITLE} & {_CURRENT_ARMS_POOL_TITLE} {POOL_IMG}')
true
true
f735fc72e40be41a0923043ba0a95bbe6b54bb26
4,541
py
Python
engine/api/gcp/tasks/system_notify.py
torrotitans/torro_community
a3f153e69a860f0d6c831145f529d9e92193a0ae
[ "MIT" ]
1
2022-01-12T08:31:59.000Z
2022-01-12T08:31:59.000Z
engine/api/gcp/tasks/system_notify.py
torrotitans/torro_community
a3f153e69a860f0d6c831145f529d9e92193a0ae
[ "MIT" ]
null
null
null
engine/api/gcp/tasks/system_notify.py
torrotitans/torro_community
a3f153e69a860f0d6c831145f529d9e92193a0ae
[ "MIT" ]
2
2022-01-19T06:26:32.000Z
2022-01-26T15:25:15.000Z
from api.gcp.tasks.baseTask import baseTask from utils.ldap_helper import Ldap from db.connection_pool import MysqlConn from config import configuration import datetime import traceback import logging from googleapiclient.errors import HttpError from utils.status_code import response_code import json logger = logging.getLogger("main.api.gcp.tasks" + __name__) class system_notify(baseTask): api_type = 'system' api_name = 'system_notify' arguments = { "groups": {"type": str, "default": ''}, "emails": {"type": str, "default": ''}, 'notify_msg': {"type": str, "default": ''}} def __init__(self, stage_dict): super(system_notify, self).__init__(stage_dict) def execute(self, workspace_id=None, form_id=None, input_form_id=None, user_id=None): missing_set = set() for key in self.arguments: check_key = self.stage_dict.get(key, 'NotFound') if check_key == 'NotFound': missing_set.add(key) # logger.debug('FN:system_notify.execute key:{} stage_dict:{}'.format(key, self.stage_dict[key])) if len(missing_set) != 0: data = response_code.BAD_REQUEST data['msg'] = 'Missing parameters: {}'.format(', '.join(missing_set)) return data else: conn = MysqlConn() try: db_name = configuration.get_database_name() # get history id table_name = 'inputFormTable' condition = "id='%s' order by history_id desc" % (input_form_id) fields = '*' sql = self.create_select_sql(db_name, table_name, fields, condition) input_form_infos = self.execute_fetch_all(conn, sql) if not input_form_infos: data = response_code.BAD_REQUEST data['msg'] = 'input form not found: {}'.format(str(input_form_id)) return data # get history id history_id = input_form_infos[0]['history_id'] notify_msg = str(self.stage_dict['notify_msg']) create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # get requestor email emails = self.stage_dict['emails'] # logger.debug('FN:system_notify.execute stage_dict:{}'.format(self.stage_dict)) if not isinstance(emails, list): emails = emails.split(',') groups = self.stage_dict['groups'] if not isinstance(groups, list): groups = groups.split(',') # logger.debug('FN:system_notify.execute groups:{}'.format(groups)) for group in groups: mail_list, _ = Ldap.get_ad_group_member(group) # logger.debug('FN:system_notify.execute mail_list:{}'.format(mail_list)) if mail_list: emails.extend(mail_list) # logger.debug('FN:system_notify.execute emails:{}'.format(emails)) notify_id_list = [] for email in emails: values = (email, input_form_id, history_id, notify_msg, 0, create_time) fields = ('account_id', 'input_form_id', 'history_id', 'comment', 'is_read', 'create_time') sql = self.create_insert_sql(db_name, 'inputNotifyTable', '({})'.format(', '.join(fields)), values) notify_id = self.insert_exec(conn, sql, return_insert_id=True) notify_id_list.append(str(notify_id)) # logger.debug('FN:system_notify.execute notify_id_list:{}'.format(notify_id_list)) data = response_code.SUCCESS data['data'] = 'create notify successfully: length{}'.format(str(len(notify_id_list))) return data except HttpError as e: error_json = json.loads(e.content, strict=False) data = error_json['error'] data["msg"] = data.pop("message") logger.error("FN:system_notify_execute error:{}".format(traceback.format_exc())) return data except Exception as e: logger.error("FN:system_notify_execute error:{}".format(traceback.format_exc())) data = response_code.BAD_REQUEST data['msg'] = str(e) return data finally: conn.close()
46.814433
119
0.568377
from api.gcp.tasks.baseTask import baseTask from utils.ldap_helper import Ldap from db.connection_pool import MysqlConn from config import configuration import datetime import traceback import logging from googleapiclient.errors import HttpError from utils.status_code import response_code import json logger = logging.getLogger("main.api.gcp.tasks" + __name__) class system_notify(baseTask): api_type = 'system' api_name = 'system_notify' arguments = { "groups": {"type": str, "default": ''}, "emails": {"type": str, "default": ''}, 'notify_msg': {"type": str, "default": ''}} def __init__(self, stage_dict): super(system_notify, self).__init__(stage_dict) def execute(self, workspace_id=None, form_id=None, input_form_id=None, user_id=None): missing_set = set() for key in self.arguments: check_key = self.stage_dict.get(key, 'NotFound') if check_key == 'NotFound': missing_set.add(key) if len(missing_set) != 0: data = response_code.BAD_REQUEST data['msg'] = 'Missing parameters: {}'.format(', '.join(missing_set)) return data else: conn = MysqlConn() try: db_name = configuration.get_database_name() table_name = 'inputFormTable' condition = "id='%s' order by history_id desc" % (input_form_id) fields = '*' sql = self.create_select_sql(db_name, table_name, fields, condition) input_form_infos = self.execute_fetch_all(conn, sql) if not input_form_infos: data = response_code.BAD_REQUEST data['msg'] = 'input form not found: {}'.format(str(input_form_id)) return data history_id = input_form_infos[0]['history_id'] notify_msg = str(self.stage_dict['notify_msg']) create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") emails = self.stage_dict['emails'] if not isinstance(emails, list): emails = emails.split(',') groups = self.stage_dict['groups'] if not isinstance(groups, list): groups = groups.split(',') for group in groups: mail_list, _ = Ldap.get_ad_group_member(group) if mail_list: emails.extend(mail_list) notify_id_list = [] for email in emails: values = (email, input_form_id, history_id, notify_msg, 0, create_time) fields = ('account_id', 'input_form_id', 'history_id', 'comment', 'is_read', 'create_time') sql = self.create_insert_sql(db_name, 'inputNotifyTable', '({})'.format(', '.join(fields)), values) notify_id = self.insert_exec(conn, sql, return_insert_id=True) notify_id_list.append(str(notify_id)) data = response_code.SUCCESS data['data'] = 'create notify successfully: length{}'.format(str(len(notify_id_list))) return data except HttpError as e: error_json = json.loads(e.content, strict=False) data = error_json['error'] data["msg"] = data.pop("message") logger.error("FN:system_notify_execute error:{}".format(traceback.format_exc())) return data except Exception as e: logger.error("FN:system_notify_execute error:{}".format(traceback.format_exc())) data = response_code.BAD_REQUEST data['msg'] = str(e) return data finally: conn.close()
true
true
f735fffb7f5c66d98450e2d3ee3182ffd0ad3c39
8,258
py
Python
Bkjwer/modules/bkjwer.py
quartz010/Bkjwer
7ba02eeae60ff508ef97aae4108c35d541dbbb7a
[ "MIT" ]
1
2020-07-03T01:13:39.000Z
2020-07-03T01:13:39.000Z
Bkjwer/modules/bkjwer.py
r4ym0n/Bkjwer
7ba02eeae60ff508ef97aae4108c35d541dbbb7a
[ "MIT" ]
null
null
null
Bkjwer/modules/bkjwer.py
r4ym0n/Bkjwer
7ba02eeae60ff508ef97aae4108c35d541dbbb7a
[ "MIT" ]
null
null
null
import requests import threading from bs4 import BeautifulSoup import re TIMEOUT = 3 ATTEMPT = 5 class Bkjw: """ 这个是Bkjw的类负责底层操作 """ def __init__(self): self.root_url = "http://172.16.64.236/" self.session = requests.session() self.std_info: Dict[str, str] = dict() self.islogedin = False self.net_congestion = False self.NET_STATUES = False self.net_quality = 0 self.attempt = ATTEMPT net_qu = self.__net_test__() if net_qu > 0: # 检测是否网络可达 self.NET_STATUES = True if net_qu < ATTEMPT - 1: self.net_congestion = True else: raise Network.connection("Network Unreachable!") # 要提交的键值对的一个结构 keywords = {"username": "", "passwd": "", 'login': '%B5%C7%A1%A1%C2%BC'} # term = {"term": "2017-2018_1"} # 表单要提交到的子地址 sub_url_tab = { "url_login": "student/public/login.asp", "url_info": "student/Info.asp", "url_logout": "student/public/logout.asp", "url_courses": "student/Selected.asp", "url_elva": "student/teachinpj.asp", } def login(self, keywords): """ 登陆方法 :param keywords: 账号密码键值 :return: BOOL 是否成功 """ if self.NET_STATUES is False: return False def http_req(): # 以post的方式提交表单并保存结果在变量res中 return self.session.post(self.root_url + self.sub_url_tab["url_login"], data=keywords, json=None, timeout=TIMEOUT) try: # 是否网络拥塞 if self.net_congestion is True: self.__multi_th__(http_req) else: res = http_req() # 这里对超时进行异常处理 except requests.exceptions.ConnectTimeout: self.islogedin = False print('[-] Connect Timeout!') return False res = self.session.get(self.root_url + self.sub_url_tab["url_info"]) # 验证是否成功登陆 if res.text.find(keywords["username"]) > 0: print('[+] Logged in') # print(self.session.cookies) self.islogedin = True return True else: print("[-] Login Error!") return False def logout(self): """ 登出方法 :return: None """ if not self.islogedin: return self.session.get(self.root_url + self.sub_url_tab["url_logout"]) self.session.close() def get_info(self): """ 获取信息列表 :return: set """ # 如果没有登陆就返回 if not self.islogedin: return def http_req(): return self.session.get(self.root_url + self.sub_url_tab["url_info"]) res = str() # 是否网络拥塞 if self.net_congestion is True: self.__multi_th__(http_req) else: res = http_req() info_list = BeautifulSoup(res.content, 'html.parser').find_all('p') #从冒号开始分隔数据 self.std_info['name'] = info_list[1].string.split(':')[1] self.std_info['class'] = info_list[2].string.split(':')[1] self.std_info['grade'] = info_list[3].string.split(':')[1] self.std_info['term'] = info_list[4].string.split(':')[1] return info_list def get_courses(self, term): """ :param term:当前学期 :return:已选课程SET """ if not self.islogedin: return # 建立正则表达式 check_regex = re.compile("\d+-\d+_[12]") if check_regex.match(term) is None: # raise 如 throw 抛个异常, 类型自己指定 如 ValueError raise ValueError('[-] 学期格式不正确,正确的示例:2017-2018_1,意为2017年到2018年上学期') # payload: Dict[str, str] = dict() # payload["term"] = term payload = {'term': term} res = self.session.post(self.root_url + self.sub_url_tab["url_courses"], data=payload) # print(res.text) # 这里是findall 之前写了find 只找了一个 raw_tab = BeautifulSoup(res.content, 'html.parser').find_all('tr') th = raw_tab[0] # 第一个就是表头 data = raw_tab[1:-1] # 后面的就是数据了 -1 是索引的最后一个 selected_lesson_headers = list() selected_lesson_data = list() selected_lesson_table = list() # get headers, and delete redundant characters from them. # 再次把标签分离并且替换\xa0 和 \u3000 两种空格符 for h in th.find_all('th'): selected_lesson_headers.append(h.string.replace('\u3000', '').replace('\xa0', '')) selected_lesson_table.append(selected_lesson_headers) tmp_data = list() for d in data: tmp_data.clear() for col in d.find_all("td"): tmp_data.append(col.string.encode().decode()) selected_lesson_data.append(tmp_data.copy()) selected_lesson_table.append(tmp_data.copy()) return selected_lesson_headers, selected_lesson_data, selected_lesson_table @staticmethod def list_out(info_set): """ 这里用于列出爬到的set """ if info_set is not None: for d in info_set: print(d) else: print('[-] None Type !') def elva_teaching(self): """ 一键强制评教的实现 """ print("[*] Wait a while...") header, data, tab = self.get_courses(self.std_info["term"]) cno = list() cid = list() for d in data: cno.append(d[0]) # cno 课程序号 cid.append(d[1]) # cid 课程代码 # for course in course_list: # payload[] = course.cid # payload[] = course.cno # 默认全部好评的表单数据(五星好评!!!) payload = "score1027=100&id=1027&qz=.02&score1028=100&id=1028&qz=.03&score1029=100&id=1029&" \ "qz=.12&score1030=100&id=1030&qz=.15&score1031=100&id=1031&qz=.15&score1032=100&id=1032" \ "&qz=.15&score1033=100&id=1033&qz=.05&score1034=100&id=1034&qz=.1&score1035=100&id=1035" \ "&qz=.05&score1036=100&id=1036&qz=.15&score1037=100&id=1037&qz=.02&score1038=100&id=1038" \ "&qz=.01&py=&pjlb=2&gx=i&tno=6357++++++++&lwBtntijiao=%CC%E1%BD%BB&" # 设置内容类型 重要 self.session.headers["Content-Type"] = "application/x-www-form-urlencoded" # 遍历已选课程评教 cont = 0 for i in range(len(cno)): res = self.session.post(self.root_url + self.sub_url_tab["url_elva"], data=(payload + "cno=%s&term=%s&cid=%s" % (cno[i], self.std_info['term'], cid[i]))) page = BeautifulSoup(res.content, 'html.parser') if page.text.find("已提交") > 0: print("[*] OK") cont += 1 if cont != 0: print("[*] All Done!") else: print("[!] No Courses to elva") self.session.headers.clear() def __net_test__(self): """ 建立多个线程发生请求,根据其正常返回数量,判断网络质量(服务器状态) 从而后面使用繁忙模式 :return: 质量等级 """ def conn_try(self): # print('the curent threading %s is running' % threading.current_thread().getName()) try: res = requests.get(self.root_url, timeout=TIMEOUT) except Exception: # print("error") return # 根据返回值判断 if res.status_code == 200: self.net_quality += 1 # print('the curent threading %s is ended' % threading.current_thread().name) th_list = list() for i in range(ATTEMPT): # 连接尝试线程 t = threading.Thread(target=conn_try(self)) t.setDaemon(True) t.start() th_list.append(t) for th in th_list: th.join() return self.net_quality @staticmethod def __multi_th__(func): """ 在网络拥塞时候用于执行多线程的请求 :param func: 请求函数 :return: """ th_list = list() res = str() for i in range(ATTEMPT): t = threading.Thread(target=func) # 连接尝试线程 t.setDaemon(True) t.start() th_list.append(t) for th in th_list: res = th.join() return res
30.360294
119
0.530274
import requests import threading from bs4 import BeautifulSoup import re TIMEOUT = 3 ATTEMPT = 5 class Bkjw: def __init__(self): self.root_url = "http://172.16.64.236/" self.session = requests.session() self.std_info: Dict[str, str] = dict() self.islogedin = False self.net_congestion = False self.NET_STATUES = False self.net_quality = 0 self.attempt = ATTEMPT net_qu = self.__net_test__() if net_qu > 0: self.NET_STATUES = True if net_qu < ATTEMPT - 1: self.net_congestion = True else: raise Network.connection("Network Unreachable!") keywords = {"username": "", "passwd": "", 'login': '%B5%C7%A1%A1%C2%BC'} sub_url_tab = { "url_login": "student/public/login.asp", "url_info": "student/Info.asp", "url_logout": "student/public/logout.asp", "url_courses": "student/Selected.asp", "url_elva": "student/teachinpj.asp", } def login(self, keywords): if self.NET_STATUES is False: return False def http_req(): return self.session.post(self.root_url + self.sub_url_tab["url_login"], data=keywords, json=None, timeout=TIMEOUT) try: if self.net_congestion is True: self.__multi_th__(http_req) else: res = http_req() except requests.exceptions.ConnectTimeout: self.islogedin = False print('[-] Connect Timeout!') return False res = self.session.get(self.root_url + self.sub_url_tab["url_info"]) if res.text.find(keywords["username"]) > 0: print('[+] Logged in') self.islogedin = True return True else: print("[-] Login Error!") return False def logout(self): if not self.islogedin: return self.session.get(self.root_url + self.sub_url_tab["url_logout"]) self.session.close() def get_info(self): if not self.islogedin: return def http_req(): return self.session.get(self.root_url + self.sub_url_tab["url_info"]) res = str() if self.net_congestion is True: self.__multi_th__(http_req) else: res = http_req() info_list = BeautifulSoup(res.content, 'html.parser').find_all('p') self.std_info['name'] = info_list[1].string.split(':')[1] self.std_info['class'] = info_list[2].string.split(':')[1] self.std_info['grade'] = info_list[3].string.split(':')[1] self.std_info['term'] = info_list[4].string.split(':')[1] return info_list def get_courses(self, term): if not self.islogedin: return check_regex = re.compile("\d+-\d+_[12]") if check_regex.match(term) is None: raise ValueError('[-] 学期格式不正确,正确的示例:2017-2018_1,意为2017年到2018年上学期') payload = {'term': term} res = self.session.post(self.root_url + self.sub_url_tab["url_courses"], data=payload) raw_tab = BeautifulSoup(res.content, 'html.parser').find_all('tr') th = raw_tab[0] data = raw_tab[1:-1] selected_lesson_headers = list() selected_lesson_data = list() selected_lesson_table = list() for h in th.find_all('th'): selected_lesson_headers.append(h.string.replace('\u3000', '').replace('\xa0', '')) selected_lesson_table.append(selected_lesson_headers) tmp_data = list() for d in data: tmp_data.clear() for col in d.find_all("td"): tmp_data.append(col.string.encode().decode()) selected_lesson_data.append(tmp_data.copy()) selected_lesson_table.append(tmp_data.copy()) return selected_lesson_headers, selected_lesson_data, selected_lesson_table @staticmethod def list_out(info_set): if info_set is not None: for d in info_set: print(d) else: print('[-] None Type !') def elva_teaching(self): print("[*] Wait a while...") header, data, tab = self.get_courses(self.std_info["term"]) cno = list() cid = list() for d in data: cno.append(d[0]) cid.append(d[1]) payload = "score1027=100&id=1027&qz=.02&score1028=100&id=1028&qz=.03&score1029=100&id=1029&" \ "qz=.12&score1030=100&id=1030&qz=.15&score1031=100&id=1031&qz=.15&score1032=100&id=1032" \ "&qz=.15&score1033=100&id=1033&qz=.05&score1034=100&id=1034&qz=.1&score1035=100&id=1035" \ "&qz=.05&score1036=100&id=1036&qz=.15&score1037=100&id=1037&qz=.02&score1038=100&id=1038" \ "&qz=.01&py=&pjlb=2&gx=i&tno=6357++++++++&lwBtntijiao=%CC%E1%BD%BB&" self.session.headers["Content-Type"] = "application/x-www-form-urlencoded" cont = 0 for i in range(len(cno)): res = self.session.post(self.root_url + self.sub_url_tab["url_elva"], data=(payload + "cno=%s&term=%s&cid=%s" % (cno[i], self.std_info['term'], cid[i]))) page = BeautifulSoup(res.content, 'html.parser') if page.text.find("已提交") > 0: print("[*] OK") cont += 1 if cont != 0: print("[*] All Done!") else: print("[!] No Courses to elva") self.session.headers.clear() def __net_test__(self): def conn_try(self): try: res = requests.get(self.root_url, timeout=TIMEOUT) except Exception: return if res.status_code == 200: self.net_quality += 1 th_list = list() for i in range(ATTEMPT): t = threading.Thread(target=conn_try(self)) t.setDaemon(True) t.start() th_list.append(t) for th in th_list: th.join() return self.net_quality @staticmethod def __multi_th__(func): th_list = list() res = str() for i in range(ATTEMPT): t = threading.Thread(target=func) t.setDaemon(True) t.start() th_list.append(t) for th in th_list: res = th.join() return res
true
true
f7360083f0e3a23374759cd4d02dd9eb724dd41f
425
py
Python
plotly/validators/scatterternary/_fillcolor.py
faezs/plotly.py
6009b5b9c746e5d2a2849ad255a4eb234b551ed7
[ "MIT" ]
2
2020-03-24T11:41:14.000Z
2021-01-14T07:59:43.000Z
plotly/validators/scatterternary/_fillcolor.py
faezs/plotly.py
6009b5b9c746e5d2a2849ad255a4eb234b551ed7
[ "MIT" ]
null
null
null
plotly/validators/scatterternary/_fillcolor.py
faezs/plotly.py
6009b5b9c746e5d2a2849ad255a4eb234b551ed7
[ "MIT" ]
4
2019-06-03T14:49:12.000Z
2022-01-06T01:05:12.000Z
import _plotly_utils.basevalidators class FillcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name='fillcolor', parent_name='scatterternary', **kwargs ): super(FillcolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type='style', role='style', **kwargs )
26.5625
77
0.637647
import _plotly_utils.basevalidators class FillcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name='fillcolor', parent_name='scatterternary', **kwargs ): super(FillcolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type='style', role='style', **kwargs )
true
true
f736013fa0db1433a9313e48251e3d7097d94f63
302
py
Python
huxley/settings/__init__.py
jmosky12/huxley
0a60cc4ac02969ee4d5f2c55bc090575fa2bbe9d
[ "BSD-3-Clause" ]
null
null
null
huxley/settings/__init__.py
jmosky12/huxley
0a60cc4ac02969ee4d5f2c55bc090575fa2bbe9d
[ "BSD-3-Clause" ]
null
null
null
huxley/settings/__init__.py
jmosky12/huxley
0a60cc4ac02969ee4d5f2c55bc090575fa2bbe9d
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). from .conference import * from .main import * from .logging import * from .pipeline import * try: from .local import * except ImportError: pass
23.230769
77
0.731788
from .conference import * from .main import * from .logging import * from .pipeline import * try: from .local import * except ImportError: pass
true
true
f736014e683b4c18936492975b531d7d84452019
8,495
py
Python
docarray/array/mixins/io/from_gen.py
fastflair/docarray
0bbdbc816b2f4a3b399779f6816875fbc1dfe862
[ "Apache-2.0" ]
1
2022-03-16T14:05:32.000Z
2022-03-16T14:05:32.000Z
docarray/array/mixins/io/from_gen.py
fastflair/docarray
0bbdbc816b2f4a3b399779f6816875fbc1dfe862
[ "Apache-2.0" ]
null
null
null
docarray/array/mixins/io/from_gen.py
fastflair/docarray
0bbdbc816b2f4a3b399779f6816875fbc1dfe862
[ "Apache-2.0" ]
null
null
null
from typing import ( Type, TYPE_CHECKING, Optional, overload, Union, List, TextIO, Dict, Iterable, ) if TYPE_CHECKING: from ....types import T import numpy as np import csv class FromGeneratorMixin: """Provide helper functions filling a :class:`DocumentArray`-like object with a generator.""" @classmethod def _from_generator(cls: Type['T'], meth: str, *args, **kwargs) -> 'T': from ....document import generators from_fn = getattr(generators, meth) da_like = cls(**kwargs) da_like.extend(from_fn(*args, **kwargs)) return da_like @classmethod @overload def from_ndarray( cls: Type['T'], array: 'np.ndarray', axis: int = 0, size: Optional[int] = None, shuffle: bool = False, *args, **kwargs, ) -> 'T': """Build from a numpy array. :param array: the numpy ndarray data source :param axis: iterate over that axis :param size: the maximum number of the sub arrays :param shuffle: shuffle the numpy data source beforehand """ ... @classmethod def from_ndarray(cls: Type['T'], *args, **kwargs) -> 'T': """ # noqa: DAR101 # noqa: DAR102 # noqa: DAR201 """ return cls._from_generator('from_ndarray', *args, **kwargs) @classmethod @overload def from_files( cls: Type['T'], patterns: Union[str, List[str]], recursive: bool = True, size: Optional[int] = None, sampling_rate: Optional[float] = None, read_mode: Optional[str] = None, to_dataturi: bool = False, exclude_regex: Optional[str] = None, *args, **kwargs, ) -> 'T': """Build from a list of file path or the content of the files. :param patterns: The pattern may contain simple shell-style wildcards, e.g. '\*.py', '[\*.zip, \*.gz]' :param recursive: If recursive is true, the pattern '**' will match any files and zero or more directories and subdirectories :param size: the maximum number of the files :param sampling_rate: the sampling rate between [0, 1] :param read_mode: specifies the mode in which the file is opened. 'r' for reading in text mode, 'rb' for reading in binary mode. If `read_mode` is None, will iterate over filenames. :param to_dataturi: if set, then the Document.uri will be filled with DataURI instead of the plan URI :param exclude_regex: if set, then filenames that match to this pattern are not included. """ ... @classmethod def from_files(cls: Type['T'], *args, **kwargs) -> 'T': """ # noqa: DAR101 # noqa: DAR102 # noqa: DAR201 """ return cls._from_generator('from_files', *args, **kwargs) @classmethod @overload def from_csv( cls: Type['T'], file: Union[str, TextIO], field_resolver: Optional[Dict[str, str]] = None, size: Optional[int] = None, sampling_rate: Optional[float] = None, dialect: Union[str, 'csv.Dialect'] = 'excel', ) -> 'T': """Build from CSV. :param file: file paths or file handler :param field_resolver: a map from field names defined in JSON, dict to the field names defined in Document. :param size: the maximum number of the documents :param sampling_rate: the sampling rate between [0, 1] :param dialect: define a set of parameters specific to a particular CSV dialect. could be a string that represents predefined dialects in your system, or could be a :class:`csv.Dialect` class that groups specific formatting parameters together. If you don't know the dialect and the default one does not work for you, you can try set it to ``auto``. """ ... @classmethod def from_csv(cls: Type['T'], *args, **kwargs) -> 'T': """ # noqa: DAR101 # noqa: DAR102 # noqa: DAR201 """ return cls._from_generator('from_csv', *args, **kwargs) @classmethod @overload def from_huggingface_datasets( cls: Type['T'], dataset_path: str, field_resolver: Optional[Dict[str, str]] = None, size: Optional[int] = None, sampling_rate: Optional[float] = None, filter_fields: bool = False, **datasets_kwargs, ) -> 'T': """Build from Hugging Face Datasets. Yields documents. This function helps to load datasets from Hugging Face Datasets Hub (https://huggingface.co/datasets) in Jina. Additional parameters can be passed to the ``datasets`` library using keyword arguments. The ``load_dataset`` method from ``datasets`` library is used to load the datasets. :param dataset_path: a valid dataset path for Hugging Face Datasets library. :param field_resolver: a map from field names defined in ``document`` (JSON, dict) to the field names defined in Protobuf. This is only used when the given ``document`` is a JSON string or a Python dict. :param size: the maximum number of the documents :param sampling_rate: the sampling rate between [0, 1] :param filter_fields: specifies whether to filter the dataset with the fields given in ```field_resolver`` argument. :param **datasets_kwargs: additional arguments for ``load_dataset`` method from Datasets library. More details at https://huggingface.co/docs/datasets/package_reference/loading_methods.html#datasets.load_dataset """ ... @classmethod def from_huggingface_datasets(cls: Type['T'], *args, **kwargs) -> 'T': """ # noqa: DAR101 # noqa: DAR102 # noqa: DAR201 """ return cls._from_generator('from_huggingface_datasets', *args, **kwargs) @classmethod @overload def from_ndjson( cls: Type['T'], fp: Iterable[str], field_resolver: Optional[Dict[str, str]] = None, size: Optional[int] = None, sampling_rate: Optional[float] = None, ) -> 'T': """Build from line separated JSON. Yields documents. :param fp: file paths :param field_resolver: a map from field names defined in ``document`` (JSON, dict) to the field names defined in Protobuf. This is only used when the given ``document`` is a JSON string or a Python dict. :param size: the maximum number of the documents :param sampling_rate: the sampling rate between [0, 1] """ ... @classmethod def from_ndjson(cls: Type['T'], *args, **kwargs) -> 'T': """ # noqa: DAR101 # noqa: DAR102 # noqa: DAR201 """ return cls._from_generator('from_ndjson', *args, **kwargs) @classmethod @overload def from_lines( cls: 'T', lines: Optional[Iterable[str]] = None, filepath: Optional[str] = None, read_mode: str = 'r', line_format: str = 'json', field_resolver: Optional[Dict[str, str]] = None, size: Optional[int] = None, sampling_rate: Optional[float] = None, ) -> 'T': """Build from lines, json and csv. Yields documents or strings. :param lines: a list of strings, each is considered as a document :param filepath: a text file that each line contains a document :param read_mode: specifies the mode in which the file is opened. 'r' for reading in text mode, 'rb' for reading in binary :param line_format: the format of each line ``json`` or ``csv`` :param field_resolver: a map from field names defined in ``document`` (JSON, dict) to the field names defined in Protobuf. This is only used when the given ``document`` is a JSON string or a Python dict. :param size: the maximum number of the documents :param sampling_rate: the sampling rate between [0, 1] """ ... @classmethod def from_lines(cls: Type['T'], *args, **kwargs) -> 'T': """ # noqa: DAR101 # noqa: DAR102 # noqa: DAR201 """ return cls._from_generator('from_lines', *args, **kwargs)
35.843882
122
0.593996
from typing import ( Type, TYPE_CHECKING, Optional, overload, Union, List, TextIO, Dict, Iterable, ) if TYPE_CHECKING: from ....types import T import numpy as np import csv class FromGeneratorMixin: @classmethod def _from_generator(cls: Type['T'], meth: str, *args, **kwargs) -> 'T': from ....document import generators from_fn = getattr(generators, meth) da_like = cls(**kwargs) da_like.extend(from_fn(*args, **kwargs)) return da_like @classmethod @overload def from_ndarray( cls: Type['T'], array: 'np.ndarray', axis: int = 0, size: Optional[int] = None, shuffle: bool = False, *args, **kwargs, ) -> 'T': ... @classmethod def from_ndarray(cls: Type['T'], *args, **kwargs) -> 'T': return cls._from_generator('from_ndarray', *args, **kwargs) @classmethod @overload def from_files( cls: Type['T'], patterns: Union[str, List[str]], recursive: bool = True, size: Optional[int] = None, sampling_rate: Optional[float] = None, read_mode: Optional[str] = None, to_dataturi: bool = False, exclude_regex: Optional[str] = None, *args, **kwargs, ) -> 'T': ... @classmethod def from_files(cls: Type['T'], *args, **kwargs) -> 'T': return cls._from_generator('from_files', *args, **kwargs) @classmethod @overload def from_csv( cls: Type['T'], file: Union[str, TextIO], field_resolver: Optional[Dict[str, str]] = None, size: Optional[int] = None, sampling_rate: Optional[float] = None, dialect: Union[str, 'csv.Dialect'] = 'excel', ) -> 'T': ... @classmethod def from_csv(cls: Type['T'], *args, **kwargs) -> 'T': return cls._from_generator('from_csv', *args, **kwargs) @classmethod @overload def from_huggingface_datasets( cls: Type['T'], dataset_path: str, field_resolver: Optional[Dict[str, str]] = None, size: Optional[int] = None, sampling_rate: Optional[float] = None, filter_fields: bool = False, **datasets_kwargs, ) -> 'T': ... @classmethod def from_huggingface_datasets(cls: Type['T'], *args, **kwargs) -> 'T': return cls._from_generator('from_huggingface_datasets', *args, **kwargs) @classmethod @overload def from_ndjson( cls: Type['T'], fp: Iterable[str], field_resolver: Optional[Dict[str, str]] = None, size: Optional[int] = None, sampling_rate: Optional[float] = None, ) -> 'T': ... @classmethod def from_ndjson(cls: Type['T'], *args, **kwargs) -> 'T': return cls._from_generator('from_ndjson', *args, **kwargs) @classmethod @overload def from_lines( cls: 'T', lines: Optional[Iterable[str]] = None, filepath: Optional[str] = None, read_mode: str = 'r', line_format: str = 'json', field_resolver: Optional[Dict[str, str]] = None, size: Optional[int] = None, sampling_rate: Optional[float] = None, ) -> 'T': ... @classmethod def from_lines(cls: Type['T'], *args, **kwargs) -> 'T': return cls._from_generator('from_lines', *args, **kwargs)
true
true
f7360155a2cf41e1ff29c50118bef76ae6d76a51
7,617
py
Python
meiduo_mall/meiduo_mall/apps/orders/serializers.py
zhiliangsu/MeiduoMall
a3968c52f6815ccda6513371d331580dc5aa58f3
[ "MIT" ]
null
null
null
meiduo_mall/meiduo_mall/apps/orders/serializers.py
zhiliangsu/MeiduoMall
a3968c52f6815ccda6513371d331580dc5aa58f3
[ "MIT" ]
null
null
null
meiduo_mall/meiduo_mall/apps/orders/serializers.py
zhiliangsu/MeiduoMall
a3968c52f6815ccda6513371d331580dc5aa58f3
[ "MIT" ]
null
null
null
# from datetime import timezone # from time import timezone from django.utils import timezone from django_redis import get_redis_connection from django.db import transaction from rest_framework import serializers from decimal import Decimal from goods.models import SKU from orders.models import OrderInfo, OrderGoods from users.models import User class CommitOrderSerializer(serializers.ModelSerializer): """保存订单序列化器""" class Meta: model = OrderInfo # order_id:输出, address和pay_method:输入 fields = ['order_id', 'address', 'pay_method'] read_only_fields = ['order_id'] # 指定address和pay_method为输出 extra_kwargs = { 'address': { 'write_only': True, 'required': True, }, 'pay_method': { 'write_only': True, 'required': True, } } def create(self, validated_data): """重写序列化器的create方法进行存储订单表/订单商品""" # 订单基本信息表 订单商品表 sku spu 四个表要么一起成功,要么一起失败 # 获取当前保存订单时需要的信息 # 获取用户对象 user = self.context['request'].user # 生成订单编号 当前时间 + user_id 2019021522320000000001 order_id = timezone.now().strftime('%Y%m%d%H%M%S') + '%09d' % user.id # 获取用户选择的收货地址 address = validated_data.get('address') # 获取支付方式 pay_method = validated_data.get('pay_method') # 订单状态: 如果用户选择的是货到付款,订单应该是待发货 如果用户选择的是支付宝支付,订单应该是待支付 # status = '待支付' if 如果用户选择的支付方式是支付宝 else '待发货' status = (OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if OrderInfo.PAY_METHODS_ENUM['ALIPAY'] == pay_method else OrderInfo.ORDER_STATUS_ENUM['UNSEND']) # 开始一个事务 with transaction.atomic(): # 创建事务保存点 save_point = transaction.savepoint() try: # 保存订单基本信息 OrderInfo(一) order = OrderInfo.objects.create( order_id=order_id, user=user, address=address, total_count=0, total_amount=Decimal('0.00'), freight=Decimal('10.00'), pay_method=pay_method, status=status ) # 从redis读取购物车中被勾选的商品信息 redis_conn = get_redis_connection('cart') # {b'16': 1, b'1':1} redis_cart_dict = redis_conn.hgetall('cart_%d' % user.id) # {b'16'} redis_selected_ids = redis_conn.smembers('selected_%d' % user.id) # 把要购买的商品id和count重新包到一个字典 cart_selected_dict = {} # for sku_id, count in redis_cart_dict.items(): # if sku_id in redis_selected_ids: # cart_selected_dict[int(sku_id)] = int(count) for sku_id in redis_selected_ids: cart_selected_dict[int(sku_id)] = int(redis_cart_dict[sku_id]) # 遍历购物车中被勾选的商品信息 for sku_id in cart_selected_dict: while True: # 获取sku对象 sku = SKU.objects.get(id=sku_id) # 获取当前sku_id商品要购买的数量 sku_count = cart_selected_dict[sku_id] # 获取查询出sku那一刻的库存和数量 origin_stock = sku.stock origin_sales = sku.sales # 判断库存 if sku_count > sku.stock: raise serializers.ValidationError('库存不足') # 只用于测试 # import time # time.sleep(5) # 计算新的库存和销量 new_stock = origin_stock - sku_count new_sales = origin_sales + sku_count # 减少库存,增加销量SKU ==> 乐观锁(使用乐观锁需要更改数据库的事务隔离级别为READ_COMMITTED) result = SKU.objects.filter(id=sku_id, stock=origin_stock).update(stock=new_stock, sales=new_sales) if result == 0: continue # 跳出本次循环进入下一次 # sku.stock -= sku_count # sku.sales += sku_count # sku.save() # 修改SPU销量 spu = sku.goods spu.sales += sku_count spu.save() # 保存订单商品信息 OrderGoods(多) OrderGoods.objects.create( order=order, sku=sku, count=sku_count, price=sku.price ) # 累加计算总数量和总价 order.total_count += sku_count order.total_amount += (sku.price * sku_count) break # 跳出无限循环,继续对下一个sku_id进行下单 # 最后加入邮费和保存订单信息 order.total_amount += order.freight order.save() except Exception: # 暴力回滚,无论中间出现什么问题全部回滚 transaction.savepoint_rollback(save_point) raise else: # 如果中间没有出现异常提交事务 transaction.savepoint_commit(save_point) # 清除购物车中已结算的商品 pl = redis_conn.pipeline() pl.hdel('cart_%d' % user.id, *redis_selected_ids) pl.srem('selected_%d' % user.id, *redis_selected_ids) pl.execute() return order class CartSKUSerializer(serializers.ModelSerializer): """购物车商品数据序列化器""" count = serializers.IntegerField(label='商品数量') class Meta: model = SKU fields = ['id', 'name', 'default_image_url', 'price', 'count'] class OrderSettlementSerializer(serializers.Serializer): """订单结算数据序列化器""" freight = serializers.DecimalField(label='运费', max_digits=10, decimal_places=2) skus = CartSKUSerializer(many=True) class GoodSerializer(serializers.ModelSerializer): """商品序列化器""" class Meta: model = SKU fields = ['id', 'default_image_url', 'name'] class OrderGoodsSerializer(serializers.ModelSerializer): """订单商品数据序列化器""" sku = GoodSerializer(read_only=True) class Meta: model = OrderGoods fields = ['sku', 'count', 'price', 'order', 'comment', 'score', 'is_anonymous', 'is_commented'] read_only_fields = ['count', 'price'] def update(self, instance, validated_data): # TODO: 涉及到三张表的操作,可以使用事务 instance.comment = validated_data.get('comment') instance.score = validated_data.get('score') instance.is_anonymous = validated_data.get('is_anonymous') instance.is_commented = True instance.save() sku = instance.sku sku.comments += 1 sku.save() not_commented = OrderGoods.objects.filter(order_id=instance.order_id, is_commented=False).count() if not not_commented: order = instance.order order.status = OrderInfo.ORDER_STATUS_ENUM['FINISHED'] order.save() return instance class OrderListSerializer(serializers.ModelSerializer): """订单列表序列化器""" create_time = serializers.DateTimeField(label='订单时间', format='%Y-%m-%d %H:%M') skus = OrderGoodsSerializer(many=True) class Meta: model = OrderInfo fields = ['skus', 'create_time', 'order_id', 'total_amount', 'freight', 'pay_method', 'status']
33.262009
106
0.527636
from django.utils import timezone from django_redis import get_redis_connection from django.db import transaction from rest_framework import serializers from decimal import Decimal from goods.models import SKU from orders.models import OrderInfo, OrderGoods from users.models import User class CommitOrderSerializer(serializers.ModelSerializer): class Meta: model = OrderInfo fields = ['order_id', 'address', 'pay_method'] read_only_fields = ['order_id'] extra_kwargs = { 'address': { 'write_only': True, 'required': True, }, 'pay_method': { 'write_only': True, 'required': True, } } def create(self, validated_data): user = self.context['request'].user order_id = timezone.now().strftime('%Y%m%d%H%M%S') + '%09d' % user.id address = validated_data.get('address') pay_method = validated_data.get('pay_method') status = (OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if OrderInfo.PAY_METHODS_ENUM['ALIPAY'] == pay_method else OrderInfo.ORDER_STATUS_ENUM['UNSEND']) with transaction.atomic(): save_point = transaction.savepoint() try: order = OrderInfo.objects.create( order_id=order_id, user=user, address=address, total_count=0, total_amount=Decimal('0.00'), freight=Decimal('10.00'), pay_method=pay_method, status=status ) redis_conn = get_redis_connection('cart') redis_cart_dict = redis_conn.hgetall('cart_%d' % user.id) redis_selected_ids = redis_conn.smembers('selected_%d' % user.id) cart_selected_dict = {} for sku_id in redis_selected_ids: cart_selected_dict[int(sku_id)] = int(redis_cart_dict[sku_id]) for sku_id in cart_selected_dict: while True: sku = SKU.objects.get(id=sku_id) sku_count = cart_selected_dict[sku_id] origin_stock = sku.stock origin_sales = sku.sales if sku_count > sku.stock: raise serializers.ValidationError('库存不足') new_stock = origin_stock - sku_count new_sales = origin_sales + sku_count result = SKU.objects.filter(id=sku_id, stock=origin_stock).update(stock=new_stock, sales=new_sales) if result == 0: continue spu = sku.goods spu.sales += sku_count spu.save() OrderGoods.objects.create( order=order, sku=sku, count=sku_count, price=sku.price ) order.total_count += sku_count order.total_amount += (sku.price * sku_count) break order.total_amount += order.freight order.save() except Exception: transaction.savepoint_rollback(save_point) raise else: transaction.savepoint_commit(save_point) pl = redis_conn.pipeline() pl.hdel('cart_%d' % user.id, *redis_selected_ids) pl.srem('selected_%d' % user.id, *redis_selected_ids) pl.execute() return order class CartSKUSerializer(serializers.ModelSerializer): count = serializers.IntegerField(label='商品数量') class Meta: model = SKU fields = ['id', 'name', 'default_image_url', 'price', 'count'] class OrderSettlementSerializer(serializers.Serializer): freight = serializers.DecimalField(label='运费', max_digits=10, decimal_places=2) skus = CartSKUSerializer(many=True) class GoodSerializer(serializers.ModelSerializer): class Meta: model = SKU fields = ['id', 'default_image_url', 'name'] class OrderGoodsSerializer(serializers.ModelSerializer): sku = GoodSerializer(read_only=True) class Meta: model = OrderGoods fields = ['sku', 'count', 'price', 'order', 'comment', 'score', 'is_anonymous', 'is_commented'] read_only_fields = ['count', 'price'] def update(self, instance, validated_data): instance.comment = validated_data.get('comment') instance.score = validated_data.get('score') instance.is_anonymous = validated_data.get('is_anonymous') instance.is_commented = True instance.save() sku = instance.sku sku.comments += 1 sku.save() not_commented = OrderGoods.objects.filter(order_id=instance.order_id, is_commented=False).count() if not not_commented: order = instance.order order.status = OrderInfo.ORDER_STATUS_ENUM['FINISHED'] order.save() return instance class OrderListSerializer(serializers.ModelSerializer): create_time = serializers.DateTimeField(label='订单时间', format='%Y-%m-%d %H:%M') skus = OrderGoodsSerializer(many=True) class Meta: model = OrderInfo fields = ['skus', 'create_time', 'order_id', 'total_amount', 'freight', 'pay_method', 'status']
true
true
f73601a0b37f24e2fbfe3ca8a4805bee0040ab5b
1,109
py
Python
platform-tools/systrace/catapult/devil/devil/android/perf/perf_control_devicetest.py
NBPS-Robotics/FTC-Code-Team-9987---2022
180538f3ebd234635fa88f96ae7cf7441df6a246
[ "MIT" ]
7
2021-06-02T06:55:50.000Z
2022-03-29T10:32:33.000Z
platform-tools/systrace/catapult/devil/devil/android/perf/perf_control_devicetest.py
NBPS-Robotics/FTC-Code-Team-9987---2022
180538f3ebd234635fa88f96ae7cf7441df6a246
[ "MIT" ]
7
2020-07-19T11:24:45.000Z
2022-03-02T07:11:57.000Z
platform-tools/systrace/catapult/devil/devil/android/perf/perf_control_devicetest.py
NBPS-Robotics/FTC-Code-Team-9987---2022
180538f3ebd234635fa88f96ae7cf7441df6a246
[ "MIT" ]
1
2020-07-24T18:22:03.000Z
2020-07-24T18:22:03.000Z
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0212 import os import sys import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) from devil.android import device_test_case from devil.android import device_utils from devil.android.perf import perf_control class TestPerfControl(device_test_case.DeviceTestCase): def setUp(self): super(TestPerfControl, self).setUp() if not os.getenv('BUILDTYPE'): os.environ['BUILDTYPE'] = 'Debug' self._device = device_utils.DeviceUtils(self.serial) def testHighPerfMode(self): perf = perf_control.PerfControl(self._device) try: perf.SetPerfProfilingMode() cpu_info = perf.GetCpuInfo() self.assertEquals(len(perf._cpu_files), len(cpu_info)) for _, online, governor in cpu_info: self.assertTrue(online) self.assertEquals('performance', governor) finally: perf.SetDefaultPerfMode() if __name__ == '__main__': unittest.main()
28.435897
72
0.724977
import os import sys import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) from devil.android import device_test_case from devil.android import device_utils from devil.android.perf import perf_control class TestPerfControl(device_test_case.DeviceTestCase): def setUp(self): super(TestPerfControl, self).setUp() if not os.getenv('BUILDTYPE'): os.environ['BUILDTYPE'] = 'Debug' self._device = device_utils.DeviceUtils(self.serial) def testHighPerfMode(self): perf = perf_control.PerfControl(self._device) try: perf.SetPerfProfilingMode() cpu_info = perf.GetCpuInfo() self.assertEquals(len(perf._cpu_files), len(cpu_info)) for _, online, governor in cpu_info: self.assertTrue(online) self.assertEquals('performance', governor) finally: perf.SetDefaultPerfMode() if __name__ == '__main__': unittest.main()
true
true
f73601c1555b67a9782615f2f35d1dff388162a4
1,052
py
Python
redirect/models.py
ashbc/tgrsite
180e5eb9c72a7a331276fe3de150ea2eea2db51e
[ "ISC" ]
1
2019-06-29T15:25:05.000Z
2019-06-29T15:25:05.000Z
redirect/models.py
ashbc/tgrsite
180e5eb9c72a7a331276fe3de150ea2eea2db51e
[ "ISC" ]
70
2017-06-21T13:13:57.000Z
2019-03-20T22:14:56.000Z
redirect/models.py
ashbc/tgrsite
180e5eb9c72a7a331276fe3de150ea2eea2db51e
[ "ISC" ]
null
null
null
from django.conf import settings from django.db import models # Create your models here. from django.urls import reverse, NoReverseMatch from django.utils.safestring import mark_safe from users.models import Achievement class Redirect(models.Model): source = models.CharField(max_length=50) sink = models.CharField(max_length=1024) permanent = models.BooleanField(default=False) usages = models.PositiveIntegerField( default=0, help_text="The number of times that link has been used") achievement = models.ForeignKey( Achievement, on_delete=models.CASCADE, null=True, blank=True, default=None) def __str__(self): return self.source def get_absolute_url(self): return reverse("redirect", kwargs={"source": self.source}) @property def url(self): try: url_ = settings.DEFAULT_PROTOCOL + settings.PRIMARY_HOST + self.get_absolute_url() return mark_safe('<a href="{}">{}</a>'.format(url_, url_)) except NoReverseMatch: return "-"
31.878788
94
0.695817
from django.conf import settings from django.db import models from django.urls import reverse, NoReverseMatch from django.utils.safestring import mark_safe from users.models import Achievement class Redirect(models.Model): source = models.CharField(max_length=50) sink = models.CharField(max_length=1024) permanent = models.BooleanField(default=False) usages = models.PositiveIntegerField( default=0, help_text="The number of times that link has been used") achievement = models.ForeignKey( Achievement, on_delete=models.CASCADE, null=True, blank=True, default=None) def __str__(self): return self.source def get_absolute_url(self): return reverse("redirect", kwargs={"source": self.source}) @property def url(self): try: url_ = settings.DEFAULT_PROTOCOL + settings.PRIMARY_HOST + self.get_absolute_url() return mark_safe('<a href="{}">{}</a>'.format(url_, url_)) except NoReverseMatch: return "-"
true
true
f736028df695f0e29db9086d14746101266e6296
1,168
py
Python
ynab_sdk/utils/parsers.py
csadorf/ynab-sdk-python
845d3798e44bbc27261f73975089d8e19366e8e8
[ "Apache-2.0" ]
19
2019-05-04T00:26:31.000Z
2021-09-01T07:31:20.000Z
ynab_sdk/utils/parsers.py
csadorf/ynab-sdk-python
845d3798e44bbc27261f73975089d8e19366e8e8
[ "Apache-2.0" ]
100
2019-04-25T00:27:57.000Z
2022-03-31T15:24:45.000Z
ynab_sdk/utils/parsers.py
csadorf/ynab-sdk-python
845d3798e44bbc27261f73975089d8e19366e8e8
[ "Apache-2.0" ]
7
2019-11-13T06:30:06.000Z
2022-03-25T15:37:53.000Z
import datetime from typing import Any, Callable, List, Type, TypeVar, cast import dateutil.parser T = TypeVar("T") def from_str(x: Any, nullable=False) -> str: try: assert isinstance(x, str) except AssertionError as ex: if nullable: return from_none(x) else: raise ex return x def from_int(x: Any, nullable=False) -> int: try: assert isinstance(x, int) and not isinstance(x, bool) except AssertionError as ex: if nullable: return from_none(x) else: raise ex return x def from_bool(x: Any) -> bool: assert isinstance(x, bool) return x def from_datetime(x: Any) -> datetime: return dateutil.parser.parse(x) def to_class(c: Type[T], x: Any) -> dict: assert isinstance(x, c) return cast(Any, x).to_dict() def from_list(f: Callable[[Any], T], x: Any) -> List[T]: assert isinstance(x, list) return [f(y) for y in x] def from_none(x: Any) -> Any: assert x is None return x def from_union(fs, x): for f in fs: try: return f(x) except: pass assert False
18.83871
61
0.586473
import datetime from typing import Any, Callable, List, Type, TypeVar, cast import dateutil.parser T = TypeVar("T") def from_str(x: Any, nullable=False) -> str: try: assert isinstance(x, str) except AssertionError as ex: if nullable: return from_none(x) else: raise ex return x def from_int(x: Any, nullable=False) -> int: try: assert isinstance(x, int) and not isinstance(x, bool) except AssertionError as ex: if nullable: return from_none(x) else: raise ex return x def from_bool(x: Any) -> bool: assert isinstance(x, bool) return x def from_datetime(x: Any) -> datetime: return dateutil.parser.parse(x) def to_class(c: Type[T], x: Any) -> dict: assert isinstance(x, c) return cast(Any, x).to_dict() def from_list(f: Callable[[Any], T], x: Any) -> List[T]: assert isinstance(x, list) return [f(y) for y in x] def from_none(x: Any) -> Any: assert x is None return x def from_union(fs, x): for f in fs: try: return f(x) except: pass assert False
true
true
f73602915122c998815f4ae1a7673a36cb812cf8
1,916
py
Python
grab/tools/watch.py
subeax/grab
55518263c543da214d1f0cb54622bbc4fda66349
[ "MIT" ]
null
null
null
grab/tools/watch.py
subeax/grab
55518263c543da214d1f0cb54622bbc4fda66349
[ "MIT" ]
null
null
null
grab/tools/watch.py
subeax/grab
55518263c543da214d1f0cb54622bbc4fda66349
[ "MIT" ]
null
null
null
import os import signal import sys import logging import time class Watcher(object): """this class solves two problems with multithreaded programs in Python, (1) a signal might be delivered to any thread (which is just a malfeature) and (2) if the thread that gets the signal is waiting, the signal is ignored (which is a bug). The watcher is a concurrent process (not thread) that waits for a signal and the process that contains the threads. See Appendix A of The Little Book of Semaphores. http://greenteapress.com/semaphores/ I have only tested this on Linux. I would expect it to work on the Macintosh and not work on Windows. """ def __init__(self): """ Creates a child thread, which returns. The parent thread waits for a KeyboardInterrupt and then kills the child thread. """ self.child = os.fork() if self.child == 0: return else: self.watch() def watch(self): try: os.wait() except KeyboardInterrupt: logging.debug('Watcher process received KeyboardInterrupt') signals = ( ('SIGUSR2', 1), ('SIGTERM', 3), ('SIGKILL', 5), ) for sig, sleep_time in signals: if not os.path.exists('/proc/%d' % self.child): logging.debug('Process terminated!') break else: logging.debug('Sending %s signal to child process' % sig) try: os.kill(self.child, getattr(signal, sig)) except OSError: pass logging.debug('Waiting 1 second after sending %s' % sig) time.sleep(sleep_time) sys.exit() def watch(): Watcher()
31.409836
77
0.549582
import os import signal import sys import logging import time class Watcher(object): def __init__(self): self.child = os.fork() if self.child == 0: return else: self.watch() def watch(self): try: os.wait() except KeyboardInterrupt: logging.debug('Watcher process received KeyboardInterrupt') signals = ( ('SIGUSR2', 1), ('SIGTERM', 3), ('SIGKILL', 5), ) for sig, sleep_time in signals: if not os.path.exists('/proc/%d' % self.child): logging.debug('Process terminated!') break else: logging.debug('Sending %s signal to child process' % sig) try: os.kill(self.child, getattr(signal, sig)) except OSError: pass logging.debug('Waiting 1 second after sending %s' % sig) time.sleep(sleep_time) sys.exit() def watch(): Watcher()
true
true
f73602a5ee89c8bf0c008b6b4c824014333bfd46
9,254
py
Python
effdet/data/transforms.py
saikrishna-pallerla/efficientdet-pytorch
dc7b790f537d28476a26af6f793acc4757becd0d
[ "Apache-2.0" ]
null
null
null
effdet/data/transforms.py
saikrishna-pallerla/efficientdet-pytorch
dc7b790f537d28476a26af6f793acc4757becd0d
[ "Apache-2.0" ]
null
null
null
effdet/data/transforms.py
saikrishna-pallerla/efficientdet-pytorch
dc7b790f537d28476a26af6f793acc4757becd0d
[ "Apache-2.0" ]
null
null
null
""" COCO transforms (quick and dirty) Hacked together by Ross Wightman """ import torch from PIL import Image import numpy as np import random import math IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) IMAGENET_INCEPTION_MEAN = (0.5, 0.5, 0.5) IMAGENET_INCEPTION_STD = (0.5, 0.5, 0.5) class ImageToNumpy: def __call__(self, pil_img, annotations: dict): np_img = np.array(pil_img, dtype=np.uint8) if np_img.ndim < 3: np_img = np.expand_dims(np_img, axis=-1) np_img = np.moveaxis(np_img, 2, 0) # HWC to CHW return np_img, annotations class ImageToTensor: def __init__(self, dtype=torch.float32): self.dtype = dtype def __call__(self, pil_img, annotations: dict): np_img = np.array(pil_img, dtype=np.uint8) if np_img.ndim < 3: np_img = np.expand_dims(np_img, axis=-1) np_img = np.moveaxis(np_img, 2, 0) # HWC to CHW return torch.from_numpy(np_img).to(dtype=self.dtype), annotations def _pil_interp(method): if method == 'bicubic': return Image.BICUBIC elif method == 'lanczos': return Image.LANCZOS elif method == 'hamming': return Image.HAMMING else: # default bilinear, do we want to allow nearest? return Image.BILINEAR _RANDOM_INTERPOLATION = (Image.BILINEAR, Image.BICUBIC) def clip_boxes_(boxes, img_size): height, width = img_size clip_upper = np.array([height, width] * 2, dtype=boxes.dtype) np.clip(boxes, 0, clip_upper, out=boxes) def clip_boxes(boxes, img_size): clipped_boxes = boxes.copy() clip_boxes_(clipped_boxes, img_size) return clipped_boxes def _size_tuple(size): if isinstance(size, int): return size, size else: assert len(size) == 2 return size class ResizePad: def __init__(self, target_size: int, interpolation: str = 'bilinear', fill_color: tuple = (0, 0, 0)): self.target_size = _size_tuple(target_size) self.interpolation = interpolation self.fill_color = fill_color def __call__(self, img, anno: dict): width, height = img.size img_scale_y = self.target_size[0] / height img_scale_x = self.target_size[1] / width img_scale = min(img_scale_y, img_scale_x) scaled_h = int(height * img_scale) scaled_w = int(width * img_scale) new_img = Image.new("RGB", (self.target_size[1], self.target_size[0]), color=self.fill_color) interp_method = _pil_interp(self.interpolation) img = img.resize((scaled_w, scaled_h), interp_method) new_img.paste(img) if 'bbox' in anno: # FIXME haven't tested this path since not currently using dataset annotations for train/eval bbox = anno['bbox'] bbox[:, :4] *= img_scale clip_boxes_(bbox, (scaled_h, scaled_w)) valid_indices = (bbox[:, :2] < bbox[:, 2:4]).all(axis=1) anno['bbox'] = bbox[valid_indices, :] anno['cls'] = anno['cls'][valid_indices] anno['img_scale'] = 1. / img_scale # back to original return new_img, anno class RandomResizePad: def __init__(self, target_size: int, scale: tuple = (0.1, 2.0), interpolation: str = 'random', fill_color: tuple = (0, 0, 0)): self.target_size = _size_tuple(target_size) self.scale = scale if interpolation == 'random': self.interpolation = _RANDOM_INTERPOLATION else: self.interpolation = _pil_interp(interpolation) self.fill_color = fill_color def _get_params(self, img): # Select a random scale factor. scale_factor = random.uniform(*self.scale) scaled_target_height = scale_factor * self.target_size[0] scaled_target_width = scale_factor * self.target_size[1] # Recompute the accurate scale_factor using rounded scaled image size. width, height = img.size img_scale_y = scaled_target_height / height img_scale_x = scaled_target_width / width img_scale = min(img_scale_y, img_scale_x) # Select non-zero random offset (x, y) if scaled image is larger than target size scaled_h = int(height * img_scale) scaled_w = int(width * img_scale) offset_y = scaled_h - self.target_size[0] offset_x = scaled_w - self.target_size[1] offset_y = int(max(0.0, float(offset_y)) * random.uniform(0, 1)) offset_x = int(max(0.0, float(offset_x)) * random.uniform(0, 1)) return scaled_h, scaled_w, offset_y, offset_x, img_scale def __call__(self, img, anno: dict): scaled_h, scaled_w, offset_y, offset_x, img_scale = self._get_params(img) if isinstance(self.interpolation, (tuple, list)): interpolation = random.choice(self.interpolation) else: interpolation = self.interpolation img = img.resize((scaled_w, scaled_h), interpolation) right, lower = min(scaled_w, offset_x + self.target_size[1]), min(scaled_h, offset_y + self.target_size[0]) img = img.crop((offset_x, offset_y, right, lower)) new_img = Image.new("RGB", (self.target_size[1], self.target_size[0]), color=self.fill_color) new_img.paste(img) if 'bbox' in anno: # FIXME not fully tested bbox = anno['bbox'].copy() # FIXME copy for debugger inspection, back to inplace bbox[:, :4] *= img_scale box_offset = np.stack([offset_y, offset_x] * 2) bbox -= box_offset clip_boxes_(bbox, (scaled_h, scaled_w)) valid_indices = (bbox[:, :2] < bbox[:, 2:4]).all(axis=1) anno['bbox'] = bbox[valid_indices, :] anno['cls'] = anno['cls'][valid_indices] anno['img_scale'] = 1. / img_scale # back to original return new_img, anno class RandomFlip: def __init__(self, horizontal=True, vertical=False, prob=0.5): self.horizontal = horizontal self.vertical = vertical self.prob = prob def _get_params(self): do_horizontal = random.random() < self.prob if self.horizontal else False do_vertical = random.random() < self.prob if self.vertical else False return do_horizontal, do_vertical def __call__(self, img, annotations: dict): do_horizontal, do_vertical = self._get_params() width, height = img.size def _fliph(bbox): x_max = width - bbox[:, 1] x_min = width - bbox[:, 3] bbox[:, 1] = x_min bbox[:, 3] = x_max def _flipv(bbox): y_max = height - bbox[:, 0] y_min = height - bbox[:, 2] bbox[:, 0] = y_min bbox[:, 2] = y_max if do_horizontal and do_vertical: img = img.transpose(Image.ROTATE_180) if 'bbox' in annotations: _fliph(annotations['bbox']) _flipv(annotations['bbox']) elif do_horizontal: img = img.transpose(Image.FLIP_LEFT_RIGHT) if 'bbox' in annotations: _fliph(annotations['bbox']) elif do_vertical: img = img.transpose(Image.FLIP_TOP_BOTTOM) if 'bbox' in annotations: _flipv(annotations['bbox']) return img, annotations def resolve_fill_color(fill_color, img_mean=IMAGENET_DEFAULT_MEAN): if isinstance(fill_color, tuple): assert len(fill_color) == 3 fill_color = fill_color else: try: int_color = int(fill_color) fill_color = (int_color,) * 3 except ValueError: assert fill_color == 'mean' fill_color = tuple([int(round(255 * x)) for x in img_mean]) return fill_color class Compose: def __init__(self, transforms: list): self.transforms = transforms def __call__(self, img, annotations: dict): for t in self.transforms: img, annotations = t(img, annotations) return img, annotations def transforms_coco_eval( img_size=224, interpolation='bilinear', use_prefetcher=False, fill_color='mean', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD): fill_color = resolve_fill_color(fill_color, mean) image_tfl = [ ResizePad( target_size=img_size, interpolation=interpolation, fill_color=fill_color), ImageToNumpy(), ] assert use_prefetcher, "Only supporting prefetcher usage right now" image_tf = Compose(image_tfl) return image_tf def transforms_coco_train( img_size=224, interpolation='random', use_prefetcher=False, fill_color='mean', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD): fill_color = resolve_fill_color(fill_color, mean) image_tfl = [ RandomFlip(horizontal=True, prob=0.5), RandomResizePad( target_size=img_size, interpolation=interpolation, fill_color=fill_color), ImageToNumpy(), ] assert use_prefetcher, "Only supporting prefetcher usage right now" image_tf = Compose(image_tfl) return image_tf
32.470175
115
0.623946
import torch from PIL import Image import numpy as np import random import math IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) IMAGENET_INCEPTION_MEAN = (0.5, 0.5, 0.5) IMAGENET_INCEPTION_STD = (0.5, 0.5, 0.5) class ImageToNumpy: def __call__(self, pil_img, annotations: dict): np_img = np.array(pil_img, dtype=np.uint8) if np_img.ndim < 3: np_img = np.expand_dims(np_img, axis=-1) np_img = np.moveaxis(np_img, 2, 0) return np_img, annotations class ImageToTensor: def __init__(self, dtype=torch.float32): self.dtype = dtype def __call__(self, pil_img, annotations: dict): np_img = np.array(pil_img, dtype=np.uint8) if np_img.ndim < 3: np_img = np.expand_dims(np_img, axis=-1) np_img = np.moveaxis(np_img, 2, 0) return torch.from_numpy(np_img).to(dtype=self.dtype), annotations def _pil_interp(method): if method == 'bicubic': return Image.BICUBIC elif method == 'lanczos': return Image.LANCZOS elif method == 'hamming': return Image.HAMMING else: return Image.BILINEAR _RANDOM_INTERPOLATION = (Image.BILINEAR, Image.BICUBIC) def clip_boxes_(boxes, img_size): height, width = img_size clip_upper = np.array([height, width] * 2, dtype=boxes.dtype) np.clip(boxes, 0, clip_upper, out=boxes) def clip_boxes(boxes, img_size): clipped_boxes = boxes.copy() clip_boxes_(clipped_boxes, img_size) return clipped_boxes def _size_tuple(size): if isinstance(size, int): return size, size else: assert len(size) == 2 return size class ResizePad: def __init__(self, target_size: int, interpolation: str = 'bilinear', fill_color: tuple = (0, 0, 0)): self.target_size = _size_tuple(target_size) self.interpolation = interpolation self.fill_color = fill_color def __call__(self, img, anno: dict): width, height = img.size img_scale_y = self.target_size[0] / height img_scale_x = self.target_size[1] / width img_scale = min(img_scale_y, img_scale_x) scaled_h = int(height * img_scale) scaled_w = int(width * img_scale) new_img = Image.new("RGB", (self.target_size[1], self.target_size[0]), color=self.fill_color) interp_method = _pil_interp(self.interpolation) img = img.resize((scaled_w, scaled_h), interp_method) new_img.paste(img) if 'bbox' in anno: bbox = anno['bbox'] bbox[:, :4] *= img_scale clip_boxes_(bbox, (scaled_h, scaled_w)) valid_indices = (bbox[:, :2] < bbox[:, 2:4]).all(axis=1) anno['bbox'] = bbox[valid_indices, :] anno['cls'] = anno['cls'][valid_indices] anno['img_scale'] = 1. / img_scale # back to original return new_img, anno class RandomResizePad: def __init__(self, target_size: int, scale: tuple = (0.1, 2.0), interpolation: str = 'random', fill_color: tuple = (0, 0, 0)): self.target_size = _size_tuple(target_size) self.scale = scale if interpolation == 'random': self.interpolation = _RANDOM_INTERPOLATION else: self.interpolation = _pil_interp(interpolation) self.fill_color = fill_color def _get_params(self, img): # Select a random scale factor. scale_factor = random.uniform(*self.scale) scaled_target_height = scale_factor * self.target_size[0] scaled_target_width = scale_factor * self.target_size[1] # Recompute the accurate scale_factor using rounded scaled image size. width, height = img.size img_scale_y = scaled_target_height / height img_scale_x = scaled_target_width / width img_scale = min(img_scale_y, img_scale_x) # Select non-zero random offset (x, y) if scaled image is larger than target size scaled_h = int(height * img_scale) scaled_w = int(width * img_scale) offset_y = scaled_h - self.target_size[0] offset_x = scaled_w - self.target_size[1] offset_y = int(max(0.0, float(offset_y)) * random.uniform(0, 1)) offset_x = int(max(0.0, float(offset_x)) * random.uniform(0, 1)) return scaled_h, scaled_w, offset_y, offset_x, img_scale def __call__(self, img, anno: dict): scaled_h, scaled_w, offset_y, offset_x, img_scale = self._get_params(img) if isinstance(self.interpolation, (tuple, list)): interpolation = random.choice(self.interpolation) else: interpolation = self.interpolation img = img.resize((scaled_w, scaled_h), interpolation) right, lower = min(scaled_w, offset_x + self.target_size[1]), min(scaled_h, offset_y + self.target_size[0]) img = img.crop((offset_x, offset_y, right, lower)) new_img = Image.new("RGB", (self.target_size[1], self.target_size[0]), color=self.fill_color) new_img.paste(img) if 'bbox' in anno: # FIXME not fully tested bbox = anno['bbox'].copy() # FIXME copy for debugger inspection, back to inplace bbox[:, :4] *= img_scale box_offset = np.stack([offset_y, offset_x] * 2) bbox -= box_offset clip_boxes_(bbox, (scaled_h, scaled_w)) valid_indices = (bbox[:, :2] < bbox[:, 2:4]).all(axis=1) anno['bbox'] = bbox[valid_indices, :] anno['cls'] = anno['cls'][valid_indices] anno['img_scale'] = 1. / img_scale # back to original return new_img, anno class RandomFlip: def __init__(self, horizontal=True, vertical=False, prob=0.5): self.horizontal = horizontal self.vertical = vertical self.prob = prob def _get_params(self): do_horizontal = random.random() < self.prob if self.horizontal else False do_vertical = random.random() < self.prob if self.vertical else False return do_horizontal, do_vertical def __call__(self, img, annotations: dict): do_horizontal, do_vertical = self._get_params() width, height = img.size def _fliph(bbox): x_max = width - bbox[:, 1] x_min = width - bbox[:, 3] bbox[:, 1] = x_min bbox[:, 3] = x_max def _flipv(bbox): y_max = height - bbox[:, 0] y_min = height - bbox[:, 2] bbox[:, 0] = y_min bbox[:, 2] = y_max if do_horizontal and do_vertical: img = img.transpose(Image.ROTATE_180) if 'bbox' in annotations: _fliph(annotations['bbox']) _flipv(annotations['bbox']) elif do_horizontal: img = img.transpose(Image.FLIP_LEFT_RIGHT) if 'bbox' in annotations: _fliph(annotations['bbox']) elif do_vertical: img = img.transpose(Image.FLIP_TOP_BOTTOM) if 'bbox' in annotations: _flipv(annotations['bbox']) return img, annotations def resolve_fill_color(fill_color, img_mean=IMAGENET_DEFAULT_MEAN): if isinstance(fill_color, tuple): assert len(fill_color) == 3 fill_color = fill_color else: try: int_color = int(fill_color) fill_color = (int_color,) * 3 except ValueError: assert fill_color == 'mean' fill_color = tuple([int(round(255 * x)) for x in img_mean]) return fill_color class Compose: def __init__(self, transforms: list): self.transforms = transforms def __call__(self, img, annotations: dict): for t in self.transforms: img, annotations = t(img, annotations) return img, annotations def transforms_coco_eval( img_size=224, interpolation='bilinear', use_prefetcher=False, fill_color='mean', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD): fill_color = resolve_fill_color(fill_color, mean) image_tfl = [ ResizePad( target_size=img_size, interpolation=interpolation, fill_color=fill_color), ImageToNumpy(), ] assert use_prefetcher, "Only supporting prefetcher usage right now" image_tf = Compose(image_tfl) return image_tf def transforms_coco_train( img_size=224, interpolation='random', use_prefetcher=False, fill_color='mean', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD): fill_color = resolve_fill_color(fill_color, mean) image_tfl = [ RandomFlip(horizontal=True, prob=0.5), RandomResizePad( target_size=img_size, interpolation=interpolation, fill_color=fill_color), ImageToNumpy(), ] assert use_prefetcher, "Only supporting prefetcher usage right now" image_tf = Compose(image_tfl) return image_tf
true
true
f736036671e3bc02c896fbd18c45ee63e5da334e
17,390
py
Python
venv/lib/python3.6/site-packages/ansible_collections/community/general/plugins/modules/net_tools/haproxy.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
22
2021-07-16T08:11:22.000Z
2022-03-31T07:15:34.000Z
venv/lib/python3.6/site-packages/ansible_collections/community/general/plugins/modules/net_tools/haproxy.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
12
2020-02-21T07:24:52.000Z
2020-04-14T09:54:32.000Z
venv/lib/python3.6/site-packages/ansible_collections/community/general/plugins/modules/net_tools/haproxy.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
39
2021-07-05T02:31:42.000Z
2022-03-31T02:46:03.000Z
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2014, Ravi Bhure <ravibhure@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: haproxy short_description: Enable, disable, and set weights for HAProxy backend servers using socket commands author: - Ravi Bhure (@ravibhure) description: - Enable, disable, drain and set weights for HAProxy backend servers using socket commands. notes: - Enable, disable and drain commands are restricted and can only be issued on sockets configured for level 'admin'. For example, you can add the line 'stats socket /var/run/haproxy.sock level admin' to the general section of haproxy.cfg. See U(http://haproxy.1wt.eu/download/1.5/doc/configuration.txt). - Depends on netcat (nc) being available; you need to install the appropriate package for your operating system before this module can be used. options: backend: description: - Name of the HAProxy backend pool. - If this parameter is unset, it will be auto-detected. type: str drain: description: - Wait until the server has no active connections or until the timeout determined by wait_interval and wait_retries is reached. - Continue only after the status changes to 'MAINT'. - This overrides the shutdown_sessions option. type: bool default: false host: description: - Name of the backend host to change. type: str required: true shutdown_sessions: description: - When disabling a server, immediately terminate all the sessions attached to the specified server. - This can be used to terminate long-running sessions after a server is put into maintenance mode. Overridden by the drain option. type: bool default: no socket: description: - Path to the HAProxy socket file. type: path default: /var/run/haproxy.sock state: description: - Desired state of the provided backend host. - Note that C(drain) state was added in version 2.4. - It is supported only by HAProxy version 1.5 or later, - When used on versions < 1.5, it will be ignored. type: str required: true choices: [ disabled, drain, enabled ] agent: description: - Disable/enable agent checks (depending on I(state) value). type: bool default: no version_added: 1.0.0 health: description: - Disable/enable health checks (depending on I(state) value). type: bool default: no version_added: "1.0.0" fail_on_not_found: description: - Fail whenever trying to enable/disable a backend host that does not exist type: bool default: no wait: description: - Wait until the server reports a status of 'UP' when C(state=enabled), status of 'MAINT' when C(state=disabled) or status of 'DRAIN' when C(state=drain) type: bool default: no wait_interval: description: - Number of seconds to wait between retries. type: int default: 5 wait_retries: description: - Number of times to check for status after changing the state. type: int default: 25 weight: description: - The value passed in argument. - If the value ends with the `%` sign, then the new weight will be relative to the initially configured weight. - Relative weights are only permitted between 0 and 100% and absolute weights are permitted between 0 and 256. type: str ''' EXAMPLES = r''' - name: Disable server in 'www' backend pool community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' backend: www - name: Disable server in 'www' backend pool, also stop health/agent checks community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' health: yes agent: yes - name: Disable server without backend pool name (apply to all available backend pool) community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' - name: Disable server, provide socket file community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' socket: /var/run/haproxy.sock backend: www - name: Disable server, provide socket file, wait until status reports in maintenance community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' socket: /var/run/haproxy.sock backend: www wait: yes # Place server in drain mode, providing a socket file. Then check the server's # status every minute to see if it changes to maintenance mode, continuing if it # does in an hour and failing otherwise. - community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' socket: /var/run/haproxy.sock backend: www wait: yes drain: yes wait_interval: 60 wait_retries: 60 - name: Disable backend server in 'www' backend pool and drop open sessions to it community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' backend: www socket: /var/run/haproxy.sock shutdown_sessions: yes - name: Disable server without backend pool name (apply to all available backend pool) but fail when the backend host is not found community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' fail_on_not_found: yes - name: Enable server in 'www' backend pool community.general.haproxy: state: enabled host: '{{ inventory_hostname }}' backend: www - name: Enable server in 'www' backend pool wait until healthy community.general.haproxy: state: enabled host: '{{ inventory_hostname }}' backend: www wait: yes - name: Enable server in 'www' backend pool wait until healthy. Retry 10 times with intervals of 5 seconds to retrieve the health community.general.haproxy: state: enabled host: '{{ inventory_hostname }}' backend: www wait: yes wait_retries: 10 wait_interval: 5 - name: Enable server in 'www' backend pool with change server(s) weight community.general.haproxy: state: enabled host: '{{ inventory_hostname }}' socket: /var/run/haproxy.sock weight: 10 backend: www - name: Set the server in 'www' backend pool to drain mode community.general.haproxy: state: drain host: '{{ inventory_hostname }}' socket: /var/run/haproxy.sock backend: www ''' import csv import socket import time from string import Template from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.common.text.converters import to_bytes, to_text DEFAULT_SOCKET_LOCATION = "/var/run/haproxy.sock" RECV_SIZE = 1024 ACTION_CHOICES = ['enabled', 'disabled', 'drain'] WAIT_RETRIES = 25 WAIT_INTERVAL = 5 ###################################################################### class TimeoutException(Exception): pass class HAProxy(object): """ Used for communicating with HAProxy through its local UNIX socket interface. Perform common tasks in Haproxy related to enable server and disable server. The complete set of external commands Haproxy handles is documented on their website: http://haproxy.1wt.eu/download/1.5/doc/configuration.txt#Unix Socket commands """ def __init__(self, module): self.module = module self.state = self.module.params['state'] self.host = self.module.params['host'] self.backend = self.module.params['backend'] self.weight = self.module.params['weight'] self.socket = self.module.params['socket'] self.shutdown_sessions = self.module.params['shutdown_sessions'] self.fail_on_not_found = self.module.params['fail_on_not_found'] self.agent = self.module.params['agent'] self.health = self.module.params['health'] self.wait = self.module.params['wait'] self.wait_retries = self.module.params['wait_retries'] self.wait_interval = self.module.params['wait_interval'] self._drain = self.module.params['drain'] self.command_results = {} def execute(self, cmd, timeout=200, capture_output=True): """ Executes a HAProxy command by sending a message to a HAProxy's local UNIX socket and waiting up to 'timeout' milliseconds for the response. """ self.client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.client.connect(self.socket) self.client.sendall(to_bytes('%s\n' % cmd)) result = b'' buf = b'' buf = self.client.recv(RECV_SIZE) while buf: result += buf buf = self.client.recv(RECV_SIZE) result = to_text(result, errors='surrogate_or_strict') if capture_output: self.capture_command_output(cmd, result.strip()) self.client.close() return result def capture_command_output(self, cmd, output): """ Capture the output for a command """ if 'command' not in self.command_results: self.command_results['command'] = [] self.command_results['command'].append(cmd) if 'output' not in self.command_results: self.command_results['output'] = [] self.command_results['output'].append(output) def discover_all_backends(self): """ Discover all entries with svname = 'BACKEND' and return a list of their corresponding pxnames """ data = self.execute('show stat', 200, False).lstrip('# ') r = csv.DictReader(data.splitlines()) return tuple(map(lambda d: d['pxname'], filter(lambda d: d['svname'] == 'BACKEND', r))) def discover_version(self): """ Attempt to extract the haproxy version. Return a tuple containing major and minor version. """ data = self.execute('show info', 200, False) lines = data.splitlines() line = [x for x in lines if 'Version:' in x] try: version_values = line[0].partition(':')[2].strip().split('.', 3) version = (int(version_values[0]), int(version_values[1])) except (ValueError, TypeError, IndexError): version = None return version def execute_for_backends(self, cmd, pxname, svname, wait_for_status=None): """ Run some command on the specified backends. If no backends are provided they will be discovered automatically (all backends) """ # Discover backends if none are given if pxname is None: backends = self.discover_all_backends() else: backends = [pxname] # Run the command for each requested backend for backend in backends: # Fail when backends were not found state = self.get_state_for(backend, svname) if (self.fail_on_not_found) and state is None: self.module.fail_json( msg="The specified backend '%s/%s' was not found!" % (backend, svname)) if state is not None: self.execute(Template(cmd).substitute(pxname=backend, svname=svname)) if self.wait: self.wait_until_status(backend, svname, wait_for_status) def get_state_for(self, pxname, svname): """ Find the state of specific services. When pxname is not set, get all backends for a specific host. Returns a list of dictionaries containing the status and weight for those services. """ data = self.execute('show stat', 200, False).lstrip('# ') r = csv.DictReader(data.splitlines()) state = tuple( map( lambda d: {'status': d['status'], 'weight': d['weight'], 'scur': d['scur']}, filter(lambda d: (pxname is None or d['pxname'] == pxname) and d['svname'] == svname, r) ) ) return state or None def wait_until_status(self, pxname, svname, status): """ Wait for a service to reach the specified status. Try RETRIES times with INTERVAL seconds of sleep in between. If the service has not reached the expected status in that time, the module will fail. If the service was not found, the module will fail. """ for i in range(1, self.wait_retries): state = self.get_state_for(pxname, svname) # We can assume there will only be 1 element in state because both svname and pxname are always set when we get here # When using track we get a status like this: MAINT (via pxname/svname) so we need to do substring matching if status in state[0]['status']: if not self._drain or state[0]['scur'] == '0': return True time.sleep(self.wait_interval) self.module.fail_json(msg="server %s/%s not status '%s' after %d retries. Aborting." % (pxname, svname, status, self.wait_retries)) def enabled(self, host, backend, weight): """ Enabled action, marks server to UP and checks are re-enabled, also supports to get current weight for server (default) and set the weight for haproxy backend server when provides. """ cmd = "get weight $pxname/$svname; enable server $pxname/$svname" if self.agent: cmd += "; enable agent $pxname/$svname" if self.health: cmd += "; enable health $pxname/$svname" if weight: cmd += "; set weight $pxname/$svname %s" % weight self.execute_for_backends(cmd, backend, host, 'UP') def disabled(self, host, backend, shutdown_sessions): """ Disabled action, marks server to DOWN for maintenance. In this mode, no more checks will be performed on the server until it leaves maintenance, also it shutdown sessions while disabling backend host server. """ cmd = "get weight $pxname/$svname" if self.agent: cmd += "; disable agent $pxname/$svname" if self.health: cmd += "; disable health $pxname/$svname" cmd += "; disable server $pxname/$svname" if shutdown_sessions: cmd += "; shutdown sessions server $pxname/$svname" self.execute_for_backends(cmd, backend, host, 'MAINT') def drain(self, host, backend, status='DRAIN'): """ Drain action, sets the server to DRAIN mode. In this mode, the server will not accept any new connections other than those that are accepted via persistence. """ haproxy_version = self.discover_version() # check if haproxy version supports DRAIN state (starting with 1.5) if haproxy_version and (1, 5) <= haproxy_version: cmd = "set server $pxname/$svname state drain" self.execute_for_backends(cmd, backend, host, "DRAIN") if status == "MAINT": self.disabled(host, backend, self.shutdown_sessions) def act(self): """ Figure out what you want to do from ansible, and then do it. """ # Get the state before the run self.command_results['state_before'] = self.get_state_for(self.backend, self.host) # toggle enable/disable server if self.state == 'enabled': self.enabled(self.host, self.backend, self.weight) elif self.state == 'disabled' and self._drain: self.drain(self.host, self.backend, status='MAINT') elif self.state == 'disabled': self.disabled(self.host, self.backend, self.shutdown_sessions) elif self.state == 'drain': self.drain(self.host, self.backend) else: self.module.fail_json(msg="unknown state specified: '%s'" % self.state) # Get the state after the run self.command_results['state_after'] = self.get_state_for(self.backend, self.host) # Report change status self.command_results['changed'] = (self.command_results['state_before'] != self.command_results['state_after']) self.module.exit_json(**self.command_results) def main(): # load ansible module object module = AnsibleModule( argument_spec=dict( state=dict(type='str', required=True, choices=ACTION_CHOICES), host=dict(type='str', required=True), backend=dict(type='str'), weight=dict(type='str'), socket=dict(type='path', default=DEFAULT_SOCKET_LOCATION), shutdown_sessions=dict(type='bool', default=False), fail_on_not_found=dict(type='bool', default=False), health=dict(type='bool', default=False), agent=dict(type='bool', default=False), wait=dict(type='bool', default=False), wait_retries=dict(type='int', default=WAIT_RETRIES), wait_interval=dict(type='int', default=WAIT_INTERVAL), drain=dict(type='bool', default=False), ), ) if not socket: module.fail_json(msg="unable to locate haproxy socket") ansible_haproxy = HAProxy(module) ansible_haproxy.act() if __name__ == '__main__': main()
36.153846
130
0.641978
from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: haproxy short_description: Enable, disable, and set weights for HAProxy backend servers using socket commands author: - Ravi Bhure (@ravibhure) description: - Enable, disable, drain and set weights for HAProxy backend servers using socket commands. notes: - Enable, disable and drain commands are restricted and can only be issued on sockets configured for level 'admin'. For example, you can add the line 'stats socket /var/run/haproxy.sock level admin' to the general section of haproxy.cfg. See U(http://haproxy.1wt.eu/download/1.5/doc/configuration.txt). - Depends on netcat (nc) being available; you need to install the appropriate package for your operating system before this module can be used. options: backend: description: - Name of the HAProxy backend pool. - If this parameter is unset, it will be auto-detected. type: str drain: description: - Wait until the server has no active connections or until the timeout determined by wait_interval and wait_retries is reached. - Continue only after the status changes to 'MAINT'. - This overrides the shutdown_sessions option. type: bool default: false host: description: - Name of the backend host to change. type: str required: true shutdown_sessions: description: - When disabling a server, immediately terminate all the sessions attached to the specified server. - This can be used to terminate long-running sessions after a server is put into maintenance mode. Overridden by the drain option. type: bool default: no socket: description: - Path to the HAProxy socket file. type: path default: /var/run/haproxy.sock state: description: - Desired state of the provided backend host. - Note that C(drain) state was added in version 2.4. - It is supported only by HAProxy version 1.5 or later, - When used on versions < 1.5, it will be ignored. type: str required: true choices: [ disabled, drain, enabled ] agent: description: - Disable/enable agent checks (depending on I(state) value). type: bool default: no version_added: 1.0.0 health: description: - Disable/enable health checks (depending on I(state) value). type: bool default: no version_added: "1.0.0" fail_on_not_found: description: - Fail whenever trying to enable/disable a backend host that does not exist type: bool default: no wait: description: - Wait until the server reports a status of 'UP' when C(state=enabled), status of 'MAINT' when C(state=disabled) or status of 'DRAIN' when C(state=drain) type: bool default: no wait_interval: description: - Number of seconds to wait between retries. type: int default: 5 wait_retries: description: - Number of times to check for status after changing the state. type: int default: 25 weight: description: - The value passed in argument. - If the value ends with the `%` sign, then the new weight will be relative to the initially configured weight. - Relative weights are only permitted between 0 and 100% and absolute weights are permitted between 0 and 256. type: str ''' EXAMPLES = r''' - name: Disable server in 'www' backend pool community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' backend: www - name: Disable server in 'www' backend pool, also stop health/agent checks community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' health: yes agent: yes - name: Disable server without backend pool name (apply to all available backend pool) community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' - name: Disable server, provide socket file community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' socket: /var/run/haproxy.sock backend: www - name: Disable server, provide socket file, wait until status reports in maintenance community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' socket: /var/run/haproxy.sock backend: www wait: yes # Place server in drain mode, providing a socket file. Then check the server's # status every minute to see if it changes to maintenance mode, continuing if it # does in an hour and failing otherwise. - community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' socket: /var/run/haproxy.sock backend: www wait: yes drain: yes wait_interval: 60 wait_retries: 60 - name: Disable backend server in 'www' backend pool and drop open sessions to it community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' backend: www socket: /var/run/haproxy.sock shutdown_sessions: yes - name: Disable server without backend pool name (apply to all available backend pool) but fail when the backend host is not found community.general.haproxy: state: disabled host: '{{ inventory_hostname }}' fail_on_not_found: yes - name: Enable server in 'www' backend pool community.general.haproxy: state: enabled host: '{{ inventory_hostname }}' backend: www - name: Enable server in 'www' backend pool wait until healthy community.general.haproxy: state: enabled host: '{{ inventory_hostname }}' backend: www wait: yes - name: Enable server in 'www' backend pool wait until healthy. Retry 10 times with intervals of 5 seconds to retrieve the health community.general.haproxy: state: enabled host: '{{ inventory_hostname }}' backend: www wait: yes wait_retries: 10 wait_interval: 5 - name: Enable server in 'www' backend pool with change server(s) weight community.general.haproxy: state: enabled host: '{{ inventory_hostname }}' socket: /var/run/haproxy.sock weight: 10 backend: www - name: Set the server in 'www' backend pool to drain mode community.general.haproxy: state: drain host: '{{ inventory_hostname }}' socket: /var/run/haproxy.sock backend: www ''' import csv import socket import time from string import Template from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.common.text.converters import to_bytes, to_text DEFAULT_SOCKET_LOCATION = "/var/run/haproxy.sock" RECV_SIZE = 1024 ACTION_CHOICES = ['enabled', 'disabled', 'drain'] WAIT_RETRIES = 25 WAIT_INTERVAL = 5 ###################################################################### class TimeoutException(Exception): pass class HAProxy(object): def __init__(self, module): self.module = module self.state = self.module.params['state'] self.host = self.module.params['host'] self.backend = self.module.params['backend'] self.weight = self.module.params['weight'] self.socket = self.module.params['socket'] self.shutdown_sessions = self.module.params['shutdown_sessions'] self.fail_on_not_found = self.module.params['fail_on_not_found'] self.agent = self.module.params['agent'] self.health = self.module.params['health'] self.wait = self.module.params['wait'] self.wait_retries = self.module.params['wait_retries'] self.wait_interval = self.module.params['wait_interval'] self._drain = self.module.params['drain'] self.command_results = {} def execute(self, cmd, timeout=200, capture_output=True): self.client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.client.connect(self.socket) self.client.sendall(to_bytes('%s\n' % cmd)) result = b'' buf = b'' buf = self.client.recv(RECV_SIZE) while buf: result += buf buf = self.client.recv(RECV_SIZE) result = to_text(result, errors='surrogate_or_strict') if capture_output: self.capture_command_output(cmd, result.strip()) self.client.close() return result def capture_command_output(self, cmd, output): if 'command' not in self.command_results: self.command_results['command'] = [] self.command_results['command'].append(cmd) if 'output' not in self.command_results: self.command_results['output'] = [] self.command_results['output'].append(output) def discover_all_backends(self): data = self.execute('show stat', 200, False).lstrip(' r = csv.DictReader(data.splitlines()) return tuple(map(lambda d: d['pxname'], filter(lambda d: d['svname'] == 'BACKEND', r))) def discover_version(self): data = self.execute('show info', 200, False) lines = data.splitlines() line = [x for x in lines if 'Version:' in x] try: version_values = line[0].partition(':')[2].strip().split('.', 3) version = (int(version_values[0]), int(version_values[1])) except (ValueError, TypeError, IndexError): version = None return version def execute_for_backends(self, cmd, pxname, svname, wait_for_status=None): # Discover backends if none are given if pxname is None: backends = self.discover_all_backends() else: backends = [pxname] # Run the command for each requested backend for backend in backends: # Fail when backends were not found state = self.get_state_for(backend, svname) if (self.fail_on_not_found) and state is None: self.module.fail_json( msg="The specified backend '%s/%s' was not found!" % (backend, svname)) if state is not None: self.execute(Template(cmd).substitute(pxname=backend, svname=svname)) if self.wait: self.wait_until_status(backend, svname, wait_for_status) def get_state_for(self, pxname, svname): data = self.execute('show stat', 200, False).lstrip(' r = csv.DictReader(data.splitlines()) state = tuple( map( lambda d: {'status': d['status'], 'weight': d['weight'], 'scur': d['scur']}, filter(lambda d: (pxname is None or d['pxname'] == pxname) and d['svname'] == svname, r) ) ) return state or None def wait_until_status(self, pxname, svname, status): for i in range(1, self.wait_retries): state = self.get_state_for(pxname, svname) # We can assume there will only be 1 element in state because both svname and pxname are always set when we get here # When using track we get a status like this: MAINT (via pxname/svname) so we need to do substring matching if status in state[0]['status']: if not self._drain or state[0]['scur'] == '0': return True time.sleep(self.wait_interval) self.module.fail_json(msg="server %s/%s not status '%s' after %d retries. Aborting." % (pxname, svname, status, self.wait_retries)) def enabled(self, host, backend, weight): cmd = "get weight $pxname/$svname; enable server $pxname/$svname" if self.agent: cmd += "; enable agent $pxname/$svname" if self.health: cmd += "; enable health $pxname/$svname" if weight: cmd += "; set weight $pxname/$svname %s" % weight self.execute_for_backends(cmd, backend, host, 'UP') def disabled(self, host, backend, shutdown_sessions): cmd = "get weight $pxname/$svname" if self.agent: cmd += "; disable agent $pxname/$svname" if self.health: cmd += "; disable health $pxname/$svname" cmd += "; disable server $pxname/$svname" if shutdown_sessions: cmd += "; shutdown sessions server $pxname/$svname" self.execute_for_backends(cmd, backend, host, 'MAINT') def drain(self, host, backend, status='DRAIN'): haproxy_version = self.discover_version() # check if haproxy version supports DRAIN state (starting with 1.5) if haproxy_version and (1, 5) <= haproxy_version: cmd = "set server $pxname/$svname state drain" self.execute_for_backends(cmd, backend, host, "DRAIN") if status == "MAINT": self.disabled(host, backend, self.shutdown_sessions) def act(self): # Get the state before the run self.command_results['state_before'] = self.get_state_for(self.backend, self.host) # toggle enable/disable server if self.state == 'enabled': self.enabled(self.host, self.backend, self.weight) elif self.state == 'disabled' and self._drain: self.drain(self.host, self.backend, status='MAINT') elif self.state == 'disabled': self.disabled(self.host, self.backend, self.shutdown_sessions) elif self.state == 'drain': self.drain(self.host, self.backend) else: self.module.fail_json(msg="unknown state specified: '%s'" % self.state) # Get the state after the run self.command_results['state_after'] = self.get_state_for(self.backend, self.host) # Report change status self.command_results['changed'] = (self.command_results['state_before'] != self.command_results['state_after']) self.module.exit_json(**self.command_results) def main(): # load ansible module object module = AnsibleModule( argument_spec=dict( state=dict(type='str', required=True, choices=ACTION_CHOICES), host=dict(type='str', required=True), backend=dict(type='str'), weight=dict(type='str'), socket=dict(type='path', default=DEFAULT_SOCKET_LOCATION), shutdown_sessions=dict(type='bool', default=False), fail_on_not_found=dict(type='bool', default=False), health=dict(type='bool', default=False), agent=dict(type='bool', default=False), wait=dict(type='bool', default=False), wait_retries=dict(type='int', default=WAIT_RETRIES), wait_interval=dict(type='int', default=WAIT_INTERVAL), drain=dict(type='bool', default=False), ), ) if not socket: module.fail_json(msg="unable to locate haproxy socket") ansible_haproxy = HAProxy(module) ansible_haproxy.act() if __name__ == '__main__': main()
true
true
f73603a8189df32a0e6bb0bedf9ab460c5707be4
3,632
py
Python
bot.py
austin1965/nuub_bot
08fce234730ce506273199ca9c5c2a5f6e8e925a
[ "MIT" ]
null
null
null
bot.py
austin1965/nuub_bot
08fce234730ce506273199ca9c5c2a5f6e8e925a
[ "MIT" ]
null
null
null
bot.py
austin1965/nuub_bot
08fce234730ce506273199ca9c5c2a5f6e8e925a
[ "MIT" ]
null
null
null
import discord from discord.ext import commands from helpers.logHelper import logger import os import logging from pymongo import MongoClient from helpers.getPrefix import getPrefix import ast from helpers.getWeather import getWeather import time from pretty_help import PrettyHelp logging.basicConfig(level=logging.INFO) DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None) MONGODB = os.environ.get("MONGODB", None) intents = discord.Intents.default() intents.members = True bot = commands.Bot(command_prefix="nb.", help_command=PrettyHelp(), intents=intents) # bot = commands.Bot(command_prefix='*', help_command=None) client = MongoClient(MONGODB) db = client["discord"] collection = db["bot"] all_categories = [category for category in os.listdir("./cogs")] print(all_categories) for category in all_categories: for filename in os.listdir(f"./cogs/{category}"): try: if filename.endswith(".py"): bot.load_extension(f"cogs.{category}.{filename[:-3]}") logger.info(f"Succesfully Loaded Cog: {filename}") else: print(f"Unable to load {filename}") logger.warning( f"Unable to load {filename}, is it suppose to be in cog directory?" ) except Exception as e: logger.warning(f"Unable to load cog: {e}") """ check for frequency data in mongo and create a doc for it if it doesnt exist """ if not collection.find_one({"_id": "word_command_freq"}): freq_data_exist = collection.find_one({"_id": "word_command_freq"}) collection.insert_one({"_id": "word_command_freq"}) if not collection.find_one({"_id": "paper_trading_accounts"}): freq_data_exist = collection.find_one({"_id": "paper_trading_accounts"}) collection.insert_one({"_id": "paper_trading_accounts"}) @bot.event async def on_message(message): user = message.author contents = message.content.split(" ") word = contents[0] member = str(message.author) if user.bot: pass elif not word: print("no words to add") else: try: if "." in word: word = word.replace(".", "(Dot)") if "$" in word: word = word.replace("$", "(Dollar_Sign)") except Exception as e: print(str(e) + "Caught in on_message") logger.warning(e) print(member + ": " + word) # is_in_word_command_freq=collection.find_one({"_id":"word_command_freq",word:{"$size": 0}}) # print(is_in_word_command_freq) if collection.find_one({"_id": "word_command_freq", word: {"$exists": True}}): collection.update_one({"_id": "word_command_freq"}, {"$inc": {word: 1}}) print("incremented freq value " + word + " by 1 in word_command_freq doc") else: print(collection.update({"_id": "word_command_freq"}, {"$set": {word: 1}})) print("added " + word + " to word_command_freq") # print(collection.find_one({"_id": "word_command_freq"})) await bot.process_commands(message) @bot.event async def on_guild_join(guild): guild_id = guild.id collection.insert_one({"_id": guild_id, "prefix": ","}) print("done") async def latency(ctx): time_1 = time.perf_counter() await ctx.trigger_typing() time_2 = time.perf_counter() ping = round((time_2 - time_1) * 1000) await ctx.send(f"ping = {ping}") try: bot.run(DISCORD_TOKEN) logger.info("Bot Is Off\n----------------------------------- END OF SESSION") except Exception as e: logger.warning(f"Bot Failed to initialise: {e}")
34.590476
100
0.638491
import discord from discord.ext import commands from helpers.logHelper import logger import os import logging from pymongo import MongoClient from helpers.getPrefix import getPrefix import ast from helpers.getWeather import getWeather import time from pretty_help import PrettyHelp logging.basicConfig(level=logging.INFO) DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None) MONGODB = os.environ.get("MONGODB", None) intents = discord.Intents.default() intents.members = True bot = commands.Bot(command_prefix="nb.", help_command=PrettyHelp(), intents=intents) client = MongoClient(MONGODB) db = client["discord"] collection = db["bot"] all_categories = [category for category in os.listdir("./cogs")] print(all_categories) for category in all_categories: for filename in os.listdir(f"./cogs/{category}"): try: if filename.endswith(".py"): bot.load_extension(f"cogs.{category}.{filename[:-3]}") logger.info(f"Succesfully Loaded Cog: {filename}") else: print(f"Unable to load {filename}") logger.warning( f"Unable to load {filename}, is it suppose to be in cog directory?" ) except Exception as e: logger.warning(f"Unable to load cog: {e}") if not collection.find_one({"_id": "word_command_freq"}): freq_data_exist = collection.find_one({"_id": "word_command_freq"}) collection.insert_one({"_id": "word_command_freq"}) if not collection.find_one({"_id": "paper_trading_accounts"}): freq_data_exist = collection.find_one({"_id": "paper_trading_accounts"}) collection.insert_one({"_id": "paper_trading_accounts"}) @bot.event async def on_message(message): user = message.author contents = message.content.split(" ") word = contents[0] member = str(message.author) if user.bot: pass elif not word: print("no words to add") else: try: if "." in word: word = word.replace(".", "(Dot)") if "$" in word: word = word.replace("$", "(Dollar_Sign)") except Exception as e: print(str(e) + "Caught in on_message") logger.warning(e) print(member + ": " + word) if collection.find_one({"_id": "word_command_freq", word: {"$exists": True}}): collection.update_one({"_id": "word_command_freq"}, {"$inc": {word: 1}}) print("incremented freq value " + word + " by 1 in word_command_freq doc") else: print(collection.update({"_id": "word_command_freq"}, {"$set": {word: 1}})) print("added " + word + " to word_command_freq") await bot.process_commands(message) @bot.event async def on_guild_join(guild): guild_id = guild.id collection.insert_one({"_id": guild_id, "prefix": ","}) print("done") async def latency(ctx): time_1 = time.perf_counter() await ctx.trigger_typing() time_2 = time.perf_counter() ping = round((time_2 - time_1) * 1000) await ctx.send(f"ping = {ping}") try: bot.run(DISCORD_TOKEN) logger.info("Bot Is Off\n----------------------------------- END OF SESSION") except Exception as e: logger.warning(f"Bot Failed to initialise: {e}")
true
true
f736049bbe2c9e2b1e12f6afa0bfd0873d6a897f
1,415
py
Python
huaweicloud-sdk-cbr/setup.py
githubmilesma/huaweicloud-sdk-python-v3
9d9449ed68a609ca65f0aa50b5b2a1c28445bf03
[ "Apache-2.0" ]
null
null
null
huaweicloud-sdk-cbr/setup.py
githubmilesma/huaweicloud-sdk-python-v3
9d9449ed68a609ca65f0aa50b5b2a1c28445bf03
[ "Apache-2.0" ]
null
null
null
huaweicloud-sdk-cbr/setup.py
githubmilesma/huaweicloud-sdk-python-v3
9d9449ed68a609ca65f0aa50b5b2a1c28445bf03
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 from os import path from setuptools import setup, find_packages NAME = "huaweicloudsdkcbr" VERSION = "3.0.43-rc" AUTHOR = "HuaweiCloud SDK" AUTHOR_EMAIL = "hwcloudsdk@huawei.com" URL = "https://github.com/huaweicloud/huaweicloud-sdk-python-v3" DESCRIPTION = "CBR" this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README_PYPI.md'), encoding='utf-8') as f: LONG_DESCRIPTION = f.read() REQUIRES = ["huaweicloudsdkcore"] setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type='text/markdown', author=AUTHOR, author_email=AUTHOR_EMAIL, license="Apache LICENSE 2.0", url=URL, keywords=["huaweicloud", "sdk", "CBR"], packages=find_packages(exclude=["tests*"]), install_requires=REQUIRES, include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development' ] )
30.76087
78
0.670671
from os import path from setuptools import setup, find_packages NAME = "huaweicloudsdkcbr" VERSION = "3.0.43-rc" AUTHOR = "HuaweiCloud SDK" AUTHOR_EMAIL = "hwcloudsdk@huawei.com" URL = "https://github.com/huaweicloud/huaweicloud-sdk-python-v3" DESCRIPTION = "CBR" this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README_PYPI.md'), encoding='utf-8') as f: LONG_DESCRIPTION = f.read() REQUIRES = ["huaweicloudsdkcore"] setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type='text/markdown', author=AUTHOR, author_email=AUTHOR_EMAIL, license="Apache LICENSE 2.0", url=URL, keywords=["huaweicloud", "sdk", "CBR"], packages=find_packages(exclude=["tests*"]), install_requires=REQUIRES, include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development' ] )
true
true
f736056e2d0a2321511326a08517deb01be3f66e
7,202
py
Python
metpy/calc/tests/test_basic.py
jtwhite79/MetPy
8f1880be1ee98c17cd00ae556324386d2a6301ac
[ "BSD-3-Clause" ]
null
null
null
metpy/calc/tests/test_basic.py
jtwhite79/MetPy
8f1880be1ee98c17cd00ae556324386d2a6301ac
[ "BSD-3-Clause" ]
null
null
null
metpy/calc/tests/test_basic.py
jtwhite79/MetPy
8f1880be1ee98c17cd00ae556324386d2a6301ac
[ "BSD-3-Clause" ]
1
2021-06-15T07:29:05.000Z
2021-06-15T07:29:05.000Z
# Copyright (c) 2008-2015 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause import numpy as np from numpy.testing import assert_array_equal from metpy.units import units from metpy.testing import assert_almost_equal, assert_array_almost_equal from metpy.calc.basic import * # noqa def test_wind_comps_basic(): 'Test the basic wind component calculation.' speed = np.array([4, 4, 4, 4, 25, 25, 25, 25, 10.]) * units.mph dirs = np.array([0, 45, 90, 135, 180, 225, 270, 315, 360]) * units.deg s2 = np.sqrt(2.) u, v = get_wind_components(speed, dirs) true_u = np.array([0, -4 / s2, -4, -4 / s2, 0, 25 / s2, 25, 25 / s2, 0]) * units.mph true_v = np.array([-4, -4 / s2, 0, 4 / s2, 25, 25 / s2, 0, -25 / s2, -10]) * units.mph assert_array_almost_equal(true_u, u, 4) assert_array_almost_equal(true_v, v, 4) def test_wind_comps_scalar(): 'Test scalar wind components' u, v = get_wind_components(8 * units('m/s'), 150 * units.deg) assert_almost_equal(u, -4 * units('m/s'), 3) assert_almost_equal(v, 6.9282 * units('m/s'), 3) def test_speed(): 'Basic test of wind speed calculation' u = np.array([4., 2., 0., 0.]) * units('m/s') v = np.array([0., 2., 4., 0.]) * units('m/s') speed = get_wind_speed(u, v) s2 = np.sqrt(2.) true_speed = np.array([4., 2 * s2, 4., 0.]) * units('m/s') assert_array_almost_equal(true_speed, speed, 4) def test_dir(): 'Basic test of wind direction calculation' u = np.array([4., 2., 0., 0.]) * units('m/s') v = np.array([0., 2., 4., 0.]) * units('m/s') direc = get_wind_dir(u, v) true_dir = np.array([270., 225., 180., 270.]) * units.deg assert_array_almost_equal(true_dir, direc, 4) def test_speed_dir_roundtrip(): 'Convert from wind speed and direction to u,v and back' # Test each quadrant of the whole circle wspd = np.array([15., 5., 2., 10.]) * units.meters / units.seconds wdir = np.array([160., 30., 225., 350.]) * units.degrees u, v = get_wind_components(wspd, wdir) wdir_out = get_wind_dir(u, v) wspd_out = get_wind_speed(u, v) assert_array_almost_equal(wspd, wspd_out, 4) assert_array_almost_equal(wdir, wdir_out, 4) def test_scalar_speed(): 'Test wind speed with scalars' s = get_wind_speed(-3. * units('m/s'), -4. * units('m/s')) assert_almost_equal(s, 5. * units('m/s'), 3) def test_scalar_dir(): 'Test wind direction with scalars' d = get_wind_dir(3. * units('m/s'), 4. * units('m/s')) assert_almost_equal(d, 216.870 * units.deg, 3) def test_windchill_scalar(): 'Test wind chill with scalars' wc = windchill(-5 * units.degC, 35 * units('m/s')) assert_almost_equal(wc, -18.9357 * units.degC, 0) def test_windchill_basic(): 'Test the basic wind chill calculation.' temp = np.array([40, -10, -45, 20]) * units.degF speed = np.array([5, 55, 25, 15]) * units.mph wc = windchill(temp, speed) values = np.array([36, -46, -84, 6]) * units.degF assert_array_almost_equal(wc, values, 0) def test_windchill_invalid(): 'Test for values that should be masked.' temp = np.array([10, 51, 49, 60, 80, 81]) * units.degF speed = np.array([4, 4, 3, 1, 10, 39]) * units.mph wc = windchill(temp, speed) mask = np.array([False, True, True, True, True, True]) assert_array_equal(wc.mask, mask) def test_windchill_undefined_flag(): 'Tests whether masking values can be disabled.' temp = units.Quantity(np.ma.array([49, 50, 49, 60, 80, 81]), units.degF) speed = units.Quantity(([4, 4, 3, 1, 10, 39]), units.mph) wc = windchill(temp, speed, mask_undefined=False) mask = np.array([False] * 6) assert_array_equal(wc.mask, mask) def test_windchill_face_level(): 'Tests using the face_level flag' temp = np.array([20, 0, -20, -40]) * units.degF speed = np.array([15, 30, 45, 60]) * units.mph wc = windchill(temp, speed, face_level_winds=True) values = np.array([3, -30, -64, -98]) * units.degF assert_array_almost_equal(wc, values, 0) def test_heat_index_basic(): 'Test the basic heat index calculation.' temp = np.array([80, 88, 92, 110]) * units.degF rh = np.array([40, 100, 70, 40]) * units.percent hi = heat_index(temp, rh) values = np.array([80, 121, 112, 136]) * units.degF assert_array_almost_equal(hi, values, 0) def test_heat_index_scalar(): 'Test heat index using scalars' hi = heat_index(96 * units.degF, 65 * units.percent) assert_almost_equal(hi, 121 * units.degF, 0) def test_heat_index_invalid(): 'Test for values that should be masked.' temp = np.array([80, 88, 92, 79, 30, 81]) * units.degF rh = np.array([40, 39, 2, 70, 50, 39]) * units.percent hi = heat_index(temp, rh) mask = np.array([False, True, True, True, True, True]) assert_array_equal(hi.mask, mask) def test_heat_index_undefined_flag(): 'Tests whether masking values can be disabled.' temp = units.Quantity(np.ma.array([80, 88, 92, 79, 30, 81]), units.degF) rh = np.ma.array([40, 39, 2, 70, 50, 39]) * units.percent hi = heat_index(temp, rh, mask_undefined=False) mask = np.array([False] * 6) assert_array_equal(hi.mask, mask) def test_heat_index_units(): 'Test units coming out of heat index' temp = units.Quantity([35., 20.], units.degC) rh = 70 * units.percent hi = heat_index(temp, rh) assert_almost_equal(hi.to('degC'), units.Quantity([50.3405, np.nan], units.degC), 4) def test_heat_index_ratio(): 'Test giving humidity as number [0, 1]' temp = units.Quantity([35., 20.], units.degC) rh = 0.7 hi = heat_index(temp, rh) assert_almost_equal(hi.to('degC'), units.Quantity([50.3405, np.nan], units.degC), 4) # class TestIrrad(object): # def test_basic(self): # 'Test the basic solar irradiance calculation.' # from datetime import date # d = date(2008, 9, 28) # lat = 35.25 # hours = np.linspace(6,18,10) # s = solar_irradiance(lat, d, hours) # values = np.array([0., 344.1, 682.6, 933.9, 1067.6, 1067.6, 933.9, # 682.6, 344.1, 0.]) # assert_array_almost_equal(s, values, 1) # def test_scalar(self): # from datetime import date # d = date(2008, 9, 28) # lat = 35.25 # hour = 9.5 # s = solar_irradiance(lat, d, hour) # assert_almost_equal(s, 852.1, 1) # def test_invalid(self): # 'Test for values that should be masked.' # from datetime import date # d = date(2008, 9, 28) # lat = 35.25 # hours = np.linspace(0,22,12) # s = solar_irradiance(lat, d, hours) # mask = np.array([ True, True, True, True, False, False, False, # False, False, True, True, True]) # assert_array_equal(s.mask, mask) def test_pressure_to_heights_basic(): 'Tests basic pressure to height calculation.' pressures = np.array([975.2, 987.5, 956., 943.]) * units.mbar heights = pressure_to_height_std(pressures) values = np.array([321.5, 216.5, 487.6, 601.7]) * units.meter assert_almost_equal(heights, values, 1)
32.008889
90
0.62802
import numpy as np from numpy.testing import assert_array_equal from metpy.units import units from metpy.testing import assert_almost_equal, assert_array_almost_equal from metpy.calc.basic import * def test_wind_comps_basic(): speed = np.array([4, 4, 4, 4, 25, 25, 25, 25, 10.]) * units.mph dirs = np.array([0, 45, 90, 135, 180, 225, 270, 315, 360]) * units.deg s2 = np.sqrt(2.) u, v = get_wind_components(speed, dirs) true_u = np.array([0, -4 / s2, -4, -4 / s2, 0, 25 / s2, 25, 25 / s2, 0]) * units.mph true_v = np.array([-4, -4 / s2, 0, 4 / s2, 25, 25 / s2, 0, -25 / s2, -10]) * units.mph assert_array_almost_equal(true_u, u, 4) assert_array_almost_equal(true_v, v, 4) def test_wind_comps_scalar(): u, v = get_wind_components(8 * units('m/s'), 150 * units.deg) assert_almost_equal(u, -4 * units('m/s'), 3) assert_almost_equal(v, 6.9282 * units('m/s'), 3) def test_speed(): u = np.array([4., 2., 0., 0.]) * units('m/s') v = np.array([0., 2., 4., 0.]) * units('m/s') speed = get_wind_speed(u, v) s2 = np.sqrt(2.) true_speed = np.array([4., 2 * s2, 4., 0.]) * units('m/s') assert_array_almost_equal(true_speed, speed, 4) def test_dir(): u = np.array([4., 2., 0., 0.]) * units('m/s') v = np.array([0., 2., 4., 0.]) * units('m/s') direc = get_wind_dir(u, v) true_dir = np.array([270., 225., 180., 270.]) * units.deg assert_array_almost_equal(true_dir, direc, 4) def test_speed_dir_roundtrip(): wspd = np.array([15., 5., 2., 10.]) * units.meters / units.seconds wdir = np.array([160., 30., 225., 350.]) * units.degrees u, v = get_wind_components(wspd, wdir) wdir_out = get_wind_dir(u, v) wspd_out = get_wind_speed(u, v) assert_array_almost_equal(wspd, wspd_out, 4) assert_array_almost_equal(wdir, wdir_out, 4) def test_scalar_speed(): s = get_wind_speed(-3. * units('m/s'), -4. * units('m/s')) assert_almost_equal(s, 5. * units('m/s'), 3) def test_scalar_dir(): d = get_wind_dir(3. * units('m/s'), 4. * units('m/s')) assert_almost_equal(d, 216.870 * units.deg, 3) def test_windchill_scalar(): wc = windchill(-5 * units.degC, 35 * units('m/s')) assert_almost_equal(wc, -18.9357 * units.degC, 0) def test_windchill_basic(): temp = np.array([40, -10, -45, 20]) * units.degF speed = np.array([5, 55, 25, 15]) * units.mph wc = windchill(temp, speed) values = np.array([36, -46, -84, 6]) * units.degF assert_array_almost_equal(wc, values, 0) def test_windchill_invalid(): temp = np.array([10, 51, 49, 60, 80, 81]) * units.degF speed = np.array([4, 4, 3, 1, 10, 39]) * units.mph wc = windchill(temp, speed) mask = np.array([False, True, True, True, True, True]) assert_array_equal(wc.mask, mask) def test_windchill_undefined_flag(): temp = units.Quantity(np.ma.array([49, 50, 49, 60, 80, 81]), units.degF) speed = units.Quantity(([4, 4, 3, 1, 10, 39]), units.mph) wc = windchill(temp, speed, mask_undefined=False) mask = np.array([False] * 6) assert_array_equal(wc.mask, mask) def test_windchill_face_level(): temp = np.array([20, 0, -20, -40]) * units.degF speed = np.array([15, 30, 45, 60]) * units.mph wc = windchill(temp, speed, face_level_winds=True) values = np.array([3, -30, -64, -98]) * units.degF assert_array_almost_equal(wc, values, 0) def test_heat_index_basic(): temp = np.array([80, 88, 92, 110]) * units.degF rh = np.array([40, 100, 70, 40]) * units.percent hi = heat_index(temp, rh) values = np.array([80, 121, 112, 136]) * units.degF assert_array_almost_equal(hi, values, 0) def test_heat_index_scalar(): hi = heat_index(96 * units.degF, 65 * units.percent) assert_almost_equal(hi, 121 * units.degF, 0) def test_heat_index_invalid(): temp = np.array([80, 88, 92, 79, 30, 81]) * units.degF rh = np.array([40, 39, 2, 70, 50, 39]) * units.percent hi = heat_index(temp, rh) mask = np.array([False, True, True, True, True, True]) assert_array_equal(hi.mask, mask) def test_heat_index_undefined_flag(): temp = units.Quantity(np.ma.array([80, 88, 92, 79, 30, 81]), units.degF) rh = np.ma.array([40, 39, 2, 70, 50, 39]) * units.percent hi = heat_index(temp, rh, mask_undefined=False) mask = np.array([False] * 6) assert_array_equal(hi.mask, mask) def test_heat_index_units(): temp = units.Quantity([35., 20.], units.degC) rh = 70 * units.percent hi = heat_index(temp, rh) assert_almost_equal(hi.to('degC'), units.Quantity([50.3405, np.nan], units.degC), 4) def test_heat_index_ratio(): temp = units.Quantity([35., 20.], units.degC) rh = 0.7 hi = heat_index(temp, rh) assert_almost_equal(hi.to('degC'), units.Quantity([50.3405, np.nan], units.degC), 4) def test_pressure_to_heights_basic(): pressures = np.array([975.2, 987.5, 956., 943.]) * units.mbar heights = pressure_to_height_std(pressures) values = np.array([321.5, 216.5, 487.6, 601.7]) * units.meter assert_almost_equal(heights, values, 1)
true
true
f736059c7aa090a309aa5bb0091aa6ddcfd2f100
8,218
py
Python
docs/conf.py
20tab/python-gmaps
f1d316592a7dbd23af3ff758cf37d08dec1572bc
[ "BSD-2-Clause" ]
30
2015-01-01T03:27:58.000Z
2021-09-20T04:17:26.000Z
docs/conf.py
20tab/python-gmaps
f1d316592a7dbd23af3ff758cf37d08dec1572bc
[ "BSD-2-Clause" ]
5
2015-08-21T12:51:42.000Z
2016-10-25T09:32:46.000Z
docs/conf.py
20tab/python-gmaps
f1d316592a7dbd23af3ff758cf37d08dec1572bc
[ "BSD-2-Clause" ]
10
2015-06-25T01:25:28.000Z
2021-12-25T18:35:03.000Z
# -*- coding: utf-8 -*- # # python-gmaps documentation build configuration file, created by # sphinx-quickstart on Thu Oct 3 16:14:10 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # 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. sys.path.insert(0, os.path.abspath('./../src')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # 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', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'python-gmaps' copyright = u'2013, Michał Jaworski' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0.2' # The full version, including alpha/beta/rc tags. release = '0.0.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- 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 = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # 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'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'python-gmapsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto/manual]). latex_documents = [ ('index', 'python-gmaps.tex', u'python-gmaps Documentation', u'Michał Jaworski', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'python-gmaps', u'python-gmaps Documentation', [u'Michał Jaworski'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'python-gmaps', u'python-gmaps Documentation', u'Michał Jaworski', 'python-gmaps', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
31.72973
79
0.71818
import sys import os sys.path.insert(0, os.path.abspath('./../src')) extensions = ['sphinx.ext.autodoc', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'python-gmaps' copyright = u'2013, Michał Jaworski' # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0.2' # The full version, including alpha/beta/rc tags. release = '0.0.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- 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 = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # 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'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'python-gmapsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto/manual]). latex_documents = [ ('index', 'python-gmaps.tex', u'python-gmaps Documentation', u'Michał Jaworski', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'python-gmaps', u'python-gmaps Documentation', [u'Michał Jaworski'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'python-gmaps', u'python-gmaps Documentation', u'Michał Jaworski', 'python-gmaps', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu.
true
true
f7360609ceab8bc60001c9b2b02bcf339b33203d
86,859
py
Python
nova/api/ec2/cloud.py
tbreeds/nova
3f8c69b2ef3eef886e36c0b7f397b83a36a7beb8
[ "Apache-2.0" ]
2
2018-11-18T16:03:18.000Z
2019-05-15T04:34:55.000Z
nova/api/ec2/cloud.py
tbreeds/nova
3f8c69b2ef3eef886e36c0b7f397b83a36a7beb8
[ "Apache-2.0" ]
null
null
null
nova/api/ec2/cloud.py
tbreeds/nova
3f8c69b2ef3eef886e36c0b7f397b83a36a7beb8
[ "Apache-2.0" ]
2
2015-12-28T14:36:29.000Z
2018-11-18T16:03:20.000Z
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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. """ Cloud Controller: Implementation of EC2 REST API calls, which are dispatched to other nodes via AMQP RPC. State is via distributed datastore. """ import base64 import time from oslo_config import cfg from oslo_log import log as logging from oslo_log import versionutils from oslo_utils import timeutils import six from nova.api.ec2 import ec2utils from nova.api.ec2 import inst_state from nova.api.metadata import password from nova.api.openstack import extensions from nova.api import validator from nova import availability_zones from nova import block_device from nova.cloudpipe import pipelib from nova import compute from nova.compute import api as compute_api from nova.compute import vm_states from nova import exception from nova.i18n import _ from nova.i18n import _LI from nova.i18n import _LW from nova.image import s3 from nova import network from nova.network.security_group import neutron_driver from nova.network.security_group import openstack_driver from nova import objects from nova import quota from nova import servicegroup from nova import utils from nova import volume ec2_opts = [ cfg.StrOpt('ec2_host', default='$my_ip', help='The IP address of the EC2 API server'), cfg.StrOpt('ec2_dmz_host', default='$my_ip', help='The internal IP address of the EC2 API server'), cfg.IntOpt('ec2_port', default=8773, min=1, max=65535, help='The port of the EC2 API server'), cfg.StrOpt('ec2_scheme', default='http', choices=('http', 'https'), help='The protocol to use when connecting to the EC2 API ' 'server'), cfg.StrOpt('ec2_path', default='/', help='The path prefix used to call the ec2 API server'), cfg.ListOpt('region_list', default=[], help='List of region=fqdn pairs separated by commas'), ] CONF = cfg.CONF CONF.register_opts(ec2_opts) CONF.import_opt('my_ip', 'nova.netconf') CONF.import_opt('vpn_key_suffix', 'nova.cloudpipe.pipelib') CONF.import_opt('internal_service_availability_zone', 'nova.availability_zones') LOG = logging.getLogger(__name__) QUOTAS = quota.QUOTAS # EC2 ID can return the following error codes: # http://docs.aws.amazon.com/AWSEC2/latest/APIReference/api-error-codes.html # Validate methods are split to return valid EC2 error codes for different # resource types def _validate_ec2_id(val): if not validator.validate_str()(val): raise exception.InvalidEc2Id(ec2_id=val) ec2utils.ec2_id_to_id(val) def validate_volume_id(volume_id): try: _validate_ec2_id(volume_id) except exception.InvalidEc2Id: raise exception.InvalidVolumeIDMalformed(volume_id=volume_id) def validate_instance_id(instance_id): try: _validate_ec2_id(instance_id) except exception.InvalidEc2Id: raise exception.InvalidInstanceIDMalformed(instance_id=instance_id) # EC2 API can return the following values as documented in the EC2 API # http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ # ApiReference-ItemType-InstanceStateType.html # pending 0 | running 16 | shutting-down 32 | terminated 48 | stopping 64 | # stopped 80 _STATE_DESCRIPTION_MAP = { None: inst_state.PENDING, vm_states.ACTIVE: inst_state.RUNNING, vm_states.BUILDING: inst_state.PENDING, vm_states.DELETED: inst_state.TERMINATED, vm_states.SOFT_DELETED: inst_state.TERMINATED, vm_states.STOPPED: inst_state.STOPPED, vm_states.PAUSED: inst_state.PAUSE, vm_states.SUSPENDED: inst_state.SUSPEND, vm_states.RESCUED: inst_state.RESCUE, vm_states.RESIZED: inst_state.RESIZE, } def _state_description(vm_state, _shutdown_terminate): """Map the vm state to the server status string.""" # Note(maoy): We do not provide EC2 compatibility # in shutdown_terminate flag behavior. So we ignore # it here. name = _STATE_DESCRIPTION_MAP.get(vm_state, vm_state) return {'code': inst_state.name_to_code(name), 'name': name} def _parse_block_device_mapping(bdm): """Parse BlockDeviceMappingItemType into flat hash BlockDevicedMapping.<N>.DeviceName BlockDevicedMapping.<N>.Ebs.SnapshotId BlockDevicedMapping.<N>.Ebs.VolumeSize BlockDevicedMapping.<N>.Ebs.DeleteOnTermination BlockDevicedMapping.<N>.Ebs.NoDevice BlockDevicedMapping.<N>.VirtualName => remove .Ebs and allow volume id in SnapshotId """ ebs = bdm.pop('ebs', None) if ebs: ec2_id = ebs.pop('snapshot_id', None) if ec2_id: if ec2_id.startswith('snap-'): bdm['snapshot_id'] = ec2utils.ec2_snap_id_to_uuid(ec2_id) elif ec2_id.startswith('vol-'): bdm['volume_id'] = ec2utils.ec2_vol_id_to_uuid(ec2_id) ebs.setdefault('delete_on_termination', True) bdm.update(ebs) return bdm def _properties_get_mappings(properties): return block_device.mappings_prepend_dev(properties.get('mappings', [])) def _format_block_device_mapping(bdm): """Construct BlockDeviceMappingItemType {'device_name': '...', 'snapshot_id': , ...} => BlockDeviceMappingItemType """ keys = (('deviceName', 'device_name'), ('virtualName', 'virtual_name')) item = {} for name, k in keys: if k in bdm: item[name] = bdm[k] if bdm.get('no_device'): item['noDevice'] = True if ('snapshot_id' in bdm) or ('volume_id' in bdm): ebs_keys = (('snapshotId', 'snapshot_id'), ('snapshotId', 'volume_id'), # snapshotId is abused ('volumeSize', 'volume_size'), ('deleteOnTermination', 'delete_on_termination')) ebs = {} for name, k in ebs_keys: if bdm.get(k) is not None: if k == 'snapshot_id': ebs[name] = ec2utils.id_to_ec2_snap_id(bdm[k]) elif k == 'volume_id': ebs[name] = ec2utils.id_to_ec2_vol_id(bdm[k]) else: ebs[name] = bdm[k] assert 'snapshotId' in ebs item['ebs'] = ebs return item def _format_mappings(properties, result): """Format multiple BlockDeviceMappingItemType.""" mappings = [{'virtualName': m['virtual'], 'deviceName': m['device']} for m in _properties_get_mappings(properties) if block_device.is_swap_or_ephemeral(m['virtual'])] block_device_mapping = [_format_block_device_mapping(bdm) for bdm in properties.get('block_device_mapping', [])] # NOTE(yamahata): overwrite mappings with block_device_mapping for bdm in block_device_mapping: for i in range(len(mappings)): if bdm.get('deviceName') == mappings[i].get('deviceName'): del mappings[i] break mappings.append(bdm) # NOTE(yamahata): trim ebs.no_device == true. Is this necessary? mappings = [bdm for bdm in mappings if not (bdm.get('noDevice', False))] if mappings: result['blockDeviceMapping'] = mappings class CloudController(object): """CloudController provides the critical dispatch between inbound API calls through the endpoint and messages sent to the other nodes. """ def __init__(self): versionutils.report_deprecated_feature( LOG, _LW('The in tree EC2 API is deprecated as of Kilo release and may ' 'be removed in a future release. The openstack ec2-api ' 'project http://git.openstack.org/cgit/openstack/ec2-api/ ' 'is the target replacement for this functionality.') ) self.image_service = s3.S3ImageService() self.network_api = network.API() self.volume_api = volume.API() self.security_group_api = get_cloud_security_group_api() self.compute_api = compute.API(network_api=self.network_api, volume_api=self.volume_api, security_group_api=self.security_group_api) self.keypair_api = compute_api.KeypairAPI() self.servicegroup_api = servicegroup.API() def __str__(self): return 'CloudController' def _enforce_valid_instance_ids(self, context, instance_ids): # NOTE(mikal): Amazon's implementation of the EC2 API requires that # _all_ instance ids passed in be valid. instances = {} if instance_ids: for ec2_id in instance_ids: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) instances[ec2_id] = instance return instances def _get_image_state(self, image): # NOTE(vish): fallback status if image_state isn't set state = image.get('status') if state == 'active': state = 'available' return image['properties'].get('image_state', state) def describe_availability_zones(self, context, **kwargs): if ('zone_name' in kwargs and 'verbose' in kwargs['zone_name'] and context.is_admin): return self._describe_availability_zones_verbose(context, **kwargs) else: return self._describe_availability_zones(context, **kwargs) def _describe_availability_zones(self, context, **kwargs): ctxt = context.elevated() available_zones, not_available_zones = \ availability_zones.get_availability_zones(ctxt) result = [] for zone in available_zones: # Hide internal_service_availability_zone if zone == CONF.internal_service_availability_zone: continue result.append({'zoneName': zone, 'zoneState': "available"}) for zone in not_available_zones: result.append({'zoneName': zone, 'zoneState': "not available"}) return {'availabilityZoneInfo': result} def _describe_availability_zones_verbose(self, context, **kwargs): ctxt = context.elevated() available_zones, not_available_zones = \ availability_zones.get_availability_zones(ctxt) # Available services enabled_services = objects.ServiceList.get_all(context, disabled=False, set_zones=True) zone_hosts = {} host_services = {} for service in enabled_services: zone_hosts.setdefault(service.availability_zone, []) if service.host not in zone_hosts[service.availability_zone]: zone_hosts[service.availability_zone].append( service.host) host_services.setdefault(service.availability_zone + service.host, []) host_services[service.availability_zone + service.host].\ append(service) result = [] for zone in available_zones: result.append({'zoneName': zone, 'zoneState': "available"}) for host in zone_hosts[zone]: result.append({'zoneName': '|- %s' % host, 'zoneState': ''}) for service in host_services[zone + host]: alive = self.servicegroup_api.service_is_up(service) art = (alive and ":-)") or "XXX" active = 'enabled' if service.disabled: active = 'disabled' result.append({'zoneName': '| |- %s' % service.binary, 'zoneState': ('%s %s %s' % (active, art, service.updated_at))}) for zone in not_available_zones: result.append({'zoneName': zone, 'zoneState': "not available"}) return {'availabilityZoneInfo': result} def describe_regions(self, context, region_name=None, **kwargs): if CONF.region_list: regions = [] for region in CONF.region_list: name, _sep, host = region.partition('=') endpoint = '%s://%s:%s%s' % (CONF.ec2_scheme, host, CONF.ec2_port, CONF.ec2_path) regions.append({'regionName': name, 'regionEndpoint': endpoint}) else: regions = [{'regionName': 'nova', 'regionEndpoint': '%s://%s:%s%s' % (CONF.ec2_scheme, CONF.ec2_host, CONF.ec2_port, CONF.ec2_path)}] return {'regionInfo': regions} def describe_snapshots(self, context, snapshot_id=None, owner=None, restorable_by=None, **kwargs): if snapshot_id: snapshots = [] for ec2_id in snapshot_id: internal_id = ec2utils.ec2_snap_id_to_uuid(ec2_id) snapshot = self.volume_api.get_snapshot( context, snapshot_id=internal_id) snapshots.append(snapshot) else: snapshots = self.volume_api.get_all_snapshots(context) formatted_snapshots = [] for s in snapshots: formatted = self._format_snapshot(context, s) if formatted: formatted_snapshots.append(formatted) return {'snapshotSet': formatted_snapshots} def _format_snapshot(self, context, snapshot): # NOTE(mikal): this is just a set of strings in cinder. If they # implement an enum, then we should move this code to use it. The # valid ec2 statuses are "pending", "completed", and "error". status_map = {'new': 'pending', 'creating': 'pending', 'available': 'completed', 'active': 'completed', 'deleting': 'pending', 'deleted': None, 'error': 'error'} mapped_status = status_map.get(snapshot['status'], snapshot['status']) if not mapped_status: return None s = {} s['snapshotId'] = ec2utils.id_to_ec2_snap_id(snapshot['id']) s['volumeId'] = ec2utils.id_to_ec2_vol_id(snapshot['volume_id']) s['status'] = mapped_status s['startTime'] = snapshot['created_at'] s['progress'] = snapshot['progress'] s['ownerId'] = snapshot['project_id'] s['volumeSize'] = snapshot['volume_size'] s['description'] = snapshot['display_description'] return s def create_snapshot(self, context, volume_id, **kwargs): validate_volume_id(volume_id) LOG.info(_LI("Create snapshot of volume %s"), volume_id, context=context) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) args = (context, volume_id, kwargs.get('name'), kwargs.get('description')) if kwargs.get('force', False): snapshot = self.volume_api.create_snapshot_force(*args) else: snapshot = self.volume_api.create_snapshot(*args) smap = objects.EC2SnapshotMapping(context, uuid=snapshot['id']) smap.create() return self._format_snapshot(context, snapshot) def delete_snapshot(self, context, snapshot_id, **kwargs): snapshot_id = ec2utils.ec2_snap_id_to_uuid(snapshot_id) self.volume_api.delete_snapshot(context, snapshot_id) return True def describe_key_pairs(self, context, key_name=None, **kwargs): key_pairs = self.keypair_api.get_key_pairs(context, context.user_id) if key_name is not None: key_pairs = [x for x in key_pairs if x['name'] in key_name] # If looking for non existent key pair if key_name is not None and not key_pairs: msg = _('Could not find key pair(s): %s') % ','.join(key_name) raise exception.KeypairNotFound(message=msg) result = [] for key_pair in key_pairs: # filter out the vpn keys suffix = CONF.vpn_key_suffix if context.is_admin or not key_pair['name'].endswith(suffix): result.append({ 'keyName': key_pair['name'], 'keyFingerprint': key_pair['fingerprint'], }) return {'keySet': result} def create_key_pair(self, context, key_name, **kwargs): LOG.info(_LI("Create key pair %s"), key_name, context=context) keypair, private_key = self.keypair_api.create_key_pair( context, context.user_id, key_name) return {'keyName': key_name, 'keyFingerprint': keypair['fingerprint'], 'keyMaterial': private_key} # TODO(vish): when context is no longer an object, pass it here def import_key_pair(self, context, key_name, public_key_material, **kwargs): LOG.info(_LI("Import key %s"), key_name, context=context) public_key = base64.b64decode(public_key_material) keypair = self.keypair_api.import_key_pair(context, context.user_id, key_name, public_key) return {'keyName': key_name, 'keyFingerprint': keypair['fingerprint']} def delete_key_pair(self, context, key_name, **kwargs): LOG.info(_LI("Delete key pair %s"), key_name, context=context) try: self.keypair_api.delete_key_pair(context, context.user_id, key_name) except exception.NotFound: # aws returns true even if the key doesn't exist pass return True def describe_security_groups(self, context, group_name=None, group_id=None, **kwargs): search_opts = ec2utils.search_opts_from_filters(kwargs.get('filter')) raw_groups = self.security_group_api.list(context, group_name, group_id, context.project_id, search_opts=search_opts) groups = [self._format_security_group(context, g) for g in raw_groups] return {'securityGroupInfo': list(sorted(groups, key=lambda k: (k['ownerId'], k['groupName'])))} def _format_security_group(self, context, group): g = {} g['groupDescription'] = group['description'] g['groupName'] = group['name'] g['ownerId'] = group['project_id'] g['ipPermissions'] = [] for rule in group['rules']: r = {} r['groups'] = [] r['ipRanges'] = [] if rule['group_id']: if rule.get('grantee_group'): source_group = rule['grantee_group'] r['groups'] += [{'groupName': source_group['name'], 'userId': source_group['project_id']}] else: # rule is not always joined with grantee_group # for example when using neutron driver. source_group = self.security_group_api.get( context, id=rule['group_id']) r['groups'] += [{'groupName': source_group.get('name'), 'userId': source_group.get('project_id')}] if rule['protocol']: r['ipProtocol'] = rule['protocol'].lower() r['fromPort'] = rule['from_port'] r['toPort'] = rule['to_port'] g['ipPermissions'] += [dict(r)] else: for protocol, min_port, max_port in (('icmp', -1, -1), ('tcp', 1, 65535), ('udp', 1, 65535)): r['ipProtocol'] = protocol r['fromPort'] = min_port r['toPort'] = max_port g['ipPermissions'] += [dict(r)] else: r['ipProtocol'] = rule['protocol'] r['fromPort'] = rule['from_port'] r['toPort'] = rule['to_port'] r['ipRanges'] += [{'cidrIp': rule['cidr']}] g['ipPermissions'] += [r] return g def _rule_args_to_dict(self, context, kwargs): rules = [] if 'groups' not in kwargs and 'ip_ranges' not in kwargs: rule = self._rule_dict_last_step(context, **kwargs) if rule: rules.append(rule) return rules if 'ip_ranges' in kwargs: rules = self._cidr_args_split(kwargs) else: rules = [kwargs] finalset = [] for rule in rules: if 'groups' in rule: groups_values = self._groups_args_split(rule) for groups_value in groups_values: final = self._rule_dict_last_step(context, **groups_value) finalset.append(final) else: final = self._rule_dict_last_step(context, **rule) finalset.append(final) return finalset def _cidr_args_split(self, kwargs): cidr_args_split = [] cidrs = kwargs['ip_ranges'] for key, cidr in six.iteritems(cidrs): mykwargs = kwargs.copy() del mykwargs['ip_ranges'] mykwargs['cidr_ip'] = cidr['cidr_ip'] cidr_args_split.append(mykwargs) return cidr_args_split def _groups_args_split(self, kwargs): groups_args_split = [] groups = kwargs['groups'] for key, group in six.iteritems(groups): mykwargs = kwargs.copy() del mykwargs['groups'] if 'group_name' in group: mykwargs['source_security_group_name'] = group['group_name'] if 'user_id' in group: mykwargs['source_security_group_owner_id'] = group['user_id'] if 'group_id' in group: mykwargs['source_security_group_id'] = group['group_id'] groups_args_split.append(mykwargs) return groups_args_split def _rule_dict_last_step(self, context, to_port=None, from_port=None, ip_protocol=None, cidr_ip=None, user_id=None, source_security_group_name=None, source_security_group_owner_id=None): if source_security_group_name: source_project_id = self._get_source_project_id(context, source_security_group_owner_id) source_security_group = objects.SecurityGroup.get_by_name( context.elevated(), source_project_id, source_security_group_name) notfound = exception.SecurityGroupNotFound if not source_security_group: raise notfound(security_group_id=source_security_group_name) group_id = source_security_group.id return self.security_group_api.new_group_ingress_rule( group_id, ip_protocol, from_port, to_port) else: cidr = self.security_group_api.parse_cidr(cidr_ip) return self.security_group_api.new_cidr_ingress_rule( cidr, ip_protocol, from_port, to_port) def _validate_group_identifier(self, group_name, group_id): if not group_name and not group_id: err = _("need group_name or group_id") raise exception.MissingParameter(reason=err) def _validate_rulevalues(self, rulesvalues): if not rulesvalues: err = _("can't build a valid rule") raise exception.MissingParameter(reason=err) def _validate_security_group_protocol(self, values): validprotocols = ['tcp', 'udp', 'icmp', '6', '17', '1'] if 'ip_protocol' in values and \ values['ip_protocol'] not in validprotocols: protocol = values['ip_protocol'] err = _("Invalid IP protocol %(protocol)s") % \ {'protocol': protocol} raise exception.InvalidParameterValue(message=err) def revoke_security_group_ingress(self, context, group_name=None, group_id=None, **kwargs): self._validate_group_identifier(group_name, group_id) security_group = self.security_group_api.get(context, group_name, group_id) extensions.check_compute_policy(context, 'security_groups', security_group, 'compute_extension') prevalues = kwargs.get('ip_permissions', [kwargs]) rule_ids = [] for values in prevalues: rulesvalues = self._rule_args_to_dict(context, values) self._validate_rulevalues(rulesvalues) for values_for_rule in rulesvalues: values_for_rule['parent_group_id'] = security_group['id'] rule_ids.append(self.security_group_api.rule_exists( security_group, values_for_rule)) rule_ids = [id for id in rule_ids if id] if rule_ids: self.security_group_api.remove_rules(context, security_group, rule_ids) return True msg = _("No rule for the specified parameters.") raise exception.InvalidParameterValue(message=msg) # TODO(soren): This has only been tested with Boto as the client. # Unfortunately, it seems Boto is using an old API # for these operations, so support for newer API versions # is sketchy. def authorize_security_group_ingress(self, context, group_name=None, group_id=None, **kwargs): self._validate_group_identifier(group_name, group_id) security_group = self.security_group_api.get(context, group_name, group_id) extensions.check_compute_policy(context, 'security_groups', security_group, 'compute_extension') prevalues = kwargs.get('ip_permissions', [kwargs]) postvalues = [] for values in prevalues: self._validate_security_group_protocol(values) rulesvalues = self._rule_args_to_dict(context, values) self._validate_rulevalues(rulesvalues) for values_for_rule in rulesvalues: values_for_rule['parent_group_id'] = security_group['id'] if self.security_group_api.rule_exists(security_group, values_for_rule): raise exception.SecurityGroupRuleExists( rule=values_for_rule) postvalues.append(values_for_rule) if postvalues: self.security_group_api.add_rules(context, security_group['id'], security_group['name'], postvalues) return True msg = _("No rule for the specified parameters.") raise exception.InvalidParameterValue(message=msg) def _get_source_project_id(self, context, source_security_group_owner_id): if source_security_group_owner_id: # Parse user:project for source group. source_parts = source_security_group_owner_id.split(':') # If no project name specified, assume it's same as user name. # Since we're looking up by project name, the user name is not # used here. It's only read for EC2 API compatibility. if len(source_parts) == 2: source_project_id = source_parts[1] else: source_project_id = source_parts[0] else: source_project_id = context.project_id return source_project_id def create_security_group(self, context, group_name, group_description): if isinstance(group_name, six.text_type): group_name = utils.utf8(group_name) if CONF.ec2_strict_validation: # EC2 specification gives constraints for name and description: # Accepts alphanumeric characters, spaces, dashes, and underscores allowed = '^[a-zA-Z0-9_\- ]+$' self.security_group_api.validate_property(group_name, 'name', allowed) self.security_group_api.validate_property(group_description, 'description', allowed) else: # Amazon accepts more symbols. # So, allow POSIX [:print:] characters. allowed = r'^[\x20-\x7E]+$' self.security_group_api.validate_property(group_name, 'name', allowed) group_ref = self.security_group_api.create_security_group( context, group_name, group_description) return {'securityGroupSet': [self._format_security_group(context, group_ref)]} def delete_security_group(self, context, group_name=None, group_id=None, **kwargs): if not group_name and not group_id: err = _("need group_name or group_id") raise exception.MissingParameter(reason=err) security_group = self.security_group_api.get(context, group_name, group_id) extensions.check_compute_policy(context, 'security_groups', security_group, 'compute_extension') self.security_group_api.destroy(context, security_group) return True def get_password_data(self, context, instance_id, **kwargs): # instance_id may be passed in as a list of instances if isinstance(instance_id, list): ec2_id = instance_id[0] else: ec2_id = instance_id validate_instance_id(ec2_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) output = password.extract_password(instance) # NOTE(vish): this should be timestamp from the metadata fields # but it isn't important enough to implement properly now = timeutils.utcnow() return {"InstanceId": ec2_id, "Timestamp": now, "passwordData": output} def get_console_output(self, context, instance_id, **kwargs): LOG.info(_LI("Get console output for instance %s"), instance_id, context=context) # instance_id may be passed in as a list of instances if isinstance(instance_id, list): ec2_id = instance_id[0] else: ec2_id = instance_id validate_instance_id(ec2_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) output = self.compute_api.get_console_output(context, instance) now = timeutils.utcnow() return {"InstanceId": ec2_id, "Timestamp": now, "output": base64.b64encode(output)} def describe_volumes(self, context, volume_id=None, **kwargs): if volume_id: volumes = [] for ec2_id in volume_id: validate_volume_id(ec2_id) internal_id = ec2utils.ec2_vol_id_to_uuid(ec2_id) volume = self.volume_api.get(context, internal_id) volumes.append(volume) else: volumes = self.volume_api.get_all(context) volumes = [self._format_volume(context, v) for v in volumes] return {'volumeSet': volumes} def _format_volume(self, context, volume): valid_ec2_api_volume_status_map = { 'attaching': 'in-use', 'detaching': 'in-use'} instance_ec2_id = None if volume.get('instance_uuid', None): instance_uuid = volume['instance_uuid'] # Make sure instance exists objects.Instance.get_by_uuid(context.elevated(), instance_uuid) instance_ec2_id = ec2utils.id_to_ec2_inst_id(instance_uuid) v = {} v['volumeId'] = ec2utils.id_to_ec2_vol_id(volume['id']) v['status'] = valid_ec2_api_volume_status_map.get(volume['status'], volume['status']) v['size'] = volume['size'] v['availabilityZone'] = volume['availability_zone'] v['createTime'] = volume['created_at'] if v['status'] == 'in-use': v['attachmentSet'] = [{'attachTime': volume.get('attach_time'), 'deleteOnTermination': False, 'device': volume['mountpoint'], 'instanceId': instance_ec2_id, 'status': self._get_volume_attach_status( volume), 'volumeId': v['volumeId']}] else: v['attachmentSet'] = [{}] if volume.get('snapshot_id') is not None: v['snapshotId'] = ec2utils.id_to_ec2_snap_id(volume['snapshot_id']) else: v['snapshotId'] = None return v def create_volume(self, context, **kwargs): snapshot_ec2id = kwargs.get('snapshot_id', None) if snapshot_ec2id is not None: snapshot_id = ec2utils.ec2_snap_id_to_uuid(kwargs['snapshot_id']) snapshot = self.volume_api.get_snapshot(context, snapshot_id) LOG.info(_LI("Create volume from snapshot %s"), snapshot_ec2id, context=context) else: snapshot = None LOG.info(_LI("Create volume of %s GB"), kwargs.get('size'), context=context) create_kwargs = dict(snapshot=snapshot, volume_type=kwargs.get('volume_type'), metadata=kwargs.get('metadata'), availability_zone=kwargs.get('availability_zone')) volume = self.volume_api.create(context, kwargs.get('size'), kwargs.get('name'), kwargs.get('description'), **create_kwargs) vmap = objects.EC2VolumeMapping(context) vmap.uuid = volume['id'] vmap.create() # TODO(vish): Instance should be None at db layer instead of # trying to lazy load, but for now we turn it into # a dict to avoid an error. return self._format_volume(context, dict(volume)) def delete_volume(self, context, volume_id, **kwargs): validate_volume_id(volume_id) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) self.volume_api.delete(context, volume_id) return True def attach_volume(self, context, volume_id, instance_id, device, **kwargs): validate_instance_id(instance_id) validate_volume_id(volume_id) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, instance_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) LOG.info(_LI('Attach volume %(volume_id)s to instance %(instance_id)s ' 'at %(device)s'), {'volume_id': volume_id, 'instance_id': instance_id, 'device': device}, context=context) self.compute_api.attach_volume(context, instance, volume_id, device) volume = self.volume_api.get(context, volume_id) ec2_attach_status = ec2utils.status_to_ec2_attach_status(volume) return {'attachTime': volume['attach_time'], 'device': volume['mountpoint'], 'instanceId': ec2utils.id_to_ec2_inst_id(instance_uuid), 'requestId': context.request_id, 'status': ec2_attach_status, 'volumeId': ec2utils.id_to_ec2_vol_id(volume_id)} def _get_instance_from_volume(self, context, volume): if volume.get('instance_uuid'): try: inst_uuid = volume['instance_uuid'] return objects.Instance.get_by_uuid(context, inst_uuid) except exception.InstanceNotFound: pass raise exception.VolumeUnattached(volume_id=volume['id']) def detach_volume(self, context, volume_id, **kwargs): validate_volume_id(volume_id) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) LOG.info(_LI("Detach volume %s"), volume_id, context=context) volume = self.volume_api.get(context, volume_id) instance = self._get_instance_from_volume(context, volume) self.compute_api.detach_volume(context, instance, volume) resp_volume = self.volume_api.get(context, volume_id) ec2_attach_status = ec2utils.status_to_ec2_attach_status(resp_volume) return {'attachTime': volume['attach_time'], 'device': volume['mountpoint'], 'instanceId': ec2utils.id_to_ec2_inst_id( volume['instance_uuid']), 'requestId': context.request_id, 'status': ec2_attach_status, 'volumeId': ec2utils.id_to_ec2_vol_id(volume_id)} def _format_kernel_id(self, context, instance_ref, result, key): kernel_uuid = instance_ref['kernel_id'] if kernel_uuid is None or kernel_uuid == '': return result[key] = ec2utils.glance_id_to_ec2_id(context, kernel_uuid, 'aki') def _format_ramdisk_id(self, context, instance_ref, result, key): ramdisk_uuid = instance_ref['ramdisk_id'] if ramdisk_uuid is None or ramdisk_uuid == '': return result[key] = ec2utils.glance_id_to_ec2_id(context, ramdisk_uuid, 'ari') def describe_instance_attribute(self, context, instance_id, attribute, **kwargs): def _unsupported_attribute(instance, result): raise exception.InvalidAttribute(attr=attribute) def _format_attr_block_device_mapping(instance, result): tmp = {} self._format_instance_root_device_name(instance, tmp) self._format_instance_bdm(context, instance.uuid, tmp['rootDeviceName'], result) def _format_attr_disable_api_termination(instance, result): result['disableApiTermination'] = instance.disable_terminate def _format_attr_group_set(instance, result): CloudController._format_group_set(instance, result) def _format_attr_instance_initiated_shutdown_behavior(instance, result): if instance.shutdown_terminate: result['instanceInitiatedShutdownBehavior'] = 'terminate' else: result['instanceInitiatedShutdownBehavior'] = 'stop' def _format_attr_instance_type(instance, result): self._format_instance_type(instance, result) def _format_attr_kernel(instance, result): self._format_kernel_id(context, instance, result, 'kernel') def _format_attr_ramdisk(instance, result): self._format_ramdisk_id(context, instance, result, 'ramdisk') def _format_attr_root_device_name(instance, result): self._format_instance_root_device_name(instance, result) def _format_attr_source_dest_check(instance, result): _unsupported_attribute(instance, result) def _format_attr_user_data(instance, result): result['userData'] = base64.b64decode(instance.user_data) attribute_formatter = { 'blockDeviceMapping': _format_attr_block_device_mapping, 'disableApiTermination': _format_attr_disable_api_termination, 'groupSet': _format_attr_group_set, 'instanceInitiatedShutdownBehavior': _format_attr_instance_initiated_shutdown_behavior, 'instanceType': _format_attr_instance_type, 'kernel': _format_attr_kernel, 'ramdisk': _format_attr_ramdisk, 'rootDeviceName': _format_attr_root_device_name, 'sourceDestCheck': _format_attr_source_dest_check, 'userData': _format_attr_user_data, } fn = attribute_formatter.get(attribute) if fn is None: raise exception.InvalidAttribute(attr=attribute) validate_instance_id(instance_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, instance_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) result = {'instance_id': instance_id} fn(instance, result) return result def describe_instances(self, context, **kwargs): # Optional DescribeInstances argument instance_id = kwargs.get('instance_id', None) filters = kwargs.get('filter', None) instances = self._enforce_valid_instance_ids(context, instance_id) return self._format_describe_instances(context, instance_id=instance_id, instance_cache=instances, filter=filters) def describe_instances_v6(self, context, **kwargs): # Optional DescribeInstancesV6 argument instance_id = kwargs.get('instance_id', None) filters = kwargs.get('filter', None) instances = self._enforce_valid_instance_ids(context, instance_id) return self._format_describe_instances(context, instance_id=instance_id, instance_cache=instances, filter=filters, use_v6=True) def _format_describe_instances(self, context, **kwargs): return {'reservationSet': self._format_instances(context, **kwargs)} def _format_run_instances(self, context, reservation_id): i = self._format_instances(context, reservation_id=reservation_id) assert len(i) == 1 return i[0] def _format_terminate_instances(self, context, instance_id, previous_states): instances_set = [] for (ec2_id, previous_state) in zip(instance_id, previous_states): i = {} i['instanceId'] = ec2_id i['previousState'] = _state_description(previous_state['vm_state'], previous_state['shutdown_terminate']) try: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) i['currentState'] = _state_description(instance.vm_state, instance.shutdown_terminate) except exception.NotFound: i['currentState'] = _state_description( inst_state.SHUTTING_DOWN, True) instances_set.append(i) return {'instancesSet': instances_set} def _format_stop_instances(self, context, instance_ids, previous_states): instances_set = [] for (ec2_id, previous_state) in zip(instance_ids, previous_states): i = {} i['instanceId'] = ec2_id i['previousState'] = _state_description(previous_state['vm_state'], previous_state['shutdown_terminate']) i['currentState'] = _state_description(inst_state.STOPPING, True) instances_set.append(i) return {'instancesSet': instances_set} def _format_start_instances(self, context, instance_id, previous_states): instances_set = [] for (ec2_id, previous_state) in zip(instance_id, previous_states): i = {} i['instanceId'] = ec2_id i['previousState'] = _state_description(previous_state['vm_state'], previous_state['shutdown_terminate']) i['currentState'] = _state_description(None, True) instances_set.append(i) return {'instancesSet': instances_set} def _format_instance_bdm(self, context, instance_uuid, root_device_name, result): """Format InstanceBlockDeviceMappingResponseItemType.""" root_device_type = 'instance-store' root_device_short_name = block_device.strip_dev(root_device_name) if root_device_name == root_device_short_name: root_device_name = block_device.prepend_dev(root_device_name) mapping = [] bdms = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance_uuid) for bdm in bdms: volume_id = bdm.volume_id if volume_id is None or bdm.no_device: continue if (bdm.is_volume and (bdm.device_name == root_device_name or bdm.device_name == root_device_short_name)): root_device_type = 'ebs' vol = self.volume_api.get(context, volume_id) LOG.debug("vol = %s\n", vol) # TODO(yamahata): volume attach time ebs = {'volumeId': ec2utils.id_to_ec2_vol_id(volume_id), 'deleteOnTermination': bdm.delete_on_termination, 'attachTime': vol['attach_time'] or '', 'status': self._get_volume_attach_status(vol), } res = {'deviceName': bdm.device_name, 'ebs': ebs, } mapping.append(res) if mapping: result['blockDeviceMapping'] = mapping result['rootDeviceType'] = root_device_type @staticmethod def _get_volume_attach_status(volume): return (volume['status'] if volume['status'] in ('attaching', 'detaching') else volume['attach_status']) @staticmethod def _format_instance_root_device_name(instance, result): result['rootDeviceName'] = (instance.get('root_device_name') or block_device.DEFAULT_ROOT_DEV_NAME) @staticmethod def _format_instance_type(instance, result): flavor = instance.get_flavor() result['instanceType'] = flavor.name @staticmethod def _format_group_set(instance, result): security_group_names = [] if instance.get('security_groups'): for security_group in instance.security_groups: security_group_names.append(security_group['name']) result['groupSet'] = utils.convert_to_list_dict( security_group_names, 'groupId') def _format_instances(self, context, instance_id=None, use_v6=False, instances_cache=None, **search_opts): # TODO(termie): this method is poorly named as its name does not imply # that it will be making a variety of database calls # rather than simply formatting a bunch of instances that # were handed to it reservations = {} if not instances_cache: instances_cache = {} # NOTE(vish): instance_id is an optional list of ids to filter by if instance_id: instances = [] for ec2_id in instance_id: if ec2_id in instances_cache: instances.append(instances_cache[ec2_id]) else: try: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) except exception.NotFound: continue instances.append(instance) else: try: # always filter out deleted instances search_opts['deleted'] = False instances = self.compute_api.get_all(context, search_opts=search_opts, sort_keys=['created_at'], sort_dirs=['asc'], want_objects=True) except exception.NotFound: instances = [] for instance in instances: if not context.is_admin: if pipelib.is_vpn_image(instance.image_ref): continue i = {} instance_uuid = instance.uuid ec2_id = ec2utils.id_to_ec2_inst_id(instance_uuid) i['instanceId'] = ec2_id image_uuid = instance.image_ref i['imageId'] = ec2utils.glance_id_to_ec2_id(context, image_uuid) self._format_kernel_id(context, instance, i, 'kernelId') self._format_ramdisk_id(context, instance, i, 'ramdiskId') i['instanceState'] = _state_description( instance.vm_state, instance.shutdown_terminate) fixed_ip = None floating_ip = None ip_info = ec2utils.get_ip_info_for_instance(context, instance) if ip_info['fixed_ips']: fixed_ip = ip_info['fixed_ips'][0] if ip_info['floating_ips']: floating_ip = ip_info['floating_ips'][0] if ip_info['fixed_ip6s']: i['dnsNameV6'] = ip_info['fixed_ip6s'][0] if CONF.ec2_private_dns_show_ip: i['privateDnsName'] = fixed_ip else: i['privateDnsName'] = instance.hostname i['privateIpAddress'] = fixed_ip if floating_ip is not None: i['ipAddress'] = floating_ip i['dnsName'] = floating_ip i['keyName'] = instance.key_name i['tagSet'] = [] for k, v in six.iteritems(utils.instance_meta(instance)): i['tagSet'].append({'key': k, 'value': v}) client_token = self._get_client_token(context, instance_uuid) if client_token: i['clientToken'] = client_token if context.is_admin: i['keyName'] = '%s (%s, %s)' % (i['keyName'], instance.project_id, instance.host) i['productCodesSet'] = utils.convert_to_list_dict([], 'product_codes') self._format_instance_type(instance, i) i['launchTime'] = instance.created_at i['amiLaunchIndex'] = instance.launch_index self._format_instance_root_device_name(instance, i) self._format_instance_bdm(context, instance.uuid, i['rootDeviceName'], i) zone = availability_zones.get_instance_availability_zone(context, instance) i['placement'] = {'availabilityZone': zone} if instance.reservation_id not in reservations: r = {} r['reservationId'] = instance.reservation_id r['ownerId'] = instance.project_id self._format_group_set(instance, r) r['instancesSet'] = [] reservations[instance.reservation_id] = r reservations[instance.reservation_id]['instancesSet'].append(i) return list(reservations.values()) def describe_addresses(self, context, public_ip=None, **kwargs): if public_ip: floatings = [] for address in public_ip: floating = self.network_api.get_floating_ip_by_address(context, address) floatings.append(floating) else: floatings = self.network_api.get_floating_ips_by_project(context) addresses = [self._format_address(context, f) for f in floatings] return {'addressesSet': addresses} def _format_address(self, context, floating_ip): ec2_id = None if floating_ip['fixed_ip_id']: if utils.is_neutron(): fixed_vm_uuid = floating_ip['instance']['uuid'] if fixed_vm_uuid is not None: ec2_id = ec2utils.id_to_ec2_inst_id(fixed_vm_uuid) else: fixed_id = floating_ip['fixed_ip_id'] fixed = self.network_api.get_fixed_ip(context, fixed_id) if fixed['instance_uuid'] is not None: ec2_id = ec2utils.id_to_ec2_inst_id(fixed['instance_uuid']) address = {'public_ip': floating_ip['address'], 'instance_id': ec2_id} if context.is_admin: details = "%s (%s)" % (address['instance_id'], floating_ip['project_id']) address['instance_id'] = details return address def allocate_address(self, context, **kwargs): LOG.info(_LI("Allocate address"), context=context) public_ip = self.network_api.allocate_floating_ip(context) return {'publicIp': public_ip} def release_address(self, context, public_ip, **kwargs): LOG.info(_LI('Release address %s'), public_ip, context=context) self.network_api.release_floating_ip(context, address=public_ip) return {'return': "true"} def associate_address(self, context, instance_id, public_ip, **kwargs): LOG.info(_LI("Associate address %(public_ip)s to instance " "%(instance_id)s"), {'public_ip': public_ip, 'instance_id': instance_id}, context=context) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, instance_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) cached_ipinfo = ec2utils.get_ip_info_for_instance(context, instance) fixed_ips = cached_ipinfo['fixed_ips'] + cached_ipinfo['fixed_ip6s'] if not fixed_ips: msg = _('Unable to associate IP Address, no fixed_ips.') raise exception.NoMoreFixedIps(message=msg) # TODO(tr3buchet): this will associate the floating IP with the # first fixed_ip an instance has. This should be # changed to support specifying a particular fixed_ip if # multiple exist but this may not apply to ec2.. if len(fixed_ips) > 1: LOG.warning(_LW('multiple fixed_ips exist, using the first: %s'), fixed_ips[0]) self.network_api.associate_floating_ip(context, instance, floating_address=public_ip, fixed_address=fixed_ips[0]) return {'return': 'true'} def disassociate_address(self, context, public_ip, **kwargs): instance_id = self.network_api.get_instance_id_by_floating_address( context, public_ip) if instance_id: instance = self.compute_api.get(context, instance_id, want_objects=True) LOG.info(_LI("Disassociate address %s"), public_ip, context=context) self.network_api.disassociate_floating_ip(context, instance, address=public_ip) else: msg = _('Floating ip is not associated.') raise exception.InvalidAssociation(message=msg) return {'return': "true"} def run_instances(self, context, **kwargs): min_count = int(kwargs.get('min_count', 1)) max_count = int(kwargs.get('max_count', min_count)) try: min_count = utils.validate_integer( min_count, "min_count", min_value=1) max_count = utils.validate_integer( max_count, "max_count", min_value=1) except exception.InvalidInput as e: raise exception.InvalidInput(message=e.format_message()) if min_count > max_count: msg = _('min_count must be <= max_count') raise exception.InvalidInput(message=msg) client_token = kwargs.get('client_token') if client_token: resv_id = self._resv_id_from_token(context, client_token) if resv_id: # since this client_token already corresponds to a reservation # id, this returns a proper response without creating a new # instance return self._format_run_instances(context, resv_id) if kwargs.get('kernel_id'): kernel = self._get_image(context, kwargs['kernel_id']) kwargs['kernel_id'] = ec2utils.id_to_glance_id(context, kernel['id']) if kwargs.get('ramdisk_id'): ramdisk = self._get_image(context, kwargs['ramdisk_id']) kwargs['ramdisk_id'] = ec2utils.id_to_glance_id(context, ramdisk['id']) for bdm in kwargs.get('block_device_mapping', []): _parse_block_device_mapping(bdm) image = self._get_image(context, kwargs['image_id']) image_uuid = ec2utils.id_to_glance_id(context, image['id']) if image: image_state = self._get_image_state(image) else: raise exception.ImageNotFoundEC2(image_id=kwargs['image_id']) if image_state != 'available': msg = _('Image must be available') raise exception.ImageNotActive(message=msg) iisb = kwargs.get('instance_initiated_shutdown_behavior', 'stop') shutdown_terminate = (iisb == 'terminate') flavor = objects.Flavor.get_by_name(context, kwargs.get('instance_type', None)) (instances, resv_id) = self.compute_api.create(context, instance_type=flavor, image_href=image_uuid, max_count=int(kwargs.get('max_count', min_count)), min_count=min_count, kernel_id=kwargs.get('kernel_id'), ramdisk_id=kwargs.get('ramdisk_id'), key_name=kwargs.get('key_name'), user_data=kwargs.get('user_data'), security_group=kwargs.get('security_group'), availability_zone=kwargs.get('placement', {}).get( 'availability_zone'), block_device_mapping=kwargs.get('block_device_mapping', {}), shutdown_terminate=shutdown_terminate) instances = self._format_run_instances(context, resv_id) if instances: instance_ids = [i['instanceId'] for i in instances['instancesSet']] self._add_client_token(context, client_token, instance_ids) return instances def _add_client_token(self, context, client_token, instance_ids): """Add client token to reservation ID mapping.""" if client_token: for ec2_id in instance_ids: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = objects.Instance.get_by_uuid(context, instance_uuid, expected_attrs=['system_metadata']) instance.system_metadata.update( {'EC2_client_token': client_token}) instance.save() def _get_client_token(self, context, instance_uuid): """Get client token for a given instance.""" instance = objects.Instance.get_by_uuid(context, instance_uuid, expected_attrs=['system_metadata']) return instance.system_metadata.get('EC2_client_token') def _remove_client_token(self, context, instance_ids): """Remove client token to reservation ID mapping.""" for ec2_id in instance_ids: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = objects.Instance.get_by_uuid(context, instance_uuid, expected_attrs=['system_metadata']) instance.system_metadata.pop('EC2_client_token', None) instance.save() def _resv_id_from_token(self, context, client_token): """Get reservation ID from db.""" resv_id = None sys_metas = self.compute_api.get_all_system_metadata( context, search_filts=[{'key': ['EC2_client_token']}, {'value': [client_token]}]) for sys_meta in sys_metas: if sys_meta and sys_meta.get('value') == client_token: instance = objects.Instance.get_by_uuid( context, sys_meta['instance_id'], expected_attrs=None) resv_id = instance.get('reservation_id') break return resv_id def _ec2_ids_to_instances(self, context, instance_id): """Get all instances first, to prevent partial executions.""" instances = [] extra = ['system_metadata', 'metadata', 'info_cache'] for ec2_id in instance_id: validate_instance_id(ec2_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = objects.Instance.get_by_uuid( context, instance_uuid, expected_attrs=extra) instances.append(instance) return instances def terminate_instances(self, context, instance_id, **kwargs): """Terminate each instance in instance_id, which is a list of ec2 ids. instance_id is a kwarg so its name cannot be modified. """ previous_states = self._ec2_ids_to_instances(context, instance_id) self._remove_client_token(context, instance_id) LOG.debug("Going to start terminating instances") for instance in previous_states: self.compute_api.delete(context, instance) return self._format_terminate_instances(context, instance_id, previous_states) def reboot_instances(self, context, instance_id, **kwargs): """instance_id is a list of instance ids.""" instances = self._ec2_ids_to_instances(context, instance_id) LOG.info(_LI("Reboot instance %r"), instance_id, context=context) for instance in instances: self.compute_api.reboot(context, instance, 'HARD') return True def stop_instances(self, context, instance_id, **kwargs): """Stop each instances in instance_id. Here instance_id is a list of instance ids """ instances = self._ec2_ids_to_instances(context, instance_id) LOG.debug("Going to stop instances") for instance in instances: extensions.check_compute_policy(context, 'stop', instance) self.compute_api.stop(context, instance) return self._format_stop_instances(context, instance_id, instances) def start_instances(self, context, instance_id, **kwargs): """Start each instances in instance_id. Here instance_id is a list of instance ids """ instances = self._ec2_ids_to_instances(context, instance_id) LOG.debug("Going to start instances") for instance in instances: extensions.check_compute_policy(context, 'start', instance) self.compute_api.start(context, instance) return self._format_start_instances(context, instance_id, instances) def _get_image(self, context, ec2_id): try: internal_id = ec2utils.ec2_id_to_id(ec2_id) image = self.image_service.show(context, internal_id) except (exception.InvalidEc2Id, exception.ImageNotFound): filters = {'name': ec2_id} images = self.image_service.detail(context, filters=filters) try: return images[0] except IndexError: raise exception.ImageNotFound(image_id=ec2_id) image_type = ec2_id.split('-')[0] if ec2utils.image_type(image.get('container_format')) != image_type: raise exception.ImageNotFound(image_id=ec2_id) return image def _format_image(self, image): """Convert from format defined by GlanceImageService to S3 format.""" i = {} image_type = ec2utils.image_type(image.get('container_format')) ec2_id = ec2utils.image_ec2_id(image.get('id'), image_type) name = image.get('name') i['imageId'] = ec2_id kernel_id = image['properties'].get('kernel_id') if kernel_id: i['kernelId'] = ec2utils.image_ec2_id(kernel_id, 'aki') ramdisk_id = image['properties'].get('ramdisk_id') if ramdisk_id: i['ramdiskId'] = ec2utils.image_ec2_id(ramdisk_id, 'ari') i['imageOwnerId'] = image.get('owner') img_loc = image['properties'].get('image_location') if img_loc: i['imageLocation'] = img_loc else: i['imageLocation'] = "%s (%s)" % (img_loc, name) i['name'] = name if not name and img_loc: # This should only occur for images registered with ec2 api # prior to that api populating the glance name i['name'] = img_loc i['imageState'] = self._get_image_state(image) i['description'] = image.get('description') display_mapping = {'aki': 'kernel', 'ari': 'ramdisk', 'ami': 'machine'} i['imageType'] = display_mapping.get(image_type) i['isPublic'] = not not image.get('is_public') i['architecture'] = image['properties'].get('architecture') properties = image['properties'] root_device_name = block_device.properties_root_device_name(properties) root_device_type = 'instance-store' for bdm in properties.get('block_device_mapping', []): if (block_device.strip_dev(bdm.get('device_name')) == block_device.strip_dev(root_device_name) and ('snapshot_id' in bdm or 'volume_id' in bdm) and not bdm.get('no_device')): root_device_type = 'ebs' i['rootDeviceName'] = (root_device_name or block_device.DEFAULT_ROOT_DEV_NAME) i['rootDeviceType'] = root_device_type _format_mappings(properties, i) return i def describe_images(self, context, image_id=None, **kwargs): # NOTE: image_id is a list! if image_id: images = [] for ec2_id in image_id: try: image = self._get_image(context, ec2_id) except exception.NotFound: raise exception.ImageNotFound(image_id=ec2_id) images.append(image) else: images = self.image_service.detail(context) images = [self._format_image(i) for i in images] return {'imagesSet': images} def deregister_image(self, context, image_id, **kwargs): LOG.info(_LI("De-registering image %s"), image_id, context=context) image = self._get_image(context, image_id) internal_id = image['id'] self.image_service.delete(context, internal_id) return True def _register_image(self, context, metadata): image = self.image_service.create(context, metadata) image_type = ec2utils.image_type(image.get('container_format')) image_id = ec2utils.image_ec2_id(image['id'], image_type) return image_id def register_image(self, context, image_location=None, **kwargs): if image_location is None and kwargs.get('name'): image_location = kwargs['name'] if image_location is None: msg = _('imageLocation is required') raise exception.MissingParameter(reason=msg) metadata = {'properties': {'image_location': image_location}} if kwargs.get('name'): metadata['name'] = kwargs['name'] else: metadata['name'] = image_location if 'root_device_name' in kwargs: metadata['properties']['root_device_name'] = kwargs.get( 'root_device_name') mappings = [_parse_block_device_mapping(bdm) for bdm in kwargs.get('block_device_mapping', [])] if mappings: metadata['properties']['block_device_mapping'] = mappings image_id = self._register_image(context, metadata) LOG.info(_LI('Registered image %(image_location)s with id ' '%(image_id)s'), {'image_location': image_location, 'image_id': image_id}, context=context) return {'imageId': image_id} def describe_image_attribute(self, context, image_id, attribute, **kwargs): def _block_device_mapping_attribute(image, result): _format_mappings(image['properties'], result) def _launch_permission_attribute(image, result): result['launchPermission'] = [] if image['is_public']: result['launchPermission'].append({'group': 'all'}) def _root_device_name_attribute(image, result): _prop_root_dev_name = block_device.properties_root_device_name result['rootDeviceName'] = _prop_root_dev_name(image['properties']) if result['rootDeviceName'] is None: result['rootDeviceName'] = block_device.DEFAULT_ROOT_DEV_NAME def _kernel_attribute(image, result): kernel_id = image['properties'].get('kernel_id') if kernel_id: result['kernel'] = { 'value': ec2utils.image_ec2_id(kernel_id, 'aki') } def _ramdisk_attribute(image, result): ramdisk_id = image['properties'].get('ramdisk_id') if ramdisk_id: result['ramdisk'] = { 'value': ec2utils.image_ec2_id(ramdisk_id, 'ari') } supported_attributes = { 'blockDeviceMapping': _block_device_mapping_attribute, 'launchPermission': _launch_permission_attribute, 'rootDeviceName': _root_device_name_attribute, 'kernel': _kernel_attribute, 'ramdisk': _ramdisk_attribute, } fn = supported_attributes.get(attribute) if fn is None: raise exception.InvalidAttribute(attr=attribute) try: image = self._get_image(context, image_id) except exception.NotFound: raise exception.ImageNotFound(image_id=image_id) result = {'imageId': image_id} fn(image, result) return result def modify_image_attribute(self, context, image_id, attribute, operation_type, **kwargs): # TODO(devcamcar): Support users and groups other than 'all'. if attribute != 'launchPermission': raise exception.InvalidAttribute(attr=attribute) if 'user_group' not in kwargs: msg = _('user or group not specified') raise exception.MissingParameter(reason=msg) if len(kwargs['user_group']) != 1 and kwargs['user_group'][0] != 'all': msg = _('only group "all" is supported') raise exception.InvalidParameterValue(message=msg) if operation_type not in ['add', 'remove']: msg = _('operation_type must be add or remove') raise exception.InvalidParameterValue(message=msg) LOG.info(_LI("Updating image %s publicity"), image_id, context=context) try: image = self._get_image(context, image_id) except exception.NotFound: raise exception.ImageNotFound(image_id=image_id) internal_id = image['id'] del(image['id']) image['is_public'] = (operation_type == 'add') try: return self.image_service.update(context, internal_id, image) except exception.ImageNotAuthorized: msg = _('Not allowed to modify attributes for image %s') % image_id raise exception.Forbidden(message=msg) def update_image(self, context, image_id, **kwargs): internal_id = ec2utils.ec2_id_to_id(image_id) result = self.image_service.update(context, internal_id, dict(kwargs)) return result # TODO(yamahata): race condition # At the moment there is no way to prevent others from # manipulating instances/volumes/snapshots. # As other code doesn't take it into consideration, here we don't # care of it for now. Ostrich algorithm # TODO(mriedem): Consider auto-locking the instance when stopping it and # doing the snapshot, then unlock it when that is done. Locking the # instance in the database would prevent other APIs from changing the state # of the instance during this operation for non-admin users. def create_image(self, context, instance_id, **kwargs): # NOTE(yamahata): name/description are ignored by register_image(), # do so here no_reboot = kwargs.get('no_reboot', False) name = kwargs.get('name') validate_instance_id(instance_id) ec2_instance_id = instance_id instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_instance_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) # CreateImage only supported for the analogue of EBS-backed instances if not self.compute_api.is_volume_backed_instance(context, instance): msg = _("Invalid value '%(ec2_instance_id)s' for instanceId. " "Instance does not have a volume attached at root " "(%(root)s)") % {'root': instance.root_device_name, 'ec2_instance_id': ec2_instance_id} raise exception.InvalidParameterValue(err=msg) # stop the instance if necessary restart_instance = False if not no_reboot: vm_state = instance.vm_state # if the instance is in subtle state, refuse to proceed. if vm_state not in (vm_states.ACTIVE, vm_states.STOPPED): raise exception.InstanceNotRunning(instance_id=ec2_instance_id) if vm_state == vm_states.ACTIVE: restart_instance = True # NOTE(mriedem): We do a call here so that we're sure the # stop request is complete before we begin polling the state. self.compute_api.stop(context, instance, do_cast=False) # wait instance for really stopped (and not transitioning tasks) start_time = time.time() while (vm_state != vm_states.STOPPED and instance.task_state is not None): time.sleep(1) instance.refresh() vm_state = instance.vm_state # NOTE(yamahata): timeout and error. 1 hour for now for safety. # Is it too short/long? # Or is there any better way? timeout = 1 * 60 * 60 if time.time() > start_time + timeout: err = (_("Couldn't stop instance %(instance)s within " "1 hour. Current vm_state: %(vm_state)s, " "current task_state: %(task_state)s") % {'instance': instance_uuid, 'vm_state': vm_state, 'task_state': instance.task_state}) raise exception.InternalError(message=err) # meaningful image name name_map = dict(instance=instance_uuid, now=utils.isotime()) name = name or _('image of %(instance)s at %(now)s') % name_map new_image = self.compute_api.snapshot_volume_backed(context, instance, name) ec2_id = ec2utils.glance_id_to_ec2_id(context, new_image['id']) if restart_instance: self.compute_api.start(context, instance) return {'imageId': ec2_id} def create_tags(self, context, **kwargs): """Add tags to a resource Returns True on success, error on failure. :param context: context under which the method is called """ resources = kwargs.get('resource_id', None) tags = kwargs.get('tag', None) if resources is None or tags is None: msg = _('resource_id and tag are required') raise exception.MissingParameter(reason=msg) if not isinstance(resources, (tuple, list, set)): msg = _('Expecting a list of resources') raise exception.InvalidParameterValue(message=msg) for r in resources: if ec2utils.resource_type_from_id(context, r) != 'instance': msg = _('Only instances implemented') raise exception.InvalidParameterValue(message=msg) if not isinstance(tags, (tuple, list, set)): msg = _('Expecting a list of tagSets') raise exception.InvalidParameterValue(message=msg) metadata = {} for tag in tags: if not isinstance(tag, dict): err = _('Expecting tagSet to be key/value pairs') raise exception.InvalidParameterValue(message=err) key = tag.get('key', None) val = tag.get('value', None) if key is None or val is None: err = _('Expecting both key and value to be set') raise exception.InvalidParameterValue(message=err) metadata[key] = val for ec2_id in resources: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) self.compute_api.update_instance_metadata(context, instance, metadata) return True def delete_tags(self, context, **kwargs): """Delete tags Returns True on success, error on failure. :param context: context under which the method is called """ resources = kwargs.get('resource_id', None) tags = kwargs.get('tag', None) if resources is None or tags is None: msg = _('resource_id and tag are required') raise exception.MissingParameter(reason=msg) if not isinstance(resources, (tuple, list, set)): msg = _('Expecting a list of resources') raise exception.InvalidParameterValue(message=msg) for r in resources: if ec2utils.resource_type_from_id(context, r) != 'instance': msg = _('Only instances implemented') raise exception.InvalidParameterValue(message=msg) if not isinstance(tags, (tuple, list, set)): msg = _('Expecting a list of tagSets') raise exception.InvalidParameterValue(message=msg) for ec2_id in resources: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) for tag in tags: if not isinstance(tag, dict): msg = _('Expecting tagSet to be key/value pairs') raise exception.InvalidParameterValue(message=msg) key = tag.get('key', None) if key is None: msg = _('Expecting key to be set') raise exception.InvalidParameterValue(message=msg) self.compute_api.delete_instance_metadata(context, instance, key) return True def describe_tags(self, context, **kwargs): """List tags Returns a dict with a single key 'tagSet' on success, error on failure. :param context: context under which the method is called """ filters = kwargs.get('filter', None) search_filts = [] if filters: for filter_block in filters: key_name = filter_block.get('name', None) val = filter_block.get('value', None) if val: if isinstance(val, dict): val = val.values() if not isinstance(val, (tuple, list, set)): val = (val,) if key_name: search_block = {} if key_name in ('resource_id', 'resource-id'): search_block['resource_id'] = [] for res_id in val: search_block['resource_id'].append( ec2utils.ec2_inst_id_to_uuid(context, res_id)) elif key_name in ['key', 'value']: search_block[key_name] = \ [ec2utils.regex_from_ec2_regex(v) for v in val] elif key_name in ('resource_type', 'resource-type'): for res_type in val: if res_type != 'instance': raise exception.InvalidParameterValue( message=_('Only instances implemented')) search_block[key_name] = 'instance' if len(search_block.keys()) > 0: search_filts.append(search_block) ts = [] for tag in self.compute_api.get_all_instance_metadata(context, search_filts): ts.append({ 'resource_id': ec2utils.id_to_ec2_inst_id(tag['instance_id']), 'resource_type': 'instance', 'key': tag['key'], 'value': tag['value'] }) return {"tagSet": ts} class EC2SecurityGroupExceptions(object): @staticmethod def raise_invalid_property(msg): raise exception.InvalidParameterValue(message=msg) @staticmethod def raise_group_already_exists(msg): raise exception.SecurityGroupExists(message=msg) @staticmethod def raise_invalid_group(msg): raise exception.InvalidGroup(reason=msg) @staticmethod def raise_invalid_cidr(cidr, decoding_exception=None): if decoding_exception: raise decoding_exception else: raise exception.InvalidParameterValue(message=_("Invalid CIDR")) @staticmethod def raise_over_quota(msg): raise exception.SecurityGroupLimitExceeded(msg) @staticmethod def raise_not_found(msg): pass class CloudSecurityGroupNovaAPI(EC2SecurityGroupExceptions, compute_api.SecurityGroupAPI): pass class CloudSecurityGroupNeutronAPI(EC2SecurityGroupExceptions, neutron_driver.SecurityGroupAPI): pass def get_cloud_security_group_api(): if cfg.CONF.security_group_api.lower() == 'nova': return CloudSecurityGroupNovaAPI() elif openstack_driver.is_neutron_security_groups(): return CloudSecurityGroupNeutronAPI() else: raise NotImplementedError()
43.234943
79
0.580124
import base64 import time from oslo_config import cfg from oslo_log import log as logging from oslo_log import versionutils from oslo_utils import timeutils import six from nova.api.ec2 import ec2utils from nova.api.ec2 import inst_state from nova.api.metadata import password from nova.api.openstack import extensions from nova.api import validator from nova import availability_zones from nova import block_device from nova.cloudpipe import pipelib from nova import compute from nova.compute import api as compute_api from nova.compute import vm_states from nova import exception from nova.i18n import _ from nova.i18n import _LI from nova.i18n import _LW from nova.image import s3 from nova import network from nova.network.security_group import neutron_driver from nova.network.security_group import openstack_driver from nova import objects from nova import quota from nova import servicegroup from nova import utils from nova import volume ec2_opts = [ cfg.StrOpt('ec2_host', default='$my_ip', help='The IP address of the EC2 API server'), cfg.StrOpt('ec2_dmz_host', default='$my_ip', help='The internal IP address of the EC2 API server'), cfg.IntOpt('ec2_port', default=8773, min=1, max=65535, help='The port of the EC2 API server'), cfg.StrOpt('ec2_scheme', default='http', choices=('http', 'https'), help='The protocol to use when connecting to the EC2 API ' 'server'), cfg.StrOpt('ec2_path', default='/', help='The path prefix used to call the ec2 API server'), cfg.ListOpt('region_list', default=[], help='List of region=fqdn pairs separated by commas'), ] CONF = cfg.CONF CONF.register_opts(ec2_opts) CONF.import_opt('my_ip', 'nova.netconf') CONF.import_opt('vpn_key_suffix', 'nova.cloudpipe.pipelib') CONF.import_opt('internal_service_availability_zone', 'nova.availability_zones') LOG = logging.getLogger(__name__) QUOTAS = quota.QUOTAS def _validate_ec2_id(val): if not validator.validate_str()(val): raise exception.InvalidEc2Id(ec2_id=val) ec2utils.ec2_id_to_id(val) def validate_volume_id(volume_id): try: _validate_ec2_id(volume_id) except exception.InvalidEc2Id: raise exception.InvalidVolumeIDMalformed(volume_id=volume_id) def validate_instance_id(instance_id): try: _validate_ec2_id(instance_id) except exception.InvalidEc2Id: raise exception.InvalidInstanceIDMalformed(instance_id=instance_id) _STATE_DESCRIPTION_MAP = { None: inst_state.PENDING, vm_states.ACTIVE: inst_state.RUNNING, vm_states.BUILDING: inst_state.PENDING, vm_states.DELETED: inst_state.TERMINATED, vm_states.SOFT_DELETED: inst_state.TERMINATED, vm_states.STOPPED: inst_state.STOPPED, vm_states.PAUSED: inst_state.PAUSE, vm_states.SUSPENDED: inst_state.SUSPEND, vm_states.RESCUED: inst_state.RESCUE, vm_states.RESIZED: inst_state.RESIZE, } def _state_description(vm_state, _shutdown_terminate): name = _STATE_DESCRIPTION_MAP.get(vm_state, vm_state) return {'code': inst_state.name_to_code(name), 'name': name} def _parse_block_device_mapping(bdm): ebs = bdm.pop('ebs', None) if ebs: ec2_id = ebs.pop('snapshot_id', None) if ec2_id: if ec2_id.startswith('snap-'): bdm['snapshot_id'] = ec2utils.ec2_snap_id_to_uuid(ec2_id) elif ec2_id.startswith('vol-'): bdm['volume_id'] = ec2utils.ec2_vol_id_to_uuid(ec2_id) ebs.setdefault('delete_on_termination', True) bdm.update(ebs) return bdm def _properties_get_mappings(properties): return block_device.mappings_prepend_dev(properties.get('mappings', [])) def _format_block_device_mapping(bdm): keys = (('deviceName', 'device_name'), ('virtualName', 'virtual_name')) item = {} for name, k in keys: if k in bdm: item[name] = bdm[k] if bdm.get('no_device'): item['noDevice'] = True if ('snapshot_id' in bdm) or ('volume_id' in bdm): ebs_keys = (('snapshotId', 'snapshot_id'), ('snapshotId', 'volume_id'), ('volumeSize', 'volume_size'), ('deleteOnTermination', 'delete_on_termination')) ebs = {} for name, k in ebs_keys: if bdm.get(k) is not None: if k == 'snapshot_id': ebs[name] = ec2utils.id_to_ec2_snap_id(bdm[k]) elif k == 'volume_id': ebs[name] = ec2utils.id_to_ec2_vol_id(bdm[k]) else: ebs[name] = bdm[k] assert 'snapshotId' in ebs item['ebs'] = ebs return item def _format_mappings(properties, result): mappings = [{'virtualName': m['virtual'], 'deviceName': m['device']} for m in _properties_get_mappings(properties) if block_device.is_swap_or_ephemeral(m['virtual'])] block_device_mapping = [_format_block_device_mapping(bdm) for bdm in properties.get('block_device_mapping', [])] for bdm in block_device_mapping: for i in range(len(mappings)): if bdm.get('deviceName') == mappings[i].get('deviceName'): del mappings[i] break mappings.append(bdm) mappings = [bdm for bdm in mappings if not (bdm.get('noDevice', False))] if mappings: result['blockDeviceMapping'] = mappings class CloudController(object): def __init__(self): versionutils.report_deprecated_feature( LOG, _LW('The in tree EC2 API is deprecated as of Kilo release and may ' 'be removed in a future release. The openstack ec2-api ' 'project http://git.openstack.org/cgit/openstack/ec2-api/ ' 'is the target replacement for this functionality.') ) self.image_service = s3.S3ImageService() self.network_api = network.API() self.volume_api = volume.API() self.security_group_api = get_cloud_security_group_api() self.compute_api = compute.API(network_api=self.network_api, volume_api=self.volume_api, security_group_api=self.security_group_api) self.keypair_api = compute_api.KeypairAPI() self.servicegroup_api = servicegroup.API() def __str__(self): return 'CloudController' def _enforce_valid_instance_ids(self, context, instance_ids): # _all_ instance ids passed in be valid. instances = {} if instance_ids: for ec2_id in instance_ids: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) instances[ec2_id] = instance return instances def _get_image_state(self, image): # NOTE(vish): fallback status if image_state isn't set state = image.get('status') if state == 'active': state = 'available' return image['properties'].get('image_state', state) def describe_availability_zones(self, context, **kwargs): if ('zone_name' in kwargs and 'verbose' in kwargs['zone_name'] and context.is_admin): return self._describe_availability_zones_verbose(context, **kwargs) else: return self._describe_availability_zones(context, **kwargs) def _describe_availability_zones(self, context, **kwargs): ctxt = context.elevated() available_zones, not_available_zones = \ availability_zones.get_availability_zones(ctxt) result = [] for zone in available_zones: if zone == CONF.internal_service_availability_zone: continue result.append({'zoneName': zone, 'zoneState': "available"}) for zone in not_available_zones: result.append({'zoneName': zone, 'zoneState': "not available"}) return {'availabilityZoneInfo': result} def _describe_availability_zones_verbose(self, context, **kwargs): ctxt = context.elevated() available_zones, not_available_zones = \ availability_zones.get_availability_zones(ctxt) enabled_services = objects.ServiceList.get_all(context, disabled=False, set_zones=True) zone_hosts = {} host_services = {} for service in enabled_services: zone_hosts.setdefault(service.availability_zone, []) if service.host not in zone_hosts[service.availability_zone]: zone_hosts[service.availability_zone].append( service.host) host_services.setdefault(service.availability_zone + service.host, []) host_services[service.availability_zone + service.host].\ append(service) result = [] for zone in available_zones: result.append({'zoneName': zone, 'zoneState': "available"}) for host in zone_hosts[zone]: result.append({'zoneName': '|- %s' % host, 'zoneState': ''}) for service in host_services[zone + host]: alive = self.servicegroup_api.service_is_up(service) art = (alive and ":-)") or "XXX" active = 'enabled' if service.disabled: active = 'disabled' result.append({'zoneName': '| |- %s' % service.binary, 'zoneState': ('%s %s %s' % (active, art, service.updated_at))}) for zone in not_available_zones: result.append({'zoneName': zone, 'zoneState': "not available"}) return {'availabilityZoneInfo': result} def describe_regions(self, context, region_name=None, **kwargs): if CONF.region_list: regions = [] for region in CONF.region_list: name, _sep, host = region.partition('=') endpoint = '%s://%s:%s%s' % (CONF.ec2_scheme, host, CONF.ec2_port, CONF.ec2_path) regions.append({'regionName': name, 'regionEndpoint': endpoint}) else: regions = [{'regionName': 'nova', 'regionEndpoint': '%s://%s:%s%s' % (CONF.ec2_scheme, CONF.ec2_host, CONF.ec2_port, CONF.ec2_path)}] return {'regionInfo': regions} def describe_snapshots(self, context, snapshot_id=None, owner=None, restorable_by=None, **kwargs): if snapshot_id: snapshots = [] for ec2_id in snapshot_id: internal_id = ec2utils.ec2_snap_id_to_uuid(ec2_id) snapshot = self.volume_api.get_snapshot( context, snapshot_id=internal_id) snapshots.append(snapshot) else: snapshots = self.volume_api.get_all_snapshots(context) formatted_snapshots = [] for s in snapshots: formatted = self._format_snapshot(context, s) if formatted: formatted_snapshots.append(formatted) return {'snapshotSet': formatted_snapshots} def _format_snapshot(self, context, snapshot): status_map = {'new': 'pending', 'creating': 'pending', 'available': 'completed', 'active': 'completed', 'deleting': 'pending', 'deleted': None, 'error': 'error'} mapped_status = status_map.get(snapshot['status'], snapshot['status']) if not mapped_status: return None s = {} s['snapshotId'] = ec2utils.id_to_ec2_snap_id(snapshot['id']) s['volumeId'] = ec2utils.id_to_ec2_vol_id(snapshot['volume_id']) s['status'] = mapped_status s['startTime'] = snapshot['created_at'] s['progress'] = snapshot['progress'] s['ownerId'] = snapshot['project_id'] s['volumeSize'] = snapshot['volume_size'] s['description'] = snapshot['display_description'] return s def create_snapshot(self, context, volume_id, **kwargs): validate_volume_id(volume_id) LOG.info(_LI("Create snapshot of volume %s"), volume_id, context=context) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) args = (context, volume_id, kwargs.get('name'), kwargs.get('description')) if kwargs.get('force', False): snapshot = self.volume_api.create_snapshot_force(*args) else: snapshot = self.volume_api.create_snapshot(*args) smap = objects.EC2SnapshotMapping(context, uuid=snapshot['id']) smap.create() return self._format_snapshot(context, snapshot) def delete_snapshot(self, context, snapshot_id, **kwargs): snapshot_id = ec2utils.ec2_snap_id_to_uuid(snapshot_id) self.volume_api.delete_snapshot(context, snapshot_id) return True def describe_key_pairs(self, context, key_name=None, **kwargs): key_pairs = self.keypair_api.get_key_pairs(context, context.user_id) if key_name is not None: key_pairs = [x for x in key_pairs if x['name'] in key_name] if key_name is not None and not key_pairs: msg = _('Could not find key pair(s): %s') % ','.join(key_name) raise exception.KeypairNotFound(message=msg) result = [] for key_pair in key_pairs: suffix = CONF.vpn_key_suffix if context.is_admin or not key_pair['name'].endswith(suffix): result.append({ 'keyName': key_pair['name'], 'keyFingerprint': key_pair['fingerprint'], }) return {'keySet': result} def create_key_pair(self, context, key_name, **kwargs): LOG.info(_LI("Create key pair %s"), key_name, context=context) keypair, private_key = self.keypair_api.create_key_pair( context, context.user_id, key_name) return {'keyName': key_name, 'keyFingerprint': keypair['fingerprint'], 'keyMaterial': private_key} def import_key_pair(self, context, key_name, public_key_material, **kwargs): LOG.info(_LI("Import key %s"), key_name, context=context) public_key = base64.b64decode(public_key_material) keypair = self.keypair_api.import_key_pair(context, context.user_id, key_name, public_key) return {'keyName': key_name, 'keyFingerprint': keypair['fingerprint']} def delete_key_pair(self, context, key_name, **kwargs): LOG.info(_LI("Delete key pair %s"), key_name, context=context) try: self.keypair_api.delete_key_pair(context, context.user_id, key_name) except exception.NotFound: pass return True def describe_security_groups(self, context, group_name=None, group_id=None, **kwargs): search_opts = ec2utils.search_opts_from_filters(kwargs.get('filter')) raw_groups = self.security_group_api.list(context, group_name, group_id, context.project_id, search_opts=search_opts) groups = [self._format_security_group(context, g) for g in raw_groups] return {'securityGroupInfo': list(sorted(groups, key=lambda k: (k['ownerId'], k['groupName'])))} def _format_security_group(self, context, group): g = {} g['groupDescription'] = group['description'] g['groupName'] = group['name'] g['ownerId'] = group['project_id'] g['ipPermissions'] = [] for rule in group['rules']: r = {} r['groups'] = [] r['ipRanges'] = [] if rule['group_id']: if rule.get('grantee_group'): source_group = rule['grantee_group'] r['groups'] += [{'groupName': source_group['name'], 'userId': source_group['project_id']}] else: # rule is not always joined with grantee_group # for example when using neutron driver. source_group = self.security_group_api.get( context, id=rule['group_id']) r['groups'] += [{'groupName': source_group.get('name'), 'userId': source_group.get('project_id')}] if rule['protocol']: r['ipProtocol'] = rule['protocol'].lower() r['fromPort'] = rule['from_port'] r['toPort'] = rule['to_port'] g['ipPermissions'] += [dict(r)] else: for protocol, min_port, max_port in (('icmp', -1, -1), ('tcp', 1, 65535), ('udp', 1, 65535)): r['ipProtocol'] = protocol r['fromPort'] = min_port r['toPort'] = max_port g['ipPermissions'] += [dict(r)] else: r['ipProtocol'] = rule['protocol'] r['fromPort'] = rule['from_port'] r['toPort'] = rule['to_port'] r['ipRanges'] += [{'cidrIp': rule['cidr']}] g['ipPermissions'] += [r] return g def _rule_args_to_dict(self, context, kwargs): rules = [] if 'groups' not in kwargs and 'ip_ranges' not in kwargs: rule = self._rule_dict_last_step(context, **kwargs) if rule: rules.append(rule) return rules if 'ip_ranges' in kwargs: rules = self._cidr_args_split(kwargs) else: rules = [kwargs] finalset = [] for rule in rules: if 'groups' in rule: groups_values = self._groups_args_split(rule) for groups_value in groups_values: final = self._rule_dict_last_step(context, **groups_value) finalset.append(final) else: final = self._rule_dict_last_step(context, **rule) finalset.append(final) return finalset def _cidr_args_split(self, kwargs): cidr_args_split = [] cidrs = kwargs['ip_ranges'] for key, cidr in six.iteritems(cidrs): mykwargs = kwargs.copy() del mykwargs['ip_ranges'] mykwargs['cidr_ip'] = cidr['cidr_ip'] cidr_args_split.append(mykwargs) return cidr_args_split def _groups_args_split(self, kwargs): groups_args_split = [] groups = kwargs['groups'] for key, group in six.iteritems(groups): mykwargs = kwargs.copy() del mykwargs['groups'] if 'group_name' in group: mykwargs['source_security_group_name'] = group['group_name'] if 'user_id' in group: mykwargs['source_security_group_owner_id'] = group['user_id'] if 'group_id' in group: mykwargs['source_security_group_id'] = group['group_id'] groups_args_split.append(mykwargs) return groups_args_split def _rule_dict_last_step(self, context, to_port=None, from_port=None, ip_protocol=None, cidr_ip=None, user_id=None, source_security_group_name=None, source_security_group_owner_id=None): if source_security_group_name: source_project_id = self._get_source_project_id(context, source_security_group_owner_id) source_security_group = objects.SecurityGroup.get_by_name( context.elevated(), source_project_id, source_security_group_name) notfound = exception.SecurityGroupNotFound if not source_security_group: raise notfound(security_group_id=source_security_group_name) group_id = source_security_group.id return self.security_group_api.new_group_ingress_rule( group_id, ip_protocol, from_port, to_port) else: cidr = self.security_group_api.parse_cidr(cidr_ip) return self.security_group_api.new_cidr_ingress_rule( cidr, ip_protocol, from_port, to_port) def _validate_group_identifier(self, group_name, group_id): if not group_name and not group_id: err = _("need group_name or group_id") raise exception.MissingParameter(reason=err) def _validate_rulevalues(self, rulesvalues): if not rulesvalues: err = _("can't build a valid rule") raise exception.MissingParameter(reason=err) def _validate_security_group_protocol(self, values): validprotocols = ['tcp', 'udp', 'icmp', '6', '17', '1'] if 'ip_protocol' in values and \ values['ip_protocol'] not in validprotocols: protocol = values['ip_protocol'] err = _("Invalid IP protocol %(protocol)s") % \ {'protocol': protocol} raise exception.InvalidParameterValue(message=err) def revoke_security_group_ingress(self, context, group_name=None, group_id=None, **kwargs): self._validate_group_identifier(group_name, group_id) security_group = self.security_group_api.get(context, group_name, group_id) extensions.check_compute_policy(context, 'security_groups', security_group, 'compute_extension') prevalues = kwargs.get('ip_permissions', [kwargs]) rule_ids = [] for values in prevalues: rulesvalues = self._rule_args_to_dict(context, values) self._validate_rulevalues(rulesvalues) for values_for_rule in rulesvalues: values_for_rule['parent_group_id'] = security_group['id'] rule_ids.append(self.security_group_api.rule_exists( security_group, values_for_rule)) rule_ids = [id for id in rule_ids if id] if rule_ids: self.security_group_api.remove_rules(context, security_group, rule_ids) return True msg = _("No rule for the specified parameters.") raise exception.InvalidParameterValue(message=msg) def authorize_security_group_ingress(self, context, group_name=None, group_id=None, **kwargs): self._validate_group_identifier(group_name, group_id) security_group = self.security_group_api.get(context, group_name, group_id) extensions.check_compute_policy(context, 'security_groups', security_group, 'compute_extension') prevalues = kwargs.get('ip_permissions', [kwargs]) postvalues = [] for values in prevalues: self._validate_security_group_protocol(values) rulesvalues = self._rule_args_to_dict(context, values) self._validate_rulevalues(rulesvalues) for values_for_rule in rulesvalues: values_for_rule['parent_group_id'] = security_group['id'] if self.security_group_api.rule_exists(security_group, values_for_rule): raise exception.SecurityGroupRuleExists( rule=values_for_rule) postvalues.append(values_for_rule) if postvalues: self.security_group_api.add_rules(context, security_group['id'], security_group['name'], postvalues) return True msg = _("No rule for the specified parameters.") raise exception.InvalidParameterValue(message=msg) def _get_source_project_id(self, context, source_security_group_owner_id): if source_security_group_owner_id: source_parts = source_security_group_owner_id.split(':') # Since we're looking up by project name, the user name is not if len(source_parts) == 2: source_project_id = source_parts[1] else: source_project_id = source_parts[0] else: source_project_id = context.project_id return source_project_id def create_security_group(self, context, group_name, group_description): if isinstance(group_name, six.text_type): group_name = utils.utf8(group_name) if CONF.ec2_strict_validation: # EC2 specification gives constraints for name and description: # Accepts alphanumeric characters, spaces, dashes, and underscores allowed = '^[a-zA-Z0-9_\- ]+$' self.security_group_api.validate_property(group_name, 'name', allowed) self.security_group_api.validate_property(group_description, 'description', allowed) else: # Amazon accepts more symbols. # So, allow POSIX [:print:] characters. allowed = r'^[\x20-\x7E]+$' self.security_group_api.validate_property(group_name, 'name', allowed) group_ref = self.security_group_api.create_security_group( context, group_name, group_description) return {'securityGroupSet': [self._format_security_group(context, group_ref)]} def delete_security_group(self, context, group_name=None, group_id=None, **kwargs): if not group_name and not group_id: err = _("need group_name or group_id") raise exception.MissingParameter(reason=err) security_group = self.security_group_api.get(context, group_name, group_id) extensions.check_compute_policy(context, 'security_groups', security_group, 'compute_extension') self.security_group_api.destroy(context, security_group) return True def get_password_data(self, context, instance_id, **kwargs): # instance_id may be passed in as a list of instances if isinstance(instance_id, list): ec2_id = instance_id[0] else: ec2_id = instance_id validate_instance_id(ec2_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) output = password.extract_password(instance) # NOTE(vish): this should be timestamp from the metadata fields # but it isn't important enough to implement properly now = timeutils.utcnow() return {"InstanceId": ec2_id, "Timestamp": now, "passwordData": output} def get_console_output(self, context, instance_id, **kwargs): LOG.info(_LI("Get console output for instance %s"), instance_id, context=context) if isinstance(instance_id, list): ec2_id = instance_id[0] else: ec2_id = instance_id validate_instance_id(ec2_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) output = self.compute_api.get_console_output(context, instance) now = timeutils.utcnow() return {"InstanceId": ec2_id, "Timestamp": now, "output": base64.b64encode(output)} def describe_volumes(self, context, volume_id=None, **kwargs): if volume_id: volumes = [] for ec2_id in volume_id: validate_volume_id(ec2_id) internal_id = ec2utils.ec2_vol_id_to_uuid(ec2_id) volume = self.volume_api.get(context, internal_id) volumes.append(volume) else: volumes = self.volume_api.get_all(context) volumes = [self._format_volume(context, v) for v in volumes] return {'volumeSet': volumes} def _format_volume(self, context, volume): valid_ec2_api_volume_status_map = { 'attaching': 'in-use', 'detaching': 'in-use'} instance_ec2_id = None if volume.get('instance_uuid', None): instance_uuid = volume['instance_uuid'] objects.Instance.get_by_uuid(context.elevated(), instance_uuid) instance_ec2_id = ec2utils.id_to_ec2_inst_id(instance_uuid) v = {} v['volumeId'] = ec2utils.id_to_ec2_vol_id(volume['id']) v['status'] = valid_ec2_api_volume_status_map.get(volume['status'], volume['status']) v['size'] = volume['size'] v['availabilityZone'] = volume['availability_zone'] v['createTime'] = volume['created_at'] if v['status'] == 'in-use': v['attachmentSet'] = [{'attachTime': volume.get('attach_time'), 'deleteOnTermination': False, 'device': volume['mountpoint'], 'instanceId': instance_ec2_id, 'status': self._get_volume_attach_status( volume), 'volumeId': v['volumeId']}] else: v['attachmentSet'] = [{}] if volume.get('snapshot_id') is not None: v['snapshotId'] = ec2utils.id_to_ec2_snap_id(volume['snapshot_id']) else: v['snapshotId'] = None return v def create_volume(self, context, **kwargs): snapshot_ec2id = kwargs.get('snapshot_id', None) if snapshot_ec2id is not None: snapshot_id = ec2utils.ec2_snap_id_to_uuid(kwargs['snapshot_id']) snapshot = self.volume_api.get_snapshot(context, snapshot_id) LOG.info(_LI("Create volume from snapshot %s"), snapshot_ec2id, context=context) else: snapshot = None LOG.info(_LI("Create volume of %s GB"), kwargs.get('size'), context=context) create_kwargs = dict(snapshot=snapshot, volume_type=kwargs.get('volume_type'), metadata=kwargs.get('metadata'), availability_zone=kwargs.get('availability_zone')) volume = self.volume_api.create(context, kwargs.get('size'), kwargs.get('name'), kwargs.get('description'), **create_kwargs) vmap = objects.EC2VolumeMapping(context) vmap.uuid = volume['id'] vmap.create() return self._format_volume(context, dict(volume)) def delete_volume(self, context, volume_id, **kwargs): validate_volume_id(volume_id) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) self.volume_api.delete(context, volume_id) return True def attach_volume(self, context, volume_id, instance_id, device, **kwargs): validate_instance_id(instance_id) validate_volume_id(volume_id) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, instance_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) LOG.info(_LI('Attach volume %(volume_id)s to instance %(instance_id)s ' 'at %(device)s'), {'volume_id': volume_id, 'instance_id': instance_id, 'device': device}, context=context) self.compute_api.attach_volume(context, instance, volume_id, device) volume = self.volume_api.get(context, volume_id) ec2_attach_status = ec2utils.status_to_ec2_attach_status(volume) return {'attachTime': volume['attach_time'], 'device': volume['mountpoint'], 'instanceId': ec2utils.id_to_ec2_inst_id(instance_uuid), 'requestId': context.request_id, 'status': ec2_attach_status, 'volumeId': ec2utils.id_to_ec2_vol_id(volume_id)} def _get_instance_from_volume(self, context, volume): if volume.get('instance_uuid'): try: inst_uuid = volume['instance_uuid'] return objects.Instance.get_by_uuid(context, inst_uuid) except exception.InstanceNotFound: pass raise exception.VolumeUnattached(volume_id=volume['id']) def detach_volume(self, context, volume_id, **kwargs): validate_volume_id(volume_id) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) LOG.info(_LI("Detach volume %s"), volume_id, context=context) volume = self.volume_api.get(context, volume_id) instance = self._get_instance_from_volume(context, volume) self.compute_api.detach_volume(context, instance, volume) resp_volume = self.volume_api.get(context, volume_id) ec2_attach_status = ec2utils.status_to_ec2_attach_status(resp_volume) return {'attachTime': volume['attach_time'], 'device': volume['mountpoint'], 'instanceId': ec2utils.id_to_ec2_inst_id( volume['instance_uuid']), 'requestId': context.request_id, 'status': ec2_attach_status, 'volumeId': ec2utils.id_to_ec2_vol_id(volume_id)} def _format_kernel_id(self, context, instance_ref, result, key): kernel_uuid = instance_ref['kernel_id'] if kernel_uuid is None or kernel_uuid == '': return result[key] = ec2utils.glance_id_to_ec2_id(context, kernel_uuid, 'aki') def _format_ramdisk_id(self, context, instance_ref, result, key): ramdisk_uuid = instance_ref['ramdisk_id'] if ramdisk_uuid is None or ramdisk_uuid == '': return result[key] = ec2utils.glance_id_to_ec2_id(context, ramdisk_uuid, 'ari') def describe_instance_attribute(self, context, instance_id, attribute, **kwargs): def _unsupported_attribute(instance, result): raise exception.InvalidAttribute(attr=attribute) def _format_attr_block_device_mapping(instance, result): tmp = {} self._format_instance_root_device_name(instance, tmp) self._format_instance_bdm(context, instance.uuid, tmp['rootDeviceName'], result) def _format_attr_disable_api_termination(instance, result): result['disableApiTermination'] = instance.disable_terminate def _format_attr_group_set(instance, result): CloudController._format_group_set(instance, result) def _format_attr_instance_initiated_shutdown_behavior(instance, result): if instance.shutdown_terminate: result['instanceInitiatedShutdownBehavior'] = 'terminate' else: result['instanceInitiatedShutdownBehavior'] = 'stop' def _format_attr_instance_type(instance, result): self._format_instance_type(instance, result) def _format_attr_kernel(instance, result): self._format_kernel_id(context, instance, result, 'kernel') def _format_attr_ramdisk(instance, result): self._format_ramdisk_id(context, instance, result, 'ramdisk') def _format_attr_root_device_name(instance, result): self._format_instance_root_device_name(instance, result) def _format_attr_source_dest_check(instance, result): _unsupported_attribute(instance, result) def _format_attr_user_data(instance, result): result['userData'] = base64.b64decode(instance.user_data) attribute_formatter = { 'blockDeviceMapping': _format_attr_block_device_mapping, 'disableApiTermination': _format_attr_disable_api_termination, 'groupSet': _format_attr_group_set, 'instanceInitiatedShutdownBehavior': _format_attr_instance_initiated_shutdown_behavior, 'instanceType': _format_attr_instance_type, 'kernel': _format_attr_kernel, 'ramdisk': _format_attr_ramdisk, 'rootDeviceName': _format_attr_root_device_name, 'sourceDestCheck': _format_attr_source_dest_check, 'userData': _format_attr_user_data, } fn = attribute_formatter.get(attribute) if fn is None: raise exception.InvalidAttribute(attr=attribute) validate_instance_id(instance_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, instance_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) result = {'instance_id': instance_id} fn(instance, result) return result def describe_instances(self, context, **kwargs): instance_id = kwargs.get('instance_id', None) filters = kwargs.get('filter', None) instances = self._enforce_valid_instance_ids(context, instance_id) return self._format_describe_instances(context, instance_id=instance_id, instance_cache=instances, filter=filters) def describe_instances_v6(self, context, **kwargs): instance_id = kwargs.get('instance_id', None) filters = kwargs.get('filter', None) instances = self._enforce_valid_instance_ids(context, instance_id) return self._format_describe_instances(context, instance_id=instance_id, instance_cache=instances, filter=filters, use_v6=True) def _format_describe_instances(self, context, **kwargs): return {'reservationSet': self._format_instances(context, **kwargs)} def _format_run_instances(self, context, reservation_id): i = self._format_instances(context, reservation_id=reservation_id) assert len(i) == 1 return i[0] def _format_terminate_instances(self, context, instance_id, previous_states): instances_set = [] for (ec2_id, previous_state) in zip(instance_id, previous_states): i = {} i['instanceId'] = ec2_id i['previousState'] = _state_description(previous_state['vm_state'], previous_state['shutdown_terminate']) try: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) i['currentState'] = _state_description(instance.vm_state, instance.shutdown_terminate) except exception.NotFound: i['currentState'] = _state_description( inst_state.SHUTTING_DOWN, True) instances_set.append(i) return {'instancesSet': instances_set} def _format_stop_instances(self, context, instance_ids, previous_states): instances_set = [] for (ec2_id, previous_state) in zip(instance_ids, previous_states): i = {} i['instanceId'] = ec2_id i['previousState'] = _state_description(previous_state['vm_state'], previous_state['shutdown_terminate']) i['currentState'] = _state_description(inst_state.STOPPING, True) instances_set.append(i) return {'instancesSet': instances_set} def _format_start_instances(self, context, instance_id, previous_states): instances_set = [] for (ec2_id, previous_state) in zip(instance_id, previous_states): i = {} i['instanceId'] = ec2_id i['previousState'] = _state_description(previous_state['vm_state'], previous_state['shutdown_terminate']) i['currentState'] = _state_description(None, True) instances_set.append(i) return {'instancesSet': instances_set} def _format_instance_bdm(self, context, instance_uuid, root_device_name, result): root_device_type = 'instance-store' root_device_short_name = block_device.strip_dev(root_device_name) if root_device_name == root_device_short_name: root_device_name = block_device.prepend_dev(root_device_name) mapping = [] bdms = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance_uuid) for bdm in bdms: volume_id = bdm.volume_id if volume_id is None or bdm.no_device: continue if (bdm.is_volume and (bdm.device_name == root_device_name or bdm.device_name == root_device_short_name)): root_device_type = 'ebs' vol = self.volume_api.get(context, volume_id) LOG.debug("vol = %s\n", vol) ebs = {'volumeId': ec2utils.id_to_ec2_vol_id(volume_id), 'deleteOnTermination': bdm.delete_on_termination, 'attachTime': vol['attach_time'] or '', 'status': self._get_volume_attach_status(vol), } res = {'deviceName': bdm.device_name, 'ebs': ebs, } mapping.append(res) if mapping: result['blockDeviceMapping'] = mapping result['rootDeviceType'] = root_device_type @staticmethod def _get_volume_attach_status(volume): return (volume['status'] if volume['status'] in ('attaching', 'detaching') else volume['attach_status']) @staticmethod def _format_instance_root_device_name(instance, result): result['rootDeviceName'] = (instance.get('root_device_name') or block_device.DEFAULT_ROOT_DEV_NAME) @staticmethod def _format_instance_type(instance, result): flavor = instance.get_flavor() result['instanceType'] = flavor.name @staticmethod def _format_group_set(instance, result): security_group_names = [] if instance.get('security_groups'): for security_group in instance.security_groups: security_group_names.append(security_group['name']) result['groupSet'] = utils.convert_to_list_dict( security_group_names, 'groupId') def _format_instances(self, context, instance_id=None, use_v6=False, instances_cache=None, **search_opts): reservations = {} if not instances_cache: instances_cache = {} if instance_id: instances = [] for ec2_id in instance_id: if ec2_id in instances_cache: instances.append(instances_cache[ec2_id]) else: try: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) except exception.NotFound: continue instances.append(instance) else: try: search_opts['deleted'] = False instances = self.compute_api.get_all(context, search_opts=search_opts, sort_keys=['created_at'], sort_dirs=['asc'], want_objects=True) except exception.NotFound: instances = [] for instance in instances: if not context.is_admin: if pipelib.is_vpn_image(instance.image_ref): continue i = {} instance_uuid = instance.uuid ec2_id = ec2utils.id_to_ec2_inst_id(instance_uuid) i['instanceId'] = ec2_id image_uuid = instance.image_ref i['imageId'] = ec2utils.glance_id_to_ec2_id(context, image_uuid) self._format_kernel_id(context, instance, i, 'kernelId') self._format_ramdisk_id(context, instance, i, 'ramdiskId') i['instanceState'] = _state_description( instance.vm_state, instance.shutdown_terminate) fixed_ip = None floating_ip = None ip_info = ec2utils.get_ip_info_for_instance(context, instance) if ip_info['fixed_ips']: fixed_ip = ip_info['fixed_ips'][0] if ip_info['floating_ips']: floating_ip = ip_info['floating_ips'][0] if ip_info['fixed_ip6s']: i['dnsNameV6'] = ip_info['fixed_ip6s'][0] if CONF.ec2_private_dns_show_ip: i['privateDnsName'] = fixed_ip else: i['privateDnsName'] = instance.hostname i['privateIpAddress'] = fixed_ip if floating_ip is not None: i['ipAddress'] = floating_ip i['dnsName'] = floating_ip i['keyName'] = instance.key_name i['tagSet'] = [] for k, v in six.iteritems(utils.instance_meta(instance)): i['tagSet'].append({'key': k, 'value': v}) client_token = self._get_client_token(context, instance_uuid) if client_token: i['clientToken'] = client_token if context.is_admin: i['keyName'] = '%s (%s, %s)' % (i['keyName'], instance.project_id, instance.host) i['productCodesSet'] = utils.convert_to_list_dict([], 'product_codes') self._format_instance_type(instance, i) i['launchTime'] = instance.created_at i['amiLaunchIndex'] = instance.launch_index self._format_instance_root_device_name(instance, i) self._format_instance_bdm(context, instance.uuid, i['rootDeviceName'], i) zone = availability_zones.get_instance_availability_zone(context, instance) i['placement'] = {'availabilityZone': zone} if instance.reservation_id not in reservations: r = {} r['reservationId'] = instance.reservation_id r['ownerId'] = instance.project_id self._format_group_set(instance, r) r['instancesSet'] = [] reservations[instance.reservation_id] = r reservations[instance.reservation_id]['instancesSet'].append(i) return list(reservations.values()) def describe_addresses(self, context, public_ip=None, **kwargs): if public_ip: floatings = [] for address in public_ip: floating = self.network_api.get_floating_ip_by_address(context, address) floatings.append(floating) else: floatings = self.network_api.get_floating_ips_by_project(context) addresses = [self._format_address(context, f) for f in floatings] return {'addressesSet': addresses} def _format_address(self, context, floating_ip): ec2_id = None if floating_ip['fixed_ip_id']: if utils.is_neutron(): fixed_vm_uuid = floating_ip['instance']['uuid'] if fixed_vm_uuid is not None: ec2_id = ec2utils.id_to_ec2_inst_id(fixed_vm_uuid) else: fixed_id = floating_ip['fixed_ip_id'] fixed = self.network_api.get_fixed_ip(context, fixed_id) if fixed['instance_uuid'] is not None: ec2_id = ec2utils.id_to_ec2_inst_id(fixed['instance_uuid']) address = {'public_ip': floating_ip['address'], 'instance_id': ec2_id} if context.is_admin: details = "%s (%s)" % (address['instance_id'], floating_ip['project_id']) address['instance_id'] = details return address def allocate_address(self, context, **kwargs): LOG.info(_LI("Allocate address"), context=context) public_ip = self.network_api.allocate_floating_ip(context) return {'publicIp': public_ip} def release_address(self, context, public_ip, **kwargs): LOG.info(_LI('Release address %s'), public_ip, context=context) self.network_api.release_floating_ip(context, address=public_ip) return {'return': "true"} def associate_address(self, context, instance_id, public_ip, **kwargs): LOG.info(_LI("Associate address %(public_ip)s to instance " "%(instance_id)s"), {'public_ip': public_ip, 'instance_id': instance_id}, context=context) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, instance_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) cached_ipinfo = ec2utils.get_ip_info_for_instance(context, instance) fixed_ips = cached_ipinfo['fixed_ips'] + cached_ipinfo['fixed_ip6s'] if not fixed_ips: msg = _('Unable to associate IP Address, no fixed_ips.') raise exception.NoMoreFixedIps(message=msg) if len(fixed_ips) > 1: LOG.warning(_LW('multiple fixed_ips exist, using the first: %s'), fixed_ips[0]) self.network_api.associate_floating_ip(context, instance, floating_address=public_ip, fixed_address=fixed_ips[0]) return {'return': 'true'} def disassociate_address(self, context, public_ip, **kwargs): instance_id = self.network_api.get_instance_id_by_floating_address( context, public_ip) if instance_id: instance = self.compute_api.get(context, instance_id, want_objects=True) LOG.info(_LI("Disassociate address %s"), public_ip, context=context) self.network_api.disassociate_floating_ip(context, instance, address=public_ip) else: msg = _('Floating ip is not associated.') raise exception.InvalidAssociation(message=msg) return {'return': "true"} def run_instances(self, context, **kwargs): min_count = int(kwargs.get('min_count', 1)) max_count = int(kwargs.get('max_count', min_count)) try: min_count = utils.validate_integer( min_count, "min_count", min_value=1) max_count = utils.validate_integer( max_count, "max_count", min_value=1) except exception.InvalidInput as e: raise exception.InvalidInput(message=e.format_message()) if min_count > max_count: msg = _('min_count must be <= max_count') raise exception.InvalidInput(message=msg) client_token = kwargs.get('client_token') if client_token: resv_id = self._resv_id_from_token(context, client_token) if resv_id: return self._format_run_instances(context, resv_id) if kwargs.get('kernel_id'): kernel = self._get_image(context, kwargs['kernel_id']) kwargs['kernel_id'] = ec2utils.id_to_glance_id(context, kernel['id']) if kwargs.get('ramdisk_id'): ramdisk = self._get_image(context, kwargs['ramdisk_id']) kwargs['ramdisk_id'] = ec2utils.id_to_glance_id(context, ramdisk['id']) for bdm in kwargs.get('block_device_mapping', []): _parse_block_device_mapping(bdm) image = self._get_image(context, kwargs['image_id']) image_uuid = ec2utils.id_to_glance_id(context, image['id']) if image: image_state = self._get_image_state(image) else: raise exception.ImageNotFoundEC2(image_id=kwargs['image_id']) if image_state != 'available': msg = _('Image must be available') raise exception.ImageNotActive(message=msg) iisb = kwargs.get('instance_initiated_shutdown_behavior', 'stop') shutdown_terminate = (iisb == 'terminate') flavor = objects.Flavor.get_by_name(context, kwargs.get('instance_type', None)) (instances, resv_id) = self.compute_api.create(context, instance_type=flavor, image_href=image_uuid, max_count=int(kwargs.get('max_count', min_count)), min_count=min_count, kernel_id=kwargs.get('kernel_id'), ramdisk_id=kwargs.get('ramdisk_id'), key_name=kwargs.get('key_name'), user_data=kwargs.get('user_data'), security_group=kwargs.get('security_group'), availability_zone=kwargs.get('placement', {}).get( 'availability_zone'), block_device_mapping=kwargs.get('block_device_mapping', {}), shutdown_terminate=shutdown_terminate) instances = self._format_run_instances(context, resv_id) if instances: instance_ids = [i['instanceId'] for i in instances['instancesSet']] self._add_client_token(context, client_token, instance_ids) return instances def _add_client_token(self, context, client_token, instance_ids): if client_token: for ec2_id in instance_ids: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = objects.Instance.get_by_uuid(context, instance_uuid, expected_attrs=['system_metadata']) instance.system_metadata.update( {'EC2_client_token': client_token}) instance.save() def _get_client_token(self, context, instance_uuid): instance = objects.Instance.get_by_uuid(context, instance_uuid, expected_attrs=['system_metadata']) return instance.system_metadata.get('EC2_client_token') def _remove_client_token(self, context, instance_ids): for ec2_id in instance_ids: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = objects.Instance.get_by_uuid(context, instance_uuid, expected_attrs=['system_metadata']) instance.system_metadata.pop('EC2_client_token', None) instance.save() def _resv_id_from_token(self, context, client_token): resv_id = None sys_metas = self.compute_api.get_all_system_metadata( context, search_filts=[{'key': ['EC2_client_token']}, {'value': [client_token]}]) for sys_meta in sys_metas: if sys_meta and sys_meta.get('value') == client_token: instance = objects.Instance.get_by_uuid( context, sys_meta['instance_id'], expected_attrs=None) resv_id = instance.get('reservation_id') break return resv_id def _ec2_ids_to_instances(self, context, instance_id): instances = [] extra = ['system_metadata', 'metadata', 'info_cache'] for ec2_id in instance_id: validate_instance_id(ec2_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = objects.Instance.get_by_uuid( context, instance_uuid, expected_attrs=extra) instances.append(instance) return instances def terminate_instances(self, context, instance_id, **kwargs): previous_states = self._ec2_ids_to_instances(context, instance_id) self._remove_client_token(context, instance_id) LOG.debug("Going to start terminating instances") for instance in previous_states: self.compute_api.delete(context, instance) return self._format_terminate_instances(context, instance_id, previous_states) def reboot_instances(self, context, instance_id, **kwargs): instances = self._ec2_ids_to_instances(context, instance_id) LOG.info(_LI("Reboot instance %r"), instance_id, context=context) for instance in instances: self.compute_api.reboot(context, instance, 'HARD') return True def stop_instances(self, context, instance_id, **kwargs): instances = self._ec2_ids_to_instances(context, instance_id) LOG.debug("Going to stop instances") for instance in instances: extensions.check_compute_policy(context, 'stop', instance) self.compute_api.stop(context, instance) return self._format_stop_instances(context, instance_id, instances) def start_instances(self, context, instance_id, **kwargs): instances = self._ec2_ids_to_instances(context, instance_id) LOG.debug("Going to start instances") for instance in instances: extensions.check_compute_policy(context, 'start', instance) self.compute_api.start(context, instance) return self._format_start_instances(context, instance_id, instances) def _get_image(self, context, ec2_id): try: internal_id = ec2utils.ec2_id_to_id(ec2_id) image = self.image_service.show(context, internal_id) except (exception.InvalidEc2Id, exception.ImageNotFound): filters = {'name': ec2_id} images = self.image_service.detail(context, filters=filters) try: return images[0] except IndexError: raise exception.ImageNotFound(image_id=ec2_id) image_type = ec2_id.split('-')[0] if ec2utils.image_type(image.get('container_format')) != image_type: raise exception.ImageNotFound(image_id=ec2_id) return image def _format_image(self, image): i = {} image_type = ec2utils.image_type(image.get('container_format')) ec2_id = ec2utils.image_ec2_id(image.get('id'), image_type) name = image.get('name') i['imageId'] = ec2_id kernel_id = image['properties'].get('kernel_id') if kernel_id: i['kernelId'] = ec2utils.image_ec2_id(kernel_id, 'aki') ramdisk_id = image['properties'].get('ramdisk_id') if ramdisk_id: i['ramdiskId'] = ec2utils.image_ec2_id(ramdisk_id, 'ari') i['imageOwnerId'] = image.get('owner') img_loc = image['properties'].get('image_location') if img_loc: i['imageLocation'] = img_loc else: i['imageLocation'] = "%s (%s)" % (img_loc, name) i['name'] = name if not name and img_loc: i['name'] = img_loc i['imageState'] = self._get_image_state(image) i['description'] = image.get('description') display_mapping = {'aki': 'kernel', 'ari': 'ramdisk', 'ami': 'machine'} i['imageType'] = display_mapping.get(image_type) i['isPublic'] = not not image.get('is_public') i['architecture'] = image['properties'].get('architecture') properties = image['properties'] root_device_name = block_device.properties_root_device_name(properties) root_device_type = 'instance-store' for bdm in properties.get('block_device_mapping', []): if (block_device.strip_dev(bdm.get('device_name')) == block_device.strip_dev(root_device_name) and ('snapshot_id' in bdm or 'volume_id' in bdm) and not bdm.get('no_device')): root_device_type = 'ebs' i['rootDeviceName'] = (root_device_name or block_device.DEFAULT_ROOT_DEV_NAME) i['rootDeviceType'] = root_device_type _format_mappings(properties, i) return i def describe_images(self, context, image_id=None, **kwargs): if image_id: images = [] for ec2_id in image_id: try: image = self._get_image(context, ec2_id) except exception.NotFound: raise exception.ImageNotFound(image_id=ec2_id) images.append(image) else: images = self.image_service.detail(context) images = [self._format_image(i) for i in images] return {'imagesSet': images} def deregister_image(self, context, image_id, **kwargs): LOG.info(_LI("De-registering image %s"), image_id, context=context) image = self._get_image(context, image_id) internal_id = image['id'] self.image_service.delete(context, internal_id) return True def _register_image(self, context, metadata): image = self.image_service.create(context, metadata) image_type = ec2utils.image_type(image.get('container_format')) image_id = ec2utils.image_ec2_id(image['id'], image_type) return image_id def register_image(self, context, image_location=None, **kwargs): if image_location is None and kwargs.get('name'): image_location = kwargs['name'] if image_location is None: msg = _('imageLocation is required') raise exception.MissingParameter(reason=msg) metadata = {'properties': {'image_location': image_location}} if kwargs.get('name'): metadata['name'] = kwargs['name'] else: metadata['name'] = image_location if 'root_device_name' in kwargs: metadata['properties']['root_device_name'] = kwargs.get( 'root_device_name') mappings = [_parse_block_device_mapping(bdm) for bdm in kwargs.get('block_device_mapping', [])] if mappings: metadata['properties']['block_device_mapping'] = mappings image_id = self._register_image(context, metadata) LOG.info(_LI('Registered image %(image_location)s with id ' '%(image_id)s'), {'image_location': image_location, 'image_id': image_id}, context=context) return {'imageId': image_id} def describe_image_attribute(self, context, image_id, attribute, **kwargs): def _block_device_mapping_attribute(image, result): _format_mappings(image['properties'], result) def _launch_permission_attribute(image, result): result['launchPermission'] = [] if image['is_public']: result['launchPermission'].append({'group': 'all'}) def _root_device_name_attribute(image, result): _prop_root_dev_name = block_device.properties_root_device_name result['rootDeviceName'] = _prop_root_dev_name(image['properties']) if result['rootDeviceName'] is None: result['rootDeviceName'] = block_device.DEFAULT_ROOT_DEV_NAME def _kernel_attribute(image, result): kernel_id = image['properties'].get('kernel_id') if kernel_id: result['kernel'] = { 'value': ec2utils.image_ec2_id(kernel_id, 'aki') } def _ramdisk_attribute(image, result): ramdisk_id = image['properties'].get('ramdisk_id') if ramdisk_id: result['ramdisk'] = { 'value': ec2utils.image_ec2_id(ramdisk_id, 'ari') } supported_attributes = { 'blockDeviceMapping': _block_device_mapping_attribute, 'launchPermission': _launch_permission_attribute, 'rootDeviceName': _root_device_name_attribute, 'kernel': _kernel_attribute, 'ramdisk': _ramdisk_attribute, } fn = supported_attributes.get(attribute) if fn is None: raise exception.InvalidAttribute(attr=attribute) try: image = self._get_image(context, image_id) except exception.NotFound: raise exception.ImageNotFound(image_id=image_id) result = {'imageId': image_id} fn(image, result) return result def modify_image_attribute(self, context, image_id, attribute, operation_type, **kwargs): if attribute != 'launchPermission': raise exception.InvalidAttribute(attr=attribute) if 'user_group' not in kwargs: msg = _('user or group not specified') raise exception.MissingParameter(reason=msg) if len(kwargs['user_group']) != 1 and kwargs['user_group'][0] != 'all': msg = _('only group "all" is supported') raise exception.InvalidParameterValue(message=msg) if operation_type not in ['add', 'remove']: msg = _('operation_type must be add or remove') raise exception.InvalidParameterValue(message=msg) LOG.info(_LI("Updating image %s publicity"), image_id, context=context) try: image = self._get_image(context, image_id) except exception.NotFound: raise exception.ImageNotFound(image_id=image_id) internal_id = image['id'] del(image['id']) image['is_public'] = (operation_type == 'add') try: return self.image_service.update(context, internal_id, image) except exception.ImageNotAuthorized: msg = _('Not allowed to modify attributes for image %s') % image_id raise exception.Forbidden(message=msg) def update_image(self, context, image_id, **kwargs): internal_id = ec2utils.ec2_id_to_id(image_id) result = self.image_service.update(context, internal_id, dict(kwargs)) return result def create_image(self, context, instance_id, **kwargs): no_reboot = kwargs.get('no_reboot', False) name = kwargs.get('name') validate_instance_id(instance_id) ec2_instance_id = instance_id instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_instance_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) if not self.compute_api.is_volume_backed_instance(context, instance): msg = _("Invalid value '%(ec2_instance_id)s' for instanceId. " "Instance does not have a volume attached at root " "(%(root)s)") % {'root': instance.root_device_name, 'ec2_instance_id': ec2_instance_id} raise exception.InvalidParameterValue(err=msg) restart_instance = False if not no_reboot: vm_state = instance.vm_state if vm_state not in (vm_states.ACTIVE, vm_states.STOPPED): raise exception.InstanceNotRunning(instance_id=ec2_instance_id) if vm_state == vm_states.ACTIVE: restart_instance = True # stop request is complete before we begin polling the state. self.compute_api.stop(context, instance, do_cast=False) # wait instance for really stopped (and not transitioning tasks) start_time = time.time() while (vm_state != vm_states.STOPPED and instance.task_state is not None): time.sleep(1) instance.refresh() vm_state = instance.vm_state # NOTE(yamahata): timeout and error. 1 hour for now for safety. # Is it too short/long? # Or is there any better way? timeout = 1 * 60 * 60 if time.time() > start_time + timeout: err = (_("Couldn't stop instance %(instance)s within " "1 hour. Current vm_state: %(vm_state)s, " "current task_state: %(task_state)s") % {'instance': instance_uuid, 'vm_state': vm_state, 'task_state': instance.task_state}) raise exception.InternalError(message=err) name_map = dict(instance=instance_uuid, now=utils.isotime()) name = name or _('image of %(instance)s at %(now)s') % name_map new_image = self.compute_api.snapshot_volume_backed(context, instance, name) ec2_id = ec2utils.glance_id_to_ec2_id(context, new_image['id']) if restart_instance: self.compute_api.start(context, instance) return {'imageId': ec2_id} def create_tags(self, context, **kwargs): resources = kwargs.get('resource_id', None) tags = kwargs.get('tag', None) if resources is None or tags is None: msg = _('resource_id and tag are required') raise exception.MissingParameter(reason=msg) if not isinstance(resources, (tuple, list, set)): msg = _('Expecting a list of resources') raise exception.InvalidParameterValue(message=msg) for r in resources: if ec2utils.resource_type_from_id(context, r) != 'instance': msg = _('Only instances implemented') raise exception.InvalidParameterValue(message=msg) if not isinstance(tags, (tuple, list, set)): msg = _('Expecting a list of tagSets') raise exception.InvalidParameterValue(message=msg) metadata = {} for tag in tags: if not isinstance(tag, dict): err = _('Expecting tagSet to be key/value pairs') raise exception.InvalidParameterValue(message=err) key = tag.get('key', None) val = tag.get('value', None) if key is None or val is None: err = _('Expecting both key and value to be set') raise exception.InvalidParameterValue(message=err) metadata[key] = val for ec2_id in resources: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) self.compute_api.update_instance_metadata(context, instance, metadata) return True def delete_tags(self, context, **kwargs): resources = kwargs.get('resource_id', None) tags = kwargs.get('tag', None) if resources is None or tags is None: msg = _('resource_id and tag are required') raise exception.MissingParameter(reason=msg) if not isinstance(resources, (tuple, list, set)): msg = _('Expecting a list of resources') raise exception.InvalidParameterValue(message=msg) for r in resources: if ec2utils.resource_type_from_id(context, r) != 'instance': msg = _('Only instances implemented') raise exception.InvalidParameterValue(message=msg) if not isinstance(tags, (tuple, list, set)): msg = _('Expecting a list of tagSets') raise exception.InvalidParameterValue(message=msg) for ec2_id in resources: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) for tag in tags: if not isinstance(tag, dict): msg = _('Expecting tagSet to be key/value pairs') raise exception.InvalidParameterValue(message=msg) key = tag.get('key', None) if key is None: msg = _('Expecting key to be set') raise exception.InvalidParameterValue(message=msg) self.compute_api.delete_instance_metadata(context, instance, key) return True def describe_tags(self, context, **kwargs): filters = kwargs.get('filter', None) search_filts = [] if filters: for filter_block in filters: key_name = filter_block.get('name', None) val = filter_block.get('value', None) if val: if isinstance(val, dict): val = val.values() if not isinstance(val, (tuple, list, set)): val = (val,) if key_name: search_block = {} if key_name in ('resource_id', 'resource-id'): search_block['resource_id'] = [] for res_id in val: search_block['resource_id'].append( ec2utils.ec2_inst_id_to_uuid(context, res_id)) elif key_name in ['key', 'value']: search_block[key_name] = \ [ec2utils.regex_from_ec2_regex(v) for v in val] elif key_name in ('resource_type', 'resource-type'): for res_type in val: if res_type != 'instance': raise exception.InvalidParameterValue( message=_('Only instances implemented')) search_block[key_name] = 'instance' if len(search_block.keys()) > 0: search_filts.append(search_block) ts = [] for tag in self.compute_api.get_all_instance_metadata(context, search_filts): ts.append({ 'resource_id': ec2utils.id_to_ec2_inst_id(tag['instance_id']), 'resource_type': 'instance', 'key': tag['key'], 'value': tag['value'] }) return {"tagSet": ts} class EC2SecurityGroupExceptions(object): @staticmethod def raise_invalid_property(msg): raise exception.InvalidParameterValue(message=msg) @staticmethod def raise_group_already_exists(msg): raise exception.SecurityGroupExists(message=msg) @staticmethod def raise_invalid_group(msg): raise exception.InvalidGroup(reason=msg) @staticmethod def raise_invalid_cidr(cidr, decoding_exception=None): if decoding_exception: raise decoding_exception else: raise exception.InvalidParameterValue(message=_("Invalid CIDR")) @staticmethod def raise_over_quota(msg): raise exception.SecurityGroupLimitExceeded(msg) @staticmethod def raise_not_found(msg): pass class CloudSecurityGroupNovaAPI(EC2SecurityGroupExceptions, compute_api.SecurityGroupAPI): pass class CloudSecurityGroupNeutronAPI(EC2SecurityGroupExceptions, neutron_driver.SecurityGroupAPI): pass def get_cloud_security_group_api(): if cfg.CONF.security_group_api.lower() == 'nova': return CloudSecurityGroupNovaAPI() elif openstack_driver.is_neutron_security_groups(): return CloudSecurityGroupNeutronAPI() else: raise NotImplementedError()
true
true
f736067c291f132a6c0900f6b550c84cb433a313
2,513
py
Python
themes/prompt-toolkit/base16/base16-ashes.py
base16-fork/base16-fork
79856b7e6195dde0874a9e6d191101ac6c5c74f5
[ "MIT" ]
null
null
null
themes/prompt-toolkit/base16/base16-ashes.py
base16-fork/base16-fork
79856b7e6195dde0874a9e6d191101ac6c5c74f5
[ "MIT" ]
null
null
null
themes/prompt-toolkit/base16/base16-ashes.py
base16-fork/base16-fork
79856b7e6195dde0874a9e6d191101ac6c5c74f5
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # base16-prompt-toolkit (https://github.com/memeplex/base16-prompt-toolkit) # Base16 Prompt Toolkit template by Carlos Pita (carlosjosepita@gmail.com # Ashes scheme by Jannik Siebert (https://github.com/janniks) try: # older than v2 from prompt_toolkit.output.vt100 import _256_colors except ModuleNotFoundError: # version 2 from prompt_toolkit.formatted_text.ansi import _256_colors from pygments.style import Style from pygments.token import (Keyword, Name, Comment, String, Error, Text, Number, Operator, Literal, Token) # See http://chriskempson.com/projects/base16/ for a description of the role # of the different colors in the base16 palette. base00 = '#1C2023' base01 = '#393F45' base02 = '#565E65' base03 = '#747C84' base04 = '#ADB3BA' base05 = '#C7CCD1' base06 = '#DFE2E5' base07 = '#F3F4F5' base08 = '#C7AE95' base09 = '#C7C795' base0A = '#AEC795' base0B = '#95C7AE' base0C = '#95AEC7' base0D = '#AE95C7' base0E = '#C795AE' base0F = '#C79595' # See https://github.com/jonathanslenders/python-prompt-toolkit/issues/355 colors = (globals()['base0' + d] for d in '08BADEC5379F1246') for i, color in enumerate(colors): r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:], 16) _256_colors[r, g, b] = i + 6 if i > 8 else i # See http://pygments.org/docs/tokens/ for a description of the different # pygments tokens. class Base16Style(Style): background_color = base00 highlight_color = base02 default_style = base05 styles = { Text: base05, Error: '%s bold' % base08, Comment: base03, Keyword: base0E, Keyword.Constant: base09, Keyword.Namespace: base0D, Name.Builtin: base0D, Name.Function: base0D, Name.Class: base0D, Name.Decorator: base0E, Name.Exception: base08, Number: base09, Operator: base0E, Literal: base0B, String: base0B } # See https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/styles/defaults.py # for a description of prompt_toolkit related pseudo-tokens. overrides = { Token.Prompt: base0B, Token.PromptNum: '%s bold' % base0B, Token.OutPrompt: base08, Token.OutPromptNum: '%s bold' % base08, Token.Menu.Completions.Completion: 'bg:%s %s' % (base01, base04), Token.Menu.Completions.Completion.Current: 'bg:%s %s' % (base04, base01), Token.MatchingBracket.Other: 'bg:%s %s' % (base03, base00) }
30.277108
109
0.672503
try: from prompt_toolkit.output.vt100 import _256_colors except ModuleNotFoundError: from prompt_toolkit.formatted_text.ansi import _256_colors from pygments.style import Style from pygments.token import (Keyword, Name, Comment, String, Error, Text, Number, Operator, Literal, Token) base00 = '#1C2023' base01 = '#393F45' base02 = '#565E65' base03 = '#747C84' base04 = '#ADB3BA' base05 = '#C7CCD1' base06 = '#DFE2E5' base07 = '#F3F4F5' base08 = '#C7AE95' base09 = '#C7C795' base0A = '#AEC795' base0B = '#95C7AE' base0C = '#95AEC7' base0D = '#AE95C7' base0E = '#C795AE' base0F = '#C79595' colors = (globals()['base0' + d] for d in '08BADEC5379F1246') for i, color in enumerate(colors): r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:], 16) _256_colors[r, g, b] = i + 6 if i > 8 else i class Base16Style(Style): background_color = base00 highlight_color = base02 default_style = base05 styles = { Text: base05, Error: '%s bold' % base08, Comment: base03, Keyword: base0E, Keyword.Constant: base09, Keyword.Namespace: base0D, Name.Builtin: base0D, Name.Function: base0D, Name.Class: base0D, Name.Decorator: base0E, Name.Exception: base08, Number: base09, Operator: base0E, Literal: base0B, String: base0B } overrides = { Token.Prompt: base0B, Token.PromptNum: '%s bold' % base0B, Token.OutPrompt: base08, Token.OutPromptNum: '%s bold' % base08, Token.Menu.Completions.Completion: 'bg:%s %s' % (base01, base04), Token.Menu.Completions.Completion.Current: 'bg:%s %s' % (base04, base01), Token.MatchingBracket.Other: 'bg:%s %s' % (base03, base00) }
true
true
f73607458de05c74a1a0f5bb517b47cd8333529d
389
py
Python
djangoapp/website/migrations/0002_userlocation_google_maps_location.py
jaysridhar/fuzzy-spoon
43ff6c424c6fe8e0d46cbb1555ada57957bf0cb4
[ "MIT" ]
null
null
null
djangoapp/website/migrations/0002_userlocation_google_maps_location.py
jaysridhar/fuzzy-spoon
43ff6c424c6fe8e0d46cbb1555ada57957bf0cb4
[ "MIT" ]
null
null
null
djangoapp/website/migrations/0002_userlocation_google_maps_location.py
jaysridhar/fuzzy-spoon
43ff6c424c6fe8e0d46cbb1555ada57957bf0cb4
[ "MIT" ]
null
null
null
# Generated by Django 4.0.2 on 2022-02-19 12:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0001_initial'), ] operations = [ migrations.AddField( model_name='userlocation', name='google_maps_location', field=models.TextField(null=True), ), ]
20.473684
47
0.601542
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0001_initial'), ] operations = [ migrations.AddField( model_name='userlocation', name='google_maps_location', field=models.TextField(null=True), ), ]
true
true
f73608570f38fd239f778eadc8b505e51cab2f8a
3,010
py
Python
Autodroid/notebook/azurlane.py
AutumnSun1996/GameTools
05ed69c09e69e284092cfaffd9eb6313f654c729
[ "BSD-3-Clause" ]
null
null
null
Autodroid/notebook/azurlane.py
AutumnSun1996/GameTools
05ed69c09e69e284092cfaffd9eb6313f654c729
[ "BSD-3-Clause" ]
null
null
null
Autodroid/notebook/azurlane.py
AutumnSun1996/GameTools
05ed69c09e69e284092cfaffd9eb6313f654c729
[ "BSD-3-Clause" ]
null
null
null
from .common import * from azurlane.map_anchor import * from azurlane import load_map const["section"] = "azurlane" def check_map_anchor(anchor): s = const["s"] if isinstance(anchor, str): anchor = s.data["Anchors"][anchor] if "ImageData" not in anchor: load_image(anchor, s.section) diff, pos = get_match(s.screen, anchor["ImageData"]) print(diff, pos) x, y = pos w, h = anchor["Size"] dx, dy = anchor["Offset"] draw = s.screen.copy() for node_name in s.g.nodes: nx, ny = s.get_map_pos(anchor["OnMap"], (x + dx, y + dy), node_name) cv.circle(draw, (nx, ny), 3, (0, 0, 0), -1) cv.rectangle(draw, (x, y), (x + w, y + h), (255, 255, 255), 2) cv.circle(draw, (x + dx, y + dy), 5, (255, 255, 255), -1) show(draw) def init_map(name): const["s"] = load_map(name) const["s"].make_screen_shot() reset_log() return const["s"] def get_grid_center(self, offx, offy): """返回格子中心点坐标列表,包括棋盘坐标和屏幕坐标""" warped = cv.warpPerspective(self.screen, trans_matrix, target_size) filtered_map = cv.filter2D(warped, 0, filter_kernel) _, poses = self.search_resource("Corner", image=filtered_map) if len(poses) < 3: raise RuntimeError("Less than 4 anchors found. ") poses = np.array(poses) poses += self.resources["Corner"]["Offset"] diff = poses % 100 dx = np.argmax(np.bincount(diff[:, 0])) dy = np.argmax(np.bincount(diff[:, 1])) res = dx + 100 * offx, dy + 100 * offy res = (np.array(list(res), dtype="float") + 50).reshape(1, -1, 2) pos_in_screen = cv.perspectiveTransform(res, inv_trans).reshape(-1, 2).astype("int") print(pos_in_screen) return pos_in_screen[0] def crop_in_map(center, offset, size): s = const["s"] x, y = center wh = np.array(list(reversed(s.screen.shape[:2]))) coef = 0.0005907301142274507 r = coef * y + 1 lt = np.asarray(offset) * r + [x, y] rb = lt + np.asarray(size) * r if lt.min() < 0: return None if np.any(rb > wh): return None print("lt/rb", lt, rb) part = cv_crop(s.screen, (*lt.astype("int"), *rb.astype("int"))) return part, lt, rb def save_enemy(pos, info): ''' Example: save_enemy((3, 2), """ CropOffset: [-40, -100] CropSize: [80, 110] Image: Enemy/E2.png Offset: [-30, -90] Size: [60, 90] Type: Dynamic """) ''' s = const["s"] if isinstance(info, str): info = hocon.loads(info) offset = info["CropOffset"] size = info["CropSize"] diff_s = [] results = [] x, y = get_grid_center(s, *pos) part = crop_in_map((x, y), info["CropOffset"], info["CropSize"]) # part = cv.resize(part, tuple(size)) show(part[0]) part = crop_in_map((x, y), info["Offset"], info["Size"]) show(part[0]) path = "%s/resources/%s" % (const["section"], info["Image"]) cv_save(path, part[0]) logger.info("%s Saved.", os.path.realpath(path))
28.666667
88
0.579402
from .common import * from azurlane.map_anchor import * from azurlane import load_map const["section"] = "azurlane" def check_map_anchor(anchor): s = const["s"] if isinstance(anchor, str): anchor = s.data["Anchors"][anchor] if "ImageData" not in anchor: load_image(anchor, s.section) diff, pos = get_match(s.screen, anchor["ImageData"]) print(diff, pos) x, y = pos w, h = anchor["Size"] dx, dy = anchor["Offset"] draw = s.screen.copy() for node_name in s.g.nodes: nx, ny = s.get_map_pos(anchor["OnMap"], (x + dx, y + dy), node_name) cv.circle(draw, (nx, ny), 3, (0, 0, 0), -1) cv.rectangle(draw, (x, y), (x + w, y + h), (255, 255, 255), 2) cv.circle(draw, (x + dx, y + dy), 5, (255, 255, 255), -1) show(draw) def init_map(name): const["s"] = load_map(name) const["s"].make_screen_shot() reset_log() return const["s"] def get_grid_center(self, offx, offy): warped = cv.warpPerspective(self.screen, trans_matrix, target_size) filtered_map = cv.filter2D(warped, 0, filter_kernel) _, poses = self.search_resource("Corner", image=filtered_map) if len(poses) < 3: raise RuntimeError("Less than 4 anchors found. ") poses = np.array(poses) poses += self.resources["Corner"]["Offset"] diff = poses % 100 dx = np.argmax(np.bincount(diff[:, 0])) dy = np.argmax(np.bincount(diff[:, 1])) res = dx + 100 * offx, dy + 100 * offy res = (np.array(list(res), dtype="float") + 50).reshape(1, -1, 2) pos_in_screen = cv.perspectiveTransform(res, inv_trans).reshape(-1, 2).astype("int") print(pos_in_screen) return pos_in_screen[0] def crop_in_map(center, offset, size): s = const["s"] x, y = center wh = np.array(list(reversed(s.screen.shape[:2]))) coef = 0.0005907301142274507 r = coef * y + 1 lt = np.asarray(offset) * r + [x, y] rb = lt + np.asarray(size) * r if lt.min() < 0: return None if np.any(rb > wh): return None print("lt/rb", lt, rb) part = cv_crop(s.screen, (*lt.astype("int"), *rb.astype("int"))) return part, lt, rb def save_enemy(pos, info): s = const["s"] if isinstance(info, str): info = hocon.loads(info) offset = info["CropOffset"] size = info["CropSize"] diff_s = [] results = [] x, y = get_grid_center(s, *pos) part = crop_in_map((x, y), info["CropOffset"], info["CropSize"]) show(part[0]) part = crop_in_map((x, y), info["Offset"], info["Size"]) show(part[0]) path = "%s/resources/%s" % (const["section"], info["Image"]) cv_save(path, part[0]) logger.info("%s Saved.", os.path.realpath(path))
true
true
f7360a0c4e6ebfce8f3547e0f10c143613ae8d9d
1,943
py
Python
jetbot/motor.py
geoc1234/jetbot
f2a8ab3bf581db53d22d788f98b7dd7ebde8bcb0
[ "MIT" ]
2,624
2019-03-18T23:46:13.000Z
2022-03-31T01:50:47.000Z
jetbot/motor.py
geoc1234/jetbot
f2a8ab3bf581db53d22d788f98b7dd7ebde8bcb0
[ "MIT" ]
389
2019-03-19T06:00:11.000Z
2022-03-28T14:08:53.000Z
jetbot/motor.py
geoc1234/jetbot
f2a8ab3bf581db53d22d788f98b7dd7ebde8bcb0
[ "MIT" ]
927
2019-03-18T23:27:46.000Z
2022-03-31T17:22:24.000Z
import atexit from Adafruit_MotorHAT import Adafruit_MotorHAT import traitlets from traitlets.config.configurable import Configurable class Motor(Configurable): value = traitlets.Float() # config alpha = traitlets.Float(default_value=1.0).tag(config=True) beta = traitlets.Float(default_value=0.0).tag(config=True) def __init__(self, driver, channel, *args, **kwargs): super(Motor, self).__init__(*args, **kwargs) # initializes traitlets self._driver = driver self._motor = self._driver.getMotor(channel) if(channel == 1): self._ina = 1 self._inb = 0 else: self._ina = 2 self._inb = 3 atexit.register(self._release) @traitlets.observe('value') def _observe_value(self, change): self._write_value(change['new']) def _write_value(self, value): """Sets motor value between [-1, 1]""" mapped_value = int(255.0 * (self.alpha * value + self.beta)) speed = min(max(abs(mapped_value), 0), 255) self._motor.setSpeed(speed) if mapped_value < 0: self._motor.run(Adafruit_MotorHAT.FORWARD) # The two lines below are required for the Waveshare JetBot Board only self._driver._pwm.setPWM(self._ina,0,0) self._driver._pwm.setPWM(self._inb,0,speed*16) else: self._motor.run(Adafruit_MotorHAT.BACKWARD) # The two lines below are required for the Waveshare JetBot Board only self._driver._pwm.setPWM(self._ina,0,speed*16) self._driver._pwm.setPWM(self._inb,0,0) def _release(self): """Stops motor by releasing control""" self._motor.run(Adafruit_MotorHAT.RELEASE) # The two lines below are required for the Waveshare JetBot Board only self._driver._pwm.setPWM(self._ina,0,0) self._driver._pwm.setPWM(self._inb,0,0)
35.981481
82
0.63613
import atexit from Adafruit_MotorHAT import Adafruit_MotorHAT import traitlets from traitlets.config.configurable import Configurable class Motor(Configurable): value = traitlets.Float() alpha = traitlets.Float(default_value=1.0).tag(config=True) beta = traitlets.Float(default_value=0.0).tag(config=True) def __init__(self, driver, channel, *args, **kwargs): super(Motor, self).__init__(*args, **kwargs) self._driver = driver self._motor = self._driver.getMotor(channel) if(channel == 1): self._ina = 1 self._inb = 0 else: self._ina = 2 self._inb = 3 atexit.register(self._release) @traitlets.observe('value') def _observe_value(self, change): self._write_value(change['new']) def _write_value(self, value): mapped_value = int(255.0 * (self.alpha * value + self.beta)) speed = min(max(abs(mapped_value), 0), 255) self._motor.setSpeed(speed) if mapped_value < 0: self._motor.run(Adafruit_MotorHAT.FORWARD) self._driver._pwm.setPWM(self._ina,0,0) self._driver._pwm.setPWM(self._inb,0,speed*16) else: self._motor.run(Adafruit_MotorHAT.BACKWARD) self._driver._pwm.setPWM(self._ina,0,speed*16) self._driver._pwm.setPWM(self._inb,0,0) def _release(self): self._motor.run(Adafruit_MotorHAT.RELEASE) self._driver._pwm.setPWM(self._ina,0,0) self._driver._pwm.setPWM(self._inb,0,0)
true
true
f7360acfd665c25a347616938a4061ba9447cf97
3,473
py
Python
python/ray/tune/automlboard/run.py
dsctt/ray
29d94a22114b02adfd3745c4991a3ce70592dd16
[ "Apache-2.0" ]
1
2021-09-20T15:45:59.000Z
2021-09-20T15:45:59.000Z
python/ray/tune/automlboard/run.py
dsctt/ray
29d94a22114b02adfd3745c4991a3ce70592dd16
[ "Apache-2.0" ]
53
2021-10-06T20:08:04.000Z
2022-03-21T20:17:25.000Z
python/ray/tune/automlboard/run.py
dsctt/ray
29d94a22114b02adfd3745c4991a3ce70592dd16
[ "Apache-2.0" ]
null
null
null
import logging import os import re import django import argparse from django.core.management import execute_from_command_line from common.exception import DatabaseError root_path = os.path.dirname(os.path.abspath(__file__)) logger = logging.getLogger(__name__) def run_board(args): """ Run main entry for AutoMLBoard. Args: args: args parsed from command line """ init_config(args) # backend service, should import after django settings initialized from backend.collector import CollectorService service = CollectorService( args.logdir, args.reload_interval, standalone=False, log_level=args.log_level ) service.run() # frontend service logger.info("Try to start automlboard on port %s\n" % args.port) command = [ os.path.join(root_path, "manage.py"), "runserver", "0.0.0.0:%s" % args.port, "--noreload", ] execute_from_command_line(command) def init_config(args): """ Initialize configs of the service. Do the following things: 1. automl board settings 2. database settings 3. django settings """ os.environ["AUTOMLBOARD_LOGDIR"] = args.logdir os.environ["AUTOMLBOARD_LOGLEVEL"] = args.log_level os.environ["AUTOMLBOARD_RELOAD_INTERVAL"] = str(args.reload_interval) if args.db: try: db_address_reg = re.compile(r"(.*)://(.*):(.*)@(.*):(.*)/(.*)") match = re.match(db_address_reg, args.db_address) os.environ["AUTOMLBOARD_DB_ENGINE"] = match.group(1) os.environ["AUTOMLBOARD_DB_USER"] = match.group(2) os.environ["AUTOMLBOARD_DB_PASSWORD"] = match.group(3) os.environ["AUTOMLBOARD_DB_HOST"] = match.group(4) os.environ["AUTOMLBOARD_DB_PORT"] = match.group(5) os.environ["AUTOMLBOARD_DB_NAME"] = match.group(6) logger.info("Using %s as the database backend." % match.group(1)) except BaseException as e: raise DatabaseError(e) else: logger.info( "Using sqlite3 as the database backend, " "information will be stored in automlboard.db" ) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ray.tune.automlboard.settings") django.setup() command = [os.path.join(root_path, "manage.py"), "migrate", "--run-syncdb"] execute_from_command_line(command) def main(): parser = argparse.ArgumentParser() parser.add_argument( "--logdir", type=str, required=True, help="Directory where AutoML Board will " "look to find tuning logs it can display", ) parser.add_argument( "--port", type=int, default=8008, help="What port to serve AutoMLBoard on, " "(default: %(default)s)", ) parser.add_argument( "--db", type=str, default=None, help="Set SQL database URI in " "schema://user:password@host:port/database, " "(default: sqlite3)", ), parser.add_argument( "--reload_interval", type=int, default=5, help="How often the backend should load more data, " "(default: %(default)s)", ) parser.add_argument( "--log_level", type=str, default="INFO", help="Set the logging level, " "(default: %(default)s)", ) cmd_args = parser.parse_args() run_board(cmd_args) if __name__ == "__main__": main()
28.467213
86
0.620789
import logging import os import re import django import argparse from django.core.management import execute_from_command_line from common.exception import DatabaseError root_path = os.path.dirname(os.path.abspath(__file__)) logger = logging.getLogger(__name__) def run_board(args): init_config(args) from backend.collector import CollectorService service = CollectorService( args.logdir, args.reload_interval, standalone=False, log_level=args.log_level ) service.run() logger.info("Try to start automlboard on port %s\n" % args.port) command = [ os.path.join(root_path, "manage.py"), "runserver", "0.0.0.0:%s" % args.port, "--noreload", ] execute_from_command_line(command) def init_config(args): os.environ["AUTOMLBOARD_LOGDIR"] = args.logdir os.environ["AUTOMLBOARD_LOGLEVEL"] = args.log_level os.environ["AUTOMLBOARD_RELOAD_INTERVAL"] = str(args.reload_interval) if args.db: try: db_address_reg = re.compile(r"(.*)://(.*):(.*)@(.*):(.*)/(.*)") match = re.match(db_address_reg, args.db_address) os.environ["AUTOMLBOARD_DB_ENGINE"] = match.group(1) os.environ["AUTOMLBOARD_DB_USER"] = match.group(2) os.environ["AUTOMLBOARD_DB_PASSWORD"] = match.group(3) os.environ["AUTOMLBOARD_DB_HOST"] = match.group(4) os.environ["AUTOMLBOARD_DB_PORT"] = match.group(5) os.environ["AUTOMLBOARD_DB_NAME"] = match.group(6) logger.info("Using %s as the database backend." % match.group(1)) except BaseException as e: raise DatabaseError(e) else: logger.info( "Using sqlite3 as the database backend, " "information will be stored in automlboard.db" ) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ray.tune.automlboard.settings") django.setup() command = [os.path.join(root_path, "manage.py"), "migrate", "--run-syncdb"] execute_from_command_line(command) def main(): parser = argparse.ArgumentParser() parser.add_argument( "--logdir", type=str, required=True, help="Directory where AutoML Board will " "look to find tuning logs it can display", ) parser.add_argument( "--port", type=int, default=8008, help="What port to serve AutoMLBoard on, " "(default: %(default)s)", ) parser.add_argument( "--db", type=str, default=None, help="Set SQL database URI in " "schema://user:password@host:port/database, " "(default: sqlite3)", ), parser.add_argument( "--reload_interval", type=int, default=5, help="How often the backend should load more data, " "(default: %(default)s)", ) parser.add_argument( "--log_level", type=str, default="INFO", help="Set the logging level, " "(default: %(default)s)", ) cmd_args = parser.parse_args() run_board(cmd_args) if __name__ == "__main__": main()
true
true
f7360b1ff28ca8cb8ff567284e2ce156676903d0
134
py
Python
monkeys-and-frogs-on-fire/server/__main__.py
markjoshua12/game-jam-2020
846dd052d649a609ab7a52ac0f4dcbeb71781c3b
[ "MIT" ]
15
2020-04-17T12:02:14.000Z
2022-03-16T03:01:34.000Z
monkeys-and-frogs-on-fire/server/__main__.py
markjoshua12/game-jam-2020
846dd052d649a609ab7a52ac0f4dcbeb71781c3b
[ "MIT" ]
49
2020-04-18T21:14:57.000Z
2022-01-13T03:05:09.000Z
monkeys-and-frogs-on-fire/server/__main__.py
markjoshua12/game-jam-2020
846dd052d649a609ab7a52ac0f4dcbeb71781c3b
[ "MIT" ]
55
2020-04-17T12:01:11.000Z
2021-12-28T10:14:02.000Z
from server.server import Server def main(): server = Server(__file__) server.run() if __name__ == '__main__': main()
12.181818
32
0.641791
from server.server import Server def main(): server = Server(__file__) server.run() if __name__ == '__main__': main()
true
true
f7360c33495af521ae375f81a7d93ff6ad67026e
483
py
Python
matches/migrations/0018_matchdata_selected_team.py
ebaymademepoor/django_milestone_project_myTeam
95d503e2c303b9525e9eaff2e08340f6e9f1987b
[ "ADSL" ]
null
null
null
matches/migrations/0018_matchdata_selected_team.py
ebaymademepoor/django_milestone_project_myTeam
95d503e2c303b9525e9eaff2e08340f6e9f1987b
[ "ADSL" ]
5
2020-06-05T19:45:53.000Z
2022-03-11T23:41:23.000Z
matches/migrations/0018_matchdata_selected_team.py
Deirdre18/django_milestone_project_myTeam
0555105f65076214087cfed73802470652dd1dcd
[ "ADSL" ]
2
2019-04-30T11:08:14.000Z
2019-07-24T20:04:50.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-03-29 17:29 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('matches', '0017_auto_20190313_1304'), ] operations = [ migrations.AddField( model_name='matchdata', name='selected_team', field=models.CharField(blank=True, max_length=10000, null=True), ), ]
23
76
0.63147
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('matches', '0017_auto_20190313_1304'), ] operations = [ migrations.AddField( model_name='matchdata', name='selected_team', field=models.CharField(blank=True, max_length=10000, null=True), ), ]
true
true
f7360c6d5fedf31018a93713b4dd66b4be3ad635
2,110
py
Python
Handling-Program-Flow-in-Python/code.py
ashweta81/ga-learner-dsmp-repo
283802b5efbe58ebdb63ef1ba9fb039bbb218245
[ "MIT" ]
null
null
null
Handling-Program-Flow-in-Python/code.py
ashweta81/ga-learner-dsmp-repo
283802b5efbe58ebdb63ef1ba9fb039bbb218245
[ "MIT" ]
null
null
null
Handling-Program-Flow-in-Python/code.py
ashweta81/ga-learner-dsmp-repo
283802b5efbe58ebdb63ef1ba9fb039bbb218245
[ "MIT" ]
null
null
null
# -------------- ##File path for the file file_path def read_file(path): file = open(path,mode='r') sentence=file.readline() file.close() return sentence sample_message=read_file(file_path) #Code starts here # -------------- #Code starts here message_1 = read_file (file_path_1) message_2 = read_file (file_path_2) print(message_1) print(message_2) def fuse_msg(message_a,message_b): quotient=int(message_b)//int(message_a) return str(quotient) secret_msg_1=fuse_msg(message_1,message_2) # -------------- #Code starts here message_3=read_file(file_path_3) print(message_3) def substitute_msg(message_c): if (message_c=='Red'): sub='Army General' elif (message_c=='Green'): sub='Data Scientist' else : sub='Marine Biolgist' return sub secret_msg_2=substitute_msg(message_3) # -------------- # File path for message 4 and message 5 file_path_4 file_path_5 #Code starts here message_4=read_file(file_path_4) message_5=read_file(file_path_5) print(message_4) print(message_5) def compare_msg(message_d,message_e): a_list=message_d.split() b_list=message_e.split() c_list=[i for i in a_list if i not in b_list] final_msg=" ".join(c_list) return final_msg secret_msg_3=compare_msg(message_4,message_5) # -------------- #Code starts here message_6=read_file(file_path_6) print(message_6) def extract_msg(message_f): a_list = message_f.split() even_word = lambda x : (len(x) % 2==0) b_list = filter(even_word , a_list) final_msg = " ".join(b_list) return final_msg secret_msg_4 = extract_msg(message_6) # -------------- #Secret message parts in the correct order message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] final_path= user_data_dir + '/secret_message.txt' #Code starts here secret_msg=secret_msg_3+' '+secret_msg_1+' '+secret_msg_4+' '+secret_msg_2 def write_file(secret_msg, path): f = open (path, 'a+') f.write(secret_msg) f.close write_file(secret_msg, final_path) print(secret_msg)
23.444444
75
0.679621
e(path): file = open(path,mode='r') sentence=file.readline() file.close() return sentence sample_message=read_file(file_path) message_1 = read_file (file_path_1) message_2 = read_file (file_path_2) print(message_1) print(message_2) def fuse_msg(message_a,message_b): quotient=int(message_b)//int(message_a) return str(quotient) secret_msg_1=fuse_msg(message_1,message_2) message_3=read_file(file_path_3) print(message_3) def substitute_msg(message_c): if (message_c=='Red'): sub='Army General' elif (message_c=='Green'): sub='Data Scientist' else : sub='Marine Biolgist' return sub secret_msg_2=substitute_msg(message_3) file_path_4 file_path_5 message_4=read_file(file_path_4) message_5=read_file(file_path_5) print(message_4) print(message_5) def compare_msg(message_d,message_e): a_list=message_d.split() b_list=message_e.split() c_list=[i for i in a_list if i not in b_list] final_msg=" ".join(c_list) return final_msg secret_msg_3=compare_msg(message_4,message_5) message_6=read_file(file_path_6) print(message_6) def extract_msg(message_f): a_list = message_f.split() even_word = lambda x : (len(x) % 2==0) b_list = filter(even_word , a_list) final_msg = " ".join(b_list) return final_msg secret_msg_4 = extract_msg(message_6) message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] final_path= user_data_dir + '/secret_message.txt' secret_msg=secret_msg_3+' '+secret_msg_1+' '+secret_msg_4+' '+secret_msg_2 def write_file(secret_msg, path): f = open (path, 'a+') f.write(secret_msg) f.close write_file(secret_msg, final_path) print(secret_msg)
true
true
f7360f48b9aa14fc0cf71c333bfdbf38b258b6a6
840
py
Python
apis/alembic/versions/cae154d4dcb4_change_systemparameter_key_to_name.py
iii-org/devops-system
71f938c9e225ac24ab9102a8221dc5341a01889c
[ "Apache-2.0" ]
4
2021-07-15T15:59:01.000Z
2022-02-24T02:58:52.000Z
apis/alembic/versions/cae154d4dcb4_change_systemparameter_key_to_name.py
iii-org/devops-system
71f938c9e225ac24ab9102a8221dc5341a01889c
[ "Apache-2.0" ]
4
2020-06-12T04:05:46.000Z
2021-11-09T03:53:13.000Z
apis/alembic/versions/cae154d4dcb4_change_systemparameter_key_to_name.py
iii-org/devops-system
71f938c9e225ac24ab9102a8221dc5341a01889c
[ "Apache-2.0" ]
2
2020-09-29T05:39:28.000Z
2021-11-26T09:52:17.000Z
"""change SystemParameter key to name Revision ID: cae154d4dcb4 Revises: 17e220f9fafb Create Date: 2021-09-24 13:42:12.722846 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'cae154d4dcb4' down_revision = '17e220f9fafb' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('system_parameter', sa.Column('name', sa.String(), nullable=True)) op.drop_column('system_parameter', 'key') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('system_parameter', sa.Column('key', sa.VARCHAR(), autoincrement=False, nullable=True)) op.drop_column('system_parameter', 'name') # ### end Alembic commands ###
27.096774
105
0.705952
from alembic import op import sqlalchemy as sa revision = 'cae154d4dcb4' down_revision = '17e220f9fafb' branch_labels = None depends_on = None def upgrade():
true
true
f73610e4056f257cfc46cfe1ece51fdb25cc295b
10,425
py
Python
powerdnsadmin/models/setting.py
ryanolson/PowerDNS-Admin
44c4531f029581690901b8098c5f9eb50a402966
[ "MIT" ]
2
2020-03-25T22:03:53.000Z
2020-03-27T01:19:16.000Z
powerdnsadmin/models/setting.py
ryanolson/PowerDNS-Admin
44c4531f029581690901b8098c5f9eb50a402966
[ "MIT" ]
null
null
null
powerdnsadmin/models/setting.py
ryanolson/PowerDNS-Admin
44c4531f029581690901b8098c5f9eb50a402966
[ "MIT" ]
null
null
null
import sys import traceback import pytimeparse from ast import literal_eval from distutils.util import strtobool from flask import current_app from .base import db class Setting(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) value = db.Column(db.Text()) defaults = { 'maintenance': False, 'fullscreen_layout': True, 'record_helper': True, 'login_ldap_first': True, 'default_record_table_size': 15, 'default_domain_table_size': 10, 'auto_ptr': False, 'record_quick_edit': True, 'pretty_ipv6_ptr': False, 'dnssec_admins_only': False, 'allow_user_create_domain': False, 'bg_domain_updates': False, 'site_name': 'PowerDNS-Admin', 'site_url': 'http://localhost:9191', 'session_timeout': 10, 'warn_session_timeout': True, 'pdns_api_url': '', 'pdns_api_key': '', 'pdns_api_timeout': 30, 'pdns_version': '4.1.1', 'verify_ssl_connections': True, 'local_db_enabled': True, 'signup_enabled': True, 'verify_user_email': False, 'ldap_enabled': False, 'ldap_type': 'ldap', 'ldap_uri': '', 'ldap_base_dn': '', 'ldap_admin_username': '', 'ldap_admin_password': '', 'ldap_filter_basic': '', 'ldap_filter_group': '', 'ldap_filter_username': '', 'ldap_filter_groupname': '', 'ldap_sg_enabled': False, 'ldap_admin_group': '', 'ldap_operator_group': '', 'ldap_user_group': '', 'ldap_domain': '', 'github_oauth_enabled': False, 'github_oauth_key': '', 'github_oauth_secret': '', 'github_oauth_scope': 'email', 'github_oauth_api_url': 'https://api.github.com/user', 'github_oauth_token_url': 'https://github.com/login/oauth/access_token', 'github_oauth_authorize_url': 'https://github.com/login/oauth/authorize', 'google_oauth_enabled': False, 'google_oauth_client_id': '', 'google_oauth_client_secret': '', 'google_token_url': 'https://oauth2.googleapis.com/token', 'google_oauth_scope': 'openid email profile', 'google_authorize_url': 'https://accounts.google.com/o/oauth2/v2/auth', 'google_base_url': 'https://www.googleapis.com/oauth2/v3/', 'azure_oauth_enabled': False, 'azure_oauth_key': '', 'azure_oauth_secret': '', 'azure_oauth_scope': 'User.Read openid email profile', 'azure_oauth_api_url': 'https://graph.microsoft.com/v1.0/', 'azure_oauth_token_url': 'https://login.microsoftonline.com/[tenancy]/oauth2/v2.0/token', 'azure_oauth_authorize_url': 'https://login.microsoftonline.com/[tenancy]/oauth2/v2.0/authorize', 'azure_sg_enabled': False, 'azure_admin_group': '', 'azure_operator_group': '', 'azure_user_group': '', 'azure_group_accounts_enabled': False, 'azure_group_accounts_name': 'displayName', 'azure_group_accounts_name_re': '', 'azure_group_accounts_description': 'description', 'azure_group_accounts_description_re': '', 'oidc_oauth_enabled': False, 'oidc_oauth_key': '', 'oidc_oauth_secret': '', 'oidc_oauth_scope': 'email', 'oidc_oauth_api_url': '', 'oidc_oauth_token_url': '', 'oidc_oauth_authorize_url': '', 'oidc_oauth_logout_url': '', 'oidc_oauth_username': 'preferred_username', 'oidc_oauth_firstname': 'given_name', 'oidc_oauth_last_name': 'family_name', 'oidc_oauth_email': 'email', 'oidc_oauth_account_name_property': '', 'oidc_oauth_account_description_property': '', 'forward_records_allow_edit': { 'A': True, 'AAAA': True, 'AFSDB': False, 'ALIAS': False, 'CAA': True, 'CERT': False, 'CDNSKEY': False, 'CDS': False, 'CNAME': True, 'DNSKEY': False, 'DNAME': False, 'DS': False, 'HINFO': False, 'KEY': False, 'LOC': True, 'LUA': False, 'MX': True, 'NAPTR': False, 'NS': True, 'NSEC': False, 'NSEC3': False, 'NSEC3PARAM': False, 'OPENPGPKEY': False, 'PTR': True, 'RP': False, 'RRSIG': False, 'SOA': False, 'SPF': True, 'SSHFP': False, 'SRV': True, 'TKEY': False, 'TSIG': False, 'TLSA': False, 'SMIMEA': False, 'TXT': True, 'URI': False }, 'reverse_records_allow_edit': { 'A': False, 'AAAA': False, 'AFSDB': False, 'ALIAS': False, 'CAA': False, 'CERT': False, 'CDNSKEY': False, 'CDS': False, 'CNAME': False, 'DNSKEY': False, 'DNAME': False, 'DS': False, 'HINFO': False, 'KEY': False, 'LOC': True, 'LUA': False, 'MX': False, 'NAPTR': False, 'NS': True, 'NSEC': False, 'NSEC3': False, 'NSEC3PARAM': False, 'OPENPGPKEY': False, 'PTR': True, 'RP': False, 'RRSIG': False, 'SOA': False, 'SPF': False, 'SSHFP': False, 'SRV': False, 'TKEY': False, 'TSIG': False, 'TLSA': False, 'SMIMEA': False, 'TXT': True, 'URI': False }, 'ttl_options': '1 minute,5 minutes,30 minutes,60 minutes,24 hours', } def __init__(self, id=None, name=None, value=None): self.id = id self.name = name self.value = value # allow database autoincrement to do its own ID assignments def __init__(self, name=None, value=None): self.id = None self.name = name self.value = value def set_maintenance(self, mode): maintenance = Setting.query.filter( Setting.name == 'maintenance').first() if maintenance is None: value = self.defaults['maintenance'] maintenance = Setting(name='maintenance', value=str(value)) db.session.add(maintenance) mode = str(mode) try: if maintenance.value != mode: maintenance.value = mode db.session.commit() return True except Exception as e: current_app.logger.error('Cannot set maintenance to {0}. DETAIL: {1}'.format( mode, e)) current_app.logger.debug(traceback.format_exec()) db.session.rollback() return False def toggle(self, setting): current_setting = Setting.query.filter(Setting.name == setting).first() if current_setting is None: value = self.defaults[setting] current_setting = Setting(name=setting, value=str(value)) db.session.add(current_setting) try: if current_setting.value == "True": current_setting.value = "False" else: current_setting.value = "True" db.session.commit() return True except Exception as e: current_app.logger.error('Cannot toggle setting {0}. DETAIL: {1}'.format( setting, e)) current_app.logger.debug(traceback.format_exec()) db.session.rollback() return False def set(self, setting, value): current_setting = Setting.query.filter(Setting.name == setting).first() if current_setting is None: current_setting = Setting(name=setting, value=None) db.session.add(current_setting) value = str(value) try: current_setting.value = value db.session.commit() return True except Exception as e: current_app.logger.error('Cannot edit setting {0}. DETAIL: {1}'.format( setting, e)) current_app.logger.debug(traceback.format_exec()) db.session.rollback() return False def get(self, setting): if setting in self.defaults: result = self.query.filter(Setting.name == setting).first() if result is not None: return strtobool(result.value) if result.value in [ 'True', 'False' ] else result.value else: return self.defaults[setting] else: current_app.logger.error('Unknown setting queried: {0}'.format(setting)) def get_records_allow_to_edit(self): return list( set(self.get_forward_records_allow_to_edit() + self.get_reverse_records_allow_to_edit())) def get_forward_records_allow_to_edit(self): records = self.get('forward_records_allow_edit') f_records = literal_eval(records) if isinstance(records, str) else records r_name = [r for r in f_records if f_records[r]] # Sort alphabetically if python version is smaller than 3.6 if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 6): r_name.sort() return r_name def get_reverse_records_allow_to_edit(self): records = self.get('reverse_records_allow_edit') r_records = literal_eval(records) if isinstance(records, str) else records r_name = [r for r in r_records if r_records[r]] # Sort alphabetically if python version is smaller than 3.6 if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 6): r_name.sort() return r_name def get_ttl_options(self): return [(pytimeparse.parse(ttl), ttl) for ttl in self.get('ttl_options').split(',')]
34.519868
89
0.539472
import sys import traceback import pytimeparse from ast import literal_eval from distutils.util import strtobool from flask import current_app from .base import db class Setting(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) value = db.Column(db.Text()) defaults = { 'maintenance': False, 'fullscreen_layout': True, 'record_helper': True, 'login_ldap_first': True, 'default_record_table_size': 15, 'default_domain_table_size': 10, 'auto_ptr': False, 'record_quick_edit': True, 'pretty_ipv6_ptr': False, 'dnssec_admins_only': False, 'allow_user_create_domain': False, 'bg_domain_updates': False, 'site_name': 'PowerDNS-Admin', 'site_url': 'http://localhost:9191', 'session_timeout': 10, 'warn_session_timeout': True, 'pdns_api_url': '', 'pdns_api_key': '', 'pdns_api_timeout': 30, 'pdns_version': '4.1.1', 'verify_ssl_connections': True, 'local_db_enabled': True, 'signup_enabled': True, 'verify_user_email': False, 'ldap_enabled': False, 'ldap_type': 'ldap', 'ldap_uri': '', 'ldap_base_dn': '', 'ldap_admin_username': '', 'ldap_admin_password': '', 'ldap_filter_basic': '', 'ldap_filter_group': '', 'ldap_filter_username': '', 'ldap_filter_groupname': '', 'ldap_sg_enabled': False, 'ldap_admin_group': '', 'ldap_operator_group': '', 'ldap_user_group': '', 'ldap_domain': '', 'github_oauth_enabled': False, 'github_oauth_key': '', 'github_oauth_secret': '', 'github_oauth_scope': 'email', 'github_oauth_api_url': 'https://api.github.com/user', 'github_oauth_token_url': 'https://github.com/login/oauth/access_token', 'github_oauth_authorize_url': 'https://github.com/login/oauth/authorize', 'google_oauth_enabled': False, 'google_oauth_client_id': '', 'google_oauth_client_secret': '', 'google_token_url': 'https://oauth2.googleapis.com/token', 'google_oauth_scope': 'openid email profile', 'google_authorize_url': 'https://accounts.google.com/o/oauth2/v2/auth', 'google_base_url': 'https://www.googleapis.com/oauth2/v3/', 'azure_oauth_enabled': False, 'azure_oauth_key': '', 'azure_oauth_secret': '', 'azure_oauth_scope': 'User.Read openid email profile', 'azure_oauth_api_url': 'https://graph.microsoft.com/v1.0/', 'azure_oauth_token_url': 'https://login.microsoftonline.com/[tenancy]/oauth2/v2.0/token', 'azure_oauth_authorize_url': 'https://login.microsoftonline.com/[tenancy]/oauth2/v2.0/authorize', 'azure_sg_enabled': False, 'azure_admin_group': '', 'azure_operator_group': '', 'azure_user_group': '', 'azure_group_accounts_enabled': False, 'azure_group_accounts_name': 'displayName', 'azure_group_accounts_name_re': '', 'azure_group_accounts_description': 'description', 'azure_group_accounts_description_re': '', 'oidc_oauth_enabled': False, 'oidc_oauth_key': '', 'oidc_oauth_secret': '', 'oidc_oauth_scope': 'email', 'oidc_oauth_api_url': '', 'oidc_oauth_token_url': '', 'oidc_oauth_authorize_url': '', 'oidc_oauth_logout_url': '', 'oidc_oauth_username': 'preferred_username', 'oidc_oauth_firstname': 'given_name', 'oidc_oauth_last_name': 'family_name', 'oidc_oauth_email': 'email', 'oidc_oauth_account_name_property': '', 'oidc_oauth_account_description_property': '', 'forward_records_allow_edit': { 'A': True, 'AAAA': True, 'AFSDB': False, 'ALIAS': False, 'CAA': True, 'CERT': False, 'CDNSKEY': False, 'CDS': False, 'CNAME': True, 'DNSKEY': False, 'DNAME': False, 'DS': False, 'HINFO': False, 'KEY': False, 'LOC': True, 'LUA': False, 'MX': True, 'NAPTR': False, 'NS': True, 'NSEC': False, 'NSEC3': False, 'NSEC3PARAM': False, 'OPENPGPKEY': False, 'PTR': True, 'RP': False, 'RRSIG': False, 'SOA': False, 'SPF': True, 'SSHFP': False, 'SRV': True, 'TKEY': False, 'TSIG': False, 'TLSA': False, 'SMIMEA': False, 'TXT': True, 'URI': False }, 'reverse_records_allow_edit': { 'A': False, 'AAAA': False, 'AFSDB': False, 'ALIAS': False, 'CAA': False, 'CERT': False, 'CDNSKEY': False, 'CDS': False, 'CNAME': False, 'DNSKEY': False, 'DNAME': False, 'DS': False, 'HINFO': False, 'KEY': False, 'LOC': True, 'LUA': False, 'MX': False, 'NAPTR': False, 'NS': True, 'NSEC': False, 'NSEC3': False, 'NSEC3PARAM': False, 'OPENPGPKEY': False, 'PTR': True, 'RP': False, 'RRSIG': False, 'SOA': False, 'SPF': False, 'SSHFP': False, 'SRV': False, 'TKEY': False, 'TSIG': False, 'TLSA': False, 'SMIMEA': False, 'TXT': True, 'URI': False }, 'ttl_options': '1 minute,5 minutes,30 minutes,60 minutes,24 hours', } def __init__(self, id=None, name=None, value=None): self.id = id self.name = name self.value = value def __init__(self, name=None, value=None): self.id = None self.name = name self.value = value def set_maintenance(self, mode): maintenance = Setting.query.filter( Setting.name == 'maintenance').first() if maintenance is None: value = self.defaults['maintenance'] maintenance = Setting(name='maintenance', value=str(value)) db.session.add(maintenance) mode = str(mode) try: if maintenance.value != mode: maintenance.value = mode db.session.commit() return True except Exception as e: current_app.logger.error('Cannot set maintenance to {0}. DETAIL: {1}'.format( mode, e)) current_app.logger.debug(traceback.format_exec()) db.session.rollback() return False def toggle(self, setting): current_setting = Setting.query.filter(Setting.name == setting).first() if current_setting is None: value = self.defaults[setting] current_setting = Setting(name=setting, value=str(value)) db.session.add(current_setting) try: if current_setting.value == "True": current_setting.value = "False" else: current_setting.value = "True" db.session.commit() return True except Exception as e: current_app.logger.error('Cannot toggle setting {0}. DETAIL: {1}'.format( setting, e)) current_app.logger.debug(traceback.format_exec()) db.session.rollback() return False def set(self, setting, value): current_setting = Setting.query.filter(Setting.name == setting).first() if current_setting is None: current_setting = Setting(name=setting, value=None) db.session.add(current_setting) value = str(value) try: current_setting.value = value db.session.commit() return True except Exception as e: current_app.logger.error('Cannot edit setting {0}. DETAIL: {1}'.format( setting, e)) current_app.logger.debug(traceback.format_exec()) db.session.rollback() return False def get(self, setting): if setting in self.defaults: result = self.query.filter(Setting.name == setting).first() if result is not None: return strtobool(result.value) if result.value in [ 'True', 'False' ] else result.value else: return self.defaults[setting] else: current_app.logger.error('Unknown setting queried: {0}'.format(setting)) def get_records_allow_to_edit(self): return list( set(self.get_forward_records_allow_to_edit() + self.get_reverse_records_allow_to_edit())) def get_forward_records_allow_to_edit(self): records = self.get('forward_records_allow_edit') f_records = literal_eval(records) if isinstance(records, str) else records r_name = [r for r in f_records if f_records[r]] if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 6): r_name.sort() return r_name def get_reverse_records_allow_to_edit(self): records = self.get('reverse_records_allow_edit') r_records = literal_eval(records) if isinstance(records, str) else records r_name = [r for r in r_records if r_records[r]] if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 6): r_name.sort() return r_name def get_ttl_options(self): return [(pytimeparse.parse(ttl), ttl) for ttl in self.get('ttl_options').split(',')]
true
true
f736128f8ec6359770146eeb234cd2fe4c28ef32
4,192
py
Python
tests/functional/registration/test_check.py
stanislaw/textX
cccb0e0680635e884841f7ef929b1234131716d3
[ "MIT" ]
1
2021-06-15T14:38:47.000Z
2021-06-15T14:38:47.000Z
tests/functional/registration/test_check.py
stanislaw/textX
cccb0e0680635e884841f7ef929b1234131716d3
[ "MIT" ]
null
null
null
tests/functional/registration/test_check.py
stanislaw/textX
cccb0e0680635e884841f7ef929b1234131716d3
[ "MIT" ]
null
null
null
""" Test check/validation command. """ import os from textx.cli import textx from click.testing import CliRunner from pytest import raises from textx.registration import metamodel_for_language from textx.exceptions import TextXSyntaxError this_folder = os.path.abspath(os.path.dirname(__file__)) def test_object_processor_with_optional_parameter_default(): mm = metamodel_for_language('types-dsl') model_file = os.path.join(this_folder, 'projects', 'types_dsl', 'tests', 'models', 'types_with_error.etype') with raises(TextXSyntaxError, match='error: types must be lowercase'): mm.model_from_file(model_file) def test_object_processor_with_optional_parameter_on(): mm = metamodel_for_language('types-dsl') model_file = os.path.join(this_folder, 'projects', 'types_dsl', 'tests', 'models', 'types_with_error.etype') with raises(TextXSyntaxError, match='error: types must be lowercase'): mm.model_from_file(model_file, type_name_check='on') def test_object_processor_with_optional_parameter_off(): mm = metamodel_for_language('types-dsl') model_file = os.path.join(this_folder, 'projects', 'types_dsl', 'tests', 'models', 'types_with_error.etype') mm.model_from_file(model_file, type_name_check='off') def test_check_metamodel(): """ Meta-model is also a model. """ metamodel_file = os.path.join(this_folder, 'projects', 'flow_dsl', 'flow_dsl', 'Flow.tx') runner = CliRunner() result = runner.invoke(textx, ['check', metamodel_file]) assert result.exit_code == 0 assert 'Flow.tx: OK.' in result.output def test_check_valid_model(): model_file = os.path.join(this_folder, 'projects', 'flow_dsl', 'tests', 'models', 'data_flow.eflow') runner = CliRunner() result = runner.invoke(textx, ['check', model_file]) assert result.exit_code == 0 assert 'data_flow.eflow: OK.' in result.output def test_check_valid_model_with_explicit_language_name(): """ Test checking of model where language name is given explicitly. """ model_file = os.path.join(this_folder, 'projects', 'flow_dsl', 'tests', 'models', 'data_flow.eflow') runner = CliRunner() result = runner.invoke(textx, ['check', '--language', 'flow-dsl', model_file]) assert result.exit_code == 0 assert 'data_flow.eflow: OK.' in result.output def test_check_valid_model_with_metamodel_from_file(): """ Test checking of model where meta-model is provided from the grammar file. """ model_file = os.path.join(this_folder, 'projects', 'types_dsl', 'tests', 'models', 'types.etype') metamodel_file = os.path.join(this_folder, 'projects', 'types_dsl', 'types_dsl', 'Types.tx') runner = CliRunner() result = runner.invoke(textx, ['check', '--grammar', metamodel_file, model_file]) assert result.exit_code == 0 assert 'types.etype: OK.' in result.output def test_check_invalid_model(): model_file = os.path.join(this_folder, 'projects', 'flow_dsl', 'tests', 'models', 'data_flow_including_error.eflow') runner = CliRunner() result = runner.invoke(textx, ['check', model_file]) assert result.exit_code != 0 assert 'error: types must be lowercase' in result.output def test_check_invalid_language(): """ Test calling check command with a file that is not registered. """ runner = CliRunner() result = runner.invoke(textx, ['check', 'some_unexisting_file']) assert 'No language registered that can parse' in result.output
35.82906
78
0.59709
import os from textx.cli import textx from click.testing import CliRunner from pytest import raises from textx.registration import metamodel_for_language from textx.exceptions import TextXSyntaxError this_folder = os.path.abspath(os.path.dirname(__file__)) def test_object_processor_with_optional_parameter_default(): mm = metamodel_for_language('types-dsl') model_file = os.path.join(this_folder, 'projects', 'types_dsl', 'tests', 'models', 'types_with_error.etype') with raises(TextXSyntaxError, match='error: types must be lowercase'): mm.model_from_file(model_file) def test_object_processor_with_optional_parameter_on(): mm = metamodel_for_language('types-dsl') model_file = os.path.join(this_folder, 'projects', 'types_dsl', 'tests', 'models', 'types_with_error.etype') with raises(TextXSyntaxError, match='error: types must be lowercase'): mm.model_from_file(model_file, type_name_check='on') def test_object_processor_with_optional_parameter_off(): mm = metamodel_for_language('types-dsl') model_file = os.path.join(this_folder, 'projects', 'types_dsl', 'tests', 'models', 'types_with_error.etype') mm.model_from_file(model_file, type_name_check='off') def test_check_metamodel(): metamodel_file = os.path.join(this_folder, 'projects', 'flow_dsl', 'flow_dsl', 'Flow.tx') runner = CliRunner() result = runner.invoke(textx, ['check', metamodel_file]) assert result.exit_code == 0 assert 'Flow.tx: OK.' in result.output def test_check_valid_model(): model_file = os.path.join(this_folder, 'projects', 'flow_dsl', 'tests', 'models', 'data_flow.eflow') runner = CliRunner() result = runner.invoke(textx, ['check', model_file]) assert result.exit_code == 0 assert 'data_flow.eflow: OK.' in result.output def test_check_valid_model_with_explicit_language_name(): model_file = os.path.join(this_folder, 'projects', 'flow_dsl', 'tests', 'models', 'data_flow.eflow') runner = CliRunner() result = runner.invoke(textx, ['check', '--language', 'flow-dsl', model_file]) assert result.exit_code == 0 assert 'data_flow.eflow: OK.' in result.output def test_check_valid_model_with_metamodel_from_file(): model_file = os.path.join(this_folder, 'projects', 'types_dsl', 'tests', 'models', 'types.etype') metamodel_file = os.path.join(this_folder, 'projects', 'types_dsl', 'types_dsl', 'Types.tx') runner = CliRunner() result = runner.invoke(textx, ['check', '--grammar', metamodel_file, model_file]) assert result.exit_code == 0 assert 'types.etype: OK.' in result.output def test_check_invalid_model(): model_file = os.path.join(this_folder, 'projects', 'flow_dsl', 'tests', 'models', 'data_flow_including_error.eflow') runner = CliRunner() result = runner.invoke(textx, ['check', model_file]) assert result.exit_code != 0 assert 'error: types must be lowercase' in result.output def test_check_invalid_language(): runner = CliRunner() result = runner.invoke(textx, ['check', 'some_unexisting_file']) assert 'No language registered that can parse' in result.output
true
true
f73613364eee173b91e7c69db1a0a30aa83442ec
2,584
py
Python
4/day_4.py
ophusdev/advent-of-code_2020
c66cc25539df263f766209b70dffd96fef2d66f6
[ "MIT" ]
null
null
null
4/day_4.py
ophusdev/advent-of-code_2020
c66cc25539df263f766209b70dffd96fef2d66f6
[ "MIT" ]
null
null
null
4/day_4.py
ophusdev/advent-of-code_2020
c66cc25539df263f766209b70dffd96fef2d66f6
[ "MIT" ]
null
null
null
import os import re class DayFour(): mandatory_fields = [ 'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid' ] optional_fields = [ 'cid' ] def check_height(height): if not any(unit in height for unit in ["cm", "in"]): return False return ( 150 <= int(height[:-2]) <= 193 if "cm" in height else 59 <= int(height[:-2]) <= 76 ) fields_rules = { "byr": lambda k: 1920 <= int(k) <= 2002, "iyr": lambda k: 2010 <= int(k) <= 2020, "eyr": lambda k: 2020 <= int(k) <= 2030, "hgt": check_height, "hcl": lambda k: re.match('^#[a-f\d]{6}$', k) is not None, "ecl": lambda k: k in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"], "pid": lambda k: len(k) == 9, } def check_height(height: str) -> bool: if not any(unit in height for unit in ["cm", "in"]): return False return ( 150 <= int(height[:-2]) <= 193 if "cm" in height else 59 <= int(height[:-2]) <= 76 ) valid_passports = 0 valid_passports_two = 0 def __init__(self): self.lines = [] self.read_list() def read_list(self): with open('./_data/data_4.txt') as f: contents = f.read() self.lines = contents.split(os.linesep + os.linesep) def is_valid_passport(self, passport): return all(field in passport for field in self.fields_rules) def is_valid_password_fields(self, passport): if self.is_valid_passport(passport): passport = dict(part.split(':') for part in passport.split(' ')) return all(self.fields_rules[field](passport[field]) for field in self.fields_rules) def part_one(self): for passport in self.lines: passport = passport.replace('\n', ' ') if self.is_valid_passport(passport): self.valid_passports += 1 return self.valid_passports def part_two(self): for passport in self.lines: passport = passport.replace('\n', ' ') if self.is_valid_password_fields(passport): self.valid_passports_two += 1 return self.valid_passports_two day_four = DayFour() print("Number of valid password: ") print(day_four.part_one()) print("======================================") print("Number of valid password part two: ") print(day_four.part_two())
27.2
76
0.517802
import os import re class DayFour(): mandatory_fields = [ 'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid' ] optional_fields = [ 'cid' ] def check_height(height): if not any(unit in height for unit in ["cm", "in"]): return False return ( 150 <= int(height[:-2]) <= 193 if "cm" in height else 59 <= int(height[:-2]) <= 76 ) fields_rules = { "byr": lambda k: 1920 <= int(k) <= 2002, "iyr": lambda k: 2010 <= int(k) <= 2020, "eyr": lambda k: 2020 <= int(k) <= 2030, "hgt": check_height, "hcl": lambda k: re.match('^#[a-f\d]{6}$', k) is not None, "ecl": lambda k: k in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"], "pid": lambda k: len(k) == 9, } def check_height(height: str) -> bool: if not any(unit in height for unit in ["cm", "in"]): return False return ( 150 <= int(height[:-2]) <= 193 if "cm" in height else 59 <= int(height[:-2]) <= 76 ) valid_passports = 0 valid_passports_two = 0 def __init__(self): self.lines = [] self.read_list() def read_list(self): with open('./_data/data_4.txt') as f: contents = f.read() self.lines = contents.split(os.linesep + os.linesep) def is_valid_passport(self, passport): return all(field in passport for field in self.fields_rules) def is_valid_password_fields(self, passport): if self.is_valid_passport(passport): passport = dict(part.split(':') for part in passport.split(' ')) return all(self.fields_rules[field](passport[field]) for field in self.fields_rules) def part_one(self): for passport in self.lines: passport = passport.replace('\n', ' ') if self.is_valid_passport(passport): self.valid_passports += 1 return self.valid_passports def part_two(self): for passport in self.lines: passport = passport.replace('\n', ' ') if self.is_valid_password_fields(passport): self.valid_passports_two += 1 return self.valid_passports_two day_four = DayFour() print("Number of valid password: ") print(day_four.part_one()) print("======================================") print("Number of valid password part two: ") print(day_four.part_two())
true
true
f7361364bd7459b873d1e65cd0a4470f1ec4ff4c
468
py
Python
FictionTools/amitools/amitools/tools/typetool.py
polluks/Puddle-BuildTools
c1762d53a33002b62d8cffe3db129505a387bec3
[ "BSD-2-Clause" ]
38
2021-06-18T12:56:15.000Z
2022-03-12T20:38:40.000Z
FictionTools/amitools/amitools/tools/typetool.py
polluks/Puddle-BuildTools
c1762d53a33002b62d8cffe3db129505a387bec3
[ "BSD-2-Clause" ]
2
2021-06-20T16:28:12.000Z
2021-11-17T21:33:56.000Z
FictionTools/amitools/amitools/tools/typetool.py
polluks/Puddle-BuildTools
c1762d53a33002b62d8cffe3db129505a387bec3
[ "BSD-2-Clause" ]
6
2021-06-18T18:18:36.000Z
2021-12-22T08:01:32.000Z
#!/usr/bin/env python3 # # typetool [options] <path> # # a tool to inspect types # import sys import os from amitools.vamos.tools import tools_main, TypeTool def main(): cfg_files = ( # first look in current dir os.path.join(os.getcwd(), ".vamosrc"), # then in home dir os.path.expanduser("~/.vamosrc"), ) tools = [TypeTool()] sys.exit(tools_main(tools, cfg_files)) if __name__ == "__main__": sys.exit(main())
17.333333
53
0.615385
import sys import os from amitools.vamos.tools import tools_main, TypeTool def main(): cfg_files = ( os.path.join(os.getcwd(), ".vamosrc"), os.path.expanduser("~/.vamosrc"), ) tools = [TypeTool()] sys.exit(tools_main(tools, cfg_files)) if __name__ == "__main__": sys.exit(main())
true
true
f73617115210975d3194a3f05821af4c1dce5a6e
14,798
py
Python
legacy-v6.0.2/dnsfilter/fortios_dnsfilter_profile.py
fortinet-solutions-cse/ansible_fgt_modules
c45fba49258d7c9705e7a8fd9c2a09ea4c8a4719
[ "Apache-2.0" ]
14
2018-09-25T20:35:25.000Z
2021-07-14T04:30:54.000Z
legacy-v6.0.2/dnsfilter/fortios_dnsfilter_profile.py
fortinet-solutions-cse/ansible_fgt_modules
c45fba49258d7c9705e7a8fd9c2a09ea4c8a4719
[ "Apache-2.0" ]
32
2018-10-09T04:13:42.000Z
2020-05-11T07:20:28.000Z
legacy-v6.0.2/dnsfilter/fortios_dnsfilter_profile.py
fortinet-solutions-cse/ansible_fgt_modules
c45fba49258d7c9705e7a8fd9c2a09ea4c8a4719
[ "Apache-2.0" ]
11
2018-10-09T00:14:53.000Z
2021-11-03T10:54:09.000Z
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_dnsfilter_profile short_description: Configure DNS domain filter profiles in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS by allowing the user to set and modify dnsfilter feature and profile category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.2 version_added: "2.8" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate ip address. required: true username: description: - FortiOS or FortiGate username. required: true password: description: - FortiOS or FortiGate password. default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol type: bool default: true dnsfilter_profile: description: - Configure DNS domain filter profiles. default: null suboptions: state: description: - Indicates whether to create or remove the object choices: - present - absent block-action: description: - Action to take for blocked domains. choices: - block - redirect block-botnet: description: - Enable/disable blocking botnet C&C DNS lookups. choices: - disable - enable comment: description: - Comment. domain-filter: description: - Domain filter settings. suboptions: domain-filter-table: description: - DNS domain filter table ID. Source dnsfilter.domain-filter.id. external-ip-blocklist: description: - One or more external IP block lists. suboptions: name: description: - External domain block list name. Source system.external-resource.name. required: true ftgd-dns: description: - FortiGuard DNS Filter settings. suboptions: filters: description: - FortiGuard DNS domain filters. suboptions: action: description: - Action to take for DNS requests matching the category. choices: - block - monitor category: description: - Category number. id: description: - ID number. required: true log: description: - Enable/disable DNS filter logging for this DNS profile. choices: - enable - disable options: description: - FortiGuard DNS filter options. choices: - error-allow - ftgd-disable log-all-domain: description: - Enable/disable logging of all domains visited (detailed DNS logging). choices: - enable - disable name: description: - Profile name. required: true redirect-portal: description: - IP address of the SDNS redirect portal. safe-search: description: - Enable/disable Google, Bing, and YouTube safe search. choices: - disable - enable sdns-domain-log: description: - Enable/disable domain filtering and botnet domain logging. choices: - enable - disable sdns-ftgd-err-log: description: - Enable/disable FortiGuard SDNS rating error logging. choices: - enable - disable youtube-restrict: description: - Set safe search for YouTube restriction level. choices: - strict - moderate ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" tasks: - name: Configure DNS domain filter profiles. fortios_dnsfilter_profile: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" dnsfilter_profile: state: "present" block-action: "block" block-botnet: "disable" comment: "Comment." domain-filter: domain-filter-table: "7 (source dnsfilter.domain-filter.id)" external-ip-blocklist: - name: "default_name_9 (source system.external-resource.name)" ftgd-dns: filters: - action: "block" category: "13" id: "14" log: "enable" options: "error-allow" log-all-domain: "enable" name: "default_name_18" redirect-portal: "<your_own_value>" safe-search: "disable" sdns-domain-log: "enable" sdns-ftgd-err-log: "enable" youtube-restrict: "strict" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule def login(data, fos): host = data['host'] username = data['username'] password = data['password'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password) def filter_dnsfilter_profile_data(json): option_list = ['block-action', 'block-botnet', 'comment', 'domain-filter', 'external-ip-blocklist', 'ftgd-dns', 'log-all-domain', 'name', 'redirect-portal', 'safe-search', 'sdns-domain-log', 'sdns-ftgd-err-log', 'youtube-restrict'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def dnsfilter_profile(data, fos): vdom = data['vdom'] dnsfilter_profile_data = data['dnsfilter_profile'] filtered_data = filter_dnsfilter_profile_data(dnsfilter_profile_data) if dnsfilter_profile_data['state'] == "present": return fos.set('dnsfilter', 'profile', data=filtered_data, vdom=vdom) elif dnsfilter_profile_data['state'] == "absent": return fos.delete('dnsfilter', 'profile', mkey=filtered_data['name'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_dnsfilter(data, fos): login(data, fos) if data['dnsfilter_profile']: resp = dnsfilter_profile(data, fos) fos.logout() return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": True, "type": "str"}, "username": {"required": True, "type": "str"}, "password": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "dnsfilter_profile": { "required": False, "type": "dict", "options": { "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "block-action": {"required": False, "type": "str", "choices": ["block", "redirect"]}, "block-botnet": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "comment": {"required": False, "type": "str"}, "domain-filter": {"required": False, "type": "dict", "options": { "domain-filter-table": {"required": False, "type": "int"} }}, "external-ip-blocklist": {"required": False, "type": "list", "options": { "name": {"required": True, "type": "str"} }}, "ftgd-dns": {"required": False, "type": "dict", "options": { "filters": {"required": False, "type": "list", "options": { "action": {"required": False, "type": "str", "choices": ["block", "monitor"]}, "category": {"required": False, "type": "int"}, "id": {"required": True, "type": "int"}, "log": {"required": False, "type": "str", "choices": ["enable", "disable"]} }}, "options": {"required": False, "type": "str", "choices": ["error-allow", "ftgd-disable"]} }}, "log-all-domain": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "name": {"required": True, "type": "str"}, "redirect-portal": {"required": False, "type": "str"}, "safe-search": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "sdns-domain-log": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "sdns-ftgd-err-log": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "youtube-restrict": {"required": False, "type": "str", "choices": ["strict", "moderate"]} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() is_error, has_changed, result = fortios_dnsfilter(module.params, fos) if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
34.983452
100
0.49162
from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_dnsfilter_profile short_description: Configure DNS domain filter profiles in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS by allowing the user to set and modify dnsfilter feature and profile category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.2 version_added: "2.8" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate ip address. required: true username: description: - FortiOS or FortiGate username. required: true password: description: - FortiOS or FortiGate password. default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol type: bool default: true dnsfilter_profile: description: - Configure DNS domain filter profiles. default: null suboptions: state: description: - Indicates whether to create or remove the object choices: - present - absent block-action: description: - Action to take for blocked domains. choices: - block - redirect block-botnet: description: - Enable/disable blocking botnet C&C DNS lookups. choices: - disable - enable comment: description: - Comment. domain-filter: description: - Domain filter settings. suboptions: domain-filter-table: description: - DNS domain filter table ID. Source dnsfilter.domain-filter.id. external-ip-blocklist: description: - One or more external IP block lists. suboptions: name: description: - External domain block list name. Source system.external-resource.name. required: true ftgd-dns: description: - FortiGuard DNS Filter settings. suboptions: filters: description: - FortiGuard DNS domain filters. suboptions: action: description: - Action to take for DNS requests matching the category. choices: - block - monitor category: description: - Category number. id: description: - ID number. required: true log: description: - Enable/disable DNS filter logging for this DNS profile. choices: - enable - disable options: description: - FortiGuard DNS filter options. choices: - error-allow - ftgd-disable log-all-domain: description: - Enable/disable logging of all domains visited (detailed DNS logging). choices: - enable - disable name: description: - Profile name. required: true redirect-portal: description: - IP address of the SDNS redirect portal. safe-search: description: - Enable/disable Google, Bing, and YouTube safe search. choices: - disable - enable sdns-domain-log: description: - Enable/disable domain filtering and botnet domain logging. choices: - enable - disable sdns-ftgd-err-log: description: - Enable/disable FortiGuard SDNS rating error logging. choices: - enable - disable youtube-restrict: description: - Set safe search for YouTube restriction level. choices: - strict - moderate ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" tasks: - name: Configure DNS domain filter profiles. fortios_dnsfilter_profile: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" dnsfilter_profile: state: "present" block-action: "block" block-botnet: "disable" comment: "Comment." domain-filter: domain-filter-table: "7 (source dnsfilter.domain-filter.id)" external-ip-blocklist: - name: "default_name_9 (source system.external-resource.name)" ftgd-dns: filters: - action: "block" category: "13" id: "14" log: "enable" options: "error-allow" log-all-domain: "enable" name: "default_name_18" redirect-portal: "<your_own_value>" safe-search: "disable" sdns-domain-log: "enable" sdns-ftgd-err-log: "enable" youtube-restrict: "strict" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule def login(data, fos): host = data['host'] username = data['username'] password = data['password'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password) def filter_dnsfilter_profile_data(json): option_list = ['block-action', 'block-botnet', 'comment', 'domain-filter', 'external-ip-blocklist', 'ftgd-dns', 'log-all-domain', 'name', 'redirect-portal', 'safe-search', 'sdns-domain-log', 'sdns-ftgd-err-log', 'youtube-restrict'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def dnsfilter_profile(data, fos): vdom = data['vdom'] dnsfilter_profile_data = data['dnsfilter_profile'] filtered_data = filter_dnsfilter_profile_data(dnsfilter_profile_data) if dnsfilter_profile_data['state'] == "present": return fos.set('dnsfilter', 'profile', data=filtered_data, vdom=vdom) elif dnsfilter_profile_data['state'] == "absent": return fos.delete('dnsfilter', 'profile', mkey=filtered_data['name'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_dnsfilter(data, fos): login(data, fos) if data['dnsfilter_profile']: resp = dnsfilter_profile(data, fos) fos.logout() return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": True, "type": "str"}, "username": {"required": True, "type": "str"}, "password": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "dnsfilter_profile": { "required": False, "type": "dict", "options": { "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "block-action": {"required": False, "type": "str", "choices": ["block", "redirect"]}, "block-botnet": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "comment": {"required": False, "type": "str"}, "domain-filter": {"required": False, "type": "dict", "options": { "domain-filter-table": {"required": False, "type": "int"} }}, "external-ip-blocklist": {"required": False, "type": "list", "options": { "name": {"required": True, "type": "str"} }}, "ftgd-dns": {"required": False, "type": "dict", "options": { "filters": {"required": False, "type": "list", "options": { "action": {"required": False, "type": "str", "choices": ["block", "monitor"]}, "category": {"required": False, "type": "int"}, "id": {"required": True, "type": "int"}, "log": {"required": False, "type": "str", "choices": ["enable", "disable"]} }}, "options": {"required": False, "type": "str", "choices": ["error-allow", "ftgd-disable"]} }}, "log-all-domain": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "name": {"required": True, "type": "str"}, "redirect-portal": {"required": False, "type": "str"}, "safe-search": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "sdns-domain-log": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "sdns-ftgd-err-log": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "youtube-restrict": {"required": False, "type": "str", "choices": ["strict", "moderate"]} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() is_error, has_changed, result = fortios_dnsfilter(module.params, fos) if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
true
true
f736186a369638f36f71eb0d86650580c5cc6478
4,311
py
Python
mmd_tools/panels/prop_material.py
cnDengyu/blender_mmd_tools
7968b82283ca868c3382a7012b11a3d17ed266ea
[ "MIT" ]
1
2019-12-08T16:58:30.000Z
2019-12-08T16:58:30.000Z
mmd_tools/panels/prop_material.py
cnDengyu/blender_mmd_tools
7968b82283ca868c3382a7012b11a3d17ed266ea
[ "MIT" ]
null
null
null
mmd_tools/panels/prop_material.py
cnDengyu/blender_mmd_tools
7968b82283ca868c3382a7012b11a3d17ed266ea
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from bpy.types import Panel class MMDMaterialPanel(Panel): bl_idname = 'MATERIAL_PT_mmd_tools_material' bl_label = 'MMD Material' bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = 'material' @classmethod def poll(cls, context): material = context.active_object.active_material return material and material.mmd_material def draw(self, context): material = context.active_object.active_material mmd_material = material.mmd_material layout = self.layout col = layout.column(align=True) col.label(text ='Information:') c = col.column() r = c.row() r.prop(mmd_material, 'name_j') r = c.row() r.prop(mmd_material, 'name_e') r = c.row() r.prop(mmd_material, 'comment') col = layout.column(align=True) col.label(text = 'Color:') c = col.column() r = c.row() r.prop(material, 'diffuse_color') r = c.row() r.label(text = 'Diffuse Alpha:') r.prop(material, 'alpha') r = c.row() r.prop(mmd_material, 'ambient_color') r = c.row() r.prop(material, 'specular_color') r = c.row() r.label(text = 'Specular Alpha:') r.prop(material, 'specular_alpha') col = layout.column(align=True) col.label(text = 'Shadow:') c = col.column() r = c.row() r.prop(mmd_material, 'is_double_sided') r.prop(mmd_material, 'enabled_drop_shadow') r = c.row() r.prop(mmd_material, 'enabled_self_shadow_map') r.prop(mmd_material, 'enabled_self_shadow') col = layout.column(align=True) col.label(text = 'Edge:') c = col.column() r = c.row() r.prop(mmd_material, 'enabled_toon_edge') r.prop(mmd_material, 'edge_weight') r = c.row() r.prop(mmd_material, 'edge_color') class MMDTexturePanel(Panel): bl_idname = 'MATERIAL_PT_mmd_tools_texture' bl_label = 'MMD Texture' bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = 'material' @classmethod def poll(cls, context): material = context.active_object.active_material return material and material.mmd_material def draw(self, context): material = context.active_object.active_material mmd_material = material.mmd_material layout = self.layout #tex_slots = material.texture_slots.values() col = layout.column(align=True) row = col.row(align=True) row.label(text = 'NoTexture:') r = row.column(align=True) ''' if tex_slots[0]: tex = tex_slots[0].texture if tex.type == 'IMAGE' and tex.image: r2 = r.row(align=True) r2.prop(tex.image, 'filepath', text='') r2.operator('mmd_tools.material_remove_texture', text='', icon='PANEL_CLOSE') else: r.operator('mmd_tools.material_remove_texture', text='Remove', icon='PANEL_CLOSE') col.label(text = 'Texture is invalid.', icon='ERROR') else: r.operator('mmd_tools.material_open_texture', text='Add', icon='FILESEL') row = col.row(align=True) row.label(text = 'Sphere Texture:') r = row.column(align=True) if tex_slots[1]: tex = tex_slots[1].texture if tex.type == 'IMAGE' and tex.image: r2 = r.row(align=True) r2.prop(tex.image, 'filepath', text='') else: r.operator('mmd_tools.material_remove_sphere_texture', text='Remove', icon='PANEL_CLOSE') col.label(text = 'Sphere Texture is invalid.', icon='ERROR') else: r.operator('mmd_tools.material_open_texture', text='Add', icon='FILESEL') ''' col = layout.column(align=True) c = col.column() r = c.row() r.prop(mmd_material, 'is_shared_toon_texture') if mmd_material.is_shared_toon_texture: r.prop(mmd_material, 'shared_toon_texture') r = c.row() r.prop(mmd_material, 'toon_texture') r = c.row() r.prop(mmd_material, 'sphere_texture_type')
32.908397
105
0.582463
from bpy.types import Panel class MMDMaterialPanel(Panel): bl_idname = 'MATERIAL_PT_mmd_tools_material' bl_label = 'MMD Material' bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = 'material' @classmethod def poll(cls, context): material = context.active_object.active_material return material and material.mmd_material def draw(self, context): material = context.active_object.active_material mmd_material = material.mmd_material layout = self.layout col = layout.column(align=True) col.label(text ='Information:') c = col.column() r = c.row() r.prop(mmd_material, 'name_j') r = c.row() r.prop(mmd_material, 'name_e') r = c.row() r.prop(mmd_material, 'comment') col = layout.column(align=True) col.label(text = 'Color:') c = col.column() r = c.row() r.prop(material, 'diffuse_color') r = c.row() r.label(text = 'Diffuse Alpha:') r.prop(material, 'alpha') r = c.row() r.prop(mmd_material, 'ambient_color') r = c.row() r.prop(material, 'specular_color') r = c.row() r.label(text = 'Specular Alpha:') r.prop(material, 'specular_alpha') col = layout.column(align=True) col.label(text = 'Shadow:') c = col.column() r = c.row() r.prop(mmd_material, 'is_double_sided') r.prop(mmd_material, 'enabled_drop_shadow') r = c.row() r.prop(mmd_material, 'enabled_self_shadow_map') r.prop(mmd_material, 'enabled_self_shadow') col = layout.column(align=True) col.label(text = 'Edge:') c = col.column() r = c.row() r.prop(mmd_material, 'enabled_toon_edge') r.prop(mmd_material, 'edge_weight') r = c.row() r.prop(mmd_material, 'edge_color') class MMDTexturePanel(Panel): bl_idname = 'MATERIAL_PT_mmd_tools_texture' bl_label = 'MMD Texture' bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = 'material' @classmethod def poll(cls, context): material = context.active_object.active_material return material and material.mmd_material def draw(self, context): material = context.active_object.active_material mmd_material = material.mmd_material layout = self.layout col = layout.column(align=True) row = col.row(align=True) row.label(text = 'NoTexture:') r = row.column(align=True) col = layout.column(align=True) c = col.column() r = c.row() r.prop(mmd_material, 'is_shared_toon_texture') if mmd_material.is_shared_toon_texture: r.prop(mmd_material, 'shared_toon_texture') r = c.row() r.prop(mmd_material, 'toon_texture') r = c.row() r.prop(mmd_material, 'sphere_texture_type')
true
true
f7361a6109e98ebe74e50f1049a1e34fd2a5fae3
600
py
Python
VideoSearchEngine/ObjectDetection/Yolo.py
AkshatSh/VideoSearchEngine
57f64b241b8a7bbc377ce7826e1206f679f41def
[ "MIT" ]
49
2018-05-22T09:06:18.000Z
2022-02-26T10:03:43.000Z
VideoSearchEngine/ObjectDetection/Yolo.py
AkshatSh/VideoSearchEngine
57f64b241b8a7bbc377ce7826e1206f679f41def
[ "MIT" ]
17
2018-05-18T21:14:36.000Z
2019-06-06T09:17:18.000Z
VideoSearchEngine/ObjectDetection/Yolo.py
AkshatSh/VideoSearchEngine
57f64b241b8a7bbc377ce7826e1206f679f41def
[ "MIT" ]
18
2018-06-06T22:14:26.000Z
2021-11-23T08:59:31.000Z
''' Citing this pytorch implementation of tiny yolo from: https://github.com/marvis/pytorch-yolo2/blob/master/models/tiny_yolo.py Original YOLO: https://pjreddie.com/darknet/yolo/ ''' import numpy as np import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from .bbox_detector import get_bbox from .DarknetModels.darknet import DarkNet class YoloNet(DarkNet): def __init__(self): super(YoloNet, self).__init__("cfg/yolov3.cfg") self.load_weights("data/yolov3.weights") def get_bbox(self, images): return get_bbox(self, images)
27.272727
125
0.748333
import numpy as np import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from .bbox_detector import get_bbox from .DarknetModels.darknet import DarkNet class YoloNet(DarkNet): def __init__(self): super(YoloNet, self).__init__("cfg/yolov3.cfg") self.load_weights("data/yolov3.weights") def get_bbox(self, images): return get_bbox(self, images)
true
true
f7361a6bb9bd3f10ce248da79c13e23df401e67d
1,019
py
Python
tortoise/utils.py
EtzelWu/tortoise-orm
6a79c87169c10ff25b0d84bca4db24f0c0737432
[ "Apache-2.0" ]
null
null
null
tortoise/utils.py
EtzelWu/tortoise-orm
6a79c87169c10ff25b0d84bca4db24f0c0737432
[ "Apache-2.0" ]
null
null
null
tortoise/utils.py
EtzelWu/tortoise-orm
6a79c87169c10ff25b0d84bca4db24f0c0737432
[ "Apache-2.0" ]
null
null
null
class QueryAsyncIterator: def __init__(self, query, callback=None): self.query = query self.sequence = None self._sequence_iterator = None self._callback = callback def __aiter__(self): return self async def fetch_sequence(self) -> None: self.sequence = await self.query self._sequence_iterator = self.sequence.__iter__() if self._callback: await self._callback(self) async def __anext__(self): if self.sequence is None: await self.fetch_sequence() try: return next(self._sequence_iterator) except StopIteration: raise StopAsyncIteration def get_schema_sql(client) -> str: generator = client.schema_generator(client) creation_string = generator.get_create_schema_sql() return creation_string async def generate_schema(client) -> None: generator = client.schema_generator(client) await generator.generate_from_string(get_schema_sql(client))
29.114286
64
0.67419
class QueryAsyncIterator: def __init__(self, query, callback=None): self.query = query self.sequence = None self._sequence_iterator = None self._callback = callback def __aiter__(self): return self async def fetch_sequence(self) -> None: self.sequence = await self.query self._sequence_iterator = self.sequence.__iter__() if self._callback: await self._callback(self) async def __anext__(self): if self.sequence is None: await self.fetch_sequence() try: return next(self._sequence_iterator) except StopIteration: raise StopAsyncIteration def get_schema_sql(client) -> str: generator = client.schema_generator(client) creation_string = generator.get_create_schema_sql() return creation_string async def generate_schema(client) -> None: generator = client.schema_generator(client) await generator.generate_from_string(get_schema_sql(client))
true
true
f7361eaeb5b96bfd9b18cd7dfe509faf9e14fb5d
903
py
Python
mypath.py
oganesManasian/pytorch-deeplab-xception
83c042e18b06ced544acb0da66f04e6dc2280d94
[ "MIT" ]
null
null
null
mypath.py
oganesManasian/pytorch-deeplab-xception
83c042e18b06ced544acb0da66f04e6dc2280d94
[ "MIT" ]
null
null
null
mypath.py
oganesManasian/pytorch-deeplab-xception
83c042e18b06ced544acb0da66f04e6dc2280d94
[ "MIT" ]
null
null
null
class Path(object): @staticmethod def db_root_dir(dataset): if dataset == 'cityscapes': # return 'data/cityscapes' return '../../../cvlabdata2/forOganes/cityscapes' # return '/path/to/datasets/cityscapes/' # folder that contains leftImg8bit/ elif dataset == 'cityscapes_local': return 'data/cityscapes' elif dataset == 'synthia': return 'data/synthia' # elif dataset == 'sbd': # return '/path/to/datasets/benchmark_RELEASE/' # folder that contains dataset/. # elif dataset == 'pascal': # return '/path/to/datasets/VOCdevkit/VOC2012/' # folder that contains VOCdevkit/. # elif dataset == 'coco': # return '/path/to/datasets/coco/' else: print('Dataset {} not available.'.format(dataset)) raise NotImplementedError
43
95
0.579181
class Path(object): @staticmethod def db_root_dir(dataset): if dataset == 'cityscapes': return '../../../cvlabdata2/forOganes/cityscapes' s_local': return 'data/cityscapes' elif dataset == 'synthia': return 'data/synthia' nt('Dataset {} not available.'.format(dataset)) raise NotImplementedError
true
true
f7362076c28593cc39298e70687c32b09591d3cb
2,134
py
Python
DjangoSales/apps/main/forms.py
laloe/djangoRest
7717ac1a28267d11ffce9e0038934ea9ef542da8
[ "MIT" ]
null
null
null
DjangoSales/apps/main/forms.py
laloe/djangoRest
7717ac1a28267d11ffce9e0038934ea9ef542da8
[ "MIT" ]
null
null
null
DjangoSales/apps/main/forms.py
laloe/djangoRest
7717ac1a28267d11ffce9e0038934ea9ef542da8
[ "MIT" ]
null
null
null
from django import forms from .models import ( Proveedor, Producto, Entradas ) from django.utils import six class ProveedorForm(): nombre = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control'}), error_messages={'required': 'Please let us know what to call you!'}) direccion = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control'}), error_messages={'required': 'Please let us know what to call you!'}) telefono = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control'}), error_messages={'required': 'Please let us know what to call you!'}) correo = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control'}), error_messages={'required': 'Please let us know what to call you!'}) class Meta: model = Proveedor fields = ('nombre', 'telefono', 'correo', 'direccion') def __init__(self, *args, **kwargs): form = super(ProveedorForm, self).__init__(*args, **kwargs) for visible in form.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class ProductoForm(): def __init__(self, *args, **kwargs): super(ProductoForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['required'] = ' ' field.widget.attrs['class'] = 'form-control border-input' class Meta: model = Producto fields = ('upc', 'proveedor', 'nombre', 'categoria', 'unidad', 'precio_entrada', 'precio_salida') class EntradasForm(): def __init__(self, *args, **kwargs): super(EntradasForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['required'] = ' ' field.widget.attrs['class'] = 'form-control border-input' class Meta: model = Entradas fields = ('upc', 'proveedor', 'nombre', 'categoria', 'unidad', 'precio_entrada', 'precio_salida', 'cantidad', 'fecha')
39.518519
124
0.611059
from django import forms from .models import ( Proveedor, Producto, Entradas ) from django.utils import six class ProveedorForm(): nombre = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control'}), error_messages={'required': 'Please let us know what to call you!'}) direccion = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control'}), error_messages={'required': 'Please let us know what to call you!'}) telefono = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control'}), error_messages={'required': 'Please let us know what to call you!'}) correo = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control'}), error_messages={'required': 'Please let us know what to call you!'}) class Meta: model = Proveedor fields = ('nombre', 'telefono', 'correo', 'direccion') def __init__(self, *args, **kwargs): form = super(ProveedorForm, self).__init__(*args, **kwargs) for visible in form.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class ProductoForm(): def __init__(self, *args, **kwargs): super(ProductoForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['required'] = ' ' field.widget.attrs['class'] = 'form-control border-input' class Meta: model = Producto fields = ('upc', 'proveedor', 'nombre', 'categoria', 'unidad', 'precio_entrada', 'precio_salida') class EntradasForm(): def __init__(self, *args, **kwargs): super(EntradasForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['required'] = ' ' field.widget.attrs['class'] = 'form-control border-input' class Meta: model = Entradas fields = ('upc', 'proveedor', 'nombre', 'categoria', 'unidad', 'precio_entrada', 'precio_salida', 'cantidad', 'fecha')
true
true
f7362278d0fb33ed86ffcdc67a341ef3f340434d
32,161
py
Python
tests/config/test_central.py
thesamesam/pkgcore
be2d9264a3fe61a323f0075cbc4838ed6ec5ffcf
[ "BSD-3-Clause" ]
null
null
null
tests/config/test_central.py
thesamesam/pkgcore
be2d9264a3fe61a323f0075cbc4838ed6ec5ffcf
[ "BSD-3-Clause" ]
null
null
null
tests/config/test_central.py
thesamesam/pkgcore
be2d9264a3fe61a323f0075cbc4838ed6ec5ffcf
[ "BSD-3-Clause" ]
null
null
null
from pkgcore.config import basics, central, errors from pkgcore.config.hint import configurable from snakeoil.errors import walk_exception_chain from snakeoil.test import TestCase # A bunch of functions used from various tests below. def repo(cache): return cache @configurable({'content': 'ref:drawer', 'contents': 'refs:drawer'}) def drawer(content=None, contents=None): return content, contents # The exception checks here also check if the str value of the # exception is what we expect. This does not mean the wording of the # error messages used here is strictly required. It just makes sure # the error we get is the expected one and is useful. Please make sure # you check for a sensible error message when more tests are added. # A lot of the ConfigManager instances get object() as a remote type. # This makes sure the types are not unnecessarily queried (since # querying object() will blow up). class RemoteSource: """Use this one for tests that do need the names but nothing more.""" def __iter__(self): return iter(('remote',)) def __getitem__(self, key): raise NotImplementedError() def _str_exc(exc): return ":\n".join(str(x) for x in walk_exception_chain(exc)) class ConfigManagerTest(TestCase): def check_error(self, message, func, *args, **kwargs): """Like assertRaises but checks for the message string too.""" klass = kwargs.pop('klass', errors.ConfigurationError) try: func(*args, **kwargs) except klass as e: self.assertEqual( message, _str_exc(e), f'\nGot:\n{_str_exc(e)!r}\nExpected:\n{message!r}\n') else: self.fail('no exception raised') def get_config_obj(self, manager, obj_type, obj_name): types = getattr(manager.objects, obj_type) return types[obj_name] def test_sections(self): manager = central.ConfigManager( [{'fooinst': basics.HardCodedConfigSection({'class': repo}), 'barinst': basics.HardCodedConfigSection({'class': drawer}), }]) self.assertEqual(['barinst', 'fooinst'], sorted(manager.sections())) self.assertEqual(list(manager.objects.drawer.keys()), ['barinst']) self.assertEqual(manager.objects.drawer, {'barinst': (None, None)}) def test_contains(self): manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({'class': drawer})}], [RemoteSource()]) self.assertIn('spork', manager.objects.drawer) self.assertNotIn('foon', manager.objects.drawer) def test_no_class(self): manager = central.ConfigManager( [{'foo': basics.HardCodedConfigSection({})}]) self.check_error( "Collapsing section named 'foo':\n" 'no class specified', manager.collapse_named_section, 'foo') def test_missing_section_ref(self): manager = central.ConfigManager( [{'rsync repo': basics.HardCodedConfigSection({'class': repo}), }]) self.check_error( "Collapsing section named 'rsync repo':\n" "type tests.config.test_central.repo needs settings for " "'cache'", self.get_config_obj, manager, 'repo', 'rsync repo') def test_unknown_type(self): manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({'class': drawer, 'foon': None})}]) self.check_error( "Collapsing section named 'spork':\n" "Type of 'foon' unknown", manager.collapse_named_section, 'spork') def test_missing_inherit_target(self): manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({ 'class': repo, 'inherit': ['baserepo'], }), }], [RemoteSource()]) self.check_error( "Collapsing section named 'myrepo':\n" "Inherit target 'baserepo' cannot be found", self.get_config_obj, manager, 'repo', 'myrepo') def test_inherit_unknown_type(self): manager = central.ConfigManager( [{'baserepo': basics.HardCodedConfigSection({ 'cache': 'available', }), 'actual repo': basics.HardCodedConfigSection({ 'class': drawer, 'inherit': ['baserepo'], }), }]) self.check_error( "Collapsing section named 'actual repo':\n" "Type of 'cache' unknown", self.get_config_obj, manager, 'repo', 'actual repo') def test_inherit(self): manager = central.ConfigManager( [{'baserepo': basics.HardCodedConfigSection({ 'cache': 'available', 'inherit': ['unneeded'], }), 'unneeded': basics.HardCodedConfigSection({ 'cache': 'unavailable'}), 'actual repo': basics.HardCodedConfigSection({ 'class': repo, 'inherit': ['baserepo'], }), }]) self.assertEqual('available', manager.objects.repo['actual repo']) def test_no_object_returned(self): def noop(): """Do not do anything.""" manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({'class': noop}), }]) self.check_error( "Failed instantiating section 'myrepo':\n" "'No object returned' instantiating " "tests.config.test_central.noop", manager.collapse_named_section('myrepo').instantiate) def test_not_callable(self): class myrepo: def __repr__(self): return 'useless' manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({'class': myrepo()}), }]) self.check_error( "Collapsing section named 'myrepo':\n" "Failed converting argument 'class' to callable:\n" "useless is not callable", self.get_config_obj, manager, 'myrepo', 'myrepo') def test_raises_instantiationerror(self): def myrepo(): raise Exception('I raised') manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({'class': myrepo}), }]) self.check_error( "Failed instantiating section 'myrepo':\n" "Failed instantiating section 'myrepo': exception caught from 'tests.config.test_central.myrepo':\n" "I raised", self.get_config_obj, manager, 'myrepo', 'myrepo') def test_raises(self): def myrepo(): raise ValueError('I raised') manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({'class': myrepo}) }]) self.check_error( "Failed instantiating section 'myrepo':\n" "Failed instantiating section 'myrepo': exception caught from 'tests.config.test_central.myrepo':\n" "I raised", self.get_config_obj, manager, 'myrepo', 'myrepo') manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({'class': myrepo}) }], debug=True) self.check_error( "Failed instantiating section 'myrepo':\n" "Failed instantiating section 'myrepo': exception caught from 'tests.config.test_central.myrepo':\n" "I raised", self.get_config_obj, manager, 'myrepo', 'myrepo', klass=errors.ConfigurationError) def test_pargs(self): @configurable(types={'p': 'str', 'notp': 'str'}, positional=['p'], required=['p']) def myrepo(*args, **kwargs): return args, kwargs manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({ 'class': myrepo, 'p': 'pos', 'notp': 'notpos', }), }]) self.assertEqual( manager.objects.myrepo['myrepo'], (('pos',), {'notp': 'notpos'})) def test_autoexec(self): @configurable(typename='configsection') def autoloader(): return {'spork': basics.HardCodedConfigSection({'class': repo, 'cache': 'test'})} manager = central.ConfigManager( [{'autoload-sub': basics.HardCodedConfigSection({ 'class': autoloader, })}]) self.assertEqual(set(['autoload-sub', 'spork']), set(manager.sections())) self.assertEqual(['spork'], list(manager.objects.repo.keys())) self.assertEqual( 'test', manager.collapse_named_section('spork').instantiate()) def test_reload(self): mod_dict = {'class': repo, 'cache': 'test'} @configurable(typename='configsection') def autoloader(): return {'spork': basics.HardCodedConfigSection(mod_dict)} manager = central.ConfigManager( [{'autoload-sub': basics.HardCodedConfigSection({ 'class': autoloader})}]) self.assertEqual(set(['autoload-sub', 'spork']), set(manager.sections())) self.assertEqual(['spork'], list(manager.objects.repo.keys())) collapsedspork = manager.collapse_named_section('spork') self.assertEqual('test', collapsedspork.instantiate()) mod_dict['cache'] = 'modded' self.assertIdentical(collapsedspork, manager.collapse_named_section('spork')) self.assertEqual('test', collapsedspork.instantiate()) types = manager.types manager.reload() newspork = manager.collapse_named_section('spork') self.assertNotIdentical(collapsedspork, newspork) self.assertEqual( 'modded', newspork.instantiate(), 'it did not throw away the cached instance') self.assertNotIdentical(types, manager.types) def test_instantiate_default_ref(self): manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({'class': drawer})}], ) self.assertEqual( (None, None), manager.collapse_named_section('spork').instantiate()) def test_allow_unknowns(self): @configurable(allow_unknowns=True) def myrepo(**kwargs): return kwargs manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({ 'class': myrepo, 'spork': 'foon'})}]) self.assertEqual( {'spork': 'foon'}, manager.collapse_named_section('spork').instantiate()) def test_reinstantiate_after_raise(self): # The most likely bug this tests for is attempting to # reprocess already processed section_ref args. spork = object() @configurable({'thing': 'ref:spork'}) def myrepo(thing): self.assertIdentical(thing, spork) raise errors.ComplexInstantiationError('I suck') @configurable(typename='spork') def spork_producer(): return spork manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({ 'class': myrepo, 'thing': basics.HardCodedConfigSection({ 'class': spork_producer, }), })}]) spork = manager.collapse_named_section('spork') for i in range(3): self.check_error( "Failed instantiating section 'spork':\n" "Failed instantiating section 'spork': exception caught from 'tests.config.test_central.myrepo':\n" "'I suck', callable unset!", spork.instantiate) for i in range(3): self.check_error( "Failed instantiating section 'spork':\n" "Failed instantiating section 'spork': exception caught from 'tests.config.test_central.myrepo':\n" "'I suck', callable unset!", manager.collapse_named_section('spork').instantiate) def test_instantiation_caching(self): @configurable(typename='drawer') def myrepo(): return object() manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({'class': myrepo}), 'drawer': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'content': 'spork', }), }]) config = manager.collapse_named_section('spork') self.assertIdentical(config.instantiate(), config.instantiate()) self.assertIdentical( config.instantiate(), manager.collapse_named_section('drawer').instantiate()[0]) def test_collapse_named_errors(self): manager = central.ConfigManager( [{'spork': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'content': 'ref'})}], [RemoteSource()]) self.assertRaises(KeyError, self.get_config_obj, manager, 'repo', 'foon') self.check_error( "Collapsing section named 'spork':\n" "Failed collapsing section key 'content':\n" "no section called 'ref'", self.get_config_obj, manager, 'repo', 'spork') def test_recursive_autoload(self): @configurable(typename='configsection') def autoloader(): return {'autoload-sub': basics.HardCodedConfigSection( {'class': autoloader}), 'spork': basics.HardCodedConfigSection({'class': repo, 'cache': 'test'})} self.check_error( "New config is trying to modify existing section(s) 'autoload-sub' " "that was already instantiated.", central.ConfigManager, [{'autoload-sub': basics.HardCodedConfigSection({ 'class': autoloader, })}]) def test_recursive_section_ref(self): manager = central.ConfigManager( [{'spork': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'content': 'foon'}), 'foon': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'content': 'spork'}), 'self': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'content': 'self'}), }]) self.check_error( "Collapsing section named 'self':\n" "Failed collapsing section key 'content':\n" "Reference to 'self' is recursive", self.get_config_obj, manager, 'drawer', 'self') self.check_error( "Collapsing section named 'spork':\n" "Failed collapsing section key 'content':\n" "Collapsing section named 'foon':\n" "Failed collapsing section key 'content':\n" "Reference to 'spork' is recursive", self.get_config_obj, manager, 'drawer', 'spork') def test_recursive_inherit(self): manager = central.ConfigManager( [{'spork': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'inherit': 'foon'}), 'foon': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'inherit': 'spork'}), }]) self.check_error( "Collapsing section named 'spork':\n" "Inherit 'spork' is recursive", self.get_config_obj, manager, 'drawer', 'spork') def test_alias(self): def myspork(): return object manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({'class': myspork}), 'foon': basics.section_alias('spork', 'myspork'), }]) # This tests both the detected typename of foon and the caching. self.assertIdentical(manager.objects.myspork['spork'], manager.objects.myspork['foon']) def test_typecheck(self): @configurable({'myrepo': 'ref:repo'}, typename='repo') def reporef(myrepo=None): return myrepo @configurable({'myrepo': 'refs:repo'}, typename='repo') def reporefs(myrepo=None): return myrepo @configurable(typename='repo') def myrepo(): return 'repo!' manager = central.ConfigManager([{ 'myrepo': basics.HardCodedConfigSection({'class': myrepo}), 'drawer': basics.HardCodedConfigSection({'class': drawer}), 'right': basics.AutoConfigSection({'class': reporef, 'myrepo': 'myrepo'}), 'wrong': basics.AutoConfigSection({'class': reporef, 'myrepo': 'drawer'}), }]) self.check_error( "Collapsing section named 'wrong':\n" "Failed collapsing section key 'myrepo':\n" "reference 'drawer' should be of type 'repo', got 'drawer'", self.get_config_obj, manager, 'repo', 'wrong') self.assertEqual('repo!', manager.objects.repo['right']) manager = central.ConfigManager([{ 'myrepo': basics.HardCodedConfigSection({'class': myrepo}), 'drawer': basics.HardCodedConfigSection({'class': drawer}), 'right': basics.AutoConfigSection({'class': reporefs, 'myrepo': 'myrepo'}), 'wrong': basics.AutoConfigSection({'class': reporefs, 'myrepo': 'drawer'}), }]) self.check_error( "Collapsing section named 'wrong':\n" "Failed collapsing section key 'myrepo':\n" "reference 'drawer' should be of type 'repo', got 'drawer'", self.get_config_obj, manager, 'repo', 'wrong') self.assertEqual(['repo!'], manager.objects.repo['right']) def test_default(self): manager = central.ConfigManager([{ 'thing': basics.HardCodedConfigSection({'class': drawer, 'default': True}), 'bug': basics.HardCodedConfigSection({'class': None, 'inherit-only':True, 'default': True}), 'ignore': basics.HardCodedConfigSection({'class': drawer}), }]) self.assertEqual((None, None), manager.get_default('drawer')) self.assertTrue(manager.collapse_named_section('thing').default) manager = central.ConfigManager([{ 'thing': basics.HardCodedConfigSection({'class': drawer, 'default': True}), 'thing2': basics.HardCodedConfigSection({'class': drawer, 'default': True}), }]) self.check_error( "type drawer incorrectly has multiple default sections: 'thing', 'thing2'", manager.get_default, 'drawer') manager = central.ConfigManager([]) self.assertIdentical(None, manager.get_default('drawer')) def test_broken_default(self): def broken(): raise errors.ComplexInstantiationError('broken') manager = central.ConfigManager([{ 'thing': basics.HardCodedConfigSection({ 'class': drawer, 'default': True, 'content': basics.HardCodedConfigSection({ 'class': 'spork'})}), 'thing2': basics.HardCodedConfigSection({ 'class': broken, 'default': True})}]) self.check_error( "Collapsing defaults for 'drawer':\n" "Collapsing section named 'thing':\n" "Failed collapsing section key 'content':\n" "Failed converting argument 'class' to callable:\n" "'spork' is not callable", manager.get_default, 'drawer') self.check_error( "Collapsing defaults for 'broken':\n" "Collapsing section named 'thing':\n" "Failed collapsing section key 'content':\n" "Failed converting argument 'class' to callable:\n" "'spork' is not callable", manager.get_default, 'broken') def test_instantiate_broken_ref(self): @configurable(typename='drawer') def broken(): raise errors.ComplexInstantiationError('broken') manager = central.ConfigManager([{ 'one': basics.HardCodedConfigSection({ 'class': drawer, 'content': basics.HardCodedConfigSection({ 'class': broken})}), 'multi': basics.HardCodedConfigSection({ 'class': drawer, 'contents': [basics.HardCodedConfigSection({ 'class': broken})]}), }]) self.check_error( "Failed instantiating section 'one':\n" "Instantiating reference 'content' pointing at None:\n" "Failed instantiating section None:\n" "Failed instantiating section None: exception caught from 'tests.config.test_central.broken':\n" "'broken', callable unset!", manager.collapse_named_section('one').instantiate) self.check_error( "Failed instantiating section 'multi':\n" "Instantiating reference 'contents' pointing at None:\n" "Failed instantiating section None:\n" "Failed instantiating section None: exception caught from 'tests.config.test_central.broken':\n" "'broken', callable unset!", manager.collapse_named_section('multi').instantiate) def test_autoload_instantiationerror(self): @configurable(typename='configsection') def broken(): raise errors.ComplexInstantiationError('broken') self.check_error( "Failed loading autoload section 'autoload_broken':\n" "Failed instantiating section 'autoload_broken':\n" "Failed instantiating section 'autoload_broken': exception caught from 'tests.config.test_central.broken':\n" "'broken', callable unset!", central.ConfigManager, [{ 'autoload_broken': basics.HardCodedConfigSection({ 'class': broken})}]) def test_autoload_uncollapsable(self): self.check_error( "Failed collapsing autoload section 'autoload_broken':\n" "Collapsing section named 'autoload_broken':\n" "Failed converting argument 'class' to callable:\n" "'spork' is not callable", central.ConfigManager, [{ 'autoload_broken': basics.HardCodedConfigSection({ 'class': 'spork'})}]) def test_autoload_wrong_type(self): self.check_error( "Section 'autoload_wrong' is marked as autoload but type is " 'drawer, not configsection', central.ConfigManager, [{ 'autoload_wrong': basics.HardCodedConfigSection({ 'class': drawer})}]) def test_lazy_refs(self): @configurable({'myrepo': 'lazy_ref:repo', 'thing': 'lazy_ref'}, typename='repo') def reporef(myrepo=None, thing=None): return myrepo, thing @configurable({'myrepo': 'lazy_refs:repo', 'thing': 'lazy_refs'}, typename='repo') def reporefs(myrepo=None, thing=None): return myrepo, thing @configurable(typename='repo') def myrepo(): return 'repo!' manager = central.ConfigManager([{ 'myrepo': basics.HardCodedConfigSection({'class': myrepo}), 'drawer': basics.HardCodedConfigSection({'class': drawer}), 'right': basics.AutoConfigSection({'class': reporef, 'myrepo': 'myrepo'}), 'wrong': basics.AutoConfigSection({'class': reporef, 'myrepo': 'drawer'}), }]) self.check_error( "reference 'drawer' should be of type 'repo', got 'drawer'", manager.objects.repo['wrong'][0].collapse) self.assertEqual('repo!', manager.objects.repo['right'][0].instantiate()) manager = central.ConfigManager([{ 'myrepo': basics.HardCodedConfigSection({'class': myrepo}), 'drawer': basics.HardCodedConfigSection({'class': drawer}), 'right': basics.AutoConfigSection({'class': reporefs, 'myrepo': 'myrepo'}), 'wrong': basics.AutoConfigSection({'class': reporefs, 'myrepo': 'drawer'}), }]) self.check_error( "reference 'drawer' should be of type 'repo', got 'drawer'", manager.objects.repo['wrong'][0][0].collapse) self.assertEqual( ['repo!'], [c.instantiate() for c in manager.objects.repo['right'][0]]) def test_inherited_default(self): manager = central.ConfigManager([{ 'default': basics.HardCodedConfigSection({ 'default': True, 'inherit': ['basic'], }), 'uncollapsable': basics.HardCodedConfigSection({ 'default': True, 'inherit': ['spork'], 'inherit-only': True, }), 'basic': basics.HardCodedConfigSection({'class': drawer}), }], [RemoteSource()]) self.assertTrue(manager.get_default('drawer')) def test_section_names(self): manager = central.ConfigManager([{ 'thing': basics.HardCodedConfigSection({'class': drawer}), }], [RemoteSource()]) collapsed = manager.collapse_named_section('thing') self.assertEqual('thing', collapsed.name) def test_inherit_only(self): manager = central.ConfigManager([{ 'source': basics.HardCodedConfigSection({ 'class': drawer, 'inherit-only': True, }), 'target': basics.HardCodedConfigSection({ 'inherit': ['source'], })}], [RemoteSource()]) self.check_error( "Collapsing section named 'source':\n" 'cannot collapse inherit-only section', manager.collapse_named_section, 'source') self.assertTrue(manager.collapse_named_section('target')) def test_self_inherit(self): section = basics.HardCodedConfigSection({'inherit': ['self']}) manager = central.ConfigManager([{ 'self': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'inherit': 'self'}), }], [RemoteSource()]) self.check_error( "Collapsing section named 'self':\n" "Self-inherit 'self' cannot be found", self.get_config_obj, manager, 'drawer', 'self') self.check_error( "Self-inherit 'self' cannot be found", manager.collapse_section, [section]) manager = central.ConfigManager([{ 'self': basics.HardCodedConfigSection({ 'inherit': ['self'], })}, { 'self': basics.HardCodedConfigSection({ 'inherit': ['self'], })}, { 'self': basics.HardCodedConfigSection({ 'class': drawer})}]) self.assertTrue(manager.collapse_named_section('self')) self.assertTrue(manager.collapse_section([section])) def test_prepend_inherit(self): manager = central.ConfigManager([{ 'sect': basics.HardCodedConfigSection({ 'inherit.prepend': ['self']})}]) self.check_error( "Collapsing section named 'sect':\n" 'Prepending or appending to the inherit list makes no sense', manager.collapse_named_section, 'sect') def test_list_prepend(self): @configurable({'seq': 'list'}) def seq(seq): return seq manager = central.ConfigManager([{ 'inh': basics.HardCodedConfigSection({ 'inherit': ['sect'], 'seq.prepend': ['pre'], }), 'sect': basics.HardCodedConfigSection({ 'inherit': ['base'], 'seq': ['1', '2'], })}, { 'base': basics.HardCodedConfigSection({ 'class': seq, 'seq.prepend': ['-1'], 'seq.append': ['post'], })}]) self.assertEqual(['-1', 'post'], manager.objects.seq['base']) self.assertEqual(['1', '2'], manager.objects.seq['sect']) self.assertEqual(['pre', '1', '2'], manager.objects.seq['inh']) def test_str_prepend(self): @configurable({'string': 'str'}) def sect(string): return string manager = central.ConfigManager([{ 'inh': basics.HardCodedConfigSection({ 'inherit': ['sect'], 'string.prepend': 'pre', }), 'sect': basics.HardCodedConfigSection({ 'inherit': ['base'], 'string': 'b', })}, { 'base': basics.HardCodedConfigSection({ 'class': sect, 'string.prepend': 'a', 'string.append': 'c', })}]) self.assertEqual('a c', manager.objects.sect['base']) self.assertEqual('b', manager.objects.sect['sect']) self.assertEqual('pre b', manager.objects.sect['inh'])
44.917598
121
0.527502
from pkgcore.config import basics, central, errors from pkgcore.config.hint import configurable from snakeoil.errors import walk_exception_chain from snakeoil.test import TestCase def repo(cache): return cache @configurable({'content': 'ref:drawer', 'contents': 'refs:drawer'}) def drawer(content=None, contents=None): return content, contents class RemoteSource: def __iter__(self): return iter(('remote',)) def __getitem__(self, key): raise NotImplementedError() def _str_exc(exc): return ":\n".join(str(x) for x in walk_exception_chain(exc)) class ConfigManagerTest(TestCase): def check_error(self, message, func, *args, **kwargs): klass = kwargs.pop('klass', errors.ConfigurationError) try: func(*args, **kwargs) except klass as e: self.assertEqual( message, _str_exc(e), f'\nGot:\n{_str_exc(e)!r}\nExpected:\n{message!r}\n') else: self.fail('no exception raised') def get_config_obj(self, manager, obj_type, obj_name): types = getattr(manager.objects, obj_type) return types[obj_name] def test_sections(self): manager = central.ConfigManager( [{'fooinst': basics.HardCodedConfigSection({'class': repo}), 'barinst': basics.HardCodedConfigSection({'class': drawer}), }]) self.assertEqual(['barinst', 'fooinst'], sorted(manager.sections())) self.assertEqual(list(manager.objects.drawer.keys()), ['barinst']) self.assertEqual(manager.objects.drawer, {'barinst': (None, None)}) def test_contains(self): manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({'class': drawer})}], [RemoteSource()]) self.assertIn('spork', manager.objects.drawer) self.assertNotIn('foon', manager.objects.drawer) def test_no_class(self): manager = central.ConfigManager( [{'foo': basics.HardCodedConfigSection({})}]) self.check_error( "Collapsing section named 'foo':\n" 'no class specified', manager.collapse_named_section, 'foo') def test_missing_section_ref(self): manager = central.ConfigManager( [{'rsync repo': basics.HardCodedConfigSection({'class': repo}), }]) self.check_error( "Collapsing section named 'rsync repo':\n" "type tests.config.test_central.repo needs settings for " "'cache'", self.get_config_obj, manager, 'repo', 'rsync repo') def test_unknown_type(self): manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({'class': drawer, 'foon': None})}]) self.check_error( "Collapsing section named 'spork':\n" "Type of 'foon' unknown", manager.collapse_named_section, 'spork') def test_missing_inherit_target(self): manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({ 'class': repo, 'inherit': ['baserepo'], }), }], [RemoteSource()]) self.check_error( "Collapsing section named 'myrepo':\n" "Inherit target 'baserepo' cannot be found", self.get_config_obj, manager, 'repo', 'myrepo') def test_inherit_unknown_type(self): manager = central.ConfigManager( [{'baserepo': basics.HardCodedConfigSection({ 'cache': 'available', }), 'actual repo': basics.HardCodedConfigSection({ 'class': drawer, 'inherit': ['baserepo'], }), }]) self.check_error( "Collapsing section named 'actual repo':\n" "Type of 'cache' unknown", self.get_config_obj, manager, 'repo', 'actual repo') def test_inherit(self): manager = central.ConfigManager( [{'baserepo': basics.HardCodedConfigSection({ 'cache': 'available', 'inherit': ['unneeded'], }), 'unneeded': basics.HardCodedConfigSection({ 'cache': 'unavailable'}), 'actual repo': basics.HardCodedConfigSection({ 'class': repo, 'inherit': ['baserepo'], }), }]) self.assertEqual('available', manager.objects.repo['actual repo']) def test_no_object_returned(self): def noop(): manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({'class': noop}), }]) self.check_error( "Failed instantiating section 'myrepo':\n" "'No object returned' instantiating " "tests.config.test_central.noop", manager.collapse_named_section('myrepo').instantiate) def test_not_callable(self): class myrepo: def __repr__(self): return 'useless' manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({'class': myrepo()}), }]) self.check_error( "Collapsing section named 'myrepo':\n" "Failed converting argument 'class' to callable:\n" "useless is not callable", self.get_config_obj, manager, 'myrepo', 'myrepo') def test_raises_instantiationerror(self): def myrepo(): raise Exception('I raised') manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({'class': myrepo}), }]) self.check_error( "Failed instantiating section 'myrepo':\n" "Failed instantiating section 'myrepo': exception caught from 'tests.config.test_central.myrepo':\n" "I raised", self.get_config_obj, manager, 'myrepo', 'myrepo') def test_raises(self): def myrepo(): raise ValueError('I raised') manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({'class': myrepo}) }]) self.check_error( "Failed instantiating section 'myrepo':\n" "Failed instantiating section 'myrepo': exception caught from 'tests.config.test_central.myrepo':\n" "I raised", self.get_config_obj, manager, 'myrepo', 'myrepo') manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({'class': myrepo}) }], debug=True) self.check_error( "Failed instantiating section 'myrepo':\n" "Failed instantiating section 'myrepo': exception caught from 'tests.config.test_central.myrepo':\n" "I raised", self.get_config_obj, manager, 'myrepo', 'myrepo', klass=errors.ConfigurationError) def test_pargs(self): @configurable(types={'p': 'str', 'notp': 'str'}, positional=['p'], required=['p']) def myrepo(*args, **kwargs): return args, kwargs manager = central.ConfigManager( [{'myrepo': basics.HardCodedConfigSection({ 'class': myrepo, 'p': 'pos', 'notp': 'notpos', }), }]) self.assertEqual( manager.objects.myrepo['myrepo'], (('pos',), {'notp': 'notpos'})) def test_autoexec(self): @configurable(typename='configsection') def autoloader(): return {'spork': basics.HardCodedConfigSection({'class': repo, 'cache': 'test'})} manager = central.ConfigManager( [{'autoload-sub': basics.HardCodedConfigSection({ 'class': autoloader, })}]) self.assertEqual(set(['autoload-sub', 'spork']), set(manager.sections())) self.assertEqual(['spork'], list(manager.objects.repo.keys())) self.assertEqual( 'test', manager.collapse_named_section('spork').instantiate()) def test_reload(self): mod_dict = {'class': repo, 'cache': 'test'} @configurable(typename='configsection') def autoloader(): return {'spork': basics.HardCodedConfigSection(mod_dict)} manager = central.ConfigManager( [{'autoload-sub': basics.HardCodedConfigSection({ 'class': autoloader})}]) self.assertEqual(set(['autoload-sub', 'spork']), set(manager.sections())) self.assertEqual(['spork'], list(manager.objects.repo.keys())) collapsedspork = manager.collapse_named_section('spork') self.assertEqual('test', collapsedspork.instantiate()) mod_dict['cache'] = 'modded' self.assertIdentical(collapsedspork, manager.collapse_named_section('spork')) self.assertEqual('test', collapsedspork.instantiate()) types = manager.types manager.reload() newspork = manager.collapse_named_section('spork') self.assertNotIdentical(collapsedspork, newspork) self.assertEqual( 'modded', newspork.instantiate(), 'it did not throw away the cached instance') self.assertNotIdentical(types, manager.types) def test_instantiate_default_ref(self): manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({'class': drawer})}], ) self.assertEqual( (None, None), manager.collapse_named_section('spork').instantiate()) def test_allow_unknowns(self): @configurable(allow_unknowns=True) def myrepo(**kwargs): return kwargs manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({ 'class': myrepo, 'spork': 'foon'})}]) self.assertEqual( {'spork': 'foon'}, manager.collapse_named_section('spork').instantiate()) def test_reinstantiate_after_raise(self): spork = object() @configurable({'thing': 'ref:spork'}) def myrepo(thing): self.assertIdentical(thing, spork) raise errors.ComplexInstantiationError('I suck') @configurable(typename='spork') def spork_producer(): return spork manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({ 'class': myrepo, 'thing': basics.HardCodedConfigSection({ 'class': spork_producer, }), })}]) spork = manager.collapse_named_section('spork') for i in range(3): self.check_error( "Failed instantiating section 'spork':\n" "Failed instantiating section 'spork': exception caught from 'tests.config.test_central.myrepo':\n" "'I suck', callable unset!", spork.instantiate) for i in range(3): self.check_error( "Failed instantiating section 'spork':\n" "Failed instantiating section 'spork': exception caught from 'tests.config.test_central.myrepo':\n" "'I suck', callable unset!", manager.collapse_named_section('spork').instantiate) def test_instantiation_caching(self): @configurable(typename='drawer') def myrepo(): return object() manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({'class': myrepo}), 'drawer': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'content': 'spork', }), }]) config = manager.collapse_named_section('spork') self.assertIdentical(config.instantiate(), config.instantiate()) self.assertIdentical( config.instantiate(), manager.collapse_named_section('drawer').instantiate()[0]) def test_collapse_named_errors(self): manager = central.ConfigManager( [{'spork': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'content': 'ref'})}], [RemoteSource()]) self.assertRaises(KeyError, self.get_config_obj, manager, 'repo', 'foon') self.check_error( "Collapsing section named 'spork':\n" "Failed collapsing section key 'content':\n" "no section called 'ref'", self.get_config_obj, manager, 'repo', 'spork') def test_recursive_autoload(self): @configurable(typename='configsection') def autoloader(): return {'autoload-sub': basics.HardCodedConfigSection( {'class': autoloader}), 'spork': basics.HardCodedConfigSection({'class': repo, 'cache': 'test'})} self.check_error( "New config is trying to modify existing section(s) 'autoload-sub' " "that was already instantiated.", central.ConfigManager, [{'autoload-sub': basics.HardCodedConfigSection({ 'class': autoloader, })}]) def test_recursive_section_ref(self): manager = central.ConfigManager( [{'spork': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'content': 'foon'}), 'foon': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'content': 'spork'}), 'self': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'content': 'self'}), }]) self.check_error( "Collapsing section named 'self':\n" "Failed collapsing section key 'content':\n" "Reference to 'self' is recursive", self.get_config_obj, manager, 'drawer', 'self') self.check_error( "Collapsing section named 'spork':\n" "Failed collapsing section key 'content':\n" "Collapsing section named 'foon':\n" "Failed collapsing section key 'content':\n" "Reference to 'spork' is recursive", self.get_config_obj, manager, 'drawer', 'spork') def test_recursive_inherit(self): manager = central.ConfigManager( [{'spork': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'inherit': 'foon'}), 'foon': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'inherit': 'spork'}), }]) self.check_error( "Collapsing section named 'spork':\n" "Inherit 'spork' is recursive", self.get_config_obj, manager, 'drawer', 'spork') def test_alias(self): def myspork(): return object manager = central.ConfigManager( [{'spork': basics.HardCodedConfigSection({'class': myspork}), 'foon': basics.section_alias('spork', 'myspork'), }]) self.assertIdentical(manager.objects.myspork['spork'], manager.objects.myspork['foon']) def test_typecheck(self): @configurable({'myrepo': 'ref:repo'}, typename='repo') def reporef(myrepo=None): return myrepo @configurable({'myrepo': 'refs:repo'}, typename='repo') def reporefs(myrepo=None): return myrepo @configurable(typename='repo') def myrepo(): return 'repo!' manager = central.ConfigManager([{ 'myrepo': basics.HardCodedConfigSection({'class': myrepo}), 'drawer': basics.HardCodedConfigSection({'class': drawer}), 'right': basics.AutoConfigSection({'class': reporef, 'myrepo': 'myrepo'}), 'wrong': basics.AutoConfigSection({'class': reporef, 'myrepo': 'drawer'}), }]) self.check_error( "Collapsing section named 'wrong':\n" "Failed collapsing section key 'myrepo':\n" "reference 'drawer' should be of type 'repo', got 'drawer'", self.get_config_obj, manager, 'repo', 'wrong') self.assertEqual('repo!', manager.objects.repo['right']) manager = central.ConfigManager([{ 'myrepo': basics.HardCodedConfigSection({'class': myrepo}), 'drawer': basics.HardCodedConfigSection({'class': drawer}), 'right': basics.AutoConfigSection({'class': reporefs, 'myrepo': 'myrepo'}), 'wrong': basics.AutoConfigSection({'class': reporefs, 'myrepo': 'drawer'}), }]) self.check_error( "Collapsing section named 'wrong':\n" "Failed collapsing section key 'myrepo':\n" "reference 'drawer' should be of type 'repo', got 'drawer'", self.get_config_obj, manager, 'repo', 'wrong') self.assertEqual(['repo!'], manager.objects.repo['right']) def test_default(self): manager = central.ConfigManager([{ 'thing': basics.HardCodedConfigSection({'class': drawer, 'default': True}), 'bug': basics.HardCodedConfigSection({'class': None, 'inherit-only':True, 'default': True}), 'ignore': basics.HardCodedConfigSection({'class': drawer}), }]) self.assertEqual((None, None), manager.get_default('drawer')) self.assertTrue(manager.collapse_named_section('thing').default) manager = central.ConfigManager([{ 'thing': basics.HardCodedConfigSection({'class': drawer, 'default': True}), 'thing2': basics.HardCodedConfigSection({'class': drawer, 'default': True}), }]) self.check_error( "type drawer incorrectly has multiple default sections: 'thing', 'thing2'", manager.get_default, 'drawer') manager = central.ConfigManager([]) self.assertIdentical(None, manager.get_default('drawer')) def test_broken_default(self): def broken(): raise errors.ComplexInstantiationError('broken') manager = central.ConfigManager([{ 'thing': basics.HardCodedConfigSection({ 'class': drawer, 'default': True, 'content': basics.HardCodedConfigSection({ 'class': 'spork'})}), 'thing2': basics.HardCodedConfigSection({ 'class': broken, 'default': True})}]) self.check_error( "Collapsing defaults for 'drawer':\n" "Collapsing section named 'thing':\n" "Failed collapsing section key 'content':\n" "Failed converting argument 'class' to callable:\n" "'spork' is not callable", manager.get_default, 'drawer') self.check_error( "Collapsing defaults for 'broken':\n" "Collapsing section named 'thing':\n" "Failed collapsing section key 'content':\n" "Failed converting argument 'class' to callable:\n" "'spork' is not callable", manager.get_default, 'broken') def test_instantiate_broken_ref(self): @configurable(typename='drawer') def broken(): raise errors.ComplexInstantiationError('broken') manager = central.ConfigManager([{ 'one': basics.HardCodedConfigSection({ 'class': drawer, 'content': basics.HardCodedConfigSection({ 'class': broken})}), 'multi': basics.HardCodedConfigSection({ 'class': drawer, 'contents': [basics.HardCodedConfigSection({ 'class': broken})]}), }]) self.check_error( "Failed instantiating section 'one':\n" "Instantiating reference 'content' pointing at None:\n" "Failed instantiating section None:\n" "Failed instantiating section None: exception caught from 'tests.config.test_central.broken':\n" "'broken', callable unset!", manager.collapse_named_section('one').instantiate) self.check_error( "Failed instantiating section 'multi':\n" "Instantiating reference 'contents' pointing at None:\n" "Failed instantiating section None:\n" "Failed instantiating section None: exception caught from 'tests.config.test_central.broken':\n" "'broken', callable unset!", manager.collapse_named_section('multi').instantiate) def test_autoload_instantiationerror(self): @configurable(typename='configsection') def broken(): raise errors.ComplexInstantiationError('broken') self.check_error( "Failed loading autoload section 'autoload_broken':\n" "Failed instantiating section 'autoload_broken':\n" "Failed instantiating section 'autoload_broken': exception caught from 'tests.config.test_central.broken':\n" "'broken', callable unset!", central.ConfigManager, [{ 'autoload_broken': basics.HardCodedConfigSection({ 'class': broken})}]) def test_autoload_uncollapsable(self): self.check_error( "Failed collapsing autoload section 'autoload_broken':\n" "Collapsing section named 'autoload_broken':\n" "Failed converting argument 'class' to callable:\n" "'spork' is not callable", central.ConfigManager, [{ 'autoload_broken': basics.HardCodedConfigSection({ 'class': 'spork'})}]) def test_autoload_wrong_type(self): self.check_error( "Section 'autoload_wrong' is marked as autoload but type is " 'drawer, not configsection', central.ConfigManager, [{ 'autoload_wrong': basics.HardCodedConfigSection({ 'class': drawer})}]) def test_lazy_refs(self): @configurable({'myrepo': 'lazy_ref:repo', 'thing': 'lazy_ref'}, typename='repo') def reporef(myrepo=None, thing=None): return myrepo, thing @configurable({'myrepo': 'lazy_refs:repo', 'thing': 'lazy_refs'}, typename='repo') def reporefs(myrepo=None, thing=None): return myrepo, thing @configurable(typename='repo') def myrepo(): return 'repo!' manager = central.ConfigManager([{ 'myrepo': basics.HardCodedConfigSection({'class': myrepo}), 'drawer': basics.HardCodedConfigSection({'class': drawer}), 'right': basics.AutoConfigSection({'class': reporef, 'myrepo': 'myrepo'}), 'wrong': basics.AutoConfigSection({'class': reporef, 'myrepo': 'drawer'}), }]) self.check_error( "reference 'drawer' should be of type 'repo', got 'drawer'", manager.objects.repo['wrong'][0].collapse) self.assertEqual('repo!', manager.objects.repo['right'][0].instantiate()) manager = central.ConfigManager([{ 'myrepo': basics.HardCodedConfigSection({'class': myrepo}), 'drawer': basics.HardCodedConfigSection({'class': drawer}), 'right': basics.AutoConfigSection({'class': reporefs, 'myrepo': 'myrepo'}), 'wrong': basics.AutoConfigSection({'class': reporefs, 'myrepo': 'drawer'}), }]) self.check_error( "reference 'drawer' should be of type 'repo', got 'drawer'", manager.objects.repo['wrong'][0][0].collapse) self.assertEqual( ['repo!'], [c.instantiate() for c in manager.objects.repo['right'][0]]) def test_inherited_default(self): manager = central.ConfigManager([{ 'default': basics.HardCodedConfigSection({ 'default': True, 'inherit': ['basic'], }), 'uncollapsable': basics.HardCodedConfigSection({ 'default': True, 'inherit': ['spork'], 'inherit-only': True, }), 'basic': basics.HardCodedConfigSection({'class': drawer}), }], [RemoteSource()]) self.assertTrue(manager.get_default('drawer')) def test_section_names(self): manager = central.ConfigManager([{ 'thing': basics.HardCodedConfigSection({'class': drawer}), }], [RemoteSource()]) collapsed = manager.collapse_named_section('thing') self.assertEqual('thing', collapsed.name) def test_inherit_only(self): manager = central.ConfigManager([{ 'source': basics.HardCodedConfigSection({ 'class': drawer, 'inherit-only': True, }), 'target': basics.HardCodedConfigSection({ 'inherit': ['source'], })}], [RemoteSource()]) self.check_error( "Collapsing section named 'source':\n" 'cannot collapse inherit-only section', manager.collapse_named_section, 'source') self.assertTrue(manager.collapse_named_section('target')) def test_self_inherit(self): section = basics.HardCodedConfigSection({'inherit': ['self']}) manager = central.ConfigManager([{ 'self': basics.ConfigSectionFromStringDict({ 'class': 'tests.config.test_central.drawer', 'inherit': 'self'}), }], [RemoteSource()]) self.check_error( "Collapsing section named 'self':\n" "Self-inherit 'self' cannot be found", self.get_config_obj, manager, 'drawer', 'self') self.check_error( "Self-inherit 'self' cannot be found", manager.collapse_section, [section]) manager = central.ConfigManager([{ 'self': basics.HardCodedConfigSection({ 'inherit': ['self'], })}, { 'self': basics.HardCodedConfigSection({ 'inherit': ['self'], })}, { 'self': basics.HardCodedConfigSection({ 'class': drawer})}]) self.assertTrue(manager.collapse_named_section('self')) self.assertTrue(manager.collapse_section([section])) def test_prepend_inherit(self): manager = central.ConfigManager([{ 'sect': basics.HardCodedConfigSection({ 'inherit.prepend': ['self']})}]) self.check_error( "Collapsing section named 'sect':\n" 'Prepending or appending to the inherit list makes no sense', manager.collapse_named_section, 'sect') def test_list_prepend(self): @configurable({'seq': 'list'}) def seq(seq): return seq manager = central.ConfigManager([{ 'inh': basics.HardCodedConfigSection({ 'inherit': ['sect'], 'seq.prepend': ['pre'], }), 'sect': basics.HardCodedConfigSection({ 'inherit': ['base'], 'seq': ['1', '2'], })}, { 'base': basics.HardCodedConfigSection({ 'class': seq, 'seq.prepend': ['-1'], 'seq.append': ['post'], })}]) self.assertEqual(['-1', 'post'], manager.objects.seq['base']) self.assertEqual(['1', '2'], manager.objects.seq['sect']) self.assertEqual(['pre', '1', '2'], manager.objects.seq['inh']) def test_str_prepend(self): @configurable({'string': 'str'}) def sect(string): return string manager = central.ConfigManager([{ 'inh': basics.HardCodedConfigSection({ 'inherit': ['sect'], 'string.prepend': 'pre', }), 'sect': basics.HardCodedConfigSection({ 'inherit': ['base'], 'string': 'b', })}, { 'base': basics.HardCodedConfigSection({ 'class': sect, 'string.prepend': 'a', 'string.append': 'c', })}]) self.assertEqual('a c', manager.objects.sect['base']) self.assertEqual('b', manager.objects.sect['sect']) self.assertEqual('pre b', manager.objects.sect['inh'])
true
true
f73622b921f9f382287c967506369eda757d746e
2,394
py
Python
speedup.py
ueqri/akitaplot
7590df560cb8e05e9f54cfcf3f447e1b1a642763
[ "MIT" ]
null
null
null
speedup.py
ueqri/akitaplot
7590df560cb8e05e9f54cfcf3f447e1b1a642763
[ "MIT" ]
null
null
null
speedup.py
ueqri/akitaplot
7590df560cb8e05e9f54cfcf3f447e1b1a642763
[ "MIT" ]
null
null
null
from akitaplot import speedup_plot_base, speedup_base, metrics grab = { "name": "kernelTime", "where": "driver", "what": "kernel_time" } baseline = { "displayName": "16 Unified MGPUSim", "benchmarks": [ ("FIR", metrics("example_data/uni/fir-1024000.csv")), ("AES", metrics("example_data/uni/aes-6553600.csv")), ("KM", metrics("example_data/uni/kmeans-notion.csv")), ("MM", metrics("example_data/uni/matrixmultiplication-512-512-512.csv")), ("MT", metrics("example_data/uni/matrixtranspose-2560.csv")), ("FFT", metrics("example_data/uni/fft-16-5.csv")), ("BFS", metrics("example_data/uni/bfs-256000.csv")), ("AX", metrics("example_data/uni/atax-4096-4096.csv")), ("NW", metrics("example_data/uni/nw-6400.csv")), ("RU", metrics("example_data/uni/relu-4096000.csv")), ("BG", metrics("example_data/uni/bicg-4096-4096.csv")), ("PR", metrics("example_data/uni/pagerank-1024.csv")), ("ST", metrics("example_data/uni/stencil2d-256-256-20.csv")), ("SV", metrics("example_data/uni/spmv-2560-0_1.csv")) ] } waferscale = { "displayName": "Wafer-Scale", "benchmarks": [ ("FIR", metrics("example_data/akkalat/fir-1024000.csv")), ("AES", metrics("example_data/akkalat/aes-6553600.csv")), ("KM", metrics("example_data/akkalat/kmeans-notion.csv")), ("MM", metrics("example_data/akkalat/matrixmultiplication-512-512-512.csv")), ("MT", metrics("example_data/akkalat/matrixtranspose-2560.csv")), ("FFT", metrics("example_data/akkalat/fft-16-5.csv")), ("BFS", metrics("example_data/akkalat/bfs-256000.csv")), ("AX", metrics("example_data/akkalat/atax-4096-4096.csv")), ("NW", metrics("example_data/akkalat/nw-6400.csv")), ("RU", metrics("example_data/akkalat/relu-4096000.csv")), ("BG", metrics("example_data/akkalat/bicg-4096-4096.csv")), ("PR", metrics("example_data/akkalat/pagerank-1024.csv")), ("ST", metrics("example_data/akkalat/stencil2d-256-256-20.csv")), ("SV", metrics("example_data/akkalat/spmv-2560-0_1.csv")) ] } class speedup_plot(speedup_plot_base): def decorate(self): # Customize the decorations, e.g. split line, text pass class speedup(speedup_base): def transform_plot(self, plot_name, table): return speedup_plot(plot_name, table, figure_size=(10, 2)) if __name__ == '__main__': s = speedup(grab, [baseline, waferscale]) s.dump_tables()
39.245902
81
0.673768
from akitaplot import speedup_plot_base, speedup_base, metrics grab = { "name": "kernelTime", "where": "driver", "what": "kernel_time" } baseline = { "displayName": "16 Unified MGPUSim", "benchmarks": [ ("FIR", metrics("example_data/uni/fir-1024000.csv")), ("AES", metrics("example_data/uni/aes-6553600.csv")), ("KM", metrics("example_data/uni/kmeans-notion.csv")), ("MM", metrics("example_data/uni/matrixmultiplication-512-512-512.csv")), ("MT", metrics("example_data/uni/matrixtranspose-2560.csv")), ("FFT", metrics("example_data/uni/fft-16-5.csv")), ("BFS", metrics("example_data/uni/bfs-256000.csv")), ("AX", metrics("example_data/uni/atax-4096-4096.csv")), ("NW", metrics("example_data/uni/nw-6400.csv")), ("RU", metrics("example_data/uni/relu-4096000.csv")), ("BG", metrics("example_data/uni/bicg-4096-4096.csv")), ("PR", metrics("example_data/uni/pagerank-1024.csv")), ("ST", metrics("example_data/uni/stencil2d-256-256-20.csv")), ("SV", metrics("example_data/uni/spmv-2560-0_1.csv")) ] } waferscale = { "displayName": "Wafer-Scale", "benchmarks": [ ("FIR", metrics("example_data/akkalat/fir-1024000.csv")), ("AES", metrics("example_data/akkalat/aes-6553600.csv")), ("KM", metrics("example_data/akkalat/kmeans-notion.csv")), ("MM", metrics("example_data/akkalat/matrixmultiplication-512-512-512.csv")), ("MT", metrics("example_data/akkalat/matrixtranspose-2560.csv")), ("FFT", metrics("example_data/akkalat/fft-16-5.csv")), ("BFS", metrics("example_data/akkalat/bfs-256000.csv")), ("AX", metrics("example_data/akkalat/atax-4096-4096.csv")), ("NW", metrics("example_data/akkalat/nw-6400.csv")), ("RU", metrics("example_data/akkalat/relu-4096000.csv")), ("BG", metrics("example_data/akkalat/bicg-4096-4096.csv")), ("PR", metrics("example_data/akkalat/pagerank-1024.csv")), ("ST", metrics("example_data/akkalat/stencil2d-256-256-20.csv")), ("SV", metrics("example_data/akkalat/spmv-2560-0_1.csv")) ] } class speedup_plot(speedup_plot_base): def decorate(self): pass class speedup(speedup_base): def transform_plot(self, plot_name, table): return speedup_plot(plot_name, table, figure_size=(10, 2)) if __name__ == '__main__': s = speedup(grab, [baseline, waferscale]) s.dump_tables()
true
true
f73625b05e9348fb81d26dabd1722edb75b48270
5,586
py
Python
gluon/packages/dal/pydal/contrib/portalocker.py
GeorgesBrantley/ResistanceGame
65ec925ec8399af355e176c4814a749fde5f907d
[ "BSD-3-Clause" ]
408
2015-01-01T10:31:47.000Z
2022-03-26T17:41:21.000Z
gluon/packages/dal/pydal/contrib/portalocker.py
GeorgesBrantley/ResistanceGame
65ec925ec8399af355e176c4814a749fde5f907d
[ "BSD-3-Clause" ]
521
2015-01-08T14:45:54.000Z
2022-03-24T11:15:22.000Z
gluon/packages/dal/pydal/contrib/portalocker.py
GeorgesBrantley/ResistanceGame
65ec925ec8399af355e176c4814a749fde5f907d
[ "BSD-3-Clause" ]
158
2015-01-25T20:02:00.000Z
2022-03-01T06:29:12.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Cross-platform (posix/nt) API for flock-style file locking. Synopsis:: import portalocker file = open(\"somefile\", \"r+\") portalocker.lock(file, portalocker.LOCK_EX) file.seek(12) file.write(\"foo\") file.close() If you know what you're doing, you may choose to:: portalocker.unlock(file) before closing the file, but why? Methods:: lock( file, flags ) unlock( file ) Constants:: LOCK_EX - exclusive lock LOCK_SH - shared lock LOCK_NB - don't lock when locking Original --------- http://code.activestate.com/recipes/65203-portalocker-cross-platform-posixnt-api-for-flock-s/ I learned the win32 technique for locking files from sample code provided by John Nielsen <nielsenjf@my-deja.com> in the documentation that accompanies the win32 modules. Author: Jonathan Feinberg <jdf@pobox.com> Roundup Changes --------------- 2012-11-28 (anatoly techtonik) - Ported to ctypes - Dropped support for Win95, Win98 and WinME - Added return result Web2py Changes -------------- 2016-07-28 (niphlod) - integrated original recipe, web2py's GAE warnings and roundup in a unique solution """ import sys import logging PY2 = sys.version_info[0] == 2 logger = logging.getLogger("pydal") os_locking = None try: import google.appengine os_locking = "gae" except: try: import fcntl os_locking = "posix" except: try: import msvcrt import ctypes from ctypes.wintypes import BOOL, DWORD, HANDLE from ctypes import windll os_locking = "windows" except: pass if os_locking == "windows": LOCK_SH = 0 # the default LOCK_NB = 0x1 # LOCKFILE_FAIL_IMMEDIATELY LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK # --- the code is taken from pyserial project --- # # detect size of ULONG_PTR def is_64bit(): return ctypes.sizeof(ctypes.c_ulong) != ctypes.sizeof(ctypes.c_void_p) if is_64bit(): ULONG_PTR = ctypes.c_int64 else: ULONG_PTR = ctypes.c_ulong PVOID = ctypes.c_void_p # --- Union inside Structure by stackoverflow:3480240 --- class _OFFSET(ctypes.Structure): _fields_ = [("Offset", DWORD), ("OffsetHigh", DWORD)] class _OFFSET_UNION(ctypes.Union): _anonymous_ = ["_offset"] _fields_ = [("_offset", _OFFSET), ("Pointer", PVOID)] class OVERLAPPED(ctypes.Structure): _anonymous_ = ["_offset_union"] _fields_ = [ ("Internal", ULONG_PTR), ("InternalHigh", ULONG_PTR), ("_offset_union", _OFFSET_UNION), ("hEvent", HANDLE), ] LPOVERLAPPED = ctypes.POINTER(OVERLAPPED) # --- Define function prototypes for extra safety --- LockFileEx = windll.kernel32.LockFileEx LockFileEx.restype = BOOL LockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, DWORD, LPOVERLAPPED] UnlockFileEx = windll.kernel32.UnlockFileEx UnlockFileEx.restype = BOOL UnlockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, LPOVERLAPPED] def lock(file, flags): hfile = msvcrt.get_osfhandle(file.fileno()) overlapped = OVERLAPPED() LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ctypes.byref(overlapped)) def unlock(file): hfile = msvcrt.get_osfhandle(file.fileno()) overlapped = OVERLAPPED() UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped)) elif os_locking == "posix": LOCK_EX = fcntl.LOCK_EX LOCK_SH = fcntl.LOCK_SH LOCK_NB = fcntl.LOCK_NB def lock(file, flags): fcntl.flock(file.fileno(), flags) def unlock(file): fcntl.flock(file.fileno(), fcntl.LOCK_UN) else: if os_locking != "gae": logger.debug("no file locking, this will cause problems") LOCK_EX = None LOCK_SH = None LOCK_NB = None def lock(file, flags): pass def unlock(file): pass def open_file(filename, mode): if PY2 or "b" in mode: f = open(filename, mode) else: f = open(filename, mode, encoding="utf8") return f class LockedFile(object): def __init__(self, filename, mode="rb"): self.filename = filename self.mode = mode self.file = None if "r" in mode: self.file = open_file(filename, mode) lock(self.file, LOCK_SH) elif "w" in mode or "a" in mode: self.file = open_file(filename, mode.replace("w", "a")) lock(self.file, LOCK_EX) if "a" not in mode: self.file.seek(0) self.file.truncate(0) else: raise RuntimeError("invalid LockedFile(...,mode)") def read(self, size=None): return self.file.read() if size is None else self.file.read(size) def readinto(self, b): b[:] = self.file.read() def readline(self): return self.file.readline() def readlines(self): return self.file.readlines() def write(self, data): self.file.write(data) self.file.flush() def close(self): if self.file is not None: unlock(self.file) self.file.close() self.file = None def __del__(self): if self.file is not None: self.close() def read_locked(filename): fp = LockedFile(filename, "rb") data = fp.read() fp.close() return data def write_locked(filename, data): fp = LockedFile(filename, "wb") data = fp.write(data) fp.close()
24.077586
93
0.61672
import sys import logging PY2 = sys.version_info[0] == 2 logger = logging.getLogger("pydal") os_locking = None try: import google.appengine os_locking = "gae" except: try: import fcntl os_locking = "posix" except: try: import msvcrt import ctypes from ctypes.wintypes import BOOL, DWORD, HANDLE from ctypes import windll os_locking = "windows" except: pass if os_locking == "windows": LOCK_SH = 0 LOCK_NB = 0x1 LOCK_EX = 0x2 def is_64bit(): return ctypes.sizeof(ctypes.c_ulong) != ctypes.sizeof(ctypes.c_void_p) if is_64bit(): ULONG_PTR = ctypes.c_int64 else: ULONG_PTR = ctypes.c_ulong PVOID = ctypes.c_void_p class _OFFSET(ctypes.Structure): _fields_ = [("Offset", DWORD), ("OffsetHigh", DWORD)] class _OFFSET_UNION(ctypes.Union): _anonymous_ = ["_offset"] _fields_ = [("_offset", _OFFSET), ("Pointer", PVOID)] class OVERLAPPED(ctypes.Structure): _anonymous_ = ["_offset_union"] _fields_ = [ ("Internal", ULONG_PTR), ("InternalHigh", ULONG_PTR), ("_offset_union", _OFFSET_UNION), ("hEvent", HANDLE), ] LPOVERLAPPED = ctypes.POINTER(OVERLAPPED) LockFileEx = windll.kernel32.LockFileEx LockFileEx.restype = BOOL LockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, DWORD, LPOVERLAPPED] UnlockFileEx = windll.kernel32.UnlockFileEx UnlockFileEx.restype = BOOL UnlockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, LPOVERLAPPED] def lock(file, flags): hfile = msvcrt.get_osfhandle(file.fileno()) overlapped = OVERLAPPED() LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ctypes.byref(overlapped)) def unlock(file): hfile = msvcrt.get_osfhandle(file.fileno()) overlapped = OVERLAPPED() UnlockFileEx(hfile, 0, 0, 0xFFFF0000, ctypes.byref(overlapped)) elif os_locking == "posix": LOCK_EX = fcntl.LOCK_EX LOCK_SH = fcntl.LOCK_SH LOCK_NB = fcntl.LOCK_NB def lock(file, flags): fcntl.flock(file.fileno(), flags) def unlock(file): fcntl.flock(file.fileno(), fcntl.LOCK_UN) else: if os_locking != "gae": logger.debug("no file locking, this will cause problems") LOCK_EX = None LOCK_SH = None LOCK_NB = None def lock(file, flags): pass def unlock(file): pass def open_file(filename, mode): if PY2 or "b" in mode: f = open(filename, mode) else: f = open(filename, mode, encoding="utf8") return f class LockedFile(object): def __init__(self, filename, mode="rb"): self.filename = filename self.mode = mode self.file = None if "r" in mode: self.file = open_file(filename, mode) lock(self.file, LOCK_SH) elif "w" in mode or "a" in mode: self.file = open_file(filename, mode.replace("w", "a")) lock(self.file, LOCK_EX) if "a" not in mode: self.file.seek(0) self.file.truncate(0) else: raise RuntimeError("invalid LockedFile(...,mode)") def read(self, size=None): return self.file.read() if size is None else self.file.read(size) def readinto(self, b): b[:] = self.file.read() def readline(self): return self.file.readline() def readlines(self): return self.file.readlines() def write(self, data): self.file.write(data) self.file.flush() def close(self): if self.file is not None: unlock(self.file) self.file.close() self.file = None def __del__(self): if self.file is not None: self.close() def read_locked(filename): fp = LockedFile(filename, "rb") data = fp.read() fp.close() return data def write_locked(filename, data): fp = LockedFile(filename, "wb") data = fp.write(data) fp.close()
true
true
f73625c823d2d4f962aa9218ec9d19a20ef0e82e
3,826
py
Python
project/span_bert/utils.py
hancia/ToxicSpansDetection
4a10600292af90a936767aee09559b39380e3d5e
[ "Apache-2.0" ]
3
2021-03-23T08:07:54.000Z
2021-11-13T07:13:32.000Z
project/span_bert/utils.py
hancia/ToxicSpansDetection
4a10600292af90a936767aee09559b39380e3d5e
[ "Apache-2.0" ]
null
null
null
project/span_bert/utils.py
hancia/ToxicSpansDetection
4a10600292af90a936767aee09559b39380e3d5e
[ "Apache-2.0" ]
null
null
null
import csv from ast import literal_eval from configparser import ConfigParser from io import StringIO import comet_ml import pandas as pd from easydict import EasyDict def f1_semeval(pred_spans, true_spans): """ F1 (a.k.a. DICE) operating on two lists of offsets (e.g., character). >>> assert f1([0, 1, 4, 5], [0, 1, 6]) == 0.5714285714285714 :param predictions: a list of predicted offsets :param gold: a list of offsets serving as the ground truth :return: a score between 0 and 1 """ if len(true_spans) == 0: return 1 if len(pred_spans) == 0 else 0 nom = 2 * len(set(pred_spans).intersection(set(true_spans))) denom = len(set(pred_spans)) + len(set(true_spans)) return nom / denom def get_preds_from_experiment(experiment): assets_list = experiment.get_asset_list() spans_asset = list(filter(lambda x: x['fileName'] == 'spans-pred-filled.txt', assets_list))[0] span_id = spans_asset['assetId'] binary_file = experiment.get_asset(span_id, return_type='text') df = pd.read_table(StringIO(binary_file), sep="\t", header=None, names=['id', 'spans'], index_col='id') return df def get_api_and_experiment(experiment_id): config = ConfigParser() config.read('config.ini') comet_config = EasyDict(config['cometml']) comet_api = comet_ml.api.API(api_key=comet_config.apikey) experiment = comet_api.get(project_name=comet_config.projectname, workspace=comet_config.workspace, experiment=experiment_id) return comet_api, experiment def fill_holes_in_row(spans: str) -> str: sorted_spans = sorted(literal_eval(spans)) new_spans = [] if sorted_spans and len(sorted_spans) > 1: for i in range(len(sorted_spans) - 1): new_spans.append(sorted_spans[i]) if sorted_spans[i + 1] - sorted_spans[i] == 2: new_spans.append(sorted_spans[i] + 1) new_spans.append(sorted_spans[-1]) return str(new_spans) def fill_holes_in_row_three(spans: str) -> str: sorted_spans = sorted(literal_eval(spans)) new_spans = [] if sorted_spans and len(sorted_spans) > 1: for i in range(len(sorted_spans) - 1): new_spans.append(sorted_spans[i]) if sorted_spans[i + 1] - sorted_spans[i] == 2: new_spans.append(sorted_spans[i] + 1) elif sorted_spans[i + 1] - sorted_spans[i] == 3: new_spans.append(sorted_spans[i] + 1) new_spans.append(sorted_spans[i] + 2) new_spans.append(sorted_spans[-1]) return str(new_spans) def remove_ones_in_row(spans: str) -> str: sorted_spans = sorted(literal_eval(spans)) new_spans = [] if sorted_spans and len(sorted_spans) > 1: if sorted_spans[1] - sorted_spans[0] == 1: new_spans.append(sorted_spans[0]) for i in range(1, len(sorted_spans) - 1): if sorted_spans[i + 1] - sorted_spans[i] == 1 or sorted_spans[i] - sorted_spans[i - 1] == 1: new_spans.append(sorted_spans[i]) if sorted_spans[-1] - sorted_spans[-2] == 1: new_spans.append(sorted_spans[-1]) return str(new_spans) def log_predicted_spans(df, logger): df.to_csv('spans-pred.txt', header=False, sep='\t', quoting=csv.QUOTE_NONE, escapechar='\n') logger.experiment.log_asset('spans-pred.txt') df['spans'] = df['spans'].apply(fill_holes_in_row) df.to_csv('spans-pred-filled.txt', header=False, sep='\t', quoting=csv.QUOTE_NONE, escapechar='\n') logger.experiment.log_asset('spans-pred-filled.txt') df['spans'] = df['spans'].apply(remove_ones_in_row) df.to_csv('spans-pred-filled-removed.txt', header=False, sep='\t', quoting=csv.QUOTE_NONE, escapechar='\n') logger.experiment.log_asset('spans-pred-filled-removed.txt')
38.646465
111
0.661526
import csv from ast import literal_eval from configparser import ConfigParser from io import StringIO import comet_ml import pandas as pd from easydict import EasyDict def f1_semeval(pred_spans, true_spans): if len(true_spans) == 0: return 1 if len(pred_spans) == 0 else 0 nom = 2 * len(set(pred_spans).intersection(set(true_spans))) denom = len(set(pred_spans)) + len(set(true_spans)) return nom / denom def get_preds_from_experiment(experiment): assets_list = experiment.get_asset_list() spans_asset = list(filter(lambda x: x['fileName'] == 'spans-pred-filled.txt', assets_list))[0] span_id = spans_asset['assetId'] binary_file = experiment.get_asset(span_id, return_type='text') df = pd.read_table(StringIO(binary_file), sep="\t", header=None, names=['id', 'spans'], index_col='id') return df def get_api_and_experiment(experiment_id): config = ConfigParser() config.read('config.ini') comet_config = EasyDict(config['cometml']) comet_api = comet_ml.api.API(api_key=comet_config.apikey) experiment = comet_api.get(project_name=comet_config.projectname, workspace=comet_config.workspace, experiment=experiment_id) return comet_api, experiment def fill_holes_in_row(spans: str) -> str: sorted_spans = sorted(literal_eval(spans)) new_spans = [] if sorted_spans and len(sorted_spans) > 1: for i in range(len(sorted_spans) - 1): new_spans.append(sorted_spans[i]) if sorted_spans[i + 1] - sorted_spans[i] == 2: new_spans.append(sorted_spans[i] + 1) new_spans.append(sorted_spans[-1]) return str(new_spans) def fill_holes_in_row_three(spans: str) -> str: sorted_spans = sorted(literal_eval(spans)) new_spans = [] if sorted_spans and len(sorted_spans) > 1: for i in range(len(sorted_spans) - 1): new_spans.append(sorted_spans[i]) if sorted_spans[i + 1] - sorted_spans[i] == 2: new_spans.append(sorted_spans[i] + 1) elif sorted_spans[i + 1] - sorted_spans[i] == 3: new_spans.append(sorted_spans[i] + 1) new_spans.append(sorted_spans[i] + 2) new_spans.append(sorted_spans[-1]) return str(new_spans) def remove_ones_in_row(spans: str) -> str: sorted_spans = sorted(literal_eval(spans)) new_spans = [] if sorted_spans and len(sorted_spans) > 1: if sorted_spans[1] - sorted_spans[0] == 1: new_spans.append(sorted_spans[0]) for i in range(1, len(sorted_spans) - 1): if sorted_spans[i + 1] - sorted_spans[i] == 1 or sorted_spans[i] - sorted_spans[i - 1] == 1: new_spans.append(sorted_spans[i]) if sorted_spans[-1] - sorted_spans[-2] == 1: new_spans.append(sorted_spans[-1]) return str(new_spans) def log_predicted_spans(df, logger): df.to_csv('spans-pred.txt', header=False, sep='\t', quoting=csv.QUOTE_NONE, escapechar='\n') logger.experiment.log_asset('spans-pred.txt') df['spans'] = df['spans'].apply(fill_holes_in_row) df.to_csv('spans-pred-filled.txt', header=False, sep='\t', quoting=csv.QUOTE_NONE, escapechar='\n') logger.experiment.log_asset('spans-pred-filled.txt') df['spans'] = df['spans'].apply(remove_ones_in_row) df.to_csv('spans-pred-filled-removed.txt', header=False, sep='\t', quoting=csv.QUOTE_NONE, escapechar='\n') logger.experiment.log_asset('spans-pred-filled-removed.txt')
true
true
f73625e7cfe600393ba0656bf47e99a78a52eb62
1,284
py
Python
src/main/python/programmingtheiot/cda/emulated/HumiditySensorEmulatorTask.py
NULishengZhang/piot-python-components
006674bc42443bb2a843bfd7dfa5b55be9843961
[ "MIT" ]
null
null
null
src/main/python/programmingtheiot/cda/emulated/HumiditySensorEmulatorTask.py
NULishengZhang/piot-python-components
006674bc42443bb2a843bfd7dfa5b55be9843961
[ "MIT" ]
null
null
null
src/main/python/programmingtheiot/cda/emulated/HumiditySensorEmulatorTask.py
NULishengZhang/piot-python-components
006674bc42443bb2a843bfd7dfa5b55be9843961
[ "MIT" ]
null
null
null
##### # # This class is part of the Programming the Internet of Things project. # # It is provided as a simple shell to guide the student and assist with # implementation for the Programming the Internet of Things exercises, # and designed to be modified by the student as needed. # from programmingtheiot.data.SensorData import SensorData import programmingtheiot.common.ConfigConst as ConfigConst from programmingtheiot.common.ConfigUtil import ConfigUtil from programmingtheiot.cda.sim.BaseSensorSimTask import BaseSensorSimTask from pisense import SenseHAT class HumiditySensorEmulatorTask(BaseSensorSimTask): """ Shell representation of class for student implementation. """ # HumiditySensorEmulatorTask Constructor def __init__(self, dataSet=None): super(HumiditySensorEmulatorTask, self).__init__( name=ConfigConst.HUMIDITY_SENSOR_NAME, typeID=ConfigConst.HUMIDITY_SENSOR_TYPE) self.sh = SenseHAT(emulate=True) # generate telemetry by name and typeId def generateTelemetry(self) -> SensorData: sensorData = SensorData(name=self.getName(), typeID=self.getTypeID()) sensorVal = self.sh.environ.humidity sensorData.setValue(sensorVal) self.latestSensorData = sensorData return sensorData
31.317073
137
0.76947
rom programmingtheiot.data.SensorData import SensorData import programmingtheiot.common.ConfigConst as ConfigConst from programmingtheiot.common.ConfigUtil import ConfigUtil from programmingtheiot.cda.sim.BaseSensorSimTask import BaseSensorSimTask from pisense import SenseHAT class HumiditySensorEmulatorTask(BaseSensorSimTask): def __init__(self, dataSet=None): super(HumiditySensorEmulatorTask, self).__init__( name=ConfigConst.HUMIDITY_SENSOR_NAME, typeID=ConfigConst.HUMIDITY_SENSOR_TYPE) self.sh = SenseHAT(emulate=True) def generateTelemetry(self) -> SensorData: sensorData = SensorData(name=self.getName(), typeID=self.getTypeID()) sensorVal = self.sh.environ.humidity sensorData.setValue(sensorVal) self.latestSensorData = sensorData return sensorData
true
true
f73627a984cb39c8412520997364c7b7eb205157
11,362
py
Python
venv/lib/python3.6/site-packages/ansible_collections/fortinet/fortimanager/plugins/modules/fmgr_firewall_ssh_localca.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
1
2020-01-22T13:11:23.000Z
2020-01-22T13:11:23.000Z
venv/lib/python3.6/site-packages/ansible_collections/fortinet/fortimanager/plugins/modules/fmgr_firewall_ssh_localca.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
12
2020-02-21T07:24:52.000Z
2020-04-14T09:54:32.000Z
venv/lib/python3.6/site-packages/ansible_collections/fortinet/fortimanager/plugins/modules/fmgr_firewall_ssh_localca.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
null
null
null
#!/usr/bin/python from __future__ import absolute_import, division, print_function # Copyright 2019-2021 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fmgr_firewall_ssh_localca short_description: SSH proxy local CA. description: - This module is able to configure a FortiManager device. - Examples include all parameters and values which need to be adjusted to data sources before usage. version_added: "2.10" author: - Link Zheng (@chillancezen) - Jie Xue (@JieX19) - Frank Shen (@fshen01) - Hongbin Lu (@fgtdev-hblu) notes: - Running in workspace locking mode is supported in this FortiManager module, the top level parameters workspace_locking_adom and workspace_locking_timeout help do the work. - To create or update an object, use state present directive. - To delete an object, use state absent directive. - Normally, running one module can fail when a non-zero rc is returned. you can also override the conditions to fail or succeed with parameters rc_failed and rc_succeeded options: enable_log: description: Enable/Disable logging for task required: false type: bool default: false proposed_method: description: The overridden method for the underlying Json RPC request required: false type: str choices: - update - set - add bypass_validation: description: only set to True when module schema diffs with FortiManager API structure, module continues to execute without validating parameters required: false type: bool default: false workspace_locking_adom: description: the adom to lock for FortiManager running in workspace mode, the value can be global and others including root required: false type: str workspace_locking_timeout: description: the maximum time in seconds to wait for other user to release the workspace lock required: false type: int default: 300 state: description: the directive to create, update or delete an object type: str required: true choices: - present - absent rc_succeeded: description: the rc codes list with which the conditions to succeed will be overriden type: list required: false rc_failed: description: the rc codes list with which the conditions to fail will be overriden type: list required: false adom: description: the parameter (adom) in requested url type: str required: true firewall_ssh_localca: description: the top level parameters set required: false type: dict suboptions: name: type: str description: 'SSH proxy local CA name.' password: description: 'Password for SSH private key.' type: str private-key: type: str description: 'SSH proxy private key, encrypted with a password.' public-key: type: str description: 'SSH proxy public key.' source: type: str description: 'SSH proxy local CA source type.' choices: - 'built-in' - 'user' ''' EXAMPLES = ''' - hosts: fortimanager-inventory collections: - fortinet.fortimanager connection: httpapi vars: ansible_httpapi_use_ssl: True ansible_httpapi_validate_certs: False ansible_httpapi_port: 443 tasks: - name: SSH proxy local CA. fmgr_firewall_ssh_localca: bypass_validation: False workspace_locking_adom: <value in [global, custom adom including root]> workspace_locking_timeout: 300 rc_succeeded: [0, -2, -3, ...] rc_failed: [-2, -3, ...] adom: <your own value> state: <value in [present, absent]> firewall_ssh_localca: name: <value of string> password: <value of string> private-key: <value of string> public-key: <value of string> source: <value in [built-in, user]> ''' RETURN = ''' request_url: description: The full url requested returned: always type: str sample: /sys/login/user response_code: description: The status of api request returned: always type: int sample: 0 response_message: description: The descriptive message of the api response type: str returned: always sample: OK. ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import NAPIManager from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import check_galaxy_version from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import check_parameter_bypass def main(): jrpc_urls = [ '/pm/config/global/obj/firewall/ssh/local-ca', '/pm/config/adom/{adom}/obj/firewall/ssh/local-ca' ] perobject_jrpc_urls = [ '/pm/config/global/obj/firewall/ssh/local-ca/{local-ca}', '/pm/config/adom/{adom}/obj/firewall/ssh/local-ca/{local-ca}' ] url_params = ['adom'] module_primary_key = 'name' module_arg_spec = { 'enable_log': { 'type': 'bool', 'required': False, 'default': False }, 'forticloud_access_token': { 'type': 'str', 'required': False, 'no_log': True }, 'proposed_method': { 'type': 'str', 'required': False, 'choices': [ 'set', 'update', 'add' ] }, 'bypass_validation': { 'type': 'bool', 'required': False, 'default': False }, 'workspace_locking_adom': { 'type': 'str', 'required': False }, 'workspace_locking_timeout': { 'type': 'int', 'required': False, 'default': 300 }, 'rc_succeeded': { 'required': False, 'type': 'list' }, 'rc_failed': { 'required': False, 'type': 'list' }, 'state': { 'type': 'str', 'required': True, 'choices': [ 'present', 'absent' ] }, 'adom': { 'required': True, 'type': 'str' }, 'firewall_ssh_localca': { 'required': False, 'type': 'dict', 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'options': { 'name': { 'required': True, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'password': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'private-key': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'public-key': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'source': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'built-in', 'user' ], 'type': 'str' } } } } params_validation_blob = [] check_galaxy_version(module_arg_spec) module = AnsibleModule(argument_spec=check_parameter_bypass(module_arg_spec, 'firewall_ssh_localca'), supports_check_mode=False) fmgr = None if module._socket_path: connection = Connection(module._socket_path) connection.set_option('enable_log', module.params['enable_log'] if 'enable_log' in module.params else False) connection.set_option('forticloud_access_token', module.params['forticloud_access_token'] if 'forticloud_access_token' in module.params else None) fmgr = NAPIManager(jrpc_urls, perobject_jrpc_urls, module_primary_key, url_params, module, connection, top_level_schema_name='data') fmgr.validate_parameters(params_validation_blob) fmgr.process_curd(argument_specs=module_arg_spec) else: module.fail_json(msg='MUST RUN IN HTTPAPI MODE') module.exit_json(meta=module.params) if __name__ == '__main__': main()
32.743516
153
0.512498
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fmgr_firewall_ssh_localca short_description: SSH proxy local CA. description: - This module is able to configure a FortiManager device. - Examples include all parameters and values which need to be adjusted to data sources before usage. version_added: "2.10" author: - Link Zheng (@chillancezen) - Jie Xue (@JieX19) - Frank Shen (@fshen01) - Hongbin Lu (@fgtdev-hblu) notes: - Running in workspace locking mode is supported in this FortiManager module, the top level parameters workspace_locking_adom and workspace_locking_timeout help do the work. - To create or update an object, use state present directive. - To delete an object, use state absent directive. - Normally, running one module can fail when a non-zero rc is returned. you can also override the conditions to fail or succeed with parameters rc_failed and rc_succeeded options: enable_log: description: Enable/Disable logging for task required: false type: bool default: false proposed_method: description: The overridden method for the underlying Json RPC request required: false type: str choices: - update - set - add bypass_validation: description: only set to True when module schema diffs with FortiManager API structure, module continues to execute without validating parameters required: false type: bool default: false workspace_locking_adom: description: the adom to lock for FortiManager running in workspace mode, the value can be global and others including root required: false type: str workspace_locking_timeout: description: the maximum time in seconds to wait for other user to release the workspace lock required: false type: int default: 300 state: description: the directive to create, update or delete an object type: str required: true choices: - present - absent rc_succeeded: description: the rc codes list with which the conditions to succeed will be overriden type: list required: false rc_failed: description: the rc codes list with which the conditions to fail will be overriden type: list required: false adom: description: the parameter (adom) in requested url type: str required: true firewall_ssh_localca: description: the top level parameters set required: false type: dict suboptions: name: type: str description: 'SSH proxy local CA name.' password: description: 'Password for SSH private key.' type: str private-key: type: str description: 'SSH proxy private key, encrypted with a password.' public-key: type: str description: 'SSH proxy public key.' source: type: str description: 'SSH proxy local CA source type.' choices: - 'built-in' - 'user' ''' EXAMPLES = ''' - hosts: fortimanager-inventory collections: - fortinet.fortimanager connection: httpapi vars: ansible_httpapi_use_ssl: True ansible_httpapi_validate_certs: False ansible_httpapi_port: 443 tasks: - name: SSH proxy local CA. fmgr_firewall_ssh_localca: bypass_validation: False workspace_locking_adom: <value in [global, custom adom including root]> workspace_locking_timeout: 300 rc_succeeded: [0, -2, -3, ...] rc_failed: [-2, -3, ...] adom: <your own value> state: <value in [present, absent]> firewall_ssh_localca: name: <value of string> password: <value of string> private-key: <value of string> public-key: <value of string> source: <value in [built-in, user]> ''' RETURN = ''' request_url: description: The full url requested returned: always type: str sample: /sys/login/user response_code: description: The status of api request returned: always type: int sample: 0 response_message: description: The descriptive message of the api response type: str returned: always sample: OK. ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import NAPIManager from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import check_galaxy_version from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import check_parameter_bypass def main(): jrpc_urls = [ '/pm/config/global/obj/firewall/ssh/local-ca', '/pm/config/adom/{adom}/obj/firewall/ssh/local-ca' ] perobject_jrpc_urls = [ '/pm/config/global/obj/firewall/ssh/local-ca/{local-ca}', '/pm/config/adom/{adom}/obj/firewall/ssh/local-ca/{local-ca}' ] url_params = ['adom'] module_primary_key = 'name' module_arg_spec = { 'enable_log': { 'type': 'bool', 'required': False, 'default': False }, 'forticloud_access_token': { 'type': 'str', 'required': False, 'no_log': True }, 'proposed_method': { 'type': 'str', 'required': False, 'choices': [ 'set', 'update', 'add' ] }, 'bypass_validation': { 'type': 'bool', 'required': False, 'default': False }, 'workspace_locking_adom': { 'type': 'str', 'required': False }, 'workspace_locking_timeout': { 'type': 'int', 'required': False, 'default': 300 }, 'rc_succeeded': { 'required': False, 'type': 'list' }, 'rc_failed': { 'required': False, 'type': 'list' }, 'state': { 'type': 'str', 'required': True, 'choices': [ 'present', 'absent' ] }, 'adom': { 'required': True, 'type': 'str' }, 'firewall_ssh_localca': { 'required': False, 'type': 'dict', 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'options': { 'name': { 'required': True, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'password': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'private-key': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'public-key': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'source': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'built-in', 'user' ], 'type': 'str' } } } } params_validation_blob = [] check_galaxy_version(module_arg_spec) module = AnsibleModule(argument_spec=check_parameter_bypass(module_arg_spec, 'firewall_ssh_localca'), supports_check_mode=False) fmgr = None if module._socket_path: connection = Connection(module._socket_path) connection.set_option('enable_log', module.params['enable_log'] if 'enable_log' in module.params else False) connection.set_option('forticloud_access_token', module.params['forticloud_access_token'] if 'forticloud_access_token' in module.params else None) fmgr = NAPIManager(jrpc_urls, perobject_jrpc_urls, module_primary_key, url_params, module, connection, top_level_schema_name='data') fmgr.validate_parameters(params_validation_blob) fmgr.process_curd(argument_specs=module_arg_spec) else: module.fail_json(msg='MUST RUN IN HTTPAPI MODE') module.exit_json(meta=module.params) if __name__ == '__main__': main()
true
true
f73627be709cc2f9d7f3dc33e61adab4c0ac819f
1,456
py
Python
release.py
hui-z/ForgiveDB
be032eb325566be02081257ee42853754b14514b
[ "MIT" ]
71
2017-07-04T11:58:06.000Z
2021-11-08T12:07:49.000Z
release.py
hui-z/ForgiveDB
be032eb325566be02081257ee42853754b14514b
[ "MIT" ]
6
2017-07-30T09:13:20.000Z
2017-12-06T15:31:28.000Z
release.py
hui-z/ForgiveDB
be032eb325566be02081257ee42853754b14514b
[ "MIT" ]
16
2017-08-09T06:31:59.000Z
2021-12-01T13:09:52.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os import sys # codecov.io project token import pypandoc codecov_token = '' or os.environ.get('FORGIVE_DB_CODECOV_TOKEN') base_dir = os.path.dirname(os.path.abspath(__file__)) sub_commands = {} def run(*commands): os.system('cd {} && {}'.format(base_dir, ' && '.join(commands))) def cmd(name): def decorator(func): sub_commands[name] = func def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper return decorator def usage(): print('Usage: {} <sub_command> <args...>'.format(sys.argv[0])) print('Sub command: [{}]'.format(', '.join(sub_commands))) exit(1) @cmd('test') def test(): run('pytest --cov=./', 'codecov --token={}'.format(codecov_token)) @cmd('release') def release(*setup_commands): markdown_file = os.path.join(base_dir, 'README.md') rst_file = os.path.join(base_dir, 'README.rst') rst_content = pypandoc.convert(markdown_file, 'rst') with open(rst_file, 'wb') as f: f.write(rst_content.encode('utf-8')) run('python setup.py {}'.format(' '.join(setup_commands))) os.unlink(rst_file) if __name__ == '__main__': if len(sys.argv) < 2: usage() sub_command = sys.argv[1] if sub_command not in sub_commands: usage() func = sub_commands[sub_command] func(*sys.argv[2:])
22.75
70
0.635989
from __future__ import absolute_import, unicode_literals import os import sys import pypandoc codecov_token = '' or os.environ.get('FORGIVE_DB_CODECOV_TOKEN') base_dir = os.path.dirname(os.path.abspath(__file__)) sub_commands = {} def run(*commands): os.system('cd {} && {}'.format(base_dir, ' && '.join(commands))) def cmd(name): def decorator(func): sub_commands[name] = func def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper return decorator def usage(): print('Usage: {} <sub_command> <args...>'.format(sys.argv[0])) print('Sub command: [{}]'.format(', '.join(sub_commands))) exit(1) @cmd('test') def test(): run('pytest --cov=./', 'codecov --token={}'.format(codecov_token)) @cmd('release') def release(*setup_commands): markdown_file = os.path.join(base_dir, 'README.md') rst_file = os.path.join(base_dir, 'README.rst') rst_content = pypandoc.convert(markdown_file, 'rst') with open(rst_file, 'wb') as f: f.write(rst_content.encode('utf-8')) run('python setup.py {}'.format(' '.join(setup_commands))) os.unlink(rst_file) if __name__ == '__main__': if len(sys.argv) < 2: usage() sub_command = sys.argv[1] if sub_command not in sub_commands: usage() func = sub_commands[sub_command] func(*sys.argv[2:])
true
true