hexsha
stringlengths
40
40
size
int64
3
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
972
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
972
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
972
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
3
1.03M
avg_line_length
float64
1.13
941k
max_line_length
int64
2
941k
alphanum_fraction
float64
0
1
12300497e33483bef60d933636d4537fcf36255e
1,563
py
Python
autovideo/augmentation/weather/Clouds_primitive.py
wanghaisheng/autovideo
ca6c05e522f6ea8cb2043a60195769f3906a3a19
[ "MIT" ]
4
2021-11-01T15:33:03.000Z
2022-02-10T10:37:56.000Z
autovideo/augmentation/weather/Clouds_primitive.py
wanghaisheng/autovideo
ca6c05e522f6ea8cb2043a60195769f3906a3a19
[ "MIT" ]
2
2021-11-08T05:09:00.000Z
2022-03-08T20:42:02.000Z
autovideo/augmentation/weather/Clouds_primitive.py
wanghaisheng/autovideo
ca6c05e522f6ea8cb2043a60195769f3906a3a19
[ "MIT" ]
2
2022-02-28T10:03:14.000Z
2022-03-23T09:00:06.000Z
''' Copyright 2021 D3M Team Copyright (c) 2021 DATA Lab at Texas A&M University 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 d3m import container from d3m.metadata import hyperparams import imgaug.augmenters as iaa from autovideo.utils import construct_primitive_metadata from autovideo.base.augmentation_base import AugmentationPrimitiveBase __all__ = ('CloudsPrimitive',) Inputs = container.DataFrame class Hyperparams(hyperparams.Hyperparams): seed = hyperparams.Constant[int]( default=0, description='Minimum workers to extract frames simultaneously', semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'], ) class CloudsPrimitive(AugmentationPrimitiveBase[Inputs, Hyperparams]): """ A primitive which add clouds to images. """ metadata = construct_primitive_metadata("augmentation", "weather_Clouds") def _get_function(self): """ set up function and parameter of functions """ seed = self.hyperparams["seed"] return iaa.Clouds(seed=seed)
30.647059
91
0.75112
6326d2519638adf686959f60dd28c5f3d30fc969
3,781
py
Python
release/config_release.py
bergsieker/bazel-toolchains
82bbccf71f17fd6e9216c9469f9caa4c82cd35c1
[ "Apache-2.0" ]
null
null
null
release/config_release.py
bergsieker/bazel-toolchains
82bbccf71f17fd6e9216c9469f9caa4c82cd35c1
[ "Apache-2.0" ]
null
null
null
release/config_release.py
bergsieker/bazel-toolchains
82bbccf71f17fd6e9216c9469f9caa4c82cd35c1
[ "Apache-2.0" ]
null
null
null
# Copyright 2016 The Bazel 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. """Script to generate toolchain configs for all config types and containers.""" from __future__ import print_function import argparse import sys # Do not generate .pyc files. sys.dont_write_bytecode = True import bazelrc import cc.create_artifacts as cc_create import cc.execute_targets as cc_execute from config import ContainerConfigs import toolchain_flags from util import get_git_root CONFIG_TYPES = ["default", "msan"] # Define path constants. GIT_ROOT = get_git_root() def _get_container_configs_list(bazel_version): """Gets the list of container configs to generate. Args: bazel_version: string, the version of Bazel used to generate configs. Returns: A list of ContainerConfigs objects corresponding to the configs to generate. """ debian8_clang_configs = ContainerConfigs( distro="debian8", version="0.4.0", image="gcr.io/cloud-marketplace/google/clang-debian8", package="configs/debian8_clang", config_types=CONFIG_TYPES, platform_target="rbe_debian8", git_root=GIT_ROOT, bazel_version=bazel_version) ubuntu16_04_clang_configs = ContainerConfigs( distro="ubuntu16_04", version="1.1", image="gcr.io/cloud-marketplace/google/clang-ubuntu", package="configs/ubuntu16_04_clang", config_types=CONFIG_TYPES, platform_target="rbe_ubuntu1604", git_root=GIT_ROOT, bazel_version=bazel_version) return [debian8_clang_configs, ubuntu16_04_clang_configs] def _parse_arguments(): """Parses command line arguments for the script. Returns: args object containing the arguments """ parser = argparse.ArgumentParser() parser.add_argument( "-b", "--bazel_version", required=True, help="the version of Bazel used to generate toolchain configs") return parser.parse_args() def main(bazel_version): """Main function. Examples of usage: python release/config_release.py -b 0.15.0 Args: bazel_version: string, the version of Bazel used to generate the configs. """ # Get current supported list of container configs to generate. container_configs_list = _get_container_configs_list(bazel_version) # Only create the new target in the BUILD file if it does not exist. cc_create.create_targets(container_configs_list, bazel_version) # Execute the target and extract toolchain configs. cc_execute.execute_and_extract_configs(container_configs_list, bazel_version) # Generate METADATA file. cc_create.generate_metadata(container_configs_list) # Generate new cpp toolchain definition targets. cc_create.generate_toolchain_definition(container_configs_list, bazel_version) # Update aliases to latest toolchain configs. cc_create.update_latest_target_aliases(container_configs_list, bazel_version) # Update toolchain.bazelrc file. toolchain_flags.update_toolchain_bazelrc_file(container_configs_list, bazel_version) # Create sample .bazelrc file and update latest.bazelrc symlink. bazelrc.create_bazelrc_and_update_link(bazel_version) if __name__ == "__main__": args = _parse_arguments() main(args.bazel_version)
30.491935
80
0.755356
718ed7a607ce5d9102c133e3ab08626215da35a2
7,147
py
Python
sandbox/oauth2/db_utils.py
aimeeu/Udacity-FullStackWebDeveloper
96b953b3fe274434b87ad15e10661fc90aab4451
[ "Apache-2.0" ]
null
null
null
sandbox/oauth2/db_utils.py
aimeeu/Udacity-FullStackWebDeveloper
96b953b3fe274434b87ad15e10661fc90aab4451
[ "Apache-2.0" ]
null
null
null
sandbox/oauth2/db_utils.py
aimeeu/Udacity-FullStackWebDeveloper
96b953b3fe274434b87ad15e10661fc90aab4451
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # DEVELOPER: Aimee Ukasick # DATE CREATED: 31 Aug 2018 # PURPOSE: common functions for retrieving data from sqlalchemy import create_engine, sql from sqlalchemy.orm import sessionmaker from database_setup import Base, Restaurant, MenuItem, User def fetch_all_restaurants(): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # return all restaurant entries items = session.query(Restaurant).order_by(sql.asc(Restaurant.name)) return items except Exception as e: print(e) raise e finally: session.close() def fetch_first_restaurant(): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # return all restaurant entries restaurant = session.query(Restaurant).first() return restaurant except Exception as e: print(e) raise e finally: session.close() def fetch_restaurant_by_id(restaurant_id): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() item = session.query(Restaurant).filter_by(id=restaurant_id).one() return item except Exception as e: print(e) raise e finally: session.close() def add_restaurant(name): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() new_restaurant = Restaurant(name=name) session.add(new_restaurant) session.commit() except Exception as e: print(e) raise e finally: session.close() def update_restaurant(restaurant_id, name): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() restaurant = session.query(Restaurant).filter_by( id=restaurant_id).one() restaurant.name = name session.add(restaurant) session.commit() except Exception as e: print(e) raise e finally: session.close() def delete_restaurant(restaurant_id): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() restaurant = session.query(Restaurant).filter_by( id=restaurant_id).one() name = restaurant.name session.delete(restaurant) session.commit() return name except Exception as e: print(e) raise e finally: session.close() def fetch_menu_items(restaurant): try: items = fetch_menu_items_by_id(restaurant.id) return items except Exception as e: print(e) raise e def fetch_menu_items_by_id(restaurant_id): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() items = session.query(MenuItem).filter_by( restaurant_id=restaurant_id).order_by(MenuItem.name) return items except Exception as e: print(e) raise e finally: session.close() def fetch_menu_item(menu_id): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() item = session.query(MenuItem).filter_by(id=menu_id).one() return item except Exception as e: print(e) raise e finally: session.close() def add_menu_item(menu_item): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() session.add(menu_item) session.commit() except Exception as e: print(e) raise e finally: session.close() def update_menu_item(edit_item, menu_id): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() item = session.query(MenuItem).filter_by(id=menu_id).one() item.name = edit_item.name item.description = edit_item.description item.price = edit_item.price session.add(item) session.commit() except Exception as e: print(e) raise e finally: session.close() def delete_menu_item(menu_id): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() item = session.query(MenuItem).filter_by(id=menu_id).one() session.delete(item) session.commit() except Exception as e: print(e) raise e finally: session.close() # User Helper Functions def create_user(login_session): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() new_user = User(name=login_session['username'], email=login_session[ 'email'], picture=login_session['picture']) session.add(new_user) session.commit() user = session.query(User).filter_by( email=login_session['email']).one() return user.id except Exception as e: print(e) raise e finally: session.close() def get_user_info(user_id): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() user = session.query(User).filter_by(id=user_id).one() return user except Exception as e: print(e) raise e finally: session.close() def get_user_id(email): session = None try: engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() user = session.query(User).filter_by(email=email).one() return user.id except Exception as e: print(e) raise e finally: session.close()
26.76779
76
0.616482
3d48495426329622847589dfeaa048692aff5636
5,493
py
Python
tests/pa/test_deprovision.py
deathly809/WALinuxAgent
c8f63b26c8412b25cb01b06a6ac68f4ce9575b84
[ "Apache-2.0" ]
null
null
null
tests/pa/test_deprovision.py
deathly809/WALinuxAgent
c8f63b26c8412b25cb01b06a6ac68f4ce9575b84
[ "Apache-2.0" ]
null
null
null
tests/pa/test_deprovision.py
deathly809/WALinuxAgent
c8f63b26c8412b25cb01b06a6ac68f4ce9575b84
[ "Apache-2.0" ]
1
2020-08-18T20:15:17.000Z
2020-08-18T20:15:17.000Z
# Copyright 2016 Microsoft Corporation # # 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. # # Requires Python 2.6+ and Openssl 1.0+ # import os import tempfile import unittest import azurelinuxagent.common.utils.fileutil as fileutil from azurelinuxagent.pa.deprovision import get_deprovision_handler from azurelinuxagent.pa.deprovision.default import DeprovisionHandler from tests.tools import AgentTestCase, distros, Mock, patch class TestDeprovision(AgentTestCase): @patch('signal.signal') @patch('azurelinuxagent.common.osutil.get_osutil') @patch('azurelinuxagent.common.protocol.util.get_protocol_util') @patch('azurelinuxagent.pa.deprovision.default.read_input') def test_confirmation(self, mock_read, mock_protocol, mock_util, mock_signal): dh = DeprovisionHandler() dh.setup = Mock() dh.setup.return_value = ([], []) dh.do_actions = Mock() # Do actions if confirmed mock_read.return_value = "y" dh.run() self.assertEqual(1, dh.do_actions.call_count) # Skip actions if not confirmed mock_read.return_value = "n" dh.run() self.assertEqual(1, dh.do_actions.call_count) # Do actions if forced mock_read.return_value = "n" dh.run(force=True) self.assertEqual(2, dh.do_actions.call_count) @distros("ubuntu") @patch('azurelinuxagent.common.conf.get_lib_dir') def test_del_lib_dir_files(self, distro_name, distro_version, distro_full_name, mock_conf): dirs = [ 'WALinuxAgent-2.2.26/config', 'Microsoft.Azure.Extensions.CustomScript-2.0.6/config', 'Microsoft.Azure.Extensions.CustomScript-2.0.6/status' ] files = [ 'HostingEnvironmentConfig.xml', 'Incarnation', 'Protocol', 'SharedConfig.xml', 'WireServerEndpoint', 'Extensions.1.xml', 'ExtensionsConfig.1.xml', 'GoalState.1.xml', 'Extensions.2.xml', 'ExtensionsConfig.2.xml', 'GoalState.2.xml', 'Microsoft.Azure.Extensions.CustomScript-2.0.6/config/42.settings', 'Microsoft.Azure.Extensions.CustomScript-2.0.6/config/HandlerStatus', 'Microsoft.Azure.Extensions.CustomScript-2.0.6/config/HandlerState', 'Microsoft.Azure.Extensions.CustomScript-2.0.6/status/12.notstatus', 'Microsoft.Azure.Extensions.CustomScript-2.0.6/mrseq', 'WALinuxAgent-2.2.26/config/0.settings' ] tmp = tempfile.mkdtemp() mock_conf.return_value = tmp for d in dirs: fileutil.mkdir(os.path.join(tmp, d)) for f in files: fileutil.write_file(os.path.join(tmp, f), "Value") deprovision_handler = get_deprovision_handler(distro_name, distro_version, distro_full_name) warnings = [] actions = [] deprovision_handler.del_lib_dir_files(warnings, actions) deprovision_handler.del_ext_handler_files(warnings, actions) self.assertTrue(len(warnings) == 0) self.assertTrue(len(actions) == 2) self.assertEqual(fileutil.rm_files, actions[0].func) self.assertEqual(fileutil.rm_files, actions[1].func) self.assertEqual(11, len(actions[0].args)) self.assertEqual(3, len(actions[1].args)) for f in actions[0].args: self.assertTrue(os.path.basename(f) in files) for f in actions[1].args: self.assertTrue(f[len(tmp)+1:] in files) @distros("redhat") def test_deprovision(self, distro_name, distro_version, distro_full_name): deprovision_handler = get_deprovision_handler(distro_name, distro_version, distro_full_name) warnings, actions = deprovision_handler.setup(deluser=False) assert any("/etc/resolv.conf" in w for w in warnings) @distros("ubuntu") def test_deprovision_ubuntu(self, distro_name, distro_version, distro_full_name): deprovision_handler = get_deprovision_handler(distro_name, distro_version, distro_full_name) with patch("os.path.realpath", return_value="/run/resolvconf/resolv.conf"): warnings, actions = deprovision_handler.setup(deluser=False) assert any("/etc/resolvconf/resolv.conf.d/tail" in w for w in warnings) if __name__ == '__main__': unittest.main()
38.683099
83
0.600947
f53de6301a35e7f76c892c0a06f12dba30f713ce
373
py
Python
httpserver/controllersX/basic.py
evinlort/http-server
7db0637da7afbdb3736e595c431477c5242320a9
[ "MIT" ]
null
null
null
httpserver/controllersX/basic.py
evinlort/http-server
7db0637da7afbdb3736e595c431477c5242320a9
[ "MIT" ]
null
null
null
httpserver/controllersX/basic.py
evinlort/http-server
7db0637da7afbdb3736e595c431477c5242320a9
[ "MIT" ]
null
null
null
def test(query): return "Text by ROUTER" def new(query): if isinstance(query, dict): if "test" in query: return query["test"].upper() if isinstance(query, bytes): with open("evgeny.pdf", "wb") as fd: fd.write(query) return "Saved" import time return f"Time is: {time.time()} and query was {query}"
23.3125
58
0.563003
797a293c46b4808faf1494f055b9684039fddb1b
11,972
py
Python
tests/grouping/test_grouping_utils.py
Slimane33/pennylane
fe5d1dffa152fd34e4f9224df02eecb219affa06
[ "Apache-2.0" ]
null
null
null
tests/grouping/test_grouping_utils.py
Slimane33/pennylane
fe5d1dffa152fd34e4f9224df02eecb219affa06
[ "Apache-2.0" ]
1
2021-05-27T05:36:41.000Z
2021-05-27T05:36:41.000Z
tests/grouping/test_grouping_utils.py
Slimane33/pennylane
fe5d1dffa152fd34e4f9224df02eecb219affa06
[ "Apache-2.0" ]
null
null
null
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # 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. """ Unit tests for the :mod:`grouping` utility functions in ``grouping/utils.py``. """ import pytest import numpy as np from pennylane import Identity, PauliX, PauliY, PauliZ, Hadamard, Hermitian, U3 from pennylane.operation import Tensor from pennylane.wires import Wires from pennylane.grouping.utils import ( is_pauli_word, are_identical_pauli_words, pauli_to_binary, binary_to_pauli, is_qwc, observables_to_binary_matrix, qwc_complement_adj_matrix, ) non_pauli_words = [ PauliX(0) @ Hadamard(1) @ Identity(2), Hadamard("a"), U3(0.1, 1, 1, wires="a"), Hermitian(np.array([[3.2, 1.1 + 0.6j], [1.1 - 0.6j, 3.2]]), wires="a") @ PauliX("b"), ] class TestGroupingUtils: """Basic usage and edge-case tests for the measurement optimization utility functions.""" ops_to_vecs_explicit_wires = [ (PauliX(0) @ PauliY(1) @ PauliZ(2), np.array([1, 1, 0, 0, 1, 1])), (PauliZ(0) @ PauliY(2), np.array([0, 1, 1, 1])), (PauliY(1) @ PauliX(2), np.array([1, 1, 1, 0])), (Identity(0), np.zeros(2)), ] @pytest.mark.parametrize("op,vec", ops_to_vecs_explicit_wires) def test_pauli_to_binary_no_wire_map(self, op, vec): """Test conversion of Pauli word from operator to binary vector representation when no ``wire_map`` is specified.""" assert (pauli_to_binary(op) == vec).all() ops_to_vecs_abstract_wires = [ (PauliX("a") @ PauliZ("b") @ Identity("c"), np.array([1, 0, 0, 0, 0, 1, 0, 0])), (PauliY(6) @ PauliZ("a") @ PauliZ("b"), np.array([0, 0, 0, 1, 1, 1, 0, 1])), (PauliX("b") @ PauliY("c"), np.array([0, 1, 1, 0, 0, 0, 1, 0])), (Identity("a") @ Identity(6), np.zeros(8)), ] @pytest.mark.parametrize("op,vec", ops_to_vecs_abstract_wires) def test_pauli_to_binary_with_wire_map(self, op, vec): """Test conversion of Pauli word from operator to binary vector representation if a ``wire_map`` is specified.""" wire_map = {"a": 0, "b": 1, "c": 2, 6: 3} assert (pauli_to_binary(op, wire_map=wire_map) == vec).all() vecs_to_ops_explicit_wires = [ (np.array([1, 0, 1, 0, 0, 1]), PauliX(0) @ PauliY(2)), (np.array([1, 1, 1, 1, 1, 1]), PauliY(0) @ PauliY(1) @ PauliY(2)), (np.array([1, 0, 1, 0, 1, 1]), PauliX(0) @ PauliZ(1) @ PauliY(2)), (np.zeros(6), Identity(0)), ] @pytest.mark.parametrize("non_pauli_word", non_pauli_words) def test_pauli_to_binary_non_pauli_word_catch(self, non_pauli_word): """Tests TypeError raise for when non Pauli-word Pennylane operations/operators are given as input to pauli_to_binary.""" assert pytest.raises(TypeError, pauli_to_binary, non_pauli_word) def test_pauli_to_binary_incompatable_wire_map_n_qubits(self): """Tests ValueError raise when n_qubits is not high enough to support the highest wire_map value.""" pauli_word = PauliX("a") @ PauliY("b") @ PauliZ("c") wire_map = {"a": 0, "b": 1, "c": 3} n_qubits = 3 assert pytest.raises(ValueError, pauli_to_binary, pauli_word, n_qubits, wire_map) @pytest.mark.parametrize("vec,op", vecs_to_ops_explicit_wires) def test_binary_to_pauli_no_wire_map(self, vec, op): """Test conversion of Pauli in binary vector representation to operator form when no ``wire_map`` is specified.""" assert are_identical_pauli_words(binary_to_pauli(vec), op) vecs_to_ops_abstract_wires = [ (np.array([1, 0, 1, 0, 0, 1]), PauliX("alice") @ PauliY("ancilla")), (np.array([1, 1, 1, 1, 1, 1]), PauliY("alice") @ PauliY("bob") @ PauliY("ancilla")), (np.array([1, 0, 1, 0, 1, 0]), PauliX("alice") @ PauliZ("bob") @ PauliX("ancilla")), (np.zeros(6), Identity("alice")), ] @pytest.mark.parametrize("vec,op", vecs_to_ops_abstract_wires) def test_binary_to_pauli_with_wire_map(self, vec, op): """Test conversion of Pauli in binary vector representation to operator form when ``wire_map`` is specified.""" wire_map = {"alice": 0, "bob": 1, "ancilla": 2} assert are_identical_pauli_words(binary_to_pauli(vec, wire_map=wire_map), op) binary_vecs_with_invalid_wire_maps = [ ([1, 0], {"a": 1}), ([1, 1, 1, 0], {"a": 0}), ([1, 0, 1, 0, 1, 1], {"a": 0, "b": 2, "c": 3}), ([1, 0, 1, 0], {"a": 0, "b": 2}), ] @pytest.mark.parametrize("binary_vec,wire_map", binary_vecs_with_invalid_wire_maps) def test_binary_to_pauli_invalid_wire_map(self, binary_vec, wire_map): """Tests ValueError raise when wire_map values are not integers 0 to N, for input 2N dimensional binary vector.""" assert pytest.raises(ValueError, binary_to_pauli, binary_vec, wire_map) not_binary_symplectic_vecs = [[1, 0, 1, 1, 0], [1], [2, 0, 0, 1], [0.1, 4.3, 2.0, 1.3]] @pytest.mark.parametrize("not_binary_symplectic", not_binary_symplectic_vecs) def test_binary_to_pauli_with_illegal_vectors(self, not_binary_symplectic): """Test ValueError raise for when non even-dimensional binary vectors are given to binary_to_pauli.""" assert pytest.raises(ValueError, binary_to_pauli, not_binary_symplectic) def test_observables_to_binary_matrix(self): """Test conversion of list of Pauli word operators to representation as a binary matrix.""" observables = [Identity(1), PauliX(1), PauliZ(0) @ PauliZ(1)] binary_observables = np.array( [[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]] ).T assert (observables_to_binary_matrix(observables) == binary_observables).all() def test_observables_to_binary_matrix_n_qubits_arg(self): """Tests if ValueError is raised when specified n_qubits is not large enough to support the number of distinct wire labels in input observables.""" observables = [Identity(1) @ PauliZ("a"), PauliX(1), PauliZ(0) @ PauliZ(2)] n_qubits_invalid = 3 assert pytest.raises( ValueError, observables_to_binary_matrix, observables, n_qubits_invalid ) def test_is_qwc(self): """Determining if two Pauli words are qubit-wise commuting.""" n_qubits = 3 wire_map = {0: 0, "a": 1, "b": 2} p1_vec = pauli_to_binary(PauliX(0) @ PauliY("a"), wire_map=wire_map) p2_vec = pauli_to_binary(PauliX(0) @ Identity("a") @ PauliX("b"), wire_map=wire_map) p3_vec = pauli_to_binary(PauliX(0) @ PauliZ("a") @ Identity("b"), wire_map=wire_map) identity = pauli_to_binary(Identity("a") @ Identity(0), wire_map=wire_map) assert is_qwc(p1_vec, p2_vec) assert not is_qwc(p1_vec, p3_vec) assert is_qwc(p2_vec, p3_vec) assert ( is_qwc(p1_vec, identity) == is_qwc(p2_vec, identity) == is_qwc(p3_vec, identity) == is_qwc(identity, identity) == True ) def test_is_qwc_not_equal_lengths(self): """Tests ValueError is raised when input Pauli vectors are not of equal length.""" pauli_vec_1 = [0, 1, 0, 1] pauli_vec_2 = [1, 1, 0, 1, 0, 1] assert pytest.raises(ValueError, is_qwc, pauli_vec_1, pauli_vec_2) def test_is_qwc_not_even_lengths(self): """Tests ValueError is raised when input Pauli vectors are not of even length.""" pauli_vec_1 = [1, 0, 1] pauli_vec_2 = [1, 1, 1] assert pytest.raises(ValueError, is_qwc, pauli_vec_1, pauli_vec_2) def test_is_qwc_not_binary_vectors(self): """Tests ValueError is raised when input Pauli vectors do not have binary components.""" pauli_vec_1 = [1, 3.2, 1, 1 + 2j] pauli_vec_2 = [1, 0, 0, 0] assert pytest.raises(ValueError, is_qwc, pauli_vec_1, pauli_vec_2) def test_is_pauli_word(self): """Test for determining whether input ``Observable`` instance is a Pauli word.""" observable_1 = PauliX(0) observable_2 = PauliZ(1) @ PauliX(2) @ PauliZ(4) observable_3 = PauliX(1) @ Hadamard(4) observable_4 = Hadamard(0) assert is_pauli_word(observable_1) assert is_pauli_word(observable_2) assert not is_pauli_word(observable_3) assert not is_pauli_word(observable_4) def test_are_identical_pauli_words(self): """Tests for determining if two Pauli words have the same ``wires`` and ``name`` attributes.""" pauli_word_1 = Tensor(PauliX(0)) pauli_word_2 = PauliX(0) assert are_identical_pauli_words(pauli_word_1, pauli_word_2) assert are_identical_pauli_words(pauli_word_2, pauli_word_1) pauli_word_1 = PauliX(0) @ PauliY(1) pauli_word_2 = PauliY(1) @ PauliX(0) pauli_word_3 = Tensor(PauliX(0), PauliY(1)) pauli_word_4 = PauliX(1) @ PauliZ(2) assert are_identical_pauli_words(pauli_word_1, pauli_word_2) assert are_identical_pauli_words(pauli_word_1, pauli_word_3) assert not are_identical_pauli_words(pauli_word_1, pauli_word_4) assert not are_identical_pauli_words(pauli_word_3, pauli_word_4) @pytest.mark.parametrize("non_pauli_word", non_pauli_words) def test_are_identical_pauli_words_non_pauli_word_catch(self, non_pauli_word): """Tests TypeError raise for when non-Pauli word Pennylane operators/operations are given as input to are_identical_pauli_words.""" with pytest.raises(TypeError): are_identical_pauli_words(non_pauli_word, PauliZ(0) @ PauliZ(1)) with pytest.raises(TypeError): are_identical_pauli_words(non_pauli_word, PauliZ(0) @ PauliZ(1)) with pytest.raises(TypeError): are_identical_pauli_words(PauliX("a") @ Identity("b"), non_pauli_word) with pytest.raises(TypeError): are_identical_pauli_words(non_pauli_word, non_pauli_word) def test_qwc_complement_adj_matrix(self): """Tests that the ``qwc_complement_adj_matrix`` function returns the correct adjacency matrix.""" binary_observables = np.array( [ [1.0, 0.0, 1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 1.0, 1.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0, 0.0, 0.0], ] ) adj = qwc_complement_adj_matrix(binary_observables) expected = np.array([[0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) assert np.all(adj == expected) binary_obs_list = list(binary_observables) adj = qwc_complement_adj_matrix(binary_obs_list) assert np.all(adj == expected) binary_obs_tuple = tuple(binary_observables) adj = qwc_complement_adj_matrix(binary_obs_tuple) assert np.all(adj == expected) def test_qwc_complement_adj_matrix_exception(self): """Tests that the ``qwc_complement_adj_matrix`` function raises an exception if the matrix is not binary.""" not_binary_observables = np.array( [ [1.1, 0.5, 1.0, 0.0, 0.0, 1.0], [0.0, 1.3, 1.0, 1.0, 0.0, 1.0], [2.2, 0.0, 0.0, 1.0, 0.0, 0.0], ] ) with pytest.raises(ValueError, match="Expected a binary array, instead got"): qwc_complement_adj_matrix(not_binary_observables)
40.309764
103
0.641079
1aa5c41e095ab05b3f4677f54817bfd2da4f9ff8
16,182
py
Python
src/client/project/template_builder/view.py
Losik/toloka-kit
1e707b17bcaa8a570f0479445906d9afbdf737ae
[ "Apache-2.0" ]
null
null
null
src/client/project/template_builder/view.py
Losik/toloka-kit
1e707b17bcaa8a570f0479445906d9afbdf737ae
[ "Apache-2.0" ]
1
2021-07-02T13:56:34.000Z
2021-07-02T14:32:10.000Z
src/client/project/template_builder/view.py
Losik/toloka-kit
1e707b17bcaa8a570f0479445906d9afbdf737ae
[ "Apache-2.0" ]
1
2021-06-09T09:32:33.000Z
2021-06-09T09:32:33.000Z
__all__ = [ 'BaseViewV1', 'ActionButtonViewV1', 'AlertViewV1', 'AudioViewV1', 'CollapseViewV1', 'DeviceFrameViewV1', 'DividerViewV1', 'GroupViewV1', 'IframeViewV1', 'ImageViewV1', 'LabeledListViewV1', 'LinkViewV1', 'LinkGroupViewV1', 'ListViewV1', 'MarkdownViewV1', 'TextViewV1', 'VideoViewV1' ] from enum import Enum, unique from typing import List, Any from ...primitives.base import attribute from .base import BaseTemplate, BaseComponent, ListDirection, ListSize, ComponentType, VersionedBaseComponent, base_component_or class BaseViewV1(VersionedBaseComponent): """Elements displayed in the interface, such as text, list, audio player, or image. """ hint: base_component_or(Any) label: base_component_or(Any) validation: BaseComponent class ActionButtonViewV1(BaseViewV1, spec_value=ComponentType.VIEW_ACTION_BUTTON): """Button that calls an action. When clicking the button, an action specified in the action property is called. Attributes: label: Button text. action: Action called when clicking the button. hint: Hint text. validation: Validation based on condition. """ action: BaseComponent class AlertViewV1(BaseViewV1, spec_value=ComponentType.VIEW_ALERT): """The component creates a color block to highlight important information. You can use both plain text and other visual components inside it. Attributes: label: Label above the component. content: Content of the block with important information. hint: Hint text. theme: Determines the block color. validation: Validation based on condition. """ @unique class Theme(Enum): """An enumeration Attributes: INFO: (default) Blue. SUCCESS: Green. WARNING: Yellow. DANGER: Red. """ DANGER = 'danger' INFO = 'info' SUCCESS = 'success' WARNING = 'warning' content: BaseComponent theme: base_component_or(Theme) class AudioViewV1(BaseViewV1, spec_value=ComponentType.VIEW_AUDIO): """The component plays audio. Format support depends on the user's browser, OS, and device. We recommend using MP3. Attributes: label: Label above the component. hint: Hint text. loop: Automatically replay audio. url: Audio link. validation: Validation based on condition. """ url: base_component_or(Any) loop: base_component_or(bool) class CollapseViewV1(BaseViewV1, spec_value=ComponentType.VIEW_COLLAPSE): """Expandable block. Lets you add hidden content that doesn't need to be shown initially or that takes up a large space. The block heading is always visible. If you set the defaultOpened property to true, the block is expanded immediately, but it can be collapsed. Attributes: label: Block heading. content: Content hidden in the block. default_opened: If true, the block is immediately displayed in expanded form. By default, false (the block is collapsed). hint: Hint text. validation: Validation based on condition. """ content: BaseComponent default_opened: base_component_or(bool) = attribute(origin='defaultOpened') class DeviceFrameViewV1(BaseViewV1, spec_value=ComponentType.VIEW_DEVICE_FRAME): """Wraps the content of a component in a frame that is similar to a mobile phone. You can place other components inside the frame. Attributes: label: Label above the component. content: Content inside the frame. full_height: If true, the element takes up all the vertical free space. The element is set to a minimum height of 400 pixels. hint: Hint text. max_width: Maximum width of the element in pixels, must be greater than min_width. min_width: Minimum width of the element in pixels. Takes priority over max_width. ratio: An array of two numbers that sets the relative dimensions of the sides: width (first number) to height (second number). Not valid if full_height=true. validation: Validation based on condition. """ content: BaseComponent full_height: base_component_or(bool) = attribute(origin='fullHeight') max_width: base_component_or(float) = attribute(origin='maxWidth') min_width: base_component_or(float) = attribute(origin='minWidth') ratio: base_component_or(List[base_component_or(float)], 'ListBaseComponentOrFloat') class DividerViewV1(BaseViewV1, spec_value=ComponentType.VIEW_DIVIDER): """Horizontal delimiter. You can place extra elements in the center of the delimiter, like a popup hint and label. Attributes: label: A label in the center of the delimiter. Line breaks are not supported. hint: Hint text. validation: Validation based on condition. """ pass class GroupViewV1(BaseViewV1, spec_value=ComponentType.VIEW_GROUP): """Groups components visually into framed blocks. Attributes: label: Group heading. content: Content of a group block. hint: Explanation of the group heading. To insert a new line, use . validation: Validation based on condition. """ content: BaseComponent class IframeViewV1(BaseViewV1, spec_value=ComponentType.VIEW_IFRAME): """Displays the web page at the URL in an iframe window. Attributes: label: Label above the component. full_height: If true, the element takes up all the vertical free space. The element is set to a minimum height of 400 pixels. hint: Hint text. max_width: Maximum width of the element in pixels, must be greater than min_width. min_width: Minimum width of the element in pixels. Takes priority over max_width. ratio: An array of two numbers that sets the relative dimensions of the sides: width (first number) to height (second number). Not valid if full_height=true. validation: Validation based on condition. """ url: base_component_or(str) full_height: base_component_or(bool) = attribute(origin='fullHeight') max_width: base_component_or(float) = attribute(origin='maxWidth') min_width: base_component_or(float) = attribute(origin='minWidth') ratio: base_component_or(List[base_component_or(float)], 'ListBaseComponentOrFloat') class ImageViewV1(BaseViewV1, spec_value=ComponentType.VIEW_IMAGE): """Displays an image. Attributes: label: Label above the component. full_height: If true, the element takes up all the vertical free space. The element is set to a minimum height of 400 pixels. hint: Hint text. max_width: Maximum width of the element in pixels, must be greater than min_width. min_width: Minimum width of the element in pixels. Takes priority over max_width. no_border: Controls the display of a frame around an image. By default, true (the frame is hidden). Set false to display the frame. no_lazy_load: Disables lazy loading. If true, images start loading immediately, even if they aren't in the viewport. Useful for icons. By default, false (lazy loading is enabled). In this mode, images start loading only when they get in the user's field of view. popup: Specifies whether opening a full-size image with a click is allowed. By default, it is true (allowed). ratio: An array of two numbers that sets the relative dimensions of the sides: width (first number) to height (second number). Not valid if full_height=true. scrollable: When set to true, an image has scroll bars if it doesn't fit in the parent element. If false, the image fits in the parent element and, when clicked, opens in its original size in the module window. Images in SVG format with no size specified always fit in their parent elements. url: Image link. validation: Validation based on condition. """ url: base_component_or(Any) full_height: base_component_or(bool) = attribute(origin='fullHeight') max_width: base_component_or(float) = attribute(origin='maxWidth') min_width: base_component_or(float) = attribute(origin='minWidth') no_border: base_component_or(bool) = attribute(origin='noBorder') no_lazy_load: base_component_or(bool) = attribute(origin='noLazyLoad') popup: base_component_or(bool) ratio: base_component_or(List[base_component_or(float)], 'ListBaseComponentOrFloat') rotatable: base_component_or(bool) scrollable: base_component_or(bool) class LabeledListViewV1(BaseViewV1, spec_value=ComponentType.VIEW_LABELED_LIST): """Displaying components as a list with labels placed on the left. If you don't need labels, use view.list. Attributes: label: Label above the component. hint: Hint text. items: List items. min_width: The minimum width of list content. If the component width is less than the specified value, it switches to compact mode. validation: Validation based on condition. """ class Item(BaseTemplate): """Item. Attributes: center_label: If true, a label is center-aligned relative to the content of a list item (content). Use it if the list consists of large items, such as images or multi-line text. By default, false (the label is aligned to the top of the content block). content: List item content. hint: A pop-up hint displayed next to a label. label: A label displayed next to a list item. """ content: BaseComponent label: base_component_or(Any) center_label: base_component_or(bool) = attribute(origin='centerLabel') hint: base_component_or(Any) items: base_component_or(List[base_component_or(Item)], 'ListBaseComponentOrItem') min_width: base_component_or(float) = attribute(origin='minWidth') class LinkViewV1(BaseViewV1, spec_value=ComponentType.VIEW_LINK): """Universal way to add a link. This link changes color when clicked. We recommend using this component if you need to insert a link without additional formatting. If you want to insert a button that will open the link, use the view.action-button and action.open-link components. To insert a link with a search query, use helper.search-query. Attributes: label: Label above the component. content: Link text displayed to the user. hint: Hint text. url: Link URL. validation: Validation based on condition. """ url: base_component_or(Any) content: base_component_or(Any) class LinkGroupViewV1(BaseViewV1, spec_value=ComponentType.VIEW_LINK_GROUP): """Puts links into groups The most important link in a group can be highlighted with a border: set the theme property to primary for this link. This only groups links, unlike GroupViewV1. Attributes: label: Label above the component. hint: Hint text. links: Array of links that make up a group. validation: Validation based on condition. Example: How to add several links. >>> links = tb.view.LinkGroupViewV1( >>> links=[ >>> tb.view.LinkGroupViewV1.Link( >>> url='https://any.com/useful/url/1', >>> content='Example1', >>> ), >>> tb.view.LinkGroupViewV1.Link( >>> url='https://any.com/useful/url/2', >>> content='Example2', >>> ), >>> ] >>> ) ... """ class Link(BaseTemplate): """Link parameters Attributes: content: Link text that's displayed to the user. Unviewed links are blue and underlined, and clicked links are purple. theme: Defines the appearance of the link. If you specify "theme": "primary", it's a button, otherwise it's a text link. url: Link address """ content: base_component_or(str) theme: base_component_or(str) url: base_component_or(str) links: base_component_or(List[base_component_or(Link)], 'ListBaseComponentOrLink') class ListViewV1(BaseViewV1, spec_value=ComponentType.VIEW_LIST): """Block for displaying data in a list. Attributes: label: Label above the component. direction: Determines the direction of the list. hint: Hint text. items: Array of list items. size: Specifies the size of the margins between elements. Acceptable values in ascending order: s, m (default value). validation: Validation based on condition. """ items: base_component_or(List[BaseComponent], 'ListBaseComponent') direction: base_component_or(ListDirection) size: base_component_or(ListSize) class MarkdownViewV1(BaseViewV1, spec_value=ComponentType.VIEW_MARKDOWN): """Block for displaying text in Markdown. The contents of the block are written to the content property in a single line. To insert line breaks, use \\n Straight quotation marks (") must be escaped like this: \\". Note that the view.markdown component is resource-intensive and might overload weak user devices. Do not use this component to display plain text. If you need to display text without formatting, use the view.text component. If you need to insert a link, use view.link, and for an image use view.image. Links with Markdown are appended with target="_blank" (the link opens in a new tab), as well as rel="noopener noreferrer" Attributes: label: Label above the component. content: Text in Markdown. hint: Hint text. validation: Validation based on condition. Example: How to add a title and description on the task interface. >>> header = tb.view.MarkdownViewV1(content='# Some Header:\n---\nSome detailed description') ... """ content: base_component_or(Any) class TextViewV1(BaseViewV1, spec_value=ComponentType.VIEW_TEXT): """Block for displaying text. If you need formatted text, use view.markdown. Attributes: label: Label above the component. content: The text displayed in the block. To insert a new line, use \n hint: Hint text. validation: Validation based on condition. Example: How to show labeled field from the task inputs. >>> text_view = tb.view.TextViewV1(label='My label:', content=tb.data.InputData(path='imput_field_name')) ... """ content: base_component_or(Any) class VideoViewV1(BaseViewV1, spec_value=ComponentType.VIEW_VIDEO): """Player for video playback. The player is a rectangular block with a frame and buttons to control the video. You can set the block size using the ratio, fullHeight, minWidth, and maxWidth properties. The video resolution does not affect the size of the block — the video will fit into the block and will not be cropped. Attributes: label: Label above the component. full_height: If true, the element takes up all the vertical free space. The element is set to a minimum height of 400 pixels. hint: Hint text. max_width: Maximum width of the element in pixels, must be greater than min_width. min_width: Minimum width of the element in pixels. Takes priority over max_width. ratio: The aspect ratio of the video block. An array of two numbers: the first sets the width of the block and the second sets the height. url: Link to the video file. validation: Validation based on condition. """ full_height: base_component_or(bool) = attribute(origin='fullHeight') max_width: base_component_or(float) = attribute(origin='maxWidth') min_width: base_component_or(float) = attribute(origin='minWidth')
38.165094
132
0.684402
85d42130da3a1d3393f5f99c7c46a81a5e4c25a3
4,104
py
Python
ui/page_elements/election_addpeople/__init__.py
ArcherLuo233/election-s-prediction
9da72cb855f6d61f9cdec6e15f7ca832629ba51a
[ "MIT" ]
null
null
null
ui/page_elements/election_addpeople/__init__.py
ArcherLuo233/election-s-prediction
9da72cb855f6d61f9cdec6e15f7ca832629ba51a
[ "MIT" ]
1
2022-01-26T01:23:26.000Z
2022-01-26T01:23:34.000Z
ui/page_elements/election_addpeople/__init__.py
ArcherLuo233/election-s-prediction
9da72cb855f6d61f9cdec6e15f7ca832629ba51a
[ "MIT" ]
1
2021-11-08T10:58:23.000Z
2021-11-08T10:58:23.000Z
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QMessageBox from model.area import Area from model.user import User from ui.page_elements.modal_dialog import ModalDialog from .AddpeopleUI import Ui_Dialog class PeopleAdd(ModalDialog): def __init__(self, parent): self.alltitle = ["炎峰里", "中正里", "玉峰里", "明正里", "和平里", "中山里", "敦和里", "山脚里", "新厝里", "上林里", "碧峰里", "碧洲里", "复兴里", "北投里", "石川里", "加老里", "新庄里", "新丰里", "御史里", "北势里", "中原里", "富寮里", "南埔里", "坪顶里", "土城里", "平林里", "双冬里"] self.title = '炎峰里' super().__init__(parent, size=(500, 400)) self.setFixedSize(500, 400) self.setWindowFlags(Qt.FramelessWindowHint) self.ui = Ui_Dialog() self.ui.setupUi(self) self.allvotenumber = 0 # btn_ self.ui.btn_close.clicked.connect(self.close) self.ui.btn_addpeople.clicked.connect(self.addallpeople) self.ui.ComboBox.currentIndexChanged.connect(self.changeanother) # widget-init self.message = QMessageBox() self.message.setStandardButtons(QMessageBox.Yes) self.message.button(QMessageBox.Yes).setText('确认') # init try: data = Area.search(name=self.title)['data'][0].extra except Exception: data = [] QMessageBox.warning(None, "添加候选人失败", "请先添加年份!") self.close() yearlist = [] for i in data: yearlist.append(str(i["year"])) self.ui.ComboBox.addItems(yearlist) def changeanother(self): try: data = Area.search(name=self.title)['data'][0].extra except Exception: return data.sort(key=lambda x: x["year"]) year = self.ui.ComboBox.currentText() prolist = [] for i in data: if str(i["year"]) == year: self.allvotenumber = i["valid_number"] for j in i["projects"]: prolist.append(j["name"]) self.ui.ComboBox_2.clear() self.ui.ComboBox_2.addItems(prolist) def addallpeople(self): for i in self.alltitle: self.title = i self.addpeople() QMessageBox.information(None, "添加候选人", "添加候选人成功!") def addpeople(self): year = self.ui.ComboBox.currentText() try: data = Area.search(name=self.title)['data'][0].extra except Exception: data = [] QMessageBox.warning(None, "添加候选人失败", "请先添加年份!") self.close() proname = self.ui.ComboBox_2.currentText() peoplename = self.ui.LineEdit.text() if peoplename == "": QMessageBox.warning(None, "添加候选人失败", "请输入正确人名!") else: fg = 0 source = Area.search(name=self.title)['data'][0] data = source.extra numyear = int(year) if fg == 0: ffg = 0 for i in data: if str(i["year"]) == year: for j in i["projects"]: if j["name"] == proname: ffg = 1 tmp = { "nickname": peoplename, "vote_number": 0, "vote_rate": 0, "reference_assignment": 0, "votes_reported": 0, "cpwl": 0, "YoY": -1 } if len(j["people"]) == 1 and j["people"][0]["nickname"] == "": j["people"] = [] j["people"].append(tmp) else: j["people"].append(tmp) break if ffg: break # source.extra=data #待修改 source.modify(extra=data) self.close()
36.318584
115
0.4654
49fcef5a56da53676590e2c65a882f7beb3913e3
12,651
py
Python
src/github3/gists/gist.py
butsyk/github3.py
72fa5125fce75c916733839963554765c907e9e7
[ "BSD-3-Clause" ]
null
null
null
src/github3/gists/gist.py
butsyk/github3.py
72fa5125fce75c916733839963554765c907e9e7
[ "BSD-3-Clause" ]
null
null
null
src/github3/gists/gist.py
butsyk/github3.py
72fa5125fce75c916733839963554765c907e9e7
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """This module contains the Gist, ShortGist, and GistFork objects.""" from json import dumps from .. import models from .. import users from ..decorators import requires_auth from . import comment from . import file as gistfile from . import history class _Gist(models.GitHubCore): """This object holds all the information returned by Github about a gist. With it you can comment on or fork the gist (assuming you are authenticated), edit or delete the gist (assuming you own it). You can also "star" or "unstar" the gist (again assuming you have authenticated). Two gist instances can be checked like so:: g1 == g2 g1 != g2 And is equivalent to:: g1.id == g2.id g1.id != g2.id See also: http://developer.github.com/v3/gists/ """ class_name = "_Gist" _file_class = gistfile.ShortGistFile def _update_attributes(self, gist): self.comments_count = gist["comments"] self.comments_url = gist["comments_url"] self.created_at = self._strptime(gist["created_at"]) self.description = gist["description"] self.files = { filename: self._file_class(gfile, self) for filename, gfile in gist["files"].items() } self.git_pull_url = gist["git_pull_url"] self.git_push_url = gist["git_push_url"] self.html_url = gist["html_url"] self.id = gist["id"] self.owner = gist.get("owner") if self.owner is not None: self.owner = users.ShortUser(self.owner, self) self.public = gist["public"] self.updated_at = self._strptime(gist["updated_at"]) self.url = self._api = gist["url"] def __str__(self): return self.id def _repr(self): return "<{s.class_name} [{s.id}]>".format(s=self) @requires_auth def create_comment(self, body): """Create a comment on this gist. :param str body: (required), body of the comment :returns: Created comment or None :rtype: :class:`~github3.gists.comment.GistComment` """ json = None if body: url = self._build_url("comments", base_url=self._api) json = self._json(self._post(url, data={"body": body}), 201) return self._instance_or_null(comment.GistComment, json) @requires_auth def delete(self): """Delete this gist. :returns: Whether the deletion was successful or not :rtype: bool """ return self._boolean(self._delete(self._api), 204, 404) @requires_auth def edit(self, description="", files={}): """Edit this gist. :param str description: (optional), description of the gist :param dict files: (optional), files that make up this gist; the key(s) should be the file name(s) and the values should be another (optional) dictionary with (optional) keys: 'content' and 'filename' where the former is the content of the file and the latter is the new name of the file. :returns: Whether the edit was successful or not :rtype: bool """ data = {} json = None if description: data["description"] = description if files: data["files"] = files if data: json = self._json(self._patch(self._api, data=dumps(data)), 200) if json: self._update_attributes(json) return True return False @requires_auth def fork(self): """Fork this gist. :returns: New gist if successfully forked, ``None`` otherwise :rtype: :class:`~github3.gists.gist.ShortGist` """ url = self._build_url("forks", base_url=self._api) json = self._json(self._post(url), 201) return self._instance_or_null(ShortGist, json) @requires_auth def is_starred(self): """Check to see if this gist is starred by the authenticated user. :returns: True if it is starred, False otherwise :rtype: bool """ url = self._build_url("star", base_url=self._api) return self._boolean(self._get(url), 204, 404) def comments(self, number=-1, etag=None): """Iterate over comments on this gist. :param int number: (optional), number of comments to iterate over. Default: -1 will iterate over all comments on the gist :param str etag: (optional), ETag from a previous request to the same endpoint :returns: generator of comments :rtype: :class:`~github3.gists.comment.GistComment` """ url = self._build_url("comments", base_url=self._api) return self._iter(int(number), url, comment.GistComment, etag=etag) def commits(self, number=-1, etag=None): """Iterate over the commits on this gist. These commits will be requested from the API and should be the same as what is in ``Gist.history``. .. versionadded:: 0.6 .. versionchanged:: 0.9 Added param ``etag``. :param int number: (optional), number of commits to iterate over. Default: -1 will iterate over all commits associated with this gist. :param str etag: (optional), ETag from a previous request to this endpoint. :returns: generator of the gist's history :rtype: :class:`~github3.gists.history.GistHistory` """ url = self._build_url("commits", base_url=self._api) return self._iter(int(number), url, history.GistHistory) def forks(self, number=-1, etag=None): """Iterator of forks of this gist. .. versionchanged:: 0.9 Added params ``number`` and ``etag``. :param int number: (optional), number of forks to iterate over. Default: -1 will iterate over all forks of this gist. :param str etag: (optional), ETag from a previous request to this endpoint. :returns: generator of gists :rtype: :class:`~github3.gists.gist.ShortGist` """ url = self._build_url("forks", base_url=self._api) return self._iter(int(number), url, ShortGist, etag=etag) @requires_auth def star(self): """Star this gist. :returns: True if successful, False otherwise :rtype: bool """ url = self._build_url("star", base_url=self._api) return self._boolean(self._put(url), 204, 404) @requires_auth def unstar(self): """Un-star this gist. :returns: True if successful, False otherwise :rtype: bool """ url = self._build_url("star", base_url=self._api) return self._boolean(self._delete(url), 204, 404) class GistFork(models.GitHubCore): """This object represents a forked Gist. This has a subset of attributes of a :class:`~github3.gists.gist.ShortGist`: .. attribute:: created_at The date and time when the gist was created. .. attribute:: id The unique identifier of the gist. .. attribute:: owner The user who forked the gist. .. attribute:: updated_at The date and time of the most recent modification of the fork. .. attribute:: url The API URL for the fork. """ def _update_attributes(self, fork): self.created_at = self._strptime(fork["created_at"]) self.id = fork["id"] self.owner = users.ShortUser(fork["user"], self) self.updated_at = self._strptime(fork["updated_at"]) self.url = self._api = fork["url"] def _repr(self): return "<GistFork [{0}]>".format(self.id) def to_gist(self): """Retrieve the full Gist representation of this fork. :returns: The Gist if retrieving it was successful or ``None`` :rtype: :class:`~github3.gists.gist.Gist` """ json = self._json(self._get(self.url), 200) return self._instance_or_null(Gist, json) refresh = to_gist class Gist(_Gist): """This object constitutes the full representation of a Gist. GitHub's API returns different amounts of information about gists based upon how that information is retrieved. This object exists to represent the full amount of information returned for a specific gist. For example, you would receive this class when calling :meth:`~github3.github.GitHub.gist`. To provide a clear distinction between the types of gists, github3.py uses different classes with different sets of attributes. This object has all the same attributes as :class:`~github3.gists.gist.ShortGist` as well as: .. attribute:: commits_url The URL to retrieve gist commits from the GitHub API. .. attribute:: original_forks A list of :class:`~github3.gists.gist.GistFork` objects representing each fork of this gist. To retrieve the most recent list of forks, use the :meth:`forks` method. .. attribute:: forks_url The URL to retrieve the current listing of forks of this gist. .. attribute:: history A list of :class:`~github3.gists.history.GistHistory` objects representing each change made to this gist. .. attribute:: truncated This is a boolean attribute that indicates whether the content of this Gist has been truncated or not. """ class_name = "Gist" _file_class = gistfile.GistFile def _update_attributes(self, gist): super(Gist, self)._update_attributes(gist) self.commits_url = gist["commits_url"] self.original_forks = [GistFork(fork, self) for fork in gist["forks"]] self.forks_url = gist["forks_url"] self.history = [history.GistHistory(h, self) for h in gist["history"]] self.truncated = gist["truncated"] class ShortGist(_Gist): """Short representation of a gist. GitHub's API returns different amounts of information about gists based upon how that information is retrieved. This object exists to represent the full amount of information returned for a specific gist. For example, you would receive this class when calling :meth:`~github3.github.GitHub.all_gists`. To provide a clear distinction between the types of gists, github3.py uses different classes with different sets of attributes. This object only has the following attributes: .. attribute:: url The GitHub API URL for this repository, e.g., ``https://api.github.com/gists/6faaaeb956dec3f51a9bd630a3490291``. .. attribute:: comments_count Number of comments on this gist .. attribute:: description Description of the gist as written by the creator .. attribute:: html_url The URL of this gist on GitHub, e.g., ``https://gist.github.com/sigmavirus24/6faaaeb956dec3f51a9bd630a3490291`` .. attribute:: id The unique identifier for this gist. .. attribute:: public This is a boolean attribute describing if the gist is public or private .. attribute:: git_pull_url The git URL to pull this gist, e.g., ``git://gist.github.com/sigmavirus24/6faaaeb956dec3f51a9bd630a3490291.git`` .. attribute:: git_push_url The git URL to push to gist, e.g., ``git@gist.github.com/sigmavirus24/6faaaeb956dec3f51a9bd630a3490291.git`` .. attribute:: created_at This is a datetime object representing when the gist was created. .. attribute:: updated_at This is a datetime object representing the last time this gist was most recently updated. .. attribute:: owner This attribute is a :class:`~github3.users.ShortUser` object representing the creator of the gist. .. attribute:: files A dictionary mapping the filename to a :class:`~github3.gists.gist.GistFile` object. .. versionchanged:: 1.0.0 Previously this was a list but it has been converted to a dictionary to preserve the structure of the API. .. attribute:: comments_url The URL to retrieve the list of comments on the Gist via the API. """ class_name = "ShortGist" _refresh_to = Gist
30.484337
83
0.61837
d78b8a31ba522378e07ebe572fea755e7708b306
13,230
py
Python
jasmin/routing/Routes.py
paradiseng/jasmin
16c54261a6a1a82db64311ee2a235f6c966c14ab
[ "Apache-2.0" ]
750
2015-01-02T23:09:54.000Z
2022-03-29T11:00:29.000Z
jasmin/routing/Routes.py
diwacreation3/jasmin
16c54261a6a1a82db64311ee2a235f6c966c14ab
[ "Apache-2.0" ]
806
2015-01-01T16:17:06.000Z
2022-03-29T20:36:03.000Z
jasmin/routing/Routes.py
diwacreation3/jasmin
16c54261a6a1a82db64311ee2a235f6c966c14ab
[ "Apache-2.0" ]
509
2015-01-16T20:15:25.000Z
2022-03-30T12:57:03.000Z
# pylint: disable=W0401,W0611,W0231 """ More info: http://docs.jasminsms.com/en/latest/routing/index.html """ import random from jasmin.routing.Bills import SubmitSmBill from jasmin.routing.Filters import Filter from jasmin.routing.Routables import Routable from jasmin.routing.jasminApi import * class InvalidRouteParameterError(Exception): """Raised when a parameter is not an instance of a desired class (used for validating inputs """ class InvalidRouteFilterError(Exception): """Raised when a route is instanciated with a non-compatible type, e.g. an MORoute can not have UserFilter (MO messages are not authentified). """ class Route: """Generic Route: Route contain a triplet of [Filter(s), Connector, Rate] When more than one Filter is given, matching these filters will use the AND operator """ _type = 'generic' _str = 'generic' _repr = 'Route' filters = [] connector = None rate = 0.0 def __init__(self, filters, connector, rate): if not isinstance(connector, Connector): raise InvalidRouteParameterError("connector is not an instance of Connector") if not isinstance(rate, float): raise InvalidRouteParameterError("rate is not float") if rate < 0: raise InvalidRouteParameterError("rate can not be a negative value") if not isinstance(filters, list): raise InvalidRouteParameterError("filters must be a list") for _filter in filters: if not isinstance(_filter, Filter): raise InvalidRouteParameterError( "filter must be an instance of Filter, %s found" % type(_filter) ) if not self._type in _filter.usedFor: raise InvalidRouteFilterError( "filter types (%s) is not compatible with this route type (%s)" % ( _filter.usedFor, self._type )) self.filters = filters self.connector = connector self.rate = rate if self.rate > 0: rate_str = 'rated %.2f' % self.rate else: rate_str = 'NOT RATED' self._str = '%s to %s(%s) %s' % (self.__class__.__name__, connector._type, connector.cid, rate_str) def __str__(self): return self._str def __repr__(self): return self.__class__.__name__ def getConnector(self): return self.connector def getRate(self): return self.rate def getBillFor(self, user): """This will return the exact bill for user depending on his defined quotas """ if not isinstance(user, User): raise InvalidRouteParameterError("user is not an instance of User") # Init bill = SubmitSmBill(user) # Route billing processing # [RULE 1] If route is rated and user's balance is not unlimited (balance != None) then # user will be billed for the selected route rate. if self.getRate() > 0 and user.mt_credential.getQuota('balance') is not None: early_decrement_balance_percent = user.mt_credential.getQuota('early_decrement_balance_percent') route_rate = self.getRate() # if early_decrement_balance_percent is defined then user will be: # - First: billed early_decrement_balance_percent % of the route rate on submit_sm # - Second: billed for the rest of the route rate on submit_sm_resp reception # If early_decrement_balance_percent is None (undefined) then the route rate will be # billed on submit_sm with no care about submit_sm_resp if early_decrement_balance_percent is not None: bill.setAmount('submit_sm', route_rate * early_decrement_balance_percent / 100) bill.setAmount('submit_sm_resp', route_rate - bill.getAmount('submit_sm')) else: bill.setAmount('submit_sm', route_rate) bill.setAmount('submit_sm_resp', 0) # [RULE 2] if user's submit_sm_count is not unlimited (!=None) then decrement it when sending # submit_sm if user.mt_credential.getQuota('submit_sm_count') is not None: bill.setAction('decrement_submit_sm_count', 1) return bill def matchFilters(self, routable): """If filters match routable, True will be returned, if not, False will be returned """ if not isinstance(routable, Routable): raise InvalidRouteParameterError("routable is not an instance of Routable") for _filter in self.filters: if not _filter.match(routable): return False return True class DefaultRoute(Route): """This is a default route which can contain one connector """ _type = 'default' def __init__(self, connector, rate=0.0): """ Default rate is set to 0.0 since DefaultRoute can be for MO or MT routes, rate must be set only for MT routes, otherwise it will be ignored """ if not isinstance(connector, Connector): raise InvalidRouteParameterError("connector is not an instance of Connector") if not isinstance(rate, float): raise InvalidRouteParameterError("rate is not float") if rate < 0: raise InvalidRouteParameterError("rate can not be a negative value") self.connector = connector self.rate = rate if self.rate > 0: rate_str = 'rated %.2f' % self.rate else: rate_str = 'NOT RATED' self._str = '%s to %s(%s) %s' % (self.__class__.__name__, connector._type, connector.cid, rate_str) def matchFilters(self, routable): return self.getConnector() class MTRoute(Route): """Generic MT Route """ _type = 'mt' class MORoute(Route): """Generic MO Route """ _type = 'mo' def __init__(self, filters, connector, rate=0.0): "Overriding Route's __init__ to remove rate parameter, MORoutes are not rated" Route.__init__(self, filters, connector, 0.0) class StaticMORoute(MORoute): """Return one unique route """ class StaticMTRoute(MTRoute): """Return one unique route """ class RoundrobinRoute: """Generic RoundrobinRoute """ _type = None def __init__(self, filters, connectors): if not isinstance(connectors, list): raise InvalidRouteParameterError("connectors must be a list") if len(connectors) == 0: raise InvalidRouteParameterError("Route cannot have zero connectors") for _connector in connectors: if not isinstance(_connector, Connector): raise InvalidRouteParameterError("connector is not an instance of Connector") if not isinstance(filters, list): raise InvalidRouteParameterError("filters must be a list") for _filter in filters: if not isinstance(_filter, Filter): raise InvalidRouteParameterError( "filter must be an instance of Filter, %s found" % type(_filter)) if self._type not in _filter.usedFor: raise InvalidRouteFilterError( "filter types (%s) is not compatible with this route type (%s)" % ( _filter.usedFor, self._type)) self.filters = filters self.connector = connectors connector_list_str = '' for c in connectors: if connector_list_str != '': connector_list_str += '\n' connector_list_str += '\t- %s(%s)' % (c._type, c.cid) self._str = '%s to %s connectors:\n%s' % (self.__class__.__name__, len(connectors), connector_list_str) def __str__(self): return self._str def getConnector(self): return random.choice(self.connector) class RandomRoundrobinMORoute(RoundrobinRoute, MORoute): """Return one route taken randomly from a pool of routes """ _type = 'mo' class RandomRoundrobinMTRoute(RoundrobinRoute, MTRoute): """Return one route taken randomly from a pool of routes """ _type = 'mt' def __init__(self, filters, connectors, rate): "Overriding RoundrobinRoute's __init__ to add rate parameter as it is only used for MT Routes" if not isinstance(rate, float): raise InvalidRouteParameterError("rate is not float") if rate < 0: raise InvalidRouteParameterError("rate can not be a negative value") self.rate = rate RoundrobinRoute.__init__(self, filters, connectors) if self.rate > 0: rate_str = '\nrated %.2f' % self.rate else: rate_str = '\nNOT RATED' self._str = "%s %s" % (self._str, rate_str) class FailoverRoute: """Generic FailoverRoute""" _type = None def __init__(self, filters, connectors): if not isinstance(connectors, list): raise InvalidRouteParameterError("connectors must be a list") if len(connectors) == 0: raise InvalidRouteParameterError("Route cannot have zero connectors") for _connector in connectors: if not isinstance(_connector, Connector): raise InvalidRouteParameterError("connector is not an instance of Connector") if not isinstance(filters, list): raise InvalidRouteParameterError("filters must be a list") for _filter in filters: if not isinstance(_filter, Filter): raise InvalidRouteParameterError( "filter must be an instance of Filter, %s found" % type(_filter)) if self._type not in _filter.usedFor: raise InvalidRouteFilterError( "filter types (%s) is not compatible with this route type (%s)" % ( _filter.usedFor, self._type)) self.filters = filters self.seq = -1 self.connector = connectors connector_list_str = '' for c in connectors: if connector_list_str != '': connector_list_str += '\n' connector_list_str += '\t- %s(%s)' % (c._type, c.cid) self._str = '%s to %s connectors:\n%s' % (self.__class__.__name__, len(connectors), connector_list_str) def __str__(self): return self._str def getConnector(self): try: self.seq += 1 return self.connector[self.seq] except IndexError: return None class FailoverMORoute(FailoverRoute, MORoute): """Returned connector from getConnector method is iterated through the list of available connectors """ _type = 'mo' def __init__(self, filters, connectors): FailoverRoute.__init__(self, filters, connectors) # Don't accept mixed connector types for FailoverMORoute # This is a design limitation: the deliver_sm throwers are isolated by type of connector, # they cannot execute a failover algorithm on top of two different connector types. _types = None for c in connectors: if _types is not None and c._type != _types: raise InvalidRouteParameterError('FailoverMORoute cannot have mixed connector types') _types = c._type if not isinstance(connectors, list): raise InvalidRouteParameterError("connectors must be a list") def getConnectors(self): return self.connector def matchFilters(self, routable): # Initialize self.seq to return first connector self.seq = -1 return MORoute.matchFilters(self, routable) class FailoverMTRoute(FailoverRoute, MTRoute): """Returned connector from getConnector method is iterated through the list of available connectors """ _type = 'mt' def __init__(self, filters, connectors, rate): """Overriding FailoverRoute's __init__ to add rate parameter as it is only used for MT Routes""" if not isinstance(rate, float): raise InvalidRouteParameterError("rate is not float") if rate < 0: raise InvalidRouteParameterError("rate can not be a negative value") self.rate = rate FailoverRoute.__init__(self, filters, connectors) if self.rate > 0: rate_str = '\nrated %.2f' % self.rate else: rate_str = '\nNOT RATED' self._str = "%s %s" % (self._str, rate_str) def matchFilters(self, routable): # Initialize self.seq to return first connector self.seq = -1 return MTRoute.matchFilters(self, routable) class BestQualityMTRoute(MTRoute): # @todo: Work in progress """Take the best route based on: * (submit_sm / submit_sm_resp) ratio * (delivered submits / underlivered submits) """ def __init__(self, filters, connector, rate): MTRoute.__init__(self, filters, connector, rate) raise NotImplementedError
34.724409
108
0.621315
63af35d4058a5259b147d831f03ada2f77e9e8f4
9,328
py
Python
connect_remote.py
NeotomaDB/Neotoma_SQL
503917b07a536d7cee9cbb67e256d0d29c97df4f
[ "MIT" ]
1
2021-07-29T01:19:11.000Z
2021-07-29T01:19:11.000Z
connect_remote.py
NeotomaDB/Neotoma_SQL
503917b07a536d7cee9cbb67e256d0d29c97df4f
[ "MIT" ]
5
2019-03-11T18:10:13.000Z
2020-10-15T21:55:48.000Z
connect_remote.py
NeotomaDB/Neotoma_SQL
503917b07a536d7cee9cbb67e256d0d29c97df4f
[ "MIT" ]
null
null
null
#! /usr/bin/python3 """ Neotoma DB Function Checker Simon Goring 2018 MIT License Connect to a Neotoma Paleoecology Database using a JSON connection string and return all the currently scripted queries. If a sql file exists in one of the local schema directories but does not have an associated function, then create that function. NOTE: This requires the inclusion of a json file in the base directory called connect_remote.json that uses the format: { "host": "hostname", "port": 9999, "database": "databasename", "user": "username", "password": "passwordname" } Please ensure that this file is included in the .gitignore file. """ import json import os import psycopg2 import argparse import copy import re import git import sys parser = argparse.ArgumentParser( description='Check Neotoma SQL functions against functions in the ' + 'online database servers (`neotoma` and `neotomadev`).') parser.add_argument('-dev', dest='isDev', default=False, help='Use the `dev` database? (`False` without the flag)', action='store_true') parser.add_argument('-push', dest='isPush', default=False, help='Assume that SQL functions in the repository are ' + 'newer, push to the db server.', action='store_true') parser.add_argument('-g', dest='pullGit', nargs='?', type=str, default=None, help='Pull from the remote git server before running?.') parser.add_argument('-tilia', dest='isTilia', default=False, help='Use the `dev` database? (`False` without the flag)', action='store_true') args = parser.parse_args() with open('.gitignore') as gi: good = False # This simply checks to see if you have a connection string in your repo. # I use `strip` to remove whitespace/newlines. for line in gi: if line.strip() == "connect_remote.json": good = True break if good is False: print("The connect_remote.json file is not in your .gitignore file. " + "Please add it!") with open('connect_remote.json') as f: data = json.load(f) if args.pullGit is not None: repo = git.Repo('.') try: repo.heads[args.pullGit].checkout() except git.exc.GitCommandError: sys.exit("Stash or commit changes in the current branch before " + "switching to " + args.pullGit + ".") repo.remotes.origin.pull() if args.isDev: data['database'] = 'neotomadev' if args.isTilia: data['database'] = 'neotomatilia' print("Using the " + data['database'] + ' Neotoma server.') conn = psycopg2.connect(**data, connect_timeout=5) cur = conn.cursor() print('Building indices:') with open('function/indexes/addingIndices.sql') as file: lines = filter(None, (line.rstrip() for line in file)) for line in lines: cur.execute(line) # This query uses the catalog to find all functions and definitions within the # neotomadev database. cur.execute(""" SELECT n.nspname AS schema, proname AS functionName, pg_get_function_identity_arguments(f.oid) AS args, pg_get_functiondef(f.oid) AS function FROM pg_catalog.pg_proc AS f INNER JOIN pg_catalog.pg_namespace AS n ON f.pronamespace = n.oid WHERE n.nspname IN ('ti','ndb','ts', 'mca', 'ecg', 'ap', 'da', 'emb', 'gen', 'doi') ORDER BY n.nspname, proname""") # For each sql function in the named namespaces go in and write out the actual # function declaration if the function does not currently exist in the GitHub # repo. print('Running!') rewrite = set() failed = set() z = 0 for record in cur: # This checks each function in the database and then tests whether there # is a file associated with it. newFile = "./function/" + record[0] + "/" + record[1] + ".sql" testPath = "./function/" + record[0] if os.path.isdir(testPath) is False: # If there is no directory for the schema, make it. os.mkdir(testPath) if os.path.exists(newFile) is False: # If there is no file for the function, make it: file = open(newFile, 'w') file.write(record[3]) file.close() print(record[0] + '.' + record[1] + ' has been added.') if os.path.exists(newFile) is True: # If there is a file, check to see if they are the same, so we # can check for updated functions. file = open(newFile) textCheck = copy.deepcopy(file.read()) serverFun = copy.deepcopy(record[3]) textCheck = re.sub(r'[\s+\t+\n+\r+]', '', textCheck) serverFun = re.sub(r'[\s+\t+\n+\r+]', '', serverFun) match = serverFun == textCheck # Pushing (to the db) and pulling (from the db) are defined by the user if match is False: if args.isPush is False: print('The function ' + record[0] + '.' + record[1] + ' differs between the database and your local copy.\n*' + newFile + ' will be written locally.') file = open(newFile, 'w') file.write(record[3]) file.close() print('The file for ' + record[0] + '.' + record[1] + ' has been updated in the repository.') else: cur2 = conn.cursor() try: cur2.execute("DROP FUNCTION " + record[0] + "." + record[1] + "(" + record[2] + ");") conn.commit() except Exception as e: print("Failed for " + record[1]) print(e) conn.rollback() print("Could not delete " + record[0] + "." + record[1]) failed.add(record[0] + "." + record[1]) try: cur2 = conn.cursor() cur2.execute( open("./function/" + record[0] + "/" + record[1] + ".sql", "r").read()) conn.commit() cur2.execute("REASSIGN OWNED BY sug335 TO functionwriter;") conn.commit() rewrite.add(record[0] + "." + record[1]) print('The function for ' + record[0] + '.' + record[1] + ' has been updated in the `' + data['database'] + '` database.') z = z + 1 except Exception as e: conn.rollback() print(e) print('The function for ' + record[0] + '.' + record[1] + ' has not been updated in the `' + data['database'] + '` database.') failed.add(record[0] + "." + record[1]) for schema in ['ti', 'ts', 'doi', 'ap', 'ndb', 'da']: # Now check all files to see if they are in the DB. . . for functs in os.listdir("./function/" + schema + "/"): # SQL = """ SELECT n.nspname AS schema, proname AS functionName, pg_get_function_identity_arguments(f.oid) AS args, pg_get_functiondef(f.oid) AS function FROM pg_catalog.pg_proc AS f INNER JOIN pg_catalog.pg_namespace AS n ON f.pronamespace = n.oid WHERE n.nspname = %s AND proname = %s""" data = (schema, functs.split(".")[0]) try: cur.execute(SQL, data) except Exception as e: conn.rollback() print("Failed to run. " + schema) print(e) if cur.rowcount == 0: # Execute the new script if there is one. Needs the commit. print("Executing " + schema + "." + functs.split(".")[0]) try: cur.execute(open("./function/" + schema + "/" + functs, "r").read()) conn.commit() cur2.execute("REASSIGN OWNED BY sug335 TO functionwriter;") conn.commit() rewrite.add(schema + "." + functs.split(".")[0]) z = z + 1 except Exception as e: conn.rollback() print("Failed to push function: ") print(e) failed.add(schema + "." + functs.split(".")[0]) z = z + 1 if cur.rowcount > 1: # TODO: Need to add a script to check that the definitions are # the same. print(schema + "." + functs.split(".")[0] + " has " + str(cur.rowcount) + " definitions.") # This section makes sure that the sequences are reset properly. We ran into # this issue unintentionally during a re-load of the Neotoma data. print('Fixing sequences') cur.execute(open('helpers/reset_sequences.sql', 'r').read()) cur2 = conn.cursor() for res in cur.fetchall(): try: cur2.execute(res[0]) conn.commit() except Exception as e: print('skipped: ' + res[0]) print(e) conn.close() print("The script has rewritten:") for funs in rewrite: print(" * " + funs) print("The script has failed for:") for funs in failed: print(" * " + funs)
35.467681
79
0.549528
499354442fb37c98b4668ce5b0e8ca5910084fbc
175
py
Python
.history/ClassFiles/Control Flow/Elif_20210101185139.py
minefarmer/Comprehensive-Python
f97b9b83ec328fc4e4815607e6a65de90bb8de66
[ "Unlicense" ]
null
null
null
.history/ClassFiles/Control Flow/Elif_20210101185139.py
minefarmer/Comprehensive-Python
f97b9b83ec328fc4e4815607e6a65de90bb8de66
[ "Unlicense" ]
null
null
null
.history/ClassFiles/Control Flow/Elif_20210101185139.py
minefarmer/Comprehensive-Python
f97b9b83ec328fc4e4815607e6a65de90bb8de66
[ "Unlicense" ]
null
null
null
''' elif Statements Used to check multiple expressions for True conditions. if(Condition1): Indented statement block for Condition1 elif(Condition2) '''
13.461538
55
0.697143
ceabf43be337f1ae19fbd4487b790274895c3be6
4,782
py
Python
venv/lib/python2.7/site-packages/pelican/paginator.py
ThoMaCarto/AtlasUECI
c10d18551ee868317f63f22fab820c366936872a
[ "MIT" ]
2
2019-07-06T06:42:05.000Z
2021-05-25T09:23:08.000Z
venv/lib/python2.7/site-packages/pelican/paginator.py
ThoMaCarto/AtlasUECI
c10d18551ee868317f63f22fab820c366936872a
[ "MIT" ]
null
null
null
venv/lib/python2.7/site-packages/pelican/paginator.py
ThoMaCarto/AtlasUECI
c10d18551ee868317f63f22fab820c366936872a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import functools import logging import os from collections import namedtuple from math import ceil import six logger = logging.getLogger(__name__) PaginationRule = namedtuple( 'PaginationRule', 'min_page URL SAVE_AS', ) class Paginator(object): def __init__(self, name, url, object_list, settings, per_page=None): self.name = name self.url = url self.object_list = object_list self.settings = settings if per_page: self.per_page = per_page self.orphans = settings['DEFAULT_ORPHANS'] else: self.per_page = len(object_list) self.orphans = 0 self._num_pages = self._count = None def page(self, number): "Returns a Page object for the given 1-based page number." bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return Page(self.name, self.url, self.object_list[bottom:top], number, self, self.settings) def _get_count(self): "Returns the total number of objects, across all pages." if self._count is None: self._count = len(self.object_list) return self._count count = property(_get_count) def _get_num_pages(self): "Returns the total number of pages." if self._num_pages is None: hits = max(1, self.count - self.orphans) self._num_pages = int(ceil(hits / (float(self.per_page) or 1))) return self._num_pages num_pages = property(_get_num_pages) def _get_page_range(self): """ Returns a 1-based range of pages for iterating through within a template for loop. """ return list(range(1, self.num_pages + 1)) page_range = property(_get_page_range) class Page(object): def __init__(self, name, url, object_list, number, paginator, settings): self.full_name = name self.name, self.extension = os.path.splitext(name) dn, fn = os.path.split(name) self.base_name = dn if fn in ('index.htm', 'index.html') else self.name self.base_url = url self.object_list = object_list self.number = number self.paginator = paginator self.settings = settings def __repr__(self): return '<Page %s of %s>' % (self.number, self.paginator.num_pages) def has_next(self): return self.number < self.paginator.num_pages def has_previous(self): return self.number > 1 def has_other_pages(self): return self.has_previous() or self.has_next() def next_page_number(self): return self.number + 1 def previous_page_number(self): return self.number - 1 def start_index(self): """ Returns the 1-based index of the first object on this page, relative to total objects in the paginator. """ # Special case, return zero if no items. if self.paginator.count == 0: return 0 return (self.paginator.per_page * (self.number - 1)) + 1 def end_index(self): """ Returns the 1-based index of the last object on this page, relative to total objects found (hits). """ # Special case for the last page because there can be orphans. if self.number == self.paginator.num_pages: return self.paginator.count return self.number * self.paginator.per_page def _from_settings(self, key): """Returns URL information as defined in settings. Similar to URLWrapper._from_settings, but specialized to deal with pagination logic.""" rule = None # find the last matching pagination rule for p in self.settings['PAGINATION_PATTERNS']: if p.min_page <= self.number: rule = p if not rule: return '' prop_value = getattr(rule, key) if not isinstance(prop_value, six.string_types): logger.warning('%s is set to %s', key, prop_value) return prop_value # URL or SAVE_AS is a string, format it with a controlled context context = { 'save_as': self.full_name, 'url': self.base_url, 'name': self.name, 'base_name': self.base_name, 'extension': self.extension, 'number': self.number, } ret = prop_value.format(**context) ret = ret.lstrip('/') return ret url = property(functools.partial(_from_settings, key='URL')) save_as = property(functools.partial(_from_settings, key='SAVE_AS'))
31.051948
79
0.612714
46a4fbf335c892457ff47c248af13c3910158dda
14,808
py
Python
homeassistant/components/evohome/climate.py
reuank/home-assistant
fb35d382e1e1cc8be5a167e1f3834c0d48273b5a
[ "Apache-2.0" ]
null
null
null
homeassistant/components/evohome/climate.py
reuank/home-assistant
fb35d382e1e1cc8be5a167e1f3834c0d48273b5a
[ "Apache-2.0" ]
null
null
null
homeassistant/components/evohome/climate.py
reuank/home-assistant
fb35d382e1e1cc8be5a167e1f3834c0d48273b5a
[ "Apache-2.0" ]
null
null
null
"""Support for Climate devices of (EMEA/EU-based) Honeywell TCC systems.""" from datetime import datetime as dt import logging from typing import List, Optional from homeassistant.components.climate import ClimateDevice from homeassistant.components.climate.const import ( CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_AWAY, PRESET_ECO, PRESET_HOME, PRESET_NONE, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import PRECISION_TENTHS from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.util.dt import parse_datetime from . import ( ATTR_DURATION_DAYS, ATTR_DURATION_HOURS, ATTR_DURATION_UNTIL, ATTR_SYSTEM_MODE, ATTR_ZONE_TEMP, CONF_LOCATION_IDX, SVC_RESET_ZONE_OVERRIDE, SVC_SET_SYSTEM_MODE, EvoChild, EvoDevice, ) from .const import ( DOMAIN, EVO_AUTO, EVO_AUTOECO, EVO_AWAY, EVO_CUSTOM, EVO_DAYOFF, EVO_FOLLOW, EVO_HEATOFF, EVO_PERMOVER, EVO_RESET, EVO_TEMPOVER, ) _LOGGER = logging.getLogger(__name__) PRESET_RESET = "Reset" # reset all child zones to EVO_FOLLOW PRESET_CUSTOM = "Custom" HA_HVAC_TO_TCS = {HVAC_MODE_OFF: EVO_HEATOFF, HVAC_MODE_HEAT: EVO_AUTO} TCS_PRESET_TO_HA = { EVO_AWAY: PRESET_AWAY, EVO_CUSTOM: PRESET_CUSTOM, EVO_AUTOECO: PRESET_ECO, EVO_DAYOFF: PRESET_HOME, EVO_RESET: PRESET_RESET, } # EVO_AUTO: None, HA_PRESET_TO_TCS = {v: k for k, v in TCS_PRESET_TO_HA.items()} EVO_PRESET_TO_HA = { EVO_FOLLOW: PRESET_NONE, EVO_TEMPOVER: "temporary", EVO_PERMOVER: "permanent", } HA_PRESET_TO_EVO = {v: k for k, v in EVO_PRESET_TO_HA.items()} STATE_ATTRS_TCS = ["systemId", "activeFaults", "systemModeStatus"] STATE_ATTRS_ZONES = ["zoneId", "activeFaults", "setpointStatus", "temperatureStatus"] async def async_setup_platform( hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None ) -> None: """Create the evohome Controller, and its Zones, if any.""" if discovery_info is None: return broker = hass.data[DOMAIN]["broker"] _LOGGER.debug( "Found the Location/Controller (%s), id=%s, name=%s (location_idx=%s)", broker.tcs.modelType, broker.tcs.systemId, broker.tcs.location.name, broker.params[CONF_LOCATION_IDX], ) controller = EvoController(broker, broker.tcs) zones = [] for zone in broker.tcs.zones.values(): if zone.zoneType == "Unknown": _LOGGER.warning( "Ignoring: %s (%s), id=%s, name=%s: invalid zone type", zone.zoneType, zone.modelType, zone.zoneId, zone.name, ) else: _LOGGER.debug( "Adding: %s (%s), id=%s, name=%s", zone.zoneType, zone.modelType, zone.zoneId, zone.name, ) new_entity = EvoZone(broker, zone) zones.append(new_entity) async_add_entities([controller] + zones, update_before_add=True) class EvoClimateDevice(EvoDevice, ClimateDevice): """Base for an evohome Climate device.""" def __init__(self, evo_broker, evo_device) -> None: """Initialize a Climate device.""" super().__init__(evo_broker, evo_device) self._preset_modes = None @property def hvac_modes(self) -> List[str]: """Return a list of available hvac operation modes.""" return list(HA_HVAC_TO_TCS) @property def preset_modes(self) -> Optional[List[str]]: """Return a list of available preset modes.""" return self._preset_modes class EvoZone(EvoChild, EvoClimateDevice): """Base for a Honeywell TCC Zone.""" def __init__(self, evo_broker, evo_device) -> None: """Initialize a Honeywell TCC Zone.""" super().__init__(evo_broker, evo_device) self._unique_id = evo_device.zoneId self._name = evo_device.name self._icon = "mdi:radiator" if evo_broker.client_v1: self._precision = PRECISION_TENTHS else: self._precision = self._evo_device.setpointCapabilities["valueResolution"] self._preset_modes = list(HA_PRESET_TO_EVO) self._supported_features = SUPPORT_PRESET_MODE | SUPPORT_TARGET_TEMPERATURE async def async_zone_svc_request(self, service: dict, data: dict) -> None: """Process a service request (setpoint override) for a zone.""" if service == SVC_RESET_ZONE_OVERRIDE: await self._evo_broker.call_client_api( self._evo_device.cancel_temp_override() ) return # otherwise it is SVC_SET_ZONE_OVERRIDE temp = round(data[ATTR_ZONE_TEMP] * self.precision) / self.precision temp = max(min(temp, self.max_temp), self.min_temp) if ATTR_DURATION_UNTIL in data: duration = data[ATTR_DURATION_UNTIL] if duration == 0: await self._update_schedule() until = parse_datetime(str(self.setpoints.get("next_sp_from"))) else: until = dt.now() + data[ATTR_DURATION_UNTIL] else: until = None # indefinitely await self._evo_broker.call_client_api( self._evo_device.set_temperature(temperature=temp, until=until) ) @property def hvac_mode(self) -> str: """Return the current operating mode of a Zone.""" if self._evo_tcs.systemModeStatus["mode"] in [EVO_AWAY, EVO_HEATOFF]: return HVAC_MODE_AUTO is_off = self.target_temperature <= self.min_temp return HVAC_MODE_OFF if is_off else HVAC_MODE_HEAT @property def hvac_action(self) -> Optional[str]: """Return the current running hvac operation if supported.""" if self._evo_tcs.systemModeStatus["mode"] == EVO_HEATOFF: return CURRENT_HVAC_OFF if self.target_temperature <= self.min_temp: return CURRENT_HVAC_OFF if not self._evo_device.temperatureStatus["isAvailable"]: return None if self.target_temperature <= self.current_temperature: return CURRENT_HVAC_IDLE return CURRENT_HVAC_HEAT @property def target_temperature(self) -> float: """Return the target temperature of a Zone.""" return self._evo_device.setpointStatus["targetHeatTemperature"] @property def preset_mode(self) -> Optional[str]: """Return the current preset mode, e.g., home, away, temp.""" if self._evo_tcs.systemModeStatus["mode"] in [EVO_AWAY, EVO_HEATOFF]: return TCS_PRESET_TO_HA.get(self._evo_tcs.systemModeStatus["mode"]) return EVO_PRESET_TO_HA.get(self._evo_device.setpointStatus["setpointMode"]) @property def min_temp(self) -> float: """Return the minimum target temperature of a Zone. The default is 5, but is user-configurable within 5-35 (in Celsius). """ return self._evo_device.setpointCapabilities["minHeatSetpoint"] @property def max_temp(self) -> float: """Return the maximum target temperature of a Zone. The default is 35, but is user-configurable within 5-35 (in Celsius). """ return self._evo_device.setpointCapabilities["maxHeatSetpoint"] async def async_set_temperature(self, **kwargs) -> None: """Set a new target temperature.""" temperature = kwargs["temperature"] until = kwargs.get("until") if until is None: if self._evo_device.setpointStatus["setpointMode"] == EVO_FOLLOW: await self._update_schedule() until = parse_datetime(str(self.setpoints.get("next_sp_from"))) elif self._evo_device.setpointStatus["setpointMode"] == EVO_TEMPOVER: until = parse_datetime(self._evo_device.setpointStatus["until"]) await self._evo_broker.call_client_api( self._evo_device.set_temperature(temperature, until) ) async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Set a Zone to one of its native EVO_* operating modes. Zones inherit their _effective_ operating mode from their Controller. Usually, Zones are in 'FollowSchedule' mode, where their setpoints are a function of their own schedule and the Controller's operating mode, e.g. 'AutoWithEco' mode means their setpoint is (by default) 3C less than scheduled. However, Zones can _override_ these setpoints, either indefinitely, 'PermanentOverride' mode, or for a set period of time, 'TemporaryOverride' mode (after which they will revert back to 'FollowSchedule' mode). Finally, some of the Controller's operating modes are _forced_ upon the Zones, regardless of any override mode, e.g. 'HeatingOff', Zones to (by default) 5C, and 'Away', Zones to (by default) 12C. """ if hvac_mode == HVAC_MODE_OFF: await self._evo_broker.call_client_api( self._evo_device.set_temperature(self.min_temp, until=None) ) else: # HVAC_MODE_HEAT await self._evo_broker.call_client_api( self._evo_device.cancel_temp_override() ) async def async_set_preset_mode(self, preset_mode: Optional[str]) -> None: """Set the preset mode; if None, then revert to following the schedule.""" evo_preset_mode = HA_PRESET_TO_EVO.get(preset_mode, EVO_FOLLOW) if evo_preset_mode == EVO_FOLLOW: await self._evo_broker.call_client_api( self._evo_device.cancel_temp_override() ) return temperature = self._evo_device.setpointStatus["targetHeatTemperature"] if evo_preset_mode == EVO_TEMPOVER: await self._update_schedule() until = parse_datetime(str(self.setpoints.get("next_sp_from"))) else: # EVO_PERMOVER until = None await self._evo_broker.call_client_api( self._evo_device.set_temperature(temperature, until) ) async def async_update(self) -> None: """Get the latest state data for a Zone.""" await super().async_update() for attr in STATE_ATTRS_ZONES: self._device_state_attrs[attr] = getattr(self._evo_device, attr) class EvoController(EvoClimateDevice): """Base for a Honeywell TCC Controller/Location. The Controller (aka TCS, temperature control system) is the parent of all the child (CH/DHW) devices. It is implemented as a Climate entity to expose the controller's operating modes to HA. It is assumed there is only one TCS per location, and they are thus synonymous. """ def __init__(self, evo_broker, evo_device) -> None: """Initialize a Honeywell TCC Controller/Location.""" super().__init__(evo_broker, evo_device) self._unique_id = evo_device.systemId self._name = evo_device.location.name self._icon = "mdi:thermostat" self._precision = PRECISION_TENTHS modes = [m["systemMode"] for m in evo_broker.config["allowedSystemModes"]] self._preset_modes = [ TCS_PRESET_TO_HA[m] for m in modes if m in list(TCS_PRESET_TO_HA) ] self._supported_features = SUPPORT_PRESET_MODE if self._preset_modes else 0 async def async_tcs_svc_request(self, service: dict, data: dict) -> None: """Process a service request (system mode) for a controller. Data validation is not required, it will have been done upstream. """ if service == SVC_SET_SYSTEM_MODE: mode = data[ATTR_SYSTEM_MODE] else: # otherwise it is SVC_RESET_SYSTEM mode = EVO_RESET if ATTR_DURATION_DAYS in data: until = dt.combine(dt.now().date(), dt.min.time()) until += data[ATTR_DURATION_DAYS] elif ATTR_DURATION_HOURS in data: until = dt.now() + data[ATTR_DURATION_HOURS] else: until = None await self._set_tcs_mode(mode, until=until) async def _set_tcs_mode(self, mode: str, until: Optional[dt] = None) -> None: """Set a Controller to any of its native EVO_* operating modes.""" await self._evo_broker.call_client_api(self._evo_tcs.set_status(mode)) @property def hvac_mode(self) -> str: """Return the current operating mode of a Controller.""" tcs_mode = self._evo_tcs.systemModeStatus["mode"] return HVAC_MODE_OFF if tcs_mode == EVO_HEATOFF else HVAC_MODE_HEAT @property def current_temperature(self) -> Optional[float]: """Return the average current temperature of the heating Zones. Controllers do not have a current temp, but one is expected by HA. """ temps = [ z.temperatureStatus["temperature"] for z in self._evo_tcs.zones.values() if z.temperatureStatus["isAvailable"] ] return round(sum(temps) / len(temps), 1) if temps else None @property def preset_mode(self) -> Optional[str]: """Return the current preset mode, e.g., home, away, temp.""" return TCS_PRESET_TO_HA.get(self._evo_tcs.systemModeStatus["mode"]) @property def min_temp(self) -> float: """Return None as Controllers don't have a target temperature.""" return None @property def max_temp(self) -> float: """Return None as Controllers don't have a target temperature.""" return None async def async_set_temperature(self, **kwargs) -> None: """Raise exception as Controllers don't have a target temperature.""" raise NotImplementedError("Evohome Controllers don't have target temperatures.") async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Set an operating mode for a Controller.""" await self._set_tcs_mode(HA_HVAC_TO_TCS.get(hvac_mode)) async def async_set_preset_mode(self, preset_mode: Optional[str]) -> None: """Set the preset mode; if None, then revert to 'Auto' mode.""" await self._set_tcs_mode(HA_PRESET_TO_TCS.get(preset_mode, EVO_AUTO)) async def async_update(self) -> None: """Get the latest state data for a Controller.""" self._device_state_attrs = {} attrs = self._device_state_attrs for attr in STATE_ATTRS_TCS: if attr == "activeFaults": attrs["activeSystemFaults"] = getattr(self._evo_tcs, attr) else: attrs[attr] = getattr(self._evo_tcs, attr)
35.510791
88
0.653566
ad1385a02ba2bafbf82d1b9be52d7fc530903ed6
11,182
py
Python
pcdet/models/roi_heads/ct3d_head.py
EmiyaNing/OpenPCDet
41ff28209cb000b51626a0ed8593b0adbe3dd447
[ "Apache-2.0" ]
null
null
null
pcdet/models/roi_heads/ct3d_head.py
EmiyaNing/OpenPCDet
41ff28209cb000b51626a0ed8593b0adbe3dd447
[ "Apache-2.0" ]
null
null
null
pcdet/models/roi_heads/ct3d_head.py
EmiyaNing/OpenPCDet
41ff28209cb000b51626a0ed8593b0adbe3dd447
[ "Apache-2.0" ]
null
null
null
import torch.nn as nn import pdb import torch import numpy as np from numpy import * import torch.nn.functional as F from ...utils import common_utils from .roi_head_template import RoIHeadTemplate from ..model_utils.ctrans import build_transformer class MLP(nn.Module): """ Very simple multi-layer perceptron (also called FFN)""" def __init__(self, input_dim, hidden_dim, output_dim, num_layers): super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])) def forward(self, x): for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) return x class CT3DHead(RoIHeadTemplate): def __init__(self, input_channels, model_cfg, voxel_size, point_cloud_range, num_class=1): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg self.up_dimension = MLP(input_dim = 28, hidden_dim = 64, output_dim = 256, num_layers = 3) num_queries = model_cfg.Transformer.num_queries hidden_dim = model_cfg.Transformer.hidden_dim self.num_points = model_cfg.Transformer.num_points self.class_embed = nn.Linear(hidden_dim, self.num_class) self.bbox_embed = MLP(hidden_dim, hidden_dim, self.box_coder.code_size, 4) self.query_embed = nn.Embedding(num_queries, hidden_dim) self.transformer = build_transformer(model_cfg.Transformer) self.aux_loss = model_cfg.Transformer.aux_loss self.init_weights(weight_init='xavier') def init_weights(self, weight_init='xavier'): if weight_init == 'kaiming': init_func = nn.init.kaiming_normal_ elif weight_init == 'xavier': init_func = nn.init.xavier_normal_ elif weight_init == 'normal': init_func = nn.init.normal_ else: raise NotImplementedError for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): if weight_init == 'normal': init_func(m.weight, mean=0, std=0.001) else: init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) nn.init.normal_(self.bbox_embed.layers[-1].weight, mean=0, std=0.001) def get_global_grid_points_of_roi(self, rois): rois = rois.view(-1, rois.shape[-1]) batch_size_rcnn = rois.shape[0] local_roi_grid_points = self.get_corner_points(rois, batch_size_rcnn) # (BxN, 2x2x2, 3) global_roi_grid_points = common_utils.rotate_points_along_z( local_roi_grid_points.clone(), rois[:, 6] ).squeeze(dim=1) global_center = rois[:, 0:3].clone() # pdb.set_trace() global_roi_grid_points += global_center.unsqueeze(dim=1) return global_roi_grid_points, local_roi_grid_points @staticmethod def get_corner_points(rois, batch_size_rcnn): faked_features = rois.new_ones((2, 2, 2)) dense_idx = faked_features.nonzero() # (N, 3) [x_idx, y_idx, z_idx] dense_idx = dense_idx.repeat(batch_size_rcnn, 1, 1).float() # (B, 2x2x2, 3) local_roi_size = rois.view(batch_size_rcnn, -1)[:, 3:6] roi_grid_points = dense_idx * local_roi_size.unsqueeze(dim=1) \ - (local_roi_size.unsqueeze(dim=1) / 2) # (B, 2x2x2, 3) return roi_grid_points def spherical_coordinate(self, src, diag_dist): assert (src.shape[-1] == 27) device = src.device indices_x = torch.LongTensor([0,3,6,9,12,15,18,21,24]).to(device) # indices_y = torch.LongTensor([1,4,7,10,13,16,19,22,25]).to(device) # indices_z = torch.LongTensor([2,5,8,11,14,17,20,23,26]).to(device) src_x = torch.index_select(src, -1, indices_x) src_y = torch.index_select(src, -1, indices_y) src_z = torch.index_select(src, -1, indices_z) dis = (src_x ** 2 + src_y ** 2 + src_z ** 2) ** 0.5 phi = torch.atan(src_y / (src_x + 1e-5)) the = torch.acos(src_z / (dis + 1e-5)) dis = dis / diag_dist src = torch.cat([dis, phi, the], dim = -1) return src def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] rois = batch_dict['rois'] batch_size = batch_dict['batch_size'] num_rois = batch_dict['rois'].shape[-2] # corner corner_points, _ = self.get_global_grid_points_of_roi(rois) # (BxN, 2x2x2, 3) corner_points = corner_points.view(batch_size, num_rois, -1, corner_points.shape[-1]) # (B, N, 2x2x2, 3) num_sample = self.num_points src = rois.new_zeros(batch_size, num_rois, num_sample, 4) for bs_idx in range(batch_size): cur_points = batch_dict['points'][(batch_dict['points'][:, 0] == bs_idx)][:,1:5] cur_batch_boxes = batch_dict['rois'][bs_idx] cur_radiis = torch.sqrt((cur_batch_boxes[:,3]/2) ** 2 + (cur_batch_boxes[:,4]/2) ** 2) * 1.2 dis = torch.norm((cur_points[:,:2].unsqueeze(0) - cur_batch_boxes[:,:2].unsqueeze(1).repeat(1,cur_points.shape[0],1)), dim = 2) point_mask = (dis <= cur_radiis.unsqueeze(-1)) for roi_box_idx in range(0, num_rois): cur_roi_points = cur_points[point_mask[roi_box_idx]] if cur_roi_points.shape[0] >= num_sample: random.seed(0) index = np.random.randint(cur_roi_points.shape[0], size=num_sample) cur_roi_points_sample = cur_roi_points[index] elif cur_roi_points.shape[0] == 0: cur_roi_points_sample = cur_roi_points.new_zeros(num_sample, 4) else: empty_num = num_sample - cur_roi_points.shape[0] add_zeros = cur_roi_points.new_zeros(empty_num, 4) add_zeros = cur_roi_points[0].repeat(empty_num, 1) cur_roi_points_sample = torch.cat([cur_roi_points, add_zeros], dim = 0) src[bs_idx, roi_box_idx, :, :] = cur_roi_points_sample src = src.view(batch_size * num_rois, -1, src.shape[-1]) # (b*128, 256, 4) corner_points = corner_points.view(batch_size * num_rois, -1) corner_add_center_points = torch.cat([corner_points, rois.view(-1, rois.shape[-1])[:,:3]], dim = -1) pos_fea = src[:,:,:3].repeat(1,1,9) - corner_add_center_points.unsqueeze(1).repeat(1,num_sample,1) # 27 维度 lwh = rois.view(-1, rois.shape[-1])[:,3:6].unsqueeze(1).repeat(1,num_sample,1) diag_dist = (lwh[:,:,0]**2 + lwh[:,:,1]**2 + lwh[:,:,2]**2) ** 0.5 pos_fea = self.spherical_coordinate(pos_fea, diag_dist = diag_dist.unsqueeze(-1)) src = torch.cat([pos_fea, src[:,:,-1].unsqueeze(-1)], dim = -1) src = self.up_dimension(src) # Transformer pos = torch.zeros_like(src) hs = self.transformer(src, self.query_embed.weight, pos)[0] # output rcnn_cls = self.class_embed(hs)[-1].squeeze(1) rcnn_reg = self.bbox_embed(hs)[-1].squeeze(1) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict return batch_dict def get_box_cls_layer_loss(self, forward_ret_dict): loss_cfgs = self.model_cfg.LOSS_CONFIG rcnn_cls = forward_ret_dict['rcnn_cls'] rcnn_cls_labels = forward_ret_dict['rcnn_cls_labels'].view(-1) if self.model_cfg.CLASS_AGNOSTIC: if loss_cfgs.CLS_LOSS == 'BinaryCrossEntropy': rcnn_cls_flat = rcnn_cls.view(-1, self.num_class) batch_loss_cls = F.binary_cross_entropy(torch.sigmoid(rcnn_cls_flat), rcnn_cls_labels.float(), reduction='none') cls_valid_mask = (rcnn_cls_labels >= 0).float() rcnn_loss_cls = (batch_loss_cls * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) elif loss_cfgs.CLS_LOSS == 'CrossEntropy': batch_loss_cls = F.cross_entropy(rcnn_cls, rcnn_cls_labels, reduction='none', ignore_index=-1) cls_valid_mask = (rcnn_cls_labels >= 0).float() rcnn_loss_cls = (batch_loss_cls * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) else: raise NotImplementedError rcnn_loss_cls = rcnn_loss_cls * loss_cfgs.LOSS_WEIGHTS['rcnn_cls_weight'] tb_dict = {'rcnn_loss_cls': rcnn_loss_cls.item()} return rcnn_loss_cls, tb_dict else: gt_cls_of_rois = forward_ret_dict['gt_cls_of_rois'].view(-1) one_hot_target = torch.zeros( [rcnn_cls_labels.shape[0], self.num_class + 1], dtype=rcnn_cls_labels.dtype, device=rcnn_cls_labels.device ) one_hot_target.scatter_(-1, gt_cls_of_rois.unsqueeze(-1).long(), rcnn_cls_labels.unsqueeze(-1)) one_hot_target = one_hot_target[:, 1:] zero_mask = one_hot_target == 0 one_hot_target[zero_mask] = 0.00001 if loss_cfgs.CLS_LOSS == 'BinaryCrossEntropy': rcnn_cls_flat = rcnn_cls.view(-1, self.num_class) batch_loss_cls = F.binary_cross_entropy(torch.sigmoid(rcnn_cls_flat), one_hot_target.float(), reduction='none') cls_valid_mask = (rcnn_cls_labels >= 0).float() rcnn_loss_cls = (batch_loss_cls * cls_valid_mask.unsqueeze(-1)).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) elif loss_cfgs.CLS_LOSS == 'CrossEntropy': batch_loss_cls = F.cross_entropy(rcnn_cls, one_hot_target, reduction='none', ignore_index=-1) cls_valid_mask = (rcnn_cls_labels >= 0).float() rcnn_loss_cls = (batch_loss_cls * cls_valid_mask.unsqueeze(-1)).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) else: raise NotImplementedError rcnn_loss_cls = rcnn_loss_cls * loss_cfgs.LOSS_WEIGHTS['rcnn_cls_weight'] tb_dict = {'rcnn_loss_cls': rcnn_loss_cls.item()} return rcnn_loss_cls, tb_dict
46.786611
139
0.619657
3d205b24765ee134c9ae212d25b9fd808a845364
3,351
py
Python
google-spiders/g4spiders/google_email_spider_4/google_email_spider_4/pipelines.py
mtaziz/email-scraper-using-google-with-linkedin
8fd3fcdec8815bc5333272c9abfc1983412cdedc
[ "MIT" ]
3
2018-08-26T09:08:01.000Z
2020-05-05T19:17:21.000Z
google-spiders/g4spiders/google_email_spider_4/google_email_spider_4/pipelines.py
mtaziz/email-scraper-using-google-x-ray-search-with-linkedin
8fd3fcdec8815bc5333272c9abfc1983412cdedc
[ "MIT" ]
null
null
null
google-spiders/g4spiders/google_email_spider_4/google_email_spider_4/pipelines.py
mtaziz/email-scraper-using-google-x-ray-search-with-linkedin
8fd3fcdec8815bc5333272c9abfc1983412cdedc
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import sys from scrapy.exceptions import DropItem import requests from scrapy.utils.project import get_project_settings from scrapy import signals from ..items import * from scrapy.exporters import JsonLinesItemExporter from scrapy.conf import settings SETTINGS = get_project_settings import csv import re from collections import OrderedDict from pprint import pprint class GoogleSpiderPipeline(object): def process_item(self, item, spider): google_title = item['G_Title'] company = re.search(r'(?<= at )(.*)', google_title) if company: item['G_WorkAt'] = company.group(0) else: item['G_WorkAt'] = '' address = re.search(r"\((.*?)\)", google_title) if address: item['G_Address'] = address.group(0) else: item['G_Address'] = '' # Sample Data: {'phd_data': 'Elena Kostova, PhD | Professioneel profiel - LinkedIn'} phd_info = re.search(r'(\bPhD\b)|(Ph.D)', google_title) if phd_info: item['G_PhD'] = phd_info.group(0) # phd_info_list.append(phd) else: item['G_PhD'] = '' # phd_info_list.append(phd) title_clean = google_title\ .replace(item['G_Address'], '')\ .replace('at {0}'.format(company), '')\ .replace('(', '').replace(')', '')\ .replace('| Professional Profile - LinkedIn', '')\ .replace(' | LinkedIn', '').replace(' on LinkedIn', '')\ .replace('{}'.format(item['G_PhD']), '') title_clean = title_clean.split('|')[0] title_clean = title_clean.split(',')[0] item['G_Name_In_Title'] = title_clean pprint("PhD or Ph.DTaken Off____________{0}".format(item['G_PhD'])) linkedin_url = item['G_LinkedIn_Url'] if "/pulse/" in linkedin_url or "/learning/" in linkedin_url: item['G_LinkedIn_Url_For_Name'] = '' else: item['G_LinkedIn_Url_For_Name'] = linkedin_url name_in_linkedin_url_split = item['G_LinkedIn_Url_For_Name'].rsplit( '-', 1)[0] name_in_linkedin_url_split = ( ' '.join((name_in_linkedin_url_split.split('/in/')[-1].split('-')))).title() item['G_Name_In_LinkedIn_Url'] = name_in_linkedin_url_split name_matched = re.search( item['G_Name_In_LinkedIn_Url'], item['G_Name_In_Title'], re.IGNORECASE) if name_matched: item['G_Matched_Name'] = name_matched.group(0) pprint("Name Found: \n {0} \n".format(name_matched)) else: item['G_Matched_Name'] = '' if not item['G_Matched_Name']: name_string_in_title = item['G_Name_In_Title'] name_string_in_title = name_string_in_title.split(' ') d = re.findall(r"(?=(" + '|'.join(name_string_in_title) + r"))", item['G_Name_In_LinkedIn_Url'], re.IGNORECASE) item['G_Matched_Name'] = ' '.join(filter(None, d)).title() else: item['G_Matched_Name'] = item['G_Matched_Name'] = name_matched.group( 0) return item
36.032258
92
0.595046
0465d3032e22baab66c483388e2eaf5abf89dd39
1,444
py
Python
setup.py
cimbi/pyacq
b320251f1cf899c1d2cc4fddd5596a1ae835b39d
[ "BSD-3-Clause" ]
20
2015-12-18T05:52:04.000Z
2021-05-22T05:12:24.000Z
setup.py
cimbi/pyacq
b320251f1cf899c1d2cc4fddd5596a1ae835b39d
[ "BSD-3-Clause" ]
72
2015-07-17T19:43:36.000Z
2021-09-14T07:37:30.000Z
setup.py
cimbi/pyacq
b320251f1cf899c1d2cc4fddd5596a1ae835b39d
[ "BSD-3-Clause" ]
14
2015-06-19T12:07:25.000Z
2021-08-16T14:44:42.000Z
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import os import pyacq long_description = """ Pyacq is a simple, pure-Python framework for distributed data acquisition and stream processing. Its primary use cases are for analog signals, digital signals, video, and events. Pyacq uses ZeroMQ to stream data between distributed threads, processes, and machines to build more complex and scalable acquisition systems. """ setup( name = "pyacq", version = pyacq.__version__, packages = [pkg for pkg in find_packages() if pkg.startswith('pyacq')], install_requires=[ 'numpy', 'pyzmq', 'pyqtgraph', #'blosc', # optional; causes install failure on appveyor #'msgpack-python', ], author = "S.Garcia", author_email = "sam.garcia.die@gmail.com", description = "Simple Framework for data acquisition (signal, video) in pure python.", long_description = long_description, license = "BSD", url='https://github.com/pyacq/pyacq', classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering'] )
30.723404
90
0.625346
ad6a6d4ae6b0757b332f88a0be2adc9c663dd7fc
2,146
py
Python
tahoe_idp/magiclink_views.py
appsembler/tahoe-auth0
f3b870b1626d76bab4e9e03c6c4c6ecdc226ffb7
[ "MIT" ]
null
null
null
tahoe_idp/magiclink_views.py
appsembler/tahoe-auth0
f3b870b1626d76bab4e9e03c6c4c6ecdc226ffb7
[ "MIT" ]
10
2021-12-03T14:03:52.000Z
2022-03-21T11:07:50.000Z
tahoe_idp/magiclink_views.py
appsembler/tahoe-auth0
f3b870b1626d76bab4e9e03c6c4c6ecdc226ffb7
[ "MIT" ]
null
null
null
import logging from django.conf import settings from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.generic import TemplateView, View from tahoe_idp.helpers import is_valid_redirect_url from tahoe_idp.magiclink_helpers import create_magiclink from tahoe_idp.magiclink_utils import get_url_path from tahoe_idp.models import MagicLink log = logging.getLogger(__name__) @method_decorator(never_cache, name='dispatch') class LoginVerify(TemplateView): def get(self, request, *args, **kwargs): token = request.GET['token'] username = request.GET['username'] user = authenticate(request, token=token, username=username) if not user: redirect_url = get_url_path(settings.MAGICLINK_LOGIN_FAILED_REDIRECT) return HttpResponseRedirect(redirect_url) login(request, user) log.info('Login successful for {username}'.format(username=username)) response = self.login_complete_action() return response def login_complete_action(self) -> HttpResponseRedirect: token = self.request.GET.get('token') magiclink = MagicLink.objects.get(token=token) return HttpResponseRedirect(magiclink.redirect_url or settings.LOGIN_REDIRECT_URL) class StudioLoginAPIView(View): @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(StudioLoginAPIView, self).dispatch(request, *args, **kwargs) def get(self, request): username = request.user.username next_url = request.GET.get('next') if next_url and not is_valid_redirect_url(next_url, request.get_host(), request.is_secure()): next_url = None magic_link = create_magiclink(username=username, request=request, redirect_url=next_url) url = magic_link.generate_url(request) return redirect(url, permanent=False)
36.372881
101
0.746039
98779333f1d104da66e410a8d408e49877e716ed
659
py
Python
dms/manage.py
tusharbohara/document-management-system
d57251b2425283c9f628de2550035dd18c79e7b1
[ "MIT" ]
null
null
null
dms/manage.py
tusharbohara/document-management-system
d57251b2425283c9f628de2550035dd18c79e7b1
[ "MIT" ]
null
null
null
dms/manage.py
tusharbohara/document-management-system
d57251b2425283c9f628de2550035dd18c79e7b1
[ "MIT" ]
null
null
null
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dms.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
28.652174
73
0.676783
6298eeeb0f70d0b9e3b9874ad67043cf4eddb920
18,689
py
Python
cirq/linalg/decompositions.py
philiptmassey/Cirq
b8b457c2fc484d76bf8a82a73f6ecc11756229a6
[ "Apache-2.0" ]
null
null
null
cirq/linalg/decompositions.py
philiptmassey/Cirq
b8b457c2fc484d76bf8a82a73f6ecc11756229a6
[ "Apache-2.0" ]
null
null
null
cirq/linalg/decompositions.py
philiptmassey/Cirq
b8b457c2fc484d76bf8a82a73f6ecc11756229a6
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility methods for breaking matrices into useful pieces.""" from typing import Set, NamedTuple # pylint: disable=unused-import from typing import Callable, List, Tuple, TypeVar import math import cmath import numpy as np from cirq import value from cirq.linalg import combinators, diagonalize, predicates from cirq.linalg.tolerance import Tolerance T = TypeVar('T') def _phase_matrix(angle: float) -> np.ndarray: return np.diag([1, np.exp(1j * angle)]) def _rotation_matrix(angle: float) -> np.ndarray: c, s = np.cos(angle), np.sin(angle) return np.array([[c, -s], [s, c]]) def deconstruct_single_qubit_matrix_into_angles( mat: np.ndarray) -> Tuple[float, float, float]: """Breaks down a 2x2 unitary into more useful ZYZ angle parameters. Args: mat: The 2x2 unitary matrix to break down. Returns: A tuple containing the amount to phase around Z, then rotate around Y, then phase around Z (all in radians). """ # Anti-cancel left-vs-right phase along top row. right_phase = cmath.phase(mat[0, 1] * np.conj(mat[0, 0])) + math.pi mat = np.dot(mat, _phase_matrix(-right_phase)) # Cancel top-vs-bottom phase along left column. bottom_phase = cmath.phase(mat[1, 0] * np.conj(mat[0, 0])) mat = np.dot(_phase_matrix(-bottom_phase), mat) # Lined up for a rotation. Clear the off-diagonal cells with one. rotation = math.atan2(abs(mat[1, 0]), abs(mat[0, 0])) mat = np.dot(_rotation_matrix(-rotation), mat) # Cancel top-left-vs-bottom-right phase. diagonal_phase = cmath.phase(mat[1, 1] * np.conj(mat[0, 0])) # Note: Ignoring global phase. return right_phase + diagonal_phase, rotation * 2, bottom_phase def _group_similar(items: List[T], comparer: Callable[[T, T], bool]) -> List[List[T]]: """Combines similar items into groups. Args: items: The list of items to group. comparer: Determines if two items are similar. Returns: A list of groups of items. """ groups = [] # type: List[List[T]] used = set() # type: Set[int] for i in range(len(items)): if i not in used: group = [items[i]] for j in range(i + 1, len(items)): if j not in used and comparer(items[i], items[j]): used.add(j) group.append(items[j]) groups.append(group) return groups def _perp_eigendecompose(matrix: np.ndarray, tolerance: Tolerance ) -> Tuple[np.array, List[np.ndarray]]: """An eigendecomposition that ensures eigenvectors are perpendicular. numpy.linalg.eig doesn't guarantee that eigenvectors from the same eigenspace will be perpendicular. This method uses Gram-Schmidt to recover a perpendicular set. It further checks that all eigenvectors are perpendicular and raises an ArithmeticError otherwise. Args: matrix: The matrix to decompose. tolerance: Thresholds for determining whether eigenvalues are from the same eigenspace and whether eigenvectors are perpendicular. Returns: The eigenvalues and column eigenvectors. The i'th eigenvalue is associated with the i'th column eigenvector. Raises: ArithmeticError: Failed to find perpendicular eigenvectors. """ vals, cols = np.linalg.eig(matrix) vecs = [cols[:, i] for i in range(len(cols))] # Convert list of row arrays to list of column arrays. for i in range(len(vecs)): vecs[i] = np.reshape(vecs[i], (len(vecs[i]), vecs[i].ndim)) # Group by similar eigenvalue. n = len(vecs) groups = _group_similar( list(range(n)), lambda k1, k2: tolerance.all_close(vals[k1], vals[k2])) # Remove overlap between eigenvectors with the same eigenvalue. for g in groups: q, _ = np.linalg.qr(np.hstack([vecs[i] for i in g])) for i in range(len(g)): vecs[g[i]] = q[:, i] # Ensure no eigenvectors overlap. for i in range(len(vecs)): for j in range(i + 1, len(vecs)): if not tolerance.all_near_zero(np.dot(np.conj(vecs[i].T), vecs[j])): raise ArithmeticError('Eigenvectors overlap.') return vals, vecs def map_eigenvalues( matrix: np.ndarray, func: Callable[[complex], complex], tolerance: Tolerance = Tolerance.DEFAULT ) -> np.ndarray: """Applies a function to the eigenvalues of a matrix. Given M = sum_k a_k |v_k><v_k|, returns f(M) = sum_k f(a_k) |v_k><v_k|. Args: matrix: The matrix to modify with the function. func: The function to apply to the eigenvalues of the matrix. tolerance: Thresholds used when separating eigenspaces. Returns: The transformed matrix. """ vals, vecs = _perp_eigendecompose(matrix, tolerance) pieces = [np.outer(vec, np.conj(vec.T)) for vec in vecs] out_vals = np.vectorize(func)(vals.astype(complex)) total = np.zeros(shape=matrix.shape) for piece, val in zip(pieces, out_vals): total = np.add(total, piece * val) return total def kron_factor_4x4_to_2x2s( matrix: np.ndarray, tolerance: Tolerance = Tolerance.DEFAULT ) -> Tuple[complex, np.ndarray, np.ndarray]: """Splits a 4x4 matrix U = kron(A, B) into A, B, and a global factor. Requires the matrix to be the kronecker product of two 2x2 unitaries. Requires the matrix to have a non-zero determinant. Args: matrix: The 4x4 unitary matrix to factor. tolerance: Acceptable numeric error thresholds. Returns: A scalar factor and a pair of 2x2 unit-determinant matrices. The kronecker product of all three is equal to the given matrix. Raises: ValueError: The given matrix can't be tensor-factored into 2x2 pieces. """ # Use the entry with the largest magnitude as a reference point. a, b = max( ((i, j) for i in range(4) for j in range(4)), key=lambda t: abs(matrix[t])) # Extract sub-factors touching the reference cell. f1 = np.zeros((2, 2), dtype=np.complex128) f2 = np.zeros((2, 2), dtype=np.complex128) for i in range(2): for j in range(2): f1[(a >> 1) ^ i, (b >> 1) ^ j] = matrix[a ^ (i << 1), b ^ (j << 1)] f2[(a & 1) ^ i, (b & 1) ^ j] = matrix[a ^ i, b ^ j] # Rescale factors to have unit determinants. f1 /= (np.sqrt(np.linalg.det(f1)) or 1) f2 /= (np.sqrt(np.linalg.det(f2)) or 1) # Determine global phase. g = matrix[a, b] / (f1[a >> 1, b >> 1] * f2[a & 1, b & 1]) if np.real(g) < 0: f1 *= -1 g = -g restored = g * combinators.kron(f1, f2) if np.any(np.isnan(restored)) or not tolerance.all_close(restored, matrix): raise ValueError("Can't factor into kronecker product.") return g, f1, f2 def so4_to_magic_su2s( mat: np.ndarray, tolerance: Tolerance = Tolerance.DEFAULT ) -> Tuple[np.ndarray, np.ndarray]: """Finds 2x2 special-unitaries A, B where mat = Mag.H @ kron(A, B) @ Mag. Mag is the magic basis matrix: 1 0 0 i 0 i 1 0 0 i -1 0 (times sqrt(0.5) to normalize) 1 0 0 -i Args: mat: A real 4x4 orthogonal matrix. tolerance: Per-matrix-entry tolerance on equality. Returns: A pair (A, B) of matrices in SU(2) such that Mag.H @ kron(A, B) @ Mag is approximately equal to the given matrix. Raises: ValueError: Bad matrix. ArithmeticError: Failed to perform the decomposition to desired tolerance. """ if mat.shape != (4, 4) or not predicates.is_special_orthogonal(mat, tolerance): raise ValueError('mat must be 4x4 special orthogonal.') magic = np.array([[1, 0, 0, 1j], [0, 1j, 1, 0], [0, 1j, -1, 0], [1, 0, 0, -1j]]) * np.sqrt(0.5) ab = combinators.dot(magic, mat, np.conj(magic.T)) _, a, b = kron_factor_4x4_to_2x2s(ab, tolerance) # Check decomposition against desired tolerance. reconstructed = combinators.dot(np.conj(magic.T), combinators.kron(a, b), magic) if not tolerance.all_close(reconstructed, mat): raise ArithmeticError('Failed to decompose to desired tolerance.') return a, b @value.value_equality class KakDecomposition: """A convenient description of an arbitrary two-qubit operation. Any two qubit operation U can be decomposed into the form U = g · (a1 ⊗ a0) · exp(i·(x·XX + y·YY + z·ZZ)) · (b1 ⊗ b0) This class stores g, (b0, b1), (x, y, z), and (a0, a1). Attributes: global_phase: g from the above equation. single_qubit_operations_before: b0, b1 from the above equation. interaction_coefficients: x, y, z from the above equation. single_qubit_operations_after: a0, a1 from the above equation. References: 'An Introduction to Cartan's KAK Decomposition for QC Programmers' https://arxiv.org/abs/quant-ph/0507171 """ def __init__(self, *, global_phase: complex, single_qubit_operations_before: Tuple[np.ndarray, np.ndarray], interaction_coefficients: Tuple[float, float, float], single_qubit_operations_after: Tuple[np.ndarray, np.ndarray]): """Initializes a decomposition for a two-qubit operation U. U = g · (a1 ⊗ a0) · exp(i·(x·XX + y·YY + z·ZZ)) · (b1 ⊗ b0) Args: global_phase: g from the above equation. single_qubit_operations_before: b0, b1 from the above equation. interaction_coefficients: x, y, z from the above equation. single_qubit_operations_after: a0, a1 from the above equation. """ self.global_phase = global_phase self.single_qubit_operations_before = single_qubit_operations_before self.interaction_coefficients = interaction_coefficients self.single_qubit_operations_after = single_qubit_operations_after def _value_equality_values_(self): def flatten(x): return tuple(tuple(e.flat) for e in x) return (type(KakDecomposition), self.global_phase, tuple(self.interaction_coefficients), flatten(self.single_qubit_operations_before), flatten(self.single_qubit_operations_after)) def __repr__(self): return ( 'cirq.KakDecomposition(\n' ' interaction_coefficients={!r},\n' ' single_qubit_operations_before=(\n' ' {},\n' ' {},\n' ' ),\n' ' single_qubit_operations_after=(\n' ' {},\n' ' {},\n' ' ),\n' ' global_phase={!r})' ).format( self.interaction_coefficients, _numpy_array_repr(self.single_qubit_operations_before[0]), _numpy_array_repr(self.single_qubit_operations_before[1]), _numpy_array_repr(self.single_qubit_operations_after[0]), _numpy_array_repr(self.single_qubit_operations_after[1]), self.global_phase, ) def _unitary_(self): """Returns the decomposition's two-qubit unitary matrix. U = g · (a1 ⊗ a0) · exp(i·(x·XX + y·YY + z·ZZ)) · (b1 ⊗ b0) """ before = np.kron(*self.single_qubit_operations_before) after = np.kron(*self.single_qubit_operations_after) def interaction_matrix(m: np.ndarray, c: float) -> np.ndarray: return map_eigenvalues(np.kron(m, m), lambda v: np.exp(1j * v * c)) x, y, z = self.interaction_coefficients x_mat = np.array([[0, 1], [1, 0]]) y_mat = np.array([[0, -1j], [1j, 0]]) z_mat = np.array([[1, 0], [0, -1]]) return self.global_phase * combinators.dot( after, interaction_matrix(z_mat, z), interaction_matrix(y_mat, y), interaction_matrix(x_mat, x), before) def _numpy_array_repr(arr: np.ndarray) -> str: return 'np.array({!r})'.format(arr.tolist()) def kak_canonicalize_vector(x: float, y: float, z: float) -> KakDecomposition: """Canonicalizes an XX/YY/ZZ interaction by swap/negate/shift-ing axes. Args: x: The strength of the XX interaction. y: The strength of the YY interaction. z: The strength of the ZZ interaction. Returns: The canonicalized decomposition, with vector coefficients (x2, y2, z2) satisfying: 0 ≤ abs(z2) ≤ y2 ≤ x2 ≤ π/4 z2 ≠ -π/4 Guarantees that the implied output matrix: g · (a1 ⊗ a0) · exp(i·(x2·XX + y2·YY + z2·ZZ)) · (b1 ⊗ b0) is approximately equal to the implied input matrix: exp(i·(x·XX + y·YY + z·ZZ)) """ phase = [complex(1)] # Accumulated global phase. left = [np.eye(2)] * 2 # Per-qubit left factors. right = [np.eye(2)] * 2 # Per-qubit right factors. v = [x, y, z] # Remaining XX/YY/ZZ interaction vector. # These special-unitary matrices flip the X, Y, and Z axes respectively. flippers = [ np.array([[0, 1], [1, 0]]) * 1j, np.array([[0, -1j], [1j, 0]]) * 1j, np.array([[1, 0], [0, -1]]) * 1j ] # Each of these special-unitary matrices swaps two the roles of two axes. # The matrix at index k swaps the *other two* axes (e.g. swappers[1] is a # Hadamard operation that swaps X and Z). swappers = [ np.array([[1, -1j], [1j, -1]]) * 1j * np.sqrt(0.5), np.array([[1, 1], [1, -1]]) * 1j * np.sqrt(0.5), np.array([[0, 1 - 1j], [1 + 1j, 0]]) * 1j * np.sqrt(0.5) ] # Shifting strength by ½π is equivalent to local ops (e.g. exp(i½π XX)∝XX). def shift(k, step): v[k] += step * np.pi / 2 phase[0] *= 1j**step right[0] = combinators.dot(flippers[k]**(step % 4), right[0]) right[1] = combinators.dot(flippers[k]**(step % 4), right[1]) # Two negations is equivalent to temporarily flipping along the other axis. def negate(k1, k2): v[k1] *= -1 v[k2] *= -1 phase[0] *= -1 s = flippers[3 - k1 - k2] # The other axis' flipper. left[1] = combinators.dot(left[1], s) right[1] = combinators.dot(s, right[1]) # Swapping components is equivalent to temporarily swapping the two axes. def swap(k1, k2): v[k1], v[k2] = v[k2], v[k1] s = swappers[3 - k1 - k2] # The other axis' swapper. left[0] = combinators.dot(left[0], s) left[1] = combinators.dot(left[1], s) right[0] = combinators.dot(s, right[0]) right[1] = combinators.dot(s, right[1]) # Shifts an axis strength into the range (-π/4, π/4]. def canonical_shift(k): while v[k] <= -np.pi / 4: shift(k, +1) while v[k] > np.pi / 4: shift(k, -1) # Sorts axis strengths into descending order by absolute magnitude. def sort(): if abs(v[0]) < abs(v[1]): swap(0, 1) if abs(v[1]) < abs(v[2]): swap(1, 2) if abs(v[0]) < abs(v[1]): swap(0, 1) # Get all strengths to (-¼π, ¼π] in descending order by absolute magnitude. canonical_shift(0) canonical_shift(1) canonical_shift(2) sort() # Move all negativity into z. if v[0] < 0: negate(0, 2) if v[1] < 0: negate(1, 2) canonical_shift(2) return KakDecomposition( global_phase=phase[0], single_qubit_operations_after=(left[1], left[0]), interaction_coefficients=(v[0], v[1], v[2]), single_qubit_operations_before=(right[1], right[0])) def kak_decomposition( mat: np.ndarray, tolerance: Tolerance = Tolerance.DEFAULT ) -> KakDecomposition: """Decomposes a 2-qubit unitary into 1-qubit ops and XX/YY/ZZ interactions. Args: mat: The 4x4 unitary matrix to decompose. tolerance: Per-matrix-entry tolerance on equality. Returns: A `cirq.KakDecomposition` canonicalized such that the interaction coefficients x, y, z satisfy: 0 ≤ abs(z) ≤ y ≤ x ≤ π/4 z ≠ -π/4 Raises: ValueError: Bad matrix. ArithmeticError: Failed to perform the decomposition. References: 'An Introduction to Cartan's KAK Decomposition for QC Programmers' https://arxiv.org/abs/quant-ph/0507171 """ magic = np.array([[1, 0, 0, 1j], [0, 1j, 1, 0], [0, 1j, -1, 0], [1, 0, 0, -1j]]) * np.sqrt(0.5) gamma = np.array([[1, 1, 1, 1], [1, 1, -1, -1], [-1, 1, -1, 1], [1, -1, -1, 1]]) * 0.25 # Diagonalize in magic basis. left, d, right = ( diagonalize.bidiagonalize_unitary_with_special_orthogonals( combinators.dot(np.conj(magic.T), mat, magic), tolerance)) # Recover pieces. a1, a0 = so4_to_magic_su2s(left.T, tolerance) b1, b0 = so4_to_magic_su2s(right.T, tolerance) w, x, y, z = gamma.dot(np.vstack(np.angle(d))).flatten() g = np.exp(1j * w) # Canonicalize. inner_cannon = kak_canonicalize_vector(x, y, z) b1 = np.dot(inner_cannon.single_qubit_operations_before[0], b1) b0 = np.dot(inner_cannon.single_qubit_operations_before[1], b0) a1 = np.dot(a1, inner_cannon.single_qubit_operations_after[0]) a0 = np.dot(a0, inner_cannon.single_qubit_operations_after[1]) return KakDecomposition( interaction_coefficients=inner_cannon.interaction_coefficients, global_phase=g * inner_cannon.global_phase, single_qubit_operations_before=(b1, b0), single_qubit_operations_after=(a1, a0))
34.867537
80
0.598855
e742898ad016572f974a6d02a833b142a04b9400
3,307
py
Python
software/tests/test_M01_covariances_correlations.py
meliao/MetaXcan
bb15480815a5c3a7ffcd0a3caa4116e427a5ef92
[ "MIT" ]
null
null
null
software/tests/test_M01_covariances_correlations.py
meliao/MetaXcan
bb15480815a5c3a7ffcd0a3caa4116e427a5ef92
[ "MIT" ]
null
null
null
software/tests/test_M01_covariances_correlations.py
meliao/MetaXcan
bb15480815a5c3a7ffcd0a3caa4116e427a5ef92
[ "MIT" ]
null
null
null
#!/usr/bin/env python import unittest import sys import shutil import os import re import gzip if "DEBUG" in sys.argv: sys.path.insert(0, "..") sys.path.insert(0, "../../") sys.path.insert(0, ".") sys.argv.remove("DEBUG") import metax.Formats as Formats from M01_covariances_correlations import ProcessWeightDB class Dummy(object): pass def buildDummyArgs(root): dummy = Dummy() dummy.verbosity = 10 dummy.weight_db = os.path.join(root, "test.db") dummy.input_folder = os.path.join(root, "filtered_dosage") dummy.covariance_output = os.path.join(root, "covariance/cov.txt.gz") dummy.correlation_output = None dummy.input_format = Formats.PrediXcan dummy.min_maf_filter = None dummy.max_maf_filter = None dummy.max_snps_in_gene = None return dummy def setupDataForArgs(args, root): if os.path.exists(root): shutil.rmtree(root) shutil.copytree("tests/_td/filtered_dosage", os.path.join(root,"filtered_dosage")) shutil.copy("tests/_td/test.db", root) def cleanUpDataForArgs(root): shutil.rmtree(root) class TestM01(unittest.TestCase): def testProcessPrerequisitesnoArgConstructor(self): with self.assertRaises(AttributeError): dummy = Dummy() p = ProcessWeightDB(dummy) def testProcessPrerequisitesConstructor(self): dummy = buildDummyArgs("_test") p = ProcessWeightDB(dummy) self.assertEqual(p.weight_db, "test.db") self.assertEqual(p.db_path, "_test/test.db") self.assertEqual(p.data_folder, "_test/filtered_dosage") self.assertEqual(p.correlation_output, None) self.assertEqual(p.covariance_output, "_test/covariance/cov.txt.gz") self.assertEqual(p.input_format, Formats.PrediXcan) self.assertEqual(p.min_maf_filter, None) self.assertEqual(p.max_maf_filter, None) def testProcessPrerequisitesConstructorDefaultCovariance(self): dummy = buildDummyArgs("_test") dummy.covariance_output = None p = ProcessWeightDB(dummy) self.assertEqual(p.covariance_output, "intermediate/cov/test.cov.txt.gz") def testProcessWeightDBRun(self): dummy = buildDummyArgs("_test") setupDataForArgs(dummy, "_test") p = ProcessWeightDB(dummy) try: p.run() except: self.assertEqual(False, True, "Prerequisites should have run without error") with gzip.open(p.covariance_output) as f: expected_lines = ["GENE RSID1 RSID2 VALUE", "A rs1 rs1 1.0", "A rs1 rs2 0.0", "A rs1 rs3 -0.3333333333333333", "A rs2 rs2 0.0", "A rs2 rs3 0.0", "A rs3 rs3 0.3333333333333333", "B rs4 rs4 0.0", "B rs4 rs5 0.0", "B rs5 rs5 0.3333333333333333", "C rs6 rs6 1.0", "D rs1 rs1 1.0"] for i,expected_line in enumerate(expected_lines): actual_line = f.readline().decode().strip() self.assertEqual(actual_line, expected_line) cleanUpDataForArgs("_test")
34.810526
88
0.61264
646318eeff46ac1f2a86ba08aba7c48787587e2e
13,938
py
Python
client/build/build_patch_info.py
AustralianDisabilityLimited/MultiversePlatform
7e1aad33d48b9e47f3db2ca638cb57592336ddb7
[ "MIT" ]
33
2015-02-16T02:52:08.000Z
2022-02-18T08:46:32.000Z
client/build/build_patch_info.py
bensku/MultiversePlatform
7e1aad33d48b9e47f3db2ca638cb57592336ddb7
[ "MIT" ]
1
2017-09-09T18:50:23.000Z
2020-12-29T18:13:56.000Z
client/build/build_patch_info.py
bensku/MultiversePlatform
7e1aad33d48b9e47f3db2ca638cb57592336ddb7
[ "MIT" ]
31
2015-02-07T16:20:24.000Z
2022-02-23T15:02:43.000Z
# # The Multiverse Platform is made available under the MIT License. # # Copyright (c) 2012 The Multiverse Foundation # # 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 sha import os import sys from patch_tool import * def add_binary_assets(asset_tree, config): asset_tree.add_exclude("Worlds") asset_tree.add_ignore("patcher.exe") asset_tree.add_ignore("repair.exe") asset_tree.add_ignore("mv.patch") asset_tree.add_ignore("patcher.log") asset_tree.add_ignore(".*MultiverseClient.vshost.exe") asset_tree.add_ignore("custom") asset_tree.add_ignore("custom/.*") asset_tree.add_asset_path("build/patch_version.txt", "patch_version.txt") # asset_tree.add_asset_path("bin/Config/world_settings_sample.xml", "Config/world_settings_sample.xml") asset_tree.add_asset_path("bin/DefaultLogConfig.xml", "DefaultLogConfig.xml") asset_tree.add_asset_path("bin/Html/ClientError.css", "Html/ClientError.css") asset_tree.add_asset_path("bin/Html/logo.gif", "Html/logo.gif") asset_tree.add_asset_path("bin/Html/bad_media.htm", "Html/bad_media.htm") asset_tree.add_asset_path("bin/Html/bad_script.htm", "Html/bad_script.htm") asset_tree.add_asset_path("bin/Html/unable_connect_tcp_world.htm", "Html/unable_connect_tcp_world.htm") asset_tree.add_asset_path("bin/MultiverseImageset.xml", "MultiverseImageset.xml") asset_tree.add_asset_path("bin/logopicture.jpg", "logopicture.jpg") asset_tree.add_asset_path("bin/mvloadscreen.bmp", "mvloadscreen.bmp") # asset_tree.add_asset_path("bin/%s/libeay32.dll" % config, "bin/libeay32.dll") # asset_tree.add_asset_path("bin/%s/ssleay32.dll" % config, "bin/ssleay32.dll") # asset_tree.add_asset_path("bin/%s/dwTVC.exe" % config, "bin/dwTVC.exe") asset_tree.add_asset_path("bin/Imageset.xsd", "bin/Imageset.xsd") asset_tree.add_asset_path("bin/%s/Axiom.Engine.dll" % config, "bin/Axiom.Engine.dll") asset_tree.add_asset_path("bin/%s/Axiom.MathLib.dll" % config, "bin/Axiom.MathLib.dll") asset_tree.add_asset_path("bin/%s/Axiom.Platforms.Win32.dll" % config, "bin/Axiom.Platforms.Win32.dll") asset_tree.add_asset_path("bin/%s/Axiom.Plugins.CgProgramManager.dll" % config, "bin/Axiom.Plugins.CgProgramManager.dll") asset_tree.add_asset_path("bin/%s/Axiom.Plugins.ParticleFX.dll" % config, "bin/Axiom.Plugins.ParticleFX.dll") asset_tree.add_asset_path("bin/%s/Axiom.RenderSystems.DirectX9.dll" % config, "bin/Axiom.RenderSystems.DirectX9.dll") # asset_tree.add_asset_path("bin/%s/Axiom.RenderSystems.OpenGL.dll" % config, "bin/Axiom.RenderSystems.OpenGL.dll") asset_tree.add_asset_path("bin/%s/Axiom.SceneManagers.Multiverse.dll" % config, "bin/Axiom.SceneManagers.Multiverse.dll") # asset_tree.add_asset_path("bin/%s/Axiom.SceneManagers.Octree.dll" % config, "bin/Axiom.SceneManagers.Octree.dll") asset_tree.add_asset_path("bin/%s/HeightfieldGenerator.dll" % config, "bin/HeightfieldGenerator.dll") asset_tree.add_asset_path("bin/%s/LogUtil.dll" % config, "bin/LogUtil.dll") asset_tree.add_asset_path("bin/%s/TextureFetcher.dll" % config, "bin/TextureFetcher.dll") asset_tree.add_asset_path("bin/%s/Multiverse.AssetRepository.dll" % config, "bin/Multiverse.AssetRepository.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Base.dll" % config, "bin/Multiverse.Base.dll") asset_tree.add_asset_path("bin/%s/Multiverse.CollisionLib.dll" % config, "bin/Multiverse.CollisionLib.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Config.dll" % config, "bin/Multiverse.Config.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Generator.dll" % config, "bin/Multiverse.Generator.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Gui.dll" % config, "bin/Multiverse.Gui.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Interface.dll" % config, "bin/Multiverse.Interface.dll") asset_tree.add_asset_path("bin/%s/Multiverse.MathLib.dll" % config, "bin/Multiverse.MathLib.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Movie.dll" % config, "bin/Multiverse.Movie.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Network.dll" % config, "bin/Multiverse.Network.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Patcher.dll" % config, "bin/Multiverse.Patcher.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Serialization.dll" % config, "bin/Multiverse.Serialization.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Utility.dll" % config, "bin/Multiverse.Utility.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Voice.dll" % config, "bin/Multiverse.Voice.dll") asset_tree.add_asset_path("bin/%s/Multiverse.Web.dll" % config, "bin/Multiverse.Web.dll") asset_tree.add_asset_path("bin/%s/MultiverseClient.exe" % config, "bin/MultiverseClient.exe") asset_tree.add_asset_path("bin/%s/DirectShowWrapper.dll" % config, "bin/DirectShowWrapper.dll") # Other projects that are part of the solution asset_tree.add_asset_path("../Lib/FMOD/FMODWrapper/bin/%s/FMODWrapper.dll" % config, "bin/FMODWrapper.dll") asset_tree.add_asset_path("../Lib/SpeexWrapper/bin/%s/SpeexWrapper.dll" % config, "bin/SpeexWrapper.dll") # Axiom dependencies asset_tree.add_asset_path("../Axiom/Dependencies/Managed/ICSharpCode.SharpZipLib.dll", "bin/ICSharpCode.SharpZipLib.dll") asset_tree.add_asset_path("../Axiom/Dependencies/Managed/Tao.Cg.dll", "bin/Tao.Cg.dll") asset_tree.add_asset_path("../Axiom/Dependencies/Managed/Tao.DevIl.dll", "bin/Tao.DevIl.dll") asset_tree.add_asset_path("../Axiom/Dependencies/Managed/Tao.Platform.Windows.dll", "bin/Tao.Platform.Windows.dll") asset_tree.add_asset_path("../Axiom/Dependencies/Managed/log4net.dll", "bin/log4net.dll") asset_tree.add_asset_path("../Axiom/Dependencies/Native/cg.dll", "bin/cg.dll") asset_tree.add_asset_path("../Axiom/Dependencies/Native/devil.dll", "bin/devil.dll") asset_tree.add_asset_path("../Axiom/Dependencies/Native/ilu.dll", "bin/ilu.dll") asset_tree.add_asset_path("../Axiom/Dependencies/Native/ilut.dll", "bin/ilut.dll") # MultiverseClient dependencies asset_tree.add_asset_path("Dependencies/Managed/IronMath.dll", "bin/IronMath.dll") asset_tree.add_asset_path("Dependencies/Managed/IronPython.dll", "bin/IronPython.dll") asset_tree.add_asset_path("Dependencies/Native/msvcp71.dll", "bin/msvcp71.dll") asset_tree.add_asset_path("Dependencies/Native/msvcr71.dll", "bin/msvcr71.dll") # SpeedTree dependencies asset_tree.add_asset_path("../Lib/SpeedTree/bin/Release/SpeedTreeWrapper.dll", "bin/SpeedTreeWrapper.dll") asset_tree.add_asset_path("../Lib/SpeedTree/bin/Release/SpeedTreeRT.dll", "bin/SpeedTreeRT.dll") # FMOD dependencies asset_tree.add_asset_path("../Lib/FMOD/fmodex.dll", "bin/fmodex.dll") # Speex dependencies asset_tree.add_asset_path("../Lib/Speex/bin/libspeex.dll", "bin/libspeex.dll") asset_tree.add_asset_path("../Lib/Speex/bin/libspeexdsp.dll", "bin/libspeexdsp.dll") # asset_tree.add_asset_path("bin/%s/OggVorbisWrapper.dll" % config, "bin/OggVorbisWrapper.dll") # asset_tree.add_asset_path("bin/%s/ogg.dll" % config, "bin/ogg.dll") # asset_tree.add_asset_path("bin/%s/vorbis.dll" % config, "bin/vorbis.dll") # asset_tree.add_asset_path("bin/%s/vorbisfile.dll" % config, "bin/vorbisfile.dll") # asset_tree.add_asset_path("bin/%s/wrap_oal.dll" % config, "bin/wrap_oal.dll") asset_tree.add_asset_path("Scripts/Animation.py", "Scripts/Animation.py") asset_tree.add_asset_path("Scripts/AnimationState.py", "Scripts/AnimationState.py") asset_tree.add_asset_path("Scripts/Camera.py", "Scripts/Camera.py") asset_tree.add_asset_path("Scripts/CharacterCreation.py", "Scripts/CharacterCreation.py") asset_tree.add_asset_path("Scripts/ClientAPI.py", "Scripts/ClientAPI.py") asset_tree.add_asset_path("Scripts/Compositor.py", "Scripts/Compositor.py") asset_tree.add_asset_path("Scripts/Decal.py", "Scripts/Decal.py") asset_tree.add_asset_path("Scripts/EditableImage.py", "Scripts/EditableImage.py") asset_tree.add_asset_path("Scripts/GPUProgramType.py", "Scripts/GPUProgramType.py") asset_tree.add_asset_path("Scripts/HardwareCaps.py", "Scripts/HardwareCaps.py") asset_tree.add_asset_path("Scripts/Input.py", "Scripts/Input.py") asset_tree.add_asset_path("Scripts/Interface.py", "Scripts/Interface.py") asset_tree.add_asset_path("Scripts/Light.py", "Scripts/Light.py") asset_tree.add_asset_path("Scripts/Material.py", "Scripts/Material.py") asset_tree.add_asset_path("Scripts/Model.py", "Scripts/Model.py") asset_tree.add_asset_path("Scripts/MorphAnimationTrack.py", "Scripts/MorphAnimationTrack.py") asset_tree.add_asset_path("Scripts/MorphKeyFrame.py", "Scripts/MorphKeyFrame.py") asset_tree.add_asset_path("Scripts/Network.py", "Scripts/Network.py") asset_tree.add_asset_path("Scripts/NodeAnimationTrack.py", "Scripts/NodeAnimationTrack.py") asset_tree.add_asset_path("Scripts/NodeKeyFrame.py", "Scripts/NodeKeyFrame.py") asset_tree.add_asset_path("Scripts/ParticleSystem.py", "Scripts/ParticleSystem.py") asset_tree.add_asset_path("Scripts/Pass.py", "Scripts/Pass.py") asset_tree.add_asset_path("Scripts/PropertyAnimationTrack.py", "Scripts/PropertyAnimationTrack.py") asset_tree.add_asset_path("Scripts/PropertyKeyFrame.py", "Scripts/PropertyKeyFrame.py") asset_tree.add_asset_path("Scripts/SceneNode.py", "Scripts/SceneNode.py") asset_tree.add_asset_path("Scripts/SceneQuery.py", "Scripts/SceneQuery.py") asset_tree.add_asset_path("Scripts/SoundSource.py", "Scripts/SoundSource.py") asset_tree.add_asset_path("Scripts/SystemStatus.py", "Scripts/SystemStatus.py") asset_tree.add_asset_path("Scripts/Technique.py", "Scripts/Technique.py") asset_tree.add_asset_path("Scripts/TextureUnit.py", "Scripts/TextureUnit.py") asset_tree.add_asset_path("Scripts/Voice.py", "Scripts/Voice.py") asset_tree.add_asset_path("Scripts/World.py", "Scripts/World.py") asset_tree.add_asset_path("Scripts/WorldObject.py", "Scripts/WorldObject.py") asset_tree.add_asset_path("build/licenses/Tao.Cg.License.txt", "doc/Tao.Cg.License.txt") asset_tree.add_asset_path("build/licenses/Tao.DevIl.License.txt", "doc/Tao.DevIl.License.txt") # asset_tree.add_asset_path("build/licenses/Tao.OpenGl.License.txt", "doc/Tao.OpenGl.License.txt") asset_tree.add_asset_path("build/licenses/Tao.Platform.Windows.License.txt", "doc/Tao.Platform.Windows.License.txt") asset_tree.add_asset_path("build/licenses/ICSharpCode.SharpZipLib.License.txt", "doc/ICSharpCode.SharpZipLib.License.txt") asset_tree.add_asset_path("build/licenses/apache2.0.txt", "doc/apache2.0.txt") asset_tree.add_asset_path("build/licenses/cpl1.0.txt", "doc/cpl1.0.txt") asset_tree.add_asset_path("build/licenses/gpl2.0.txt", "doc/gpl2.0.txt") asset_tree.add_asset_path("build/licenses/lgpl2.1.txt", "doc/lgpl2.1.txt") asset_tree.add_asset_path("build/licenses/nvidia_license.txt", "doc/nvidia_license.txt") # asset_tree.add_asset_path("build/licenses/ogg_license.txt", "doc/ogg_license.txt") asset_tree.add_asset_path("build/licenses/third_party_software.txt", "doc/third_party_software.txt") # asset_tree.add_asset_path("build/licenses/vorbis_license.txt", "doc/vorbis_license.txt") # Defaults dir_win = "c:/cygwin/home/multiverse/svn_tree/trunk/MultiverseClient/" dest_url = "http://update.multiverse.net/mvupdate.client/" patch_file = "client_patch.tar" config = "Debug" for arg in sys.argv: if arg.startswith('--dir='): dir_win = arg.split('=')[1] elif arg.startswith('--dest_url='): dest_url = arg.split('=')[1] elif arg.startswith('--patch_file='): patch_file = arg.split('=')[1] elif arg.startswith('--config='): config = arg.split('=')[1] elif arg == '--help': print '%s: [--dir=<source_dir>] [--dest_url=<update_url>] [--patch_file=<patch_file>] [--config=<configuration>]' % sys.argv[0] sys.exit() # Get the version patcher = "%sPatcher/bin/%s/patcher.exe" % (dir_win, config) # Default value of version, in case we can't run the patcher version = "1.1.2920.33098" try: output = os.popen(patcher + " --version").read() version = output.strip() except: pass # Build the patch_version.txt (for use by the patcher) f = file("patch_version.txt", "w") f.write(version + "\n") f.close() # Build the mv.patch manifest f = file("mv.patch", "w") asset_tree = AssetTree(dir_win, "") add_binary_assets(asset_tree, config) asset_tree.print_all_entries(f, version, dest_url) f.close() # Build the patch archive (which should be expanded on the update server) # tar_file = tarfile.open(patch_file, "w:gz") tar_file = tarfile.open(patch_file, "w") asset_tree.write_to_tar(tar_file) tar_file.add("mv.patch") #tar_file.add("patch_version.txt") tar_file.add(patcher, "patcher.exe") tar_file.close()
60.864629
135
0.750825
272e2751540f5d7118daa8686467ea8cc81c012a
3,480
py
Python
rasa_core/tracker_store.py
znat/rasa_core
58d224e2e3b5aa413f004822270f7230c7c7057c
[ "Apache-2.0" ]
1
2019-03-12T12:02:18.000Z
2019-03-12T12:02:18.000Z
rasa_core/tracker_store.py
znat/rasa_core
58d224e2e3b5aa413f004822270f7230c7c7057c
[ "Apache-2.0" ]
null
null
null
rasa_core/tracker_store.py
znat/rasa_core
58d224e2e3b5aa413f004822270f7230c7c7057c
[ "Apache-2.0" ]
null
null
null
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import six.moves.cPickle as pickler from typing import Text, Optional from rasa_core.actions.action import ACTION_LISTEN_NAME from rasa_core.trackers import DialogueStateTracker, ActionExecuted logger = logging.getLogger(__name__) class TrackerStore(object): def __init__(self, domain): self.domain = domain def get_or_create_tracker(self, sender_id): tracker = self.retrieve(sender_id) if tracker is None: tracker = self.create_tracker(sender_id) return tracker def init_tracker(self, sender_id): return DialogueStateTracker(sender_id, self.domain.slots, self.domain.topics, self.domain.default_topic) def create_tracker(self, sender_id, append_action_listen=True): """Creates a new tracker for the sender_id. The tracker is initially listening.""" tracker = self.init_tracker(sender_id) if append_action_listen: tracker.update(ActionExecuted(ACTION_LISTEN_NAME)) self.save(tracker) return tracker def save(self, tracker): raise NotImplementedError() def retrieve(self, sender_id): # type: (Text) -> Optional[DialogueStateTracker] raise NotImplementedError() def keys(self): # type: (Text) -> List[Text] raise NotImplementedError() @staticmethod def serialise_tracker(tracker): dialogue = tracker.as_dialogue() return pickler.dumps(dialogue) def deserialise_tracker(self, sender_id, _json): dialogue = pickler.loads(_json) tracker = self.init_tracker(sender_id) tracker.recreate_from_dialogue(dialogue) return tracker class InMemoryTrackerStore(TrackerStore): def __init__(self, domain): self.store = {} super(InMemoryTrackerStore, self).__init__(domain) def save(self, tracker): serialised = InMemoryTrackerStore.serialise_tracker(tracker) self.store[tracker.sender_id] = serialised def retrieve(self, sender_id): if sender_id in self.store: logger.debug('Recreating tracker for ' 'id \'{}\''.format(sender_id)) return self.deserialise_tracker(sender_id, self.store[sender_id]) else: logger.debug('Creating a new tracker for ' 'id \'{}\'.'.format(sender_id)) return None def keys(self): return self.store.keys() class RedisTrackerStore(TrackerStore): def keys(self): pass def __init__(self, domain, host='localhost', port=6379, db=0, password=None): import redis self.red = redis.StrictRedis(host=host, port=port, db=db, password=password) super(RedisTrackerStore, self).__init__(domain) def save(self, tracker, timeout=None): serialised_tracker = self.serialise_tracker(tracker) self.red.set(tracker.sender_id, serialised_tracker, ex=timeout) def retrieve(self, sender_id): stored = self.red.get(sender_id) if stored is not None: return self.deserialise_tracker(sender_id, stored) else: return None
30.26087
77
0.642816
184f1f357986d8a42e3cce1db383667eeafb2222
3,298
py
Python
python/chat.py
Colonel-Top/Line-Bot-Python
d890924cb89c46cdfdd80e77c1ff6175178ddc5d
[ "MIT" ]
null
null
null
python/chat.py
Colonel-Top/Line-Bot-Python
d890924cb89c46cdfdd80e77c1ff6175178ddc5d
[ "MIT" ]
null
null
null
python/chat.py
Colonel-Top/Line-Bot-Python
d890924cb89c46cdfdd80e77c1ff6175178ddc5d
[ "MIT" ]
null
null
null
#!/usr/bin/python #-*-coding: utf-8 -*- import time import random import string #from requests import .requests from gspread import client, httpsession, models ,ns, urls, utils import os import sys from oauth2client import clientsecrets import oauth2client from datetime import datetime now = datetime.now() from oauth2client.service_account import ServiceAccountCredentials scope = ['https://spreadsheets.google.com/feeds'] state = '0' credentials = ServiceAccountCredentials.from_json_keyfile_name('client_code.json', scope) gc = client.authorize(credentials) sh = gc.open_by_key('1m0OUgl7O3lXEGV6XOa_I-kUJmxBTx6yZP5VrERjQWOM') worksheet = sh.worksheet("Account") print ("Google API Connected") def Login(): print ("Messenger API Connected") scope = ['https://spreadsheets.google.com/feeds'] state = '0' credentials = ServiceAccountCredentials.from_json_keyfile_name('client_code.json', scope) gc = gspread.authorize(credentials) sh = gc.open_by_key('1m0OUgl7O3lXEGV6XOa_I-kUJmxBTx6yZP5VrERjQWOM') worksheet = sh.worksheet("Account") print ("Google API Connected") bot_status = 0 bot_mode = 0 # define hi or hello greeting_w = ['Hello', 'Hi ', 'Greeting', 'สวัสดี','hello', 'hi ', 'greetings', 'sup', 'whats up','re you here','หวัดดี'] greeting_f = ['May i help you please ?', 'Yes ?', 'Ya Anything you want ?', 'Anything ? ya ?', 'Greeting yes ?','Always here'] backasgre_w = ['Thx','Thank','ขอบคุณ','appreciate','ขอบใจ'] backasgre_f = ['Your welcome','With Pleasure :)','with Appreciated','Ya','Okay ^^','Welcome','Never mind :)'] menu_cmd = ['pen menu','pen Menu','เปิดเมนู','เรียกเมนู','show function','Show function','Show Menu','show menu','Show menu'] simq_ask = ['ho are you','hat do you do','ho is your boss','ho am i','ell me a joke','ell me some joke'] simq_ans = ['I am Chloe The Secretary of Colonel','I am Chloe The Secretary of Colonel ^^ Helping My Master & you guys','My Boss or my master is Colonel','Some Human in this world','Joke ? google it :)','Ahh Nope'] bank_ask = ['eport account','ccount report','om engr account','pdate account','heck amout account','heck amout in account'] bank_ans = ['Okay i will update account for you','Yes, wait a second','Let me check account','Here we go','Alright here is it','Ya this one ^^'] #execfile("timeahead.py") tellasc_cmd = ['tell all associate'] tellasc_ans = ['Okay i will update send msg for you','Yes, wait a second','Let me work on it','Here we go','Alright here is it','Ya this one ^^'] # Class def import json import sys ''' BOT_NAME = "Bot" chatbot = ChatBot( BOT_NAME, storage_adapter='chatterbot.adapters.storage.MongoDatabaseAdapter', database="chatterbot-database", logic_adapters=[ "chatterbot.adapters.logic.MathematicalEvaluation", "chatterbot.adapters.logic.TimeLogicAdapter", "chatterbot.adapters.logic.ClosestMatchAdapter" ], filters=[ 'chatterbot.filters.RepetitiveResponseFilter' ], ) if len(sys.argv) < 2: sys.exit(0) message = sys.argv[1] result = chatbot.get_response(message)''' result = "Done" print ("%s" % result)
41.225
214
0.667677
04064b1cce3507c084378f18fcd8632d7e3326c5
3,630
py
Python
python/tvm/meta_schedule/feature_extractor/feature_extractor.py
XiaoSong9905/tvm
48940f697e15d5b50fa1f032003e6c700ae1e423
[ "Apache-2.0" ]
4,640
2017-08-17T19:22:15.000Z
2019-11-04T15:29:46.000Z
python/tvm/meta_schedule/feature_extractor/feature_extractor.py
XiaoSong9905/tvm
48940f697e15d5b50fa1f032003e6c700ae1e423
[ "Apache-2.0" ]
2,863
2017-08-17T19:55:50.000Z
2019-11-04T17:18:41.000Z
python/tvm/meta_schedule/feature_extractor/feature_extractor.py
XiaoSong9905/tvm
48940f697e15d5b50fa1f032003e6c700ae1e423
[ "Apache-2.0" ]
1,352
2017-08-17T19:30:38.000Z
2019-11-04T16:09:29.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Meta Schedule FeatureExtractor.""" from typing import Callable, List from tvm._ffi import register_object from tvm.runtime import Object from tvm.runtime.ndarray import NDArray from .. import _ffi_api from ..utils import _get_default_str from ..tune_context import TuneContext from ..search_strategy import MeasureCandidate @register_object("meta_schedule.FeatureExtractor") class FeatureExtractor(Object): """Extractor for features from measure candidates for use in cost model.""" def extract_from( self, context: TuneContext, candidates: List[MeasureCandidate] ) -> List[NDArray]: """Extract features from the given measure candidate. Parameters ---------- context : TuneContext The tuning context for feature extraction. candidates : List[MeasureCandidate] The measure candidates to extract features from. Returns ------- features : List[NDArray] The feature tvm ndarray extracted. """ result = _ffi_api.FeatureExtractorExtractFrom( # type: ignore # pylint: disable=no-member self, context, candidates ) return result @register_object("meta_schedule.PyFeatureExtractor") class _PyFeatureExtractor(FeatureExtractor): """ A TVM object feature extractor to support customization on the python side. This is NOT the user facing class for function overloading inheritance. See also: PyFeatureExtractor """ def __init__(self, f_extract_from: Callable, f_as_string: Callable = None): """Constructor.""" self.__init_handle_by_constructor__( _ffi_api.FeatureExtractorPyFeatureExtractor, # type: ignore # pylint: disable=no-member f_extract_from, f_as_string, ) class PyFeatureExtractor: """ An abstract feature extractor with customized methods on the python-side. This is the user facing class for function overloading inheritance. Note: @derived_object is required for proper usage of any inherited class. """ _tvm_metadata = { "cls": _PyFeatureExtractor, "methods": ["extract_from", "__str__"], } def extract_from( self, context: TuneContext, candidates: List[MeasureCandidate] ) -> List[NDArray]: """Extract features from the given measure candidate. Parameters ---------- context : TuneContext The tuning context for feature extraction. candidates : List[MeasureCandidate] The measure candidates to extract features from. Returns ------- features : List[NDArray] The feature tvm ndarray extracted. """ raise NotImplementedError def __str__(self) -> str: return _get_default_str(self)
33
100
0.689256
344b32f3ff3f87713c3f1da66a3a48384cdd580c
86
py
Python
teste.py
PPedriniHp/Fiap_on_Phyton
fe06cfc931cd038dfed8c14394336f69dc953926
[ "MIT" ]
null
null
null
teste.py
PPedriniHp/Fiap_on_Phyton
fe06cfc931cd038dfed8c14394336f69dc953926
[ "MIT" ]
null
null
null
teste.py
PPedriniHp/Fiap_on_Phyton
fe06cfc931cd038dfed8c14394336f69dc953926
[ "MIT" ]
null
null
null
import ctypes dll = ctypes.windll.biblioteca funcaoTeste = dll.funcaoTeste a = open
12.285714
30
0.77907
a24837a659f2794a6cb66d7412ef4d98eb2624cc
805
py
Python
antiope/__init__.py
jchrisfarris/antiope-aws-module
574fe681092b021daa3aab234cc59afc81fed696
[ "Apache-2.0" ]
null
null
null
antiope/__init__.py
jchrisfarris/antiope-aws-module
574fe681092b021daa3aab234cc59afc81fed696
[ "Apache-2.0" ]
null
null
null
antiope/__init__.py
jchrisfarris/antiope-aws-module
574fe681092b021daa3aab234cc59afc81fed696
[ "Apache-2.0" ]
null
null
null
# Copyright 2019-2020 Turner Broadcasting Inc. / WarnerMedia # # 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 .aws_account import * from .aws_organization import * from .foreign_aws_account import * from .vpc import * from ._version import __version__, __version_info__ # from .entry_points import TBD
38.333333
74
0.775155
a172ea27691f990e2635199b94ab264b9d8a9cd7
1,216
py
Python
cogs/help/web.py
tuna2134/hortbot
43176217a59af9b3ed16b2aa911b3a267569009e
[ "BSD-3-Clause" ]
1
2021-11-17T15:08:07.000Z
2021-11-17T15:08:07.000Z
cogs/help/web.py
tuna2134/hortbot
43176217a59af9b3ed16b2aa911b3a267569009e
[ "BSD-3-Clause" ]
null
null
null
cogs/help/web.py
tuna2134/hortbot
43176217a59af9b3ed16b2aa911b3a267569009e
[ "BSD-3-Clause" ]
null
null
null
from discord.ext import commands import ujson import urllib.parse from sanic.response import json class Helpweb(commands.Cog): def __init__(self, bot): self.bot = bot with open("data/help.json", "r") as f: self.data = bot.help bot.web.add_route(self.help_web, "/help") bot.web.add_route(self.help_category, "/help/<category>") bot.web.add_route(self.help_command, "/help/<category>/<cmd>") @commands.route("/help/reload") async def reloadhelp(self, request): with open("data/help.json", "r") as f: self.bot.help = ujson.load(f) return json({"message": "complete"}) async def help_web(self, request): return await self.bot.template("help.html", data=self.data) async def help_category(self, request, category): return await self.bot.template("help_category.html", category=urllib.parse.unquote(category), data=self.data[urllib.parse.unquote(category)]) async def help_command(self, request, category, cmd): return await self.bot.template("help_command.html", cmd=urllib.parse.unquote(cmd), data=self.data[category]["command"][urllib.parse.unquote(cmd)][1])
43.428571
157
0.658717
431b1ff7b0ff2e97de813ccfc88175813655a6eb
2,174
py
Python
powrl3/agent/chrl/ddqn.py
leferrad/powrl3
c3193516d5ad3485b55fe72c23849398a173309d
[ "MIT" ]
1
2018-10-07T18:07:09.000Z
2018-10-07T18:07:09.000Z
powrl3/agent/chrl/ddqn.py
leferrad/powrl3
c3193516d5ad3485b55fe72c23849398a173309d
[ "MIT" ]
null
null
null
powrl3/agent/chrl/ddqn.py
leferrad/powrl3
c3193516d5ad3485b55fe72c23849398a173309d
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function """""" # https://github.com/jaara/AI-blog/blob/master/Seaquest-DDQN-PER.py # https://jaromiru.com/2016/11/07/lets-make-a-dqn-double-learning-and-prioritized-experience-replay/ from powrl3.agent.chrl.base import BaseAgent from chainer import links as L from chainerrl import links from chainerrl.agents import DoubleDQN from chainerrl.q_functions import FCStateQFunctionWithDiscreteAction import chainerrl import numpy as np def phi(obs): return obs.astype(np.float32, copy=False) def exp_return_of_episode(episode): return np.exp(sum(x['reward'] for x in episode)) class DoubleDQNAgent(BaseAgent): def __init__(self, env, feature_transformer, gamma=0.99, optimizer='adam', max_memory=10000): BaseAgent.__init__(self, env=env, feature_transformer=feature_transformer, gamma=gamma, optimizer=optimizer) self.model = links.Sequence(L.ConvolutionND(ndim=1, in_channels=self.n_dims, out_channels=100, ksize=3, stride=1, pad=1, cover_all=True), FCStateQFunctionWithDiscreteAction(ndim_obs=100, n_actions=self.n_actions, n_hidden_channels=100, n_hidden_layers=2) ) self.optimizer.setup(self.model) #self.optimizer.add_hook(chainer.optimizer.GradientClipping(40)) self.replay_buffer = \ chainerrl.replay_buffer.PrioritizedEpisodicReplayBuffer( capacity=max_memory, uniform_ratio=0.1, default_priority_func=exp_return_of_episode, wait_priority_after_sampling=False, return_sample_weights=False) self.agent = DoubleDQN(q_function=self.model, optimizer=self.optimizer, replay_buffer=self.replay_buffer, explorer=self.explorer, gamma=self.gamma, phi=phi, update_interval=500, minibatch_size=50)
36.847458
113
0.628335
ee0d738b4cfaef36fb13640f45159ab685bd7d31
157
py
Python
src/learners/__init__.py
YetAnotherPolicy/RMIX
dbc8f0a6560aa3f274765fa78aaaca22351ab8ad
[ "Apache-2.0" ]
6
2021-11-18T16:21:43.000Z
2021-12-31T02:22:23.000Z
src/learners/__init__.py
YetAnotherPolicy/RMIX
dbc8f0a6560aa3f274765fa78aaaca22351ab8ad
[ "Apache-2.0" ]
null
null
null
src/learners/__init__.py
YetAnotherPolicy/RMIX
dbc8f0a6560aa3f274765fa78aaaca22351ab8ad
[ "Apache-2.0" ]
1
2022-02-22T02:37:30.000Z
2022-02-22T02:37:30.000Z
from .q_learner import QLearner from .rmix_learner import RMIXLearner REGISTRY = {} REGISTRY["q_learner"] = QLearner REGISTRY["rmix_learner"] = RMIXLearner
22.428571
38
0.789809
ba3448a25a2229be3a077f358da375f4c461391c
2,763
py
Python
2021/03/code.py
mr-bigbang/advent-of-code
5fa0f78c70b10c66e516b21c08335e63e71d9e95
[ "MIT" ]
null
null
null
2021/03/code.py
mr-bigbang/advent-of-code
5fa0f78c70b10c66e516b21c08335e63e71d9e95
[ "MIT" ]
2
2020-12-04T00:58:16.000Z
2020-12-05T21:08:59.000Z
2021/03/code.py
mr-bigbang/advent-of-code
5fa0f78c70b10c66e516b21c08335e63e71d9e95
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import sys, timeit from typing import Tuple def bit_at(value: int, pos: int) -> bool: return value & (1 << pos) != 0 # -or- #return (value >> pos) & 1 != 0 def most_common(values: Tuple[int], pos: int) -> bool: # This looks nicer but is ~3x slower :-( # $ ./code.py -1 -b # Part One: 1 loops, best of 10000 repeats: 0.00258914s # $ ./code.py -2 -b # Part Two: 1 loops, best of 10000 repeats: 0.00175088s #return len(list(filter(lambda x: bit_at(x, pos), values))) * 2 >= len(values) # Why is this faster? # $ ./code.py -1 -b # Part One: 1 loops, best of 10000 repeats: 0.00085089s # $ ./code.py -2 -b # Part Two: 1 loops, best of 10000 repeats: 0.00111577s counter = 0 mask = 1 << pos for v in values: if v & mask == mask: counter += 1 else: counter -= 1 return counter >= 0 def rating(values: Tuple[int], want: bool): num_bits = max(values).bit_length() matching_values = values for i in reversed(range(num_bits)): if len(matching_values) == 1: break if most_common(matching_values, i) == want: matching_values = list(filter(lambda x: bit_at(x, i), matching_values)) else: matching_values = list(filter(lambda x: not bit_at(x, i), matching_values)) return matching_values[0] def part01(data: Tuple[int]) -> int: gamma_rate = 0 epsilon_rate = 0 num_bits = max(data).bit_length() for i in range(num_bits): if most_common(data, i): gamma_rate |= (1 << i) else: epsilon_rate |= (1 << i) return gamma_rate * epsilon_rate def part02(data: Tuple[int]) -> int: return rating(data, True) * rating(data, False) if __name__ == '__main__': BENCH_LOOPS = 1 BENCH_REPEAT = 10000 with open("input.txt", "r") as f: data = tuple(map(lambda x: int(x, 2), f.readlines())) if "-1" in sys.argv: print("Solution to Part One is:", part01(data)) if "-b" in sys.argv: t1 = timeit.Timer("part01(data)", globals=locals()) time_p1 = min(t1.repeat(repeat=BENCH_REPEAT, number=BENCH_LOOPS)) print(f"Part One: {BENCH_LOOPS} loops, best of {BENCH_REPEAT} repeats: {time_p1:0.8f}s") elif "-2" in sys.argv: print("Solution to Part Two is:", part02(data)) if "-b" in sys.argv: t2 = timeit.Timer("part02(data)", globals=locals()) time_p2 = min(t2.repeat(repeat=BENCH_REPEAT, number=BENCH_LOOPS)) print(f"Part Two: {BENCH_LOOPS} loops, best of {BENCH_REPEAT} repeats: {time_p2:0.8f}s") else: print("Usage: ./code.py (-1|-2) [-b]")
29.393617
100
0.581614
80e525c8cd11f18c97a3176f69d1e82cba4b535f
771
py
Python
code/download_count.py
jindui/t66y
cb0fb4158f463faf79b0486bc6e104156d126447
[ "MIT" ]
null
null
null
code/download_count.py
jindui/t66y
cb0fb4158f463faf79b0486bc6e104156d126447
[ "MIT" ]
1
2019-06-11T04:20:50.000Z
2020-01-31T09:22:08.000Z
code/download_count.py
jindui/t66y
cb0fb4158f463faf79b0486bc6e104156d126447
[ "MIT" ]
3
2017-10-12T02:23:47.000Z
2019-06-11T04:07:05.000Z
# coding= utf-8 import requests from bs4 import BeautifulSoup def download_count(url): proxies = { "http": "http://127.0.0.1:1080", } r = requests.get(url, proxies=proxies) r.encoding='gbk' soup = BeautifulSoup(r.text,"lxml") alist = soup.find_all("a") for child in alist: if child.text.startswith("http://www.rmdown.com/link.php?hash=") : seed = requests.get(child.text, proxies=proxies) seedSoup = BeautifulSoup(seed.text,"lxml") for contentStr in seedSoup.form.table.tr.td.strings: if contentStr.strip().startswith("downloaded:"): return int(contentStr.strip()[12:]) return 0 #print soup.prettify("gbk") if __name__ == "__main__": down_count = download_count("http://t66y.com/htm_data/2/1706/2462520.html") print down_count
27.535714
79
0.699092
659b559c5ea79db2dbc7aea8963d30e717e49979
143
py
Python
examples/formal_project/sampleproject/base.py
reorx/torext
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
[ "MIT" ]
31
2015-03-20T14:11:11.000Z
2020-10-19T08:07:45.000Z
examples/formal_project/sampleproject/base.py
reorx/torext
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
[ "MIT" ]
1
2016-09-15T07:17:26.000Z
2016-09-15T07:17:26.000Z
examples/formal_project/sampleproject/base.py
reorx/torext
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
[ "MIT" ]
8
2015-03-04T04:08:57.000Z
2019-08-31T03:03:42.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- from torext.handlers import BaseHandler class MyBaseHandler(BaseHandler): visit_count = 0
15.888889
39
0.706294
99e67da06ffb63869ddf478757deacddd75cdf4d
15,162
py
Python
salt/_logging/impl.py
lllamnyp/salt
de112e5b362191e3708e170b7eb8e990787ad412
[ "Apache-2.0" ]
1
2015-04-01T21:38:46.000Z
2015-04-01T21:38:46.000Z
salt/_logging/impl.py
lllamnyp/salt
de112e5b362191e3708e170b7eb8e990787ad412
[ "Apache-2.0" ]
9
2021-03-31T20:25:25.000Z
2021-07-04T05:33:46.000Z
salt/_logging/impl.py
lllamnyp/salt
de112e5b362191e3708e170b7eb8e990787ad412
[ "Apache-2.0" ]
null
null
null
""" salt._logging.impl ~~~~~~~~~~~~~~~~~~ Salt's logging implementation classes/functionality """ import logging import re import sys import types # Let's define these custom logging levels before importing the salt._logging.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 from salt._logging.handlers import StreamHandler # isort:skip # from salt._logging.handlers import SysLogHandler # isort:skip # from salt._logging.handlers import RotatingFileHandler # isort:skip # from salt._logging.handlers import WatchedFileHandler # isort:skip from salt._logging.handlers import TemporaryLoggingHandler # isort:skip from salt._logging.mixins import LoggingMixinMeta # isort:skip from salt._logging.mixins import NewStyleClassMixin # isort:skip from salt.exceptions import LoggingRuntimeError # isort:skip from salt.utils.ctx import RequestContext # isort:skip from salt.utils.textformat import TextFormat # isort:skip # from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module LOG_LEVELS = { "all": logging.NOTSET, "debug": logging.DEBUG, "error": logging.ERROR, "critical": logging.CRITICAL, "garbage": GARBAGE, "info": logging.INFO, "profile": PROFILE, "quiet": QUIET, "trace": TRACE, "warning": logging.WARNING, } LOG_VALUES_TO_LEVELS = {v: k for (k, v) in LOG_LEVELS.items()} LOG_COLORS = { "levels": { "QUIET": TextFormat("reset"), "CRITICAL": TextFormat("bold", "red"), "ERROR": TextFormat("bold", "red"), "WARNING": TextFormat("bold", "yellow"), "INFO": TextFormat("bold", "green"), "PROFILE": TextFormat("bold", "cyan"), "DEBUG": TextFormat("bold", "cyan"), "TRACE": TextFormat("bold", "magenta"), "GARBAGE": TextFormat("bold", "blue"), "NOTSET": TextFormat("reset"), "SUBDEBUG": TextFormat( "bold", "cyan" ), # used by multiprocessing.log_to_stderr() "SUBWARNING": TextFormat( "bold", "yellow" ), # used by multiprocessing.log_to_stderr() }, "msgs": { "QUIET": TextFormat("reset"), "CRITICAL": TextFormat("bold", "red"), "ERROR": TextFormat("red"), "WARNING": TextFormat("yellow"), "INFO": TextFormat("green"), "PROFILE": TextFormat("bold", "cyan"), "DEBUG": TextFormat("cyan"), "TRACE": TextFormat("magenta"), "GARBAGE": TextFormat("blue"), "NOTSET": TextFormat("reset"), "SUBDEBUG": TextFormat( "bold", "cyan" ), # used by multiprocessing.log_to_stderr() "SUBWARNING": TextFormat( "bold", "yellow" ), # used by multiprocessing.log_to_stderr() }, "name": TextFormat("bold", "green"), "process": TextFormat("bold", "blue"), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [l[0] for l in sorted(LOG_LEVELS.items(), key=lambda x: x[1])] MODNAME_PATTERN = re.compile(r"(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)") # ----- REMOVE ME ON REFACTOR COMPLETE ------------------------------------------------------------------------------> class __NullLoggingHandler(TemporaryLoggingHandler): """ This class exists just to better identify which temporary logging handler is being used for what. """ class __StoreLoggingHandler(TemporaryLoggingHandler): """ This class exists just to better identify which temporary logging handler is being used for what. """ # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() # <---- REMOVE ME ON REFACTOR COMPLETE ------------------------------------------------------------------------------- class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) self.bracketname = "[{:<17}]".format(str(self.name)) self.bracketlevel = "[{:<8}]".format(str(self.levelname)) self.bracketprocess = "[{:>5}]".format(str(self.process)) class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat("reset") clevel = LOG_COLORS["levels"].get(self.levelname, reset) cmsg = LOG_COLORS["msgs"].get(self.levelname, reset) self.colorname = "{}[{:<17}]{}".format( LOG_COLORS["name"], str(self.name), reset ) self.colorlevel = "{}[{:<8}]{}".format(clevel, str(self.levelname), reset) self.colorprocess = "{}[{:>5}]{}".format( LOG_COLORS["process"], str(self.process), reset ) self.colormsg = "{}{}{}".format(cmsg, self.getMessage(), reset) def get_log_record_factory(): """ Get the logging log record factory """ try: return get_log_record_factory.__factory__ except AttributeError: return def set_log_record_factory(factory): """ Set the logging log record factory """ get_log_record_factory.__factory__ = factory logging.setLogRecordFactory(factory) set_log_record_factory(SaltLogRecord) # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() class SaltLoggingClass( LOGGING_LOGGER_CLASS, NewStyleClassMixin, metaclass=LoggingMixinMeta ): def __new__(cls, *args): """ We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) """ instance = super().__new__(cls) try: max_logger_length = len( max(list(logging.Logger.manager.loggerDict), key=len) ) for handler in logging.root.handlers: if handler in ( LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER, ): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace("%", "%%") match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if "digits" not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group("digits") if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group("name"), "%%(name)-%ds") formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log( self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ stack_info=False, stacklevel=1, exc_info_on_loglevel=None, ): if extra is None: extra = {} # pylint: disable=no-member current_jid = RequestContext.current.get("data", {}).get("jid", None) log_fmt_jid = RequestContext.current.get("opts", {}).get("log_fmt_jid", None) # pylint: enable=no-member if current_jid is not None: extra["jid"] = current_jid if log_fmt_jid is not None: extra["log_fmt_jid"] = log_fmt_jid # If both exc_info and exc_info_on_loglevel are both passed, let's fail if exc_info and exc_info_on_loglevel: raise LoggingRuntimeError( "Only one of 'exc_info' and 'exc_info_on_loglevel' is " "permitted" ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, str): exc_info_on_loglevel = LOG_LEVELS.get( exc_info_on_loglevel, logging.ERROR ) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( "The value of 'exc_info_on_loglevel' needs to be a " "logging level or a logging level name, not '{}'".format( exc_info_on_loglevel ) ) if extra is None: extra = {"exc_info_on_loglevel": exc_info_on_loglevel} else: extra["exc_info_on_loglevel"] = exc_info_on_loglevel if sys.version_info < (3,): LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) elif sys.version_info < (3, 8): LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra, stack_info=stack_info, ) else: LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra, stack_info=stack_info, stacklevel=stacklevel, ) def makeRecord( self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None, ): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop("exc_info_on_loglevel") jid = extra.pop("jid", "") if jid: log_fmt_jid = extra.pop("log_fmt_jid") jid = log_fmt_jid % {"jid": jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode try: salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == "ascii": # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = "utf-8" except NameError: salt_system_encoding = "utf-8" if isinstance(msg, bytes): try: _msg = msg.decode(salt_system_encoding, "replace") except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, "ignore") else: _msg = msg _args = [] for item in args: if isinstance(item, bytes): try: _args.append(item.decode(salt_system_encoding, "replace")) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, "ignore")) else: _args.append(item) _args = tuple(_args) logrecord = LOGGING_LOGGER_CLASS.makeRecord( self, name, level, fn, lno, _msg, _args, exc_info, func, sinfo ) if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, "QUIET") logging.addLevelName(PROFILE, "PROFILE") logging.addLevelName(TRACE, "TRACE") logging.addLevelName(GARBAGE, "GARBAGE") # ----- REMOVE ON REFACTORING COMPLETE --------------------------------------------------------------------------> if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) # <---- REMOVE ON REFACTORING COMPLETE --------------------------------------------------------------------------- # Now that we defined the default logging logger class, we can instantiate our logger # DO NOT MOVE THIS log = logging.getLogger(__name__) def __get_exposed_module_attributes(): """ This function just ``dir()``'s this module and filters out any functions or variables which should not be available when wildcard importing it """ exposed = [] module = sys.modules[__name__] for name in dir(module): if name.startswith("_"): continue obj = getattr(module, name) if not isinstance(obj, types.FunctionType): if name.startswith(("LOG_", "SORTED_")): exposed.append(name) continue if obj.__module__ != __name__: continue exposed.append(name) return exposed # Define what can be imported by wildcard imports __all__ = __get_exposed_module_attributes() # We're done with the function, nuke it del __get_exposed_module_attributes
33.995516
118
0.585609
7d5ca6b4b5051f168d4d1d29eebae6f027138ded
4,088
py
Python
ross/units.py
LMEst-Rotor/ross
33aaa4b32ff7c32465cb81840f3cb2d6b2cdd65a
[ "MIT" ]
null
null
null
ross/units.py
LMEst-Rotor/ross
33aaa4b32ff7c32465cb81840f3cb2d6b2cdd65a
[ "MIT" ]
null
null
null
ross/units.py
LMEst-Rotor/ross
33aaa4b32ff7c32465cb81840f3cb2d6b2cdd65a
[ "MIT" ]
null
null
null
"""This module deals with units conversion in the ROSS library.""" import inspect import warnings from functools import wraps from pathlib import Path import pint new_units_path = Path(__file__).parent / "new_units.txt" ureg = pint.get_application_registry() if isinstance(ureg, pint.registry.LazyRegistry): ureg = pint.UnitRegistry() ureg.load_definitions(str(new_units_path)) # set ureg to make pickle possible pint.set_application_registry(ureg) Q_ = ureg.Quantity with warnings.catch_warnings(): warnings.simplefilter("ignore") pint.Quantity([]) __all__ = ["Q_", "check_units"] units = { "E": "N/m**2", "G_s": "N/m**2", "rho": "kg/m**3", "density": "kg/m**3", "L": "meter", "idl": "meter", "idr": "meter", "odl": "meter", "odr": "meter", "id": "meter", "od": "meter", "i_d": "meter", "o_d": "meter", "speed": "radian/second", "frequency": "radian/second", "m": "kg", "mx": "kg", "my": "kg", "Ip": "kg*m**2", "Id": "kg*m**2", "width": "meter", "depth": "meter", "thickness": "meter", "pitch": "meter", "height": "meter", "radius": "meter", "diameter": "meter", "clearance": "meter", "length": "meter", "area": "meter**2", "unbalance_magnitude": "kg*m", "unbalance_phase": "rad", "pressure": "pascal", "temperature": "degK", "velocity": "m/s", "angle": "rad", "arc": "rad", "convection": "W/(m²*degK)", "conductivity": "W/(m*degK)", "expansion": "1/degK", "stiffness": "N/m", "weight": "N", "load": "N", "flowv": "m³/s", "fit": "m", } for i, unit in zip(["k", "c"], ["N/m", "N*s/m"]): for j in ["x", "y", "z"]: for k in ["x", "y", "z"]: units["".join([i, j, k])] = unit def check_units(func): """Wrapper to check and convert units to base_units. If we use the check_units decorator in a function the arguments are checked, and if they are in the dictionary, they are converted to the 'default' unit given in the dictionary. For example: >>> units = { ... "L": "meter", ... } >>> @check_units ... def foo(L=None): ... print(L) ... If we call the function with the argument as a float: >>> foo(L=0.5) 0.5 If we call the function with a pint.Quantity object the value is automatically converted to the default: >>> foo(L=Q_(0.5, 'inches')) 0.0127 """ @wraps(func) def inner(*args, **kwargs): base_unit_args = [] args_names = inspect.getfullargspec(func)[0] for arg_name, arg_value in zip(args_names, args): names = arg_name.split("_") if arg_name not in names: names.append(arg_name) for name in names: if name in units and arg_value is not None: # For now, we only return the magnitude for the converted Quantity # If pint is fully adopted by ross in the future, and we have all Quantities # using it, we could remove this, which would allows us to use pint in its full capability try: base_unit_args.append(arg_value.to(units[name]).m) except AttributeError: base_unit_args.append(Q_(arg_value, units[name]).m) break else: base_unit_args.append(arg_value) base_unit_kwargs = {} for k, v in kwargs.items(): names = k.split("_") if k not in names: names.append(k) for name in names: if name in units and v is not None: try: base_unit_kwargs[k] = v.to(units[name]).m except AttributeError: base_unit_kwargs[k] = Q_(v, units[name]).m break else: base_unit_kwargs[k] = v return func(*base_unit_args, **base_unit_kwargs) return inner
28
110
0.536448
aceef0c54aeaa0701c81c489aff7411dc3594461
2,050
py
Python
06-higher-order-functions/main.py
johnehunt/PythonIntroLabsDS
d0d63730e9bacefa99225559be98fb933eed15c8
[ "Apache-2.0" ]
1
2021-05-16T10:24:19.000Z
2021-05-16T10:24:19.000Z
06-higher-order-functions/main.py
johnehunt/PythonIntroLabsDS
d0d63730e9bacefa99225559be98fb933eed15c8
[ "Apache-2.0" ]
null
null
null
06-higher-order-functions/main.py
johnehunt/PythonIntroLabsDS
d0d63730e9bacefa99225559be98fb933eed15c8
[ "Apache-2.0" ]
null
null
null
# Illustrates use of higher order functions such as filter, map and reduce from functools import reduce def average(data): return sum(data) / len(data) def median(data): sorted_data = sorted(data) data_length = len(data) index = (data_length - 1) // 2 if data_length % 2: return sorted_data[index] else: return (sorted_data[index] + sorted_data[index + 1]) / 2.0 def minimum(data, index=0): if index == 0: data_slice = data else: data_slice = data[index:] return min(data_slice) def maximum(data, index=0): if index == 0: data_slice = data else: data_slice = data[index:] return max(data_slice) def data_range(data): return minimum(data), maximum(data) def celsius_to_fahrenheit(celsius): return (celsius * 9 / 5) + 32 def fahrenheit_to_celsius(fahrenheit): return (fahrenheit - 32) * 5/9 # Set up the data the data file readings = [13.5, 12.6, 15.3, 12.2, 16.6, 14.6, 15.6] print(f'Readings: {readings}') # Find minimum, maximum etc in readings print('Min temp in list =', minimum(readings)) print('Max temp in list =', maximum(readings)) print('Average temperature = {:.2f}'.format(average(readings))) print('Median temperature value =', median(readings)) readings_range = data_range(readings) print(f'Range of temperatures from {readings_range[0]} to {readings_range[1]}') # Convert all the temperatures from Celsius to fahrenheit fahrenheit_temperatures = list(map(celsius_to_fahrenheit, readings)) print(f'Fahrenheit Temperatures: {fahrenheit_temperatures}') # Find all temperatures above 14.0 higher_temperatures = list(filter(lambda r: r > 14.0, readings)) print(f'Temperatures above 14.0: {higher_temperatures}') # Total all the readings result = reduce(lambda total, value: total + value, readings) print(f'Total value of all readings is {result}') # Convert all readings above 14.0 to fahrenheit converted_temperatures = list(map(celsius_to_fahrenheit, filter(lambda r: r > 15.5, readings))) print(f'Fahrenheit Temperatures above 14.0c: {converted_temperatures}') print('Done')
25.625
95
0.730244
c90854e1c5b0a2123498c7117a356ffb5b534e85
7,955
py
Python
PythonPlotting/PlotDataGUI.py
DCHartlen/WindEnergyProject
5921cbe99e9c744014e41e6dc628c1f7aa2f3b6f
[ "MIT" ]
null
null
null
PythonPlotting/PlotDataGUI.py
DCHartlen/WindEnergyProject
5921cbe99e9c744014e41e6dc628c1f7aa2f3b6f
[ "MIT" ]
null
null
null
PythonPlotting/PlotDataGUI.py
DCHartlen/WindEnergyProject
5921cbe99e9c744014e41e6dc628c1f7aa2f3b6f
[ "MIT" ]
null
null
null
""" Contains all objects in the GUI (buttons, plots, etc). Generated using ui_convert.py from "PlotDataGUI.ui" Created By: D.C. Hartlen, EIT Created On: 16-JUN-2018 Modified By: Modified On: """ # Form implementation generated from reading ui file 'PlotDataGUI.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1021, 630) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.mainPlotWindow = PlotWidget(self.centralwidget) self.mainPlotWindow.setMinimumSize(QtCore.QSize(756, 571)) self.mainPlotWindow.setObjectName("mainPlotWindow") self.gridLayout.addWidget(self.mainPlotWindow, 0, 0, 1, 1) self.verticalFrame = QtWidgets.QFrame(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.verticalFrame.sizePolicy().hasHeightForWidth()) self.verticalFrame.setSizePolicy(sizePolicy) self.verticalFrame.setMinimumSize(QtCore.QSize(241, 0)) self.verticalFrame.setObjectName("verticalFrame") self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalFrame) self.verticalLayout.setObjectName("verticalLayout") spacerItem = QtWidgets.QSpacerItem(20, 60, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) self.verticalLayout.addItem(spacerItem) self.label = QtWidgets.QLabel(self.verticalFrame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setMaximumSize(QtCore.QSize(450, 40)) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) self.maxVoltsOut = QtWidgets.QLineEdit(self.verticalFrame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.maxVoltsOut.sizePolicy().hasHeightForWidth()) self.maxVoltsOut.setSizePolicy(sizePolicy) self.maxVoltsOut.setMaximumSize(QtCore.QSize(450, 40)) font = QtGui.QFont() font.setPointSize(16) font.setBold(False) font.setWeight(50) self.maxVoltsOut.setFont(font) self.maxVoltsOut.setAlignment(QtCore.Qt.AlignCenter) self.maxVoltsOut.setObjectName("maxVoltsOut") self.verticalLayout.addWidget(self.maxVoltsOut) spacerItem1 = QtWidgets.QSpacerItem(17, 357, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.startPlotting = QtWidgets.QPushButton(self.verticalFrame) self.startPlotting.setMaximumSize(QtCore.QSize(450, 23)) self.startPlotting.setObjectName("startPlotting") self.horizontalLayout.addWidget(self.startPlotting) self.stopPlotting = QtWidgets.QPushButton(self.verticalFrame) self.stopPlotting.setMaximumSize(QtCore.QSize(450, 23)) self.stopPlotting.setObjectName("stopPlotting") self.horizontalLayout.addWidget(self.stopPlotting) self.verticalLayout.addLayout(self.horizontalLayout) spacerItem2 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) self.verticalLayout.addItem(spacerItem2) self.resetPlots = QtWidgets.QPushButton(self.verticalFrame) self.resetPlots.setMaximumSize(QtCore.QSize(450, 23)) self.resetPlots.setObjectName("resetPlots") self.verticalLayout.addWidget(self.resetPlots) self.gridLayout.addWidget(self.verticalFrame, 0, 1, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.menuBar = QtWidgets.QMenuBar(MainWindow) self.menuBar.setGeometry(QtCore.QRect(0, 0, 1021, 21)) self.menuBar.setObjectName("menuBar") self.menuAbout = QtWidgets.QMenu(self.menuBar) self.menuAbout.setObjectName("menuAbout") self.menuOptions = QtWidgets.QMenu(self.menuBar) self.menuOptions.setObjectName("menuOptions") MainWindow.setMenuBar(self.menuBar) self.actionInformation = QtWidgets.QAction(MainWindow) self.actionInformation.setObjectName("actionInformation") self.actionExit_App = QtWidgets.QAction(MainWindow) self.actionExit_App.setObjectName("actionExit_App") self.actionHelp = QtWidgets.QAction(MainWindow) self.actionHelp.setObjectName("actionHelp") self.actionAbout = QtWidgets.QAction(MainWindow) self.actionAbout.setObjectName("actionAbout") self.actionTest = QtWidgets.QAction(MainWindow) self.actionTest.setObjectName("actionTest") self.actionTest_2 = QtWidgets.QAction(MainWindow) self.actionTest_2.setObjectName("actionTest_2") self.actionSelectCOMPort = QtWidgets.QAction(MainWindow) self.actionSelectCOMPort.setObjectName("actionSelectCOMPort") self.actionSetFilterCoef = QtWidgets.QAction(MainWindow) self.actionSetFilterCoef.setObjectName("actionSetFilterCoef") self.menuAbout.addAction(self.actionHelp) self.menuAbout.addAction(self.actionAbout) self.menuOptions.addAction(self.actionSelectCOMPort) self.menuOptions.addAction(self.actionSetFilterCoef) self.menuBar.addAction(self.menuOptions.menuAction()) self.menuBar.addAction(self.menuAbout.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Wind Energy Demonstration Plotter")) self.label.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:14pt; font-weight:600;\">Peak Voltage (V)</span></p></body></html>")) self.startPlotting.setText(_translate("MainWindow", "Start")) self.stopPlotting.setText(_translate("MainWindow", "Stop")) self.resetPlots.setText(_translate("MainWindow", "Reset")) self.menuAbout.setTitle(_translate("MainWindow", "About")) self.menuOptions.setTitle(_translate("MainWindow", "Options")) self.actionInformation.setText(_translate("MainWindow", "Information")) self.actionExit_App.setText(_translate("MainWindow", "Exit App")) self.actionHelp.setText(_translate("MainWindow", "Help")) self.actionAbout.setText(_translate("MainWindow", "About")) self.actionTest.setText(_translate("MainWindow", "test")) self.actionTest_2.setText(_translate("MainWindow", "test")) self.actionSelectCOMPort.setText(_translate("MainWindow", "Select COM Port")) self.actionSetFilterCoef.setText(_translate("MainWindow", "Set Filter Parameters")) from pyqtgraph import PlotWidget
55.243056
186
0.727718
1c3497047196a31028998ae4617a866c66a753ef
4,399
py
Python
pygasus/model/decorators/lazy_property.py
talismud/pygasus
fb01c8bd51003b5a008b572182a96bad86ef769f
[ "BSD-3-Clause" ]
2
2021-11-18T09:35:10.000Z
2021-11-18T14:46:32.000Z
pygasus/model/decorators/lazy_property.py
talismud/pygasus
fb01c8bd51003b5a008b572182a96bad86ef769f
[ "BSD-3-Clause" ]
null
null
null
pygasus/model/decorators/lazy_property.py
talismud/pygasus
fb01c8bd51003b5a008b572182a96bad86ef769f
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) 20201, LE GOFF Vincent # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 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. """Lazy property, to optimize getting and setting data. The lazy property descriptor is used similarly to a property, but it caches the data it retrieves the first time it's called and then will only return this cached data, unless a setter is called in the meantime. """ _MISSING = object() class LazyPropertyDescriptor: """ Delays loading of property until first access. Although extended, this was inspired by Evennia's utility (wwww.evennia.com), itself based on the iplementation in the werkzeug suite: http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property A lazy property should be used as a decorator over the getter method, just like a property. The difference is that a lazy property will call the getter method only once, the first time for this object, and then cache the result for following queries. This allows for fast-access to handlers that are not re-created each time the property is called: ```python class SomeTest(Model): @lazy_property def db(self): return AttributeHandler(self) @db.setter def db(self, handler): raise ValueError("you can't change that") ``` Once initialized, the `AttributeHandler` will be available as a property "db" on the object. """ def __init__(self, fget, fset=None): self.fget = fget self.fset = fset self.memory = {} def __get__(self, instance, owner=None): if instance is None: return self # The value might be cached in `memory` try: identifier = hash(instance) except TypeError: identifier = None attr = self.fget.__name__ cached_attr = f"_cached_{attr}" if identifier: value = self.memory.get(identifier, _MISSING) else: value = getattr(instance, cached_attr, _MISSING) if value is _MISSING: value = self.fget(instance) if identifier: self.memory[identifier] = value else: setattr(instance, cached_attr, value) return value def __set__(self, instance, value): if not self.fset: raise AttributeError("can't set attribute") try: identifier = hash(instance) except TypeError: identifier = None attr = self.fget.__name__ cached_attr = f"_cached_{attr}" self.fset(instance, value) if identifier: self.memory[identifier] = value else: setattr(instance, cached_attr, value) def setter(self, func): self.fset = func return self def lazy_property(func): return LazyPropertyDescriptor(func)
33.838462
78
0.674926
26fa6ab7c20256b82a7ad089c651f304f768d1a2
564
py
Python
pyggi/base.py
nak/pyggi
139a72d72c1a3bb17005e0c9c64e06ba4e2cd329
[ "BSD-3-Clause" ]
1
2017-12-22T06:58:47.000Z
2017-12-22T06:58:47.000Z
pyggi/base.py
nak/pyggi
139a72d72c1a3bb17005e0c9c64e06ba4e2cd329
[ "BSD-3-Clause" ]
null
null
null
pyggi/base.py
nak/pyggi
139a72d72c1a3bb17005e0c9c64e06ba4e2cd329
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ :copyright: (c) 2011 by Tobias Heinzen :license: BSD, see LICENSE for more details """ import functools from pyggi.lib.decorators import templated import pyggi.lib.filters from flask import Blueprint, redirect base = Blueprint('base', __name__) get = functools.partial(base.route, methods=['GET']) post = functools.partial(base.route, methods=['POST']) @get("/favicon.ico") def favicon(): return redirect(pyggi.lib.filters.static_url_for("favicon.ico")) @get("/404") @templated("404.xhtml") def not_found(): pass
20.888889
68
0.702128
454038fef43b53d4ce9b59be48fecb78a10b299d
150
py
Python
config/pytorch_rnn_config.py
Aczy156/pytorch-deeplearning-models
e3aad44a0c62b84492f6135959cc8440d323387f
[ "MIT" ]
null
null
null
config/pytorch_rnn_config.py
Aczy156/pytorch-deeplearning-models
e3aad44a0c62b84492f6135959cc8440d323387f
[ "MIT" ]
null
null
null
config/pytorch_rnn_config.py
Aczy156/pytorch-deeplearning-models
e3aad44a0c62b84492f6135959cc8440d323387f
[ "MIT" ]
null
null
null
""" 数据预处理 超参数 """ num = 20 """ 模型 超参数 """ input_size = 1 output_size = 1 hidden_dim = 32 n_layers = 1 """ 模型训练 超参数 """ n_steps = 100 print_every = 25
8.823529
16
0.613333
8a64399fbaa60591fedc3b119cb20fab54cbe978
1,029
py
Python
tests/recipe/test_recipe.py
j-sommer/recipe-organizer
91d39e12c453ecf3d3254645b565bbceacaecde9
[ "MIT" ]
null
null
null
tests/recipe/test_recipe.py
j-sommer/recipe-organizer
91d39e12c453ecf3d3254645b565bbceacaecde9
[ "MIT" ]
null
null
null
tests/recipe/test_recipe.py
j-sommer/recipe-organizer
91d39e12c453ecf3d3254645b565bbceacaecde9
[ "MIT" ]
null
null
null
from recipe_organizer.recipe.ingredient.ingredient import Ingredient from recipe_organizer.recipe.recipe import Recipe def test_recipe_serialization(): # Given recipe = Recipe( "title", ["labelA", "labelB"], [Ingredient("name", "g", 50)], "preparation" ) # When json_string = recipe.to_json() # Then assert "title" in json_string assert "labelA" in json_string assert "preparation" in json_string def test_recipe_deserialization(): # Given json_string = """{"py/object": "recipe_organizer.recipe.recipe.Recipe", "title": "title", "labels": ["labelA", "labelB"], "ingredients": [{"py/object": "recipe_organizer.recipe.ingredient.ingredient.Ingredient", "name": "name", "quantity_type": "g", "quantity": 50}], "preparation": "preparation"}""" # When actual: Recipe = Recipe.from_json(json_string) # Then assert actual.title == "title" assert actual.labels == ["labelA", "labelB"] assert actual.preparation == "preparation"
30.264706
304
0.660836
4d266d975dbb3001f30efb47f67338d911faf850
466
py
Python
_includes/code/minimum-remove-to-make-valid-parentheses/solution.py
rajat19/interview-questions
cb1fa382a76f2f287f1c12dd3d1fca9bfb7fa311
[ "MIT" ]
null
null
null
_includes/code/minimum-remove-to-make-valid-parentheses/solution.py
rajat19/interview-questions
cb1fa382a76f2f287f1c12dd3d1fca9bfb7fa311
[ "MIT" ]
2
2022-03-01T06:30:35.000Z
2022-03-13T07:05:50.000Z
_includes/code/minimum-remove-to-make-valid-parentheses/solution.py
rajat19/interview-questions
cb1fa382a76f2f287f1c12dd3d1fca9bfb7fa311
[ "MIT" ]
1
2022-02-09T12:13:36.000Z
2022-02-09T12:13:36.000Z
class Solution: def minRemoveToMakeValid(self, s: str) -> str: stack = [] arr = list(s) print(arr) for i in range(len(s)): if s[i] == '(': stack.append(i) elif s[i] == ')': if not stack: arr[i] = '*' else: stack.pop() while stack: arr[stack.pop()] = '*' return ''.join(arr).replace('*', '')
29.125
50
0.369099
5f8aef124cb067e9a1ebadcccf6933853c754afd
13,327
py
Python
tests/python/testing.py
MichaelChirico/xgboost
028bdc174086d22dcda4130ca5955efca9a0eed7
[ "Apache-2.0" ]
null
null
null
tests/python/testing.py
MichaelChirico/xgboost
028bdc174086d22dcda4130ca5955efca9a0eed7
[ "Apache-2.0" ]
40
2021-09-10T06:17:11.000Z
2022-03-19T19:30:56.000Z
tests/python/testing.py
MichaelChirico/xgboost
028bdc174086d22dcda4130ca5955efca9a0eed7
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 import os import urllib import zipfile import sys from typing import Optional from contextlib import contextmanager from io import StringIO from xgboost.compat import SKLEARN_INSTALLED, PANDAS_INSTALLED from xgboost.compat import DASK_INSTALLED import pytest import gc import xgboost as xgb import numpy as np import platform hypothesis = pytest.importorskip('hypothesis') sklearn = pytest.importorskip('sklearn') from hypothesis import strategies from hypothesis.extra.numpy import arrays from joblib import Memory from sklearn import datasets try: import cupy as cp except ImportError: cp = None memory = Memory('./cachedir', verbose=0) def no_ubjson(): reason = "ubjson is not intsalled." try: import ubjson # noqa return {"condition": False, "reason": reason} except ImportError: return {"condition": True, "reason": reason} def no_sklearn(): return {'condition': not SKLEARN_INSTALLED, 'reason': 'Scikit-Learn is not installed'} def no_dask(): return {'condition': not DASK_INSTALLED, 'reason': 'Dask is not installed'} def no_pandas(): return {'condition': not PANDAS_INSTALLED, 'reason': 'Pandas is not installed.'} def no_modin(): reason = 'Modin is not installed.' try: import modin.pandas as _ # noqa return {'condition': False, 'reason': reason} except ImportError: return {'condition': True, 'reason': reason} def no_dt(): import importlib.util spec = importlib.util.find_spec('datatable') return {'condition': spec is None, 'reason': 'Datatable is not installed.'} def no_matplotlib(): reason = 'Matplotlib is not installed.' try: import matplotlib.pyplot as _ # noqa return {'condition': False, 'reason': reason} except ImportError: return {'condition': True, 'reason': reason} def no_dask_cuda(): reason = 'dask_cuda is not installed.' try: import dask_cuda as _ # noqa return {'condition': False, 'reason': reason} except ImportError: return {'condition': True, 'reason': reason} def no_cudf(): try: import cudf # noqa CUDF_INSTALLED = True except ImportError: CUDF_INSTALLED = False return {'condition': not CUDF_INSTALLED, 'reason': 'CUDF is not installed'} def no_cupy(): reason = 'cupy is not installed.' try: import cupy as _ # noqa return {'condition': False, 'reason': reason} except ImportError: return {'condition': True, 'reason': reason} def no_dask_cudf(): reason = 'dask_cudf is not installed.' try: import dask_cudf as _ # noqa return {'condition': False, 'reason': reason} except ImportError: return {'condition': True, 'reason': reason} def no_json_schema(): reason = 'jsonschema is not installed' try: import jsonschema # noqa return {'condition': False, 'reason': reason} except ImportError: return {'condition': True, 'reason': reason} def no_graphviz(): reason = 'graphviz is not installed' try: import graphviz # noqa return {'condition': False, 'reason': reason} except ImportError: return {'condition': True, 'reason': reason} def no_multiple(*args): condition = False reason = '' for arg in args: condition = (condition or arg['condition']) if arg['condition']: reason = arg['reason'] break return {'condition': condition, 'reason': reason} def skip_s390x(): condition = platform.machine() == "s390x" reason = "Known to fail on s390x" return {"condition": condition, "reason": reason} class IteratorForTest(xgb.core.DataIter): def __init__(self, X, y): assert len(X) == len(y) self.X = X self.y = y self.it = 0 super().__init__("./") def next(self, input_data): if self.it == len(self.X): return 0 # Use copy to make sure the iterator doesn't hold a reference to the data. input_data(data=self.X[self.it].copy(), label=self.y[self.it].copy()) gc.collect() # clear up the copy, see if XGBoost access freed memory. self.it += 1 return 1 def reset(self): self.it = 0 def as_arrays(self): X = np.concatenate(self.X, axis=0) y = np.concatenate(self.y, axis=0) return X, y # Contains a dataset in numpy format as well as the relevant objective and metric class TestDataset: def __init__(self, name, get_dataset, objective, metric): self.name = name self.objective = objective self.metric = metric self.X, self.y = get_dataset() self.w = None self.margin: Optional[np.ndarray] = None def set_params(self, params_in): params_in['objective'] = self.objective params_in['eval_metric'] = self.metric if self.objective == "multi:softmax": params_in["num_class"] = int(np.max(self.y) + 1) return params_in def get_dmat(self): return xgb.DMatrix(self.X, self.y, self.w, base_margin=self.margin) def get_device_dmat(self): w = None if self.w is None else cp.array(self.w) X = cp.array(self.X, dtype=np.float32) y = cp.array(self.y, dtype=np.float32) return xgb.DeviceQuantileDMatrix(X, y, w, base_margin=self.margin) def get_external_dmat(self): n_samples = self.X.shape[0] n_batches = 10 per_batch = n_samples // n_batches + 1 predictor = [] response = [] for i in range(n_batches): beg = i * per_batch end = min((i + 1) * per_batch, n_samples) assert end != beg X = self.X[beg: end, ...] y = self.y[beg: end] predictor.append(X) response.append(y) it = IteratorForTest(predictor, response) return xgb.DMatrix(it) def __repr__(self): return self.name @memory.cache def get_boston(): data = datasets.load_boston() return data.data, data.target @memory.cache def get_digits(): data = datasets.load_digits() return data.data, data.target @memory.cache def get_cancer(): data = datasets.load_breast_cancer() return data.data, data.target @memory.cache def get_sparse(): rng = np.random.RandomState(199) n = 2000 sparsity = 0.75 X, y = datasets.make_regression(n, random_state=rng) flag = rng.binomial(1, sparsity, X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): if flag[i, j]: X[i, j] = np.nan return X, y @memory.cache def get_mq2008(dpath): from sklearn.datasets import load_svmlight_files src = 'https://s3-us-west-2.amazonaws.com/xgboost-examples/MQ2008.zip' target = dpath + '/MQ2008.zip' if not os.path.exists(target): urllib.request.urlretrieve(url=src, filename=target) with zipfile.ZipFile(target, 'r') as f: f.extractall(path=dpath) (x_train, y_train, qid_train, x_test, y_test, qid_test, x_valid, y_valid, qid_valid) = load_svmlight_files( (dpath + "MQ2008/Fold1/train.txt", dpath + "MQ2008/Fold1/test.txt", dpath + "MQ2008/Fold1/vali.txt"), query_id=True, zero_based=False) return (x_train, y_train, qid_train, x_test, y_test, qid_test, x_valid, y_valid, qid_valid) @memory.cache def make_categorical( n_samples: int, n_features: int, n_categories: int, onehot: bool ): import pandas as pd rng = np.random.RandomState(1994) pd_dict = {} for i in range(n_features + 1): c = rng.randint(low=0, high=n_categories, size=n_samples) pd_dict[str(i)] = pd.Series(c, dtype=np.int64) df = pd.DataFrame(pd_dict) label = df.iloc[:, 0] df = df.iloc[:, 1:] for i in range(0, n_features): label += df.iloc[:, i] label += 1 df = df.astype("category") categories = np.arange(0, n_categories) for col in df.columns: df[col] = df[col].cat.set_categories(categories) if onehot: return pd.get_dummies(df), label return df, label _unweighted_datasets_strategy = strategies.sampled_from( [ TestDataset("boston", get_boston, "reg:squarederror", "rmse"), TestDataset("digits", get_digits, "multi:softmax", "mlogloss"), TestDataset("cancer", get_cancer, "binary:logistic", "logloss"), TestDataset( "mtreg", lambda: datasets.make_regression(n_samples=128, n_targets=3), "reg:squarederror", "rmse", ), TestDataset("sparse", get_sparse, "reg:squarederror", "rmse"), TestDataset( "empty", lambda: (np.empty((0, 100)), np.empty(0)), "reg:squarederror", "rmse", ), ] ) @strategies.composite def _dataset_weight_margin(draw): data: TestDataset = draw(_unweighted_datasets_strategy) if draw(strategies.booleans()): data.w = draw( arrays(np.float64, (len(data.y)), elements=strategies.floats(0.1, 2.0)) ) if draw(strategies.booleans()): num_class = 1 if data.objective == "multi:softmax": num_class = int(np.max(data.y) + 1) elif data.name == "mtreg": num_class = data.y.shape[1] data.margin = draw( arrays( np.float64, (data.y.shape[0] * num_class), elements=strategies.floats(0.5, 1.0), ) ) if num_class != 1: data.margin = data.margin.reshape(data.y.shape[0], num_class) return data # A strategy for drawing from a set of example datasets # May add random weights to the dataset dataset_strategy = _dataset_weight_margin() def non_increasing(L, tolerance=1e-4): return all((y - x) < tolerance for x, y in zip(L, L[1:])) def eval_error_metric(predt, dtrain: xgb.DMatrix): """Evaluation metric for xgb.train""" label = dtrain.get_label() r = np.zeros(predt.shape) gt = predt > 0.5 if predt.size == 0: return "CustomErr", 0 r[gt] = 1 - label[gt] le = predt <= 0.5 r[le] = label[le] return 'CustomErr', np.sum(r) def eval_error_metric_skl(y_true: np.ndarray, y_score: np.ndarray) -> float: """Evaluation metric that looks like metrics provided by sklearn.""" r = np.zeros(y_score.shape) gt = y_score > 0.5 r[gt] = 1 - y_true[gt] le = y_score <= 0.5 r[le] = y_true[le] return np.sum(r) def softmax(x): e = np.exp(x) return e / np.sum(e) def softprob_obj(classes): def objective(labels, predt): rows = labels.shape[0] grad = np.zeros((rows, classes), dtype=float) hess = np.zeros((rows, classes), dtype=float) eps = 1e-6 for r in range(predt.shape[0]): target = labels[r] p = softmax(predt[r, :]) for c in range(predt.shape[1]): assert target >= 0 or target <= classes g = p[c] - 1.0 if c == target else p[c] h = max((2.0 * p[c] * (1.0 - p[c])).item(), eps) grad[r, c] = g hess[r, c] = h grad = grad.reshape((rows * classes, 1)) hess = hess.reshape((rows * classes, 1)) return grad, hess return objective class DirectoryExcursion: def __init__(self, path: os.PathLike, cleanup=False): '''Change directory. Change back and optionally cleaning up the directory when exit. ''' self.path = path self.curdir = os.path.normpath(os.path.abspath(os.path.curdir)) self.cleanup = cleanup self.files = {} def __enter__(self): os.chdir(self.path) if self.cleanup: self.files = { os.path.join(root, f) for root, subdir, files in os.walk(self.path) for f in files } def __exit__(self, *args): os.chdir(self.curdir) if self.cleanup: files = { os.path.join(root, f) for root, subdir, files in os.walk(self.path) for f in files } diff = files.difference(self.files) for f in diff: os.remove(f) @contextmanager def captured_output(): """Reassign stdout temporarily in order to test printed statements Taken from: https://stackoverflow.com/questions/4219717/how-to-assert-output-with-nosetest-unittest-in-python Also works for pytest. """ new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err try: # Python 3.7+ from contextlib import nullcontext as noop_context except ImportError: # Python 3.6 from contextlib import suppress as noop_context CURDIR = os.path.normpath(os.path.abspath(os.path.dirname(__file__))) PROJECT_ROOT = os.path.normpath( os.path.join(CURDIR, os.path.pardir, os.path.pardir))
27.535124
101
0.603212
ace35e0698b42ad728fc39b43376756574423c0f
3,071
py
Python
build/sdk/sdk_common.py
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
build/sdk/sdk_common.py
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
build/sdk/sdk_common.py
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2021-08-23T11:33:57.000Z
2021-08-23T11:33:57.000Z
# Copyright 2018 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import functools import json class File(object): '''Wrapper class for file definitions.''' def __init__(self, json): self.source = json['source'] self.destination = json['destination'] def __str__(self): return '{%s <-- %s}' % (self.destination, self.source) @functools.total_ordering class Atom(object): '''Wrapper class for atom data, adding convenience methods.''' def __init__(self, json): self.json = json self.id = json['id'] self.metadata = json['meta'] self.label = json['gn-label'] self.category = json['category'] self.deps = json['deps'] self.files = [File(f) for f in json['files']] self.type = json['type'] def __str__(self): return str(self.id) def __hash__(self): return hash(self.label) def __eq__(self, other): return self.label == other.label def __ne__(self, other): return not __eq__(self, other) def __lt__(self, other): return self.id < other.id def gather_dependencies(manifests): '''Extracts the set of all required atoms from the given manifests, as well as the set of names of all the direct dependencies. ''' direct_deps = set() atoms = set() if manifests is None: return (direct_deps, atoms) for dep in manifests: with open(dep, 'r') as dep_file: dep_manifest = json.load(dep_file) direct_deps.update(dep_manifest['ids']) atoms.update([Atom(a) for a in dep_manifest['atoms']]) return (direct_deps, atoms) def detect_collisions(atoms): '''Detects name collisions in a given atom list.''' mappings = collections.defaultdict(lambda: []) for atom in atoms: mappings[atom.id].append(atom) has_collisions = False for id, group in mappings.items(): if len(group) == 1: continue has_collisions = True labels = [a.label for a in group] print('Targets sharing the SDK id %s:' % id) for label in labels: print(' - %s' % label) return has_collisions CATEGORIES = [ 'excluded', 'experimental', 'internal', 'cts', 'partner', 'public', ] def index_for_category(category): if not category in CATEGORIES: raise Exception('Unknown SDK category "%s"' % category) return CATEGORIES.index(category) def detect_category_violations(category, atoms): '''Detects mismatches in publication categories.''' has_violations = False category_index = index_for_category(category) for atom in atoms: if index_for_category(atom.category) < category_index: has_violations = True print( '%s has publication level %s, incompatible with %s' % (atom, atom.category, category)) return has_violations
27.176991
79
0.624552
933973550d1867b90948d3288e4890581f4c0f34
396
py
Python
online-shop/myshop/cart/forms.py
EssaAlshammri/django-by-example
d1a1cba9308d4f19bbb1228dbd191ad5540b2c78
[ "MIT" ]
3
2017-04-25T10:19:02.000Z
2017-06-07T12:50:30.000Z
online-shop/myshop/cart/forms.py
EssaAlshammri/django-by-example
d1a1cba9308d4f19bbb1228dbd191ad5540b2c78
[ "MIT" ]
null
null
null
online-shop/myshop/cart/forms.py
EssaAlshammri/django-by-example
d1a1cba9308d4f19bbb1228dbd191ad5540b2c78
[ "MIT" ]
null
null
null
from django import forms from django.utils.translation import gettext_lazy as _ PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField( choices=PRODUCT_QUANTITY_CHOICES, coerce=int, label=_('Quantity')) update = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput)
33
74
0.747475
a829eb0f19b349d7f22745c9b5d963ebf999ffe8
635
py
Python
data_collectors/generate_stable_join_selectivity_data_pgfplots.py
tinvukhac/deep-join
73e4b79b9e3b488860437bca278940c8a5b2ced8
[ "Apache-2.0" ]
null
null
null
data_collectors/generate_stable_join_selectivity_data_pgfplots.py
tinvukhac/deep-join
73e4b79b9e3b488860437bca278940c8a5b2ced8
[ "Apache-2.0" ]
null
null
null
data_collectors/generate_stable_join_selectivity_data_pgfplots.py
tinvukhac/deep-join
73e4b79b9e3b488860437bca278940c8a5b2ced8
[ "Apache-2.0" ]
null
null
null
def main(): print ('Generate data to copy to pgfplots') count = 5 query_ids = ['group {}'.format(i) for i in range(1, count + 1)] print (','.join(query_ids)) f = open('../data/bak/join_results_same_distribution_diff_width_height/join_selectivities/join_selectivities.csv') i = 0 line = f.readline() line = f.readline() while line and i < count: i += 1 data = line.strip().split(',') mean = data[8] std = data[9] print ('(group {},{}) +- ({},{})'.format(i, mean, std, std)) line = f.readline() f.close() if __name__ == '__main__': main()
24.423077
118
0.555906
acecb0d999647c96e6602c0ec4e31e7f0f786c3a
7,178
py
Python
scripts/dvs_file_reader.py
cisprague/smarc_perception
149bc7873a029466d7dbfbfb09ab9d34e6c9232b
[ "BSD-3-Clause" ]
null
null
null
scripts/dvs_file_reader.py
cisprague/smarc_perception
149bc7873a029466d7dbfbfb09ab9d34e6c9232b
[ "BSD-3-Clause" ]
null
null
null
scripts/dvs_file_reader.py
cisprague/smarc_perception
149bc7873a029466d7dbfbfb09ab9d34e6c9232b
[ "BSD-3-Clause" ]
null
null
null
from enum import Enum from dataclasses import dataclass import utils from typing import List, BinaryIO, Tuple, Dict import struct from pathlib import Path from matplotlib import pyplot as plt import numpy as np class Side(Enum): """The side-scan sonar ping side (port or starboard)""" PORT = 0 STARBOARD = 1 @dataclass class SSSPing: """A side-scan sonar ping.""" lat: float #Ctype double in V1_Position in deepvision_sss_driver lon: float #Ctype double in V1_Position deepvision_sss_driver speed: float heading: float side: Side ping: List[int] def plot(self) -> None: plt.figure() plt.plot(self.ping, linestyle='-', marker='o', markersize=1, linewidth=.5) plt.title(f'SSS Ping, side = {self.side}') @dataclass class DVSFileHeader: """DVS File header. See details in deepvision_sss_driver.""" version: int = -1 sample_res: float = -1 line_rate: float = -1 n_samples: int = -1 left: bool = False right: bool = False class DVSFile: def __init__(self, filename: str): self.filename = filename # Placeholder attributes, filled by _parse_file() self.header = None self.sss_pings = {Side.PORT: [], Side.STARBOARD: []} self._parse_file() def _parse_file(self): with open(self.filename, 'rb') as f: self.header = self._parse_header(f) while True: try: ping = self._parse_ping(f) for key, value in ping.items(): self.sss_pings[key].append(value) except struct.error as e: pointer_pos = f.tell() file_size = Path(self.filename).stat().st_size print(f'Current pointer position: {pointer_pos}') print(f'Total file size: {file_size}') print(f'Remaining bytes: {file_size - pointer_pos}') print(f'Parsing completed: {e}') return def _parse_ping(self, fileobj: BinaryIO) -> Dict[Side, SSSPing]: """Read one side-scan ping from the fileobj. Note that one ping may consists of two channels (port and starboard).""" lat = utils.unpack_struct(fileobj, struct_type='double') lon = utils.unpack_struct(fileobj, struct_type='double') speed = utils.unpack_struct(fileobj, struct_type='float') heading = utils.unpack_struct(fileobj, struct_type='float') ping = dict() if self.header.left: left_channel = utils.unpack_channel( fileobj, channel_size=self.header.n_samples) ping[Side.PORT] = SSSPing(lat=lat, lon=lon, speed=speed, heading=heading, side=Side.PORT, ping=left_channel) if self.header.right: right_channel = utils.unpack_channel( fileobj, channel_size=self.header.n_samples) ping[Side.STARBOARD] = SSSPing(lat=lat, lon=lon, speed=speed, heading=heading, side=Side.STARBOARD, ping=right_channel) return ping def _parse_header(self, fileobj: BinaryIO) -> DVSFileHeader: """Read version and V1_FileHeader from the file object""" header = DVSFileHeader() header.version = utils.unpack_struct(fileobj, struct_type='uint') header.sample_res = utils.unpack_struct(fileobj, struct_type='float') header.line_rate = utils.unpack_struct(fileobj, struct_type='float') header.n_samples = utils.unpack_struct(fileobj, struct_type='int') header.left = utils.unpack_struct(fileobj, struct_type='bool') header.right = utils.unpack_struct(fileobj, struct_type='bool') # DVSFileHeader object is 16 bytes, although all fields together adds up to # 14 bytes. The 2 extra bytes are for probably for data structure alignment fileobj.read(2) return header def _get_pings_from_one_side(self, side: Side, start_idx: int, end_idx) -> np.ndarray: pings = [] for i in range(start_idx, end_idx): pings.append(self.sss_pings[side][i].ping) return np.array(pings) def _imshow(self, sss_pings: np.ndarray, start_idx: int, end_idx: int, title: str, figsize: tuple) -> None: """Plot multiple SSSPings as an heatmap.""" num_pings, num_channels = sss_pings.shape plt.figure(figsize=figsize) plt.imshow(sss_pings, origin='lower', extent=(0, num_channels, start_idx, end_idx)) plt.title(title) def plot_one_side( self, side: Side, start_idx: int = 0, end_idx: int = None, figsize: tuple = (5, 10)) -> np.ndarray: """Plot sss pings between (start_idx, end_idx) from the requested side if exists.""" if side not in self.sss_pings.keys(): raise ValueError( f'Side {side} does not exist. Available sides: {self.sss_pings.keys()}' ) if not end_idx: end_idx = len(self.sss_pings[side]) side_pings = self._get_pings_from_one_side(side, start_idx, end_idx) title = f'SSS pings from {side} of {self.filename}' self._imshow(side_pings, start_idx, end_idx, title, figsize) return side_pings def plot(self, start_idx: int = 0, end_idx: int = None, figsize: tuple = (10, 20)) -> np.ndarray: """Plot all sss pings in the DVSFile""" if self.header.right and not self.header.left: return self.plot_one_side(side=Side.STARBOARD, start_idx=start_idx, end_idx=end_idx) if self.header.left and not self.header.right: return self.plot_one_side(side=Side.PORT, start_idx=start_idx, end_idx=end_idx) if not end_idx: end_idx = min(len(self.sss_pings[Side.PORT]), len(self.sss_pings[Side.STARBOARD])) left_pings = self._get_pings_from_one_side(Side.PORT, start_idx, end_idx) right_pings = self._get_pings_from_one_side(Side.STARBOARD, start_idx, end_idx) sss_image = np.concatenate((np.flip(left_pings, axis=1), right_pings), axis=1) title = f'SSS pings from {self.filename}' self._imshow(sss_image, start_idx, end_idx, title, figsize) return sss_image
38.8
87
0.552104
db2068552adcf4770064cca1687231a679e77c72
385
py
Python
backend/api/api/settings/test.py
lanoir42/makefeeconverge
61456d581a415257ebeb6b1d102820a164ded913
[ "MIT" ]
null
null
null
backend/api/api/settings/test.py
lanoir42/makefeeconverge
61456d581a415257ebeb6b1d102820a164ded913
[ "MIT" ]
5
2022-03-04T14:53:43.000Z
2022-03-21T00:00:28.000Z
backend/api/api/settings/test.py
lanoir42/makefeeconverge
61456d581a415257ebeb6b1d102820a164ded913
[ "MIT" ]
null
null
null
from api.settings.base import * # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "test", "USER": "test", "PASSWORD": "test", "HOST": "localhost", "PORT": "5432", "TEST": { "NAME": "test", }, }, }
21.388889
63
0.496104
de93a3cd800ef9d73afc7a1317bb9849aba6346f
1,444
py
Python
pythran/tests/cases/calculate_u.py
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
1
2018-03-24T00:33:03.000Z
2018-03-24T00:33:03.000Z
pythran/tests/cases/calculate_u.py
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
pythran/tests/cases/calculate_u.py
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
# from the paper `using cython to speedup numerical python programs' #pythran export timeloop(float, float, float, float, float, float list list, float list list, float list list) #pythran export timeloop(float, float, float, float, float, int list list, int list list, int list list) #bench A=[list(range(70)) for i in range(100)] ; B=[list(range(70)) for i in range(100)] ; C=[list(range(70)) for i in range(100)] ; timeloop(1.,2.,.01,.1,.18, A,B,C ) #runas A=[list(range(20)) for i in range(10)] ; B=[list(range(20)) for i in range(10)] ; C=[list(range(20)) for i in range(10)] ; timeloop(1.,2.,.01,.1,.18, A,B,C ) def timeloop(t, t_stop, dt, dx, dy, u, um, k): while t <= t_stop: t += dt new_u = calculate_u(dt, dx, dy, u, um, k) um = u u = new_u return u def calculate_u(dt, dx, dy, u, um, k): up = [ [0.]*len(u[0]) for i in xrange(len(u)) ] "omp parallel for" for i in xrange(1, len(u)-1): for j in xrange(1, len(u[0])-1): up[i][j] = 2*u[i][j] - um[i][j] + \ (dt/dx)**2*( (0.5*(k[i+1][j] + k[i][j])*(u[i+1][j] - u[i][j]) - 0.5*(k[i][j] + k[i-1][j])*(u[i][j] - u[i-1][j]))) + \ (dt/dy)**2*( (0.5*(k[i][j+1] + k[i][j])*(u[i][j+1] - u[i][j]) - 0.5*(k[i][j] + k[i][j-1])*(u[i][j] - u[i][j-1]))) return up
53.481481
167
0.481994
d966191e573f2642caa7e62b2010d2b26765a27a
8,187
py
Python
datapreparation.py
asisakov/stock_prediction_finhub_2y
7bd107d2d11e7e736e1895b1259d43f1c79d6cf9
[ "MIT" ]
null
null
null
datapreparation.py
asisakov/stock_prediction_finhub_2y
7bd107d2d11e7e736e1895b1259d43f1c79d6cf9
[ "MIT" ]
null
null
null
datapreparation.py
asisakov/stock_prediction_finhub_2y
7bd107d2d11e7e736e1895b1259d43f1c79d6cf9
[ "MIT" ]
null
null
null
# Import libraries import datetime import os import logging import pandas as pd import numpy as np from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import pickle import config SEED = config.SEED # Configure and create logger current_dir = os.getcwd() log_path = os.path.join(current_dir, 'LOGS','data_preparation_info.log') logging.basicConfig(filename=log_path, format='%(asctime)s %(message)s', filemode='w') logger = logging.getLogger() logger.setLevel(logging.INFO) # Define functions def exctract_features_from_reports(report, start=datetime.datetime(2009, 1, 1), end=datetime.datetime(2019, 12, 31)): """ Function for data retrieval from dict type to pd.DataFrame :param report: dictionary with financial report data for each period :param start: first date in observation range, default = 01.01.2009 :param end: last date in observation range, default = 31.12.2019 :return: dict with DataFrames, which contains structured information from financial reports """ res = dict() for i in range(len(report) - 1, -1, -1): if report[i]['quarter'] == 0: report[i]['year'] -= 1 report[i]['quarter'] = 4 curr_date = pd.to_datetime(f"{report[i]['year']}Q{report[i]['quarter']}") if curr_date < start: break # if curr_date > end: # continue buff_info = dict() for key in ['bs', 'cf', 'ic']: for line in report[i]['report'][key]: if not isinstance(line, dict): logger.info(f"[CHECK] For {report[i]['symbol']} at {curr_date}, in {key} no info at line: {line}") continue if f"{key}_{line['concept']}_{line['unit']}" not in buff_info.keys(): if line['value'] == 'N/A': buff_info[f"{key}_{line['concept']}"] = np.nan elif line['value'] == '': buff_info[f"{key}_{line['concept']}"] = 0 else: buff_info[f"{key}_{line['concept']}"] = int(line['value']) res[curr_date] = buff_info result = pd.DataFrame(res) return result.transpose() def make_target_and_features(dat, targetcolumn='Close Price', num=4): """ Function to add columns with prices for past 'num' observations :param dat: DataFrame with data and price info for certain period and ticker :param targetcolumn: name of column with price information :param num: total number of last observations to append :return: DataFrame with additional columns for price lags """ data = dat.copy() data = data.sort_index() for k in range(num): data[f'{targetcolumn}_last_{k+1}Q'] = np.nan for i in range(len(data.index)-1,-1,-1): for k in range(num): data.loc[data.index[i],f'{targetcolumn}_last_{k+1}Q'] = data.loc[data.index[i - (k+1)],targetcolumn] return data def form_big_onlyprices(data, targetcolumn='Close Price', num=4): """ Formation of DataFrame for each industry, which contains only price info for current and last 'num' observations :param data: dict of DataFrames with data and price info for certain period and ticker :param targetcolumn: name of column with price information :param num: total number of last observations to append :return: dict of DataFrames with only prices for each industry """ res = pd.DataFrame() for ticker in data.keys(): data[ticker]['ticker'] = ticker res = pd.concat([res, data[ticker]], sort=True) cols = [] cols.append('ticker') for k in range(num): cols.append(f'{targetcolumn}_last_{k+1}Q') cols.append(targetcolumn) return res[cols] def form_big_dataset(data): """ Formation of DataFrame for each industry, which contains prices and reports info for current and last 'num' observations :param data: dict of DataFrames with data and price info for certain period and ticker :return: dict with DataFrames, which contains prices and reports info for each industry """ res = pd.DataFrame() for ticker in data.keys(): data[ticker]['ticker'] = ticker res = pd.concat([res, data[ticker]], sort=True) return res # Define global variables START = config.START END = config.END LAG_NUM = config.LAG_NUM MAX_NANS_COUNT = config.MAX_NANS_COUNT TARGETCOLUMN = config.TARGETCOLUMN # Open loaded data reports_path = os.path.join(current_dir, 'DATA', 'reports.pkl') prices_path = os.path.join(current_dir, 'DATA', 'prices.pkl') with open(reports_path, 'rb') as outp: reports = pickle.load(outp) with open(prices_path, 'rb') as outp: quarter_prices = pickle.load(outp) logger.info(f"[INFO] Succefully loaded saved data") # Make some figures with price dynamics price_plots_path = os.path.join(current_dir, 'Figures', 'price_plots.pdf') with PdfPages(price_plots_path) as pdf: for key in reports.keys(): fig = plt.figure(figsize=(16,9)) for ticker in reports[key]: plt.plot(quarter_prices[key][ticker], label=ticker) plt.ylabel('Price, $') plt.xlabel('Date') plt.title(f'Prices in {key.upper()} industry') plt.legend() pdf.savefig(fig) plt.close() logger.info(f"[INFO] Saved price plots to pdf doc at path: {price_plots_path}") # If prices seems normal, proceed to Financial Report data extraction data = dict() for key in reports.keys(): data[key] = dict() for ticker in reports[key]: dat1 = exctract_features_from_reports(reports[key][ticker]['data']) dat2 = dat1.join(quarter_prices[key][ticker]) data[key][ticker] = make_target_and_features(dat2, targetcolumn=config.TARGETCOLUMN, num=config.LAG_NUM) logger.info("[INFO] Initial data is prepared") # Check formed dataset on Apple company check_formed_data_path = os.path.join(current_dir, 'DATA', 'AAPL_full.xlsx') data['it']['AAPL'].to_excel(check_formed_data_path, index=True) logger.info(f"[INFO] Saved price plots to pdf doc at path: {price_plots_path}") # Save initial data for each company data_path = os.path.join(current_dir, 'DATA', 'data.pkl') with open(data_path, 'wb') as outp: pickle.dump(data, outp, pickle.HIGHEST_PROTOCOL) logger.info(f"[INFO] Succefully saved data at {data_path}") # Make dataset which contains only price info formed_data_short = dict() for key in data.keys(): formed_data_short[key] = form_big_onlyprices(data[key], targetcolumn=config.TARGETCOLUMN, num=config.LAG_NUM) formed_data_short[key] = formed_data_short[key].loc[(formed_data_short[key].index >= START) & (formed_data_short[key].index <= END)] # Save only prices dataset data_short_path = os.path.join(current_dir, 'DATA', 'data_short_prices.pkl') with open(data_short_path, 'wb') as outp: pickle.dump(formed_data_short, outp, pickle.HIGHEST_PROTOCOL) logger.info(f"[INFO] Succefully saved data with only prices at {data_short_path}") # Make dataset with financial data formed_data_fr = dict() for key in data.keys(): formed_data_fr[key] = form_big_dataset(data[key]) # Drop columns with a lot of NaN's formed_data_short_fr = dict() dropcols = dict() for key in data.keys(): dropcols[key] = [] rowcount, colcount = formed_data_fr[key].shape[0], formed_data_fr[key].shape[1] for column in formed_data_fr[key].columns: if sum(formed_data_fr[key][column].isna()) / rowcount > MAX_NANS_COUNT: dropcols[key].append(column) dropcols[key] = [i for i in dropcols[key] if not i.startswith(config.TARGETCOLUMN)] formed_data_short_fr[key] = formed_data_fr[key].drop(columns=dropcols[key]) formed_data_short_fr[key] = formed_data_short_fr[key].loc[(formed_data_short_fr[key].index >= START) & (formed_data_short_fr[key].index <= END)] # Save dataset with financial info data_fr_path = os.path.join(current_dir, 'DATA', 'data_short_financial.pkl') with open(data_fr_path, 'wb') as outp: pickle.dump(formed_data_short_fr, outp, pickle.HIGHEST_PROTOCOL) logger.info(f"[INFO] Succefully financial data at {data_fr_path}")
34.25523
148
0.677904
2b2a7bbfa679650afc230540c9bbd75a2a3ee9ff
98
py
Python
src/zsl_openapi/configuration.py
AtteqCom/zsl_openapi
0d9fac32ae3516b2f53a302716f162a4d688bed0
[ "BSD-2-Clause" ]
null
null
null
src/zsl_openapi/configuration.py
AtteqCom/zsl_openapi
0d9fac32ae3516b2f53a302716f162a4d688bed0
[ "BSD-2-Clause" ]
null
null
null
src/zsl_openapi/configuration.py
AtteqCom/zsl_openapi
0d9fac32ae3516b2f53a302716f162a4d688bed0
[ "BSD-2-Clause" ]
null
null
null
from collections import namedtuple OpenAPIConfiguration = namedtuple('OpenAPIConfiguration', [])
24.5
61
0.826531
003d5f06ee0d03eac930dced8cee3d1c6af9ee87
479
py
Python
new/VL53L0X_rasp_python/a.py
Deepakbaskar94/Autonomous_car_base_program
9ab79aacccabb4720f9eb419838497c565d01665
[ "Apache-2.0" ]
null
null
null
new/VL53L0X_rasp_python/a.py
Deepakbaskar94/Autonomous_car_base_program
9ab79aacccabb4720f9eb419838497c565d01665
[ "Apache-2.0" ]
null
null
null
new/VL53L0X_rasp_python/a.py
Deepakbaskar94/Autonomous_car_base_program
9ab79aacccabb4720f9eb419838497c565d01665
[ "Apache-2.0" ]
null
null
null
import time import VL53L0X # Create a VL53L0X object tof = VL53L0X.VL53L0X() # Start ranging tof.start_ranging(VL53L0X.VL53L0X_BETTER_ACCURACY_MODE) timing = tof.get_timing() if (timing &lt> 20000): timing = 20000 print ("Timing %d ms" % (timing/1000)) for count in range(1,101): distance = tof.get_distance() if (distance &gt> 0): print ("%d mm, %d cm, %d" % (distance, (distance/10), count)) time.sleep(timing/1000000.00) tof.stop_ranging()
20.826087
69
0.670146
a2e7e57643e95a257e68db8346a6439369fb07e9
21
py
Python
src/rolw_dummy_package/__init__.py
rolandweber/try-out-github-workflows
83520a49990eca81a205c489cf53a10a179af42f
[ "CC0-1.0" ]
null
null
null
src/rolw_dummy_package/__init__.py
rolandweber/try-out-github-workflows
83520a49990eca81a205c489cf53a10a179af42f
[ "CC0-1.0" ]
null
null
null
src/rolw_dummy_package/__init__.py
rolandweber/try-out-github-workflows
83520a49990eca81a205c489cf53a10a179af42f
[ "CC0-1.0" ]
null
null
null
version = '0.0.0a0'
7
19
0.571429
bf3a85b15809d255c8529de683a9927a8e833807
8,309
py
Python
bot/cogs/sqcs_plugin/cadre.py
phantom0174/HSQCC_bot
93d4b40f7d8885bcf927590926370d67e05a5760
[ "MIT" ]
4
2020-11-25T16:31:41.000Z
2021-08-28T21:35:01.000Z
bot/cogs/sqcs_plugin/cadre.py
phantom0174/HSQCC_bot
93d4b40f7d8885bcf927590926370d67e05a5760
[ "MIT" ]
12
2020-12-21T09:42:13.000Z
2021-05-16T06:17:49.000Z
bot/cogs/sqcs_plugin/cadre.py
phantom0174/HSQCC_bot
93d4b40f7d8885bcf927590926370d67e05a5760
[ "MIT" ]
2
2021-04-13T08:28:12.000Z
2021-07-11T02:41:35.000Z
from discord.ext import commands import os from ...core.cog_config import CogExtension from ...core.db.jsonstorage import JsonApi from ...core.db.mongodb import Mongo from ...core.utils import Time import discord class Cadre(CogExtension): @commands.group() async def ca(self, ctx): pass @ca.command() async def apply(self, ctx, cadre: str): """cmd 於幹部申請區申請 幹部<cadre> .cadre: 可為SQCS現在有的幹部部門 """ cadre_set_cursor, cadre_cursor = Mongo('sqcs-bot').get_curs(['CadreSetting', 'Cadre']) cadre_setting = cadre_set_cursor.find_one({"_id": 0}) if ctx.channel.id != cadre_setting['apply_channel']: return cadre_options = cadre_setting['apply_options'] if cadre not in cadre_options: return await ctx.send( content=f':x: 職位選項必須要在 {cadre_options} 中!', delete_after=8 ) data = cadre_cursor.find_one({"_id": ctx.author.id}) if data: return await ctx.author.send( f':x: {ctx.author.mention} (id: {data["_id"]})\n' f':scroll: 你已經於 {data["apply_time"]} 申請 `{data["apply_cadre"]}` 職位\n' f'> 請確認是否發生 `重複申請` `同時申請兩職位` `申請錯誤`\n' f'> 如有疑問,請洽總召' ) apply_time = Time.get_info('whole') apply_info = { "_id": ctx.author.id, "name": ctx.author.display_name, "apply_cadre": cadre, "apply_time": apply_time } cadre_cursor.insert_one(apply_info) # no perm to send msg to user via server try: await ctx.author.send( f':white_check_mark: 我收到你的申請了!請耐心等待審核\n' f'申請人名字:{ctx.author.display_name},\n' f'申請人id:{ctx.author.id},\n' f'申請職位:{cadre},\n' f'申請時間:{apply_time}' ) except BaseException: pass @ca.command() @commands.has_any_role('總召', 'Administrator') async def list(self, ctx): """cmd 列出現在的所有幹部申請。 """ cadre_cursor = Mongo('sqcs-bot').get_cur('Cadre') data = cadre_cursor.find({}) if data.count() == 0: return await ctx.send(':x: 職位申請名單為空!') apply_info = '' for item in data: apply_info += ( f'{item["name"]}({item["_id"]}): ' f'{item["apply_cadre"]}, ' f'{item["apply_time"]}\n' ) if len(apply_info) > 1600: await ctx.send(apply_info) apply_info = '' if len(apply_info) > 0: # no perm to send msg to user via server try: await ctx.author.send(apply_info) except BaseException: pass @ca.command() @commands.has_any_role('總召', 'Administrator') async def permit(self, ctx, permit_id: int): """cmd 批准 成員<permit_id> 的幹部申請。 .permit_id: 要批准成員的Discord id """ cadre_cursor = Mongo('sqcs-bot').get_cur('Cadre') data = cadre_cursor.find_one({"_id": permit_id}) if not data: return await ctx.send(f':x: 申請名單中沒有id為 {permit_id} 的申請!') # no perm to send msg to user via server try: await ctx.author.send( f':white_check_mark: 你已批准 {data["name"]} 對職位 {data["apply_cadre"]} 的申請!' ) except BaseException: pass member = ctx.guild.get_member(data["_id"]) # no perm to send msg to user via server try: await member.send( f':white_check_mark: 你於 {data["apply_time"]} 申請 {data["apply_cadre"]} 的程序已通過!\n' f'此為幹部群的連結,請在加入之後使用指令領取屬於你的身分組\n' f'{os.environ.get("WORKING_DC_GUILD_LINK")}' ) except BaseException: pass cadre_cursor.delete_one({"_id": data["_id"]}) @ca.command() @commands.has_any_role('總召', 'Administrator') async def search(self, ctx, search_id: int): """cmd 查詢 成員<permit_id> 的幹部申請。 .permit_id: 要查詢成員的Discord id """ cadre_cursor = Mongo('sqcs-bot').get_cur('Cadre') data = cadre_cursor.find_one({"_id": search_id}) if not data: return await ctx.send(f':x: 申請名單中沒有id為 {search_id} 的申請!') await ctx.send( f'{data["name"]}({data["_id"]}): ' f'{data["apply_cadre"]}, ' f'{data["apply_time"]}' ) @ca.command(aliases=['delete']) @commands.has_any_role('總召', 'Administrator') async def remove(self, ctx, delete_id: int): """cmd 移除 成員<permit_id> 的幹部申請。 .permit_id: 要移除的成員之Discord id """ cadre_cursor = Mongo('sqcs-bot').get_cur('Cadre') data = cadre_cursor.find_one({"_id": delete_id}) if not data: return await ctx.send(f':x: 申請名單中沒有id為 {delete_id} 的申請!') cadre_cursor.delete_one({"_id": delete_id}) await ctx.send(f':white_check_mark: 成員 {data["name"]}({delete_id}) 的申請已被刪除!') # need to be fixed! class GuildRole(CogExtension): @commands.group(aliases=['rl']) @commands.has_any_role('總召', 'Administrator') async def role_level(self, ctx): pass @role_level.command() async def init(self, ctx): default_role = ctx.guild.get_role(743654256565026817) new_default_role = ctx.guild.get_role(823803958052257813) for member in ctx.guild.members: if member.bot: continue if default_role in member.roles: try: await member.remove_roles(default_role) await member.add_roles(new_default_role) except BaseException: pass await ctx.send(':white_check_mark: 指令執行完畢!') @role_level.command() async def init_single(self, ctx, member: discord.Member): default_role = ctx.guild.get_role(823803958052257813) for role in member.roles: if role.name != '@everyone': await member.remove_roles(role) await member.add_roles(default_role) await ctx.send(':white_check_mark: 指令執行完畢!') @role_level.command() async def advance(self, ctx, member: discord.Member): if member not in ctx.guild.members: return await ctx.send(f':x: 不存在成員 {member.display_name}!') sta_json = JsonApi.get('StaticSetting') name_to_index: dict = sta_json['level_role_id'] current_roles = member.roles for role in current_roles: if role.name in name_to_index.keys(): name_to_index: dict = sta_json['level_role_name_to_index'] index_to_name: dict = sta_json['level_role_index_to_name'] advance_index = int(name_to_index.get(role.name)) + 1 new_role_name = index_to_name.get(str(advance_index)) new_role = ctx.guild.get_role(name_to_index.get(new_role_name)) await member.remove_roles(role) await member.add_roles(new_role) break await ctx.send(':white_check_mark: 指令執行完畢!') @role_level.command() async def retract(self, ctx, member: discord.Member): if member not in ctx.guild.members: return await ctx.send(f':x: 不存在成員 {member.display_name}!') sta_json = JsonApi.get('StaticSetting') name_to_index: dict = sta_json['level_role_id'] current_roles = member.roles for role in current_roles: if role.name in name_to_index.keys(): name_to_index: dict = sta_json['level_role_name_to_index'] index_to_name: dict = sta_json['level_role_index_to_name'] advance_index = int(name_to_index.get(role.name)) - 1 new_role_name = index_to_name.get(str(advance_index)) new_role = ctx.guild.get_role(name_to_index.get(new_role_name)) await member.remove_roles(role) await member.add_roles(new_role) break await ctx.send(':white_check_mark: 指令執行完畢!') def setup(bot): bot.add_cog(Cadre(bot)) bot.add_cog(GuildRole(bot))
31.957692
96
0.567096
f69bcba68d64bb95d63a2f4b3336c59193caf48f
616,576
py
Python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/models/_models.py
vchske/azure-sdk-for-python
6383ed3676b7355af7be394562b126209961ec13
[ "MIT" ]
null
null
null
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/models/_models.py
vchske/azure-sdk-for-python
6383ed3676b7355af7be394562b126209961ec13
[ "MIT" ]
1
2019-06-04T18:12:16.000Z
2019-06-04T18:12:16.000Z
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/models/_models.py
vchske/azure-sdk-for-python
6383ed3676b7355af7be394562b126209961ec13
[ "MIT" ]
null
null
null
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model from msrest.exceptions import HttpOperationError class AddressSpace(Model): """AddressSpace contains an array of IP address ranges that can be used by subnets of the virtual network. :param address_prefixes: A list of address blocks reserved for this virtual network in CIDR notation. :type address_prefixes: list[str] """ _attribute_map = { 'address_prefixes': {'key': 'addressPrefixes', 'type': '[str]'}, } def __init__(self, **kwargs): super(AddressSpace, self).__init__(**kwargs) self.address_prefixes = kwargs.get('address_prefixes', None) class Resource(Model): """Common resource representation. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__(self, **kwargs): super(Resource, self).__init__(**kwargs) self.id = kwargs.get('id', None) self.name = None self.type = None self.location = kwargs.get('location', None) self.tags = kwargs.get('tags', None) class ApplicationGateway(Resource): """Application gateway resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param sku: SKU of the application gateway resource. :type sku: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySku :param ssl_policy: SSL policy of the application gateway resource. :type ssl_policy: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslPolicy :ivar operational_state: Operational state of the application gateway resource. Possible values include: 'Stopped', 'Starting', 'Running', 'Stopping' :vartype operational_state: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayOperationalState :param gateway_ip_configurations: Subnets of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type gateway_ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayIPConfiguration] :param authentication_certificates: Authentication certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type authentication_certificates: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayAuthenticationCertificate] :param trusted_root_certificates: Trusted Root certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type trusted_root_certificates: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayTrustedRootCertificate] :param ssl_certificates: SSL certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type ssl_certificates: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslCertificate] :param frontend_ip_configurations: Frontend IP addresses of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type frontend_ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayFrontendIPConfiguration] :param frontend_ports: Frontend ports of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type frontend_ports: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayFrontendPort] :param probes: Probes of the application gateway resource. :type probes: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayProbe] :param backend_address_pools: Backend address pool of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type backend_address_pools: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendAddressPool] :param backend_http_settings_collection: Backend http settings of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type backend_http_settings_collection: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendHttpSettings] :param http_listeners: Http listeners of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type http_listeners: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayHttpListener] :param url_path_maps: URL path map of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type url_path_maps: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayUrlPathMap] :param request_routing_rules: Request routing rules of the application gateway resource. :type request_routing_rules: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayRequestRoutingRule] :param rewrite_rule_sets: Rewrite rules for the application gateway resource. :type rewrite_rule_sets: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayRewriteRuleSet] :param redirect_configurations: Redirect configurations of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). :type redirect_configurations: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayRedirectConfiguration] :param web_application_firewall_configuration: Web application firewall configuration. :type web_application_firewall_configuration: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayWebApplicationFirewallConfiguration :param firewall_policy: Reference of the FirewallPolicy resource. :type firewall_policy: ~azure.mgmt.network.v2019_06_01.models.SubResource :param enable_http2: Whether HTTP2 is enabled on the application gateway resource. :type enable_http2: bool :param enable_fips: Whether FIPS is enabled on the application gateway resource. :type enable_fips: bool :param autoscale_configuration: Autoscale Configuration. :type autoscale_configuration: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayAutoscaleConfiguration :param resource_guid: Resource GUID property of the application gateway resource. :type resource_guid: str :param provisioning_state: Provisioning state of the application gateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param custom_error_configurations: Custom error configurations of the application gateway resource. :type custom_error_configurations: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayCustomError] :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param zones: A list of availability zones denoting where the resource needs to come from. :type zones: list[str] :param identity: The identity of the application gateway, if configured. :type identity: ~azure.mgmt.network.v2019_06_01.models.ManagedServiceIdentity """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'operational_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'sku': {'key': 'properties.sku', 'type': 'ApplicationGatewaySku'}, 'ssl_policy': {'key': 'properties.sslPolicy', 'type': 'ApplicationGatewaySslPolicy'}, 'operational_state': {'key': 'properties.operationalState', 'type': 'str'}, 'gateway_ip_configurations': {'key': 'properties.gatewayIPConfigurations', 'type': '[ApplicationGatewayIPConfiguration]'}, 'authentication_certificates': {'key': 'properties.authenticationCertificates', 'type': '[ApplicationGatewayAuthenticationCertificate]'}, 'trusted_root_certificates': {'key': 'properties.trustedRootCertificates', 'type': '[ApplicationGatewayTrustedRootCertificate]'}, 'ssl_certificates': {'key': 'properties.sslCertificates', 'type': '[ApplicationGatewaySslCertificate]'}, 'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[ApplicationGatewayFrontendIPConfiguration]'}, 'frontend_ports': {'key': 'properties.frontendPorts', 'type': '[ApplicationGatewayFrontendPort]'}, 'probes': {'key': 'properties.probes', 'type': '[ApplicationGatewayProbe]'}, 'backend_address_pools': {'key': 'properties.backendAddressPools', 'type': '[ApplicationGatewayBackendAddressPool]'}, 'backend_http_settings_collection': {'key': 'properties.backendHttpSettingsCollection', 'type': '[ApplicationGatewayBackendHttpSettings]'}, 'http_listeners': {'key': 'properties.httpListeners', 'type': '[ApplicationGatewayHttpListener]'}, 'url_path_maps': {'key': 'properties.urlPathMaps', 'type': '[ApplicationGatewayUrlPathMap]'}, 'request_routing_rules': {'key': 'properties.requestRoutingRules', 'type': '[ApplicationGatewayRequestRoutingRule]'}, 'rewrite_rule_sets': {'key': 'properties.rewriteRuleSets', 'type': '[ApplicationGatewayRewriteRuleSet]'}, 'redirect_configurations': {'key': 'properties.redirectConfigurations', 'type': '[ApplicationGatewayRedirectConfiguration]'}, 'web_application_firewall_configuration': {'key': 'properties.webApplicationFirewallConfiguration', 'type': 'ApplicationGatewayWebApplicationFirewallConfiguration'}, 'firewall_policy': {'key': 'properties.firewallPolicy', 'type': 'SubResource'}, 'enable_http2': {'key': 'properties.enableHttp2', 'type': 'bool'}, 'enable_fips': {'key': 'properties.enableFips', 'type': 'bool'}, 'autoscale_configuration': {'key': 'properties.autoscaleConfiguration', 'type': 'ApplicationGatewayAutoscaleConfiguration'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'custom_error_configurations': {'key': 'properties.customErrorConfigurations', 'type': '[ApplicationGatewayCustomError]'}, 'etag': {'key': 'etag', 'type': 'str'}, 'zones': {'key': 'zones', 'type': '[str]'}, 'identity': {'key': 'identity', 'type': 'ManagedServiceIdentity'}, } def __init__(self, **kwargs): super(ApplicationGateway, self).__init__(**kwargs) self.sku = kwargs.get('sku', None) self.ssl_policy = kwargs.get('ssl_policy', None) self.operational_state = None self.gateway_ip_configurations = kwargs.get('gateway_ip_configurations', None) self.authentication_certificates = kwargs.get('authentication_certificates', None) self.trusted_root_certificates = kwargs.get('trusted_root_certificates', None) self.ssl_certificates = kwargs.get('ssl_certificates', None) self.frontend_ip_configurations = kwargs.get('frontend_ip_configurations', None) self.frontend_ports = kwargs.get('frontend_ports', None) self.probes = kwargs.get('probes', None) self.backend_address_pools = kwargs.get('backend_address_pools', None) self.backend_http_settings_collection = kwargs.get('backend_http_settings_collection', None) self.http_listeners = kwargs.get('http_listeners', None) self.url_path_maps = kwargs.get('url_path_maps', None) self.request_routing_rules = kwargs.get('request_routing_rules', None) self.rewrite_rule_sets = kwargs.get('rewrite_rule_sets', None) self.redirect_configurations = kwargs.get('redirect_configurations', None) self.web_application_firewall_configuration = kwargs.get('web_application_firewall_configuration', None) self.firewall_policy = kwargs.get('firewall_policy', None) self.enable_http2 = kwargs.get('enable_http2', None) self.enable_fips = kwargs.get('enable_fips', None) self.autoscale_configuration = kwargs.get('autoscale_configuration', None) self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.custom_error_configurations = kwargs.get('custom_error_configurations', None) self.etag = kwargs.get('etag', None) self.zones = kwargs.get('zones', None) self.identity = kwargs.get('identity', None) class SubResource(Model): """Reference to another subresource. :param id: Resource ID. :type id: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__(self, **kwargs): super(SubResource, self).__init__(**kwargs) self.id = kwargs.get('id', None) class ApplicationGatewayAuthenticationCertificate(SubResource): """Authentication certificates of an application gateway. :param id: Resource ID. :type id: str :param data: Certificate public data. :type data: str :param provisioning_state: Provisioning state of the authentication certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the authentication certificate that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'data': {'key': 'properties.data', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayAuthenticationCertificate, self).__init__(**kwargs) self.data = kwargs.get('data', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayAutoscaleConfiguration(Model): """Application Gateway autoscale configuration. All required parameters must be populated in order to send to Azure. :param min_capacity: Required. Lower bound on number of Application Gateway capacity. :type min_capacity: int :param max_capacity: Upper bound on number of Application Gateway capacity. :type max_capacity: int """ _validation = { 'min_capacity': {'required': True, 'minimum': 0}, 'max_capacity': {'minimum': 2}, } _attribute_map = { 'min_capacity': {'key': 'minCapacity', 'type': 'int'}, 'max_capacity': {'key': 'maxCapacity', 'type': 'int'}, } def __init__(self, **kwargs): super(ApplicationGatewayAutoscaleConfiguration, self).__init__(**kwargs) self.min_capacity = kwargs.get('min_capacity', None) self.max_capacity = kwargs.get('max_capacity', None) class ApplicationGatewayAvailableSslOptions(Resource): """Response for ApplicationGatewayAvailableSslOptions API service call. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param predefined_policies: List of available Ssl predefined policy. :type predefined_policies: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param default_policy: Name of the Ssl predefined policy applied by default to application gateway. Possible values include: 'AppGwSslPolicy20150501', 'AppGwSslPolicy20170401', 'AppGwSslPolicy20170401S' :type default_policy: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslPolicyName :param available_cipher_suites: List of available Ssl cipher suites. :type available_cipher_suites: list[str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslCipherSuite] :param available_protocols: List of available Ssl protocols. :type available_protocols: list[str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslProtocol] """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'predefined_policies': {'key': 'properties.predefinedPolicies', 'type': '[SubResource]'}, 'default_policy': {'key': 'properties.defaultPolicy', 'type': 'str'}, 'available_cipher_suites': {'key': 'properties.availableCipherSuites', 'type': '[str]'}, 'available_protocols': {'key': 'properties.availableProtocols', 'type': '[str]'}, } def __init__(self, **kwargs): super(ApplicationGatewayAvailableSslOptions, self).__init__(**kwargs) self.predefined_policies = kwargs.get('predefined_policies', None) self.default_policy = kwargs.get('default_policy', None) self.available_cipher_suites = kwargs.get('available_cipher_suites', None) self.available_protocols = kwargs.get('available_protocols', None) class ApplicationGatewayAvailableWafRuleSetsResult(Model): """Response for ApplicationGatewayAvailableWafRuleSets API service call. :param value: The list of application gateway rule sets. :type value: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayFirewallRuleSet] """ _attribute_map = { 'value': {'key': 'value', 'type': '[ApplicationGatewayFirewallRuleSet]'}, } def __init__(self, **kwargs): super(ApplicationGatewayAvailableWafRuleSetsResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) class ApplicationGatewayBackendAddress(Model): """Backend address of an application gateway. :param fqdn: Fully qualified domain name (FQDN). :type fqdn: str :param ip_address: IP address. :type ip_address: str """ _attribute_map = { 'fqdn': {'key': 'fqdn', 'type': 'str'}, 'ip_address': {'key': 'ipAddress', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayBackendAddress, self).__init__(**kwargs) self.fqdn = kwargs.get('fqdn', None) self.ip_address = kwargs.get('ip_address', None) class ApplicationGatewayBackendAddressPool(SubResource): """Backend Address Pool of an application gateway. :param id: Resource ID. :type id: str :param backend_ip_configurations: Collection of references to IPs defined in network interfaces. :type backend_ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.NetworkInterfaceIPConfiguration] :param backend_addresses: Backend addresses. :type backend_addresses: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendAddress] :param provisioning_state: Provisioning state of the backend address pool resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the backend address pool that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'backend_ip_configurations': {'key': 'properties.backendIPConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'}, 'backend_addresses': {'key': 'properties.backendAddresses', 'type': '[ApplicationGatewayBackendAddress]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayBackendAddressPool, self).__init__(**kwargs) self.backend_ip_configurations = kwargs.get('backend_ip_configurations', None) self.backend_addresses = kwargs.get('backend_addresses', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayBackendHealth(Model): """Response for ApplicationGatewayBackendHealth API service call. :param backend_address_pools: A list of ApplicationGatewayBackendHealthPool resources. :type backend_address_pools: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendHealthPool] """ _attribute_map = { 'backend_address_pools': {'key': 'backendAddressPools', 'type': '[ApplicationGatewayBackendHealthPool]'}, } def __init__(self, **kwargs): super(ApplicationGatewayBackendHealth, self).__init__(**kwargs) self.backend_address_pools = kwargs.get('backend_address_pools', None) class ApplicationGatewayBackendHealthHttpSettings(Model): """Application gateway BackendHealthHttp settings. :param backend_http_settings: Reference of an ApplicationGatewayBackendHttpSettings resource. :type backend_http_settings: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendHttpSettings :param servers: List of ApplicationGatewayBackendHealthServer resources. :type servers: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendHealthServer] """ _attribute_map = { 'backend_http_settings': {'key': 'backendHttpSettings', 'type': 'ApplicationGatewayBackendHttpSettings'}, 'servers': {'key': 'servers', 'type': '[ApplicationGatewayBackendHealthServer]'}, } def __init__(self, **kwargs): super(ApplicationGatewayBackendHealthHttpSettings, self).__init__(**kwargs) self.backend_http_settings = kwargs.get('backend_http_settings', None) self.servers = kwargs.get('servers', None) class ApplicationGatewayBackendHealthOnDemand(Model): """Result of on demand test probe. :param backend_address_pool: Reference of an ApplicationGatewayBackendAddressPool resource. :type backend_address_pool: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendAddressPool :param backend_health_http_settings: Application gateway BackendHealthHttp settings. :type backend_health_http_settings: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendHealthHttpSettings """ _attribute_map = { 'backend_address_pool': {'key': 'backendAddressPool', 'type': 'ApplicationGatewayBackendAddressPool'}, 'backend_health_http_settings': {'key': 'backendHealthHttpSettings', 'type': 'ApplicationGatewayBackendHealthHttpSettings'}, } def __init__(self, **kwargs): super(ApplicationGatewayBackendHealthOnDemand, self).__init__(**kwargs) self.backend_address_pool = kwargs.get('backend_address_pool', None) self.backend_health_http_settings = kwargs.get('backend_health_http_settings', None) class ApplicationGatewayBackendHealthPool(Model): """Application gateway BackendHealth pool. :param backend_address_pool: Reference of an ApplicationGatewayBackendAddressPool resource. :type backend_address_pool: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendAddressPool :param backend_http_settings_collection: List of ApplicationGatewayBackendHealthHttpSettings resources. :type backend_http_settings_collection: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendHealthHttpSettings] """ _attribute_map = { 'backend_address_pool': {'key': 'backendAddressPool', 'type': 'ApplicationGatewayBackendAddressPool'}, 'backend_http_settings_collection': {'key': 'backendHttpSettingsCollection', 'type': '[ApplicationGatewayBackendHealthHttpSettings]'}, } def __init__(self, **kwargs): super(ApplicationGatewayBackendHealthPool, self).__init__(**kwargs) self.backend_address_pool = kwargs.get('backend_address_pool', None) self.backend_http_settings_collection = kwargs.get('backend_http_settings_collection', None) class ApplicationGatewayBackendHealthServer(Model): """Application gateway backendhealth http settings. :param address: IP address or FQDN of backend server. :type address: str :param ip_configuration: Reference of IP configuration of backend server. :type ip_configuration: ~azure.mgmt.network.v2019_06_01.models.NetworkInterfaceIPConfiguration :param health: Health of backend server. Possible values include: 'Unknown', 'Up', 'Down', 'Partial', 'Draining' :type health: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendHealthServerHealth :param health_probe_log: Health Probe Log. :type health_probe_log: str """ _attribute_map = { 'address': {'key': 'address', 'type': 'str'}, 'ip_configuration': {'key': 'ipConfiguration', 'type': 'NetworkInterfaceIPConfiguration'}, 'health': {'key': 'health', 'type': 'str'}, 'health_probe_log': {'key': 'healthProbeLog', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayBackendHealthServer, self).__init__(**kwargs) self.address = kwargs.get('address', None) self.ip_configuration = kwargs.get('ip_configuration', None) self.health = kwargs.get('health', None) self.health_probe_log = kwargs.get('health_probe_log', None) class ApplicationGatewayBackendHttpSettings(SubResource): """Backend address pool settings of an application gateway. :param id: Resource ID. :type id: str :param port: The destination port on the backend. :type port: int :param protocol: The protocol used to communicate with the backend. Possible values include: 'Http', 'Https' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayProtocol :param cookie_based_affinity: Cookie based affinity. Possible values include: 'Enabled', 'Disabled' :type cookie_based_affinity: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayCookieBasedAffinity :param request_timeout: Request timeout in seconds. Application Gateway will fail the request if response is not received within RequestTimeout. Acceptable values are from 1 second to 86400 seconds. :type request_timeout: int :param probe: Probe resource of an application gateway. :type probe: ~azure.mgmt.network.v2019_06_01.models.SubResource :param authentication_certificates: Array of references to application gateway authentication certificates. :type authentication_certificates: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param trusted_root_certificates: Array of references to application gateway trusted root certificates. :type trusted_root_certificates: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param connection_draining: Connection draining of the backend http settings resource. :type connection_draining: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayConnectionDraining :param host_name: Host header to be sent to the backend servers. :type host_name: str :param pick_host_name_from_backend_address: Whether to pick host header should be picked from the host name of the backend server. Default value is false. :type pick_host_name_from_backend_address: bool :param affinity_cookie_name: Cookie name to use for the affinity cookie. :type affinity_cookie_name: str :param probe_enabled: Whether the probe is enabled. Default value is false. :type probe_enabled: bool :param path: Path which should be used as a prefix for all HTTP requests. Null means no path will be prefixed. Default value is null. :type path: str :param provisioning_state: Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the backend http settings that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'port': {'key': 'properties.port', 'type': 'int'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'cookie_based_affinity': {'key': 'properties.cookieBasedAffinity', 'type': 'str'}, 'request_timeout': {'key': 'properties.requestTimeout', 'type': 'int'}, 'probe': {'key': 'properties.probe', 'type': 'SubResource'}, 'authentication_certificates': {'key': 'properties.authenticationCertificates', 'type': '[SubResource]'}, 'trusted_root_certificates': {'key': 'properties.trustedRootCertificates', 'type': '[SubResource]'}, 'connection_draining': {'key': 'properties.connectionDraining', 'type': 'ApplicationGatewayConnectionDraining'}, 'host_name': {'key': 'properties.hostName', 'type': 'str'}, 'pick_host_name_from_backend_address': {'key': 'properties.pickHostNameFromBackendAddress', 'type': 'bool'}, 'affinity_cookie_name': {'key': 'properties.affinityCookieName', 'type': 'str'}, 'probe_enabled': {'key': 'properties.probeEnabled', 'type': 'bool'}, 'path': {'key': 'properties.path', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayBackendHttpSettings, self).__init__(**kwargs) self.port = kwargs.get('port', None) self.protocol = kwargs.get('protocol', None) self.cookie_based_affinity = kwargs.get('cookie_based_affinity', None) self.request_timeout = kwargs.get('request_timeout', None) self.probe = kwargs.get('probe', None) self.authentication_certificates = kwargs.get('authentication_certificates', None) self.trusted_root_certificates = kwargs.get('trusted_root_certificates', None) self.connection_draining = kwargs.get('connection_draining', None) self.host_name = kwargs.get('host_name', None) self.pick_host_name_from_backend_address = kwargs.get('pick_host_name_from_backend_address', None) self.affinity_cookie_name = kwargs.get('affinity_cookie_name', None) self.probe_enabled = kwargs.get('probe_enabled', None) self.path = kwargs.get('path', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayConnectionDraining(Model): """Connection draining allows open connections to a backend server to be active for a specified time after the backend server got removed from the configuration. All required parameters must be populated in order to send to Azure. :param enabled: Required. Whether connection draining is enabled or not. :type enabled: bool :param drain_timeout_in_sec: Required. The number of seconds connection draining is active. Acceptable values are from 1 second to 3600 seconds. :type drain_timeout_in_sec: int """ _validation = { 'enabled': {'required': True}, 'drain_timeout_in_sec': {'required': True, 'maximum': 3600, 'minimum': 1}, } _attribute_map = { 'enabled': {'key': 'enabled', 'type': 'bool'}, 'drain_timeout_in_sec': {'key': 'drainTimeoutInSec', 'type': 'int'}, } def __init__(self, **kwargs): super(ApplicationGatewayConnectionDraining, self).__init__(**kwargs) self.enabled = kwargs.get('enabled', None) self.drain_timeout_in_sec = kwargs.get('drain_timeout_in_sec', None) class ApplicationGatewayCustomError(Model): """Customer error of an application gateway. :param status_code: Status code of the application gateway customer error. Possible values include: 'HttpStatus403', 'HttpStatus502' :type status_code: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayCustomErrorStatusCode :param custom_error_page_url: Error page URL of the application gateway customer error. :type custom_error_page_url: str """ _attribute_map = { 'status_code': {'key': 'statusCode', 'type': 'str'}, 'custom_error_page_url': {'key': 'customErrorPageUrl', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayCustomError, self).__init__(**kwargs) self.status_code = kwargs.get('status_code', None) self.custom_error_page_url = kwargs.get('custom_error_page_url', None) class ApplicationGatewayFirewallDisabledRuleGroup(Model): """Allows to disable rules within a rule group or an entire rule group. All required parameters must be populated in order to send to Azure. :param rule_group_name: Required. The name of the rule group that will be disabled. :type rule_group_name: str :param rules: The list of rules that will be disabled. If null, all rules of the rule group will be disabled. :type rules: list[int] """ _validation = { 'rule_group_name': {'required': True}, } _attribute_map = { 'rule_group_name': {'key': 'ruleGroupName', 'type': 'str'}, 'rules': {'key': 'rules', 'type': '[int]'}, } def __init__(self, **kwargs): super(ApplicationGatewayFirewallDisabledRuleGroup, self).__init__(**kwargs) self.rule_group_name = kwargs.get('rule_group_name', None) self.rules = kwargs.get('rules', None) class ApplicationGatewayFirewallExclusion(Model): """Allow to exclude some variable satisfy the condition for the WAF check. All required parameters must be populated in order to send to Azure. :param match_variable: Required. The variable to be excluded. :type match_variable: str :param selector_match_operator: Required. When matchVariable is a collection, operate on the selector to specify which elements in the collection this exclusion applies to. :type selector_match_operator: str :param selector: Required. When matchVariable is a collection, operator used to specify which elements in the collection this exclusion applies to. :type selector: str """ _validation = { 'match_variable': {'required': True}, 'selector_match_operator': {'required': True}, 'selector': {'required': True}, } _attribute_map = { 'match_variable': {'key': 'matchVariable', 'type': 'str'}, 'selector_match_operator': {'key': 'selectorMatchOperator', 'type': 'str'}, 'selector': {'key': 'selector', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayFirewallExclusion, self).__init__(**kwargs) self.match_variable = kwargs.get('match_variable', None) self.selector_match_operator = kwargs.get('selector_match_operator', None) self.selector = kwargs.get('selector', None) class ApplicationGatewayFirewallRule(Model): """A web application firewall rule. All required parameters must be populated in order to send to Azure. :param rule_id: Required. The identifier of the web application firewall rule. :type rule_id: int :param description: The description of the web application firewall rule. :type description: str """ _validation = { 'rule_id': {'required': True}, } _attribute_map = { 'rule_id': {'key': 'ruleId', 'type': 'int'}, 'description': {'key': 'description', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayFirewallRule, self).__init__(**kwargs) self.rule_id = kwargs.get('rule_id', None) self.description = kwargs.get('description', None) class ApplicationGatewayFirewallRuleGroup(Model): """A web application firewall rule group. All required parameters must be populated in order to send to Azure. :param rule_group_name: Required. The name of the web application firewall rule group. :type rule_group_name: str :param description: The description of the web application firewall rule group. :type description: str :param rules: Required. The rules of the web application firewall rule group. :type rules: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayFirewallRule] """ _validation = { 'rule_group_name': {'required': True}, 'rules': {'required': True}, } _attribute_map = { 'rule_group_name': {'key': 'ruleGroupName', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'rules': {'key': 'rules', 'type': '[ApplicationGatewayFirewallRule]'}, } def __init__(self, **kwargs): super(ApplicationGatewayFirewallRuleGroup, self).__init__(**kwargs) self.rule_group_name = kwargs.get('rule_group_name', None) self.description = kwargs.get('description', None) self.rules = kwargs.get('rules', None) class ApplicationGatewayFirewallRuleSet(Resource): """A web application firewall rule set. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param provisioning_state: The provisioning state of the web application firewall rule set. :type provisioning_state: str :param rule_set_type: Required. The type of the web application firewall rule set. :type rule_set_type: str :param rule_set_version: Required. The version of the web application firewall rule set type. :type rule_set_version: str :param rule_groups: Required. The rule groups of the web application firewall rule set. :type rule_groups: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayFirewallRuleGroup] """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'rule_set_type': {'required': True}, 'rule_set_version': {'required': True}, 'rule_groups': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'rule_set_type': {'key': 'properties.ruleSetType', 'type': 'str'}, 'rule_set_version': {'key': 'properties.ruleSetVersion', 'type': 'str'}, 'rule_groups': {'key': 'properties.ruleGroups', 'type': '[ApplicationGatewayFirewallRuleGroup]'}, } def __init__(self, **kwargs): super(ApplicationGatewayFirewallRuleSet, self).__init__(**kwargs) self.provisioning_state = kwargs.get('provisioning_state', None) self.rule_set_type = kwargs.get('rule_set_type', None) self.rule_set_version = kwargs.get('rule_set_version', None) self.rule_groups = kwargs.get('rule_groups', None) class ApplicationGatewayFrontendIPConfiguration(SubResource): """Frontend IP configuration of an application gateway. :param id: Resource ID. :type id: str :param private_ip_address: PrivateIPAddress of the network interface IP Configuration. :type private_ip_address: str :param private_ip_allocation_method: The private IP address allocation method. Possible values include: 'Static', 'Dynamic' :type private_ip_allocation_method: str or ~azure.mgmt.network.v2019_06_01.models.IPAllocationMethod :param subnet: Reference of the subnet resource. :type subnet: ~azure.mgmt.network.v2019_06_01.models.SubResource :param public_ip_address: Reference of the PublicIP resource. :type public_ip_address: ~azure.mgmt.network.v2019_06_01.models.SubResource :param provisioning_state: Provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the frontend IP configuration that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'}, 'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'SubResource'}, 'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayFrontendIPConfiguration, self).__init__(**kwargs) self.private_ip_address = kwargs.get('private_ip_address', None) self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None) self.subnet = kwargs.get('subnet', None) self.public_ip_address = kwargs.get('public_ip_address', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayFrontendPort(SubResource): """Frontend port of an application gateway. :param id: Resource ID. :type id: str :param port: Frontend port. :type port: int :param provisioning_state: Provisioning state of the frontend port resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the frontend port that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'port': {'key': 'properties.port', 'type': 'int'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayFrontendPort, self).__init__(**kwargs) self.port = kwargs.get('port', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayHeaderConfiguration(Model): """Header configuration of the Actions set in Application Gateway. :param header_name: Header name of the header configuration. :type header_name: str :param header_value: Header value of the header configuration. :type header_value: str """ _attribute_map = { 'header_name': {'key': 'headerName', 'type': 'str'}, 'header_value': {'key': 'headerValue', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayHeaderConfiguration, self).__init__(**kwargs) self.header_name = kwargs.get('header_name', None) self.header_value = kwargs.get('header_value', None) class ApplicationGatewayHttpListener(SubResource): """Http listener of an application gateway. :param id: Resource ID. :type id: str :param frontend_ip_configuration: Frontend IP configuration resource of an application gateway. :type frontend_ip_configuration: ~azure.mgmt.network.v2019_06_01.models.SubResource :param frontend_port: Frontend port resource of an application gateway. :type frontend_port: ~azure.mgmt.network.v2019_06_01.models.SubResource :param protocol: Protocol of the HTTP listener. Possible values include: 'Http', 'Https' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayProtocol :param host_name: Host name of HTTP listener. :type host_name: str :param ssl_certificate: SSL certificate resource of an application gateway. :type ssl_certificate: ~azure.mgmt.network.v2019_06_01.models.SubResource :param require_server_name_indication: Applicable only if protocol is https. Enables SNI for multi-hosting. :type require_server_name_indication: bool :param provisioning_state: Provisioning state of the HTTP listener resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param custom_error_configurations: Custom error configurations of the HTTP listener. :type custom_error_configurations: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayCustomError] :param name: Name of the HTTP listener that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'}, 'frontend_port': {'key': 'properties.frontendPort', 'type': 'SubResource'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'host_name': {'key': 'properties.hostName', 'type': 'str'}, 'ssl_certificate': {'key': 'properties.sslCertificate', 'type': 'SubResource'}, 'require_server_name_indication': {'key': 'properties.requireServerNameIndication', 'type': 'bool'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'custom_error_configurations': {'key': 'properties.customErrorConfigurations', 'type': '[ApplicationGatewayCustomError]'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayHttpListener, self).__init__(**kwargs) self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None) self.frontend_port = kwargs.get('frontend_port', None) self.protocol = kwargs.get('protocol', None) self.host_name = kwargs.get('host_name', None) self.ssl_certificate = kwargs.get('ssl_certificate', None) self.require_server_name_indication = kwargs.get('require_server_name_indication', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.custom_error_configurations = kwargs.get('custom_error_configurations', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayIPConfiguration(SubResource): """IP configuration of an application gateway. Currently 1 public and 1 private IP configuration is allowed. :param id: Resource ID. :type id: str :param subnet: Reference of the subnet resource. A subnet from where application gateway gets its private address. :type subnet: ~azure.mgmt.network.v2019_06_01.models.SubResource :param provisioning_state: Provisioning state of the application gateway subnet resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the IP configuration that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayIPConfiguration, self).__init__(**kwargs) self.subnet = kwargs.get('subnet', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayOnDemandProbe(Model): """Details of on demand test probe request. :param protocol: The protocol used for the probe. Possible values include: 'Http', 'Https' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayProtocol :param host: Host name to send the probe to. :type host: str :param path: Relative path of probe. Valid path starts from '/'. Probe is sent to <Protocol>://<host>:<port><path>. :type path: str :param timeout: The probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable values are from 1 second to 86400 seconds. :type timeout: int :param pick_host_name_from_backend_http_settings: Whether the host header should be picked from the backend http settings. Default value is false. :type pick_host_name_from_backend_http_settings: bool :param match: Criterion for classifying a healthy probe response. :type match: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayProbeHealthResponseMatch :param backend_pool_name: Name of backend pool of application gateway to which probe request will be sent. :type backend_pool_name: str :param backend_http_setting_name: Name of backend http setting of application gateway to be used for test probe. :type backend_http_setting_name: str """ _attribute_map = { 'protocol': {'key': 'protocol', 'type': 'str'}, 'host': {'key': 'host', 'type': 'str'}, 'path': {'key': 'path', 'type': 'str'}, 'timeout': {'key': 'timeout', 'type': 'int'}, 'pick_host_name_from_backend_http_settings': {'key': 'pickHostNameFromBackendHttpSettings', 'type': 'bool'}, 'match': {'key': 'match', 'type': 'ApplicationGatewayProbeHealthResponseMatch'}, 'backend_pool_name': {'key': 'backendPoolName', 'type': 'str'}, 'backend_http_setting_name': {'key': 'backendHttpSettingName', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayOnDemandProbe, self).__init__(**kwargs) self.protocol = kwargs.get('protocol', None) self.host = kwargs.get('host', None) self.path = kwargs.get('path', None) self.timeout = kwargs.get('timeout', None) self.pick_host_name_from_backend_http_settings = kwargs.get('pick_host_name_from_backend_http_settings', None) self.match = kwargs.get('match', None) self.backend_pool_name = kwargs.get('backend_pool_name', None) self.backend_http_setting_name = kwargs.get('backend_http_setting_name', None) class ApplicationGatewayPathRule(SubResource): """Path rule of URL path map of an application gateway. :param id: Resource ID. :type id: str :param paths: Path rules of URL path map. :type paths: list[str] :param backend_address_pool: Backend address pool resource of URL path map path rule. :type backend_address_pool: ~azure.mgmt.network.v2019_06_01.models.SubResource :param backend_http_settings: Backend http settings resource of URL path map path rule. :type backend_http_settings: ~azure.mgmt.network.v2019_06_01.models.SubResource :param redirect_configuration: Redirect configuration resource of URL path map path rule. :type redirect_configuration: ~azure.mgmt.network.v2019_06_01.models.SubResource :param rewrite_rule_set: Rewrite rule set resource of URL path map path rule. :type rewrite_rule_set: ~azure.mgmt.network.v2019_06_01.models.SubResource :param provisioning_state: Path rule of URL path map resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the path rule that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'paths': {'key': 'properties.paths', 'type': '[str]'}, 'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'}, 'backend_http_settings': {'key': 'properties.backendHttpSettings', 'type': 'SubResource'}, 'redirect_configuration': {'key': 'properties.redirectConfiguration', 'type': 'SubResource'}, 'rewrite_rule_set': {'key': 'properties.rewriteRuleSet', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayPathRule, self).__init__(**kwargs) self.paths = kwargs.get('paths', None) self.backend_address_pool = kwargs.get('backend_address_pool', None) self.backend_http_settings = kwargs.get('backend_http_settings', None) self.redirect_configuration = kwargs.get('redirect_configuration', None) self.rewrite_rule_set = kwargs.get('rewrite_rule_set', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayProbe(SubResource): """Probe of the application gateway. :param id: Resource ID. :type id: str :param protocol: The protocol used for the probe. Possible values include: 'Http', 'Https' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayProtocol :param host: Host name to send the probe to. :type host: str :param path: Relative path of probe. Valid path starts from '/'. Probe is sent to <Protocol>://<host>:<port><path>. :type path: str :param interval: The probing interval in seconds. This is the time interval between two consecutive probes. Acceptable values are from 1 second to 86400 seconds. :type interval: int :param timeout: The probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable values are from 1 second to 86400 seconds. :type timeout: int :param unhealthy_threshold: The probe retry count. Backend server is marked down after consecutive probe failure count reaches UnhealthyThreshold. Acceptable values are from 1 second to 20. :type unhealthy_threshold: int :param pick_host_name_from_backend_http_settings: Whether the host header should be picked from the backend http settings. Default value is false. :type pick_host_name_from_backend_http_settings: bool :param min_servers: Minimum number of servers that are always marked healthy. Default value is 0. :type min_servers: int :param match: Criterion for classifying a healthy probe response. :type match: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayProbeHealthResponseMatch :param provisioning_state: Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param port: Custom port which will be used for probing the backend servers. The valid value ranges from 1 to 65535. In case not set, port from http settings will be used. This property is valid for Standard_v2 and WAF_v2 only. :type port: int :param name: Name of the probe that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _validation = { 'port': {'maximum': 65535, 'minimum': 1}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'host': {'key': 'properties.host', 'type': 'str'}, 'path': {'key': 'properties.path', 'type': 'str'}, 'interval': {'key': 'properties.interval', 'type': 'int'}, 'timeout': {'key': 'properties.timeout', 'type': 'int'}, 'unhealthy_threshold': {'key': 'properties.unhealthyThreshold', 'type': 'int'}, 'pick_host_name_from_backend_http_settings': {'key': 'properties.pickHostNameFromBackendHttpSettings', 'type': 'bool'}, 'min_servers': {'key': 'properties.minServers', 'type': 'int'}, 'match': {'key': 'properties.match', 'type': 'ApplicationGatewayProbeHealthResponseMatch'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'port': {'key': 'properties.port', 'type': 'int'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayProbe, self).__init__(**kwargs) self.protocol = kwargs.get('protocol', None) self.host = kwargs.get('host', None) self.path = kwargs.get('path', None) self.interval = kwargs.get('interval', None) self.timeout = kwargs.get('timeout', None) self.unhealthy_threshold = kwargs.get('unhealthy_threshold', None) self.pick_host_name_from_backend_http_settings = kwargs.get('pick_host_name_from_backend_http_settings', None) self.min_servers = kwargs.get('min_servers', None) self.match = kwargs.get('match', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.port = kwargs.get('port', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayProbeHealthResponseMatch(Model): """Application gateway probe health response match. :param body: Body that must be contained in the health response. Default value is empty. :type body: str :param status_codes: Allowed ranges of healthy status codes. Default range of healthy status codes is 200-399. :type status_codes: list[str] """ _attribute_map = { 'body': {'key': 'body', 'type': 'str'}, 'status_codes': {'key': 'statusCodes', 'type': '[str]'}, } def __init__(self, **kwargs): super(ApplicationGatewayProbeHealthResponseMatch, self).__init__(**kwargs) self.body = kwargs.get('body', None) self.status_codes = kwargs.get('status_codes', None) class ApplicationGatewayRedirectConfiguration(SubResource): """Redirect configuration of an application gateway. :param id: Resource ID. :type id: str :param redirect_type: HTTP redirection type. Possible values include: 'Permanent', 'Found', 'SeeOther', 'Temporary' :type redirect_type: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayRedirectType :param target_listener: Reference to a listener to redirect the request to. :type target_listener: ~azure.mgmt.network.v2019_06_01.models.SubResource :param target_url: Url to redirect the request to. :type target_url: str :param include_path: Include path in the redirected url. :type include_path: bool :param include_query_string: Include query string in the redirected url. :type include_query_string: bool :param request_routing_rules: Request routing specifying redirect configuration. :type request_routing_rules: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param url_path_maps: Url path maps specifying default redirect configuration. :type url_path_maps: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param path_rules: Path rules specifying redirect configuration. :type path_rules: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param name: Name of the redirect configuration that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'redirect_type': {'key': 'properties.redirectType', 'type': 'str'}, 'target_listener': {'key': 'properties.targetListener', 'type': 'SubResource'}, 'target_url': {'key': 'properties.targetUrl', 'type': 'str'}, 'include_path': {'key': 'properties.includePath', 'type': 'bool'}, 'include_query_string': {'key': 'properties.includeQueryString', 'type': 'bool'}, 'request_routing_rules': {'key': 'properties.requestRoutingRules', 'type': '[SubResource]'}, 'url_path_maps': {'key': 'properties.urlPathMaps', 'type': '[SubResource]'}, 'path_rules': {'key': 'properties.pathRules', 'type': '[SubResource]'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayRedirectConfiguration, self).__init__(**kwargs) self.redirect_type = kwargs.get('redirect_type', None) self.target_listener = kwargs.get('target_listener', None) self.target_url = kwargs.get('target_url', None) self.include_path = kwargs.get('include_path', None) self.include_query_string = kwargs.get('include_query_string', None) self.request_routing_rules = kwargs.get('request_routing_rules', None) self.url_path_maps = kwargs.get('url_path_maps', None) self.path_rules = kwargs.get('path_rules', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayRequestRoutingRule(SubResource): """Request routing rule of an application gateway. :param id: Resource ID. :type id: str :param rule_type: Rule type. Possible values include: 'Basic', 'PathBasedRouting' :type rule_type: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayRequestRoutingRuleType :param backend_address_pool: Backend address pool resource of the application gateway. :type backend_address_pool: ~azure.mgmt.network.v2019_06_01.models.SubResource :param backend_http_settings: Backend http settings resource of the application gateway. :type backend_http_settings: ~azure.mgmt.network.v2019_06_01.models.SubResource :param http_listener: Http listener resource of the application gateway. :type http_listener: ~azure.mgmt.network.v2019_06_01.models.SubResource :param url_path_map: URL path map resource of the application gateway. :type url_path_map: ~azure.mgmt.network.v2019_06_01.models.SubResource :param rewrite_rule_set: Rewrite Rule Set resource in Basic rule of the application gateway. :type rewrite_rule_set: ~azure.mgmt.network.v2019_06_01.models.SubResource :param redirect_configuration: Redirect configuration resource of the application gateway. :type redirect_configuration: ~azure.mgmt.network.v2019_06_01.models.SubResource :param provisioning_state: Provisioning state of the request routing rule resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the request routing rule that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'rule_type': {'key': 'properties.ruleType', 'type': 'str'}, 'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'}, 'backend_http_settings': {'key': 'properties.backendHttpSettings', 'type': 'SubResource'}, 'http_listener': {'key': 'properties.httpListener', 'type': 'SubResource'}, 'url_path_map': {'key': 'properties.urlPathMap', 'type': 'SubResource'}, 'rewrite_rule_set': {'key': 'properties.rewriteRuleSet', 'type': 'SubResource'}, 'redirect_configuration': {'key': 'properties.redirectConfiguration', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayRequestRoutingRule, self).__init__(**kwargs) self.rule_type = kwargs.get('rule_type', None) self.backend_address_pool = kwargs.get('backend_address_pool', None) self.backend_http_settings = kwargs.get('backend_http_settings', None) self.http_listener = kwargs.get('http_listener', None) self.url_path_map = kwargs.get('url_path_map', None) self.rewrite_rule_set = kwargs.get('rewrite_rule_set', None) self.redirect_configuration = kwargs.get('redirect_configuration', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayRewriteRule(Model): """Rewrite rule of an application gateway. :param name: Name of the rewrite rule that is unique within an Application Gateway. :type name: str :param rule_sequence: Rule Sequence of the rewrite rule that determines the order of execution of a particular rule in a RewriteRuleSet. :type rule_sequence: int :param conditions: Conditions based on which the action set execution will be evaluated. :type conditions: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayRewriteRuleCondition] :param action_set: Set of actions to be done as part of the rewrite Rule. :type action_set: ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayRewriteRuleActionSet """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'rule_sequence': {'key': 'ruleSequence', 'type': 'int'}, 'conditions': {'key': 'conditions', 'type': '[ApplicationGatewayRewriteRuleCondition]'}, 'action_set': {'key': 'actionSet', 'type': 'ApplicationGatewayRewriteRuleActionSet'}, } def __init__(self, **kwargs): super(ApplicationGatewayRewriteRule, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.rule_sequence = kwargs.get('rule_sequence', None) self.conditions = kwargs.get('conditions', None) self.action_set = kwargs.get('action_set', None) class ApplicationGatewayRewriteRuleActionSet(Model): """Set of actions in the Rewrite Rule in Application Gateway. :param request_header_configurations: Request Header Actions in the Action Set. :type request_header_configurations: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayHeaderConfiguration] :param response_header_configurations: Response Header Actions in the Action Set. :type response_header_configurations: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayHeaderConfiguration] """ _attribute_map = { 'request_header_configurations': {'key': 'requestHeaderConfigurations', 'type': '[ApplicationGatewayHeaderConfiguration]'}, 'response_header_configurations': {'key': 'responseHeaderConfigurations', 'type': '[ApplicationGatewayHeaderConfiguration]'}, } def __init__(self, **kwargs): super(ApplicationGatewayRewriteRuleActionSet, self).__init__(**kwargs) self.request_header_configurations = kwargs.get('request_header_configurations', None) self.response_header_configurations = kwargs.get('response_header_configurations', None) class ApplicationGatewayRewriteRuleCondition(Model): """Set of conditions in the Rewrite Rule in Application Gateway. :param variable: The condition parameter of the RewriteRuleCondition. :type variable: str :param pattern: The pattern, either fixed string or regular expression, that evaluates the truthfulness of the condition. :type pattern: str :param ignore_case: Setting this paramter to truth value with force the pattern to do a case in-sensitive comparison. :type ignore_case: bool :param negate: Setting this value as truth will force to check the negation of the condition given by the user. :type negate: bool """ _attribute_map = { 'variable': {'key': 'variable', 'type': 'str'}, 'pattern': {'key': 'pattern', 'type': 'str'}, 'ignore_case': {'key': 'ignoreCase', 'type': 'bool'}, 'negate': {'key': 'negate', 'type': 'bool'}, } def __init__(self, **kwargs): super(ApplicationGatewayRewriteRuleCondition, self).__init__(**kwargs) self.variable = kwargs.get('variable', None) self.pattern = kwargs.get('pattern', None) self.ignore_case = kwargs.get('ignore_case', None) self.negate = kwargs.get('negate', None) class ApplicationGatewayRewriteRuleSet(SubResource): """Rewrite rule set of an application gateway. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param rewrite_rules: Rewrite rules in the rewrite rule set. :type rewrite_rules: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayRewriteRule] :ivar provisioning_state: Provisioning state of the rewrite rule set resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: Name of the rewrite rule set that is unique within an Application Gateway. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'rewrite_rules': {'key': 'properties.rewriteRules', 'type': '[ApplicationGatewayRewriteRule]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayRewriteRuleSet, self).__init__(**kwargs) self.rewrite_rules = kwargs.get('rewrite_rules', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = None class ApplicationGatewaySku(Model): """SKU of an application gateway. :param name: Name of an application gateway SKU. Possible values include: 'Standard_Small', 'Standard_Medium', 'Standard_Large', 'WAF_Medium', 'WAF_Large', 'Standard_v2', 'WAF_v2' :type name: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySkuName :param tier: Tier of an application gateway. Possible values include: 'Standard', 'WAF', 'Standard_v2', 'WAF_v2' :type tier: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayTier :param capacity: Capacity (instance count) of an application gateway. :type capacity: int """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, 'capacity': {'key': 'capacity', 'type': 'int'}, } def __init__(self, **kwargs): super(ApplicationGatewaySku, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.tier = kwargs.get('tier', None) self.capacity = kwargs.get('capacity', None) class ApplicationGatewaySslCertificate(SubResource): """SSL certificates of an application gateway. :param id: Resource ID. :type id: str :param data: Base-64 encoded pfx certificate. Only applicable in PUT Request. :type data: str :param password: Password for the pfx file specified in data. Only applicable in PUT request. :type password: str :param public_cert_data: Base-64 encoded Public cert data corresponding to pfx specified in data. Only applicable in GET request. :type public_cert_data: str :param key_vault_secret_id: Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. :type key_vault_secret_id: str :param provisioning_state: Provisioning state of the SSL certificate resource Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the SSL certificate that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'data': {'key': 'properties.data', 'type': 'str'}, 'password': {'key': 'properties.password', 'type': 'str'}, 'public_cert_data': {'key': 'properties.publicCertData', 'type': 'str'}, 'key_vault_secret_id': {'key': 'properties.keyVaultSecretId', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewaySslCertificate, self).__init__(**kwargs) self.data = kwargs.get('data', None) self.password = kwargs.get('password', None) self.public_cert_data = kwargs.get('public_cert_data', None) self.key_vault_secret_id = kwargs.get('key_vault_secret_id', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewaySslPolicy(Model): """Application Gateway Ssl policy. :param disabled_ssl_protocols: Ssl protocols to be disabled on application gateway. :type disabled_ssl_protocols: list[str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslProtocol] :param policy_type: Type of Ssl Policy. Possible values include: 'Predefined', 'Custom' :type policy_type: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslPolicyType :param policy_name: Name of Ssl predefined policy. Possible values include: 'AppGwSslPolicy20150501', 'AppGwSslPolicy20170401', 'AppGwSslPolicy20170401S' :type policy_name: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslPolicyName :param cipher_suites: Ssl cipher suites to be enabled in the specified order to application gateway. :type cipher_suites: list[str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslCipherSuite] :param min_protocol_version: Minimum version of Ssl protocol to be supported on application gateway. Possible values include: 'TLSv1_0', 'TLSv1_1', 'TLSv1_2' :type min_protocol_version: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslProtocol """ _attribute_map = { 'disabled_ssl_protocols': {'key': 'disabledSslProtocols', 'type': '[str]'}, 'policy_type': {'key': 'policyType', 'type': 'str'}, 'policy_name': {'key': 'policyName', 'type': 'str'}, 'cipher_suites': {'key': 'cipherSuites', 'type': '[str]'}, 'min_protocol_version': {'key': 'minProtocolVersion', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewaySslPolicy, self).__init__(**kwargs) self.disabled_ssl_protocols = kwargs.get('disabled_ssl_protocols', None) self.policy_type = kwargs.get('policy_type', None) self.policy_name = kwargs.get('policy_name', None) self.cipher_suites = kwargs.get('cipher_suites', None) self.min_protocol_version = kwargs.get('min_protocol_version', None) class ApplicationGatewaySslPredefinedPolicy(SubResource): """An Ssl predefined policy. :param id: Resource ID. :type id: str :param name: Name of the Ssl predefined policy. :type name: str :param cipher_suites: Ssl cipher suites to be enabled in the specified order for application gateway. :type cipher_suites: list[str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslCipherSuite] :param min_protocol_version: Minimum version of Ssl protocol to be supported on application gateway. Possible values include: 'TLSv1_0', 'TLSv1_1', 'TLSv1_2' :type min_protocol_version: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewaySslProtocol """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'cipher_suites': {'key': 'properties.cipherSuites', 'type': '[str]'}, 'min_protocol_version': {'key': 'properties.minProtocolVersion', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewaySslPredefinedPolicy, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.cipher_suites = kwargs.get('cipher_suites', None) self.min_protocol_version = kwargs.get('min_protocol_version', None) class ApplicationGatewayTrustedRootCertificate(SubResource): """Trusted Root certificates of an application gateway. :param id: Resource ID. :type id: str :param data: Certificate public data. :type data: str :param key_vault_secret_id: Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. :type key_vault_secret_id: str :param provisioning_state: Provisioning state of the trusted root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the trusted root certificate that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'data': {'key': 'properties.data', 'type': 'str'}, 'key_vault_secret_id': {'key': 'properties.keyVaultSecretId', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayTrustedRootCertificate, self).__init__(**kwargs) self.data = kwargs.get('data', None) self.key_vault_secret_id = kwargs.get('key_vault_secret_id', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayUrlPathMap(SubResource): """UrlPathMaps give a url path to the backend mapping information for PathBasedRouting. :param id: Resource ID. :type id: str :param default_backend_address_pool: Default backend address pool resource of URL path map. :type default_backend_address_pool: ~azure.mgmt.network.v2019_06_01.models.SubResource :param default_backend_http_settings: Default backend http settings resource of URL path map. :type default_backend_http_settings: ~azure.mgmt.network.v2019_06_01.models.SubResource :param default_rewrite_rule_set: Default Rewrite rule set resource of URL path map. :type default_rewrite_rule_set: ~azure.mgmt.network.v2019_06_01.models.SubResource :param default_redirect_configuration: Default redirect configuration resource of URL path map. :type default_redirect_configuration: ~azure.mgmt.network.v2019_06_01.models.SubResource :param path_rules: Path rule of URL path map resource. :type path_rules: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayPathRule] :param provisioning_state: Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the URL path map that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'default_backend_address_pool': {'key': 'properties.defaultBackendAddressPool', 'type': 'SubResource'}, 'default_backend_http_settings': {'key': 'properties.defaultBackendHttpSettings', 'type': 'SubResource'}, 'default_rewrite_rule_set': {'key': 'properties.defaultRewriteRuleSet', 'type': 'SubResource'}, 'default_redirect_configuration': {'key': 'properties.defaultRedirectConfiguration', 'type': 'SubResource'}, 'path_rules': {'key': 'properties.pathRules', 'type': '[ApplicationGatewayPathRule]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewayUrlPathMap, self).__init__(**kwargs) self.default_backend_address_pool = kwargs.get('default_backend_address_pool', None) self.default_backend_http_settings = kwargs.get('default_backend_http_settings', None) self.default_rewrite_rule_set = kwargs.get('default_rewrite_rule_set', None) self.default_redirect_configuration = kwargs.get('default_redirect_configuration', None) self.path_rules = kwargs.get('path_rules', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = kwargs.get('type', None) class ApplicationGatewayWebApplicationFirewallConfiguration(Model): """Application gateway web application firewall configuration. All required parameters must be populated in order to send to Azure. :param enabled: Required. Whether the web application firewall is enabled or not. :type enabled: bool :param firewall_mode: Required. Web application firewall mode. Possible values include: 'Detection', 'Prevention' :type firewall_mode: str or ~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayFirewallMode :param rule_set_type: Required. The type of the web application firewall rule set. Possible values are: 'OWASP'. :type rule_set_type: str :param rule_set_version: Required. The version of the rule set type. :type rule_set_version: str :param disabled_rule_groups: The disabled rule groups. :type disabled_rule_groups: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayFirewallDisabledRuleGroup] :param request_body_check: Whether allow WAF to check request Body. :type request_body_check: bool :param max_request_body_size: Maximum request body size for WAF. :type max_request_body_size: int :param max_request_body_size_in_kb: Maximum request body size in Kb for WAF. :type max_request_body_size_in_kb: int :param file_upload_limit_in_mb: Maximum file upload size in Mb for WAF. :type file_upload_limit_in_mb: int :param exclusions: The exclusion list. :type exclusions: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayFirewallExclusion] """ _validation = { 'enabled': {'required': True}, 'firewall_mode': {'required': True}, 'rule_set_type': {'required': True}, 'rule_set_version': {'required': True}, 'max_request_body_size': {'maximum': 128, 'minimum': 8}, 'max_request_body_size_in_kb': {'maximum': 128, 'minimum': 8}, 'file_upload_limit_in_mb': {'minimum': 0}, } _attribute_map = { 'enabled': {'key': 'enabled', 'type': 'bool'}, 'firewall_mode': {'key': 'firewallMode', 'type': 'str'}, 'rule_set_type': {'key': 'ruleSetType', 'type': 'str'}, 'rule_set_version': {'key': 'ruleSetVersion', 'type': 'str'}, 'disabled_rule_groups': {'key': 'disabledRuleGroups', 'type': '[ApplicationGatewayFirewallDisabledRuleGroup]'}, 'request_body_check': {'key': 'requestBodyCheck', 'type': 'bool'}, 'max_request_body_size': {'key': 'maxRequestBodySize', 'type': 'int'}, 'max_request_body_size_in_kb': {'key': 'maxRequestBodySizeInKb', 'type': 'int'}, 'file_upload_limit_in_mb': {'key': 'fileUploadLimitInMb', 'type': 'int'}, 'exclusions': {'key': 'exclusions', 'type': '[ApplicationGatewayFirewallExclusion]'}, } def __init__(self, **kwargs): super(ApplicationGatewayWebApplicationFirewallConfiguration, self).__init__(**kwargs) self.enabled = kwargs.get('enabled', None) self.firewall_mode = kwargs.get('firewall_mode', None) self.rule_set_type = kwargs.get('rule_set_type', None) self.rule_set_version = kwargs.get('rule_set_version', None) self.disabled_rule_groups = kwargs.get('disabled_rule_groups', None) self.request_body_check = kwargs.get('request_body_check', None) self.max_request_body_size = kwargs.get('max_request_body_size', None) self.max_request_body_size_in_kb = kwargs.get('max_request_body_size_in_kb', None) self.file_upload_limit_in_mb = kwargs.get('file_upload_limit_in_mb', None) self.exclusions = kwargs.get('exclusions', None) class ApplicationSecurityGroup(Resource): """An application security group in a resource group. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :ivar resource_guid: The resource GUID property of the application security group resource. It uniquely identifies a resource, even if the user changes its name or migrate the resource across subscriptions or resource groups. :vartype resource_guid: str :ivar provisioning_state: The provisioning state of the application security group resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'resource_guid': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationSecurityGroup, self).__init__(**kwargs) self.resource_guid = None self.provisioning_state = None self.etag = None class AutoApprovedPrivateLinkService(Model): """The information of an AutoApprovedPrivateLinkService. :param private_link_service: The id of the private link service resource. :type private_link_service: str """ _attribute_map = { 'private_link_service': {'key': 'privateLinkService', 'type': 'str'}, } def __init__(self, **kwargs): super(AutoApprovedPrivateLinkService, self).__init__(**kwargs) self.private_link_service = kwargs.get('private_link_service', None) class Availability(Model): """Availability of the metric. :param time_grain: The time grain of the availability. :type time_grain: str :param retention: The retention of the availability. :type retention: str :param blob_duration: Duration of the availability blob. :type blob_duration: str """ _attribute_map = { 'time_grain': {'key': 'timeGrain', 'type': 'str'}, 'retention': {'key': 'retention', 'type': 'str'}, 'blob_duration': {'key': 'blobDuration', 'type': 'str'}, } def __init__(self, **kwargs): super(Availability, self).__init__(**kwargs) self.time_grain = kwargs.get('time_grain', None) self.retention = kwargs.get('retention', None) self.blob_duration = kwargs.get('blob_duration', None) class AvailableDelegation(Model): """The serviceName of an AvailableDelegation indicates a possible delegation for a subnet. :param name: The name of the AvailableDelegation resource. :type name: str :param id: A unique identifier of the AvailableDelegation resource. :type id: str :param type: Resource type. :type type: str :param service_name: The name of the service and resource. :type service_name: str :param actions: Describes the actions permitted to the service upon delegation. :type actions: list[str] """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'service_name': {'key': 'serviceName', 'type': 'str'}, 'actions': {'key': 'actions', 'type': '[str]'}, } def __init__(self, **kwargs): super(AvailableDelegation, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.id = kwargs.get('id', None) self.type = kwargs.get('type', None) self.service_name = kwargs.get('service_name', None) self.actions = kwargs.get('actions', None) class AvailablePrivateEndpointType(Model): """The information of an AvailablePrivateEndpointType. :param name: The name of the service and resource. :type name: str :param id: A unique identifier of the AvailablePrivateEndpoint Type resource. :type id: str :param type: Resource type. :type type: str :param resource_name: The name of the service and resource. :type resource_name: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'resource_name': {'key': 'resourceName', 'type': 'str'}, } def __init__(self, **kwargs): super(AvailablePrivateEndpointType, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.id = kwargs.get('id', None) self.type = kwargs.get('type', None) self.resource_name = kwargs.get('resource_name', None) class AvailableProvidersList(Model): """List of available countries with details. All required parameters must be populated in order to send to Azure. :param countries: Required. List of available countries. :type countries: list[~azure.mgmt.network.v2019_06_01.models.AvailableProvidersListCountry] """ _validation = { 'countries': {'required': True}, } _attribute_map = { 'countries': {'key': 'countries', 'type': '[AvailableProvidersListCountry]'}, } def __init__(self, **kwargs): super(AvailableProvidersList, self).__init__(**kwargs) self.countries = kwargs.get('countries', None) class AvailableProvidersListCity(Model): """City or town details. :param city_name: The city or town name. :type city_name: str :param providers: A list of Internet service providers. :type providers: list[str] """ _attribute_map = { 'city_name': {'key': 'cityName', 'type': 'str'}, 'providers': {'key': 'providers', 'type': '[str]'}, } def __init__(self, **kwargs): super(AvailableProvidersListCity, self).__init__(**kwargs) self.city_name = kwargs.get('city_name', None) self.providers = kwargs.get('providers', None) class AvailableProvidersListCountry(Model): """Country details. :param country_name: The country name. :type country_name: str :param providers: A list of Internet service providers. :type providers: list[str] :param states: List of available states in the country. :type states: list[~azure.mgmt.network.v2019_06_01.models.AvailableProvidersListState] """ _attribute_map = { 'country_name': {'key': 'countryName', 'type': 'str'}, 'providers': {'key': 'providers', 'type': '[str]'}, 'states': {'key': 'states', 'type': '[AvailableProvidersListState]'}, } def __init__(self, **kwargs): super(AvailableProvidersListCountry, self).__init__(**kwargs) self.country_name = kwargs.get('country_name', None) self.providers = kwargs.get('providers', None) self.states = kwargs.get('states', None) class AvailableProvidersListParameters(Model): """Constraints that determine the list of available Internet service providers. :param azure_locations: A list of Azure regions. :type azure_locations: list[str] :param country: The country for available providers list. :type country: str :param state: The state for available providers list. :type state: str :param city: The city or town for available providers list. :type city: str """ _attribute_map = { 'azure_locations': {'key': 'azureLocations', 'type': '[str]'}, 'country': {'key': 'country', 'type': 'str'}, 'state': {'key': 'state', 'type': 'str'}, 'city': {'key': 'city', 'type': 'str'}, } def __init__(self, **kwargs): super(AvailableProvidersListParameters, self).__init__(**kwargs) self.azure_locations = kwargs.get('azure_locations', None) self.country = kwargs.get('country', None) self.state = kwargs.get('state', None) self.city = kwargs.get('city', None) class AvailableProvidersListState(Model): """State details. :param state_name: The state name. :type state_name: str :param providers: A list of Internet service providers. :type providers: list[str] :param cities: List of available cities or towns in the state. :type cities: list[~azure.mgmt.network.v2019_06_01.models.AvailableProvidersListCity] """ _attribute_map = { 'state_name': {'key': 'stateName', 'type': 'str'}, 'providers': {'key': 'providers', 'type': '[str]'}, 'cities': {'key': 'cities', 'type': '[AvailableProvidersListCity]'}, } def __init__(self, **kwargs): super(AvailableProvidersListState, self).__init__(**kwargs) self.state_name = kwargs.get('state_name', None) self.providers = kwargs.get('providers', None) self.cities = kwargs.get('cities', None) class AzureAsyncOperationResult(Model): """The response body contains the status of the specified asynchronous operation, indicating whether it has succeeded, is in progress, or has failed. Note that this status is distinct from the HTTP status code returned for the Get Operation Status operation itself. If the asynchronous operation succeeded, the response body includes the HTTP status code for the successful request. If the asynchronous operation failed, the response body includes the HTTP status code for the failed request and error information regarding the failure. :param status: Status of the Azure async operation. Possible values include: 'InProgress', 'Succeeded', 'Failed' :type status: str or ~azure.mgmt.network.v2019_06_01.models.NetworkOperationStatus :param error: Details of the error occurred during specified asynchronous operation. :type error: ~azure.mgmt.network.v2019_06_01.models.Error """ _attribute_map = { 'status': {'key': 'status', 'type': 'str'}, 'error': {'key': 'error', 'type': 'Error'}, } def __init__(self, **kwargs): super(AzureAsyncOperationResult, self).__init__(**kwargs) self.status = kwargs.get('status', None) self.error = kwargs.get('error', None) class AzureFirewall(Resource): """Azure Firewall resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param application_rule_collections: Collection of application rule collections used by Azure Firewall. :type application_rule_collections: list[~azure.mgmt.network.v2019_06_01.models.AzureFirewallApplicationRuleCollection] :param nat_rule_collections: Collection of NAT rule collections used by Azure Firewall. :type nat_rule_collections: list[~azure.mgmt.network.v2019_06_01.models.AzureFirewallNatRuleCollection] :param network_rule_collections: Collection of network rule collections used by Azure Firewall. :type network_rule_collections: list[~azure.mgmt.network.v2019_06_01.models.AzureFirewallNetworkRuleCollection] :param ip_configurations: IP configuration of the Azure Firewall resource. :type ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.AzureFirewallIPConfiguration] :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param threat_intel_mode: The operation mode for Threat Intelligence. Possible values include: 'Alert', 'Deny', 'Off' :type threat_intel_mode: str or ~azure.mgmt.network.v2019_06_01.models.AzureFirewallThreatIntelMode :param zones: A list of availability zones denoting where the resource needs to come from. :type zones: list[str] :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'application_rule_collections': {'key': 'properties.applicationRuleCollections', 'type': '[AzureFirewallApplicationRuleCollection]'}, 'nat_rule_collections': {'key': 'properties.natRuleCollections', 'type': '[AzureFirewallNatRuleCollection]'}, 'network_rule_collections': {'key': 'properties.networkRuleCollections', 'type': '[AzureFirewallNetworkRuleCollection]'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[AzureFirewallIPConfiguration]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'threat_intel_mode': {'key': 'properties.threatIntelMode', 'type': 'str'}, 'zones': {'key': 'zones', 'type': '[str]'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(AzureFirewall, self).__init__(**kwargs) self.application_rule_collections = kwargs.get('application_rule_collections', None) self.nat_rule_collections = kwargs.get('nat_rule_collections', None) self.network_rule_collections = kwargs.get('network_rule_collections', None) self.ip_configurations = kwargs.get('ip_configurations', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.threat_intel_mode = kwargs.get('threat_intel_mode', None) self.zones = kwargs.get('zones', None) self.etag = None class AzureFirewallApplicationRule(Model): """Properties of an application rule. :param name: Name of the application rule. :type name: str :param description: Description of the rule. :type description: str :param source_addresses: List of source IP addresses for this rule. :type source_addresses: list[str] :param protocols: Array of ApplicationRuleProtocols. :type protocols: list[~azure.mgmt.network.v2019_06_01.models.AzureFirewallApplicationRuleProtocol] :param target_fqdns: List of FQDNs for this rule. :type target_fqdns: list[str] :param fqdn_tags: List of FQDN Tags for this rule. :type fqdn_tags: list[str] """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'}, 'protocols': {'key': 'protocols', 'type': '[AzureFirewallApplicationRuleProtocol]'}, 'target_fqdns': {'key': 'targetFqdns', 'type': '[str]'}, 'fqdn_tags': {'key': 'fqdnTags', 'type': '[str]'}, } def __init__(self, **kwargs): super(AzureFirewallApplicationRule, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.description = kwargs.get('description', None) self.source_addresses = kwargs.get('source_addresses', None) self.protocols = kwargs.get('protocols', None) self.target_fqdns = kwargs.get('target_fqdns', None) self.fqdn_tags = kwargs.get('fqdn_tags', None) class AzureFirewallApplicationRuleCollection(SubResource): """Application rule collection resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param priority: Priority of the application rule collection resource. :type priority: int :param action: The action type of a rule collection. :type action: ~azure.mgmt.network.v2019_06_01.models.AzureFirewallRCAction :param rules: Collection of rules used by a application rule collection. :type rules: list[~azure.mgmt.network.v2019_06_01.models.AzureFirewallApplicationRule] :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'priority': {'maximum': 65000, 'minimum': 100}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'priority': {'key': 'properties.priority', 'type': 'int'}, 'action': {'key': 'properties.action', 'type': 'AzureFirewallRCAction'}, 'rules': {'key': 'properties.rules', 'type': '[AzureFirewallApplicationRule]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(AzureFirewallApplicationRuleCollection, self).__init__(**kwargs) self.priority = kwargs.get('priority', None) self.action = kwargs.get('action', None) self.rules = kwargs.get('rules', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = None class AzureFirewallApplicationRuleProtocol(Model): """Properties of the application rule protocol. :param protocol_type: Protocol type. Possible values include: 'Http', 'Https' :type protocol_type: str or ~azure.mgmt.network.v2019_06_01.models.AzureFirewallApplicationRuleProtocolType :param port: Port number for the protocol, cannot be greater than 64000. This field is optional. :type port: int """ _validation = { 'port': {'maximum': 64000, 'minimum': 0}, } _attribute_map = { 'protocol_type': {'key': 'protocolType', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__(self, **kwargs): super(AzureFirewallApplicationRuleProtocol, self).__init__(**kwargs) self.protocol_type = kwargs.get('protocol_type', None) self.port = kwargs.get('port', None) class AzureFirewallFqdnTag(Resource): """Azure Firewall FQDN Tag Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :ivar provisioning_state: The provisioning state of the resource. :vartype provisioning_state: str :ivar fqdn_tag_name: The name of this FQDN Tag. :vartype fqdn_tag_name: str :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'fqdn_tag_name': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'fqdn_tag_name': {'key': 'properties.fqdnTagName', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(AzureFirewallFqdnTag, self).__init__(**kwargs) self.provisioning_state = None self.fqdn_tag_name = None self.etag = None class AzureFirewallIPConfiguration(SubResource): """IP configuration of an Azure Firewall. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar private_ip_address: The Firewall Internal Load Balancer IP to be used as the next hop in User Defined Routes. :vartype private_ip_address: str :param subnet: Reference of the subnet resource. This resource must be named 'AzureFirewallSubnet'. :type subnet: ~azure.mgmt.network.v2019_06_01.models.SubResource :param public_ip_address: Reference of the PublicIP resource. This field is a mandatory input if subnet is not null. :type public_ip_address: ~azure.mgmt.network.v2019_06_01.models.SubResource :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'private_ip_address': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'SubResource'}, 'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(AzureFirewallIPConfiguration, self).__init__(**kwargs) self.private_ip_address = None self.subnet = kwargs.get('subnet', None) self.public_ip_address = kwargs.get('public_ip_address', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = None class AzureFirewallNatRCAction(Model): """AzureFirewall NAT Rule Collection Action. :param type: The type of action. Possible values include: 'Snat', 'Dnat' :type type: str or ~azure.mgmt.network.v2019_06_01.models.AzureFirewallNatRCActionType """ _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(AzureFirewallNatRCAction, self).__init__(**kwargs) self.type = kwargs.get('type', None) class AzureFirewallNatRule(Model): """Properties of a NAT rule. :param name: Name of the NAT rule. :type name: str :param description: Description of the rule. :type description: str :param source_addresses: List of source IP addresses for this rule. :type source_addresses: list[str] :param destination_addresses: List of destination IP addresses for this rule. Supports IP ranges, prefixes, and service tags. :type destination_addresses: list[str] :param destination_ports: List of destination ports. :type destination_ports: list[str] :param protocols: Array of AzureFirewallNetworkRuleProtocols applicable to this NAT rule. :type protocols: list[str or ~azure.mgmt.network.v2019_06_01.models.AzureFirewallNetworkRuleProtocol] :param translated_address: The translated address for this NAT rule. :type translated_address: str :param translated_port: The translated port for this NAT rule. :type translated_port: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'}, 'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'}, 'destination_ports': {'key': 'destinationPorts', 'type': '[str]'}, 'protocols': {'key': 'protocols', 'type': '[str]'}, 'translated_address': {'key': 'translatedAddress', 'type': 'str'}, 'translated_port': {'key': 'translatedPort', 'type': 'str'}, } def __init__(self, **kwargs): super(AzureFirewallNatRule, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.description = kwargs.get('description', None) self.source_addresses = kwargs.get('source_addresses', None) self.destination_addresses = kwargs.get('destination_addresses', None) self.destination_ports = kwargs.get('destination_ports', None) self.protocols = kwargs.get('protocols', None) self.translated_address = kwargs.get('translated_address', None) self.translated_port = kwargs.get('translated_port', None) class AzureFirewallNatRuleCollection(SubResource): """NAT rule collection resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param priority: Priority of the NAT rule collection resource. :type priority: int :param action: The action type of a NAT rule collection. :type action: ~azure.mgmt.network.v2019_06_01.models.AzureFirewallNatRCAction :param rules: Collection of rules used by a NAT rule collection. :type rules: list[~azure.mgmt.network.v2019_06_01.models.AzureFirewallNatRule] :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'priority': {'maximum': 65000, 'minimum': 100}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'priority': {'key': 'properties.priority', 'type': 'int'}, 'action': {'key': 'properties.action', 'type': 'AzureFirewallNatRCAction'}, 'rules': {'key': 'properties.rules', 'type': '[AzureFirewallNatRule]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(AzureFirewallNatRuleCollection, self).__init__(**kwargs) self.priority = kwargs.get('priority', None) self.action = kwargs.get('action', None) self.rules = kwargs.get('rules', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = None class AzureFirewallNetworkRule(Model): """Properties of the network rule. :param name: Name of the network rule. :type name: str :param description: Description of the rule. :type description: str :param protocols: Array of AzureFirewallNetworkRuleProtocols. :type protocols: list[str or ~azure.mgmt.network.v2019_06_01.models.AzureFirewallNetworkRuleProtocol] :param source_addresses: List of source IP addresses for this rule. :type source_addresses: list[str] :param destination_addresses: List of destination IP addresses. :type destination_addresses: list[str] :param destination_ports: List of destination ports. :type destination_ports: list[str] """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'protocols': {'key': 'protocols', 'type': '[str]'}, 'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'}, 'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'}, 'destination_ports': {'key': 'destinationPorts', 'type': '[str]'}, } def __init__(self, **kwargs): super(AzureFirewallNetworkRule, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.description = kwargs.get('description', None) self.protocols = kwargs.get('protocols', None) self.source_addresses = kwargs.get('source_addresses', None) self.destination_addresses = kwargs.get('destination_addresses', None) self.destination_ports = kwargs.get('destination_ports', None) class AzureFirewallNetworkRuleCollection(SubResource): """Network rule collection resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param priority: Priority of the network rule collection resource. :type priority: int :param action: The action type of a rule collection. :type action: ~azure.mgmt.network.v2019_06_01.models.AzureFirewallRCAction :param rules: Collection of rules used by a network rule collection. :type rules: list[~azure.mgmt.network.v2019_06_01.models.AzureFirewallNetworkRule] :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'priority': {'maximum': 65000, 'minimum': 100}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'priority': {'key': 'properties.priority', 'type': 'int'}, 'action': {'key': 'properties.action', 'type': 'AzureFirewallRCAction'}, 'rules': {'key': 'properties.rules', 'type': '[AzureFirewallNetworkRule]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(AzureFirewallNetworkRuleCollection, self).__init__(**kwargs) self.priority = kwargs.get('priority', None) self.action = kwargs.get('action', None) self.rules = kwargs.get('rules', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = None class AzureFirewallRCAction(Model): """Properties of the AzureFirewallRCAction. :param type: The type of action. Possible values include: 'Allow', 'Deny' :type type: str or ~azure.mgmt.network.v2019_06_01.models.AzureFirewallRCActionType """ _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(AzureFirewallRCAction, self).__init__(**kwargs) self.type = kwargs.get('type', None) class AzureReachabilityReport(Model): """Azure reachability report details. All required parameters must be populated in order to send to Azure. :param aggregation_level: Required. The aggregation level of Azure reachability report. Can be Country, State or City. :type aggregation_level: str :param provider_location: Required. Parameters that define a geographic location. :type provider_location: ~azure.mgmt.network.v2019_06_01.models.AzureReachabilityReportLocation :param reachability_report: Required. List of Azure reachability report items. :type reachability_report: list[~azure.mgmt.network.v2019_06_01.models.AzureReachabilityReportItem] """ _validation = { 'aggregation_level': {'required': True}, 'provider_location': {'required': True}, 'reachability_report': {'required': True}, } _attribute_map = { 'aggregation_level': {'key': 'aggregationLevel', 'type': 'str'}, 'provider_location': {'key': 'providerLocation', 'type': 'AzureReachabilityReportLocation'}, 'reachability_report': {'key': 'reachabilityReport', 'type': '[AzureReachabilityReportItem]'}, } def __init__(self, **kwargs): super(AzureReachabilityReport, self).__init__(**kwargs) self.aggregation_level = kwargs.get('aggregation_level', None) self.provider_location = kwargs.get('provider_location', None) self.reachability_report = kwargs.get('reachability_report', None) class AzureReachabilityReportItem(Model): """Azure reachability report details for a given provider location. :param provider: The Internet service provider. :type provider: str :param azure_location: The Azure region. :type azure_location: str :param latencies: List of latency details for each of the time series. :type latencies: list[~azure.mgmt.network.v2019_06_01.models.AzureReachabilityReportLatencyInfo] """ _attribute_map = { 'provider': {'key': 'provider', 'type': 'str'}, 'azure_location': {'key': 'azureLocation', 'type': 'str'}, 'latencies': {'key': 'latencies', 'type': '[AzureReachabilityReportLatencyInfo]'}, } def __init__(self, **kwargs): super(AzureReachabilityReportItem, self).__init__(**kwargs) self.provider = kwargs.get('provider', None) self.azure_location = kwargs.get('azure_location', None) self.latencies = kwargs.get('latencies', None) class AzureReachabilityReportLatencyInfo(Model): """Details on latency for a time series. :param time_stamp: The time stamp. :type time_stamp: datetime :param score: The relative latency score between 1 and 100, higher values indicating a faster connection. :type score: int """ _validation = { 'score': {'maximum': 100, 'minimum': 1}, } _attribute_map = { 'time_stamp': {'key': 'timeStamp', 'type': 'iso-8601'}, 'score': {'key': 'score', 'type': 'int'}, } def __init__(self, **kwargs): super(AzureReachabilityReportLatencyInfo, self).__init__(**kwargs) self.time_stamp = kwargs.get('time_stamp', None) self.score = kwargs.get('score', None) class AzureReachabilityReportLocation(Model): """Parameters that define a geographic location. All required parameters must be populated in order to send to Azure. :param country: Required. The name of the country. :type country: str :param state: The name of the state. :type state: str :param city: The name of the city or town. :type city: str """ _validation = { 'country': {'required': True}, } _attribute_map = { 'country': {'key': 'country', 'type': 'str'}, 'state': {'key': 'state', 'type': 'str'}, 'city': {'key': 'city', 'type': 'str'}, } def __init__(self, **kwargs): super(AzureReachabilityReportLocation, self).__init__(**kwargs) self.country = kwargs.get('country', None) self.state = kwargs.get('state', None) self.city = kwargs.get('city', None) class AzureReachabilityReportParameters(Model): """Geographic and time constraints for Azure reachability report. All required parameters must be populated in order to send to Azure. :param provider_location: Required. Parameters that define a geographic location. :type provider_location: ~azure.mgmt.network.v2019_06_01.models.AzureReachabilityReportLocation :param providers: List of Internet service providers. :type providers: list[str] :param azure_locations: Optional Azure regions to scope the query to. :type azure_locations: list[str] :param start_time: Required. The start time for the Azure reachability report. :type start_time: datetime :param end_time: Required. The end time for the Azure reachability report. :type end_time: datetime """ _validation = { 'provider_location': {'required': True}, 'start_time': {'required': True}, 'end_time': {'required': True}, } _attribute_map = { 'provider_location': {'key': 'providerLocation', 'type': 'AzureReachabilityReportLocation'}, 'providers': {'key': 'providers', 'type': '[str]'}, 'azure_locations': {'key': 'azureLocations', 'type': '[str]'}, 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, } def __init__(self, **kwargs): super(AzureReachabilityReportParameters, self).__init__(**kwargs) self.provider_location = kwargs.get('provider_location', None) self.providers = kwargs.get('providers', None) self.azure_locations = kwargs.get('azure_locations', None) self.start_time = kwargs.get('start_time', None) self.end_time = kwargs.get('end_time', None) class BackendAddressPool(SubResource): """Pool of backend IP addresses. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar backend_ip_configurations: Gets collection of references to IP addresses defined in network interfaces. :vartype backend_ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.NetworkInterfaceIPConfiguration] :ivar load_balancing_rules: Gets load balancing rules that use this backend address pool. :vartype load_balancing_rules: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :ivar outbound_rule: Gets outbound rules that use this backend address pool. :vartype outbound_rule: ~azure.mgmt.network.v2019_06_01.models.SubResource :ivar outbound_rules: Gets outbound rules that use this backend address pool. :vartype outbound_rules: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param provisioning_state: Get provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Gets name of the resource that is unique within the set of backend address pools used by the load balancer. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :ivar type: Type of the resource. :vartype type: str """ _validation = { 'backend_ip_configurations': {'readonly': True}, 'load_balancing_rules': {'readonly': True}, 'outbound_rule': {'readonly': True}, 'outbound_rules': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'backend_ip_configurations': {'key': 'properties.backendIPConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'}, 'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'}, 'outbound_rule': {'key': 'properties.outboundRule', 'type': 'SubResource'}, 'outbound_rules': {'key': 'properties.outboundRules', 'type': '[SubResource]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(BackendAddressPool, self).__init__(**kwargs) self.backend_ip_configurations = None self.load_balancing_rules = None self.outbound_rule = None self.outbound_rules = None self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = None class BastionHost(Resource): """Bastion Host resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param ip_configurations: IP configuration of the Bastion Host resource. :type ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.BastionHostIPConfiguration] :param dns_name: FQDN for the endpoint on which bastion host is accessible. :type dns_name: str :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[BastionHostIPConfiguration]'}, 'dns_name': {'key': 'properties.dnsName', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(BastionHost, self).__init__(**kwargs) self.ip_configurations = kwargs.get('ip_configurations', None) self.dns_name = kwargs.get('dns_name', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.etag = None class BastionHostIPConfiguration(SubResource): """IP configuration of an Bastion Host. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param subnet: Required. Reference of the subnet resource. :type subnet: ~azure.mgmt.network.v2019_06_01.models.SubResource :param public_ip_address: Required. Reference of the PublicIP resource. :type public_ip_address: ~azure.mgmt.network.v2019_06_01.models.SubResource :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param private_ip_allocation_method: Private IP allocation method. Possible values include: 'Static', 'Dynamic' :type private_ip_allocation_method: str or ~azure.mgmt.network.v2019_06_01.models.IPAllocationMethod :param name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Ip configuration type. :vartype type: str """ _validation = { 'subnet': {'required': True}, 'public_ip_address': {'required': True}, 'etag': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'SubResource'}, 'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(BastionHostIPConfiguration, self).__init__(**kwargs) self.subnet = kwargs.get('subnet', None) self.public_ip_address = kwargs.get('public_ip_address', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None) self.name = kwargs.get('name', None) self.etag = None self.type = None class BGPCommunity(Model): """Contains bgp community information offered in Service Community resources. :param service_supported_region: The region which the service support. e.g. For O365, region is Global. :type service_supported_region: str :param community_name: The name of the bgp community. e.g. Skype. :type community_name: str :param community_value: The value of the bgp community. For more information: https://docs.microsoft.com/en-us/azure/expressroute/expressroute-routing. :type community_value: str :param community_prefixes: The prefixes that the bgp community contains. :type community_prefixes: list[str] :param is_authorized_to_use: Customer is authorized to use bgp community or not. :type is_authorized_to_use: bool :param service_group: The service group of the bgp community contains. :type service_group: str """ _attribute_map = { 'service_supported_region': {'key': 'serviceSupportedRegion', 'type': 'str'}, 'community_name': {'key': 'communityName', 'type': 'str'}, 'community_value': {'key': 'communityValue', 'type': 'str'}, 'community_prefixes': {'key': 'communityPrefixes', 'type': '[str]'}, 'is_authorized_to_use': {'key': 'isAuthorizedToUse', 'type': 'bool'}, 'service_group': {'key': 'serviceGroup', 'type': 'str'}, } def __init__(self, **kwargs): super(BGPCommunity, self).__init__(**kwargs) self.service_supported_region = kwargs.get('service_supported_region', None) self.community_name = kwargs.get('community_name', None) self.community_value = kwargs.get('community_value', None) self.community_prefixes = kwargs.get('community_prefixes', None) self.is_authorized_to_use = kwargs.get('is_authorized_to_use', None) self.service_group = kwargs.get('service_group', None) class BgpPeerStatus(Model): """BGP peer status details. Variables are only populated by the server, and will be ignored when sending a request. :ivar local_address: The virtual network gateway's local address. :vartype local_address: str :ivar neighbor: The remote BGP peer. :vartype neighbor: str :ivar asn: The autonomous system number of the remote BGP peer. :vartype asn: int :ivar state: The BGP peer state. Possible values include: 'Unknown', 'Stopped', 'Idle', 'Connecting', 'Connected' :vartype state: str or ~azure.mgmt.network.v2019_06_01.models.BgpPeerState :ivar connected_duration: For how long the peering has been up. :vartype connected_duration: str :ivar routes_received: The number of routes learned from this peer. :vartype routes_received: long :ivar messages_sent: The number of BGP messages sent. :vartype messages_sent: long :ivar messages_received: The number of BGP messages received. :vartype messages_received: long """ _validation = { 'local_address': {'readonly': True}, 'neighbor': {'readonly': True}, 'asn': {'readonly': True}, 'state': {'readonly': True}, 'connected_duration': {'readonly': True}, 'routes_received': {'readonly': True}, 'messages_sent': {'readonly': True}, 'messages_received': {'readonly': True}, } _attribute_map = { 'local_address': {'key': 'localAddress', 'type': 'str'}, 'neighbor': {'key': 'neighbor', 'type': 'str'}, 'asn': {'key': 'asn', 'type': 'int'}, 'state': {'key': 'state', 'type': 'str'}, 'connected_duration': {'key': 'connectedDuration', 'type': 'str'}, 'routes_received': {'key': 'routesReceived', 'type': 'long'}, 'messages_sent': {'key': 'messagesSent', 'type': 'long'}, 'messages_received': {'key': 'messagesReceived', 'type': 'long'}, } def __init__(self, **kwargs): super(BgpPeerStatus, self).__init__(**kwargs) self.local_address = None self.neighbor = None self.asn = None self.state = None self.connected_duration = None self.routes_received = None self.messages_sent = None self.messages_received = None class BgpPeerStatusListResult(Model): """Response for list BGP peer status API service call. :param value: List of BGP peers. :type value: list[~azure.mgmt.network.v2019_06_01.models.BgpPeerStatus] """ _attribute_map = { 'value': {'key': 'value', 'type': '[BgpPeerStatus]'}, } def __init__(self, **kwargs): super(BgpPeerStatusListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) class BgpServiceCommunity(Resource): """Service Community Properties. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param service_name: The name of the bgp community. e.g. Skype. :type service_name: str :param bgp_communities: Get a list of bgp communities. :type bgp_communities: list[~azure.mgmt.network.v2019_06_01.models.BGPCommunity] """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'service_name': {'key': 'properties.serviceName', 'type': 'str'}, 'bgp_communities': {'key': 'properties.bgpCommunities', 'type': '[BGPCommunity]'}, } def __init__(self, **kwargs): super(BgpServiceCommunity, self).__init__(**kwargs) self.service_name = kwargs.get('service_name', None) self.bgp_communities = kwargs.get('bgp_communities', None) class BgpSettings(Model): """BGP settings details. :param asn: The BGP speaker's ASN. :type asn: long :param bgp_peering_address: The BGP peering address and BGP identifier of this BGP speaker. :type bgp_peering_address: str :param peer_weight: The weight added to routes learned from this BGP speaker. :type peer_weight: int """ _attribute_map = { 'asn': {'key': 'asn', 'type': 'long'}, 'bgp_peering_address': {'key': 'bgpPeeringAddress', 'type': 'str'}, 'peer_weight': {'key': 'peerWeight', 'type': 'int'}, } def __init__(self, **kwargs): super(BgpSettings, self).__init__(**kwargs) self.asn = kwargs.get('asn', None) self.bgp_peering_address = kwargs.get('bgp_peering_address', None) self.peer_weight = kwargs.get('peer_weight', None) class CheckPrivateLinkServiceVisibilityRequest(Model): """Request body of the CheckPrivateLinkServiceVisibility API service call. :param private_link_service_alias: The alias of the private link service. :type private_link_service_alias: str """ _attribute_map = { 'private_link_service_alias': {'key': 'privateLinkServiceAlias', 'type': 'str'}, } def __init__(self, **kwargs): super(CheckPrivateLinkServiceVisibilityRequest, self).__init__(**kwargs) self.private_link_service_alias = kwargs.get('private_link_service_alias', None) class CloudError(Model): """An error response from the Batch service. :param error: Cloud error body. :type error: ~azure.mgmt.network.v2019_06_01.models.CloudErrorBody """ _attribute_map = { 'error': {'key': 'error', 'type': 'CloudErrorBody'}, } def __init__(self, **kwargs): super(CloudError, self).__init__(**kwargs) self.error = kwargs.get('error', None) class CloudErrorException(HttpOperationError): """Server responsed with exception of type: 'CloudError'. :param deserialize: A deserializer :param response: Server response to be deserialized. """ def __init__(self, deserialize, response, *args): super(CloudErrorException, self).__init__(deserialize, response, 'CloudError', *args) class CloudErrorBody(Model): """An error response from the Batch service. :param code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. :type code: str :param message: A message describing the error, intended to be suitable for display in a user interface. :type message: str :param target: The target of the particular error. For example, the name of the property in error. :type target: str :param details: A list of additional details about the error. :type details: list[~azure.mgmt.network.v2019_06_01.models.CloudErrorBody] """ _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, } def __init__(self, **kwargs): super(CloudErrorBody, self).__init__(**kwargs) self.code = kwargs.get('code', None) self.message = kwargs.get('message', None) self.target = kwargs.get('target', None) self.details = kwargs.get('details', None) class ConnectionMonitor(Model): """Parameters that define the operation to create a connection monitor. All required parameters must be populated in order to send to Azure. :param location: Connection monitor location. :type location: str :param tags: Connection monitor tags. :type tags: dict[str, str] :param source: Required. Describes the source of connection monitor. :type source: ~azure.mgmt.network.v2019_06_01.models.ConnectionMonitorSource :param destination: Required. Describes the destination of connection monitor. :type destination: ~azure.mgmt.network.v2019_06_01.models.ConnectionMonitorDestination :param auto_start: Determines if the connection monitor will start automatically once created. Default value: True . :type auto_start: bool :param monitoring_interval_in_seconds: Monitoring interval in seconds. Default value: 60 . :type monitoring_interval_in_seconds: int """ _validation = { 'source': {'required': True}, 'destination': {'required': True}, } _attribute_map = { 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'source': {'key': 'properties.source', 'type': 'ConnectionMonitorSource'}, 'destination': {'key': 'properties.destination', 'type': 'ConnectionMonitorDestination'}, 'auto_start': {'key': 'properties.autoStart', 'type': 'bool'}, 'monitoring_interval_in_seconds': {'key': 'properties.monitoringIntervalInSeconds', 'type': 'int'}, } def __init__(self, **kwargs): super(ConnectionMonitor, self).__init__(**kwargs) self.location = kwargs.get('location', None) self.tags = kwargs.get('tags', None) self.source = kwargs.get('source', None) self.destination = kwargs.get('destination', None) self.auto_start = kwargs.get('auto_start', True) self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60) class ConnectionMonitorDestination(Model): """Describes the destination of connection monitor. :param resource_id: The ID of the resource used as the destination by connection monitor. :type resource_id: str :param address: Address of the connection monitor destination (IP or domain name). :type address: str :param port: The destination port used by connection monitor. :type port: int """ _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'address': {'key': 'address', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__(self, **kwargs): super(ConnectionMonitorDestination, self).__init__(**kwargs) self.resource_id = kwargs.get('resource_id', None) self.address = kwargs.get('address', None) self.port = kwargs.get('port', None) class ConnectionMonitorParameters(Model): """Parameters that define the operation to create a connection monitor. All required parameters must be populated in order to send to Azure. :param source: Required. Describes the source of connection monitor. :type source: ~azure.mgmt.network.v2019_06_01.models.ConnectionMonitorSource :param destination: Required. Describes the destination of connection monitor. :type destination: ~azure.mgmt.network.v2019_06_01.models.ConnectionMonitorDestination :param auto_start: Determines if the connection monitor will start automatically once created. Default value: True . :type auto_start: bool :param monitoring_interval_in_seconds: Monitoring interval in seconds. Default value: 60 . :type monitoring_interval_in_seconds: int """ _validation = { 'source': {'required': True}, 'destination': {'required': True}, } _attribute_map = { 'source': {'key': 'source', 'type': 'ConnectionMonitorSource'}, 'destination': {'key': 'destination', 'type': 'ConnectionMonitorDestination'}, 'auto_start': {'key': 'autoStart', 'type': 'bool'}, 'monitoring_interval_in_seconds': {'key': 'monitoringIntervalInSeconds', 'type': 'int'}, } def __init__(self, **kwargs): super(ConnectionMonitorParameters, self).__init__(**kwargs) self.source = kwargs.get('source', None) self.destination = kwargs.get('destination', None) self.auto_start = kwargs.get('auto_start', True) self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60) class ConnectionMonitorQueryResult(Model): """List of connection states snapshots. :param source_status: Status of connection monitor source. Possible values include: 'Unknown', 'Active', 'Inactive' :type source_status: str or ~azure.mgmt.network.v2019_06_01.models.ConnectionMonitorSourceStatus :param states: Information about connection states. :type states: list[~azure.mgmt.network.v2019_06_01.models.ConnectionStateSnapshot] """ _attribute_map = { 'source_status': {'key': 'sourceStatus', 'type': 'str'}, 'states': {'key': 'states', 'type': '[ConnectionStateSnapshot]'}, } def __init__(self, **kwargs): super(ConnectionMonitorQueryResult, self).__init__(**kwargs) self.source_status = kwargs.get('source_status', None) self.states = kwargs.get('states', None) class ConnectionMonitorResult(Model): """Information about the connection monitor. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar name: Name of the connection monitor. :vartype name: str :ivar id: ID of the connection monitor. :vartype id: str :param etag: A unique read-only string that changes whenever the resource is updated. Default value: "A unique read-only string that changes whenever the resource is updated." . :type etag: str :ivar type: Connection monitor type. :vartype type: str :param location: Connection monitor location. :type location: str :param tags: Connection monitor tags. :type tags: dict[str, str] :param source: Required. Describes the source of connection monitor. :type source: ~azure.mgmt.network.v2019_06_01.models.ConnectionMonitorSource :param destination: Required. Describes the destination of connection monitor. :type destination: ~azure.mgmt.network.v2019_06_01.models.ConnectionMonitorDestination :param auto_start: Determines if the connection monitor will start automatically once created. Default value: True . :type auto_start: bool :param monitoring_interval_in_seconds: Monitoring interval in seconds. Default value: 60 . :type monitoring_interval_in_seconds: int :param provisioning_state: The provisioning state of the connection monitor. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param start_time: The date and time when the connection monitor was started. :type start_time: datetime :param monitoring_status: The monitoring status of the connection monitor. :type monitoring_status: str """ _validation = { 'name': {'readonly': True}, 'id': {'readonly': True}, 'type': {'readonly': True}, 'source': {'required': True}, 'destination': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'source': {'key': 'properties.source', 'type': 'ConnectionMonitorSource'}, 'destination': {'key': 'properties.destination', 'type': 'ConnectionMonitorDestination'}, 'auto_start': {'key': 'properties.autoStart', 'type': 'bool'}, 'monitoring_interval_in_seconds': {'key': 'properties.monitoringIntervalInSeconds', 'type': 'int'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, 'monitoring_status': {'key': 'properties.monitoringStatus', 'type': 'str'}, } def __init__(self, **kwargs): super(ConnectionMonitorResult, self).__init__(**kwargs) self.name = None self.id = None self.etag = kwargs.get('etag', "A unique read-only string that changes whenever the resource is updated.") self.type = None self.location = kwargs.get('location', None) self.tags = kwargs.get('tags', None) self.source = kwargs.get('source', None) self.destination = kwargs.get('destination', None) self.auto_start = kwargs.get('auto_start', True) self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60) self.provisioning_state = kwargs.get('provisioning_state', None) self.start_time = kwargs.get('start_time', None) self.monitoring_status = kwargs.get('monitoring_status', None) class ConnectionMonitorSource(Model): """Describes the source of connection monitor. All required parameters must be populated in order to send to Azure. :param resource_id: Required. The ID of the resource used as the source by connection monitor. :type resource_id: str :param port: The source port used by connection monitor. :type port: int """ _validation = { 'resource_id': {'required': True}, } _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__(self, **kwargs): super(ConnectionMonitorSource, self).__init__(**kwargs) self.resource_id = kwargs.get('resource_id', None) self.port = kwargs.get('port', None) class ConnectionResetSharedKey(Model): """The virtual network connection reset shared key. All required parameters must be populated in order to send to Azure. :param key_length: Required. The virtual network connection reset shared key length, should between 1 and 128. :type key_length: int """ _validation = { 'key_length': {'required': True, 'maximum': 128, 'minimum': 1}, } _attribute_map = { 'key_length': {'key': 'keyLength', 'type': 'int'}, } def __init__(self, **kwargs): super(ConnectionResetSharedKey, self).__init__(**kwargs) self.key_length = kwargs.get('key_length', None) class ConnectionSharedKey(SubResource): """Response for GetConnectionSharedKey API service call. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param value: Required. The virtual network connection shared key value. :type value: str """ _validation = { 'value': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__(self, **kwargs): super(ConnectionSharedKey, self).__init__(**kwargs) self.value = kwargs.get('value', None) class ConnectionStateSnapshot(Model): """Connection state snapshot. Variables are only populated by the server, and will be ignored when sending a request. :param connection_state: The connection state. Possible values include: 'Reachable', 'Unreachable', 'Unknown' :type connection_state: str or ~azure.mgmt.network.v2019_06_01.models.ConnectionState :param start_time: The start time of the connection snapshot. :type start_time: datetime :param end_time: The end time of the connection snapshot. :type end_time: datetime :param evaluation_state: Connectivity analysis evaluation state. Possible values include: 'NotStarted', 'InProgress', 'Completed' :type evaluation_state: str or ~azure.mgmt.network.v2019_06_01.models.EvaluationState :param avg_latency_in_ms: Average latency in ms. :type avg_latency_in_ms: int :param min_latency_in_ms: Minimum latency in ms. :type min_latency_in_ms: int :param max_latency_in_ms: Maximum latency in ms. :type max_latency_in_ms: int :param probes_sent: The number of sent probes. :type probes_sent: int :param probes_failed: The number of failed probes. :type probes_failed: int :ivar hops: List of hops between the source and the destination. :vartype hops: list[~azure.mgmt.network.v2019_06_01.models.ConnectivityHop] """ _validation = { 'hops': {'readonly': True}, } _attribute_map = { 'connection_state': {'key': 'connectionState', 'type': 'str'}, 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, 'evaluation_state': {'key': 'evaluationState', 'type': 'str'}, 'avg_latency_in_ms': {'key': 'avgLatencyInMs', 'type': 'int'}, 'min_latency_in_ms': {'key': 'minLatencyInMs', 'type': 'int'}, 'max_latency_in_ms': {'key': 'maxLatencyInMs', 'type': 'int'}, 'probes_sent': {'key': 'probesSent', 'type': 'int'}, 'probes_failed': {'key': 'probesFailed', 'type': 'int'}, 'hops': {'key': 'hops', 'type': '[ConnectivityHop]'}, } def __init__(self, **kwargs): super(ConnectionStateSnapshot, self).__init__(**kwargs) self.connection_state = kwargs.get('connection_state', None) self.start_time = kwargs.get('start_time', None) self.end_time = kwargs.get('end_time', None) self.evaluation_state = kwargs.get('evaluation_state', None) self.avg_latency_in_ms = kwargs.get('avg_latency_in_ms', None) self.min_latency_in_ms = kwargs.get('min_latency_in_ms', None) self.max_latency_in_ms = kwargs.get('max_latency_in_ms', None) self.probes_sent = kwargs.get('probes_sent', None) self.probes_failed = kwargs.get('probes_failed', None) self.hops = None class ConnectivityDestination(Model): """Parameters that define destination of connection. :param resource_id: The ID of the resource to which a connection attempt will be made. :type resource_id: str :param address: The IP address or URI the resource to which a connection attempt will be made. :type address: str :param port: Port on which check connectivity will be performed. :type port: int """ _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'address': {'key': 'address', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__(self, **kwargs): super(ConnectivityDestination, self).__init__(**kwargs) self.resource_id = kwargs.get('resource_id', None) self.address = kwargs.get('address', None) self.port = kwargs.get('port', None) class ConnectivityHop(Model): """Information about a hop between the source and the destination. Variables are only populated by the server, and will be ignored when sending a request. :ivar type: The type of the hop. :vartype type: str :ivar id: The ID of the hop. :vartype id: str :ivar address: The IP address of the hop. :vartype address: str :ivar resource_id: The ID of the resource corresponding to this hop. :vartype resource_id: str :ivar next_hop_ids: List of next hop identifiers. :vartype next_hop_ids: list[str] :ivar issues: List of issues. :vartype issues: list[~azure.mgmt.network.v2019_06_01.models.ConnectivityIssue] """ _validation = { 'type': {'readonly': True}, 'id': {'readonly': True}, 'address': {'readonly': True}, 'resource_id': {'readonly': True}, 'next_hop_ids': {'readonly': True}, 'issues': {'readonly': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'address': {'key': 'address', 'type': 'str'}, 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'next_hop_ids': {'key': 'nextHopIds', 'type': '[str]'}, 'issues': {'key': 'issues', 'type': '[ConnectivityIssue]'}, } def __init__(self, **kwargs): super(ConnectivityHop, self).__init__(**kwargs) self.type = None self.id = None self.address = None self.resource_id = None self.next_hop_ids = None self.issues = None class ConnectivityInformation(Model): """Information on the connectivity status. Variables are only populated by the server, and will be ignored when sending a request. :ivar hops: List of hops between the source and the destination. :vartype hops: list[~azure.mgmt.network.v2019_06_01.models.ConnectivityHop] :ivar connection_status: The connection status. Possible values include: 'Unknown', 'Connected', 'Disconnected', 'Degraded' :vartype connection_status: str or ~azure.mgmt.network.v2019_06_01.models.ConnectionStatus :ivar avg_latency_in_ms: Average latency in milliseconds. :vartype avg_latency_in_ms: int :ivar min_latency_in_ms: Minimum latency in milliseconds. :vartype min_latency_in_ms: int :ivar max_latency_in_ms: Maximum latency in milliseconds. :vartype max_latency_in_ms: int :ivar probes_sent: Total number of probes sent. :vartype probes_sent: int :ivar probes_failed: Number of failed probes. :vartype probes_failed: int """ _validation = { 'hops': {'readonly': True}, 'connection_status': {'readonly': True}, 'avg_latency_in_ms': {'readonly': True}, 'min_latency_in_ms': {'readonly': True}, 'max_latency_in_ms': {'readonly': True}, 'probes_sent': {'readonly': True}, 'probes_failed': {'readonly': True}, } _attribute_map = { 'hops': {'key': 'hops', 'type': '[ConnectivityHop]'}, 'connection_status': {'key': 'connectionStatus', 'type': 'str'}, 'avg_latency_in_ms': {'key': 'avgLatencyInMs', 'type': 'int'}, 'min_latency_in_ms': {'key': 'minLatencyInMs', 'type': 'int'}, 'max_latency_in_ms': {'key': 'maxLatencyInMs', 'type': 'int'}, 'probes_sent': {'key': 'probesSent', 'type': 'int'}, 'probes_failed': {'key': 'probesFailed', 'type': 'int'}, } def __init__(self, **kwargs): super(ConnectivityInformation, self).__init__(**kwargs) self.hops = None self.connection_status = None self.avg_latency_in_ms = None self.min_latency_in_ms = None self.max_latency_in_ms = None self.probes_sent = None self.probes_failed = None class ConnectivityIssue(Model): """Information about an issue encountered in the process of checking for connectivity. Variables are only populated by the server, and will be ignored when sending a request. :ivar origin: The origin of the issue. Possible values include: 'Local', 'Inbound', 'Outbound' :vartype origin: str or ~azure.mgmt.network.v2019_06_01.models.Origin :ivar severity: The severity of the issue. Possible values include: 'Error', 'Warning' :vartype severity: str or ~azure.mgmt.network.v2019_06_01.models.Severity :ivar type: The type of issue. Possible values include: 'Unknown', 'AgentStopped', 'GuestFirewall', 'DnsResolution', 'SocketBind', 'NetworkSecurityRule', 'UserDefinedRoute', 'PortThrottled', 'Platform' :vartype type: str or ~azure.mgmt.network.v2019_06_01.models.IssueType :ivar context: Provides additional context on the issue. :vartype context: list[dict[str, str]] """ _validation = { 'origin': {'readonly': True}, 'severity': {'readonly': True}, 'type': {'readonly': True}, 'context': {'readonly': True}, } _attribute_map = { 'origin': {'key': 'origin', 'type': 'str'}, 'severity': {'key': 'severity', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'context': {'key': 'context', 'type': '[{str}]'}, } def __init__(self, **kwargs): super(ConnectivityIssue, self).__init__(**kwargs) self.origin = None self.severity = None self.type = None self.context = None class ConnectivityParameters(Model): """Parameters that determine how the connectivity check will be performed. All required parameters must be populated in order to send to Azure. :param source: Required. Describes the source of the connection. :type source: ~azure.mgmt.network.v2019_06_01.models.ConnectivitySource :param destination: Required. Describes the destination of connection. :type destination: ~azure.mgmt.network.v2019_06_01.models.ConnectivityDestination :param protocol: Network protocol. Possible values include: 'Tcp', 'Http', 'Https', 'Icmp' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.Protocol :param protocol_configuration: Configuration of the protocol. :type protocol_configuration: ~azure.mgmt.network.v2019_06_01.models.ProtocolConfiguration """ _validation = { 'source': {'required': True}, 'destination': {'required': True}, } _attribute_map = { 'source': {'key': 'source', 'type': 'ConnectivitySource'}, 'destination': {'key': 'destination', 'type': 'ConnectivityDestination'}, 'protocol': {'key': 'protocol', 'type': 'str'}, 'protocol_configuration': {'key': 'protocolConfiguration', 'type': 'ProtocolConfiguration'}, } def __init__(self, **kwargs): super(ConnectivityParameters, self).__init__(**kwargs) self.source = kwargs.get('source', None) self.destination = kwargs.get('destination', None) self.protocol = kwargs.get('protocol', None) self.protocol_configuration = kwargs.get('protocol_configuration', None) class ConnectivitySource(Model): """Parameters that define the source of the connection. All required parameters must be populated in order to send to Azure. :param resource_id: Required. The ID of the resource from which a connectivity check will be initiated. :type resource_id: str :param port: The source port from which a connectivity check will be performed. :type port: int """ _validation = { 'resource_id': {'required': True}, } _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__(self, **kwargs): super(ConnectivitySource, self).__init__(**kwargs) self.resource_id = kwargs.get('resource_id', None) self.port = kwargs.get('port', None) class Container(SubResource): """Reference to container resource in remote resource provider. :param id: Resource ID. :type id: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__(self, **kwargs): super(Container, self).__init__(**kwargs) class ContainerNetworkInterface(SubResource): """Container network interface child resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param container_network_interface_configuration: Container network interface configuration from which this container network interface is created. :type container_network_interface_configuration: ~azure.mgmt.network.v2019_06_01.models.ContainerNetworkInterfaceConfiguration :param container: Reference to the container to which this container network interface is attached. :type container: ~azure.mgmt.network.v2019_06_01.models.Container :param ip_configurations: Reference to the ip configuration on this container nic. :type ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.ContainerNetworkInterfaceIpConfiguration] :ivar provisioning_state: The provisioning state of the resource. :vartype provisioning_state: str :param name: The name of the resource. This name can be used to access the resource. :type name: str :ivar type: Sub Resource type. :vartype type: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'provisioning_state': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'container_network_interface_configuration': {'key': 'properties.containerNetworkInterfaceConfiguration', 'type': 'ContainerNetworkInterfaceConfiguration'}, 'container': {'key': 'properties.container', 'type': 'Container'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[ContainerNetworkInterfaceIpConfiguration]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ContainerNetworkInterface, self).__init__(**kwargs) self.container_network_interface_configuration = kwargs.get('container_network_interface_configuration', None) self.container = kwargs.get('container', None) self.ip_configurations = kwargs.get('ip_configurations', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.type = None self.etag = kwargs.get('etag', None) class ContainerNetworkInterfaceConfiguration(SubResource): """Container network interface configuration child resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param ip_configurations: A list of ip configurations of the container network interface configuration. :type ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.IPConfigurationProfile] :param container_network_interfaces: A list of container network interfaces created from this container network interface configuration. :type container_network_interfaces: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :ivar provisioning_state: The provisioning state of the resource. :vartype provisioning_state: str :param name: The name of the resource. This name can be used to access the resource. :type name: str :ivar type: Sub Resource type. :vartype type: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'provisioning_state': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[IPConfigurationProfile]'}, 'container_network_interfaces': {'key': 'properties.containerNetworkInterfaces', 'type': '[SubResource]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ContainerNetworkInterfaceConfiguration, self).__init__(**kwargs) self.ip_configurations = kwargs.get('ip_configurations', None) self.container_network_interfaces = kwargs.get('container_network_interfaces', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.type = None self.etag = kwargs.get('etag', None) class ContainerNetworkInterfaceIpConfiguration(Model): """The ip configuration for a container network interface. Variables are only populated by the server, and will be ignored when sending a request. :ivar provisioning_state: The provisioning state of the resource. :vartype provisioning_state: str :param name: The name of the resource. This name can be used to access the resource. :type name: str :ivar type: Sub Resource type. :vartype type: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'provisioning_state': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ContainerNetworkInterfaceIpConfiguration, self).__init__(**kwargs) self.provisioning_state = None self.name = kwargs.get('name', None) self.type = None self.etag = kwargs.get('etag', None) class DdosCustomPolicy(Resource): """A DDoS custom policy in a resource group. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :ivar resource_guid: The resource GUID property of the DDoS custom policy resource. It uniquely identifies the resource, even if the user changes its name or migrate the resource across subscriptions or resource groups. :vartype resource_guid: str :ivar provisioning_state: The provisioning state of the DDoS custom policy resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :ivar public_ip_addresses: The list of public IPs associated with the DDoS custom policy resource. This list is read-only. :vartype public_ip_addresses: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param protocol_custom_settings: The protocol-specific DDoS policy customization parameters. :type protocol_custom_settings: list[~azure.mgmt.network.v2019_06_01.models.ProtocolCustomSettingsFormat] :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'resource_guid': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'public_ip_addresses': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'public_ip_addresses': {'key': 'properties.publicIPAddresses', 'type': '[SubResource]'}, 'protocol_custom_settings': {'key': 'properties.protocolCustomSettings', 'type': '[ProtocolCustomSettingsFormat]'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(DdosCustomPolicy, self).__init__(**kwargs) self.resource_guid = None self.provisioning_state = None self.public_ip_addresses = None self.protocol_custom_settings = kwargs.get('protocol_custom_settings', None) self.etag = None class DdosProtectionPlan(Model): """A DDoS protection plan in a resource group. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource ID. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :ivar resource_guid: The resource GUID property of the DDoS protection plan resource. It uniquely identifies the resource, even if the user changes its name or migrate the resource across subscriptions or resource groups. :vartype resource_guid: str :ivar provisioning_state: The provisioning state of the DDoS protection plan resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :ivar virtual_networks: The list of virtual networks associated with the DDoS protection plan resource. This list is read-only. :vartype virtual_networks: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'resource_guid': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'virtual_networks': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'virtual_networks': {'key': 'properties.virtualNetworks', 'type': '[SubResource]'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(DdosProtectionPlan, self).__init__(**kwargs) self.id = None self.name = None self.type = None self.location = kwargs.get('location', None) self.tags = kwargs.get('tags', None) self.resource_guid = None self.provisioning_state = None self.virtual_networks = None self.etag = None class DdosSettings(Model): """Contains the DDoS protection settings of the public IP. :param ddos_custom_policy: The DDoS custom policy associated with the public IP. :type ddos_custom_policy: ~azure.mgmt.network.v2019_06_01.models.SubResource :param protection_coverage: The DDoS protection policy customizability of the public IP. Only standard coverage will have the ability to be customized. Possible values include: 'Basic', 'Standard' :type protection_coverage: str or ~azure.mgmt.network.v2019_06_01.models.DdosSettingsProtectionCoverage """ _attribute_map = { 'ddos_custom_policy': {'key': 'ddosCustomPolicy', 'type': 'SubResource'}, 'protection_coverage': {'key': 'protectionCoverage', 'type': 'str'}, } def __init__(self, **kwargs): super(DdosSettings, self).__init__(**kwargs) self.ddos_custom_policy = kwargs.get('ddos_custom_policy', None) self.protection_coverage = kwargs.get('protection_coverage', None) class Delegation(SubResource): """Details the service to which the subnet is delegated. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param service_name: The name of the service to whom the subnet should be delegated (e.g. Microsoft.Sql/servers). :type service_name: str :param actions: Describes the actions permitted to the service upon delegation. :type actions: list[str] :ivar provisioning_state: The provisioning state of the resource. :vartype provisioning_state: str :param name: The name of the resource that is unique within a subnet. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'service_name': {'key': 'properties.serviceName', 'type': 'str'}, 'actions': {'key': 'properties.actions', 'type': '[str]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(Delegation, self).__init__(**kwargs) self.service_name = kwargs.get('service_name', None) self.actions = kwargs.get('actions', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class DeviceProperties(Model): """List of properties of the device. :param device_vendor: Name of the device Vendor. :type device_vendor: str :param device_model: Model of the device. :type device_model: str :param link_speed_in_mbps: Link speed. :type link_speed_in_mbps: int """ _attribute_map = { 'device_vendor': {'key': 'deviceVendor', 'type': 'str'}, 'device_model': {'key': 'deviceModel', 'type': 'str'}, 'link_speed_in_mbps': {'key': 'linkSpeedInMbps', 'type': 'int'}, } def __init__(self, **kwargs): super(DeviceProperties, self).__init__(**kwargs) self.device_vendor = kwargs.get('device_vendor', None) self.device_model = kwargs.get('device_model', None) self.link_speed_in_mbps = kwargs.get('link_speed_in_mbps', None) class DhcpOptions(Model): """DhcpOptions contains an array of DNS servers available to VMs deployed in the virtual network. Standard DHCP option for a subnet overrides VNET DHCP options. :param dns_servers: The list of DNS servers IP addresses. :type dns_servers: list[str] """ _attribute_map = { 'dns_servers': {'key': 'dnsServers', 'type': '[str]'}, } def __init__(self, **kwargs): super(DhcpOptions, self).__init__(**kwargs) self.dns_servers = kwargs.get('dns_servers', None) class Dimension(Model): """Dimension of the metric. :param name: The name of the dimension. :type name: str :param display_name: The display name of the dimension. :type display_name: str :param internal_name: The internal name of the dimension. :type internal_name: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'internal_name': {'key': 'internalName', 'type': 'str'}, } def __init__(self, **kwargs): super(Dimension, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.display_name = kwargs.get('display_name', None) self.internal_name = kwargs.get('internal_name', None) class DnsNameAvailabilityResult(Model): """Response for the CheckDnsNameAvailability API service call. :param available: Domain availability (True/False). :type available: bool """ _attribute_map = { 'available': {'key': 'available', 'type': 'bool'}, } def __init__(self, **kwargs): super(DnsNameAvailabilityResult, self).__init__(**kwargs) self.available = kwargs.get('available', None) class EffectiveNetworkSecurityGroup(Model): """Effective network security group. :param network_security_group: The ID of network security group that is applied. :type network_security_group: ~azure.mgmt.network.v2019_06_01.models.SubResource :param association: Associated resources. :type association: ~azure.mgmt.network.v2019_06_01.models.EffectiveNetworkSecurityGroupAssociation :param effective_security_rules: A collection of effective security rules. :type effective_security_rules: list[~azure.mgmt.network.v2019_06_01.models.EffectiveNetworkSecurityRule] :param tag_map: Mapping of tags to list of IP Addresses included within the tag. :type tag_map: dict[str, list[str]] """ _attribute_map = { 'network_security_group': {'key': 'networkSecurityGroup', 'type': 'SubResource'}, 'association': {'key': 'association', 'type': 'EffectiveNetworkSecurityGroupAssociation'}, 'effective_security_rules': {'key': 'effectiveSecurityRules', 'type': '[EffectiveNetworkSecurityRule]'}, 'tag_map': {'key': 'tagMap', 'type': '{[str]}'}, } def __init__(self, **kwargs): super(EffectiveNetworkSecurityGroup, self).__init__(**kwargs) self.network_security_group = kwargs.get('network_security_group', None) self.association = kwargs.get('association', None) self.effective_security_rules = kwargs.get('effective_security_rules', None) self.tag_map = kwargs.get('tag_map', None) class EffectiveNetworkSecurityGroupAssociation(Model): """The effective network security group association. :param subnet: The ID of the subnet if assigned. :type subnet: ~azure.mgmt.network.v2019_06_01.models.SubResource :param network_interface: The ID of the network interface if assigned. :type network_interface: ~azure.mgmt.network.v2019_06_01.models.SubResource """ _attribute_map = { 'subnet': {'key': 'subnet', 'type': 'SubResource'}, 'network_interface': {'key': 'networkInterface', 'type': 'SubResource'}, } def __init__(self, **kwargs): super(EffectiveNetworkSecurityGroupAssociation, self).__init__(**kwargs) self.subnet = kwargs.get('subnet', None) self.network_interface = kwargs.get('network_interface', None) class EffectiveNetworkSecurityGroupListResult(Model): """Response for list effective network security groups API service call. Variables are only populated by the server, and will be ignored when sending a request. :param value: A list of effective network security groups. :type value: list[~azure.mgmt.network.v2019_06_01.models.EffectiveNetworkSecurityGroup] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _validation = { 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[EffectiveNetworkSecurityGroup]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(self, **kwargs): super(EffectiveNetworkSecurityGroupListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = None class EffectiveNetworkSecurityRule(Model): """Effective network security rules. :param name: The name of the security rule specified by the user (if created by the user). :type name: str :param protocol: The network protocol this rule applies to. Possible values include: 'Tcp', 'Udp', 'All' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.EffectiveSecurityRuleProtocol :param source_port_range: The source port or range. :type source_port_range: str :param destination_port_range: The destination port or range. :type destination_port_range: str :param source_port_ranges: The source port ranges. Expected values include a single integer between 0 and 65535, a range using '-' as separator (e.g. 100-400), or an asterisk (*). :type source_port_ranges: list[str] :param destination_port_ranges: The destination port ranges. Expected values include a single integer between 0 and 65535, a range using '-' as separator (e.g. 100-400), or an asterisk (*). :type destination_port_ranges: list[str] :param source_address_prefix: The source address prefix. :type source_address_prefix: str :param destination_address_prefix: The destination address prefix. :type destination_address_prefix: str :param source_address_prefixes: The source address prefixes. Expected values include CIDR IP ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and the asterisk (*). :type source_address_prefixes: list[str] :param destination_address_prefixes: The destination address prefixes. Expected values include CIDR IP ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and the asterisk (*). :type destination_address_prefixes: list[str] :param expanded_source_address_prefix: The expanded source address prefix. :type expanded_source_address_prefix: list[str] :param expanded_destination_address_prefix: Expanded destination address prefix. :type expanded_destination_address_prefix: list[str] :param access: Whether network traffic is allowed or denied. Possible values include: 'Allow', 'Deny' :type access: str or ~azure.mgmt.network.v2019_06_01.models.SecurityRuleAccess :param priority: The priority of the rule. :type priority: int :param direction: The direction of the rule. Possible values include: 'Inbound', 'Outbound' :type direction: str or ~azure.mgmt.network.v2019_06_01.models.SecurityRuleDirection """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'protocol': {'key': 'protocol', 'type': 'str'}, 'source_port_range': {'key': 'sourcePortRange', 'type': 'str'}, 'destination_port_range': {'key': 'destinationPortRange', 'type': 'str'}, 'source_port_ranges': {'key': 'sourcePortRanges', 'type': '[str]'}, 'destination_port_ranges': {'key': 'destinationPortRanges', 'type': '[str]'}, 'source_address_prefix': {'key': 'sourceAddressPrefix', 'type': 'str'}, 'destination_address_prefix': {'key': 'destinationAddressPrefix', 'type': 'str'}, 'source_address_prefixes': {'key': 'sourceAddressPrefixes', 'type': '[str]'}, 'destination_address_prefixes': {'key': 'destinationAddressPrefixes', 'type': '[str]'}, 'expanded_source_address_prefix': {'key': 'expandedSourceAddressPrefix', 'type': '[str]'}, 'expanded_destination_address_prefix': {'key': 'expandedDestinationAddressPrefix', 'type': '[str]'}, 'access': {'key': 'access', 'type': 'str'}, 'priority': {'key': 'priority', 'type': 'int'}, 'direction': {'key': 'direction', 'type': 'str'}, } def __init__(self, **kwargs): super(EffectiveNetworkSecurityRule, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.protocol = kwargs.get('protocol', None) self.source_port_range = kwargs.get('source_port_range', None) self.destination_port_range = kwargs.get('destination_port_range', None) self.source_port_ranges = kwargs.get('source_port_ranges', None) self.destination_port_ranges = kwargs.get('destination_port_ranges', None) self.source_address_prefix = kwargs.get('source_address_prefix', None) self.destination_address_prefix = kwargs.get('destination_address_prefix', None) self.source_address_prefixes = kwargs.get('source_address_prefixes', None) self.destination_address_prefixes = kwargs.get('destination_address_prefixes', None) self.expanded_source_address_prefix = kwargs.get('expanded_source_address_prefix', None) self.expanded_destination_address_prefix = kwargs.get('expanded_destination_address_prefix', None) self.access = kwargs.get('access', None) self.priority = kwargs.get('priority', None) self.direction = kwargs.get('direction', None) class EffectiveRoute(Model): """Effective Route. :param name: The name of the user defined route. This is optional. :type name: str :param disable_bgp_route_propagation: If true, on-premises routes are not propagated to the network interfaces in the subnet. :type disable_bgp_route_propagation: bool :param source: Who created the route. Possible values include: 'Unknown', 'User', 'VirtualNetworkGateway', 'Default' :type source: str or ~azure.mgmt.network.v2019_06_01.models.EffectiveRouteSource :param state: The value of effective route. Possible values include: 'Active', 'Invalid' :type state: str or ~azure.mgmt.network.v2019_06_01.models.EffectiveRouteState :param address_prefix: The address prefixes of the effective routes in CIDR notation. :type address_prefix: list[str] :param next_hop_ip_address: The IP address of the next hop of the effective route. :type next_hop_ip_address: list[str] :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values include: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', 'None' :type next_hop_type: str or ~azure.mgmt.network.v2019_06_01.models.RouteNextHopType """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'disable_bgp_route_propagation': {'key': 'disableBgpRoutePropagation', 'type': 'bool'}, 'source': {'key': 'source', 'type': 'str'}, 'state': {'key': 'state', 'type': 'str'}, 'address_prefix': {'key': 'addressPrefix', 'type': '[str]'}, 'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': '[str]'}, 'next_hop_type': {'key': 'nextHopType', 'type': 'str'}, } def __init__(self, **kwargs): super(EffectiveRoute, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.disable_bgp_route_propagation = kwargs.get('disable_bgp_route_propagation', None) self.source = kwargs.get('source', None) self.state = kwargs.get('state', None) self.address_prefix = kwargs.get('address_prefix', None) self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None) self.next_hop_type = kwargs.get('next_hop_type', None) class EffectiveRouteListResult(Model): """Response for list effective route API service call. Variables are only populated by the server, and will be ignored when sending a request. :param value: A list of effective routes. :type value: list[~azure.mgmt.network.v2019_06_01.models.EffectiveRoute] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _validation = { 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[EffectiveRoute]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(self, **kwargs): super(EffectiveRouteListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = None class EndpointServiceResult(SubResource): """Endpoint service. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Name of the endpoint service. :vartype name: str :ivar type: Type of the endpoint service. :vartype type: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(EndpointServiceResult, self).__init__(**kwargs) self.name = None self.type = None class Error(Model): """Common error representation. :param code: Error code. :type code: str :param message: Error message. :type message: str :param target: Error target. :type target: str :param details: Error details. :type details: list[~azure.mgmt.network.v2019_06_01.models.ErrorDetails] :param inner_error: Inner error message. :type inner_error: str """ _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[ErrorDetails]'}, 'inner_error': {'key': 'innerError', 'type': 'str'}, } def __init__(self, **kwargs): super(Error, self).__init__(**kwargs) self.code = kwargs.get('code', None) self.message = kwargs.get('message', None) self.target = kwargs.get('target', None) self.details = kwargs.get('details', None) self.inner_error = kwargs.get('inner_error', None) class ErrorException(HttpOperationError): """Server responsed with exception of type: 'Error'. :param deserialize: A deserializer :param response: Server response to be deserialized. """ def __init__(self, deserialize, response, *args): super(ErrorException, self).__init__(deserialize, response, 'Error', *args) class ErrorDetails(Model): """Common error details representation. :param code: Error code. :type code: str :param target: Error target. :type target: str :param message: Error message. :type message: str """ _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, } def __init__(self, **kwargs): super(ErrorDetails, self).__init__(**kwargs) self.code = kwargs.get('code', None) self.target = kwargs.get('target', None) self.message = kwargs.get('message', None) class ErrorResponse(Model): """The error object. :param error: Error. The error details object. :type error: ~azure.mgmt.network.v2019_06_01.models.ErrorDetails """ _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorDetails'}, } def __init__(self, **kwargs): super(ErrorResponse, self).__init__(**kwargs) self.error = kwargs.get('error', None) class ErrorResponseException(HttpOperationError): """Server responsed with exception of type: 'ErrorResponse'. :param deserialize: A deserializer :param response: Server response to be deserialized. """ def __init__(self, deserialize, response, *args): super(ErrorResponseException, self).__init__(deserialize, response, 'ErrorResponse', *args) class EvaluatedNetworkSecurityGroup(Model): """Results of network security group evaluation. Variables are only populated by the server, and will be ignored when sending a request. :param network_security_group_id: Network security group ID. :type network_security_group_id: str :param applied_to: Resource ID of nic or subnet to which network security group is applied. :type applied_to: str :param matched_rule: Matched network security rule. :type matched_rule: ~azure.mgmt.network.v2019_06_01.models.MatchedRule :ivar rules_evaluation_result: List of network security rules evaluation results. :vartype rules_evaluation_result: list[~azure.mgmt.network.v2019_06_01.models.NetworkSecurityRulesEvaluationResult] """ _validation = { 'rules_evaluation_result': {'readonly': True}, } _attribute_map = { 'network_security_group_id': {'key': 'networkSecurityGroupId', 'type': 'str'}, 'applied_to': {'key': 'appliedTo', 'type': 'str'}, 'matched_rule': {'key': 'matchedRule', 'type': 'MatchedRule'}, 'rules_evaluation_result': {'key': 'rulesEvaluationResult', 'type': '[NetworkSecurityRulesEvaluationResult]'}, } def __init__(self, **kwargs): super(EvaluatedNetworkSecurityGroup, self).__init__(**kwargs) self.network_security_group_id = kwargs.get('network_security_group_id', None) self.applied_to = kwargs.get('applied_to', None) self.matched_rule = kwargs.get('matched_rule', None) self.rules_evaluation_result = None class ExpressRouteCircuit(Resource): """ExpressRouteCircuit resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param sku: The SKU. :type sku: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitSku :param allow_classic_operations: Allow classic operations. :type allow_classic_operations: bool :param circuit_provisioning_state: The CircuitProvisioningState state of the resource. :type circuit_provisioning_state: str :param service_provider_provisioning_state: The ServiceProviderProvisioningState state of the resource. Possible values include: 'NotProvisioned', 'Provisioning', 'Provisioned', 'Deprovisioning' :type service_provider_provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ServiceProviderProvisioningState :param authorizations: The list of authorizations. :type authorizations: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitAuthorization] :param peerings: The list of peerings. :type peerings: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeering] :param service_key: The ServiceKey. :type service_key: str :param service_provider_notes: The ServiceProviderNotes. :type service_provider_notes: str :param service_provider_properties: The ServiceProviderProperties. :type service_provider_properties: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitServiceProviderProperties :param express_route_port: The reference to the ExpressRoutePort resource when the circuit is provisioned on an ExpressRoutePort resource. :type express_route_port: ~azure.mgmt.network.v2019_06_01.models.SubResource :param bandwidth_in_gbps: The bandwidth of the circuit when the circuit is provisioned on an ExpressRoutePort resource. :type bandwidth_in_gbps: float :ivar stag: The identifier of the circuit traffic. Outer tag for QinQ encapsulation. :vartype stag: int :param provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param gateway_manager_etag: The GatewayManager Etag. :type gateway_manager_etag: str :param global_reach_enabled: Flag denoting Global reach status. :type global_reach_enabled: bool :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'stag': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'sku': {'key': 'sku', 'type': 'ExpressRouteCircuitSku'}, 'allow_classic_operations': {'key': 'properties.allowClassicOperations', 'type': 'bool'}, 'circuit_provisioning_state': {'key': 'properties.circuitProvisioningState', 'type': 'str'}, 'service_provider_provisioning_state': {'key': 'properties.serviceProviderProvisioningState', 'type': 'str'}, 'authorizations': {'key': 'properties.authorizations', 'type': '[ExpressRouteCircuitAuthorization]'}, 'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'}, 'service_key': {'key': 'properties.serviceKey', 'type': 'str'}, 'service_provider_notes': {'key': 'properties.serviceProviderNotes', 'type': 'str'}, 'service_provider_properties': {'key': 'properties.serviceProviderProperties', 'type': 'ExpressRouteCircuitServiceProviderProperties'}, 'express_route_port': {'key': 'properties.expressRoutePort', 'type': 'SubResource'}, 'bandwidth_in_gbps': {'key': 'properties.bandwidthInGbps', 'type': 'float'}, 'stag': {'key': 'properties.stag', 'type': 'int'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'gateway_manager_etag': {'key': 'properties.gatewayManagerEtag', 'type': 'str'}, 'global_reach_enabled': {'key': 'properties.globalReachEnabled', 'type': 'bool'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuit, self).__init__(**kwargs) self.sku = kwargs.get('sku', None) self.allow_classic_operations = kwargs.get('allow_classic_operations', None) self.circuit_provisioning_state = kwargs.get('circuit_provisioning_state', None) self.service_provider_provisioning_state = kwargs.get('service_provider_provisioning_state', None) self.authorizations = kwargs.get('authorizations', None) self.peerings = kwargs.get('peerings', None) self.service_key = kwargs.get('service_key', None) self.service_provider_notes = kwargs.get('service_provider_notes', None) self.service_provider_properties = kwargs.get('service_provider_properties', None) self.express_route_port = kwargs.get('express_route_port', None) self.bandwidth_in_gbps = kwargs.get('bandwidth_in_gbps', None) self.stag = None self.provisioning_state = kwargs.get('provisioning_state', None) self.gateway_manager_etag = kwargs.get('gateway_manager_etag', None) self.global_reach_enabled = kwargs.get('global_reach_enabled', None) self.etag = None class ExpressRouteCircuitArpTable(Model): """The ARP table associated with the ExpressRouteCircuit. :param age: Entry age in minutes. :type age: int :param interface: Interface address. :type interface: str :param ip_address: The IP address. :type ip_address: str :param mac_address: The MAC address. :type mac_address: str """ _attribute_map = { 'age': {'key': 'age', 'type': 'int'}, 'interface': {'key': 'interface', 'type': 'str'}, 'ip_address': {'key': 'ipAddress', 'type': 'str'}, 'mac_address': {'key': 'macAddress', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitArpTable, self).__init__(**kwargs) self.age = kwargs.get('age', None) self.interface = kwargs.get('interface', None) self.ip_address = kwargs.get('ip_address', None) self.mac_address = kwargs.get('mac_address', None) class ExpressRouteCircuitAuthorization(SubResource): """Authorization in an ExpressRouteCircuit resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param authorization_key: The authorization key. :type authorization_key: str :param authorization_use_status: The authorization use status. Possible values include: 'Available', 'InUse' :type authorization_use_status: str or ~azure.mgmt.network.v2019_06_01.models.AuthorizationUseStatus :param provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Type of the resource. :vartype type: str """ _validation = { 'etag': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'}, 'authorization_use_status': {'key': 'properties.authorizationUseStatus', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitAuthorization, self).__init__(**kwargs) self.authorization_key = kwargs.get('authorization_key', None) self.authorization_use_status = kwargs.get('authorization_use_status', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = None self.type = None class ExpressRouteCircuitConnection(SubResource): """Express Route Circuit Connection in an ExpressRouteCircuitPeering resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param express_route_circuit_peering: Reference to Express Route Circuit Private Peering Resource of the circuit initiating connection. :type express_route_circuit_peering: ~azure.mgmt.network.v2019_06_01.models.SubResource :param peer_express_route_circuit_peering: Reference to Express Route Circuit Private Peering Resource of the peered circuit. :type peer_express_route_circuit_peering: ~azure.mgmt.network.v2019_06_01.models.SubResource :param address_prefix: /29 IP address space to carve out Customer addresses for tunnels. :type address_prefix: str :param authorization_key: The authorization key. :type authorization_key: str :param circuit_connection_status: Express Route Circuit connection state. Possible values include: 'Connected', 'Connecting', 'Disconnected' :type circuit_connection_status: str or ~azure.mgmt.network.v2019_06_01.models.CircuitConnectionStatus :ivar provisioning_state: Provisioning state of the circuit connection resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Type of the resource. :vartype type: str """ _validation = { 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'express_route_circuit_peering': {'key': 'properties.expressRouteCircuitPeering', 'type': 'SubResource'}, 'peer_express_route_circuit_peering': {'key': 'properties.peerExpressRouteCircuitPeering', 'type': 'SubResource'}, 'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'}, 'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'}, 'circuit_connection_status': {'key': 'properties.circuitConnectionStatus', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitConnection, self).__init__(**kwargs) self.express_route_circuit_peering = kwargs.get('express_route_circuit_peering', None) self.peer_express_route_circuit_peering = kwargs.get('peer_express_route_circuit_peering', None) self.address_prefix = kwargs.get('address_prefix', None) self.authorization_key = kwargs.get('authorization_key', None) self.circuit_connection_status = kwargs.get('circuit_connection_status', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = None self.type = None class ExpressRouteCircuitPeering(SubResource): """Peering in an ExpressRouteCircuit resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param peering_type: The peering type. Possible values include: 'AzurePublicPeering', 'AzurePrivatePeering', 'MicrosoftPeering' :type peering_type: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRoutePeeringType :param state: The peering state. Possible values include: 'Disabled', 'Enabled' :type state: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRoutePeeringState :param azure_asn: The Azure ASN. :type azure_asn: int :param peer_asn: The peer ASN. :type peer_asn: long :param primary_peer_address_prefix: The primary address prefix. :type primary_peer_address_prefix: str :param secondary_peer_address_prefix: The secondary address prefix. :type secondary_peer_address_prefix: str :param primary_azure_port: The primary port. :type primary_azure_port: str :param secondary_azure_port: The secondary port. :type secondary_azure_port: str :param shared_key: The shared key. :type shared_key: str :param vlan_id: The VLAN ID. :type vlan_id: int :param microsoft_peering_config: The Microsoft peering configuration. :type microsoft_peering_config: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeeringConfig :param stats: Gets peering stats. :type stats: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitStats :param provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param gateway_manager_etag: The GatewayManager Etag. :type gateway_manager_etag: str :param last_modified_by: Gets whether the provider or the customer last modified the peering. :type last_modified_by: str :param route_filter: The reference of the RouteFilter resource. :type route_filter: ~azure.mgmt.network.v2019_06_01.models.SubResource :param ipv6_peering_config: The IPv6 peering configuration. :type ipv6_peering_config: ~azure.mgmt.network.v2019_06_01.models.Ipv6ExpressRouteCircuitPeeringConfig :param express_route_connection: The ExpressRoute connection. :type express_route_connection: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteConnectionId :param connections: The list of circuit connections associated with Azure Private Peering for this circuit. :type connections: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitConnection] :ivar peered_connections: The list of peered circuit connections associated with Azure Private Peering for this circuit. :vartype peered_connections: list[~azure.mgmt.network.v2019_06_01.models.PeerExpressRouteCircuitConnection] :param name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Type of the resource. :vartype type: str """ _validation = { 'peer_asn': {'maximum': 4294967295, 'minimum': 1}, 'peered_connections': {'readonly': True}, 'etag': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'peering_type': {'key': 'properties.peeringType', 'type': 'str'}, 'state': {'key': 'properties.state', 'type': 'str'}, 'azure_asn': {'key': 'properties.azureASN', 'type': 'int'}, 'peer_asn': {'key': 'properties.peerASN', 'type': 'long'}, 'primary_peer_address_prefix': {'key': 'properties.primaryPeerAddressPrefix', 'type': 'str'}, 'secondary_peer_address_prefix': {'key': 'properties.secondaryPeerAddressPrefix', 'type': 'str'}, 'primary_azure_port': {'key': 'properties.primaryAzurePort', 'type': 'str'}, 'secondary_azure_port': {'key': 'properties.secondaryAzurePort', 'type': 'str'}, 'shared_key': {'key': 'properties.sharedKey', 'type': 'str'}, 'vlan_id': {'key': 'properties.vlanId', 'type': 'int'}, 'microsoft_peering_config': {'key': 'properties.microsoftPeeringConfig', 'type': 'ExpressRouteCircuitPeeringConfig'}, 'stats': {'key': 'properties.stats', 'type': 'ExpressRouteCircuitStats'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'gateway_manager_etag': {'key': 'properties.gatewayManagerEtag', 'type': 'str'}, 'last_modified_by': {'key': 'properties.lastModifiedBy', 'type': 'str'}, 'route_filter': {'key': 'properties.routeFilter', 'type': 'SubResource'}, 'ipv6_peering_config': {'key': 'properties.ipv6PeeringConfig', 'type': 'Ipv6ExpressRouteCircuitPeeringConfig'}, 'express_route_connection': {'key': 'properties.expressRouteConnection', 'type': 'ExpressRouteConnectionId'}, 'connections': {'key': 'properties.connections', 'type': '[ExpressRouteCircuitConnection]'}, 'peered_connections': {'key': 'properties.peeredConnections', 'type': '[PeerExpressRouteCircuitConnection]'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitPeering, self).__init__(**kwargs) self.peering_type = kwargs.get('peering_type', None) self.state = kwargs.get('state', None) self.azure_asn = kwargs.get('azure_asn', None) self.peer_asn = kwargs.get('peer_asn', None) self.primary_peer_address_prefix = kwargs.get('primary_peer_address_prefix', None) self.secondary_peer_address_prefix = kwargs.get('secondary_peer_address_prefix', None) self.primary_azure_port = kwargs.get('primary_azure_port', None) self.secondary_azure_port = kwargs.get('secondary_azure_port', None) self.shared_key = kwargs.get('shared_key', None) self.vlan_id = kwargs.get('vlan_id', None) self.microsoft_peering_config = kwargs.get('microsoft_peering_config', None) self.stats = kwargs.get('stats', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.gateway_manager_etag = kwargs.get('gateway_manager_etag', None) self.last_modified_by = kwargs.get('last_modified_by', None) self.route_filter = kwargs.get('route_filter', None) self.ipv6_peering_config = kwargs.get('ipv6_peering_config', None) self.express_route_connection = kwargs.get('express_route_connection', None) self.connections = kwargs.get('connections', None) self.peered_connections = None self.name = kwargs.get('name', None) self.etag = None self.type = None class ExpressRouteCircuitPeeringConfig(Model): """Specifies the peering configuration. :param advertised_public_prefixes: The reference of AdvertisedPublicPrefixes. :type advertised_public_prefixes: list[str] :param advertised_communities: The communities of bgp peering. Specified for microsoft peering. :type advertised_communities: list[str] :param advertised_public_prefixes_state: The advertised public prefix state of the Peering resource. Possible values include: 'NotConfigured', 'Configuring', 'Configured', 'ValidationNeeded' :type advertised_public_prefixes_state: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeeringAdvertisedPublicPrefixState :param legacy_mode: The legacy mode of the peering. :type legacy_mode: int :param customer_asn: The CustomerASN of the peering. :type customer_asn: int :param routing_registry_name: The RoutingRegistryName of the configuration. :type routing_registry_name: str """ _attribute_map = { 'advertised_public_prefixes': {'key': 'advertisedPublicPrefixes', 'type': '[str]'}, 'advertised_communities': {'key': 'advertisedCommunities', 'type': '[str]'}, 'advertised_public_prefixes_state': {'key': 'advertisedPublicPrefixesState', 'type': 'str'}, 'legacy_mode': {'key': 'legacyMode', 'type': 'int'}, 'customer_asn': {'key': 'customerASN', 'type': 'int'}, 'routing_registry_name': {'key': 'routingRegistryName', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitPeeringConfig, self).__init__(**kwargs) self.advertised_public_prefixes = kwargs.get('advertised_public_prefixes', None) self.advertised_communities = kwargs.get('advertised_communities', None) self.advertised_public_prefixes_state = kwargs.get('advertised_public_prefixes_state', None) self.legacy_mode = kwargs.get('legacy_mode', None) self.customer_asn = kwargs.get('customer_asn', None) self.routing_registry_name = kwargs.get('routing_registry_name', None) class ExpressRouteCircuitPeeringId(Model): """ExpressRoute circuit peering identifier. :param id: The ID of the ExpressRoute circuit peering. :type id: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitPeeringId, self).__init__(**kwargs) self.id = kwargs.get('id', None) class ExpressRouteCircuitReference(Model): """Reference to an express route circuit. :param id: Corresponding Express Route Circuit Id. :type id: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitReference, self).__init__(**kwargs) self.id = kwargs.get('id', None) class ExpressRouteCircuitRoutesTable(Model): """The routes table associated with the ExpressRouteCircuit. :param network: IP address of a network entity. :type network: str :param next_hop: NextHop address. :type next_hop: str :param loc_prf: Local preference value as set with the set local-preference route-map configuration command. :type loc_prf: str :param weight: Route Weight. :type weight: int :param path: Autonomous system paths to the destination network. :type path: str """ _attribute_map = { 'network': {'key': 'network', 'type': 'str'}, 'next_hop': {'key': 'nextHop', 'type': 'str'}, 'loc_prf': {'key': 'locPrf', 'type': 'str'}, 'weight': {'key': 'weight', 'type': 'int'}, 'path': {'key': 'path', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitRoutesTable, self).__init__(**kwargs) self.network = kwargs.get('network', None) self.next_hop = kwargs.get('next_hop', None) self.loc_prf = kwargs.get('loc_prf', None) self.weight = kwargs.get('weight', None) self.path = kwargs.get('path', None) class ExpressRouteCircuitRoutesTableSummary(Model): """The routes table associated with the ExpressRouteCircuit. :param neighbor: IP address of the neighbor. :type neighbor: str :param v: BGP version number spoken to the neighbor. :type v: int :param as_property: Autonomous system number. :type as_property: int :param up_down: The length of time that the BGP session has been in the Established state, or the current status if not in the Established state. :type up_down: str :param state_pfx_rcd: Current state of the BGP session, and the number of prefixes that have been received from a neighbor or peer group. :type state_pfx_rcd: str """ _attribute_map = { 'neighbor': {'key': 'neighbor', 'type': 'str'}, 'v': {'key': 'v', 'type': 'int'}, 'as_property': {'key': 'as', 'type': 'int'}, 'up_down': {'key': 'upDown', 'type': 'str'}, 'state_pfx_rcd': {'key': 'statePfxRcd', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitRoutesTableSummary, self).__init__(**kwargs) self.neighbor = kwargs.get('neighbor', None) self.v = kwargs.get('v', None) self.as_property = kwargs.get('as_property', None) self.up_down = kwargs.get('up_down', None) self.state_pfx_rcd = kwargs.get('state_pfx_rcd', None) class ExpressRouteCircuitsArpTableListResult(Model): """Response for ListArpTable associated with the Express Route Circuits API. :param value: Gets list of the ARP table. :type value: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitArpTable] :param next_link: The URL to get the next set of results. :type next_link: str """ _attribute_map = { 'value': {'key': 'value', 'type': '[ExpressRouteCircuitArpTable]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitsArpTableListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = kwargs.get('next_link', None) class ExpressRouteCircuitServiceProviderProperties(Model): """Contains ServiceProviderProperties in an ExpressRouteCircuit. :param service_provider_name: The serviceProviderName. :type service_provider_name: str :param peering_location: The peering location. :type peering_location: str :param bandwidth_in_mbps: The BandwidthInMbps. :type bandwidth_in_mbps: int """ _attribute_map = { 'service_provider_name': {'key': 'serviceProviderName', 'type': 'str'}, 'peering_location': {'key': 'peeringLocation', 'type': 'str'}, 'bandwidth_in_mbps': {'key': 'bandwidthInMbps', 'type': 'int'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitServiceProviderProperties, self).__init__(**kwargs) self.service_provider_name = kwargs.get('service_provider_name', None) self.peering_location = kwargs.get('peering_location', None) self.bandwidth_in_mbps = kwargs.get('bandwidth_in_mbps', None) class ExpressRouteCircuitSku(Model): """Contains SKU in an ExpressRouteCircuit. :param name: The name of the SKU. :type name: str :param tier: The tier of the SKU. Possible values include: 'Standard', 'Premium', 'Basic', 'Local' :type tier: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitSkuTier :param family: The family of the SKU. Possible values include: 'UnlimitedData', 'MeteredData' :type family: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitSkuFamily """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, 'family': {'key': 'family', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitSku, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.tier = kwargs.get('tier', None) self.family = kwargs.get('family', None) class ExpressRouteCircuitsRoutesTableListResult(Model): """Response for ListRoutesTable associated with the Express Route Circuits API. :param value: The list of routes table. :type value: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitRoutesTable] :param next_link: The URL to get the next set of results. :type next_link: str """ _attribute_map = { 'value': {'key': 'value', 'type': '[ExpressRouteCircuitRoutesTable]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitsRoutesTableListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = kwargs.get('next_link', None) class ExpressRouteCircuitsRoutesTableSummaryListResult(Model): """Response for ListRoutesTable associated with the Express Route Circuits API. :param value: A list of the routes table. :type value: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitRoutesTableSummary] :param next_link: The URL to get the next set of results. :type next_link: str """ _attribute_map = { 'value': {'key': 'value', 'type': '[ExpressRouteCircuitRoutesTableSummary]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitsRoutesTableSummaryListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = kwargs.get('next_link', None) class ExpressRouteCircuitStats(Model): """Contains stats associated with the peering. :param primarybytes_in: Gets BytesIn of the peering. :type primarybytes_in: long :param primarybytes_out: Gets BytesOut of the peering. :type primarybytes_out: long :param secondarybytes_in: Gets BytesIn of the peering. :type secondarybytes_in: long :param secondarybytes_out: Gets BytesOut of the peering. :type secondarybytes_out: long """ _attribute_map = { 'primarybytes_in': {'key': 'primarybytesIn', 'type': 'long'}, 'primarybytes_out': {'key': 'primarybytesOut', 'type': 'long'}, 'secondarybytes_in': {'key': 'secondarybytesIn', 'type': 'long'}, 'secondarybytes_out': {'key': 'secondarybytesOut', 'type': 'long'}, } def __init__(self, **kwargs): super(ExpressRouteCircuitStats, self).__init__(**kwargs) self.primarybytes_in = kwargs.get('primarybytes_in', None) self.primarybytes_out = kwargs.get('primarybytes_out', None) self.secondarybytes_in = kwargs.get('secondarybytes_in', None) self.secondarybytes_out = kwargs.get('secondarybytes_out', None) class ExpressRouteConnection(SubResource): """ExpressRouteConnection resource. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param express_route_circuit_peering: Required. The ExpressRoute circuit peering. :type express_route_circuit_peering: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeeringId :param authorization_key: Authorization key to establish the connection. :type authorization_key: str :param routing_weight: The routing weight associated to the connection. :type routing_weight: int :param name: Required. The name of the resource. :type name: str """ _validation = { 'express_route_circuit_peering': {'required': True}, 'name': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'express_route_circuit_peering': {'key': 'properties.expressRouteCircuitPeering', 'type': 'ExpressRouteCircuitPeeringId'}, 'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'}, 'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'}, 'name': {'key': 'name', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteConnection, self).__init__(**kwargs) self.provisioning_state = kwargs.get('provisioning_state', None) self.express_route_circuit_peering = kwargs.get('express_route_circuit_peering', None) self.authorization_key = kwargs.get('authorization_key', None) self.routing_weight = kwargs.get('routing_weight', None) self.name = kwargs.get('name', None) class ExpressRouteConnectionId(Model): """The ID of the ExpressRouteConnection. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The ID of the ExpressRouteConnection. :vartype id: str """ _validation = { 'id': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteConnectionId, self).__init__(**kwargs) self.id = None class ExpressRouteConnectionList(Model): """ExpressRouteConnection list. :param value: The list of ExpressRoute connections. :type value: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteConnection] """ _attribute_map = { 'value': {'key': 'value', 'type': '[ExpressRouteConnection]'}, } def __init__(self, **kwargs): super(ExpressRouteConnectionList, self).__init__(**kwargs) self.value = kwargs.get('value', None) class ExpressRouteCrossConnection(Resource): """ExpressRouteCrossConnection resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :ivar primary_azure_port: The name of the primary port. :vartype primary_azure_port: str :ivar secondary_azure_port: The name of the secondary port. :vartype secondary_azure_port: str :ivar s_tag: The identifier of the circuit traffic. :vartype s_tag: int :param peering_location: The peering location of the ExpressRoute circuit. :type peering_location: str :param bandwidth_in_mbps: The circuit bandwidth In Mbps. :type bandwidth_in_mbps: int :param express_route_circuit: The ExpressRouteCircuit. :type express_route_circuit: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitReference :param service_provider_provisioning_state: The provisioning state of the circuit in the connectivity provider system. Possible values include: 'NotProvisioned', 'Provisioning', 'Provisioned', 'Deprovisioning' :type service_provider_provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ServiceProviderProvisioningState :param service_provider_notes: Additional read only notes set by the connectivity provider. :type service_provider_notes: str :ivar provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param peerings: The list of peerings. :type peerings: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCrossConnectionPeering] :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'primary_azure_port': {'readonly': True}, 'secondary_azure_port': {'readonly': True}, 's_tag': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'primary_azure_port': {'key': 'properties.primaryAzurePort', 'type': 'str'}, 'secondary_azure_port': {'key': 'properties.secondaryAzurePort', 'type': 'str'}, 's_tag': {'key': 'properties.sTag', 'type': 'int'}, 'peering_location': {'key': 'properties.peeringLocation', 'type': 'str'}, 'bandwidth_in_mbps': {'key': 'properties.bandwidthInMbps', 'type': 'int'}, 'express_route_circuit': {'key': 'properties.expressRouteCircuit', 'type': 'ExpressRouteCircuitReference'}, 'service_provider_provisioning_state': {'key': 'properties.serviceProviderProvisioningState', 'type': 'str'}, 'service_provider_notes': {'key': 'properties.serviceProviderNotes', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCrossConnectionPeering]'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCrossConnection, self).__init__(**kwargs) self.primary_azure_port = None self.secondary_azure_port = None self.s_tag = None self.peering_location = kwargs.get('peering_location', None) self.bandwidth_in_mbps = kwargs.get('bandwidth_in_mbps', None) self.express_route_circuit = kwargs.get('express_route_circuit', None) self.service_provider_provisioning_state = kwargs.get('service_provider_provisioning_state', None) self.service_provider_notes = kwargs.get('service_provider_notes', None) self.provisioning_state = None self.peerings = kwargs.get('peerings', None) self.etag = None class ExpressRouteCrossConnectionPeering(SubResource): """Peering in an ExpressRoute Cross Connection resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param peering_type: The peering type. Possible values include: 'AzurePublicPeering', 'AzurePrivatePeering', 'MicrosoftPeering' :type peering_type: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRoutePeeringType :param state: The peering state. Possible values include: 'Disabled', 'Enabled' :type state: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRoutePeeringState :ivar azure_asn: The Azure ASN. :vartype azure_asn: int :param peer_asn: The peer ASN. :type peer_asn: long :param primary_peer_address_prefix: The primary address prefix. :type primary_peer_address_prefix: str :param secondary_peer_address_prefix: The secondary address prefix. :type secondary_peer_address_prefix: str :ivar primary_azure_port: The primary port. :vartype primary_azure_port: str :ivar secondary_azure_port: The secondary port. :vartype secondary_azure_port: str :param shared_key: The shared key. :type shared_key: str :param vlan_id: The VLAN ID. :type vlan_id: int :param microsoft_peering_config: The Microsoft peering configuration. :type microsoft_peering_config: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeeringConfig :ivar provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param gateway_manager_etag: The GatewayManager Etag. :type gateway_manager_etag: str :param last_modified_by: Gets whether the provider or the customer last modified the peering. :type last_modified_by: str :param ipv6_peering_config: The IPv6 peering configuration. :type ipv6_peering_config: ~azure.mgmt.network.v2019_06_01.models.Ipv6ExpressRouteCircuitPeeringConfig :param name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'azure_asn': {'readonly': True}, 'peer_asn': {'maximum': 4294967295, 'minimum': 1}, 'primary_azure_port': {'readonly': True}, 'secondary_azure_port': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'peering_type': {'key': 'properties.peeringType', 'type': 'str'}, 'state': {'key': 'properties.state', 'type': 'str'}, 'azure_asn': {'key': 'properties.azureASN', 'type': 'int'}, 'peer_asn': {'key': 'properties.peerASN', 'type': 'long'}, 'primary_peer_address_prefix': {'key': 'properties.primaryPeerAddressPrefix', 'type': 'str'}, 'secondary_peer_address_prefix': {'key': 'properties.secondaryPeerAddressPrefix', 'type': 'str'}, 'primary_azure_port': {'key': 'properties.primaryAzurePort', 'type': 'str'}, 'secondary_azure_port': {'key': 'properties.secondaryAzurePort', 'type': 'str'}, 'shared_key': {'key': 'properties.sharedKey', 'type': 'str'}, 'vlan_id': {'key': 'properties.vlanId', 'type': 'int'}, 'microsoft_peering_config': {'key': 'properties.microsoftPeeringConfig', 'type': 'ExpressRouteCircuitPeeringConfig'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'gateway_manager_etag': {'key': 'properties.gatewayManagerEtag', 'type': 'str'}, 'last_modified_by': {'key': 'properties.lastModifiedBy', 'type': 'str'}, 'ipv6_peering_config': {'key': 'properties.ipv6PeeringConfig', 'type': 'Ipv6ExpressRouteCircuitPeeringConfig'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCrossConnectionPeering, self).__init__(**kwargs) self.peering_type = kwargs.get('peering_type', None) self.state = kwargs.get('state', None) self.azure_asn = None self.peer_asn = kwargs.get('peer_asn', None) self.primary_peer_address_prefix = kwargs.get('primary_peer_address_prefix', None) self.secondary_peer_address_prefix = kwargs.get('secondary_peer_address_prefix', None) self.primary_azure_port = None self.secondary_azure_port = None self.shared_key = kwargs.get('shared_key', None) self.vlan_id = kwargs.get('vlan_id', None) self.microsoft_peering_config = kwargs.get('microsoft_peering_config', None) self.provisioning_state = None self.gateway_manager_etag = kwargs.get('gateway_manager_etag', None) self.last_modified_by = kwargs.get('last_modified_by', None) self.ipv6_peering_config = kwargs.get('ipv6_peering_config', None) self.name = kwargs.get('name', None) self.etag = None class ExpressRouteCrossConnectionRoutesTableSummary(Model): """The routes table associated with the ExpressRouteCircuit. :param neighbor: IP address of Neighbor router. :type neighbor: str :param asn: Autonomous system number. :type asn: int :param up_down: The length of time that the BGP session has been in the Established state, or the current status if not in the Established state. :type up_down: str :param state_or_prefixes_received: Current state of the BGP session, and the number of prefixes that have been received from a neighbor or peer group. :type state_or_prefixes_received: str """ _attribute_map = { 'neighbor': {'key': 'neighbor', 'type': 'str'}, 'asn': {'key': 'asn', 'type': 'int'}, 'up_down': {'key': 'upDown', 'type': 'str'}, 'state_or_prefixes_received': {'key': 'stateOrPrefixesReceived', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCrossConnectionRoutesTableSummary, self).__init__(**kwargs) self.neighbor = kwargs.get('neighbor', None) self.asn = kwargs.get('asn', None) self.up_down = kwargs.get('up_down', None) self.state_or_prefixes_received = kwargs.get('state_or_prefixes_received', None) class ExpressRouteCrossConnectionsRoutesTableSummaryListResult(Model): """Response for ListRoutesTable associated with the Express Route Cross Connections. Variables are only populated by the server, and will be ignored when sending a request. :param value: A list of the routes table. :type value: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCrossConnectionRoutesTableSummary] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _validation = { 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[ExpressRouteCrossConnectionRoutesTableSummary]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteCrossConnectionsRoutesTableSummaryListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = None class ExpressRouteGateway(Resource): """ExpressRoute gateway resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param auto_scale_configuration: Configuration for auto scaling. :type auto_scale_configuration: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteGatewayPropertiesAutoScaleConfiguration :ivar express_route_connections: List of ExpressRoute connections to the ExpressRoute gateway. :vartype express_route_connections: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteConnection] :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param virtual_hub: Required. The Virtual Hub where the ExpressRoute gateway is or will be deployed. :type virtual_hub: ~azure.mgmt.network.v2019_06_01.models.VirtualHubId :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'express_route_connections': {'readonly': True}, 'virtual_hub': {'required': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'auto_scale_configuration': {'key': 'properties.autoScaleConfiguration', 'type': 'ExpressRouteGatewayPropertiesAutoScaleConfiguration'}, 'express_route_connections': {'key': 'properties.expressRouteConnections', 'type': '[ExpressRouteConnection]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'virtual_hub': {'key': 'properties.virtualHub', 'type': 'VirtualHubId'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteGateway, self).__init__(**kwargs) self.auto_scale_configuration = kwargs.get('auto_scale_configuration', None) self.express_route_connections = None self.provisioning_state = kwargs.get('provisioning_state', None) self.virtual_hub = kwargs.get('virtual_hub', None) self.etag = None class ExpressRouteGatewayList(Model): """List of ExpressRoute gateways. :param value: List of ExpressRoute gateways. :type value: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteGateway] """ _attribute_map = { 'value': {'key': 'value', 'type': '[ExpressRouteGateway]'}, } def __init__(self, **kwargs): super(ExpressRouteGatewayList, self).__init__(**kwargs) self.value = kwargs.get('value', None) class ExpressRouteGatewayPropertiesAutoScaleConfiguration(Model): """Configuration for auto scaling. :param bounds: Minimum and maximum number of scale units to deploy. :type bounds: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds """ _attribute_map = { 'bounds': {'key': 'bounds', 'type': 'ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds'}, } def __init__(self, **kwargs): super(ExpressRouteGatewayPropertiesAutoScaleConfiguration, self).__init__(**kwargs) self.bounds = kwargs.get('bounds', None) class ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds(Model): """Minimum and maximum number of scale units to deploy. :param min: Minimum number of scale units deployed for ExpressRoute gateway. :type min: int :param max: Maximum number of scale units deployed for ExpressRoute gateway. :type max: int """ _attribute_map = { 'min': {'key': 'min', 'type': 'int'}, 'max': {'key': 'max', 'type': 'int'}, } def __init__(self, **kwargs): super(ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds, self).__init__(**kwargs) self.min = kwargs.get('min', None) self.max = kwargs.get('max', None) class ExpressRouteLink(SubResource): """ExpressRouteLink. ExpressRouteLink child resource definition. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar router_name: Name of Azure router associated with physical port. :vartype router_name: str :ivar interface_name: Name of Azure router interface. :vartype interface_name: str :ivar patch_panel_id: Mapping between physical port to patch panel port. :vartype patch_panel_id: str :ivar rack_id: Mapping of physical patch panel to rack. :vartype rack_id: str :ivar connector_type: Physical fiber port type. Possible values include: 'LC', 'SC' :vartype connector_type: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRouteLinkConnectorType :param admin_state: Administrative state of the physical port. Possible values include: 'Enabled', 'Disabled' :type admin_state: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRouteLinkAdminState :ivar provisioning_state: The provisioning state of the ExpressRouteLink resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: Name of child port resource that is unique among child port resources of the parent. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'router_name': {'readonly': True}, 'interface_name': {'readonly': True}, 'patch_panel_id': {'readonly': True}, 'rack_id': {'readonly': True}, 'connector_type': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'router_name': {'key': 'properties.routerName', 'type': 'str'}, 'interface_name': {'key': 'properties.interfaceName', 'type': 'str'}, 'patch_panel_id': {'key': 'properties.patchPanelId', 'type': 'str'}, 'rack_id': {'key': 'properties.rackId', 'type': 'str'}, 'connector_type': {'key': 'properties.connectorType', 'type': 'str'}, 'admin_state': {'key': 'properties.adminState', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteLink, self).__init__(**kwargs) self.router_name = None self.interface_name = None self.patch_panel_id = None self.rack_id = None self.connector_type = None self.admin_state = kwargs.get('admin_state', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = None class ExpressRoutePort(Resource): """ExpressRoute Port. ExpressRoutePort resource definition. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param peering_location: The name of the peering location that the ExpressRoutePort is mapped to physically. :type peering_location: str :param bandwidth_in_gbps: Bandwidth of procured ports in Gbps. :type bandwidth_in_gbps: int :ivar provisioned_bandwidth_in_gbps: Aggregate Gbps of associated circuit bandwidths. :vartype provisioned_bandwidth_in_gbps: float :ivar mtu: Maximum transmission unit of the physical port pair(s). :vartype mtu: str :param encapsulation: Encapsulation method on physical ports. Possible values include: 'Dot1Q', 'QinQ' :type encapsulation: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRoutePortsEncapsulation :ivar ether_type: Ether type of the physical port. :vartype ether_type: str :ivar allocation_date: Date of the physical port allocation to be used in Letter of Authorization. :vartype allocation_date: str :param links: ExpressRouteLink Sub-Resources. The set of physical links of the ExpressRoutePort resource. :type links: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteLink] :ivar circuits: Reference the ExpressRoute circuit(s) that are provisioned on this ExpressRoutePort resource. :vartype circuits: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :ivar provisioning_state: The provisioning state of the ExpressRoutePort resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param resource_guid: The resource GUID property of the ExpressRoutePort resource. :type resource_guid: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'provisioned_bandwidth_in_gbps': {'readonly': True}, 'mtu': {'readonly': True}, 'ether_type': {'readonly': True}, 'allocation_date': {'readonly': True}, 'circuits': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'peering_location': {'key': 'properties.peeringLocation', 'type': 'str'}, 'bandwidth_in_gbps': {'key': 'properties.bandwidthInGbps', 'type': 'int'}, 'provisioned_bandwidth_in_gbps': {'key': 'properties.provisionedBandwidthInGbps', 'type': 'float'}, 'mtu': {'key': 'properties.mtu', 'type': 'str'}, 'encapsulation': {'key': 'properties.encapsulation', 'type': 'str'}, 'ether_type': {'key': 'properties.etherType', 'type': 'str'}, 'allocation_date': {'key': 'properties.allocationDate', 'type': 'str'}, 'links': {'key': 'properties.links', 'type': '[ExpressRouteLink]'}, 'circuits': {'key': 'properties.circuits', 'type': '[SubResource]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRoutePort, self).__init__(**kwargs) self.peering_location = kwargs.get('peering_location', None) self.bandwidth_in_gbps = kwargs.get('bandwidth_in_gbps', None) self.provisioned_bandwidth_in_gbps = None self.mtu = None self.encapsulation = kwargs.get('encapsulation', None) self.ether_type = None self.allocation_date = None self.links = kwargs.get('links', None) self.circuits = None self.provisioning_state = None self.resource_guid = kwargs.get('resource_guid', None) self.etag = None class ExpressRoutePortsLocation(Resource): """ExpressRoutePorts Peering Location. Definition of the ExpressRoutePorts peering location resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :ivar address: Address of peering location. :vartype address: str :ivar contact: Contact details of peering locations. :vartype contact: str :param available_bandwidths: The inventory of available ExpressRoutePort bandwidths. :type available_bandwidths: list[~azure.mgmt.network.v2019_06_01.models.ExpressRoutePortsLocationBandwidths] :ivar provisioning_state: The provisioning state of the ExpressRoutePortLocation resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'address': {'readonly': True}, 'contact': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'address': {'key': 'properties.address', 'type': 'str'}, 'contact': {'key': 'properties.contact', 'type': 'str'}, 'available_bandwidths': {'key': 'properties.availableBandwidths', 'type': '[ExpressRoutePortsLocationBandwidths]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRoutePortsLocation, self).__init__(**kwargs) self.address = None self.contact = None self.available_bandwidths = kwargs.get('available_bandwidths', None) self.provisioning_state = None class ExpressRoutePortsLocationBandwidths(Model): """ExpressRoutePorts Location Bandwidths. Real-time inventory of available ExpressRoute port bandwidths. Variables are only populated by the server, and will be ignored when sending a request. :ivar offer_name: Bandwidth descriptive name. :vartype offer_name: str :ivar value_in_gbps: Bandwidth value in Gbps. :vartype value_in_gbps: int """ _validation = { 'offer_name': {'readonly': True}, 'value_in_gbps': {'readonly': True}, } _attribute_map = { 'offer_name': {'key': 'offerName', 'type': 'str'}, 'value_in_gbps': {'key': 'valueInGbps', 'type': 'int'}, } def __init__(self, **kwargs): super(ExpressRoutePortsLocationBandwidths, self).__init__(**kwargs) self.offer_name = None self.value_in_gbps = None class ExpressRouteServiceProvider(Resource): """A ExpressRouteResourceProvider object. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param peering_locations: Get a list of peering locations. :type peering_locations: list[str] :param bandwidths_offered: Gets bandwidths offered. :type bandwidths_offered: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteServiceProviderBandwidthsOffered] :param provisioning_state: Gets the provisioning state of the resource. :type provisioning_state: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'peering_locations': {'key': 'properties.peeringLocations', 'type': '[str]'}, 'bandwidths_offered': {'key': 'properties.bandwidthsOffered', 'type': '[ExpressRouteServiceProviderBandwidthsOffered]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } def __init__(self, **kwargs): super(ExpressRouteServiceProvider, self).__init__(**kwargs) self.peering_locations = kwargs.get('peering_locations', None) self.bandwidths_offered = kwargs.get('bandwidths_offered', None) self.provisioning_state = kwargs.get('provisioning_state', None) class ExpressRouteServiceProviderBandwidthsOffered(Model): """Contains bandwidths offered in ExpressRouteServiceProvider resources. :param offer_name: The OfferName. :type offer_name: str :param value_in_mbps: The ValueInMbps. :type value_in_mbps: int """ _attribute_map = { 'offer_name': {'key': 'offerName', 'type': 'str'}, 'value_in_mbps': {'key': 'valueInMbps', 'type': 'int'}, } def __init__(self, **kwargs): super(ExpressRouteServiceProviderBandwidthsOffered, self).__init__(**kwargs) self.offer_name = kwargs.get('offer_name', None) self.value_in_mbps = kwargs.get('value_in_mbps', None) class FlowLogFormatParameters(Model): """Parameters that define the flow log format. :param type: The file type of flow log. Possible values include: 'JSON' :type type: str or ~azure.mgmt.network.v2019_06_01.models.FlowLogFormatType :param version: The version (revision) of the flow log. Default value: 0 . :type version: int """ _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'version': {'key': 'version', 'type': 'int'}, } def __init__(self, **kwargs): super(FlowLogFormatParameters, self).__init__(**kwargs) self.type = kwargs.get('type', None) self.version = kwargs.get('version', 0) class FlowLogInformation(Model): """Information on the configuration of flow log and traffic analytics (optional) . All required parameters must be populated in order to send to Azure. :param target_resource_id: Required. The ID of the resource to configure for flow log and traffic analytics (optional) . :type target_resource_id: str :param storage_id: Required. ID of the storage account which is used to store the flow log. :type storage_id: str :param enabled: Required. Flag to enable/disable flow logging. :type enabled: bool :param retention_policy: Parameters that define the retention policy for flow log. :type retention_policy: ~azure.mgmt.network.v2019_06_01.models.RetentionPolicyParameters :param format: Parameters that define the flow log format. :type format: ~azure.mgmt.network.v2019_06_01.models.FlowLogFormatParameters :param flow_analytics_configuration: Parameters that define the configuration of traffic analytics. :type flow_analytics_configuration: ~azure.mgmt.network.v2019_06_01.models.TrafficAnalyticsProperties """ _validation = { 'target_resource_id': {'required': True}, 'storage_id': {'required': True}, 'enabled': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, 'storage_id': {'key': 'properties.storageId', 'type': 'str'}, 'enabled': {'key': 'properties.enabled', 'type': 'bool'}, 'retention_policy': {'key': 'properties.retentionPolicy', 'type': 'RetentionPolicyParameters'}, 'format': {'key': 'properties.format', 'type': 'FlowLogFormatParameters'}, 'flow_analytics_configuration': {'key': 'flowAnalyticsConfiguration', 'type': 'TrafficAnalyticsProperties'}, } def __init__(self, **kwargs): super(FlowLogInformation, self).__init__(**kwargs) self.target_resource_id = kwargs.get('target_resource_id', None) self.storage_id = kwargs.get('storage_id', None) self.enabled = kwargs.get('enabled', None) self.retention_policy = kwargs.get('retention_policy', None) self.format = kwargs.get('format', None) self.flow_analytics_configuration = kwargs.get('flow_analytics_configuration', None) class FlowLogStatusParameters(Model): """Parameters that define a resource to query flow log and traffic analytics (optional) status. All required parameters must be populated in order to send to Azure. :param target_resource_id: Required. The target resource where getting the flow log and traffic analytics (optional) status. :type target_resource_id: str """ _validation = { 'target_resource_id': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, } def __init__(self, **kwargs): super(FlowLogStatusParameters, self).__init__(**kwargs) self.target_resource_id = kwargs.get('target_resource_id', None) class FrontendIPConfiguration(SubResource): """Frontend IP address of the load balancer. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar inbound_nat_rules: Read only. Inbound rules URIs that use this frontend IP. :vartype inbound_nat_rules: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :ivar inbound_nat_pools: Read only. Inbound pools URIs that use this frontend IP. :vartype inbound_nat_pools: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :ivar outbound_rules: Read only. Outbound rules URIs that use this frontend IP. :vartype outbound_rules: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :ivar load_balancing_rules: Gets load balancing rules URIs that use this frontend IP. :vartype load_balancing_rules: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param private_ip_address: The private IP address of the IP configuration. :type private_ip_address: str :param private_ip_allocation_method: The Private IP allocation method. Possible values include: 'Static', 'Dynamic' :type private_ip_allocation_method: str or ~azure.mgmt.network.v2019_06_01.models.IPAllocationMethod :param private_ip_address_version: It represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values include: 'IPv4', 'IPv6' :type private_ip_address_version: str or ~azure.mgmt.network.v2019_06_01.models.IPVersion :param subnet: The reference of the subnet resource. :type subnet: ~azure.mgmt.network.v2019_06_01.models.Subnet :param public_ip_address: The reference of the Public IP resource. :type public_ip_address: ~azure.mgmt.network.v2019_06_01.models.PublicIPAddress :param public_ip_prefix: The reference of the Public IP Prefix resource. :type public_ip_prefix: ~azure.mgmt.network.v2019_06_01.models.SubResource :param provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: The name of the resource that is unique within the set of frontend IP configurations used by the load balancer. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :ivar type: Type of the resource. :vartype type: str :param zones: A list of availability zones denoting the IP allocated for the resource needs to come from. :type zones: list[str] """ _validation = { 'inbound_nat_rules': {'readonly': True}, 'inbound_nat_pools': {'readonly': True}, 'outbound_rules': {'readonly': True}, 'load_balancing_rules': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'inbound_nat_rules': {'key': 'properties.inboundNatRules', 'type': '[SubResource]'}, 'inbound_nat_pools': {'key': 'properties.inboundNatPools', 'type': '[SubResource]'}, 'outbound_rules': {'key': 'properties.outboundRules', 'type': '[SubResource]'}, 'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'}, 'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'}, 'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'}, 'private_ip_address_version': {'key': 'properties.privateIPAddressVersion', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'Subnet'}, 'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'}, 'public_ip_prefix': {'key': 'properties.publicIPPrefix', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'zones': {'key': 'zones', 'type': '[str]'}, } def __init__(self, **kwargs): super(FrontendIPConfiguration, self).__init__(**kwargs) self.inbound_nat_rules = None self.inbound_nat_pools = None self.outbound_rules = None self.load_balancing_rules = None self.private_ip_address = kwargs.get('private_ip_address', None) self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None) self.private_ip_address_version = kwargs.get('private_ip_address_version', None) self.subnet = kwargs.get('subnet', None) self.public_ip_address = kwargs.get('public_ip_address', None) self.public_ip_prefix = kwargs.get('public_ip_prefix', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = None self.zones = kwargs.get('zones', None) class GatewayRoute(Model): """Gateway routing details. Variables are only populated by the server, and will be ignored when sending a request. :ivar local_address: The gateway's local address. :vartype local_address: str :ivar network: The route's network prefix. :vartype network: str :ivar next_hop: The route's next hop. :vartype next_hop: str :ivar source_peer: The peer this route was learned from. :vartype source_peer: str :ivar origin: The source this route was learned from. :vartype origin: str :ivar as_path: The route's AS path sequence. :vartype as_path: str :ivar weight: The route's weight. :vartype weight: int """ _validation = { 'local_address': {'readonly': True}, 'network': {'readonly': True}, 'next_hop': {'readonly': True}, 'source_peer': {'readonly': True}, 'origin': {'readonly': True}, 'as_path': {'readonly': True}, 'weight': {'readonly': True}, } _attribute_map = { 'local_address': {'key': 'localAddress', 'type': 'str'}, 'network': {'key': 'network', 'type': 'str'}, 'next_hop': {'key': 'nextHop', 'type': 'str'}, 'source_peer': {'key': 'sourcePeer', 'type': 'str'}, 'origin': {'key': 'origin', 'type': 'str'}, 'as_path': {'key': 'asPath', 'type': 'str'}, 'weight': {'key': 'weight', 'type': 'int'}, } def __init__(self, **kwargs): super(GatewayRoute, self).__init__(**kwargs) self.local_address = None self.network = None self.next_hop = None self.source_peer = None self.origin = None self.as_path = None self.weight = None class GatewayRouteListResult(Model): """List of virtual network gateway routes. :param value: List of gateway routes. :type value: list[~azure.mgmt.network.v2019_06_01.models.GatewayRoute] """ _attribute_map = { 'value': {'key': 'value', 'type': '[GatewayRoute]'}, } def __init__(self, **kwargs): super(GatewayRouteListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) class GetVpnSitesConfigurationRequest(Model): """List of Vpn-Sites. All required parameters must be populated in order to send to Azure. :param vpn_sites: List of resource-ids of the vpn-sites for which config is to be downloaded. :type vpn_sites: list[str] :param output_blob_sas_url: Required. The sas-url to download the configurations for vpn-sites. :type output_blob_sas_url: str """ _validation = { 'output_blob_sas_url': {'required': True}, } _attribute_map = { 'vpn_sites': {'key': 'vpnSites', 'type': '[str]'}, 'output_blob_sas_url': {'key': 'outputBlobSasUrl', 'type': 'str'}, } def __init__(self, **kwargs): super(GetVpnSitesConfigurationRequest, self).__init__(**kwargs) self.vpn_sites = kwargs.get('vpn_sites', None) self.output_blob_sas_url = kwargs.get('output_blob_sas_url', None) class HTTPConfiguration(Model): """HTTP configuration of the connectivity check. :param method: HTTP method. Possible values include: 'Get' :type method: str or ~azure.mgmt.network.v2019_06_01.models.HTTPMethod :param headers: List of HTTP headers. :type headers: list[~azure.mgmt.network.v2019_06_01.models.HTTPHeader] :param valid_status_codes: Valid status codes. :type valid_status_codes: list[int] """ _attribute_map = { 'method': {'key': 'method', 'type': 'str'}, 'headers': {'key': 'headers', 'type': '[HTTPHeader]'}, 'valid_status_codes': {'key': 'validStatusCodes', 'type': '[int]'}, } def __init__(self, **kwargs): super(HTTPConfiguration, self).__init__(**kwargs) self.method = kwargs.get('method', None) self.headers = kwargs.get('headers', None) self.valid_status_codes = kwargs.get('valid_status_codes', None) class HTTPHeader(Model): """Describes the HTTP header. :param name: The name in HTTP header. :type name: str :param value: The value in HTTP header. :type value: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__(self, **kwargs): super(HTTPHeader, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.value = kwargs.get('value', None) class HubVirtualNetworkConnection(SubResource): """HubVirtualNetworkConnection Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param remote_virtual_network: Reference to the remote virtual network. :type remote_virtual_network: ~azure.mgmt.network.v2019_06_01.models.SubResource :param allow_hub_to_remote_vnet_transit: VirtualHub to RemoteVnet transit to enabled or not. :type allow_hub_to_remote_vnet_transit: bool :param allow_remote_vnet_to_use_hub_vnet_gateways: Allow RemoteVnet to use Virtual Hub's gateways. :type allow_remote_vnet_to_use_hub_vnet_gateways: bool :param enable_internet_security: Enable internet security. :type enable_internet_security: bool :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'remote_virtual_network': {'key': 'properties.remoteVirtualNetwork', 'type': 'SubResource'}, 'allow_hub_to_remote_vnet_transit': {'key': 'properties.allowHubToRemoteVnetTransit', 'type': 'bool'}, 'allow_remote_vnet_to_use_hub_vnet_gateways': {'key': 'properties.allowRemoteVnetToUseHubVnetGateways', 'type': 'bool'}, 'enable_internet_security': {'key': 'properties.enableInternetSecurity', 'type': 'bool'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(HubVirtualNetworkConnection, self).__init__(**kwargs) self.remote_virtual_network = kwargs.get('remote_virtual_network', None) self.allow_hub_to_remote_vnet_transit = kwargs.get('allow_hub_to_remote_vnet_transit', None) self.allow_remote_vnet_to_use_hub_vnet_gateways = kwargs.get('allow_remote_vnet_to_use_hub_vnet_gateways', None) self.enable_internet_security = kwargs.get('enable_internet_security', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = None class InboundNatPool(SubResource): """Inbound NAT pool of the load balancer. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param frontend_ip_configuration: A reference to frontend IP addresses. :type frontend_ip_configuration: ~azure.mgmt.network.v2019_06_01.models.SubResource :param protocol: Required. The reference to the transport protocol used by the inbound NAT pool. Possible values include: 'Udp', 'Tcp', 'All' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.TransportProtocol :param frontend_port_range_start: Required. The first port number in the range of external ports that will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range between 1 and 65534. :type frontend_port_range_start: int :param frontend_port_range_end: Required. The last port number in the range of external ports that will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range between 1 and 65535. :type frontend_port_range_end: int :param backend_port: Required. The port used for internal connections on the endpoint. Acceptable values are between 1 and 65535. :type backend_port: int :param idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. :type idle_timeout_in_minutes: int :param enable_floating_ip: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :type enable_floating_ip: bool :param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. :type enable_tcp_reset: bool :param provisioning_state: Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: The name of the resource that is unique within the set of inbound NAT pools used by the load balancer. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :ivar type: Type of the resource. :vartype type: str """ _validation = { 'protocol': {'required': True}, 'frontend_port_range_start': {'required': True}, 'frontend_port_range_end': {'required': True}, 'backend_port': {'required': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'frontend_port_range_start': {'key': 'properties.frontendPortRangeStart', 'type': 'int'}, 'frontend_port_range_end': {'key': 'properties.frontendPortRangeEnd', 'type': 'int'}, 'backend_port': {'key': 'properties.backendPort', 'type': 'int'}, 'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'}, 'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'}, 'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(InboundNatPool, self).__init__(**kwargs) self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None) self.protocol = kwargs.get('protocol', None) self.frontend_port_range_start = kwargs.get('frontend_port_range_start', None) self.frontend_port_range_end = kwargs.get('frontend_port_range_end', None) self.backend_port = kwargs.get('backend_port', None) self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None) self.enable_floating_ip = kwargs.get('enable_floating_ip', None) self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = None class InboundNatRule(SubResource): """Inbound NAT rule of the load balancer. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param frontend_ip_configuration: A reference to frontend IP addresses. :type frontend_ip_configuration: ~azure.mgmt.network.v2019_06_01.models.SubResource :ivar backend_ip_configuration: A reference to a private IP address defined on a network interface of a VM. Traffic sent to the frontend port of each of the frontend IP configurations is forwarded to the backend IP. :vartype backend_ip_configuration: ~azure.mgmt.network.v2019_06_01.models.NetworkInterfaceIPConfiguration :param protocol: The reference to the transport protocol used by the load balancing rule. Possible values include: 'Udp', 'Tcp', 'All' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.TransportProtocol :param frontend_port: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. :type frontend_port: int :param backend_port: The port used for the internal endpoint. Acceptable values range from 1 to 65535. :type backend_port: int :param idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. :type idle_timeout_in_minutes: int :param enable_floating_ip: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :type enable_floating_ip: bool :param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. :type enable_tcp_reset: bool :param provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Gets name of the resource that is unique within the set of inbound NAT rules used by the load balancer. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :ivar type: Type of the resource. :vartype type: str """ _validation = { 'backend_ip_configuration': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'}, 'backend_ip_configuration': {'key': 'properties.backendIPConfiguration', 'type': 'NetworkInterfaceIPConfiguration'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'frontend_port': {'key': 'properties.frontendPort', 'type': 'int'}, 'backend_port': {'key': 'properties.backendPort', 'type': 'int'}, 'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'}, 'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'}, 'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(InboundNatRule, self).__init__(**kwargs) self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None) self.backend_ip_configuration = None self.protocol = kwargs.get('protocol', None) self.frontend_port = kwargs.get('frontend_port', None) self.backend_port = kwargs.get('backend_port', None) self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None) self.enable_floating_ip = kwargs.get('enable_floating_ip', None) self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = None class IPAddressAvailabilityResult(Model): """Response for CheckIPAddressAvailability API service call. :param available: Private IP address availability. :type available: bool :param available_ip_addresses: Contains other available private IP addresses if the asked for address is taken. :type available_ip_addresses: list[str] """ _attribute_map = { 'available': {'key': 'available', 'type': 'bool'}, 'available_ip_addresses': {'key': 'availableIPAddresses', 'type': '[str]'}, } def __init__(self, **kwargs): super(IPAddressAvailabilityResult, self).__init__(**kwargs) self.available = kwargs.get('available', None) self.available_ip_addresses = kwargs.get('available_ip_addresses', None) class IPConfiguration(SubResource): """IP configuration. :param id: Resource ID. :type id: str :param private_ip_address: The private IP address of the IP configuration. :type private_ip_address: str :param private_ip_allocation_method: The private IP address allocation method. Possible values include: 'Static', 'Dynamic' :type private_ip_allocation_method: str or ~azure.mgmt.network.v2019_06_01.models.IPAllocationMethod :param subnet: The reference of the subnet resource. :type subnet: ~azure.mgmt.network.v2019_06_01.models.Subnet :param public_ip_address: The reference of the public IP resource. :type public_ip_address: ~azure.mgmt.network.v2019_06_01.models.PublicIPAddress :param provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'}, 'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'Subnet'}, 'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(IPConfiguration, self).__init__(**kwargs) self.private_ip_address = kwargs.get('private_ip_address', None) self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None) self.subnet = kwargs.get('subnet', None) self.public_ip_address = kwargs.get('public_ip_address', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class IPConfigurationProfile(SubResource): """IP configuration profile child resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param subnet: The reference of the subnet resource to create a container network interface ip configuration. :type subnet: ~azure.mgmt.network.v2019_06_01.models.Subnet :ivar provisioning_state: The provisioning state of the resource. :vartype provisioning_state: str :param name: The name of the resource. This name can be used to access the resource. :type name: str :ivar type: Sub Resource type. :vartype type: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'provisioning_state': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'Subnet'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(IPConfigurationProfile, self).__init__(**kwargs) self.subnet = kwargs.get('subnet', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.type = None self.etag = kwargs.get('etag', None) class IpsecPolicy(Model): """An IPSec Policy configuration for a virtual network gateway connection. All required parameters must be populated in order to send to Azure. :param sa_life_time_seconds: Required. The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for a site to site VPN tunnel. :type sa_life_time_seconds: int :param sa_data_size_kilobytes: Required. The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for a site to site VPN tunnel. :type sa_data_size_kilobytes: int :param ipsec_encryption: Required. The IPSec encryption algorithm (IKE phase 1). Possible values include: 'None', 'DES', 'DES3', 'AES128', 'AES192', 'AES256', 'GCMAES128', 'GCMAES192', 'GCMAES256' :type ipsec_encryption: str or ~azure.mgmt.network.v2019_06_01.models.IpsecEncryption :param ipsec_integrity: Required. The IPSec integrity algorithm (IKE phase 1). Possible values include: 'MD5', 'SHA1', 'SHA256', 'GCMAES128', 'GCMAES192', 'GCMAES256' :type ipsec_integrity: str or ~azure.mgmt.network.v2019_06_01.models.IpsecIntegrity :param ike_encryption: Required. The IKE encryption algorithm (IKE phase 2). Possible values include: 'DES', 'DES3', 'AES128', 'AES192', 'AES256', 'GCMAES256', 'GCMAES128' :type ike_encryption: str or ~azure.mgmt.network.v2019_06_01.models.IkeEncryption :param ike_integrity: Required. The IKE integrity algorithm (IKE phase 2). Possible values include: 'MD5', 'SHA1', 'SHA256', 'SHA384', 'GCMAES256', 'GCMAES128' :type ike_integrity: str or ~azure.mgmt.network.v2019_06_01.models.IkeIntegrity :param dh_group: Required. The DH Group used in IKE Phase 1 for initial SA. Possible values include: 'None', 'DHGroup1', 'DHGroup2', 'DHGroup14', 'DHGroup2048', 'ECP256', 'ECP384', 'DHGroup24' :type dh_group: str or ~azure.mgmt.network.v2019_06_01.models.DhGroup :param pfs_group: Required. The Pfs Group used in IKE Phase 2 for new child SA. Possible values include: 'None', 'PFS1', 'PFS2', 'PFS2048', 'ECP256', 'ECP384', 'PFS24', 'PFS14', 'PFSMM' :type pfs_group: str or ~azure.mgmt.network.v2019_06_01.models.PfsGroup """ _validation = { 'sa_life_time_seconds': {'required': True}, 'sa_data_size_kilobytes': {'required': True}, 'ipsec_encryption': {'required': True}, 'ipsec_integrity': {'required': True}, 'ike_encryption': {'required': True}, 'ike_integrity': {'required': True}, 'dh_group': {'required': True}, 'pfs_group': {'required': True}, } _attribute_map = { 'sa_life_time_seconds': {'key': 'saLifeTimeSeconds', 'type': 'int'}, 'sa_data_size_kilobytes': {'key': 'saDataSizeKilobytes', 'type': 'int'}, 'ipsec_encryption': {'key': 'ipsecEncryption', 'type': 'str'}, 'ipsec_integrity': {'key': 'ipsecIntegrity', 'type': 'str'}, 'ike_encryption': {'key': 'ikeEncryption', 'type': 'str'}, 'ike_integrity': {'key': 'ikeIntegrity', 'type': 'str'}, 'dh_group': {'key': 'dhGroup', 'type': 'str'}, 'pfs_group': {'key': 'pfsGroup', 'type': 'str'}, } def __init__(self, **kwargs): super(IpsecPolicy, self).__init__(**kwargs) self.sa_life_time_seconds = kwargs.get('sa_life_time_seconds', None) self.sa_data_size_kilobytes = kwargs.get('sa_data_size_kilobytes', None) self.ipsec_encryption = kwargs.get('ipsec_encryption', None) self.ipsec_integrity = kwargs.get('ipsec_integrity', None) self.ike_encryption = kwargs.get('ike_encryption', None) self.ike_integrity = kwargs.get('ike_integrity', None) self.dh_group = kwargs.get('dh_group', None) self.pfs_group = kwargs.get('pfs_group', None) class IpTag(Model): """Contains the IpTag associated with the object. :param ip_tag_type: Gets or sets the ipTag type: Example FirstPartyUsage. :type ip_tag_type: str :param tag: Gets or sets value of the IpTag associated with the public IP. Example SQL, Storage etc. :type tag: str """ _attribute_map = { 'ip_tag_type': {'key': 'ipTagType', 'type': 'str'}, 'tag': {'key': 'tag', 'type': 'str'}, } def __init__(self, **kwargs): super(IpTag, self).__init__(**kwargs) self.ip_tag_type = kwargs.get('ip_tag_type', None) self.tag = kwargs.get('tag', None) class Ipv6ExpressRouteCircuitPeeringConfig(Model): """Contains IPv6 peering config. :param primary_peer_address_prefix: The primary address prefix. :type primary_peer_address_prefix: str :param secondary_peer_address_prefix: The secondary address prefix. :type secondary_peer_address_prefix: str :param microsoft_peering_config: The Microsoft peering configuration. :type microsoft_peering_config: ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeeringConfig :param route_filter: The reference of the RouteFilter resource. :type route_filter: ~azure.mgmt.network.v2019_06_01.models.SubResource :param state: The state of peering. Possible values include: 'Disabled', 'Enabled' :type state: str or ~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeeringState """ _attribute_map = { 'primary_peer_address_prefix': {'key': 'primaryPeerAddressPrefix', 'type': 'str'}, 'secondary_peer_address_prefix': {'key': 'secondaryPeerAddressPrefix', 'type': 'str'}, 'microsoft_peering_config': {'key': 'microsoftPeeringConfig', 'type': 'ExpressRouteCircuitPeeringConfig'}, 'route_filter': {'key': 'routeFilter', 'type': 'SubResource'}, 'state': {'key': 'state', 'type': 'str'}, } def __init__(self, **kwargs): super(Ipv6ExpressRouteCircuitPeeringConfig, self).__init__(**kwargs) self.primary_peer_address_prefix = kwargs.get('primary_peer_address_prefix', None) self.secondary_peer_address_prefix = kwargs.get('secondary_peer_address_prefix', None) self.microsoft_peering_config = kwargs.get('microsoft_peering_config', None) self.route_filter = kwargs.get('route_filter', None) self.state = kwargs.get('state', None) class LoadBalancer(Resource): """LoadBalancer resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param sku: The load balancer SKU. :type sku: ~azure.mgmt.network.v2019_06_01.models.LoadBalancerSku :param frontend_ip_configurations: Object representing the frontend IPs to be used for the load balancer. :type frontend_ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.FrontendIPConfiguration] :param backend_address_pools: Collection of backend address pools used by a load balancer. :type backend_address_pools: list[~azure.mgmt.network.v2019_06_01.models.BackendAddressPool] :param load_balancing_rules: Object collection representing the load balancing rules Gets the provisioning. :type load_balancing_rules: list[~azure.mgmt.network.v2019_06_01.models.LoadBalancingRule] :param probes: Collection of probe objects used in the load balancer. :type probes: list[~azure.mgmt.network.v2019_06_01.models.Probe] :param inbound_nat_rules: Collection of inbound NAT Rules used by a load balancer. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. :type inbound_nat_rules: list[~azure.mgmt.network.v2019_06_01.models.InboundNatRule] :param inbound_nat_pools: Defines an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound Nat rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. :type inbound_nat_pools: list[~azure.mgmt.network.v2019_06_01.models.InboundNatPool] :param outbound_rules: The outbound rules. :type outbound_rules: list[~azure.mgmt.network.v2019_06_01.models.OutboundRule] :param resource_guid: The resource GUID property of the load balancer resource. :type resource_guid: str :param provisioning_state: Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'sku': {'key': 'sku', 'type': 'LoadBalancerSku'}, 'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[FrontendIPConfiguration]'}, 'backend_address_pools': {'key': 'properties.backendAddressPools', 'type': '[BackendAddressPool]'}, 'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[LoadBalancingRule]'}, 'probes': {'key': 'properties.probes', 'type': '[Probe]'}, 'inbound_nat_rules': {'key': 'properties.inboundNatRules', 'type': '[InboundNatRule]'}, 'inbound_nat_pools': {'key': 'properties.inboundNatPools', 'type': '[InboundNatPool]'}, 'outbound_rules': {'key': 'properties.outboundRules', 'type': '[OutboundRule]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(LoadBalancer, self).__init__(**kwargs) self.sku = kwargs.get('sku', None) self.frontend_ip_configurations = kwargs.get('frontend_ip_configurations', None) self.backend_address_pools = kwargs.get('backend_address_pools', None) self.load_balancing_rules = kwargs.get('load_balancing_rules', None) self.probes = kwargs.get('probes', None) self.inbound_nat_rules = kwargs.get('inbound_nat_rules', None) self.inbound_nat_pools = kwargs.get('inbound_nat_pools', None) self.outbound_rules = kwargs.get('outbound_rules', None) self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.etag = kwargs.get('etag', None) class LoadBalancerSku(Model): """SKU of a load balancer. :param name: Name of a load balancer SKU. Possible values include: 'Basic', 'Standard' :type name: str or ~azure.mgmt.network.v2019_06_01.models.LoadBalancerSkuName """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, } def __init__(self, **kwargs): super(LoadBalancerSku, self).__init__(**kwargs) self.name = kwargs.get('name', None) class LoadBalancingRule(SubResource): """A load balancing rule for a load balancer. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param frontend_ip_configuration: A reference to frontend IP addresses. :type frontend_ip_configuration: ~azure.mgmt.network.v2019_06_01.models.SubResource :param backend_address_pool: A reference to a pool of DIPs. Inbound traffic is randomly load balanced across IPs in the backend IPs. :type backend_address_pool: ~azure.mgmt.network.v2019_06_01.models.SubResource :param probe: The reference of the load balancer probe used by the load balancing rule. :type probe: ~azure.mgmt.network.v2019_06_01.models.SubResource :param protocol: Required. The reference to the transport protocol used by the load balancing rule. Possible values include: 'Udp', 'Tcp', 'All' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.TransportProtocol :param load_distribution: The load distribution policy for this rule. Possible values include: 'Default', 'SourceIP', 'SourceIPProtocol' :type load_distribution: str or ~azure.mgmt.network.v2019_06_01.models.LoadDistribution :param frontend_port: Required. The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables "Any Port". :type frontend_port: int :param backend_port: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables "Any Port". :type backend_port: int :param idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. :type idle_timeout_in_minutes: int :param enable_floating_ip: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :type enable_floating_ip: bool :param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. :type enable_tcp_reset: bool :param disable_outbound_snat: Configures SNAT for the VMs in the backend pool to use the publicIP address specified in the frontend of the load balancing rule. :type disable_outbound_snat: bool :param provisioning_state: Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: The name of the resource that is unique within the set of load balancing rules used by the load balancer. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :ivar type: Type of the resource. :vartype type: str """ _validation = { 'protocol': {'required': True}, 'frontend_port': {'required': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'}, 'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'}, 'probe': {'key': 'properties.probe', 'type': 'SubResource'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'load_distribution': {'key': 'properties.loadDistribution', 'type': 'str'}, 'frontend_port': {'key': 'properties.frontendPort', 'type': 'int'}, 'backend_port': {'key': 'properties.backendPort', 'type': 'int'}, 'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'}, 'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'}, 'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'}, 'disable_outbound_snat': {'key': 'properties.disableOutboundSnat', 'type': 'bool'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(LoadBalancingRule, self).__init__(**kwargs) self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None) self.backend_address_pool = kwargs.get('backend_address_pool', None) self.probe = kwargs.get('probe', None) self.protocol = kwargs.get('protocol', None) self.load_distribution = kwargs.get('load_distribution', None) self.frontend_port = kwargs.get('frontend_port', None) self.backend_port = kwargs.get('backend_port', None) self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None) self.enable_floating_ip = kwargs.get('enable_floating_ip', None) self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None) self.disable_outbound_snat = kwargs.get('disable_outbound_snat', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = None class LocalNetworkGateway(Resource): """A common class for general resource information. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param local_network_address_space: Local network site address space. :type local_network_address_space: ~azure.mgmt.network.v2019_06_01.models.AddressSpace :param gateway_ip_address: IP address of local network gateway. :type gateway_ip_address: str :param bgp_settings: Local network gateway's BGP speaker settings. :type bgp_settings: ~azure.mgmt.network.v2019_06_01.models.BgpSettings :param resource_guid: The resource GUID property of the LocalNetworkGateway resource. :type resource_guid: str :ivar provisioning_state: The provisioning state of the LocalNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'local_network_address_space': {'key': 'properties.localNetworkAddressSpace', 'type': 'AddressSpace'}, 'gateway_ip_address': {'key': 'properties.gatewayIpAddress', 'type': 'str'}, 'bgp_settings': {'key': 'properties.bgpSettings', 'type': 'BgpSettings'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(LocalNetworkGateway, self).__init__(**kwargs) self.local_network_address_space = kwargs.get('local_network_address_space', None) self.gateway_ip_address = kwargs.get('gateway_ip_address', None) self.bgp_settings = kwargs.get('bgp_settings', None) self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = None self.etag = kwargs.get('etag', None) class LogSpecification(Model): """Description of logging specification. :param name: The name of the specification. :type name: str :param display_name: The display name of the specification. :type display_name: str :param blob_duration: Duration of the blob. :type blob_duration: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'blob_duration': {'key': 'blobDuration', 'type': 'str'}, } def __init__(self, **kwargs): super(LogSpecification, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.display_name = kwargs.get('display_name', None) self.blob_duration = kwargs.get('blob_duration', None) class ManagedServiceIdentity(Model): """Identity for the resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar principal_id: The principal id of the system assigned identity. This property will only be provided for a system assigned identity. :vartype principal_id: str :ivar tenant_id: The tenant id of the system assigned identity. This property will only be provided for a system assigned identity. :vartype tenant_id: str :param type: The type of identity used for the resource. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine. Possible values include: 'SystemAssigned', 'UserAssigned', 'SystemAssigned, UserAssigned', 'None' :type type: str or ~azure.mgmt.network.v2019_06_01.models.ResourceIdentityType :param user_assigned_identities: The list of user identities associated with resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. :type user_assigned_identities: dict[str, ~azure.mgmt.network.v2019_06_01.models.ManagedServiceIdentityUserAssignedIdentitiesValue] """ _validation = { 'principal_id': {'readonly': True}, 'tenant_id': {'readonly': True}, } _attribute_map = { 'principal_id': {'key': 'principalId', 'type': 'str'}, 'tenant_id': {'key': 'tenantId', 'type': 'str'}, 'type': {'key': 'type', 'type': 'ResourceIdentityType'}, 'user_assigned_identities': {'key': 'userAssignedIdentities', 'type': '{ManagedServiceIdentityUserAssignedIdentitiesValue}'}, } def __init__(self, **kwargs): super(ManagedServiceIdentity, self).__init__(**kwargs) self.principal_id = None self.tenant_id = None self.type = kwargs.get('type', None) self.user_assigned_identities = kwargs.get('user_assigned_identities', None) class ManagedServiceIdentityUserAssignedIdentitiesValue(Model): """ManagedServiceIdentityUserAssignedIdentitiesValue. Variables are only populated by the server, and will be ignored when sending a request. :ivar principal_id: The principal id of user assigned identity. :vartype principal_id: str :ivar client_id: The client id of user assigned identity. :vartype client_id: str """ _validation = { 'principal_id': {'readonly': True}, 'client_id': {'readonly': True}, } _attribute_map = { 'principal_id': {'key': 'principalId', 'type': 'str'}, 'client_id': {'key': 'clientId', 'type': 'str'}, } def __init__(self, **kwargs): super(ManagedServiceIdentityUserAssignedIdentitiesValue, self).__init__(**kwargs) self.principal_id = None self.client_id = None class MatchCondition(Model): """Define match conditions. All required parameters must be populated in order to send to Azure. :param match_variables: Required. List of match variables. :type match_variables: list[~azure.mgmt.network.v2019_06_01.models.MatchVariable] :param operator: Required. Describes operator to be matched. Possible values include: 'IPMatch', 'Equal', 'Contains', 'LessThan', 'GreaterThan', 'LessThanOrEqual', 'GreaterThanOrEqual', 'BeginsWith', 'EndsWith', 'Regex' :type operator: str or ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallOperator :param negation_conditon: Describes if this is negate condition or not. :type negation_conditon: bool :param match_values: Required. Match value. :type match_values: list[str] :param transforms: List of transforms. :type transforms: list[str or ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallTransform] """ _validation = { 'match_variables': {'required': True}, 'operator': {'required': True}, 'match_values': {'required': True}, } _attribute_map = { 'match_variables': {'key': 'matchVariables', 'type': '[MatchVariable]'}, 'operator': {'key': 'operator', 'type': 'str'}, 'negation_conditon': {'key': 'negationConditon', 'type': 'bool'}, 'match_values': {'key': 'matchValues', 'type': '[str]'}, 'transforms': {'key': 'transforms', 'type': '[str]'}, } def __init__(self, **kwargs): super(MatchCondition, self).__init__(**kwargs) self.match_variables = kwargs.get('match_variables', None) self.operator = kwargs.get('operator', None) self.negation_conditon = kwargs.get('negation_conditon', None) self.match_values = kwargs.get('match_values', None) self.transforms = kwargs.get('transforms', None) class MatchedRule(Model): """Matched rule. :param rule_name: Name of the matched network security rule. :type rule_name: str :param action: The network traffic is allowed or denied. Possible values are 'Allow' and 'Deny'. :type action: str """ _attribute_map = { 'rule_name': {'key': 'ruleName', 'type': 'str'}, 'action': {'key': 'action', 'type': 'str'}, } def __init__(self, **kwargs): super(MatchedRule, self).__init__(**kwargs) self.rule_name = kwargs.get('rule_name', None) self.action = kwargs.get('action', None) class MatchVariable(Model): """Define match variables. All required parameters must be populated in order to send to Azure. :param variable_name: Required. Match Variable. Possible values include: 'RemoteAddr', 'RequestMethod', 'QueryString', 'PostArgs', 'RequestUri', 'RequestHeaders', 'RequestBody', 'RequestCookies' :type variable_name: str or ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallMatchVariable :param selector: Describes field of the matchVariable collection. :type selector: str """ _validation = { 'variable_name': {'required': True}, } _attribute_map = { 'variable_name': {'key': 'variableName', 'type': 'str'}, 'selector': {'key': 'selector', 'type': 'str'}, } def __init__(self, **kwargs): super(MatchVariable, self).__init__(**kwargs) self.variable_name = kwargs.get('variable_name', None) self.selector = kwargs.get('selector', None) class MetricSpecification(Model): """Description of metrics specification. :param name: The name of the metric. :type name: str :param display_name: The display name of the metric. :type display_name: str :param display_description: The description of the metric. :type display_description: str :param unit: Units the metric to be displayed in. :type unit: str :param aggregation_type: The aggregation type. :type aggregation_type: str :param availabilities: List of availability. :type availabilities: list[~azure.mgmt.network.v2019_06_01.models.Availability] :param enable_regional_mdm_account: Whether regional MDM account enabled. :type enable_regional_mdm_account: bool :param fill_gap_with_zero: Whether gaps would be filled with zeros. :type fill_gap_with_zero: bool :param metric_filter_pattern: Pattern for the filter of the metric. :type metric_filter_pattern: str :param dimensions: List of dimensions. :type dimensions: list[~azure.mgmt.network.v2019_06_01.models.Dimension] :param is_internal: Whether the metric is internal. :type is_internal: bool :param source_mdm_account: The source MDM account. :type source_mdm_account: str :param source_mdm_namespace: The source MDM namespace. :type source_mdm_namespace: str :param resource_id_dimension_name_override: The resource Id dimension name override. :type resource_id_dimension_name_override: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'display_description': {'key': 'displayDescription', 'type': 'str'}, 'unit': {'key': 'unit', 'type': 'str'}, 'aggregation_type': {'key': 'aggregationType', 'type': 'str'}, 'availabilities': {'key': 'availabilities', 'type': '[Availability]'}, 'enable_regional_mdm_account': {'key': 'enableRegionalMdmAccount', 'type': 'bool'}, 'fill_gap_with_zero': {'key': 'fillGapWithZero', 'type': 'bool'}, 'metric_filter_pattern': {'key': 'metricFilterPattern', 'type': 'str'}, 'dimensions': {'key': 'dimensions', 'type': '[Dimension]'}, 'is_internal': {'key': 'isInternal', 'type': 'bool'}, 'source_mdm_account': {'key': 'sourceMdmAccount', 'type': 'str'}, 'source_mdm_namespace': {'key': 'sourceMdmNamespace', 'type': 'str'}, 'resource_id_dimension_name_override': {'key': 'resourceIdDimensionNameOverride', 'type': 'str'}, } def __init__(self, **kwargs): super(MetricSpecification, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.display_name = kwargs.get('display_name', None) self.display_description = kwargs.get('display_description', None) self.unit = kwargs.get('unit', None) self.aggregation_type = kwargs.get('aggregation_type', None) self.availabilities = kwargs.get('availabilities', None) self.enable_regional_mdm_account = kwargs.get('enable_regional_mdm_account', None) self.fill_gap_with_zero = kwargs.get('fill_gap_with_zero', None) self.metric_filter_pattern = kwargs.get('metric_filter_pattern', None) self.dimensions = kwargs.get('dimensions', None) self.is_internal = kwargs.get('is_internal', None) self.source_mdm_account = kwargs.get('source_mdm_account', None) self.source_mdm_namespace = kwargs.get('source_mdm_namespace', None) self.resource_id_dimension_name_override = kwargs.get('resource_id_dimension_name_override', None) class NatGateway(Resource): """Nat Gateway resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param sku: The nat gateway SKU. :type sku: ~azure.mgmt.network.v2019_06_01.models.NatGatewaySku :param idle_timeout_in_minutes: The idle timeout of the nat gateway. :type idle_timeout_in_minutes: int :param public_ip_addresses: An array of public ip addresses associated with the nat gateway resource. :type public_ip_addresses: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param public_ip_prefixes: An array of public ip prefixes associated with the nat gateway resource. :type public_ip_prefixes: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :ivar subnets: An array of references to the subnets using this nat gateway resource. :vartype subnets: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param resource_guid: The resource GUID property of the nat gateway resource. :type resource_guid: str :param provisioning_state: The provisioning state of the NatGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param zones: A list of availability zones denoting the zone in which Nat Gateway should be deployed. :type zones: list[str] :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'subnets': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'sku': {'key': 'sku', 'type': 'NatGatewaySku'}, 'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'}, 'public_ip_addresses': {'key': 'properties.publicIpAddresses', 'type': '[SubResource]'}, 'public_ip_prefixes': {'key': 'properties.publicIpPrefixes', 'type': '[SubResource]'}, 'subnets': {'key': 'properties.subnets', 'type': '[SubResource]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'zones': {'key': 'zones', 'type': '[str]'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(NatGateway, self).__init__(**kwargs) self.sku = kwargs.get('sku', None) self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None) self.public_ip_addresses = kwargs.get('public_ip_addresses', None) self.public_ip_prefixes = kwargs.get('public_ip_prefixes', None) self.subnets = None self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.zones = kwargs.get('zones', None) self.etag = kwargs.get('etag', None) class NatGatewaySku(Model): """SKU of nat gateway. :param name: Name of Nat Gateway SKU. Possible values include: 'Standard' :type name: str or ~azure.mgmt.network.v2019_06_01.models.NatGatewaySkuName """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, } def __init__(self, **kwargs): super(NatGatewaySku, self).__init__(**kwargs) self.name = kwargs.get('name', None) class NetworkConfigurationDiagnosticParameters(Model): """Parameters to get network configuration diagnostic. All required parameters must be populated in order to send to Azure. :param target_resource_id: Required. The ID of the target resource to perform network configuration diagnostic. Valid options are VM, NetworkInterface, VMSS/NetworkInterface and Application Gateway. :type target_resource_id: str :param verbosity_level: Verbosity level. Possible values include: 'Normal', 'Minimum', 'Full' :type verbosity_level: str or ~azure.mgmt.network.v2019_06_01.models.VerbosityLevel :param profiles: Required. List of network configuration diagnostic profiles. :type profiles: list[~azure.mgmt.network.v2019_06_01.models.NetworkConfigurationDiagnosticProfile] """ _validation = { 'target_resource_id': {'required': True}, 'profiles': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, 'verbosity_level': {'key': 'verbosityLevel', 'type': 'str'}, 'profiles': {'key': 'profiles', 'type': '[NetworkConfigurationDiagnosticProfile]'}, } def __init__(self, **kwargs): super(NetworkConfigurationDiagnosticParameters, self).__init__(**kwargs) self.target_resource_id = kwargs.get('target_resource_id', None) self.verbosity_level = kwargs.get('verbosity_level', None) self.profiles = kwargs.get('profiles', None) class NetworkConfigurationDiagnosticProfile(Model): """Parameters to compare with network configuration. All required parameters must be populated in order to send to Azure. :param direction: Required. The direction of the traffic. Possible values include: 'Inbound', 'Outbound' :type direction: str or ~azure.mgmt.network.v2019_06_01.models.Direction :param protocol: Required. Protocol to be verified on. Accepted values are '*', TCP, UDP. :type protocol: str :param source: Required. Traffic source. Accepted values are '*', IP Address/CIDR, Service Tag. :type source: str :param destination: Required. Traffic destination. Accepted values are: '*', IP Address/CIDR, Service Tag. :type destination: str :param destination_port: Required. Traffic destination port. Accepted values are '*', port (for example, 3389) and port range (for example, 80-100). :type destination_port: str """ _validation = { 'direction': {'required': True}, 'protocol': {'required': True}, 'source': {'required': True}, 'destination': {'required': True}, 'destination_port': {'required': True}, } _attribute_map = { 'direction': {'key': 'direction', 'type': 'str'}, 'protocol': {'key': 'protocol', 'type': 'str'}, 'source': {'key': 'source', 'type': 'str'}, 'destination': {'key': 'destination', 'type': 'str'}, 'destination_port': {'key': 'destinationPort', 'type': 'str'}, } def __init__(self, **kwargs): super(NetworkConfigurationDiagnosticProfile, self).__init__(**kwargs) self.direction = kwargs.get('direction', None) self.protocol = kwargs.get('protocol', None) self.source = kwargs.get('source', None) self.destination = kwargs.get('destination', None) self.destination_port = kwargs.get('destination_port', None) class NetworkConfigurationDiagnosticResponse(Model): """Results of network configuration diagnostic on the target resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar results: List of network configuration diagnostic results. :vartype results: list[~azure.mgmt.network.v2019_06_01.models.NetworkConfigurationDiagnosticResult] """ _validation = { 'results': {'readonly': True}, } _attribute_map = { 'results': {'key': 'results', 'type': '[NetworkConfigurationDiagnosticResult]'}, } def __init__(self, **kwargs): super(NetworkConfigurationDiagnosticResponse, self).__init__(**kwargs) self.results = None class NetworkConfigurationDiagnosticResult(Model): """Network configuration diagnostic result corresponded to provided traffic query. :param profile: Network configuration diagnostic profile. :type profile: ~azure.mgmt.network.v2019_06_01.models.NetworkConfigurationDiagnosticProfile :param network_security_group_result: Network security group result. :type network_security_group_result: ~azure.mgmt.network.v2019_06_01.models.NetworkSecurityGroupResult """ _attribute_map = { 'profile': {'key': 'profile', 'type': 'NetworkConfigurationDiagnosticProfile'}, 'network_security_group_result': {'key': 'networkSecurityGroupResult', 'type': 'NetworkSecurityGroupResult'}, } def __init__(self, **kwargs): super(NetworkConfigurationDiagnosticResult, self).__init__(**kwargs) self.profile = kwargs.get('profile', None) self.network_security_group_result = kwargs.get('network_security_group_result', None) class NetworkIntentPolicy(Resource): """Network Intent Policy resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(NetworkIntentPolicy, self).__init__(**kwargs) self.etag = kwargs.get('etag', None) class NetworkIntentPolicyConfiguration(Model): """Details of NetworkIntentPolicyConfiguration for PrepareNetworkPoliciesRequest. :param network_intent_policy_name: The name of the Network Intent Policy for storing in target subscription. :type network_intent_policy_name: str :param source_network_intent_policy: Source network intent policy. :type source_network_intent_policy: ~azure.mgmt.network.v2019_06_01.models.NetworkIntentPolicy """ _attribute_map = { 'network_intent_policy_name': {'key': 'networkIntentPolicyName', 'type': 'str'}, 'source_network_intent_policy': {'key': 'sourceNetworkIntentPolicy', 'type': 'NetworkIntentPolicy'}, } def __init__(self, **kwargs): super(NetworkIntentPolicyConfiguration, self).__init__(**kwargs) self.network_intent_policy_name = kwargs.get('network_intent_policy_name', None) self.source_network_intent_policy = kwargs.get('source_network_intent_policy', None) class NetworkInterface(Resource): """A network interface in a resource group. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :ivar virtual_machine: The reference of a virtual machine. :vartype virtual_machine: ~azure.mgmt.network.v2019_06_01.models.SubResource :param network_security_group: The reference of the NetworkSecurityGroup resource. :type network_security_group: ~azure.mgmt.network.v2019_06_01.models.NetworkSecurityGroup :ivar private_endpoint: A reference to the private endpoint to which the network interface is linked. :vartype private_endpoint: ~azure.mgmt.network.v2019_06_01.models.PrivateEndpoint :param ip_configurations: A list of IPConfigurations of the network interface. :type ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.NetworkInterfaceIPConfiguration] :param tap_configurations: A list of TapConfigurations of the network interface. :type tap_configurations: list[~azure.mgmt.network.v2019_06_01.models.NetworkInterfaceTapConfiguration] :param dns_settings: The DNS settings in network interface. :type dns_settings: ~azure.mgmt.network.v2019_06_01.models.NetworkInterfaceDnsSettings :param mac_address: The MAC address of the network interface. :type mac_address: str :param primary: Gets whether this is a primary network interface on a virtual machine. :type primary: bool :param enable_accelerated_networking: If the network interface is accelerated networking enabled. :type enable_accelerated_networking: bool :param enable_ip_forwarding: Indicates whether IP forwarding is enabled on this network interface. :type enable_ip_forwarding: bool :ivar hosted_workloads: A list of references to linked BareMetal resources. :vartype hosted_workloads: list[str] :param resource_guid: The resource GUID property of the network interface resource. :type resource_guid: str :param provisioning_state: The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'virtual_machine': {'readonly': True}, 'private_endpoint': {'readonly': True}, 'hosted_workloads': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'virtual_machine': {'key': 'properties.virtualMachine', 'type': 'SubResource'}, 'network_security_group': {'key': 'properties.networkSecurityGroup', 'type': 'NetworkSecurityGroup'}, 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'}, 'tap_configurations': {'key': 'properties.tapConfigurations', 'type': '[NetworkInterfaceTapConfiguration]'}, 'dns_settings': {'key': 'properties.dnsSettings', 'type': 'NetworkInterfaceDnsSettings'}, 'mac_address': {'key': 'properties.macAddress', 'type': 'str'}, 'primary': {'key': 'properties.primary', 'type': 'bool'}, 'enable_accelerated_networking': {'key': 'properties.enableAcceleratedNetworking', 'type': 'bool'}, 'enable_ip_forwarding': {'key': 'properties.enableIPForwarding', 'type': 'bool'}, 'hosted_workloads': {'key': 'properties.hostedWorkloads', 'type': '[str]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(NetworkInterface, self).__init__(**kwargs) self.virtual_machine = None self.network_security_group = kwargs.get('network_security_group', None) self.private_endpoint = None self.ip_configurations = kwargs.get('ip_configurations', None) self.tap_configurations = kwargs.get('tap_configurations', None) self.dns_settings = kwargs.get('dns_settings', None) self.mac_address = kwargs.get('mac_address', None) self.primary = kwargs.get('primary', None) self.enable_accelerated_networking = kwargs.get('enable_accelerated_networking', None) self.enable_ip_forwarding = kwargs.get('enable_ip_forwarding', None) self.hosted_workloads = None self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.etag = kwargs.get('etag', None) class NetworkInterfaceAssociation(Model): """Network interface and its custom security rules. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Network interface ID. :vartype id: str :param security_rules: Collection of custom security rules. :type security_rules: list[~azure.mgmt.network.v2019_06_01.models.SecurityRule] """ _validation = { 'id': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'security_rules': {'key': 'securityRules', 'type': '[SecurityRule]'}, } def __init__(self, **kwargs): super(NetworkInterfaceAssociation, self).__init__(**kwargs) self.id = None self.security_rules = kwargs.get('security_rules', None) class NetworkInterfaceDnsSettings(Model): """DNS settings of a network interface. :param dns_servers: List of DNS servers IP addresses. Use 'AzureProvidedDNS' to switch to azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dnsServers collection. :type dns_servers: list[str] :param applied_dns_servers: If the VM that uses this NIC is part of an Availability Set, then this list will have the union of all DNS servers from all NICs that are part of the Availability Set. This property is what is configured on each of those VMs. :type applied_dns_servers: list[str] :param internal_dns_name_label: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. :type internal_dns_name_label: str :param internal_fqdn: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. :type internal_fqdn: str :param internal_domain_name_suffix: Even if internalDnsNameLabel is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internalDomainNameSuffix. :type internal_domain_name_suffix: str """ _attribute_map = { 'dns_servers': {'key': 'dnsServers', 'type': '[str]'}, 'applied_dns_servers': {'key': 'appliedDnsServers', 'type': '[str]'}, 'internal_dns_name_label': {'key': 'internalDnsNameLabel', 'type': 'str'}, 'internal_fqdn': {'key': 'internalFqdn', 'type': 'str'}, 'internal_domain_name_suffix': {'key': 'internalDomainNameSuffix', 'type': 'str'}, } def __init__(self, **kwargs): super(NetworkInterfaceDnsSettings, self).__init__(**kwargs) self.dns_servers = kwargs.get('dns_servers', None) self.applied_dns_servers = kwargs.get('applied_dns_servers', None) self.internal_dns_name_label = kwargs.get('internal_dns_name_label', None) self.internal_fqdn = kwargs.get('internal_fqdn', None) self.internal_domain_name_suffix = kwargs.get('internal_domain_name_suffix', None) class NetworkInterfaceIPConfiguration(SubResource): """IPConfiguration in a network interface. :param id: Resource ID. :type id: str :param virtual_network_taps: The reference to Virtual Network Taps. :type virtual_network_taps: list[~azure.mgmt.network.v2019_06_01.models.VirtualNetworkTap] :param application_gateway_backend_address_pools: The reference of ApplicationGatewayBackendAddressPool resource. :type application_gateway_backend_address_pools: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGatewayBackendAddressPool] :param load_balancer_backend_address_pools: The reference of LoadBalancerBackendAddressPool resource. :type load_balancer_backend_address_pools: list[~azure.mgmt.network.v2019_06_01.models.BackendAddressPool] :param load_balancer_inbound_nat_rules: A list of references of LoadBalancerInboundNatRules. :type load_balancer_inbound_nat_rules: list[~azure.mgmt.network.v2019_06_01.models.InboundNatRule] :param private_ip_address: Private IP address of the IP configuration. :type private_ip_address: str :param private_ip_allocation_method: The private IP address allocation method. Possible values include: 'Static', 'Dynamic' :type private_ip_allocation_method: str or ~azure.mgmt.network.v2019_06_01.models.IPAllocationMethod :param private_ip_address_version: Available from Api-Version 2016-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values include: 'IPv4', 'IPv6' :type private_ip_address_version: str or ~azure.mgmt.network.v2019_06_01.models.IPVersion :param subnet: Subnet bound to the IP configuration. :type subnet: ~azure.mgmt.network.v2019_06_01.models.Subnet :param primary: Gets whether this is a primary customer address on the network interface. :type primary: bool :param public_ip_address: Public IP address bound to the IP configuration. :type public_ip_address: ~azure.mgmt.network.v2019_06_01.models.PublicIPAddress :param application_security_groups: Application security groups in which the IP configuration is included. :type application_security_groups: list[~azure.mgmt.network.v2019_06_01.models.ApplicationSecurityGroup] :param provisioning_state: The provisioning state of the network interface IP configuration. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'virtual_network_taps': {'key': 'properties.virtualNetworkTaps', 'type': '[VirtualNetworkTap]'}, 'application_gateway_backend_address_pools': {'key': 'properties.applicationGatewayBackendAddressPools', 'type': '[ApplicationGatewayBackendAddressPool]'}, 'load_balancer_backend_address_pools': {'key': 'properties.loadBalancerBackendAddressPools', 'type': '[BackendAddressPool]'}, 'load_balancer_inbound_nat_rules': {'key': 'properties.loadBalancerInboundNatRules', 'type': '[InboundNatRule]'}, 'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'}, 'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'}, 'private_ip_address_version': {'key': 'properties.privateIPAddressVersion', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'Subnet'}, 'primary': {'key': 'properties.primary', 'type': 'bool'}, 'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'}, 'application_security_groups': {'key': 'properties.applicationSecurityGroups', 'type': '[ApplicationSecurityGroup]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(NetworkInterfaceIPConfiguration, self).__init__(**kwargs) self.virtual_network_taps = kwargs.get('virtual_network_taps', None) self.application_gateway_backend_address_pools = kwargs.get('application_gateway_backend_address_pools', None) self.load_balancer_backend_address_pools = kwargs.get('load_balancer_backend_address_pools', None) self.load_balancer_inbound_nat_rules = kwargs.get('load_balancer_inbound_nat_rules', None) self.private_ip_address = kwargs.get('private_ip_address', None) self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None) self.private_ip_address_version = kwargs.get('private_ip_address_version', None) self.subnet = kwargs.get('subnet', None) self.primary = kwargs.get('primary', None) self.public_ip_address = kwargs.get('public_ip_address', None) self.application_security_groups = kwargs.get('application_security_groups', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class NetworkInterfaceTapConfiguration(SubResource): """Tap configuration in a Network Interface. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param virtual_network_tap: The reference of the Virtual Network Tap resource. :type virtual_network_tap: ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkTap :ivar provisioning_state: The provisioning state of the network interface tap configuration. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :ivar type: Sub Resource type. :vartype type: str """ _validation = { 'provisioning_state': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'virtual_network_tap': {'key': 'properties.virtualNetworkTap', 'type': 'VirtualNetworkTap'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(NetworkInterfaceTapConfiguration, self).__init__(**kwargs) self.virtual_network_tap = kwargs.get('virtual_network_tap', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = None class NetworkProfile(Resource): """Network profile resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param container_network_interfaces: List of child container network interfaces. :type container_network_interfaces: list[~azure.mgmt.network.v2019_06_01.models.ContainerNetworkInterface] :param container_network_interface_configurations: List of chid container network interface configurations. :type container_network_interface_configurations: list[~azure.mgmt.network.v2019_06_01.models.ContainerNetworkInterfaceConfiguration] :ivar resource_guid: The resource GUID property of the network interface resource. :vartype resource_guid: str :ivar provisioning_state: The provisioning state of the resource. :vartype provisioning_state: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'resource_guid': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'container_network_interfaces': {'key': 'properties.containerNetworkInterfaces', 'type': '[ContainerNetworkInterface]'}, 'container_network_interface_configurations': {'key': 'properties.containerNetworkInterfaceConfigurations', 'type': '[ContainerNetworkInterfaceConfiguration]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(NetworkProfile, self).__init__(**kwargs) self.container_network_interfaces = kwargs.get('container_network_interfaces', None) self.container_network_interface_configurations = kwargs.get('container_network_interface_configurations', None) self.resource_guid = None self.provisioning_state = None self.etag = kwargs.get('etag', None) class NetworkSecurityGroup(Resource): """NetworkSecurityGroup resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param security_rules: A collection of security rules of the network security group. :type security_rules: list[~azure.mgmt.network.v2019_06_01.models.SecurityRule] :param default_security_rules: The default security rules of network security group. :type default_security_rules: list[~azure.mgmt.network.v2019_06_01.models.SecurityRule] :ivar network_interfaces: A collection of references to network interfaces. :vartype network_interfaces: list[~azure.mgmt.network.v2019_06_01.models.NetworkInterface] :ivar subnets: A collection of references to subnets. :vartype subnets: list[~azure.mgmt.network.v2019_06_01.models.Subnet] :param resource_guid: The resource GUID property of the network security group resource. :type resource_guid: str :param provisioning_state: The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'network_interfaces': {'readonly': True}, 'subnets': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'security_rules': {'key': 'properties.securityRules', 'type': '[SecurityRule]'}, 'default_security_rules': {'key': 'properties.defaultSecurityRules', 'type': '[SecurityRule]'}, 'network_interfaces': {'key': 'properties.networkInterfaces', 'type': '[NetworkInterface]'}, 'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(NetworkSecurityGroup, self).__init__(**kwargs) self.security_rules = kwargs.get('security_rules', None) self.default_security_rules = kwargs.get('default_security_rules', None) self.network_interfaces = None self.subnets = None self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.etag = kwargs.get('etag', None) class NetworkSecurityGroupResult(Model): """Network configuration diagnostic result corresponded provided traffic query. Variables are only populated by the server, and will be ignored when sending a request. :param security_rule_access_result: The network traffic is allowed or denied. Possible values include: 'Allow', 'Deny' :type security_rule_access_result: str or ~azure.mgmt.network.v2019_06_01.models.SecurityRuleAccess :ivar evaluated_network_security_groups: List of results network security groups diagnostic. :vartype evaluated_network_security_groups: list[~azure.mgmt.network.v2019_06_01.models.EvaluatedNetworkSecurityGroup] """ _validation = { 'evaluated_network_security_groups': {'readonly': True}, } _attribute_map = { 'security_rule_access_result': {'key': 'securityRuleAccessResult', 'type': 'str'}, 'evaluated_network_security_groups': {'key': 'evaluatedNetworkSecurityGroups', 'type': '[EvaluatedNetworkSecurityGroup]'}, } def __init__(self, **kwargs): super(NetworkSecurityGroupResult, self).__init__(**kwargs) self.security_rule_access_result = kwargs.get('security_rule_access_result', None) self.evaluated_network_security_groups = None class NetworkSecurityRulesEvaluationResult(Model): """Network security rules evaluation result. :param name: Name of the network security rule. :type name: str :param protocol_matched: Value indicating whether protocol is matched. :type protocol_matched: bool :param source_matched: Value indicating whether source is matched. :type source_matched: bool :param source_port_matched: Value indicating whether source port is matched. :type source_port_matched: bool :param destination_matched: Value indicating whether destination is matched. :type destination_matched: bool :param destination_port_matched: Value indicating whether destination port is matched. :type destination_port_matched: bool """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'protocol_matched': {'key': 'protocolMatched', 'type': 'bool'}, 'source_matched': {'key': 'sourceMatched', 'type': 'bool'}, 'source_port_matched': {'key': 'sourcePortMatched', 'type': 'bool'}, 'destination_matched': {'key': 'destinationMatched', 'type': 'bool'}, 'destination_port_matched': {'key': 'destinationPortMatched', 'type': 'bool'}, } def __init__(self, **kwargs): super(NetworkSecurityRulesEvaluationResult, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.protocol_matched = kwargs.get('protocol_matched', None) self.source_matched = kwargs.get('source_matched', None) self.source_port_matched = kwargs.get('source_port_matched', None) self.destination_matched = kwargs.get('destination_matched', None) self.destination_port_matched = kwargs.get('destination_port_matched', None) class NetworkWatcher(Resource): """Network watcher in a resource group. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'etag': {'key': 'etag', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } def __init__(self, **kwargs): super(NetworkWatcher, self).__init__(**kwargs) self.etag = kwargs.get('etag', None) self.provisioning_state = kwargs.get('provisioning_state', None) class NextHopParameters(Model): """Parameters that define the source and destination endpoint. All required parameters must be populated in order to send to Azure. :param target_resource_id: Required. The resource identifier of the target resource against which the action is to be performed. :type target_resource_id: str :param source_ip_address: Required. The source IP address. :type source_ip_address: str :param destination_ip_address: Required. The destination IP address. :type destination_ip_address: str :param target_nic_resource_id: The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of the nics, then this parameter must be specified. Otherwise optional). :type target_nic_resource_id: str """ _validation = { 'target_resource_id': {'required': True}, 'source_ip_address': {'required': True}, 'destination_ip_address': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, 'source_ip_address': {'key': 'sourceIPAddress', 'type': 'str'}, 'destination_ip_address': {'key': 'destinationIPAddress', 'type': 'str'}, 'target_nic_resource_id': {'key': 'targetNicResourceId', 'type': 'str'}, } def __init__(self, **kwargs): super(NextHopParameters, self).__init__(**kwargs) self.target_resource_id = kwargs.get('target_resource_id', None) self.source_ip_address = kwargs.get('source_ip_address', None) self.destination_ip_address = kwargs.get('destination_ip_address', None) self.target_nic_resource_id = kwargs.get('target_nic_resource_id', None) class NextHopResult(Model): """The information about next hop from the specified VM. :param next_hop_type: Next hop type. Possible values include: 'Internet', 'VirtualAppliance', 'VirtualNetworkGateway', 'VnetLocal', 'HyperNetGateway', 'None' :type next_hop_type: str or ~azure.mgmt.network.v2019_06_01.models.NextHopType :param next_hop_ip_address: Next hop IP Address. :type next_hop_ip_address: str :param route_table_id: The resource identifier for the route table associated with the route being returned. If the route being returned does not correspond to any user created routes then this field will be the string 'System Route'. :type route_table_id: str """ _attribute_map = { 'next_hop_type': {'key': 'nextHopType', 'type': 'str'}, 'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': 'str'}, 'route_table_id': {'key': 'routeTableId', 'type': 'str'}, } def __init__(self, **kwargs): super(NextHopResult, self).__init__(**kwargs) self.next_hop_type = kwargs.get('next_hop_type', None) self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None) self.route_table_id = kwargs.get('route_table_id', None) class Operation(Model): """Network REST API operation definition. :param name: Operation name: {provider}/{resource}/{operation}. :type name: str :param display: Display metadata associated with the operation. :type display: ~azure.mgmt.network.v2019_06_01.models.OperationDisplay :param origin: Origin of the operation. :type origin: str :param service_specification: Specification of the service. :type service_specification: ~azure.mgmt.network.v2019_06_01.models.OperationPropertiesFormatServiceSpecification """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display': {'key': 'display', 'type': 'OperationDisplay'}, 'origin': {'key': 'origin', 'type': 'str'}, 'service_specification': {'key': 'properties.serviceSpecification', 'type': 'OperationPropertiesFormatServiceSpecification'}, } def __init__(self, **kwargs): super(Operation, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.display = kwargs.get('display', None) self.origin = kwargs.get('origin', None) self.service_specification = kwargs.get('service_specification', None) class OperationDisplay(Model): """Display metadata associated with the operation. :param provider: Service provider: Microsoft Network. :type provider: str :param resource: Resource on which the operation is performed. :type resource: str :param operation: Type of the operation: get, read, delete, etc. :type operation: str :param description: Description of the operation. :type description: str """ _attribute_map = { 'provider': {'key': 'provider', 'type': 'str'}, 'resource': {'key': 'resource', 'type': 'str'}, 'operation': {'key': 'operation', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, } def __init__(self, **kwargs): super(OperationDisplay, self).__init__(**kwargs) self.provider = kwargs.get('provider', None) self.resource = kwargs.get('resource', None) self.operation = kwargs.get('operation', None) self.description = kwargs.get('description', None) class OperationPropertiesFormatServiceSpecification(Model): """Specification of the service. :param metric_specifications: Operation service specification. :type metric_specifications: list[~azure.mgmt.network.v2019_06_01.models.MetricSpecification] :param log_specifications: Operation log specification. :type log_specifications: list[~azure.mgmt.network.v2019_06_01.models.LogSpecification] """ _attribute_map = { 'metric_specifications': {'key': 'metricSpecifications', 'type': '[MetricSpecification]'}, 'log_specifications': {'key': 'logSpecifications', 'type': '[LogSpecification]'}, } def __init__(self, **kwargs): super(OperationPropertiesFormatServiceSpecification, self).__init__(**kwargs) self.metric_specifications = kwargs.get('metric_specifications', None) self.log_specifications = kwargs.get('log_specifications', None) class OutboundRule(SubResource): """Outbound rule of the load balancer. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param allocated_outbound_ports: The number of outbound ports to be used for NAT. :type allocated_outbound_ports: int :param frontend_ip_configurations: Required. The Frontend IP addresses of the load balancer. :type frontend_ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param backend_address_pool: Required. A reference to a pool of DIPs. Outbound traffic is randomly load balanced across IPs in the backend IPs. :type backend_address_pool: ~azure.mgmt.network.v2019_06_01.models.SubResource :param provisioning_state: Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param protocol: Required. The protocol for the outbound rule in load balancer. Possible values include: 'Tcp', 'Udp', 'All' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.LoadBalancerOutboundRuleProtocol :param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. :type enable_tcp_reset: bool :param idle_timeout_in_minutes: The timeout for the TCP idle connection. :type idle_timeout_in_minutes: int :param name: The name of the resource that is unique within the set of outbound rules used by the load balancer. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :ivar type: Type of the resource. :vartype type: str """ _validation = { 'frontend_ip_configurations': {'required': True}, 'backend_address_pool': {'required': True}, 'protocol': {'required': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'allocated_outbound_ports': {'key': 'properties.allocatedOutboundPorts', 'type': 'int'}, 'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[SubResource]'}, 'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'}, 'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(OutboundRule, self).__init__(**kwargs) self.allocated_outbound_ports = kwargs.get('allocated_outbound_ports', None) self.frontend_ip_configurations = kwargs.get('frontend_ip_configurations', None) self.backend_address_pool = kwargs.get('backend_address_pool', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.protocol = kwargs.get('protocol', None) self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None) self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = None class P2SVpnGateway(Resource): """P2SVpnGateway Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param virtual_hub: The VirtualHub to which the gateway belongs. :type virtual_hub: ~azure.mgmt.network.v2019_06_01.models.SubResource :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param vpn_gateway_scale_unit: The scale unit for this p2s vpn gateway. :type vpn_gateway_scale_unit: int :param p2_svpn_server_configuration: The P2SVpnServerConfiguration to which the p2sVpnGateway is attached to. :type p2_svpn_server_configuration: ~azure.mgmt.network.v2019_06_01.models.SubResource :param vpn_client_address_pool: The reference of the address space resource which represents Address space for P2S VpnClient. :type vpn_client_address_pool: ~azure.mgmt.network.v2019_06_01.models.AddressSpace :param custom_routes: The reference of the address space resource which represents the custom routes specified by the customer for P2SVpnGateway and P2S VpnClient. :type custom_routes: ~azure.mgmt.network.v2019_06_01.models.AddressSpace :ivar vpn_client_connection_health: All P2S VPN clients' connection health status. :vartype vpn_client_connection_health: ~azure.mgmt.network.v2019_06_01.models.VpnClientConnectionHealth :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'vpn_client_connection_health': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'virtual_hub': {'key': 'properties.virtualHub', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'vpn_gateway_scale_unit': {'key': 'properties.vpnGatewayScaleUnit', 'type': 'int'}, 'p2_svpn_server_configuration': {'key': 'properties.p2SVpnServerConfiguration', 'type': 'SubResource'}, 'vpn_client_address_pool': {'key': 'properties.vpnClientAddressPool', 'type': 'AddressSpace'}, 'custom_routes': {'key': 'properties.customRoutes', 'type': 'AddressSpace'}, 'vpn_client_connection_health': {'key': 'properties.vpnClientConnectionHealth', 'type': 'VpnClientConnectionHealth'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(P2SVpnGateway, self).__init__(**kwargs) self.virtual_hub = kwargs.get('virtual_hub', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.vpn_gateway_scale_unit = kwargs.get('vpn_gateway_scale_unit', None) self.p2_svpn_server_configuration = kwargs.get('p2_svpn_server_configuration', None) self.vpn_client_address_pool = kwargs.get('vpn_client_address_pool', None) self.custom_routes = kwargs.get('custom_routes', None) self.vpn_client_connection_health = None self.etag = None class P2SVpnProfileParameters(Model): """Vpn Client Parameters for package generation. :param authentication_method: VPN client authentication method. Possible values include: 'EAPTLS', 'EAPMSCHAPv2' :type authentication_method: str or ~azure.mgmt.network.v2019_06_01.models.AuthenticationMethod """ _attribute_map = { 'authentication_method': {'key': 'authenticationMethod', 'type': 'str'}, } def __init__(self, **kwargs): super(P2SVpnProfileParameters, self).__init__(**kwargs) self.authentication_method = kwargs.get('authentication_method', None) class P2SVpnServerConfigRadiusClientRootCertificate(SubResource): """Radius client root certificate of P2SVpnServerConfiguration. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param thumbprint: The Radius client root certificate thumbprint. :type thumbprint: str :ivar provisioning_state: The provisioning state of the Radius client root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'thumbprint': {'key': 'properties.thumbprint', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(P2SVpnServerConfigRadiusClientRootCertificate, self).__init__(**kwargs) self.thumbprint = kwargs.get('thumbprint', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class P2SVpnServerConfigRadiusServerRootCertificate(SubResource): """Radius Server root certificate of P2SVpnServerConfiguration. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param public_cert_data: Required. The certificate public data. :type public_cert_data: str :ivar provisioning_state: The provisioning state of the P2SVpnServerConfiguration Radius Server root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'public_cert_data': {'required': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'public_cert_data': {'key': 'properties.publicCertData', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(P2SVpnServerConfigRadiusServerRootCertificate, self).__init__(**kwargs) self.public_cert_data = kwargs.get('public_cert_data', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class P2SVpnServerConfiguration(SubResource): """P2SVpnServerConfiguration Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param p2_svpn_server_configuration_properties_name: The name of the P2SVpnServerConfiguration that is unique within a VirtualWan in a resource group. This name can be used to access the resource along with Paren VirtualWan resource name. :type p2_svpn_server_configuration_properties_name: str :param vpn_protocols: VPN protocols for the P2SVpnServerConfiguration. :type vpn_protocols: list[str or ~azure.mgmt.network.v2019_06_01.models.VpnGatewayTunnelingProtocol] :param p2_svpn_server_config_vpn_client_root_certificates: VPN client root certificate of P2SVpnServerConfiguration. :type p2_svpn_server_config_vpn_client_root_certificates: list[~azure.mgmt.network.v2019_06_01.models.P2SVpnServerConfigVpnClientRootCertificate] :param p2_svpn_server_config_vpn_client_revoked_certificates: VPN client revoked certificate of P2SVpnServerConfiguration. :type p2_svpn_server_config_vpn_client_revoked_certificates: list[~azure.mgmt.network.v2019_06_01.models.P2SVpnServerConfigVpnClientRevokedCertificate] :param p2_svpn_server_config_radius_server_root_certificates: Radius Server root certificate of P2SVpnServerConfiguration. :type p2_svpn_server_config_radius_server_root_certificates: list[~azure.mgmt.network.v2019_06_01.models.P2SVpnServerConfigRadiusServerRootCertificate] :param p2_svpn_server_config_radius_client_root_certificates: Radius client root certificate of P2SVpnServerConfiguration. :type p2_svpn_server_config_radius_client_root_certificates: list[~azure.mgmt.network.v2019_06_01.models.P2SVpnServerConfigRadiusClientRootCertificate] :param vpn_client_ipsec_policies: VpnClientIpsecPolicies for P2SVpnServerConfiguration. :type vpn_client_ipsec_policies: list[~azure.mgmt.network.v2019_06_01.models.IpsecPolicy] :param radius_server_address: The radius server address property of the P2SVpnServerConfiguration resource for point to site client connection. :type radius_server_address: str :param radius_server_secret: The radius secret property of the P2SVpnServerConfiguration resource for point to site client connection. :type radius_server_secret: str :ivar provisioning_state: The provisioning state of the P2SVpnServerConfiguration resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :ivar p2_svpn_gateways: List of references to P2SVpnGateways. :vartype p2_svpn_gateways: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param p2_svpn_server_configuration_properties_etag: A unique read-only string that changes whenever the resource is updated. :type p2_svpn_server_configuration_properties_etag: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'provisioning_state': {'readonly': True}, 'p2_svpn_gateways': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'p2_svpn_server_configuration_properties_name': {'key': 'properties.name', 'type': 'str'}, 'vpn_protocols': {'key': 'properties.vpnProtocols', 'type': '[str]'}, 'p2_svpn_server_config_vpn_client_root_certificates': {'key': 'properties.p2SVpnServerConfigVpnClientRootCertificates', 'type': '[P2SVpnServerConfigVpnClientRootCertificate]'}, 'p2_svpn_server_config_vpn_client_revoked_certificates': {'key': 'properties.p2SVpnServerConfigVpnClientRevokedCertificates', 'type': '[P2SVpnServerConfigVpnClientRevokedCertificate]'}, 'p2_svpn_server_config_radius_server_root_certificates': {'key': 'properties.p2SVpnServerConfigRadiusServerRootCertificates', 'type': '[P2SVpnServerConfigRadiusServerRootCertificate]'}, 'p2_svpn_server_config_radius_client_root_certificates': {'key': 'properties.p2SVpnServerConfigRadiusClientRootCertificates', 'type': '[P2SVpnServerConfigRadiusClientRootCertificate]'}, 'vpn_client_ipsec_policies': {'key': 'properties.vpnClientIpsecPolicies', 'type': '[IpsecPolicy]'}, 'radius_server_address': {'key': 'properties.radiusServerAddress', 'type': 'str'}, 'radius_server_secret': {'key': 'properties.radiusServerSecret', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'p2_svpn_gateways': {'key': 'properties.p2SVpnGateways', 'type': '[SubResource]'}, 'p2_svpn_server_configuration_properties_etag': {'key': 'properties.etag', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(P2SVpnServerConfiguration, self).__init__(**kwargs) self.p2_svpn_server_configuration_properties_name = kwargs.get('p2_svpn_server_configuration_properties_name', None) self.vpn_protocols = kwargs.get('vpn_protocols', None) self.p2_svpn_server_config_vpn_client_root_certificates = kwargs.get('p2_svpn_server_config_vpn_client_root_certificates', None) self.p2_svpn_server_config_vpn_client_revoked_certificates = kwargs.get('p2_svpn_server_config_vpn_client_revoked_certificates', None) self.p2_svpn_server_config_radius_server_root_certificates = kwargs.get('p2_svpn_server_config_radius_server_root_certificates', None) self.p2_svpn_server_config_radius_client_root_certificates = kwargs.get('p2_svpn_server_config_radius_client_root_certificates', None) self.vpn_client_ipsec_policies = kwargs.get('vpn_client_ipsec_policies', None) self.radius_server_address = kwargs.get('radius_server_address', None) self.radius_server_secret = kwargs.get('radius_server_secret', None) self.provisioning_state = None self.p2_svpn_gateways = None self.p2_svpn_server_configuration_properties_etag = kwargs.get('p2_svpn_server_configuration_properties_etag', None) self.name = kwargs.get('name', None) self.etag = None class P2SVpnServerConfigVpnClientRevokedCertificate(SubResource): """VPN client revoked certificate of P2SVpnServerConfiguration. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param thumbprint: The revoked VPN client certificate thumbprint. :type thumbprint: str :ivar provisioning_state: The provisioning state of the VPN client revoked certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'thumbprint': {'key': 'properties.thumbprint', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(P2SVpnServerConfigVpnClientRevokedCertificate, self).__init__(**kwargs) self.thumbprint = kwargs.get('thumbprint', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class P2SVpnServerConfigVpnClientRootCertificate(SubResource): """VPN client root certificate of P2SVpnServerConfiguration. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param public_cert_data: Required. The certificate public data. :type public_cert_data: str :ivar provisioning_state: The provisioning state of the P2SVpnServerConfiguration VPN client root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'public_cert_data': {'required': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'public_cert_data': {'key': 'properties.publicCertData', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(P2SVpnServerConfigVpnClientRootCertificate, self).__init__(**kwargs) self.public_cert_data = kwargs.get('public_cert_data', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class PacketCapture(Model): """Parameters that define the create packet capture operation. All required parameters must be populated in order to send to Azure. :param target: Required. The ID of the targeted resource, only VM is currently supported. :type target: str :param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes are truncated. Default value: 0 . :type bytes_to_capture_per_packet: int :param total_bytes_per_session: Maximum size of the capture output. Default value: 1073741824 . :type total_bytes_per_session: int :param time_limit_in_seconds: Maximum duration of the capture session in seconds. Default value: 18000 . :type time_limit_in_seconds: int :param storage_location: Required. Describes the storage location for a packet capture session. :type storage_location: ~azure.mgmt.network.v2019_06_01.models.PacketCaptureStorageLocation :param filters: A list of packet capture filters. :type filters: list[~azure.mgmt.network.v2019_06_01.models.PacketCaptureFilter] """ _validation = { 'target': {'required': True}, 'storage_location': {'required': True}, } _attribute_map = { 'target': {'key': 'properties.target', 'type': 'str'}, 'bytes_to_capture_per_packet': {'key': 'properties.bytesToCapturePerPacket', 'type': 'int'}, 'total_bytes_per_session': {'key': 'properties.totalBytesPerSession', 'type': 'int'}, 'time_limit_in_seconds': {'key': 'properties.timeLimitInSeconds', 'type': 'int'}, 'storage_location': {'key': 'properties.storageLocation', 'type': 'PacketCaptureStorageLocation'}, 'filters': {'key': 'properties.filters', 'type': '[PacketCaptureFilter]'}, } def __init__(self, **kwargs): super(PacketCapture, self).__init__(**kwargs) self.target = kwargs.get('target', None) self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0) self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824) self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000) self.storage_location = kwargs.get('storage_location', None) self.filters = kwargs.get('filters', None) class PacketCaptureFilter(Model): """Filter that is applied to packet capture request. Multiple filters can be applied. :param protocol: Protocol to be filtered on. Possible values include: 'TCP', 'UDP', 'Any'. Default value: "Any" . :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.PcProtocol :param local_ip_address: Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5"? for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. :type local_ip_address: str :param remote_ip_address: Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. :type remote_ip_address: str :param local_port: Local port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. :type local_port: str :param remote_port: Remote port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. :type remote_port: str """ _attribute_map = { 'protocol': {'key': 'protocol', 'type': 'str'}, 'local_ip_address': {'key': 'localIPAddress', 'type': 'str'}, 'remote_ip_address': {'key': 'remoteIPAddress', 'type': 'str'}, 'local_port': {'key': 'localPort', 'type': 'str'}, 'remote_port': {'key': 'remotePort', 'type': 'str'}, } def __init__(self, **kwargs): super(PacketCaptureFilter, self).__init__(**kwargs) self.protocol = kwargs.get('protocol', "Any") self.local_ip_address = kwargs.get('local_ip_address', None) self.remote_ip_address = kwargs.get('remote_ip_address', None) self.local_port = kwargs.get('local_port', None) self.remote_port = kwargs.get('remote_port', None) class PacketCaptureParameters(Model): """Parameters that define the create packet capture operation. All required parameters must be populated in order to send to Azure. :param target: Required. The ID of the targeted resource, only VM is currently supported. :type target: str :param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes are truncated. Default value: 0 . :type bytes_to_capture_per_packet: int :param total_bytes_per_session: Maximum size of the capture output. Default value: 1073741824 . :type total_bytes_per_session: int :param time_limit_in_seconds: Maximum duration of the capture session in seconds. Default value: 18000 . :type time_limit_in_seconds: int :param storage_location: Required. Describes the storage location for a packet capture session. :type storage_location: ~azure.mgmt.network.v2019_06_01.models.PacketCaptureStorageLocation :param filters: A list of packet capture filters. :type filters: list[~azure.mgmt.network.v2019_06_01.models.PacketCaptureFilter] """ _validation = { 'target': {'required': True}, 'storage_location': {'required': True}, } _attribute_map = { 'target': {'key': 'target', 'type': 'str'}, 'bytes_to_capture_per_packet': {'key': 'bytesToCapturePerPacket', 'type': 'int'}, 'total_bytes_per_session': {'key': 'totalBytesPerSession', 'type': 'int'}, 'time_limit_in_seconds': {'key': 'timeLimitInSeconds', 'type': 'int'}, 'storage_location': {'key': 'storageLocation', 'type': 'PacketCaptureStorageLocation'}, 'filters': {'key': 'filters', 'type': '[PacketCaptureFilter]'}, } def __init__(self, **kwargs): super(PacketCaptureParameters, self).__init__(**kwargs) self.target = kwargs.get('target', None) self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0) self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824) self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000) self.storage_location = kwargs.get('storage_location', None) self.filters = kwargs.get('filters', None) class PacketCaptureQueryStatusResult(Model): """Status of packet capture session. :param name: The name of the packet capture resource. :type name: str :param id: The ID of the packet capture resource. :type id: str :param capture_start_time: The start time of the packet capture session. :type capture_start_time: datetime :param packet_capture_status: The status of the packet capture session. Possible values include: 'NotStarted', 'Running', 'Stopped', 'Error', 'Unknown' :type packet_capture_status: str or ~azure.mgmt.network.v2019_06_01.models.PcStatus :param stop_reason: The reason the current packet capture session was stopped. :type stop_reason: str :param packet_capture_error: List of errors of packet capture session. :type packet_capture_error: list[str or ~azure.mgmt.network.v2019_06_01.models.PcError] """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'capture_start_time': {'key': 'captureStartTime', 'type': 'iso-8601'}, 'packet_capture_status': {'key': 'packetCaptureStatus', 'type': 'str'}, 'stop_reason': {'key': 'stopReason', 'type': 'str'}, 'packet_capture_error': {'key': 'packetCaptureError', 'type': '[str]'}, } def __init__(self, **kwargs): super(PacketCaptureQueryStatusResult, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.id = kwargs.get('id', None) self.capture_start_time = kwargs.get('capture_start_time', None) self.packet_capture_status = kwargs.get('packet_capture_status', None) self.stop_reason = kwargs.get('stop_reason', None) self.packet_capture_error = kwargs.get('packet_capture_error', None) class PacketCaptureResult(Model): """Information about packet capture session. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar name: Name of the packet capture session. :vartype name: str :ivar id: ID of the packet capture operation. :vartype id: str :param etag: A unique read-only string that changes whenever the resource is updated. Default value: "A unique read-only string that changes whenever the resource is updated." . :type etag: str :param target: Required. The ID of the targeted resource, only VM is currently supported. :type target: str :param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes are truncated. Default value: 0 . :type bytes_to_capture_per_packet: int :param total_bytes_per_session: Maximum size of the capture output. Default value: 1073741824 . :type total_bytes_per_session: int :param time_limit_in_seconds: Maximum duration of the capture session in seconds. Default value: 18000 . :type time_limit_in_seconds: int :param storage_location: Required. Describes the storage location for a packet capture session. :type storage_location: ~azure.mgmt.network.v2019_06_01.models.PacketCaptureStorageLocation :param filters: A list of packet capture filters. :type filters: list[~azure.mgmt.network.v2019_06_01.models.PacketCaptureFilter] :param provisioning_state: The provisioning state of the packet capture session. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState """ _validation = { 'name': {'readonly': True}, 'id': {'readonly': True}, 'target': {'required': True}, 'storage_location': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'target': {'key': 'properties.target', 'type': 'str'}, 'bytes_to_capture_per_packet': {'key': 'properties.bytesToCapturePerPacket', 'type': 'int'}, 'total_bytes_per_session': {'key': 'properties.totalBytesPerSession', 'type': 'int'}, 'time_limit_in_seconds': {'key': 'properties.timeLimitInSeconds', 'type': 'int'}, 'storage_location': {'key': 'properties.storageLocation', 'type': 'PacketCaptureStorageLocation'}, 'filters': {'key': 'properties.filters', 'type': '[PacketCaptureFilter]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } def __init__(self, **kwargs): super(PacketCaptureResult, self).__init__(**kwargs) self.name = None self.id = None self.etag = kwargs.get('etag', "A unique read-only string that changes whenever the resource is updated.") self.target = kwargs.get('target', None) self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0) self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824) self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000) self.storage_location = kwargs.get('storage_location', None) self.filters = kwargs.get('filters', None) self.provisioning_state = kwargs.get('provisioning_state', None) class PacketCaptureStorageLocation(Model): """Describes the storage location for a packet capture session. :param storage_id: The ID of the storage account to save the packet capture session. Required if no local file path is provided. :type storage_id: str :param storage_path: The URI of the storage path to save the packet capture. Must be a well-formed URI describing the location to save the packet capture. :type storage_path: str :param file_path: A valid local path on the targeting VM. Must include the name of the capture file (*.cap). For linux virtual machine it must start with /var/captures. Required if no storage ID is provided, otherwise optional. :type file_path: str """ _attribute_map = { 'storage_id': {'key': 'storageId', 'type': 'str'}, 'storage_path': {'key': 'storagePath', 'type': 'str'}, 'file_path': {'key': 'filePath', 'type': 'str'}, } def __init__(self, **kwargs): super(PacketCaptureStorageLocation, self).__init__(**kwargs) self.storage_id = kwargs.get('storage_id', None) self.storage_path = kwargs.get('storage_path', None) self.file_path = kwargs.get('file_path', None) class PatchRouteFilter(SubResource): """Route Filter Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param rules: Collection of RouteFilterRules contained within a route filter. :type rules: list[~azure.mgmt.network.v2019_06_01.models.RouteFilterRule] :param peerings: A collection of references to express route circuit peerings. :type peerings: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeering] :param ipv6_peerings: A collection of references to express route circuit ipv6 peerings. :type ipv6_peerings: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeering] :ivar provisioning_state: The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', 'Succeeded' and 'Failed'. :vartype provisioning_state: str :ivar name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :vartype name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Resource type. :vartype type: str :param tags: Resource tags. :type tags: dict[str, str] """ _validation = { 'provisioning_state': {'readonly': True}, 'name': {'readonly': True}, 'etag': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'rules': {'key': 'properties.rules', 'type': '[RouteFilterRule]'}, 'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'}, 'ipv6_peerings': {'key': 'properties.ipv6Peerings', 'type': '[ExpressRouteCircuitPeering]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__(self, **kwargs): super(PatchRouteFilter, self).__init__(**kwargs) self.rules = kwargs.get('rules', None) self.peerings = kwargs.get('peerings', None) self.ipv6_peerings = kwargs.get('ipv6_peerings', None) self.provisioning_state = None self.name = None self.etag = None self.type = None self.tags = kwargs.get('tags', None) class PatchRouteFilterRule(SubResource): """Route Filter Rule Resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param access: Required. The access type of the rule. Possible values include: 'Allow', 'Deny' :type access: str or ~azure.mgmt.network.v2019_06_01.models.Access :ivar route_filter_rule_type: Required. The rule type of the rule. Default value: "Community" . :vartype route_filter_rule_type: str :param communities: Required. The collection for bgp community values to filter on. e.g. ['12076:5010','12076:5020']. :type communities: list[str] :ivar provisioning_state: The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', 'Succeeded' and 'Failed'. :vartype provisioning_state: str :ivar name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :vartype name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'access': {'required': True}, 'route_filter_rule_type': {'required': True, 'constant': True}, 'communities': {'required': True}, 'provisioning_state': {'readonly': True}, 'name': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'access': {'key': 'properties.access', 'type': 'str'}, 'route_filter_rule_type': {'key': 'properties.routeFilterRuleType', 'type': 'str'}, 'communities': {'key': 'properties.communities', 'type': '[str]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } route_filter_rule_type = "Community" def __init__(self, **kwargs): super(PatchRouteFilterRule, self).__init__(**kwargs) self.access = kwargs.get('access', None) self.communities = kwargs.get('communities', None) self.provisioning_state = None self.name = None self.etag = None class PeerExpressRouteCircuitConnection(SubResource): """Peer Express Route Circuit Connection in an ExpressRouteCircuitPeering resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param express_route_circuit_peering: Reference to Express Route Circuit Private Peering Resource of the circuit. :type express_route_circuit_peering: ~azure.mgmt.network.v2019_06_01.models.SubResource :param peer_express_route_circuit_peering: Reference to Express Route Circuit Private Peering Resource of the peered circuit. :type peer_express_route_circuit_peering: ~azure.mgmt.network.v2019_06_01.models.SubResource :param address_prefix: /29 IP address space to carve out Customer addresses for tunnels. :type address_prefix: str :param circuit_connection_status: Express Route Circuit connection state. Possible values include: 'Connected', 'Connecting', 'Disconnected' :type circuit_connection_status: str or ~azure.mgmt.network.v2019_06_01.models.CircuitConnectionStatus :param connection_name: The name of the express route circuit connection resource. :type connection_name: str :param auth_resource_guid: The resource guid of the authorization used for the express route circuit connection. :type auth_resource_guid: str :ivar provisioning_state: Provisioning state of the peer express route circuit connection resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Type of the resource. :vartype type: str """ _validation = { 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'express_route_circuit_peering': {'key': 'properties.expressRouteCircuitPeering', 'type': 'SubResource'}, 'peer_express_route_circuit_peering': {'key': 'properties.peerExpressRouteCircuitPeering', 'type': 'SubResource'}, 'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'}, 'circuit_connection_status': {'key': 'properties.circuitConnectionStatus', 'type': 'str'}, 'connection_name': {'key': 'properties.connectionName', 'type': 'str'}, 'auth_resource_guid': {'key': 'properties.authResourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(PeerExpressRouteCircuitConnection, self).__init__(**kwargs) self.express_route_circuit_peering = kwargs.get('express_route_circuit_peering', None) self.peer_express_route_circuit_peering = kwargs.get('peer_express_route_circuit_peering', None) self.address_prefix = kwargs.get('address_prefix', None) self.circuit_connection_status = kwargs.get('circuit_connection_status', None) self.connection_name = kwargs.get('connection_name', None) self.auth_resource_guid = kwargs.get('auth_resource_guid', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = None self.type = None class PolicySettings(Model): """Defines contents of a web application firewall global configuration. :param enabled_state: Describes if the policy is in enabled state or disabled state. Possible values include: 'Disabled', 'Enabled' :type enabled_state: str or ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallEnabledState :param mode: Describes if it is in detection mode or prevention mode at policy level. Possible values include: 'Prevention', 'Detection' :type mode: str or ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallMode """ _attribute_map = { 'enabled_state': {'key': 'enabledState', 'type': 'str'}, 'mode': {'key': 'mode', 'type': 'str'}, } def __init__(self, **kwargs): super(PolicySettings, self).__init__(**kwargs) self.enabled_state = kwargs.get('enabled_state', None) self.mode = kwargs.get('mode', None) class PrepareNetworkPoliciesRequest(Model): """Details of PrepareNetworkPolicies for Subnet. :param service_name: The name of the service for which subnet is being prepared for. :type service_name: str :param network_intent_policy_configurations: A list of NetworkIntentPolicyConfiguration. :type network_intent_policy_configurations: list[~azure.mgmt.network.v2019_06_01.models.NetworkIntentPolicyConfiguration] """ _attribute_map = { 'service_name': {'key': 'serviceName', 'type': 'str'}, 'network_intent_policy_configurations': {'key': 'networkIntentPolicyConfigurations', 'type': '[NetworkIntentPolicyConfiguration]'}, } def __init__(self, **kwargs): super(PrepareNetworkPoliciesRequest, self).__init__(**kwargs) self.service_name = kwargs.get('service_name', None) self.network_intent_policy_configurations = kwargs.get('network_intent_policy_configurations', None) class PrivateEndpoint(Resource): """Private endpoint resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param subnet: The ID of the subnet from which the private IP will be allocated. :type subnet: ~azure.mgmt.network.v2019_06_01.models.Subnet :ivar network_interfaces: Gets an array of references to the network interfaces created for this private endpoint. :vartype network_interfaces: list[~azure.mgmt.network.v2019_06_01.models.NetworkInterface] :ivar provisioning_state: The provisioning state of the private endpoint. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param private_link_service_connections: A grouping of information about the connection to the remote resource. :type private_link_service_connections: list[~azure.mgmt.network.v2019_06_01.models.PrivateLinkServiceConnection] :param manual_private_link_service_connections: A grouping of information about the connection to the remote resource. Used when the network admin does not have access to approve connections to the remote resource. :type manual_private_link_service_connections: list[~azure.mgmt.network.v2019_06_01.models.PrivateLinkServiceConnection] :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'network_interfaces': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'subnet': {'key': 'properties.subnet', 'type': 'Subnet'}, 'network_interfaces': {'key': 'properties.networkInterfaces', 'type': '[NetworkInterface]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'private_link_service_connections': {'key': 'properties.privateLinkServiceConnections', 'type': '[PrivateLinkServiceConnection]'}, 'manual_private_link_service_connections': {'key': 'properties.manualPrivateLinkServiceConnections', 'type': '[PrivateLinkServiceConnection]'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(PrivateEndpoint, self).__init__(**kwargs) self.subnet = kwargs.get('subnet', None) self.network_interfaces = None self.provisioning_state = None self.private_link_service_connections = kwargs.get('private_link_service_connections', None) self.manual_private_link_service_connections = kwargs.get('manual_private_link_service_connections', None) self.etag = kwargs.get('etag', None) class PrivateEndpointConnection(SubResource): """PrivateEndpointConnection resource. :param id: Resource ID. :type id: str :param private_endpoint: The resource of private end point. :type private_endpoint: ~azure.mgmt.network.v2019_06_01.models.PrivateEndpoint :param private_link_service_connection_state: A collection of information about the state of the connection between service consumer and provider. :type private_link_service_connection_state: ~azure.mgmt.network.v2019_06_01.models.PrivateLinkServiceConnectionState :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'}, 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'}, 'name': {'key': 'name', 'type': 'str'}, } def __init__(self, **kwargs): super(PrivateEndpointConnection, self).__init__(**kwargs) self.private_endpoint = kwargs.get('private_endpoint', None) self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None) self.name = kwargs.get('name', None) class PrivateLinkService(Resource): """Private link service resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param load_balancer_frontend_ip_configurations: An array of references to the load balancer IP configurations. :type load_balancer_frontend_ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.FrontendIPConfiguration] :param ip_configurations: An array of references to the private link service IP configuration. :type ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.PrivateLinkServiceIpConfiguration] :ivar network_interfaces: Gets an array of references to the network interfaces created for this private link service. :vartype network_interfaces: list[~azure.mgmt.network.v2019_06_01.models.NetworkInterface] :ivar provisioning_state: The provisioning state of the private link service. Possible values are: 'Updating', 'Succeeded', and 'Failed'. :vartype provisioning_state: str :param private_endpoint_connections: An array of list about connections to the private endpoint. :type private_endpoint_connections: list[~azure.mgmt.network.v2019_06_01.models.PrivateEndpointConnection] :param visibility: The visibility list of the private link service. :type visibility: ~azure.mgmt.network.v2019_06_01.models.PrivateLinkServicePropertiesVisibility :param auto_approval: The auto-approval list of the private link service. :type auto_approval: ~azure.mgmt.network.v2019_06_01.models.PrivateLinkServicePropertiesAutoApproval :param fqdns: The list of Fqdn. :type fqdns: list[str] :ivar alias: The alias of the private link service. :vartype alias: str :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'network_interfaces': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'alias': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'load_balancer_frontend_ip_configurations': {'key': 'properties.loadBalancerFrontendIpConfigurations', 'type': '[FrontendIPConfiguration]'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[PrivateLinkServiceIpConfiguration]'}, 'network_interfaces': {'key': 'properties.networkInterfaces', 'type': '[NetworkInterface]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'private_endpoint_connections': {'key': 'properties.privateEndpointConnections', 'type': '[PrivateEndpointConnection]'}, 'visibility': {'key': 'properties.visibility', 'type': 'PrivateLinkServicePropertiesVisibility'}, 'auto_approval': {'key': 'properties.autoApproval', 'type': 'PrivateLinkServicePropertiesAutoApproval'}, 'fqdns': {'key': 'properties.fqdns', 'type': '[str]'}, 'alias': {'key': 'properties.alias', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(PrivateLinkService, self).__init__(**kwargs) self.load_balancer_frontend_ip_configurations = kwargs.get('load_balancer_frontend_ip_configurations', None) self.ip_configurations = kwargs.get('ip_configurations', None) self.network_interfaces = None self.provisioning_state = None self.private_endpoint_connections = kwargs.get('private_endpoint_connections', None) self.visibility = kwargs.get('visibility', None) self.auto_approval = kwargs.get('auto_approval', None) self.fqdns = kwargs.get('fqdns', None) self.alias = None self.etag = kwargs.get('etag', None) class PrivateLinkServiceConnection(SubResource): """PrivateLinkServiceConnection resource. :param id: Resource ID. :type id: str :param private_link_service_id: The resource id of private link service. :type private_link_service_id: str :param group_ids: The ID(s) of the group(s) obtained from the remote resource that this private endpoint should connect to. :type group_ids: list[str] :param request_message: A message passed to the owner of the remote resource with this connection request. Restricted to 140 chars. :type request_message: str :param private_link_service_connection_state: A collection of read-only information about the state of the connection to the remote resource. :type private_link_service_connection_state: ~azure.mgmt.network.v2019_06_01.models.PrivateLinkServiceConnectionState :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'private_link_service_id': {'key': 'properties.privateLinkServiceId', 'type': 'str'}, 'group_ids': {'key': 'properties.groupIds', 'type': '[str]'}, 'request_message': {'key': 'properties.requestMessage', 'type': 'str'}, 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'}, 'name': {'key': 'name', 'type': 'str'}, } def __init__(self, **kwargs): super(PrivateLinkServiceConnection, self).__init__(**kwargs) self.private_link_service_id = kwargs.get('private_link_service_id', None) self.group_ids = kwargs.get('group_ids', None) self.request_message = kwargs.get('request_message', None) self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None) self.name = kwargs.get('name', None) class PrivateLinkServiceConnectionState(Model): """A collection of information about the state of the connection between service consumer and provider. :param status: Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. :type status: str :param description: The reason for approval/rejection of the connection. :type description: str :param action_required: A message indicating if changes on the service provider require any updates on the consumer. :type action_required: str """ _attribute_map = { 'status': {'key': 'status', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'action_required': {'key': 'actionRequired', 'type': 'str'}, } def __init__(self, **kwargs): super(PrivateLinkServiceConnectionState, self).__init__(**kwargs) self.status = kwargs.get('status', None) self.description = kwargs.get('description', None) self.action_required = kwargs.get('action_required', None) class PrivateLinkServiceIpConfiguration(Model): """The private link service ip configuration. :param private_ip_address: The private IP address of the IP configuration. :type private_ip_address: str :param private_ip_allocation_method: The private IP address allocation method. Possible values include: 'Static', 'Dynamic' :type private_ip_allocation_method: str or ~azure.mgmt.network.v2019_06_01.models.IPAllocationMethod :param subnet: The reference of the subnet resource. :type subnet: ~azure.mgmt.network.v2019_06_01.models.Subnet :param public_ip_address: The reference of the public IP resource. :type public_ip_address: ~azure.mgmt.network.v2019_06_01.models.PublicIPAddress :param provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param private_ip_address_version: Available from Api-Version 2016-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values include: 'IPv4', 'IPv6' :type private_ip_address_version: str or ~azure.mgmt.network.v2019_06_01.models.IPVersion :param name: The name of private link service ip configuration. :type name: str """ _attribute_map = { 'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'}, 'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'Subnet'}, 'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'private_ip_address_version': {'key': 'properties.privateIPAddressVersion', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, } def __init__(self, **kwargs): super(PrivateLinkServiceIpConfiguration, self).__init__(**kwargs) self.private_ip_address = kwargs.get('private_ip_address', None) self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None) self.subnet = kwargs.get('subnet', None) self.public_ip_address = kwargs.get('public_ip_address', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.private_ip_address_version = kwargs.get('private_ip_address_version', None) self.name = kwargs.get('name', None) class ResourceSet(Model): """The base resource set for visibility and auto-approval. :param subscriptions: The list of subscriptions. :type subscriptions: list[str] """ _attribute_map = { 'subscriptions': {'key': 'subscriptions', 'type': '[str]'}, } def __init__(self, **kwargs): super(ResourceSet, self).__init__(**kwargs) self.subscriptions = kwargs.get('subscriptions', None) class PrivateLinkServicePropertiesAutoApproval(ResourceSet): """The auto-approval list of the private link service. :param subscriptions: The list of subscriptions. :type subscriptions: list[str] """ _attribute_map = { 'subscriptions': {'key': 'subscriptions', 'type': '[str]'}, } def __init__(self, **kwargs): super(PrivateLinkServicePropertiesAutoApproval, self).__init__(**kwargs) class PrivateLinkServicePropertiesVisibility(ResourceSet): """The visibility list of the private link service. :param subscriptions: The list of subscriptions. :type subscriptions: list[str] """ _attribute_map = { 'subscriptions': {'key': 'subscriptions', 'type': '[str]'}, } def __init__(self, **kwargs): super(PrivateLinkServicePropertiesVisibility, self).__init__(**kwargs) class PrivateLinkServiceVisibility(Model): """Response for the CheckPrivateLinkServiceVisibility API service call. :param visible: Private Link Service Visibility (True/False). :type visible: bool """ _attribute_map = { 'visible': {'key': 'visible', 'type': 'bool'}, } def __init__(self, **kwargs): super(PrivateLinkServiceVisibility, self).__init__(**kwargs) self.visible = kwargs.get('visible', None) class Probe(SubResource): """A load balancer probe. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :ivar load_balancing_rules: The load balancer rules that use this probe. :vartype load_balancing_rules: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param protocol: Required. The protocol of the end point. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' or 'Https' is specified, a 200 OK response from the specifies URI is required for the probe to be successful. Possible values include: 'Http', 'Tcp', 'Https' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.ProbeProtocol :param port: Required. The port for communicating the probe. Possible values range from 1 to 65535, inclusive. :type port: int :param interval_in_seconds: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. :type interval_in_seconds: int :param number_of_probes: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. :type number_of_probes: int :param request_path: The URI used for requesting health status from the VM. Path is required if a protocol is set to http. Otherwise, it is not allowed. There is no default value. :type request_path: str :param provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Gets name of the resource that is unique within the set of probes used by the load balancer. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :ivar type: Type of the resource. :vartype type: str """ _validation = { 'load_balancing_rules': {'readonly': True}, 'protocol': {'required': True}, 'port': {'required': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'port': {'key': 'properties.port', 'type': 'int'}, 'interval_in_seconds': {'key': 'properties.intervalInSeconds', 'type': 'int'}, 'number_of_probes': {'key': 'properties.numberOfProbes', 'type': 'int'}, 'request_path': {'key': 'properties.requestPath', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(Probe, self).__init__(**kwargs) self.load_balancing_rules = None self.protocol = kwargs.get('protocol', None) self.port = kwargs.get('port', None) self.interval_in_seconds = kwargs.get('interval_in_seconds', None) self.number_of_probes = kwargs.get('number_of_probes', None) self.request_path = kwargs.get('request_path', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) self.type = None class ProtocolConfiguration(Model): """Configuration of the protocol. :param http_configuration: HTTP configuration of the connectivity check. :type http_configuration: ~azure.mgmt.network.v2019_06_01.models.HTTPConfiguration """ _attribute_map = { 'http_configuration': {'key': 'HTTPConfiguration', 'type': 'HTTPConfiguration'}, } def __init__(self, **kwargs): super(ProtocolConfiguration, self).__init__(**kwargs) self.http_configuration = kwargs.get('http_configuration', None) class ProtocolCustomSettingsFormat(Model): """DDoS custom policy properties. :param protocol: The protocol for which the DDoS protection policy is being customized. Possible values include: 'Tcp', 'Udp', 'Syn' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.DdosCustomPolicyProtocol :param trigger_rate_override: The customized DDoS protection trigger rate. :type trigger_rate_override: str :param source_rate_override: The customized DDoS protection source rate. :type source_rate_override: str :param trigger_sensitivity_override: The customized DDoS protection trigger rate sensitivity degrees. High: Trigger rate set with most sensitivity w.r.t. normal traffic. Default: Trigger rate set with moderate sensitivity w.r.t. normal traffic. Low: Trigger rate set with less sensitivity w.r.t. normal traffic. Relaxed: Trigger rate set with least sensitivity w.r.t. normal traffic. Possible values include: 'Relaxed', 'Low', 'Default', 'High' :type trigger_sensitivity_override: str or ~azure.mgmt.network.v2019_06_01.models.DdosCustomPolicyTriggerSensitivityOverride """ _attribute_map = { 'protocol': {'key': 'protocol', 'type': 'str'}, 'trigger_rate_override': {'key': 'triggerRateOverride', 'type': 'str'}, 'source_rate_override': {'key': 'sourceRateOverride', 'type': 'str'}, 'trigger_sensitivity_override': {'key': 'triggerSensitivityOverride', 'type': 'str'}, } def __init__(self, **kwargs): super(ProtocolCustomSettingsFormat, self).__init__(**kwargs) self.protocol = kwargs.get('protocol', None) self.trigger_rate_override = kwargs.get('trigger_rate_override', None) self.source_rate_override = kwargs.get('source_rate_override', None) self.trigger_sensitivity_override = kwargs.get('trigger_sensitivity_override', None) class PublicIPAddress(Resource): """Public IP address resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param sku: The public IP address SKU. :type sku: ~azure.mgmt.network.v2019_06_01.models.PublicIPAddressSku :param public_ip_allocation_method: The public IP address allocation method. Possible values include: 'Static', 'Dynamic' :type public_ip_allocation_method: str or ~azure.mgmt.network.v2019_06_01.models.IPAllocationMethod :param public_ip_address_version: The public IP address version. Possible values include: 'IPv4', 'IPv6' :type public_ip_address_version: str or ~azure.mgmt.network.v2019_06_01.models.IPVersion :ivar ip_configuration: The IP configuration associated with the public IP address. :vartype ip_configuration: ~azure.mgmt.network.v2019_06_01.models.IPConfiguration :param dns_settings: The FQDN of the DNS record associated with the public IP address. :type dns_settings: ~azure.mgmt.network.v2019_06_01.models.PublicIPAddressDnsSettings :param ddos_settings: The DDoS protection custom policy associated with the public IP address. :type ddos_settings: ~azure.mgmt.network.v2019_06_01.models.DdosSettings :param ip_tags: The list of tags associated with the public IP address. :type ip_tags: list[~azure.mgmt.network.v2019_06_01.models.IpTag] :param ip_address: The IP address associated with the public IP address resource. :type ip_address: str :param public_ip_prefix: The Public IP Prefix this Public IP Address should be allocated from. :type public_ip_prefix: ~azure.mgmt.network.v2019_06_01.models.SubResource :param idle_timeout_in_minutes: The idle timeout of the public IP address. :type idle_timeout_in_minutes: int :param resource_guid: The resource GUID property of the public IP resource. :type resource_guid: str :param provisioning_state: The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param zones: A list of availability zones denoting the IP allocated for the resource needs to come from. :type zones: list[str] """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'ip_configuration': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'sku': {'key': 'sku', 'type': 'PublicIPAddressSku'}, 'public_ip_allocation_method': {'key': 'properties.publicIPAllocationMethod', 'type': 'str'}, 'public_ip_address_version': {'key': 'properties.publicIPAddressVersion', 'type': 'str'}, 'ip_configuration': {'key': 'properties.ipConfiguration', 'type': 'IPConfiguration'}, 'dns_settings': {'key': 'properties.dnsSettings', 'type': 'PublicIPAddressDnsSettings'}, 'ddos_settings': {'key': 'properties.ddosSettings', 'type': 'DdosSettings'}, 'ip_tags': {'key': 'properties.ipTags', 'type': '[IpTag]'}, 'ip_address': {'key': 'properties.ipAddress', 'type': 'str'}, 'public_ip_prefix': {'key': 'properties.publicIPPrefix', 'type': 'SubResource'}, 'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'zones': {'key': 'zones', 'type': '[str]'}, } def __init__(self, **kwargs): super(PublicIPAddress, self).__init__(**kwargs) self.sku = kwargs.get('sku', None) self.public_ip_allocation_method = kwargs.get('public_ip_allocation_method', None) self.public_ip_address_version = kwargs.get('public_ip_address_version', None) self.ip_configuration = None self.dns_settings = kwargs.get('dns_settings', None) self.ddos_settings = kwargs.get('ddos_settings', None) self.ip_tags = kwargs.get('ip_tags', None) self.ip_address = kwargs.get('ip_address', None) self.public_ip_prefix = kwargs.get('public_ip_prefix', None) self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None) self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.etag = kwargs.get('etag', None) self.zones = kwargs.get('zones', None) class PublicIPAddressDnsSettings(Model): """Contains FQDN of the DNS record associated with the public IP address. :param domain_name_label: Gets or sets the Domain name label.The concatenation of the domain name label and the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. :type domain_name_label: str :param fqdn: Gets the FQDN, Fully qualified domain name of the A DNS record associated with the public IP. This is the concatenation of the domainNameLabel and the regionalized DNS zone. :type fqdn: str :param reverse_fqdn: Gets or Sets the Reverse FQDN. A user-visible, fully qualified domain name that resolves to this public IP address. If the reverseFqdn is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :type reverse_fqdn: str """ _attribute_map = { 'domain_name_label': {'key': 'domainNameLabel', 'type': 'str'}, 'fqdn': {'key': 'fqdn', 'type': 'str'}, 'reverse_fqdn': {'key': 'reverseFqdn', 'type': 'str'}, } def __init__(self, **kwargs): super(PublicIPAddressDnsSettings, self).__init__(**kwargs) self.domain_name_label = kwargs.get('domain_name_label', None) self.fqdn = kwargs.get('fqdn', None) self.reverse_fqdn = kwargs.get('reverse_fqdn', None) class PublicIPAddressSku(Model): """SKU of a public IP address. :param name: Name of a public IP address SKU. Possible values include: 'Basic', 'Standard' :type name: str or ~azure.mgmt.network.v2019_06_01.models.PublicIPAddressSkuName """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, } def __init__(self, **kwargs): super(PublicIPAddressSku, self).__init__(**kwargs) self.name = kwargs.get('name', None) class PublicIPPrefix(Resource): """Public IP prefix resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param sku: The public IP prefix SKU. :type sku: ~azure.mgmt.network.v2019_06_01.models.PublicIPPrefixSku :param public_ip_address_version: The public IP address version. Possible values include: 'IPv4', 'IPv6' :type public_ip_address_version: str or ~azure.mgmt.network.v2019_06_01.models.IPVersion :param ip_tags: The list of tags associated with the public IP prefix. :type ip_tags: list[~azure.mgmt.network.v2019_06_01.models.IpTag] :param prefix_length: The Length of the Public IP Prefix. :type prefix_length: int :param ip_prefix: The allocated Prefix. :type ip_prefix: str :param public_ip_addresses: The list of all referenced PublicIPAddresses. :type public_ip_addresses: list[~azure.mgmt.network.v2019_06_01.models.ReferencedPublicIpAddress] :param resource_guid: The resource GUID property of the public IP prefix resource. :type resource_guid: str :param provisioning_state: The provisioning state of the Public IP prefix resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param zones: A list of availability zones denoting the IP allocated for the resource needs to come from. :type zones: list[str] """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'sku': {'key': 'sku', 'type': 'PublicIPPrefixSku'}, 'public_ip_address_version': {'key': 'properties.publicIPAddressVersion', 'type': 'str'}, 'ip_tags': {'key': 'properties.ipTags', 'type': '[IpTag]'}, 'prefix_length': {'key': 'properties.prefixLength', 'type': 'int'}, 'ip_prefix': {'key': 'properties.ipPrefix', 'type': 'str'}, 'public_ip_addresses': {'key': 'properties.publicIPAddresses', 'type': '[ReferencedPublicIpAddress]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'zones': {'key': 'zones', 'type': '[str]'}, } def __init__(self, **kwargs): super(PublicIPPrefix, self).__init__(**kwargs) self.sku = kwargs.get('sku', None) self.public_ip_address_version = kwargs.get('public_ip_address_version', None) self.ip_tags = kwargs.get('ip_tags', None) self.prefix_length = kwargs.get('prefix_length', None) self.ip_prefix = kwargs.get('ip_prefix', None) self.public_ip_addresses = kwargs.get('public_ip_addresses', None) self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.etag = kwargs.get('etag', None) self.zones = kwargs.get('zones', None) class PublicIPPrefixSku(Model): """SKU of a public IP prefix. :param name: Name of a public IP prefix SKU. Possible values include: 'Standard' :type name: str or ~azure.mgmt.network.v2019_06_01.models.PublicIPPrefixSkuName """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, } def __init__(self, **kwargs): super(PublicIPPrefixSku, self).__init__(**kwargs) self.name = kwargs.get('name', None) class QueryTroubleshootingParameters(Model): """Parameters that define the resource to query the troubleshooting result. All required parameters must be populated in order to send to Azure. :param target_resource_id: Required. The target resource ID to query the troubleshooting result. :type target_resource_id: str """ _validation = { 'target_resource_id': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, } def __init__(self, **kwargs): super(QueryTroubleshootingParameters, self).__init__(**kwargs) self.target_resource_id = kwargs.get('target_resource_id', None) class ReferencedPublicIpAddress(Model): """Reference to a public IP address. :param id: The PublicIPAddress Reference. :type id: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__(self, **kwargs): super(ReferencedPublicIpAddress, self).__init__(**kwargs) self.id = kwargs.get('id', None) class ResourceNavigationLink(SubResource): """ResourceNavigationLink resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param linked_resource_type: Resource type of the linked resource. :type linked_resource_type: str :param link: Link to the external resource. :type link: str :ivar provisioning_state: Provisioning state of the ResourceNavigationLink resource. :vartype provisioning_state: str :param name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Resource type. :vartype type: str """ _validation = { 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'linked_resource_type': {'key': 'properties.linkedResourceType', 'type': 'str'}, 'link': {'key': 'properties.link', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ResourceNavigationLink, self).__init__(**kwargs) self.linked_resource_type = kwargs.get('linked_resource_type', None) self.link = kwargs.get('link', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = None self.type = None class ResourceNavigationLinksListResult(Model): """Response for ResourceNavigationLinks_List operation. Variables are only populated by the server, and will be ignored when sending a request. :param value: The resource navigation links in a subnet. :type value: list[~azure.mgmt.network.v2019_06_01.models.ResourceNavigationLink] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _validation = { 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[ResourceNavigationLink]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(self, **kwargs): super(ResourceNavigationLinksListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = None class RetentionPolicyParameters(Model): """Parameters that define the retention policy for flow log. :param days: Number of days to retain flow log records. Default value: 0 . :type days: int :param enabled: Flag to enable/disable retention. Default value: False . :type enabled: bool """ _attribute_map = { 'days': {'key': 'days', 'type': 'int'}, 'enabled': {'key': 'enabled', 'type': 'bool'}, } def __init__(self, **kwargs): super(RetentionPolicyParameters, self).__init__(**kwargs) self.days = kwargs.get('days', 0) self.enabled = kwargs.get('enabled', False) class Route(SubResource): """Route resource. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param address_prefix: The destination CIDR to which the route applies. :type address_prefix: str :param next_hop_type: Required. The type of Azure hop the packet should be sent to. Possible values include: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', 'None' :type next_hop_type: str or ~azure.mgmt.network.v2019_06_01.models.RouteNextHopType :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance. :type next_hop_ip_address: str :param provisioning_state: The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'next_hop_type': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'}, 'next_hop_type': {'key': 'properties.nextHopType', 'type': 'str'}, 'next_hop_ip_address': {'key': 'properties.nextHopIpAddress', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(Route, self).__init__(**kwargs) self.address_prefix = kwargs.get('address_prefix', None) self.next_hop_type = kwargs.get('next_hop_type', None) self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class RouteFilter(Resource): """Route Filter Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param rules: Collection of RouteFilterRules contained within a route filter. :type rules: list[~azure.mgmt.network.v2019_06_01.models.RouteFilterRule] :param peerings: A collection of references to express route circuit peerings. :type peerings: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeering] :param ipv6_peerings: A collection of references to express route circuit ipv6 peerings. :type ipv6_peerings: list[~azure.mgmt.network.v2019_06_01.models.ExpressRouteCircuitPeering] :ivar provisioning_state: The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', 'Succeeded' and 'Failed'. :vartype provisioning_state: str :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'rules': {'key': 'properties.rules', 'type': '[RouteFilterRule]'}, 'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'}, 'ipv6_peerings': {'key': 'properties.ipv6Peerings', 'type': '[ExpressRouteCircuitPeering]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(RouteFilter, self).__init__(**kwargs) self.rules = kwargs.get('rules', None) self.peerings = kwargs.get('peerings', None) self.ipv6_peerings = kwargs.get('ipv6_peerings', None) self.provisioning_state = None self.etag = None class RouteFilterRule(SubResource): """Route Filter Rule Resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param access: Required. The access type of the rule. Possible values include: 'Allow', 'Deny' :type access: str or ~azure.mgmt.network.v2019_06_01.models.Access :ivar route_filter_rule_type: Required. The rule type of the rule. Default value: "Community" . :vartype route_filter_rule_type: str :param communities: Required. The collection for bgp community values to filter on. e.g. ['12076:5010','12076:5020']. :type communities: list[str] :ivar provisioning_state: The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', 'Succeeded' and 'Failed'. :vartype provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param location: Resource location. :type location: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'access': {'required': True}, 'route_filter_rule_type': {'required': True, 'constant': True}, 'communities': {'required': True}, 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'access': {'key': 'properties.access', 'type': 'str'}, 'route_filter_rule_type': {'key': 'properties.routeFilterRuleType', 'type': 'str'}, 'communities': {'key': 'properties.communities', 'type': '[str]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } route_filter_rule_type = "Community" def __init__(self, **kwargs): super(RouteFilterRule, self).__init__(**kwargs) self.access = kwargs.get('access', None) self.communities = kwargs.get('communities', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.location = kwargs.get('location', None) self.etag = None class RouteTable(Resource): """Route table resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param routes: Collection of routes contained within a route table. :type routes: list[~azure.mgmt.network.v2019_06_01.models.Route] :ivar subnets: A collection of references to subnets. :vartype subnets: list[~azure.mgmt.network.v2019_06_01.models.Subnet] :param disable_bgp_route_propagation: Gets or sets whether to disable the routes learned by BGP on that route table. True means disable. :type disable_bgp_route_propagation: bool :param provisioning_state: The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'subnets': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'routes': {'key': 'properties.routes', 'type': '[Route]'}, 'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'}, 'disable_bgp_route_propagation': {'key': 'properties.disableBgpRoutePropagation', 'type': 'bool'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(RouteTable, self).__init__(**kwargs) self.routes = kwargs.get('routes', None) self.subnets = None self.disable_bgp_route_propagation = kwargs.get('disable_bgp_route_propagation', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.etag = kwargs.get('etag', None) class SecurityGroupNetworkInterface(Model): """Network interface and all its associated security rules. :param id: ID of the network interface. :type id: str :param security_rule_associations: All security rules associated with the network interface. :type security_rule_associations: ~azure.mgmt.network.v2019_06_01.models.SecurityRuleAssociations """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'security_rule_associations': {'key': 'securityRuleAssociations', 'type': 'SecurityRuleAssociations'}, } def __init__(self, **kwargs): super(SecurityGroupNetworkInterface, self).__init__(**kwargs) self.id = kwargs.get('id', None) self.security_rule_associations = kwargs.get('security_rule_associations', None) class SecurityGroupViewParameters(Model): """Parameters that define the VM to check security groups for. All required parameters must be populated in order to send to Azure. :param target_resource_id: Required. ID of the target VM. :type target_resource_id: str """ _validation = { 'target_resource_id': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, } def __init__(self, **kwargs): super(SecurityGroupViewParameters, self).__init__(**kwargs) self.target_resource_id = kwargs.get('target_resource_id', None) class SecurityGroupViewResult(Model): """The information about security rules applied to the specified VM. :param network_interfaces: List of network interfaces on the specified VM. :type network_interfaces: list[~azure.mgmt.network.v2019_06_01.models.SecurityGroupNetworkInterface] """ _attribute_map = { 'network_interfaces': {'key': 'networkInterfaces', 'type': '[SecurityGroupNetworkInterface]'}, } def __init__(self, **kwargs): super(SecurityGroupViewResult, self).__init__(**kwargs) self.network_interfaces = kwargs.get('network_interfaces', None) class SecurityRule(SubResource): """Network security rule. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param description: A description for this rule. Restricted to 140 chars. :type description: str :param protocol: Required. Network protocol this rule applies to. Possible values include: 'Tcp', 'Udp', 'Icmp', 'Esp', '*' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.SecurityRuleProtocol :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. :type source_port_range: str :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. :type destination_port_range: str :param source_address_prefix: The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :type source_address_prefix: str :param source_address_prefixes: The CIDR or source IP ranges. :type source_address_prefixes: list[str] :param source_application_security_groups: The application security group specified as source. :type source_application_security_groups: list[~azure.mgmt.network.v2019_06_01.models.ApplicationSecurityGroup] :param destination_address_prefix: The destination address prefix. CIDR or destination IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. :type destination_address_prefix: str :param destination_address_prefixes: The destination address prefixes. CIDR or destination IP ranges. :type destination_address_prefixes: list[str] :param destination_application_security_groups: The application security group specified as destination. :type destination_application_security_groups: list[~azure.mgmt.network.v2019_06_01.models.ApplicationSecurityGroup] :param source_port_ranges: The source port ranges. :type source_port_ranges: list[str] :param destination_port_ranges: The destination port ranges. :type destination_port_ranges: list[str] :param access: Required. The network traffic is allowed or denied. Possible values include: 'Allow', 'Deny' :type access: str or ~azure.mgmt.network.v2019_06_01.models.SecurityRuleAccess :param priority: The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule. :type priority: int :param direction: Required. The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic. Possible values include: 'Inbound', 'Outbound' :type direction: str or ~azure.mgmt.network.v2019_06_01.models.SecurityRuleDirection :param provisioning_state: The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'protocol': {'required': True}, 'access': {'required': True}, 'direction': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'description': {'key': 'properties.description', 'type': 'str'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'source_port_range': {'key': 'properties.sourcePortRange', 'type': 'str'}, 'destination_port_range': {'key': 'properties.destinationPortRange', 'type': 'str'}, 'source_address_prefix': {'key': 'properties.sourceAddressPrefix', 'type': 'str'}, 'source_address_prefixes': {'key': 'properties.sourceAddressPrefixes', 'type': '[str]'}, 'source_application_security_groups': {'key': 'properties.sourceApplicationSecurityGroups', 'type': '[ApplicationSecurityGroup]'}, 'destination_address_prefix': {'key': 'properties.destinationAddressPrefix', 'type': 'str'}, 'destination_address_prefixes': {'key': 'properties.destinationAddressPrefixes', 'type': '[str]'}, 'destination_application_security_groups': {'key': 'properties.destinationApplicationSecurityGroups', 'type': '[ApplicationSecurityGroup]'}, 'source_port_ranges': {'key': 'properties.sourcePortRanges', 'type': '[str]'}, 'destination_port_ranges': {'key': 'properties.destinationPortRanges', 'type': '[str]'}, 'access': {'key': 'properties.access', 'type': 'str'}, 'priority': {'key': 'properties.priority', 'type': 'int'}, 'direction': {'key': 'properties.direction', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(SecurityRule, self).__init__(**kwargs) self.description = kwargs.get('description', None) self.protocol = kwargs.get('protocol', None) self.source_port_range = kwargs.get('source_port_range', None) self.destination_port_range = kwargs.get('destination_port_range', None) self.source_address_prefix = kwargs.get('source_address_prefix', None) self.source_address_prefixes = kwargs.get('source_address_prefixes', None) self.source_application_security_groups = kwargs.get('source_application_security_groups', None) self.destination_address_prefix = kwargs.get('destination_address_prefix', None) self.destination_address_prefixes = kwargs.get('destination_address_prefixes', None) self.destination_application_security_groups = kwargs.get('destination_application_security_groups', None) self.source_port_ranges = kwargs.get('source_port_ranges', None) self.destination_port_ranges = kwargs.get('destination_port_ranges', None) self.access = kwargs.get('access', None) self.priority = kwargs.get('priority', None) self.direction = kwargs.get('direction', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class SecurityRuleAssociations(Model): """All security rules associated with the network interface. :param network_interface_association: Network interface and it's custom security rules. :type network_interface_association: ~azure.mgmt.network.v2019_06_01.models.NetworkInterfaceAssociation :param subnet_association: Subnet and it's custom security rules. :type subnet_association: ~azure.mgmt.network.v2019_06_01.models.SubnetAssociation :param default_security_rules: Collection of default security rules of the network security group. :type default_security_rules: list[~azure.mgmt.network.v2019_06_01.models.SecurityRule] :param effective_security_rules: Collection of effective security rules. :type effective_security_rules: list[~azure.mgmt.network.v2019_06_01.models.EffectiveNetworkSecurityRule] """ _attribute_map = { 'network_interface_association': {'key': 'networkInterfaceAssociation', 'type': 'NetworkInterfaceAssociation'}, 'subnet_association': {'key': 'subnetAssociation', 'type': 'SubnetAssociation'}, 'default_security_rules': {'key': 'defaultSecurityRules', 'type': '[SecurityRule]'}, 'effective_security_rules': {'key': 'effectiveSecurityRules', 'type': '[EffectiveNetworkSecurityRule]'}, } def __init__(self, **kwargs): super(SecurityRuleAssociations, self).__init__(**kwargs) self.network_interface_association = kwargs.get('network_interface_association', None) self.subnet_association = kwargs.get('subnet_association', None) self.default_security_rules = kwargs.get('default_security_rules', None) self.effective_security_rules = kwargs.get('effective_security_rules', None) class ServiceAssociationLink(SubResource): """ServiceAssociationLink resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param linked_resource_type: Resource type of the linked resource. :type linked_resource_type: str :param link: Link to the external resource. :type link: str :ivar provisioning_state: Provisioning state of the ServiceAssociationLink resource. :vartype provisioning_state: str :param allow_delete: If true, the resource can be deleted. :type allow_delete: bool :param locations: A list of locations. :type locations: list[str] :param name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :param type: Resource type. :type type: str """ _validation = { 'provisioning_state': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'linked_resource_type': {'key': 'properties.linkedResourceType', 'type': 'str'}, 'link': {'key': 'properties.link', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'allow_delete': {'key': 'properties.allowDelete', 'type': 'bool'}, 'locations': {'key': 'properties.locations', 'type': '[str]'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(ServiceAssociationLink, self).__init__(**kwargs) self.linked_resource_type = kwargs.get('linked_resource_type', None) self.link = kwargs.get('link', None) self.provisioning_state = None self.allow_delete = kwargs.get('allow_delete', None) self.locations = kwargs.get('locations', None) self.name = kwargs.get('name', None) self.etag = None self.type = kwargs.get('type', None) class ServiceAssociationLinksListResult(Model): """Response for ServiceAssociationLinks_List operation. Variables are only populated by the server, and will be ignored when sending a request. :param value: The service association links in a subnet. :type value: list[~azure.mgmt.network.v2019_06_01.models.ServiceAssociationLink] :ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _validation = { 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[ServiceAssociationLink]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(self, **kwargs): super(ServiceAssociationLinksListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = None class ServiceEndpointPolicy(Resource): """Service End point policy resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param service_endpoint_policy_definitions: A collection of service endpoint policy definitions of the service endpoint policy. :type service_endpoint_policy_definitions: list[~azure.mgmt.network.v2019_06_01.models.ServiceEndpointPolicyDefinition] :ivar subnets: A collection of references to subnets. :vartype subnets: list[~azure.mgmt.network.v2019_06_01.models.Subnet] :ivar resource_guid: The resource GUID property of the service endpoint policy resource. :vartype resource_guid: str :ivar provisioning_state: The provisioning state of the service endpoint policy. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'subnets': {'readonly': True}, 'resource_guid': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'service_endpoint_policy_definitions': {'key': 'properties.serviceEndpointPolicyDefinitions', 'type': '[ServiceEndpointPolicyDefinition]'}, 'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ServiceEndpointPolicy, self).__init__(**kwargs) self.service_endpoint_policy_definitions = kwargs.get('service_endpoint_policy_definitions', None) self.subnets = None self.resource_guid = None self.provisioning_state = None self.etag = kwargs.get('etag', None) class ServiceEndpointPolicyDefinition(SubResource): """Service Endpoint policy definitions. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param description: A description for this rule. Restricted to 140 chars. :type description: str :param service: Service endpoint name. :type service: str :param service_resources: A list of service resources. :type service_resources: list[str] :ivar provisioning_state: The provisioning state of the service end point policy definition. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'description': {'key': 'properties.description', 'type': 'str'}, 'service': {'key': 'properties.service', 'type': 'str'}, 'service_resources': {'key': 'properties.serviceResources', 'type': '[str]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(ServiceEndpointPolicyDefinition, self).__init__(**kwargs) self.description = kwargs.get('description', None) self.service = kwargs.get('service', None) self.service_resources = kwargs.get('service_resources', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class ServiceEndpointPropertiesFormat(Model): """The service endpoint properties. :param service: The type of the endpoint service. :type service: str :param locations: A list of locations. :type locations: list[str] :param provisioning_state: The provisioning state of the resource. :type provisioning_state: str """ _attribute_map = { 'service': {'key': 'service', 'type': 'str'}, 'locations': {'key': 'locations', 'type': '[str]'}, 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, } def __init__(self, **kwargs): super(ServiceEndpointPropertiesFormat, self).__init__(**kwargs) self.service = kwargs.get('service', None) self.locations = kwargs.get('locations', None) self.provisioning_state = kwargs.get('provisioning_state', None) class ServiceTagInformation(Model): """The service tag information. Variables are only populated by the server, and will be ignored when sending a request. :ivar properties: Properties of the service tag information. :vartype properties: ~azure.mgmt.network.v2019_06_01.models.ServiceTagInformationPropertiesFormat :ivar name: The name of service tag. :vartype name: str :ivar id: The ID of service tag. :vartype id: str """ _validation = { 'properties': {'readonly': True}, 'name': {'readonly': True}, 'id': {'readonly': True}, } _attribute_map = { 'properties': {'key': 'properties', 'type': 'ServiceTagInformationPropertiesFormat'}, 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, } def __init__(self, **kwargs): super(ServiceTagInformation, self).__init__(**kwargs) self.properties = None self.name = None self.id = None class ServiceTagInformationPropertiesFormat(Model): """Properties of the service tag information. Variables are only populated by the server, and will be ignored when sending a request. :ivar change_number: The iteration number of service tag. :vartype change_number: str :ivar region: The region of service tag. :vartype region: str :ivar system_service: The name of system service. :vartype system_service: str :ivar address_prefixes: The list of IP address prefixes. :vartype address_prefixes: list[str] """ _validation = { 'change_number': {'readonly': True}, 'region': {'readonly': True}, 'system_service': {'readonly': True}, 'address_prefixes': {'readonly': True}, } _attribute_map = { 'change_number': {'key': 'changeNumber', 'type': 'str'}, 'region': {'key': 'region', 'type': 'str'}, 'system_service': {'key': 'systemService', 'type': 'str'}, 'address_prefixes': {'key': 'addressPrefixes', 'type': '[str]'}, } def __init__(self, **kwargs): super(ServiceTagInformationPropertiesFormat, self).__init__(**kwargs) self.change_number = None self.region = None self.system_service = None self.address_prefixes = None class ServiceTagsListResult(Model): """Response for the ListServiceTags API service call. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of the cloud. :vartype name: str :ivar id: The ID of the cloud. :vartype id: str :ivar type: The azure resource type. :vartype type: str :ivar change_number: The iteration number. :vartype change_number: str :ivar cloud: The name of the cloud. :vartype cloud: str :ivar values: The list of service tag information resources. :vartype values: list[~azure.mgmt.network.v2019_06_01.models.ServiceTagInformation] """ _validation = { 'name': {'readonly': True}, 'id': {'readonly': True}, 'type': {'readonly': True}, 'change_number': {'readonly': True}, 'cloud': {'readonly': True}, 'values': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'change_number': {'key': 'changeNumber', 'type': 'str'}, 'cloud': {'key': 'cloud', 'type': 'str'}, 'values': {'key': 'values', 'type': '[ServiceTagInformation]'}, } def __init__(self, **kwargs): super(ServiceTagsListResult, self).__init__(**kwargs) self.name = None self.id = None self.type = None self.change_number = None self.cloud = None self.values = None class Subnet(SubResource): """Subnet in a virtual network resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param address_prefix: The address prefix for the subnet. :type address_prefix: str :param address_prefixes: List of address prefixes for the subnet. :type address_prefixes: list[str] :param network_security_group: The reference of the NetworkSecurityGroup resource. :type network_security_group: ~azure.mgmt.network.v2019_06_01.models.NetworkSecurityGroup :param route_table: The reference of the RouteTable resource. :type route_table: ~azure.mgmt.network.v2019_06_01.models.RouteTable :param nat_gateway: Nat gateway associated with this subnet. :type nat_gateway: ~azure.mgmt.network.v2019_06_01.models.SubResource :param service_endpoints: An array of service endpoints. :type service_endpoints: list[~azure.mgmt.network.v2019_06_01.models.ServiceEndpointPropertiesFormat] :param service_endpoint_policies: An array of service endpoint policies. :type service_endpoint_policies: list[~azure.mgmt.network.v2019_06_01.models.ServiceEndpointPolicy] :ivar private_endpoints: An array of references to private endpoints. :vartype private_endpoints: list[~azure.mgmt.network.v2019_06_01.models.PrivateEndpoint] :ivar ip_configurations: Gets an array of references to the network interface IP configurations using subnet. :vartype ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.IPConfiguration] :ivar ip_configuration_profiles: Array of IP configuration profiles which reference this subnet. :vartype ip_configuration_profiles: list[~azure.mgmt.network.v2019_06_01.models.IPConfigurationProfile] :param resource_navigation_links: Gets an array of references to the external resources using subnet. :type resource_navigation_links: list[~azure.mgmt.network.v2019_06_01.models.ResourceNavigationLink] :param service_association_links: Gets an array of references to services injecting into this subnet. :type service_association_links: list[~azure.mgmt.network.v2019_06_01.models.ServiceAssociationLink] :param delegations: Gets an array of references to the delegations on the subnet. :type delegations: list[~azure.mgmt.network.v2019_06_01.models.Delegation] :ivar purpose: A read-only string identifying the intention of use for this subnet based on delegations and other user-defined properties. :vartype purpose: str :param provisioning_state: The provisioning state of the resource. :type provisioning_state: str :param private_endpoint_network_policies: Enable or Disable apply network policies on private end point in the subnet. :type private_endpoint_network_policies: str :param private_link_service_network_policies: Enable or Disable apply network policies on private link service in the subnet. :type private_link_service_network_policies: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'private_endpoints': {'readonly': True}, 'ip_configurations': {'readonly': True}, 'ip_configuration_profiles': {'readonly': True}, 'purpose': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'}, 'address_prefixes': {'key': 'properties.addressPrefixes', 'type': '[str]'}, 'network_security_group': {'key': 'properties.networkSecurityGroup', 'type': 'NetworkSecurityGroup'}, 'route_table': {'key': 'properties.routeTable', 'type': 'RouteTable'}, 'nat_gateway': {'key': 'properties.natGateway', 'type': 'SubResource'}, 'service_endpoints': {'key': 'properties.serviceEndpoints', 'type': '[ServiceEndpointPropertiesFormat]'}, 'service_endpoint_policies': {'key': 'properties.serviceEndpointPolicies', 'type': '[ServiceEndpointPolicy]'}, 'private_endpoints': {'key': 'properties.privateEndpoints', 'type': '[PrivateEndpoint]'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[IPConfiguration]'}, 'ip_configuration_profiles': {'key': 'properties.ipConfigurationProfiles', 'type': '[IPConfigurationProfile]'}, 'resource_navigation_links': {'key': 'properties.resourceNavigationLinks', 'type': '[ResourceNavigationLink]'}, 'service_association_links': {'key': 'properties.serviceAssociationLinks', 'type': '[ServiceAssociationLink]'}, 'delegations': {'key': 'properties.delegations', 'type': '[Delegation]'}, 'purpose': {'key': 'properties.purpose', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'private_endpoint_network_policies': {'key': 'properties.privateEndpointNetworkPolicies', 'type': 'str'}, 'private_link_service_network_policies': {'key': 'properties.privateLinkServiceNetworkPolicies', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(Subnet, self).__init__(**kwargs) self.address_prefix = kwargs.get('address_prefix', None) self.address_prefixes = kwargs.get('address_prefixes', None) self.network_security_group = kwargs.get('network_security_group', None) self.route_table = kwargs.get('route_table', None) self.nat_gateway = kwargs.get('nat_gateway', None) self.service_endpoints = kwargs.get('service_endpoints', None) self.service_endpoint_policies = kwargs.get('service_endpoint_policies', None) self.private_endpoints = None self.ip_configurations = None self.ip_configuration_profiles = None self.resource_navigation_links = kwargs.get('resource_navigation_links', None) self.service_association_links = kwargs.get('service_association_links', None) self.delegations = kwargs.get('delegations', None) self.purpose = None self.provisioning_state = kwargs.get('provisioning_state', None) self.private_endpoint_network_policies = kwargs.get('private_endpoint_network_policies', None) self.private_link_service_network_policies = kwargs.get('private_link_service_network_policies', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class SubnetAssociation(Model): """Subnet and it's custom security rules. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Subnet ID. :vartype id: str :param security_rules: Collection of custom security rules. :type security_rules: list[~azure.mgmt.network.v2019_06_01.models.SecurityRule] """ _validation = { 'id': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'security_rules': {'key': 'securityRules', 'type': '[SecurityRule]'}, } def __init__(self, **kwargs): super(SubnetAssociation, self).__init__(**kwargs) self.id = None self.security_rules = kwargs.get('security_rules', None) class TagsObject(Model): """Tags object for patch operations. :param tags: Resource tags. :type tags: dict[str, str] """ _attribute_map = { 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__(self, **kwargs): super(TagsObject, self).__init__(**kwargs) self.tags = kwargs.get('tags', None) class Topology(Model): """Topology of the specified resource group. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: GUID representing the operation id. :vartype id: str :ivar created_date_time: The datetime when the topology was initially created for the resource group. :vartype created_date_time: datetime :ivar last_modified: The datetime when the topology was last modified. :vartype last_modified: datetime :param resources: A list of topology resources. :type resources: list[~azure.mgmt.network.v2019_06_01.models.TopologyResource] """ _validation = { 'id': {'readonly': True}, 'created_date_time': {'readonly': True}, 'last_modified': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'created_date_time': {'key': 'createdDateTime', 'type': 'iso-8601'}, 'last_modified': {'key': 'lastModified', 'type': 'iso-8601'}, 'resources': {'key': 'resources', 'type': '[TopologyResource]'}, } def __init__(self, **kwargs): super(Topology, self).__init__(**kwargs) self.id = None self.created_date_time = None self.last_modified = None self.resources = kwargs.get('resources', None) class TopologyAssociation(Model): """Resources that have an association with the parent resource. :param name: The name of the resource that is associated with the parent resource. :type name: str :param resource_id: The ID of the resource that is associated with the parent resource. :type resource_id: str :param association_type: The association type of the child resource to the parent resource. Possible values include: 'Associated', 'Contains' :type association_type: str or ~azure.mgmt.network.v2019_06_01.models.AssociationType """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'association_type': {'key': 'associationType', 'type': 'str'}, } def __init__(self, **kwargs): super(TopologyAssociation, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.resource_id = kwargs.get('resource_id', None) self.association_type = kwargs.get('association_type', None) class TopologyParameters(Model): """Parameters that define the representation of topology. :param target_resource_group_name: The name of the target resource group to perform topology on. :type target_resource_group_name: str :param target_virtual_network: The reference of the Virtual Network resource. :type target_virtual_network: ~azure.mgmt.network.v2019_06_01.models.SubResource :param target_subnet: The reference of the Subnet resource. :type target_subnet: ~azure.mgmt.network.v2019_06_01.models.SubResource """ _attribute_map = { 'target_resource_group_name': {'key': 'targetResourceGroupName', 'type': 'str'}, 'target_virtual_network': {'key': 'targetVirtualNetwork', 'type': 'SubResource'}, 'target_subnet': {'key': 'targetSubnet', 'type': 'SubResource'}, } def __init__(self, **kwargs): super(TopologyParameters, self).__init__(**kwargs) self.target_resource_group_name = kwargs.get('target_resource_group_name', None) self.target_virtual_network = kwargs.get('target_virtual_network', None) self.target_subnet = kwargs.get('target_subnet', None) class TopologyResource(Model): """The network resource topology information for the given resource group. :param name: Name of the resource. :type name: str :param id: ID of the resource. :type id: str :param location: Resource location. :type location: str :param associations: Holds the associations the resource has with other resources in the resource group. :type associations: list[~azure.mgmt.network.v2019_06_01.models.TopologyAssociation] """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'associations': {'key': 'associations', 'type': '[TopologyAssociation]'}, } def __init__(self, **kwargs): super(TopologyResource, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.id = kwargs.get('id', None) self.location = kwargs.get('location', None) self.associations = kwargs.get('associations', None) class TrafficAnalyticsConfigurationProperties(Model): """Parameters that define the configuration of traffic analytics. All required parameters must be populated in order to send to Azure. :param enabled: Required. Flag to enable/disable traffic analytics. :type enabled: bool :param workspace_id: Required. The resource guid of the attached workspace. :type workspace_id: str :param workspace_region: Required. The location of the attached workspace. :type workspace_region: str :param workspace_resource_id: Required. Resource Id of the attached workspace. :type workspace_resource_id: str :param traffic_analytics_interval: The interval in minutes which would decide how frequently TA service should do flow analytics. :type traffic_analytics_interval: int """ _validation = { 'enabled': {'required': True}, 'workspace_id': {'required': True}, 'workspace_region': {'required': True}, 'workspace_resource_id': {'required': True}, } _attribute_map = { 'enabled': {'key': 'enabled', 'type': 'bool'}, 'workspace_id': {'key': 'workspaceId', 'type': 'str'}, 'workspace_region': {'key': 'workspaceRegion', 'type': 'str'}, 'workspace_resource_id': {'key': 'workspaceResourceId', 'type': 'str'}, 'traffic_analytics_interval': {'key': 'trafficAnalyticsInterval', 'type': 'int'}, } def __init__(self, **kwargs): super(TrafficAnalyticsConfigurationProperties, self).__init__(**kwargs) self.enabled = kwargs.get('enabled', None) self.workspace_id = kwargs.get('workspace_id', None) self.workspace_region = kwargs.get('workspace_region', None) self.workspace_resource_id = kwargs.get('workspace_resource_id', None) self.traffic_analytics_interval = kwargs.get('traffic_analytics_interval', None) class TrafficAnalyticsProperties(Model): """Parameters that define the configuration of traffic analytics. All required parameters must be populated in order to send to Azure. :param network_watcher_flow_analytics_configuration: Required. Parameters that define the configuration of traffic analytics. :type network_watcher_flow_analytics_configuration: ~azure.mgmt.network.v2019_06_01.models.TrafficAnalyticsConfigurationProperties """ _validation = { 'network_watcher_flow_analytics_configuration': {'required': True}, } _attribute_map = { 'network_watcher_flow_analytics_configuration': {'key': 'networkWatcherFlowAnalyticsConfiguration', 'type': 'TrafficAnalyticsConfigurationProperties'}, } def __init__(self, **kwargs): super(TrafficAnalyticsProperties, self).__init__(**kwargs) self.network_watcher_flow_analytics_configuration = kwargs.get('network_watcher_flow_analytics_configuration', None) class TroubleshootingDetails(Model): """Information gained from troubleshooting of specified resource. :param id: The id of the get troubleshoot operation. :type id: str :param reason_type: Reason type of failure. :type reason_type: str :param summary: A summary of troubleshooting. :type summary: str :param detail: Details on troubleshooting results. :type detail: str :param recommended_actions: List of recommended actions. :type recommended_actions: list[~azure.mgmt.network.v2019_06_01.models.TroubleshootingRecommendedActions] """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'reason_type': {'key': 'reasonType', 'type': 'str'}, 'summary': {'key': 'summary', 'type': 'str'}, 'detail': {'key': 'detail', 'type': 'str'}, 'recommended_actions': {'key': 'recommendedActions', 'type': '[TroubleshootingRecommendedActions]'}, } def __init__(self, **kwargs): super(TroubleshootingDetails, self).__init__(**kwargs) self.id = kwargs.get('id', None) self.reason_type = kwargs.get('reason_type', None) self.summary = kwargs.get('summary', None) self.detail = kwargs.get('detail', None) self.recommended_actions = kwargs.get('recommended_actions', None) class TroubleshootingParameters(Model): """Parameters that define the resource to troubleshoot. All required parameters must be populated in order to send to Azure. :param target_resource_id: Required. The target resource to troubleshoot. :type target_resource_id: str :param storage_id: Required. The ID for the storage account to save the troubleshoot result. :type storage_id: str :param storage_path: Required. The path to the blob to save the troubleshoot result in. :type storage_path: str """ _validation = { 'target_resource_id': {'required': True}, 'storage_id': {'required': True}, 'storage_path': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, 'storage_id': {'key': 'properties.storageId', 'type': 'str'}, 'storage_path': {'key': 'properties.storagePath', 'type': 'str'}, } def __init__(self, **kwargs): super(TroubleshootingParameters, self).__init__(**kwargs) self.target_resource_id = kwargs.get('target_resource_id', None) self.storage_id = kwargs.get('storage_id', None) self.storage_path = kwargs.get('storage_path', None) class TroubleshootingRecommendedActions(Model): """Recommended actions based on discovered issues. :param action_id: ID of the recommended action. :type action_id: str :param action_text: Description of recommended actions. :type action_text: str :param action_uri: The uri linking to a documentation for the recommended troubleshooting actions. :type action_uri: str :param action_uri_text: The information from the URI for the recommended troubleshooting actions. :type action_uri_text: str """ _attribute_map = { 'action_id': {'key': 'actionId', 'type': 'str'}, 'action_text': {'key': 'actionText', 'type': 'str'}, 'action_uri': {'key': 'actionUri', 'type': 'str'}, 'action_uri_text': {'key': 'actionUriText', 'type': 'str'}, } def __init__(self, **kwargs): super(TroubleshootingRecommendedActions, self).__init__(**kwargs) self.action_id = kwargs.get('action_id', None) self.action_text = kwargs.get('action_text', None) self.action_uri = kwargs.get('action_uri', None) self.action_uri_text = kwargs.get('action_uri_text', None) class TroubleshootingResult(Model): """Troubleshooting information gained from specified resource. :param start_time: The start time of the troubleshooting. :type start_time: datetime :param end_time: The end time of the troubleshooting. :type end_time: datetime :param code: The result code of the troubleshooting. :type code: str :param results: Information from troubleshooting. :type results: list[~azure.mgmt.network.v2019_06_01.models.TroubleshootingDetails] """ _attribute_map = { 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, 'code': {'key': 'code', 'type': 'str'}, 'results': {'key': 'results', 'type': '[TroubleshootingDetails]'}, } def __init__(self, **kwargs): super(TroubleshootingResult, self).__init__(**kwargs) self.start_time = kwargs.get('start_time', None) self.end_time = kwargs.get('end_time', None) self.code = kwargs.get('code', None) self.results = kwargs.get('results', None) class TunnelConnectionHealth(Model): """VirtualNetworkGatewayConnection properties. Variables are only populated by the server, and will be ignored when sending a request. :ivar tunnel: Tunnel name. :vartype tunnel: str :ivar connection_status: Virtual Network Gateway connection status. Possible values include: 'Unknown', 'Connecting', 'Connected', 'NotConnected' :vartype connection_status: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayConnectionStatus :ivar ingress_bytes_transferred: The Ingress Bytes Transferred in this connection. :vartype ingress_bytes_transferred: long :ivar egress_bytes_transferred: The Egress Bytes Transferred in this connection. :vartype egress_bytes_transferred: long :ivar last_connection_established_utc_time: The time at which connection was established in Utc format. :vartype last_connection_established_utc_time: str """ _validation = { 'tunnel': {'readonly': True}, 'connection_status': {'readonly': True}, 'ingress_bytes_transferred': {'readonly': True}, 'egress_bytes_transferred': {'readonly': True}, 'last_connection_established_utc_time': {'readonly': True}, } _attribute_map = { 'tunnel': {'key': 'tunnel', 'type': 'str'}, 'connection_status': {'key': 'connectionStatus', 'type': 'str'}, 'ingress_bytes_transferred': {'key': 'ingressBytesTransferred', 'type': 'long'}, 'egress_bytes_transferred': {'key': 'egressBytesTransferred', 'type': 'long'}, 'last_connection_established_utc_time': {'key': 'lastConnectionEstablishedUtcTime', 'type': 'str'}, } def __init__(self, **kwargs): super(TunnelConnectionHealth, self).__init__(**kwargs) self.tunnel = None self.connection_status = None self.ingress_bytes_transferred = None self.egress_bytes_transferred = None self.last_connection_established_utc_time = None class Usage(Model): """Describes network resource usage. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Resource identifier. :vartype id: str :ivar unit: Required. An enum describing the unit of measurement. Default value: "Count" . :vartype unit: str :param current_value: Required. The current value of the usage. :type current_value: long :param limit: Required. The limit of usage. :type limit: long :param name: Required. The name of the type of usage. :type name: ~azure.mgmt.network.v2019_06_01.models.UsageName """ _validation = { 'id': {'readonly': True}, 'unit': {'required': True, 'constant': True}, 'current_value': {'required': True}, 'limit': {'required': True}, 'name': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'unit': {'key': 'unit', 'type': 'str'}, 'current_value': {'key': 'currentValue', 'type': 'long'}, 'limit': {'key': 'limit', 'type': 'long'}, 'name': {'key': 'name', 'type': 'UsageName'}, } unit = "Count" def __init__(self, **kwargs): super(Usage, self).__init__(**kwargs) self.id = None self.current_value = kwargs.get('current_value', None) self.limit = kwargs.get('limit', None) self.name = kwargs.get('name', None) class UsageName(Model): """The usage names. :param value: A string describing the resource name. :type value: str :param localized_value: A localized string describing the resource name. :type localized_value: str """ _attribute_map = { 'value': {'key': 'value', 'type': 'str'}, 'localized_value': {'key': 'localizedValue', 'type': 'str'}, } def __init__(self, **kwargs): super(UsageName, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.localized_value = kwargs.get('localized_value', None) class VerificationIPFlowParameters(Model): """Parameters that define the IP flow to be verified. All required parameters must be populated in order to send to Azure. :param target_resource_id: Required. The ID of the target resource to perform next-hop on. :type target_resource_id: str :param direction: Required. The direction of the packet represented as a 5-tuple. Possible values include: 'Inbound', 'Outbound' :type direction: str or ~azure.mgmt.network.v2019_06_01.models.Direction :param protocol: Required. Protocol to be verified on. Possible values include: 'TCP', 'UDP' :type protocol: str or ~azure.mgmt.network.v2019_06_01.models.IpFlowProtocol :param local_port: Required. The local port. Acceptable values are a single integer in the range (0-65535). Support for * for the source port, which depends on the direction. :type local_port: str :param remote_port: Required. The remote port. Acceptable values are a single integer in the range (0-65535). Support for * for the source port, which depends on the direction. :type remote_port: str :param local_ip_address: Required. The local IP address. Acceptable values are valid IPv4 addresses. :type local_ip_address: str :param remote_ip_address: Required. The remote IP address. Acceptable values are valid IPv4 addresses. :type remote_ip_address: str :param target_nic_resource_id: The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of them, then this parameter must be specified. Otherwise optional). :type target_nic_resource_id: str """ _validation = { 'target_resource_id': {'required': True}, 'direction': {'required': True}, 'protocol': {'required': True}, 'local_port': {'required': True}, 'remote_port': {'required': True}, 'local_ip_address': {'required': True}, 'remote_ip_address': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, 'direction': {'key': 'direction', 'type': 'str'}, 'protocol': {'key': 'protocol', 'type': 'str'}, 'local_port': {'key': 'localPort', 'type': 'str'}, 'remote_port': {'key': 'remotePort', 'type': 'str'}, 'local_ip_address': {'key': 'localIPAddress', 'type': 'str'}, 'remote_ip_address': {'key': 'remoteIPAddress', 'type': 'str'}, 'target_nic_resource_id': {'key': 'targetNicResourceId', 'type': 'str'}, } def __init__(self, **kwargs): super(VerificationIPFlowParameters, self).__init__(**kwargs) self.target_resource_id = kwargs.get('target_resource_id', None) self.direction = kwargs.get('direction', None) self.protocol = kwargs.get('protocol', None) self.local_port = kwargs.get('local_port', None) self.remote_port = kwargs.get('remote_port', None) self.local_ip_address = kwargs.get('local_ip_address', None) self.remote_ip_address = kwargs.get('remote_ip_address', None) self.target_nic_resource_id = kwargs.get('target_nic_resource_id', None) class VerificationIPFlowResult(Model): """Results of IP flow verification on the target resource. :param access: Indicates whether the traffic is allowed or denied. Possible values include: 'Allow', 'Deny' :type access: str or ~azure.mgmt.network.v2019_06_01.models.Access :param rule_name: Name of the rule. If input is not matched against any security rule, it is not displayed. :type rule_name: str """ _attribute_map = { 'access': {'key': 'access', 'type': 'str'}, 'rule_name': {'key': 'ruleName', 'type': 'str'}, } def __init__(self, **kwargs): super(VerificationIPFlowResult, self).__init__(**kwargs) self.access = kwargs.get('access', None) self.rule_name = kwargs.get('rule_name', None) class VirtualHub(Resource): """VirtualHub Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param virtual_wan: The VirtualWAN to which the VirtualHub belongs. :type virtual_wan: ~azure.mgmt.network.v2019_06_01.models.SubResource :param vpn_gateway: The VpnGateway associated with this VirtualHub. :type vpn_gateway: ~azure.mgmt.network.v2019_06_01.models.SubResource :param p2_svpn_gateway: The P2SVpnGateway associated with this VirtualHub. :type p2_svpn_gateway: ~azure.mgmt.network.v2019_06_01.models.SubResource :param express_route_gateway: The expressRouteGateway associated with this VirtualHub. :type express_route_gateway: ~azure.mgmt.network.v2019_06_01.models.SubResource :param virtual_network_connections: List of all vnet connections with this VirtualHub. :type virtual_network_connections: list[~azure.mgmt.network.v2019_06_01.models.HubVirtualNetworkConnection] :param address_prefix: Address-prefix for this VirtualHub. :type address_prefix: str :param route_table: The routeTable associated with this virtual hub. :type route_table: ~azure.mgmt.network.v2019_06_01.models.VirtualHubRouteTable :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'virtual_wan': {'key': 'properties.virtualWan', 'type': 'SubResource'}, 'vpn_gateway': {'key': 'properties.vpnGateway', 'type': 'SubResource'}, 'p2_svpn_gateway': {'key': 'properties.p2SVpnGateway', 'type': 'SubResource'}, 'express_route_gateway': {'key': 'properties.expressRouteGateway', 'type': 'SubResource'}, 'virtual_network_connections': {'key': 'properties.virtualNetworkConnections', 'type': '[HubVirtualNetworkConnection]'}, 'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'}, 'route_table': {'key': 'properties.routeTable', 'type': 'VirtualHubRouteTable'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualHub, self).__init__(**kwargs) self.virtual_wan = kwargs.get('virtual_wan', None) self.vpn_gateway = kwargs.get('vpn_gateway', None) self.p2_svpn_gateway = kwargs.get('p2_svpn_gateway', None) self.express_route_gateway = kwargs.get('express_route_gateway', None) self.virtual_network_connections = kwargs.get('virtual_network_connections', None) self.address_prefix = kwargs.get('address_prefix', None) self.route_table = kwargs.get('route_table', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.etag = None class VirtualHubId(Model): """Virtual Hub identifier. :param id: The resource URI for the Virtual Hub where the ExpressRoute gateway is or will be deployed. The Virtual Hub resource and the ExpressRoute gateway resource reside in the same subscription. :type id: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualHubId, self).__init__(**kwargs) self.id = kwargs.get('id', None) class VirtualHubRoute(Model): """VirtualHub route. :param address_prefixes: List of all addressPrefixes. :type address_prefixes: list[str] :param next_hop_ip_address: NextHop ip address. :type next_hop_ip_address: str """ _attribute_map = { 'address_prefixes': {'key': 'addressPrefixes', 'type': '[str]'}, 'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualHubRoute, self).__init__(**kwargs) self.address_prefixes = kwargs.get('address_prefixes', None) self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None) class VirtualHubRouteTable(Model): """VirtualHub route table. :param routes: List of all routes. :type routes: list[~azure.mgmt.network.v2019_06_01.models.VirtualHubRoute] """ _attribute_map = { 'routes': {'key': 'routes', 'type': '[VirtualHubRoute]'}, } def __init__(self, **kwargs): super(VirtualHubRouteTable, self).__init__(**kwargs) self.routes = kwargs.get('routes', None) class VirtualNetwork(Resource): """Virtual Network resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param address_space: The AddressSpace that contains an array of IP address ranges that can be used by subnets. :type address_space: ~azure.mgmt.network.v2019_06_01.models.AddressSpace :param dhcp_options: The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network. :type dhcp_options: ~azure.mgmt.network.v2019_06_01.models.DhcpOptions :param subnets: A list of subnets in a Virtual Network. :type subnets: list[~azure.mgmt.network.v2019_06_01.models.Subnet] :param virtual_network_peerings: A list of peerings in a Virtual Network. :type virtual_network_peerings: list[~azure.mgmt.network.v2019_06_01.models.VirtualNetworkPeering] :param resource_guid: The resourceGuid property of the Virtual Network resource. :type resource_guid: str :param provisioning_state: The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param enable_ddos_protection: Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection plan associated with the resource. Default value: False . :type enable_ddos_protection: bool :param enable_vm_protection: Indicates if VM protection is enabled for all the subnets in the virtual network. Default value: False . :type enable_vm_protection: bool :param ddos_protection_plan: The DDoS protection plan associated with the virtual network. :type ddos_protection_plan: ~azure.mgmt.network.v2019_06_01.models.SubResource :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'address_space': {'key': 'properties.addressSpace', 'type': 'AddressSpace'}, 'dhcp_options': {'key': 'properties.dhcpOptions', 'type': 'DhcpOptions'}, 'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'}, 'virtual_network_peerings': {'key': 'properties.virtualNetworkPeerings', 'type': '[VirtualNetworkPeering]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'enable_ddos_protection': {'key': 'properties.enableDdosProtection', 'type': 'bool'}, 'enable_vm_protection': {'key': 'properties.enableVmProtection', 'type': 'bool'}, 'ddos_protection_plan': {'key': 'properties.ddosProtectionPlan', 'type': 'SubResource'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetwork, self).__init__(**kwargs) self.address_space = kwargs.get('address_space', None) self.dhcp_options = kwargs.get('dhcp_options', None) self.subnets = kwargs.get('subnets', None) self.virtual_network_peerings = kwargs.get('virtual_network_peerings', None) self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.enable_ddos_protection = kwargs.get('enable_ddos_protection', False) self.enable_vm_protection = kwargs.get('enable_vm_protection', False) self.ddos_protection_plan = kwargs.get('ddos_protection_plan', None) self.etag = kwargs.get('etag', None) class VirtualNetworkConnectionGatewayReference(Model): """A reference to VirtualNetworkGateway or LocalNetworkGateway resource. All required parameters must be populated in order to send to Azure. :param id: Required. The ID of VirtualNetworkGateway or LocalNetworkGateway resource. :type id: str """ _validation = { 'id': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkConnectionGatewayReference, self).__init__(**kwargs) self.id = kwargs.get('id', None) class VirtualNetworkGateway(Resource): """A common class for general resource information. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param ip_configurations: IP configurations for virtual network gateway. :type ip_configurations: list[~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayIPConfiguration] :param gateway_type: The type of this virtual network gateway. Possible values include: 'Vpn', 'ExpressRoute' :type gateway_type: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayType :param vpn_type: The type of this virtual network gateway. Possible values include: 'PolicyBased', 'RouteBased' :type vpn_type: str or ~azure.mgmt.network.v2019_06_01.models.VpnType :param enable_bgp: Whether BGP is enabled for this virtual network gateway or not. :type enable_bgp: bool :param active_active: ActiveActive flag. :type active_active: bool :param gateway_default_site: The reference of the LocalNetworkGateway resource which represents local network site having default routes. Assign Null value in case of removing existing default site setting. :type gateway_default_site: ~azure.mgmt.network.v2019_06_01.models.SubResource :param sku: The reference of the VirtualNetworkGatewaySku resource which represents the SKU selected for Virtual network gateway. :type sku: ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewaySku :param vpn_client_configuration: The reference of the VpnClientConfiguration resource which represents the P2S VpnClient configurations. :type vpn_client_configuration: ~azure.mgmt.network.v2019_06_01.models.VpnClientConfiguration :param bgp_settings: Virtual network gateway's BGP speaker settings. :type bgp_settings: ~azure.mgmt.network.v2019_06_01.models.BgpSettings :param custom_routes: The reference of the address space resource which represents the custom routes address space specified by the customer for virtual network gateway and VpnClient. :type custom_routes: ~azure.mgmt.network.v2019_06_01.models.AddressSpace :param resource_guid: The resource GUID property of the VirtualNetworkGateway resource. :type resource_guid: str :ivar provisioning_state: The provisioning state of the VirtualNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[VirtualNetworkGatewayIPConfiguration]'}, 'gateway_type': {'key': 'properties.gatewayType', 'type': 'str'}, 'vpn_type': {'key': 'properties.vpnType', 'type': 'str'}, 'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'}, 'active_active': {'key': 'properties.activeActive', 'type': 'bool'}, 'gateway_default_site': {'key': 'properties.gatewayDefaultSite', 'type': 'SubResource'}, 'sku': {'key': 'properties.sku', 'type': 'VirtualNetworkGatewaySku'}, 'vpn_client_configuration': {'key': 'properties.vpnClientConfiguration', 'type': 'VpnClientConfiguration'}, 'bgp_settings': {'key': 'properties.bgpSettings', 'type': 'BgpSettings'}, 'custom_routes': {'key': 'properties.customRoutes', 'type': 'AddressSpace'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkGateway, self).__init__(**kwargs) self.ip_configurations = kwargs.get('ip_configurations', None) self.gateway_type = kwargs.get('gateway_type', None) self.vpn_type = kwargs.get('vpn_type', None) self.enable_bgp = kwargs.get('enable_bgp', None) self.active_active = kwargs.get('active_active', None) self.gateway_default_site = kwargs.get('gateway_default_site', None) self.sku = kwargs.get('sku', None) self.vpn_client_configuration = kwargs.get('vpn_client_configuration', None) self.bgp_settings = kwargs.get('bgp_settings', None) self.custom_routes = kwargs.get('custom_routes', None) self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = None self.etag = kwargs.get('etag', None) class VirtualNetworkGatewayConnection(Resource): """A common class for general resource information. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param authorization_key: The authorizationKey. :type authorization_key: str :param virtual_network_gateway1: Required. The reference to virtual network gateway resource. :type virtual_network_gateway1: ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGateway :param virtual_network_gateway2: The reference to virtual network gateway resource. :type virtual_network_gateway2: ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGateway :param local_network_gateway2: The reference to local network gateway resource. :type local_network_gateway2: ~azure.mgmt.network.v2019_06_01.models.LocalNetworkGateway :param connection_type: Required. Gateway connection type. Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient' :type connection_type: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayConnectionType :param connection_protocol: Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' :type connection_protocol: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayConnectionProtocol :param routing_weight: The routing weight. :type routing_weight: int :param shared_key: The IPSec shared key. :type shared_key: str :ivar connection_status: Virtual Network Gateway connection status. Possible values include: 'Unknown', 'Connecting', 'Connected', 'NotConnected' :vartype connection_status: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayConnectionStatus :ivar tunnel_connection_status: Collection of all tunnels' connection health status. :vartype tunnel_connection_status: list[~azure.mgmt.network.v2019_06_01.models.TunnelConnectionHealth] :ivar egress_bytes_transferred: The egress bytes transferred in this connection. :vartype egress_bytes_transferred: long :ivar ingress_bytes_transferred: The ingress bytes transferred in this connection. :vartype ingress_bytes_transferred: long :param peer: The reference to peerings resource. :type peer: ~azure.mgmt.network.v2019_06_01.models.SubResource :param enable_bgp: EnableBgp flag. :type enable_bgp: bool :param use_policy_based_traffic_selectors: Enable policy-based traffic selectors. :type use_policy_based_traffic_selectors: bool :param ipsec_policies: The IPSec Policies to be considered by this connection. :type ipsec_policies: list[~azure.mgmt.network.v2019_06_01.models.IpsecPolicy] :param resource_guid: The resource GUID property of the VirtualNetworkGatewayConnection resource. :type resource_guid: str :ivar provisioning_state: The provisioning state of the VirtualNetworkGatewayConnection resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param express_route_gateway_bypass: Bypass ExpressRoute Gateway for data forwarding. :type express_route_gateway_bypass: bool :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'virtual_network_gateway1': {'required': True}, 'connection_type': {'required': True}, 'connection_status': {'readonly': True}, 'tunnel_connection_status': {'readonly': True}, 'egress_bytes_transferred': {'readonly': True}, 'ingress_bytes_transferred': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'}, 'virtual_network_gateway1': {'key': 'properties.virtualNetworkGateway1', 'type': 'VirtualNetworkGateway'}, 'virtual_network_gateway2': {'key': 'properties.virtualNetworkGateway2', 'type': 'VirtualNetworkGateway'}, 'local_network_gateway2': {'key': 'properties.localNetworkGateway2', 'type': 'LocalNetworkGateway'}, 'connection_type': {'key': 'properties.connectionType', 'type': 'str'}, 'connection_protocol': {'key': 'properties.connectionProtocol', 'type': 'str'}, 'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'}, 'shared_key': {'key': 'properties.sharedKey', 'type': 'str'}, 'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'}, 'tunnel_connection_status': {'key': 'properties.tunnelConnectionStatus', 'type': '[TunnelConnectionHealth]'}, 'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'}, 'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'}, 'peer': {'key': 'properties.peer', 'type': 'SubResource'}, 'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'}, 'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'}, 'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'express_route_gateway_bypass': {'key': 'properties.expressRouteGatewayBypass', 'type': 'bool'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkGatewayConnection, self).__init__(**kwargs) self.authorization_key = kwargs.get('authorization_key', None) self.virtual_network_gateway1 = kwargs.get('virtual_network_gateway1', None) self.virtual_network_gateway2 = kwargs.get('virtual_network_gateway2', None) self.local_network_gateway2 = kwargs.get('local_network_gateway2', None) self.connection_type = kwargs.get('connection_type', None) self.connection_protocol = kwargs.get('connection_protocol', None) self.routing_weight = kwargs.get('routing_weight', None) self.shared_key = kwargs.get('shared_key', None) self.connection_status = None self.tunnel_connection_status = None self.egress_bytes_transferred = None self.ingress_bytes_transferred = None self.peer = kwargs.get('peer', None) self.enable_bgp = kwargs.get('enable_bgp', None) self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None) self.ipsec_policies = kwargs.get('ipsec_policies', None) self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = None self.express_route_gateway_bypass = kwargs.get('express_route_gateway_bypass', None) self.etag = kwargs.get('etag', None) class VirtualNetworkGatewayConnectionListEntity(Resource): """A common class for general resource information. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param authorization_key: The authorizationKey. :type authorization_key: str :param virtual_network_gateway1: Required. The reference to virtual network gateway resource. :type virtual_network_gateway1: ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkConnectionGatewayReference :param virtual_network_gateway2: The reference to virtual network gateway resource. :type virtual_network_gateway2: ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkConnectionGatewayReference :param local_network_gateway2: The reference to local network gateway resource. :type local_network_gateway2: ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkConnectionGatewayReference :param connection_type: Required. Gateway connection type. Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient' :type connection_type: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayConnectionType :param connection_protocol: Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' :type connection_protocol: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayConnectionProtocol :param routing_weight: The routing weight. :type routing_weight: int :param shared_key: The IPSec shared key. :type shared_key: str :ivar connection_status: Virtual Network Gateway connection status. Possible values include: 'Unknown', 'Connecting', 'Connected', 'NotConnected' :vartype connection_status: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayConnectionStatus :ivar tunnel_connection_status: Collection of all tunnels' connection health status. :vartype tunnel_connection_status: list[~azure.mgmt.network.v2019_06_01.models.TunnelConnectionHealth] :ivar egress_bytes_transferred: The egress bytes transferred in this connection. :vartype egress_bytes_transferred: long :ivar ingress_bytes_transferred: The ingress bytes transferred in this connection. :vartype ingress_bytes_transferred: long :param peer: The reference to peerings resource. :type peer: ~azure.mgmt.network.v2019_06_01.models.SubResource :param enable_bgp: EnableBgp flag. :type enable_bgp: bool :param use_policy_based_traffic_selectors: Enable policy-based traffic selectors. :type use_policy_based_traffic_selectors: bool :param ipsec_policies: The IPSec Policies to be considered by this connection. :type ipsec_policies: list[~azure.mgmt.network.v2019_06_01.models.IpsecPolicy] :param resource_guid: The resource GUID property of the VirtualNetworkGatewayConnection resource. :type resource_guid: str :ivar provisioning_state: The provisioning state of the VirtualNetworkGatewayConnection resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param express_route_gateway_bypass: Bypass ExpressRoute Gateway for data forwarding. :type express_route_gateway_bypass: bool :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'virtual_network_gateway1': {'required': True}, 'connection_type': {'required': True}, 'connection_status': {'readonly': True}, 'tunnel_connection_status': {'readonly': True}, 'egress_bytes_transferred': {'readonly': True}, 'ingress_bytes_transferred': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'}, 'virtual_network_gateway1': {'key': 'properties.virtualNetworkGateway1', 'type': 'VirtualNetworkConnectionGatewayReference'}, 'virtual_network_gateway2': {'key': 'properties.virtualNetworkGateway2', 'type': 'VirtualNetworkConnectionGatewayReference'}, 'local_network_gateway2': {'key': 'properties.localNetworkGateway2', 'type': 'VirtualNetworkConnectionGatewayReference'}, 'connection_type': {'key': 'properties.connectionType', 'type': 'str'}, 'connection_protocol': {'key': 'properties.connectionProtocol', 'type': 'str'}, 'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'}, 'shared_key': {'key': 'properties.sharedKey', 'type': 'str'}, 'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'}, 'tunnel_connection_status': {'key': 'properties.tunnelConnectionStatus', 'type': '[TunnelConnectionHealth]'}, 'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'}, 'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'}, 'peer': {'key': 'properties.peer', 'type': 'SubResource'}, 'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'}, 'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'}, 'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'express_route_gateway_bypass': {'key': 'properties.expressRouteGatewayBypass', 'type': 'bool'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkGatewayConnectionListEntity, self).__init__(**kwargs) self.authorization_key = kwargs.get('authorization_key', None) self.virtual_network_gateway1 = kwargs.get('virtual_network_gateway1', None) self.virtual_network_gateway2 = kwargs.get('virtual_network_gateway2', None) self.local_network_gateway2 = kwargs.get('local_network_gateway2', None) self.connection_type = kwargs.get('connection_type', None) self.connection_protocol = kwargs.get('connection_protocol', None) self.routing_weight = kwargs.get('routing_weight', None) self.shared_key = kwargs.get('shared_key', None) self.connection_status = None self.tunnel_connection_status = None self.egress_bytes_transferred = None self.ingress_bytes_transferred = None self.peer = kwargs.get('peer', None) self.enable_bgp = kwargs.get('enable_bgp', None) self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None) self.ipsec_policies = kwargs.get('ipsec_policies', None) self.resource_guid = kwargs.get('resource_guid', None) self.provisioning_state = None self.express_route_gateway_bypass = kwargs.get('express_route_gateway_bypass', None) self.etag = kwargs.get('etag', None) class VirtualNetworkGatewayIPConfiguration(SubResource): """IP configuration for virtual network gateway. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param private_ip_allocation_method: The private IP address allocation method. Possible values include: 'Static', 'Dynamic' :type private_ip_allocation_method: str or ~azure.mgmt.network.v2019_06_01.models.IPAllocationMethod :param subnet: The reference of the subnet resource. :type subnet: ~azure.mgmt.network.v2019_06_01.models.SubResource :param public_ip_address: The reference of the public IP resource. :type public_ip_address: ~azure.mgmt.network.v2019_06_01.models.SubResource :ivar provisioning_state: The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'SubResource'}, 'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkGatewayIPConfiguration, self).__init__(**kwargs) self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None) self.subnet = kwargs.get('subnet', None) self.public_ip_address = kwargs.get('public_ip_address', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class VirtualNetworkGatewaySku(Model): """VirtualNetworkGatewaySku details. :param name: Gateway SKU name. Possible values include: 'Basic', 'HighPerformance', 'Standard', 'UltraPerformance', 'VpnGw1', 'VpnGw2', 'VpnGw3', 'VpnGw1AZ', 'VpnGw2AZ', 'VpnGw3AZ', 'ErGw1AZ', 'ErGw2AZ', 'ErGw3AZ' :type name: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewaySkuName :param tier: Gateway SKU tier. Possible values include: 'Basic', 'HighPerformance', 'Standard', 'UltraPerformance', 'VpnGw1', 'VpnGw2', 'VpnGw3', 'VpnGw1AZ', 'VpnGw2AZ', 'VpnGw3AZ', 'ErGw1AZ', 'ErGw2AZ', 'ErGw3AZ' :type tier: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewaySkuTier :param capacity: The capacity. :type capacity: int """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, 'capacity': {'key': 'capacity', 'type': 'int'}, } def __init__(self, **kwargs): super(VirtualNetworkGatewaySku, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.tier = kwargs.get('tier', None) self.capacity = kwargs.get('capacity', None) class VirtualNetworkPeering(SubResource): """Peerings in a virtual network resource. :param id: Resource ID. :type id: str :param allow_virtual_network_access: Whether the VMs in the local virtual network space would be able to access the VMs in remote virtual network space. :type allow_virtual_network_access: bool :param allow_forwarded_traffic: Whether the forwarded traffic from the VMs in the local virtual network will be allowed/disallowed in remote virtual network. :type allow_forwarded_traffic: bool :param allow_gateway_transit: If gateway links can be used in remote virtual networking to link to this virtual network. :type allow_gateway_transit: bool :param use_remote_gateways: If remote gateways can be used on this virtual network. If the flag is set to true, and allowGatewayTransit on remote peering is also true, virtual network will use gateways of remote virtual network for transit. Only one peering can have this flag set to true. This flag cannot be set if virtual network already has a gateway. :type use_remote_gateways: bool :param remote_virtual_network: The reference of the remote virtual network. The remote virtual network can be in the same or different region (preview). See here to register for the preview and learn more (https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-peering). :type remote_virtual_network: ~azure.mgmt.network.v2019_06_01.models.SubResource :param remote_address_space: The reference of the remote virtual network address space. :type remote_address_space: ~azure.mgmt.network.v2019_06_01.models.AddressSpace :param peering_state: The status of the virtual network peering. Possible values include: 'Initiated', 'Connected', 'Disconnected' :type peering_state: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkPeeringState :param provisioning_state: The provisioning state of the resource. :type provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'allow_virtual_network_access': {'key': 'properties.allowVirtualNetworkAccess', 'type': 'bool'}, 'allow_forwarded_traffic': {'key': 'properties.allowForwardedTraffic', 'type': 'bool'}, 'allow_gateway_transit': {'key': 'properties.allowGatewayTransit', 'type': 'bool'}, 'use_remote_gateways': {'key': 'properties.useRemoteGateways', 'type': 'bool'}, 'remote_virtual_network': {'key': 'properties.remoteVirtualNetwork', 'type': 'SubResource'}, 'remote_address_space': {'key': 'properties.remoteAddressSpace', 'type': 'AddressSpace'}, 'peering_state': {'key': 'properties.peeringState', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkPeering, self).__init__(**kwargs) self.allow_virtual_network_access = kwargs.get('allow_virtual_network_access', None) self.allow_forwarded_traffic = kwargs.get('allow_forwarded_traffic', None) self.allow_gateway_transit = kwargs.get('allow_gateway_transit', None) self.use_remote_gateways = kwargs.get('use_remote_gateways', None) self.remote_virtual_network = kwargs.get('remote_virtual_network', None) self.remote_address_space = kwargs.get('remote_address_space', None) self.peering_state = kwargs.get('peering_state', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class VirtualNetworkTap(Resource): """Virtual Network Tap resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :ivar network_interface_tap_configurations: Specifies the list of resource IDs for the network interface IP configuration that needs to be tapped. :vartype network_interface_tap_configurations: list[~azure.mgmt.network.v2019_06_01.models.NetworkInterfaceTapConfiguration] :ivar resource_guid: The resourceGuid property of the virtual network tap. :vartype resource_guid: str :ivar provisioning_state: The provisioning state of the virtual network tap. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param destination_network_interface_ip_configuration: The reference to the private IP Address of the collector nic that will receive the tap. :type destination_network_interface_ip_configuration: ~azure.mgmt.network.v2019_06_01.models.NetworkInterfaceIPConfiguration :param destination_load_balancer_front_end_ip_configuration: The reference to the private IP address on the internal Load Balancer that will receive the tap. :type destination_load_balancer_front_end_ip_configuration: ~azure.mgmt.network.v2019_06_01.models.FrontendIPConfiguration :param destination_port: The VXLAN destination port that will receive the tapped traffic. :type destination_port: int :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'network_interface_tap_configurations': {'readonly': True}, 'resource_guid': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'network_interface_tap_configurations': {'key': 'properties.networkInterfaceTapConfigurations', 'type': '[NetworkInterfaceTapConfiguration]'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'destination_network_interface_ip_configuration': {'key': 'properties.destinationNetworkInterfaceIPConfiguration', 'type': 'NetworkInterfaceIPConfiguration'}, 'destination_load_balancer_front_end_ip_configuration': {'key': 'properties.destinationLoadBalancerFrontEndIPConfiguration', 'type': 'FrontendIPConfiguration'}, 'destination_port': {'key': 'properties.destinationPort', 'type': 'int'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkTap, self).__init__(**kwargs) self.network_interface_tap_configurations = None self.resource_guid = None self.provisioning_state = None self.destination_network_interface_ip_configuration = kwargs.get('destination_network_interface_ip_configuration', None) self.destination_load_balancer_front_end_ip_configuration = kwargs.get('destination_load_balancer_front_end_ip_configuration', None) self.destination_port = kwargs.get('destination_port', None) self.etag = kwargs.get('etag', None) class VirtualNetworkUsage(Model): """Usage details for subnet. Variables are only populated by the server, and will be ignored when sending a request. :ivar current_value: Indicates number of IPs used from the Subnet. :vartype current_value: float :ivar id: Subnet identifier. :vartype id: str :ivar limit: Indicates the size of the subnet. :vartype limit: float :ivar name: The name containing common and localized value for usage. :vartype name: ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkUsageName :ivar unit: Usage units. Returns 'Count'. :vartype unit: str """ _validation = { 'current_value': {'readonly': True}, 'id': {'readonly': True}, 'limit': {'readonly': True}, 'name': {'readonly': True}, 'unit': {'readonly': True}, } _attribute_map = { 'current_value': {'key': 'currentValue', 'type': 'float'}, 'id': {'key': 'id', 'type': 'str'}, 'limit': {'key': 'limit', 'type': 'float'}, 'name': {'key': 'name', 'type': 'VirtualNetworkUsageName'}, 'unit': {'key': 'unit', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkUsage, self).__init__(**kwargs) self.current_value = None self.id = None self.limit = None self.name = None self.unit = None class VirtualNetworkUsageName(Model): """Usage strings container. Variables are only populated by the server, and will be ignored when sending a request. :ivar localized_value: Localized subnet size and usage string. :vartype localized_value: str :ivar value: Subnet size and usage string. :vartype value: str """ _validation = { 'localized_value': {'readonly': True}, 'value': {'readonly': True}, } _attribute_map = { 'localized_value': {'key': 'localizedValue', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkUsageName, self).__init__(**kwargs) self.localized_value = None self.value = None class VirtualWAN(Resource): """VirtualWAN Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param disable_vpn_encryption: Vpn encryption to be disabled or not. :type disable_vpn_encryption: bool :ivar virtual_hubs: List of VirtualHubs in the VirtualWAN. :vartype virtual_hubs: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :ivar vpn_sites: List of VpnSites in the VirtualWAN. :vartype vpn_sites: list[~azure.mgmt.network.v2019_06_01.models.SubResource] :param security_provider_name: The Security Provider name. :type security_provider_name: str :param allow_branch_to_branch_traffic: True if branch to branch traffic is allowed. :type allow_branch_to_branch_traffic: bool :param allow_vnet_to_vnet_traffic: True if Vnet to Vnet traffic is allowed. :type allow_vnet_to_vnet_traffic: bool :param office365_local_breakout_category: The office local breakout category. Possible values include: 'Optimize', 'OptimizeAndAllow', 'All', 'None' :type office365_local_breakout_category: str or ~azure.mgmt.network.v2019_06_01.models.OfficeTrafficCategory :param p2_svpn_server_configurations: List of all P2SVpnServerConfigurations associated with the virtual wan. :type p2_svpn_server_configurations: list[~azure.mgmt.network.v2019_06_01.models.P2SVpnServerConfiguration] :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'virtual_hubs': {'readonly': True}, 'vpn_sites': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'disable_vpn_encryption': {'key': 'properties.disableVpnEncryption', 'type': 'bool'}, 'virtual_hubs': {'key': 'properties.virtualHubs', 'type': '[SubResource]'}, 'vpn_sites': {'key': 'properties.vpnSites', 'type': '[SubResource]'}, 'security_provider_name': {'key': 'properties.securityProviderName', 'type': 'str'}, 'allow_branch_to_branch_traffic': {'key': 'properties.allowBranchToBranchTraffic', 'type': 'bool'}, 'allow_vnet_to_vnet_traffic': {'key': 'properties.allowVnetToVnetTraffic', 'type': 'bool'}, 'office365_local_breakout_category': {'key': 'properties.office365LocalBreakoutCategory', 'type': 'str'}, 'p2_svpn_server_configurations': {'key': 'properties.p2SVpnServerConfigurations', 'type': '[P2SVpnServerConfiguration]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualWAN, self).__init__(**kwargs) self.disable_vpn_encryption = kwargs.get('disable_vpn_encryption', None) self.virtual_hubs = None self.vpn_sites = None self.security_provider_name = kwargs.get('security_provider_name', None) self.allow_branch_to_branch_traffic = kwargs.get('allow_branch_to_branch_traffic', None) self.allow_vnet_to_vnet_traffic = kwargs.get('allow_vnet_to_vnet_traffic', None) self.office365_local_breakout_category = kwargs.get('office365_local_breakout_category', None) self.p2_svpn_server_configurations = kwargs.get('p2_svpn_server_configurations', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.etag = None class VirtualWanSecurityProvider(Model): """Collection of SecurityProviders. :param name: Name of the security provider. :type name: str :param url: Url of the security provider. :type url: str :param type: Name of the security provider. Possible values include: 'External', 'Native' :type type: str or ~azure.mgmt.network.v2019_06_01.models.VirtualWanSecurityProviderType """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualWanSecurityProvider, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.url = kwargs.get('url', None) self.type = kwargs.get('type', None) class VirtualWanSecurityProviders(Model): """Collection of SecurityProviders. :param supported_providers: List of VirtualWAN security providers. :type supported_providers: list[~azure.mgmt.network.v2019_06_01.models.VirtualWanSecurityProvider] """ _attribute_map = { 'supported_providers': {'key': 'supportedProviders', 'type': '[VirtualWanSecurityProvider]'}, } def __init__(self, **kwargs): super(VirtualWanSecurityProviders, self).__init__(**kwargs) self.supported_providers = kwargs.get('supported_providers', None) class VpnClientConfiguration(Model): """VpnClientConfiguration for P2S client. :param vpn_client_address_pool: The reference of the address space resource which represents Address space for P2S VpnClient. :type vpn_client_address_pool: ~azure.mgmt.network.v2019_06_01.models.AddressSpace :param vpn_client_root_certificates: VpnClientRootCertificate for virtual network gateway. :type vpn_client_root_certificates: list[~azure.mgmt.network.v2019_06_01.models.VpnClientRootCertificate] :param vpn_client_revoked_certificates: VpnClientRevokedCertificate for Virtual network gateway. :type vpn_client_revoked_certificates: list[~azure.mgmt.network.v2019_06_01.models.VpnClientRevokedCertificate] :param vpn_client_protocols: VpnClientProtocols for Virtual network gateway. :type vpn_client_protocols: list[str or ~azure.mgmt.network.v2019_06_01.models.VpnClientProtocol] :param vpn_client_ipsec_policies: VpnClientIpsecPolicies for virtual network gateway P2S client. :type vpn_client_ipsec_policies: list[~azure.mgmt.network.v2019_06_01.models.IpsecPolicy] :param radius_server_address: The radius server address property of the VirtualNetworkGateway resource for vpn client connection. :type radius_server_address: str :param radius_server_secret: The radius secret property of the VirtualNetworkGateway resource for vpn client connection. :type radius_server_secret: str :param aad_tenant: The AADTenant property of the VirtualNetworkGateway resource for vpn client connection used for AAD authentication. :type aad_tenant: str :param aad_audience: The AADAudience property of the VirtualNetworkGateway resource for vpn client connection used for AAD authentication. :type aad_audience: str :param aad_issuer: The AADIssuer property of the VirtualNetworkGateway resource for vpn client connection used for AAD authentication. :type aad_issuer: str """ _attribute_map = { 'vpn_client_address_pool': {'key': 'vpnClientAddressPool', 'type': 'AddressSpace'}, 'vpn_client_root_certificates': {'key': 'vpnClientRootCertificates', 'type': '[VpnClientRootCertificate]'}, 'vpn_client_revoked_certificates': {'key': 'vpnClientRevokedCertificates', 'type': '[VpnClientRevokedCertificate]'}, 'vpn_client_protocols': {'key': 'vpnClientProtocols', 'type': '[str]'}, 'vpn_client_ipsec_policies': {'key': 'vpnClientIpsecPolicies', 'type': '[IpsecPolicy]'}, 'radius_server_address': {'key': 'radiusServerAddress', 'type': 'str'}, 'radius_server_secret': {'key': 'radiusServerSecret', 'type': 'str'}, 'aad_tenant': {'key': 'aadTenant', 'type': 'str'}, 'aad_audience': {'key': 'aadAudience', 'type': 'str'}, 'aad_issuer': {'key': 'aadIssuer', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnClientConfiguration, self).__init__(**kwargs) self.vpn_client_address_pool = kwargs.get('vpn_client_address_pool', None) self.vpn_client_root_certificates = kwargs.get('vpn_client_root_certificates', None) self.vpn_client_revoked_certificates = kwargs.get('vpn_client_revoked_certificates', None) self.vpn_client_protocols = kwargs.get('vpn_client_protocols', None) self.vpn_client_ipsec_policies = kwargs.get('vpn_client_ipsec_policies', None) self.radius_server_address = kwargs.get('radius_server_address', None) self.radius_server_secret = kwargs.get('radius_server_secret', None) self.aad_tenant = kwargs.get('aad_tenant', None) self.aad_audience = kwargs.get('aad_audience', None) self.aad_issuer = kwargs.get('aad_issuer', None) class VpnClientConnectionHealth(Model): """VpnClientConnectionHealth properties. Variables are only populated by the server, and will be ignored when sending a request. :ivar total_ingress_bytes_transferred: Total of the Ingress Bytes Transferred in this P2S Vpn connection. :vartype total_ingress_bytes_transferred: long :ivar total_egress_bytes_transferred: Total of the Egress Bytes Transferred in this connection. :vartype total_egress_bytes_transferred: long :param vpn_client_connections_count: The total of p2s vpn clients connected at this time to this P2SVpnGateway. :type vpn_client_connections_count: int :param allocated_ip_addresses: List of allocated ip addresses to the connected p2s vpn clients. :type allocated_ip_addresses: list[str] """ _validation = { 'total_ingress_bytes_transferred': {'readonly': True}, 'total_egress_bytes_transferred': {'readonly': True}, } _attribute_map = { 'total_ingress_bytes_transferred': {'key': 'totalIngressBytesTransferred', 'type': 'long'}, 'total_egress_bytes_transferred': {'key': 'totalEgressBytesTransferred', 'type': 'long'}, 'vpn_client_connections_count': {'key': 'vpnClientConnectionsCount', 'type': 'int'}, 'allocated_ip_addresses': {'key': 'allocatedIpAddresses', 'type': '[str]'}, } def __init__(self, **kwargs): super(VpnClientConnectionHealth, self).__init__(**kwargs) self.total_ingress_bytes_transferred = None self.total_egress_bytes_transferred = None self.vpn_client_connections_count = kwargs.get('vpn_client_connections_count', None) self.allocated_ip_addresses = kwargs.get('allocated_ip_addresses', None) class VpnClientConnectionHealthDetail(Model): """VPN client connection health detail. Variables are only populated by the server, and will be ignored when sending a request. :ivar vpn_connection_id: The vpn client Id. :vartype vpn_connection_id: str :ivar vpn_connection_duration: The duration time of a connected vpn client. :vartype vpn_connection_duration: long :ivar vpn_connection_time: The start time of a connected vpn client. :vartype vpn_connection_time: str :ivar public_ip_address: The public Ip of a connected vpn client. :vartype public_ip_address: str :ivar private_ip_address: The assigned private Ip of a connected vpn client. :vartype private_ip_address: str :ivar vpn_user_name: The user name of a connected vpn client. :vartype vpn_user_name: str :ivar max_bandwidth: The max band width. :vartype max_bandwidth: long :ivar egress_packets_transferred: The egress packets per second. :vartype egress_packets_transferred: long :ivar egress_bytes_transferred: The egress bytes per second. :vartype egress_bytes_transferred: long :ivar ingress_packets_transferred: The ingress packets per second. :vartype ingress_packets_transferred: long :ivar ingress_bytes_transferred: The ingress bytes per second. :vartype ingress_bytes_transferred: long :ivar max_packets_per_second: The max packets transferred per second. :vartype max_packets_per_second: long """ _validation = { 'vpn_connection_id': {'readonly': True}, 'vpn_connection_duration': {'readonly': True}, 'vpn_connection_time': {'readonly': True}, 'public_ip_address': {'readonly': True}, 'private_ip_address': {'readonly': True}, 'vpn_user_name': {'readonly': True}, 'max_bandwidth': {'readonly': True}, 'egress_packets_transferred': {'readonly': True}, 'egress_bytes_transferred': {'readonly': True}, 'ingress_packets_transferred': {'readonly': True}, 'ingress_bytes_transferred': {'readonly': True}, 'max_packets_per_second': {'readonly': True}, } _attribute_map = { 'vpn_connection_id': {'key': 'vpnConnectionId', 'type': 'str'}, 'vpn_connection_duration': {'key': 'vpnConnectionDuration', 'type': 'long'}, 'vpn_connection_time': {'key': 'vpnConnectionTime', 'type': 'str'}, 'public_ip_address': {'key': 'publicIpAddress', 'type': 'str'}, 'private_ip_address': {'key': 'privateIpAddress', 'type': 'str'}, 'vpn_user_name': {'key': 'vpnUserName', 'type': 'str'}, 'max_bandwidth': {'key': 'maxBandwidth', 'type': 'long'}, 'egress_packets_transferred': {'key': 'egressPacketsTransferred', 'type': 'long'}, 'egress_bytes_transferred': {'key': 'egressBytesTransferred', 'type': 'long'}, 'ingress_packets_transferred': {'key': 'ingressPacketsTransferred', 'type': 'long'}, 'ingress_bytes_transferred': {'key': 'ingressBytesTransferred', 'type': 'long'}, 'max_packets_per_second': {'key': 'maxPacketsPerSecond', 'type': 'long'}, } def __init__(self, **kwargs): super(VpnClientConnectionHealthDetail, self).__init__(**kwargs) self.vpn_connection_id = None self.vpn_connection_duration = None self.vpn_connection_time = None self.public_ip_address = None self.private_ip_address = None self.vpn_user_name = None self.max_bandwidth = None self.egress_packets_transferred = None self.egress_bytes_transferred = None self.ingress_packets_transferred = None self.ingress_bytes_transferred = None self.max_packets_per_second = None class VpnClientConnectionHealthDetailListResult(Model): """List of virtual network gateway vpn client connection health. :param value: List of vpn client connection health. :type value: list[~azure.mgmt.network.v2019_06_01.models.VpnClientConnectionHealthDetail] """ _attribute_map = { 'value': {'key': 'value', 'type': '[VpnClientConnectionHealthDetail]'}, } def __init__(self, **kwargs): super(VpnClientConnectionHealthDetailListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) class VpnClientIPsecParameters(Model): """An IPSec parameters for a virtual network gateway P2S connection. All required parameters must be populated in order to send to Azure. :param sa_life_time_seconds: Required. The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for P2S client. :type sa_life_time_seconds: int :param sa_data_size_kilobytes: Required. The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for P2S client.. :type sa_data_size_kilobytes: int :param ipsec_encryption: Required. The IPSec encryption algorithm (IKE phase 1). Possible values include: 'None', 'DES', 'DES3', 'AES128', 'AES192', 'AES256', 'GCMAES128', 'GCMAES192', 'GCMAES256' :type ipsec_encryption: str or ~azure.mgmt.network.v2019_06_01.models.IpsecEncryption :param ipsec_integrity: Required. The IPSec integrity algorithm (IKE phase 1). Possible values include: 'MD5', 'SHA1', 'SHA256', 'GCMAES128', 'GCMAES192', 'GCMAES256' :type ipsec_integrity: str or ~azure.mgmt.network.v2019_06_01.models.IpsecIntegrity :param ike_encryption: Required. The IKE encryption algorithm (IKE phase 2). Possible values include: 'DES', 'DES3', 'AES128', 'AES192', 'AES256', 'GCMAES256', 'GCMAES128' :type ike_encryption: str or ~azure.mgmt.network.v2019_06_01.models.IkeEncryption :param ike_integrity: Required. The IKE integrity algorithm (IKE phase 2). Possible values include: 'MD5', 'SHA1', 'SHA256', 'SHA384', 'GCMAES256', 'GCMAES128' :type ike_integrity: str or ~azure.mgmt.network.v2019_06_01.models.IkeIntegrity :param dh_group: Required. The DH Group used in IKE Phase 1 for initial SA. Possible values include: 'None', 'DHGroup1', 'DHGroup2', 'DHGroup14', 'DHGroup2048', 'ECP256', 'ECP384', 'DHGroup24' :type dh_group: str or ~azure.mgmt.network.v2019_06_01.models.DhGroup :param pfs_group: Required. The Pfs Group used in IKE Phase 2 for new child SA. Possible values include: 'None', 'PFS1', 'PFS2', 'PFS2048', 'ECP256', 'ECP384', 'PFS24', 'PFS14', 'PFSMM' :type pfs_group: str or ~azure.mgmt.network.v2019_06_01.models.PfsGroup """ _validation = { 'sa_life_time_seconds': {'required': True}, 'sa_data_size_kilobytes': {'required': True}, 'ipsec_encryption': {'required': True}, 'ipsec_integrity': {'required': True}, 'ike_encryption': {'required': True}, 'ike_integrity': {'required': True}, 'dh_group': {'required': True}, 'pfs_group': {'required': True}, } _attribute_map = { 'sa_life_time_seconds': {'key': 'saLifeTimeSeconds', 'type': 'int'}, 'sa_data_size_kilobytes': {'key': 'saDataSizeKilobytes', 'type': 'int'}, 'ipsec_encryption': {'key': 'ipsecEncryption', 'type': 'str'}, 'ipsec_integrity': {'key': 'ipsecIntegrity', 'type': 'str'}, 'ike_encryption': {'key': 'ikeEncryption', 'type': 'str'}, 'ike_integrity': {'key': 'ikeIntegrity', 'type': 'str'}, 'dh_group': {'key': 'dhGroup', 'type': 'str'}, 'pfs_group': {'key': 'pfsGroup', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnClientIPsecParameters, self).__init__(**kwargs) self.sa_life_time_seconds = kwargs.get('sa_life_time_seconds', None) self.sa_data_size_kilobytes = kwargs.get('sa_data_size_kilobytes', None) self.ipsec_encryption = kwargs.get('ipsec_encryption', None) self.ipsec_integrity = kwargs.get('ipsec_integrity', None) self.ike_encryption = kwargs.get('ike_encryption', None) self.ike_integrity = kwargs.get('ike_integrity', None) self.dh_group = kwargs.get('dh_group', None) self.pfs_group = kwargs.get('pfs_group', None) class VpnClientParameters(Model): """Vpn Client Parameters for package generation. :param processor_architecture: VPN client Processor Architecture. Possible values include: 'Amd64', 'X86' :type processor_architecture: str or ~azure.mgmt.network.v2019_06_01.models.ProcessorArchitecture :param authentication_method: VPN client authentication method. Possible values include: 'EAPTLS', 'EAPMSCHAPv2' :type authentication_method: str or ~azure.mgmt.network.v2019_06_01.models.AuthenticationMethod :param radius_server_auth_certificate: The public certificate data for the radius server authentication certificate as a Base-64 encoded string. Required only if external radius authentication has been configured with EAPTLS authentication. :type radius_server_auth_certificate: str :param client_root_certificates: A list of client root certificates public certificate data encoded as Base-64 strings. Optional parameter for external radius based authentication with EAPTLS. :type client_root_certificates: list[str] """ _attribute_map = { 'processor_architecture': {'key': 'processorArchitecture', 'type': 'str'}, 'authentication_method': {'key': 'authenticationMethod', 'type': 'str'}, 'radius_server_auth_certificate': {'key': 'radiusServerAuthCertificate', 'type': 'str'}, 'client_root_certificates': {'key': 'clientRootCertificates', 'type': '[str]'}, } def __init__(self, **kwargs): super(VpnClientParameters, self).__init__(**kwargs) self.processor_architecture = kwargs.get('processor_architecture', None) self.authentication_method = kwargs.get('authentication_method', None) self.radius_server_auth_certificate = kwargs.get('radius_server_auth_certificate', None) self.client_root_certificates = kwargs.get('client_root_certificates', None) class VpnClientRevokedCertificate(SubResource): """VPN client revoked certificate of virtual network gateway. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param thumbprint: The revoked VPN client certificate thumbprint. :type thumbprint: str :ivar provisioning_state: The provisioning state of the VPN client revoked certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'thumbprint': {'key': 'properties.thumbprint', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnClientRevokedCertificate, self).__init__(**kwargs) self.thumbprint = kwargs.get('thumbprint', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class VpnClientRootCertificate(SubResource): """VPN client root certificate of virtual network gateway. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param public_cert_data: Required. The certificate public data. :type public_cert_data: str :ivar provisioning_state: The provisioning state of the VPN client root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'public_cert_data': {'required': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'public_cert_data': {'key': 'properties.publicCertData', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnClientRootCertificate, self).__init__(**kwargs) self.public_cert_data = kwargs.get('public_cert_data', None) self.provisioning_state = None self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None) class VpnConnection(SubResource): """VpnConnection Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param remote_vpn_site: Id of the connected vpn site. :type remote_vpn_site: ~azure.mgmt.network.v2019_06_01.models.SubResource :param routing_weight: Routing weight for vpn connection. :type routing_weight: int :param connection_status: The connection status. Possible values include: 'Unknown', 'Connecting', 'Connected', 'NotConnected' :type connection_status: str or ~azure.mgmt.network.v2019_06_01.models.VpnConnectionStatus :param vpn_connection_protocol_type: Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' :type vpn_connection_protocol_type: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayConnectionProtocol :ivar ingress_bytes_transferred: Ingress bytes transferred. :vartype ingress_bytes_transferred: long :ivar egress_bytes_transferred: Egress bytes transferred. :vartype egress_bytes_transferred: long :param connection_bandwidth: Expected bandwidth in MBPS. :type connection_bandwidth: int :param shared_key: SharedKey for the vpn connection. :type shared_key: str :param enable_bgp: EnableBgp flag. :type enable_bgp: bool :param use_policy_based_traffic_selectors: Enable policy-based traffic selectors. :type use_policy_based_traffic_selectors: bool :param ipsec_policies: The IPSec Policies to be considered by this connection. :type ipsec_policies: list[~azure.mgmt.network.v2019_06_01.models.IpsecPolicy] :param enable_rate_limiting: EnableBgp flag. :type enable_rate_limiting: bool :param enable_internet_security: Enable internet security. :type enable_internet_security: bool :param use_local_azure_ip_address: Use local azure ip to initiate connection. :type use_local_azure_ip_address: bool :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param vpn_link_connections: List of all vpn site link connections to the gateway. :type vpn_link_connections: list[~azure.mgmt.network.v2019_06_01.models.VpnSiteLinkConnection] :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'ingress_bytes_transferred': {'readonly': True}, 'egress_bytes_transferred': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'remote_vpn_site': {'key': 'properties.remoteVpnSite', 'type': 'SubResource'}, 'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'}, 'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'}, 'vpn_connection_protocol_type': {'key': 'properties.vpnConnectionProtocolType', 'type': 'str'}, 'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'}, 'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'}, 'connection_bandwidth': {'key': 'properties.connectionBandwidth', 'type': 'int'}, 'shared_key': {'key': 'properties.sharedKey', 'type': 'str'}, 'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'}, 'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'}, 'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'}, 'enable_rate_limiting': {'key': 'properties.enableRateLimiting', 'type': 'bool'}, 'enable_internet_security': {'key': 'properties.enableInternetSecurity', 'type': 'bool'}, 'use_local_azure_ip_address': {'key': 'properties.useLocalAzureIpAddress', 'type': 'bool'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'vpn_link_connections': {'key': 'properties.vpnLinkConnections', 'type': '[VpnSiteLinkConnection]'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnConnection, self).__init__(**kwargs) self.remote_vpn_site = kwargs.get('remote_vpn_site', None) self.routing_weight = kwargs.get('routing_weight', None) self.connection_status = kwargs.get('connection_status', None) self.vpn_connection_protocol_type = kwargs.get('vpn_connection_protocol_type', None) self.ingress_bytes_transferred = None self.egress_bytes_transferred = None self.connection_bandwidth = kwargs.get('connection_bandwidth', None) self.shared_key = kwargs.get('shared_key', None) self.enable_bgp = kwargs.get('enable_bgp', None) self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None) self.ipsec_policies = kwargs.get('ipsec_policies', None) self.enable_rate_limiting = kwargs.get('enable_rate_limiting', None) self.enable_internet_security = kwargs.get('enable_internet_security', None) self.use_local_azure_ip_address = kwargs.get('use_local_azure_ip_address', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.vpn_link_connections = kwargs.get('vpn_link_connections', None) self.name = kwargs.get('name', None) self.etag = None class VpnDeviceScriptParameters(Model): """Vpn device configuration script generation parameters. :param vendor: The vendor for the vpn device. :type vendor: str :param device_family: The device family for the vpn device. :type device_family: str :param firmware_version: The firmware version for the vpn device. :type firmware_version: str """ _attribute_map = { 'vendor': {'key': 'vendor', 'type': 'str'}, 'device_family': {'key': 'deviceFamily', 'type': 'str'}, 'firmware_version': {'key': 'firmwareVersion', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnDeviceScriptParameters, self).__init__(**kwargs) self.vendor = kwargs.get('vendor', None) self.device_family = kwargs.get('device_family', None) self.firmware_version = kwargs.get('firmware_version', None) class VpnGateway(Resource): """VpnGateway Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param virtual_hub: The VirtualHub to which the gateway belongs. :type virtual_hub: ~azure.mgmt.network.v2019_06_01.models.SubResource :param connections: List of all vpn connections to the gateway. :type connections: list[~azure.mgmt.network.v2019_06_01.models.VpnConnection] :param bgp_settings: Local network gateway's BGP speaker settings. :type bgp_settings: ~azure.mgmt.network.v2019_06_01.models.BgpSettings :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param vpn_gateway_scale_unit: The scale unit for this vpn gateway. :type vpn_gateway_scale_unit: int :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'virtual_hub': {'key': 'properties.virtualHub', 'type': 'SubResource'}, 'connections': {'key': 'properties.connections', 'type': '[VpnConnection]'}, 'bgp_settings': {'key': 'properties.bgpSettings', 'type': 'BgpSettings'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'vpn_gateway_scale_unit': {'key': 'properties.vpnGatewayScaleUnit', 'type': 'int'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnGateway, self).__init__(**kwargs) self.virtual_hub = kwargs.get('virtual_hub', None) self.connections = kwargs.get('connections', None) self.bgp_settings = kwargs.get('bgp_settings', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.vpn_gateway_scale_unit = kwargs.get('vpn_gateway_scale_unit', None) self.etag = None class VpnLinkBgpSettings(Model): """BGP settings details for a link. :param asn: The BGP speaker's ASN. :type asn: long :param bgp_peering_address: The BGP peering address and BGP identifier of this BGP speaker. :type bgp_peering_address: str """ _attribute_map = { 'asn': {'key': 'asn', 'type': 'long'}, 'bgp_peering_address': {'key': 'bgpPeeringAddress', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnLinkBgpSettings, self).__init__(**kwargs) self.asn = kwargs.get('asn', None) self.bgp_peering_address = kwargs.get('bgp_peering_address', None) class VpnLinkProviderProperties(Model): """List of properties of a link provider. :param link_provider_name: Name of the link provider. :type link_provider_name: str :param link_speed_in_mbps: Link speed. :type link_speed_in_mbps: int """ _attribute_map = { 'link_provider_name': {'key': 'linkProviderName', 'type': 'str'}, 'link_speed_in_mbps': {'key': 'linkSpeedInMbps', 'type': 'int'}, } def __init__(self, **kwargs): super(VpnLinkProviderProperties, self).__init__(**kwargs) self.link_provider_name = kwargs.get('link_provider_name', None) self.link_speed_in_mbps = kwargs.get('link_speed_in_mbps', None) class VpnProfileResponse(Model): """Vpn Profile Response for package generation. :param profile_url: URL to the VPN profile. :type profile_url: str """ _attribute_map = { 'profile_url': {'key': 'profileUrl', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnProfileResponse, self).__init__(**kwargs) self.profile_url = kwargs.get('profile_url', None) class VpnSite(Resource): """VpnSite Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param virtual_wan: The VirtualWAN to which the vpnSite belongs. :type virtual_wan: ~azure.mgmt.network.v2019_06_01.models.SubResource :param device_properties: The device properties. :type device_properties: ~azure.mgmt.network.v2019_06_01.models.DeviceProperties :param ip_address: The ip-address for the vpn-site. :type ip_address: str :param site_key: The key for vpn-site that can be used for connections. :type site_key: str :param address_space: The AddressSpace that contains an array of IP address ranges. :type address_space: ~azure.mgmt.network.v2019_06_01.models.AddressSpace :param bgp_properties: The set of bgp properties. :type bgp_properties: ~azure.mgmt.network.v2019_06_01.models.BgpSettings :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param is_security_site: IsSecuritySite flag. :type is_security_site: bool :param vpn_site_links: List of all vpn site links :type vpn_site_links: list[~azure.mgmt.network.v2019_06_01.models.VpnSiteLink] :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'virtual_wan': {'key': 'properties.virtualWan', 'type': 'SubResource'}, 'device_properties': {'key': 'properties.deviceProperties', 'type': 'DeviceProperties'}, 'ip_address': {'key': 'properties.ipAddress', 'type': 'str'}, 'site_key': {'key': 'properties.siteKey', 'type': 'str'}, 'address_space': {'key': 'properties.addressSpace', 'type': 'AddressSpace'}, 'bgp_properties': {'key': 'properties.bgpProperties', 'type': 'BgpSettings'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'is_security_site': {'key': 'properties.isSecuritySite', 'type': 'bool'}, 'vpn_site_links': {'key': 'properties.vpnSiteLinks', 'type': '[VpnSiteLink]'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnSite, self).__init__(**kwargs) self.virtual_wan = kwargs.get('virtual_wan', None) self.device_properties = kwargs.get('device_properties', None) self.ip_address = kwargs.get('ip_address', None) self.site_key = kwargs.get('site_key', None) self.address_space = kwargs.get('address_space', None) self.bgp_properties = kwargs.get('bgp_properties', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.is_security_site = kwargs.get('is_security_site', None) self.vpn_site_links = kwargs.get('vpn_site_links', None) self.etag = None class VpnSiteId(Model): """VpnSite Resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar vpn_site: The resource-uri of the vpn-site for which config is to be fetched. :vartype vpn_site: str """ _validation = { 'vpn_site': {'readonly': True}, } _attribute_map = { 'vpn_site': {'key': 'vpnSite', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnSiteId, self).__init__(**kwargs) self.vpn_site = None class VpnSiteLink(SubResource): """VpnSiteLink Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param link_properties: The link provider properties. :type link_properties: ~azure.mgmt.network.v2019_06_01.models.VpnLinkProviderProperties :param ip_address: The ip-address for the vpn-site-link. :type ip_address: str :param bgp_properties: The set of bgp properties. :type bgp_properties: ~azure.mgmt.network.v2019_06_01.models.VpnLinkBgpSettings :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar type: Resource type. :vartype type: str """ _validation = { 'etag': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'link_properties': {'key': 'properties.linkProperties', 'type': 'VpnLinkProviderProperties'}, 'ip_address': {'key': 'properties.ipAddress', 'type': 'str'}, 'bgp_properties': {'key': 'properties.bgpProperties', 'type': 'VpnLinkBgpSettings'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnSiteLink, self).__init__(**kwargs) self.link_properties = kwargs.get('link_properties', None) self.ip_address = kwargs.get('ip_address', None) self.bgp_properties = kwargs.get('bgp_properties', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.etag = None self.name = kwargs.get('name', None) self.type = None class VpnSiteLinkConnection(SubResource): """VpnSiteLinkConnection Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param vpn_site_link: Id of the connected vpn site link. :type vpn_site_link: ~azure.mgmt.network.v2019_06_01.models.SubResource :param routing_weight: Routing weight for vpn connection. :type routing_weight: int :param connection_status: The connection status. Possible values include: 'Unknown', 'Connecting', 'Connected', 'NotConnected' :type connection_status: str or ~azure.mgmt.network.v2019_06_01.models.VpnConnectionStatus :param vpn_connection_protocol_type: Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' :type vpn_connection_protocol_type: str or ~azure.mgmt.network.v2019_06_01.models.VirtualNetworkGatewayConnectionProtocol :ivar ingress_bytes_transferred: Ingress bytes transferred. :vartype ingress_bytes_transferred: long :ivar egress_bytes_transferred: Egress bytes transferred. :vartype egress_bytes_transferred: long :param connection_bandwidth: Expected bandwidth in MBPS. :type connection_bandwidth: int :param shared_key: SharedKey for the vpn connection. :type shared_key: str :param enable_bgp: EnableBgp flag. :type enable_bgp: bool :param use_policy_based_traffic_selectors: Enable policy-based traffic selectors. :type use_policy_based_traffic_selectors: bool :param ipsec_policies: The IPSec Policies to be considered by this connection. :type ipsec_policies: list[~azure.mgmt.network.v2019_06_01.models.IpsecPolicy] :param enable_rate_limiting: EnableBgp flag. :type enable_rate_limiting: bool :param use_local_azure_ip_address: Use local azure ip to initiate connection. :type use_local_azure_ip_address: bool :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2019_06_01.models.ProvisioningState :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Resource type. :vartype type: str """ _validation = { 'ingress_bytes_transferred': {'readonly': True}, 'egress_bytes_transferred': {'readonly': True}, 'etag': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'vpn_site_link': {'key': 'properties.vpnSiteLink', 'type': 'SubResource'}, 'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'}, 'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'}, 'vpn_connection_protocol_type': {'key': 'properties.vpnConnectionProtocolType', 'type': 'str'}, 'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'}, 'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'}, 'connection_bandwidth': {'key': 'properties.connectionBandwidth', 'type': 'int'}, 'shared_key': {'key': 'properties.sharedKey', 'type': 'str'}, 'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'}, 'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'}, 'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'}, 'enable_rate_limiting': {'key': 'properties.enableRateLimiting', 'type': 'bool'}, 'use_local_azure_ip_address': {'key': 'properties.useLocalAzureIpAddress', 'type': 'bool'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, **kwargs): super(VpnSiteLinkConnection, self).__init__(**kwargs) self.vpn_site_link = kwargs.get('vpn_site_link', None) self.routing_weight = kwargs.get('routing_weight', None) self.connection_status = kwargs.get('connection_status', None) self.vpn_connection_protocol_type = kwargs.get('vpn_connection_protocol_type', None) self.ingress_bytes_transferred = None self.egress_bytes_transferred = None self.connection_bandwidth = kwargs.get('connection_bandwidth', None) self.shared_key = kwargs.get('shared_key', None) self.enable_bgp = kwargs.get('enable_bgp', None) self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None) self.ipsec_policies = kwargs.get('ipsec_policies', None) self.enable_rate_limiting = kwargs.get('enable_rate_limiting', None) self.use_local_azure_ip_address = kwargs.get('use_local_azure_ip_address', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = None self.type = None class WebApplicationFirewallCustomRule(Model): """Defines contents of a web application rule. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param name: Gets name of the resource that is unique within a policy. This name can be used to access the resource. :type name: str :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str :param priority: Required. Describes priority of the rule. Rules with a lower value will be evaluated before rules with a higher value. :type priority: int :param rule_type: Required. Describes type of rule. Possible values include: 'MatchRule', 'Invalid' :type rule_type: str or ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallRuleType :param match_conditions: Required. List of match conditions. :type match_conditions: list[~azure.mgmt.network.v2019_06_01.models.MatchCondition] :param action: Required. Type of Actions. Possible values include: 'Allow', 'Block', 'Log' :type action: str or ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallAction """ _validation = { 'name': {'max_length': 128}, 'etag': {'readonly': True}, 'priority': {'required': True}, 'rule_type': {'required': True}, 'match_conditions': {'required': True}, 'action': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'priority': {'key': 'priority', 'type': 'int'}, 'rule_type': {'key': 'ruleType', 'type': 'str'}, 'match_conditions': {'key': 'matchConditions', 'type': '[MatchCondition]'}, 'action': {'key': 'action', 'type': 'str'}, } def __init__(self, **kwargs): super(WebApplicationFirewallCustomRule, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.etag = None self.priority = kwargs.get('priority', None) self.rule_type = kwargs.get('rule_type', None) self.match_conditions = kwargs.get('match_conditions', None) self.action = kwargs.get('action', None) class WebApplicationFirewallPolicy(Resource): """Defines web application firewall policy. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param policy_settings: Describes policySettings for policy. :type policy_settings: ~azure.mgmt.network.v2019_06_01.models.PolicySettings :param custom_rules: Describes custom rules inside the policy. :type custom_rules: list[~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallCustomRule] :ivar application_gateways: A collection of references to application gateways. :vartype application_gateways: list[~azure.mgmt.network.v2019_06_01.models.ApplicationGateway] :ivar provisioning_state: Provisioning state of the WebApplicationFirewallPolicy. :vartype provisioning_state: str :ivar resource_state: Resource status of the policy. Resource status of the policy. Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Deleting' :vartype resource_state: str or ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallPolicyResourceState :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'application_gateways': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'resource_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'policy_settings': {'key': 'properties.policySettings', 'type': 'PolicySettings'}, 'custom_rules': {'key': 'properties.customRules', 'type': '[WebApplicationFirewallCustomRule]'}, 'application_gateways': {'key': 'properties.applicationGateways', 'type': '[ApplicationGateway]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'resource_state': {'key': 'properties.resourceState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(WebApplicationFirewallPolicy, self).__init__(**kwargs) self.policy_settings = kwargs.get('policy_settings', None) self.custom_rules = kwargs.get('custom_rules', None) self.application_gateways = None self.provisioning_state = None self.resource_state = None self.etag = kwargs.get('etag', None)
42.898212
193
0.676168
13035ae0a5b4eb1507de6faf943c45e34a7aa033
3,994
py
Python
rforests/urban_sound_tagging_baseline/urban-sound-tagging-baseline/vggish/vggish_postprocess.py
ihounie/urban-sound-tagging-baseline
686a5168c6e88570c3a964e13028ed01bd5598f9
[ "MIT" ]
16
2019-03-20T03:15:14.000Z
2021-08-10T07:35:24.000Z
urban_sound_tagging_baseline/vggish/vggish_postprocess.py
bongjun/dcase2019-task5
9b2e251cd59c55c6e2ab001830edde1bccf3840f
[ "MIT" ]
6
2019-06-10T14:48:36.000Z
2022-02-10T00:20:53.000Z
urban_sound_tagging_baseline/vggish/vggish_postprocess.py
bongjun/dcase2019-task5
9b2e251cd59c55c6e2ab001830edde1bccf3840f
[ "MIT" ]
8
2019-04-28T03:43:29.000Z
2021-12-09T17:33:01.000Z
# Copyright 2017 The TensorFlow 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. # ============================================================================== """Post-process embeddings from VGGish.""" import numpy as np class Postprocessor(object): """Post-processes VGGish embeddings. The initial release of AudioSet included 128-D VGGish embeddings for each segment of AudioSet. These released embeddings were produced by applying a PCA transformation (technically, a whitening transform is included as well) and 8-bit quantization to the raw embedding output from VGGish, in order to stay compatible with the YouTube-8M project which provides visual embeddings in the same format for a large set of YouTube videos. This class implements the same PCA (with whitening) and quantization transformations. """ def __init__(self, pca_params_npz_path, pca_eigen_vectors_name='pca_eigen_vectors', pca_means_name='pca_means', embedding_size=128, **params): """Constructs a postprocessor. Args: pca_params_npz_path: Path to a NumPy-format .npz file that contains the PCA parameters used in postprocessing. """ params = np.load(pca_params_npz_path) self._pca_matrix = params[pca_eigen_vectors_name] # Load means into a column vector for easier broadcasting later. self._pca_means = params[pca_means_name].reshape(-1, 1) assert self._pca_matrix.shape == ( embedding_size, embedding_size), ( 'Bad PCA matrix shape: %r' % (self._pca_matrix.shape,)) assert self._pca_means.shape == (embedding_size, 1), ( 'Bad PCA means shape: %r' % (self._pca_means.shape,)) def postprocess(self, embeddings_batch, embedding_size=128, quantize=True, quantize_min_val=-2.0, quantize_max_val=+2.0, **params): """Applies postprocessing to a batch of embeddings. Args: embeddings_batch: An nparray of shape [batch_size, embedding_size] containing output from the embedding layer of VGGish. Returns: An nparray of the same shape as the input but of type uint8, containing the PCA-transformed and quantized version of the input. """ assert len(embeddings_batch.shape) == 2, ( 'Expected 2-d batch, got %r' % (embeddings_batch.shape,)) assert embeddings_batch.shape[1] == embedding_size, ( 'Bad batch shape: %r' % (embeddings_batch.shape,)) # Apply PCA. # - Embeddings come in as [batch_size, embedding_size]. # - Transpose to [embedding_size, batch_size]. # - Subtract pca_means column vector from each column. # - Premultiply by PCA matrix of shape [output_dims, input_dims] # where both are are equal to embedding_size in our case. # - Transpose result back to [batch_size, embedding_size]. pca_applied = np.dot(self._pca_matrix, (embeddings_batch.T - self._pca_means)).T # Quantize by: # - clipping to [min, max] range clipped_embeddings = np.clip( pca_applied, quantize_min_val, quantize_max_val) if quantize: # - convert to 8-bit in range [0.0, 255.0] quantized_embeddings = ( (clipped_embeddings - quantize_min_val) * (255.0 / (quantize_max_val - quantize_min_val))) # - cast 8-bit float to uint8 quantized_embeddings = quantized_embeddings.astype(np.uint8) return quantized_embeddings else: return clipped_embeddings
42.042105
85
0.691287
9ef79b0fd3e7b579d9b6b48c1594705722979f0c
4,906
py
Python
Examples/GirlImages/GirlImages.py
wxh0000mm/TKinterDesigner
01878e78746082413a09444283edbd52118d15ef
[ "Apache-2.0" ]
1
2022-03-09T08:43:41.000Z
2022-03-09T08:43:41.000Z
Examples/GirlImages/GirlImages.py
wxh0000mm/TKinterDesigner
01878e78746082413a09444283edbd52118d15ef
[ "Apache-2.0" ]
null
null
null
Examples/GirlImages/GirlImages.py
wxh0000mm/TKinterDesigner
01878e78746082413a09444283edbd52118d15ef
[ "Apache-2.0" ]
null
null
null
#coding=utf-8 #import libs import sys import codecs sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) import GirlImages_cmd import GirlImages_sty import Fun import os import LeftTreeBar import RightTextBar import tkinter from tkinter import * import tkinter.ttk import tkinter.font #Add your Varial Here: (Keep This Line of comments) #Define UI Class class GirlImages: def __init__(self,root,isTKroot = True): uiName = self.__class__.__name__ Fun.Register(uiName,'UIClass',self) self.root = root style = GirlImages_sty.SetupStyle() if isTKroot == True: root.title("Form1") Fun.CenterDlg(uiName,root,820,660) root['background'] = '#efefef' root.bind('<Configure>',self.Configure) Form_1= tkinter.Canvas(root,width = 10,height = 4) Form_1.place(x = 0,y = 0,width = 820,height = 660) Form_1.configure(bg = "#efefef") Form_1.configure(highlightthickness = 0) Fun.Register(uiName,'root',root) Fun.Register(uiName,'Form_1',Form_1) #Create the elements of root Label_2= tkinter.Label(root,text="网址",width = 10,height = 4) Fun.Register(uiName,'Label_2',Label_2) Label_2.place(x = 10,y = 2,width = 50,height = 24) Label_2.configure(relief = "flat") Entry_3_Variable = Fun.AddTKVariable(uiName,'Entry_3','') Entry_3= tkinter.Entry(root,textvariable=Entry_3_Variable) Fun.Register(uiName,'Entry_3',Entry_3) Entry_3.place(x = 60,y = 2,width = 500,height = 24) Entry_3.configure(relief = "sunken") Label_4= tkinter.Label(root,text="最大数量",width = 10,height = 4) Fun.Register(uiName,'Label_4',Label_4) Label_4.place(x = 560,y = 2,width = 60,height = 24) Label_4.configure(relief = "flat") Entry_5_Variable = Fun.AddTKVariable(uiName,'Entry_5','') Entry_5= tkinter.Entry(root,textvariable=Entry_5_Variable) Fun.Register(uiName,'Entry_5',Entry_5) Entry_5.place(x = 620,y = 2,width = 70,height = 24) Entry_5.configure(relief = "sunken") Button_6= tkinter.Button(root,text="开始",width = 10,height = 4) Fun.Register(uiName,'Button_6',Button_6) Button_6.place(x = 710,y = 2,width = 50,height = 24) Button_6.configure(command=lambda:GirlImages_cmd.Button_6_onCommand(uiName,"Button_6")) Button_7= tkinter.Button(root,text="停止",width = 10,height = 4) Fun.Register(uiName,'Button_7',Button_7) Button_7.place(x = 770,y = 2,width = 50,height = 24) Button_7.configure(command=lambda:GirlImages_cmd.Button_7_onCommand(uiName,"Button_7")) PanedWindow_8= tkinter.PanedWindow(root) Fun.Register(uiName,'PanedWindow_8',PanedWindow_8) PanedWindow_8.place(x = 0,y = 30,width = 871,height = 610) PanedWindow_8.configure(orient = tkinter.HORIZONTAL) PanedWindow_8.configure(showhandle = "0") PanedWindow_8.configure(sashrelief = "flat") PanedWindow_8.configure(sashwidth = "4") PanedWindow_8_child1= tkinter.Canvas(PanedWindow_8,bg="#FFDD94",name="child1") PanedWindow_8_child1.place(x = 1,y = 1,width = 261,height = 608) LeftTreeBar.LeftTreeBar(PanedWindow_8_child1,False) PanedWindow_8.add(PanedWindow_8_child1,width =261) PanedWindow_8_child2= tkinter.Canvas(PanedWindow_8,bg="#D0E6A5",name="child2") Fun.Register(uiName,'PanedWindow_8_child1',PanedWindow_8_child1) Fun.Register(uiName,'PanedWindow_8_child2',PanedWindow_8_child2) PanedWindow_8_child2.place(x = 266,y = 1,width = 604,height = 608) RightTextBar.RightTextBar(PanedWindow_8_child2,False) PanedWindow_8.add(PanedWindow_8_child2,width =604) Fun.Register(uiName,'PanedWindow_8_child1',PanedWindow_8_child1) Fun.Register(uiName,'PanedWindow_8_child2',PanedWindow_8_child2) Label_9= tkinter.Label(root,text="Label",width = 10,height = 4) Fun.Register(uiName,'Label_9',Label_9) Label_9.place(x = 0,y = 640,width = 820,height = 20) Label_9.configure(relief = "flat") #Inital all element's Data Fun.InitElementData(uiName) #Call Form_1's OnLoad Function GirlImages_cmd.Form_1_onLoad(uiName) #Add Some Logic Code Here: (Keep This Line of comments) def Configure(self,event): if self.root == event.widget: PanedWindow_8 = Fun.GetElement(self.__class__.__name__,'PanedWindow_8') Label_9 = Fun.GetElement(self.__class__.__name__,'Label_9') PanedWindow_8.place(x = 0,y = 50,width = event.width,height = event.height - 51 - 20) Label_9.place(x = 0,y = event.height - 20,width = event.width,height = 20) #Create the root of Kinter if __name__ == '__main__': root = tkinter.Tk() MyDlg = GirlImages(root) root.mainloop()
47.631068
97
0.669384
a8f9a9ed3932d6fc3e047fc2c0f962477325e914
4,816
py
Python
modules/models.py
yoshum/lower-bounded-proper-losses
725c333bf24c0ae9e0218a6dae767f043a9548a3
[ "MIT" ]
1
2021-08-21T10:59:08.000Z
2021-08-21T10:59:08.000Z
modules/models.py
yoshum/lower-bounded-proper-losses
725c333bf24c0ae9e0218a6dae767f043a9548a3
[ "MIT" ]
null
null
null
modules/models.py
yoshum/lower-bounded-proper-losses
725c333bf24c0ae9e0218a6dae767f043a9548a3
[ "MIT" ]
null
null
null
from typing import Optional import torch import torch.nn as nn from torchvision import models def conv3x3(in_planes: int, out_planes: int, stride: int = 1) -> nn.Module: return nn.Conv2d( in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False ) def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Module: return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) class BasicBlock(nn.Module): def __init__( self, inplanes: int, planes: int, stride: int = 1, downsample: Optional[nn.Module] = None, ): super().__init__() norm_layer = nn.BatchNorm2d self.bn1 = norm_layer(inplanes) self.relu = nn.ReLU(inplace=True) self.conv1 = conv3x3(inplanes, planes, stride) self.bn2 = norm_layer(planes) self.conv2 = conv3x3(planes, planes) self.downsample = downsample self.stride = stride def forward(self, x): identity = x out = self.bn1(x) out = self.relu(out) out = self.conv1(out) out = self.bn2(out) out = self.relu(out) out = self.conv2(out) if self.downsample is not None: identity = self.downsample(x) out += identity return out class ResNetMini(nn.Module): def __init__(self, num_classes: int = 1000, width: int = 2, blocks: int = 4): super().__init__() norm_layer = nn.BatchNorm2d self.width = width n_channels = [16, 16 * width, 32 * width, 64 * width] self.conv1 = nn.Conv2d( 3, n_channels[0], kernel_size=3, stride=1, padding=1, bias=False ) self.layer1 = self._make_layer(n_channels[0], n_channels[1], blocks) self.layer2 = self._make_layer(n_channels[1], n_channels[2], blocks, stride=2) self.layer3 = self._make_layer(n_channels[2], n_channels[3], blocks, stride=2) self.bn = norm_layer(n_channels[3]) self.relu = nn.ReLU(inplace=True) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(n_channels[3], num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _make_layer( self, in_channels: int, out_channels: int, blocks: int, stride: int = 1 ): norm_layer = nn.BatchNorm2d downsample = None if stride != 1 or in_channels != out_channels: downsample = nn.Sequential( conv1x1(in_channels, out_channels, stride), norm_layer(out_channels) ) layers = [] layers.append(BasicBlock(in_channels, out_channels, stride, downsample)) for _ in range(1, blocks): layers.append(BasicBlock(out_channels, out_channels)) return nn.Sequential(*layers) def _forward_impl(self, x): # See note [TorchScript super()] x = self.conv1(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.relu(self.bn(x)) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x) class MLP(nn.Module): def __init__(self, input_dim: int, hidden_dim: int, output_dim: int): super().__init__() self.fc1 = nn.Linear(input_dim, hidden_dim) self.relu = nn.ReLU() self.fc2 = nn.Linear(hidden_dim, output_dim) def forward(self, x): out = torch.flatten(x, start_dim=1) out = self.fc1(out) out = self.relu(out) out = self.fc2(out) return out class LinearModel(nn.Module): def __init__(self, input_dim: int, output_dim: int): super().__init__() self.linear = nn.Linear(input_dim, output_dim) def forward(self, x): out = torch.flatten(x, start_dim=1) out = self.linear(out) return out def get_model(name: str) -> nn.Module: if name == "resnet20": return ResNetMini(num_classes=10, width=1, blocks=3) elif name == "wrn_28_2": return ResNetMini(num_classes=10, width=2, blocks=4) elif name == "wrn_28_10": return ResNetMini(num_classes=10, width=10, blocks=4) elif name == "mlp500": return MLP(28 * 28, 500, 10) elif name == "linear": return LinearModel(28 * 28, 10) elif name in models.__dict__: fn = models.__dict__[name] else: raise RuntimeError("Unknown model name {}".format(name)) return fn(num_classes=10)
30.1
86
0.598007
c380e0f5b5927e55a7d291a0ab15b54321ed98da
579
py
Python
aioclustermanager/job_list.py
sunbit/aioclustermanager
f5a2f4ba7936a75c7748cff9f77c3bfff1a3a61d
[ "BSD-3-Clause" ]
1
2020-03-24T16:15:56.000Z
2020-03-24T16:15:56.000Z
aioclustermanager/job_list.py
bloodbare/aioclustermanager
9abe7e9db7140854709c8044128e0153debe6971
[ "BSD-3-Clause" ]
8
2018-03-12T20:40:23.000Z
2018-06-05T18:35:16.000Z
aioclustermanager/job_list.py
onna/aioclustermanager
9abe7e9db7140854709c8044128e0153debe6971
[ "BSD-3-Clause" ]
2
2020-05-21T17:32:23.000Z
2021-05-11T12:17:56.000Z
class JobList: """Generic job class.""" def __init__(self, data=None, **kw): self._raw = data @property def values(self): raise NotImplementedError() def __len__(self): return len(self.values()) def __iter__(self): for job in self.values(): yield job def schedulled_pods(self): for key, value in self.items(): if len(value) > 0: # XXX work with both nomad and k8s? schedulled = list(filter(lambda x: x[0] == 'PodScheduled', value[0].events)) # noqa
25.173913
100
0.554404
7ec97f6e619a40950e385484b14b4ac0abbbb580
21
py
Python
vega/algorithms/data_augmentation/common/__init__.py
jie311/vega
1bba6100ead802697e691403b951e6652a99ccae
[ "MIT" ]
724
2020-06-22T12:05:30.000Z
2022-03-31T07:10:54.000Z
vega/algorithms/data_augmentation/common/__init__.py
jie311/vega
1bba6100ead802697e691403b951e6652a99ccae
[ "MIT" ]
147
2020-06-30T13:34:46.000Z
2022-03-29T11:30:17.000Z
vega/algorithms/data_augmentation/common/__init__.py
jie311/vega
1bba6100ead802697e691403b951e6652a99ccae
[ "MIT" ]
160
2020-06-29T18:27:58.000Z
2022-03-23T08:42:21.000Z
from .pba import PBA
10.5
20
0.761905
ab79595509f55bbac4d9010aceac0c587efb53cd
1,244
py
Python
lib/python3.7/site-packages/aiofiles/threadpool/utils.py
teomoney1999/ACT_gatco_project
a804a6348efeab90f3114606cfbc73aaebab63e1
[ "MIT" ]
3
2020-03-31T10:36:31.000Z
2020-04-23T12:01:10.000Z
lib/python3.7/site-packages/aiofiles/threadpool/utils.py
teomoney1999/ACT_gatco_project
a804a6348efeab90f3114606cfbc73aaebab63e1
[ "MIT" ]
9
2021-04-12T13:44:34.000Z
2021-04-13T16:50:08.000Z
lib/python3.7/site-packages/aiofiles/threadpool/utils.py
teomoney1999/ACT_gatco_project
a804a6348efeab90f3114606cfbc73aaebab63e1
[ "MIT" ]
1
2021-06-12T06:11:34.000Z
2021-06-12T06:11:34.000Z
import functools from types import coroutine def delegate_to_executor(*attrs): def cls_builder(cls): for attr_name in attrs: setattr(cls, attr_name, _make_delegate_method(attr_name)) return cls return cls_builder def proxy_method_directly(*attrs): def cls_builder(cls): for attr_name in attrs: setattr(cls, attr_name, _make_proxy_method(attr_name)) return cls return cls_builder def proxy_property_directly(*attrs): def cls_builder(cls): for attr_name in attrs: setattr(cls, attr_name, _make_proxy_property(attr_name)) return cls return cls_builder def _make_delegate_method(attr_name): @coroutine def method(self, *args, **kwargs): cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs) return (yield from self._loop.run_in_executor(self._executor, cb)) return method def _make_proxy_method(attr_name): def method(self, *args, **kwargs): return getattr(self._file, attr_name)(*args, **kwargs) return method def _make_proxy_property(attr_name): def proxy_property(self): return getattr(self._file, attr_name) return property(proxy_property)
23.471698
79
0.689711
c17ec04f8780e56066253a0682611319c62f9a4e
3,367
py
Python
profiles_project/settings.py
iboumiza/profiles-rest-api
dd1c161ee4e1a2dcd941f766c0755041040e23ed
[ "MIT" ]
null
null
null
profiles_project/settings.py
iboumiza/profiles-rest-api
dd1c161ee4e1a2dcd941f766c0755041040e23ed
[ "MIT" ]
5
2021-03-19T00:37:39.000Z
2021-09-22T18:42:36.000Z
profiles_project/settings.py
BlueSkyTrading/profiles-rest-api
dd1c161ee4e1a2dcd941f766c0755041040e23ed
[ "MIT" ]
null
null
null
""" Django settings for profiles_project project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '5tb14)@0xwh2qk0kl@j-cu0@789)*!end&ehi7)cuv-am*nqkq' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = bool(int(os.environ.get('DEBUG', 1))) ALLOWED_HOSTS = [ 'ec2-3-19-221-156.us-east-2.compute.amazonaws.com', '127.0.0.1' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'profiles_api', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'profiles_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'profiles_project.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' AUTH_USER_MODEL = 'profiles_api.UserProfile' STATIC_ROOT = 'static/'
25.70229
91
0.69706
1c6ef2286e905444a56d16faeee8c32b59878361
2,569
py
Python
paramak/parametric_components/poloidal_field_coil.py
moatazharb/paramak
785c3ed7304e22eac7d58bb1bdc6515fbd20b9a8
[ "MIT" ]
1
2021-12-14T15:53:46.000Z
2021-12-14T15:53:46.000Z
paramak/parametric_components/poloidal_field_coil.py
bam241/paramak
785c3ed7304e22eac7d58bb1bdc6515fbd20b9a8
[ "MIT" ]
null
null
null
paramak/parametric_components/poloidal_field_coil.py
bam241/paramak
785c3ed7304e22eac7d58bb1bdc6515fbd20b9a8
[ "MIT" ]
null
null
null
from typing import Optional, Tuple from paramak import RotateStraightShape class PoloidalFieldCoil(RotateStraightShape): """Creates a rectangular poloidal field coil. Args: height: the vertical (z axis) height of the coil (cm). width: the horizontal (x axis) width of the coil (cm). center_point: the center of the coil (x,z) values (cm). stp_filename: defaults to "PoloidalFieldCoil.stp". stl_filename: defaults to "PoloidalFieldCoil.stl". name: defaults to "pf_coil". material_tag: defaults to "pf_coil_mat". """ def __init__( self, height: float, width: float, center_point: Tuple[float, float], stp_filename: Optional[str] = "PoloidalFieldCoil.stp", stl_filename: Optional[str] = "PoloidalFieldCoil.stl", name: Optional[str] = "pf_coil", material_tag: Optional[str] = "pf_coil_mat", **kwargs ) -> None: super().__init__( name=name, material_tag=material_tag, stp_filename=stp_filename, stl_filename=stl_filename, **kwargs ) self.center_point = center_point self.height = height self.width = width @property def center_point(self): return self._center_point @center_point.setter def center_point(self, center_point): self._center_point = center_point @property def height(self): return self._height @height.setter def height(self, height): self._height = height @property def width(self): return self._width @width.setter def width(self, width): self._width = width def find_points(self): """Finds the XZ points joined by straight connections that describe the 2D profile of the poloidal field coil shape.""" points = [ ( self.center_point[0] + self.width / 2.0, self.center_point[1] + self.height / 2.0, ), # upper right ( self.center_point[0] + self.width / 2.0, self.center_point[1] - self.height / 2.0, ), # lower right ( self.center_point[0] - self.width / 2.0, self.center_point[1] - self.height / 2.0, ), # lower left ( self.center_point[0] - self.width / 2.0, self.center_point[1] + self.height / 2.0, ) ] self.points = points
28.230769
75
0.567536
4080d4861ecee8ea1ea91ed8f835b282ce36b91b
8,428
py
Python
docs/conf.py
bopamo/calc
02bbbbc62e9c9a14a7eba6bc13f0045db33c447a
[ "MIT" ]
null
null
null
docs/conf.py
bopamo/calc
02bbbbc62e9c9a14a7eba6bc13f0045db33c447a
[ "MIT" ]
790
2019-09-04T20:09:05.000Z
2022-03-31T12:31:10.000Z
docs/conf.py
bopamo/calc
02bbbbc62e9c9a14a7eba6bc13f0045db33c447a
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # # calc documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 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('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) import calc # -- 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', 'sphinx.ext.viewcode'] # 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'A Basic TDD Calculator' copyright = u"2019, Bopamo Osaisai" # 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 = calc.__version__ # The full version, including alpha/beta/rc tags. release = calc.__version__ # 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'] # 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 = 'calcdoc' # -- 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', 'calc.tex', u'A Basic TDD Calculator Documentation', u'Bopamo Osaisai', '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', 'calc', u'A Basic TDD Calculator Documentation', [u'Bopamo Osaisai'], 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', 'calc', u'A Basic TDD Calculator Documentation', u'Bopamo Osaisai', 'calc', '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
30.536232
76
0.714998
691321ca3ae9d65f3b06403cbb51c0a8691d9f2e
2,131
py
Python
dev/unittest/structure.py
PowerDNS/exabgp
bbf69f25853e10432fbe588b5bc2f8d9f1e5dda2
[ "BSD-3-Clause" ]
8
2015-01-11T09:57:26.000Z
2019-07-05T05:57:02.000Z
dev/unittest/structure.py
Acidburn0zzz/exabgp
bbf69f25853e10432fbe588b5bc2f8d9f1e5dda2
[ "BSD-3-Clause" ]
1
2018-11-15T22:10:09.000Z
2018-11-15T22:20:31.000Z
dev/unittest/structure.py
Acidburn0zzz/exabgp
bbf69f25853e10432fbe588b5bc2f8d9f1e5dda2
[ "BSD-3-Clause" ]
6
2015-09-11T01:51:06.000Z
2020-03-10T19:16:18.000Z
#!/usr/bin/env python # encoding: utf-8 """ data.py Created by Thomas Mangin on 2009-09-06. Copyright (c) 2009-2013 Exa Networks. All rights reserved. """ import unittest from exabgp.configuration.environment import environment env = environment.setup('') from exabgp.protocol.family import AFI from exabgp.protocol.family import SAFI from exabgp.protocol.ip.inet import * class TestData (unittest.TestCase): def test_1_nlri_1 (self): self.assertEqual(''.join([chr(c) for c in [32,1,2,3,4]]),to_NLRI('1.2.3.4','32').pack()) def test_1_nlri_2 (self): self.assertEqual(''.join([chr(c) for c in [24,1,2,3]]),to_NLRI('1.2.3.4','24').pack()) def test_1_nlri_3 (self): self.assertEqual(''.join([chr(c) for c in [20,1,2,3]]),to_NLRI('1.2.3.4','20').pack()) def test_2_ip_2 (self): self.assertEqual(str(InetIP('::ffff:192.168.1.26')),'::ffff:192.168.1.26/128') self.assertEqual(str(InetIP('::ffff:192.168.1.26').ip),'::ffff:192.168.1.26') def test_3_ipv6_1 (self): default = InetIP('::') self.assertEqual(str(default),'::/128') self.assertEqual(default.ip,'::') self.assertEqual(default.packedip(),'\0'*16) def test_3_ipv6_2 (self): default = InetIP('1234:5678::') self.assertEqual(str(default),'1234:5678::/128') self.assertEqual(default.ip,'1234:5678::') self.assertEqual(default.packedip(),'\x12\x34\x56\x78'+'\0'*12) def test_3_ipv6_3 (self): default = InetIP('1234:5678::1') self.assertEqual(str(default),'1234:5678::1/128') self.assertEqual(default.ip,'1234:5678::1') self.assertEqual(default.packedip(),'\x12\x34\x56\x78'+'\0'*11 + '\x01') def test_xxx (self): ip = "192.0.2.0" net = chr (192) + chr(0) + chr(2) +chr(0) bnt = chr(24) + chr (192) + chr(0) + chr(2) pfx = Prefix(AFI.ipv4,ip,24) bgp = BGPNLRI(AFI.ipv4,bnt) self.assertEqual(str(pfx),"%s/24" % ip) self.assertEqual(str(afi),"%s/24" % ip) self.assertEqual(str(bgp),"%s/24" % ip) self.assertEqual(pfx.pack(),bnt) self.assertEqual(afi.pack(),bnt) self.assertEqual(bgp.pack(),bnt) # README: NEED To add ASN test # README: NEED To add NLRI test if __name__ == '__main__': unittest.main()
30.014085
90
0.667762
b5677de698584a2c82edbb4a657ff55a109ee436
6,820
py
Python
sdk/python/pulumi_azure_native/network/v20190701/get_express_route_gateway.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/network/v20190701/get_express_route_gateway.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/network/v20190701/get_express_route_gateway.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs __all__ = [ 'GetExpressRouteGatewayResult', 'AwaitableGetExpressRouteGatewayResult', 'get_express_route_gateway', ] @pulumi.output_type class GetExpressRouteGatewayResult: """ ExpressRoute gateway resource. """ def __init__(__self__, auto_scale_configuration=None, etag=None, express_route_connections=None, id=None, location=None, name=None, provisioning_state=None, tags=None, type=None, virtual_hub=None): if auto_scale_configuration and not isinstance(auto_scale_configuration, dict): raise TypeError("Expected argument 'auto_scale_configuration' to be a dict") pulumi.set(__self__, "auto_scale_configuration", auto_scale_configuration) if etag and not isinstance(etag, str): raise TypeError("Expected argument 'etag' to be a str") pulumi.set(__self__, "etag", etag) if express_route_connections and not isinstance(express_route_connections, list): raise TypeError("Expected argument 'express_route_connections' to be a list") pulumi.set(__self__, "express_route_connections", express_route_connections) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if location and not isinstance(location, str): raise TypeError("Expected argument 'location' to be a str") pulumi.set(__self__, "location", location) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if tags and not isinstance(tags, dict): raise TypeError("Expected argument 'tags' to be a dict") pulumi.set(__self__, "tags", tags) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) if virtual_hub and not isinstance(virtual_hub, dict): raise TypeError("Expected argument 'virtual_hub' to be a dict") pulumi.set(__self__, "virtual_hub", virtual_hub) @property @pulumi.getter(name="autoScaleConfiguration") def auto_scale_configuration(self) -> Optional['outputs.ExpressRouteGatewayPropertiesResponseAutoScaleConfiguration']: """ Configuration for auto scaling. """ return pulumi.get(self, "auto_scale_configuration") @property @pulumi.getter def etag(self) -> str: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="expressRouteConnections") def express_route_connections(self) -> Sequence['outputs.ExpressRouteConnectionResponse']: """ List of ExpressRoute connections to the ExpressRoute gateway. """ return pulumi.get(self, "express_route_connections") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def location(self) -> Optional[str]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state of the express route gateway resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") @property @pulumi.getter(name="virtualHub") def virtual_hub(self) -> 'outputs.VirtualHubIdResponse': """ The Virtual Hub where the ExpressRoute gateway is or will be deployed. """ return pulumi.get(self, "virtual_hub") class AwaitableGetExpressRouteGatewayResult(GetExpressRouteGatewayResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetExpressRouteGatewayResult( auto_scale_configuration=self.auto_scale_configuration, etag=self.etag, express_route_connections=self.express_route_connections, id=self.id, location=self.location, name=self.name, provisioning_state=self.provisioning_state, tags=self.tags, type=self.type, virtual_hub=self.virtual_hub) def get_express_route_gateway(express_route_gateway_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetExpressRouteGatewayResult: """ ExpressRoute gateway resource. :param str express_route_gateway_name: The name of the ExpressRoute gateway. :param str resource_group_name: The name of the resource group. """ __args__ = dict() __args__['expressRouteGatewayName'] = express_route_gateway_name __args__['resourceGroupName'] = resource_group_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:network/v20190701:getExpressRouteGateway', __args__, opts=opts, typ=GetExpressRouteGatewayResult).value return AwaitableGetExpressRouteGatewayResult( auto_scale_configuration=__ret__.auto_scale_configuration, etag=__ret__.etag, express_route_connections=__ret__.express_route_connections, id=__ret__.id, location=__ret__.location, name=__ret__.name, provisioning_state=__ret__.provisioning_state, tags=__ret__.tags, type=__ret__.type, virtual_hub=__ret__.virtual_hub)
37.065217
201
0.66349
cd3257d0779671635a6ebb2c62b4a892e4acdd75
3,849
py
Python
resource/py_api/login.py
fengleyl/NetEase
1dbcea741bd294da633233c766b24113c293f94e
[ "MIT" ]
35
2015-06-18T14:11:46.000Z
2020-12-01T10:06:17.000Z
resource/py_api/login.py
StevennyZhang/NetEase
1dbcea741bd294da633233c766b24113c293f94e
[ "MIT" ]
1
2015-09-15T13:09:58.000Z
2016-05-09T05:47:24.000Z
resource/py_api/login.py
StevennyZhang/NetEase
1dbcea741bd294da633233c766b24113c293f94e
[ "MIT" ]
10
2015-05-28T15:19:18.000Z
2018-06-26T17:54:31.000Z
# -*- coding: utf-8 -*- import re import os import json import requests from Crypto.Cipher import AES import hashlib import random import base64 import sqlite3 default_timeout = 10 modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7' nonce = '0CoJUm6Qyw8W8jud' pubKey = '010001' header = { 'Accept': '*/*', 'Accept-Encoding': 'gzip,deflate,sdch', 'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'music.163.com', 'Referer': 'http://music.163.com/search/', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36' } # 登录加密算法, 基于https://github.com/stkevintan/nw_musicbox脚本实现 def encrypted_login(username, password): text = { 'username': username, 'password': hashlib.md5(str(password)).hexdigest(), 'rememberLogin': 'true' } text = json.dumps(text) secKey = createSecretKey(16) encText = aesEncrypt(aesEncrypt(text, nonce), secKey) encSecKey = rsaEncrypt(secKey, pubKey, modulus) data = { 'params': encText, 'encSecKey': encSecKey } return data def encrypted_phonelogin(username, password): text = { 'phone': username, 'password': password, 'rememberLogin': 'true' } text = json.dumps(text) secKey = createSecretKey(16) encText = aesEncrypt(aesEncrypt(text, nonce), secKey) encSecKey = rsaEncrypt(secKey, pubKey, modulus) data = { 'params': encText, 'encSecKey': encSecKey } return data def aesEncrypt(text, secKey): pad = 16 - len(text) % 16 text = text + pad * chr(pad) encryptor = AES.new(secKey, 2, '0102030405060708') ciphertext = encryptor.encrypt(text) ciphertext = base64.b64encode(ciphertext) return ciphertext def rsaEncrypt(text, pubKey, modulus): text = text[::-1] rs = int(text.encode('hex'), 16) ** int(pubKey, 16) % int(modulus, 16) return format(rs, 'x').zfill(256) def createSecretKey(size): return (''.join(map(lambda xx: (hex(ord(xx))[2:]), os.urandom(size))))[0:16] # 登录 def login(username, password, databasePath): pattern = re.compile(r'^0\d{2,3}\d{7,8}$|^1[34578]\d{9}$') if (pattern.match(username)): return phone_login(username, password) action = 'https://music.163.com/weapi/login/' data = encrypted_login(username, password) try: userInfo = httpRequest(action, data) sqlite_write(userInfo, databasePath) return 0 except: return 1 # 手机登录 def phone_login(username, password, databasePath): action = 'http://music.163.com/weapi/login/cellphone' data = encrypted_phonelogin(username, password) try: userInfo = httpRequest(action, data) sqlite_write(userInfo, databasePath) return 0 except: return 1 def httpRequest(action, query): connection = requests.post( action, data=query, headers=header, timeout=default_timeout ) connection.encoding = "UTF-8" cookies_tuple = tuple(connection.cookies) cookies = getCookies(cookies_tuple) data = json.loads(connection.text) userId = data['account']['id'] userName = data['account']['userName'] userNickName = data['profile']['nickname'] userInfo = [userId, userName, userNickName, cookies] return userInfo def sqlite_write(user_info, databasePath) : conn = sqlite3.connect(databasePath) sql = """update user_info set user_id='%s', user_name='%s', user_nickname='%s', user_autologin='1', user_cookies='%s' where id='1'; """ % (user_info[0], user_info[1], user_info[2], user_info[3]) conn.execute(sql) conn.commit() conn.close() def getCookies(_tuple): cookies = "" for i in _tuple : _str = str(i) cookies += _str.split(' ')[1] + "; " return cookies
26.916084
270
0.720447
b66435dc0fec987b9180af628e2577e8d6939962
5,232
py
Python
onderwijsscrapers/onderwijsscrapers/pipelines.py
dsbaars/openonderwijsdata-api
9d0415e82e411cc0102cec98ec5668eb9540cb35
[ "CC-BY-4.0" ]
null
null
null
onderwijsscrapers/onderwijsscrapers/pipelines.py
dsbaars/openonderwijsdata-api
9d0415e82e411cc0102cec98ec5668eb9540cb35
[ "CC-BY-4.0" ]
null
null
null
onderwijsscrapers/onderwijsscrapers/pipelines.py
dsbaars/openonderwijsdata-api
9d0415e82e411cc0102cec98ec5668eb9540cb35
[ "CC-BY-4.0" ]
null
null
null
from datetime import datetime import pytz from scrapy.conf import settings from scrapy.exceptions import DropItem from scrapy import log # from onderwijsscrapers import exporters from onderwijsscrapers.item_enrichment import bag42_geocode from onderwijsscrapers.validation import validate class OnderwijsscrapersPipeline(object): def __init__(self): self.scrape_started = datetime.utcnow().replace(tzinfo=pytz.utc)\ .strftime('%Y-%m-%dT%H:%M:%SZ') self.items = {} self.universal_items = {} def process_item(self, item, spider): # Check if the fields that identify the item are present. If not, # log and drop the item. id_fields = settings['EXPORT_SETTINGS'][spider.name]['id_fields'] if not all(field in item for field in id_fields): log.msg('Dropped item, not all required fields are present. %s' % item, level=log.WARNING, spider=spider) raise DropItem return item_id = '-'.join([str(item[field]) for field in id_fields]) print '=' * 10 print item_id if item_id not in self.items: self.items[item_id] = dict(item) else: self.items[item_id].update(dict(item)) # Check if this item should be included into all related items # of the same spider (e.g. ignore reference year) universal_item = False if 'ignore_id_fields' in item: for field in item['ignore_id_fields']: item[field] = None del item['ignore_id_fields'] universal_item = True item_id = '-'.join([str(item[field]) for field in id_fields]) if universal_item: self.universal_items[item_id] = dict(item).copy() return item def close_spider(self, spider): export_settings = settings['EXPORT_SETTINGS'][spider.name] items = {} validation_reports = [] # Add metadata to items and (if required) merge universal items. # Also validate and perform 'item_enrichment' functions # (i.e. geocodeing). id_fields = export_settings['id_fields'] total_items = len(self.items.keys()) count = 0 # Create colander schema for all items validation_schema = export_settings['schema']() for item_id, item in self.items.iteritems(): universal_item = 'None-%s' % '-'.join([str(item[field]) for field in id_fields[1:]]) if universal_item in self.universal_items: universal_item = self.universal_items[universal_item] if 'reference_year' in universal_item: del universal_item['reference_year'] item.update(universal_item) if 'ignore_id_fields' in item: del item['ignore_id_fields'] item['meta'] = { 'scrape_started_at': self.scrape_started, 'item_scraped_at': datetime.utcnow().replace(tzinfo=pytz.utc) .strftime('%Y-%m-%dT%H:%M:%SZ') } # Geocode if enabled for this index if export_settings['geocode']: count += 1 for address_field in export_settings['geocode_fields']: if address_field in item: geocoded = bag42_geocode(item[address_field]) if geocoded: item[address_field].update(geocoded) log.msg('Geocoded %d/%d' % (count, total_items), level=log.INFO) # Validate the item is this is enabled if export_settings['validate']: item, validation = validate(validation_schema, export_settings['index'], export_settings['doctype'], item_id, item) validation_reports.append(validation) items[item_id] = item for method, method_properties in settings['EXPORT_METHODS'].items(): # Export the document exporter = method_properties['exporter'](self.scrape_started, export_settings['index'], export_settings['doctype'], **method_properties['options']) for item_id, item in items.iteritems(): exporter.save(item, item_id) exporter.close() # Export validation documents if export_settings['validate']: exporter = method_properties['exporter'](self.scrape_started, export_settings['validation_index'], 'doc_validation', **method_properties['options']) for item in validation_reports: exporter.save(item) exporter.close()
39.338346
93
0.539946
7567ce0ac170fd333d2bfa438124f09037490566
1,908
py
Python
src/file_infos.py
guionardo/py-housekeeping
3aaedc001b7ddb0b5a3397f99bd6bf4e8958f69c
[ "MIT" ]
null
null
null
src/file_infos.py
guionardo/py-housekeeping
3aaedc001b7ddb0b5a3397f99bd6bf4e8958f69c
[ "MIT" ]
null
null
null
src/file_infos.py
guionardo/py-housekeeping
3aaedc001b7ddb0b5a3397f99bd6bf4e8958f69c
[ "MIT" ]
null
null
null
import logging import os from file_age import is_aged_file class FileInfos: LOG = logging.getLogger(__name__) def __init__(self, folder): self._folder = folder self._files = [] for root, dirs, files in os.walk(folder): for file in files: fn = os.path.join(root, file) self._files.append( (fn, os.path.getmtime(fn), os.path.getsize(fn))) self._files.sort(key=lambda x: x[1]) def get_files(self): return self._files def processing_files(self, rules): keep = [] processing = [] if rules.max_file_count > 0 and\ len(self._files) > rules.max_file_count: keep = self._files[-rules.max_file_count:] processing = self._files[0:len(self._files)-rules.max_file_count] else: keep = self._files if rules.max_folder_size > 0: folder_size = 0 keep0 = [] while keep: file = keep.pop(0) if folder_size+file[2] < rules.max_folder_size: keep0.append(file) folder_size += file[2] else: processing.append(file) keep = keep0 if rules.max_file_age.seconds > 0: keep0 = [] while keep: file = keep.pop(0) if not is_aged_file(file[1], rules.max_file_age): keep0.append(file) else: processing.append(file) keep = keep0 if processing: size_processing = 0 for file in processing: size_processing += file[2] self.LOG.info('Processing %s files (%s bytes) in folder %s', len( processing), size_processing, self._folder) return processing, keep
29.8125
77
0.516247
d669cb1b0bdea7ac60c5496d2bd4da57a6c777f6
8,839
py
Python
doc/conf.py
Tim-HU/sphinx-report
3a0dc225e594c4b2083dff7a93b6d77054256416
[ "BSD-2-Clause" ]
1
2020-04-10T12:48:40.000Z
2020-04-10T12:48:40.000Z
doc/conf.py
Tim-HU/sphinx-report
3a0dc225e594c4b2083dff7a93b6d77054256416
[ "BSD-2-Clause" ]
null
null
null
doc/conf.py
Tim-HU/sphinx-report
3a0dc225e594c4b2083dff7a93b6d77054256416
[ "BSD-2-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # # Test documentation build configuration file, created by # sphinx-quickstart on Mon Mar 23 15:27:57 2009. # # 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, 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.extend( [os.path.join('..', 'SphinxReport'), os.path.abspath('trackers'), os.path.abspath('.') ] ) # The cachedir holding the data from the Trackers. If not defined, no cache will # be used. sphinxreport_cachedir=os.path.abspath("_cache") # urls to include within the annotation of an image sphinxreport_urls=("code", "rst", "data") # The Database backend. Possible values are mysql, psql and sqlite sphinxreport_sql_backend="sqlite:///%s/csvdb" % os.path.abspath(".") # add errors into the document sphinxreport_show_errors = True # add warnings into the document sphinxreport_show_warnings = True # static images to create for each plot # a tuple of (id, format, dpi). sphinxreport_images=( ( "hires", "hires.png", 200), # ( "eps", "eps", 50 ), ( "svg", "svg", 50 ) ) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'sphinx.ext.todo', 'SphinxReport.only_directives', 'SphinxReport.roles', 'SphinxReport.errors_directive', 'SphinxReport.warnings_directive', 'SphinxReport.report_directive' ] # inheritance_diagram broken in python3 if sys.version_info[0] == 2: extensions.append( 'sphinx.ext.inheritance_diagram' ) # Included at the end of each rst file rst_epilog=''' .. _CGAT Training Programme: http://www.cgat.org .. _pysam: http://code.google.com/p/pysam/ .. _samtools: http://samtools.sourceforge.net/ .. _tabix: http://samtools.sourceforge.net/tabix.shtml/ .. _Galaxy: https://main.g2.bx.psu.edu/ .. _cython: http://cython.org/ .. _pyximport: http://www.prescod.net/pyximport/ .. _sphinx: http://sphinx-doc.org/ .. _ruffus: http://www.ruffus.org.uk/ .. _sphinxreport: http://code.google.com/p/sphinx-report/ .. _sqlite: http://www.sqlite.org/ .. _make: http://www.gnu.org/software/make .. _UCSC: http://genome.ucsc.edu .. _mysql: https://mariadb.org/ .. _postgres: http://www.postgresql.org/ .. _bedtools: http://bedtools.readthedocs.org/en/latest/ .. _UCSC Tools: http://genome.ucsc.edu/admin/git.html .. _seaborn: https://github.com/mwaskom/seaborn .. _ggplot: https://github.com/yhat/ggplot/ .. _ggplot2: http://ggplot2.org/ .. _rpy2: http://rpy.sourceforge.net/rpy2.html .. _pandas: http://pandas.pydata.org/ ''' # 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' # The master toctree document. master_doc = 'contents' # General information about the project. project = u'SphinxReport' copyright = u'2009, Andreas Heger' # 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 = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0a2' # 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 documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_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, include todo list todo_include_todos = True # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'nature' # 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'] # 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 = { 'index' : 'index.html', } # 'gallery' : 'gallery.html' } # If false, no module index is generated. #html_use_modindex = 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, 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 = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Testdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('contents', 'Test.tex', r'Test Documentation', r'Andreas Heger', '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 # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
33.229323
81
0.700079
77baf2ed891cc3ae9c85768d456ca4777a8029af
811
py
Python
models/vgg.py
SanaAwan5/edgecase_backdoors
c892024242e45557fa94363ecadc355a9250bca0
[ "MIT" ]
8
2021-05-08T07:49:45.000Z
2022-03-17T16:18:05.000Z
models/vgg.py
SanaAwan5/edgecase_backdoors
c892024242e45557fa94363ecadc355a9250bca0
[ "MIT" ]
3
2021-05-19T14:58:53.000Z
2022-01-13T15:53:19.000Z
models/vgg.py
SanaAwan5/edgecase_backdoors
c892024242e45557fa94363ecadc355a9250bca0
[ "MIT" ]
5
2021-05-22T08:56:20.000Z
2022-03-31T06:50:21.000Z
''' dummy file to use as an adaptor to switch between two vgg architectures vgg9: use vgg9_only.py which is from https://github.com/kuangliu/pytorch-cifar vgg11/13/16/19: use vgg_modified.py which is modified from https://github.com/pytorch/vision.git ''' import torch import torch.nn as nn import models.vgg9_only as vgg9 import models.vgg_modified as vgg_mod import logging logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) def get_vgg_model(vgg_name): logging.info("GET_VGG_MODEL: Fetch {}".format(vgg_name)) if vgg_name == 'vgg9': return vgg9.VGG('VGG9') elif vgg_name == 'vgg11': return vgg_mod.vgg11() elif vgg_name == 'vgg13': return vgg_mod.vgg13() elif vgg_name == 'vgg16': return vgg_mod.vgg16()
26.16129
100
0.70037
04052510f5d425892d1dd652a4c373a261680547
37,155
py
Python
xarray/core/rolling.py
lusewell/xarray
da99a5664df4f5013c2f6b0e758394bec5e0bc80
[ "CC-BY-4.0", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
xarray/core/rolling.py
lusewell/xarray
da99a5664df4f5013c2f6b0e758394bec5e0bc80
[ "CC-BY-4.0", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "BSD-3-Clause" ]
3
2021-09-13T13:10:45.000Z
2022-01-10T13:09:30.000Z
xarray/core/rolling.py
lusewell/xarray
da99a5664df4f5013c2f6b0e758394bec5e0bc80
[ "CC-BY-4.0", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
import functools import itertools import warnings from typing import Any, Callable, Dict import numpy as np from . import dtypes, duck_array_ops, utils from .arithmetic import CoarsenArithmetic from .options import _get_keep_attrs from .pycompat import is_duck_dask_array from .utils import either_dict_or_kwargs try: import bottleneck except ImportError: # use numpy methods instead bottleneck = None _ROLLING_REDUCE_DOCSTRING_TEMPLATE = """\ Reduce this object's data windows by applying `{name}` along its dimension. Parameters ---------- keep_attrs : bool, default: None If True, the attributes (``attrs``) will be copied from the original object to the new one. If False, the new object will be returned without attributes. If None uses the global default. **kwargs : dict Additional keyword arguments passed on to `{name}`. Returns ------- reduced : same type as caller New object with `{name}` applied along its rolling dimnension. """ class Rolling: """A object that implements the moving window pattern. See Also -------- xarray.Dataset.groupby xarray.DataArray.groupby xarray.Dataset.rolling xarray.DataArray.rolling """ __slots__ = ("obj", "window", "min_periods", "center", "dim") _attributes = ("window", "min_periods", "center", "dim") def __init__(self, obj, windows, min_periods=None, center=False): """ Moving window object. Parameters ---------- obj : Dataset or DataArray Object to window. windows : mapping of hashable to int A mapping from the name of the dimension to create the rolling window along (e.g. `time`) to the size of the moving window. min_periods : int, default: None Minimum number of observations in window required to have a value (otherwise result is NA). The default, None, is equivalent to setting min_periods equal to the size of the window. center : bool, default: False Set the labels at the center of the window. Returns ------- rolling : type of input argument """ self.dim, self.window = [], [] for d, w in windows.items(): self.dim.append(d) if w <= 0: raise ValueError("window must be > 0") self.window.append(w) self.center = self._mapping_to_list(center, default=False) self.obj = obj # attributes if min_periods is not None and min_periods <= 0: raise ValueError("min_periods must be greater than zero or None") self.min_periods = np.prod(self.window) if min_periods is None else min_periods def __repr__(self): """provide a nice str repr of our rolling object""" attrs = [ "{k}->{v}{c}".format(k=k, v=w, c="(center)" if c else "") for k, w, c in zip(self.dim, self.window, self.center) ] return "{klass} [{attrs}]".format( klass=self.__class__.__name__, attrs=",".join(attrs) ) def __len__(self): return self.obj.sizes[self.dim] def _reduce_method( # type: ignore[misc] name: str, fillna, rolling_agg_func: Callable = None ) -> Callable: """Constructs reduction methods built on a numpy reduction function (e.g. sum), a bottleneck reduction function (e.g. move_sum), or a Rolling reduction (_mean).""" if rolling_agg_func: array_agg_func = None else: array_agg_func = getattr(duck_array_ops, name) bottleneck_move_func = getattr(bottleneck, "move_" + name, None) def method(self, keep_attrs=None, **kwargs): keep_attrs = self._get_keep_attrs(keep_attrs) return self._numpy_or_bottleneck_reduce( array_agg_func, bottleneck_move_func, rolling_agg_func, keep_attrs=keep_attrs, fillna=fillna, **kwargs, ) method.__name__ = name method.__doc__ = _ROLLING_REDUCE_DOCSTRING_TEMPLATE.format(name=name) return method def _mean(self, keep_attrs, **kwargs): result = self.sum(keep_attrs=False, **kwargs) / self.count(keep_attrs=False) if keep_attrs: result.attrs = self.obj.attrs return result _mean.__doc__ = _ROLLING_REDUCE_DOCSTRING_TEMPLATE.format(name="mean") argmax = _reduce_method("argmax", dtypes.NINF) argmin = _reduce_method("argmin", dtypes.INF) max = _reduce_method("max", dtypes.NINF) min = _reduce_method("min", dtypes.INF) prod = _reduce_method("prod", 1) sum = _reduce_method("sum", 0) mean = _reduce_method("mean", None, _mean) std = _reduce_method("std", None) var = _reduce_method("var", None) median = _reduce_method("median", None) def count(self, keep_attrs=None): keep_attrs = self._get_keep_attrs(keep_attrs) rolling_count = self._counts(keep_attrs=keep_attrs) enough_periods = rolling_count >= self.min_periods return rolling_count.where(enough_periods) count.__doc__ = _ROLLING_REDUCE_DOCSTRING_TEMPLATE.format(name="count") def _mapping_to_list( self, arg, default=None, allow_default=True, allow_allsame=True ): if utils.is_dict_like(arg): if allow_default: return [arg.get(d, default) for d in self.dim] for d in self.dim: if d not in arg: raise KeyError(f"argument has no key {d}.") return [arg[d] for d in self.dim] elif allow_allsame: # for single argument return [arg] * len(self.dim) elif len(self.dim) == 1: return [arg] else: raise ValueError( "Mapping argument is necessary for {}d-rolling.".format(len(self.dim)) ) def _get_keep_attrs(self, keep_attrs): if keep_attrs is None: keep_attrs = _get_keep_attrs(default=True) return keep_attrs class DataArrayRolling(Rolling): __slots__ = ("window_labels",) def __init__(self, obj, windows, min_periods=None, center=False): """ Moving window object for DataArray. You should use DataArray.rolling() method to construct this object instead of the class constructor. Parameters ---------- obj : DataArray Object to window. windows : mapping of hashable to int A mapping from the name of the dimension to create the rolling exponential window along (e.g. `time`) to the size of the moving window. min_periods : int, default: None Minimum number of observations in window required to have a value (otherwise result is NA). The default, None, is equivalent to setting min_periods equal to the size of the window. center : bool, default: False Set the labels at the center of the window. Returns ------- rolling : type of input argument See Also -------- xarray.DataArray.rolling xarray.DataArray.groupby xarray.Dataset.rolling xarray.Dataset.groupby """ super().__init__(obj, windows, min_periods=min_periods, center=center) # TODO legacy attribute self.window_labels = self.obj[self.dim[0]] def __iter__(self): if len(self.dim) > 1: raise ValueError("__iter__ is only supported for 1d-rolling") stops = np.arange(1, len(self.window_labels) + 1) starts = stops - int(self.window[0]) starts[: int(self.window[0])] = 0 for (label, start, stop) in zip(self.window_labels, starts, stops): window = self.obj.isel(**{self.dim[0]: slice(start, stop)}) counts = window.count(dim=self.dim[0]) window = window.where(counts >= self.min_periods) yield (label, window) def construct( self, window_dim=None, stride=1, fill_value=dtypes.NA, keep_attrs=None, **window_dim_kwargs, ): """ Convert this rolling object to xr.DataArray, where the window dimension is stacked as a new dimension Parameters ---------- window_dim : str or mapping, optional A mapping from dimension name to the new window dimension names. stride : int or mapping of int, default: 1 Size of stride for the rolling window. fill_value : default: dtypes.NA Filling value to match the dimension size. keep_attrs : bool, default: None If True, the attributes (``attrs``) will be copied from the original object to the new one. If False, the new object will be returned without attributes. If None uses the global default. **window_dim_kwargs : {dim: new_name, ...}, optional The keyword arguments form of ``window_dim``. Returns ------- DataArray that is a view of the original array. The returned array is not writeable. Examples -------- >>> da = xr.DataArray(np.arange(8).reshape(2, 4), dims=("a", "b")) >>> rolling = da.rolling(b=3) >>> rolling.construct("window_dim") <xarray.DataArray (a: 2, b: 4, window_dim: 3)> array([[[nan, nan, 0.], [nan, 0., 1.], [ 0., 1., 2.], [ 1., 2., 3.]], <BLANKLINE> [[nan, nan, 4.], [nan, 4., 5.], [ 4., 5., 6.], [ 5., 6., 7.]]]) Dimensions without coordinates: a, b, window_dim >>> rolling = da.rolling(b=3, center=True) >>> rolling.construct("window_dim") <xarray.DataArray (a: 2, b: 4, window_dim: 3)> array([[[nan, 0., 1.], [ 0., 1., 2.], [ 1., 2., 3.], [ 2., 3., nan]], <BLANKLINE> [[nan, 4., 5.], [ 4., 5., 6.], [ 5., 6., 7.], [ 6., 7., nan]]]) Dimensions without coordinates: a, b, window_dim """ return self._construct( self.obj, window_dim=window_dim, stride=stride, fill_value=fill_value, keep_attrs=keep_attrs, **window_dim_kwargs, ) def _construct( self, obj, window_dim=None, stride=1, fill_value=dtypes.NA, keep_attrs=None, **window_dim_kwargs, ): from .dataarray import DataArray keep_attrs = self._get_keep_attrs(keep_attrs) if window_dim is None: if len(window_dim_kwargs) == 0: raise ValueError( "Either window_dim or window_dim_kwargs need to be specified." ) window_dim = {d: window_dim_kwargs[d] for d in self.dim} window_dim = self._mapping_to_list( window_dim, allow_default=False, allow_allsame=False ) stride = self._mapping_to_list(stride, default=1) window = obj.variable.rolling_window( self.dim, self.window, window_dim, self.center, fill_value=fill_value ) attrs = obj.attrs if keep_attrs else {} result = DataArray( window, dims=obj.dims + tuple(window_dim), coords=obj.coords, attrs=attrs, name=obj.name, ) return result.isel( **{d: slice(None, None, s) for d, s in zip(self.dim, stride)} ) def reduce(self, func, keep_attrs=None, **kwargs): """Reduce the items in this group by applying `func` along some dimension(s). Parameters ---------- func : callable Function which can be called in the form `func(x, **kwargs)` to return the result of collapsing an np.ndarray over an the rolling dimension. keep_attrs : bool, default: None If True, the attributes (``attrs``) will be copied from the original object to the new one. If False, the new object will be returned without attributes. If None uses the global default. **kwargs : dict Additional keyword arguments passed on to `func`. Returns ------- reduced : DataArray Array with summarized data. Examples -------- >>> da = xr.DataArray(np.arange(8).reshape(2, 4), dims=("a", "b")) >>> rolling = da.rolling(b=3) >>> rolling.construct("window_dim") <xarray.DataArray (a: 2, b: 4, window_dim: 3)> array([[[nan, nan, 0.], [nan, 0., 1.], [ 0., 1., 2.], [ 1., 2., 3.]], <BLANKLINE> [[nan, nan, 4.], [nan, 4., 5.], [ 4., 5., 6.], [ 5., 6., 7.]]]) Dimensions without coordinates: a, b, window_dim >>> rolling.reduce(np.sum) <xarray.DataArray (a: 2, b: 4)> array([[nan, nan, 3., 6.], [nan, nan, 15., 18.]]) Dimensions without coordinates: a, b >>> rolling = da.rolling(b=3, min_periods=1) >>> rolling.reduce(np.nansum) <xarray.DataArray (a: 2, b: 4)> array([[ 0., 1., 3., 6.], [ 4., 9., 15., 18.]]) Dimensions without coordinates: a, b """ keep_attrs = self._get_keep_attrs(keep_attrs) rolling_dim = { d: utils.get_temp_dimname(self.obj.dims, f"_rolling_dim_{d}") for d in self.dim } # save memory with reductions GH4325 fillna = kwargs.pop("fillna", dtypes.NA) if fillna is not dtypes.NA: obj = self.obj.fillna(fillna) else: obj = self.obj windows = self._construct( obj, rolling_dim, keep_attrs=keep_attrs, fill_value=fillna ) result = windows.reduce( func, dim=list(rolling_dim.values()), keep_attrs=keep_attrs, **kwargs ) # Find valid windows based on count. counts = self._counts(keep_attrs=False) return result.where(counts >= self.min_periods) def _counts(self, keep_attrs): """Number of non-nan entries in each rolling window.""" rolling_dim = { d: utils.get_temp_dimname(self.obj.dims, f"_rolling_dim_{d}") for d in self.dim } # We use False as the fill_value instead of np.nan, since boolean # array is faster to be reduced than object array. # The use of skipna==False is also faster since it does not need to # copy the strided array. counts = ( self.obj.notnull(keep_attrs=keep_attrs) .rolling( center={d: self.center[i] for i, d in enumerate(self.dim)}, **{d: w for d, w in zip(self.dim, self.window)}, ) .construct(rolling_dim, fill_value=False, keep_attrs=keep_attrs) .sum(dim=list(rolling_dim.values()), skipna=False, keep_attrs=keep_attrs) ) return counts def _bottleneck_reduce(self, func, keep_attrs, **kwargs): from .dataarray import DataArray # bottleneck doesn't allow min_count to be 0, although it should # work the same as if min_count = 1 # Note bottleneck only works with 1d-rolling. if self.min_periods is not None and self.min_periods == 0: min_count = 1 else: min_count = self.min_periods axis = self.obj.get_axis_num(self.dim[0]) padded = self.obj.variable if self.center[0]: if is_duck_dask_array(padded.data): # workaround to make the padded chunk size larger than # self.window - 1 shift = -(self.window[0] + 1) // 2 offset = (self.window[0] - 1) // 2 valid = (slice(None),) * axis + ( slice(offset, offset + self.obj.shape[axis]), ) else: shift = (-self.window[0] // 2) + 1 valid = (slice(None),) * axis + (slice(-shift, None),) padded = padded.pad({self.dim[0]: (0, -shift)}, mode="constant") if is_duck_dask_array(padded.data): raise AssertionError("should not be reachable") else: values = func( padded.data, window=self.window[0], min_count=min_count, axis=axis ) if self.center[0]: values = values[valid] attrs = self.obj.attrs if keep_attrs else {} return DataArray(values, self.obj.coords, attrs=attrs, name=self.obj.name) def _numpy_or_bottleneck_reduce( self, array_agg_func, bottleneck_move_func, rolling_agg_func, keep_attrs, fillna, **kwargs, ): if "dim" in kwargs: warnings.warn( f"Reductions are applied along the rolling dimension(s) " f"'{self.dim}'. Passing the 'dim' kwarg to reduction " f"operations has no effect.", DeprecationWarning, stacklevel=3, ) del kwargs["dim"] if ( bottleneck_move_func is not None and not is_duck_dask_array(self.obj.data) and len(self.dim) == 1 ): # TODO: renable bottleneck with dask after the issues # underlying https://github.com/pydata/xarray/issues/2940 are # fixed. return self._bottleneck_reduce( bottleneck_move_func, keep_attrs=keep_attrs, **kwargs ) if rolling_agg_func: return rolling_agg_func(self, keep_attrs=self._get_keep_attrs(keep_attrs)) if fillna is not None: if fillna is dtypes.INF: fillna = dtypes.get_pos_infinity(self.obj.dtype, max_for_int=True) elif fillna is dtypes.NINF: fillna = dtypes.get_neg_infinity(self.obj.dtype, min_for_int=True) kwargs.setdefault("skipna", False) kwargs.setdefault("fillna", fillna) return self.reduce(array_agg_func, keep_attrs=keep_attrs, **kwargs) class DatasetRolling(Rolling): __slots__ = ("rollings",) def __init__(self, obj, windows, min_periods=None, center=False): """ Moving window object for Dataset. You should use Dataset.rolling() method to construct this object instead of the class constructor. Parameters ---------- obj : Dataset Object to window. windows : mapping of hashable to int A mapping from the name of the dimension to create the rolling exponential window along (e.g. `time`) to the size of the moving window. min_periods : int, default: None Minimum number of observations in window required to have a value (otherwise result is NA). The default, None, is equivalent to setting min_periods equal to the size of the window. center : bool or mapping of hashable to bool, default: False Set the labels at the center of the window. Returns ------- rolling : type of input argument See Also -------- xarray.Dataset.rolling xarray.DataArray.rolling xarray.Dataset.groupby xarray.DataArray.groupby """ super().__init__(obj, windows, min_periods, center) if any(d not in self.obj.dims for d in self.dim): raise KeyError(self.dim) # Keep each Rolling object as a dictionary self.rollings = {} for key, da in self.obj.data_vars.items(): # keeps rollings only for the dataset depending on self.dim dims, center = [], {} for i, d in enumerate(self.dim): if d in da.dims: dims.append(d) center[d] = self.center[i] if dims: w = {d: windows[d] for d in dims} self.rollings[key] = DataArrayRolling(da, w, min_periods, center) def _dataset_implementation(self, func, keep_attrs, **kwargs): from .dataset import Dataset keep_attrs = self._get_keep_attrs(keep_attrs) reduced = {} for key, da in self.obj.data_vars.items(): if any(d in da.dims for d in self.dim): reduced[key] = func(self.rollings[key], keep_attrs=keep_attrs, **kwargs) else: reduced[key] = self.obj[key].copy() # we need to delete the attrs of the copied DataArray if not keep_attrs: reduced[key].attrs = {} attrs = self.obj.attrs if keep_attrs else {} return Dataset(reduced, coords=self.obj.coords, attrs=attrs) def reduce(self, func, keep_attrs=None, **kwargs): """Reduce the items in this group by applying `func` along some dimension(s). Parameters ---------- func : callable Function which can be called in the form `func(x, **kwargs)` to return the result of collapsing an np.ndarray over an the rolling dimension. keep_attrs : bool, default: None If True, the attributes (``attrs``) will be copied from the original object to the new one. If False, the new object will be returned without attributes. If None uses the global default. **kwargs : dict Additional keyword arguments passed on to `func`. Returns ------- reduced : DataArray Array with summarized data. """ return self._dataset_implementation( functools.partial(DataArrayRolling.reduce, func=func), keep_attrs=keep_attrs, **kwargs, ) def _counts(self, keep_attrs): return self._dataset_implementation( DataArrayRolling._counts, keep_attrs=keep_attrs ) def _numpy_or_bottleneck_reduce( self, array_agg_func, bottleneck_move_func, rolling_agg_func, keep_attrs, **kwargs, ): return self._dataset_implementation( functools.partial( DataArrayRolling._numpy_or_bottleneck_reduce, array_agg_func=array_agg_func, bottleneck_move_func=bottleneck_move_func, rolling_agg_func=rolling_agg_func, ), keep_attrs=keep_attrs, **kwargs, ) def construct( self, window_dim=None, stride=1, fill_value=dtypes.NA, keep_attrs=None, **window_dim_kwargs, ): """ Convert this rolling object to xr.Dataset, where the window dimension is stacked as a new dimension Parameters ---------- window_dim : str or mapping, optional A mapping from dimension name to the new window dimension names. Just a string can be used for 1d-rolling. stride : int, optional size of stride for the rolling window. fill_value : Any, default: dtypes.NA Filling value to match the dimension size. **window_dim_kwargs : {dim: new_name, ...}, optional The keyword arguments form of ``window_dim``. Returns ------- Dataset with variables converted from rolling object. """ from .dataset import Dataset keep_attrs = self._get_keep_attrs(keep_attrs) if window_dim is None: if len(window_dim_kwargs) == 0: raise ValueError( "Either window_dim or window_dim_kwargs need to be specified." ) window_dim = {d: window_dim_kwargs[d] for d in self.dim} window_dim = self._mapping_to_list( window_dim, allow_default=False, allow_allsame=False ) stride = self._mapping_to_list(stride, default=1) dataset = {} for key, da in self.obj.data_vars.items(): # keeps rollings only for the dataset depending on self.dim dims = [d for d in self.dim if d in da.dims] if dims: wi = {d: window_dim[i] for i, d in enumerate(self.dim) if d in da.dims} st = {d: stride[i] for i, d in enumerate(self.dim) if d in da.dims} dataset[key] = self.rollings[key].construct( window_dim=wi, fill_value=fill_value, stride=st, keep_attrs=keep_attrs, ) else: dataset[key] = da.copy() # as the DataArrays can be copied we need to delete the attrs if not keep_attrs: dataset[key].attrs = {} attrs = self.obj.attrs if keep_attrs else {} return Dataset(dataset, coords=self.obj.coords, attrs=attrs).isel( **{d: slice(None, None, s) for d, s in zip(self.dim, stride)} ) class Coarsen(CoarsenArithmetic): """A object that implements the coarsen. See Also -------- Dataset.coarsen DataArray.coarsen """ __slots__ = ( "obj", "boundary", "coord_func", "windows", "side", "trim_excess", ) _attributes = ("windows", "side", "trim_excess") def __init__(self, obj, windows, boundary, side, coord_func): """ Moving window object. Parameters ---------- obj : Dataset or DataArray Object to window. windows : mapping of hashable to int A mapping from the name of the dimension to create the rolling exponential window along (e.g. `time`) to the size of the moving window. boundary : 'exact' | 'trim' | 'pad' If 'exact', a ValueError will be raised if dimension size is not a multiple of window size. If 'trim', the excess indexes are trimed. If 'pad', NA will be padded. side : 'left' or 'right' or mapping from dimension to 'left' or 'right' coord_func : mapping from coordinate name to func. Returns ------- coarsen """ self.obj = obj self.windows = windows self.side = side self.boundary = boundary absent_dims = [dim for dim in windows.keys() if dim not in self.obj.dims] if absent_dims: raise ValueError( f"Dimensions {absent_dims!r} not found in {self.obj.__class__.__name__}." ) if not utils.is_dict_like(coord_func): coord_func = {d: coord_func for d in self.obj.dims} for c in self.obj.coords: if c not in coord_func: coord_func[c] = duck_array_ops.mean self.coord_func = coord_func def _get_keep_attrs(self, keep_attrs): if keep_attrs is None: keep_attrs = _get_keep_attrs(default=True) return keep_attrs def __repr__(self): """provide a nice str repr of our coarsen object""" attrs = [ "{k}->{v}".format(k=k, v=getattr(self, k)) for k in self._attributes if getattr(self, k, None) is not None ] return "{klass} [{attrs}]".format( klass=self.__class__.__name__, attrs=",".join(attrs) ) def construct( self, window_dim=None, keep_attrs=None, **window_dim_kwargs, ): """ Convert this Coarsen object to a DataArray or Dataset, where the coarsening dimension is split or reshaped to two new dimensions. Parameters ---------- window_dim: mapping A mapping from existing dimension name to new dimension names. The size of the second dimension will be the length of the coarsening window. keep_attrs: bool, optional Preserve attributes if True **window_dim_kwargs : {dim: new_name, ...} The keyword arguments form of ``window_dim``. Returns ------- Dataset or DataArray with reshaped dimensions Examples -------- >>> da = xr.DataArray(np.arange(24), dims="time") >>> da.coarsen(time=12).construct(time=("year", "month")) <xarray.DataArray (year: 2, month: 12)> array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]]) Dimensions without coordinates: year, month See Also -------- DataArrayRolling.construct DatasetRolling.construct """ from .dataarray import DataArray from .dataset import Dataset window_dim = either_dict_or_kwargs( window_dim, window_dim_kwargs, "Coarsen.construct" ) if not window_dim: raise ValueError( "Either window_dim or window_dim_kwargs need to be specified." ) bad_new_dims = tuple( win for win, dims in window_dim.items() if len(dims) != 2 or isinstance(dims, str) ) if bad_new_dims: raise ValueError( f"Please provide exactly two dimension names for the following coarsening dimensions: {bad_new_dims}" ) if keep_attrs is None: keep_attrs = _get_keep_attrs(default=True) missing_dims = set(window_dim) - set(self.windows) if missing_dims: raise ValueError( f"'window_dim' must contain entries for all dimensions to coarsen. Missing {missing_dims}" ) extra_windows = set(self.windows) - set(window_dim) if extra_windows: raise ValueError( f"'window_dim' includes dimensions that will not be coarsened: {extra_windows}" ) reshaped = Dataset() if isinstance(self.obj, DataArray): obj = self.obj._to_temp_dataset() else: obj = self.obj reshaped.attrs = obj.attrs if keep_attrs else {} for key, var in obj.variables.items(): reshaped_dims = tuple( itertools.chain(*[window_dim.get(dim, [dim]) for dim in list(var.dims)]) ) if reshaped_dims != var.dims: windows = {w: self.windows[w] for w in window_dim if w in var.dims} reshaped_var, _ = var.coarsen_reshape(windows, self.boundary, self.side) attrs = var.attrs if keep_attrs else {} reshaped[key] = (reshaped_dims, reshaped_var, attrs) else: reshaped[key] = var should_be_coords = set(window_dim) & set(self.obj.coords) result = reshaped.set_coords(should_be_coords) if isinstance(self.obj, DataArray): return self.obj._from_temp_dataset(result) else: return result class DataArrayCoarsen(Coarsen): __slots__ = () _reduce_extra_args_docstring = """""" @classmethod def _reduce_method( cls, func: Callable, include_skipna: bool = False, numeric_only: bool = False ): """ Return a wrapped function for injecting reduction methods. see ops.inject_reduce_methods """ kwargs: Dict[str, Any] = {} if include_skipna: kwargs["skipna"] = None def wrapped_func(self, keep_attrs: bool = None, **kwargs): from .dataarray import DataArray keep_attrs = self._get_keep_attrs(keep_attrs) reduced = self.obj.variable.coarsen( self.windows, func, self.boundary, self.side, keep_attrs, **kwargs ) coords = {} for c, v in self.obj.coords.items(): if c == self.obj.name: coords[c] = reduced else: if any(d in self.windows for d in v.dims): coords[c] = v.variable.coarsen( self.windows, self.coord_func[c], self.boundary, self.side, keep_attrs, **kwargs, ) else: coords[c] = v return DataArray( reduced, dims=self.obj.dims, coords=coords, name=self.obj.name ) return wrapped_func def reduce(self, func: Callable, keep_attrs: bool = None, **kwargs): """Reduce the items in this group by applying `func` along some dimension(s). Parameters ---------- func : callable Function which can be called in the form `func(x, axis, **kwargs)` to return the result of collapsing an np.ndarray over the coarsening dimensions. It must be possible to provide the `axis` argument with a tuple of integers. keep_attrs : bool, default: None If True, the attributes (``attrs``) will be copied from the original object to the new one. If False, the new object will be returned without attributes. If None uses the global default. **kwargs : dict Additional keyword arguments passed on to `func`. Returns ------- reduced : DataArray Array with summarized data. Examples -------- >>> da = xr.DataArray(np.arange(8).reshape(2, 4), dims=("a", "b")) >>> coarsen = da.coarsen(b=2) >>> coarsen.reduce(np.sum) <xarray.DataArray (a: 2, b: 2)> array([[ 1, 5], [ 9, 13]]) Dimensions without coordinates: a, b """ wrapped_func = self._reduce_method(func) return wrapped_func(self, keep_attrs=keep_attrs, **kwargs) class DatasetCoarsen(Coarsen): __slots__ = () _reduce_extra_args_docstring = """""" @classmethod def _reduce_method( cls, func: Callable, include_skipna: bool = False, numeric_only: bool = False ): """ Return a wrapped function for injecting reduction methods. see ops.inject_reduce_methods """ kwargs: Dict[str, Any] = {} if include_skipna: kwargs["skipna"] = None def wrapped_func(self, keep_attrs: bool = None, **kwargs): from .dataset import Dataset keep_attrs = self._get_keep_attrs(keep_attrs) if keep_attrs: attrs = self.obj.attrs else: attrs = {} reduced = {} for key, da in self.obj.data_vars.items(): reduced[key] = da.variable.coarsen( self.windows, func, self.boundary, self.side, keep_attrs=keep_attrs, **kwargs, ) coords = {} for c, v in self.obj.coords.items(): # variable.coarsen returns variables not containing the window dims # unchanged (maybe removes attrs) coords[c] = v.variable.coarsen( self.windows, self.coord_func[c], self.boundary, self.side, keep_attrs=keep_attrs, **kwargs, ) return Dataset(reduced, coords=coords, attrs=attrs) return wrapped_func def reduce(self, func: Callable, keep_attrs=None, **kwargs): """Reduce the items in this group by applying `func` along some dimension(s). Parameters ---------- func : callable Function which can be called in the form `func(x, axis, **kwargs)` to return the result of collapsing an np.ndarray over the coarsening dimensions. It must be possible to provide the `axis` argument with a tuple of integers. keep_attrs : bool, default: None If True, the attributes (``attrs``) will be copied from the original object to the new one. If False, the new object will be returned without attributes. If None uses the global default. **kwargs : dict Additional keyword arguments passed on to `func`. Returns ------- reduced : Dataset Arrays with summarized data. """ wrapped_func = self._reduce_method(func) return wrapped_func(self, keep_attrs=keep_attrs, **kwargs)
34.370953
117
0.559736
a928a1f643a5787c49e6e723051144f7b44e9c15
2,493
py
Python
voting_site/settings.py
lzh9102/ee-voting
f657499d736ff54a81ee2612e855aa9d8dc55382
[ "MIT" ]
null
null
null
voting_site/settings.py
lzh9102/ee-voting
f657499d736ff54a81ee2612e855aa9d8dc55382
[ "MIT" ]
null
null
null
voting_site/settings.py
lzh9102/ee-voting
f657499d736ff54a81ee2612e855aa9d8dc55382
[ "MIT" ]
null
null
null
""" Django settings for voting_site project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$s!h$4hp-f@l64kr2v(x&=&)kwn@5ly%wcry^97&_mge!pt-_5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'voting', ) CRISPY_TEMPLATE_PACK= 'bootstrap3' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.request', ) ROOT_URLCONF = 'voting_site.urls' WSGI_APPLICATION = 'voting_site.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'zh-tw' TIME_ZONE = 'Asia/Taipei' USE_I18N = True USE_L10N = True USE_TZ = False LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'public') # login/logout LOGIN_URL = '/admin/login' LOGOUT_URL = '/admin/logout'
24.441176
71
0.734456
09e392ab39a67567d685800550f09b8652981933
4,236
py
Python
pyabsa/core/tc/classic/__glove__/dataset_utils/data_utils_for_inference.py
yangheng95/LCF-ABSA
0eeb4788269a498d34c2aff942e03af78026617e
[ "MIT" ]
31
2019-10-07T03:05:39.000Z
2020-06-17T01:34:21.000Z
pyabsa/core/tc/classic/__glove__/dataset_utils/data_utils_for_inference.py
yangheng95/LCF-ABSA
0eeb4788269a498d34c2aff942e03af78026617e
[ "MIT" ]
7
2019-10-16T13:37:52.000Z
2020-03-30T03:40:56.000Z
pyabsa/core/tc/classic/__glove__/dataset_utils/data_utils_for_inference.py
yangheng95/LCF-ABSA
0eeb4788269a498d34c2aff942e03af78026617e
[ "MIT" ]
3
2020-01-12T13:03:35.000Z
2020-06-11T08:26:01.000Z
# -*- coding: utf-8 -*- # file: data_utils.py # author: songyouwei <youwei0314@gmail.com> # Copyright (C) 2018. All Rights Reserved. import numpy as np import tqdm from torch.utils.data import Dataset from pyabsa.core.apc.dataset_utils.apc_utils import load_apc_datasets, LABEL_PADDING def pad_and_truncate(sequence, maxlen, dtype='int64', padding='post', truncating='post', value=0): x = (np.ones(maxlen) * value).astype(dtype) if truncating == 'pre': trunc = sequence[-maxlen:] else: trunc = sequence[:maxlen] trunc = np.asarray(trunc, dtype=dtype) if padding == 'post': x[:len(trunc)] = trunc else: x[-len(trunc):] = trunc return x class Tokenizer(object): def __init__(self, max_seq_len, lower=True): self.lower = lower self.max_seq_len = max_seq_len self.word2idx = {} self.idx2word = {} self.idx = 1 def fit_on_text(self, text): if self.lower: text = text.lower() words = text.split() for word in words: if word not in self.word2idx: self.word2idx[word] = self.idx self.idx2word[self.idx] = word self.idx += 1 def text_to_sequence(self, text, reverse=False, padding='post', truncating='post'): if self.lower: text = text.lower() words = text.split() unknownidx = len(self.word2idx) + 1 sequence = [self.word2idx[w] if w in self.word2idx else unknownidx for w in words] if len(sequence) == 0: sequence = [0] if reverse: sequence = sequence[::-1] return pad_and_truncate(sequence, self.max_seq_len, padding=padding, truncating=truncating) class GloVeTCDataset(Dataset): def __init__(self, tokenizer, opt): self.glove_input_colses = { 'lstm': ['text_indices'] } self.tokenizer = tokenizer self.opt = opt self.all_data = [] def parse_sample(self, text): return [text] def prepare_infer_sample(self, text: str, ignore_error): self.process_data(self.parse_sample(text), ignore_error=ignore_error) def prepare_infer_dataset(self, infer_file, ignore_error): lines = load_apc_datasets(infer_file) samples = [] for sample in lines: if sample: samples.extend(self.parse_sample(sample)) self.process_data(samples, ignore_error) def process_data(self, samples, ignore_error=True): all_data = [] if len(samples) > 100: it = tqdm.tqdm(samples, postfix='building word indices...') else: it = samples for text in it: try: # handle for empty lines in inferring_tutorials dataset_utils if text is None or '' == text.strip(): raise RuntimeError('Invalid Input!') if '!ref!' in text: text, label = text.split('!ref!')[0].strip(), text.split('!ref!')[1].strip() label = int(label) if label else LABEL_PADDING text = text.replace('[PADDING]', '') if label < 0: raise RuntimeError( 'Invalid label detected, only please label the sentiment between {0, N-1} ' '(assume there are N types of labels.)') else: label = LABEL_PADDING text_indices = self.tokenizer.text_to_sequence(text) data = { 'text_indices': text_indices if 'text_indices' in self.opt.model.inputs else 0, 'text_raw': text, 'label': label, } all_data.append(data) except Exception as e: if ignore_error: print('Ignore error while processing:', text) else: raise e self.all_data = all_data return self.all_data def __getitem__(self, index): return self.all_data[index] def __len__(self): return len(self.all_data)
30.919708
103
0.555241
a43680b22df767422976af77c8a3d2ca726c1a40
2,217
py
Python
logger/writers/record_screen_writer.py
somasopenrvdas/openrvdas
a415c30447b27ec98600d15a00553c856137c534
[ "BSD-2-Clause" ]
17
2019-10-25T19:54:19.000Z
2022-03-17T19:08:00.000Z
logger/writers/record_screen_writer.py
somasopenrvdas/openrvdas
a415c30447b27ec98600d15a00553c856137c534
[ "BSD-2-Clause" ]
120
2019-10-06T02:57:25.000Z
2022-03-11T13:03:47.000Z
logger/writers/record_screen_writer.py
somasopenrvdas/openrvdas
a415c30447b27ec98600d15a00553c856137c534
[ "BSD-2-Clause" ]
24
2019-10-25T20:01:18.000Z
2021-12-23T15:04:51.000Z
#!/usr/bin/env python3 import logging import shutil import sys from os.path import dirname, realpath sys.path.append(dirname(dirname(dirname(realpath(__file__))))) from logger.utils.formats import Python_Record # noqa: E402 from logger.utils.das_record import DASRecord # noqa: E402 from logger.writers.writer import Writer # noqa: E402 class RecordScreenWriter(Writer): """Write DASRecords to terminal screen in some survivable format. Mostly intended for debugging.""" def __init__(self): super().__init__(input_format=Python_Record) self.values = {} self.timestamps = {} self.latest = 0 ############################ def move_cursor(self, x, y): print('\033[{};{}f'.format(str(x), str(y))) ############################ # receives a DASRecord def write(self, record): if not record: return # If we've got a list, hope it's a list of records. Recurse, # calling write() on each of the list elements in order. if isinstance(record, list): for single_record in record: self.write(single_record) return if not isinstance(record, DASRecord): logging.error('ScreenWriter got non-DASRecord: %s', str(type(record))) return # Incorporate the values from the record self.latest = record.timestamp for field in record.fields: self.values[field] = record.fields[field] self.timestamps[field] = self.latest # Get term size, in case it's been resized (cols, rows) = shutil.get_terminal_size() self.move_cursor(0, 0) # Redraw stuff keys = sorted(self.values.keys()) for i in range(rows): # Go through keys in alpha order if i < len(keys): key = keys[i] line = '{} : {}'.format(key, self.values[key]) # Fill the rest of the screen with blank lines else: line = '' # Pad the lines out to screen width to overwrite old stuff pad_size = cols - len(line) line += ' ' * pad_size print(line)
30.791667
82
0.576906
f0b95e05efe33aad3ac89d03995c5d625c839061
4,836
py
Python
OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/GL/NV/vertex_program2.py
JE-Chen/je_old_repo
a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5
[ "MIT" ]
null
null
null
OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/GL/NV/vertex_program2.py
JE-Chen/je_old_repo
a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5
[ "MIT" ]
null
null
null
OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/GL/NV/vertex_program2.py
JE-Chen/je_old_repo
a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5
[ "MIT" ]
null
null
null
'''OpenGL extension NV.vertex_program2 This module customises the behaviour of the OpenGL.raw.GL.NV.vertex_program2 to provide a more Python-friendly API Overview (from the spec) This extension further enhances the concept of vertex programmability introduced by the NV_vertex_program extension, and extended by NV_vertex_program1_1. These extensions create a separate vertex program mode where the configurable vertex transformation operations in unextended OpenGL are replaced by a user-defined program. This extension introduces the VP2 execution environment, which extends the VP1 execution environment introduced in NV_vertex_program. The VP2 environment provides several language features not present in previous vertex programming execution environments: * Branch instructions allow a program to jump to another instruction specified in the program. * Branching support allows for up to four levels of subroutine calls/returns. * A four-component condition code register allows an application to compute a component-wise write mask at run time and apply that mask to register writes. * Conditional branches are supported, where the condition code register is used to determine if a branch should be taken. * Programmable user clipping is supported support (via the CLP0-CLP5 clip distance registers). Primitives are clipped to the area where the interpolated clip distances are greater than or equal to zero. * Instructions can perform a component-wise absolute value operation on any operand load. The VP2 execution environment provides a number of new instructions, and extends the semantics of several instructions already defined in NV_vertex_program. * ARR: Operates like ARL, except that float-to-int conversion is done by rounding. Equivalent results could be achieved (less efficiently) in NV_vertex program using an ADD/ARL sequence and a program parameter holding the value 0.5. * BRA, CAL, RET: Branch, subroutine call, and subroutine return instructions. * COS, SIN: Adds support for high-precision sine and cosine computations. * FLR, FRC: Adds support for computing the floor and fractional portion of floating-point vector components. Equivalent results could be achieved (less efficiently) in NV_vertex_program using the EXP instruction to compute the fractional portion of one component at a time. * EX2, LG2: Adds support for high-precision exponentiation and logarithm computations. * ARA: Adds pairs of components of an address register; useful for looping and other operations. * SEQ, SFL, SGT, SLE, SNE, STR: Add six new "set on" instructions, similar to the SLT and SGE instructions defined in NV_vertex_program. Equivalent results could be achieved (less efficiently) in NV_vertex_program with multiple SLT, SGE, and arithmetic instructions. * SSG: Adds a new "set sign" operation, which produces a vector holding negative one for negative components, zero for components with a value of zero, and positive one for positive components. Equivalent results could be achieved (less efficiently) in NV_vertex_program with multiple SLT, SGE, and arithmetic instructions. * The ARL instruction is extended to operate on four components instead of a single component. * All instructions that produce integer or floating-point result vectors have variants that update the condition code register based on the result vector. This extension also raises some of the resource limitations in the NV_vertex_program extension. * 256 program parameter registers (versus 96 in NV_vertex_program). * 16 temporary registers (versus 12 in NV_vertex_program). * Two four-component integer address registers (versus one single-component register in NV_vertex_program). * 256 total vertex program instructions (versus 128 in NV_vertex_program). * Including loops, programs can execute up to 64K instructions. The official definition of this extension is available here: http://www.opengl.org/registry/specs/NV/vertex_program2.txt ''' from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GL import _types, _glgets from OpenGL.raw.GL.NV.vertex_program2 import * from OpenGL.raw.GL.NV.vertex_program2 import _EXTENSION_NAME def glInitVertexProgram2NV(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) ### END AUTOGENERATED SECTION
41.333333
76
0.748346
97254693c945c9ec75420e962ab1d5a0617ea3a4
673
py
Python
4-collatz.py
eoinlees/pands-problems-2020
a9a3a5801590e80d023138ad36d928b395a26390
[ "MIT" ]
null
null
null
4-collatz.py
eoinlees/pands-problems-2020
a9a3a5801590e80d023138ad36d928b395a26390
[ "MIT" ]
null
null
null
4-collatz.py
eoinlees/pands-problems-2020
a9a3a5801590e80d023138ad36d928b395a26390
[ "MIT" ]
null
null
null
#Eoin Lees # This program inputs a positive integer and outputs the value of it if # value even divide by two # value odd mulitply it by three and add one # program ends when current value is 1 # Get positive value from input x = int(input("Please enter a positive integer: ")) # Return if x <= 0: print("Please enter a positive number.") # Use while loop to ensure value is positive and greater than 1. Ends once value is 1. while x > 1: if x % 2 == 0: # Divides value by 2 if even x = (x/2) else: # multiplies by 3 and adds 1 if off x = ((x * 3)+1) print(x) # Prints value of input following calculation. restarts loop until x = 1
35.421053
87
0.668648
c57a2eaec67ebc6046e983ecf731eb1871bf8068
15,234
py
Python
Feature Generation/topicModelLDA(dominant_document, dominant_topic, topic_distribution).py
ShahedSabab/tutVis
af2b86b17650c3d92438876d871ee0867deacf2a
[ "MIT" ]
null
null
null
Feature Generation/topicModelLDA(dominant_document, dominant_topic, topic_distribution).py
ShahedSabab/tutVis
af2b86b17650c3d92438876d871ee0867deacf2a
[ "MIT" ]
null
null
null
Feature Generation/topicModelLDA(dominant_document, dominant_topic, topic_distribution).py
ShahedSabab/tutVis
af2b86b17650c3d92438876d871ee0867deacf2a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Wed Dec 12 14:29:52 2018 @author: sabab05 """ import re import numpy as np import pandas as pd import pyLDAvis import pyLDAvis.sklearn import gensim import gensim.corpora as corpora import pyLDAvis.gensim import numpy #from gensim.utils import simple_preproess from gensim.models import CoherenceModel from gensim.utils import simple_preprocess from pprint import pprint import spacy import pyLDAvis import matplotlib.pyplot as plt import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.ERROR) import warnings warnings.filterwarnings("ignore",category=DeprecationWarning) documents = [] stopWords = [] def sent_to_words(sentences): for sentence in sentences: yield(simple_preprocess(str(sentence), deacc=True)) # deacc=True removes punctuations def remove_stopwords(texts): with open(r'''D:\CLoud\Academic\Research\___\Backup\stopwords_en.txt''') as f1: for line in f1: stopWords.append(line.strip()) return [[word for word in simple_preprocess(str(doc)) if word not in stopWords] for doc in texts] def length_check(texts): return [[word for word in simple_preprocess(str(doc)) if len(word)>2] for doc in texts] def make_bigrams(texts): return [bigram_mod[doc] for doc in texts] def make_trigrams(texts): return [trigram_mod[bigram_mod[doc]] for doc in texts] def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']): """https://spacy.io/api/annotation""" texts_out = [] for sent in texts: doc = nlp(" ".join(sent)) texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags]) return texts_out def compute_coherence_value_mallet(dictionary, corpus, texts, limit, start, step): """ Compute c_v coherence for various number of topics Parameters: ---------- dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Returns: ------- model_list : List of LDA topic models coherence_values : Coherence values corresponding to the LDA model with respective number of topics """ coherence_values = [] model_list = [] mallet_path = 'C:/mallet/bin/mallet' for num_topics in range(start, limit, step): model = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics=num_topics, id2word=id2word) model_list.append(model) coherencemodel = CoherenceModel(model=model, corpus=corpus, dictionary=dictionary, coherence='u_mass') coherence_values.append(coherencemodel.get_coherence()) return model_list, coherence_values def compute_coherence_value_gensim(dictionary, corpus, texts, limit, start, step): coherence_values = [] model_list = [] perplexity_values = [] for num_topics in range(start, limit, step): model = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=id2word, num_topics=num_topics, random_state=100, update_every=1, chunksize=100, passes=10, alpha='auto', per_word_topics=True) model_list.append(model) coherencemodel = CoherenceModel(model=model, corpus=corpus, dictionary=dictionary, coherence='u_mass') coherence_values.append(coherencemodel.get_coherence()) perplexity = model.log_perplexity(corpus) perplexity_values.append(perplexity) return model_list, coherence_values, perplexity_values def fileRead(fileNumber): input_file = r'''D:\CLoud\Academic\Research\___\Analysis (Photoshop)\4.2 Analysis Visualization - pyLDAvis (Using 750 symmetrical data)\1. Feature (Words)\Topic Model\Input\S('''+repr(fileNumber)+''').txt''' f = open (input_file, 'r',encoding="utf-8",errors='ignore') lines = ''.join(f.readlines()) lines = lines.lower().strip('\n') lines= re.sub('[^A-Za-z\.\,]+', ' ', lines) return lines def fileWrite(fileNumber,text,length): out_path = r'''D:\CLoud\Academic\Research\___\Photoshop COmmands\4.2 Analyzing with Bigram and trigram (Using 750 symmetrical data)\1. Feature (Words)\Topic Model\Output\A'''+repr(fileNumber)+'''_.txt''' fileOut =open(out_path,"a",encoding="utf-8") fileOut.write("\n"+text) fileOut.write("\n"+str(length)) def plotCoherence(limit, start, step,coherence_values): x = range(start, limit, step) plt.plot(x, coherence_values) plt.xlabel("Num Topics") plt.ylabel("Coherence score") plt.legend(("coherence_values"), loc='best') plt.show() return x def plotPerplexity(limit, start, step,perplexity_values): y = range(start, limit, step) plt.plot(x, perplexity_values) plt.xlabel("Num Topics") plt.ylabel("Perplexity") plt.legend(("perplexity_values"), loc='best') plt.show() return y def malletmodel2ldamodel(mallet_model, gamma_threshold=0.001, iterations=50): """ Function to convert mallet model to gensim LdaModel. This works by copying the training model weights (alpha, beta...) from a trained mallet model into the gensim model. Args: mallet_model : Trained mallet model gamma_threshold : To be used for inference in the new LdaModel. iterations : number of iterations to be used for inference in the new LdaModel. Returns: model_gensim : LdaModel instance; copied gensim LdaModel """ model_gensim = gensim.models.ldamodel.LdaModel( id2word=mallet_model.id2word, num_topics=mallet_model.num_topics, alpha=mallet_model.alpha, iterations=iterations, eta=mallet_model.word_topics, gamma_threshold=gamma_threshold, dtype=numpy.float64 # don't loose precision when converting from MALLET ) model_gensim.expElogbeta[:] = mallet_model.wordtopics return model_gensim def format_dominant_topics(ldamodel, corpus, texts): global start_doc global end_doc # Init output sent_topics_df = pd.DataFrame() # Get main topic in each document for i, row in enumerate(ldamodel[corpus]): row = sorted(row, key=lambda x: (x[1]), reverse=True) # Get the Dominant topic, Perc Contribution and Keywords for each document for j, (topic_num, prop_topic) in enumerate(row): if j == 0: # => dominant topic wp = ldamodel.show_topic(topic_num) topic_keywords = ", ".join([word for word, prop in wp]) sent_topics_df = sent_topics_df.append(pd.Series([int(topic_num)+1, round(prop_topic,4), topic_keywords]), ignore_index=True) else: break sent_topics_df.columns = ['Dominant_Topic', 'Perc_Contribution', 'Topic_Keywords'] file_name = [] for x in range(start_doc,end_doc): file_name.append(x) file = pd.Series(file_name) sent_topics_df = pd.concat([file, sent_topics_df], axis=1) # Add original text to the end of the output #contents = pd.Series(texts) #sent_topics_df = pd.concat([sent_topics_df, contents], axis=1) return(sent_topics_df) def format_document_topic_distribution(ldamodel, corpus, num_topic): global start_doc global end_doc # Init output topics = [] doc_topics = [] for i, row in enumerate(ldamodel[corpus]): topics = [prop_topic for j, (topic_num, prop_topic) in enumerate(row)] doc_topics.append(topics) sent_topics_df = pd.DataFrame.from_records(doc_topics) column_name = [] file_name = [] for x in range(1,num_topic+1): column_name.append("Topic "+str(x)) for x in range(start_doc,end_doc): file_name.append(x) sent_topics_df.columns = column_name file = pd.Series(file_name) sent_topics_df = pd.concat([file, sent_topics_df], axis=1) return(sent_topics_df) # Get the Dominant topic, Perc Contribution and Keywords for each document start_doc=1 end_doc=751 for x in range(start_doc,end_doc): print(x) corpus=fileRead(x) documents.append(corpus) data_words = list(sent_to_words(documents)) # See trigram example #print(trigram_mod[bigram_mod[data_words[0]]]) # Remove Stop Words data_words_nostops = remove_stopwords(data_words) # length greater than 2 data_words_nostops = length_check(data_words_nostops) nlp = spacy.load('en', disable=['parser', 'ner']) # Do lemmatization keeping only noun, adj, vb, adv data_lemmatized = lemmatization(data_words_nostops, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']) # Build the bigram and trigram models bigram = gensim.models.Phrases(data_lemmatized, min_count=5) # higher threshold fewer phrases. trigram = gensim.models.Phrases(bigram[data_lemmatized], threshold=100) # Faster way to get a sentence clubbed as a trigram/bigram bigram_mod = gensim.models.phrases.Phraser(bigram) trigram_mod = gensim.models.phrases.Phraser(trigram) # Form Bigrams data_words_bigrams = make_bigrams(data_lemmatized) # Form trigrams #data_words_trigrams = make_trigrams(data_words_nostops) data_final = data_words_bigrams # Create Dictionary id2word = corpora.Dictionary(data_final) # Create Corpus texts = data_final # Term Document Frequency corpus = [id2word.doc2bow(text) for text in texts] # ============================================================================= """ # ## Build LDA model using gensim #lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus, # id2word=id2word, # num_topics=10, # random_state=100, # update_every=1, # chunksize=100, # passes=10, # alpha='auto', # per_word_topics=True) # #Print the Keyword in the 10 topics #pprint(lda_model.print_topics()) #doc_lda = lda_model[corpus] """ #============================================================================= #============================================================================= # Build LDA model using mallet _numberOftopics = 30 _iterations = 10000 mallet_path = 'C:/mallet/bin/mallet' ldamallet = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics=_numberOftopics, id2word=id2word, workers = 4) optimal_model = ldamallet model_topics = optimal_model.show_topics(formatted=False) pprint(optimal_model.print_topics(num_words=10)) # dominant topic calculation df_topic_sents_keywords = format_dominant_topics(optimal_model, corpus, data_words) pprint(df_topic_sents_keywords.head(10)) out_path = r'''D:\CLoud\Academic\Research\___\Analysis (Photoshop)\4.2 Analysis Visualization - pyLDAvis (Using 750 symmetrical data)\1. Feature (Words)\Topic Model\Trial COdes\Model\dominant_topic_mallet_30_V1.csv''' df_topic_sents_keywords.to_csv(out_path, index=False) #dominant document calculation sent_topics_sorted_df_mallet = pd.DataFrame() sent_topics_outdf_grpd = df_topic_sents_keywords.groupby('Dominant_Topic') for i, grp in sent_topics_outdf_grpd: sent_topics_sorted_df_mallet = pd.concat([sent_topics_sorted_df_mallet, grp.sort_values(['Perc_Contribution'], ascending=[0]).head(5)], axis=0) out_path = r'''D:\CLoud\Academic\Research\___\Analysis (Photoshop)\4.2 Analysis Visualization - pyLDAvis (Using 750 symmetrical data)\1. Feature (Words)\Topic Model\Trial COdes\Model\dominant_document_mallet_30_V1.csv''' sent_topics_sorted_df_mallet.to_csv(out_path, index=False) #topic distribution calculation out_path = r'''D:\CLoud\Academic\Research\___\Analysis (Photoshop)\4.2 Analysis Visualization - pyLDAvis (Using 750 symmetrical data)\1. Feature (Words)\Topic Model\Trial COdes\Model\topic_distribution_mallet_30_V1.csv''' df_topic_distribution=format_document_topic_distribution(optimal_model, corpus,_numberOftopics) df_topic_distribution.to_csv(out_path, index=False) print(df_topic_distribution) #============================================================================= #============================================================================= #convert ldamallet to gensim so that pyLDAvis can work ldamallet = malletmodel2ldamodel(ldamallet) #pyLDAvis result generation print('prepare') pyLDAvis.enable_notebook() vis=pyLDAvis.gensim.prepare(ldamallet, corpus, id2word, mds='pcoa',sort_topics=False) pprint(ldamallet.show_topics(formatted=True)) #pyLDAvis.show(vis) pyLDAvis.save_html(vis, r'''D:\CLoud\Academic\Research\___\Analysis (Photoshop)\4.2 Analysis Visualization - pyLDAvis (Using 750 symmetrical data)\1. Feature (Words)\Topic Model\Trial COdes\pyLdavis\malletLDA_30topics_V1.html''') #============================================================================= # ============================================================================= """ #Compute Perplexity #print('\nPerplexity: ', lda_model.log_perplexity(corpus)) # a measure of how good the model is. lower the better """ # ============================================================================= # ============================================================================= # coherence c_v does not work """ # #coherence_model_lda = CoherenceModel(model=ldamallet, texts=texts_2, dictionary=id2word, coherence='c_v') # #coherence_lda = coherence_model_lda.get_coherence() # #print('\nCoherence Score: ', coherence_lda) """ # ============================================================================= # ============================================================================= # initialization of the values for plotting """ #_start=20 #_limit=100 #_step=5 # ============================================================================= # # Coherence value for gensim # #model_list, coherence_values, perplexity_values = compute_coherence_value_gensim(dictionary=id2word, corpus=corpus, texts=data_final, limit=_limit, start=_start, step=_step) # # # # comment out if using gensim LDA model # # # y = plotPerplexity(_limit,_start, _step,perplexity_values) # ============================================================================= # ============================================================================= # # Coherence value for mallet # # model_list, coherence_values = compute_coherence_value_mallet(dictionary=id2word, corpus=corpus, texts=data_final, limit=_limit, start=_start, step=_step) # ============================================================================= # # # Show graph limit, start, step # x = plotCoherence(_limit,_start, _step,coherence_values) ## Print the coherence scores #for m, cv in zip(x, coherence_values): # print("Num Topics =", m, " has Coherence Value of", round(cv, 4)) """ # =============================================================================
36.797101
229
0.634436
f66e98e8de267d67fa118dc57df71f4efafb172e
2,743
py
Python
HLTrigger/Configuration/python/HLT_75e33/tasks/l1tReconstructionTask_cfi.py
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
1
2021-11-30T16:24:46.000Z
2021-11-30T16:24:46.000Z
HLTrigger/Configuration/python/HLT_75e33/tasks/l1tReconstructionTask_cfi.py
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
4
2021-11-29T13:57:56.000Z
2022-03-29T06:28:36.000Z
HLTrigger/Configuration/python/HLT_75e33/tasks/l1tReconstructionTask_cfi.py
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
1
2021-11-30T16:16:05.000Z
2021-11-30T16:16:05.000Z
import FWCore.ParameterSet.Config as cms from ..modules.L1EGammaClusterEmuProducer_cfi import * from ..modules.l1EGammaEEProducer_cfi import * from ..modules.l1NNTauProducerPuppi_cfi import * from ..modules.l1pfCandidates_cfi import * from ..modules.l1PFMetPuppi_cfi import * from ..modules.l1pfProducerBarrel_cfi import * from ..modules.l1pfProducerHF_cfi import * from ..modules.l1pfProducerHGCal_cfi import * from ..modules.l1pfProducerHGCalNoTK_cfi import * from ..modules.hltL1TkElectronsEllipticMatchCrystal_cfi import * from ..modules.hltL1TkElectronsEllipticMatchHGC_cfi import * from ..modules.hltL1TkMuons_cfi import * from ..modules.hltL1TkPhotonsCrystal_cfi import * from ..modules.hltL1TkPhotonsHGC_cfi import * from ..modules.L1TkPrimaryVertex_cfi import * from ..modules.l1tSlwPFPuppiJets_cfi import * from ..modules.l1tSlwPFPuppiJetsCorrected_cfi import * from ..modules.pfClustersFromCombinedCaloHCal_cfi import * from ..modules.pfClustersFromCombinedCaloHF_cfi import * from ..modules.pfClustersFromHGC3DClusters_cfi import * from ..modules.pfClustersFromL1EGClusters_cfi import * from ..modules.pfTracksFromL1TracksBarrel_cfi import * from ..modules.pfTracksFromL1TracksHGCal_cfi import * from ..modules.simCaloStage2Layer1Digis_cfi import * from ..modules.simCscTriggerPrimitiveDigis_cfi import * from ..modules.simDtTriggerPrimitiveDigis_cfi import * from ..modules.simEmtfDigis_cfi import * from ..modules.simGmtCaloSumDigis_cfi import * from ..modules.simGmtStage2Digis_cfi import * from ..modules.simKBmtfDigis_cfi import * from ..modules.simKBmtfStubs_cfi import * from ..modules.simMuonGEMPadDigiClusters_cfi import * from ..modules.simMuonGEMPadDigis_cfi import * from ..modules.simOmtfDigis_cfi import * from ..modules.simTwinMuxDigis_cfi import * l1tReconstructionTask = cms.Task( L1EGammaClusterEmuProducer, hltL1TkElectronsEllipticMatchCrystal, hltL1TkElectronsEllipticMatchHGC, hltL1TkMuons, hltL1TkPhotonsCrystal, hltL1TkPhotonsHGC, L1TkPrimaryVertex, l1EGammaEEProducer, l1NNTauProducerPuppi, l1PFMetPuppi, l1pfCandidates, l1pfProducerBarrel, l1pfProducerHF, l1pfProducerHGCal, l1pfProducerHGCalNoTK, l1tSlwPFPuppiJets, l1tSlwPFPuppiJetsCorrected, pfClustersFromCombinedCaloHCal, pfClustersFromCombinedCaloHF, pfClustersFromHGC3DClusters, pfClustersFromL1EGClusters, pfTracksFromL1TracksBarrel, pfTracksFromL1TracksHGCal, simCaloStage2Layer1Digis, simCscTriggerPrimitiveDigis, simDtTriggerPrimitiveDigis, simEmtfDigis, simGmtCaloSumDigis, simGmtStage2Digis, simKBmtfDigis, simKBmtfStubs, simMuonGEMPadDigiClusters, simMuonGEMPadDigis, simOmtfDigis, simTwinMuxDigis )
36.092105
64
0.815895
7730d8a39c05186831225a682801e9c45696f28a
476
py
Python
src/wsgi.py
chunky2808/SPOJ-history-Django-App-
490c58b1593cd3626f0ddc27fdd09c6e8d1c56e1
[ "MIT" ]
1
2019-04-11T18:28:38.000Z
2019-04-11T18:28:38.000Z
src/wsgi.py
chunky2808/SPOJ-history-Django-App-
490c58b1593cd3626f0ddc27fdd09c6e8d1c56e1
[ "MIT" ]
2
2020-02-12T00:41:47.000Z
2020-06-05T18:17:31.000Z
src/wsgi.py
chunky2808/SPOJ-history-Django-App
490c58b1593cd3626f0ddc27fdd09c6e8d1c56e1
[ "MIT" ]
null
null
null
""" WSGI config for src 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.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "src.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application)
23.8
78
0.798319
8239ae8cbc2db25fc42b515347d530e534338097
572
py
Python
dashboard/modules/job/tests/subprocess_driver_scripts/override_env_var.py
dsctt/ray
29d94a22114b02adfd3745c4991a3ce70592dd16
[ "Apache-2.0" ]
1
2021-09-20T15:45:59.000Z
2021-09-20T15:45:59.000Z
dashboard/modules/job/tests/subprocess_driver_scripts/override_env_var.py
dsctt/ray
29d94a22114b02adfd3745c4991a3ce70592dd16
[ "Apache-2.0" ]
53
2021-10-06T20:08:04.000Z
2022-03-21T20:17:25.000Z
dashboard/modules/job/tests/subprocess_driver_scripts/override_env_var.py
dsctt/ray
29d94a22114b02adfd3745c4991a3ce70592dd16
[ "Apache-2.0" ]
null
null
null
""" Test script that attempts to set its own runtime_env, but we should ensure we ended up using job submission API call's runtime_env instead of scripts """ def run(): import ray import os ray.init( address=os.environ["RAY_ADDRESS"], runtime_env={ "env_vars": {"TEST_SUBPROCESS_JOB_CONFIG_ENV_VAR": "SHOULD_BE_OVERRIDEN"} }, ) @ray.remote def foo(): return "bar" ray.get(foo.remote()) print(os.environ.get("TEST_SUBPROCESS_JOB_CONFIG_ENV_VAR", None)) if __name__ == "__main__": run()
20.428571
85
0.641608
78baf4a183a494cd314f2b78c437d9ed7faca157
2,190
py
Python
tests/python/unittest/test_profiler.py
hanzz2007/mxnet
cc0b2d67c40170aced702c9f80b4b7acbb1f2b79
[ "Apache-2.0" ]
116
2018-01-01T03:53:49.000Z
2021-09-06T07:09:09.000Z
tests/python/unittest/test_profiler.py
wkcn/incubator-mxnet
2586c6691ca74d2df455a49cad964bcac8e34f25
[ "Apache-2.0" ]
4
2019-04-01T07:36:04.000Z
2022-03-24T03:11:26.000Z
tests/python/unittest/test_profiler.py
wkcn/incubator-mxnet
2586c6691ca74d2df455a49cad964bcac8e34f25
[ "Apache-2.0" ]
40
2018-01-16T04:12:39.000Z
2022-02-25T11:53:17.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import print_function import mxnet as mx from mxnet import profiler import time def test_profiler(): profile_filename = "test_profile.json" iter_num = 5 begin_profiling_iter = 2 end_profiling_iter = 4 profiler.profiler_set_config(mode='symbolic', filename=profile_filename) print('profile file save to {0}'.format(profile_filename)) A = mx.sym.Variable('A') B = mx.sym.Variable('B') C = mx.symbol.dot(A, B) executor = C.simple_bind(mx.cpu(1), 'write', A=(4096, 4096), B=(4096, 4096)) a = mx.random.uniform(-1.0, 1.0, shape=(4096, 4096)) b = mx.random.uniform(-1.0, 1.0, shape=(4096, 4096)) a.copyto(executor.arg_dict['A']) b.copyto(executor.arg_dict['B']) print("execution begin") for i in range(iter_num): print("Iteration {}/{}".format(i + 1, iter_num)) if i == begin_profiling_iter: t0 = time.clock() profiler.profiler_set_state('run') if i == end_profiling_iter: t1 = time.clock() profiler.profiler_set_state('stop') executor.forward() c = executor.outputs[0] c.wait_to_read() print("execution end") duration = t1 - t0 print('duration: {0}s'.format(duration)) print(' {0}ms/operator'.format(duration*1000/iter_num)) profiler.dump_profile() if __name__ == '__main__': test_profiler()
34.21875
80
0.680365
3095fc8d14b2623cd3deb14bf905a1bf27af8bc3
1,670
py
Python
adversarial_defense/jpeg_compression/jpeg.py
machanic/TangentAttack
17c1a8e93f9bbd03e209e8650631af744a0ff6b8
[ "Apache-2.0" ]
4
2021-11-12T04:06:32.000Z
2022-01-27T09:01:41.000Z
adversarial_defense/jpeg_compression/jpeg.py
machanic/TangentAttack
17c1a8e93f9bbd03e209e8650631af744a0ff6b8
[ "Apache-2.0" ]
1
2022-02-22T14:00:59.000Z
2022-02-25T08:57:29.000Z
adversarial_defense/jpeg_compression/jpeg.py
machanic/TangentAttack
17c1a8e93f9bbd03e209e8650631af744a0ff6b8
[ "Apache-2.0" ]
null
null
null
try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO import torch from torchvision import transforms from PIL import Image _to_pil_image = transforms.ToPILImage() _to_tensor = transforms.ToTensor() class FloatToIntSqueezing(torch.autograd.Function): @staticmethod def forward(ctx, x, max_int, vmin, vmax): # here assuming 0 =< x =< 1 x = (x - vmin) / (vmax - vmin) x = torch.round(x * max_int) / max_int return x * (vmax - vmin) + vmin @staticmethod def backward(ctx, grad_output): raise NotImplementedError( "backward not implemented", FloatToIntSqueezing) class JPEGEncodingDecoding(torch.autograd.Function): @staticmethod def forward(ctx, x, quality): lst_img = [] for img in x: img = _to_pil_image(img.detach().clone().cpu()) virtualpath = BytesIO() img.save(virtualpath, 'JPEG', quality=quality) lst_img.append(_to_tensor(Image.open(virtualpath))) return torch.stack(lst_img).clone().detach().cuda() @staticmethod def backward(ctx, grad_output): raise NotImplementedError( "backward not implemented", JPEGEncodingDecoding) class JPEGFilter(object): """ JPEG Filter. :param quality: quality of the output. """ def __init__(self, quality=75): super(JPEGFilter, self).__init__() self.quality = quality def forward(self, x): if x.dim() == 3: x = x.unsqueeze(0) return JPEGEncodingDecoding.apply(x, self.quality) def __call__(self, x): return self.forward(x)
28.305085
63
0.637725
145f7e448869161761feaa02555fd8b8677180cc
3,691
py
Python
utils.py
snigdhagit/compare-selection
26f41d06405e9a9be9894878bf604c38049a4729
[ "BSD-3-Clause" ]
1
2020-02-14T00:47:35.000Z
2020-02-14T00:47:35.000Z
utils.py
snigdhagit/compare-selection
26f41d06405e9a9be9894878bf604c38049a4729
[ "BSD-3-Clause" ]
null
null
null
utils.py
snigdhagit/compare-selection
26f41d06405e9a9be9894878bf604c38049a4729
[ "BSD-3-Clause" ]
2
2019-09-23T15:36:45.000Z
2020-02-14T03:55:29.000Z
import numpy as np import pandas as pd # Rpy import rpy2.robjects as rpy from rpy2.robjects import numpy2ri rpy.r('suppressMessages(library(selectiveInference)); suppressMessages(library(knockoff))') # R libraries we will use rpy.r(""" estimate_sigma_data_splitting = function(X,y, verbose=FALSE){ nrep = 10 sigma_est = 0 nest = 0 for (i in 1:nrep){ n=nrow(X) m=floor(n/2) subsample = sample(1:n, m, replace=FALSE) leftover = setdiff(1:n, subsample) CV = cv.glmnet(X[subsample,], y[subsample], standardize=FALSE, intercept=FALSE, family="gaussian") beta_hat = coef(CV, s="lambda.min")[-1] selected = which(beta_hat!=0) if (verbose){ print(c("nselected", length(selected))) } if (length(selected)>0){ LM = lm(y[leftover]~X[leftover,][,selected]) sigma_est = sigma_est+sigma(LM) nest = nest+1 } } return(sigma_est/nest) } """) def gaussian_setup(X, Y, run_CV=True): """ Some calculations that can be reused by methods: lambda.min, lambda.1se, lambda.theory and Reid et al. estimate of noise """ n, p = X.shape Xn = X / np.sqrt((X**2).sum(0))[None, :] numpy2ri.activate() rpy.r.assign('X', X) rpy.r.assign('Y', Y) numpy2ri.deactivate() rpy.r('X=as.matrix(X)') rpy.r('Y=as.numeric(Y)') l_theory = np.fabs(Xn.T.dot(np.random.standard_normal((n, 500)))).max(1).mean() * np.ones(p) if run_CV: numpy2ri.activate() rpy.r.assign('X', X) rpy.r.assign('Y', Y) rpy.r('X=as.matrix(X)') rpy.r('Y=as.numeric(Y)') rpy.r('G = cv.glmnet(X, Y, intercept=FALSE, standardize=FALSE)') rpy.r('sigma_reid = selectiveInference:::estimate_sigma(X, Y, coef(G, s="lambda.min")[-1]) # sigma via Reid et al.') rpy.r("L = G[['lambda.min']]") rpy.r("L1 = G[['lambda.1se']]") L = rpy.r('L') L1 = rpy.r('L1') sigma_reid = rpy.r('sigma_reid')[0] numpy2ri.deactivate() return L * np.sqrt(X.shape[0]) * 1.0001, L1 * np.sqrt(X.shape[0]) * 1.0001, l_theory, sigma_reid else: return None, None, l_theory, None def BHfilter(pval, q=0.2): numpy2ri.activate() rpy.r.assign('pval', np.asarray(pval)) rpy.r.assign('q', q) rpy.r('Pval = p.adjust(pval, method="BH")') rpy.r('S = which((Pval < q)) - 1') S = rpy.r('S') numpy2ri.deactivate() return np.asarray(S, np.int) def summarize(groupings, results_df, summary): grouped = results_df.groupby(groupings, as_index=False) summaries = [] summaries = [(n, summary(g)) for n, g in grouped] summary_df = pd.concat([s for _, s in summaries]) summary_df.index = [n for n, _ in summaries] return summary_df def get_method_params(methods): # find all columns needed for output colnames = [] for method in methods: M = method(np.random.standard_normal((10,5)), np.random.standard_normal(10), 1., 1., 1., 1.) colnames += M.trait_names() colnames = sorted(np.unique(colnames)) def get_col(method, colname): if colname in method.trait_names(): return getattr(method, colname) def get_params(method): return [get_col(method, colname) for colname in colnames] method_names = [] method_params = [] for method in methods: M = method(np.random.standard_normal((10,5)), np.random.standard_normal(10), 1., 1., 1., 1.) method_params.append(get_params(M)) method_names.append(M.method_name) method_params = pd.DataFrame(method_params, columns=colnames) return method_params, [m.__name__ for m in methods], method_names
28.175573
124
0.611487
d818b16b9c7dc5463ca85bdd62d8414153b7b5d1
409
py
Python
examples/rabbitmq/dispatch_commands.py
alice-biometrics/petisco
b96e697cc875f67a28e60b4fc0d9ed9fc646cd86
[ "MIT" ]
19
2019-11-01T09:27:17.000Z
2021-12-15T10:52:31.000Z
examples/rabbitmq/dispatch_commands.py
alice-biometrics/petisco
b96e697cc875f67a28e60b4fc0d9ed9fc646cd86
[ "MIT" ]
68
2020-01-15T06:55:00.000Z
2022-02-22T15:57:24.000Z
examples/rabbitmq/dispatch_commands.py
alice-biometrics/petisco
b96e697cc875f67a28e60b4fc0d9ed9fc646cd86
[ "MIT" ]
2
2019-11-19T10:40:25.000Z
2019-11-28T07:12:07.000Z
from examples.rabbitmq.common import ORGANIZATION, SERVICE, PersistUser from petisco import Uuid from petisco.extra.rabbitmq import RabbitMqConnector, RabbitMqCommandBus connector = RabbitMqConnector() command_bus = RabbitMqCommandBus(connector, ORGANIZATION, SERVICE) user_id = Uuid.v4() command = PersistUser(user_id=user_id) print("Commands") print(f"Dispatch {command}") command_bus.dispatch(command)
27.266667
72
0.821516
d16e491808c2d4eaee98d5b5baa661570e1043c5
2,074
py
Python
helper.py
newzzack/ZhiShiWenDa-Helper
51390a7d2efbb5ce39400d7fec69aa80c69fc3a7
[ "MIT" ]
1
2019-09-30T05:52:38.000Z
2019-09-30T05:52:38.000Z
helper.py
newzzack/ZhiShiWenDa-Helper
51390a7d2efbb5ce39400d7fec69aa80c69fc3a7
[ "MIT" ]
null
null
null
helper.py
newzzack/ZhiShiWenDa-Helper
51390a7d2efbb5ce39400d7fec69aa80c69fc3a7
[ "MIT" ]
null
null
null
import requests, base64, json, os, time,config from PIL import Image from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome(config.driver_location) # 访问百度 driver.get('http://www.baidu.com') count = 0 screenpath = config.image_directory while True: text = input('按下回车发起搜索') start = time.time() count = count+1 imagepath = config.image_directory+"screen" + str(count) +".png" region_path = config.image_directory+"region" + str(count) +".png" if not os.path.exists(config.image_directory): os.mkdir(config.image_directory) os.system("adb shell /system/bin/screencap -p /sdcard/screenshot.png") os.system("adb pull /sdcard/screenshot.png " + imagepath) im = Image.open(imagepath) img_size = im.size w = im.size[0] h = im.size[1] region = im.crop((config.left, config.top, w - config.right, config.bottom)) # 裁剪的区域 region.save(region_path) f = open(region_path, 'rb') ls_f = base64.b64encode(f.read()) f.close() image_byte = bytes.decode(ls_f) url = 'http://text.aliapi.hanvon.com/rt/ws/v1/ocr/text/recg?code=74e51a88-41ec-413e-b162-bd031fe0407e' data = {"uid": "118.12.0.12", "lang": "chns", "color": "color", 'image': image_byte} headers = {"Content-Type": "application/json; charset=UTF-8", "Accept-Content-Type": "application/octet-stream", "Authorization": "APPCODE " + config.appcode } res = requests.post(url, data=json.dumps(data), headers=headers) content = res.text if res.status_code != 200: print("orc识别错误") break json_data = json.loads(content)['textResult'] keyword = str(json_data).strip().rstrip().lstrip().replace("\r", "").replace("\n","").replace(" ","") print("OCR识别内容: " + keyword) driver.find_element_by_id('kw').send_keys(Keys.CONTROL, 'a') driver.find_element_by_id('kw').send_keys(Keys.BACK_SPACE) driver.find_element_by_id('kw').send_keys(keyword) driver.find_element_by_id('su').send_keys(Keys.ENTER) end = time.time() print('程序用时:' + str(end - start) + '秒')
31.907692
104
0.680328
716c473a4f4f4ac135a0f9a543d3090f82841276
412
py
Python
api/migrations/0006_alter_todo_create_date.py
jadsonlucio/TodoApp
0aaa0f0aa6753516b7fe4957ef5b64a13627fb46
[ "MIT" ]
1
2021-06-08T00:57:53.000Z
2021-06-08T00:57:53.000Z
api/migrations/0006_alter_todo_create_date.py
jadsonlucio/TodoApp
0aaa0f0aa6753516b7fe4957ef5b64a13627fb46
[ "MIT" ]
1
2021-04-10T05:51:51.000Z
2021-04-10T05:51:51.000Z
api/migrations/0006_alter_todo_create_date.py
jadsonlucio/TodoApp
0aaa0f0aa6753516b7fe4957ef5b64a13627fb46
[ "MIT" ]
null
null
null
# Generated by Django 3.2 on 2021-04-09 02:42 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0005_alter_todo_user'), ] operations = [ migrations.AlterField( model_name='todo', name='create_date', field=models.DateField(default=datetime.datetime.now), ), ]
20.6
66
0.616505
a006af275ff33d2c08818000a063961f8013d7c5
5,652
py
Python
datasets/wikiasp/wikiasp.py
ExpressAI/DataLab
c3eddd4068f131d031c2486c60b650092bb0ae84
[ "Apache-2.0" ]
54
2022-01-26T06:58:58.000Z
2022-03-31T05:11:35.000Z
datasets/wikiasp/wikiasp.py
ExpressAI/DataLab
c3eddd4068f131d031c2486c60b650092bb0ae84
[ "Apache-2.0" ]
81
2022-01-26T06:46:41.000Z
2022-03-24T05:05:31.000Z
datasets/wikiasp/wikiasp.py
ExpressAI/DataLab
c3eddd4068f131d031c2486c60b650092bb0ae84
[ "Apache-2.0" ]
7
2022-02-06T09:28:31.000Z
2022-03-16T01:06:37.000Z
"""WikiAsp: A Dataset for Multi-domain Aspect-based Summarization""" import os import datalabs from datalabs import get_task, TaskType import json _CITATION = """\ @article{10.1162/tacl_a_00362, author = {Hayashi, Hiroaki and Budania, Prashant and Wang, Peng and Ackerson, Chris and Neervannan, Raj and Neubig, Graham}, title = "{WikiAsp: A Dataset for Multi-domain Aspect-based Summarization}", journal = {Transactions of the Association for Computational Linguistics}, volume = {9}, pages = {211-225}, year = {2021}, month = {03}, abstract = "{Aspect-based summarization is the task of generating focused summaries based on specific points of interest. Such summaries aid efficient analysis of text, such as quickly understanding reviews or opinions from different angles. However, due to large differences in the type of aspects for different domains (e.g., sentiment, product features), the development of previous models has tended to be domain-specific. In this paper, we propose WikiAsp,1 a large-scale dataset for multi-domain aspect- based summarization that attempts to spur research in the direction of open-domain aspect-based summarization. Specifically, we build the dataset using Wikipedia articles from 20 different domains, using the section titles and boundaries of each article as a proxy for aspect annotation. We propose several straightforward baseline models for this task and conduct experiments on the dataset. Results highlight key challenges that existing summarization models face in this setting, such as proper pronoun handling of quoted sources and consistent explanation of time-sensitive events.}", issn = {2307-387X}, doi = {10.1162/tacl_a_00362}, url = {https://doi.org/10.1162/tacl\_a\_00362}, eprint = {https://direct.mit.edu/tacl/article-pdf/doi/10.1162/tacl\_a\_00362/1924027/tacl\_a\_00362.pdf}, } """ _DESCRIPTION = """\ WikiAsp is a multi-domain, aspect-based summarization dataset in the encyclopedic domain. In this task, models are asked to summarize cited reference documents of a Wikipedia article into aspect-based summaries. Each of the 20 domains include 10 domain-specific pre-defined aspects. see: https://direct.mit.edu/tacl/article/doi/10.1162/tacl_a_00362/98088/WikiAsp-A-Dataset-for-Multi-domain-Aspect-based """ _HOMEPAGE = "https://github.com/neulab/wikiasp" _ABSTRACT = "summary" _ARTICLE = "text" _KEY = "query" class WikiAspConfig(datalabs.BuilderConfig): """BuilderConfig for WikiAsp.""" def __init__(self, task_templates, **kwargs): """BuilderConfig for WikiAsp. Args: **kwargs: keyword arguments forwarded to super. """ super(WikiAspConfig, self).__init__(**kwargs) self.task_templates = task_templates class WikiAspDataset(datalabs.GeneratorBasedBuilder): """WikiAsp Dataset.""" _DOMAINS = [ "Album", "Animal", "Artist", "Building", "Company", "EducationalInstitution", "Event", "Film", "Group", "HistoricPlace", "Infrastructure", "MeanOfTransportation", "OfficeHolder", "Plant", "Single", "SoccerPlayer", "Software", "TelevisionShow", "Town", "WrittenWork" ] BUILDER_CONFIGS = list([WikiAspConfig( name=x, version=datalabs.Version("1.0.0"), description=f"WikiAsp Dataset for aspect-based summarization, {x} split", task_templates=[get_task(TaskType.query_summarization)( source_column=_ARTICLE, reference_column=_ABSTRACT, guidance_column=_KEY)] ) for x in _DOMAINS]) DEFAULT_CONFIG_NAME = "Album" def _info(self): return datalabs.DatasetInfo( description=_DESCRIPTION, features=datalabs.Features( { _ARTICLE: datalabs.Value("string"), _ABSTRACT: datalabs.Value("string"), _KEY: datalabs.Value("string"), } ), supervised_keys=None, homepage=_HOMEPAGE, citation=_CITATION, version=self.VERSION, languages=[self.config.name], task_templates=[get_task(TaskType.query_summarization)( source_column=_ARTICLE, reference_column=_ABSTRACT, guidance_column=_KEY), ], ) def _split_generators(self, dl_manager): name = self.config.name url = f"http://phontron.com/download/wikiasp/{name}.tar.bz2" path = dl_manager.download_and_extract(url) return [ datalabs.SplitGenerator( name=datalabs.Split.TRAIN, gen_kwargs={"f_path": os.path.join(path, f"{name}/train.jsonl")}, ), datalabs.SplitGenerator( name=datalabs.Split.VALIDATION, gen_kwargs={"f_path": os.path.join(path, f"{name}/valid.jsonl")}, ), datalabs.SplitGenerator( name=datalabs.Split.TEST, gen_kwargs={"f_path": os.path.join(path, f"{name}/test.jsonl")}, ), ] def _generate_examples(self, f_path): """Generate WikiAsp examples.""" cnt = 0 with open(f_path, encoding="utf-8") as f: for line in f: data = json.loads(line) text = " ".join(data["inputs"]) for t in data["targets"]: yield cnt, {_ARTICLE: text, _ABSTRACT: t[1], _KEY: t[0]} cnt += 1
43.476923
1,102
0.63712
5552c943fe4707bf1aaeea7d8a63762c470b319f
8,973
py
Python
backend/server/profiles/forms.py
Wisani90/care-curls
248d58679024b7b0d0212a9f659d472873696977
[ "MIT" ]
null
null
null
backend/server/profiles/forms.py
Wisani90/care-curls
248d58679024b7b0d0212a9f659d472873696977
[ "MIT" ]
null
null
null
backend/server/profiles/forms.py
Wisani90/care-curls
248d58679024b7b0d0212a9f659d472873696977
[ "MIT" ]
null
null
null
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from datetime import timedelta # from django import forms from django.forms import ValidationError from django.conf import settings from django.contrib.auth.models import User # from django.contrib.auth.forms import UserCreationForm from django.utils import timezone from django.db.models import Q from django.utils.translation import gettext_lazy as _ class SignUpForm(UserCreationForm): # first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') # last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') avatar = forms.ImageField() birthday = forms.DateField(help_text="Required. Format: YYYY-MM-DD") town = forms.CharField(max_length=128) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'birthday', 'town', 'avatar') class UserCacheMixin: user_cache = None class SignIn(UserCacheMixin, forms.Form): password = forms.CharField(label=_('Password'), strip=False, widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if settings.USE_REMEMBER_ME: self.fields['remember_me'] = forms.BooleanField(label=_('Remember me'), required=False) def clean_password(self): password = self.cleaned_data['password'] if not self.user_cache: return password if not self.user_cache.check_password(password): raise ValidationError(_('You entered an invalid password.')) return password class SignInViaUsernameForm(SignIn): username = forms.CharField(label=_('Username')) @property def field_order(self): if settings.USE_REMEMBER_ME: return ['username', 'password', 'remember_me'] return ['username', 'password'] def clean_username(self): username = self.cleaned_data['username'] user = User.objects.filter(username=username).first() if not user: raise ValidationError(_('You entered an invalid username.')) if not user.is_active: raise ValidationError(_('This account is not active.')) self.user_cache = user return username class SignInViaEmailForm(SignIn): email = forms.EmailField(label=_('Email')) @property def field_order(self): if settings.USE_REMEMBER_ME: return ['email', 'password', 'remember_me'] return ['email', 'password'] def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).first() if not user: raise ValidationError(_('You entered an invalid email address.')) if not user.is_active: raise ValidationError(_('This account is not active.')) self.user_cache = user return email class SignInViaEmailOrUsernameForm(SignIn): email_or_username = forms.CharField(label=_('Email or Username')) @property def field_order(self): if settings.USE_REMEMBER_ME: return ['email_or_username', 'password', 'remember_me'] return ['email_or_username', 'password'] def clean_email_or_username(self): email_or_username = self.cleaned_data['email_or_username'] user = User.objects.filter(Q(username=email_or_username) | Q(email__iexact=email_or_username)).first() if not user: raise ValidationError(_('You entered an invalid email address or username.')) if not user.is_active: raise ValidationError(_('This account is not active.')) self.user_cache = user return email_or_username class SignUpForm(UserCreationForm): class Meta: model = User fields = settings.SIGN_UP_FIELDS email = forms.EmailField(label=_('Email'), help_text=_('Required. Enter an existing email address.')) # email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') # avatar = forms.ImageField() # birthday = forms.DateField(help_text="Required. Format: YYYY-MM-DD") # town = forms.CharField(max_length=128) def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).exists() if user: raise ValidationError(_('You can not use this email address.')) return email class ResendActivationCodeForm(UserCacheMixin, forms.Form): email_or_username = forms.CharField(label=_('Email or Username')) def clean_email_or_username(self): email_or_username = self.cleaned_data['email_or_username'] user = User.objects.filter(Q(username=email_or_username) | Q(email__iexact=email_or_username)).first() if not user: raise ValidationError(_('You entered an invalid email address or username.')) if user.is_active: raise ValidationError(_('This account has already been activated.')) activation = user.activation_set.first() if not activation: raise ValidationError(_('Activation code not found.')) now_with_shift = timezone.now() - timedelta(hours=24) if activation.created_at > now_with_shift: raise ValidationError(_('Activation code has already been sent. You can request a new code in 24 hours.')) self.user_cache = user return email_or_username class ResendActivationCodeViaEmailForm(UserCacheMixin, forms.Form): email = forms.EmailField(label=_('Email')) def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).first() if not user: raise ValidationError(_('You entered an invalid email address.')) if user.is_active: raise ValidationError(_('This account has already been activated.')) activation = user.activation_set.first() if not activation: raise ValidationError(_('Activation code not found.')) now_with_shift = timezone.now() - timedelta(hours=24) if activation.created_at > now_with_shift: raise ValidationError(_('Activation code has already been sent. You can request a new code in 24 hours.')) self.user_cache = user return email class RestorePasswordForm(UserCacheMixin, forms.Form): email = forms.EmailField(label=_('Email')) def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).first() if not user: raise ValidationError(_('You entered an invalid email address.')) if not user.is_active: raise ValidationError(_('This account is not active.')) self.user_cache = user return email class RestorePasswordViaEmailOrUsernameForm(UserCacheMixin, forms.Form): email_or_username = forms.CharField(label=_('Email or Username')) def clean_email_or_username(self): email_or_username = self.cleaned_data['email_or_username'] user = User.objects.filter(Q(username=email_or_username) | Q(email__iexact=email_or_username)).first() if not user: raise ValidationError(_('You entered an invalid email address or username.')) if not user.is_active: raise ValidationError(_('This account is not active.')) self.user_cache = user return email_or_username class ChangeProfileForm(forms.Form): first_name = forms.CharField(label=_('First name'), max_length=30, required=False) last_name = forms.CharField(label=_('Last name'), max_length=150, required=False) class ChangeEmailForm(forms.Form): email = forms.EmailField(label=_('Email')) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_email(self): email = self.cleaned_data['email'] if email == self.user.email: raise ValidationError(_('Please enter another email.')) user = User.objects.filter(Q(email__iexact=email) & ~Q(id=self.user.id)).exists() if user: raise ValidationError(_('You can not use this mail.')) return email class RemindUsernameForm(UserCacheMixin, forms.Form): email = forms.EmailField(label=_('Email')) def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).first() if not user: raise ValidationError(_('You entered an invalid email address.')) if not user.is_active: raise ValidationError(_('This account is not active.')) self.user_cache = user return email
32.276978
118
0.673353
a014a38f4da9628602a004ae141b0a383b2b2a07
1,691
py
Python
tests/test_figure.py
CDonnerer/shellplot
52860a2af2dad1bb2eeb9d94342350038d17da66
[ "MIT" ]
1
2021-11-15T18:52:43.000Z
2021-11-15T18:52:43.000Z
tests/test_figure.py
CDonnerer/shellplot
52860a2af2dad1bb2eeb9d94342350038d17da66
[ "MIT" ]
null
null
null
tests/test_figure.py
CDonnerer/shellplot
52860a2af2dad1bb2eeb9d94342350038d17da66
[ "MIT" ]
null
null
null
"""Test figure api for shellplot """ import pytest import numpy as np from shellplot.figure import array_split, figure @pytest.mark.parametrize( "x, y, expected_xy", [ ( np.array([[0, 1], [1, 0]]), np.array([[1, 1], [2, 2]]), [ (np.array([0, 1]), np.array([1, 1])), (np.array([1, 0]), np.array([2, 2])), ], ), ], ) def test_array_split_arrays(x, y, expected_xy): kwargs = {} for x, y, kwargs in array_split(x, y, kwargs): expected_x, expected_y = expected_xy.pop(0) np.testing.assert_array_equal(x, expected_x) np.testing.assert_array_equal(y, expected_y) @pytest.mark.parametrize( # fmt: off "kwargs, expected_kwargs", [ ( {"label": ["a", "b"]}, [{"label": "a"}, {"label": "b"}] ), ( {"label": ["a"]}, [{"label": "a"}, {}] ), ( {}, [{}, {}] ), ], ) def test_array_split_label_kwargs(kwargs, expected_kwargs): x = np.array([[0, 1], [1, 0]]) y = np.array([[1, 1], [2, 2]]) for x, y, kwargs in array_split(x, y, kwargs): assert kwargs == expected_kwargs.pop(0) def test_figure_setters(): """Faux test for checking that setters do not fail""" fig = figure() properties = { "xlim": (0, 1), "ylim": (0, 1), "xlabel": "a", "ylabel": "b", "xticks": [0, 1], "yticks": [0, 1], "xticklabels": ["a", "b"], "yticklabels": ["a", "b"], } for key, val in properties.items(): getattr(fig, f"set_{key}")(val)
22.851351
59
0.465996
65aa0716b5aeb26927a540ea4f69a6dcfc6276b6
4,326
py
Python
contrib/seeds/generate-seeds.py
HaimenToshi/public
6dff42726821d426ef4895687fce2edb27df10ea
[ "MIT" ]
null
null
null
contrib/seeds/generate-seeds.py
HaimenToshi/public
6dff42726821d426ef4895687fce2edb27df10ea
[ "MIT" ]
null
null
null
contrib/seeds/generate-seeds.py
HaimenToshi/public
6dff42726821d426ef4895687fce2edb27df10ea
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2014-2017 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Script to generate list of seed nodes for chainparams.cpp. This script expects two text files in the directory that is passed as an argument: nodes_main.txt nodes_test.txt These files must consist of lines in the format <ip> <ip>:<port> [<ipv6>] [<ipv6>]:<port> <onion>.onion 0xDDBBCCAA (IPv4 little-endian old pnSeeds format) The output will be two data structures with the peers in binary format: static SeedSpec6 pnSeed6_main[]={ ... } static SeedSpec6 pnSeed6_test[]={ ... } These should be pasted into `src/chainparamsseeds.h`. ''' from base64 import b32decode from binascii import a2b_hex import sys, os import re # ipv4 in ipv6 prefix pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) # tor-specific ipv6 prefix pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) def name_to_ipv6(addr): if len(addr)>6 and addr.endswith('.onion'): vchAddr = b32decode(addr[0:-6], True) if len(vchAddr) != 16-len(pchOnionCat): raise ValueError('Invalid onion %s' % s) return pchOnionCat + vchAddr elif '.' in addr: # IPv4 return pchIPv4 + bytearray((int(x) for x in addr.split('.'))) elif ':' in addr: # IPv6 sub = [[], []] # prefix, suffix x = 0 addr = addr.split(':') for i,comp in enumerate(addr): if comp == '': if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end continue x += 1 # :: skips to suffix assert(x < 2) else: # two bytes per component val = int(comp, 16) sub[x].append(val >> 8) sub[x].append(val & 0xff) nullbytes = 16 - len(sub[0]) - len(sub[1]) assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) return bytearray(sub[0] + ([0] * nullbytes) + sub[1]) elif addr.startswith('0x'): # IPv4-in-little-endian return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:]))) else: raise ValueError('Could not parse address %s' % addr) def parse_spec(s, defaultport): match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) if match: # ipv6 host = match.group(1) port = match.group(2) elif s.count(':') > 1: # ipv6, no port host = s port = '' else: (host,_,port) = s.partition(':') if not port: port = defaultport else: port = int(port) host = name_to_ipv6(host) return (host,port) def process_nodes(g, f, structname, defaultport): g.write('static SeedSpec6 %s[] = {\n' % structname) first = True for line in f: comment = line.find('#') if comment != -1: line = line[0:comment] line = line.strip() if not line: continue if not first: g.write(',\n') first = False (host,port) = parse_spec(line, defaultport) hoststr = ','.join(('0x%02x' % b) for b in host) g.write(' {{%s}, %i}' % (hoststr, port)) g.write('\n};\n') def main(): if len(sys.argv)<2: print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr) exit(1) g = sys.stdout indir = sys.argv[1] g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * List of fixed seed nodes for the bitcoin network\n') g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n') g.write(' *\n') g.write(' * Each line contains a 16-byte IPv6 address and a port.\n') g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n') g.write(' */\n') with open(os.path.join(indir,'nodes_main.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_main', 7332) g.write('\n') with open(os.path.join(indir,'nodes_test.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_test', 6250) g.write('#endif // BITCOIN_CHAINPARAMSSEEDS_H\n') if __name__ == '__main__': main()
31.347826
98
0.581368
629d15809365873e526f2f34a49f1060b8219caa
28,780
py
Python
pylinex/fitter/Extractor.py
CU-NESS/pylinex
b6f342595b6a154e129eb303782e5268088f34d5
[ "Apache-2.0" ]
null
null
null
pylinex/fitter/Extractor.py
CU-NESS/pylinex
b6f342595b6a154e129eb303782e5268088f34d5
[ "Apache-2.0" ]
null
null
null
pylinex/fitter/Extractor.py
CU-NESS/pylinex
b6f342595b6a154e129eb303782e5268088f34d5
[ "Apache-2.0" ]
null
null
null
""" File: pylinex/fitter/Extractor.py Author: Keith Tauscher Date: 3 Sep 2017 Description: Class which uses the rest of the module to perform an end-to-end extraction. The inputs of the class are data and error vectors, training set matrices and expanders. """ import numpy as np from ..util import Savable, VariableGrid, create_hdf5_dataset, sequence_types,\ int_types, bool_types, real_numerical_types from ..quantity import QuantityFinder, FunctionQuantity, CompiledQuantity from ..expander import Expander, NullExpander, ExpanderSet from ..basis import TrainedBasis, BasisSum, effective_training_set_rank from .MetaFitter import MetaFitter try: # this runs with no issues in python 2 but raises error in python 3 basestring except: # this try/except allows for python 2/3 compatible string type checking basestring = str class Extractor(Savable, VariableGrid, QuantityFinder): """ Class which, given: 1) 1D data array 2) 1D error array 3) names of different components of data 4) training set matrices for each of component of the data 5) (optional) Expander objects which transform curves from the space in which the training set is defined to the space in which the data is defined 6) dimensions over which the Extractor should analytically explore 7) quantities of which to calculate grids 8) the name of the quantity to minimize extracts components of the data. """ def __init__(self, data, error, names, training_sets, dimensions,\ compiled_quantity=CompiledQuantity('empty'),\ quantity_to_minimize='bias_score', expanders=None,\ mean_translation=False, num_curves_to_score=None,\ use_priors_in_fit=False, prior_covariance_expansion_factor=1.,\ prior_covariance_diagonal=False, verbose=True): """ Initializes an Extractor object with the given data and error vectors, names, training sets, dimensions, compiled quantity, quantity to minimize, and expanders. data: 1D numpy.ndarray of observed values of some quantity error: 1D numpy.ndarray of error values on the observed data names: names of distinct bases to separate training_sets: training sets corresponding to given names of bases. Must be 2D array where the first dimension represents the number of the curve. dimensions: the dimensions of the grid in which to search for the chosen solution. Should be a list of dictionaries of arrays where each element of the list is a dimension and the arrays in each dictionary must be of equal length compiled_quantity: Quantity or CompiledQuantity to find at each point in the grid described by dimensions quantity_to_minimize: the name of the Quantity object in the CompiledQuantity to minimize to perform model selection expanders: list of Expander objects which expand each of the basis sets mean_translation: if True (default False), means are subtracted before taking SVD when making bases. The means are set to the bases' translation properties. num_curves_to_score: the approximate number of combined training set curves to use when computing the bias_score quantity use_priors_in_fit: if True, priors derived from training set will be used in fits if False, no priors are used in fits prior_covariance_expansion_factor: factor by which prior covariance matrices should be expanded (if they are used), default 1 prior_covariance_diagonal: boolean determining whether off-diagonal elements of the prior covariance are used or not, default False (meaning they are used). Setting this to true will weaken priors but should enhance numerical stability verbose: if True, messages should be printed to the screen """ self.mean_translation = mean_translation self.data = data self.error = error self.names = names self.num_curves_to_score = num_curves_to_score self.training_sets = training_sets self.expanders = expanders self.dimensions = dimensions if ('bias_score' in compiled_quantity) or\ ((type(self.num_curves_to_score) is not type(None)) and\ (self.num_curves_to_score == 0)): self.compiled_quantity = compiled_quantity else: self.compiled_quantity =\ compiled_quantity + self.bias_score_quantity self.quantity_to_minimize = quantity_to_minimize self.prior_covariance_expansion_factor =\ prior_covariance_expansion_factor self.prior_covariance_diagonal = prior_covariance_diagonal self.use_priors_in_fit = use_priors_in_fit self.verbose = verbose @property def mean_translation(self): """ Property storing a boolean determining whether mean is subtracted before SVD is performed when computing basis vectors. """ if not hasattr(self, '_mean_translation'): raise AttributeError("mean_translation was referenced before " +\ "it was set.") return self._mean_translation @mean_translation.setter def mean_translation(self, value): """ Setter for the mean translation property that determines whether mean is subtracted before SVD is performed when computing basis vectors. value: True or False """ if type(value) in bool_types: self._mean_translation = value else: raise TypeError("mean_translation was set to a non-bool.") @property def use_priors_in_fit(self): """ Property storing bool desribing whether priors will be used in fits. """ if not hasattr(self, '_use_priors_in_fit'): raise AttributeError("use_priors_in_fit referenced before it " +\ "was set.") return self._use_priors_in_fit @use_priors_in_fit.setter def use_priors_in_fit(self, value): """ Setter for whether priors will be used in fits. value: if True, priors derived from training set will be used in fits if False, no priors are used in fits """ if type(value) in bool_types: self._use_priors_in_fit = {name: value for name in self.names} elif isinstance(value, dict): if set([key for key in value.keys()]) <= set(self.names): if all([(type(value[key]) in bool_types) for key in value]): self._use_priors_in_fit = value for name in\ (set(self.names) - set([key for key in value.keys()])): self._use_priors_in_fit[name] = False print(("{!s} wasn't included in use_priors_in_fit " +\ "dict, so no priors will be used for it.").format(\ name)) else: raise TypeError("Not all values of the given " +\ "dictionary are bools.") else: raise ValueError("Not all names in the given dictionary " +\ "are names of this Extractor.") else: raise TypeError("If use_priors_in_fit is set to a non-bool, " +\ "it should be set to a dictionary whose keys are the " +\ "names of this Extractor and whose values are bools.") @property def num_curves_to_score(self): """ Property storing the approximate number of curves for which to calculate the bias_score. """ if not hasattr(self, '_num_curves_to_score'): raise AttributeError("num_curves_to_score referenced before it " +\ "was set.") return self._num_curves_to_score @num_curves_to_score.setter def num_curves_to_score(self, value): """ Setter for the maximum number of curves to score. value: if None, all combinations of training set curves are scored if value == 0, bias_score quantity is not calculated at all otherwise, value must be an integer number of curves to score (+-1 block). If integer is greater than number of curves, all curves are returned as if None was passed as value """ if type(value) is type(None): self._num_curves_to_score = None elif type(value) in int_types: if value >= 0: self._num_curves_to_score = value else: raise ValueError("Cannot score non-positive number of curves.") else: raise TypeError("num_curves_to_score was neither None nor of " +\ "an integer type.") @property def bias_score_quantity(self): """ Property storing the quantity which will calculate the training set based bias score. """ if not hasattr(self, '_bias_score_quantity'): self._bias_score_quantity =\ FunctionQuantity('bias_score', self.training_sets,\ num_curves_to_score=self.num_curves_to_score) return self._bias_score_quantity @property def verbose(self): """ Property storing a boolean switch determining which things are printed. """ if not hasattr(self, '_verbose'): raise AttributeError("verbose was referenced before it was set.") return self._verbose @verbose.setter def verbose(self, value): """ Setter for the verbose property which decided whether things are printed. value: must be a bool """ if type(value) in bool_types: self._verbose = value else: raise TypeError("verbose was set to a non-bool.") @property def quantity_to_minimize(self): """ Property storing string name of quantity to minimize. """ if not hasattr(self, '_quantity_to_minimize'): raise AttributeError("quantity_to_minimize was referenced " +\ "before it was set.") return self._quantity_to_minimize @quantity_to_minimize.setter def quantity_to_minimize(self, value): """ Allows user to supply string name of the quantity to minimize. """ if isinstance(value, basestring): if value in self.compiled_quantity: self._quantity_to_minimize = value else: raise ValueError("quantity_to_minimize was not in " +\ "compiled_quantity.") else: raise TypeError("quantity_to_minimize was not a string.") @property def data(self): """ Property storing the data from which pieces are to be extracted. Should be a 1D numpy array. """ if not hasattr(self, '_data'): raise AttributeError("data was referenced before it was set.") return self._data @data.setter def data(self, value): """ Setter for the data property. It checks to ensure that value is a 1D numpy.ndarray or can be cast to one. """ try: value = np.array(value) except: raise TypeError("data given to Extractor couldn't be cast as a " +\ "numpy.ndarray.") if value.ndim in [1, 2]: self._data = value else: raise ValueError("data must be 1D or 2D.") @property def num_channels(self): """ Property storing the number of channels in the data. A positive integer """ if not hasattr(self, '_num_channels'): self._num_channels = self.data.shape[-1] return self._num_channels @property def error(self): """ Property storing the error level in the data. This is used to define the dot product. """ if not hasattr(self, '_error'): raise AttributeError("error was referenced before it was set.") return self._error @error.setter def error(self, value): """ Setter for the error property. value: must be a 1D numpy.ndarray of positive values with the same length as the data. """ try: value = np.array(value) except: raise TypeError("error could not be cast to a numpy.ndarray.") if value.shape == (self.num_channels,): self._error = value else: raise ValueError("error was set to a numpy.ndarray which " +\ "didn't have the expected shape (i.e. 1D with " +\ "length given by number of data channels.") @property def num_bases(self): """ Property storing the number of sets of basis functions (also the same as the number of distinguished pieces of the data). """ if not hasattr(self, '_num_bases'): self._num_bases = len(self.names) return self._num_bases @property def training_sets(self): """ Property storing the training sets used in this extraction. returns a list of numpy.ndarrays """ if not hasattr(self, '_training_sets'): raise AttributeError("training_sets was referenced before it " +\ "was set.") return self._training_sets @training_sets.setter def training_sets(self, value): """ Allows user to set training_sets with list of numpy arrays. value: sequence of numpy.ndarray objects storing training sets, which are 2D """ if type(value) in sequence_types: num_training_sets = len(value) if num_training_sets == self.num_bases: if all([isinstance(ts, np.ndarray) for ts in value]): if all([(ts.ndim == 2) for ts in value]): if (type(self.num_curves_to_score) is type(None)) or\ (self.num_curves_to_score == 0): self._training_sets = [ts for ts in value] else: lengths = [len(ts) for ts in value] perms =\ [np.random.permutation(l) for l in lengths] self._training_sets = [value[its][perms[its]]\ for its in range(len(value))] else: raise ValueError("At least one of the training " +\ "sets given to Extractor was not 2D.") else: raise TypeError("At least one of the given training " +\ "sets given to Extractor was not a " +\ "numpy.ndarray.") else: raise ValueError(("The number of names given to Extractor " +\ "({0}) was not equal to the number of training sets " +\ "given ({1})").format(self.num_bases, num_training_sets)) else: raise TypeError("training_sets of Extractor class was set to a " +\ "non-sequence.") @property def training_set_ranks(self): """ Property storing the effective ranks of the training sets given. This is computed by fitting the training set with its own SVD modes and checking how many terms are necessary to fit down to the (expander-contracted) noise level. """ if not hasattr(self, '_training_set_ranks'): self._training_set_ranks = {} for (name, expander, training_set) in\ zip(self.names, self.expanders, self.training_sets): self._training_set_ranks[name] = effective_training_set_rank(\ training_set, expander.contract_error(self.error),\ mean_translation=self.mean_translation) return self._training_set_ranks @property def training_set_rank_indices(self): """ Property storing a dictionary with tuples containing the dimension and rank index as values indexed by the associated subbasis name. """ if not hasattr(self, '_training_set_rank_indices'): self._training_set_rank_indices = {} for name in self.names: rank = self.training_set_ranks[name] for (idimension, dimension) in self.dimensions: if name in dimension: if rank in dimension[name]: rank_index =\ np.where(dimension[name] == rank)[0][0] else: print(("rank of {0!s} (1:d) not in its grid " +\ "dimension. Are you sure you're using " +\ "enough terms?").format(name, rank)) rank_index = None self._training_set_rank_indices[name] =\ (idimension, rank_index) break else: pass return self._training_set_rank_indices @property def training_set_lengths(self): """ Property storing the number of channels in each of the different training sets. """ if not hasattr(self, '_training_set_lengths'): self._training_set_lengths =\ [ts.shape[-1] for ts in self.training_sets] return self._training_set_lengths @property def total_number_of_combined_training_set_curves(self): """ The number of combined training set curves which are given by the training sets of this Extractor. """ if not hasattr(self, '_total_number_of_combined_training_set_curves'): self._total_number_of_combined_training_set_curves =\ np.prod(self.training_set_lengths) return self._total_number_of_combined_training_set_curves @property def expanders(self): """ Property storing the Expander objects connecting the training set spaces to the data space. returns: list of values which are either None or 2D numpy.ndarrays """ if not hasattr(self, '_expanders'): raise AttributeError("expanders was referenced before it was set.") return self._expanders @expanders.setter def expanders(self, value): """ Allows user to set expanders. value: list of length self.num_bases. Each element is either None (only allowed if length of training set corresponding to element is num_channels) or an Expander object """ if type(value) is type(None): value = [NullExpander()] * self.num_bases if type(value) in sequence_types: num_expanders = len(value) if num_expanders == self.num_bases: for ibasis in range(self.num_bases): expander = value[ibasis] if isinstance(expander, Expander): ts_len = self.training_set_lengths[ibasis] if expander.is_compatible(ts_len, self.num_channels): continue else: raise ValueError("At least one expander was " +\ "not compatible with the " +\ "given training set length " +\ "and number of channels.") else: raise TypeError("Not all expanders are Expander " +\ "objects.") self._expanders = value else: raise ValueError(("The number of expanders ({0}) given was " +\ "not equal to the number of names and training sets " +\ "({1}).").format(num_expanders, self.num_bases)) else: raise TypeError("expanders was set to a non-sequence.") @property def basis_sum(self): """ Property storing the Basis objects associated with all training sets. """ if not hasattr(self, '_basis_sum'): bases = [] for ibasis in range(self.num_bases): training_set = self.training_sets[ibasis] num_basis_vectors = self.maxima[self.names[ibasis]] expander = self.expanders[ibasis] basis = TrainedBasis(training_set, num_basis_vectors,\ error=self.error, expander=expander,\ mean_translation=self.mean_translation) bases.append(basis) self._basis_sum = BasisSum(self.names, bases) return self._basis_sum @property def prior_covariance_expansion_factor(self): """ Property storing the factor by which the prior covariance matrix should be expanded (default 1). """ if not hasattr(self, '_prior_covariance_expansion_factor'): raise AttributeError("prior_covariance_expansion_factor was " +\ "referenced before it was set.") return self._prior_covariance_expansion_factor @prior_covariance_expansion_factor.setter def prior_covariance_expansion_factor(self, value): """ Setter for the expansion factor of the prior covariance matrix value: positive number (usually greater than 1) """ if type(value) in real_numerical_types: if value > 0: self._prior_covariance_expansion_factor = value else: raise ValueError("prior_covariance_expansion_factor was " +\ "set to a non-positive number.") else: raise TypeError("prior_covariance_expansion_factor was set to " +\ "a non-number.") @property def prior_covariance_diagonal(self): """ Property storing whether the prior covariance matrix should be taken to be diagonal or not (default False). """ if not hasattr(self, '_prior_covariance_diagonal'): raise AttributeError("prior_covariance_diagonal was referenced " +\ "before it was set.") return self._prior_covariance_diagonal @prior_covariance_diagonal.setter def prior_covariance_diagonal(self, value): """ Setter for whether prior covariance used should be diagonal or not. value: True or False """ if type(value) in bool_types: self._prior_covariance_diagonal = value else: raise TypeError("prior_covariance_diagonal was set to a non-bool.") @property def priors(self): """ Property storing a dictionary whose keys are names of bases with '_prior' appended and whose values are GaussianDistribution objects. """ if not hasattr(self, '_priors'): self._priors = {} for name in self.names: if self.use_priors_in_fit[name]: self.basis_sum[name].generate_gaussian_prior(\ covariance_expansion_factor=\ self.prior_covariance_expansion_factor,\ diagonal=self.prior_covariance_diagonal) self._priors['{!s}_prior'.format(name)] =\ self.basis_sum[name].gaussian_prior return self._priors @property def meta_fitter(self): """ Property storing the MetaFitter object doing the searching to find the right number of parameters. """ if not hasattr(self, '_meta_fitter'): self._meta_fitter = MetaFitter(self.basis_sum, self.data,\ self.error, self.compiled_quantity, self.quantity_to_minimize,\ *self.dimensions, **self.priors) return self._meta_fitter @property def fitter(self): """ Property storing the Fitter object which minimizes the Quantity object named quantity_to_minimize. """ if not hasattr(self, '_fitter'): if self.data.ndim == 1: indices = self.meta_fitter.minimize_quantity(\ self.quantity_to_minimize) self._fitter = self.meta_fitter.fitter_from_indices(indices) if self.verbose: print("Chose the following numbers of parameters: " +\ "{!s}".format(self._fitter.sizes)) elif self.data.ndim > 1: self._fitter = np.ndarray(self.data.shape[:-1], dtype=object) for data_indices in np.ndindex(*self.data.shape[:-1]): indices = self.meta_fitter.minimize_quantity(\ self.quantity_to_minimize, data_indices) self._fitter[data_indices] =\ self.meta_fitter.fitter_from_indices(indices) if self.verbose: print("Chose the following numbers of parameters: " +\ "{!s}".format(self._fitter[data_indices])) return self._fitter @property def expander_set(self): """ Property yielding an ExpanderSet object organizing the expanders here so that "true" curves for (e.g.) systematics can be found by using the data as well as a "true" curve for the signal. """ if not hasattr(self, '_expander_set'): self._expander_set = ExpanderSet(self.data, self.error,\ **{self.names[iname]: self.expanders[iname]\ for iname in range(self.num_bases)}) return self._expander_set def fill_hdf5_group(self, group, save_all_fitters=False,\ save_training_sets=False, save_channel_estimates=False): """ Fills the given hdf5 file group with data about this extraction, including the optimal fitter and the grids of statistics which were calculated. group: the hdf5 file group into which to save data save_all_fitters: bool determining whether to save all fitters in grid save_training_sets: bool determining whether to save training sets """ data_link = create_hdf5_dataset(group, 'data', data=self.data) error_link = create_hdf5_dataset(group, 'error', data=self.error) subgroup = group.create_group('names') for name in self.names: subgroup.attrs[name] = name subgroup = group.create_group('expanders') self.expander_set.fill_hdf5_group(subgroup) expander_links = [subgroup[name] for name in self.names] self.meta_fitter.fill_hdf5_group(group.create_group('meta_fitter'),\ save_all_fitters=save_all_fitters, data_link=data_link,\ error_link=error_link, expander_links=expander_links,\ save_channel_estimates=save_channel_estimates) subgroup = group.create_group('ranks') for name in self.names: subgroup.attrs[name] = self.training_set_ranks[name] if save_training_sets: subgroup = group.create_group('training_sets') for ibasis in range(self.num_bases): create_hdf5_dataset(subgroup, self.names[ibasis],\ data=self.training_sets[ibasis])
42.511078
79
0.579812
c74c2c2bbed2224d6fcdf33cb481b6cba1df5b3d
12,664
py
Python
temp/modul.py
fadlytanjung/Prediction-DBD-case-with-ANN
36078c98498a9eaaaa11e8d1f96fa743add2887c
[ "MIT" ]
null
null
null
temp/modul.py
fadlytanjung/Prediction-DBD-case-with-ANN
36078c98498a9eaaaa11e8d1f96fa743add2887c
[ "MIT" ]
2
2021-08-25T16:11:50.000Z
2022-02-10T01:56:00.000Z
temp/modul.py
fadlytanjung/Prediction-DBD-case-with-ANN
36078c98498a9eaaaa11e8d1f96fa743add2887c
[ "MIT" ]
null
null
null
import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from tensorflow.keras.layers import Dense from tensorflow.keras.models import Sequential from tensorflow.keras import backend as K from tensorflow.keras.optimizers import SGD, Adagrad, RMSprop, Adadelta, Adamax, Adam from tensorflow.keras.models import model_from_json from tensorflow.keras import backend as K import matplotlib import matplotlib.pyplot as plt matplotlib.use('Agg') import math class Preprocessing: def __init__(self): self.trainScore = 0 self.testScore = 0 self.rmseTrain = 0 self.rmseTest = 0 "load data input" def load_data(self, file): data = pd.read_excel(file) data = data.sort_values([4,1, 0], ascending=[True, True, True]) return data.values '''milih baris data yang obat''' def selecting_data(self, data): temp = np.zeros(4, ) for i in data: if i[3] == 1: pecah_date = i[0].split('-') nama_obat = i[1].upper() np.put(i, [0], (pecah_date[1])) np.put(i, [1], nama_obat) np.put(i,[3],'OBAT') temp = np.vstack((temp, i)) temp = np.delete(temp, (0, 0), 0) return temp '''hitung jumlah obat perbulan''' def sum_data(self, data): df = pd.DataFrame(data) df = df.groupby([0, 1]) new_data = np.zeros(4, ) j = 1 for name, group in df: j += 1 stok = 0 for i in group.values: stok += i[2] isi = i np.put(isi, 2, stok) new_data = np.vstack((new_data, isi)) new_data = np.delete(new_data, 0, axis=-0) return new_data def simpan_file(self, data): np.savetxt("new_dataset.csv", data, delimiter=',', fmt='%s') def one_hot(self, data): values = data[:, 4] # define example '''encode nama obat ke integer''' # integer encode self.label_encoder = LabelEncoder() integer_encoded = self.label_encoder.fit_transform(values) data[:, 4] = integer_encoded return data '''hapus kolom yg gak dipake''' def hapus_kolom(self, data, kolom): return np.delete(data, kolom, axis=1) '''bagi train sama test data''' def split_data(self, dataset): train_size = int(len(dataset) * 0.80) test_size = len(dataset) - train_size train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :] return train, test def normalisasi(self, data): self.scaler = MinMaxScaler(feature_range=(0, 1)) dataset = self.scaler.fit_transform(np.reshape(data[:,1],(-1,1))) data[:,1] = np.reshape(dataset,(1,-1)) return data def create_dataset(self, dataset, look_back=1): dataX, dataY = [], [] hapus_baris = [] for i in range(len(dataset) - look_back - 1): a = dataset[i, :] dataX.append(a) dataY.append(dataset[i + look_back, 1]) if i>0 and dataset[i,0] != dataset[i-1,0]: hapus_baris.append((i-1)) dataX = np.array(dataX) dataY = np.array(dataY) dataX = np.delete(dataX,hapus_baris,axis=0) dataY = np.delete(dataY,hapus_baris,axis=0) return dataX, dataY class ANN: def __init__(self): self.model_loaded = False def set_param(self, neuron=4, optimizer="Adam", epoch=10, batch_size=1, lr=0.001, activation='relu'): self.neuron = neuron self.optimizer = optimizer self.epoch = epoch self.batch_size = batch_size self.model_loaded = False self.learning_rate = lr self.activation = activation def soft_acc(self, y_true, y_pred): return K.mean(K.equal(K.round(y_true), K.round(y_pred))) '''pembuatan model''' def training(self, trainX, trainY, testX, testY, preprocessing): model = Sequential() model.add(Dense(2, input_dim=2, activation=self.activation)) # inputlayer model.add(Dense(self.neuron, activation=self.activation)) # hiddenlayer model.add(Dense(1, activation='linear')) # outputlayer if 'SGD' in self.optimizer: opt = SGD(lr=self.learning_rate, momentum=0.0, decay=0.0, nesterov=False) if 'RMSProp' in self.optimizer: opt = RMSprop(lr=self.learning_rate, rho=0.9, epsilon=None, decay=0.0) if 'Adgrad' in self.optimizer: opt = Adagrad(lr=self.learning_rate, epsilon=None, decay=0.0) if 'Adamax' in self.optimizer: opt = Adamax(lr=self.learning_rate, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0) if 'Adam' in self.optimizer: opt = Adam(lr=self.learning_rate, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False) if 'Adadelta' in self.optimizer: opt = Adadelta(lr=self.learning_rate, rho=0.95, epsilon=None, decay=0.0) model.compile(loss='mean_squared_error', optimizer=opt) self.history = model.fit(trainX, trainY, epochs=self.epoch, batch_size=self.batch_size, verbose=2, validation_data=(testX,testY)) # save history loss_history = self.history.history["loss"] # acc_history = self.history.history["soft_acc"] testing_loss_history = self.history.history["val_loss"] # testing_acc_history = self.history.history["val_soft_acc"] loss = np.array(loss_history) np.savetxt("static/loss_history.txt", loss, delimiter=",") # acc = np.array(acc_history) # np.savetxt("static/acc_history.txt", acc, delimiter=",") tes_loss = np.array(testing_loss_history) np.savetxt("static/testing_loss_history.txt", tes_loss, delimiter=",") # tes_acc = np.array(testing_acc_history) # np.savetxt("static/testing_acc_history.txt", tes_acc, delimiter=",") model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) model.save_weights('weights.h5') testPredict = model.predict(testX) testPredict = preprocessing.scaler.inverse_transform(testPredict) # Estimate model performance trainScore = model.evaluate(trainX, trainY, verbose=0) print('Train Score: %.5f MSE (%.5f RMSE)' % (trainScore, math.sqrt(trainScore))) testScore = model.evaluate(testX, testY, verbose=0) print('Test Score: %.5f MSE (%.5f RMSE)' % (testScore, math.sqrt(testScore))) self.trainScore = trainScore self.testScore = testScore self.rmseTrain = math.sqrt(trainScore) self.rmseTest = math.sqrt(testScore) score = np.array([self.trainScore,self.testScore,self.rmseTrain,self.rmseTest]); np.savetxt("static/score.txt",score, delimiter=";") # plot baseline and predictions testY = preprocessing.scaler.inverse_transform(np.reshape(testY,(-1,1))) testX = testX.astype(int) testY = testY.astype(int) testPredict = testPredict.astype(int) obat_asli = preprocessing.label_encoder.inverse_transform(testX[:,0]) testX = testX.astype("S100") testY = testY.astype("S100") testX[:, 0] = obat_asli simpan = np.hstack((testX,testY)) simpan = np.hstack((simpan,testPredict)) simpan = np.delete(simpan,1,axis=1) df = pd.DataFrame(simpan) df.columns = ["Obat","Actual","Predicted"] writer = pd.ExcelWriter('static/hasil_training.xlsx', engine='xlsxwriter') df.to_excel(writer, "Sheet1") writer.save() K.clear_session() def load_model(self): # load json file json_file = open("model.json", "r") loaded_model_json = json_file.read() json_file.close() # load weight self.model = model_from_json(loaded_model_json) self.model.load_weights("weights.h5") self.model.compile(loss='mean_squared_error', optimizer=self.optimizer, metrics=[self.soft_acc]) self.model_loaded = True def prediction(self, datax, bulan, start_bulan, start_tahun, preprocessing): if self.model_loaded == False: print("Model loaded") self.load_model() tulis = np.zeros((4,), dtype="S250") '''prediksi sebanyak variabel bulan''' for bln in range(bulan): # make predictions '''masukkan hasil prediksi ke feature untuk ditabelin''' predict = self.model.predict(datax) predict = preprocessing.scaler.inverse_transform(np.reshape(predict,(-1,1))) new_data = np.zeros(4, ) x = 0 for i in datax: temp = np.array((start_bulan,start_tahun,i[0])) new_data = np.vstack((new_data, np.append(temp, predict[x]))) x += 1 new_data = np.delete(new_data, 0, axis=0) result_test = new_data # preprocessing.scaler.inverse_transform(new_data) result_test = np.rint(result_test) obat = result_test[:, 2] obat = obat.astype(int) obat_asli = preprocessing.label_encoder.inverse_transform(obat) start_bulan += 1 if start_bulan>12: start_tahun+=1 start_bulan=1 tampilkan = result_test tampilkan = tampilkan.astype("S250") tampilkan[:, 2] = obat_asli # tampilkan[:,0] = start_bulan df = pd.DataFrame(tampilkan) tulis = np.vstack((tulis, tampilkan)) print("yang ke-", bln) df.columns = ['Bulan ke','Tahun','Obat', 'Stok'] # print(df) # result_test[:, 0] = start_bulan # result_test[:,1] = start_tahun datax = result_test[:,2:4] #print("bulan") #print(datax) datax = preprocessing.normalisasi(datax) tulis = np.delete(tulis, 0, axis=0) df = pd.DataFrame(tulis) df.columns = ['Bulan ke','Tahun','Obat', 'Stok'] writer = pd.ExcelWriter('static/prediksi.xlsx', engine='xlsxwriter') df.to_excel(writer, "Sheet1") writer.save() K.clear_session() def save_image(self): data = pd.read_csv("static/loss_history.txt") data = data.values data2= pd.read_csv("static/testing_loss_history.txt") data2 = data2.values # summarize history for loss plt.plot(data) plt.plot(data2) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train','test'], loc='upper left') plt.savefig('static/loss.png') plt.close() data = pd.read_csv("static/testing_loss_history.txt") data = data.values # summarize history for loss plt.plot(data) plt.title('model test loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['test'], loc='upper left') plt.savefig('static/loss_test.png') plt.close() if __name__ == "__main__": # fix random seed for reproducibility# np.random.seed(7) preprocessing = Preprocessing() data = preprocessing.load_data("data/datatraining.xlsx") #data = preprocessing.selecting_data(data) #data = preprocessing.sum_data(data) data = preprocessing.one_hot(data) #data = data[data[:, 4].argsort()] data = preprocessing.hapus_kolom(data, [0, 1, 2, 3, 5, 7]) data = data.astype('float32') normal_data = preprocessing.normalisasi(data) train, test = preprocessing.split_data(normal_data) '''buat label''' look_back = 1 trainx, trainY = preprocessing.create_dataset(train, look_back) testx, testY = preprocessing.create_dataset(test, look_back) # trainY = trainY.reshape(len(trainY),1) # testY = testY.reshape(len(testY),1)p nn = ANN() nn.set_param(neuron=8, optimizer="Adam", epoch=5, batch_size=16) nn.training(trainx, trainY, testx, testY, preprocessing) nn.prediction(trainx, 12, 1, 2020, preprocessing)
36.495677
138
0.589071
e0e3404f0ba98fb13139aee4b98452461775fab8
940
py
Python
setup.py
ngendah/vumi-africastalking
89922cd7931a83a089ce3f56b47d233d6003a155
[ "MIT" ]
1
2019-02-17T10:18:35.000Z
2019-02-17T10:18:35.000Z
setup.py
ngendah/vumi-africastalking
89922cd7931a83a089ce3f56b47d233d6003a155
[ "MIT" ]
null
null
null
setup.py
ngendah/vumi-africastalking
89922cd7931a83a089ce3f56b47d233d6003a155
[ "MIT" ]
null
null
null
import os from setuptools import setup, find_packages def read_file(filename): filepath = os.path.join(os.path.abspath(os.path.dirname(__file__)), filename) return open(filepath, 'r').read() setup( name='vumi-africastalking', version=read_file('VERSION'), license='BSD', description='AfricasTalking transport for Vumi and Junebug', long_description='', author='Ngenda Henry', author_email='ngendahk@gmail.com', packages=find_packages(), include_package_data=True, install_requires=[ 'vumi>=0.6.0', 'mock' ], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking', ], )
28.484848
81
0.635106
3ed0233e16fe678fa9921a0817843068c493c7e4
7,150
py
Python
thorpy/elements/lift.py
YannThorimbert/Thorpy-1.5.2a
2f0e5c9c1e17f984498b93bbdb1848e658f5d979
[ "MIT" ]
null
null
null
thorpy/elements/lift.py
YannThorimbert/Thorpy-1.5.2a
2f0e5c9c1e17f984498b93bbdb1848e658f5d979
[ "MIT" ]
null
null
null
thorpy/elements/lift.py
YannThorimbert/Thorpy-1.5.2a
2f0e5c9c1e17f984498b93bbdb1848e658f5d979
[ "MIT" ]
null
null
null
from thorpy.elements.ghost import Ghost from thorpy.elements._sliderutils._shifters import Plus, Minus from thorpy.elements.slider import SliderY from thorpy.elements._sliderutils._dragger import DraggerLiftY, DraggerDirViewerY from thorpy.miscgui.reaction import ConstantReaction from thorpy.miscgui import constants, functions, parameters, style, painterstyle class LiftY(SliderY): def __init__(self, link, text="", elements=None, dragsize=style.LIFT_DRAG_SIZE, buttonsize=style.LIFT_BUTTON_SIZE, normal_params=None): """<link> is the element affected by the lift""" dragsize = style.LIFT_DRAG_SIZE if dragsize is None else dragsize buttonsize=style.LIFT_BUTTON_SIZE if buttonsize is None else buttonsize link_h = link.get_fus_size()[1] # get height of the linked element # set maxval to link height !!!! not link_h, but link_h - self_h limvals = (0, link_h) surplus_h = self._get_theo_size(buttonsize, dragsize, link_h, surplus=True)[1] length = link.get_fus_size()[1] - surplus_h # compute proper height super(LiftY, self).__init__(length, limvals, text, elements, normal_params) self._add_buttons() self._linked = link self.finish() e_right = link.get_fus_rect().right l_width = self.get_fus_size()[0] x = e_right - l_width - style.LIFT_MARGINS[0] y = link.get_fus_rect().top + style.LIFT_MARGINS[1] self.set_topleft((x, y)) self._drag_element.place_at(self._limvals[0]) def _reaction_wheel(self, event): if self.active_wheel: if self.father.collide(event.pos, self.father.current_state_key): self._drag_element.shift(parameters.WHEEL_LIFT_SHIFT) def _reaction_unwheel(self, event): if self.active_wheel: if self.father.collide(event.pos, self.father.current_state_key): self._drag_element.shift(-parameters.WHEEL_LIFT_SHIFT) def get_value(self): return int(SliderY.get_value(self)) def finish(self): SliderY.finish(self) self._finish_add() def misc_refresh(self): SliderY.misc_refresh(self) self._refresh_limvals() def _refresh_limvals(self, fact=1.): linked_family = fact * self._linked.get_family_rect().height selfh = self.get_fus_size()[1] uplim = max(1, linked_family - selfh) self._limvals = (0, uplim) def _setup(self, width=None, dragsize=None): if width is None: width = style.LIFT_BUTTON_SIZE[0] if dragsize is None: dragsize = style.LIFT_DRAG_SIZE self._drag_element = DraggerLiftY(self) self._height = width painter = functions.obtain_valid_painter( painterstyle.DEF_PAINTER, pressed=True, color=style.DEF_COLOR2, size=( width, self._length + dragsize[1] + style.LIFT_MARGINS[1] + 1)) self.set_painter(painter) self._drag_element.set_painter( painterstyle.DEF_PAINTER( size=dragsize), autopress=False) try: self._drag_element.set_center((self.get_fus_center()[0], None)) except AttributeError: # state is ghost state, and has no fusionner self._drag_element.set_center((self.get_ghost_center()[0], None)) self._drag_element.set_free(y=False) Ghost.fit_children(self) def _add_buttons(self, size=None): size = style.SMALL_SIZE if size is None else size self._plus = Plus() self._minus = Minus() self._plus.finish() self._minus.finish() self._plus.drag = self._drag_element self._minus.drag = self._drag_element reac_plus_time = ConstantReaction(constants.THORPY_EVENT, self._plus._reaction_time, {"id":constants.EVENT_TIME}, reac_name=constants.REAC_MOUSE_REPEAT) self.add_reaction(reac_plus_time) reac_minus_time = ConstantReaction(constants.THORPY_EVENT, self._minus._reaction_time, {"id":constants.EVENT_TIME}, reac_name=constants.REAC_MOUSE_REPEAT+0.1) self.add_reaction(reac_minus_time) self.add_elements([self._plus, self._minus]) # reactions to mouse press: reac_pluspress2 = ConstantReaction(constants.THORPY_EVENT, self._drag_element.shift, {"el": self._plus, "id": constants.EVENT_PRESS}, {"sign":parameters.CLICK_LIFT_SHIFT}, reac_name=constants.REAC_PRESSED2) self.add_reaction(reac_pluspress2) reac_minuspress2 = ConstantReaction(constants.THORPY_EVENT, self._drag_element.shift, {"el": self._minus, "id": constants.EVENT_PRESS}, {"sign":-parameters.CLICK_LIFT_SHIFT}, reac_name=constants.REAC_PRESSED2+0.1) self.add_reaction(reac_minuspress2) def _finish_add(self, size=None): size = style.LIFT_BUTTON_SIZE if size is None else size rect = self.get_fus_rect() pos = (rect.centerx, rect.bottom + style.BUTTON_MARGINS[1] + size[1]/2) self._minus.set_center(pos) pos = (rect.centerx, rect.top - style.BUTTON_MARGINS[1] - size[1]/2) self._plus.set_center(pos) Ghost.fit_children(self) self._add_buttons_reactions() class LiftDirViewerY(LiftY): def _setup(self, width=None, dragsize=None): width = style.LIFT_BUTTON_SIZE[0] if width is None else width dragsize = style.LIFT_DRAG_SIZE if dragsize is None else dragsize self._drag_element = DraggerDirViewerY(self) self._height = width painter = functions.obtain_valid_painter( painterstyle.DEF_PAINTER, color=style.DEF_COLOR2, pressed=True, size=(width, self._length + dragsize[1] + style.LIFT_MARGINS[1] + 1)) self.set_painter(painter) self._drag_element.set_painter(painterstyle.DEF_PAINTER(size=dragsize), autopress=False) self.current_state.ghost_rect.height = self._length try: self._drag_element.set_center((self.get_fus_center()[0], None)) except AttributeError: # state is ghost state, and has no fusionner self._drag_element.set_center((self.get_ghost_center()[0], None)) self._drag_element.set_free(y=False) Ghost.fit_children(self)
44.135802
81
0.595385
14e5c0fb293ab4d9a39f178bf927b3d434ece7b5
2,366
py
Python
brbanks2ynab/config/config.py
andreroggeri/br-to-ynab
c5d0ef3804bb575badc05ac6dc771f6a9281f955
[ "MIT" ]
5
2021-09-20T13:15:37.000Z
2022-03-01T01:03:27.000Z
brbanks2ynab/config/config.py
andreroggeri/br-to-ynab
c5d0ef3804bb575badc05ac6dc771f6a9281f955
[ "MIT" ]
4
2021-04-28T14:11:42.000Z
2021-10-09T16:18:15.000Z
brbanks2ynab/config/config.py
andreroggeri/br-to-ynab
c5d0ef3804bb575badc05ac6dc771f6a9281f955
[ "MIT" ]
1
2021-09-27T15:13:30.000Z
2021-09-27T15:13:30.000Z
from dataclasses import dataclass from typing import List, Optional @dataclass class AleloConfig: login: str password: str flex_account: str refeicao_account: str alimentacao_account: str @staticmethod def from_dict(data: dict) -> 'AleloConfig': return AleloConfig( data['login'], data['alelo_password'], data['alelo_flex_account'], data['alelo_refeicao_account'], data['alelo_alimentacao_account'], ) @dataclass class NubankConfig: login: str token: str cert: str credit_card_account: str checking_account: str @staticmethod def from_dict(data: dict) -> 'NubankConfig': return NubankConfig( data['nubank_login'], data['nubank_token'], data['nubank_cert'], data['nubank_credit_card_account'], data['nubank_checking_account'], ) @dataclass class BradescoConfig: branch: str account_no: str account_digit: str web_password: str credit_card_account: str checking_account: str @staticmethod def from_json(data: dict) -> 'BradescoConfig': return BradescoConfig( data['bradesco_branch'], data['bradesco_account_no'], data['bradesco_account_digit'], data['bradesco_web_password'], data['bradesco_credit_card_account'], data['bradesco_checking_account'], ) @dataclass class ImporterConfig: ynab_token: str ynab_budget: str banks: List[str] start_import_date: str bradesco: Optional[BradescoConfig] nubank: Optional[NubankConfig] alelo: Optional[AleloConfig] @staticmethod def from_dict(json_data: dict) -> 'ImporterConfig': bradesco_config = BradescoConfig.from_json(json_data) if json_data.get('bradesco_branch') else None nubank_config = NubankConfig.from_dict(json_data) if json_data.get('nubank_login') else None alelo_config = AleloConfig.from_dict(json_data) if json_data.get('login') else None return ImporterConfig( json_data['ynab_token'], json_data['ynab_budget'], json_data['banks'], json_data['start_import_date'], bradesco_config, nubank_config, alelo_config )
26.886364
107
0.636517
2d403d73a7b6b2e9e1909b018a15b7025e970a12
36,277
py
Python
validator/validator_gen_js.py
brandcast/amphtml
9bbee9915541972a36209c50c6173fe00564463d
[ "Apache-2.0" ]
1
2017-03-10T09:39:45.000Z
2017-03-10T09:39:45.000Z
validator/validator_gen_js.py
brandcast/amphtml
9bbee9915541972a36209c50c6173fe00564463d
[ "Apache-2.0" ]
2
2018-06-18T07:53:55.000Z
2021-05-09T11:56:13.000Z
validator/validator_gen_js.py
brandcast/amphtml
9bbee9915541972a36209c50c6173fe00564463d
[ "Apache-2.0" ]
null
null
null
# # Copyright 2015 The AMP HTML 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. # """Generates validator-generated.js. This script reads validator.protoascii and reflects over its contents to generate Javascript. This Javascript consists of Closure-style classes and enums, as well as a createRules function which instantiates the data structures specified in validator.protoascii - the validator rules. From a Javascript perspective, this approach looks elaborate - you may wonder why we're not just writing Javascript directly, or why we're not encoding our rules in JSON or YAML or even, gasp, XML? Besides the additional type safety that we gain from our approach, it allows us to share the rule specifications, error codes, etc. between multiple validator implemenations, including an implementation in C++. This makes it much easier to keep otherwise likely divergent behavior in sync. """ import hashlib import json import os def UnderscoreToCamelCase(under_score): """Helper function which converts under_score names to camelCase. In proto buffers, fields have under_scores. In Javascript, fields have camelCase. Args: under_score: A name, segmented by under_scores. Returns: A name, segmented as camelCase. """ segments = under_score.split('_') return '%s%s' % (segments[0], ''.join([s.title() for s in segments[1:]])) def FindDescriptors(validator_pb2, msg_desc_by_name, enum_desc_by_name): """Finds the message and enum descriptors in the file. This method finds the message and enum descriptors from a file descriptor; it will visit the top-level messages, and within those the enums. Args: validator_pb2: The proto2 Python module generated from validator.proto. msg_desc_by_name: A map of message descriptors, keyed by full_name. enum_desc_by_name: A map of enum descriptors, keyed by full name. """ for msg_type in validator_pb2.DESCRIPTOR.message_types_by_name.values(): msg_desc_by_name[msg_type.full_name] = msg_type for enum_type in msg_type.enum_types: enum_desc_by_name[enum_type.full_name] = enum_type class OutputFormatter(object): """Helper class for indenting lines.""" def __init__(self, lines): """Initializes the indenter with indent 0.""" self.lines = lines self.indent_by_ = [0] def PushIndent(self, indent): """Pushes a particular indent onto the stack.""" self.indent_by_.append(self.indent_by_[-1] + indent) def PopIndent(self): """Pops a particular indent from the stack, reverting to the previous.""" self.indent_by_.pop() def Line(self, line): """Adds a line to self.lines, applying the indent.""" self.lines.append('%s%s' % (' ' * self.indent_by_[-1], line)) class MessageKey(object): """A hashable key for a proto message capturing its type and content. Messages of the same type (we use the short type name here, e.g. AttrSpec) that serialize to the same byte string are considered the same. """ def __init__(self, proto_message): self.type_name = proto_message.DESCRIPTOR.name # While it's not strictly necessary to use a digest here, we do so # to avoid carrying around the whole serialized string all the time. self.digest = hashlib.sha1(proto_message.SerializeToString()).hexdigest() def __hash__(self): return hash((self.type_name, self.digest)) def __eq__(self, other): return (self.type_name, self.digest) == (other.type_name, other.digest) def __ne__(self, other): return not self == other class MessageRegistry(object): """Maps from messages to ids, used for de-duplication.""" def __init__(self): # We maintain seperate message ids for each type name, e.g. for AttrList, # TagSpec, AttrSpec, etc., there are ids 0 - # unique message instances. self.next_message_id_by_type_name_ = {} # The key for this map is an instance of MessageKey. self.message_id_by_message_key_ = {} # A bit that keeps track whether a message has been emitted or # not. Strictly speaking, this bit gets flipped when the message # is about to be printed - it being true will prevent that # something gets printed twice. self.is_printed_by_message_key_ = {} # References between tag specs in the .protoascii are expressed as # tag spec names (see also TagSpecName), so we maintain this special # case mapping to resolve them to message ids. self.message_id_by_tag_spec_name_ = {} # References from tag specs to attr specs in the .protoascii are expressed # as attr list names, so we maintain this mapping to resolve them to # message ids for the generated Javascript. self.message_id_by_attr_list_name_ = {} # Interned strings have negative IDs, starting from -1. This makes it # easy to distinguish them from other message ids. In the interned_strings_ # array, they can be found by calculating their index -1 - <string_id>. self.interned_strings_ = [] self.string_id_by_interned_string_ = {} def InternString(self, a_string): """Interns strings to eliminate duplicates and to refer to them as numbers. Args: a_string: the string to be interned Returns: The string id, a negative number -1 to -MAXINT. """ string_id = self.string_id_by_interned_string_.get(a_string, 0) if string_id != 0: return string_id self.interned_strings_.append(a_string) string_id = -len(self.interned_strings_) self.string_id_by_interned_string_[a_string] = string_id return string_id def InternedStrings(self): """The interned strings which will be emitted into validator-generated.js. Returns: A list of strings. """ return self.interned_strings_ def MessageIdForKey(self, message_key): """Yields the message id for a key, registering a new one if needed. Args: message_key: an instance of MessageKey Returns: The message id - a number. """ message_id = self.message_id_by_message_key_.get(message_key, -1) if message_id != -1: return message_id message_id = self.next_message_id_by_type_name_.get(message_key.type_name, 0) self.next_message_id_by_type_name_[message_key.type_name] = message_id + 1 self.message_id_by_message_key_[message_key] = message_id return message_id def MessageReferenceForKey(self, message_key): """A message reference is the variable name used in validator-generated.js. Args: message_key: an instance of MessageKey Returns: The message reference - a string. """ return '%s_%d' % (message_key.type_name.lower(), self.MessageIdForKey(message_key)) def MarkPrinted(self, message_key): """Marks a message as printed. Args: message_key: an instance of MessageKey to indentify the message """ self.is_printed_by_message_key_[message_key] = True def IsPrinted(self, message_key): """Whether a message was printed. Args: message_key: an instance of MessageKey to identify the message. Returns: a boolean indicating whether the message was printed. """ return message_key in self.is_printed_by_message_key_ def RegisterTagSpec(self, tag_spec): """Registers a tag spec, including for lookups by TagSpecName. Args: tag_spec: an instance of validator_pb2.TagSpec """ message_id = self.MessageIdForKey(MessageKey(tag_spec)) self.message_id_by_tag_spec_name_[TagSpecName(tag_spec)] = message_id def MessageIdForTagSpecName(self, tag_spec_name): """Looks up a message id for a tag spec by TagSpecName. Args: tag_spec_name: a string - see TagSpecName for computing it. Returns: The message id - a number. """ return self.message_id_by_tag_spec_name_[tag_spec_name] def RegisterAttrList(self, attr_list): """Registers an attr list, including for lookups by name. Args: attr_list: an instance of validator_pb2.AttrList """ message_id = self.MessageIdForKey(MessageKey(attr_list)) self.message_id_by_attr_list_name_[attr_list.name] = message_id def MessageIdForAttrListName(self, attr_list_name): """Looks up a message id for a tag spec by TagSpecName. Args: attr_list_name: a string - the AttrList::name field. Returns: The message id - a number. """ return self.message_id_by_attr_list_name_[attr_list_name] def ElementTypeFor(descriptor, field_desc): """Returns the element Javascript type for a given field descriptor. Args: descriptor: The descriptor module from the protobuf package, e.g. google.protobuf.descriptor. field_desc: A field descriptor for a particular field in a message. Returns: A string; either the type of a field descriptor or iff the field descriptor is a repeated field, it's the element type. """ # If the field is a reference to a tagspec name (string) or if it's # holding a message that we're deduplicating and replacing with a # synthetic reference field, make it a number instead as we'll be # replacing this with the message id. if (field_desc.full_name in TAG_SPEC_NAME_REFERENCE_FIELD) or ( field_desc.full_name in SYNTHETIC_REFERENCE_FIELD) or ( field_desc.full_name in ATTR_LIST_NAME_REFERENCE_FIELD): return 'number' return { descriptor.FieldDescriptor.TYPE_DOUBLE: lambda: 'number', descriptor.FieldDescriptor.TYPE_INT32: lambda: 'number', descriptor.FieldDescriptor.TYPE_BOOL: lambda: 'boolean', descriptor.FieldDescriptor.TYPE_STRING: lambda: 'string', descriptor.FieldDescriptor.TYPE_ENUM: ( lambda: field_desc.enum_type.full_name), descriptor.FieldDescriptor.TYPE_MESSAGE: ( lambda: field_desc.message_type.full_name) }[field_desc.type]() def FieldTypeFor(descriptor, field_desc, nullable): """Returns the Javascript type for a given field descriptor. Args: descriptor: The descriptor module from the protobuf package, e.g. google.protobuf.descriptor. field_desc: A field descriptor for a particular field in a message. nullable: Whether or not the value may be null. Returns: The Javascript type for the given field descriptor. """ element_type = ElementTypeFor(descriptor, field_desc) if field_desc.label == descriptor.FieldDescriptor.LABEL_REPEATED: if nullable: return 'Array<!%s>' % element_type return '!Array<!%s>' % element_type if nullable: return '?%s' % element_type return '%s' % element_type def ValueToString(descriptor, field_desc, value): """For a non-repeated field, renders the value as a Javascript literal. Args: descriptor: The descriptor module from the protobuf package, e.g. google.protobuf.descriptor. field_desc: The type descriptor for the field value to be rendered. value: The value of the non-repeated field to be rendered. Returns: A Javascript literal for the provided non-repeated value. """ if field_desc.type == descriptor.FieldDescriptor.TYPE_STRING: escaped = ('' + value).encode('unicode-escape') return "'%s'" % escaped.replace("'", "\\'") if field_desc.type == descriptor.FieldDescriptor.TYPE_BOOL: if value: return 'true' return 'false' if field_desc.type == descriptor.FieldDescriptor.TYPE_ENUM: enum_value_name = field_desc.enum_type.values_by_number[value].name return '%s.%s' % (field_desc.enum_type.full_name, enum_value_name) if value is None: return 'null' return str(value) # For the validator-light version, skip these fields.This works by # putting them inside a conditional with !amp.validator.LIGHT. # The Closure compiler will then leave them out via dead code elimination. SKIP_FIELDS_FOR_LIGHT = [ 'also_requires_tag_warning', 'deprecation_url', 'error_formats', 'error_specificity', 'errors', 'extension_unused_unless_tag_present', 'html_format', 'max_bytes_spec_url', 'min_validator_revision_required', 'spec_file_revision', 'spec_url', 'template_spec_url', 'unique_warning', 'validator_revision', ] SKIP_CLASSES_FOR_LIGHT = ['amp.validator.ValidationError', 'amp.validator.ErrorFormat'] EXPORTED_CLASSES = [ 'amp.validator.ValidationResult', 'amp.validator.ValidationError' ] CONSTRUCTOR_ARG_FIELDS = [ 'amp.validator.AmpLayout.supported_layouts', 'amp.validator.AtRuleSpec.name', 'amp.validator.AtRuleSpec.type', 'amp.validator.AttrSpec.name', 'amp.validator.AttrTriggerSpec.also_requires_attr', 'amp.validator.BlackListedCDataRegex.error_message', 'amp.validator.BlackListedCDataRegex.regex', 'amp.validator.ErrorFormat.code', 'amp.validator.ErrorFormat.format', 'amp.validator.PropertySpec.name', 'amp.validator.PropertySpecList.properties', 'amp.validator.TagSpec.tag_name', 'amp.validator.UrlSpec.allowed_protocol', 'amp.validator.ValidatorRules.tags', ] # In the .protoascii, some fields reference other tags by tag spec name. # See TagSpecName for how it's computed. This is a string, and this # code generator replaces these fields with tag ids, which are numbers. TAG_SPEC_NAME_REFERENCE_FIELD = [ 'amp.validator.ReferencePoint.tag_spec_name', 'amp.validator.TagSpec.also_requires_tag_warning', 'amp.validator.TagSpec.extension_unused_unless_tag_present', ] # In the .protoascii, some fields reference other tags by attr list name. # This is a string, and this code generator replaces these fields with attr # list ids, which are numbers. ATTR_LIST_NAME_REFERENCE_FIELD = ['amp.validator.TagSpec.attr_lists'] # These fields contain messages in the .protoascii, but we replace # them with message ids, which are numbers. Thus far we do this for # the AttrSpecs. SYNTHETIC_REFERENCE_FIELD = [ 'amp.validator.AttrList.attrs', 'amp.validator.TagSpec.attrs', 'amp.validator.TagSpec.requires', 'amp.validator.TagSpec.satisfies', ] class GenerateNonLightSectionIf(object): """Wraps output lines in a condition for a light validator. For example, the code: ---------------------- with GenerateNonLightSectionIf(true, out): out.Line('DoStuff()') ---------------------- Will generate the output: ---------------------- if (!amp.validator.LIGHT) { DoStuff(); } ---------------------- """ def __init__(self, condition, out): """Constructor. Args: condition: If true, this with generator will indent upon entering and unindent upon exiting. out: a list of lines to output (without the newline characters) wrapped as an OutputFormatter instance, to which this function will append. """ self.condition = condition self.out = out def __enter__(self): if self.condition: self.out.Line('if (!amp.validator.LIGHT) {') self.out.PushIndent(2) def __exit__(self, exception_type, value, traceback): if self.condition: self.out.PopIndent() self.out.Line('}') def PrintClassFor(descriptor, msg_desc, light, out): """Prints a Javascript class for the given proto message. This method emits a Javascript class (Closure-style) for the given proto message to sys.stdout. Args: descriptor: The descriptor module from the protobuf package, e.g. google.protobuf.descriptor. msg_desc: The descriptor for a particular message type. light: A bool indicating whether or not to generate a light validator, that is, one which is configured to not emit detailed errors, only supports a single html_format, and will not export the full API for the Node.js library / tool. out: a list of lines to output (without the newline characters) wrapped as an OutputFormatter instance, to which this function will append. """ with GenerateNonLightSectionIf(msg_desc.full_name in SKIP_CLASSES_FOR_LIGHT, out): constructor_arg_fields = [] constructor_arg_field_names = {} for field in msg_desc.fields: if field.full_name in CONSTRUCTOR_ARG_FIELDS: constructor_arg_fields.append(field) constructor_arg_field_names[field.name] = 1 out.Line('/**') for field in constructor_arg_fields: out.Line(' * @param {%s} %s' % (FieldTypeFor( descriptor, field, nullable=False), UnderscoreToCamelCase(field.name))) out.Line(' * @constructor') out.Line(' * @struct') export_or_empty = '' if not light and msg_desc.full_name in EXPORTED_CLASSES: out.Line(' * @export') export_or_empty = ' @export' out.Line(' */') arguments = ','.join( [UnderscoreToCamelCase(f.name) for f in constructor_arg_fields]) out.Line('%s = function(%s) {' % (msg_desc.full_name, arguments)) out.PushIndent(2) for field in msg_desc.fields: # We generate ValidatorRules.directAttrLists, ValidatorRules.globalAttrs, # and validator.ampLayoutAttrs instead. if field.full_name == 'amp.validator.ValidatorRules.attr_lists': continue assigned_value = 'null' if field.name in constructor_arg_field_names: # field.name is also the parameter name. assigned_value = UnderscoreToCamelCase(field.name) elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: # ValidationResult instances may be mutated by validator.js, # so we can't share the empty arrays. But for all other # instances, we do share. if msg_desc.full_name == 'amp.validator.ValidationResult': assigned_value = '[]' else: assigned_value = 'EMPTY_%s_ARRAY' % ( ElementTypeFor(descriptor, field).replace('.', '_')) elif field.type == descriptor.FieldDescriptor.TYPE_BOOL: assigned_value = str(field.default_value).lower() elif field.type == descriptor.FieldDescriptor.TYPE_INT32: assigned_value = str(field.default_value) # TODO(johannes): Increase coverage for default values, e.g. enums. type_name = FieldTypeFor( descriptor, field, nullable=assigned_value == 'null') with GenerateNonLightSectionIf(field.name in SKIP_FIELDS_FOR_LIGHT, out): out.Line('/**%s @type {%s} */' % (export_or_empty, type_name)) out.Line('this.%s = %s;' % (UnderscoreToCamelCase(field.name), assigned_value)) if msg_desc.full_name == 'amp.validator.ValidatorRules': out.Line('/** @type {!Array<!string>} */') out.Line('this.dispatchKeyByTagSpecId = Array(tags.length);') out.Line('/** @type {!Array<!string>} */') out.Line('this.internedStrings = [];') out.Line('/** @type {!Array<!amp.validator.AttrSpec>} */') out.Line('this.attrs = [];') out.Line('/** @type {!Array<!Array<number>>} */') out.Line('this.directAttrLists = [];') out.Line('/** @type {!Array<number>} */') out.Line('this.globalAttrs = [];') out.Line('/** @type {!Array<number>} */') out.Line('this.ampLayoutAttrs = [];') out.PopIndent() out.Line('};') SKIP_ENUMS_FOR_LIGHT = [ 'amp.validator.ValidationError.Code', 'amp.validator.ValidationError.Severity', 'amp.validator.ErrorCategory.Code', ] def PrintEnumFor(enum_desc, light, out): """Prints a Javascript enum for the given enum descriptor. Args: enum_desc: The descriptor for a particular enum type. light: A bool indicating whether or not to generate a light validator, that is, one which is configured to not emit detailed errors, only supports a single html_format, and will not export the full API for the Node.js library / tool. out: a list of lines to output (without the newline characters) wrapped as an OutputFormatter instance, to which this function will append. """ with GenerateNonLightSectionIf(enum_desc.full_name in SKIP_ENUMS_FOR_LIGHT, out): out.Line('/**') if light: out.Line(' * @enum {number}') else: out.Line(' * @enum {string}') out.Line(' * @export') out.Line(' */') out.Line('%s = {' % enum_desc.full_name) out.PushIndent(2) names = [] for v in enum_desc.values: names.append('%s' % v.name) if light: out.Line('%s: %d,' % (v.name, v.number)) else: out.Line("%s: '%s'," % (v.name, v.name)) out.PopIndent() out.Line('};') out.Line('/** @type {!Array<string>} */') out.Line('%s_NamesByIndex = ["%s"];' % (enum_desc.full_name, '","'.join(names))) out.Line('/** @type {!Array<!%s>} */' % enum_desc.full_name) out.Line('%s_ValuesByIndex = [%s];' % ( enum_desc.full_name, ','.join( ['%s.%s' % (enum_desc.full_name, n)for n in names]))) def TagSpecName(tag_spec): """Generates a name for a given TagSpec. This should be unique. Same logic as getTagSpecName(tagSpec) in javascript. We choose the spec_name if one is set, otherwise use the lower cased version of the tagname Args: tag_spec: A TagSpec protocol message instance. Returns: This TagSpec's name (string). """ if tag_spec.HasField('spec_name'): return tag_spec.spec_name return tag_spec.tag_name.lower() def MaybePrintMessageValue(descriptor, field_val, registry, light, out): """Print field_val if necessary, and return its message reference. Args: descriptor: The descriptor module from the protobuf package, e.g. google.protobuf.descriptor. field_val: The value of a field, a proto message. registry: an instance of MessageRegistry, used for mapping from messages to message keys. light: A bool indicating whether or not to generate a light validator, that is, one which is configured to not emit detailed errors, only supports a single html_format, and will not export the full API for the Node.js library / tool. out: a list of lines to output (without the newline characters) wrapped as an OutputFormatter instance, to which this function will append. Returns: This object's message reference, e.g. typically the variable name in validator-generated.js. """ message_key = MessageKey(field_val) if not registry.IsPrinted(message_key): PrintObject(descriptor, field_val, registry, light, out) return registry.MessageReferenceForKey(message_key) def IsTrivialAttrSpec(attr): """Determines whether a given attr only has its name field set. Args: attr: an AttrSpec instance. Returns: true iff the only field that is set is the name field. """ return (attr.DESCRIPTOR.full_name == 'amp.validator.AttrSpec' and attr.HasField('name') and len(attr.ListFields()) == 1) def AssignedValueFor(descriptor, field_desc, field_val, registry, light, out): """Helper function for PrintObject: computes / assigns a value for a field. Note that if the field is a complex field (a message), this function may print the message and then reference it via a variable name. Args: descriptor: The descriptor module from the protobuf package, e.g. google.protobuf.descriptor. field_desc: The descriptor for a particular field. field_val: The value for a particular field. registry: an instance of MessageRegistry, used for mapping from messages to message keys. light: A bool indicating whether or not to generate a light validator, that is, one which is configured to not emit detailed errors, only supports a single html_format, and will not export the full API for the Node.js library / tool. out: a list of lines to output (without the newline characters) wrapped as an OutputFormatter instance, to which this function will append. Returns: The rendered field value to assign. """ # First we establish how an individual value for this field is going # to be rendered, that is, converted into a string. render_value = lambda: None if field_desc.full_name in TAG_SPEC_NAME_REFERENCE_FIELD: render_value = lambda v: str(registry.MessageIdForTagSpecName(v)) elif field_desc.full_name in ATTR_LIST_NAME_REFERENCE_FIELD: render_value = lambda v: str(registry.MessageIdForAttrListName(v)) elif field_desc.full_name in SYNTHETIC_REFERENCE_FIELD: def InternOrReference(value): if field_desc.type == descriptor.FieldDescriptor.TYPE_STRING: return str(registry.InternString(value)) if IsTrivialAttrSpec(value): return str(registry.InternString(value.name)) return str(registry.MessageIdForKey(MessageKey(value))) render_value = InternOrReference elif field_desc.type == descriptor.FieldDescriptor.TYPE_MESSAGE: render_value = ( lambda v: MaybePrintMessageValue(descriptor, v, registry, light, out)) else: render_value = (lambda v: ValueToString(descriptor, field_desc, v)) # pylint: disable=cell-var-from-loop # Then we iterate over the field if it's repeated, or else just # call the render function once. if field_desc.label == descriptor.FieldDescriptor.LABEL_REPEATED: elements = [render_value(v) for v in field_val] return '[%s]' % ','.join(elements) return render_value(field_val) def PrintObject(descriptor, msg, registry, light, out): """Prints an object, by recursively constructing it. This routine emits Javascript which will construct an object modeling the provided message (in practice the ValidatorRules message). It references the classes and enums enitted by PrintClassFor and PrintEnumFor. Args: descriptor: The descriptor module from the protobuf package, e.g. google.protobuf.descriptor. msg: A protocol message instance. registry: an instance of MessageRegistry, used for mapping from messages to message keys. light: A bool indicating whether or not to generate a light validator, that is, one which is configured to not emit detailed errors, only supports a single html_format, and will not export the full API for the Node.js library / tool. out: a list of lines to output (without the newline characters) wrapped as an OutputFormatter instance, to which this function will append. Returns: This object's object id, that is, the consumed variable for creating objects. """ this_message_key = MessageKey(msg) registry.MarkPrinted(this_message_key) field_and_assigned_values = [] for (field_desc, field_val) in msg.ListFields(): # We generate ValidatorRules.directAttrLists, ValidatorRules.globalAttrs, # and validator.ampLayoutAttrs instead. if field_desc.full_name == 'amp.validator.ValidatorRules.attr_lists': continue if light and field_desc.name in SKIP_FIELDS_FOR_LIGHT: continue field_and_assigned_values.append((field_desc, AssignedValueFor( descriptor, field_desc, field_val, registry, light, out))) # First we emit the constructor call, with the appropriate arguments. constructor_arg_values = [ value for (field, value) in field_and_assigned_values if field.full_name in CONSTRUCTOR_ARG_FIELDS ] this_message_reference = registry.MessageReferenceForKey(this_message_key) out.Line('var %s = new %s(%s);' % (this_message_reference, msg.DESCRIPTOR.full_name, ','.join(constructor_arg_values))) # Then we emit the remaining field values as assignments. for (field, value) in field_and_assigned_values: if light and field.name in SKIP_FIELDS_FOR_LIGHT: continue if field.full_name in CONSTRUCTOR_ARG_FIELDS: continue out.Line('%s.%s = %s;' % (this_message_reference, UnderscoreToCamelCase(field.name), value)) def DispatchKeyForTagSpecOrNone(tag_spec): """For a provided tag_spec, generates its dispatch key. Args: tag_spec: an instance of type validator_pb2.TagSpec. Returns: a string indicating the dispatch key, or None. """ for attr in tag_spec.attrs: if attr.dispatch_key: mandatory_parent = tag_spec.mandatory_parent or '' attr_name = attr.name attr_value = attr.value_casei or attr.value.lower() assert attr_value is not None return '%s\\0%s\\0%s' % (attr_name, attr_value, mandatory_parent) return None def GenerateValidatorGeneratedJs(specfile, validator_pb2, text_format, light, html_format, descriptor, out): """Main method for the code generator. This method reads the specfile and emits Javascript to sys.stdout. Args: specfile: Path to validator.protoascii, the specfile to generate Javascript from. validator_pb2: The proto2 Python module generated from validator.proto. text_format: The text_format module from the protobuf package, e.g. google.protobuf.text_format. light: If true, then no detailed errors will be emitted by the validator, and the rules will be pre-filtered for html_format. html_format: Either a TagSpec.HtmlFormat enum value indicating which HTML format the generated validator code should support, or None indicating that all formats should be supported. descriptor: The descriptor module from the protobuf package, e.g. google.protobuf.descriptor. out: a list of lines to output (without the newline characters), to which this function will append. """ if light: # If we generate a light validator, we require that the rules be filtered # for a specific format (in practice thus far 'AMP' or 'AMP4ADS'). assert html_format is not None else: assert html_format is None # First, find the descriptors and enums and generate Javascript # classes and enums. msg_desc_by_name = {} enum_desc_by_name = {} FindDescriptors(validator_pb2, msg_desc_by_name, enum_desc_by_name) rules_obj = '%s.RULES' % validator_pb2.DESCRIPTOR.package all_names = [rules_obj] + msg_desc_by_name.keys() + enum_desc_by_name.keys() all_names.sort() out = OutputFormatter(out) out.Line('//') out.Line('// Generated by %s - do not edit.' % os.path.basename(__file__)) out.Line('//') out.Line('') for name in all_names: out.Line("goog.provide('%s');" % name) out.Line("goog.provide('amp.validator.LIGHT');") out.Line("goog.provide('amp.validator.VALIDATE_CSS');") out.Line("goog.provide('amp.validator.createRules');") out.Line('') out.Line('/** @define {boolean} */') if light: out.Line('amp.validator.LIGHT = true;') else: out.Line('amp.validator.LIGHT = false;') out.Line('') out.Line('/** @define {boolean} */') out.Line('amp.validator.VALIDATE_CSS = true;') out.Line('') # We share the empty arrays between all specification object instances; this # works because these arrays are never mutated. To make the Closure compiler # happy, we use one empty array per element type. # PS: It may also help execution performance in V8 to keep the element types # separate but we did not verify that. all_type_names = ['string', 'number', 'boolean'] + [ n for n in all_names if n in msg_desc_by_name] + [ n for n in all_names if n in enum_desc_by_name] for name in all_type_names: out.Line('/** @type {!Array<!%s>} */' % name) out.Line('var EMPTY_%s_ARRAY = [];' % name.replace('.', '_')) out.Line('') for name in all_names: if name in msg_desc_by_name: PrintClassFor(descriptor, msg_desc_by_name[name], light, out) elif name in enum_desc_by_name: PrintEnumFor(enum_desc_by_name[name], light, out) # Read the rules file, validator.protoascii by parsing it as a text # message of type ValidatorRules. rules = validator_pb2.ValidatorRules() text_format.Merge(open(specfile).read(), rules) # If html_format is set, only keep the tags which are relevant to it. if html_format is not None: filtered_rules = [ t for t in rules.tags if not t.html_format or html_format in t.html_format ] del rules.tags[:] rules.tags.extend(filtered_rules) registry = MessageRegistry() # Register the tagspecs so they have ids 0 - rules.tags.length. This means # that rules.tags[tagspec_id] works. for t in rules.tags: registry.RegisterTagSpec(t) # Register the attrlists so they have ids 0 - rules.attr_lists.length. # This means that rules.attr_lists[attr_list_id] works. for a in rules.attr_lists: registry.RegisterAttrList(a) out.Line('/**') out.Line(' * @return {!%s}' % rules.DESCRIPTOR.full_name) out.Line(' */') out.Line('amp.validator.createRules = function() {') out.PushIndent(2) PrintObject(descriptor, rules, registry, light, out) # We use this below to reference the variable holding the rules instance. rules_reference = registry.MessageReferenceForKey(MessageKey(rules)) # Add the dispatchKeyByTagSpecId array, for those tag specs that have # a dispatch key. for tag_spec in rules.tags: tag_spec_id = registry.MessageIdForTagSpecName(TagSpecName(tag_spec)) dispatch_key = DispatchKeyForTagSpecOrNone(tag_spec) if dispatch_key: out.Line('%s.dispatchKeyByTagSpecId[%d]="%s";' % (rules_reference, tag_spec_id, dispatch_key)) # Create a mapping from attr spec ids to AttrSpec instances, deduping the # AttrSpecs. Then sort by these ids, so now we get a dense array starting # with the attr that has attr spec id 0 - number of attr specs. attrs_by_id = {} for attr_container in list(rules.attr_lists) + list(rules.tags): for attr in attr_container.attrs: if not IsTrivialAttrSpec(attr): attrs_by_id[registry.MessageIdForKey(MessageKey(attr))] = attr sorted_attrs = [attr for (_, attr) in sorted(attrs_by_id.items())] # Emit the attr specs, then assign a list of references to them to # Rules.attrs. for attr in sorted_attrs: PrintObject(descriptor, attr, registry, light, out) out.Line('%s.attrs = [%s];' % (rules_reference, ','.join( [registry.MessageReferenceForKey(MessageKey(a)) for a in sorted_attrs]))) # We emit the attr lists as arrays of arrays of numbers (which are # the attr ids), and treat the globalAttrs and the ampLayoutAttrs # seperately for fast access. direct_attr_lists = [] global_attrs = [] amp_layout_attrs = [] unique_attr_list_names = set() for attr_list in rules.attr_lists: assert attr_list.name not in unique_attr_list_names, attr_list.name unique_attr_list_names.add(attr_list.name) assert attr_list.attrs attr_id_list = [] for attr in attr_list.attrs: if IsTrivialAttrSpec(attr): attr_id_list.append(registry.InternString(attr.name)) else: attr_id_list.append(registry.MessageIdForKey(MessageKey(attr))) if attr_list.name == '$GLOBAL_ATTRS': global_attrs = attr_id_list direct_attr_lists.append([]) elif attr_list.name == '$AMP_LAYOUT_ATTRS': amp_layout_attrs = attr_id_list direct_attr_lists.append([]) else: direct_attr_lists.append(attr_id_list) out.Line('%s.directAttrLists = %s;' % ( rules_reference, json.dumps(direct_attr_lists))) out.Line('%s.globalAttrs = %s;' % ( rules_reference, json.dumps(global_attrs))) out.Line('%s.ampLayoutAttrs = %s;' % ( rules_reference, json.dumps(amp_layout_attrs))) # We emit these after the last call to registry.InternString. out.Line('%s.internedStrings = ["%s"];' % (rules_reference, '","'.join(registry.InternedStrings()))) out.Line('return %s;' % rules_reference) out.PopIndent() out.Line('}') out.Line('')
38.226554
109
0.701353
85bc45834243e7cfe9eeb3504c8581f1276266fa
2,016
py
Python
interactive_scene/scene_builder/scripts/utils.py
OneOneEleven/Interactive-Scene-Reconstruction
dade6e95eea56e04a5d39441f4e03e1667fe37ef
[ "BSD-3-Clause" ]
62
2021-04-04T13:44:24.000Z
2022-03-30T08:13:42.000Z
interactive_scene/scene_builder/scripts/utils.py
OneOneEleven/Interactive-Scene-Reconstruction
dade6e95eea56e04a5d39441f4e03e1667fe37ef
[ "BSD-3-Clause" ]
1
2021-11-23T23:10:07.000Z
2021-11-24T17:29:07.000Z
interactive_scene/scene_builder/scripts/utils.py
hmz-15/Interactive-Scene-Reconstruction
70412c8f5e9ce1c2543fe866f3c5728a723d6478
[ "BSD-3-Clause" ]
8
2021-09-28T12:44:54.000Z
2022-03-03T10:55:29.000Z
import json import argparse class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def print_err(msg): print("{}{}{}".format(bcolors.FAIL, msg, bcolors.ENDC)) def print_info(msg): print("{}{}{}".format(bcolors.OKBLUE, msg, bcolors.ENDC)) def print_warn(msg): print("{}{}{}".format(bcolors.WARNING, msg, bcolors.ENDC)) def print_ok(msg): print("{}{}{}".format(bcolors.OKGREEN, msg, bcolors.ENDC)) def load_json(file_dir): ret = None with open(file_dir, "r") as fin: ret = json.load(fin) return ret def arg_parser(): """Argument Parser Parse arguments from command line, and perform error checking Returns: An argument object which contains arguments from cmd line """ parser = argparse.ArgumentParser(prog='Scene Builder') parser.add_argument( "-c, --src", dest="src", type=str, required=True, help="Input source" ) parser.add_argument( "-o, --out", dest="out", type=str, default="./output", help="Output directory" ) parser.add_argument( "--name", dest="name", type=str, default=None, help="Scene name" ) parser.add_argument( "--vrgym", dest="vrgym", action="store_true", help="Enable VRGym" ) parser.add_argument( "--physics", dest="physics", action="store_true", help="Enable Physical Properties" ) parser.add_argument( "--gazebo", dest="gazebo", action="store_true", help="Enable Gazebo Output" ) args = parser.parse_args() # if gazebo output is enabled, the physical properties # must be enabled as well if args.gazebo: args.physics = True return args
19.960396
65
0.561012
c6f1b58807575725f205bad4104de07b6f8a81cc
6,159
py
Python
functions_modified.py
oezgueracar/hatespeech-detection-with-BERT
d212d0d86eb3002d13cce985d07aa3bb6f8532a8
[ "MIT" ]
null
null
null
functions_modified.py
oezgueracar/hatespeech-detection-with-BERT
d212d0d86eb3002d13cce985d07aa3bb6f8532a8
[ "MIT" ]
null
null
null
functions_modified.py
oezgueracar/hatespeech-detection-with-BERT
d212d0d86eb3002d13cce985d07aa3bb6f8532a8
[ "MIT" ]
1
2021-07-09T13:41:18.000Z
2021-07-09T13:41:18.000Z
# Import packages and change some pandas display options import pandas as pd import numpy as np import re import warnings import xgboost as xgb import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import auc, f1_score, roc_curve, roc_auc_score def get_simple_features(data): """ Creates simple features from the comments and adds them as new columns to the dataset.""" # data['words'] = data.Comment_text.apply(lambda x: len(x.split())) data['uppercase'] = data.Comment_text.apply(lambda x: len(re.findall("[A-Z]", x))) data['uppercase_per_word'] = data['uppercase'] / data['words'] data['punctuation'] = data.Comment_text.apply(lambda x: len(re.findall("[,.!?]", x))) data['punctuation_per_word'] = data['punctuation'] / data['words'] data['numbers'] = data.Comment_text.apply(lambda x: len(re.findall("[1-9]+", x))) data['numbers_per_word'] = data['numbers'] / data['words'] simple_features = ['words', 'uppercase', 'uppercase_per_word', 'punctuation', 'punctuation_per_word', 'numbers', 'numbers_per_word'] return data, simple_features def evaluate_model(y_test, y_pred, plot=False, model_name="", features=""): """ Evaluates model and plots ROC. """ fpr, tpr, _ = roc_curve(y_test, y_pred) roc_auc = auc(fpr, tpr) f1 = f1_score(y_test, y_pred > 0.5) print(model_name) print("F1 Score : {}".format(round(f1, 3))) print("AUC : {}".format(round(roc_auc, 3))) if plot: # Compute micro-average ROC curve and ROC area plt.figure(figsize=(9, 6)) lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic {} -- {}'.format(model_name, features)) plt.legend(loc="lower right") plt.show() print("-----------------------------------------------") def make_confusion_matrix(cf, group_names=None, categories='auto', count=True, percent=True, cbar=True, xyticks=True, xyplotlabels=True, sum_stats=True, figsize=None, cmap='Blues', title=None): ''' This function will make a pretty plot of an sklearn Confusion Matrix cm using a Seaborn heatmap visualization. Arguments --------- cf: confusion matrix to be passed in group_names: List of strings that represent the labels row by row to be shown in each square. categories: List of strings containing the categories to be displayed on the x,y axis. Default is 'auto' count: If True, show the raw number in the confusion matrix. Default is True. normalize: If True, show the proportions for each category. Default is True. cbar: If True, show the color bar. The cbar values are based off the values in the confusion matrix. Default is True. xyticks: If True, show x and y ticks. Default is True. xyplotlabels: If True, show 'True Label' and 'Predicted Label' on the figure. Default is True. sum_stats: If True, display summary statistics below the figure. Default is True. figsize: Tuple representing the figure size. Default will be the matplotlib rcParams value. cmap: Colormap of the values displayed from matplotlib.pyplot.cm. Default is 'Blues' See http://matplotlib.org/examples/color/colormaps_reference.html title: Title for the heatmap. Default is None. ''' # CODE TO GENERATE TEXT INSIDE EACH SQUARE blanks = ['' for i in range(cf.size)] if group_names and len(group_names)==cf.size: group_labels = ["{}\n".format(value) for value in group_names] else: group_labels = blanks if count: group_counts = ["{0:0.0f}\n".format(value) for value in cf.flatten()] else: group_counts = blanks if percent: group_percentages = ["{0:.2%}".format(value) for value in cf.flatten()/np.sum(cf)] else: group_percentages = blanks box_labels = [f"{v1}{v2}{v3}".strip() for v1, v2, v3 in zip(group_labels,group_counts,group_percentages)] box_labels = np.asarray(box_labels).reshape(cf.shape[0],cf.shape[1]) # CODE TO GENERATE SUMMARY STATISTICS & TEXT FOR SUMMARY STATS if sum_stats: #Accuracy is sum of diagonal divided by total observations accuracy = np.trace(cf) / float(np.sum(cf)) #if it is a binary confusion matrix, show some more stats if len(cf)==2: #Metrics for Binary Confusion Matrices precision = cf[1,1] / sum(cf[:,1]) recall = cf[1,1] / sum(cf[1,:]) f1_score = 2*precision*recall / (precision + recall) stats_text = "\n\nAccuracy={:0.3f}\nPrecision={:0.3f}\nRecall={:0.3f}\nF1 Score={:0.3f}".format( accuracy,precision,recall,f1_score) else: stats_text = "\n\nAccuracy={:0.3f}".format(accuracy) else: stats_text = "" # SET FIGURE PARAMETERS ACCORDING TO OTHER ARGUMENTS if figsize==None: #Get default figure size if not set figsize = plt.rcParams.get('figure.figsize') if xyticks==False: #Do not show categories if xyticks is False categories=False # MAKE THE HEATMAP VISUALIZATION plt.figure(figsize=figsize) sns.heatmap(cf,annot=box_labels,fmt="",cmap=cmap,cbar=cbar,xticklabels=categories,yticklabels=categories) if xyplotlabels: plt.ylabel('True label') plt.xlabel('Predicted label' + stats_text) else: plt.xlabel(stats_text) if title: plt.title(title)
37.554878
114
0.60578
65c54ca48b3280d22524fcf00d3af979e88d9983
28,445
py
Python
evalme/tests/test_object_detection.py
heartexlabs/label-studio-evalme
48f7a5226346b6e074edb4717b84122cc089bc7a
[ "MIT" ]
3
2020-04-11T13:01:57.000Z
2021-05-19T13:53:16.000Z
evalme/tests/test_object_detection.py
heartexlabs/label-studio-evalme
48f7a5226346b6e074edb4717b84122cc089bc7a
[ "MIT" ]
28
2020-05-21T01:34:44.000Z
2022-03-21T15:39:16.000Z
evalme/tests/test_object_detection.py
heartexlabs/label-studio-evalme
48f7a5226346b6e074edb4717b84122cc089bc7a
[ "MIT" ]
1
2020-05-21T17:43:26.000Z
2020-05-21T17:43:26.000Z
import pytest from evalme.image.object_detection import KeyPointsEvalItem, keypoints_distance, PolygonObjectDetectionEvalItem, OCREvalItem def test_keypoints_matching(): ''' Matching with almost 1 distance ''' test_data = [ [{ "id": "S6oszbKrqK", "type": "keypointlabels", "value": { "x": 35.111111, "y": 65.41666666666667, "width": 0.625, "keypointlabels": ["Engine"] }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 320, "original_height": 240 }], [{ "id": "S6oszbKrqK", "type": "keypointlabels", "value": { "x": 34.222222, "y": 64.4167, "width": 0.625, "keypointlabels": ["Engine"] }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 320, "original_height": 240 }] ] assert keypoints_distance(test_data[0], test_data[1], label_weights={}) == 1 def test_keypoints_matching_per_label(): ''' Matching with almost 1 distance per label ''' test_data = [ [{ "id": "S6oszbKrqK", "type": "keypointlabels", "value": { "x": 35.111111, "y": 65.41666666666667, "width": 0.625, "keypointlabels": ["Engine"] }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 320, "original_height": 240 }], [{ "id": "S6oszbKrqK", "type": "keypointlabels", "value": { "x": 34.222222, "y": 64.4167, "width": 0.625, "keypointlabels": ["Engine"] }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 320, "original_height": 240 }] ] assert keypoints_distance(test_data[0], test_data[1], label_weights={}, per_label=True) == {"Engine": 1} def test_keypoints_not_matching(): ''' Not Matching with almost 1 distance ''' test_data = [ [{ "id": "S6oszbKrqK", "type": "keypointlabels", "value": { "x": 35.333333, "y": 65.41666666666667, "width": 0.625, "keypointlabels": ["Engine"] }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 320, "original_height": 240 }], [{ "id": "S6oszbKrqK", "type": "keypointlabels", "value": { "x": 34.222222, "y": 64.4165, "width": 0.625, "keypointlabels": ["Engine"] }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 320, "original_height": 240 }] ] assert keypoints_distance(test_data[0], test_data[1], label_weights={}) == 0 def test_keypoints_not_matching_label(): ''' Not Matching label ''' test_data = [ [{ "id": "S6oszbKrqK", "type": "keypointlabels", "value": { "x": 34.0, "y": 64.0, "width": 0.625, "keypointlabels": ["Engine"] }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 320, "original_height": 240 }], [{ "id": "S6oszbKrqK", "type": "keypointlabels", "value": { "x": 34.0, "y": 64.0, "width": 0.625, "keypointlabels": ["Engine1"] }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 320, "original_height": 240 }] ] assert keypoints_distance(test_data[0], test_data[1], label_weights={}) == 0 def test_keypoints_not_matching_per_label(): ''' Not Matching with almost 1 distance per label ''' test_data = [ [{ "id": "S6oszbKrqK", "type": "keypointlabels", "value": { "x": 35.333333, "y": 65.41666666666667, "width": 0.625, "keypointlabels": ["Engine"] }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 320, "original_height": 240 }], [{ "id": "S6oszbKrqK", "type": "keypointlabels", "value": { "x": 34.222222, "y": 64.4165, "width": 0.625, "keypointlabels": ["Engine"] }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 320, "original_height": 240 }] ] assert keypoints_distance(test_data[0], test_data[1], label_weights={}, per_label=True) =={"Engine": 0} def test_object_detection_fixing_polygon(): points = [[37.5, 23.046875], [36.328125, 23.828125], [35.15625, 25.0], [37.109375, 23.4375], [38.671875, 23.046875], [41.015625, 25.390625], [41.015625, 26.953125], [40.625, 34.375], [40.234375, 37.890625], [41.40625, 39.453125], [41.796875, 40.625], [42.1875, 41.796875], [42.96875, 42.96875], [39.453125, 43.359375], [39.453125, 41.796875], [38.28125, 41.015625], [39.0625, 42.1875], [38.28125, 44.140625], [36.71875, 43.359375], [37.109375, 41.796875], [36.71875, 40.625], [37.5, 39.453125], [36.328125, 38.28125], [35.15625, 39.0625], [34.765625, 40.234375], [34.375, 41.40625], [33.984375, 42.96875], [33.203125, 44.140625], [32.8125, 45.3125], [32.421875, 46.484375], [31.640625, 47.65625], [31.25, 48.828125], [31.25, 50.390625], [30.859375, 51.5625], [30.078125, 52.734375], [29.6875, 53.90625], [29.296875, 55.078125], [28.90625, 56.25], [29.296875, 57.8125], [38.28125, 57.8125], [42.96875, 58.203125], [56.25, 57.8125], [59.765625, 58.203125], [60.9375, 57.421875], [60.546875, 55.859375], [60.15625, 54.296875], [59.765625, 53.125], [59.765625, 48.828125], [59.375, 46.875], [58.984375, 44.921875], [58.203125, 43.75], [57.8125, 42.578125], [57.421875, 41.40625], [57.421875, 37.890625], [57.03125, 35.9375], [56.640625, 34.765625], [56.25, 31.640625], [55.859375, 29.6875], [55.46875, 27.734375], [54.6875, 26.5625], [55.46875, 25.390625], [53.90625, 25.0], [52.734375, 25.390625], [51.5625, 25.0], [50.390625, 24.21875], [48.828125, 23.828125], [47.65625, 24.21875], [46.484375, 23.4375], [45.3125, 24.21875], [46.09375, 26.953125], [44.921875, 27.34375], [43.359375, 26.171875], [41.40625, 24.609375], [40.234375, 23.046875]] p = PolygonObjectDetectionEvalItem(raw_data=None) polygon = p._try_build_poly(points) assert polygon.is_valid def test_object_detection_fixing_polygon(): """ Test for checking building invalid polygons with loops """ p = PolygonObjectDetectionEvalItem(raw_data=None) points1 = [[71.24548999277505, 36.442868897058716], [71.31558790201544, 37.70463126338564], [71.45578372049621, 39.49212794901545], [71.52588162973657, 41.17447777078468], [71.52588162973657, 42.96197445641448], [71.42744842558623, 45.27520546134716], [71.32230156172567, 47.30468799946319], [71.21044103815485, 49.42850658383994], [70.96509835581352, 52.00460474842407], [70.78985358271255, 54.265262321426476], [70.54451090037121, 56.57849332635916], [70.34093083236029, 58.807458774596476], [70.26411926340965, 60.258633561479336], [70.16568605925933, 61.90929125848349], [70.09558815001893, 63.61252238741793], [70.01877658106832, 64.41193468397212], [70.33421717265004, 66.04171107381104], [70.509461945751, 67.77663432751056], [70.58627351470162, 69.20692780722821], [70.69142037856221, 70.85758550423236], [70.8176953255995, 72.64508218986217], [70.90171410628336, 74.46427100025706], [71.01406818187716, 76.74580988042466], [71.03519626505388, 78.39646757742882], [71.10529417429427, 79.92109710340716], [71.18210574324492, 81.5299921860809], [71.21044103815485, 82.23432810833987], [71.07695887938432, 82.67579687094738], [70.93004940119332, 82.9177827234336], [70.54451090037121, 82.97035615536389], [70.18878835052809, 82.60086147578286], [69.97227451511971, 81.78767704949077], [69.97048961465292, 80.90606805814588], [69.86484919876933, 80.43068618666975], [69.52679986794186, 80.20884131331421], [69.2098786202911, 79.92361219042854], [68.70280462404989, 79.701767317073], [68.17460254463198, 79.54330669324763], [67.68865663156748, 79.63838306754286], [67.0970703026194, 79.76515156660317], [66.48435589049461, 80.08207281425392], [65.74487297930952, 80.39899406190467], [64.8363654027107, 80.71591530955543], [63.69648963582931, 80.99337713085148], [62.70240761490822, 81.38157207973887], [61.784075352967555, 81.83738885841124], [60.605850385566455, 81.87386039550947], [59.65999873999142, 81.79340974568201], [58.73492518962879, 81.67225917510848], [57.85780403220267, 81.63517862484865], [57.43529069195391, 81.71175837580526], [56.75889812040099, 82.25500990165214], [56.37309564523462, 82.40121795693683], [56.03277336117247, 82.45725418825431], [55.7151554112775, 82.26999733190546], [55.326917291475496, 81.88653465985347], [55.058061904904946, 81.36917038099757], [54.81980387642082, 80.68320401905817], [54.658559177049796, 79.8972182739836], [54.57795248388386, 79.21247101818575], [54.58786254237386, 78.31563727052497], [54.65744788021747, 77.32990585050003], [54.83977505252922, 74.792935976939], [55.17620037056849, 72.30473837034044], [55.3583293680495, 70.7532969148149], [55.60257456419653, 69.70893636699515], [55.783799901722084, 68.33456897337967], [55.85825286218083, 67.08414411711703], [55.93177037724768, 65.76804422219723], [55.94015426181347, 64.30099510919057], [55.94832194493592, 62.86909389643798], [55.96427935908149, 62.098023087460696], [56.615029525666664, 61.002802357662496], [57.02527568231736, 61.29596595758693], [57.46273366498702, 61.83028687299975], [58.07050051782664, 62.25380786427346], [58.50389989802015, 62.5171573413049], [58.91879381577917, 62.999267914918605], [59.268562115515415, 63.06605068811326], [59.76005622645524, 63.11999279809634], [60.66139312484395, 63.515046526694505], [61.35051604759635, 63.423340732929645], [61.808574623067514, 63.106240060787805], [62.30432304818241, 62.54327537914041], [62.539587740692454, 62.325116299571405], [62.701051475838895, 62.13850046431015], [63.14586691284543, 61.85717292059291], [63.202574327194625, 61.54864449551725], [63.11650219433461, 61.264041361548685], [63.274309291605334, 61.22151134316702], [63.582222682455466, 61.2478114045958], [63.75181297117496, 61.20139237851563], [63.857191244642124, 60.970382934677055], [63.91814492387204, 60.7641684432282], [63.92312129493989, 60.59745156025348], [65.0463149189407, 61.25941764845373], [65.26880983467146, 61.19402295639785], [65.46676384125016, 61.012843304807575], [65.6123736498138, 60.67692773078017], [65.59604489008994, 60.35646600722881], [65.41896154775907, 60.023177806943735], [64.77191598191997, 59.41690925218269], [64.1102731388132, 58.84895732540074], [62.981803205149085, 58.06039045019356], [62.27164004306869, 57.527117916145414], [61.67247382657756, 56.90039294960442], [61.799599957596286, 56.67646440884397], [61.94017088193441, 56.455007201204374], [62.45993772054322, 56.04610401425424], [62.89643561187592, 55.644356500727994], [63.26697706818597, 55.17486124375921], [63.494035357433795, 54.2992312297473], [63.50053269403326, 53.62317766665219], [63.37350720761441, 53.33902533686241], [63.155714962569014, 53.28547820194824], [62.93646558232525, 53.467955360686666], [62.75750778876408, 53.84796659605624], [62.51358363920958, 54.20704608897229], [62.19592381110928, 54.42049191776855], [61.86510534683914, 54.76663160134683], [61.5584376140037, 55.02540945221735], [61.23542311979876, 55.38703932414456], [61.008044494654534, 55.53373279178538], [60.77725906662706, 55.69279453789216], [60.582252028989245, 56.01155377925047], [60.22746959329231, 56.352486418021705], [59.89775460423932, 56.70636858783149], [59.68277910344004, 57.17862985566916], [59.44928001985543, 57.3149276037563], [59.36463419352438, 57.567519400805146], [58.987793860548834, 57.854797289506095], [58.52559786339017, 58.07313198091575], [58.24434785689984, 58.19215402593864], [58.077723717313056, 58.121470940970845], [57.89359234179078, 58.1606992666703], [57.67251611790723, 58.23713702708523], [57.84937591912521, 57.961590785049204], [58.06187606719222, 57.56530903495161], [58.21133943908635, 57.07174404340931], [58.29430454972359, 56.32974077406917], [58.31969169477289, 55.02957071624504], [58.435808363835285, 53.697081552322054], [58.649470464180425, 52.61819639193315], [58.89781449260207, 51.53422336516053], [59.06282111541507, 50.82814637206523], [59.28767650641035, 50.31260035578549], [59.4313703272291, 49.900796984713594], [59.474775368756816, 48.96510288587076], [59.403972830570574, 47.52965772633963], [59.23276525734068, 45.796951211939245], [59.171278783971104, 45.077484253139055], [59.082753938223746, 44.388948899918795], [58.966611547569435, 43.28526667806965], [58.912438598470956, 41.91598270138615], [58.8987991918453, 40.56595175598115], [58.87839066486148, 39.953793495574956], [58.96645332254199, 38.071295960351215], [59.04503499682862, 36.49942433070164], [59.384522359533335, 35.64443640738881], [59.74517246454507, 34.448201172071], [59.87982738580833, 34.08344698503056], [59.893086405566386, 33.87428634636171], [60.6808904611383, 31.940211162639486], [61.605356522644634, 29.677699633344925], [62.34241758643345, 27.893863288378906], [60.952549423160285, 29.34680069116033], [55.76160558614943, 35.32618023397065], [55.605506396023245, 35.42073813617422], [55.32715112944967, 35.73508199284892], [54.97103071960984, 36.25797742952729], [54.633528241537626, 36.9843285912676], [54.26807096343351, 37.497235560356465], [53.83217258093989, 38.17825775749258], [53.50162649038513, 38.82396866456495], [53.06786127867833, 40.601739955066876], [52.84196368499808, 42.274530364303985], [52.783383655409835, 43.50938477202643], [52.50839748642768, 44.888336083281494], [52.27768684320113, 46.18629756025955], [52.08641844032083, 47.37588014112915], [51.89566214915828, 48.73266925030944], [51.767322528757404, 50.556542209518994], [51.736372698058275, 51.54206297327813], [51.573990445706315, 52.63373910051626], [51.460791538415, 52.80725375510232], [51.18430899498759, 53.32131252483345], [51.151662652699535, 54.10159729440949], [51.03533729809058, 54.37210075071141], [51.01499813520173, 55.17663231836683], [50.76725409047201, 55.70161729889367], [50.58968379533592, 56.46000611085433], [50.46707739306644, 57.722815377595246], [50.27082356745067, 57.89138016219952], [50.13187687357528, 58.137339781228505], [50.0505686270744, 58.49945538885535], [50.14341425874418, 59.16469263980238], [49.90914966679136, 59.847920599849765], [49.788683653097344, 60.07596583726081], [49.49172086583298, 60.84586996559508], [49.342901624433125, 62.06998842588095], [49.44041859346952, 63.165749955028346], [49.668574290179805, 64.25848784417997], [49.928395850437056, 64.84305279936005], [50.045011644085044, 65.77996047111341], [50.23549100699365, 66.31095971614643], [50.47181880846324, 66.7936169724774], [50.58996806612921, 67.40380181374151], [50.86712300509155, 68.23554400882216], [51.59897199956446, 68.14526579162069], [51.95153704809118, 67.66791136732252], [52.358679530540996, 67.16988440595944], [54.16704190258511, 64.94553664502024], [52.83206973286896, 66.54983768172292], [52.532778438919806, 67.08044997450287], [51.903247322225354, 68.06972794484054], [51.50610560216469, 69.05767590607314], [50.9763233009358, 70.27166785402501], [50.643172261999155, 71.47216701540958], [50.326294994272324, 72.8395583813219], [50.03638925654642, 74.14605788254052], [49.71391643855616, 75.58382795671191], [49.28807344733942, 77.21490358075039], [48.929120399392765, 79.09330268348658], [48.66901680622432, 80.20108084054931], [48.398138379146346, 81.50535576181836], [48.25063589117616, 83.05711020633949], [48.06391298950883, 84.79611358302171], [47.94539885735842, 86.1971092057169], [48.053392825320884, 86.43685855038606], [48.27501899364376, 86.78694831748697], [48.51450477872317, 87.00091570116585], [48.765382164740195, 86.99654280439964], [48.963754939739204, 86.90510968569275], [49.33711718690008, 86.41847473794789], [49.623338541643015, 85.87302289375616], [49.90191566957567, 85.12933633620422], [50.165129293348876, 84.15921547587293], [50.53503291688815, 82.95540932606576], [50.8425972664721, 81.68713373626564], [51.448810109552355, 79.28079697536243], [52.01489270758875, 77.25119324876009], [52.397596113371925, 75.53728494854272], [52.84880150303474, 73.60041029173141], [53.200356278734176, 72.25757073582841], [53.55414118029318, 70.56654297468714], [54.09316588867561, 68.66701901873371], [54.49009452250821, 67.13851701864796], [54.765570133787854, 65.95636820582571], [54.988354931064855, 65.45988879571682], [55.20746733105245, 65.06114792853795], [55.35881698296463, 64.56310037826378], [55.52796053323985, 63.4684275275065], [55.65506462817371, 62.66928007195139], [54.970870757233286, 56.976136683492406], [54.81722694678211, 56.486161932449185], [54.534615960529436, 55.5960275401542], [54.20026803388244, 54.473773490150734], [53.81265797615115, 53.10707703191306], [53.53970603636695, 52.16462875865812], [53.40800663144548, 51.37397226079495], [53.40600958902171, 50.54830848080784], [53.39971745622639, 49.740420779485895], [53.42019042398491, 48.985118280857606], [53.555862382265154, 48.04355632801825], [53.69391853898538, 48.04536749780579], [53.82490938412744, 47.40243294385485], [54.29413081269998, 45.89443917195816], [54.69197287851976, 44.57950920119552], [55.00946162616242, 43.57893556516054], [55.13387583055568, 42.67917658806935], [55.325327441870236, 40.59723983750328], [55.623374845658255, 38.212844537177176], [55.71981824562783, 36.588936573240204], [55.78559152860122, 35.332379462641015], [62.699666338793875, 26.8117100745742], [62.936586468431884, 27.045428761365315], [63.843428465370565, 27.33794376174733], [65.75375388377067, 28.362506138960082], [66.36252637750958, 28.331606991988995], [67.59390862819974, 28.27529080240259], [68.61872688988996, 28.609172524220007], [69.64706780180786, 29.766475576045952], [70.50000726932018, 31.827931997229065], [70.99035785108931, 34.144349909489875]] polygon1 = p._try_build_poly(points1) points2 = [[37.5, 23.046875], [36.328125, 23.828125], [35.15625, 25.0], [37.109375, 23.4375], [38.671875, 23.046875], [41.015625, 25.390625], [41.015625, 26.953125], [40.625, 34.375], [40.234375, 37.890625], [41.40625, 39.453125], [41.796875, 40.625], [42.1875, 41.796875], [42.96875, 42.96875], [39.453125, 43.359375], [39.453125, 41.796875], [38.28125, 41.015625], [39.0625, 42.1875], [38.28125, 44.140625], [36.71875, 43.359375], [37.109375, 41.796875], [36.71875, 40.625], [37.5, 39.453125], [36.328125, 38.28125], [35.15625, 39.0625], [34.765625, 40.234375], [34.375, 41.40625], [33.984375, 42.96875], [33.203125, 44.140625], [32.8125, 45.3125], [32.421875, 46.484375], [31.640625, 47.65625], [31.25, 48.828125], [31.25, 50.390625], [30.859375, 51.5625], [30.078125, 52.734375], [29.6875, 53.90625], [29.296875, 55.078125], [28.90625, 56.25], [29.296875, 57.8125], [38.28125, 57.8125], [42.96875, 58.203125], [56.25, 57.8125], [59.765625, 58.203125], [60.9375, 57.421875], [60.546875, 55.859375], [60.15625, 54.296875], [59.765625, 53.125], [59.765625, 48.828125], [59.375, 46.875], [58.984375, 44.921875], [58.203125, 43.75], [57.8125, 42.578125], [57.421875, 41.40625], [57.421875, 37.890625], [57.03125, 35.9375], [56.640625, 34.765625], [56.25, 31.640625], [55.859375, 29.6875], [55.46875, 27.734375], [54.6875, 26.5625], [55.46875, 25.390625], [53.90625, 25.0], [52.734375, 25.390625], [51.5625, 25.0], [50.390625, 24.21875], [48.828125, 23.828125], [47.65625, 24.21875], [46.484375, 23.4375], [45.3125, 24.21875], [46.09375, 26.953125], [44.921875, 27.34375], [43.359375, 26.171875], [41.40625, 24.609375], [40.234375, 23.046875]] polygon2 = p._try_build_poly(points2) a = polygon1.intersection(polygon2).area b = p._iou({'points': points1}, {'points': points2}) assert a > 184 assert b > 0.17 def test_OCR_matching_function(): res1 = [{ "id": "rSbk_pk1g-", "type": "rectangle", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "width": 37.157534246575345, "height": 17.12962962962963, "rotation": 0 }, "to_name": "image", "from_name": "bbox", "image_rotation": 0, "original_width": 584, "original_height": 216 }, { "id": "rSbk_pk1g-", "type": "labels", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "width": 37.157534246575345, "height": 17.12962962962963, "labels": ["Text"], "rotation": 0 }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 584, "original_height": 216 }, { "id": "rSbk_pk1g-", "type": "textarea", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "text": ["oh no"], "width": 37.157534246575345, "height": 17.12962962962963, "rotation": 0 }, "to_name": "image", "from_name": "transcription", "image_rotation": 0, "original_width": 584, "original_height": 216 } ] obj1 = OCREvalItem(res1) obj2 = OCREvalItem(res1) assert obj1.compare(obj2) == 1 def test_OCR_matching_function_no_rectangle(): res1 = [{ "id": "rSbk_pk1g-", "type": "rectangle", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "width": 37.157534246575345, "height": 17.12962962962963, "rotation": 0 }, "to_name": "image", "from_name": "bbox", "image_rotation": 0, "original_width": 584, "original_height": 216 }, { "id": "rSbk_pk1g-", "type": "labels", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "width": 37.157534246575345, "height": 17.12962962962963, "labels": ["Text"], "rotation": 0 }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 584, "original_height": 216 }, { "id": "rSbk_pk1g-", "type": "textarea", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "text": ["oh no"], "width": 37.157534246575345, "height": 17.12962962962963, "rotation": 0 }, "to_name": "image", "from_name": "transcription", "image_rotation": 0, "original_width": 584, "original_height": 216 } ] res2 = [ { "id": "rSbk_pk1g", "type": "labels", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "width": 37.157534246575345, "height": 17.12962962962963, "labels": ["Text"], "rotation": 0 }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 584, "original_height": 216 }, { "id": "rSbk_pk1g", "type": "textarea", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "text": ["oh no"], "width": 37.157534246575345, "height": 17.12962962962963, "rotation": 0 }, "to_name": "image", "from_name": "transcription", "image_rotation": 0, "original_width": 584, "original_height": 216 } ] obj1 = OCREvalItem(res1) obj2 = OCREvalItem(res2) assert obj1.compare(obj2) == 0 def test_OCR_matching_function_not_matching_text(): res1 = [{ "id": "rSbk_pk1g-", "type": "rectangle", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "width": 37.157534246575345, "height": 17.12962962962963, "rotation": 0 }, "to_name": "image", "from_name": "bbox", "image_rotation": 0, "original_width": 584, "original_height": 216 }, { "id": "rSbk_pk1g-", "type": "labels", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "width": 37.157534246575345, "height": 17.12962962962963, "labels": ["Text"], "rotation": 0 }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 584, "original_height": 216 }, { "id": "rSbk_pk1g-", "type": "textarea", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "text": ["oh no"], "width": 37.157534246575345, "height": 17.12962962962963, "rotation": 0 }, "to_name": "image", "from_name": "transcription", "image_rotation": 0, "original_width": 584, "original_height": 216 } ] res2 = [{ "id": "rSbk_pk1g", "type": "rectangle", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "width": 37.157534246575345, "height": 17.12962962962963, "rotation": 0 }, "to_name": "image", "from_name": "bbox", "image_rotation": 0, "original_width": 584, "original_height": 216 }, { "id": "rSbk_pk1g", "type": "labels", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "width": 37.157534246575345, "height": 17.12962962962963, "labels": ["Text"], "rotation": 0 }, "to_name": "image", "from_name": "label", "image_rotation": 0, "original_width": 584, "original_height": 216 }, { "id": "rSbk_pk1g", "type": "textarea", "value": { "x": 35.273972602739725, "y": 6.481481481481482, "text": ["ayyes"], "width": 37.157534246575345, "height": 17.12962962962963, "rotation": 0 }, "to_name": "image", "from_name": "transcription", "image_rotation": 0, "original_width": 584, "original_height": 216 } ] obj1 = OCREvalItem(res1) obj2 = OCREvalItem(res2) assert obj1.compare(obj2) == 0
59.384134
11,461
0.604851