hexsha stringlengths 40 40 | size int64 4 996k | ext stringclasses 8
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 4 996k | avg_line_length float64 1.33 58.2k | max_line_length int64 2 323k | alphanum_fraction float64 0 0.97 | content_no_comment stringlengths 0 946k | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7f6a9c5bd9533b4b4280d4516c823495f0b1ee3 | 17,283 | py | Python | neutron/tests/fullstack/test_l3_agent.py | knodir/neutron | ac4e28478ac8a8a0c9f5c5785f6a6bcf532c66b8 | [
"Apache-2.0"
] | null | null | null | neutron/tests/fullstack/test_l3_agent.py | knodir/neutron | ac4e28478ac8a8a0c9f5c5785f6a6bcf532c66b8 | [
"Apache-2.0"
] | 5 | 2019-08-14T06:46:03.000Z | 2021-12-13T20:01:25.000Z | neutron/tests/fullstack/test_l3_agent.py | knodir/neutron | ac4e28478ac8a8a0c9f5c5785f6a6bcf532c66b8 | [
"Apache-2.0"
] | 2 | 2020-03-15T01:24:15.000Z | 2020-07-22T20:34:26.000Z | # Copyright 2015 Red Hat, 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.
import functools
import os
import time
import netaddr
from neutron_lib import constants
from oslo_utils import uuidutils
from neutron.agent.l3 import ha_router
from neutron.agent.l3 import namespaces
from neutron.agent.linux import ip_lib
from neutron.common import utils as common_utils
from neutron.tests.common.exclusive_resources import ip_network
from neutron.tests.fullstack import base
from neutron.tests.fullstack.resources import environment
from neutron.tests.fullstack.resources import machine
from neutron.tests.unit import testlib_api
load_tests = testlib_api.module_load_tests
class TestL3Agent(base.BaseFullStackTestCase):
def _create_external_network_and_subnet(self, tenant_id):
network = self.safe_client.create_network(
tenant_id, name='public', external=True)
cidr = self.useFixture(
ip_network.ExclusiveIPNetwork(
"240.0.0.0", "240.255.255.255", "24")).network
subnet = self.safe_client.create_subnet(tenant_id, network['id'], cidr)
return network, subnet
def block_until_port_status_active(self, port_id):
def is_port_status_active():
port = self.client.show_port(port_id)
return port['port']['status'] == 'ACTIVE'
common_utils.wait_until_true(lambda: is_port_status_active(), sleep=1)
def _create_and_attach_subnet(
self, tenant_id, subnet_cidr, network_id, router_id):
subnet = self.safe_client.create_subnet(
tenant_id, network_id, subnet_cidr)
router_interface_info = self.safe_client.add_router_interface(
router_id, subnet['id'])
self.block_until_port_status_active(
router_interface_info['port_id'])
def _boot_fake_vm_in_network(self, host, tenant_id, network_id, wait=True):
vm = self.useFixture(
machine.FakeFullstackMachine(
host, network_id, tenant_id, self.safe_client, use_dhcp=True))
if wait:
vm.block_until_boot()
return vm
def _create_net_subnet_and_vm(self, tenant_id, subnet_cidrs, host, router):
network = self.safe_client.create_network(tenant_id)
for cidr in subnet_cidrs:
self._create_and_attach_subnet(
tenant_id, cidr, network['id'], router['id'])
return self._boot_fake_vm_in_network(host, tenant_id, network['id'])
def _test_gateway_ip_changed(self):
tenant_id = uuidutils.generate_uuid()
ext_net, ext_sub = self._create_external_network_and_subnet(tenant_id)
external_vm = self._create_external_vm(ext_net, ext_sub)
router = self.safe_client.create_router(tenant_id,
external_network=ext_net['id'])
vm = self._create_net_subnet_and_vm(
tenant_id, ['20.0.0.0/24', '2001:db8:aaaa::/64'],
self.environment.hosts[1], router)
# ping external vm to test snat
vm.block_until_ping(external_vm.ip)
fip = self.safe_client.create_floatingip(
tenant_id, ext_net['id'], vm.ip, vm.neutron_port['id'])
# ping floating ip from external vm
external_vm.block_until_ping(fip['floating_ip_address'])
# ping router gateway IP
old_gw_ip = router['external_gateway_info'][
'external_fixed_ips'][0]['ip_address']
external_vm.block_until_ping(old_gw_ip)
gateway_port = self.safe_client.list_ports(
device_id=router['id'],
device_owner=constants.DEVICE_OWNER_ROUTER_GW)[0]
ip_1, ip_2 = self._find_available_ips(ext_net, ext_sub, 2)
self.safe_client.update_port(gateway_port['id'], fixed_ips=[
{'ip_address': ip_1},
{'ip_address': ip_2}])
# ping router gateway new IPs
external_vm.block_until_ping(ip_1)
external_vm.block_until_ping(ip_2)
# ping router old gateway IP, should fail now
external_vm.block_until_no_ping(old_gw_ip)
class TestLegacyL3Agent(TestL3Agent):
def setUp(self):
host_descriptions = [
environment.HostDescription(l3_agent=True, dhcp_agent=True),
environment.HostDescription()]
env = environment.Environment(
environment.EnvironmentDescription(
network_type='vlan', l2_pop=False),
host_descriptions)
super(TestLegacyL3Agent, self).setUp(env)
def _get_namespace(self, router_id):
return namespaces.build_ns_name(namespaces.NS_PREFIX, router_id)
def _assert_namespace_exists(self, ns_name):
common_utils.wait_until_true(
lambda: ip_lib.network_namespace_exists(ns_name))
def test_namespace_exists(self):
tenant_id = uuidutils.generate_uuid()
router = self.safe_client.create_router(tenant_id)
network = self.safe_client.create_network(tenant_id)
subnet = self.safe_client.create_subnet(
tenant_id, network['id'], '20.0.0.0/24', gateway_ip='20.0.0.1')
self.safe_client.add_router_interface(router['id'], subnet['id'])
namespace = "%s@%s" % (
self._get_namespace(router['id']),
self.environment.hosts[0].l3_agent.get_namespace_suffix(), )
self._assert_namespace_exists(namespace)
def test_mtu_update(self):
tenant_id = uuidutils.generate_uuid()
router = self.safe_client.create_router(tenant_id)
network = self.safe_client.create_network(tenant_id)
subnet = self.safe_client.create_subnet(
tenant_id, network['id'], '20.0.0.0/24', gateway_ip='20.0.0.1')
self.safe_client.add_router_interface(router['id'], subnet['id'])
namespace = "%s@%s" % (
self._get_namespace(router['id']),
self.environment.hosts[0].l3_agent.get_namespace_suffix(), )
self._assert_namespace_exists(namespace)
ip = ip_lib.IPWrapper(namespace)
common_utils.wait_until_true(lambda: ip.get_devices())
devices = ip.get_devices()
self.assertEqual(1, len(devices))
ri_dev = devices[0]
mtu = ri_dev.link.mtu
self.assertEqual(1500, mtu)
mtu -= 1
network = self.safe_client.update_network(network['id'], mtu=mtu)
common_utils.wait_until_true(lambda: ri_dev.link.mtu == mtu)
def test_east_west_traffic(self):
tenant_id = uuidutils.generate_uuid()
router = self.safe_client.create_router(tenant_id)
vm1 = self._create_net_subnet_and_vm(
tenant_id, ['20.0.0.0/24', '2001:db8:aaaa::/64'],
self.environment.hosts[0], router)
vm2 = self._create_net_subnet_and_vm(
tenant_id, ['21.0.0.0/24', '2001:db8:bbbb::/64'],
self.environment.hosts[1], router)
vm1.block_until_ping(vm2.ip)
# Verify ping6 from vm2 to vm1 IPv6 Address
vm2.block_until_ping(vm1.ipv6)
def test_north_south_traffic(self):
# This function creates an external network which is connected to
# central_bridge and spawns an external_vm on it.
# The external_vm is configured with the gateway_ip (both v4 & v6
# addresses) of external subnet. Later, it creates a tenant router,
# a tenant network and two tenant subnets (v4 and v6). The tenant
# router is associated with tenant network and external network to
# provide north-south connectivity to the VMs.
# We validate the following in this testcase.
# 1. SNAT support: using ping from tenant VM to external_vm
# 2. Floating IP support: using ping from external_vm to VM floating ip
# 3. IPv6 ext connectivity: using ping6 from tenant vm to external_vm.
tenant_id = uuidutils.generate_uuid()
ext_net, ext_sub = self._create_external_network_and_subnet(tenant_id)
external_vm = self._create_external_vm(ext_net, ext_sub)
# Create an IPv6 subnet in the external network
v6network = self.useFixture(
ip_network.ExclusiveIPNetwork(
"2001:db8:1234::1", "2001:db8:1234::10", "64")).network
ext_v6sub = self.safe_client.create_subnet(
tenant_id, ext_net['id'], v6network)
router = self.safe_client.create_router(tenant_id,
external_network=ext_net['id'])
# Configure the gateway_ip of external v6subnet on the external_vm.
external_vm.ipv6_cidr = common_utils.ip_to_cidr(
ext_v6sub['gateway_ip'], 64)
# Configure an IPv6 downstream route to the v6Address of router gw port
for fixed_ip in router['external_gateway_info']['external_fixed_ips']:
if netaddr.IPNetwork(fixed_ip['ip_address']).version == 6:
external_vm.set_default_gateway(fixed_ip['ip_address'])
vm = self._create_net_subnet_and_vm(
tenant_id, ['20.0.0.0/24', '2001:db8:aaaa::/64'],
self.environment.hosts[1], router)
# ping external vm to test snat
vm.block_until_ping(external_vm.ip)
fip = self.safe_client.create_floatingip(
tenant_id, ext_net['id'], vm.ip, vm.neutron_port['id'])
# ping floating ip from external vm
external_vm.block_until_ping(fip['floating_ip_address'])
# Verify VM is able to reach the router interface.
vm.block_until_ping(vm.gateway_ipv6)
# Verify north-south connectivity using ping6 to external_vm.
vm.block_until_ping(external_vm.ipv6)
# Now let's remove and create again phys bridge and check connectivity
# once again
br_phys = self.environment.hosts[0].br_phys
br_phys.destroy()
br_phys.create()
self.environment.hosts[0].connect_to_central_network_via_vlans(
br_phys)
# ping floating ip from external vm
external_vm.block_until_ping(fip['floating_ip_address'])
# Verify VM is able to reach the router interface.
vm.block_until_ping(vm.gateway_ipv6)
# Verify north-south connectivity using ping6 to external_vm.
vm.block_until_ping(external_vm.ipv6)
def test_gateway_ip_changed(self):
self._test_gateway_ip_changed()
class TestHAL3Agent(TestL3Agent):
def setUp(self):
host_descriptions = [
environment.HostDescription(l3_agent=True, dhcp_agent=True)
for _ in range(2)]
env = environment.Environment(
environment.EnvironmentDescription(
network_type='vlan', l2_pop=True),
host_descriptions)
super(TestHAL3Agent, self).setUp(env)
def _is_ha_router_active_on_one_agent(self, router_id):
agents = self.client.list_l3_agent_hosting_routers(router_id)
return (
agents['agents'][0]['ha_state'] != agents['agents'][1]['ha_state'])
def test_ha_router(self):
# TODO(amuller): Test external connectivity before and after a
# failover, see: https://review.openstack.org/#/c/196393/
tenant_id = uuidutils.generate_uuid()
router = self.safe_client.create_router(tenant_id, ha=True)
common_utils.wait_until_true(
lambda:
len(self.client.list_l3_agent_hosting_routers(
router['id'])['agents']) == 2,
timeout=90)
common_utils.wait_until_true(
functools.partial(
self._is_ha_router_active_on_one_agent,
router['id']),
timeout=90)
def _get_keepalived_state(self, keepalived_state_file):
with open(keepalived_state_file, "r") as fd:
return fd.read()
def _get_state_file_for_master_agent(self, router_id):
for host in self.environment.hosts:
keepalived_state_file = os.path.join(
host.neutron_config.state_path, "ha_confs", router_id, "state")
if self._get_keepalived_state(keepalived_state_file) == "master":
return keepalived_state_file
def _get_l3_agents_with_ha_state(self, l3_agents, router_id, ha_state):
found_agents = []
agents_hosting_router = self.client.list_l3_agent_hosting_routers(
router_id)['agents']
for agent in l3_agents:
agent_host = agent.neutron_cfg_fixture.get_host()
for agent_hosting_router in agents_hosting_router:
if (agent_hosting_router['host'] == agent_host and
agent_hosting_router['ha_state'] == ha_state):
found_agents.append(agent)
break
return found_agents
def test_keepalived_multiple_sighups_does_not_forfeit_mastership(self):
"""Setup a complete "Neutron stack" - both an internal and an external
network+subnet, and a router connected to both.
"""
tenant_id = uuidutils.generate_uuid()
ext_net, ext_sub = self._create_external_network_and_subnet(tenant_id)
router = self.safe_client.create_router(tenant_id, ha=True,
external_network=ext_net['id'])
common_utils.wait_until_true(
lambda:
len(self.client.list_l3_agent_hosting_routers(
router['id'])['agents']) == 2,
timeout=90)
common_utils.wait_until_true(
functools.partial(
self._is_ha_router_active_on_one_agent,
router['id']),
timeout=90)
keepalived_state_file = self._get_state_file_for_master_agent(
router['id'])
self.assertIsNotNone(keepalived_state_file)
network = self.safe_client.create_network(tenant_id)
self._create_and_attach_subnet(
tenant_id, '13.37.0.0/24', network['id'], router['id'])
# Create 10 fake VMs, each with a floating ip. Each floating ip
# association should send a SIGHUP to the keepalived's parent process,
# unless the Throttler works.
host = self.environment.hosts[0]
vms = [self._boot_fake_vm_in_network(host, tenant_id, network['id'],
wait=False)
for i in range(10)]
for vm in vms:
self.safe_client.create_floatingip(
tenant_id, ext_net['id'], vm.ip, vm.neutron_port['id'])
# Check that the keepalived's state file has not changed and is still
# master. This will indicate that the Throttler works. We want to check
# for ha_vrrp_advert_int (the default is 2 seconds), plus a bit more.
time_to_stop = (time.time() +
(common_utils.DEFAULT_THROTTLER_VALUE *
ha_router.THROTTLER_MULTIPLIER * 1.3))
while True:
if time.time() > time_to_stop:
break
self.assertEqual(
"master",
self._get_keepalived_state(keepalived_state_file))
def test_ha_router_restart_agents_no_packet_lost(self):
tenant_id = uuidutils.generate_uuid()
ext_net, ext_sub = self._create_external_network_and_subnet(tenant_id)
router = self.safe_client.create_router(tenant_id, ha=True,
external_network=ext_net['id'])
external_vm = self._create_external_vm(ext_net, ext_sub)
common_utils.wait_until_true(
lambda:
len(self.client.list_l3_agent_hosting_routers(
router['id'])['agents']) == 2,
timeout=90)
common_utils.wait_until_true(
functools.partial(
self._is_ha_router_active_on_one_agent,
router['id']),
timeout=90)
router_ip = router['external_gateway_info'][
'external_fixed_ips'][0]['ip_address']
# Let's check first if connectivity from external_vm to router's
# external gateway IP is possible before we restart agents
external_vm.block_until_ping(router_ip)
l3_agents = [host.agents['l3'] for host in self.environment.hosts]
l3_standby_agents = self._get_l3_agents_with_ha_state(
l3_agents, router['id'], 'standby')
l3_active_agents = self._get_l3_agents_with_ha_state(
l3_agents, router['id'], 'active')
self._assert_ping_during_agents_restart(
l3_standby_agents, external_vm.namespace, [router_ip], count=60)
self._assert_ping_during_agents_restart(
l3_active_agents, external_vm.namespace, [router_ip], count=60)
def test_gateway_ip_changed(self):
self._test_gateway_ip_changed()
| 41.545673 | 79 | 0.652259 |
import functools
import os
import time
import netaddr
from neutron_lib import constants
from oslo_utils import uuidutils
from neutron.agent.l3 import ha_router
from neutron.agent.l3 import namespaces
from neutron.agent.linux import ip_lib
from neutron.common import utils as common_utils
from neutron.tests.common.exclusive_resources import ip_network
from neutron.tests.fullstack import base
from neutron.tests.fullstack.resources import environment
from neutron.tests.fullstack.resources import machine
from neutron.tests.unit import testlib_api
load_tests = testlib_api.module_load_tests
class TestL3Agent(base.BaseFullStackTestCase):
def _create_external_network_and_subnet(self, tenant_id):
network = self.safe_client.create_network(
tenant_id, name='public', external=True)
cidr = self.useFixture(
ip_network.ExclusiveIPNetwork(
"240.0.0.0", "240.255.255.255", "24")).network
subnet = self.safe_client.create_subnet(tenant_id, network['id'], cidr)
return network, subnet
def block_until_port_status_active(self, port_id):
def is_port_status_active():
port = self.client.show_port(port_id)
return port['port']['status'] == 'ACTIVE'
common_utils.wait_until_true(lambda: is_port_status_active(), sleep=1)
def _create_and_attach_subnet(
self, tenant_id, subnet_cidr, network_id, router_id):
subnet = self.safe_client.create_subnet(
tenant_id, network_id, subnet_cidr)
router_interface_info = self.safe_client.add_router_interface(
router_id, subnet['id'])
self.block_until_port_status_active(
router_interface_info['port_id'])
def _boot_fake_vm_in_network(self, host, tenant_id, network_id, wait=True):
vm = self.useFixture(
machine.FakeFullstackMachine(
host, network_id, tenant_id, self.safe_client, use_dhcp=True))
if wait:
vm.block_until_boot()
return vm
def _create_net_subnet_and_vm(self, tenant_id, subnet_cidrs, host, router):
network = self.safe_client.create_network(tenant_id)
for cidr in subnet_cidrs:
self._create_and_attach_subnet(
tenant_id, cidr, network['id'], router['id'])
return self._boot_fake_vm_in_network(host, tenant_id, network['id'])
def _test_gateway_ip_changed(self):
tenant_id = uuidutils.generate_uuid()
ext_net, ext_sub = self._create_external_network_and_subnet(tenant_id)
external_vm = self._create_external_vm(ext_net, ext_sub)
router = self.safe_client.create_router(tenant_id,
external_network=ext_net['id'])
vm = self._create_net_subnet_and_vm(
tenant_id, ['20.0.0.0/24', '2001:db8:aaaa::/64'],
self.environment.hosts[1], router)
vm.block_until_ping(external_vm.ip)
fip = self.safe_client.create_floatingip(
tenant_id, ext_net['id'], vm.ip, vm.neutron_port['id'])
external_vm.block_until_ping(fip['floating_ip_address'])
old_gw_ip = router['external_gateway_info'][
'external_fixed_ips'][0]['ip_address']
external_vm.block_until_ping(old_gw_ip)
gateway_port = self.safe_client.list_ports(
device_id=router['id'],
device_owner=constants.DEVICE_OWNER_ROUTER_GW)[0]
ip_1, ip_2 = self._find_available_ips(ext_net, ext_sub, 2)
self.safe_client.update_port(gateway_port['id'], fixed_ips=[
{'ip_address': ip_1},
{'ip_address': ip_2}])
external_vm.block_until_ping(ip_1)
external_vm.block_until_ping(ip_2)
external_vm.block_until_no_ping(old_gw_ip)
class TestLegacyL3Agent(TestL3Agent):
def setUp(self):
host_descriptions = [
environment.HostDescription(l3_agent=True, dhcp_agent=True),
environment.HostDescription()]
env = environment.Environment(
environment.EnvironmentDescription(
network_type='vlan', l2_pop=False),
host_descriptions)
super(TestLegacyL3Agent, self).setUp(env)
def _get_namespace(self, router_id):
return namespaces.build_ns_name(namespaces.NS_PREFIX, router_id)
def _assert_namespace_exists(self, ns_name):
common_utils.wait_until_true(
lambda: ip_lib.network_namespace_exists(ns_name))
def test_namespace_exists(self):
tenant_id = uuidutils.generate_uuid()
router = self.safe_client.create_router(tenant_id)
network = self.safe_client.create_network(tenant_id)
subnet = self.safe_client.create_subnet(
tenant_id, network['id'], '20.0.0.0/24', gateway_ip='20.0.0.1')
self.safe_client.add_router_interface(router['id'], subnet['id'])
namespace = "%s@%s" % (
self._get_namespace(router['id']),
self.environment.hosts[0].l3_agent.get_namespace_suffix(), )
self._assert_namespace_exists(namespace)
def test_mtu_update(self):
tenant_id = uuidutils.generate_uuid()
router = self.safe_client.create_router(tenant_id)
network = self.safe_client.create_network(tenant_id)
subnet = self.safe_client.create_subnet(
tenant_id, network['id'], '20.0.0.0/24', gateway_ip='20.0.0.1')
self.safe_client.add_router_interface(router['id'], subnet['id'])
namespace = "%s@%s" % (
self._get_namespace(router['id']),
self.environment.hosts[0].l3_agent.get_namespace_suffix(), )
self._assert_namespace_exists(namespace)
ip = ip_lib.IPWrapper(namespace)
common_utils.wait_until_true(lambda: ip.get_devices())
devices = ip.get_devices()
self.assertEqual(1, len(devices))
ri_dev = devices[0]
mtu = ri_dev.link.mtu
self.assertEqual(1500, mtu)
mtu -= 1
network = self.safe_client.update_network(network['id'], mtu=mtu)
common_utils.wait_until_true(lambda: ri_dev.link.mtu == mtu)
def test_east_west_traffic(self):
tenant_id = uuidutils.generate_uuid()
router = self.safe_client.create_router(tenant_id)
vm1 = self._create_net_subnet_and_vm(
tenant_id, ['20.0.0.0/24', '2001:db8:aaaa::/64'],
self.environment.hosts[0], router)
vm2 = self._create_net_subnet_and_vm(
tenant_id, ['21.0.0.0/24', '2001:db8:bbbb::/64'],
self.environment.hosts[1], router)
vm1.block_until_ping(vm2.ip)
vm2.block_until_ping(vm1.ipv6)
def test_north_south_traffic(self):
tenant_id = uuidutils.generate_uuid()
ext_net, ext_sub = self._create_external_network_and_subnet(tenant_id)
external_vm = self._create_external_vm(ext_net, ext_sub)
v6network = self.useFixture(
ip_network.ExclusiveIPNetwork(
"2001:db8:1234::1", "2001:db8:1234::10", "64")).network
ext_v6sub = self.safe_client.create_subnet(
tenant_id, ext_net['id'], v6network)
router = self.safe_client.create_router(tenant_id,
external_network=ext_net['id'])
external_vm.ipv6_cidr = common_utils.ip_to_cidr(
ext_v6sub['gateway_ip'], 64)
for fixed_ip in router['external_gateway_info']['external_fixed_ips']:
if netaddr.IPNetwork(fixed_ip['ip_address']).version == 6:
external_vm.set_default_gateway(fixed_ip['ip_address'])
vm = self._create_net_subnet_and_vm(
tenant_id, ['20.0.0.0/24', '2001:db8:aaaa::/64'],
self.environment.hosts[1], router)
vm.block_until_ping(external_vm.ip)
fip = self.safe_client.create_floatingip(
tenant_id, ext_net['id'], vm.ip, vm.neutron_port['id'])
external_vm.block_until_ping(fip['floating_ip_address'])
vm.block_until_ping(vm.gateway_ipv6)
vm.block_until_ping(external_vm.ipv6)
# once again
br_phys = self.environment.hosts[0].br_phys
br_phys.destroy()
br_phys.create()
self.environment.hosts[0].connect_to_central_network_via_vlans(
br_phys)
# ping floating ip from external vm
external_vm.block_until_ping(fip['floating_ip_address'])
# Verify VM is able to reach the router interface.
vm.block_until_ping(vm.gateway_ipv6)
# Verify north-south connectivity using ping6 to external_vm.
vm.block_until_ping(external_vm.ipv6)
def test_gateway_ip_changed(self):
self._test_gateway_ip_changed()
class TestHAL3Agent(TestL3Agent):
def setUp(self):
host_descriptions = [
environment.HostDescription(l3_agent=True, dhcp_agent=True)
for _ in range(2)]
env = environment.Environment(
environment.EnvironmentDescription(
network_type='vlan', l2_pop=True),
host_descriptions)
super(TestHAL3Agent, self).setUp(env)
def _is_ha_router_active_on_one_agent(self, router_id):
agents = self.client.list_l3_agent_hosting_routers(router_id)
return (
agents['agents'][0]['ha_state'] != agents['agents'][1]['ha_state'])
def test_ha_router(self):
# TODO(amuller): Test external connectivity before and after a
# failover, see: https://review.openstack.org/#/c/196393/
tenant_id = uuidutils.generate_uuid()
router = self.safe_client.create_router(tenant_id, ha=True)
common_utils.wait_until_true(
lambda:
len(self.client.list_l3_agent_hosting_routers(
router['id'])['agents']) == 2,
timeout=90)
common_utils.wait_until_true(
functools.partial(
self._is_ha_router_active_on_one_agent,
router['id']),
timeout=90)
def _get_keepalived_state(self, keepalived_state_file):
with open(keepalived_state_file, "r") as fd:
return fd.read()
def _get_state_file_for_master_agent(self, router_id):
for host in self.environment.hosts:
keepalived_state_file = os.path.join(
host.neutron_config.state_path, "ha_confs", router_id, "state")
if self._get_keepalived_state(keepalived_state_file) == "master":
return keepalived_state_file
def _get_l3_agents_with_ha_state(self, l3_agents, router_id, ha_state):
found_agents = []
agents_hosting_router = self.client.list_l3_agent_hosting_routers(
router_id)['agents']
for agent in l3_agents:
agent_host = agent.neutron_cfg_fixture.get_host()
for agent_hosting_router in agents_hosting_router:
if (agent_hosting_router['host'] == agent_host and
agent_hosting_router['ha_state'] == ha_state):
found_agents.append(agent)
break
return found_agents
def test_keepalived_multiple_sighups_does_not_forfeit_mastership(self):
tenant_id = uuidutils.generate_uuid()
ext_net, ext_sub = self._create_external_network_and_subnet(tenant_id)
router = self.safe_client.create_router(tenant_id, ha=True,
external_network=ext_net['id'])
common_utils.wait_until_true(
lambda:
len(self.client.list_l3_agent_hosting_routers(
router['id'])['agents']) == 2,
timeout=90)
common_utils.wait_until_true(
functools.partial(
self._is_ha_router_active_on_one_agent,
router['id']),
timeout=90)
keepalived_state_file = self._get_state_file_for_master_agent(
router['id'])
self.assertIsNotNone(keepalived_state_file)
network = self.safe_client.create_network(tenant_id)
self._create_and_attach_subnet(
tenant_id, '13.37.0.0/24', network['id'], router['id'])
# Create 10 fake VMs, each with a floating ip. Each floating ip
# association should send a SIGHUP to the keepalived's parent process,
host = self.environment.hosts[0]
vms = [self._boot_fake_vm_in_network(host, tenant_id, network['id'],
wait=False)
for i in range(10)]
for vm in vms:
self.safe_client.create_floatingip(
tenant_id, ext_net['id'], vm.ip, vm.neutron_port['id'])
# master. This will indicate that the Throttler works. We want to check
# for ha_vrrp_advert_int (the default is 2 seconds), plus a bit more.
time_to_stop = (time.time() +
(common_utils.DEFAULT_THROTTLER_VALUE *
ha_router.THROTTLER_MULTIPLIER * 1.3))
while True:
if time.time() > time_to_stop:
break
self.assertEqual(
"master",
self._get_keepalived_state(keepalived_state_file))
def test_ha_router_restart_agents_no_packet_lost(self):
tenant_id = uuidutils.generate_uuid()
ext_net, ext_sub = self._create_external_network_and_subnet(tenant_id)
router = self.safe_client.create_router(tenant_id, ha=True,
external_network=ext_net['id'])
external_vm = self._create_external_vm(ext_net, ext_sub)
common_utils.wait_until_true(
lambda:
len(self.client.list_l3_agent_hosting_routers(
router['id'])['agents']) == 2,
timeout=90)
common_utils.wait_until_true(
functools.partial(
self._is_ha_router_active_on_one_agent,
router['id']),
timeout=90)
router_ip = router['external_gateway_info'][
'external_fixed_ips'][0]['ip_address']
# Let's check first if connectivity from external_vm to router's
# external gateway IP is possible before we restart agents
external_vm.block_until_ping(router_ip)
l3_agents = [host.agents['l3'] for host in self.environment.hosts]
l3_standby_agents = self._get_l3_agents_with_ha_state(
l3_agents, router['id'], 'standby')
l3_active_agents = self._get_l3_agents_with_ha_state(
l3_agents, router['id'], 'active')
self._assert_ping_during_agents_restart(
l3_standby_agents, external_vm.namespace, [router_ip], count=60)
self._assert_ping_during_agents_restart(
l3_active_agents, external_vm.namespace, [router_ip], count=60)
def test_gateway_ip_changed(self):
self._test_gateway_ip_changed()
| true | true |
f7f6a9e3917944234292a4fcb928c3120028b8b7 | 1,631 | py | Python | mistral/actions/generator_factory.py | soda-research/mistral | 550a3de9c2defc7ce26336cb705d9c8d87bbaddd | [
"Apache-2.0"
] | null | null | null | mistral/actions/generator_factory.py | soda-research/mistral | 550a3de9c2defc7ce26336cb705d9c8d87bbaddd | [
"Apache-2.0"
] | 5 | 2019-08-14T06:46:03.000Z | 2021-12-13T20:01:25.000Z | mistral/actions/generator_factory.py | soda-research/mistral | 550a3de9c2defc7ce26336cb705d9c8d87bbaddd | [
"Apache-2.0"
] | 2 | 2020-03-15T01:24:15.000Z | 2020-07-22T20:34:26.000Z | # Copyright 2014 - Mirantis, 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.
from oslo_utils import importutils
from mistral.actions.openstack.action_generator import base
SUPPORTED_MODULES = [
'Nova', 'Glance', 'Keystone', 'Heat', 'Neutron', 'Cinder',
'Trove', 'Ironic', 'Baremetal Introspection', 'Swift', 'SwiftService',
'Zaqar', 'Barbican', 'Mistral', 'Designate', 'Magnum', 'Murano', 'Tacker',
'Aodh', 'Gnocchi', 'Glare', 'Vitrage', 'Senlin', 'Zun', 'Qinling', 'Manila'
]
def all_generators():
for mod_name in SUPPORTED_MODULES:
prefix = mod_name.replace(' ', '')
mod_namespace = mod_name.lower().replace(' ', '_')
mod_cls_name = 'mistral.actions.openstack.actions.%sAction' % prefix
mod_action_cls = importutils.import_class(mod_cls_name)
generator_cls_name = '%sActionGenerator' % prefix
yield type(
generator_cls_name,
(base.OpenStackActionGenerator,),
{
'action_namespace': mod_namespace,
'base_action_class': mod_action_cls
}
)
| 37.068182 | 79 | 0.661557 |
from oslo_utils import importutils
from mistral.actions.openstack.action_generator import base
SUPPORTED_MODULES = [
'Nova', 'Glance', 'Keystone', 'Heat', 'Neutron', 'Cinder',
'Trove', 'Ironic', 'Baremetal Introspection', 'Swift', 'SwiftService',
'Zaqar', 'Barbican', 'Mistral', 'Designate', 'Magnum', 'Murano', 'Tacker',
'Aodh', 'Gnocchi', 'Glare', 'Vitrage', 'Senlin', 'Zun', 'Qinling', 'Manila'
]
def all_generators():
for mod_name in SUPPORTED_MODULES:
prefix = mod_name.replace(' ', '')
mod_namespace = mod_name.lower().replace(' ', '_')
mod_cls_name = 'mistral.actions.openstack.actions.%sAction' % prefix
mod_action_cls = importutils.import_class(mod_cls_name)
generator_cls_name = '%sActionGenerator' % prefix
yield type(
generator_cls_name,
(base.OpenStackActionGenerator,),
{
'action_namespace': mod_namespace,
'base_action_class': mod_action_cls
}
)
| true | true |
f7f6aa204c34e2de8f37ef87b7845cea3d0004ac | 8,467 | py | Python | usim/py/resources/base.py | AndreiBarsan/usim | c0ebaeef3c10bc7d50f983133ad346aeb9c3a6a1 | [
"MIT"
] | 10 | 2019-04-26T14:58:54.000Z | 2022-02-02T10:21:37.000Z | usim/py/resources/base.py | AndreiBarsan/usim | c0ebaeef3c10bc7d50f983133ad346aeb9c3a6a1 | [
"MIT"
] | 97 | 2019-04-04T15:22:12.000Z | 2022-02-28T11:23:22.000Z | usim/py/resources/base.py | AndreiBarsan/usim | c0ebaeef3c10bc7d50f983133ad346aeb9c3a6a1 | [
"MIT"
] | 3 | 2020-07-25T11:30:40.000Z | 2021-05-14T17:36:44.000Z | from typing import Sequence, ClassVar, Type, TypeVar, Generic
from itertools import takewhile
from ..core import Environment
from ..events import Event
__all__ = ['Put', 'Get', 'BaseResource']
# Implementation Note
# We take some liberty in interpreting SimPy's API. Several parts
# are loosely specified - e.g. BaseResource.GetQueue has to satisfy
# different specs for ``BaseResource`` and ``Request``. We take the
# most general if it means the code gets cleaner.
T = TypeVar('T')
class BaseRequest(Event[T]):
r"""
Base class for :py:class:`~.Put` and :py:class:`~.Get` events
A request is commonly created via
:py:meth:`~.BaseResource.put` or :py:meth:`~.BaseResource.get` and must
be ``yield``\ ed by a Process to wait until the request has been served.
If a request has not been served but is no longer desired, the process should
:py:class:`~.cancel` the request.
A request can be used as a context manager to automatically cancel it
at the end of the context. Note that the request is not automatically
waited on -- this must be done explicitly if desired.
.. code:: python3
with resource.get() as request:
yield request
"""
def __init__(self, resource: 'BaseResource'):
super().__init__(resource._env)
self.resource = resource
#: the process that requested the action
self.proc = self.env.active_process
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.cancel()
def cancel(self):
"""
Cancel the request
Requests should be cancelled when they have not been triggered but
are no longer needed. This may happen when a process is interrupted
while waiting for a request.
Cancelling is idempotent: If the request has already been triggered or canceled,
:py:meth:`~.cancel` can still be called without error.
"""
raise NotImplementedError
class Put(BaseRequest[T]):
"""Request to put content into a resource"""
def __init__(self, resource: 'BaseResource'):
super().__init__(resource)
# Enqueue the event to be processed...
resource.put_queue.append(self)
# ...schedule our inverse when we trigger (put item -> get item)...
self.callbacks.append(resource._trigger_get)
# ...and immediately check whether we could trigger
resource._trigger_put(None)
def cancel(self):
if not self.triggered:
self.resource.put_queue.remove(self)
class Get(BaseRequest[T]):
"""Request to get content out of a resource"""
def __init__(self, resource: 'BaseResource'):
super().__init__(resource)
# Enqueue the event to be processed...
resource.get_queue.append(self)
# ...schedule our inverse when we trigger (put item -> get item)...
self.callbacks.append(resource._trigger_put)
# ...and immediately check whether we could trigger
resource._trigger_get(None)
def cancel(self):
if not self.triggered:
self.resource.get_queue.remove(self)
class BaseResource(Generic[T]):
"""
Base class for all synchronised resources of :py:mod:`usim.py`
This type codifies the basic semantics of :py:mod:`usim.py` resources:
processes can :py:meth:`~.put` content into the resource or :py:meth:`~.get`
content out of the resource. Both actions return an
:py:class:`~usim.py.events.Event`; once the event triggers, the process did
successfully get or put content into or out of the resource.
Processes should ``yield`` this even to wait for success of their request.
.. code:: python3
def foo(env, resources: BaseResource):
print('Getting a resource at', env.time)
yield resources.get()
print('Got resource at', env.time)
yield env.timeout(2)
print('Returning a resource at', env.time)
yield resources.put()
print('Returned a resource at', env.time)
Subclasses should define their behaviour by implementing at least one of:
:py:attr:`~.BaseResource.PutQueue` or :py:attr:`~.BaseResource.GetQueue`
The types used to create the :py:attr:`~.put_queue` and :py:attr:`~.get_queue`.
These may, for example, customize priority of queued requests.
:py:meth:`~.put` or :py:meth:`~.get`
The methods used to create :py:class:`~.Put` and :py:class:`~.Get` events.
These may, for example, customize how much of a resource to handle at once.
:py:meth:`~._do_put` or :py:meth:`~._do_get`
The methods used to process :py:class:`~.Put` and :py:class:`~.Get` events.
These are an alternative to customizing :py:meth:`~.put` or :py:meth:`~.get`.
.. note::
This is *not* an Abstract Base Class.
Subclasses do not need to implement
:py:meth:`~.BaseResource._do_get` or :py:meth:`~.BaseResource._do_put`.
.. hint::
**Migrating to μSim**
There is no common base type for resources in μSim -- instead there
are several different types of resources made for various use-cases.
If you need to create a custom resource, you are free to choose
whatever interface is appropriate for your use-case.
μSim itself usually uses the ``await``, ``async for`` and ``async with``
depending on the intended use of a resource.
Commonly this means
``await resource`` to get content from a resource,
``await resource.put(...)`` to add content to a resource,
``async for item in resource:`` to subscribe to a resource,
and
``async with resource:`` to temporarily use a resource.
"""
#: The type used to create :py:attr:`~.put_queue`
PutQueue: ClassVar[Type[Sequence]] = list
#: The type used to create :py:attr:`~.get_queue`
GetQueue: ClassVar[Type[Sequence]] = list
def __init__(self, env: Environment, capacity):
self._env = env
self._capacity = capacity
#: pending put events
self.put_queue = self.PutQueue()
#: pending get events
self.get_queue = self.GetQueue()
@property
def capacity(self):
"""Maximum capacity of the resource"""
return self._capacity
def put(self) -> Put[T]:
"""Create a request to put content into the resource"""
return Put(self)
def get(self) -> Get[T]:
"""Create a request to get content out of the resource"""
return Get(self)
def _trigger_put(self, get_event: Get):
"""
Trigger all possible put events
Called when a ``Put`` event was created or a ``Get`` event triggered.
This trigger scheme handles a new request to an uncontested resource
(the ``Put`` succeeds immediately),
as well as a full one (the ``Get`` may serve a waiting ``Put``).
:param get_event: ``Get`` event that was triggered or :py:const:`None`
"""
triggered = list(takewhile(self._do_put, self.put_queue))
self.put_queue = self.put_queue[len(triggered):]
def _trigger_get(self, put_event: Put):
"""
Trigger all possible put events
Called when a ``Get`` event was created or a ``Put`` event triggered.
This trigger scheme handles a new request to an uncontested resource
(the ``Get`` succeeds immediately),
as well as a full one (the ``Put`` may serve a waiting ``Get``).
:param put_event: ``Get`` event that was triggered or :py:const:`None`
"""
triggered = list(takewhile(self._do_get, self.get_queue))
self.get_queue = self.get_queue[len(triggered):]
# NOTE: Per the SimPy spec, these are **PUBLIC**
def _do_get(self, get_event: Get) -> bool:
"""
Trigger a :py:class:`~.Get` event if possible
:param get_event: the event that may be triggered
:return: whether another event may be triggered
"""
raise NotImplementedError("'_do_get' must be overridden in subclasses")
def _do_put(self, get_event: Put) -> bool:
"""
Trigger a :py:class:`~.Put` event if possible
:param get_event: the event that may be triggered
:return: whether another event may be triggered
"""
raise NotImplementedError("'_do_put' must be overridden in subclasses")
| 36.973799 | 88 | 0.644266 | from typing import Sequence, ClassVar, Type, TypeVar, Generic
from itertools import takewhile
from ..core import Environment
from ..events import Event
__all__ = ['Put', 'Get', 'BaseResource']
# are loosely specified - e.g. BaseResource.GetQueue has to satisfy
# different specs for ``BaseResource`` and ``Request``. We take the
# most general if it means the code gets cleaner.
T = TypeVar('T')
class BaseRequest(Event[T]):
def __init__(self, resource: 'BaseResource'):
super().__init__(resource._env)
self.resource = resource
#: the process that requested the action
self.proc = self.env.active_process
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.cancel()
def cancel(self):
raise NotImplementedError
class Put(BaseRequest[T]):
def __init__(self, resource: 'BaseResource'):
super().__init__(resource)
# Enqueue the event to be processed...
resource.put_queue.append(self)
# ...schedule our inverse when we trigger (put item -> get item)...
self.callbacks.append(resource._trigger_get)
# ...and immediately check whether we could trigger
resource._trigger_put(None)
def cancel(self):
if not self.triggered:
self.resource.put_queue.remove(self)
class Get(BaseRequest[T]):
def __init__(self, resource: 'BaseResource'):
super().__init__(resource)
# Enqueue the event to be processed...
resource.get_queue.append(self)
# ...schedule our inverse when we trigger (put item -> get item)...
self.callbacks.append(resource._trigger_put)
# ...and immediately check whether we could trigger
resource._trigger_get(None)
def cancel(self):
if not self.triggered:
self.resource.get_queue.remove(self)
class BaseResource(Generic[T]):
#: The type used to create :py:attr:`~.put_queue`
PutQueue: ClassVar[Type[Sequence]] = list
#: The type used to create :py:attr:`~.get_queue`
GetQueue: ClassVar[Type[Sequence]] = list
def __init__(self, env: Environment, capacity):
self._env = env
self._capacity = capacity
#: pending put events
self.put_queue = self.PutQueue()
#: pending get events
self.get_queue = self.GetQueue()
@property
def capacity(self):
return self._capacity
def put(self) -> Put[T]:
return Put(self)
def get(self) -> Get[T]:
return Get(self)
def _trigger_put(self, get_event: Get):
triggered = list(takewhile(self._do_put, self.put_queue))
self.put_queue = self.put_queue[len(triggered):]
def _trigger_get(self, put_event: Put):
triggered = list(takewhile(self._do_get, self.get_queue))
self.get_queue = self.get_queue[len(triggered):]
# NOTE: Per the SimPy spec, these are **PUBLIC**
def _do_get(self, get_event: Get) -> bool:
raise NotImplementedError("'_do_get' must be overridden in subclasses")
def _do_put(self, get_event: Put) -> bool:
raise NotImplementedError("'_do_put' must be overridden in subclasses")
| true | true |
f7f6aab62dcc90e16391be7604ce93ccb372b1ac | 2,051 | py | Python | benchmarks/osb/extensions/util.py | martin-gaievski/k-NN | 77353512c1f15e0dc996428a982941a7ee3036fb | [
"Apache-2.0"
] | 1 | 2021-12-29T02:09:12.000Z | 2021-12-29T02:09:12.000Z | benchmarks/osb/extensions/util.py | martin-gaievski/k-NN | 77353512c1f15e0dc996428a982941a7ee3036fb | [
"Apache-2.0"
] | null | null | null | benchmarks/osb/extensions/util.py | martin-gaievski/k-NN | 77353512c1f15e0dc996428a982941a7ee3036fb | [
"Apache-2.0"
] | null | null | null | # SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import numpy as np
from typing import List
from typing import Dict
from typing import Any
def bulk_transform(partition: np.ndarray, field_name: str, action,
offset: int) -> List[Dict[str, Any]]:
"""Partitions and transforms a list of vectors into OpenSearch's bulk
injection format.
Args:
offset: to start counting from
partition: An array of vectors to transform.
field_name: field name for action
action: Bulk API action.
Returns:
An array of transformed vectors in bulk format.
"""
actions = []
_ = [
actions.extend([action(i + offset), None])
for i in range(len(partition))
]
actions[1::2] = [{field_name: vec} for vec in partition.tolist()]
return actions
def parse_string_parameter(key: str, params: dict, default: str = None) -> str:
if key not in params:
if default is not None:
return default
raise ConfigurationError(
"Value cannot be None for param {}".format(key)
)
if type(params[key]) is str:
return params[key]
raise ConfigurationError("Value must be a string for param {}".format(key))
def parse_int_parameter(key: str, params: dict, default: int = None) -> int:
if key not in params:
if default:
return default
raise ConfigurationError(
"Value cannot be None for param {}".format(key)
)
if type(params[key]) is int:
return params[key]
raise ConfigurationError("Value must be a int for param {}".format(key))
class ConfigurationError(Exception):
"""Exception raised for errors configuration.
Attributes:
message -- explanation of the error
"""
def __init__(self, message: str):
self.message = f'{message}'
super().__init__(self.message)
| 28.486111 | 79 | 0.643588 |
import numpy as np
from typing import List
from typing import Dict
from typing import Any
def bulk_transform(partition: np.ndarray, field_name: str, action,
offset: int) -> List[Dict[str, Any]]:
actions = []
_ = [
actions.extend([action(i + offset), None])
for i in range(len(partition))
]
actions[1::2] = [{field_name: vec} for vec in partition.tolist()]
return actions
def parse_string_parameter(key: str, params: dict, default: str = None) -> str:
if key not in params:
if default is not None:
return default
raise ConfigurationError(
"Value cannot be None for param {}".format(key)
)
if type(params[key]) is str:
return params[key]
raise ConfigurationError("Value must be a string for param {}".format(key))
def parse_int_parameter(key: str, params: dict, default: int = None) -> int:
if key not in params:
if default:
return default
raise ConfigurationError(
"Value cannot be None for param {}".format(key)
)
if type(params[key]) is int:
return params[key]
raise ConfigurationError("Value must be a int for param {}".format(key))
class ConfigurationError(Exception):
def __init__(self, message: str):
self.message = f'{message}'
super().__init__(self.message)
| true | true |
f7f6ab3cf534ed9585a57726fc4caab9d54408da | 596 | py | Python | travelling/migrations/0038_auto_20190223_1748.py | HerbyDE/jagdreisencheck-webapp | 9af5deda2423b787da88a0c893f3c474d8e4f73f | [
"BSD-3-Clause"
] | null | null | null | travelling/migrations/0038_auto_20190223_1748.py | HerbyDE/jagdreisencheck-webapp | 9af5deda2423b787da88a0c893f3c474d8e4f73f | [
"BSD-3-Clause"
] | null | null | null | travelling/migrations/0038_auto_20190223_1748.py | HerbyDE/jagdreisencheck-webapp | 9af5deda2423b787da88a0c893f3c474d8e4f73f | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-02-23 16:48
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('travelling', '0037_auto_20190223_1748'),
]
operations = [
migrations.AlterField(
model_name='ratingreply',
name='rating',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='travelling.Rating', verbose_name='Associated Rating'),
),
]
| 27.090909 | 153 | 0.669463 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('travelling', '0037_auto_20190223_1748'),
]
operations = [
migrations.AlterField(
model_name='ratingreply',
name='rating',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='travelling.Rating', verbose_name='Associated Rating'),
),
]
| true | true |
f7f6ac461b14578ff50a93e859ee54529f66b8e7 | 109 | py | Python | main.py | QuickyDev/QuickyNote | 796e1c20b7fce988d86dc977b4b4f3b16de8e529 | [
"MIT"
] | null | null | null | main.py | QuickyDev/QuickyNote | 796e1c20b7fce988d86dc977b4b4f3b16de8e529 | [
"MIT"
] | 3 | 2021-03-23T10:07:43.000Z | 2021-03-23T20:28:56.000Z | main.py | Yste1000/github-slideshow | c5420242d4da54cc52b74b3c8438c374869b0a4d | [
"MIT"
] | null | null | null | from website import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
| 15.571429 | 31 | 0.669725 | from website import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
| true | true |
f7f6ac552ec4b90993ff3b0a690f648d34eda552 | 1,283 | py | Python | tests/ev3dev/geometry/matrix.py | cschlack/pybricks-micropython | 0abfd2918267a4e6e7a04062976ac1bb3da1f4b1 | [
"MIT"
] | 115 | 2020-06-15T16:43:14.000Z | 2022-03-21T21:11:57.000Z | tests/ev3dev/geometry/matrix.py | cschlack/pybricks-micropython | 0abfd2918267a4e6e7a04062976ac1bb3da1f4b1 | [
"MIT"
] | 83 | 2020-06-17T17:19:29.000Z | 2022-03-08T18:50:35.000Z | tests/ev3dev/geometry/matrix.py | BertLindeman/pybricks-micropython | 8f22a99551100e66ddf08d014d9f442f22b33b4d | [
"MIT"
] | 40 | 2020-06-15T18:36:39.000Z | 2022-03-28T13:22:43.000Z | from pybricks.geometry import Matrix, vector
# Basic matrix algebra
A = Matrix(
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
)
B = -A
C = A - A.T
print("A =", A)
print("B = -A =", B)
print("A.T =", A.T)
print("A + B =", A + B)
print("C = A - A.T =", C)
print("C + C.T =", C + C.T)
print("A * A.T =", A * A.T)
print("A.shape =", A.shape)
print("A * 3 =", A * 3)
print("3 * A =", 3 * A)
# Reading elements
print("B[0, 1] =", B[0, 1])
print("B.T[0, 1] =", B.T[0, 1])
# Vector basics
b = vector(3, 4, 0)
c = b.T
print("b = vector(3, 4, 0) =", b)
print("b.shape =", b.shape)
print("abs(b) =", abs(b))
print("c = b.T", c)
print("A * b =", A * b)
# Dealing with resulting scalar types
print("b.T * b =", b.T * b)
print("type(b.T * b) =", type(b.T * b))
print("b.T * A * b =", b.T * A * b)
print("(b.T * A * b) * A / 2 =", (b.T * A * b) * A / 2)
# Nonsquare matrices
D = Matrix(
[
[0, 1, 0, 2],
[3, 0, 4, 0],
]
)
print("D =", D)
print("D.shape =", D.shape)
print("D.T.shape =", D.T.shape)
print("D.T * D =", D.T * D)
print("D * D.T =", D * D.T)
# Test catch of dimension errors
try:
b - c
except ValueError:
pass
try:
b * A
except ValueError:
pass
# B points to A, test that data stays alive
del A
print("B = -A =", B)
| 18.328571 | 55 | 0.478566 | from pybricks.geometry import Matrix, vector
A = Matrix(
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
)
B = -A
C = A - A.T
print("A =", A)
print("B = -A =", B)
print("A.T =", A.T)
print("A + B =", A + B)
print("C = A - A.T =", C)
print("C + C.T =", C + C.T)
print("A * A.T =", A * A.T)
print("A.shape =", A.shape)
print("A * 3 =", A * 3)
print("3 * A =", 3 * A)
print("B[0, 1] =", B[0, 1])
print("B.T[0, 1] =", B.T[0, 1])
b = vector(3, 4, 0)
c = b.T
print("b = vector(3, 4, 0) =", b)
print("b.shape =", b.shape)
print("abs(b) =", abs(b))
print("c = b.T", c)
print("A * b =", A * b)
print("b.T * b =", b.T * b)
print("type(b.T * b) =", type(b.T * b))
print("b.T * A * b =", b.T * A * b)
print("(b.T * A * b) * A / 2 =", (b.T * A * b) * A / 2)
D = Matrix(
[
[0, 1, 0, 2],
[3, 0, 4, 0],
]
)
print("D =", D)
print("D.shape =", D.shape)
print("D.T.shape =", D.T.shape)
print("D.T * D =", D.T * D)
print("D * D.T =", D * D.T)
try:
b - c
except ValueError:
pass
try:
b * A
except ValueError:
pass
del A
print("B = -A =", B)
| true | true |
f7f6adbc34d6db52b35714a0256acbd53402fab1 | 1,952 | py | Python | scripts/show_regions.py | higex/qpath | 0377f2fdadad6e02ecde8ba2557fe9b957280fa1 | [
"MIT"
] | 6 | 2017-03-18T19:17:42.000Z | 2019-05-05T14:57:31.000Z | WSItk/tools/show_regions.py | vladpopovici/WSItk | 02db9dbf1148106a576d7b4dd7965c73607efdae | [
"MIT"
] | null | null | null | WSItk/tools/show_regions.py | vladpopovici/WSItk | 02db9dbf1148106a576d7b4dd7965c73607efdae | [
"MIT"
] | 4 | 2015-11-29T14:47:25.000Z | 2019-11-28T03:16:39.000Z | # -*- coding: utf-8 -*-
"""
SHOW_REGIONS
Emphasizes some regions in the image, by decreasing the importance of the rest.
@author: vlad
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import *
import argparse as opt
import skimage.io
from util.visualization import enhance_patches
__author__ = 'vlad'
__version__ = 0.1
def main():
p = opt.ArgumentParser(description="""
Emphasizes some regions of an image by reducing the contrast of the rest of the image.
""",
epilog="""
The regions are specified in an external file where each (rectangular) region is given in
terms of corner coordinates - row min, row max, col min, col max - and a (numeric) label.
The user must specify the label of the regions to be emphasized.
""")
p.add_argument('image', action='store', help='image file name')
p.add_argument('result', action='store', help='result image file')
p.add_argument('regions', action='store', help='file with the regions of interest')
p.add_argument('label', action='store', nargs='+', type=int,
help='one or more labels (space-separated) of the regions to be emphasized')
p.add_argument('-g', '--gamma', action='store', nargs=1, type=float,
help='the gamma level of the background regions',
default=0.2)
args = p.parse_args()
img_file = args.image
res_file = args.result
reg_file = args.regions
labels = args.label
gam = args.gamma
img = skimage.io.imread(img_file)
regs = []
with open(reg_file, 'r') as f:
lines = f.readlines()
for l in lines:
r = [int(x_) for x_ in l.strip().split()[:-1]]
if r[4] in labels:
regs.append(r[0:4])
img = enhance_patches(img, regs, _gamma=gam)
skimage.io.imsave(res_file, img)
return
if __name__ == '__main__':
main() | 30.5 | 95 | 0.641906 |
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import *
import argparse as opt
import skimage.io
from util.visualization import enhance_patches
__author__ = 'vlad'
__version__ = 0.1
def main():
p = opt.ArgumentParser(description="""
Emphasizes some regions of an image by reducing the contrast of the rest of the image.
""",
epilog="""
The regions are specified in an external file where each (rectangular) region is given in
terms of corner coordinates - row min, row max, col min, col max - and a (numeric) label.
The user must specify the label of the regions to be emphasized.
""")
p.add_argument('image', action='store', help='image file name')
p.add_argument('result', action='store', help='result image file')
p.add_argument('regions', action='store', help='file with the regions of interest')
p.add_argument('label', action='store', nargs='+', type=int,
help='one or more labels (space-separated) of the regions to be emphasized')
p.add_argument('-g', '--gamma', action='store', nargs=1, type=float,
help='the gamma level of the background regions',
default=0.2)
args = p.parse_args()
img_file = args.image
res_file = args.result
reg_file = args.regions
labels = args.label
gam = args.gamma
img = skimage.io.imread(img_file)
regs = []
with open(reg_file, 'r') as f:
lines = f.readlines()
for l in lines:
r = [int(x_) for x_ in l.strip().split()[:-1]]
if r[4] in labels:
regs.append(r[0:4])
img = enhance_patches(img, regs, _gamma=gam)
skimage.io.imsave(res_file, img)
return
if __name__ == '__main__':
main() | true | true |
f7f6add8b56d91dfe1d32605c705a2daf81c9fb4 | 6,527 | py | Python | advanced/13_profiling.py | duckherder/python-reminders | 23f650142b0745dbd7a51445aba186d85933300b | [
"MIT"
] | null | null | null | advanced/13_profiling.py | duckherder/python-reminders | 23f650142b0745dbd7a51445aba186d85933300b | [
"MIT"
] | null | null | null | advanced/13_profiling.py | duckherder/python-reminders | 23f650142b0745dbd7a51445aba186d85933300b | [
"MIT"
] | null | null | null | """Profiling CPU and memory with Python."""
import time
import timeit
import statistics # in standard library since Python 3.4/PEP450
import sys
from pympler import asizeof
import tracemalloc
from memory_profiler import profile
import objgraph
from guppy import hpy
print("########## timing code ############")
def is_prime_fn1(x):
for i in range(2, x-1):
if x % i == 0:
return False
return True
def is_prime_fn2(x):
for i in range(2, int(x**.5)+1):
if x % i == 0:
return False
return True
is_prime_lambda = lambda x: all(x % i != 0 for i in range(2, int(x**.5)+1))
def get_primes(y, func):
_primes = []
for val in range(y):
if func(val):
_primes.append(val)
return _primes
print("\nwe can use time.time() to time code...")
start_time = time.time()
print(get_primes(1000, is_prime_fn1))
print(get_primes(1000, is_prime_fn2))
print(get_primes(1000, is_prime_lambda))
end_time = time.time()
print(f"elapsed time = {end_time - start_time} seconds")
print("\nwe can use time.perf_counter() for system wide elapsed time...")
start_time = time.perf_counter() # time.clock() deprecated in Python 3.8
get_primes(10000, is_prime_fn1)
print(f"is_prime_fn1 elapsed time = {time.perf_counter()- start_time} seconds")
start_time = time.perf_counter()
get_primes(10000, is_prime_fn2)
print(f"is_prime_fn2 elapsed time = {time.perf_counter()- start_time} seconds")
start_time = time.perf_counter()
get_primes(10000, is_prime_lambda)
print(f"is_prime_lambda elapsed time = {time.perf_counter()- start_time} seconds")
print("\nwe can use time.process_time() if only want time for this process, excluding any sleeps...")
start_time = time.process_time()
get_primes(10000, is_prime_lambda)
print(f"is_prime_lambda elapsed time = {time.process_time()- start_time} seconds")
print("\nwe can use time.process_time_ns() for nanoseconds counting...")
start_time = time.perf_counter_ns()
print("hello!")
print(f"print elapsed time = {time.perf_counter_ns()- start_time}ns")
print("\nwe can use timeit.timeit if you prefer...")
print(timeit.timeit("get_primes(10000, is_prime_fn1)", globals=globals(), number=5))
print(timeit.timeit("get_primes(10000, is_prime_fn2)", globals=globals(), number=5))
print(timeit.timeit("get_primes(10000, is_prime_lambda)", globals=globals(), number=5))
def time_primes(number_tests=1):
def my_time_prime_decorator(func):
def time_prime_execution(*args, **kwargs):
_tests = []
for t in range(1, number_tests):
_start_time = time.process_time()
func(*args, **kwargs)
_end_time = time.process_time()
_tests.append(_end_time - _start_time)
print("number of tests executed =", number_tests)
print("mean execution time =", statistics.mean(_tests))
print("standard deviation execution time =", statistics.stdev(_tests))
return time_prime_execution
return my_time_prime_decorator
@time_primes(number_tests=10)
def get_primes(y, func):
_primes = []
for val in range(y):
if func(val):
_primes.append(val)
return _primes
print("\nwe can use a decorator if we so wish...")
get_primes(10000, is_prime_fn1)
get_primes(10000, is_prime_fn2)
get_primes(10000, is_prime_lambda)
print("\nfor large lists of data it is often much faster to create a dictionary than perform linear search...")
my_big_data_list = [(7263, 'bob'), (221333, 'sally'), (212892, 'simon')]
for x in my_big_data_list:
if x[0] == 221333:
print("found them!")
my_big_data_list_dict = {x[0]: x for x in my_big_data_list} # use a dictionary comprehension
print(my_big_data_list_dict)
print(my_big_data_list_dict[221333])
print("########## memory usage ############")
print("\nmemory usage...")
my_number_list = [1, 2, 3, 4]
print("some objects have the __sizeof__ attribute")
print("my_list =", my_number_list)
print(dir(my_number_list))
print("type(my_list.__sizeof__) =", type(my_number_list.__sizeof__))
print("len(my_list) =", len(my_number_list)) # just number of elements
print("my_list.__sizeof__() =", my_number_list.__sizeof__()) # raw object size
print("sys.getsizeof(1) =", sys.getsizeof(1))
print("sys.getsizeof(my_number_list) =", sys.getsizeof(my_number_list)) # __sizeof__ + garbage collector overhead
print("len(my_number_list) * (1).__sizeof__() =", len(my_number_list) * (1).__sizeof__())
print("total size of elements greater than list object size!")
my_string_list = ['hello world', 'my name is Bob', 'quick brown fox', 'phillip the cat']
print("my_string_list =", my_string_list)
print("len(my_string_list) =", len(my_string_list)) # just number of elements
print("my_string_list.__sizeof__() =", my_string_list.__sizeof__()) # raw object size
print("sys.getsizeof(my_string_list) =", sys.getsizeof(my_string_list)) # __sizeof__ + garbage collector overhead
print("string list the same size as integer list")
print("sys.getsizeof(my_number_list) + sys.getsizeof(1) + ... =",
sys.getsizeof(my_number_list) +
sys.getsizeof(1) +
sys.getsizeof(2) +
sys.getsizeof(3) +
sys.getsizeof(4))
print("sys.getsizeof(my_string_list) + sys.getsizeof('hello world') + ... =",
sys.getsizeof(my_string_list) +
sys.getsizeof('hello world') +
sys.getsizeof('my name is Bob') +
sys.getsizeof('quick brown fox') +
sys.getsizeof('phillip the cat'))
print("asizeof.asizeof(my_number_list) =", asizeof.asizeof(my_number_list))
print("asizeof.asizeof(my_string_list) =", asizeof.asizeof(my_string_list))
print("\nusing tracemalloc...")
tracemalloc.start()
trace_malloc_vector = [z for z in range(1000)]
memory_snapshot = tracemalloc.take_snapshot()
stats = memory_snapshot.statistics('lineno')
for stat in stats[:10]:
print(stat)
print("\nusing guppy...")
h = hpy()
h.setrelheap()
my_number_heaped_list = ['red', 'brown', 'green', 'blue']
print(my_number_heaped_list)
result = h.heap()
print(result)
print("\nusing memory_profiler...")
@profile
def my_func():
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del b
return a
my_func()
print("\nusing objgraph...")
objgraph.show_most_common_types()
objgraph.show_growth(limit=3)
my_new_number_list = [1, 2, 3, 4]
my_new_string_list = ['hello world', 'my name is Bob', 'quick brown fox', 'phillip the cat']
objgraph.show_growth()
| 34.903743 | 117 | 0.68546 |
import time
import timeit
import statistics
import sys
from pympler import asizeof
import tracemalloc
from memory_profiler import profile
import objgraph
from guppy import hpy
print("########## timing code ############")
def is_prime_fn1(x):
for i in range(2, x-1):
if x % i == 0:
return False
return True
def is_prime_fn2(x):
for i in range(2, int(x**.5)+1):
if x % i == 0:
return False
return True
is_prime_lambda = lambda x: all(x % i != 0 for i in range(2, int(x**.5)+1))
def get_primes(y, func):
_primes = []
for val in range(y):
if func(val):
_primes.append(val)
return _primes
print("\nwe can use time.time() to time code...")
start_time = time.time()
print(get_primes(1000, is_prime_fn1))
print(get_primes(1000, is_prime_fn2))
print(get_primes(1000, is_prime_lambda))
end_time = time.time()
print(f"elapsed time = {end_time - start_time} seconds")
print("\nwe can use time.perf_counter() for system wide elapsed time...")
start_time = time.perf_counter()
get_primes(10000, is_prime_fn1)
print(f"is_prime_fn1 elapsed time = {time.perf_counter()- start_time} seconds")
start_time = time.perf_counter()
get_primes(10000, is_prime_fn2)
print(f"is_prime_fn2 elapsed time = {time.perf_counter()- start_time} seconds")
start_time = time.perf_counter()
get_primes(10000, is_prime_lambda)
print(f"is_prime_lambda elapsed time = {time.perf_counter()- start_time} seconds")
print("\nwe can use time.process_time() if only want time for this process, excluding any sleeps...")
start_time = time.process_time()
get_primes(10000, is_prime_lambda)
print(f"is_prime_lambda elapsed time = {time.process_time()- start_time} seconds")
print("\nwe can use time.process_time_ns() for nanoseconds counting...")
start_time = time.perf_counter_ns()
print("hello!")
print(f"print elapsed time = {time.perf_counter_ns()- start_time}ns")
print("\nwe can use timeit.timeit if you prefer...")
print(timeit.timeit("get_primes(10000, is_prime_fn1)", globals=globals(), number=5))
print(timeit.timeit("get_primes(10000, is_prime_fn2)", globals=globals(), number=5))
print(timeit.timeit("get_primes(10000, is_prime_lambda)", globals=globals(), number=5))
def time_primes(number_tests=1):
def my_time_prime_decorator(func):
def time_prime_execution(*args, **kwargs):
_tests = []
for t in range(1, number_tests):
_start_time = time.process_time()
func(*args, **kwargs)
_end_time = time.process_time()
_tests.append(_end_time - _start_time)
print("number of tests executed =", number_tests)
print("mean execution time =", statistics.mean(_tests))
print("standard deviation execution time =", statistics.stdev(_tests))
return time_prime_execution
return my_time_prime_decorator
@time_primes(number_tests=10)
def get_primes(y, func):
_primes = []
for val in range(y):
if func(val):
_primes.append(val)
return _primes
print("\nwe can use a decorator if we so wish...")
get_primes(10000, is_prime_fn1)
get_primes(10000, is_prime_fn2)
get_primes(10000, is_prime_lambda)
print("\nfor large lists of data it is often much faster to create a dictionary than perform linear search...")
my_big_data_list = [(7263, 'bob'), (221333, 'sally'), (212892, 'simon')]
for x in my_big_data_list:
if x[0] == 221333:
print("found them!")
my_big_data_list_dict = {x[0]: x for x in my_big_data_list}
print(my_big_data_list_dict)
print(my_big_data_list_dict[221333])
print("########## memory usage ############")
print("\nmemory usage...")
my_number_list = [1, 2, 3, 4]
print("some objects have the __sizeof__ attribute")
print("my_list =", my_number_list)
print(dir(my_number_list))
print("type(my_list.__sizeof__) =", type(my_number_list.__sizeof__))
print("len(my_list) =", len(my_number_list))
print("my_list.__sizeof__() =", my_number_list.__sizeof__())
print("sys.getsizeof(1) =", sys.getsizeof(1))
print("sys.getsizeof(my_number_list) =", sys.getsizeof(my_number_list))
print("len(my_number_list) * (1).__sizeof__() =", len(my_number_list) * (1).__sizeof__())
print("total size of elements greater than list object size!")
my_string_list = ['hello world', 'my name is Bob', 'quick brown fox', 'phillip the cat']
print("my_string_list =", my_string_list)
print("len(my_string_list) =", len(my_string_list))
print("my_string_list.__sizeof__() =", my_string_list.__sizeof__())
print("sys.getsizeof(my_string_list) =", sys.getsizeof(my_string_list))
print("string list the same size as integer list")
print("sys.getsizeof(my_number_list) + sys.getsizeof(1) + ... =",
sys.getsizeof(my_number_list) +
sys.getsizeof(1) +
sys.getsizeof(2) +
sys.getsizeof(3) +
sys.getsizeof(4))
print("sys.getsizeof(my_string_list) + sys.getsizeof('hello world') + ... =",
sys.getsizeof(my_string_list) +
sys.getsizeof('hello world') +
sys.getsizeof('my name is Bob') +
sys.getsizeof('quick brown fox') +
sys.getsizeof('phillip the cat'))
print("asizeof.asizeof(my_number_list) =", asizeof.asizeof(my_number_list))
print("asizeof.asizeof(my_string_list) =", asizeof.asizeof(my_string_list))
print("\nusing tracemalloc...")
tracemalloc.start()
trace_malloc_vector = [z for z in range(1000)]
memory_snapshot = tracemalloc.take_snapshot()
stats = memory_snapshot.statistics('lineno')
for stat in stats[:10]:
print(stat)
print("\nusing guppy...")
h = hpy()
h.setrelheap()
my_number_heaped_list = ['red', 'brown', 'green', 'blue']
print(my_number_heaped_list)
result = h.heap()
print(result)
print("\nusing memory_profiler...")
@profile
def my_func():
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del b
return a
my_func()
print("\nusing objgraph...")
objgraph.show_most_common_types()
objgraph.show_growth(limit=3)
my_new_number_list = [1, 2, 3, 4]
my_new_string_list = ['hello world', 'my name is Bob', 'quick brown fox', 'phillip the cat']
objgraph.show_growth()
| true | true |
f7f6ae9a938a96047beabf2295f81d82aafa8c50 | 198 | py | Python | models/en_fl/__init__.py | redperiabras/FILIPINEU | 833fd8d44c9d4de94d3433ca810a4a17831343ff | [
"MIT"
] | null | null | null | models/en_fl/__init__.py | redperiabras/FILIPINEU | 833fd8d44c9d4de94d3433ca810a4a17831343ff | [
"MIT"
] | 1 | 2017-10-30T12:02:44.000Z | 2017-10-30T12:02:44.000Z | models/en_fl/__init__.py | redperiabras/FILIPINEU | 833fd8d44c9d4de94d3433ca810a4a17831343ff | [
"MIT"
] | 1 | 2020-11-16T07:56:58.000Z | 2020-11-16T07:56:58.000Z | import os
import pickle
from modules.model import NMT
with open(os.getcwd()+'/models/en_fl/en-fl.nlm', 'rb') as f:
config = pickle.load(f)
model = NMT('fl-en', config)
model.load(f)
f.close() | 18 | 60 | 0.681818 | import os
import pickle
from modules.model import NMT
with open(os.getcwd()+'/models/en_fl/en-fl.nlm', 'rb') as f:
config = pickle.load(f)
model = NMT('fl-en', config)
model.load(f)
f.close() | true | true |
f7f6aee013739de8f7a041ed680167ba11ba985c | 1,349 | py | Python | synthesize.py | HappyBall/asr_guided_tacotron | be36f0895b81e338c5c51a7ab6d421fbf3aa055b | [
"MIT"
] | 5 | 2018-08-02T13:44:11.000Z | 2020-04-27T23:48:21.000Z | synthesize.py | HappyBall/asr_guided_tacotron | be36f0895b81e338c5c51a7ab6d421fbf3aa055b | [
"MIT"
] | 1 | 2019-08-19T06:47:26.000Z | 2020-05-24T01:18:22.000Z | synthesize.py | HappyBall/asr_guided_tacotron | be36f0895b81e338c5c51a7ab6d421fbf3aa055b | [
"MIT"
] | 5 | 2019-02-18T16:39:47.000Z | 2021-08-19T14:10:43.000Z | '''
modified from
https://www.github.com/kyubyong/tacotron
'''
from hyperparams import Hyperparams as hp
import tqdm
from data_load import load_data
import tensorflow as tf
from train import Graph
from utils import spectrogram2wav
from scipy.io.wavfile import write
import os
import numpy as np
def synthesize():
if not os.path.exists(hp.taco_sampledir): os.mkdir(hp.taco_sampledir)
# Load graph
g = Graph(mode="synthesize"); print("Graph loaded")
# Load data
texts = load_data(mode="synthesize")
_, mel_ref, _ = load_spectrograms(hp.ref_wavfile)
mel_ref = np.tile(mel_ref, (texts.shape[0], 1, 1))
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint(hp.taco_logdir)); print("Restored!")
# Feed Forward
## mel
_y_hat = sess.run(g.diff_mels_taco_hat, {g.random_texts_taco: texts, g.mels_taco: mel_ref})
y_hat = _y_hat # we can plot spectrogram
mags = sess.run(g.diff_mags_taco_hat, {g.diff_mels_taco_hat: y_hat})
for i, mag in enumerate(mags):
print("File {}.wav is being generated ...".format(i+1))
audio = spectrogram2wav(mag)
write(os.path.join(hp.taco_sampledir, '{}.wav'.format(i+1)), hp.sr, audio)
if __name__ == '__main__':
synthesize()
print("Done")
| 28.702128 | 99 | 0.670867 |
from hyperparams import Hyperparams as hp
import tqdm
from data_load import load_data
import tensorflow as tf
from train import Graph
from utils import spectrogram2wav
from scipy.io.wavfile import write
import os
import numpy as np
def synthesize():
if not os.path.exists(hp.taco_sampledir): os.mkdir(hp.taco_sampledir)
g = Graph(mode="synthesize"); print("Graph loaded")
texts = load_data(mode="synthesize")
_, mel_ref, _ = load_spectrograms(hp.ref_wavfile)
mel_ref = np.tile(mel_ref, (texts.shape[0], 1, 1))
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint(hp.taco_logdir)); print("Restored!")
_y_hat = sess.run(g.diff_mels_taco_hat, {g.random_texts_taco: texts, g.mels_taco: mel_ref})
y_hat = _y_hat
mags = sess.run(g.diff_mags_taco_hat, {g.diff_mels_taco_hat: y_hat})
for i, mag in enumerate(mags):
print("File {}.wav is being generated ...".format(i+1))
audio = spectrogram2wav(mag)
write(os.path.join(hp.taco_sampledir, '{}.wav'.format(i+1)), hp.sr, audio)
if __name__ == '__main__':
synthesize()
print("Done")
| true | true |
f7f6b1eb297796bd265d1e6ed82032bf7688277d | 9,079 | py | Python | sdk/python/pulumi_azure/mssql/server_vulnerability_assessment.py | apollo2030/pulumi-azure | 034665c61665f4dc7e291b8813747012d34fa044 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure/mssql/server_vulnerability_assessment.py | apollo2030/pulumi-azure | 034665c61665f4dc7e291b8813747012d34fa044 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure/mssql/server_vulnerability_assessment.py | apollo2030/pulumi-azure | 034665c61665f4dc7e291b8813747012d34fa044 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class ServerVulnerabilityAssessment(pulumi.CustomResource):
recurring_scans: pulumi.Output[dict]
"""
The recurring scans settings. The `recurring_scans` block supports fields documented below.
* `emailSubscriptionAdmins` (`bool`) - Boolean flag which specifies if the schedule scan notification will be sent to the subscription administrators. Defaults to `false`.
* `emails` (`list`) - Specifies an array of e-mail addresses to which the scan notification is sent.
* `enabled` (`bool`) - Boolean flag which specifies if recurring scans is enabled or disabled. Defaults to `false`.
"""
server_security_alert_policy_id: pulumi.Output[str]
"""
The id of the security alert policy of the MS SQL Server. Changing this forces a new resource to be created.
"""
storage_account_access_key: pulumi.Output[str]
"""
Specifies the identifier key of the storage account for vulnerability assessment scan results. If `storage_container_sas_key` isn't specified, `storage_account_access_key` is required.
"""
storage_container_path: pulumi.Output[str]
"""
A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/).
"""
storage_container_sas_key: pulumi.Output[str]
"""
A shared access signature (SAS Key) that has write access to the blob container specified in `storage_container_path` parameter. If `storage_account_access_key` isn't specified, `storage_container_sas_key` is required.
"""
def __init__(__self__, resource_name, opts=None, recurring_scans=None, server_security_alert_policy_id=None, storage_account_access_key=None, storage_container_path=None, storage_container_sas_key=None, __props__=None, __name__=None, __opts__=None):
"""
Manages the Vulnerability Assessment for a MS SQL Server.
> **NOTE** Vulnerability Assessment is currently only available for MS SQL databases.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[dict] recurring_scans: The recurring scans settings. The `recurring_scans` block supports fields documented below.
:param pulumi.Input[str] server_security_alert_policy_id: The id of the security alert policy of the MS SQL Server. Changing this forces a new resource to be created.
:param pulumi.Input[str] storage_account_access_key: Specifies the identifier key of the storage account for vulnerability assessment scan results. If `storage_container_sas_key` isn't specified, `storage_account_access_key` is required.
:param pulumi.Input[str] storage_container_path: A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/).
:param pulumi.Input[str] storage_container_sas_key: A shared access signature (SAS Key) that has write access to the blob container specified in `storage_container_path` parameter. If `storage_account_access_key` isn't specified, `storage_container_sas_key` is required.
The **recurring_scans** object supports the following:
* `emailSubscriptionAdmins` (`pulumi.Input[bool]`) - Boolean flag which specifies if the schedule scan notification will be sent to the subscription administrators. Defaults to `false`.
* `emails` (`pulumi.Input[list]`) - Specifies an array of e-mail addresses to which the scan notification is sent.
* `enabled` (`pulumi.Input[bool]`) - Boolean flag which specifies if recurring scans is enabled or disabled. Defaults to `false`.
> This content is derived from https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/website/docs/r/mssql_server_vulnerability_assessment.html.markdown.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['recurring_scans'] = recurring_scans
if server_security_alert_policy_id is None:
raise TypeError("Missing required property 'server_security_alert_policy_id'")
__props__['server_security_alert_policy_id'] = server_security_alert_policy_id
__props__['storage_account_access_key'] = storage_account_access_key
if storage_container_path is None:
raise TypeError("Missing required property 'storage_container_path'")
__props__['storage_container_path'] = storage_container_path
__props__['storage_container_sas_key'] = storage_container_sas_key
super(ServerVulnerabilityAssessment, __self__).__init__(
'azure:mssql/serverVulnerabilityAssessment:ServerVulnerabilityAssessment',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name, id, opts=None, recurring_scans=None, server_security_alert_policy_id=None, storage_account_access_key=None, storage_container_path=None, storage_container_sas_key=None):
"""
Get an existing ServerVulnerabilityAssessment resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param str id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[dict] recurring_scans: The recurring scans settings. The `recurring_scans` block supports fields documented below.
:param pulumi.Input[str] server_security_alert_policy_id: The id of the security alert policy of the MS SQL Server. Changing this forces a new resource to be created.
:param pulumi.Input[str] storage_account_access_key: Specifies the identifier key of the storage account for vulnerability assessment scan results. If `storage_container_sas_key` isn't specified, `storage_account_access_key` is required.
:param pulumi.Input[str] storage_container_path: A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/).
:param pulumi.Input[str] storage_container_sas_key: A shared access signature (SAS Key) that has write access to the blob container specified in `storage_container_path` parameter. If `storage_account_access_key` isn't specified, `storage_container_sas_key` is required.
The **recurring_scans** object supports the following:
* `emailSubscriptionAdmins` (`pulumi.Input[bool]`) - Boolean flag which specifies if the schedule scan notification will be sent to the subscription administrators. Defaults to `false`.
* `emails` (`pulumi.Input[list]`) - Specifies an array of e-mail addresses to which the scan notification is sent.
* `enabled` (`pulumi.Input[bool]`) - Boolean flag which specifies if recurring scans is enabled or disabled. Defaults to `false`.
> This content is derived from https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/website/docs/r/mssql_server_vulnerability_assessment.html.markdown.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["recurring_scans"] = recurring_scans
__props__["server_security_alert_policy_id"] = server_security_alert_policy_id
__props__["storage_account_access_key"] = storage_account_access_key
__props__["storage_container_path"] = storage_container_path
__props__["storage_container_sas_key"] = storage_container_sas_key
return ServerVulnerabilityAssessment(resource_name, opts=opts, __props__=__props__)
def translate_output_property(self, prop):
return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| 70.379845 | 278 | 0.734883 |
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class ServerVulnerabilityAssessment(pulumi.CustomResource):
recurring_scans: pulumi.Output[dict]
server_security_alert_policy_id: pulumi.Output[str]
storage_account_access_key: pulumi.Output[str]
storage_container_path: pulumi.Output[str]
storage_container_sas_key: pulumi.Output[str]
def __init__(__self__, resource_name, opts=None, recurring_scans=None, server_security_alert_policy_id=None, storage_account_access_key=None, storage_container_path=None, storage_container_sas_key=None, __props__=None, __name__=None, __opts__=None):
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['recurring_scans'] = recurring_scans
if server_security_alert_policy_id is None:
raise TypeError("Missing required property 'server_security_alert_policy_id'")
__props__['server_security_alert_policy_id'] = server_security_alert_policy_id
__props__['storage_account_access_key'] = storage_account_access_key
if storage_container_path is None:
raise TypeError("Missing required property 'storage_container_path'")
__props__['storage_container_path'] = storage_container_path
__props__['storage_container_sas_key'] = storage_container_sas_key
super(ServerVulnerabilityAssessment, __self__).__init__(
'azure:mssql/serverVulnerabilityAssessment:ServerVulnerabilityAssessment',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name, id, opts=None, recurring_scans=None, server_security_alert_policy_id=None, storage_account_access_key=None, storage_container_path=None, storage_container_sas_key=None):
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["recurring_scans"] = recurring_scans
__props__["server_security_alert_policy_id"] = server_security_alert_policy_id
__props__["storage_account_access_key"] = storage_account_access_key
__props__["storage_container_path"] = storage_container_path
__props__["storage_container_sas_key"] = storage_container_sas_key
return ServerVulnerabilityAssessment(resource_name, opts=opts, __props__=__props__)
def translate_output_property(self, prop):
return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| true | true |
f7f6b2786502a423291fd8144b0198c45ce02efc | 1,684 | py | Python | BookClub/management/commands/importuserstargeted.py | amir-rahim/BookClubSocialNetwork | b69a07cd33592f700214252a64c7c1c53845625d | [
"MIT"
] | 4 | 2022-02-04T02:11:48.000Z | 2022-03-12T21:38:01.000Z | BookClub/management/commands/importuserstargeted.py | amir-rahim/BookClubSocialNetwork | b69a07cd33592f700214252a64c7c1c53845625d | [
"MIT"
] | 51 | 2022-02-01T18:56:23.000Z | 2022-03-31T15:35:37.000Z | BookClub/management/commands/importuserstargeted.py | amir-rahim/BookClubSocialNetwork | b69a07cd33592f700214252a64c7c1c53845625d | [
"MIT"
] | null | null | null | from django.core.management.base import BaseCommand
import random
from faker import Faker
import pandas as pd
from pandas import DataFrame
import time
from BookClub.management.commands.helper import get_top_n_books, get_top_n_users_who_have_rated_xyz_books, get_top_n_books_shifted
from BookClub.models.user import User
class Command(BaseCommand):
"""The database seeder."""
def handle(self, *args, **options):
tic = time.time()
model_instances = self.import_users()
try:
User.objects.bulk_create(model_instances)
except Exception as e:
print(e)
toc = time.time()
total = toc-tic
print('Done in {:.4f} seconds'.format(total))
print(str(len(model_instances)) + " Users created")
def import_users(self):
file_path = ("static/dataset/BX-Users.csv")
data = DataFrame(pd.read_csv(file_path, header=0, encoding= "ISO-8859-1", sep=';'))
isbns = get_top_n_books_shifted(300)
rating_users = get_top_n_users_who_have_rated_xyz_books(1000, isbns)
faker = Faker()
chosen_users = data[data['User-ID'].isin(rating_users)]
chosen_users = chosen_users.to_dict('records')
model_instances = []
i = 0;
for record in chosen_users:
i +=1
Faker.seed(i)
u = User(
pk=i,
username=faker.unique.user_name(),
email=faker.unique.email(),
password='pbkdf2_sha256$260000$qw2y9qdBlYmFUZVdkUqlOO$nuzhHvRnVDDOAo70OL14IEqk+bASVNTLjWS1N+c40VU=',
)
model_instances.append(u)
return model_instances
| 31.773585 | 130 | 0.637767 | from django.core.management.base import BaseCommand
import random
from faker import Faker
import pandas as pd
from pandas import DataFrame
import time
from BookClub.management.commands.helper import get_top_n_books, get_top_n_users_who_have_rated_xyz_books, get_top_n_books_shifted
from BookClub.models.user import User
class Command(BaseCommand):
def handle(self, *args, **options):
tic = time.time()
model_instances = self.import_users()
try:
User.objects.bulk_create(model_instances)
except Exception as e:
print(e)
toc = time.time()
total = toc-tic
print('Done in {:.4f} seconds'.format(total))
print(str(len(model_instances)) + " Users created")
def import_users(self):
file_path = ("static/dataset/BX-Users.csv")
data = DataFrame(pd.read_csv(file_path, header=0, encoding= "ISO-8859-1", sep=';'))
isbns = get_top_n_books_shifted(300)
rating_users = get_top_n_users_who_have_rated_xyz_books(1000, isbns)
faker = Faker()
chosen_users = data[data['User-ID'].isin(rating_users)]
chosen_users = chosen_users.to_dict('records')
model_instances = []
i = 0;
for record in chosen_users:
i +=1
Faker.seed(i)
u = User(
pk=i,
username=faker.unique.user_name(),
email=faker.unique.email(),
password='pbkdf2_sha256$260000$qw2y9qdBlYmFUZVdkUqlOO$nuzhHvRnVDDOAo70OL14IEqk+bASVNTLjWS1N+c40VU=',
)
model_instances.append(u)
return model_instances
| true | true |
f7f6b2a89736e3b92a223108452ac6a9411b3e07 | 3,330 | py | Python | trading/models.py | cgajagon/Trading-App | 10ffbea9dec3deca94489bf62d9f79e22f5ebebc | [
"MIT"
] | null | null | null | trading/models.py | cgajagon/Trading-App | 10ffbea9dec3deca94489bf62d9f79e22f5ebebc | [
"MIT"
] | 11 | 2020-02-21T20:57:13.000Z | 2022-02-10T19:27:01.000Z | trading/models.py | cgajagon/Trading-App | 10ffbea9dec3deca94489bf62d9f79e22f5ebebc | [
"MIT"
] | null | null | null | from django.db import models
from django.urls import reverse, reverse_lazy
import datetime
class Symbols(models.Model):
AD = 'ADR'
RE = 'REIT'
CE = 'Closed end fund'
SI = 'Secondary Issue'
LP = 'Limited Partnerships'
CS = 'Common Stock'
ET = 'ETF'
TYPE = [
(AD, 'ADR'),
(RE, 'REIT'),
(CE, 'Closed end fund'),
(SI, 'Secondary Issue'),
(LP, 'Limited Partnerships'),
(CS, 'Common Stock'),
(ET, 'ETF'),
]
symbol = models.CharField(max_length=20, null=False, blank=False, unique=True, primary_key=True)
name = models.CharField(max_length=200, null=True, blank=True)
isEnabled = models.BooleanField(null=False, blank=False, default=True)
iexId = models.IntegerField()
date = models.DateField(default=datetime.date.today)
symbol_type = models.CharField(max_length=20, choices=TYPE, default='AD')
def __str__(self):
return self.symbol
class SymbolsAutocomplete(models.Model):
search = models.CharField(max_length=20, null=False, blank=False, unique=True, primary_key=True)
def __str__(self):
return self.search
class SymbolsAutocompleteRelation(models.Model):
symbol = models.CharField(max_length=20, null=False, blank=False)
search = models.ForeignKey(SymbolsAutocomplete, on_delete=models.CASCADE, null=False, blank=False, related_name='related_symbols')
class WatchSymbols(models.Model):
symbol = models.OneToOneField(Symbols, on_delete=models.CASCADE, null=False, blank=False)
date_enter = models.DateField(default=datetime.date.today)
notes = models.TextField(max_length=200, null=True, blank=True)
def __str__(self):
return '%s on %s' % (self.symbol, self.date_enter)
class AlertWatch(models.Model):
watched_symbol = models.ForeignKey(WatchSymbols, on_delete=models.CASCADE, null=False, blank=False)
date_enter = models.DateField(default=datetime.date.today)
expected_min_price = models.FloatField(null=False, blank=False)
expected_max_price = models.FloatField(null=False, blank=False)
notes = models.TextField(max_length=200, null=True, blank=True)
def __str__(self):
return '%s on %s' % (self.watched_symbol, self.date_enter)
# Return to Watch Symbol Detail View
def get_absolute_url(self):
return reverse_lazy('watchsymbol_detail', args=[str(self.watched_symbol.pk)])
class HistoricalPrices(models.Model):
symbol = models.ForeignKey(Symbols, on_delete=models.CASCADE, null=False, blank=False)
date = models.DateField(default=datetime.date.today)
open_price = models.FloatField(null=True, blank=True)
high_price = models.FloatField(null=True, blank=True)
low_price = models.FloatField(null=True, blank=True)
close_price = models.FloatField(null=True, blank=True)
volume = models.IntegerField(null=True, blank=True)
uOpen = models.FloatField(null=True, blank=True)
uHigh = models.FloatField(null=True, blank=True)
uLow = models.FloatField(null=True, blank=True)
uClose = models.FloatField(null=True, blank=True)
uVolume = models.IntegerField(null=True, blank=True)
change = models.FloatField(null=True, blank=True)
changePercent = models.FloatField(null=True, blank=True)
changeOverTime = models.FloatField(null=True, blank=True) | 41.111111 | 134 | 0.710511 | from django.db import models
from django.urls import reverse, reverse_lazy
import datetime
class Symbols(models.Model):
AD = 'ADR'
RE = 'REIT'
CE = 'Closed end fund'
SI = 'Secondary Issue'
LP = 'Limited Partnerships'
CS = 'Common Stock'
ET = 'ETF'
TYPE = [
(AD, 'ADR'),
(RE, 'REIT'),
(CE, 'Closed end fund'),
(SI, 'Secondary Issue'),
(LP, 'Limited Partnerships'),
(CS, 'Common Stock'),
(ET, 'ETF'),
]
symbol = models.CharField(max_length=20, null=False, blank=False, unique=True, primary_key=True)
name = models.CharField(max_length=200, null=True, blank=True)
isEnabled = models.BooleanField(null=False, blank=False, default=True)
iexId = models.IntegerField()
date = models.DateField(default=datetime.date.today)
symbol_type = models.CharField(max_length=20, choices=TYPE, default='AD')
def __str__(self):
return self.symbol
class SymbolsAutocomplete(models.Model):
search = models.CharField(max_length=20, null=False, blank=False, unique=True, primary_key=True)
def __str__(self):
return self.search
class SymbolsAutocompleteRelation(models.Model):
symbol = models.CharField(max_length=20, null=False, blank=False)
search = models.ForeignKey(SymbolsAutocomplete, on_delete=models.CASCADE, null=False, blank=False, related_name='related_symbols')
class WatchSymbols(models.Model):
symbol = models.OneToOneField(Symbols, on_delete=models.CASCADE, null=False, blank=False)
date_enter = models.DateField(default=datetime.date.today)
notes = models.TextField(max_length=200, null=True, blank=True)
def __str__(self):
return '%s on %s' % (self.symbol, self.date_enter)
class AlertWatch(models.Model):
watched_symbol = models.ForeignKey(WatchSymbols, on_delete=models.CASCADE, null=False, blank=False)
date_enter = models.DateField(default=datetime.date.today)
expected_min_price = models.FloatField(null=False, blank=False)
expected_max_price = models.FloatField(null=False, blank=False)
notes = models.TextField(max_length=200, null=True, blank=True)
def __str__(self):
return '%s on %s' % (self.watched_symbol, self.date_enter)
def get_absolute_url(self):
return reverse_lazy('watchsymbol_detail', args=[str(self.watched_symbol.pk)])
class HistoricalPrices(models.Model):
symbol = models.ForeignKey(Symbols, on_delete=models.CASCADE, null=False, blank=False)
date = models.DateField(default=datetime.date.today)
open_price = models.FloatField(null=True, blank=True)
high_price = models.FloatField(null=True, blank=True)
low_price = models.FloatField(null=True, blank=True)
close_price = models.FloatField(null=True, blank=True)
volume = models.IntegerField(null=True, blank=True)
uOpen = models.FloatField(null=True, blank=True)
uHigh = models.FloatField(null=True, blank=True)
uLow = models.FloatField(null=True, blank=True)
uClose = models.FloatField(null=True, blank=True)
uVolume = models.IntegerField(null=True, blank=True)
change = models.FloatField(null=True, blank=True)
changePercent = models.FloatField(null=True, blank=True)
changeOverTime = models.FloatField(null=True, blank=True) | true | true |
f7f6b30c0db72e839b28d0a9f70a0532357f7a53 | 1,128 | py | Python | tests/test_migen_fsmgen.py | cactorium/fsm-gen-migen | 9a177088d412ceff25a40848e95c133b524e2cf4 | [
"MIT"
] | null | null | null | tests/test_migen_fsmgen.py | cactorium/fsm-gen-migen | 9a177088d412ceff25a40848e95c133b524e2cf4 | [
"MIT"
] | null | null | null | tests/test_migen_fsmgen.py | cactorium/fsm-gen-migen | 9a177088d412ceff25a40848e95c133b524e2cf4 | [
"MIT"
] | null | null | null | from migen import *
from migen.fhdl import verilog
# TODO get this working right
from .context import migen_fsmgen
class Foo(Module):
def __init__(self):
self.s = Signal()
self.counter = Signal(8)
x = Array(Signal(name="a") for i in range(7))
self.submodules += self.test_fsm(self.counter, self.counter)
@fsmgen(True)
def test_fsm(self, x, inp):
f = Signal(2)
while True:
if inp == 1:
self.s.eq(1)
elif inp == 0:
self.s.eq(0)
yield
NextValue(self.s, 1)
NextValue(self.counter, self.counter + 1)
yield "B"
@fsmgen()
def test_fsm2(self, x):
self.s.eq(1)
yield "A"
NextValue(self.s, 1)
NextValue(self.counter, self.counter + 1)
yield B
# TODO: fix this case
@fsmgen()
def test_fsm3(x, y):
while x == 1:
yield A
NextValue(y, 0)
while x == 0:
yield B
NextValue(y, 0)
while x == 1:
yield C
yield C2
NextValue(y, 1)
f = Foo()
# print(f.test_fsm(5, 7))
# print(f.test_fsm2(5))
print(f.test_fsm.fsmgen_source)
# print(verilog.convert(f))
print(f.test_fsm3.fsmgen_source)
| 19.789474 | 64 | 0.600177 | from migen import *
from migen.fhdl import verilog
from .context import migen_fsmgen
class Foo(Module):
def __init__(self):
self.s = Signal()
self.counter = Signal(8)
x = Array(Signal(name="a") for i in range(7))
self.submodules += self.test_fsm(self.counter, self.counter)
@fsmgen(True)
def test_fsm(self, x, inp):
f = Signal(2)
while True:
if inp == 1:
self.s.eq(1)
elif inp == 0:
self.s.eq(0)
yield
NextValue(self.s, 1)
NextValue(self.counter, self.counter + 1)
yield "B"
@fsmgen()
def test_fsm2(self, x):
self.s.eq(1)
yield "A"
NextValue(self.s, 1)
NextValue(self.counter, self.counter + 1)
yield B
@fsmgen()
def test_fsm3(x, y):
while x == 1:
yield A
NextValue(y, 0)
while x == 0:
yield B
NextValue(y, 0)
while x == 1:
yield C
yield C2
NextValue(y, 1)
f = Foo()
print(f.test_fsm.fsmgen_source)
print(f.test_fsm3.fsmgen_source)
| true | true |
f7f6b31288268de01e1635fa60cd094441226754 | 2,018 | py | Python | girder/test_girder/girder_utilities.py | naglepuff/large_image | 4e928166f228fe894c38e4b01af5370e72f7229c | [
"Apache-2.0"
] | null | null | null | girder/test_girder/girder_utilities.py | naglepuff/large_image | 4e928166f228fe894c38e4b01af5370e72f7229c | [
"Apache-2.0"
] | null | null | null | girder/test_girder/girder_utilities.py | naglepuff/large_image | 4e928166f228fe894c38e4b01af5370e72f7229c | [
"Apache-2.0"
] | null | null | null | import os
from test.datastore import datastore
from test.utilities import BigTIFFHeader, JFIFHeader, JPEGHeader, PNGHeader, TIFFHeader # noqa
try:
from girder.models.folder import Folder
from girder.models.upload import Upload
except ImportError:
# Make it easier to test without girder
pass
def namedFolder(user, folderName='Public'):
return Folder().find({
'parentId': user['_id'],
'name': folderName,
})[0]
def uploadFile(filePath, user, assetstore, folderName='Public', name=None):
if name is None:
name = os.path.basename(filePath)
folder = namedFolder(user, folderName)
file = Upload().uploadFromFile(
open(filePath, 'rb'), os.path.getsize(filePath), name,
parentType='folder', parent=folder, user=user, assetstore=assetstore)
return file
def uploadExternalFile(hashPath, user, assetstore, folderName='Public', name=None):
imagePath = datastore.fetch(hashPath)
return uploadFile(imagePath, user=user, assetstore=assetstore, folderName=folderName, name=name)
def uploadTestFile(fileName, user, assetstore, folderName='Public', name=None):
testDir = os.path.dirname(os.path.realpath(__file__))
imagePath = os.path.join(testDir, '..', '..', 'test', 'test_files', fileName)
return uploadFile(imagePath, user=user, assetstore=assetstore, folderName=folderName, name=None)
def respStatus(resp):
return int(resp.output_status.split()[0])
def getBody(response, text=True):
"""
Returns the response body as a text type or binary string.
:param response: The response object from the server.
:param text: If true, treat the data as a text string, otherwise, treat
as binary.
"""
data = '' if text else b''
for chunk in response.body:
if text and isinstance(chunk, bytes):
chunk = chunk.decode('utf8')
elif not text and not isinstance(chunk, bytes):
chunk = chunk.encode('utf8')
data += chunk
return data
| 32.031746 | 100 | 0.684341 | import os
from test.datastore import datastore
from test.utilities import BigTIFFHeader, JFIFHeader, JPEGHeader, PNGHeader, TIFFHeader
try:
from girder.models.folder import Folder
from girder.models.upload import Upload
except ImportError:
pass
def namedFolder(user, folderName='Public'):
return Folder().find({
'parentId': user['_id'],
'name': folderName,
})[0]
def uploadFile(filePath, user, assetstore, folderName='Public', name=None):
if name is None:
name = os.path.basename(filePath)
folder = namedFolder(user, folderName)
file = Upload().uploadFromFile(
open(filePath, 'rb'), os.path.getsize(filePath), name,
parentType='folder', parent=folder, user=user, assetstore=assetstore)
return file
def uploadExternalFile(hashPath, user, assetstore, folderName='Public', name=None):
imagePath = datastore.fetch(hashPath)
return uploadFile(imagePath, user=user, assetstore=assetstore, folderName=folderName, name=name)
def uploadTestFile(fileName, user, assetstore, folderName='Public', name=None):
testDir = os.path.dirname(os.path.realpath(__file__))
imagePath = os.path.join(testDir, '..', '..', 'test', 'test_files', fileName)
return uploadFile(imagePath, user=user, assetstore=assetstore, folderName=folderName, name=None)
def respStatus(resp):
return int(resp.output_status.split()[0])
def getBody(response, text=True):
data = '' if text else b''
for chunk in response.body:
if text and isinstance(chunk, bytes):
chunk = chunk.decode('utf8')
elif not text and not isinstance(chunk, bytes):
chunk = chunk.encode('utf8')
data += chunk
return data
| true | true |
f7f6b3ad2f358cd2bd2a52177bb7bd548c0b3c86 | 110 | py | Python | blipy/Postmasters/__init__.py | liviaalmeida/blipy | 95b3cebd2d28900a81d288122d90305b9bf72d4e | [
"MIT"
] | null | null | null | blipy/Postmasters/__init__.py | liviaalmeida/blipy | 95b3cebd2d28900a81d288122d90305b9bf72d4e | [
"MIT"
] | null | null | null | blipy/Postmasters/__init__.py | liviaalmeida/blipy | 95b3cebd2d28900a81d288122d90305b9bf72d4e | [
"MIT"
] | null | null | null | from blipy.Postmasters.__AI import AIPostmaster
from blipy.Postmasters.__Analytics import AnalyticsPostmaster
| 36.666667 | 61 | 0.890909 | from blipy.Postmasters.__AI import AIPostmaster
from blipy.Postmasters.__Analytics import AnalyticsPostmaster
| true | true |
f7f6b4f0461aec76c26d492fdf434de0b7e98ece | 6,515 | py | Python | src/test/python/twitter/aurora/config/test_thrift.py | isomer/incubator-aurora | 5f54d4de25413bb18acec16120eb18f3e08c6bf0 | [
"Apache-2.0"
] | null | null | null | src/test/python/twitter/aurora/config/test_thrift.py | isomer/incubator-aurora | 5f54d4de25413bb18acec16120eb18f3e08c6bf0 | [
"Apache-2.0"
] | null | null | null | src/test/python/twitter/aurora/config/test_thrift.py | isomer/incubator-aurora | 5f54d4de25413bb18acec16120eb18f3e08c6bf0 | [
"Apache-2.0"
] | null | null | null | import getpass
import re
from twitter.aurora.config import AuroraConfig
from twitter.aurora.config.schema.base import Job, SimpleTask
from twitter.aurora.config.thrift import (
convert as convert_pystachio_to_thrift,
InvalidConfig,
task_instance_from_job,
)
from twitter.thermos.config.schema import (
Process,
Resources,
Task,
)
from gen.twitter.aurora.constants import GOOD_IDENTIFIER_PATTERN_PYTHON
from gen.twitter.aurora.test.constants import (
INVALID_IDENTIFIERS,
VALID_IDENTIFIERS,
)
from gen.twitter.aurora.ttypes import (
CronCollisionPolicy,
JobKey,
Identity,
)
from pystachio import Map, String
from pystachio.naming import frozendict
import pytest
HELLO_WORLD = Job(
name = 'hello_world',
role = 'john_doe',
environment = 'staging66',
cluster = 'smf1-test',
task = Task(
name = 'main',
processes = [Process(name = 'hello_world', cmdline = 'echo {{mesos.instance}}')],
resources = Resources(cpu = 0.1, ram = 64 * 1048576, disk = 64 * 1048576),
)
)
def test_simple_config():
job = convert_pystachio_to_thrift(HELLO_WORLD)
assert job.instanceCount == 1
tti = job.taskConfig
assert job.key == JobKey(
role=HELLO_WORLD.role().get(),
environment=HELLO_WORLD.environment().get(),
name=HELLO_WORLD.name().get())
assert job.owner == Identity(role=HELLO_WORLD.role().get(), user=getpass.getuser())
assert job.cronSchedule == ''
assert tti.jobName == 'hello_world'
assert tti.isService == False
assert tti.numCpus == 0.1
assert tti.ramMb == 64
assert tti.diskMb == 64
assert tti.requestedPorts == set()
assert tti.production == False
assert tti.priority == 0
assert tti.maxTaskFailures == 1
assert tti.constraints == set()
assert tti.packages == set()
assert tti.environment == HELLO_WORLD.environment().get()
def test_config_with_options():
hwc = HELLO_WORLD(
production = True,
priority = 200,
service = True,
cron_policy = 'RUN_OVERLAP',
constraints = {
'dedicated': 'your_mom',
'cpu': 'x86_64'
},
environment = 'prod'
)
job = convert_pystachio_to_thrift(hwc)
assert job.instanceCount == 1
tti = job.taskConfig
assert tti.production == True
assert tti.priority == 200
assert tti.isService == True
assert job.cronCollisionPolicy == CronCollisionPolicy.RUN_OVERLAP
assert len(tti.constraints) == 2
assert tti.environment == 'prod'
assert job.key.environment == 'prod'
def test_config_with_ports():
hwc = HELLO_WORLD(
task = HELLO_WORLD.task()(
processes = [
Process(name = 'hello_world',
cmdline = 'echo {{thermos.ports[http]}} {{thermos.ports[admin]}}')
]
)
)
config = AuroraConfig(hwc)
job = config.job()
assert job.taskConfig.requestedPorts == set(['http', 'admin'])
def test_config_with_bad_resources():
MB = 1048576
hwtask = HELLO_WORLD.task()
convert_pystachio_to_thrift(HELLO_WORLD)
good_resources = [
Resources(cpu = 1.0, ram = 1 * MB, disk = 1 * MB)
]
bad_resources = [
Resources(cpu = 0, ram = 1 * MB, disk = 1 * MB),
Resources(cpu = 1, ram = 0 * MB, disk = 1 * MB),
Resources(cpu = 1, ram = 1 * MB, disk = 0 * MB),
Resources(cpu = 1, ram = 1 * MB - 1, disk = 1 * MB),
Resources(cpu = 1, ram = 1 * MB, disk = 1 * MB - 1)
]
for resource in good_resources:
convert_pystachio_to_thrift(HELLO_WORLD(task = hwtask(resources = resource)))
for resource in bad_resources:
with pytest.raises(ValueError):
convert_pystachio_to_thrift(HELLO_WORLD(task = hwtask(resources = resource)))
def test_config_with_task_links():
tl = Map(String, String)
unresolved_tl = {
'foo': 'http://%host%:{{thermos.ports[foo]}}',
'bar': 'http://%host%:{{thermos.ports[bar]}}/{{mesos.instance}}',
}
resolved_tl = {
'foo': 'http://%host%:%port:foo%',
'bar': 'http://%host%:%port:bar%/%shard_id%'
}
aurora_config = AuroraConfig(HELLO_WORLD(task_links = tl(unresolved_tl)))
assert aurora_config.task_links() == tl(resolved_tl)
assert aurora_config.job().taskConfig.taskLinks == frozendict(resolved_tl)
bad_tl = {
'foo': '{{thermos.ports.bad}}'
}
with pytest.raises(AuroraConfig.InvalidConfig):
AuroraConfig(HELLO_WORLD(task_links=tl(bad_tl))).job()
def test_unbound_references():
def job_command(cmdline):
return AuroraConfig(HELLO_WORLD(task = SimpleTask('hello_world', cmdline))).raw()
# bindingless and bad => good bindings should work
convert_pystachio_to_thrift(job_command('echo hello world'))
convert_pystachio_to_thrift(job_command('echo {{mesos.user}}')
.bind(mesos = {'user': '{{mesos.role}}'}))
# unbound
with pytest.raises(InvalidConfig):
convert_pystachio_to_thrift(job_command('echo {{mesos.user}}'))
def test_cron_policy_alias():
cron_schedule = '*/10 * * * *'
CRON_HELLO_WORLD = HELLO_WORLD(cron_schedule=cron_schedule)
tti = convert_pystachio_to_thrift(CRON_HELLO_WORLD)
assert tti.cronSchedule == cron_schedule
assert tti.cronCollisionPolicy == CronCollisionPolicy.KILL_EXISTING
tti = convert_pystachio_to_thrift(CRON_HELLO_WORLD(cron_policy='RUN_OVERLAP'))
assert tti.cronSchedule == cron_schedule
assert tti.cronCollisionPolicy == CronCollisionPolicy.RUN_OVERLAP
tti = convert_pystachio_to_thrift(CRON_HELLO_WORLD(cron_collision_policy='RUN_OVERLAP'))
assert tti.cronSchedule == cron_schedule
assert tti.cronCollisionPolicy == CronCollisionPolicy.RUN_OVERLAP
with pytest.raises(ValueError):
tti = convert_pystachio_to_thrift(CRON_HELLO_WORLD(cron_policy='RUN_OVERLAP',
cron_collision_policy='RUN_OVERLAP'))
with pytest.raises(ValueError):
tti = convert_pystachio_to_thrift(CRON_HELLO_WORLD(cron_collision_policy='GARBAGE'))
def test_packages_in_config():
job = convert_pystachio_to_thrift(HELLO_WORLD, packages = [('alpha', 'beta', 1)])
assert job.instanceCount == 1
tti = job.taskConfig
assert len(tti.packages) == 1
pi = iter(tti.packages).next()
assert pi.role == 'alpha'
assert pi.name == 'beta'
assert pi.version == 1
def test_task_instance_from_job():
instance = task_instance_from_job(Job(health_check_interval_secs=30), 0)
assert instance is not None
def test_identifier_validation():
matcher = re.compile(GOOD_IDENTIFIER_PATTERN_PYTHON)
for identifier in VALID_IDENTIFIERS:
assert matcher.match(identifier)
for identifier in INVALID_IDENTIFIERS:
assert not matcher.match(identifier)
| 30.023041 | 92 | 0.702686 | import getpass
import re
from twitter.aurora.config import AuroraConfig
from twitter.aurora.config.schema.base import Job, SimpleTask
from twitter.aurora.config.thrift import (
convert as convert_pystachio_to_thrift,
InvalidConfig,
task_instance_from_job,
)
from twitter.thermos.config.schema import (
Process,
Resources,
Task,
)
from gen.twitter.aurora.constants import GOOD_IDENTIFIER_PATTERN_PYTHON
from gen.twitter.aurora.test.constants import (
INVALID_IDENTIFIERS,
VALID_IDENTIFIERS,
)
from gen.twitter.aurora.ttypes import (
CronCollisionPolicy,
JobKey,
Identity,
)
from pystachio import Map, String
from pystachio.naming import frozendict
import pytest
HELLO_WORLD = Job(
name = 'hello_world',
role = 'john_doe',
environment = 'staging66',
cluster = 'smf1-test',
task = Task(
name = 'main',
processes = [Process(name = 'hello_world', cmdline = 'echo {{mesos.instance}}')],
resources = Resources(cpu = 0.1, ram = 64 * 1048576, disk = 64 * 1048576),
)
)
def test_simple_config():
job = convert_pystachio_to_thrift(HELLO_WORLD)
assert job.instanceCount == 1
tti = job.taskConfig
assert job.key == JobKey(
role=HELLO_WORLD.role().get(),
environment=HELLO_WORLD.environment().get(),
name=HELLO_WORLD.name().get())
assert job.owner == Identity(role=HELLO_WORLD.role().get(), user=getpass.getuser())
assert job.cronSchedule == ''
assert tti.jobName == 'hello_world'
assert tti.isService == False
assert tti.numCpus == 0.1
assert tti.ramMb == 64
assert tti.diskMb == 64
assert tti.requestedPorts == set()
assert tti.production == False
assert tti.priority == 0
assert tti.maxTaskFailures == 1
assert tti.constraints == set()
assert tti.packages == set()
assert tti.environment == HELLO_WORLD.environment().get()
def test_config_with_options():
hwc = HELLO_WORLD(
production = True,
priority = 200,
service = True,
cron_policy = 'RUN_OVERLAP',
constraints = {
'dedicated': 'your_mom',
'cpu': 'x86_64'
},
environment = 'prod'
)
job = convert_pystachio_to_thrift(hwc)
assert job.instanceCount == 1
tti = job.taskConfig
assert tti.production == True
assert tti.priority == 200
assert tti.isService == True
assert job.cronCollisionPolicy == CronCollisionPolicy.RUN_OVERLAP
assert len(tti.constraints) == 2
assert tti.environment == 'prod'
assert job.key.environment == 'prod'
def test_config_with_ports():
hwc = HELLO_WORLD(
task = HELLO_WORLD.task()(
processes = [
Process(name = 'hello_world',
cmdline = 'echo {{thermos.ports[http]}} {{thermos.ports[admin]}}')
]
)
)
config = AuroraConfig(hwc)
job = config.job()
assert job.taskConfig.requestedPorts == set(['http', 'admin'])
def test_config_with_bad_resources():
MB = 1048576
hwtask = HELLO_WORLD.task()
convert_pystachio_to_thrift(HELLO_WORLD)
good_resources = [
Resources(cpu = 1.0, ram = 1 * MB, disk = 1 * MB)
]
bad_resources = [
Resources(cpu = 0, ram = 1 * MB, disk = 1 * MB),
Resources(cpu = 1, ram = 0 * MB, disk = 1 * MB),
Resources(cpu = 1, ram = 1 * MB, disk = 0 * MB),
Resources(cpu = 1, ram = 1 * MB - 1, disk = 1 * MB),
Resources(cpu = 1, ram = 1 * MB, disk = 1 * MB - 1)
]
for resource in good_resources:
convert_pystachio_to_thrift(HELLO_WORLD(task = hwtask(resources = resource)))
for resource in bad_resources:
with pytest.raises(ValueError):
convert_pystachio_to_thrift(HELLO_WORLD(task = hwtask(resources = resource)))
def test_config_with_task_links():
tl = Map(String, String)
unresolved_tl = {
'foo': 'http://%host%:{{thermos.ports[foo]}}',
'bar': 'http://%host%:{{thermos.ports[bar]}}/{{mesos.instance}}',
}
resolved_tl = {
'foo': 'http://%host%:%port:foo%',
'bar': 'http://%host%:%port:bar%/%shard_id%'
}
aurora_config = AuroraConfig(HELLO_WORLD(task_links = tl(unresolved_tl)))
assert aurora_config.task_links() == tl(resolved_tl)
assert aurora_config.job().taskConfig.taskLinks == frozendict(resolved_tl)
bad_tl = {
'foo': '{{thermos.ports.bad}}'
}
with pytest.raises(AuroraConfig.InvalidConfig):
AuroraConfig(HELLO_WORLD(task_links=tl(bad_tl))).job()
def test_unbound_references():
def job_command(cmdline):
return AuroraConfig(HELLO_WORLD(task = SimpleTask('hello_world', cmdline))).raw()
convert_pystachio_to_thrift(job_command('echo hello world'))
convert_pystachio_to_thrift(job_command('echo {{mesos.user}}')
.bind(mesos = {'user': '{{mesos.role}}'}))
with pytest.raises(InvalidConfig):
convert_pystachio_to_thrift(job_command('echo {{mesos.user}}'))
def test_cron_policy_alias():
cron_schedule = '*/10 * * * *'
CRON_HELLO_WORLD = HELLO_WORLD(cron_schedule=cron_schedule)
tti = convert_pystachio_to_thrift(CRON_HELLO_WORLD)
assert tti.cronSchedule == cron_schedule
assert tti.cronCollisionPolicy == CronCollisionPolicy.KILL_EXISTING
tti = convert_pystachio_to_thrift(CRON_HELLO_WORLD(cron_policy='RUN_OVERLAP'))
assert tti.cronSchedule == cron_schedule
assert tti.cronCollisionPolicy == CronCollisionPolicy.RUN_OVERLAP
tti = convert_pystachio_to_thrift(CRON_HELLO_WORLD(cron_collision_policy='RUN_OVERLAP'))
assert tti.cronSchedule == cron_schedule
assert tti.cronCollisionPolicy == CronCollisionPolicy.RUN_OVERLAP
with pytest.raises(ValueError):
tti = convert_pystachio_to_thrift(CRON_HELLO_WORLD(cron_policy='RUN_OVERLAP',
cron_collision_policy='RUN_OVERLAP'))
with pytest.raises(ValueError):
tti = convert_pystachio_to_thrift(CRON_HELLO_WORLD(cron_collision_policy='GARBAGE'))
def test_packages_in_config():
job = convert_pystachio_to_thrift(HELLO_WORLD, packages = [('alpha', 'beta', 1)])
assert job.instanceCount == 1
tti = job.taskConfig
assert len(tti.packages) == 1
pi = iter(tti.packages).next()
assert pi.role == 'alpha'
assert pi.name == 'beta'
assert pi.version == 1
def test_task_instance_from_job():
instance = task_instance_from_job(Job(health_check_interval_secs=30), 0)
assert instance is not None
def test_identifier_validation():
matcher = re.compile(GOOD_IDENTIFIER_PATTERN_PYTHON)
for identifier in VALID_IDENTIFIERS:
assert matcher.match(identifier)
for identifier in INVALID_IDENTIFIERS:
assert not matcher.match(identifier)
| true | true |
f7f6b5a8f70adbced21c4a3644fffbb128022d07 | 948 | py | Python | bot/database/video.py | TupaBan-Dev/jdan734-bot | 891238591477e81ab8bda3f29bb4bc10424f1588 | [
"MIT"
] | null | null | null | bot/database/video.py | TupaBan-Dev/jdan734-bot | 891238591477e81ab8bda3f29bb4bc10424f1588 | [
"MIT"
] | null | null | null | bot/database/video.py | TupaBan-Dev/jdan734-bot | 891238591477e81ab8bda3f29bb4bc10424f1588 | [
"MIT"
] | null | null | null | import json
from .connection import db, manager
from peewee import *
class Video(Model):
channelid = CharField()
link = CharField()
class Meta:
db_table = "videos"
database = db
primary_key = False
async def save(channelid, link):
links = list(await manager.execute(
Video.select()
.where(Video.channelid == channelid)
))
if len(links) > 0:
links = json.loads(links[0].link)[-15:]
links.append(link)
links_str = json.dumps(links)
await manager.execute(
Video.update(link=links_str)
.where(Video.channelid == channelid)
)
else:
links = [link]
links_str = json.dumps(links)
await manager.execute(
Video.insert(channelid=channelid,
link=links_str)
) | 23.121951 | 57 | 0.511603 | import json
from .connection import db, manager
from peewee import *
class Video(Model):
channelid = CharField()
link = CharField()
class Meta:
db_table = "videos"
database = db
primary_key = False
async def save(channelid, link):
links = list(await manager.execute(
Video.select()
.where(Video.channelid == channelid)
))
if len(links) > 0:
links = json.loads(links[0].link)[-15:]
links.append(link)
links_str = json.dumps(links)
await manager.execute(
Video.update(link=links_str)
.where(Video.channelid == channelid)
)
else:
links = [link]
links_str = json.dumps(links)
await manager.execute(
Video.insert(channelid=channelid,
link=links_str)
) | true | true |
f7f6b5c97f84d88ad8e10acea53d43063a3c9d24 | 3,086 | py | Python | idfy_rest_client/controllers/languages_controller.py | dealflowteam/Idfy | fa3918a6c54ea0eedb9146578645b7eb1755b642 | [
"MIT"
] | null | null | null | idfy_rest_client/controllers/languages_controller.py | dealflowteam/Idfy | fa3918a6c54ea0eedb9146578645b7eb1755b642 | [
"MIT"
] | null | null | null | idfy_rest_client/controllers/languages_controller.py | dealflowteam/Idfy | fa3918a6c54ea0eedb9146578645b7eb1755b642 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
idfy_rest_client.controllers.languages_controller
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ).
"""
from .base_controller import BaseController
from ..api_helper import APIHelper
from ..configuration import Configuration
from ..models.language_dto import LanguageDTO
class LanguagesController(BaseController):
"""A Controller to access Endpoints in the idfy_rest_client API."""
def list_all_languages(self):
"""Does a GET request to /text/languages.
Returns a list of all supported languages.
Returns:
LanguageDTO: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Prepare query URL
_query_builder = Configuration.get_base_uri()
_query_builder += '/text/languages'
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
_headers = {
'accept': 'application/json'
}
# Prepare and execute request
_request = self.http_client.get(_query_url, headers=_headers)
_context = self.execute_request(_request)
self.validate_response(_context)
# Return appropriate type
return APIHelper.json_deserialize(_context.response.raw_body, LanguageDTO.from_dictionary)
def retrieve_language(self,
id):
"""Does a GET request to /text/languages/{id}.
Retrieve language
Args:
id (int): TODO: type description here. Example:
Returns:
LanguageDTO: Response from the API. Success
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Validate required parameters
self.validate_parameters(id=id)
# Prepare query URL
_query_builder = Configuration.get_base_uri()
_query_builder += '/text/languages/{id}'
_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {
'id': id
})
_query_url = APIHelper.clean_url(_query_builder)
# Prepare headers
_headers = {
'accept': 'application/json'
}
# Prepare and execute request
_request = self.http_client.get(_query_url, headers=_headers)
_context = self.execute_request(_request)
self.validate_response(_context)
# Return appropriate type
return APIHelper.json_deserialize(_context.response.raw_body, LanguageDTO.from_dictionary)
| 32.145833 | 99 | 0.623461 |
from .base_controller import BaseController
from ..api_helper import APIHelper
from ..configuration import Configuration
from ..models.language_dto import LanguageDTO
class LanguagesController(BaseController):
def list_all_languages(self):
_query_builder = Configuration.get_base_uri()
_query_builder += '/text/languages'
_query_url = APIHelper.clean_url(_query_builder)
_headers = {
'accept': 'application/json'
}
_request = self.http_client.get(_query_url, headers=_headers)
_context = self.execute_request(_request)
self.validate_response(_context)
return APIHelper.json_deserialize(_context.response.raw_body, LanguageDTO.from_dictionary)
def retrieve_language(self,
id):
self.validate_parameters(id=id)
_query_builder = Configuration.get_base_uri()
_query_builder += '/text/languages/{id}'
_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {
'id': id
})
_query_url = APIHelper.clean_url(_query_builder)
_headers = {
'accept': 'application/json'
}
_request = self.http_client.get(_query_url, headers=_headers)
_context = self.execute_request(_request)
self.validate_response(_context)
return APIHelper.json_deserialize(_context.response.raw_body, LanguageDTO.from_dictionary)
| true | true |
f7f6b5e6470d609a34700ddcbffd64fa5e01b0c3 | 6,361 | py | Python | tests/test_utils_objects.py | Gallaecio/js2xml | d01b79e1a82de157deffcc1a22f4e0b6bfa07715 | [
"MIT"
] | null | null | null | tests/test_utils_objects.py | Gallaecio/js2xml | d01b79e1a82de157deffcc1a22f4e0b6bfa07715 | [
"MIT"
] | null | null | null | tests/test_utils_objects.py | Gallaecio/js2xml | d01b79e1a82de157deffcc1a22f4e0b6bfa07715 | [
"MIT"
] | null | null | null | import js2xml
from js2xml.utils.objects import findall, getall, make
from nose.tools import *
def test_json():
jscode_snippets = [
(
r"""
var arr1 = ["a","b","c"];
var arr2 = ["d","e","f"];
""",
[['a', 'b', 'c'],
['d', 'e', 'f']]
),
(
r"""
var arr1 = ["a", null, "c"];
var arr2 = [null, "e", null];
""",
[['a', None, 'c'],
[None, 'e', None]]
),
(
r"""
var arr1 = ["a", undefined, "c"];
var arr2 = [undefined, "e", null];
""",
[['a', 'undefined', 'c'],
['undefined', 'e', None]]
),
(
r"""
var i = -3.14;
""", []
),
(
r"""
money = {
'quarters': 20
};
""",
[{"quarters": 20}]
),
(
r"""
money = {
quarters: 20
};
""",
[{"quarters": 20}]
),
(
r"""
currency = 'USD',
money = {
"value": 20,
"currency": currency
};
""",
[{'currency': 'currency', 'value': 20}]
),
(
r"""
t = {a: "3", "b": 3, "3": 3.0};
""",
[{'3': 3.0, 'a': '3', 'b': 3}]
),
(
r"""
money = {
'quarters': 10,
'addQuarters': function(amount) {
this.quarters += amount;
}
};
money.addQuarters(10);
""",
[]
),
(
r"""
var money = {
'quarters': 10,
'something': [1,2,3,4],
'somethingelse': {'nested': [5,6,7,8]},
'addQuarters': function(amount) {
this.quarters += amount;
}
};
money.addQuarters(10);
""",
[[1,2,3,4], {'nested': [5,6,7,8]}]
),
(
r"""
var store = {
'apples': 10,
'carrots': [1,2,3,4],
'chicken': {'eggs': [5,6,7,8]}
};
""",
[{'apples': 10,
'carrots': [1, 2, 3, 4],
'chicken': {'eggs': [5, 6, 7, 8]}}]
),
(
r"""
var store1 = {
'apples': 10,
'carrots': [1,2,3,4],
'chicken': {'eggs': [5,6,7,8]}
};
var store2 = {
'tomatoes': 20,
'potatoes': [9, false, 7, 6],
'spinach': {'cans': [true, 2]}
};
""",
[{'apples': 10,
'carrots': [1, 2, 3, 4],
'chicken': {'eggs': [5, 6, 7, 8]}},
{'potatoes': [9, False, 7, 6],
'spinach': {'cans': [True, 2]},
'tomatoes': 20}]
),
]
for snippet, expected in jscode_snippets:
jsxml = js2xml.parse(snippet)
assert_list_equal(getall(jsxml, types=[dict, list]), expected)
def test_findall():
jscode_snippets = [
(
r"""
var arr1 = ["a","b","c"];
var arr2 = ["d","e","f"];
""",
'//array',
[dict, list],
[['a', 'b', 'c'],
['d', 'e', 'f']]
),
(
r"""
var arr1 = {"a": "b", "c": "d"};
var arr2 = {"e": 1, "f": 2};
""",
'//object',
[dict, list],
[{'a': 'b', 'c': 'd'},
{'e': 1, 'f': 2}]
),
]
for snippet, xp, types, expected in jscode_snippets:
js = js2xml.parse(snippet)
results = []
for r in js.xpath(xp):
results.extend(findall(r, types=types))
assert_list_equal([make(r) for r in results], expected)
def test_getall_complex():
jscode_snippets = [
(
r"""
var needleParam = needleParam || {};
needleParam.chatGroup = "test";
needleParam.productId = "6341292";
needleParam.productPrice = "EUR 138.53".replace("$","n_").replace(/,/g,"");
//Begin Needle (fan-sourcing platform) snippet
jQuery(document).ready(function(){
var e = document.createElement("script"); e.type = "text/javascript";
e.async = true;
e.src = document.location.protocol +
"//overstock.needle.com/needle_service.js?1"; document.body.appendChild(e);
});
// End Needle snippet
""",
[dict, list],
[{}],
),
(
r"""
var needleParam = needleParam || {};
needleParam.chatGroup = "test";
needleParam.productId = "6341292";
needleParam.productPrice = "EUR 138.53".replace("$","n_").replace(/,/g,"");
//Begin Needle (fan-sourcing platform) snippet
jQuery(document).ready(function(){
var e = document.createElement("script"); e.type = "text/javascript";
e.async = true;
e.src = document.location.protocol +
"//overstock.needle.com/needle_service.js?1"; document.body.appendChild(e);
});
// End Needle snippet
""",
[str],
['test',
'6341292',
'EUR 138.53',
'$',
'n_',
'',
'script',
'text/javascript',
'//overstock.needle.com/needle_service.js?1']
),
(
r"""
var needleParam = needleParam || {};
needleParam.chatGroup = "test";
needleParam.productId = "6341292";
needleParam.productPrice = "EUR 138.53".replace("$","n_").replace(/,/g,"");
//Begin Needle (fan-sourcing platform) snippet
jQuery(document).ready(function(){
var e = document.createElement("script"); e.type = "text/javascript";
e.async = true;
e.src = document.location.protocol +
"//overstock.needle.com/needle_service.js?1"; document.body.appendChild(e);
});
// End Needle snippet
""",
[bool],
[True]
),
]
for snippet, types, expected in jscode_snippets:
jsxml = js2xml.parse(snippet)
assert_list_equal(getall(jsxml, types=types), expected)
| 26.176955 | 88 | 0.394749 | import js2xml
from js2xml.utils.objects import findall, getall, make
from nose.tools import *
def test_json():
jscode_snippets = [
(
r"""
var arr1 = ["a","b","c"];
var arr2 = ["d","e","f"];
""",
[['a', 'b', 'c'],
['d', 'e', 'f']]
),
(
r"""
var arr1 = ["a", null, "c"];
var arr2 = [null, "e", null];
""",
[['a', None, 'c'],
[None, 'e', None]]
),
(
r"""
var arr1 = ["a", undefined, "c"];
var arr2 = [undefined, "e", null];
""",
[['a', 'undefined', 'c'],
['undefined', 'e', None]]
),
(
r"""
var i = -3.14;
""", []
),
(
r"""
money = {
'quarters': 20
};
""",
[{"quarters": 20}]
),
(
r"""
money = {
quarters: 20
};
""",
[{"quarters": 20}]
),
(
r"""
currency = 'USD',
money = {
"value": 20,
"currency": currency
};
""",
[{'currency': 'currency', 'value': 20}]
),
(
r"""
t = {a: "3", "b": 3, "3": 3.0};
""",
[{'3': 3.0, 'a': '3', 'b': 3}]
),
(
r"""
money = {
'quarters': 10,
'addQuarters': function(amount) {
this.quarters += amount;
}
};
money.addQuarters(10);
""",
[]
),
(
r"""
var money = {
'quarters': 10,
'something': [1,2,3,4],
'somethingelse': {'nested': [5,6,7,8]},
'addQuarters': function(amount) {
this.quarters += amount;
}
};
money.addQuarters(10);
""",
[[1,2,3,4], {'nested': [5,6,7,8]}]
),
(
r"""
var store = {
'apples': 10,
'carrots': [1,2,3,4],
'chicken': {'eggs': [5,6,7,8]}
};
""",
[{'apples': 10,
'carrots': [1, 2, 3, 4],
'chicken': {'eggs': [5, 6, 7, 8]}}]
),
(
r"""
var store1 = {
'apples': 10,
'carrots': [1,2,3,4],
'chicken': {'eggs': [5,6,7,8]}
};
var store2 = {
'tomatoes': 20,
'potatoes': [9, false, 7, 6],
'spinach': {'cans': [true, 2]}
};
""",
[{'apples': 10,
'carrots': [1, 2, 3, 4],
'chicken': {'eggs': [5, 6, 7, 8]}},
{'potatoes': [9, False, 7, 6],
'spinach': {'cans': [True, 2]},
'tomatoes': 20}]
),
]
for snippet, expected in jscode_snippets:
jsxml = js2xml.parse(snippet)
assert_list_equal(getall(jsxml, types=[dict, list]), expected)
def test_findall():
jscode_snippets = [
(
r"""
var arr1 = ["a","b","c"];
var arr2 = ["d","e","f"];
""",
'//array',
[dict, list],
[['a', 'b', 'c'],
['d', 'e', 'f']]
),
(
r"""
var arr1 = {"a": "b", "c": "d"};
var arr2 = {"e": 1, "f": 2};
""",
'//object',
[dict, list],
[{'a': 'b', 'c': 'd'},
{'e': 1, 'f': 2}]
),
]
for snippet, xp, types, expected in jscode_snippets:
js = js2xml.parse(snippet)
results = []
for r in js.xpath(xp):
results.extend(findall(r, types=types))
assert_list_equal([make(r) for r in results], expected)
def test_getall_complex():
jscode_snippets = [
(
r"""
var needleParam = needleParam || {};
needleParam.chatGroup = "test";
needleParam.productId = "6341292";
needleParam.productPrice = "EUR 138.53".replace("$","n_").replace(/,/g,"");
//Begin Needle (fan-sourcing platform) snippet
jQuery(document).ready(function(){
var e = document.createElement("script"); e.type = "text/javascript";
e.async = true;
e.src = document.location.protocol +
"//overstock.needle.com/needle_service.js?1"; document.body.appendChild(e);
});
// End Needle snippet
""",
[dict, list],
[{}],
),
(
r"""
var needleParam = needleParam || {};
needleParam.chatGroup = "test";
needleParam.productId = "6341292";
needleParam.productPrice = "EUR 138.53".replace("$","n_").replace(/,/g,"");
//Begin Needle (fan-sourcing platform) snippet
jQuery(document).ready(function(){
var e = document.createElement("script"); e.type = "text/javascript";
e.async = true;
e.src = document.location.protocol +
"//overstock.needle.com/needle_service.js?1"; document.body.appendChild(e);
});
// End Needle snippet
""",
[str],
['test',
'6341292',
'EUR 138.53',
'$',
'n_',
'',
'script',
'text/javascript',
'//overstock.needle.com/needle_service.js?1']
),
(
r"""
var needleParam = needleParam || {};
needleParam.chatGroup = "test";
needleParam.productId = "6341292";
needleParam.productPrice = "EUR 138.53".replace("$","n_").replace(/,/g,"");
//Begin Needle (fan-sourcing platform) snippet
jQuery(document).ready(function(){
var e = document.createElement("script"); e.type = "text/javascript";
e.async = true;
e.src = document.location.protocol +
"//overstock.needle.com/needle_service.js?1"; document.body.appendChild(e);
});
// End Needle snippet
""",
[bool],
[True]
),
]
for snippet, types, expected in jscode_snippets:
jsxml = js2xml.parse(snippet)
assert_list_equal(getall(jsxml, types=types), expected)
| true | true |
f7f6b617ea2ec3bd2e4b2852962c6b655eaf34c8 | 784 | py | Python | tests/standardise/surface/test_glasgow_licor.py | openghg/openghg | 9a05dd6fe3cee6123898b8f390cfaded08dbb408 | [
"Apache-2.0"
] | 5 | 2021-03-02T09:04:07.000Z | 2022-01-25T09:58:16.000Z | tests/standardise/surface/test_glasgow_licor.py | openghg/openghg | 9a05dd6fe3cee6123898b8f390cfaded08dbb408 | [
"Apache-2.0"
] | 229 | 2020-09-30T15:08:39.000Z | 2022-03-31T14:23:55.000Z | tests/standardise/surface/test_glasgow_licor.py | openghg/openghg | 9a05dd6fe3cee6123898b8f390cfaded08dbb408 | [
"Apache-2.0"
] | null | null | null | from helpers import get_mobile_datapath
from openghg.standardise.surface import parse_glasow_licor
from pandas import Timestamp
import pytest
def test_glasgow_licor_read():
test_data = get_mobile_datapath(filename="glasgow_licor_sample.txt")
data = parse_glasow_licor(filepath=test_data)
ch4_data = data["ch4"]["data"]
metadata = data["ch4"]["metadata"]
assert ch4_data.time[0] == Timestamp("2021-08-25T14:35:57")
assert ch4_data.longitude[0] == pytest.approx(-4.2321)
assert ch4_data.latitude[0] == pytest.approx(55.82689833)
assert ch4_data.ch4[0] == 13.43
assert metadata == {'units': 'ppb',
'notes': 'measurement value is methane enhancement over background',
'sampling_period': 'NOT_SET'}
| 35.636364 | 92 | 0.691327 | from helpers import get_mobile_datapath
from openghg.standardise.surface import parse_glasow_licor
from pandas import Timestamp
import pytest
def test_glasgow_licor_read():
test_data = get_mobile_datapath(filename="glasgow_licor_sample.txt")
data = parse_glasow_licor(filepath=test_data)
ch4_data = data["ch4"]["data"]
metadata = data["ch4"]["metadata"]
assert ch4_data.time[0] == Timestamp("2021-08-25T14:35:57")
assert ch4_data.longitude[0] == pytest.approx(-4.2321)
assert ch4_data.latitude[0] == pytest.approx(55.82689833)
assert ch4_data.ch4[0] == 13.43
assert metadata == {'units': 'ppb',
'notes': 'measurement value is methane enhancement over background',
'sampling_period': 'NOT_SET'}
| true | true |
f7f6b70fae9102a5808155e1b544ecf727dac1fd | 394 | py | Python | backend/users/migrations/0002_auto_20211031_1843.py | crowdbotics-apps/dot-31776 | 246413d282d3b6585e29c9580cb02a7adb8cde36 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | backend/users/migrations/0002_auto_20211031_1843.py | crowdbotics-apps/dot-31776 | 246413d282d3b6585e29c9580cb02a7adb8cde36 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | backend/users/migrations/0002_auto_20211031_1843.py | crowdbotics-apps/dot-31776 | 246413d282d3b6585e29c9580cb02a7adb8cde36 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | # Generated by Django 2.2.24 on 2021-10-31 18:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='name',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
| 20.736842 | 74 | 0.591371 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='name',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
| true | true |
f7f6b73cd72e26ba9973d9dab40b2aa2be25f903 | 606 | py | Python | 6. Abstraccion.py | elviscruz45/POOAlgoritmoPython | c1f94a67d553c15f59a092030e880681c0300212 | [
"MIT"
] | null | null | null | 6. Abstraccion.py | elviscruz45/POOAlgoritmoPython | c1f94a67d553c15f59a092030e880681c0300212 | [
"MIT"
] | null | null | null | 6. Abstraccion.py | elviscruz45/POOAlgoritmoPython | c1f94a67d553c15f59a092030e880681c0300212 | [
"MIT"
] | null | null | null | class Lavadora:
def __init__(self):
pass
def lavar(self, temperatura='caliente'):
self._llenar_tanque_de_agua(temperatura)
self._anadir_jabon()
self._lavar()
self._centrifugar()
def _llenar_tanque_de_agua(self, temperatura):
print(f'Llenando el tanque con agua {temperatura}')
def _anadir_jabon(self):
print('Anadiendo jabon')
def _lavar(self):
print('Lavando la ropa')
def _centrifugar(self):
print('Centrifugando la ropa')
if __name__ == '__main__':
lavadora = Lavadora()
lavadora.lavar()
| 22.444444 | 59 | 0.632013 | class Lavadora:
def __init__(self):
pass
def lavar(self, temperatura='caliente'):
self._llenar_tanque_de_agua(temperatura)
self._anadir_jabon()
self._lavar()
self._centrifugar()
def _llenar_tanque_de_agua(self, temperatura):
print(f'Llenando el tanque con agua {temperatura}')
def _anadir_jabon(self):
print('Anadiendo jabon')
def _lavar(self):
print('Lavando la ropa')
def _centrifugar(self):
print('Centrifugando la ropa')
if __name__ == '__main__':
lavadora = Lavadora()
lavadora.lavar()
| true | true |
f7f6b7a9f33de22cda2d034228d41b68c51d1248 | 1,977 | py | Python | tests/test_types.py | ddejohn/dork | 6ff877c721086c1f1d98a4592b8959ef17cb934e | [
"MIT"
] | 1 | 2021-07-28T21:23:53.000Z | 2021-07-28T21:23:53.000Z | tests/test_types.py | fbabonoy/dork | 6ff877c721086c1f1d98a4592b8959ef17cb934e | [
"MIT"
] | null | null | null | tests/test_types.py | fbabonoy/dork | 6ff877c721086c1f1d98a4592b8959ef17cb934e | [
"MIT"
] | 1 | 2021-06-09T03:09:06.000Z | 2021-06-09T03:09:06.000Z | # -*- coding: utf-8 -*-
"""Basic tests for state and entity relationships in dork"""
import dork.types as types
import dork.game_utils.factory_data as factory_data
# pylint: disable=protected-access
def test_confirm_method_blank(capsys, mocker):
"""confirm should do things"""
mocked_input = mocker.patch('builtins.input')
mocked_input.side_effect = ["bumblebee", "y", "tester"]
types.Game._confirm()
captured = capsys.readouterr()
assert "\n!!!WARNING!!! You will lose unsaved data!\n" in captured.out
assert "That is not a valid response!" in captured.out
assert mocked_input.call_count == 2
def test_start_over_no(capsys, mocker, game):
"""confirm should do things"""
mocked_input = mocker.patch('builtins.input')
mocked_input.side_effect = ["bumblebee", "n"]
assert game._start_over() == ("guess you changed your mind!", False)
captured = capsys.readouterr()
assert "\n!!!WARNING!!! You will lose unsaved data!\n" in captured.out
assert mocked_input.call_count == 2
def test_start_over_yes(capsys, mocker, game):
"""confirm should do things"""
# the call count here as 2 is a magic number need to document that
mocked_input = mocker.patch('builtins.input')
mocked_input.side_effect = ["y", "tester"]
game._start_over()
captured = capsys.readouterr()
assert "\n!!!WARNING!!! You will lose unsaved data!\n" in captured.out
assert mocked_input.call_count == 1
def test_move_method(game, cardinals):
"""testing the move function for any map"""
for direction in cardinals:
assert game._move(direction) in [
(game.hero.location.description, False),
(f"You cannot go {direction} from here.", False)
]
def test_mazefactory():
"""builds all game types"""
assert isinstance(factory_data.rules(0, 0), list)
assert isinstance(factory_data.stats("magic"), dict)
assert isinstance(types.MazeFactory.build(), dict)
| 32.409836 | 74 | 0.687911 |
import dork.types as types
import dork.game_utils.factory_data as factory_data
def test_confirm_method_blank(capsys, mocker):
mocked_input = mocker.patch('builtins.input')
mocked_input.side_effect = ["bumblebee", "y", "tester"]
types.Game._confirm()
captured = capsys.readouterr()
assert "\n!!!WARNING!!! You will lose unsaved data!\n" in captured.out
assert "That is not a valid response!" in captured.out
assert mocked_input.call_count == 2
def test_start_over_no(capsys, mocker, game):
mocked_input = mocker.patch('builtins.input')
mocked_input.side_effect = ["bumblebee", "n"]
assert game._start_over() == ("guess you changed your mind!", False)
captured = capsys.readouterr()
assert "\n!!!WARNING!!! You will lose unsaved data!\n" in captured.out
assert mocked_input.call_count == 2
def test_start_over_yes(capsys, mocker, game):
mocked_input = mocker.patch('builtins.input')
mocked_input.side_effect = ["y", "tester"]
game._start_over()
captured = capsys.readouterr()
assert "\n!!!WARNING!!! You will lose unsaved data!\n" in captured.out
assert mocked_input.call_count == 1
def test_move_method(game, cardinals):
for direction in cardinals:
assert game._move(direction) in [
(game.hero.location.description, False),
(f"You cannot go {direction} from here.", False)
]
def test_mazefactory():
assert isinstance(factory_data.rules(0, 0), list)
assert isinstance(factory_data.stats("magic"), dict)
assert isinstance(types.MazeFactory.build(), dict)
| true | true |
f7f6b99a2247e4df84c6ad297716a2120ebc6b55 | 3,832 | py | Python | cnn/genotypes.py | flymin/darts | 05b942e3535bcb87ff4ce86f8098ba63c48840c6 | [
"Apache-2.0"
] | 1 | 2020-04-17T11:39:26.000Z | 2020-04-17T11:39:26.000Z | cnn/genotypes.py | flymin/darts | 05b942e3535bcb87ff4ce86f8098ba63c48840c6 | [
"Apache-2.0"
] | null | null | null | cnn/genotypes.py | flymin/darts | 05b942e3535bcb87ff4ce86f8098ba63c48840c6 | [
"Apache-2.0"
] | null | null | null | from collections import namedtuple
Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat')
PRIMITIVES = [
'none',
'max_pool_3x3',
'avg_pool_3x3',
'skip_connect',
'sep_conv_3x3',
'sep_conv_5x5',
'dil_conv_3x3',
'dil_conv_5x5'
]
NASNet = Genotype(
normal = [
('sep_conv_5x5', 1),
('sep_conv_3x3', 0),
('sep_conv_5x5', 0),
('sep_conv_3x3', 0),
('avg_pool_3x3', 1),
('skip_connect', 0),
('avg_pool_3x3', 0),
('avg_pool_3x3', 0),
('sep_conv_3x3', 1),
('skip_connect', 1),
],
normal_concat = [2, 3, 4, 5, 6],
reduce = [
('sep_conv_5x5', 1),
('sep_conv_7x7', 0),
('max_pool_3x3', 1),
('sep_conv_7x7', 0),
('avg_pool_3x3', 1),
('sep_conv_5x5', 0),
('skip_connect', 3),
('avg_pool_3x3', 2),
('sep_conv_3x3', 2),
('max_pool_3x3', 1),
],
reduce_concat = [4, 5, 6],
)
AmoebaNet = Genotype(
normal = [
('avg_pool_3x3', 0),
('max_pool_3x3', 1),
('sep_conv_3x3', 0),
('sep_conv_5x5', 2),
('sep_conv_3x3', 0),
('avg_pool_3x3', 3),
('sep_conv_3x3', 1),
('skip_connect', 1),
('skip_connect', 0),
('avg_pool_3x3', 1),
],
normal_concat = [4, 5, 6],
reduce = [
('avg_pool_3x3', 0),
('sep_conv_3x3', 1),
('max_pool_3x3', 0),
('sep_conv_7x7', 2),
('sep_conv_7x7', 0),
('avg_pool_3x3', 1),
('max_pool_3x3', 0),
('max_pool_3x3', 1),
('conv_7x1_1x7', 0),
('sep_conv_3x3', 5),
],
reduce_concat = [3, 4, 6]
)
DARTS_V1 = Genotype(normal=[('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('skip_connect', 0), ('sep_conv_3x3', 1), ('skip_connect', 0), ('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('skip_connect', 2)], normal_concat=[2, 3, 4, 5], reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('skip_connect', 2), ('max_pool_3x3', 0), ('max_pool_3x3', 0), ('skip_connect', 2), ('skip_connect', 2), ('avg_pool_3x3', 0)], reduce_concat=[2, 3, 4, 5])
DARTS_V2 = Genotype(normal=[('sep_conv_3x3', 0), ('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('sep_conv_3x3', 1), ('sep_conv_3x3', 1), ('skip_connect', 0), ('skip_connect', 0), ('dil_conv_3x3', 2)], normal_concat=[2, 3, 4, 5], reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('skip_connect', 2), ('max_pool_3x3', 1), ('max_pool_3x3', 0), ('skip_connect', 2), ('skip_connect', 2), ('max_pool_3x3', 1)], reduce_concat=[2, 3, 4, 5])
DARTS = DARTS_V1
PDARTS = Genotype(normal=[('skip_connect', 0), ('dil_conv_3x3', 1), ('skip_connect', 0),('sep_conv_3x3', 1), ('sep_conv_3x3', 1), ('sep_conv_3x3', 3), ('sep_conv_3x3',0), ('dil_conv_5x5', 4)], normal_concat=range(2, 6), reduce=[('avg_pool_3x3', 0), ('sep_conv_5x5', 1), ('sep_conv_3x3', 0), ('dil_conv_5x5', 2), ('max_pool_3x3', 0), ('dil_conv_3x3', 1), ('dil_conv_3x3', 1), ('dil_conv_5x5', 3)], reduce_concat=range(2, 6))
PC_DARTS_cifar = Genotype(normal=[('sep_conv_3x3', 1), ('skip_connect', 0), ('sep_conv_3x3', 0), ('dil_conv_3x3', 1), ('sep_conv_5x5', 0), ('sep_conv_3x3', 1), ('avg_pool_3x3', 0), ('dil_conv_3x3', 1)], normal_concat=range(2, 6), reduce=[('sep_conv_5x5', 1), ('max_pool_3x3', 0), ('sep_conv_5x5', 1), ('sep_conv_5x5', 2), ('sep_conv_3x3', 0), ('sep_conv_3x3', 3), ('sep_conv_3x3', 1), ('sep_conv_3x3', 2)], reduce_concat=range(2, 6))
PC_DARTS_image = Genotype(normal=[('skip_connect', 1), ('sep_conv_3x3', 0), ('sep_conv_3x3', 0), ('skip_connect', 1), ('sep_conv_3x3', 1), ('sep_conv_3x3', 3), ('sep_conv_3x3', 1), ('dil_conv_5x5', 4)], normal_concat=range(2, 6), reduce=[('sep_conv_3x3', 0), ('skip_connect', 1), ('dil_conv_5x5', 2), ('max_pool_3x3', 1), ('sep_conv_3x3', 2), ('sep_conv_3x3', 1), ('sep_conv_5x5', 0), ('sep_conv_3x3', 3)], reduce_concat=range(2, 6))
AllNAS = [PC_DARTS_image,
PC_DARTS_image,
PC_DARTS_image,
PDARTS,
PDARTS] | 43.545455 | 433 | 0.596294 | from collections import namedtuple
Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat')
PRIMITIVES = [
'none',
'max_pool_3x3',
'avg_pool_3x3',
'skip_connect',
'sep_conv_3x3',
'sep_conv_5x5',
'dil_conv_3x3',
'dil_conv_5x5'
]
NASNet = Genotype(
normal = [
('sep_conv_5x5', 1),
('sep_conv_3x3', 0),
('sep_conv_5x5', 0),
('sep_conv_3x3', 0),
('avg_pool_3x3', 1),
('skip_connect', 0),
('avg_pool_3x3', 0),
('avg_pool_3x3', 0),
('sep_conv_3x3', 1),
('skip_connect', 1),
],
normal_concat = [2, 3, 4, 5, 6],
reduce = [
('sep_conv_5x5', 1),
('sep_conv_7x7', 0),
('max_pool_3x3', 1),
('sep_conv_7x7', 0),
('avg_pool_3x3', 1),
('sep_conv_5x5', 0),
('skip_connect', 3),
('avg_pool_3x3', 2),
('sep_conv_3x3', 2),
('max_pool_3x3', 1),
],
reduce_concat = [4, 5, 6],
)
AmoebaNet = Genotype(
normal = [
('avg_pool_3x3', 0),
('max_pool_3x3', 1),
('sep_conv_3x3', 0),
('sep_conv_5x5', 2),
('sep_conv_3x3', 0),
('avg_pool_3x3', 3),
('sep_conv_3x3', 1),
('skip_connect', 1),
('skip_connect', 0),
('avg_pool_3x3', 1),
],
normal_concat = [4, 5, 6],
reduce = [
('avg_pool_3x3', 0),
('sep_conv_3x3', 1),
('max_pool_3x3', 0),
('sep_conv_7x7', 2),
('sep_conv_7x7', 0),
('avg_pool_3x3', 1),
('max_pool_3x3', 0),
('max_pool_3x3', 1),
('conv_7x1_1x7', 0),
('sep_conv_3x3', 5),
],
reduce_concat = [3, 4, 6]
)
DARTS_V1 = Genotype(normal=[('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('skip_connect', 0), ('sep_conv_3x3', 1), ('skip_connect', 0), ('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('skip_connect', 2)], normal_concat=[2, 3, 4, 5], reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('skip_connect', 2), ('max_pool_3x3', 0), ('max_pool_3x3', 0), ('skip_connect', 2), ('skip_connect', 2), ('avg_pool_3x3', 0)], reduce_concat=[2, 3, 4, 5])
DARTS_V2 = Genotype(normal=[('sep_conv_3x3', 0), ('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('sep_conv_3x3', 1), ('sep_conv_3x3', 1), ('skip_connect', 0), ('skip_connect', 0), ('dil_conv_3x3', 2)], normal_concat=[2, 3, 4, 5], reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('skip_connect', 2), ('max_pool_3x3', 1), ('max_pool_3x3', 0), ('skip_connect', 2), ('skip_connect', 2), ('max_pool_3x3', 1)], reduce_concat=[2, 3, 4, 5])
DARTS = DARTS_V1
PDARTS = Genotype(normal=[('skip_connect', 0), ('dil_conv_3x3', 1), ('skip_connect', 0),('sep_conv_3x3', 1), ('sep_conv_3x3', 1), ('sep_conv_3x3', 3), ('sep_conv_3x3',0), ('dil_conv_5x5', 4)], normal_concat=range(2, 6), reduce=[('avg_pool_3x3', 0), ('sep_conv_5x5', 1), ('sep_conv_3x3', 0), ('dil_conv_5x5', 2), ('max_pool_3x3', 0), ('dil_conv_3x3', 1), ('dil_conv_3x3', 1), ('dil_conv_5x5', 3)], reduce_concat=range(2, 6))
PC_DARTS_cifar = Genotype(normal=[('sep_conv_3x3', 1), ('skip_connect', 0), ('sep_conv_3x3', 0), ('dil_conv_3x3', 1), ('sep_conv_5x5', 0), ('sep_conv_3x3', 1), ('avg_pool_3x3', 0), ('dil_conv_3x3', 1)], normal_concat=range(2, 6), reduce=[('sep_conv_5x5', 1), ('max_pool_3x3', 0), ('sep_conv_5x5', 1), ('sep_conv_5x5', 2), ('sep_conv_3x3', 0), ('sep_conv_3x3', 3), ('sep_conv_3x3', 1), ('sep_conv_3x3', 2)], reduce_concat=range(2, 6))
PC_DARTS_image = Genotype(normal=[('skip_connect', 1), ('sep_conv_3x3', 0), ('sep_conv_3x3', 0), ('skip_connect', 1), ('sep_conv_3x3', 1), ('sep_conv_3x3', 3), ('sep_conv_3x3', 1), ('dil_conv_5x5', 4)], normal_concat=range(2, 6), reduce=[('sep_conv_3x3', 0), ('skip_connect', 1), ('dil_conv_5x5', 2), ('max_pool_3x3', 1), ('sep_conv_3x3', 2), ('sep_conv_3x3', 1), ('sep_conv_5x5', 0), ('sep_conv_3x3', 3)], reduce_concat=range(2, 6))
AllNAS = [PC_DARTS_image,
PC_DARTS_image,
PC_DARTS_image,
PDARTS,
PDARTS] | true | true |
f7f6ba0f25c86f470f20030f3ca111068509131c | 9,579 | py | Python | codes/projects/test_continuous_parameter/utils_project/prediction_and_plotting_routine_vaeiaf.py | hwangoh/uq-vae | 382548e6f6dd7f9d72feff0e0752beec871db348 | [
"MIT"
] | 2 | 2021-07-28T16:47:18.000Z | 2021-08-03T00:53:58.000Z | codes/projects/test_discrete_parameter/utils_project/prediction_and_plotting_routine_vaeiaf.py | HwanGoh/uq-vae | 24a3d26987e2ec807d57601b14c68b22f3652a18 | [
"MIT"
] | null | null | null | codes/projects/test_discrete_parameter/utils_project/prediction_and_plotting_routine_vaeiaf.py | HwanGoh/uq-vae | 24a3d26987e2ec807d57601b14c68b22f3652a18 | [
"MIT"
] | 2 | 2021-09-29T08:31:46.000Z | 2021-11-07T10:26:45.000Z | '''Prediction and plotting routine
In preparation for prediction and plotting, this script will:
1) Load the obs_dimensions
2) Specify the input_dimensions and latent_dimensions
3) Instantiate the DataHandler class
4) Instantiate the neural network
5) Load the trained neural network weights
6) Select and prepare an illustrative test example
7) Draw from the predicted posterior by utilizing nn.iaf_chain_posterior as
well as the encoder
8) Predict the state using the draw from the posterior either using the
modelled or learned (decoder) parameter-to-observable map
9) Plot the prediction
Inputs:
- hyperp: dictionary storing set hyperparameter values
- options: dictionary storing the set options
- filepaths: instance of the FilePaths class storing the default strings for
importing and exporting required objects.
Author: Hwan Goh, Oden Institute, Austin, Texas 2020
'''
import sys
sys.path.append('../../../../..')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.ioff() # Turn interactive plotting off
# Import src code
from utils_data.data_handler import DataHandler
from neural_networks.nn_vaeiaf import VAEIAF
from utils_misc.positivity_constraints import positivity_constraint_log_exp
# Import FEM Code
from Finite_Element_Method.src.load_mesh import load_mesh
from utils_project.plot_fem_function import plot_fem_function
import pdb #Equivalent of keyboard in MATLAB, just add "pdb.set_trace()"
###############################################################################
# Plot Predictions #
###############################################################################
def predict_and_plot(hyperp, options, filepaths):
#=== Load Observation Indices ===#
if options.obs_type == 'full':
obs_dimensions = options.parameter_dimensions
if options.obs_type == 'obs':
obs_dimensions = options.num_obs_points
#=== Data and Latent Dimensions of Autoencoder ===#
input_dimensions = obs_dimensions
latent_dimensions = options.parameter_dimensions
#=== Prepare Data ===#
data = DataHandler(hyperp, options, filepaths,
options.parameter_dimensions, obs_dimensions)
data.load_data_test()
if options.add_noise == 1:
data.add_noise_qoi_test()
parameter_test = data.poi_test
state_obs_test = data.qoi_test
#=== Load Trained Neural Network ===#
nn = VAEIAF(hyperp, options,
input_dimensions, latent_dimensions,
None, None,
None, None,
positivity_constraint_log_exp)
nn.load_weights(filepaths.trained_nn)
#=== Selecting Samples ===#
sample_number = 105
parameter_test_sample = np.expand_dims(parameter_test[sample_number,:], 0)
state_obs_test_sample = np.expand_dims(state_obs_test[sample_number,:], 0)
#=== Predictions ===#
parameter_pred_sample, _ = nn.iaf_chain_posterior(
nn.encoder(state_obs_test_sample))
state_obs_pred_sample = nn.decoder(parameter_test_sample)
parameter_pred_sample = parameter_pred_sample.numpy().flatten()
state_obs_pred_sample = state_obs_pred_sample.numpy().flatten()
#=== Plotting Prediction ===#
print('================================')
print(' Plotting Predictions ')
print('================================')
#=== Load Mesh ===#
nodes, elements, _, _, _, _, _, _ = load_mesh(filepaths.project)
#=== Plot FEM Functions ===#
plot_fem_function(filepaths.figures_savefile_name_parameter_test,
'True Parameter', 7.0,
nodes, elements,
parameter_test_sample)
plot_fem_function(filepaths.figures_savefile_name_parameter_pred,
'Parameter Prediction', 7.0,
nodes, elements,
parameter_pred_sample)
if options.obs_type == 'full':
plot_fem_function(filepaths.figures_savefile_name_state_test,
'True State', 2.6,
nodes, elements,
state_obs_test_sample)
plot_fem_function(filepaths.figures_savefile_name_state_pred,
'State Prediction', 2.6,
nodes, elements,
state_obs_pred_sample)
print('Predictions plotted')
###############################################################################
# Plot Metrics #
###############################################################################
def plot_and_save_metrics(hyperp, options, filepaths):
print('================================')
print(' Plotting Metrics ')
print('================================')
#=== Load Metrics ===#
print('Loading Metrics')
df_metrics = pd.read_csv(filepaths.trained_nn + "_metrics" + '.csv')
array_metrics = df_metrics.to_numpy()
####################
# Load Metrics #
####################
storage_array_loss_train = array_metrics[:,0]
storage_array_loss_train_VAE = array_metrics[:,1]
storage_array_loss_train_encoder = array_metrics[:,2]
storage_array_relative_error_input_VAE = array_metrics[:,10]
storage_array_relative_error_latent_encoder = array_metrics[:,11]
storage_array_relative_error_input_decoder = array_metrics[:,12]
storage_array_relative_gradient_norm = array_metrics[:,13]
################
# Plotting #
################
#=== Loss Train ===#
fig_loss = plt.figure()
x_axis = np.linspace(1, hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, np.log(storage_array_loss_train))
plt.title('Log-Loss for Training Neural Network')
plt.xlabel('Epochs')
plt.ylabel('Log-Loss')
figures_savefile_name = filepaths.directory_figures + '/' +\
'loss.png'
plt.savefig(figures_savefile_name)
plt.close(fig_loss)
#=== Loss Autoencoder ===#
fig_loss = plt.figure()
x_axis = np.linspace(1, hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, np.log(storage_array_loss_train_VAE))
plt.title('Log-Loss for VAE')
plt.xlabel('Epochs')
plt.ylabel('Log-Loss')
figures_savefile_name = filepaths.directory_figures + '/' +\
'loss_autoencoder.png'
plt.savefig(figures_savefile_name)
plt.close(fig_loss)
#=== Loss Encoder ===#
fig_loss = plt.figure()
x_axis = np.linspace(1, hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, np.log(storage_array_loss_train_encoder))
plt.title('Log-Loss for Encoder')
plt.xlabel('Epochs')
plt.ylabel('Log-Loss')
figures_savefile_name = filepaths.directory_figures + '/' +\
'loss_encoder.png'
plt.savefig(figures_savefile_name)
plt.close(fig_loss)
#=== Relative Error Autoencoder ===#
fig_accuracy = plt.figure()
x_axis = np.linspace(1,hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, storage_array_relative_error_input_VAE)
plt.title('Relative Error for Autoencoder')
plt.xlabel('Epochs')
plt.ylabel('Relative Error')
figures_savefile_name = filepaths.directory_figures + '/' +\
'relative_error_autoencoder.png'
plt.savefig(figures_savefile_name)
plt.close(fig_accuracy)
#=== Relative Error Encoder ===#
fig_accuracy = plt.figure()
x_axis = np.linspace(1,hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, storage_array_relative_error_latent_encoder)
plt.title('Relative Error for Encoder')
plt.xlabel('Epochs')
plt.ylabel('Relative Error')
figures_savefile_name = filepaths.directory_figures + '/' +\
'relative_error_encoder.png'
plt.savefig(figures_savefile_name)
plt.close(fig_accuracy)
#=== Relative Error Decoder ===#
fig_accuracy = plt.figure()
x_axis = np.linspace(1,hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, storage_array_relative_error_input_decoder)
plt.title('Relative Error for Decoder')
plt.xlabel('Epochs')
plt.ylabel('Relative Error')
figures_savefile_name = filepaths.directory_figures + '/' +\
'relative_error_decoder.png'
plt.savefig(figures_savefile_name)
plt.close(fig_accuracy)
#=== Relative Gradient Norm ===#
fig_gradient_norm = plt.figure()
x_axis = np.linspace(1,hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, storage_array_relative_gradient_norm)
plt.title('Relative Gradient Norm')
plt.xlabel('Epochs')
plt.ylabel('Relative Error')
figures_savefile_name = filepaths.directory_figures + '/' +\
'relative_error_gradient_norm.png'
plt.savefig(figures_savefile_name)
plt.close(fig_gradient_norm)
if options.model_augmented == 1:
#=== Relative Error Decoder ===#
fig_loss = plt.figure()
x_axis = np.linspace(1,hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, storage_array_loss_train_forward_model)
plt.title('Log-loss Forward Model')
plt.xlabel('Epochs')
plt.ylabel('Relative Error')
figures_savefile_name = filepaths.directory_figures + '/' +\
'loss_forward_model.png'
plt.savefig(figures_savefile_name)
plt.close(fig_loss)
print('Plotting complete')
| 40.079498 | 85 | 0.63587 | import sys
sys.path.append('../../../../..')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.ioff()
from utils_data.data_handler import DataHandler
from neural_networks.nn_vaeiaf import VAEIAF
from utils_misc.positivity_constraints import positivity_constraint_log_exp
from Finite_Element_Method.src.load_mesh import load_mesh
from utils_project.plot_fem_function import plot_fem_function
import pdb
| true | true |
f7f6ba1394581664dde0de101e3300233906c804 | 1,160 | py | Python | vocannotation.py | fwgg8547/deeplean_mc | 1b858e59caf082df0cd4b1ca12dc21875fb00b26 | [
"MIT"
] | null | null | null | vocannotation.py | fwgg8547/deeplean_mc | 1b858e59caf082df0cd4b1ca12dc21875fb00b26 | [
"MIT"
] | null | null | null | vocannotation.py | fwgg8547/deeplean_mc | 1b858e59caf082df0cd4b1ca12dc21875fb00b26 | [
"MIT"
] | null | null | null | import xml.etree.ElementTree as ET
from os import getcwd
sets = ['train', 'val']
classes = ["skeleton",]
def convert_annotation(image_id, list_file):
print(image_id)
in_file = open('./data/mindata/Annotations/%s.xml'% image_id)
tree=ET.parse(in_file)
root = tree.getroot()
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult)==1:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))
list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))
wd = getcwd()
for image_set in sets:
image_ids = open('./data/mindata/ImageSets/Main/%s.txt'% image_set).read().strip().split()
list_file = open('%s.txt'% image_set, 'w')
for image_id in image_ids:
list_file.write('./data/mindata/JPEGImages/%s.jpg'% image_id)
convert_annotation(image_id, list_file)
list_file.write('\n')
list_file.close()
| 33.142857 | 136 | 0.625 | import xml.etree.ElementTree as ET
from os import getcwd
sets = ['train', 'val']
classes = ["skeleton",]
def convert_annotation(image_id, list_file):
print(image_id)
in_file = open('./data/mindata/Annotations/%s.xml'% image_id)
tree=ET.parse(in_file)
root = tree.getroot()
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult)==1:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))
list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))
wd = getcwd()
for image_set in sets:
image_ids = open('./data/mindata/ImageSets/Main/%s.txt'% image_set).read().strip().split()
list_file = open('%s.txt'% image_set, 'w')
for image_id in image_ids:
list_file.write('./data/mindata/JPEGImages/%s.jpg'% image_id)
convert_annotation(image_id, list_file)
list_file.write('\n')
list_file.close()
| true | true |
f7f6ba4a3242ab5fd3d0b25b52e8124848bf987b | 27,483 | py | Python | django_zero_downtime_migrations/backends/postgres/schema.py | getsentry/django-pg-zero-downtime-migrations | 62dacf9888f0012ab6aaf77a7dca30168bdaba52 | [
"MIT"
] | 376 | 2018-08-21T07:05:20.000Z | 2022-03-26T00:41:10.000Z | django_zero_downtime_migrations/backends/postgres/schema.py | getsentry/django-pg-zero-downtime-migrations | 62dacf9888f0012ab6aaf77a7dca30168bdaba52 | [
"MIT"
] | 17 | 2018-10-23T19:44:13.000Z | 2022-03-17T01:28:16.000Z | django_zero_downtime_migrations/backends/postgres/schema.py | getsentry/django-pg-zero-downtime-migrations | 62dacf9888f0012ab6aaf77a7dca30168bdaba52 | [
"MIT"
] | 17 | 2018-09-06T10:06:54.000Z | 2022-03-21T04:44:45.000Z | import re
import warnings
from contextlib import contextmanager
import django
from django.conf import settings
from django.db.backends.ddl_references import Statement
from django.db.backends.postgresql.schema import (
DatabaseSchemaEditor as PostgresDatabaseSchemaEditor
)
from django.utils.functional import cached_property
class Unsafe:
ADD_COLUMN_DEFAULT = (
"ADD COLUMN DEFAULT is unsafe operation\n"
"See details for safe alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#create-column-with-default"
)
ADD_COLUMN_NOT_NULL = (
"ADD COLUMN NOT NULL is unsafe operation\n"
"See details for safe alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#dealing-with-not-null-constraint"
)
ALTER_COLUMN_NOT_NULL = (
"ALTER COLUMN NOT NULL is unsafe operation\n"
"See details for safe alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#dealing-with-not-null-constraint"
)
ALTER_COLUMN_TYPE = (
"ALTER COLUMN TYPE is unsafe operation\n"
"See details for safe alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#dealing-with-alter-table-alter-column-type"
)
ADD_CONSTRAINT_EXCLUDE = (
"ADD CONSTRAINT EXCLUDE is unsafe operation\n"
"See details for safe alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#changes-for-working-logic"
)
ALTER_TABLE_RENAME = (
"ALTER TABLE RENAME is unsafe operation\n"
"See details for save alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#changes-for-working-logic"
)
ALTER_TABLE_SET_TABLESPACE = (
"ALTER TABLE SET TABLESPACE is unsafe operation\n"
"See details for save alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#changes-for-working-logic"
)
ALTER_TABLE_RENAME_COLUMN = (
"ALTER TABLE RENAME COLUMN is unsafe operation\n"
"See details for save alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#changes-for-working-logic"
)
class UnsafeOperationWarning(Warning):
pass
class UnsafeOperationException(Exception):
pass
class DummySQL:
def __mod__(self, other):
return DUMMY_SQL
def format(self, *args, **kwargs):
return DUMMY_SQL
DUMMY_SQL = DummySQL()
class MultiStatementSQL(list):
def __init__(self, obj, *args):
if args:
obj = [obj] + list(args)
super().__init__(obj)
def __str__(self):
return '\n'.join(s.rstrip(';') + ';' for s in self)
def __repr__(self):
return str(self)
def __mod__(self, other):
if other is DUMMY_SQL:
return DUMMY_SQL
if isinstance(other, (list, tuple)) and any(arg is DUMMY_SQL for arg in other):
return DUMMY_SQL
if isinstance(other, dict) and any(val is DUMMY_SQL for val in other.values()):
return DUMMY_SQL
return MultiStatementSQL(s % other for s in self)
def format(self, *args, **kwargs):
if any(arg is DUMMY_SQL for arg in args) or any(val is DUMMY_SQL for val in kwargs.values()):
return DUMMY_SQL
return MultiStatementSQL(s.format(*args, **kwargs) for s in self)
class PGLock:
def __init__(self, sql, use_timeouts=False, disable_statement_timeout=False):
self.sql = sql
if use_timeouts and disable_statement_timeout:
raise ValueError("Can't apply use_timeouts and disable_statement_timeout simultaneously.")
self.use_timeouts = use_timeouts
self.disable_statement_timeout = disable_statement_timeout
def __str__(self):
return self.sql
def __repr__(self):
return str(self)
def __mod__(self, other):
if other is DUMMY_SQL:
return DUMMY_SQL
if isinstance(other, (list, tuple)) and any(arg is DUMMY_SQL for arg in other):
return DUMMY_SQL
if isinstance(other, dict) and any(val is DUMMY_SQL for val in other.values()):
return DUMMY_SQL
return self.__class__(self.sql % other, self.use_timeouts, self.disable_statement_timeout)
def format(self, *args, **kwargs):
if any(arg is DUMMY_SQL for arg in args) or any(val is DUMMY_SQL for val in kwargs.values()):
return DUMMY_SQL
return self.__class__(self.sql.format(*args, **kwargs), self.use_timeouts, self.disable_statement_timeout)
class PGAccessExclusive(PGLock):
def __init__(self, sql, use_timeouts=True, disable_statement_timeout=False):
super().__init__(sql, use_timeouts, disable_statement_timeout)
class PGShareUpdateExclusive(PGLock):
pass
class DatabaseSchemaEditorMixin:
ZERO_TIMEOUT = '0ms'
USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER = 'USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER'
sql_get_lock_timeout = "SELECT setting || unit FROM pg_settings WHERE name = 'lock_timeout'"
sql_get_statement_timeout = "SELECT setting || unit FROM pg_settings WHERE name = 'statement_timeout'"
sql_set_lock_timeout = "SET lock_timeout TO '%(lock_timeout)s'"
sql_set_statement_timeout = "SET statement_timeout TO '%(statement_timeout)s'"
sql_create_sequence = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_create_sequence, use_timeouts=False)
sql_delete_sequence = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_sequence, use_timeouts=False)
sql_create_table = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_create_table, use_timeouts=False)
sql_delete_table = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_table, use_timeouts=False)
sql_rename_table = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_rename_table)
sql_retablespace_table = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_retablespace_table)
sql_create_column_inline_fk = None
sql_create_column = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_create_column)
sql_alter_column = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_alter_column)
sql_delete_column = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_column)
sql_rename_column = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_rename_column)
sql_create_check = MultiStatementSQL(
PGAccessExclusive("ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s) NOT VALID"),
PGShareUpdateExclusive("ALTER TABLE %(table)s VALIDATE CONSTRAINT %(name)s",
disable_statement_timeout=True),
)
sql_delete_check = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_check)
sql_create_unique = MultiStatementSQL(
PGShareUpdateExclusive("CREATE UNIQUE INDEX CONCURRENTLY %(name)s ON %(table)s (%(columns)s)",
disable_statement_timeout=True),
PGAccessExclusive("ALTER TABLE %(table)s ADD CONSTRAINT %(name)s UNIQUE USING INDEX %(name)s"),
)
sql_delete_unique = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_unique)
sql_create_fk = MultiStatementSQL(
PGAccessExclusive("ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) "
"REFERENCES %(to_table)s (%(to_column)s)%(deferrable)s NOT VALID"),
PGShareUpdateExclusive("ALTER TABLE %(table)s VALIDATE CONSTRAINT %(name)s",
disable_statement_timeout=True),
)
sql_delete_fk = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_fk)
sql_create_pk = MultiStatementSQL(
PGShareUpdateExclusive("CREATE UNIQUE INDEX CONCURRENTLY %(name)s ON %(table)s (%(columns)s)",
disable_statement_timeout=True),
PGAccessExclusive("ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY USING INDEX %(name)s"),
)
sql_delete_pk = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_pk)
sql_create_index = PGShareUpdateExclusive(
"CREATE INDEX CONCURRENTLY %(name)s ON %(table)s%(using)s (%(columns)s)%(extra)s%(condition)s",
disable_statement_timeout=True
)
if django.VERSION[:2] >= (3, 0):
sql_create_index_concurrently = PGShareUpdateExclusive(
PostgresDatabaseSchemaEditor.sql_create_index_concurrently,
disable_statement_timeout=True
)
sql_create_unique_index = PGShareUpdateExclusive(
"CREATE UNIQUE INDEX CONCURRENTLY %(name)s ON %(table)s (%(columns)s)%(condition)s",
disable_statement_timeout=True
)
sql_delete_index = PGShareUpdateExclusive("DROP INDEX CONCURRENTLY IF EXISTS %(name)s")
if django.VERSION[:2] >= (3, 0):
sql_delete_index_concurrently = PGShareUpdateExclusive(
PostgresDatabaseSchemaEditor.sql_delete_index_concurrently
)
_sql_table_count = "SELECT reltuples FROM pg_class WHERE oid = '%(table)s'::regclass"
_sql_check_notnull_constraint = (
"SELECT conname FROM pg_constraint "
"WHERE contype = 'c' "
"AND conrelid = '%(table)s'::regclass "
"AND conname LIKE '%%_notnull'"
"AND pg_get_constraintdef(oid) = replace('CHECK ((%(columns)s IS NOT NULL))', '\"', '')"
)
_sql_column_not_null_compatible_le_pg12 = MultiStatementSQL(
PGAccessExclusive("ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(column)s IS NOT NULL) NOT VALID"),
PGShareUpdateExclusive("ALTER TABLE %(table)s VALIDATE CONSTRAINT %(name)s",
disable_statement_timeout=True),
)
_sql_column_not_null_le_pg12_pg_attributes_for_root = MultiStatementSQL(
*_sql_column_not_null_compatible_le_pg12,
# pg_catalog.pg_attribute update require extra privileges
# that can be granted manually of already available for superusers
"UPDATE pg_catalog.pg_attribute SET attnotnull = TRUE "
"WHERE attrelid = '%(table)s'::regclass::oid AND attname = replace('%(column)s', '\"', '')",
PGAccessExclusive("ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"),
)
_sql_column_not_null = MultiStatementSQL(
*_sql_column_not_null_compatible_le_pg12,
PGAccessExclusive("ALTER TABLE %(table)s ALTER COLUMN %(column)s SET NOT NULL"),
PGAccessExclusive("ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"),
)
_varchar_type_regexp = re.compile(r'^varchar\((?P<max_length>\d+)\)$')
_numeric_type_regexp = re.compile(r'^numeric\((?P<precision>\d+), *(?P<scale>\d+)\)$')
@cached_property
def is_postgresql_12(self):
return self.connection.pg_version >= 120000
def __init__(self, connection, collect_sql=False, atomic=True):
# Disable atomic transactions as it can be reason of downtime or deadlock
# in case if you combine many operation in one migration module.
super().__init__(connection, collect_sql=collect_sql, atomic=False)
# Avoid using DUMMY_SQL in combined alters
connection.features.supports_combined_alters = False
# Get settings with defaults
self.LOCK_TIMEOUT = getattr(settings, "ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT", None)
self.STATEMENT_TIMEOUT = getattr(settings, "ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT", None)
self.FLEXIBLE_STATEMENT_TIMEOUT = getattr(
settings, "ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT", False)
if self.is_postgresql_12 and hasattr(settings, "ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL"):
warnings.warn(
'settings.ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL not applicable for postgres 12+. '
'Please remove this setting. If you migrated form old version, please move to NOT NULL constraint '
'from CHECK IS NOT NULL before with `migrate_isnotnull_check_constraints` management command.',
DeprecationWarning
)
self.USE_NOT_NULL = getattr(settings, "ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL", None)
self.RAISE_FOR_UNSAFE = getattr(settings, "ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE", False)
def execute(self, sql, params=()):
if sql is DUMMY_SQL:
return
statements = []
if isinstance(sql, MultiStatementSQL):
statements.extend(sql)
elif isinstance(sql, Statement) and isinstance(sql.template, MultiStatementSQL):
statements.extend(Statement(s, **sql.parts) for s in sql.template)
else:
statements.append(sql)
for statement in statements:
if isinstance(statement, PGLock):
use_timeouts = statement.use_timeouts
disable_statement_timeout = statement.disable_statement_timeout
statement = statement.sql
elif isinstance(statement, Statement) and isinstance(statement.template, PGLock):
use_timeouts = statement.template.use_timeouts
disable_statement_timeout = statement.template.disable_statement_timeout
statement = Statement(statement.template.sql, **statement.parts)
else:
use_timeouts = False
disable_statement_timeout = False
if use_timeouts:
with self._set_operation_timeout(self.STATEMENT_TIMEOUT, self.LOCK_TIMEOUT):
super().execute(statement, params)
elif disable_statement_timeout and self.FLEXIBLE_STATEMENT_TIMEOUT:
with self._set_operation_timeout(self.ZERO_TIMEOUT):
super().execute(statement, params)
else:
super().execute(statement, params)
@contextmanager
def _set_operation_timeout(self, statement_timeout=None, lock_timeout=None):
if self.collect_sql:
previous_statement_timeout = self.ZERO_TIMEOUT
previous_lock_timeout = self.ZERO_TIMEOUT
else:
with self.connection.cursor() as cursor:
cursor.execute(self.sql_get_statement_timeout)
previous_statement_timeout, = cursor.fetchone()
cursor.execute(self.sql_get_lock_timeout)
previous_lock_timeout, = cursor.fetchone()
if statement_timeout is not None:
self.execute(self.sql_set_statement_timeout % {"statement_timeout": statement_timeout})
if lock_timeout is not None:
self.execute(self.sql_set_lock_timeout % {"lock_timeout": lock_timeout})
yield
if statement_timeout is not None:
self.execute(self.sql_set_statement_timeout % {"statement_timeout": previous_statement_timeout})
if lock_timeout is not None:
self.execute(self.sql_set_lock_timeout % {"lock_timeout": previous_lock_timeout})
def _flush_deferred_sql(self):
"""As some alternative sql use deferred sql and deferred sql run after all operations in miration module
so good idea to run deferred sql as soon as possible to provide similar as possible state
between operations in migration module."""
for sql in self.deferred_sql:
self.execute(sql)
self.deferred_sql.clear()
def create_model(self, model):
super().create_model(model)
self._flush_deferred_sql()
def delete_model(self, model):
super().delete_model(model)
self._flush_deferred_sql()
def alter_index_together(self, model, old_index_together, new_index_together):
super().alter_index_together(model, old_index_together, new_index_together)
self._flush_deferred_sql()
def alter_unique_together(self, model, old_unique_together, new_unique_together):
super().alter_unique_together(model, old_unique_together, new_unique_together)
self._flush_deferred_sql()
def add_index(self, model, index, concurrently=False):
if django.VERSION[:2] >= (3, 0):
super().add_index(model, index, concurrently=concurrently)
else:
super().add_index(model, index)
self._flush_deferred_sql()
def remove_index(self, model, index, concurrently=False):
if django.VERSION[:2] >= (3, 0):
super().remove_index(model, index, concurrently=concurrently)
else:
super().remove_index(model, index)
self._flush_deferred_sql()
def add_constraint(self, model, constraint):
if django.VERSION[:2] >= (3, 0):
from django.contrib.postgres.constraints import ExclusionConstraint
if isinstance(constraint, ExclusionConstraint):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ADD_CONSTRAINT_EXCLUDE)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ADD_CONSTRAINT_EXCLUDE))
super().add_constraint(model, constraint)
self._flush_deferred_sql()
def remove_constraint(self, model, constraint):
super().remove_constraint(model, constraint)
self._flush_deferred_sql()
def add_field(self, model, field):
super().add_field(model, field)
self._flush_deferred_sql()
def remove_field(self, model, field):
super().remove_field(model, field)
self._flush_deferred_sql()
def alter_field(self, model, old_field, new_field, strict=False):
super().alter_field(model, old_field, new_field, strict)
self._flush_deferred_sql()
def alter_db_table(self, model, old_db_table, new_db_table):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ALTER_TABLE_RENAME)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ALTER_TABLE_RENAME))
super().alter_db_table(model, old_db_table, new_db_table)
self._flush_deferred_sql()
def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ALTER_TABLE_SET_TABLESPACE)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ALTER_TABLE_SET_TABLESPACE))
super().alter_db_tablespace(model, old_db_tablespace, new_db_tablespace)
self._flush_deferred_sql()
def _rename_field_sql(self, table, old_field, new_field, new_type):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ALTER_TABLE_RENAME_COLUMN)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ALTER_TABLE_RENAME_COLUMN))
return super()._rename_field_sql(table, old_field, new_field, new_type)
def _get_table_rows_count(self, model):
sql = self._sql_table_count % {"table": model._meta.db_table}
with self.connection.cursor() as cursor:
cursor.execute(sql)
rows_count, = cursor.fetchone()
return rows_count
def _use_pg_attribute_update_for_not_null(self):
return self.USE_NOT_NULL == self.USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER
def _use_check_constraint_for_not_null(self, model):
if self.USE_NOT_NULL is True:
return False
if self.USE_NOT_NULL is False:
return True
if isinstance(self.USE_NOT_NULL, int):
rows_count = self._get_table_rows_count(model)
if rows_count >= self.USE_NOT_NULL:
return True
return False
def _add_column_default(self):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ADD_COLUMN_DEFAULT)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ADD_COLUMN_DEFAULT))
return " DEFAULT %s"
def _add_column_not_null(self, model, field):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ADD_COLUMN_NOT_NULL)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ADD_COLUMN_NOT_NULL))
return " NOT NULL"
def _add_column_primary_key(self, model, field):
self.deferred_sql.append(self.sql_create_pk % {
"table": self.quote_name(model._meta.db_table),
"name": self.quote_name(self._create_index_name(model._meta.db_table, [field.column], suffix="_pk")),
"columns": self.quote_name(field.column),
})
return ""
def _add_column_unique(self, model, field):
self.deferred_sql.append(self._create_unique_sql(model, [field.column]))
return ""
def column_sql(self, model, field, include_default=False):
"""
Take a field and return its column definition.
The field must already have had set_attributes_from_name() called.
"""
if not include_default:
return super().column_sql(model, field, include_default)
# Get the column's type and use that as the basis of the SQL
db_params = field.db_parameters(connection=self.connection)
sql = db_params['type']
params = []
# Check for fields that aren't actually columns (e.g. M2M)
if sql is None:
return None, None
# Work out nullability
null = field.null
# If we were told to include a default value, do so
include_default = include_default and not self.skip_default(field)
if include_default:
default_value = self.effective_default(field)
if default_value is not None:
sql += self._add_column_default()
params += [default_value]
# Oracle treats the empty string ('') as null, so coerce the null
# option whenever '' is a possible value.
if (field.empty_strings_allowed and not field.primary_key and
self.connection.features.interprets_empty_strings_as_nulls):
null = True
if null and not self.connection.features.implied_column_null:
sql += " NULL"
elif not null:
sql += self._add_column_not_null(model, field)
# Primary key/unique outputs
if field.primary_key:
sql += self._add_column_primary_key(model, field)
elif field.unique:
sql += self._add_column_unique(model, field)
# Optionally add the tablespace if it's an implicitly indexed column
tablespace = field.db_tablespace or model._meta.db_tablespace
if tablespace and self.connection.features.supports_tablespaces and field.unique:
sql += " %s" % self.connection.ops.tablespace_sql(tablespace, inline=True)
# Return the sql
return sql, params
def _alter_column_set_not_null(self, model, new_field):
if not self.is_postgresql_12 and self.RAISE_FOR_UNSAFE and self.USE_NOT_NULL is None:
raise UnsafeOperationException(Unsafe.ALTER_COLUMN_NOT_NULL)
elif self.is_postgresql_12:
self.deferred_sql.append(self._sql_column_not_null % {
"column": self.quote_name(new_field.column),
"table": self.quote_name(model._meta.db_table),
"name": self.quote_name(
self._create_index_name(model._meta.db_table, [new_field.column], suffix="_notnull")
),
})
return DUMMY_SQL, []
elif self._use_pg_attribute_update_for_not_null():
self.deferred_sql.append(self._sql_column_not_null_le_pg12_pg_attributes_for_root % {
"column": self.quote_name(new_field.column),
"table": self.quote_name(model._meta.db_table),
"name": self.quote_name(
self._create_index_name(model._meta.db_table, [new_field.column], suffix="_notnull")
),
})
return DUMMY_SQL, []
elif self._use_check_constraint_for_not_null(model):
self.deferred_sql.append(self._sql_column_not_null_compatible_le_pg12 % {
"column": self.quote_name(new_field.column),
"table": self.quote_name(model._meta.db_table),
"name": self.quote_name(
self._create_index_name(model._meta.db_table, [new_field.column], suffix="_notnull")
),
})
return DUMMY_SQL, []
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ALTER_COLUMN_NOT_NULL))
return self.sql_alter_column_not_null % {
"column": self.quote_name(new_field.column),
}, []
def _alter_column_drop_not_null(self, model, new_field):
with self.connection.cursor() as cursor:
cursor.execute(self._sql_check_notnull_constraint % {
"table": self.quote_name(model._meta.db_table),
"columns": self.quote_name(new_field.column),
})
result = cursor.fetchone()
if result:
constraint_name, = result
self.deferred_sql.append(self.sql_delete_check % {
"table": self.quote_name(model._meta.db_table),
"name": constraint_name,
})
else:
return self.sql_alter_column_null % {
"column": self.quote_name(new_field.column),
}, []
def _alter_column_null_sql(self, model, old_field, new_field):
if new_field.null:
return self._alter_column_drop_not_null(model, new_field)
else:
return self._alter_column_set_not_null(model, new_field)
def _immediate_type_cast(self, old_type, new_type):
old_type_varchar_match = self._varchar_type_regexp.match(old_type)
if old_type_varchar_match:
if new_type == "text":
return True
new_type_varchar_match = self._varchar_type_regexp.match(new_type)
if new_type_varchar_match:
old_type_max_length = int(old_type_varchar_match.group("max_length"))
new_type_max_length = int(new_type_varchar_match.group("max_length"))
if new_type_max_length >= old_type_max_length:
return True
else:
return False
old_type_numeric_match = self._numeric_type_regexp.match(old_type)
if old_type_numeric_match:
new_type_numeric_match = self._numeric_type_regexp.match(new_type)
old_type_precision = int(old_type_numeric_match.group("precision"))
old_type_scale = int(old_type_numeric_match.group("scale"))
try:
new_type_precision = int(new_type_numeric_match.group("precision"))
new_type_scale = int(new_type_numeric_match.group("scale"))
except AttributeError:
return False
return new_type_precision >= old_type_precision and new_type_scale == old_type_scale
return False
def _alter_column_type_sql(self, model, old_field, new_field, new_type):
old_db_params = old_field.db_parameters(connection=self.connection)
old_type = old_db_params["type"]
if not self._immediate_type_cast(old_type, new_type):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ALTER_COLUMN_TYPE)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ALTER_COLUMN_TYPE))
return super()._alter_column_type_sql(model, old_field, new_field, new_type)
class DatabaseSchemaEditor(DatabaseSchemaEditorMixin, PostgresDatabaseSchemaEditor):
pass
| 45.426446 | 116 | 0.6762 | import re
import warnings
from contextlib import contextmanager
import django
from django.conf import settings
from django.db.backends.ddl_references import Statement
from django.db.backends.postgresql.schema import (
DatabaseSchemaEditor as PostgresDatabaseSchemaEditor
)
from django.utils.functional import cached_property
class Unsafe:
ADD_COLUMN_DEFAULT = (
"ADD COLUMN DEFAULT is unsafe operation\n"
"See details for safe alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#create-column-with-default"
)
ADD_COLUMN_NOT_NULL = (
"ADD COLUMN NOT NULL is unsafe operation\n"
"See details for safe alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#dealing-with-not-null-constraint"
)
ALTER_COLUMN_NOT_NULL = (
"ALTER COLUMN NOT NULL is unsafe operation\n"
"See details for safe alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#dealing-with-not-null-constraint"
)
ALTER_COLUMN_TYPE = (
"ALTER COLUMN TYPE is unsafe operation\n"
"See details for safe alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#dealing-with-alter-table-alter-column-type"
)
ADD_CONSTRAINT_EXCLUDE = (
"ADD CONSTRAINT EXCLUDE is unsafe operation\n"
"See details for safe alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#changes-for-working-logic"
)
ALTER_TABLE_RENAME = (
"ALTER TABLE RENAME is unsafe operation\n"
"See details for save alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#changes-for-working-logic"
)
ALTER_TABLE_SET_TABLESPACE = (
"ALTER TABLE SET TABLESPACE is unsafe operation\n"
"See details for save alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#changes-for-working-logic"
)
ALTER_TABLE_RENAME_COLUMN = (
"ALTER TABLE RENAME COLUMN is unsafe operation\n"
"See details for save alternative "
"https://github.com/tbicr/django-pg-zero-downtime-migrations#changes-for-working-logic"
)
class UnsafeOperationWarning(Warning):
pass
class UnsafeOperationException(Exception):
pass
class DummySQL:
def __mod__(self, other):
return DUMMY_SQL
def format(self, *args, **kwargs):
return DUMMY_SQL
DUMMY_SQL = DummySQL()
class MultiStatementSQL(list):
def __init__(self, obj, *args):
if args:
obj = [obj] + list(args)
super().__init__(obj)
def __str__(self):
return '\n'.join(s.rstrip(';') + ';' for s in self)
def __repr__(self):
return str(self)
def __mod__(self, other):
if other is DUMMY_SQL:
return DUMMY_SQL
if isinstance(other, (list, tuple)) and any(arg is DUMMY_SQL for arg in other):
return DUMMY_SQL
if isinstance(other, dict) and any(val is DUMMY_SQL for val in other.values()):
return DUMMY_SQL
return MultiStatementSQL(s % other for s in self)
def format(self, *args, **kwargs):
if any(arg is DUMMY_SQL for arg in args) or any(val is DUMMY_SQL for val in kwargs.values()):
return DUMMY_SQL
return MultiStatementSQL(s.format(*args, **kwargs) for s in self)
class PGLock:
def __init__(self, sql, use_timeouts=False, disable_statement_timeout=False):
self.sql = sql
if use_timeouts and disable_statement_timeout:
raise ValueError("Can't apply use_timeouts and disable_statement_timeout simultaneously.")
self.use_timeouts = use_timeouts
self.disable_statement_timeout = disable_statement_timeout
def __str__(self):
return self.sql
def __repr__(self):
return str(self)
def __mod__(self, other):
if other is DUMMY_SQL:
return DUMMY_SQL
if isinstance(other, (list, tuple)) and any(arg is DUMMY_SQL for arg in other):
return DUMMY_SQL
if isinstance(other, dict) and any(val is DUMMY_SQL for val in other.values()):
return DUMMY_SQL
return self.__class__(self.sql % other, self.use_timeouts, self.disable_statement_timeout)
def format(self, *args, **kwargs):
if any(arg is DUMMY_SQL for arg in args) or any(val is DUMMY_SQL for val in kwargs.values()):
return DUMMY_SQL
return self.__class__(self.sql.format(*args, **kwargs), self.use_timeouts, self.disable_statement_timeout)
class PGAccessExclusive(PGLock):
def __init__(self, sql, use_timeouts=True, disable_statement_timeout=False):
super().__init__(sql, use_timeouts, disable_statement_timeout)
class PGShareUpdateExclusive(PGLock):
pass
class DatabaseSchemaEditorMixin:
ZERO_TIMEOUT = '0ms'
USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER = 'USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER'
sql_get_lock_timeout = "SELECT setting || unit FROM pg_settings WHERE name = 'lock_timeout'"
sql_get_statement_timeout = "SELECT setting || unit FROM pg_settings WHERE name = 'statement_timeout'"
sql_set_lock_timeout = "SET lock_timeout TO '%(lock_timeout)s'"
sql_set_statement_timeout = "SET statement_timeout TO '%(statement_timeout)s'"
sql_create_sequence = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_create_sequence, use_timeouts=False)
sql_delete_sequence = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_sequence, use_timeouts=False)
sql_create_table = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_create_table, use_timeouts=False)
sql_delete_table = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_table, use_timeouts=False)
sql_rename_table = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_rename_table)
sql_retablespace_table = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_retablespace_table)
sql_create_column_inline_fk = None
sql_create_column = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_create_column)
sql_alter_column = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_alter_column)
sql_delete_column = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_column)
sql_rename_column = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_rename_column)
sql_create_check = MultiStatementSQL(
PGAccessExclusive("ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s) NOT VALID"),
PGShareUpdateExclusive("ALTER TABLE %(table)s VALIDATE CONSTRAINT %(name)s",
disable_statement_timeout=True),
)
sql_delete_check = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_check)
sql_create_unique = MultiStatementSQL(
PGShareUpdateExclusive("CREATE UNIQUE INDEX CONCURRENTLY %(name)s ON %(table)s (%(columns)s)",
disable_statement_timeout=True),
PGAccessExclusive("ALTER TABLE %(table)s ADD CONSTRAINT %(name)s UNIQUE USING INDEX %(name)s"),
)
sql_delete_unique = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_unique)
sql_create_fk = MultiStatementSQL(
PGAccessExclusive("ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) "
"REFERENCES %(to_table)s (%(to_column)s)%(deferrable)s NOT VALID"),
PGShareUpdateExclusive("ALTER TABLE %(table)s VALIDATE CONSTRAINT %(name)s",
disable_statement_timeout=True),
)
sql_delete_fk = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_fk)
sql_create_pk = MultiStatementSQL(
PGShareUpdateExclusive("CREATE UNIQUE INDEX CONCURRENTLY %(name)s ON %(table)s (%(columns)s)",
disable_statement_timeout=True),
PGAccessExclusive("ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY USING INDEX %(name)s"),
)
sql_delete_pk = PGAccessExclusive(PostgresDatabaseSchemaEditor.sql_delete_pk)
sql_create_index = PGShareUpdateExclusive(
"CREATE INDEX CONCURRENTLY %(name)s ON %(table)s%(using)s (%(columns)s)%(extra)s%(condition)s",
disable_statement_timeout=True
)
if django.VERSION[:2] >= (3, 0):
sql_create_index_concurrently = PGShareUpdateExclusive(
PostgresDatabaseSchemaEditor.sql_create_index_concurrently,
disable_statement_timeout=True
)
sql_create_unique_index = PGShareUpdateExclusive(
"CREATE UNIQUE INDEX CONCURRENTLY %(name)s ON %(table)s (%(columns)s)%(condition)s",
disable_statement_timeout=True
)
sql_delete_index = PGShareUpdateExclusive("DROP INDEX CONCURRENTLY IF EXISTS %(name)s")
if django.VERSION[:2] >= (3, 0):
sql_delete_index_concurrently = PGShareUpdateExclusive(
PostgresDatabaseSchemaEditor.sql_delete_index_concurrently
)
_sql_table_count = "SELECT reltuples FROM pg_class WHERE oid = '%(table)s'::regclass"
_sql_check_notnull_constraint = (
"SELECT conname FROM pg_constraint "
"WHERE contype = 'c' "
"AND conrelid = '%(table)s'::regclass "
"AND conname LIKE '%%_notnull'"
"AND pg_get_constraintdef(oid) = replace('CHECK ((%(columns)s IS NOT NULL))', '\"', '')"
)
_sql_column_not_null_compatible_le_pg12 = MultiStatementSQL(
PGAccessExclusive("ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(column)s IS NOT NULL) NOT VALID"),
PGShareUpdateExclusive("ALTER TABLE %(table)s VALIDATE CONSTRAINT %(name)s",
disable_statement_timeout=True),
)
_sql_column_not_null_le_pg12_pg_attributes_for_root = MultiStatementSQL(
*_sql_column_not_null_compatible_le_pg12,
# pg_catalog.pg_attribute update require extra privileges
# that can be granted manually of already available for superusers
"UPDATE pg_catalog.pg_attribute SET attnotnull = TRUE "
"WHERE attrelid = '%(table)s'::regclass::oid AND attname = replace('%(column)s', '\"', '')",
PGAccessExclusive("ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"),
)
_sql_column_not_null = MultiStatementSQL(
*_sql_column_not_null_compatible_le_pg12,
PGAccessExclusive("ALTER TABLE %(table)s ALTER COLUMN %(column)s SET NOT NULL"),
PGAccessExclusive("ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"),
)
_varchar_type_regexp = re.compile(r'^varchar\((?P<max_length>\d+)\)$')
_numeric_type_regexp = re.compile(r'^numeric\((?P<precision>\d+), *(?P<scale>\d+)\)$')
@cached_property
def is_postgresql_12(self):
return self.connection.pg_version >= 120000
def __init__(self, connection, collect_sql=False, atomic=True):
# Disable atomic transactions as it can be reason of downtime or deadlock
# in case if you combine many operation in one migration module.
super().__init__(connection, collect_sql=collect_sql, atomic=False)
# Avoid using DUMMY_SQL in combined alters
connection.features.supports_combined_alters = False
# Get settings with defaults
self.LOCK_TIMEOUT = getattr(settings, "ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT", None)
self.STATEMENT_TIMEOUT = getattr(settings, "ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT", None)
self.FLEXIBLE_STATEMENT_TIMEOUT = getattr(
settings, "ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT", False)
if self.is_postgresql_12 and hasattr(settings, "ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL"):
warnings.warn(
'settings.ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL not applicable for postgres 12+. '
'Please remove this setting. If you migrated form old version, please move to NOT NULL constraint '
'from CHECK IS NOT NULL before with `migrate_isnotnull_check_constraints` management command.',
DeprecationWarning
)
self.USE_NOT_NULL = getattr(settings, "ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL", None)
self.RAISE_FOR_UNSAFE = getattr(settings, "ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE", False)
def execute(self, sql, params=()):
if sql is DUMMY_SQL:
return
statements = []
if isinstance(sql, MultiStatementSQL):
statements.extend(sql)
elif isinstance(sql, Statement) and isinstance(sql.template, MultiStatementSQL):
statements.extend(Statement(s, **sql.parts) for s in sql.template)
else:
statements.append(sql)
for statement in statements:
if isinstance(statement, PGLock):
use_timeouts = statement.use_timeouts
disable_statement_timeout = statement.disable_statement_timeout
statement = statement.sql
elif isinstance(statement, Statement) and isinstance(statement.template, PGLock):
use_timeouts = statement.template.use_timeouts
disable_statement_timeout = statement.template.disable_statement_timeout
statement = Statement(statement.template.sql, **statement.parts)
else:
use_timeouts = False
disable_statement_timeout = False
if use_timeouts:
with self._set_operation_timeout(self.STATEMENT_TIMEOUT, self.LOCK_TIMEOUT):
super().execute(statement, params)
elif disable_statement_timeout and self.FLEXIBLE_STATEMENT_TIMEOUT:
with self._set_operation_timeout(self.ZERO_TIMEOUT):
super().execute(statement, params)
else:
super().execute(statement, params)
@contextmanager
def _set_operation_timeout(self, statement_timeout=None, lock_timeout=None):
if self.collect_sql:
previous_statement_timeout = self.ZERO_TIMEOUT
previous_lock_timeout = self.ZERO_TIMEOUT
else:
with self.connection.cursor() as cursor:
cursor.execute(self.sql_get_statement_timeout)
previous_statement_timeout, = cursor.fetchone()
cursor.execute(self.sql_get_lock_timeout)
previous_lock_timeout, = cursor.fetchone()
if statement_timeout is not None:
self.execute(self.sql_set_statement_timeout % {"statement_timeout": statement_timeout})
if lock_timeout is not None:
self.execute(self.sql_set_lock_timeout % {"lock_timeout": lock_timeout})
yield
if statement_timeout is not None:
self.execute(self.sql_set_statement_timeout % {"statement_timeout": previous_statement_timeout})
if lock_timeout is not None:
self.execute(self.sql_set_lock_timeout % {"lock_timeout": previous_lock_timeout})
def _flush_deferred_sql(self):
for sql in self.deferred_sql:
self.execute(sql)
self.deferred_sql.clear()
def create_model(self, model):
super().create_model(model)
self._flush_deferred_sql()
def delete_model(self, model):
super().delete_model(model)
self._flush_deferred_sql()
def alter_index_together(self, model, old_index_together, new_index_together):
super().alter_index_together(model, old_index_together, new_index_together)
self._flush_deferred_sql()
def alter_unique_together(self, model, old_unique_together, new_unique_together):
super().alter_unique_together(model, old_unique_together, new_unique_together)
self._flush_deferred_sql()
def add_index(self, model, index, concurrently=False):
if django.VERSION[:2] >= (3, 0):
super().add_index(model, index, concurrently=concurrently)
else:
super().add_index(model, index)
self._flush_deferred_sql()
def remove_index(self, model, index, concurrently=False):
if django.VERSION[:2] >= (3, 0):
super().remove_index(model, index, concurrently=concurrently)
else:
super().remove_index(model, index)
self._flush_deferred_sql()
def add_constraint(self, model, constraint):
if django.VERSION[:2] >= (3, 0):
from django.contrib.postgres.constraints import ExclusionConstraint
if isinstance(constraint, ExclusionConstraint):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ADD_CONSTRAINT_EXCLUDE)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ADD_CONSTRAINT_EXCLUDE))
super().add_constraint(model, constraint)
self._flush_deferred_sql()
def remove_constraint(self, model, constraint):
super().remove_constraint(model, constraint)
self._flush_deferred_sql()
def add_field(self, model, field):
super().add_field(model, field)
self._flush_deferred_sql()
def remove_field(self, model, field):
super().remove_field(model, field)
self._flush_deferred_sql()
def alter_field(self, model, old_field, new_field, strict=False):
super().alter_field(model, old_field, new_field, strict)
self._flush_deferred_sql()
def alter_db_table(self, model, old_db_table, new_db_table):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ALTER_TABLE_RENAME)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ALTER_TABLE_RENAME))
super().alter_db_table(model, old_db_table, new_db_table)
self._flush_deferred_sql()
def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ALTER_TABLE_SET_TABLESPACE)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ALTER_TABLE_SET_TABLESPACE))
super().alter_db_tablespace(model, old_db_tablespace, new_db_tablespace)
self._flush_deferred_sql()
def _rename_field_sql(self, table, old_field, new_field, new_type):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ALTER_TABLE_RENAME_COLUMN)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ALTER_TABLE_RENAME_COLUMN))
return super()._rename_field_sql(table, old_field, new_field, new_type)
def _get_table_rows_count(self, model):
sql = self._sql_table_count % {"table": model._meta.db_table}
with self.connection.cursor() as cursor:
cursor.execute(sql)
rows_count, = cursor.fetchone()
return rows_count
def _use_pg_attribute_update_for_not_null(self):
return self.USE_NOT_NULL == self.USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER
def _use_check_constraint_for_not_null(self, model):
if self.USE_NOT_NULL is True:
return False
if self.USE_NOT_NULL is False:
return True
if isinstance(self.USE_NOT_NULL, int):
rows_count = self._get_table_rows_count(model)
if rows_count >= self.USE_NOT_NULL:
return True
return False
def _add_column_default(self):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ADD_COLUMN_DEFAULT)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ADD_COLUMN_DEFAULT))
return " DEFAULT %s"
def _add_column_not_null(self, model, field):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ADD_COLUMN_NOT_NULL)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ADD_COLUMN_NOT_NULL))
return " NOT NULL"
def _add_column_primary_key(self, model, field):
self.deferred_sql.append(self.sql_create_pk % {
"table": self.quote_name(model._meta.db_table),
"name": self.quote_name(self._create_index_name(model._meta.db_table, [field.column], suffix="_pk")),
"columns": self.quote_name(field.column),
})
return ""
def _add_column_unique(self, model, field):
self.deferred_sql.append(self._create_unique_sql(model, [field.column]))
return ""
def column_sql(self, model, field, include_default=False):
if not include_default:
return super().column_sql(model, field, include_default)
# Get the column's type and use that as the basis of the SQL
db_params = field.db_parameters(connection=self.connection)
sql = db_params['type']
params = []
if sql is None:
return None, None
# Work out nullability
null = field.null
# If we were told to include a default value, do so
include_default = include_default and not self.skip_default(field)
if include_default:
default_value = self.effective_default(field)
if default_value is not None:
sql += self._add_column_default()
params += [default_value]
# Oracle treats the empty string ('') as null, so coerce the null
# option whenever '' is a possible value.
if (field.empty_strings_allowed and not field.primary_key and
self.connection.features.interprets_empty_strings_as_nulls):
null = True
if null and not self.connection.features.implied_column_null:
sql += " NULL"
elif not null:
sql += self._add_column_not_null(model, field)
# Primary key/unique outputs
if field.primary_key:
sql += self._add_column_primary_key(model, field)
elif field.unique:
sql += self._add_column_unique(model, field)
# Optionally add the tablespace if it's an implicitly indexed column
tablespace = field.db_tablespace or model._meta.db_tablespace
if tablespace and self.connection.features.supports_tablespaces and field.unique:
sql += " %s" % self.connection.ops.tablespace_sql(tablespace, inline=True)
return sql, params
def _alter_column_set_not_null(self, model, new_field):
if not self.is_postgresql_12 and self.RAISE_FOR_UNSAFE and self.USE_NOT_NULL is None:
raise UnsafeOperationException(Unsafe.ALTER_COLUMN_NOT_NULL)
elif self.is_postgresql_12:
self.deferred_sql.append(self._sql_column_not_null % {
"column": self.quote_name(new_field.column),
"table": self.quote_name(model._meta.db_table),
"name": self.quote_name(
self._create_index_name(model._meta.db_table, [new_field.column], suffix="_notnull")
),
})
return DUMMY_SQL, []
elif self._use_pg_attribute_update_for_not_null():
self.deferred_sql.append(self._sql_column_not_null_le_pg12_pg_attributes_for_root % {
"column": self.quote_name(new_field.column),
"table": self.quote_name(model._meta.db_table),
"name": self.quote_name(
self._create_index_name(model._meta.db_table, [new_field.column], suffix="_notnull")
),
})
return DUMMY_SQL, []
elif self._use_check_constraint_for_not_null(model):
self.deferred_sql.append(self._sql_column_not_null_compatible_le_pg12 % {
"column": self.quote_name(new_field.column),
"table": self.quote_name(model._meta.db_table),
"name": self.quote_name(
self._create_index_name(model._meta.db_table, [new_field.column], suffix="_notnull")
),
})
return DUMMY_SQL, []
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ALTER_COLUMN_NOT_NULL))
return self.sql_alter_column_not_null % {
"column": self.quote_name(new_field.column),
}, []
def _alter_column_drop_not_null(self, model, new_field):
with self.connection.cursor() as cursor:
cursor.execute(self._sql_check_notnull_constraint % {
"table": self.quote_name(model._meta.db_table),
"columns": self.quote_name(new_field.column),
})
result = cursor.fetchone()
if result:
constraint_name, = result
self.deferred_sql.append(self.sql_delete_check % {
"table": self.quote_name(model._meta.db_table),
"name": constraint_name,
})
else:
return self.sql_alter_column_null % {
"column": self.quote_name(new_field.column),
}, []
def _alter_column_null_sql(self, model, old_field, new_field):
if new_field.null:
return self._alter_column_drop_not_null(model, new_field)
else:
return self._alter_column_set_not_null(model, new_field)
def _immediate_type_cast(self, old_type, new_type):
old_type_varchar_match = self._varchar_type_regexp.match(old_type)
if old_type_varchar_match:
if new_type == "text":
return True
new_type_varchar_match = self._varchar_type_regexp.match(new_type)
if new_type_varchar_match:
old_type_max_length = int(old_type_varchar_match.group("max_length"))
new_type_max_length = int(new_type_varchar_match.group("max_length"))
if new_type_max_length >= old_type_max_length:
return True
else:
return False
old_type_numeric_match = self._numeric_type_regexp.match(old_type)
if old_type_numeric_match:
new_type_numeric_match = self._numeric_type_regexp.match(new_type)
old_type_precision = int(old_type_numeric_match.group("precision"))
old_type_scale = int(old_type_numeric_match.group("scale"))
try:
new_type_precision = int(new_type_numeric_match.group("precision"))
new_type_scale = int(new_type_numeric_match.group("scale"))
except AttributeError:
return False
return new_type_precision >= old_type_precision and new_type_scale == old_type_scale
return False
def _alter_column_type_sql(self, model, old_field, new_field, new_type):
old_db_params = old_field.db_parameters(connection=self.connection)
old_type = old_db_params["type"]
if not self._immediate_type_cast(old_type, new_type):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ALTER_COLUMN_TYPE)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ALTER_COLUMN_TYPE))
return super()._alter_column_type_sql(model, old_field, new_field, new_type)
class DatabaseSchemaEditor(DatabaseSchemaEditorMixin, PostgresDatabaseSchemaEditor):
pass
| true | true |
f7f6ba8b114e75d3fd7aaa887292d3e5794f03f9 | 10,916 | py | Python | pandas/tests/arithmetic/test_object.py | ajspera/pandas | f38020f33052ea9029b410d7fae79bc8f249c0ac | [
"BSD-3-Clause"
] | 5 | 2019-07-26T15:22:41.000Z | 2021-09-28T09:22:17.000Z | pandas/tests/arithmetic/test_object.py | ajspera/pandas | f38020f33052ea9029b410d7fae79bc8f249c0ac | [
"BSD-3-Clause"
] | null | null | null | pandas/tests/arithmetic/test_object.py | ajspera/pandas | f38020f33052ea9029b410d7fae79bc8f249c0ac | [
"BSD-3-Clause"
] | 3 | 2019-07-26T10:47:23.000Z | 2020-08-10T12:40:32.000Z | # Arithmetic tests for DataFrame/Series/Index/Array classes that should
# behave identically.
# Specifically for object dtype
from decimal import Decimal
import operator
import numpy as np
import pytest
import pandas as pd
from pandas import Series, Timestamp
from pandas.core import ops
import pandas.util.testing as tm
# ------------------------------------------------------------------
# Comparisons
class TestObjectComparisons:
def test_comparison_object_numeric_nas(self):
ser = Series(np.random.randn(10), dtype=object)
shifted = ser.shift(2)
ops = ["lt", "le", "gt", "ge", "eq", "ne"]
for op in ops:
func = getattr(operator, op)
result = func(ser, shifted)
expected = func(ser.astype(float), shifted.astype(float))
tm.assert_series_equal(result, expected)
def test_object_comparisons(self):
ser = Series(["a", "b", np.nan, "c", "a"])
result = ser == "a"
expected = Series([True, False, False, False, True])
tm.assert_series_equal(result, expected)
result = ser < "a"
expected = Series([False, False, False, False, False])
tm.assert_series_equal(result, expected)
result = ser != "a"
expected = -(ser == "a")
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dtype", [None, object])
def test_more_na_comparisons(self, dtype):
left = Series(["a", np.nan, "c"], dtype=dtype)
right = Series(["a", np.nan, "d"], dtype=dtype)
result = left == right
expected = Series([True, False, False])
tm.assert_series_equal(result, expected)
result = left != right
expected = Series([False, True, True])
tm.assert_series_equal(result, expected)
result = left == np.nan
expected = Series([False, False, False])
tm.assert_series_equal(result, expected)
result = left != np.nan
expected = Series([True, True, True])
tm.assert_series_equal(result, expected)
# ------------------------------------------------------------------
# Arithmetic
class TestArithmetic:
# TODO: parametrize
def test_pow_ops_object(self):
# GH#22922
# pow is weird with masking & 1, so testing here
a = Series([1, np.nan, 1, np.nan], dtype=object)
b = Series([1, np.nan, np.nan, 1], dtype=object)
result = a ** b
expected = Series(a.values ** b.values, dtype=object)
tm.assert_series_equal(result, expected)
result = b ** a
expected = Series(b.values ** a.values, dtype=object)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("op", [operator.add, ops.radd])
@pytest.mark.parametrize("other", ["category", "Int64"])
def test_add_extension_scalar(self, other, box, op):
# GH#22378
# Check that scalars satisfying is_extension_array_dtype(obj)
# do not incorrectly try to dispatch to an ExtensionArray operation
arr = pd.Series(["a", "b", "c"])
expected = pd.Series([op(x, other) for x in arr])
arr = tm.box_expected(arr, box)
expected = tm.box_expected(expected, box)
result = op(arr, other)
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"box",
[
pytest.param(
pd.Index,
marks=pytest.mark.xfail(reason="Does not mask nulls", raises=TypeError),
),
pd.Series,
pd.DataFrame,
],
ids=lambda x: x.__name__,
)
def test_objarr_add_str(self, box):
ser = pd.Series(["x", np.nan, "x"])
expected = pd.Series(["xa", np.nan, "xa"])
ser = tm.box_expected(ser, box)
expected = tm.box_expected(expected, box)
result = ser + "a"
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"box",
[
pytest.param(
pd.Index,
marks=pytest.mark.xfail(reason="Does not mask nulls", raises=TypeError),
),
pd.Series,
pd.DataFrame,
],
ids=lambda x: x.__name__,
)
def test_objarr_radd_str(self, box):
ser = pd.Series(["x", np.nan, "x"])
expected = pd.Series(["ax", np.nan, "ax"])
ser = tm.box_expected(ser, box)
expected = tm.box_expected(expected, box)
result = "a" + ser
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"data",
[
[1, 2, 3],
[1.1, 2.2, 3.3],
[Timestamp("2011-01-01"), Timestamp("2011-01-02"), pd.NaT],
["x", "y", 1],
],
)
@pytest.mark.parametrize("dtype", [None, object])
def test_objarr_radd_str_invalid(self, dtype, data, box):
ser = Series(data, dtype=dtype)
ser = tm.box_expected(ser, box)
with pytest.raises(TypeError):
"foo_" + ser
@pytest.mark.parametrize("op", [operator.add, ops.radd, operator.sub, ops.rsub])
def test_objarr_add_invalid(self, op, box):
# invalid ops
obj_ser = tm.makeObjectSeries()
obj_ser.name = "objects"
obj_ser = tm.box_expected(obj_ser, box)
with pytest.raises(Exception):
op(obj_ser, 1)
with pytest.raises(Exception):
op(obj_ser, np.array(1, dtype=np.int64))
# TODO: Moved from tests.series.test_operators; needs cleanup
def test_operators_na_handling(self):
ser = Series(["foo", "bar", "baz", np.nan])
result = "prefix_" + ser
expected = pd.Series(["prefix_foo", "prefix_bar", "prefix_baz", np.nan])
tm.assert_series_equal(result, expected)
result = ser + "_suffix"
expected = pd.Series(["foo_suffix", "bar_suffix", "baz_suffix", np.nan])
tm.assert_series_equal(result, expected)
# TODO: parametrize over box
@pytest.mark.parametrize("dtype", [None, object])
def test_series_with_dtype_radd_timedelta(self, dtype):
# note this test is _not_ aimed at timedelta64-dtyped Series
ser = pd.Series(
[pd.Timedelta("1 days"), pd.Timedelta("2 days"), pd.Timedelta("3 days")],
dtype=dtype,
)
expected = pd.Series(
[pd.Timedelta("4 days"), pd.Timedelta("5 days"), pd.Timedelta("6 days")]
)
result = pd.Timedelta("3 days") + ser
tm.assert_series_equal(result, expected)
result = ser + pd.Timedelta("3 days")
tm.assert_series_equal(result, expected)
# TODO: cleanup & parametrize over box
def test_mixed_timezone_series_ops_object(self):
# GH#13043
ser = pd.Series(
[
pd.Timestamp("2015-01-01", tz="US/Eastern"),
pd.Timestamp("2015-01-01", tz="Asia/Tokyo"),
],
name="xxx",
)
assert ser.dtype == object
exp = pd.Series(
[
pd.Timestamp("2015-01-02", tz="US/Eastern"),
pd.Timestamp("2015-01-02", tz="Asia/Tokyo"),
],
name="xxx",
)
tm.assert_series_equal(ser + pd.Timedelta("1 days"), exp)
tm.assert_series_equal(pd.Timedelta("1 days") + ser, exp)
# object series & object series
ser2 = pd.Series(
[
pd.Timestamp("2015-01-03", tz="US/Eastern"),
pd.Timestamp("2015-01-05", tz="Asia/Tokyo"),
],
name="xxx",
)
assert ser2.dtype == object
exp = pd.Series([pd.Timedelta("2 days"), pd.Timedelta("4 days")], name="xxx")
tm.assert_series_equal(ser2 - ser, exp)
tm.assert_series_equal(ser - ser2, -exp)
ser = pd.Series(
[pd.Timedelta("01:00:00"), pd.Timedelta("02:00:00")],
name="xxx",
dtype=object,
)
assert ser.dtype == object
exp = pd.Series(
[pd.Timedelta("01:30:00"), pd.Timedelta("02:30:00")], name="xxx"
)
tm.assert_series_equal(ser + pd.Timedelta("00:30:00"), exp)
tm.assert_series_equal(pd.Timedelta("00:30:00") + ser, exp)
# TODO: cleanup & parametrize over box
def test_iadd_preserves_name(self):
# GH#17067, GH#19723 __iadd__ and __isub__ should preserve index name
ser = pd.Series([1, 2, 3])
ser.index.name = "foo"
ser.index += 1
assert ser.index.name == "foo"
ser.index -= 1
assert ser.index.name == "foo"
def test_add_string(self):
# from bug report
index = pd.Index(["a", "b", "c"])
index2 = index + "foo"
assert "a" not in index2
assert "afoo" in index2
def test_iadd_string(self):
index = pd.Index(["a", "b", "c"])
# doesn't fail test unless there is a check before `+=`
assert "a" in index
index += "_x"
assert "a_x" in index
def test_add(self):
index = tm.makeStringIndex(100)
expected = pd.Index(index.values * 2)
tm.assert_index_equal(index + index, expected)
tm.assert_index_equal(index + index.tolist(), expected)
tm.assert_index_equal(index.tolist() + index, expected)
# test add and radd
index = pd.Index(list("abc"))
expected = pd.Index(["a1", "b1", "c1"])
tm.assert_index_equal(index + "1", expected)
expected = pd.Index(["1a", "1b", "1c"])
tm.assert_index_equal("1" + index, expected)
def test_sub_fail(self):
index = tm.makeStringIndex(100)
with pytest.raises(TypeError):
index - "a"
with pytest.raises(TypeError):
index - index
with pytest.raises(TypeError):
index - index.tolist()
with pytest.raises(TypeError):
index.tolist() - index
def test_sub_object(self):
# GH#19369
index = pd.Index([Decimal(1), Decimal(2)])
expected = pd.Index([Decimal(0), Decimal(1)])
result = index - Decimal(1)
tm.assert_index_equal(result, expected)
result = index - pd.Index([Decimal(1), Decimal(1)])
tm.assert_index_equal(result, expected)
with pytest.raises(TypeError):
index - "foo"
with pytest.raises(TypeError):
index - np.array([2, "foo"])
def test_rsub_object(self):
# GH#19369
index = pd.Index([Decimal(1), Decimal(2)])
expected = pd.Index([Decimal(1), Decimal(0)])
result = Decimal(2) - index
tm.assert_index_equal(result, expected)
result = np.array([Decimal(2), Decimal(2)]) - index
tm.assert_index_equal(result, expected)
with pytest.raises(TypeError):
"foo" - index
with pytest.raises(TypeError):
np.array([True, pd.Timestamp.now()]) - index
| 31.825073 | 88 | 0.561378 |
from decimal import Decimal
import operator
import numpy as np
import pytest
import pandas as pd
from pandas import Series, Timestamp
from pandas.core import ops
import pandas.util.testing as tm
class TestObjectComparisons:
def test_comparison_object_numeric_nas(self):
ser = Series(np.random.randn(10), dtype=object)
shifted = ser.shift(2)
ops = ["lt", "le", "gt", "ge", "eq", "ne"]
for op in ops:
func = getattr(operator, op)
result = func(ser, shifted)
expected = func(ser.astype(float), shifted.astype(float))
tm.assert_series_equal(result, expected)
def test_object_comparisons(self):
ser = Series(["a", "b", np.nan, "c", "a"])
result = ser == "a"
expected = Series([True, False, False, False, True])
tm.assert_series_equal(result, expected)
result = ser < "a"
expected = Series([False, False, False, False, False])
tm.assert_series_equal(result, expected)
result = ser != "a"
expected = -(ser == "a")
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dtype", [None, object])
def test_more_na_comparisons(self, dtype):
left = Series(["a", np.nan, "c"], dtype=dtype)
right = Series(["a", np.nan, "d"], dtype=dtype)
result = left == right
expected = Series([True, False, False])
tm.assert_series_equal(result, expected)
result = left != right
expected = Series([False, True, True])
tm.assert_series_equal(result, expected)
result = left == np.nan
expected = Series([False, False, False])
tm.assert_series_equal(result, expected)
result = left != np.nan
expected = Series([True, True, True])
tm.assert_series_equal(result, expected)
class TestArithmetic:
def test_pow_ops_object(self):
a = Series([1, np.nan, 1, np.nan], dtype=object)
b = Series([1, np.nan, np.nan, 1], dtype=object)
result = a ** b
expected = Series(a.values ** b.values, dtype=object)
tm.assert_series_equal(result, expected)
result = b ** a
expected = Series(b.values ** a.values, dtype=object)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("op", [operator.add, ops.radd])
@pytest.mark.parametrize("other", ["category", "Int64"])
def test_add_extension_scalar(self, other, box, op):
arr = pd.Series(["a", "b", "c"])
expected = pd.Series([op(x, other) for x in arr])
arr = tm.box_expected(arr, box)
expected = tm.box_expected(expected, box)
result = op(arr, other)
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"box",
[
pytest.param(
pd.Index,
marks=pytest.mark.xfail(reason="Does not mask nulls", raises=TypeError),
),
pd.Series,
pd.DataFrame,
],
ids=lambda x: x.__name__,
)
def test_objarr_add_str(self, box):
ser = pd.Series(["x", np.nan, "x"])
expected = pd.Series(["xa", np.nan, "xa"])
ser = tm.box_expected(ser, box)
expected = tm.box_expected(expected, box)
result = ser + "a"
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"box",
[
pytest.param(
pd.Index,
marks=pytest.mark.xfail(reason="Does not mask nulls", raises=TypeError),
),
pd.Series,
pd.DataFrame,
],
ids=lambda x: x.__name__,
)
def test_objarr_radd_str(self, box):
ser = pd.Series(["x", np.nan, "x"])
expected = pd.Series(["ax", np.nan, "ax"])
ser = tm.box_expected(ser, box)
expected = tm.box_expected(expected, box)
result = "a" + ser
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"data",
[
[1, 2, 3],
[1.1, 2.2, 3.3],
[Timestamp("2011-01-01"), Timestamp("2011-01-02"), pd.NaT],
["x", "y", 1],
],
)
@pytest.mark.parametrize("dtype", [None, object])
def test_objarr_radd_str_invalid(self, dtype, data, box):
ser = Series(data, dtype=dtype)
ser = tm.box_expected(ser, box)
with pytest.raises(TypeError):
"foo_" + ser
@pytest.mark.parametrize("op", [operator.add, ops.radd, operator.sub, ops.rsub])
def test_objarr_add_invalid(self, op, box):
obj_ser = tm.makeObjectSeries()
obj_ser.name = "objects"
obj_ser = tm.box_expected(obj_ser, box)
with pytest.raises(Exception):
op(obj_ser, 1)
with pytest.raises(Exception):
op(obj_ser, np.array(1, dtype=np.int64))
def test_operators_na_handling(self):
ser = Series(["foo", "bar", "baz", np.nan])
result = "prefix_" + ser
expected = pd.Series(["prefix_foo", "prefix_bar", "prefix_baz", np.nan])
tm.assert_series_equal(result, expected)
result = ser + "_suffix"
expected = pd.Series(["foo_suffix", "bar_suffix", "baz_suffix", np.nan])
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dtype", [None, object])
def test_series_with_dtype_radd_timedelta(self, dtype):
ser = pd.Series(
[pd.Timedelta("1 days"), pd.Timedelta("2 days"), pd.Timedelta("3 days")],
dtype=dtype,
)
expected = pd.Series(
[pd.Timedelta("4 days"), pd.Timedelta("5 days"), pd.Timedelta("6 days")]
)
result = pd.Timedelta("3 days") + ser
tm.assert_series_equal(result, expected)
result = ser + pd.Timedelta("3 days")
tm.assert_series_equal(result, expected)
def test_mixed_timezone_series_ops_object(self):
ser = pd.Series(
[
pd.Timestamp("2015-01-01", tz="US/Eastern"),
pd.Timestamp("2015-01-01", tz="Asia/Tokyo"),
],
name="xxx",
)
assert ser.dtype == object
exp = pd.Series(
[
pd.Timestamp("2015-01-02", tz="US/Eastern"),
pd.Timestamp("2015-01-02", tz="Asia/Tokyo"),
],
name="xxx",
)
tm.assert_series_equal(ser + pd.Timedelta("1 days"), exp)
tm.assert_series_equal(pd.Timedelta("1 days") + ser, exp)
ser2 = pd.Series(
[
pd.Timestamp("2015-01-03", tz="US/Eastern"),
pd.Timestamp("2015-01-05", tz="Asia/Tokyo"),
],
name="xxx",
)
assert ser2.dtype == object
exp = pd.Series([pd.Timedelta("2 days"), pd.Timedelta("4 days")], name="xxx")
tm.assert_series_equal(ser2 - ser, exp)
tm.assert_series_equal(ser - ser2, -exp)
ser = pd.Series(
[pd.Timedelta("01:00:00"), pd.Timedelta("02:00:00")],
name="xxx",
dtype=object,
)
assert ser.dtype == object
exp = pd.Series(
[pd.Timedelta("01:30:00"), pd.Timedelta("02:30:00")], name="xxx"
)
tm.assert_series_equal(ser + pd.Timedelta("00:30:00"), exp)
tm.assert_series_equal(pd.Timedelta("00:30:00") + ser, exp)
def test_iadd_preserves_name(self):
== "foo"
ser.index -= 1
assert ser.index.name == "foo"
def test_add_string(self):
index = pd.Index(["a", "b", "c"])
index2 = index + "foo"
assert "a" not in index2
assert "afoo" in index2
def test_iadd_string(self):
index = pd.Index(["a", "b", "c"])
assert "a" in index
index += "_x"
assert "a_x" in index
def test_add(self):
index = tm.makeStringIndex(100)
expected = pd.Index(index.values * 2)
tm.assert_index_equal(index + index, expected)
tm.assert_index_equal(index + index.tolist(), expected)
tm.assert_index_equal(index.tolist() + index, expected)
# test add and radd
index = pd.Index(list("abc"))
expected = pd.Index(["a1", "b1", "c1"])
tm.assert_index_equal(index + "1", expected)
expected = pd.Index(["1a", "1b", "1c"])
tm.assert_index_equal("1" + index, expected)
def test_sub_fail(self):
index = tm.makeStringIndex(100)
with pytest.raises(TypeError):
index - "a"
with pytest.raises(TypeError):
index - index
with pytest.raises(TypeError):
index - index.tolist()
with pytest.raises(TypeError):
index.tolist() - index
def test_sub_object(self):
# GH#19369
index = pd.Index([Decimal(1), Decimal(2)])
expected = pd.Index([Decimal(0), Decimal(1)])
result = index - Decimal(1)
tm.assert_index_equal(result, expected)
result = index - pd.Index([Decimal(1), Decimal(1)])
tm.assert_index_equal(result, expected)
with pytest.raises(TypeError):
index - "foo"
with pytest.raises(TypeError):
index - np.array([2, "foo"])
def test_rsub_object(self):
# GH#19369
index = pd.Index([Decimal(1), Decimal(2)])
expected = pd.Index([Decimal(1), Decimal(0)])
result = Decimal(2) - index
tm.assert_index_equal(result, expected)
result = np.array([Decimal(2), Decimal(2)]) - index
tm.assert_index_equal(result, expected)
with pytest.raises(TypeError):
"foo" - index
with pytest.raises(TypeError):
np.array([True, pd.Timestamp.now()]) - index
| true | true |
f7f6bace4333575ee395f8c94362a447c8d67e98 | 44,055 | py | Python | isort/_future/_dataclasses.py | honnix/isort | 6b8f57b8f64676ce2125e5b3c7bb7590539287c7 | [
"MIT"
] | null | null | null | isort/_future/_dataclasses.py | honnix/isort | 6b8f57b8f64676ce2125e5b3c7bb7590539287c7 | [
"MIT"
] | null | null | null | isort/_future/_dataclasses.py | honnix/isort | 6b8f57b8f64676ce2125e5b3c7bb7590539287c7 | [
"MIT"
] | null | null | null | # type: ignore
# flake8: noqa
"""Backport of Python3.7 dataclasses Library
Taken directly from here: https://github.com/ericvsmith/dataclasses
Licensed under the Apache License: https://github.com/ericvsmith/dataclasses/blob/master/LICENSE.txt
Needed due to isorts strict no non-optional requirements stance.
TODO: Remove once isort only supports 3.7+
"""
import copy
import inspect
import keyword
import re
import sys
import types
__all__ = [
"dataclass",
"field",
"Field",
"FrozenInstanceError",
"InitVar",
"MISSING",
# Helper functions.
"fields",
"asdict",
"astuple",
"make_dataclass",
"replace",
"is_dataclass",
]
# Conditions for adding methods. The boxes indicate what action the
# dataclass decorator takes. For all of these tables, when I talk
# about init=, repr=, eq=, order=, unsafe_hash=, or frozen=, I'm
# referring to the arguments to the @dataclass decorator. When
# checking if a dunder method already exists, I mean check for an
# entry in the class's __dict__. I never check to see if an attribute
# is defined in a base class.
# Key:
# +=========+=========================================+
# + Value | Meaning |
# +=========+=========================================+
# | <blank> | No action: no method is added. |
# +---------+-----------------------------------------+
# | add | Generated method is added. |
# +---------+-----------------------------------------+
# | raise | TypeError is raised. |
# +---------+-----------------------------------------+
# | None | Attribute is set to None. |
# +=========+=========================================+
# __init__
#
# +--- init= parameter
# |
# v | | |
# | no | yes | <--- class has __init__ in __dict__?
# +=======+=======+=======+
# | False | | |
# +-------+-------+-------+
# | True | add | | <- the default
# +=======+=======+=======+
# __repr__
#
# +--- repr= parameter
# |
# v | | |
# | no | yes | <--- class has __repr__ in __dict__?
# +=======+=======+=======+
# | False | | |
# +-------+-------+-------+
# | True | add | | <- the default
# +=======+=======+=======+
# __setattr__
# __delattr__
#
# +--- frozen= parameter
# |
# v | | |
# | no | yes | <--- class has __setattr__ or __delattr__ in __dict__?
# +=======+=======+=======+
# | False | | | <- the default
# +-------+-------+-------+
# | True | add | raise |
# +=======+=======+=======+
# Raise because not adding these methods would break the "frozen-ness"
# of the class.
# __eq__
#
# +--- eq= parameter
# |
# v | | |
# | no | yes | <--- class has __eq__ in __dict__?
# +=======+=======+=======+
# | False | | |
# +-------+-------+-------+
# | True | add | | <- the default
# +=======+=======+=======+
# __lt__
# __le__
# __gt__
# __ge__
#
# +--- order= parameter
# |
# v | | |
# | no | yes | <--- class has any comparison method in __dict__?
# +=======+=======+=======+
# | False | | | <- the default
# +-------+-------+-------+
# | True | add | raise |
# +=======+=======+=======+
# Raise because to allow this case would interfere with using
# functools.total_ordering.
# __hash__
# +------------------- unsafe_hash= parameter
# | +----------- eq= parameter
# | | +--- frozen= parameter
# | | |
# v v v | | |
# | no | yes | <--- class has explicitly defined __hash__
# +=======+=======+=======+========+========+
# | False | False | False | | | No __eq__, use the base class __hash__
# +-------+-------+-------+--------+--------+
# | False | False | True | | | No __eq__, use the base class __hash__
# +-------+-------+-------+--------+--------+
# | False | True | False | None | | <-- the default, not hashable
# +-------+-------+-------+--------+--------+
# | False | True | True | add | | Frozen, so hashable, allows override
# +-------+-------+-------+--------+--------+
# | True | False | False | add | raise | Has no __eq__, but hashable
# +-------+-------+-------+--------+--------+
# | True | False | True | add | raise | Has no __eq__, but hashable
# +-------+-------+-------+--------+--------+
# | True | True | False | add | raise | Not frozen, but hashable
# +-------+-------+-------+--------+--------+
# | True | True | True | add | raise | Frozen, so hashable
# +=======+=======+=======+========+========+
# For boxes that are blank, __hash__ is untouched and therefore
# inherited from the base class. If the base is object, then
# id-based hashing is used.
#
# Note that a class may already have __hash__=None if it specified an
# __eq__ method in the class body (not one that was created by
# @dataclass).
#
# See _hash_action (below) for a coded version of this table.
# Raised when an attempt is made to modify a frozen class.
class FrozenInstanceError(AttributeError):
pass
# A sentinel object for default values to signal that a default
# factory will be used. This is given a nice repr() which will appear
# in the function signature of dataclasses' constructors.
class _HAS_DEFAULT_FACTORY_CLASS:
def __repr__(self):
return "<factory>"
_HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()
# A sentinel object to detect if a parameter is supplied or not. Use
# a class to give it a better repr.
class _MISSING_TYPE:
pass
MISSING = _MISSING_TYPE()
# Since most per-field metadata will be unused, create an empty
# read-only proxy that can be shared among all fields.
_EMPTY_METADATA = types.MappingProxyType({})
# Markers for the various kinds of fields and pseudo-fields.
class _FIELD_BASE:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
_FIELD = _FIELD_BASE("_FIELD")
_FIELD_CLASSVAR = _FIELD_BASE("_FIELD_CLASSVAR")
_FIELD_INITVAR = _FIELD_BASE("_FIELD_INITVAR")
# The name of an attribute on the class where we store the Field
# objects. Also used to check if a class is a Data Class.
_FIELDS = "__dataclass_fields__"
# The name of an attribute on the class that stores the parameters to
# @dataclass.
_PARAMS = "__dataclass_params__"
# The name of the function, that if it exists, is called at the end of
# __init__.
_POST_INIT_NAME = "__post_init__"
# String regex that string annotations for ClassVar or InitVar must match.
# Allows "identifier.identifier[" or "identifier[".
# https://bugs.python.org/issue33453 for details.
_MODULE_IDENTIFIER_RE = re.compile(r"^(?:\s*(\w+)\s*\.)?\s*(\w+)")
class _InitVarMeta(type):
def __getitem__(self, params):
return self
class InitVar(metaclass=_InitVarMeta):
pass
# Instances of Field are only ever created from within this module,
# and only from the field() function, although Field instances are
# exposed externally as (conceptually) read-only objects.
#
# name and type are filled in after the fact, not in __init__.
# They're not known at the time this class is instantiated, but it's
# convenient if they're available later.
#
# When cls._FIELDS is filled in with a list of Field objects, the name
# and type fields will have been populated.
class Field:
__slots__ = (
"name",
"type",
"default",
"default_factory",
"repr",
"hash",
"init",
"compare",
"metadata",
"_field_type", # Private: not to be used by user code.
)
def __init__(self, default, default_factory, init, repr, hash, compare, metadata):
self.name = None
self.type = None
self.default = default
self.default_factory = default_factory
self.init = init
self.repr = repr
self.hash = hash
self.compare = compare
self.metadata = (
_EMPTY_METADATA
if metadata is None or len(metadata) == 0
else types.MappingProxyType(metadata)
)
self._field_type = None
def __repr__(self):
return (
"Field("
f"name={self.name!r},"
f"type={self.type!r},"
f"default={self.default!r},"
f"default_factory={self.default_factory!r},"
f"init={self.init!r},"
f"repr={self.repr!r},"
f"hash={self.hash!r},"
f"compare={self.compare!r},"
f"metadata={self.metadata!r},"
f"_field_type={self._field_type}"
")"
)
# This is used to support the PEP 487 __set_name__ protocol in the
# case where we're using a field that contains a descriptor as a
# defaul value. For details on __set_name__, see
# https://www.python.org/dev/peps/pep-0487/#implementation-details.
#
# Note that in _process_class, this Field object is overwritten
# with the default value, so the end result is a descriptor that
# had __set_name__ called on it at the right time.
def __set_name__(self, owner, name):
func = getattr(type(self.default), "__set_name__", None)
if func:
# There is a __set_name__ method on the descriptor, call
# it.
func(self.default, owner, name)
class _DataclassParams:
__slots__ = ("init", "repr", "eq", "order", "unsafe_hash", "frozen")
def __init__(self, init, repr, eq, order, unsafe_hash, frozen):
self.init = init
self.repr = repr
self.eq = eq
self.order = order
self.unsafe_hash = unsafe_hash
self.frozen = frozen
def __repr__(self):
return (
"_DataclassParams("
f"init={self.init!r},"
f"repr={self.repr!r},"
f"eq={self.eq!r},"
f"order={self.order!r},"
f"unsafe_hash={self.unsafe_hash!r},"
f"frozen={self.frozen!r}"
")"
)
# This function is used instead of exposing Field creation directly,
# so that a type checker can be told (via overloads) that this is a
# function whose type depends on its parameters.
def field(
*,
default=MISSING,
default_factory=MISSING,
init=True,
repr=True,
hash=None,
compare=True,
metadata=None,
):
"""Return an object to identify dataclass fields.
default is the default value of the field. default_factory is a
0-argument function called to initialize a field's value. If init
is True, the field will be a parameter to the class's __init__()
function. If repr is True, the field will be included in the
object's repr(). If hash is True, the field will be included in
the object's hash(). If compare is True, the field will be used
in comparison functions. metadata, if specified, must be a
mapping which is stored but not otherwise examined by dataclass.
It is an error to specify both default and default_factory.
"""
if default is not MISSING and default_factory is not MISSING:
raise ValueError("cannot specify both default and default_factory")
return Field(default, default_factory, init, repr, hash, compare, metadata)
def _tuple_str(obj_name, fields):
# Return a string representing each field of obj_name as a tuple
# member. So, if fields is ['x', 'y'] and obj_name is "self",
# return "(self.x,self.y)".
# Special case for the 0-tuple.
if not fields:
return "()"
# Note the trailing comma, needed if this turns out to be a 1-tuple.
return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)'
def _create_fn(name, args, body, *, globals=None, locals=None, return_type=MISSING):
# Note that we mutate locals when exec() is called. Caller
# beware! The only callers are internal to this module, so no
# worries about external callers.
if locals is None:
locals = {}
return_annotation = ""
if return_type is not MISSING:
locals["_return_type"] = return_type
return_annotation = "->_return_type"
args = ",".join(args)
body = "\n".join(f" {b}" for b in body)
# Compute the text of the entire function.
txt = f"def {name}({args}){return_annotation}:\n{body}"
exec(txt, globals, locals) # nosec
return locals[name]
def _field_assign(frozen, name, value, self_name):
# If we're a frozen class, then assign to our fields in __init__
# via object.__setattr__. Otherwise, just use a simple
# assignment.
#
# self_name is what "self" is called in this function: don't
# hard-code "self", since that might be a field name.
if frozen:
return f"object.__setattr__({self_name},{name!r},{value})"
return f"{self_name}.{name}={value}"
def _field_init(f, frozen, globals, self_name):
# Return the text of the line in the body of __init__ that will
# initialize this field.
default_name = f"_dflt_{f.name}"
if f.default_factory is not MISSING:
if f.init:
# This field has a default factory. If a parameter is
# given, use it. If not, call the factory.
globals[default_name] = f.default_factory
value = f"{default_name}() " f"if {f.name} is _HAS_DEFAULT_FACTORY " f"else {f.name}"
else:
# This is a field that's not in the __init__ params, but
# has a default factory function. It needs to be
# initialized here by calling the factory function,
# because there's no other way to initialize it.
# For a field initialized with a default=defaultvalue, the
# class dict just has the default value
# (cls.fieldname=defaultvalue). But that won't work for a
# default factory, the factory must be called in __init__
# and we must assign that to self.fieldname. We can't
# fall back to the class dict's value, both because it's
# not set, and because it might be different per-class
# (which, after all, is why we have a factory function!).
globals[default_name] = f.default_factory
value = f"{default_name}()"
else:
# No default factory.
if f.init:
if f.default is MISSING:
# There's no default, just do an assignment.
value = f.name
elif f.default is not MISSING:
globals[default_name] = f.default
value = f.name
else:
# This field does not need initialization. Signify that
# to the caller by returning None.
return None
# Only test this now, so that we can create variables for the
# default. However, return None to signify that we're not going
# to actually do the assignment statement for InitVars.
if f._field_type == _FIELD_INITVAR:
return None
# Now, actually generate the field assignment.
return _field_assign(frozen, f.name, value, self_name)
def _init_param(f):
# Return the __init__ parameter string for this field. For
# example, the equivalent of 'x:int=3' (except instead of 'int',
# reference a variable set to int, and instead of '3', reference a
# variable set to 3).
if f.default is MISSING and f.default_factory is MISSING:
# There's no default, and no default_factory, just output the
# variable name and type.
default = ""
elif f.default is not MISSING:
# There's a default, this will be the name that's used to look
# it up.
default = f"=_dflt_{f.name}"
elif f.default_factory is not MISSING:
# There's a factory function. Set a marker.
default = "=_HAS_DEFAULT_FACTORY"
return f"{f.name}:_type_{f.name}{default}"
def _init_fn(fields, frozen, has_post_init, self_name):
# fields contains both real fields and InitVar pseudo-fields.
# Make sure we don't have fields without defaults following fields
# with defaults. This actually would be caught when exec-ing the
# function source code, but catching it here gives a better error
# message, and future-proofs us in case we build up the function
# using ast.
seen_default = False
for f in fields:
# Only consider fields in the __init__ call.
if f.init:
if not (f.default is MISSING and f.default_factory is MISSING):
seen_default = True
elif seen_default:
raise TypeError(f"non-default argument {f.name!r} " "follows default argument")
globals = {"MISSING": MISSING, "_HAS_DEFAULT_FACTORY": _HAS_DEFAULT_FACTORY}
body_lines = []
for f in fields:
line = _field_init(f, frozen, globals, self_name)
# line is None means that this field doesn't require
# initialization (it's a pseudo-field). Just skip it.
if line:
body_lines.append(line)
# Does this class have a post-init function?
if has_post_init:
params_str = ",".join(f.name for f in fields if f._field_type is _FIELD_INITVAR)
body_lines.append(f"{self_name}.{_POST_INIT_NAME}({params_str})")
# If no body lines, use 'pass'.
if not body_lines:
body_lines = ["pass"]
locals = {f"_type_{f.name}": f.type for f in fields}
return _create_fn(
"__init__",
[self_name] + [_init_param(f) for f in fields if f.init],
body_lines,
locals=locals,
globals=globals,
return_type=None,
)
def _repr_fn(fields):
return _create_fn(
"__repr__",
("self",),
[
'return self.__class__.__qualname__ + f"('
+ ", ".join([f"{f.name}={{self.{f.name}!r}}" for f in fields])
+ ')"'
],
)
def _frozen_get_del_attr(cls, fields):
# XXX: globals is modified on the first call to _create_fn, then
# the modified version is used in the second call. Is this okay?
globals = {"cls": cls, "FrozenInstanceError": FrozenInstanceError}
if fields:
fields_str = "(" + ",".join(repr(f.name) for f in fields) + ",)"
else:
# Special case for the zero-length tuple.
fields_str = "()"
return (
_create_fn(
"__setattr__",
("self", "name", "value"),
(
f"if type(self) is cls or name in {fields_str}:",
' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
f"super(cls, self).__setattr__(name, value)",
),
globals=globals,
),
_create_fn(
"__delattr__",
("self", "name"),
(
f"if type(self) is cls or name in {fields_str}:",
' raise FrozenInstanceError(f"cannot delete field {name!r}")',
f"super(cls, self).__delattr__(name)",
),
globals=globals,
),
)
def _cmp_fn(name, op, self_tuple, other_tuple):
# Create a comparison function. If the fields in the object are
# named 'x' and 'y', then self_tuple is the string
# '(self.x,self.y)' and other_tuple is the string
# '(other.x,other.y)'.
return _create_fn(
name,
("self", "other"),
[
"if other.__class__ is self.__class__:",
f" return {self_tuple}{op}{other_tuple}",
"return NotImplemented",
],
)
def _hash_fn(fields):
self_tuple = _tuple_str("self", fields)
return _create_fn("__hash__", ("self",), [f"return hash({self_tuple})"])
def _is_classvar(a_type, typing):
# This test uses a typing internal class, but it's the best way to
# test if this is a ClassVar.
return type(a_type) is typing._ClassVar
def _is_initvar(a_type, dataclasses):
# The module we're checking against is the module we're
# currently in (dataclasses.py).
return a_type is dataclasses.InitVar
def _is_type(annotation, cls, a_module, a_type, is_type_predicate):
# Given a type annotation string, does it refer to a_type in
# a_module? For example, when checking that annotation denotes a
# ClassVar, then a_module is typing, and a_type is
# typing.ClassVar.
# It's possible to look up a_module given a_type, but it involves
# looking in sys.modules (again!), and seems like a waste since
# the caller already knows a_module.
# - annotation is a string type annotation
# - cls is the class that this annotation was found in
# - a_module is the module we want to match
# - a_type is the type in that module we want to match
# - is_type_predicate is a function called with (obj, a_module)
# that determines if obj is of the desired type.
# Since this test does not do a local namespace lookup (and
# instead only a module (global) lookup), there are some things it
# gets wrong.
# With string annotations, cv0 will be detected as a ClassVar:
# CV = ClassVar
# @dataclass
# class C0:
# cv0: CV
# But in this example cv1 will not be detected as a ClassVar:
# @dataclass
# class C1:
# CV = ClassVar
# cv1: CV
# In C1, the code in this function (_is_type) will look up "CV" in
# the module and not find it, so it will not consider cv1 as a
# ClassVar. This is a fairly obscure corner case, and the best
# way to fix it would be to eval() the string "CV" with the
# correct global and local namespaces. However that would involve
# a eval() penalty for every single field of every dataclass
# that's defined. It was judged not worth it.
match = _MODULE_IDENTIFIER_RE.match(annotation)
if match:
ns = None
module_name = match.group(1)
if not module_name:
# No module name, assume the class's module did
# "from dataclasses import InitVar".
ns = sys.modules.get(cls.__module__).__dict__
else:
# Look up module_name in the class's module.
module = sys.modules.get(cls.__module__)
if module and module.__dict__.get(module_name) is a_module:
ns = sys.modules.get(a_type.__module__).__dict__
if ns and is_type_predicate(ns.get(match.group(2)), a_module):
return True
return False
def _get_field(cls, a_name, a_type):
# Return a Field object for this field name and type. ClassVars
# and InitVars are also returned, but marked as such (see
# f._field_type).
# If the default value isn't derived from Field, then it's only a
# normal default value. Convert it to a Field().
default = getattr(cls, a_name, MISSING)
if isinstance(default, Field):
f = default
else:
if isinstance(default, types.MemberDescriptorType):
# This is a field in __slots__, so it has no default value.
default = MISSING
f = field(default=default)
# Only at this point do we know the name and the type. Set them.
f.name = a_name
f.type = a_type
# Assume it's a normal field until proven otherwise. We're next
# going to decide if it's a ClassVar or InitVar, everything else
# is just a normal field.
f._field_type = _FIELD
# In addition to checking for actual types here, also check for
# string annotations. get_type_hints() won't always work for us
# (see https://github.com/python/typing/issues/508 for example),
# plus it's expensive and would require an eval for every stirng
# annotation. So, make a best effort to see if this is a ClassVar
# or InitVar using regex's and checking that the thing referenced
# is actually of the correct type.
# For the complete discussion, see https://bugs.python.org/issue33453
# If typing has not been imported, then it's impossible for any
# annotation to be a ClassVar. So, only look for ClassVar if
# typing has been imported by any module (not necessarily cls's
# module).
typing = sys.modules.get("typing")
if typing:
if _is_classvar(a_type, typing) or (
isinstance(f.type, str) and _is_type(f.type, cls, typing, typing.ClassVar, _is_classvar)
):
f._field_type = _FIELD_CLASSVAR
# If the type is InitVar, or if it's a matching string annotation,
# then it's an InitVar.
if f._field_type is _FIELD:
# The module we're checking against is the module we're
# currently in (dataclasses.py).
dataclasses = sys.modules[__name__]
if _is_initvar(a_type, dataclasses) or (
isinstance(f.type, str)
and _is_type(f.type, cls, dataclasses, dataclasses.InitVar, _is_initvar)
):
f._field_type = _FIELD_INITVAR
# Validations for individual fields. This is delayed until now,
# instead of in the Field() constructor, since only here do we
# know the field name, which allows for better error reporting.
# Special restrictions for ClassVar and InitVar.
if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):
if f.default_factory is not MISSING:
raise TypeError(f"field {f.name} cannot have a " "default factory")
# Should I check for other field settings? default_factory
# seems the most serious to check for. Maybe add others. For
# example, how about init=False (or really,
# init=<not-the-default-init-value>)? It makes no sense for
# ClassVar and InitVar to specify init=<anything>.
# For real fields, disallow mutable defaults for known types.
if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)):
raise ValueError(
f"mutable default {type(f.default)} for field "
f"{f.name} is not allowed: use default_factory"
)
return f
def _set_new_attribute(cls, name, value):
# Never overwrites an existing attribute. Returns True if the
# attribute already exists.
if name in cls.__dict__:
return True
setattr(cls, name, value)
return False
# Decide if/how we're going to create a hash function. Key is
# (unsafe_hash, eq, frozen, does-hash-exist). Value is the action to
# take. The common case is to do nothing, so instead of providing a
# function that is a no-op, use None to signify that.
def _hash_set_none(cls, fields):
return None
def _hash_add(cls, fields):
flds = [f for f in fields if (f.compare if f.hash is None else f.hash)]
return _hash_fn(flds)
def _hash_exception(cls, fields):
# Raise an exception.
raise TypeError(f"Cannot overwrite attribute __hash__ " f"in class {cls.__name__}")
#
# +-------------------------------------- unsafe_hash?
# | +------------------------------- eq?
# | | +------------------------ frozen?
# | | | +---------------- has-explicit-hash?
# | | | |
# | | | | +------- action
# | | | | |
# v v v v v
_hash_action = {
(False, False, False, False): None,
(False, False, False, True): None,
(False, False, True, False): None,
(False, False, True, True): None,
(False, True, False, False): _hash_set_none,
(False, True, False, True): None,
(False, True, True, False): _hash_add,
(False, True, True, True): None,
(True, False, False, False): _hash_add,
(True, False, False, True): _hash_exception,
(True, False, True, False): _hash_add,
(True, False, True, True): _hash_exception,
(True, True, False, False): _hash_add,
(True, True, False, True): _hash_exception,
(True, True, True, False): _hash_add,
(True, True, True, True): _hash_exception,
}
# See https://bugs.python.org/issue32929#msg312829 for an if-statement
# version of this table.
def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
# Now that dicts retain insertion order, there's no reason to use
# an ordered dict. I am leveraging that ordering here, because
# derived class fields overwrite base class fields, but the order
# is defined by the base class, which is found first.
fields = {}
setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order, unsafe_hash, frozen))
# Find our base classes in reverse MRO order, and exclude
# ourselves. In reversed order so that more derived classes
# override earlier field definitions in base classes. As long as
# we're iterating over them, see if any are frozen.
any_frozen_base = False
has_dataclass_bases = False
for b in cls.__mro__[-1:0:-1]:
# Only process classes that have been processed by our
# decorator. That is, they have a _FIELDS attribute.
base_fields = getattr(b, _FIELDS, None)
if base_fields:
has_dataclass_bases = True
for f in base_fields.values():
fields[f.name] = f
if getattr(b, _PARAMS).frozen:
any_frozen_base = True
# Annotations that are defined in this class (not in base
# classes). If __annotations__ isn't present, then this class
# adds no new annotations. We use this to compute fields that are
# added by this class.
#
# Fields are found from cls_annotations, which is guaranteed to be
# ordered. Default values are from class attributes, if a field
# has a default. If the default value is a Field(), then it
# contains additional info beyond (and possibly including) the
# actual default value. Pseudo-fields ClassVars and InitVars are
# included, despite the fact that they're not real fields. That's
# dealt with later.
cls_annotations = cls.__dict__.get("__annotations__", {})
# Now find fields in our class. While doing so, validate some
# things, and set the default values (as class attributes) where
# we can.
cls_fields = [_get_field(cls, name, type) for name, type in cls_annotations.items()]
for f in cls_fields:
fields[f.name] = f
# If the class attribute (which is the default value for this
# field) exists and is of type 'Field', replace it with the
# real default. This is so that normal class introspection
# sees a real default value, not a Field.
if isinstance(getattr(cls, f.name, None), Field):
if f.default is MISSING:
# If there's no default, delete the class attribute.
# This happens if we specify field(repr=False), for
# example (that is, we specified a field object, but
# no default value). Also if we're using a default
# factory. The class attribute should not be set at
# all in the post-processed class.
delattr(cls, f.name)
else:
setattr(cls, f.name, f.default)
# Do we have any Field members that don't also have annotations?
for name, value in cls.__dict__.items():
if isinstance(value, Field) and not name in cls_annotations:
raise TypeError(f"{name!r} is a field but has no type annotation")
# Check rules that apply if we are derived from any dataclasses.
if has_dataclass_bases:
# Raise an exception if any of our bases are frozen, but we're not.
if any_frozen_base and not frozen:
raise TypeError("cannot inherit non-frozen dataclass from a " "frozen one")
# Raise an exception if we're frozen, but none of our bases are.
if not any_frozen_base and frozen:
raise TypeError("cannot inherit frozen dataclass from a " "non-frozen one")
# Remember all of the fields on our class (including bases). This
# also marks this class as being a dataclass.
setattr(cls, _FIELDS, fields)
# Was this class defined with an explicit __hash__? Note that if
# __eq__ is defined in this class, then python will automatically
# set __hash__ to None. This is a heuristic, as it's possible
# that such a __hash__ == None was not auto-generated, but it
# close enough.
class_hash = cls.__dict__.get("__hash__", MISSING)
has_explicit_hash = not (
class_hash is MISSING or (class_hash is None and "__eq__" in cls.__dict__)
)
# If we're generating ordering methods, we must be generating the
# eq methods.
if order and not eq:
raise ValueError("eq must be true if order is true")
if init:
# Does this class have a post-init function?
has_post_init = hasattr(cls, _POST_INIT_NAME)
# Include InitVars and regular fields (so, not ClassVars).
flds = [f for f in fields.values() if f._field_type in (_FIELD, _FIELD_INITVAR)]
_set_new_attribute(
cls,
"__init__",
_init_fn(
flds,
frozen,
has_post_init,
# The name to use for the "self"
# param in __init__. Use "self"
# if possible.
"__dataclass_self__" if "self" in fields else "self",
),
)
# Get the fields as a list, and include only real fields. This is
# used in all of the following methods.
field_list = [f for f in fields.values() if f._field_type is _FIELD]
if repr:
flds = [f for f in field_list if f.repr]
_set_new_attribute(cls, "__repr__", _repr_fn(flds))
if eq:
# Create _eq__ method. There's no need for a __ne__ method,
# since python will call __eq__ and negate it.
flds = [f for f in field_list if f.compare]
self_tuple = _tuple_str("self", flds)
other_tuple = _tuple_str("other", flds)
_set_new_attribute(cls, "__eq__", _cmp_fn("__eq__", "==", self_tuple, other_tuple))
if order:
# Create and set the ordering methods.
flds = [f for f in field_list if f.compare]
self_tuple = _tuple_str("self", flds)
other_tuple = _tuple_str("other", flds)
for name, op in [("__lt__", "<"), ("__le__", "<="), ("__gt__", ">"), ("__ge__", ">=")]:
if _set_new_attribute(cls, name, _cmp_fn(name, op, self_tuple, other_tuple)):
raise TypeError(
f"Cannot overwrite attribute {name} "
f"in class {cls.__name__}. Consider using "
"functools.total_ordering"
)
if frozen:
for fn in _frozen_get_del_attr(cls, field_list):
if _set_new_attribute(cls, fn.__name__, fn):
raise TypeError(
f"Cannot overwrite attribute {fn.__name__} " f"in class {cls.__name__}"
)
# Decide if/how we're going to create a hash function.
hash_action = _hash_action[bool(unsafe_hash), bool(eq), bool(frozen), has_explicit_hash]
if hash_action:
# No need to call _set_new_attribute here, since by the time
# we're here the overwriting is unconditional.
cls.__hash__ = hash_action(cls, field_list)
if not getattr(cls, "__doc__"):
# Create a class doc-string.
cls.__doc__ = cls.__name__ + str(inspect.signature(cls)).replace(" -> None", "")
return cls
# _cls should never be specified by keyword, so start it with an
# underscore. The presence of _cls is used to detect if this
# decorator is being called with parameters or not.
def dataclass(
_cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False
):
"""Returns the same class as was passed in, with dunder methods
added based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine fields.
If init is true, an __init__() method is added to the class. If
repr is true, a __repr__() method is added. If order is true, rich
comparison dunder methods are added. If unsafe_hash is true, a
__hash__() method function is added. If frozen is true, fields may
not be assigned to after instance creation.
"""
def wrap(cls):
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
# See if we're being called as @dataclass or @dataclass().
if _cls is None:
# We're called with parens.
return wrap
# We're called as @dataclass without parens.
return wrap(_cls)
def fields(class_or_instance):
"""Return a tuple describing the fields of this dataclass.
Accepts a dataclass or an instance of one. Tuple elements are of
type Field.
"""
# Might it be worth caching this, per class?
try:
fields = getattr(class_or_instance, _FIELDS)
except AttributeError:
raise TypeError("must be called with a dataclass type or instance")
# Exclude pseudo-fields. Note that fields is sorted by insertion
# order, so the order of the tuple is as the fields were defined.
return tuple(f for f in fields.values() if f._field_type is _FIELD)
def _is_dataclass_instance(obj):
"""Returns True if obj is an instance of a dataclass."""
return not isinstance(obj, type) and hasattr(obj, _FIELDS)
def is_dataclass(obj):
"""Returns True if obj is a dataclass or an instance of a
dataclass."""
return hasattr(obj, _FIELDS)
def asdict(obj, *, dict_factory=dict):
"""Return the fields of a dataclass instance as a new dictionary mapping
field names to field values.
Example usage:
@dataclass
class C:
x: int
y: int
c = C(1, 2)
assert asdict(c) == {'x': 1, 'y': 2}
If given, 'dict_factory' will be used instead of built-in dict.
The function applies recursively to field values that are
dataclass instances. This will also look into built-in containers:
tuples, lists, and dicts.
"""
if not _is_dataclass_instance(obj):
raise TypeError("asdict() should be called on dataclass instances")
return _asdict_inner(obj, dict_factory)
def _asdict_inner(obj, dict_factory):
if _is_dataclass_instance(obj):
result = []
for f in fields(obj):
value = _asdict_inner(getattr(obj, f.name), dict_factory)
result.append((f.name, value))
return dict_factory(result)
elif isinstance(obj, (list, tuple)):
return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
elif isinstance(obj, dict):
return type(obj)(
(_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items()
)
else:
return copy.deepcopy(obj)
def astuple(obj, *, tuple_factory=tuple):
"""Return the fields of a dataclass instance as a new tuple of field values.
Example usage::
@dataclass
class C:
x: int
y: int
c = C(1, 2)
assert astuple(c) == (1, 2)
If given, 'tuple_factory' will be used instead of built-in tuple.
The function applies recursively to field values that are
dataclass instances. This will also look into built-in containers:
tuples, lists, and dicts.
"""
if not _is_dataclass_instance(obj):
raise TypeError("astuple() should be called on dataclass instances")
return _astuple_inner(obj, tuple_factory)
def _astuple_inner(obj, tuple_factory):
if _is_dataclass_instance(obj):
result = []
for f in fields(obj):
value = _astuple_inner(getattr(obj, f.name), tuple_factory)
result.append(value)
return tuple_factory(result)
elif isinstance(obj, (list, tuple)):
return type(obj)(_astuple_inner(v, tuple_factory) for v in obj)
elif isinstance(obj, dict):
return type(obj)(
(_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory))
for k, v in obj.items()
)
else:
return copy.deepcopy(obj)
def make_dataclass(
cls_name,
fields,
*,
bases=(),
namespace=None,
init=True,
repr=True,
eq=True,
order=False,
unsafe_hash=False,
frozen=False,
):
"""Return a new dynamically created dataclass.
The dataclass name will be 'cls_name'. 'fields' is an iterable
of either (name), (name, type) or (name, type, Field) objects. If type is
omitted, use the string 'typing.Any'. Field objects are created by
the equivalent of calling 'field(name, type [, Field-info])'.
C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,))
is equivalent to:
@dataclass
class C(Base):
x: 'typing.Any'
y: int
z: int = field(init=False)
For the bases and namespace parameters, see the builtin type() function.
The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to
dataclass().
"""
if namespace is None:
namespace = {}
else:
# Copy namespace since we're going to mutate it.
namespace = namespace.copy()
# While we're looking through the field names, validate that they
# are identifiers, are not keywords, and not duplicates.
seen = set()
anns = {}
for item in fields:
if isinstance(item, str):
name = item
tp = "typing.Any"
elif len(item) == 2:
name, tp, = item
elif len(item) == 3:
name, tp, spec = item
namespace[name] = spec
else:
raise TypeError(f"Invalid field: {item!r}")
if not isinstance(name, str) or not name.isidentifier():
raise TypeError(f"Field names must be valid identifers: {name!r}")
if keyword.iskeyword(name):
raise TypeError(f"Field names must not be keywords: {name!r}")
if name in seen:
raise TypeError(f"Field name duplicated: {name!r}")
seen.add(name)
anns[name] = tp
namespace["__annotations__"] = anns
# We use `types.new_class()` instead of simply `type()` to allow dynamic creation
# of generic dataclassses.
cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace))
return dataclass(
cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen
)
def replace(obj, **changes):
"""Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@dataclass(frozen=True)
class C:
x: int
y: int
c = C(1, 2)
c1 = replace(c, x=3)
assert c1.x == 3 and c1.y == 2
"""
# We're going to mutate 'changes', but that's okay because it's a
# new dict, even if called with 'replace(obj, **my_changes)'.
if not _is_dataclass_instance(obj):
raise TypeError("replace() should be called on dataclass instances")
# It's an error to have init=False fields in 'changes'.
# If a field is not in 'changes', read its value from the provided obj.
for f in getattr(obj, _FIELDS).values():
if not f.init:
# Error if this field is specified in changes.
if f.name in changes:
raise ValueError(
f"field {f.name} is declared with "
"init=False, it cannot be specified with "
"replace()"
)
continue
if f.name not in changes:
changes[f.name] = getattr(obj, f.name)
# Create the new object, which calls __init__() and
# __post_init__() (if defined), using all of the init fields we've
# added and/or left in 'changes'. If there are values supplied in
# changes that aren't fields, this will correctly raise a
# TypeError.
return obj.__class__(**changes)
| 36.529851 | 100 | 0.605902 |
import copy
import inspect
import keyword
import re
import sys
import types
__all__ = [
"dataclass",
"field",
"Field",
"FrozenInstanceError",
"InitVar",
"MISSING",
"fields",
"asdict",
"astuple",
"make_dataclass",
"replace",
"is_dataclass",
]
# referring to the arguments to the @dataclass decorator. When
# checking if a dunder method already exists, I mean check for an
# entry in the class's __dict__. I never check to see if an attribute
class FrozenInstanceError(AttributeError):
pass
class _HAS_DEFAULT_FACTORY_CLASS:
def __repr__(self):
return "<factory>"
_HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()
# A sentinel object to detect if a parameter is supplied or not. Use
# a class to give it a better repr.
class _MISSING_TYPE:
pass
MISSING = _MISSING_TYPE()
# Since most per-field metadata will be unused, create an empty
# read-only proxy that can be shared among all fields.
_EMPTY_METADATA = types.MappingProxyType({})
# Markers for the various kinds of fields and pseudo-fields.
class _FIELD_BASE:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
_FIELD = _FIELD_BASE("_FIELD")
_FIELD_CLASSVAR = _FIELD_BASE("_FIELD_CLASSVAR")
_FIELD_INITVAR = _FIELD_BASE("_FIELD_INITVAR")
# The name of an attribute on the class where we store the Field
# objects. Also used to check if a class is a Data Class.
_FIELDS = "__dataclass_fields__"
# The name of an attribute on the class that stores the parameters to
# @dataclass.
_PARAMS = "__dataclass_params__"
# The name of the function, that if it exists, is called at the end of
# __init__.
_POST_INIT_NAME = "__post_init__"
# String regex that string annotations for ClassVar or InitVar must match.
# Allows "identifier.identifier[" or "identifier[".
# https://bugs.python.org/issue33453 for details.
_MODULE_IDENTIFIER_RE = re.compile(r"^(?:\s*(\w+)\s*\.)?\s*(\w+)")
class _InitVarMeta(type):
def __getitem__(self, params):
return self
class InitVar(metaclass=_InitVarMeta):
pass
# Instances of Field are only ever created from within this module,
# and only from the field() function, although Field instances are
# exposed externally as (conceptually) read-only objects.
#
# name and type are filled in after the fact, not in __init__.
# They're not known at the time this class is instantiated, but it's
# convenient if they're available later.
class Field:
__slots__ = (
"name",
"type",
"default",
"default_factory",
"repr",
"hash",
"init",
"compare",
"metadata",
"_field_type",
)
def __init__(self, default, default_factory, init, repr, hash, compare, metadata):
self.name = None
self.type = None
self.default = default
self.default_factory = default_factory
self.init = init
self.repr = repr
self.hash = hash
self.compare = compare
self.metadata = (
_EMPTY_METADATA
if metadata is None or len(metadata) == 0
else types.MappingProxyType(metadata)
)
self._field_type = None
def __repr__(self):
return (
"Field("
f"name={self.name!r},"
f"type={self.type!r},"
f"default={self.default!r},"
f"default_factory={self.default_factory!r},"
f"init={self.init!r},"
f"repr={self.repr!r},"
f"hash={self.hash!r},"
f"compare={self.compare!r},"
f"metadata={self.metadata!r},"
f"_field_type={self._field_type}"
")"
)
# defaul value. For details on __set_name__, see
# https://www.python.org/dev/peps/pep-0487/#implementation-details.
#
# Note that in _process_class, this Field object is overwritten
# with the default value, so the end result is a descriptor that
# had __set_name__ called on it at the right time.
def __set_name__(self, owner, name):
func = getattr(type(self.default), "__set_name__", None)
if func:
# There is a __set_name__ method on the descriptor, call
# it.
func(self.default, owner, name)
class _DataclassParams:
__slots__ = ("init", "repr", "eq", "order", "unsafe_hash", "frozen")
def __init__(self, init, repr, eq, order, unsafe_hash, frozen):
self.init = init
self.repr = repr
self.eq = eq
self.order = order
self.unsafe_hash = unsafe_hash
self.frozen = frozen
def __repr__(self):
return (
"_DataclassParams("
f"init={self.init!r},"
f"repr={self.repr!r},"
f"eq={self.eq!r},"
f"order={self.order!r},"
f"unsafe_hash={self.unsafe_hash!r},"
f"frozen={self.frozen!r}"
")"
)
# This function is used instead of exposing Field creation directly,
# so that a type checker can be told (via overloads) that this is a
# function whose type depends on its parameters.
def field(
*,
default=MISSING,
default_factory=MISSING,
init=True,
repr=True,
hash=None,
compare=True,
metadata=None,
):
if default is not MISSING and default_factory is not MISSING:
raise ValueError("cannot specify both default and default_factory")
return Field(default, default_factory, init, repr, hash, compare, metadata)
def _tuple_str(obj_name, fields):
# Return a string representing each field of obj_name as a tuple
# member. So, if fields is ['x', 'y'] and obj_name is "self",
# return "(self.x,self.y)".
# Special case for the 0-tuple.
if not fields:
return "()"
# Note the trailing comma, needed if this turns out to be a 1-tuple.
return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)'
def _create_fn(name, args, body, *, globals=None, locals=None, return_type=MISSING):
# Note that we mutate locals when exec() is called. Caller
# beware! The only callers are internal to this module, so no
# worries about external callers.
if locals is None:
locals = {}
return_annotation = ""
if return_type is not MISSING:
locals["_return_type"] = return_type
return_annotation = "->_return_type"
args = ",".join(args)
body = "\n".join(f" {b}" for b in body)
# Compute the text of the entire function.
txt = f"def {name}({args}){return_annotation}:\n{body}"
exec(txt, globals, locals) # nosec
return locals[name]
def _field_assign(frozen, name, value, self_name):
# If we're a frozen class, then assign to our fields in __init__
# hard-code "self", since that might be a field name.
if frozen:
return f"object.__setattr__({self_name},{name!r},{value})"
return f"{self_name}.{name}={value}"
def _field_init(f, frozen, globals, self_name):
# Return the text of the line in the body of __init__ that will
# initialize this field.
default_name = f"_dflt_{f.name}"
if f.default_factory is not MISSING:
if f.init:
# This field has a default factory. If a parameter is
# given, use it. If not, call the factory.
globals[default_name] = f.default_factory
value = f"{default_name}() " f"if {f.name} is _HAS_DEFAULT_FACTORY " f"else {f.name}"
else:
# This is a field that's not in the __init__ params, but
# For a field initialized with a default=defaultvalue, the
# class dict just has the default value
# (cls.fieldname=defaultvalue). But that won't work for a
# fall back to the class dict's value, both because it's
# not set, and because it might be different per-class
# (which, after all, is why we have a factory function!).
globals[default_name] = f.default_factory
value = f"{default_name}()"
else:
# No default factory.
if f.init:
if f.default is MISSING:
# There's no default, just do an assignment.
value = f.name
elif f.default is not MISSING:
globals[default_name] = f.default
value = f.name
else:
return None
# to actually do the assignment statement for InitVars.
if f._field_type == _FIELD_INITVAR:
return None
# Now, actually generate the field assignment.
return _field_assign(frozen, f.name, value, self_name)
def _init_param(f):
# Return the __init__ parameter string for this field. For
# example, the equivalent of 'x:int=3' (except instead of 'int',
# reference a variable set to int, and instead of '3', reference a
# variable set to 3).
if f.default is MISSING and f.default_factory is MISSING:
# There's no default, and no default_factory, just output the
default = ""
elif f.default is not MISSING:
default = f"=_dflt_{f.name}"
elif f.default_factory is not MISSING:
default = "=_HAS_DEFAULT_FACTORY"
return f"{f.name}:_type_{f.name}{default}"
def _init_fn(fields, frozen, has_post_init, self_name):
# fields contains both real fields and InitVar pseudo-fields.
# Make sure we don't have fields without defaults following fields
seen_default = False
for f in fields:
if f.init:
if not (f.default is MISSING and f.default_factory is MISSING):
seen_default = True
elif seen_default:
raise TypeError(f"non-default argument {f.name!r} " "follows default argument")
globals = {"MISSING": MISSING, "_HAS_DEFAULT_FACTORY": _HAS_DEFAULT_FACTORY}
body_lines = []
for f in fields:
line = _field_init(f, frozen, globals, self_name)
# initialization (it's a pseudo-field). Just skip it.
if line:
body_lines.append(line)
if has_post_init:
params_str = ",".join(f.name for f in fields if f._field_type is _FIELD_INITVAR)
body_lines.append(f"{self_name}.{_POST_INIT_NAME}({params_str})")
if not body_lines:
body_lines = ["pass"]
locals = {f"_type_{f.name}": f.type for f in fields}
return _create_fn(
"__init__",
[self_name] + [_init_param(f) for f in fields if f.init],
body_lines,
locals=locals,
globals=globals,
return_type=None,
)
def _repr_fn(fields):
return _create_fn(
"__repr__",
("self",),
[
'return self.__class__.__qualname__ + f"('
+ ", ".join([f"{f.name}={{self.{f.name}!r}}" for f in fields])
+ ')"'
],
)
def _frozen_get_del_attr(cls, fields):
globals = {"cls": cls, "FrozenInstanceError": FrozenInstanceError}
if fields:
fields_str = "(" + ",".join(repr(f.name) for f in fields) + ",)"
else:
fields_str = "()"
return (
_create_fn(
"__setattr__",
("self", "name", "value"),
(
f"if type(self) is cls or name in {fields_str}:",
' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
f"super(cls, self).__setattr__(name, value)",
),
globals=globals,
),
_create_fn(
"__delattr__",
("self", "name"),
(
f"if type(self) is cls or name in {fields_str}:",
' raise FrozenInstanceError(f"cannot delete field {name!r}")',
f"super(cls, self).__delattr__(name)",
),
globals=globals,
),
)
def _cmp_fn(name, op, self_tuple, other_tuple):
return _create_fn(
name,
("self", "other"),
[
"if other.__class__ is self.__class__:",
f" return {self_tuple}{op}{other_tuple}",
"return NotImplemented",
],
)
def _hash_fn(fields):
self_tuple = _tuple_str("self", fields)
return _create_fn("__hash__", ("self",), [f"return hash({self_tuple})"])
def _is_classvar(a_type, typing):
# test if this is a ClassVar.
return type(a_type) is typing._ClassVar
def _is_initvar(a_type, dataclasses):
# The module we're checking against is the module we're
# currently in (dataclasses.py).
return a_type is dataclasses.InitVar
def _is_type(annotation, cls, a_module, a_type, is_type_predicate):
# Given a type annotation string, does it refer to a_type in
# a_module? For example, when checking that annotation denotes a
# ClassVar, then a_module is typing, and a_type is
# typing.ClassVar.
# It's possible to look up a_module given a_type, but it involves
match = _MODULE_IDENTIFIER_RE.match(annotation)
if match:
ns = None
module_name = match.group(1)
if not module_name:
# No module name, assume the class's module did
ns = sys.modules.get(cls.__module__).__dict__
else:
module = sys.modules.get(cls.__module__)
if module and module.__dict__.get(module_name) is a_module:
ns = sys.modules.get(a_type.__module__).__dict__
if ns and is_type_predicate(ns.get(match.group(2)), a_module):
return True
return False
def _get_field(cls, a_name, a_type):
# Return a Field object for this field name and type. ClassVars
# and InitVars are also returned, but marked as such (see
# f._field_type).
# If the default value isn't derived from Field, then it's only a
# normal default value. Convert it to a Field().
default = getattr(cls, a_name, MISSING)
if isinstance(default, Field):
f = default
else:
if isinstance(default, types.MemberDescriptorType):
# This is a field in __slots__, so it has no default value.
default = MISSING
f = field(default=default)
# Only at this point do we know the name and the type. Set them.
f.name = a_name
f.type = a_type
# Assume it's a normal field until proven otherwise. We're next
# going to decide if it's a ClassVar or InitVar, everything else
f._field_type = _FIELD
# (see https://github.com/python/typing/issues/508 for example),
# plus it's expensive and would require an eval for every stirng
# is actually of the correct type.
# For the complete discussion, see https://bugs.python.org/issue33453
# If typing has not been imported, then it's impossible for any
# module).
typing = sys.modules.get("typing")
if typing:
if _is_classvar(a_type, typing) or (
isinstance(f.type, str) and _is_type(f.type, cls, typing, typing.ClassVar, _is_classvar)
):
f._field_type = _FIELD_CLASSVAR
# If the type is InitVar, or if it's a matching string annotation,
if f._field_type is _FIELD:
# The module we're checking against is the module we're
# currently in (dataclasses.py).
dataclasses = sys.modules[__name__]
if _is_initvar(a_type, dataclasses) or (
isinstance(f.type, str)
and _is_type(f.type, cls, dataclasses, dataclasses.InitVar, _is_initvar)
):
f._field_type = _FIELD_INITVAR
# Validations for individual fields. This is delayed until now,
# instead of in the Field() constructor, since only here do we
# know the field name, which allows for better error reporting.
# Special restrictions for ClassVar and InitVar.
if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):
if f.default_factory is not MISSING:
raise TypeError(f"field {f.name} cannot have a " "default factory")
# Should I check for other field settings? default_factory
# seems the most serious to check for. Maybe add others. For
# example, how about init=False (or really,
# init=<not-the-default-init-value>)? It makes no sense for
# ClassVar and InitVar to specify init=<anything>.
# For real fields, disallow mutable defaults for known types.
if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)):
raise ValueError(
f"mutable default {type(f.default)} for field "
f"{f.name} is not allowed: use default_factory"
)
return f
def _set_new_attribute(cls, name, value):
# Never overwrites an existing attribute. Returns True if the
# attribute already exists.
if name in cls.__dict__:
return True
setattr(cls, name, value)
return False
# Decide if/how we're going to create a hash function. Key is
def _hash_set_none(cls, fields):
return None
def _hash_add(cls, fields):
flds = [f for f in fields if (f.compare if f.hash is None else f.hash)]
return _hash_fn(flds)
def _hash_exception(cls, fields):
raise TypeError(f"Cannot overwrite attribute __hash__ " f"in class {cls.__name__}")
_hash_action = {
(False, False, False, False): None,
(False, False, False, True): None,
(False, False, True, False): None,
(False, False, True, True): None,
(False, True, False, False): _hash_set_none,
(False, True, False, True): None,
(False, True, True, False): _hash_add,
(False, True, True, True): None,
(True, False, False, False): _hash_add,
(True, False, False, True): _hash_exception,
(True, False, True, False): _hash_add,
(True, False, True, True): _hash_exception,
(True, True, False, False): _hash_add,
(True, True, False, True): _hash_exception,
(True, True, True, False): _hash_add,
(True, True, True, True): _hash_exception,
}
it, repr, eq, order, unsafe_hash, frozen):
# an ordered dict. I am leveraging that ordering here, because
# derived class fields overwrite base class fields, but the order
# is defined by the base class, which is found first.
fields = {}
setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order, unsafe_hash, frozen))
# Find our base classes in reverse MRO order, and exclude
# ourselves. In reversed order so that more derived classes
# override earlier field definitions in base classes. As long as
# we're iterating over them, see if any are frozen.
any_frozen_base = False
has_dataclass_bases = False
for b in cls.__mro__[-1:0:-1]:
base_fields = getattr(b, _FIELDS, None)
if base_fields:
has_dataclass_bases = True
for f in base_fields.values():
fields[f.name] = f
if getattr(b, _PARAMS).frozen:
any_frozen_base = True
# adds no new annotations. We use this to compute fields that are
# added by this class.
#
# Fields are found from cls_annotations, which is guaranteed to be
# ordered. Default values are from class attributes, if a field
# has a default. If the default value is a Field(), then it
# contains additional info beyond (and possibly including) the
# actual default value. Pseudo-fields ClassVars and InitVars are
# included, despite the fact that they're not real fields. That's
# dealt with later.
cls_annotations = cls.__dict__.get("__annotations__", {})
# Now find fields in our class. While doing so, validate some
# things, and set the default values (as class attributes) where
# we can.
cls_fields = [_get_field(cls, name, type) for name, type in cls_annotations.items()]
for f in cls_fields:
fields[f.name] = f
# If the class attribute (which is the default value for this
# field) exists and is of type 'Field', replace it with the
# real default. This is so that normal class introspection
# sees a real default value, not a Field.
if isinstance(getattr(cls, f.name, None), Field):
if f.default is MISSING:
# If there's no default, delete the class attribute.
# factory. The class attribute should not be set at
# all in the post-processed class.
delattr(cls, f.name)
else:
setattr(cls, f.name, f.default)
# Do we have any Field members that don't also have annotations?
for name, value in cls.__dict__.items():
if isinstance(value, Field) and not name in cls_annotations:
raise TypeError(f"{name!r} is a field but has no type annotation")
if has_dataclass_bases:
if any_frozen_base and not frozen:
raise TypeError("cannot inherit non-frozen dataclass from a " "frozen one")
# Raise an exception if we're frozen, but none of our bases are.
if not any_frozen_base and frozen:
raise TypeError("cannot inherit frozen dataclass from a " "non-frozen one")
setattr(cls, _FIELDS, fields)
# that such a __hash__ == None was not auto-generated, but it
# close enough.
class_hash = cls.__dict__.get("__hash__", MISSING)
has_explicit_hash = not (
class_hash is MISSING or (class_hash is None and "__eq__" in cls.__dict__)
)
# If we're generating ordering methods, we must be generating the
if order and not eq:
raise ValueError("eq must be true if order is true")
if init:
has_post_init = hasattr(cls, _POST_INIT_NAME)
flds = [f for f in fields.values() if f._field_type in (_FIELD, _FIELD_INITVAR)]
_set_new_attribute(
cls,
"__init__",
_init_fn(
flds,
frozen,
has_post_init,
"__dataclass_self__" if "self" in fields else "self",
),
)
field_list = [f for f in fields.values() if f._field_type is _FIELD]
if repr:
flds = [f for f in field_list if f.repr]
_set_new_attribute(cls, "__repr__", _repr_fn(flds))
if eq:
# since python will call __eq__ and negate it.
flds = [f for f in field_list if f.compare]
self_tuple = _tuple_str("self", flds)
other_tuple = _tuple_str("other", flds)
_set_new_attribute(cls, "__eq__", _cmp_fn("__eq__", "==", self_tuple, other_tuple))
if order:
# Create and set the ordering methods.
flds = [f for f in field_list if f.compare]
self_tuple = _tuple_str("self", flds)
other_tuple = _tuple_str("other", flds)
for name, op in [("__lt__", "<"), ("__le__", "<="), ("__gt__", ">"), ("__ge__", ">=")]:
if _set_new_attribute(cls, name, _cmp_fn(name, op, self_tuple, other_tuple)):
raise TypeError(
f"Cannot overwrite attribute {name} "
f"in class {cls.__name__}. Consider using "
"functools.total_ordering"
)
if frozen:
for fn in _frozen_get_del_attr(cls, field_list):
if _set_new_attribute(cls, fn.__name__, fn):
raise TypeError(
f"Cannot overwrite attribute {fn.__name__} " f"in class {cls.__name__}"
)
# Decide if/how we're going to create a hash function.
hash_action = _hash_action[bool(unsafe_hash), bool(eq), bool(frozen), has_explicit_hash]
if hash_action:
cls.__hash__ = hash_action(cls, field_list)
if not getattr(cls, "__doc__"):
# Create a class doc-string.
cls.__doc__ = cls.__name__ + str(inspect.signature(cls)).replace(" -> None", "")
return cls
# _cls should never be specified by keyword, so start it with an
# underscore. The presence of _cls is used to detect if this
# decorator is being called with parameters or not.
def dataclass(
_cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False
):
def wrap(cls):
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
# See if we're being called as @dataclass or @dataclass().
if _cls is None:
return wrap
# We're called as @dataclass without parens.
return wrap(_cls)
def fields(class_or_instance):
try:
fields = getattr(class_or_instance, _FIELDS)
except AttributeError:
raise TypeError("must be called with a dataclass type or instance")
return tuple(f for f in fields.values() if f._field_type is _FIELD)
def _is_dataclass_instance(obj):
return not isinstance(obj, type) and hasattr(obj, _FIELDS)
def is_dataclass(obj):
return hasattr(obj, _FIELDS)
def asdict(obj, *, dict_factory=dict):
if not _is_dataclass_instance(obj):
raise TypeError("asdict() should be called on dataclass instances")
return _asdict_inner(obj, dict_factory)
def _asdict_inner(obj, dict_factory):
if _is_dataclass_instance(obj):
result = []
for f in fields(obj):
value = _asdict_inner(getattr(obj, f.name), dict_factory)
result.append((f.name, value))
return dict_factory(result)
elif isinstance(obj, (list, tuple)):
return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
elif isinstance(obj, dict):
return type(obj)(
(_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items()
)
else:
return copy.deepcopy(obj)
def astuple(obj, *, tuple_factory=tuple):
if not _is_dataclass_instance(obj):
raise TypeError("astuple() should be called on dataclass instances")
return _astuple_inner(obj, tuple_factory)
def _astuple_inner(obj, tuple_factory):
if _is_dataclass_instance(obj):
result = []
for f in fields(obj):
value = _astuple_inner(getattr(obj, f.name), tuple_factory)
result.append(value)
return tuple_factory(result)
elif isinstance(obj, (list, tuple)):
return type(obj)(_astuple_inner(v, tuple_factory) for v in obj)
elif isinstance(obj, dict):
return type(obj)(
(_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory))
for k, v in obj.items()
)
else:
return copy.deepcopy(obj)
def make_dataclass(
cls_name,
fields,
*,
bases=(),
namespace=None,
init=True,
repr=True,
eq=True,
order=False,
unsafe_hash=False,
frozen=False,
):
if namespace is None:
namespace = {}
else:
namespace = namespace.copy()
# While we're looking through the field names, validate that they
seen = set()
anns = {}
for item in fields:
if isinstance(item, str):
name = item
tp = "typing.Any"
elif len(item) == 2:
name, tp, = item
elif len(item) == 3:
name, tp, spec = item
namespace[name] = spec
else:
raise TypeError(f"Invalid field: {item!r}")
if not isinstance(name, str) or not name.isidentifier():
raise TypeError(f"Field names must be valid identifers: {name!r}")
if keyword.iskeyword(name):
raise TypeError(f"Field names must not be keywords: {name!r}")
if name in seen:
raise TypeError(f"Field name duplicated: {name!r}")
seen.add(name)
anns[name] = tp
namespace["__annotations__"] = anns
cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace))
return dataclass(
cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen
)
def replace(obj, **changes):
# new dict, even if called with 'replace(obj, **my_changes)'.
if not _is_dataclass_instance(obj):
raise TypeError("replace() should be called on dataclass instances")
# It's an error to have init=False fields in 'changes'.
for f in getattr(obj, _FIELDS).values():
if not f.init:
if f.name in changes:
raise ValueError(
f"field {f.name} is declared with "
"init=False, it cannot be specified with "
"replace()"
)
continue
if f.name not in changes:
changes[f.name] = getattr(obj, f.name)
# added and/or left in 'changes'. If there are values supplied in
# changes that aren't fields, this will correctly raise a
return obj.__class__(**changes)
| true | true |
f7f6baff27102aeff0ebb938d362e6f28d09e521 | 4,635 | py | Python | docs/_exts/nir.py | SoftReaper/Mesa-Renoir-deb | 8d1de1f66058d62b41fe55d36522efea2bdf996d | [
"MIT"
] | null | null | null | docs/_exts/nir.py | SoftReaper/Mesa-Renoir-deb | 8d1de1f66058d62b41fe55d36522efea2bdf996d | [
"MIT"
] | null | null | null | docs/_exts/nir.py | SoftReaper/Mesa-Renoir-deb | 8d1de1f66058d62b41fe55d36522efea2bdf996d | [
"MIT"
] | null | null | null | # Copyright © 2021 Intel Corporation
#
# 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, sub license, 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 (including the
# next paragraph) 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 NON-INFRINGEMENT.
# IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 docutils.nodes
import mako.template
import os
import sphinx
from sphinx.directives import SphinxDirective
from sphinx.domains import Domain
from sphinx.util.nodes import make_refnode
import sys
import textwrap
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
MESA_DIR = os.path.join(THIS_DIR, '..', '..')
NIR_PATH = os.path.join(MESA_DIR, 'src', 'compiler', 'nir')
sys.path.append(NIR_PATH)
import nir_opcodes
OP_DESC_TEMPLATE = mako.template.Template("""
<%
def src_decl_list(num_srcs):
return ', '.join('nir_ssa_def *src' + str(i) for i in range(num_srcs))
def to_yn(b):
return 'Y' if b else 'N'
%>
**Properties:**
.. list-table::
:header-rows: 1
* - Per-component
- Associative
- 2-src commutative
* - ${to_yn(op.output_size == 0)}
- ${to_yn('associative' in op.algebraic_properties)}
- ${to_yn('2src_commutative' in op.algebraic_properties)}
**Constant-folding:**
.. code-block:: c
${textwrap.indent(op.const_expr, ' ')}
**Builder function:**
.. c:function:: nir_ssa_def *nir_${op.name}(nir_builder *, ${src_decl_list(op.num_inputs)})
""")
def parse_rst(state, parent, rst):
vl = docutils.statemachine.ViewList(rst.splitlines())
state.nested_parse(vl, 0, parent)
def nir_alu_type_name(t, s):
if s:
return '{}[{}]'.format(t, s)
else:
return '{}[N]'.format(t)
def build_alu_op_desc(state, env, op):
desc = sphinx.addnodes.desc(domain='nir', objtype='aluop')
# Add the signature
sig = sphinx.addnodes.desc_signature()
desc.append(sig)
sig += sphinx.addnodes.desc_name(op.name, op.name)
params = sphinx.addnodes.desc_parameterlist()
for i, t, s in zip(range(100), op.input_types, op.input_sizes):
params += docutils.nodes.Text(nir_alu_type_name(t, s) + ' ')
params += sphinx.addnodes.desc_parameter('', 'src' + str(i))
sig += params
sig += sphinx.addnodes.desc_returns('',
nir_alu_type_name(op.output_type, op.output_size))
nir_domain = env.get_domain('nir')
sig['ids'].append(nir_domain.add_alu_op_ref(op))
# Build the description
content = sphinx.addnodes.desc_content()
desc.append(content)
parse_rst(state, content, OP_DESC_TEMPLATE.render(op=op, textwrap=textwrap))
return desc
class NIRALUOpcodesDirective(SphinxDirective):
def run(self):
return [build_alu_op_desc(self.state, self.env, op)
for op in nir_opcodes.opcodes.values()]
class NIRDomain(Domain):
"""A new NIR directive
To list all NIR ALU opcodes with their descriptions:
```rst
.. nir:alu-opcodes::
```
To reference a NIR opcode, ``:nir:alu-op:`fadd```
"""
name = 'nir'
roles = {
'alu-op' : sphinx.roles.XRefRole(),
}
directives = {
'alu-opcodes' : NIRALUOpcodesDirective,
}
initial_data = {
'alu-op-refs': [],
}
def add_alu_op_ref(self, op):
"""Add reference to an ALU op."""
self.data['alu-op-refs'].append((op.name, self.env.docname))
return 'nir-alu-op-' + op.name
def resolve_xref(self, env, fromdocname, builder, typ, target, node,
contnode):
for opname, todocname in self.data['alu-op-refs']:
if target == opname:
targ = 'nir-alu-op-' + opname
return make_refnode(builder, fromdocname, todocname, targ,
contnode, targ)
return None
def setup(app):
app.add_domain(NIRDomain)
| 30.493421 | 91 | 0.670982 |
import docutils.nodes
import mako.template
import os
import sphinx
from sphinx.directives import SphinxDirective
from sphinx.domains import Domain
from sphinx.util.nodes import make_refnode
import sys
import textwrap
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
MESA_DIR = os.path.join(THIS_DIR, '..', '..')
NIR_PATH = os.path.join(MESA_DIR, 'src', 'compiler', 'nir')
sys.path.append(NIR_PATH)
import nir_opcodes
OP_DESC_TEMPLATE = mako.template.Template("""
<%
def src_decl_list(num_srcs):
return ', '.join('nir_ssa_def *src' + str(i) for i in range(num_srcs))
def to_yn(b):
return 'Y' if b else 'N'
%>
**Properties:**
.. list-table::
:header-rows: 1
* - Per-component
- Associative
- 2-src commutative
* - ${to_yn(op.output_size == 0)}
- ${to_yn('associative' in op.algebraic_properties)}
- ${to_yn('2src_commutative' in op.algebraic_properties)}
**Constant-folding:**
.. code-block:: c
${textwrap.indent(op.const_expr, ' ')}
**Builder function:**
.. c:function:: nir_ssa_def *nir_${op.name}(nir_builder *, ${src_decl_list(op.num_inputs)})
""")
def parse_rst(state, parent, rst):
vl = docutils.statemachine.ViewList(rst.splitlines())
state.nested_parse(vl, 0, parent)
def nir_alu_type_name(t, s):
if s:
return '{}[{}]'.format(t, s)
else:
return '{}[N]'.format(t)
def build_alu_op_desc(state, env, op):
desc = sphinx.addnodes.desc(domain='nir', objtype='aluop')
sig = sphinx.addnodes.desc_signature()
desc.append(sig)
sig += sphinx.addnodes.desc_name(op.name, op.name)
params = sphinx.addnodes.desc_parameterlist()
for i, t, s in zip(range(100), op.input_types, op.input_sizes):
params += docutils.nodes.Text(nir_alu_type_name(t, s) + ' ')
params += sphinx.addnodes.desc_parameter('', 'src' + str(i))
sig += params
sig += sphinx.addnodes.desc_returns('',
nir_alu_type_name(op.output_type, op.output_size))
nir_domain = env.get_domain('nir')
sig['ids'].append(nir_domain.add_alu_op_ref(op))
content = sphinx.addnodes.desc_content()
desc.append(content)
parse_rst(state, content, OP_DESC_TEMPLATE.render(op=op, textwrap=textwrap))
return desc
class NIRALUOpcodesDirective(SphinxDirective):
def run(self):
return [build_alu_op_desc(self.state, self.env, op)
for op in nir_opcodes.opcodes.values()]
class NIRDomain(Domain):
name = 'nir'
roles = {
'alu-op' : sphinx.roles.XRefRole(),
}
directives = {
'alu-opcodes' : NIRALUOpcodesDirective,
}
initial_data = {
'alu-op-refs': [],
}
def add_alu_op_ref(self, op):
self.data['alu-op-refs'].append((op.name, self.env.docname))
return 'nir-alu-op-' + op.name
def resolve_xref(self, env, fromdocname, builder, typ, target, node,
contnode):
for opname, todocname in self.data['alu-op-refs']:
if target == opname:
targ = 'nir-alu-op-' + opname
return make_refnode(builder, fromdocname, todocname, targ,
contnode, targ)
return None
def setup(app):
app.add_domain(NIRDomain)
| true | true |
f7f6bb9ab02584f13d1d76dd26b94737c5267f1a | 597 | gyp | Python | build/linux/unbundle/libxslt.gyp | TwistedCore/external_v8 | c6725dab9be251fbfc6fd7d53c3513a23e78c36c | [
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | build/linux/unbundle/libxslt.gyp | TwistedCore/external_v8 | c6725dab9be251fbfc6fd7d53c3513a23e78c36c | [
"BSD-3-Clause"
] | 8 | 2015-08-31T06:39:59.000Z | 2021-12-04T14:53:28.000Z | build/linux/unbundle/libxslt.gyp | TwistedCore/external_v8 | c6725dab9be251fbfc6fd7d53c3513a23e78c36c | [
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'libxslt',
'type': 'none',
'direct_dependent_settings': {
'cflags': [
'<!@(pkg-config --cflags libxslt)',
],
},
'link_settings': {
'ldflags': [
'<!@(pkg-config --libs-only-L --libs-only-other libxslt)',
],
'libraries': [
'<!@(pkg-config --libs-only-l libxslt)',
],
},
},
],
}
| 22.961538 | 72 | 0.507538 |
{
'targets': [
{
'target_name': 'libxslt',
'type': 'none',
'direct_dependent_settings': {
'cflags': [
'<!@(pkg-config --cflags libxslt)',
],
},
'link_settings': {
'ldflags': [
'<!@(pkg-config --libs-only-L --libs-only-other libxslt)',
],
'libraries': [
'<!@(pkg-config --libs-only-l libxslt)',
],
},
},
],
}
| true | true |
f7f6bcc22044281e719b7f092f39612e6900217a | 565 | py | Python | resotolib/test/test_baseresources.py | MrMarvin/cloudkeeper | cdca21c1a3b945da6e53a5dbb37a437e1d46f557 | [
"Apache-2.0"
] | 316 | 2021-07-08T12:54:19.000Z | 2022-01-12T18:50:17.000Z | resotolib/test/test_baseresources.py | MrMarvin/cloudkeeper | cdca21c1a3b945da6e53a5dbb37a437e1d46f557 | [
"Apache-2.0"
] | 110 | 2022-01-13T22:27:55.000Z | 2022-03-30T22:26:50.000Z | resotolib/test/test_baseresources.py | MrMarvin/cloudkeeper | cdca21c1a3b945da6e53a5dbb37a437e1d46f557 | [
"Apache-2.0"
] | 14 | 2021-08-23T08:29:29.000Z | 2022-01-08T04:42:28.000Z | from typing import ClassVar
from dataclasses import dataclass
from resotolib.baseresources import BaseResource
@dataclass(eq=False)
class SomeTestResource(BaseResource):
kind: ClassVar[str] = "some_test_resource"
def delete(self, graph) -> bool:
return False
def test_resource():
r = SomeTestResource("foo", {"foo": "bar"})
log_msg = "some log"
r.log(log_msg)
assert r.id == "foo"
assert r.name == "foo"
assert r.kind == "some_test_resource"
assert r.tags["foo"] == "bar"
assert r.event_log[0]["msg"] == log_msg
| 24.565217 | 48 | 0.670796 | from typing import ClassVar
from dataclasses import dataclass
from resotolib.baseresources import BaseResource
@dataclass(eq=False)
class SomeTestResource(BaseResource):
kind: ClassVar[str] = "some_test_resource"
def delete(self, graph) -> bool:
return False
def test_resource():
r = SomeTestResource("foo", {"foo": "bar"})
log_msg = "some log"
r.log(log_msg)
assert r.id == "foo"
assert r.name == "foo"
assert r.kind == "some_test_resource"
assert r.tags["foo"] == "bar"
assert r.event_log[0]["msg"] == log_msg
| true | true |
f7f6bcfda437fc75023abe3c83af757d71434e93 | 1,680 | py | Python | tests/integrations/test_experimental.py | renedlog/determined | 7b1f2b1a845e4def17d489a5ad7592a2eaef0608 | [
"Apache-2.0"
] | null | null | null | tests/integrations/test_experimental.py | renedlog/determined | 7b1f2b1a845e4def17d489a5ad7592a2eaef0608 | [
"Apache-2.0"
] | 1 | 2022-02-10T07:31:44.000Z | 2022-02-10T07:31:44.000Z | tests/integrations/test_experimental.py | renedlog/determined | 7b1f2b1a845e4def17d489a5ad7592a2eaef0608 | [
"Apache-2.0"
] | null | null | null | import pytest
from tests.integrations import config as conf
from tests.integrations import experiment as exp
@pytest.mark.nightly # type: ignore
def test_nas_search() -> None:
config = conf.load_config(conf.experimental_path("nas_search/train_one_arch.yaml"))
config = conf.set_max_steps(config, 2)
exp.run_basic_test_with_temp_config(config, conf.experimental_path("nas_search"), 1)
@pytest.mark.nightly # type: ignore
def test_bert_glue() -> None:
config = conf.load_config(conf.experimental_path("bert_glue_pytorch/const.yaml"))
config = conf.set_max_steps(config, 2)
exp.run_basic_test_with_temp_config(config, conf.experimental_path("bert_glue_pytorch/"), 1)
@pytest.mark.nightly # type: ignore
def test_faster_rcnn() -> None:
config = conf.load_config(conf.experimental_path("FasterRCNN_tp/16-gpus.yaml"))
config = conf.set_max_steps(config, 2)
config = conf.set_slots_per_trial(config, 1)
exp.run_basic_test_with_temp_config(
config, conf.experimental_path("FasterRCNN_tp"), 1, max_wait_secs=4800
)
@pytest.mark.nightly # type: ignore
def test_mnist_tp_to_estimator() -> None:
config = conf.load_config(conf.experimental_path("mnist_tp_to_estimator/const.yaml"))
config = conf.set_max_steps(config, 2)
exp.run_basic_test_with_temp_config(config, conf.experimental_path("mnist_tp_to_estimator"), 1)
@pytest.mark.nightly # type: ignore
def test_resnet50() -> None:
config = conf.load_config(conf.experimental_path("resnet50_tf_keras/const.yaml"))
config = conf.set_max_steps(config, 2)
exp.run_basic_test_with_temp_config(config, conf.experimental_path("resnet50_tf_keras"), 1)
| 35 | 99 | 0.7625 | import pytest
from tests.integrations import config as conf
from tests.integrations import experiment as exp
@pytest.mark.nightly
def test_nas_search() -> None:
config = conf.load_config(conf.experimental_path("nas_search/train_one_arch.yaml"))
config = conf.set_max_steps(config, 2)
exp.run_basic_test_with_temp_config(config, conf.experimental_path("nas_search"), 1)
@pytest.mark.nightly
def test_bert_glue() -> None:
config = conf.load_config(conf.experimental_path("bert_glue_pytorch/const.yaml"))
config = conf.set_max_steps(config, 2)
exp.run_basic_test_with_temp_config(config, conf.experimental_path("bert_glue_pytorch/"), 1)
@pytest.mark.nightly
def test_faster_rcnn() -> None:
config = conf.load_config(conf.experimental_path("FasterRCNN_tp/16-gpus.yaml"))
config = conf.set_max_steps(config, 2)
config = conf.set_slots_per_trial(config, 1)
exp.run_basic_test_with_temp_config(
config, conf.experimental_path("FasterRCNN_tp"), 1, max_wait_secs=4800
)
@pytest.mark.nightly
def test_mnist_tp_to_estimator() -> None:
config = conf.load_config(conf.experimental_path("mnist_tp_to_estimator/const.yaml"))
config = conf.set_max_steps(config, 2)
exp.run_basic_test_with_temp_config(config, conf.experimental_path("mnist_tp_to_estimator"), 1)
@pytest.mark.nightly
def test_resnet50() -> None:
config = conf.load_config(conf.experimental_path("resnet50_tf_keras/const.yaml"))
config = conf.set_max_steps(config, 2)
exp.run_basic_test_with_temp_config(config, conf.experimental_path("resnet50_tf_keras"), 1)
| true | true |
f7f6bd4107da458d05f0c5465d5447e4b20815d3 | 659 | py | Python | visorspass/visor/migrations/0007_auto_20210814_0009.py | RobertoMarroquin/spass | 7afa348f72f036a230a3bbe068a9716cd068adf1 | [
"MIT"
] | null | null | null | visorspass/visor/migrations/0007_auto_20210814_0009.py | RobertoMarroquin/spass | 7afa348f72f036a230a3bbe068a9716cd068adf1 | [
"MIT"
] | null | null | null | visorspass/visor/migrations/0007_auto_20210814_0009.py | RobertoMarroquin/spass | 7afa348f72f036a230a3bbe068a9716cd068adf1 | [
"MIT"
] | null | null | null | # Generated by Django 3.2.5 on 2021-08-14 00:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('visor', '0006_auto_20210814_0007'),
]
operations = [
migrations.RemoveField(
model_name='unidadmedida',
name='variable',
),
migrations.AddField(
model_name='variable',
name='unidad',
field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='variable', to='visor.unidadmedida'),
preserve_default=False,
),
]
| 26.36 | 145 | 0.622155 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('visor', '0006_auto_20210814_0007'),
]
operations = [
migrations.RemoveField(
model_name='unidadmedida',
name='variable',
),
migrations.AddField(
model_name='variable',
name='unidad',
field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='variable', to='visor.unidadmedida'),
preserve_default=False,
),
]
| true | true |
f7f6bd6cc598329151b502560f8bbb935e81faa2 | 904 | py | Python | python/taichi/scoping/transform_scope.py | willFederer/taichi | 59b37adf83fba5a06583dcf6b9bf2a74a985fe3e | [
"MIT"
] | 1 | 2021-02-04T13:59:59.000Z | 2021-02-04T13:59:59.000Z | python/taichi/scoping/transform_scope.py | willFederer/taichi | 59b37adf83fba5a06583dcf6b9bf2a74a985fe3e | [
"MIT"
] | null | null | null | python/taichi/scoping/transform_scope.py | willFederer/taichi | 59b37adf83fba5a06583dcf6b9bf2a74a985fe3e | [
"MIT"
] | null | null | null | from taichi.core import tc_core
from taichi.tools.transform import Transform
from taichi.misc.util import *
import traceback
current_transform = [tc_core.Matrix4(1.0)]
class TransformScope:
def __init__(self, transform=None, translate=None, rotation=None, scale=None):
self.transform = Transform(transform, translate, rotation, scale).get_matrix()
def __enter__(self):
self.previous_transform = get_current_transform()
set_current_tranform(self.previous_transform * self.transform)
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_val:
traceback.print_exception(exc_type, exc_val, exc_tb)
exit(-1)
set_current_tranform(self.previous_transform)
def get_current_transform():
return current_transform[0]
def set_current_tranform(transform):
current_transform[0] = transform
transform_scope = TransformScope
| 27.393939 | 86 | 0.740044 | from taichi.core import tc_core
from taichi.tools.transform import Transform
from taichi.misc.util import *
import traceback
current_transform = [tc_core.Matrix4(1.0)]
class TransformScope:
def __init__(self, transform=None, translate=None, rotation=None, scale=None):
self.transform = Transform(transform, translate, rotation, scale).get_matrix()
def __enter__(self):
self.previous_transform = get_current_transform()
set_current_tranform(self.previous_transform * self.transform)
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_val:
traceback.print_exception(exc_type, exc_val, exc_tb)
exit(-1)
set_current_tranform(self.previous_transform)
def get_current_transform():
return current_transform[0]
def set_current_tranform(transform):
current_transform[0] = transform
transform_scope = TransformScope
| true | true |
f7f6be4308f616eb254a1324b1214ceef731bf35 | 6,861 | py | Python | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/instruction_0379cfa9d0d64cb1c14d9f8a669dcb24.py | OpenIxia/ixnetwork_restpy | f628db450573a104f327cf3c737ca25586e067ae | [
"MIT"
] | 20 | 2019-05-07T01:59:14.000Z | 2022-02-11T05:24:47.000Z | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/instruction_0379cfa9d0d64cb1c14d9f8a669dcb24.py | OpenIxia/ixnetwork_restpy | f628db450573a104f327cf3c737ca25586e067ae | [
"MIT"
] | 60 | 2019-04-03T18:59:35.000Z | 2022-02-22T12:05:05.000Z | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/instruction_0379cfa9d0d64cb1c14d9f8a669dcb24.py | OpenIxia/ixnetwork_restpy | f628db450573a104f327cf3c737ca25586e067ae | [
"MIT"
] | 13 | 2019-05-20T10:48:31.000Z | 2021-10-06T07:45:44.000Z | # MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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.
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
from typing import List, Any, Union
class Instruction(Base):
"""NOT DEFINED
The Instruction class encapsulates a required instruction resource which will be retrieved from the server every time the property is accessed.
"""
__slots__ = ()
_SDM_NAME = 'instruction'
_SDM_ATT_MAP = {
'ExperimenterData': 'experimenterData',
'ExperimenterDataLength': 'experimenterDataLength',
'ExperimenterDataLengthMiss': 'experimenterDataLengthMiss',
'ExperimenterDataMiss': 'experimenterDataMiss',
'ExperimenterId': 'experimenterId',
'ExperimenterIdMiss': 'experimenterIdMiss',
}
_SDM_ENUM_MAP = {
}
def __init__(self, parent, list_op=False):
super(Instruction, self).__init__(parent, list_op)
@property
def InstructionType(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.instructiontype_48ecf22c686ab3b403480ead04a36305.InstructionType): An instance of the InstructionType class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.instructiontype_48ecf22c686ab3b403480ead04a36305 import InstructionType
if self._properties.get('InstructionType', None) is not None:
return self._properties.get('InstructionType')
else:
return InstructionType(self)._select()
@property
def InstructionTypeMiss(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.instructiontypemiss_253739e9542d1a3617b510285726bcd8.InstructionTypeMiss): An instance of the InstructionTypeMiss class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.instructiontypemiss_253739e9542d1a3617b510285726bcd8 import InstructionTypeMiss
if self._properties.get('InstructionTypeMiss', None) is not None:
return self._properties.get('InstructionTypeMiss')
else:
return InstructionTypeMiss(self)._select()
@property
def ExperimenterData(self):
# type: () -> str
"""
Returns
-------
- str: NOT DEFINED
"""
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterData'])
@ExperimenterData.setter
def ExperimenterData(self, value):
# type: (str) -> None
self._set_attribute(self._SDM_ATT_MAP['ExperimenterData'], value)
@property
def ExperimenterDataLength(self):
# type: () -> int
"""
Returns
-------
- number: NOT DEFINED
"""
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterDataLength'])
@ExperimenterDataLength.setter
def ExperimenterDataLength(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['ExperimenterDataLength'], value)
@property
def ExperimenterDataLengthMiss(self):
# type: () -> int
"""
Returns
-------
- number: NOT DEFINED
"""
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterDataLengthMiss'])
@ExperimenterDataLengthMiss.setter
def ExperimenterDataLengthMiss(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['ExperimenterDataLengthMiss'], value)
@property
def ExperimenterDataMiss(self):
# type: () -> str
"""
Returns
-------
- str: NOT DEFINED
"""
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterDataMiss'])
@ExperimenterDataMiss.setter
def ExperimenterDataMiss(self, value):
# type: (str) -> None
self._set_attribute(self._SDM_ATT_MAP['ExperimenterDataMiss'], value)
@property
def ExperimenterId(self):
# type: () -> int
"""
Returns
-------
- number: NOT DEFINED
"""
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterId'])
@ExperimenterId.setter
def ExperimenterId(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['ExperimenterId'], value)
@property
def ExperimenterIdMiss(self):
# type: () -> int
"""
Returns
-------
- number: NOT DEFINED
"""
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterIdMiss'])
@ExperimenterIdMiss.setter
def ExperimenterIdMiss(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['ExperimenterIdMiss'], value)
def update(self, ExperimenterData=None, ExperimenterDataLength=None, ExperimenterDataLengthMiss=None, ExperimenterDataMiss=None, ExperimenterId=None, ExperimenterIdMiss=None):
# type: (str, int, int, str, int, int) -> Instruction
"""Updates instruction resource on the server.
Args
----
- ExperimenterData (str): NOT DEFINED
- ExperimenterDataLength (number): NOT DEFINED
- ExperimenterDataLengthMiss (number): NOT DEFINED
- ExperimenterDataMiss (str): NOT DEFINED
- ExperimenterId (number): NOT DEFINED
- ExperimenterIdMiss (number): NOT DEFINED
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))
| 37.288043 | 198 | 0.670893 |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
from typing import List, Any, Union
class Instruction(Base):
__slots__ = ()
_SDM_NAME = 'instruction'
_SDM_ATT_MAP = {
'ExperimenterData': 'experimenterData',
'ExperimenterDataLength': 'experimenterDataLength',
'ExperimenterDataLengthMiss': 'experimenterDataLengthMiss',
'ExperimenterDataMiss': 'experimenterDataMiss',
'ExperimenterId': 'experimenterId',
'ExperimenterIdMiss': 'experimenterIdMiss',
}
_SDM_ENUM_MAP = {
}
def __init__(self, parent, list_op=False):
super(Instruction, self).__init__(parent, list_op)
@property
def InstructionType(self):
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.instructiontype_48ecf22c686ab3b403480ead04a36305 import InstructionType
if self._properties.get('InstructionType', None) is not None:
return self._properties.get('InstructionType')
else:
return InstructionType(self)._select()
@property
def InstructionTypeMiss(self):
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.instructiontypemiss_253739e9542d1a3617b510285726bcd8 import InstructionTypeMiss
if self._properties.get('InstructionTypeMiss', None) is not None:
return self._properties.get('InstructionTypeMiss')
else:
return InstructionTypeMiss(self)._select()
@property
def ExperimenterData(self):
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterData'])
@ExperimenterData.setter
def ExperimenterData(self, value):
self._set_attribute(self._SDM_ATT_MAP['ExperimenterData'], value)
@property
def ExperimenterDataLength(self):
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterDataLength'])
@ExperimenterDataLength.setter
def ExperimenterDataLength(self, value):
self._set_attribute(self._SDM_ATT_MAP['ExperimenterDataLength'], value)
@property
def ExperimenterDataLengthMiss(self):
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterDataLengthMiss'])
@ExperimenterDataLengthMiss.setter
def ExperimenterDataLengthMiss(self, value):
self._set_attribute(self._SDM_ATT_MAP['ExperimenterDataLengthMiss'], value)
@property
def ExperimenterDataMiss(self):
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterDataMiss'])
@ExperimenterDataMiss.setter
def ExperimenterDataMiss(self, value):
self._set_attribute(self._SDM_ATT_MAP['ExperimenterDataMiss'], value)
@property
def ExperimenterId(self):
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterId'])
@ExperimenterId.setter
def ExperimenterId(self, value):
self._set_attribute(self._SDM_ATT_MAP['ExperimenterId'], value)
@property
def ExperimenterIdMiss(self):
return self._get_attribute(self._SDM_ATT_MAP['ExperimenterIdMiss'])
@ExperimenterIdMiss.setter
def ExperimenterIdMiss(self, value):
self._set_attribute(self._SDM_ATT_MAP['ExperimenterIdMiss'], value)
def update(self, ExperimenterData=None, ExperimenterDataLength=None, ExperimenterDataLengthMiss=None, ExperimenterDataMiss=None, ExperimenterId=None, ExperimenterIdMiss=None):
return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))
| true | true |
f7f6be4a73d0d4303360c24d28b5ebeff728367f | 2,063 | py | Python | configman/config_exceptions.py | peterbe/configman | 724d80b25a0ebbb2e75ad69e92a6611494cd68b4 | [
"BSD-3-Clause"
] | null | null | null | configman/config_exceptions.py | peterbe/configman | 724d80b25a0ebbb2e75ad69e92a6611494cd68b4 | [
"BSD-3-Clause"
] | null | null | null | configman/config_exceptions.py | peterbe/configman | 724d80b25a0ebbb2e75ad69e92a6611494cd68b4 | [
"BSD-3-Clause"
] | null | null | null | # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is configman
#
# The Initial Developer of the Original Code is
# Mozilla Foundation
# Portions created by the Initial Developer are Copyright (C) 2011
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# K Lars Lohn, lars@mozilla.com
# Peter Bengtsson, peterbe@mozilla.com
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
class ConfigmanException(Exception):
pass
class ConfigFileMissingError(IOError, ConfigmanException):
pass
class ConfigFileOptionNameMissingError(ConfigmanException):
pass
class NotAnOptionError(ConfigmanException):
pass
class OptionError(ConfigmanException):
pass
class CannotConvertError(ConfigmanException):
pass
| 33.274194 | 77 | 0.752787 |
class ConfigmanException(Exception):
pass
class ConfigFileMissingError(IOError, ConfigmanException):
pass
class ConfigFileOptionNameMissingError(ConfigmanException):
pass
class NotAnOptionError(ConfigmanException):
pass
class OptionError(ConfigmanException):
pass
class CannotConvertError(ConfigmanException):
pass
| true | true |
f7f6be6ccca469c361d7bad78eeb684cc6275f20 | 163 | py | Python | scripts/list_graphs.py | knshnb/MQLib | 66495e135f7bba3e84fb6836b03eb5f13a6ca7cf | [
"MIT"
] | 1 | 2021-08-09T17:13:32.000Z | 2021-08-09T17:13:32.000Z | scripts/list_graphs.py | knshnb/MQLib | 66495e135f7bba3e84fb6836b03eb5f13a6ca7cf | [
"MIT"
] | null | null | null | scripts/list_graphs.py | knshnb/MQLib | 66495e135f7bba3e84fb6836b03eb5f13a6ca7cf | [
"MIT"
] | 1 | 2020-02-18T10:55:02.000Z | 2020-02-18T10:55:02.000Z | import boto
import os
import sys
conn = boto.connect_s3(anon=True)
b = conn.get_bucket("mqlibinstances", validate=False)
for key in b.list():
print key.name
| 16.3 | 53 | 0.736196 | import boto
import os
import sys
conn = boto.connect_s3(anon=True)
b = conn.get_bucket("mqlibinstances", validate=False)
for key in b.list():
print key.name
| false | true |
f7f6beb209251bddef33548c6ab0a8bd40b8fa12 | 1,261 | py | Python | 1D_example.py | AndrewWangJZ/pyfem | 8e7df6aa69c1c761bb8ec67302847e30a83190b4 | [
"MIT"
] | 1 | 2022-03-10T17:22:53.000Z | 2022-03-10T17:22:53.000Z | 1D_example.py | AndrewWangJZ/pyfem | 8e7df6aa69c1c761bb8ec67302847e30a83190b4 | [
"MIT"
] | null | null | null | 1D_example.py | AndrewWangJZ/pyfem | 8e7df6aa69c1c761bb8ec67302847e30a83190b4 | [
"MIT"
] | 2 | 2022-03-10T12:47:34.000Z | 2022-03-10T13:25:18.000Z | import numpy as np
import scipy.integrate.quadrature as integrator
"""
An 1-dimensional linear problem is used to describe the FEM process
reference:
[1] https://www.youtube.com/watch?v=rdaZuKFK-4k
"""
class OneDimensionalProblem:
def __init__(self):
self.NodeNum = 5
self.elementNum = 4
self.nodeCoordinate = np.linspace(0, 1, 5)
self.element = [[i, i+1] for i in range(self.NodeNum-1)]
self.gaussionNorm = np.array([-1/np.sqrt(3), 1/np.sqrt(3)])
self.gaussionGlobal = [self.mapGaussian2Local(self.nodeCoordinate[i[0]], self.nodeCoordinate[i[1]]) for i in self.element]
print()
def shapeFunction(self, x, x1, x2):
w1 = (x2-x)/(x2-x1)
w2 = (x-x1)/(x2-x1)
return np.array([w1, w2])
def shapeFunctionDx(self, x1, x2):
dx1 = -1/(x2-x1)
dx2 = 1/(x2-x1)
return np.array([dx1, dx2])
def mapGaussian2Local(self, x1, x2):
gaussionLocal = np.zeros_like(self.gaussionNorm)
for i in range(len(self.gaussionNorm)):
gaussionLocal[i] = (self.gaussionNorm[i]+1)/2*(x2-x1)+x1
return gaussionLocal
if __name__ == '__main__':
oneDimProblem = OneDimensionalProblem() | 30.756098 | 130 | 0.605075 | import numpy as np
import scipy.integrate.quadrature as integrator
class OneDimensionalProblem:
def __init__(self):
self.NodeNum = 5
self.elementNum = 4
self.nodeCoordinate = np.linspace(0, 1, 5)
self.element = [[i, i+1] for i in range(self.NodeNum-1)]
self.gaussionNorm = np.array([-1/np.sqrt(3), 1/np.sqrt(3)])
self.gaussionGlobal = [self.mapGaussian2Local(self.nodeCoordinate[i[0]], self.nodeCoordinate[i[1]]) for i in self.element]
print()
def shapeFunction(self, x, x1, x2):
w1 = (x2-x)/(x2-x1)
w2 = (x-x1)/(x2-x1)
return np.array([w1, w2])
def shapeFunctionDx(self, x1, x2):
dx1 = -1/(x2-x1)
dx2 = 1/(x2-x1)
return np.array([dx1, dx2])
def mapGaussian2Local(self, x1, x2):
gaussionLocal = np.zeros_like(self.gaussionNorm)
for i in range(len(self.gaussionNorm)):
gaussionLocal[i] = (self.gaussionNorm[i]+1)/2*(x2-x1)+x1
return gaussionLocal
if __name__ == '__main__':
oneDimProblem = OneDimensionalProblem() | true | true |
f7f6bfc9b23c7e1df4edc3c0a4c01fad3b28ea52 | 1,162 | py | Python | appenlight_client/timing/timing_urllib3.py | atomekk/appenlight-client-python | e5fd8a39b983343f23c0aa8ceaea0892a77d38c0 | [
"BSD-3-Clause"
] | 22 | 2015-03-09T15:00:56.000Z | 2018-09-27T06:57:39.000Z | appenlight_client/timing/timing_urllib3.py | atomekk/appenlight-client-python | e5fd8a39b983343f23c0aa8ceaea0892a77d38c0 | [
"BSD-3-Clause"
] | 31 | 2015-02-13T08:45:35.000Z | 2019-06-22T21:56:58.000Z | appenlight_client/timing/timing_urllib3.py | atomekk/appenlight-client-python | e5fd8a39b983343f23c0aa8ceaea0892a77d38c0 | [
"BSD-3-Clause"
] | 17 | 2015-02-12T20:40:36.000Z | 2020-04-22T02:43:57.000Z | from appenlight_client.utils import import_module, deco_func_or_method
from appenlight_client.timing import time_trace
ignore_set = frozenset(['remote', 'nosql'])
def add_timing(min_duration=3):
module = import_module('urllib3')
if not module:
return
def gather_args_url(r, m, url, *args, **kwargs):
return {'type': 'remote',
'statement': 'urllib3.request.RequestMethods.request_encode_url',
'parameters': url,
'count': True,
'ignore_in': ignore_set}
deco_func_or_method(module.request, 'RequestMethods.request_encode_url',
time_trace, gatherer=gather_args_url, min_duration=min_duration)
def gather_args_body(r, m, url, *args, **kwargs):
return {'type': 'remote',
'statement': 'urllib3.request.RequestMethods.request_encode_body',
'parameters': url,
'count': True,
'ignore_in': ignore_set}
deco_func_or_method(module.request, 'RequestMethods.request_encode_body',
time_trace, gatherer=gather_args_body, min_duration=min_duration)
| 37.483871 | 89 | 0.638554 | from appenlight_client.utils import import_module, deco_func_or_method
from appenlight_client.timing import time_trace
ignore_set = frozenset(['remote', 'nosql'])
def add_timing(min_duration=3):
module = import_module('urllib3')
if not module:
return
def gather_args_url(r, m, url, *args, **kwargs):
return {'type': 'remote',
'statement': 'urllib3.request.RequestMethods.request_encode_url',
'parameters': url,
'count': True,
'ignore_in': ignore_set}
deco_func_or_method(module.request, 'RequestMethods.request_encode_url',
time_trace, gatherer=gather_args_url, min_duration=min_duration)
def gather_args_body(r, m, url, *args, **kwargs):
return {'type': 'remote',
'statement': 'urllib3.request.RequestMethods.request_encode_body',
'parameters': url,
'count': True,
'ignore_in': ignore_set}
deco_func_or_method(module.request, 'RequestMethods.request_encode_body',
time_trace, gatherer=gather_args_body, min_duration=min_duration)
| true | true |
f7f6c05baee01152e649e022449e228c4baa192a | 72 | py | Python | notebooks/_solutions/pandas_06_groupby_operations3.py | jonasvdd/DS-python-data-analysis | 835226f562ee0b0631d70e48a17c4526ff58a538 | [
"BSD-3-Clause"
] | 65 | 2017-03-21T09:15:40.000Z | 2022-02-01T23:43:08.000Z | notebooks/_solutions/pandas_06_groupby_operations3.py | jonasvdd/DS-python-data-analysis | 835226f562ee0b0631d70e48a17c4526ff58a538 | [
"BSD-3-Clause"
] | 100 | 2016-12-15T03:44:06.000Z | 2022-03-07T08:14:07.000Z | notebooks/_solutions/pandas_06_groupby_operations3.py | jonasvdd/DS-python-data-analysis | 835226f562ee0b0631d70e48a17c4526ff58a538 | [
"BSD-3-Clause"
] | 52 | 2016-12-19T07:48:52.000Z | 2022-02-19T17:53:48.000Z | df25 = df[df['Age'] < 25]
df25['Survived'].sum() / len(df25['Survived']) | 36 | 46 | 0.597222 | df25 = df[df['Age'] < 25]
df25['Survived'].sum() / len(df25['Survived']) | true | true |
f7f6c0780f7b3708ec596f3795143e043ec616a6 | 233 | py | Python | tests/conftest.py | thiagohk/bank_process | 1738bfd638def0f7114a94966e260314f2d14ccd | [
"MIT"
] | null | null | null | tests/conftest.py | thiagohk/bank_process | 1738bfd638def0f7114a94966e260314f2d14ccd | [
"MIT"
] | null | null | null | tests/conftest.py | thiagohk/bank_process | 1738bfd638def0f7114a94966e260314f2d14ccd | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Dummy conftest.py for bank_process.
If you don't know what this is for, just leave it empty.
Read more about conftest.py under:
https://pytest.org/latest/plugins.html
"""
# import pytest
| 21.181818 | 60 | 0.656652 | true | true | |
f7f6c0a4c17a1bd88a9a059a831b3cb56e947e26 | 1,220 | py | Python | python/check_docker.py | cookish/deeptile | 159275b4d63286dd6ad08010a4e457ba9af9ae2d | [
"MIT"
] | null | null | null | python/check_docker.py | cookish/deeptile | 159275b4d63286dd6ad08010a4e457ba9af9ae2d | [
"MIT"
] | 6 | 2018-12-04T22:33:59.000Z | 2018-12-07T23:07:35.000Z | python/check_docker.py | cookish/deeptile | 159275b4d63286dd6ad08010a4e457ba9af9ae2d | [
"MIT"
] | null | null | null | import requests
import numpy as np
import json
import include.board_utilities as board_utilities
host = 'localhost'
port = '8503'
test_boards = np.empty(shape=1000, dtype="uint64")
for i in range(1000):
test_boards[i] = 0xfedcba9876543210 + i
test_board_arr = board_utilities.int_to_arr(test_boards)
board_utilities.print_board_hex(test_board_arr[0])
test_board_shaped = board_utilities.arr_to_board(test_board_arr)
print()
print("===============================")
print("Converting board to list")
x = test_board_shaped.tolist()
# print("x:")
# print(x)
print("Converting list to json string")
data = json.dumps({"instances": x})
# headers = {"content-type": "application/json"}
print("Posting string to Docker")
json_response = requests.post("http://%s:%s/v1/models/serving_default:predict" % (host, port), data=data)
print("Received response from Docker")
response = json.loads(json_response.text)
if 'predictions' in response:
print("================= Predictions: =======================")
predictions = json.loads(json_response.text)['predictions']
print('Found', len(predictions), 'predictions')
for i in range(500, 510):
print(predictions[i])
else:
print(json_response)
| 27.727273 | 105 | 0.694262 | import requests
import numpy as np
import json
import include.board_utilities as board_utilities
host = 'localhost'
port = '8503'
test_boards = np.empty(shape=1000, dtype="uint64")
for i in range(1000):
test_boards[i] = 0xfedcba9876543210 + i
test_board_arr = board_utilities.int_to_arr(test_boards)
board_utilities.print_board_hex(test_board_arr[0])
test_board_shaped = board_utilities.arr_to_board(test_board_arr)
print()
print("===============================")
print("Converting board to list")
x = test_board_shaped.tolist()
print("Converting list to json string")
data = json.dumps({"instances": x})
print("Posting string to Docker")
json_response = requests.post("http://%s:%s/v1/models/serving_default:predict" % (host, port), data=data)
print("Received response from Docker")
response = json.loads(json_response.text)
if 'predictions' in response:
print("================= Predictions: =======================")
predictions = json.loads(json_response.text)['predictions']
print('Found', len(predictions), 'predictions')
for i in range(500, 510):
print(predictions[i])
else:
print(json_response)
| true | true |
f7f6c15c821bcbe7cf610da9b7858ffc606cd0f5 | 226 | py | Python | tests/test_app/models/author.py | 5783354/awokado | 9454067f005fd8905409902fb955de664ba3d5b6 | [
"MIT"
] | 6 | 2019-02-08T16:21:24.000Z | 2019-03-13T13:00:05.000Z | tests/test_app/models/author.py | 5783354/awokado | 9454067f005fd8905409902fb955de664ba3d5b6 | [
"MIT"
] | 10 | 2019-05-21T10:29:16.000Z | 2021-05-21T12:09:49.000Z | tests/test_app/models/author.py | 5783354/awokado | 9454067f005fd8905409902fb955de664ba3d5b6 | [
"MIT"
] | 1 | 2020-02-26T06:47:41.000Z | 2020-02-26T06:47:41.000Z | import sqlalchemy as sa
from .base import Model
class Author(Model):
__tablename__ = "authors"
id = Model.PK()
first_name = sa.Column(sa.Text, nullable=False)
last_name = sa.Column(sa.Text, nullable=False)
| 18.833333 | 51 | 0.69469 | import sqlalchemy as sa
from .base import Model
class Author(Model):
__tablename__ = "authors"
id = Model.PK()
first_name = sa.Column(sa.Text, nullable=False)
last_name = sa.Column(sa.Text, nullable=False)
| true | true |
f7f6c2bf51d80214d42b4c539d82d7cd3f01bb13 | 134,883 | py | Python | Python/Matlab.py | Spectavi/video-diff | 4ad28aea48877937f6b5b25f374f9c14eaf79212 | [
"BSD-3-Clause"
] | 1 | 2021-04-18T21:24:42.000Z | 2021-04-18T21:24:42.000Z | Python/Matlab.py | Spectavi/video-diff | 4ad28aea48877937f6b5b25f374f9c14eaf79212 | [
"BSD-3-Clause"
] | null | null | null | Python/Matlab.py | Spectavi/video-diff | 4ad28aea48877937f6b5b25f374f9c14eaf79212 | [
"BSD-3-Clause"
] | null | null | null | #import cv
import cv2
import math
import numpy as np
from numpy import linalg as npla
import sys
import scipy.interpolate
import scipy.sparse
import weave
import unittest
import common
import config
def CompareMatricesWithNanElements(M1, M2):
assert M1.shape == M2.shape;
assert M1.ndim == 2;
for r in range(M1.shape[0]):
for c in range(M2.shape[0]):
if np.isnan(M1[r, c]):
if not np.isnan(M2[r, c]):
return False;
else:
if M1[r, c] != M2[r, c]:
return False;
return True;
def ConvertCvMatToNPArray(cvmat):
m = [];
for r in range(cvmat.rows):
mR = [cvmat[r, c] for c in range(cvmat.cols)];
m.append(mR);
return np.array(m);
def Repr3DMatrix(m):
assert m.ndim == 3;
res = "";
for i in range(m.shape[2]):
res += ("\n[:, :, %d] = " % i) + str(m[:, :, i]); # + "\n";
return res;
"""
From http://www.mathworks.com/help/matlab/matlab_prog/symbol-reference.html:
Dot-Dot-Dot (Ellipsis) - ...
A series of three consecutive periods (...) is the line continuation operator in MATLAB.
Line Continuation
Continue any MATLAB command or expression by placing an ellipsis at the end of the line to be continued:
"""
def fix(x):
"""
From http://www.mathworks.com/help/matlab/ref/fix.html
fix
Round toward zero
Syntax:
B = fix(A)
Description:
B = fix(A) rounds the elements of A toward zero,
resulting in an array of integers.
For complex A, the imaginary and real parts are
rounded independently.
Examples:
a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i]
a =
Columns 1 through 4
-1.9000 -0.2000 3.4000 5.6000
Columns 5 through 6
7.0000 2.4000 + 3.6000i
fix(a)
ans =
Columns 1 through 4
-1.0000 0 3.0000 5.0000
Columns 5 through 6
7.0000 2.0000 + 3.0000i
"""
if x < 0:
return math.ceil(x);
else:
return math.floor(x);
# eps() is used by fspecial().
def eps(val=1.0):
"""
Following http://wiki.scipy.org/NumPy_for_Matlab_Users,
eps is equivalent to spacing(1).
Note: Matlab's double precision is numpy's float64.
"""
"""
From NumPy help (see also
http://docs.scipy.org/doc/numpy/reference/generated/numpy.finfo.html)
>>> np.info(np.spacing)
spacing(x[, out])
Return the distance between x and the nearest adjacent number.
Parameters
----------
x1: array_like
Values to find the spacing of.
Returns
-------
out : array_like
The spacing of values of `x1`.
Notes
-----
It can be considered as a generalization of EPS:
``spacing(np.float64(1)) == np.finfo(np.float64).eps``, and there
should not be any representable number between ``x + spacing(x)`` and
x for any finite x.
Spacing of +- inf and nan is nan.
"""
"""
From http://www.mathworks.com/help/matlab/ref/eps.html
"""
epsRes = np.spacing(val);
return epsRes;
def max(A):
"""
From http://www.mathworks.com/help/matlab/ref/max.html:
C = max(A) returns the largest elements along different dimensions of an array.
If A is a vector, max(A) returns the largest element in A.
[C,I] = max(...) finds the indices of the maximum values of A,
and returns them in output vector I.
If there are several identical maximum values,
the index of the first one found is returned.
"""
assert A.ndim == 1;
for i in range(A.shape[0]):
if np.isnan(A[i]):
A[i] = -1.0e-300;
C = np.max(A);
# We find now the index(indices) of C in A
I = np.nonzero(A == C)[0];
if False:
common.DebugPrint("MatlabMax(): a = %s" % str(A));
common.DebugPrint("MatlabMax(): C = %s" % str(C));
common.DebugPrint("MatlabMax(): I.shape = %s" % str(I.shape));
# We want only 1 element, so we make the index also an int
I = I[0];
return C, I;
def fliplr(M):
#fliplr(M);
return M[:, ::-1];
"""
We convert a tuple of (2 or 3) array indices (or array or indices) into a
linear (scalar) index (respectively, array of linear indice)
"""
def sub2ind(matrixSize, rowSub, colSub, dim3Sub=None):
"""
Note that this is a limited implementation of Matlab's sub2ind,
in the sense we support only 2 and 3 dimensions.
BUT it is easy to generalize it.
"""
assert (len(matrixSize) == 2) or (len(matrixSize) == 3);
"""
Inspired from https://stackoverflow.com/questions/15230179/how-to-get-the-linear-index-for-a-numpy-array-sub2ind
(see also http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel_multi_index.html)
From Matlab help of sub2ind (http://www.mathworks.com/help/matlab/ref/sub2ind.html):
Convert subscripts to linear indices
Syntax
linearInd = sub2ind(matrixSize, rowSub, colSub)
linearInd = sub2ind(arraySize, dim1Sub, dim2Sub, dim3Sub, ...)
# Determines whether the multi-index should be viewed as indexing in
# C (row-major) order or FORTRAN (column-major) order.
"""
#return np.ravel_multi_index((rowSub - 1, colSub - 1), dims=matrixSize, order="F");
if dim3Sub == None:
res = np.ravel_multi_index((rowSub, colSub), dims=matrixSize, order="F");
else:
res = np.ravel_multi_index((rowSub, colSub, dim3Sub), dims=matrixSize, order="F");
return res;
def find(X):
"""
find Find indices of nonzero elements.
I = find(X) returns the linear indices corresponding to
the nonzero entries of the array X. X may be a logical expression.
Use IND2SUB(SIZE(X),I) to calculate multiple subscripts from
the linear indices I.
I = find(X,K) returns at most the first K indices corresponding to
the nonzero entries of the array X. K must be a positive integer,
but can be of any numeric type.
I = find(X,K,'first') is the same as I = find(X,K).
I = find(X,K,'last') returns at most the last K indices corresponding
to the nonzero entries of the array X.
[I,J] = find(X,...) returns the row and column indices instead of
linear indices into X. This syntax is especially useful when working
with sparse matrices. If X is an N-dimensional array where N > 2, then
J is a linear index over the N-1 trailing dimensions of X.
[I,J,V] = find(X,...) also returns a vector V containing the values
that correspond to the row and column indices I and J.
Example:
A = magic(3)
find(A > 5)
finds the linear indices of the 4 entries of the matrix A that are
greater than 5.
[rows,cols,vals] = find(speye(5))
finds the row and column indices and nonzero values of the 5-by-5
sparse identity matrix.
See also sparse, ind2sub, relop, nonzeros.
"""
"""
Alex: caution needs to be taken when translating
find() - in Matlab when find() is supposed to return 1 array the
indices are of the elements numbered in
Fortran order (column-major order), while np.nonzero() returns
invariably a tuple of 2 arrays, the first for the rows, the second
for the columns;
but when find is supposed to return 2 arrays, for row and
column we don't need to worry about this.
"""
"""
Retrieving indices in "Fortran" (column-major) order, like in Matlab.
We do this in order to get the harris points sorted like in Matlab.
"""
c, r = np.nonzero(X.T);
#return c, r;
return sub2ind(c, r, X.shape);
"""
This version is at least 50 times faster than ordfilt2_vectorized().
It is very efficient. It also makes a few assumptions which were
respected in the code of Evangelidis - check below.
"""
def ordfilt2(A, order, domain):
"""
common.DebugPrint("Entered Matlab.ordfilt2(order=%d, domain=%s): " \
"A.dtype = %s" % \
(order, str(domain), str(A.dtype)));
"""
common.DebugPrint("Entered Matlab.ordfilt2(order=%d): " \
"A.dtype = %s" % \
(order, str(A.dtype)));
assert A.ndim == 2;
assert domain.shape[0] == domain.shape[1];
assert order == domain.shape[0] * domain.shape[0];
assert np.abs((domain - 1.0) < 1.0e-5).all(); # !!!!TODO: this is time consuming - take it out if there are issues
"""
(Documented from http://stackoverflow.com/questions/16685071/implementation-of-matlab-api-ordfilt2-in-opencv)
See http://docs.opencv.org/modules/imgproc/doc/filtering.html#dilate
cv2.dilate(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) -> dst
Inspired from
http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html#dilation
"""
#(order == domain.shape[0] * domain.shape[0])
kernel = np.ones(domain.shape, np.uint8);
res = cv2.dilate(A, kernel, iterations=1);
return res;
if False:
# From http://docs.opencv.org/modules/imgproc/doc/filtering.html#erode
if (order == 0):
res = cv2.dilate(A, kernel, iterations=1);
return res;
#res = np.zeros(A.shape, dtype=np.int32);
if False:
res = np.empty(A.shape, dtype=np.float64); #np.int64);
else:
res = np.empty(A.shape, dtype=A.dtype); #np.int64);
"""
PyArray_Descr *PyArray_DESCR(PyArrayObject* arr)
Returns a borrowed reference to the dtype property of the array.
PyArray_Descr *PyArray_DTYPE(PyArrayObject* arr)
New in version 1.7.
A synonym for PyArray_DESCR, named to be consistent with the .dtype. usage within Python.
"""
if False:
assert A.dtype == np.float64; #np.int64;
assert res.dtype == np.float64; #np.int64;
else:
assert (A.dtype == np.float32) or (A.dtype == np.float64);
assert res.dtype == A.dtype;
if A.dtype == np.float32:
dtypeSize = 4; # np.float32 is 4 bytes
elif A.dtype == np.float64:
dtypeSize = 8; # np.float64 is 8 bytes
common.DebugPrint("Matlab.ordfilt2(): dtypeSize = %d" % dtypeSize);
# We check to have the matrices in row-major order-style
assert A.strides == (A.shape[1] * dtypeSize, dtypeSize);
assert res.strides == (res.shape[1] * dtypeSize, dtypeSize);
# See http://wiki.scipy.org/Weave, about how to handle NP array in Weave
CPP_code = """
int r, c;
int rd, cd;
int rdu, cdu;
int center = domain_array->dimensions[0] / 2;
int numRows, numCols;
//int myMax;
double myMax;
// On various alternatives of accessing the elements of np.array: https://stackoverflow.com/questions/7744149/typecasting-pyarrayobject-data-to-a-c-array
//#define elem(row, col) (((double *)npa_array->data)[(row) * npa_array->dimensions[1] + (col)])
#define MYMIN(a, b) ((a) < (b) ? (a) : (b))
#define MYMAX(a, b) ((a) > (b) ? (a) : (b))
//assert(A_array->ndims == 2);
numRows = A_array->dimensions[0];
numCols = A_array->dimensions[1];
#define elemA(row, col) (((double *)A_array->data)[(row) * numCols + (col)])
#define elemRes(row, col) (((double *)res_array->data)[(row) * numCols + (col)])
//#define elemA(row, col) (((int *)A_array->data)[(row) * numCols + (col)])
//#define elemRes(row, col) (((int *)res_array->data)[(row) * numCols + (col)])
//#define elemA(row, col) (((long long *)A_array->data)[(row) * numCols + (col)])
//#define elemRes(row, col) (((long long *)res_array->data)[(row) * numCols + (col)])
/*
for (r = 0; r < numRows; r++) {
for (c = 0; c < numCols; c++) {
printf("A[%d, %d] = %lld ", r, c, elemA(r, c));
}
printf("%c", 10);
}
*/
for (r = 0; r < numRows; r++) {
for (c = 0; c < numCols; c++) {
if (r - center < 0)
rd = 0;
else
rd = -center;
myMax = -1;
rdu = MYMIN(center, numRows - r - 1);
for (; rd <= rdu; rd++) {
cd = -center;
if (c - center < 0)
cd = 0;
else
cd = -center;
cdu = MYMIN(center, numCols - c - 1);
for (; cd <= cdu; cd++) {
//printf("r=%d, c=%d, rd = %d, cd = %d\\n", r, c, rd, cd);
myMax = MYMAX(myMax, elemA(r + rd, c + cd));
}
}
elemRes(r, c) = myMax;
}
}
//printf("res[1, 0] = %d", elemRes(1, 0));
//printf("sum = %.2f, npa = %d", sum, PyArray_NDIM(A_array));
printf("A.shape = %ld, %ld\\n", A_array->dimensions[0], A_array->dimensions[1]);
//printf("npa[0, 0] = %.3f", ((double *)PyArray_DATA(A_array))[0]);
//printf("npa[0, 0] = %.3f", ((double *)A_array->data)[0]);
//printf("npa[1, 0] = %.3f", ((double *)A_array->data)[200]);
//printf("npa[1, 0] = %.3f", *((double *)PyArray_GETPTR2(A_array, 1, 0)));
//printf("res[1, 0] = %.3f", *((int *)PyArray_GETPTR2(res_array, 1, 0)));
"""
if A.dtype == np.float32:
CPP_code = CPP_code.replace("double", "float");
#common.DebugPrint("Matlab.ordfilt2(): CPP_code = %s" % CPP_code);
scipy.weave.inline(CPP_code, ['A', 'res', 'domain']);
#common.DebugPrint("res[1, 0] = %d" % res[1, 0]);
#common.DebugPrint("\n\nres = %s" % str(res));
return res;
# This version is at least 10x faster than the ordfilt2_4_nested_loops()
def ordfilt2_vectorized(A, order, domain):
"""
OUR ordfilt2 IMPLEMENTATION IS LIMITED w.r.t. the one in Matlab
- SEE below for details!
"""
"""
From http://www.mathworks.com/help/images/ref/ordfilt2.html
2-D order-statistic filtering
expand all in page
Syntax
B = ordfilt2(A, order, domain)
B = ordfilt2(A, order, domain, S)
B = ordfilt2(..., padopt)
Description
B = ordfilt2(A, order, domain) replaces each element in A by the
orderth element in the sorted set of neighbors specified
by the nonzero elements in domain.
B = ordfilt2(A, order, domain, S) where S is the same size as domain,
uses the values of S corresponding to the nonzero values of
domain as additive offsets.
B = ordfilt2(..., padopt) controls how the matrix boundaries are padded.
Set padopt to 'zeros' (the default) or 'symmetric'.
If padopt is 'zeros', A is padded with 0's at the boundaries.
If padopt is 'symmetric', A is symmetrically extended at the
boundaries.
Class Support
The class of A can be logical, uint8, uint16, or double.
The class of B is the same as the class of A, unless the additive
offset form of ordfilt2 is used, in which case the class of B
is double.
Examples
This examples uses a maximum filter with a [5 5] neighborhood.
This is equivalent to imdilate(image,strel('square',5)).
A = imread('snowflakes.png');
B = ordfilt2(A,25,true(5));
figure, imshow(A), figure, imshow(B)
References
[1] Haralick, Robert M., and Linda G. Shapiro, Computer and Robot Vision,
Volume I, Addison-Wesley, 1992.
[2] Huang, T.S., G.J.Yang, and G.Y.Tang.
"A fast two-dimensional median filtering algorithm.",
IEEE transactions on Acoustics, Speech and Signal Processing,
Vol ASSP 27, No. 1, February 1979
From type ordfilt2 (extra info):
%
% Remarks
% -------
% DOMAIN is equivalent to the structuring element used for
% binary image operations. It is a matrix containing only 1's
% and 0's; the 1's define the neighborhood for the filtering
% operation.
%
% For example, B=ORDFILT2(A,5,ONES(3,3)) implements a 3-by-3
% median filter; B=ORDFILT2(A,1,ONES(3,3)) implements a 3-by-3
% minimum filter; and B=ORDFILT2(A,9,ONES(3,3)) implements a
% 3-by-3 maximum filter. B=ORDFILT2(A,4,[0 1 0; 1 0 1; 0 1 0])
% replaces each element in A by the maximum of its north, east,
% south, and west neighbors.
%
% See also MEDFILT2.
% Copyright 1993-2011 The MathWorks, Inc.
"""
"""
OUR ordfilt2 IMPLEMENTATION IS LIMITED w.r.t. the one in Matlab.
We assume that:
- the matrix A contains only positive elements;
- domain is all ones and;
- order = num. elements of domain - i.e., we look for the
maximum in the domain.
To use their terminology we implement ONLY a N-by-N neighborhood
maximum filter, where N = domain.shape[0] == domain.shape[1].
To implement a generic order-th filter we can use:
- k-th order statistic algorithm - time complexity O(N lg N)
OR
- use a MIN-heap of size k - time complexity O(k lg k)
We can alternate using one or the other depending on the values of
k and N :))
"""
# We consider PADOPT is 'zeros', which pads A with zeros at the boundaries.
res = np.empty(A.shape);
assert domain.shape[0] == domain.shape[1];
assert order == domain.shape[0] * domain.shape[1];
center = domain.shape[0] / 2;
common.DebugPrint("Matlab.ordfilt2(): domain.shape = %s" % str(domain.shape));
common.DebugPrint("Matlab.ordfilt2(): center = %s" % str(center));
numRows, numCols = A.shape;
#N = numRows;
common.DebugPrint("ordfilt2(): (numRows, numCols) = %s" % \
str((numRows, numCols)));
# Vectorized implemetation
c, r = np.meshgrid(range(numCols), range(numRows));
common.DebugPrint("Matlab.ordfilt2(): c.shape = %s" % str(c.shape));
common.DebugPrint("Matlab.ordfilt2(): r.shape = %s" % str(r.shape));
assert c.shape == A.shape;
assert r.shape == A.shape;
res = np.zeros(A.shape);
nonZeroDomain = np.nonzero(domain == 1);
#common.DebugPrint("Matlab.ordfilt2(): nonZeroDomain = %s" % str(nonZeroDomain));
"""
rd = -center;
while (rd <= center):
cd = -center;
while (cd <= center):
if domain[rd + center, cd + center] == 1:
"""
if True:
if True:
for i in range(len(nonZeroDomain[0])):
rd = nonZeroDomain[0][i] - center;
cd = nonZeroDomain[1][i] - center;
#if (rd == 0) and (cd == 0):
# res = ...
"""
if True:
common.DebugPrint("ordfilt2(): (rd, cd) = %s" % \
str((rd, cd)));
common.DebugPrint("ordfilt2(): r + rd = %s" % str(r + rd));
"""
rf = r + rd;
cf = c + cd;
"""
if True:
common.DebugPrint("ordfilt2(): rf = %s" % str(rf));
common.DebugPrint("ordfilt2(): cf = %s" % str(cf));
#common.DebugPrint("ordfilt2(): rf[rf < 0] = %s" % str(rf[rf < 0]));
"""
indRZeroBelow = np.nonzero(rf < 0);
#common.DebugPrint("ordfilt2(): indRZeroBelow = %s" % str(indRZeroBelow));
indRZeroAbove = np.nonzero(rf >= numRows);
#common.DebugPrint("ordfilt2(): indRZeroAbove = %s" % str(indRZeroAbove));
indCZeroBelow = np.nonzero(cf < 0);
#common.DebugPrint("ordfilt2(): indCZeroBelow = %s" % str(indCZeroBelow));
indCZeroAbove = np.nonzero(cf >= numCols);
#common.DebugPrint("ordfilt2(): indCZeroAbove = %s" % str(indCZeroAbove));
#common.DebugPrint("ordfilt2(): c + cd = %s" % str(c + cd));
"""
Note: if we give negative values in matrices as indices,
it acts as PADOPT=='symmetric' in ordfilt2.
BUT if we have values in rf or cf > N then A[rf, cf]
gives exception like:
"IndexError: index (4) out of range (0<=index<3) in dimension 1"
"""
rf[indRZeroAbove] = 0;
cf[indCZeroAbove] = 0;
"""
if True:
common.DebugPrint("ordfilt2(): rf = %s" % str(rf));
common.DebugPrint("ordfilt2(): cf = %s" % str(cf));
"""
#crtD = A[r + rd, c + cd];
crtD = A[rf, cf];
# We rectify at the boundaries with 0, since PADOPT is 'zeros'
indicesR = np.r_[indRZeroBelow[0], indRZeroAbove[0], \
indCZeroBelow[0], indCZeroAbove[0]];
indicesC = np.r_[indRZeroBelow[1], indRZeroAbove[1], \
indCZeroBelow[1], indCZeroAbove[1]];
crtD[indicesR, indicesC] = 0.0;
"""
if True:
#common.DebugPrint("ordfilt2(): A[r + rd, c + cd] = %s" % \
# str(A[r + rd, c + cd]));
common.DebugPrint("ordfilt2(): crtD = %s" % str(crtD));
"""
# See http://docs.scipy.org/doc/numpy/reference/generated/numpy.maximum.html
res = np.maximum(res, crtD);
#cd += 1; #!!!!TODO: remove
#rd += 1; #!!!!TODO: remove
#common.DebugPrint("ordfilt2(): res = %s" % str(res));
return res;
def ordfilt2_4_nested_loops(A, order, domain):
import __builtin__
res = np.empty(A.shape);
assert domain.shape[0] == domain.shape[1];
assert order == domain.shape[0] * domain.shape[1];
center = domain.shape[0] / 2;
common.DebugPrint("Matlab.ordfilt2(): domain.shape = %s" % str(domain.shape));
common.DebugPrint("Matlab.ordfilt2(): center = %s" % str(center));
numRows, numCols = A.shape;
#N = numRows;
common.DebugPrint("ordfilt2(): (numRows, numCols) = %s" % \
str((numRows, numCols)));
r = 0;
while (r < numRows):
c = 0;
while (c < numCols):
"""
rd = -center;
if r + rd < 0: # rd < -r
rd = 0; #-r;
"""
if r - center < 0:
rd = 0; #-r;
else:
rd = -center;
#rdl = - min(center, center + r);
myMax = -1;
rdu = min(center, A.shape[0] - r - 1);
while (rd <= rdu): #center):
cd = -center;
"""
if c + cd < 0: # cd < -c
cd = 0; #-c;
"""
if c - center < 0:
cd = 0; #-r;
else:
cd = -center;
cdu = min(center, A.shape[1] - c - 1);
while (cd <= cdu): #center):
#if True:
if False:
common.DebugPrint("ordfilt2(): (r, c) = %s" % str((r, c)));
common.DebugPrint("ordfilt2(): (r+rd, c+cd) = %s" % \
str((r+rd, c+cd)));
myMax = __builtin__.max(myMax, A[r + rd, c + cd]);
#if c == A.shape[1] - 1:
if False:
common.DebugPrint("ordfilt2(): (r, c) = %s" % str((r, c)));
common.DebugPrint("ordfilt2(): (r+rd, c+cd) = %s" % \
str((r+rd, c+cd)));
common.DebugPrint("ordfilt2(): A[r + rd, c + cd] = %s" % \
str(A[r + rd, c + cd]));
common.DebugPrint("ordfilt2(): myMax = %s" % str(myMax));
cd += 1;
rd += 1;
res[r, c] = myMax;
c += 1;
r += 1;
return res;
def mean2(x):
"""
function y = mean2(x) %#codegen
%MEAN2 Average or mean of matrix elements.
% B = MEAN2(A) computes the mean of the values in A.
%
% Class Support
% -------------
% A can be numeric or logical. B is a scalar of class double.
%
% Example
% -------
% I = imread('liftingbody.png');
% val = mean2(I)
%
% See also MEAN, STD, STD2.
% Copyright 1993-2013 The MathWorks, Inc.
y = sum(x(:),'double') / numel(x);
"""
y = float(x.sum()) / x.size;
return y;
def testEqualMatrices(res, res2):
# Note: res2 is supposed to be correct
rows, cols = res.shape;
numMismatches = 0;
for r in range(rows):
for c in range(cols):
if np.isnan(res[r, c]) or np.isnan(res[r, c]):
if not (np.isnan(res2[r, c]) and np.isnan(res[r, c])):
#match = False;
numMismatches += 1;
common.DebugPrint("testEqualMatrices(): Mismatching nan at r=%d, c=%d, res2[r,c]=%s, res[r,c]=%s" % \
(r, c, str(res2[r, c]), str(res[r, c])));
elif (abs(res2[r, c] - res[r, c]) > 1.e-4):
#match = False;
numMismatches += 1;
common.DebugPrint("testEqualMatrices(): Mismatching vals at r=%d, c=%d, res2[r,c]=%s, res[r,c]=%s" % \
(r, c, str(res2[r, c]), str(res[r, c])));
#V = V[:10, :10];
#Xq = Xq[:10, :10];
#Yq = Yq[:10, :10];
if numMismatches > 0: # match == False:
common.DebugPrint("testEqualMatrices(): Mismatch with canonical implementation!!!! numMismatches = %d" % numMismatches);
return numMismatches
def interp2(V, Xq, Yq, interpolationMethod="linear"):
common.DebugPrint("Entered Matlab.interp2(): " \
"V.dtype = %s" % \
(str(V.dtype)));
#res = np.zeros(A.shape, dtype=np.int32);
if False:
res = np.empty(V.shape, dtype=np.float64); #np.int64);
else:
res = np.empty(V.shape, dtype=V.dtype); #np.int64);
"""
PyArray_Descr *PyArray_DESCR(PyArrayObject* arr)
Returns a borrowed reference to the dtype property of the array.
PyArray_Descr *PyArray_DTYPE(PyArrayObject* arr)
New in version 1.7.
A synonym for PyArray_DESCR, named to be consistent with the .dtype. usage within Python.
"""
if common.MY_DEBUG_STDOUT:
common.DebugPrint("interp2(): V.strides = %s" % str(V.strides));
common.DebugPrint("interp2(): V.shape = %s" % str(V.shape));
common.DebugPrint("interp2(): V.dtype = %s" % str(V.dtype));
common.DebugPrint("interp2(): Xq.strides = %s" % str(Xq.strides));
common.DebugPrint("interp2(): Xq.shape = %s" % str(Xq.shape));
common.DebugPrint("interp2(): Xq.dtype = %s" % str(Xq.dtype));
common.DebugPrint("interp2(): Yq.strides = %s" % str(Yq.strides));
common.DebugPrint("interp2(): Yq.shape = %s" % str(Yq.shape));
common.DebugPrint("interp2(): Yq.dtype = %s" % str(Yq.dtype));
common.DebugPrint("interp2(): res.strides = %s" % str(res.strides));
common.DebugPrint("interp2(): res.shape = %s" % str(res.shape));
common.DebugPrint("interp2(): res.dtype = %s" % str(res.dtype));
if False:
assert V.dtype == np.float64; #np.int64;
assert Xq.dtype == np.float64; #np.int64;
assert Yq.dtype == np.float64; #np.int64;
else:
if common.MY_DEBUG_STDOUT:
common.DebugPrint("interp2(): V.dtype (again) = %s" % str(V.dtype));
common.DebugPrint("interp2(): V.dtype == np.float32 is %s" % str(V.dtype == np.float32));
common.DebugPrint("interp2(): V.dtype == float is %s" % str(V.dtype == float));
"""
if False:
"""
assert (V.dtype == np.float32) or (V.dtype == np.float64); #np.int64;
assert Xq.dtype == V.dtype; #np.int64;
assert Yq.dtype == V.dtype; #np.int64;
assert V.ndim == 2;
assert Xq.ndim == 2;
assert Yq.ndim == 2;
if V.dtype == np.float32:
dtypeSize = 4; # np.float32 is 4 bytes
elif V.dtype == np.float64:
dtypeSize = 8; # np.float64 is 8 bytes
# See http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html
# We check if we have the matrices in row-major order-style
assert V.strides == (V.shape[1] * dtypeSize, dtypeSize);
assert res.strides == (res.shape[1] * dtypeSize, dtypeSize);
"""
# We check if we have the matrices in column-major order (Fortran) style
assert Xq.strides == (dtypeSize, Xq.shape[0] * dtypeSize);
assert Yq.strides == (dtypeSize, Yq.shape[0] * dtypeSize);
"""
assert interpolationMethod == "linear"; # Bilinear interpolation
CPP_code2_prefix_Row_Major_Order = """
#define elemXq(row, col) (((double *)Xq_array->data)[(row) * numC + (col)])
#define elemYq(row, col) (((double *)Yq_array->data)[(row) * numC + (col)])
"""
CPP_code2_prefix_Fortran_Major_Order = """
#define elemXq(row, col) (((double *)Xq_array->data)[(col) * numR + (row)])
#define elemYq(row, col) (((double *)Yq_array->data)[(col) * numR + (row)])
"""
if (Xq.strides == (dtypeSize, Xq.shape[0] * dtypeSize)):
assert Yq.strides == (dtypeSize, Yq.shape[0] * dtypeSize);
CPP_prefix = CPP_code2_prefix_Fortran_Major_Order;
else:
CPP_prefix = CPP_code2_prefix_Row_Major_Order;
# See http://wiki.scipy.org/Weave, about how to handle NP array in Weave
CPP_code2 = """
int r, c;
int rp, cp;
int numR, numC;
double x, y;
double x1, y1;
double val;
numR = V_array->dimensions[0];
numC = V_array->dimensions[1];
#define elemV(row, col) (((double *)V_array->data)[(row) * numC + (col)])
#define elemRes(row, col) (((double *)res_array->data)[(row) * numC + (col)])
for (r = 0; r < numR; r++) {
for (c = 0; c < numC; c++) {
x = elemXq(r, c);
y = elemYq(r, c);
//printf("interp2(): (initial) x = %.5f, y = %.5f\\n", x, y);
if ((x < 0.0) or (y < 0.0) or (x >= numC) or (y >= numR)) {
elemRes(r, c) = NAN;
continue;
}
// Need to check in which square unit (x, y) falls into
rp = (int)y;
cp = (int)x;
// Adjust (x, y) relative to this particular unit square where it falls into
y -= rp;
x -= cp;
assert((x <= 1) && (x >= 0));
assert((y <= 1) && (y >= 0));
//printf("interp2(): x = %.5f, y = %.5f\\n", x, y);
if ((x == 0.0) && (y == 0.0)) {
val = elemV(r, c);
}
else {
/*
common.DebugPrint("interp2(): r = %d, c = %d" % (r, c));
common.DebugPrint(" rp = %d, cp = %d" % (rp, cp));
common.DebugPrint(" x = %.3f, y = %.3f" % (x, y));
*/
// First index of f is the col, 2nd index is row
/*
f00 = V[rp, cp];
f01 = V[rp + 1, cp];
f10 = V[rp, cp + 1];
f11 = V[rp + 1, cp + 1];
# As said in https://en.wikipedia.org/wiki/Bilinear_interpolation
val = f00 * (1 - x) * (1 - y) + f10 * x * (1 - y) + \
f01 * (1 - x) * y + f11 * x * y;
*/
x1 = 1 - x;
y1 = 1 - y;
if (
//(rp < numR) &&
(rp >= 0) &&
//(cp < numC) &&
(cp >= 0) &&
(cp + 1 < numC) &&
//(cp + 1 >= 0) &&
(rp + 1 < numR) &&
//(rp + 1 >= 0) &&
(cp + 1 < numC)
//&& (cp + 1 >= 0)
)
{
/*
printf("interp2(): elemV(rp, cp) = %.5f\\n", elemV(rp, cp));
printf("interp2(): elemV(rp, cp + 1) = %.5f\\n", elemV(rp, cp + 1));
printf("interp2(): elemV(rp + 1, cp) = %.5f\\n", elemV(rp + 1, cp));
printf("interp2(): elemV(rp + 1, cp + 1) = %.5f\\n", elemV(rp + 1, cp + 1));
printf("interp2(): at val, x = %.5f, y = %.5f\\n", x, y);
printf("interp2(): at val, x1 = %.5f, y1 = %.5f\\n", x1, y1);
*/
val = elemV(rp, cp) * x1 * y1 + elemV(rp, cp + 1) * x * y1 +
elemV(rp + 1, cp) * x1 * y + elemV(rp + 1, cp + 1) * x * y;
}
else {
// If out of the array bounds, assign NaN
/*
This portion of code can be executed even
if we checked for out-of-bounds of (x,y).
*/
// From http://www.cplusplus.com/reference/cmath/NAN/
val = NAN;
}
}
elemRes(r, c) = val;
}
}
"""
CPP_code = CPP_prefix + CPP_code2;
if V.dtype == np.float32:
CPP_code = CPP_code.replace("double", "float");
#common.DebugPrint("Matlab.interp2(): CPP_code = %s" % CPP_code);
#scipy.weave.inline(CPP_prefix + CPP_code2, ["V", "Xq", "Yq", "res"]);
scipy.weave.inline(CPP_code, ["V", "Xq", "Yq", "res"]);
#common.DebugPrint("res[1, 0] = %d" % res[1, 0]);
#common.DebugPrint("\n\nres = %s" % str(res));
return res;
def interp2_vectorized(V, Xq, Yq, interpolationMethod="linear"):
#common.DebugPrint("Entered interp2().");
#common.DebugPrint("interp2(): Xq = %s" % str(Xq));
#TODO: think if really have to do nan or can replace it with 0 and also change the callers a bit
"""
From http://www.mathworks.com/help/matlab/ref/interp2.html :
Vq = interp2(V,Xq,Yq) assumes a default grid of sample points.
The default grid points cover the rectangular region,
X=1:n and Y=1:m, where [m,n] = size(V).
Use this syntax to when you want to conserve memory and are
not concerned about the absolute distances between points.
Vq = interp2(X,Y,V,Xq,Yq) returns interpolated values of a function
of two variables at specific query points using linear interpolation.
The results always pass through the original sampling of the function.
X and Y contain the coordinates of the sample points.
V contains the corresponding function values at each sample point.
Xq and Yq contain the coordinates of the query points.
Vq = interp2(___,method) specifies an optional, trailing input
argument that you can pass with any of the previous syntaxes.
The method argument can be any of the following strings that
specify alternative interpolation methods:
'linear', 'nearest', 'cubic', or 'spline'.
The default method is 'linear'.
Alex:
So, we give the query coordinates xi, yi and
bidimensional function wimg_time
"""
assert interpolationMethod == "linear"; # Bilinear interpolation
if False:
common.DebugPrint("interp2(): V.shape = %s" % str(V.shape));
common.DebugPrint("interp2(): Xq[:20, :20] = %s" % str(Xq[:20, :20]));
common.DebugPrint("interp2(): Xq.shape = %s" % str(Xq.shape));
common.DebugPrint("interp2(): Yq[:20, :20] = %s" % str(Yq[:20, :20]));
common.DebugPrint("interp2(): Yq.shape = %s" % str(Yq.shape));
"""
From https://en.wikipedia.org/wiki/Bilinear_interpolation
- unit square case
If we choose a coordinate system in which the four points where
f is known are (0, 0), (0, 1), (1, 0), and (1, 1), then the
interpolation formula simplifies to
f(x, y) = f(0, 0) (1-x) (1-y) + f(1, 0) x (1-y) + f(0, 1)(1-x)y + f(1, 1) xy
Or equivalently, in matrix operations:
f(x,y) = [1-x, x] [f(0,0) f(0,1); f(1,0) f(1,1)] [1-y; y]
One could use the more complex, (yet more accurate I guess),
barycentric interpolation from
http://classes.soe.ucsc.edu/cmps160/Fall10/resources/barycentricInterpolation.pdf
"""
res = np.zeros( V.shape );
numR, numC = V.shape;
yM = Yq.copy();
xM = Xq.copy();
indY = np.nonzero( np.logical_or(yM < 0, yM > numR - 1) );
#common.DebugPrint("ind from Yq = %s" % str(ind));
yM[indY] = 0.0;
#common.DebugPrint("Xq = %s" % str(Xq));
indX = np.nonzero( np.logical_or(xM < 0, xM > numC - 1) );
#common.DebugPrint("ind from Xq = %s" % str(ind));
xM[indX] = 0.0;
rpM = yM.astype(int);
cpM = xM.astype(int);
#y = Yq[r, c];
#x = Xq[r, c];
# Now they contain only fractional part
yM = yM - rpM;
xM = xM - cpM;
y1M = 1.0 - yM;
x1M = 1.0 - xM;
if False:
common.DebugPrint("interp2(): yM = %s" % str(yM));
common.DebugPrint("interp2(): xM = %s" % str(xM));
common.DebugPrint("interp2(): y1M = %s" % str(y1M));
common.DebugPrint("interp2(): x1M = %s" % str(x1M));
# nan is stronger than any other number - can't mix with other numbers
zeroRow = np.zeros( (1, V.shape[1]) ); #+ np.nan;
zeroCol = np.zeros( (V.shape[0], 1) ); #+ np.nan;
"""
if False:
V4 = np.zeros((V.shape[0], V.shape[1])); #+ np.nan;
V4[:-1, :-1] = V[1:, 1:] * xM * yM;
else:
zeroCol1 = np.zeros((V.shape[0] - 1, 1)); #+ np.nan;
#V4 = np.c_[V[1:, 1:] * xM[:-1, :-1] * yM[:-1, :-1], zeroCol1];
#V4 = np.r_[V4, zeroRow];
V4 = np.hstack( (V[1:, 1:] * xM[:-1, :-1] * yM[:-1, :-1], zeroCol1) );
V4 = np.vstack( (V4, zeroRow) );
"""
"""
Note that each element in Xq and Yq is NOT just x \in [0,1) away from the
value col, respectively raw of that element.
Therefore, we need to compute for each result element res[r, c] its
four neighbors: V00[r, c], V01[r, c], V10[r, c], V11[r, c].
"""
V00 = V[rpM, cpM];
# When FASTER is true we have an improvement of 1.13 secs / 10000.
FASTER = False; #True;
if FASTER:
V01 = np.zeros(V.shape);
V01[:, :-1] = V[:, 1:];
V01 = V01[rpM, cpM];
else:
V01 = np.c_[V[:,1:], zeroCol][rpM, cpM];
if FASTER:
V10 = np.zeros(V.shape);
V10[:-1, :] = V[1:, :];
V10 = V10[rpM, cpM];
else:
V10 = np.r_[V[1:,:], zeroRow][rpM, cpM];
if FASTER:
V11 = np.zeros(V.shape);
V11[:-1, :-1] = V[1:, 1:];
V11 = V11[rpM, cpM];
else:
zeroCol1 = np.zeros((V.shape[0] - 1, 1));
V11 = np.c_[V[1:, 1:], zeroCol1];
V11 = np.r_[V11, zeroRow][rpM, cpM];
if False:
V01 = np.c_[V00[:,1:], zeroCol];
V10 = np.r_[V00[1:,:], zeroRow];
#
V11 = np.c_[V00[1:, 1:], zeroCol1];
V11 = np.r_[V11, zeroRow];
if False:
common.DebugPrint("interp2(): V = %s" % str(V));
common.DebugPrint("interp2(): rpM = %s" % str(rpM));
common.DebugPrint("interp2(): cpM = %s" % str(cpM));
common.DebugPrint("interp2(): V00 = %s" % str(V00));
common.DebugPrint("interp2(): V01 = %s" % str(V01));
common.DebugPrint("interp2(): V10 = %s" % str(V10));
common.DebugPrint("interp2(): V11 = %s" % str(V11));
#common.DebugPrint("interp2(): xM = %s" % str(V11));
"""
x = Xq[r, c];
y = Yq[r, c];
rp = int(y);
cp = int(x);
y -= rp;
x -= cp;
x1 = 1 - x;
y1 = 1 - y;
val = V[rp, cp] * x1 * y1 + \
V[rp, cp + 1] * x * y1 + \
V[rp + 1, cp] * x1 * y + \
V[rp + 1, cp + 1] * x * y;
"""
if False:
common.DebugPrint("V[:,1:].shape = %s" % str(V[:,1:].shape));
common.DebugPrint("xM[:,:-1].shape = %s" % str(xM[:,:-1].shape));
common.DebugPrint("y1M[:,:-1].shape = %s" % str(y1M[:,:-1].shape));
common.DebugPrint("nanCol.shape = %s" % str(nanCol.shape));
common.DebugPrint("V[1:,:].shape = %s" % str(V[1:,:].shape));
common.DebugPrint("x1M[:-1,:].shape = %s" % str(x1M[:-1,:].shape));
common.DebugPrint("yM[:-1,:].shape = %s" % str(yM[:-1,:].shape));
common.DebugPrint("nanRow.shape = %s" % str(nanRow.shape));
if False:
res = V00 * x1M * y1M + \
np.c_[V01[:,1:] * xM[:,:-1] * y1M[:,:-1], zeroCol] + \
np.r_[V10[1:,:] * x1M[:-1,:] * yM[:-1,:], zeroRow] + \
V11;
res = V00 * x1M * y1M + \
V01 * xM * y1M + \
V10 * x1M * yM + \
V11 * xM * yM;
if False:
#common.DebugPrint("Yq = %s" % str(Yq));
ind = np.nonzero( np.logical_or(Yq < 0, Yq > numR - 1) );
#common.DebugPrint("ind from Yq = %s" % str(ind));
res[ind] = np.nan;
#common.DebugPrint("Xq = %s" % str(Xq));
ind = np.nonzero( np.logical_or(Xq < 0, Xq > numC - 1) );
#common.DebugPrint("ind from Xq = %s" % str(ind));
res[ind] = np.nan;
res[indY] = np.nan;
res[indX] = np.nan;
"""
# Following is a DIDACTIC example of ONE bilinear interpolation:
x = Xq[0, 0]; # - 1;
y = Yq[0, 0]; # - 1;
# First index of f is the col, 2nd index is row
f00 = V[0, 0];
f01 = V[1, 0];
f10 = V[0, 1];
f11 = V[1, 1];
# As said, https://en.wikipedia.org/wiki/Bilinear_interpolation
val = f00 * (1 - x) * (1 - y) + f10 * x * (1 - y) + f01 * (1 - x) * y + f11 * x * y;
common.DebugPrint("interp2-related: val (bilinear interpolation) = %.5f" % val);
"""
"""
# Another a bit more complex formula for bilinear interpolation,
for the general (NOT unit square) case:
from http://www.ajdesigner.com/phpinterpolation/bilinear_interpolation_equation.php#ajscroll
# it has even a calculator
x1 = 0.0;
x2 = 1.0;
y1 = 0.0;
y2 = 1.0;
Q11 = V[0, 0];
Q12 = V[1, 0];
Q21 = V[0, 1];
Q22 = V[1, 1];
common.DebugPrint("Q11 = %s" % str(Q11));
common.DebugPrint("Q21 = %s" % str(Q21));
common.DebugPrint("Q12 = %s" % str(Q12));
common.DebugPrint("Q22 = %s" % str(Q22));
nom = (x2 - x1) * (y2 - y1);
common.DebugPrint("interp2-related: nom (bilinear interpolation) = %.5f" % nom);
val2 = (x2 - x) * (y2 - y) / ( (x2 - x1) * (y2 - y1) ) * Q11 + \
(x - x1) * (y2 - y) / ( (x2 - x1) * (y2 - y1) ) * Q21 + \
(x2 - x) * (y - y1) / ( (x2 - x1) * (y2 - y1) ) * Q12 + \
(x - x1) * (y - y1) / ( (x2 - x1) * (y2 - y1) ) * Q22;
common.DebugPrint("interp2-related: val2 (bilinear interpolation) = %.5f" % val2);
"""
return res;
def interp2VectorizedWithTest(V, Xq, Yq, interpolationMethod="linear"):
common.DebugPrint("Entered interp2VectorizedWithTest()");
res = interp2Orig(V, Xq, Yq, interpolationMethod);
res2 = interp2_nested_loops(V, Xq, Yq, interpolationMethod);
resN = testEqualMatrices(res, res2);
if resN != 0:
common.DebugPrint("testEqualMatrices(): V.shape = %s" % str(V.shape));
common.DebugPrint("testEqualMatrices(): V = %s" % str(V));
common.DebugPrint("testEqualMatrices(): Xq.shape = %s" % str(Xq.shape));
common.DebugPrint("testEqualMatrices(): Xq = %s" % str(Xq));
common.DebugPrint("testEqualMatrices(): Yq.shape = %s" % str(Yq.shape));
common.DebugPrint("testEqualMatrices(): Yq = %s" % str(Yq));
return res;
#TEST_INTERP2 = True
TEST_INTERP2 = False
if TEST_INTERP2:
interp2Orig = interp2;
interp2 = interp2VectorizedWithTest;
else:
interp2Orig = interp2;
# TODO: remove
# This implementation is BAD: it assumes each query is placed in "its own square"
def interp2_BAD(V, Xq, Yq, interpolationMethod="linear"):
common.DebugPrint("Entered interp2().");
#common.DebugPrint("interp2(): Xq = %s" % str(Xq));
"""
From http://www.mathworks.com/help/matlab/ref/interp2.html :
Vq = interp2(V,Xq,Yq) assumes a default grid of sample points.
The default grid points cover the rectangular region,
X=1:n and Y=1:m, where [m,n] = size(V).
Use this syntax to when you want to conserve memory and are
not concerned about the absolute distances between points.
Vq = interp2(X,Y,V,Xq,Yq) returns interpolated values of a function
of two variables at specific query points using linear interpolation.
The results always pass through the original sampling of the function.
X and Y contain the coordinates of the sample points.
V contains the corresponding function values at each sample point.
Xq and Yq contain the coordinates of the query points.
Vq = interp2(___,method) specifies an optional, trailing input
argument that you can pass with any of the previous syntaxes.
The method argument can be any of the following strings that
specify alternative interpolation methods:
'linear', 'nearest', 'cubic', or 'spline'.
The default method is 'linear'.
Alex:
So, we give the query coordinates xi, yi and
bidimensional function wimg_time
"""
assert interpolationMethod == "linear"; # Bilinear interpolation
if False:
common.DebugPrint("interp2(): V.shape = %s" % str(V.shape));
common.DebugPrint("interp2(): Xq[:20, :20] = %s" % str(Xq[:20, :20]));
common.DebugPrint("interp2(): Xq.shape = %s" % str(Xq.shape));
common.DebugPrint("interp2(): Yq[:20, :20] = %s" % str(Yq[:20, :20]));
common.DebugPrint("interp2(): Yq.shape = %s" % str(Yq.shape));
"""
From https://en.wikipedia.org/wiki/Bilinear_interpolation
- unit square case
If we choose a coordinate system in which the four points where
f is known are (0, 0), (0, 1), (1, 0), and (1, 1), then the
interpolation formula simplifies to
f(x, y) = f(0, 0) (1-x) (1-y) + f(1, 0) x (1-y) + f(0, 1)(1-x)y + f(1, 1) xy
Or equivalently, in matrix operations:
f(x,y) = [1-x, x] [f(0,0) f(0,1); f(1,0) f(1,1)] [1-y; y]
One could use the more complex, (yet more accurate I guess),
barycentric interpolation from
http://classes.soe.ucsc.edu/cmps160/Fall10/resources/barycentricInterpolation.pdf
"""
res = np.zeros( V.shape );
numR, numC = V.shape;
yM = Yq.copy();
xM = Xq.copy();
rpM = yM.astype(int);
cpM = xM.astype(int);
#y = Yq[r, c];
#x = Xq[r, c];
yM = yM - rpM;
xM = xM - cpM;
y1M = 1.0 - yM;
x1M = 1.0 - xM;
common.DebugPrint("interp2(): yM = %s" % str(yM));
common.DebugPrint("interp2(): xM = %s" % str(xM));
common.DebugPrint("interp2(): y1M = %s" % str(y1M));
common.DebugPrint("interp2(): x1M = %s" % str(x1M));
# nan is stronger than any other number - can't mix with other numbers
zeroRow = np.zeros( (1, V.shape[1]) ); #+ np.nan;
zeroCol = np.zeros( (V.shape[0], 1) ); #+ np.nan;
if False:
V4 = np.zeros((V.shape[0], V.shape[1])); #+ np.nan;
V4[:-1, :-1] = V[1:, 1:] * xM * yM;
else:
zeroCol1 = np.zeros((V.shape[0] - 1, 1)); #+ np.nan;
#V4 = np.c_[V[1:, 1:] * xM[:-1, :-1] * yM[:-1, :-1], zeroCol1];
#V4 = np.r_[V4, zeroRow];
V4 = np.hstack( (V[1:, 1:] * xM[:-1, :-1] * yM[:-1, :-1], zeroCol1) );
V4 = np.vstack( (V4, zeroRow) );
"""
x = Xq[r, c];
y = Yq[r, c];
rp = int(y);
cp = int(x);
y -= rp;
x -= cp;
x1 = 1 - x;
y1 = 1 - y;
val = V[rp, cp] * x1 * y1 + \
V[rp, cp + 1] * x * y1 + \
V[rp + 1, cp] * x1 * y + \
V[rp + 1, cp + 1] * x * y;
"""
if False:
common.DebugPrint("V[:,1:].shape = %s" % str(V[:,1:].shape));
common.DebugPrint("xM[:,:-1].shape = %s" % str(xM[:,:-1].shape));
common.DebugPrint("y1M[:,:-1].shape = %s" % str(y1M[:,:-1].shape));
common.DebugPrint("nanCol.shape = %s" % str(nanCol.shape));
common.DebugPrint("V[1:,:].shape = %s" % str(V[1:,:].shape));
common.DebugPrint("x1M[:-1,:].shape = %s" % str(x1M[:-1,:].shape));
common.DebugPrint("yM[:-1,:].shape = %s" % str(yM[:-1,:].shape));
common.DebugPrint("nanRow.shape = %s" % str(nanRow.shape));
res = V * x1M * y1M + \
np.c_[V[:,1:] * xM[:,:-1] * y1M[:,:-1], zeroCol] + \
np.r_[V[1:,:] * x1M[:-1,:] * yM[:-1,:], zeroRow] + \
V4;
#common.DebugPrint("Yq = %s" % str(Yq));
ind = np.nonzero( np.logical_or(Yq < 0, Yq > numR - 1) );
#common.DebugPrint("ind from Yq = %s" % str(ind));
res[ind] = np.nan;
#common.DebugPrint("Xq = %s" % str(Xq));
ind = np.nonzero( np.logical_or(Xq < 0, Xq > numC - 1) );
#common.DebugPrint("ind from Xq = %s" % str(ind));
res[ind] = np.nan;
return res;
"""
This implementation is for the sake of documenting the algorithm,
but is VERY VERY slow - 1.55 secs / call for resolution of 320x240.
(So we will need to implement it in C++ in OpenCV, preferably vectorized :) .)
"""
def interp2_nested_loops(V, Xq, Yq, interpolationMethod="linear"):
assert interpolationMethod == "linear"; # Bilinear interpolation
"""
From https://en.wikipedia.org/wiki/Bilinear_interpolation
- unit square case
If we choose a coordinate system in which the four points where
f is known are (0, 0), (0, 1), (1, 0), and (1, 1), then the
interpolation formula simplifies to
f(x, y) = f(0, 0) (1-x) (1-y) + f(1, 0) x (1-y) + f(0, 1)(1-x)y + f(1, 1) xy
Or equivalently, in matrix operations:
f(x,y) = [1-x, x] [f(0,0) f(0,1); f(1,0) f(1,1)] [1-y; y]
One could use the more complex, (yet more accurate I guess),
barycentric Interpolation from
http://classes.soe.ucsc.edu/cmps160/Fall10/resources/barycentricInterpolation.pdf
"""
res = np.zeros( V.shape );
numR, numC = V.shape;
for r in range(numR):
for c in range(numC):
x = Xq[r, c];
y = Yq[r, c];
if (x < 0.0) or (y < 0.0) or (x >= numC) or (y >= numR):
res[r, c] = np.nan;
continue;
# Need to check in which square unit (x, y) falls into
rp = int(y);
cp = int(x);
# Adjust (x, y) relative to this particular unit square where it falls into
y -= rp;
x -= cp;
if not((y <= 1) and (y >= 0)) or \
not((x <= 1) and (x >= 0)):
common.DebugPrint("interp2(): r = %d, c = %d" % (r, c));
common.DebugPrint(" rp = %d, cp = %d" % (rp, cp));
common.DebugPrint(" x = %.3f, y = %.3f" % (x, y));
common.DebugPrint(" Xq[r, c] = %.3f, Yq[r, c] = %.3f" % \
(Xq[r, c], Yq[r, c]));
#sys.stdout.flush();
assert (x <= 1) and (x >= 0);
assert (y <= 1) and (y >= 0);
if (x == 0.0) and (y == 0.0):
val = V[r, c];
else:
"""
common.DebugPrint("interp2(): r = %d, c = %d" % (r, c));
common.DebugPrint(" rp = %d, cp = %d" % (rp, cp));
common.DebugPrint(" x = %.3f, y = %.3f" % (x, y));
"""
# First index of f is the col, 2nd index is row
try:
"""
f00 = V[rp, cp];
f01 = V[rp + 1, cp];
f10 = V[rp, cp + 1];
f11 = V[rp + 1, cp + 1];
# As said in https://en.wikipedia.org/wiki/Bilinear_interpolation
val = f00 * (1 - x) * (1 - y) + f10 * x * (1 - y) + \
f01 * (1 - x) * y + f11 * x * y;
"""
x1 = 1 - x;
y1 = 1 - y;
val = V[rp, cp] * x1 * y1 + V[rp, cp + 1] * x * y1 + \
V[rp + 1, cp] * x1 * y + V[rp + 1, cp + 1] * x * y;
except:
# If out of the array bounds, assign NaN
"""
This portion of code can be executed even
if we checked for out-of-bounds of (x,y).
"""
val = np.nan;
res[r, c] = val;
return res;
"""
This is a slightly optimized version of the interp2_nested_loops.
1.135 secs / call for resolution of 320x240.
The gain in performance is around 27% .
"""
def interp2_1loop(V, Xq, Yq, interpolationMethod="linear"):
assert interpolationMethod == "linear"; # Bilinear interpolation
res = np.zeros( V.shape );
numR, numC = V.shape;
#for r in range(numR):
# for c in range(numC):
numPixels = numR * numC;
i = 0;
r = 0;
c = -1;
while i < numPixels:
i += 1;
c += 1;
if c == numC:
c = 0;
r += 1;
#common.DebugPrint("interp2(): r = %d, c = %d, i=%d" % (r, c, i));
x = Xq[r, c];
y = Yq[r, c];
if (x < 0.0) or (y < 0.0) or (x >= numC) or (y >= numR):
res[r, c] = np.nan;
continue;
# Need to check in which square unit (x, y) falls into
rp = int(y);
cp = int(x);
# Adjust (x, y) relative to this particular unit square where it falls into
y -= rp;
x -= cp;
"""
if not((y <= 1) and (y >= 0)) or \
not((x <= 1) and (x >= 0)):
common.DebugPrint("interp2(): r = %d, c = %d" % (r, c));
common.DebugPrint(" rp = %d, cp = %d" % (rp, cp));
common.DebugPrint(" x = %.3f, y = %.3f" % (x, y));
common.DebugPrint(" Xq[r, c] = %.3f, Yq[r, c] = %.3f" % \
(Xq[r, c], Yq[r, c]));
#sys.stdout.flush();
"""
# For efficiency reasons we do not do the asserts
#assert (x <= 1) and (x >= 0);
#assert (y <= 1) and (y >= 0);
if (x == 0.0) and (y == 0.0):
val = V[r, c];
else:
"""
common.DebugPrint("interp2(): r = %d, c = %d" % (r, c));
common.DebugPrint(" rp = %d, cp = %d" % (rp, cp));
common.DebugPrint(" x = %.3f, y = %.3f" % (x, y));
"""
# First index of f is the col, 2nd index is row
try:
"""
f00 = V[rp, cp];
f01 = V[rp + 1, cp];
f10 = V[rp, cp + 1];
f11 = V[rp + 1, cp + 1];
# As said in https://en.wikipedia.org/wiki/Bilinear_interpolation
val = f00 * (1 - x) * (1 - y) + f10 * x * (1 - y) + \
f01 * (1 - x) * y + f11 * x * y;
"""
x1 = 1 - x;
y1 = 1 - y;
val = V[rp, cp] * x1 * y1 + V[rp, cp + 1] * x * y1 + \
V[rp + 1, cp] * x1 * y + V[rp + 1, cp + 1] * x * y;
except:
# If out of the array bounds, assign NaN
"""
This portion of code can be executed even
if we checked for out-of-bounds of (x,y).
"""
val = np.nan;
res[r, c] = val;
return res;
def interp2_scipy(V, Xq, Yq, interpolationMethod="linear"):
assert interpolationMethod == "linear"; # Bilinear interpolation
###UNFORTUNATELY, THIS IMPLEMENTATION WHEN TRYING TO BE EFFICIENT CRASHES##
# Unfortunately, scipy.interpolate.interp2d (from scipy v0.14 - latest Mar 2014)
# crashes in some cases, hence we don't really use this implementation yet
# See http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp2d.html
if False:
#yVals = np.array([[[i] * V.shape[1]] for i in range(V.shape[0])]);
yList = [];
for i in range(V.shape[0]):
yList += [i] * V.shape[1];
#yVals = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]);
xVals = np.array(range(V.shape[1]) * V.shape[0]);
else:
yVals = np.array(range(V.shape[0]));
xVals = np.array(range(V.shape[1]));
f = scipy.interpolate.interp2d(x=xVals, y=yVals, z=V, \
kind="linear", copy=False); # Gives strange errors: "cubic");
# We flatten the query matrices to 1D arrays:
Xqf = np.ravel(Xq);
Yqf = np.ravel(Yq);
if False:
# Copied from scipy\interpolate\fitpack.py
Xqf = np.atleast_1d(Xqf);
Yqf = np.atleast_1d(Yqf);
Xqf,Yqf = map(np.atleast_1d,[Xqf,Yqf]);
if False:
common.DebugPrint("interp2(): xVals = %s" % str(xVals));
common.DebugPrint("interp2(): yVals = %s" % str(yVals));
common.DebugPrint("interp2(): Xqf = %s" % str(Xqf));
common.DebugPrint("interp2(): Xqf.shape = %s" % str(Xqf.shape));
common.DebugPrint("interp2(): len(Xqf.shape) = %s" % str(len(Xqf.shape)));
common.DebugPrint("interp2(): Yqf = %s" % str(Yqf));
common.DebugPrint("interp2(): Yqf.shape = %s" % str(Yqf.shape));
common.DebugPrint("interp2(): len(Yqf.shape) = %s" % str(len(Yqf.shape)));
#zNew = f(Xq, Yq); # ValueError: First two entries should be rank-1 arrays.
if False:
# It is more efficient like this - but the SciPy implementation (v0.11, at least ) has bugsTODO
# Don't understand/see a reason why - I reported to scipy community on forum
zNew = f(Xqf, Yqf); # Gives: ValueError: Invalid input data
else:
zNew = np.zeros( V.shape );
numRows, numCols = V.shape;
r =0; c = 0;
for i in range(len(Xqf)):
#print f(Xqf[i], Yqf[i]);
#zNew[i / numRows, i % numRows] = f(Xqf[i], Yqf[i]);
zNew[r, c] = f(Xqf[i], Yqf[i]);
c += 1;
if c == numCols:
r += 1;
c = 0;
#zNew = f(Xqf, Yqf); # ValueError: Invalid input data
#zNew = f(0.7, 0.3);
return zNew;
def interp2_OpenCV(V, Xq, Yq, interpolationMethod="linear"):
assert interpolationMethod == "linear"; # Bilinear interpolation
####UNFORTUNATELY, IMPLEMENTATION WITH OpenCV REMAP GIVES WRONG RESULTS####
# BUT MAYBE USEFUL FOR OTHER PROCEDURES...
"""
From https://stackoverflow.com/questions/19912234/cvremap-in-opencv-and-interp2-matlab
<<In case you didn't find your answer yet, this is how you should use it.
remap(f,f2,x2,y2,CV_INTER_CUBIC);
The function remap supposes that you're working on exactly the grid where
f is defined so no need to pass the x,y monotonic coordinates.
I'm almost sure that the matrices cannot be CV_64F (double) so, take that
into account.>>
Alex: VERY GOOD explanation:
<<interp2 is interpolator - if you get x,y and f values for some mesh
it gives you the value f2 for x2 and y2.
remap - wraps your mesh by moving x and y coordinates acording to the
deformation maps.
if you want interpolate regular mesh then use scaling (cv::resize for example).
If data is scattered then you can use Delaunay triangulation and then
barycentric interpolation as variant or inverse distance weighting.>>
"""
#OpenCV Error: Assertion failed (ifunc != 0) in unknown function, file ..\..\..\src\opencv\modules\imgproc\src\imgwarp.cpp, line 2973
# error: ..\..\..\src\opencv\modules\imgproc\src\imgwarp.cpp:2973: error: (-215) ifunc != 0
V = V.astype(float);
#Xq = cv.fromarray(Xq);
#Yq = cv.fromarray(Yq);
#Xq = Xq.astype(float);
#Yq = Yq.astype(float);
common.DebugPrint("cv2.INTER_LINEAR = %s" % str(cv2.INTER_LINEAR));
# Inspired from https://stackoverflow.com/questions/12535715/set-type-for-fromarray-in-opencv-for-python
r, c = Xq.shape[0], Xq.shape[1];
Xq_32FC1 = cv.CreateMat(r, c, cv.CV_32FC1);
cv.Convert(cv.fromarray(Xq), Xq_32FC1);
r, c = Yq.shape[0], Yq.shape[1];
Yq_32FC1 = cv.CreateMat(r, c, cv.CV_32FC1);
cv.Convert(cv.fromarray(Yq), Yq_32FC1);
if common.MY_DEBUG_STDOUT:
common.DebugPrint("interp2_OpenCV(): Xq_32FC1 = %s" % str(ConvertCvMatToNPArray(Xq_32FC1)));
common.DebugPrint("interp2_OpenCV(): Yq_32FC1 = %s" % str(ConvertCvMatToNPArray(Yq_32FC1)));
"""
From http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=remap#remap
cv2.remap(src, map1, map2, interpolation[, dst[, borderMode[, borderValue ] ] ])
"""
"""
Gives error:
OpenCV Error: Assertion failed (((map1.type() == CV_32FC2 || map1.type() == CV_16SC2) && !map2.data) || (map1.type() == CV_32FC1
&& map2.type() == CV_32FC1)) in unknown function, file ..\..\..\src\opencv\modules\imgproc\src\imgwarp.cpp, line 2988
dst = cv2.remap(src=V, map1=Xq, map2=Yq, interpolation=cv2.INTER_LINEAR);
"""
# Gives error: TypeError: map1 is not a numpy array, neither a scalar
#dst = cv2.remap(src=V, map1=Xq_32FC1, map2=Xq_32FC1, interpolation=cv2.INTER_LINEAR);
# From http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=remap#remap
dst = cv.fromarray(V.copy());
cv.Remap(src=cv.fromarray(V), dst=dst, \
mapx=Xq_32FC1, mapy=Yq_32FC1, \
flags=cv.CV_INTER_LINEAR); #CV_INTER_NN, CV_INTER_AREA, CV_INTER_CUBIC
if False:
dst = cv.fromarray(V.copy());
"""
Gives error:
OpenCV Error: Assertion failed (((map1.type() == CV_32FC2 || map1.type() == CV_16SC2) && !map2.data) || (map1.type() == CV_32FC1
&& map2.type() == CV_32FC1)) in unknown function, file ..\..\..\src\opencv\modules\imgproc\src\imgwarp.cpp, line 2988
"""
# From http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=remap#remap
cv.Remap(src=cv.fromarray(V), dst=dst, \
mapx=cv.fromarray(Xq), mapy=cv.fromarray(Yq), \
flags=cv.CV_INTER_LINEAR); #flags=CV_INNER_LINEAR+CV_WARP_FILL_OUTLIERS, fillval=(0, 0, 0, 0))
return dst;
###############################################################################
###############################################################################
###############################################################################
###############################################################################
"""
# From Matlab help (also http://www.mathworks.com/help/images/ref/imresize.html) :
B = imresize(A, scale) returns image B that is scale times
the size of A. The input image A can be a grayscale, RGB, or binary image. If scale is
between 0 and 1.0, B is smaller than A.
If scale is greater than 1.0, B is larger than A.
B = imresize(A, [numrows numcols]) returns
image B that has the number of rows and columns
specified by [numrows numcols]. Either numrows or numcols may
be NaN, in which case imresize computes
the number of rows or columns automatically to preserve the image
aspect ratio.
Options:
- 'nearest' Nearest-neighbor interpolation; the output pixel is assigned
the value of the pixel that the point falls within. No other pixels
are considered.
- 'bicubic' Bicubic interpolation (the default); the output pixel
value is a weighted average of pixels in the nearest 4-by-4 neighborhood
Example of standard imresize() in Matlab:
Trial>> img=ones(240, 320);
Trial>> img(92,192) = 0;
Trial>> res=imresize(img, [11, 11]) % this is default, bicubic interpolation
res(3,7)=1.0001
res(4,7)=0.9995
res(5,7)=0.9987
res(6,7)=1.0001
res(5,8)=0.9999
all other elems of res are 1.0000
What is surprising is that in this case, instead of let's say having
res(4,7) = 0.99 and the rest 1, we have like above.
This could indicate that because of antialiasing we have in the original image
a 100x100 stretch to the neighboring 1s influenced due to the 0 at img(92,192).
This is highly unlikely the case, therefore DOES imresize() scale down using
"pyramids", i.e., a few intermediate scale-downs to reach the desired
destination size?
Trial>> res=imresize(img, [11, 11], 'bilinear')
res(4,7)=0.9996
res(5,7)=0.9990
res(5,8)=0.9999
all other elems of res are 1.0000
Trial>> res=imresize(img, [11, 11], 'nearest')
all elems of res are 1
"""
def imresize(A, scale=None, newSize=None, interpolationMethod=cv2.INTER_CUBIC): #!!!!TODO: should we put something different than
assert (scale != None) or (newSize != None);
assert not ((scale != None) and (newSize != None));
common.DebugPrint("Entered imresize(A.shape=%s, scale=%s, newSize=%s)" % \
(str(A.shape), str(scale), str(newSize)));
if scale != None:
newSize = (int(A.shape[0] * scale), int(A.shape[1] * scale));
# Matlab has [numrows numcols] and OpenCV has [numcols numrows] for size specification.
newSize = (newSize[1], newSize[0]);
"""
NOTE: the image returned by cv2.resize after INTER_CUBIC contains slightly
different results compared to Matlab's imresize(, 'bicubic').
# From http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html#resize
cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation ]]]]) -> dst
interpolation - interpolation method:
- INTER_NEAREST - a nearest-neighbor interpolation
- INTER_LINEAR - a bilinear interpolation (used by default)
- INTER_AREA - resampling using pixel area relation.
It may be a preferred method for image decimation,
as it gives moire'-free results. But when the image is zoomed,
it is similar to the INTER_NEAREST method.
- INTER_CUBIC - a bicubic interpolation over 4x4 pixel neighborhood
- INTER_LANCZOS4 - a Lanczos interpolation over 8x8 pixel neighborhood
"""
if True:
"""
NOTE:
From http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.html
"Scaling is just resizing of the image.
OpenCV comes with a function cv2.resize() for this purpose.
The size of the image can be specified manually,
or you can specify the scaling factor.
Different interpolation methods are used.
Preferable interpolation methods are cv2.INTER_AREA for shrinking and
cv2.INTER_CUBIC (slow) & cv2.INTER_LINEAR for zooming.
By default, interpolation method used is cv2.INTER_LINEAR for all
resizing purposes."
"""
if newSize[0] >= A.shape[0]:
# We do zoom in of the image (make the image bigger)
"""
common.DebugPrint("imresize(): issue - A.shape=%s, newSize=%s" % \
(str(A.shape), newSize));
"""
#assert newSize[0] < A.shape[0];
res = cv2.resize(A, newSize, interpolation=cv2.INTER_LINEAR);
else:
# We make the image smaller
"""
This is a ~bit equivalent with Matlab's imresize w.r.t. antialiasing:
- even for 1 pixel 0 surrounded only by 1s, when we reduce
the image, that 0 contributes a bit to the result of resize()
in only a pixel (not a square of pixels like in Matlab).
See test_OpenCV.py for behavior of resize(..., INTER_AREA)
"""
res = cv2.resize(A, newSize, interpolation=cv2.INTER_AREA);
else:
"""
NOTE: As said above INTER_CUBIC interp. method is slow and does not do
anti-aliasing at all (while Matlab's imresize does antialiasing).
"""
res = cv2.resize(A, newSize, interpolation=interpolationMethod);
return res;
"""
From Matlab help (http://www.mathworks.com/help/matlab/ref/hist.html):
"hist(data) creates a histogram bar plot of data.
Elements in data are sorted into 10 equally spaced bins along the x-axis
between the minimum and maximum values of data."
"hist(data,xvalues) uses the values in vector xvalues to determine the bin
intervals and sorts data into the number of bins
determined by length(xvalues). To specify the bin
centers, set xvalues equal to a vector of evenly
spaced values. The first and last bins extend to cover the minimum
and maximum values in data."
"nelements = hist(___) returns a row vector, nelements, indicating the number of elements in each bin."
"""
"""
From https://stackoverflow.com/questions/18065951/why-does-numpy-histogram-python-leave-off-one-element-as-compared-to-hist-in-m:
<<Note that in matlab's hist(x, vec), vec difines the bin-centers, while in
matlab histc(x, vec) vec defines the bin-edges of the histogram.
Numpy's histogram seems to work with bin-edges.
Is this difference important to you?
It should be easy to convert from one to the other, and you might have to
add an extra Inf to the end of the bin-edges to get it to return the
extra bin you want.
More or less like this (untested):
For sure it does not cover all the edge-cases that matlab's hist provides,
but you get the idea.>>
"""
def hist(x, binCenters):
#!!!!TODO: verify if it covers all the edge-cases that matlab's hist provides
#print binCenters[:-1] + binCenters[1:]
binEdges = np.r_[-np.Inf, 0.5 * (binCenters[:-1] + binCenters[1:]), np.Inf]
counts, edges = np.histogram(x, binEdges)
return counts
def kron(A, B):
"""
From Matlab help:
kron
Kronecker tensor product
K = kron(A,B)
example
Description
example
K = kron(A,B)
returns the Kronecker tensor product of matrices A and B.
If A is an m-by-n matrix
and B is a p-by-q matrix,
then kron(A,B) is an m*p-by-n*q matrix
formed by taking all possible products between the elements of A and
the matrix B.
% KRON(X,Y) is the Kronecker tensor product of X and Y.
% The result is a large matrix formed by taking all possible
% products between the elements of X and those of Y. For
% example, if X is 2 by 3, then KRON(X,Y) is
%
% [ X(1,1)*Y X(1,2)*Y X(1,3)*Y
% X(2,1)*Y X(2,2)*Y X(2,3)*Y ]
%
% If either X or Y is sparse, only nonzero elements are multiplied
% in the computation, and the result is sparse.
"""
# See the interesting Matlab implementation
# See http://docs.scipy.org/doc/numpy/reference/generated/numpy.kron.html
res = np.kron(A, B);
"""
Note: it seems that np.kron might be failing to compute exactly what
Matlab kron() computes.
See https://stackoverflow.com/questions/17035767/kronecker-product-in-python-and-matlab.
Following https://stackoverflow.com/questions/17035767/kronecker-product-in-python-and-matlab
we can get the right result.??
# See http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.kron.html
res = scipy.sparse.kron(A, B);
"""
return res;
"""
Matlab unique from http://www.mathworks.com/help/matlab/ref/unique.html:
C = unique(A) returns the same data as in A, but with no repetitions.
If A is a numeric array, logical array, character array, categorical array, or a cell array of strings, then unique returns the unique values in A. The values of C are in sorted order.
If A is a table, then unique returns the unique rows in A. The rows of table C are in sorted order.
example
C = unique(A,'rows') treats each row of A as a single entity and returns the unique rows of A. The rows of the array C are in sorted order.
The 'rows' option does not support cell arrays.
[C,ia,ic] = unique(A) also returns index vectors ia and ic.
If A is a numeric array, logical array, character array, categorical array, or a cell array of strings, then C = A(ia) and A = C(ic).
If A is a table, then C = A(ia,:) and A = C(ic,:).
[C,ia,ic] = unique(A,'rows') also returns index vectors ia and ic, such that C = A(ia,:) and A = C(ic,:).
"""
def unique(c2):
# NOT good since it flattens the array (transforms multidim vector into 1D vector)
#c2, c2i = np.unique(ar=c2, return_index=True) #Check if "rows", "first" is really required
# c2 is a list of lists of 2 float elements. Ex: c2F = [[89.188, 33.111], [90.994, 250.105], ...]
#common.DebugPrint("c2 = %s" % str(c2));
c2l = c2.tolist();
#common.DebugPrint("unique(): c2l=%s" % str(c2l));
c2lSorted = [];
for i, e in enumerate(c2l):
#e1 = e; #.copy();
e.append(i);
c2lSorted.append(e);
c2lSorted.sort();
#common.DebugPrint("unique(): c2lSorted = %s" % str(c2lSorted));
c2lSortedIndex = [];
for e in c2lSorted:
c2lSortedIndex.append(e[2]);
#common.DebugPrint("unique(): c2lSortedIndex = %s" % str(c2lSortedIndex));
#quit();
"""
np.argsort() is a crappy function in the end...
Unfortunately I don't understand the output of np.argsort() when a is
bi/multi-dimensional... - and it's not my fault - see
http://stackoverflow.com/questions/12496531/sort-numpy-float-array-column-by-column
and http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html
"""
if False:
#c2i = []
# Does NOT return c2i: c2 = np.sort(a=c2, axis=0, kind="quicksort")
c2i = np.argsort(a=c2, axis=0, kind="quicksort");
assert len(c2i) == len(c2);
if common.MY_DEBUG_STDOUT:
common.DebugPrint("unique(): c2i = %s" % str(c2i));
c2i = c2i[:, 0]; # c2i returned is a list of lists of 2 elements: c2i[k][1] is the index of the kth element in c2i
c2i = np.array(c2lSortedIndex);
#common.DebugPrint("unique(): c2i = %s" % str(c2i));
# This is not good since the last element is the position: c2 = np.array(c2lSorted);
try:
c2 = c2[c2i];
except:
#common.DebugPrint("c2 = %s" % str(c2))
#common.DebugPrint("c2i = %s" % str(c2i))
return np.array([]), np.array([]);
#quit()
#common.DebugPrint("unique(): c2 = %s" % str(c2));
#common.DebugPrint("c2 (after indirect sorting) = %s" % str(c2));
c2F = []; #np.array([])
c2iF = [];
#rowFirst = 0;
#for row in range(c2i.size - 1):
row = 0;
#for row in range(c2i.size - 1):
while row < c2i.size:
#print "row = %d" % row;
c2F.append(c2[row].tolist());
c2iF.append(c2i[row]);
#common.DebugPrint("row = %d" % row);
if row + 1 < c2i.size:
rowCrt = row + 1;
while rowCrt < c2i.size:
#common.DebugPrint("rowCrt = %d" % rowCrt);
"""
# This comparison is NOT general - it assumes
# np.dims(c2) == (X, 2).
if (c2[row][0] == c2[rowCrt][0]) and \
(c2[row][1] == c2[rowCrt][1]):
"""
"""
Test that the 2 rows are identical
(each pair of corresponding elements are equal)
"""
if (c2[row] == c2[rowCrt]).all():
pass;
else:
break;
rowCrt += 1;
row = rowCrt;
else:
row += 1;
"""
#for row in range(c2i.size - 1):
while row < c2i.size:
#print "row = %d" % row
if row == c2i.size - 1:
c2F.append(c2[row].tolist());
c2iF.append(c2i[row]);
for rowCrt in range(row + 1, c2i.size):
#print "rowCrt = %d" % rowCrt
if (c2[row][0] == c2[rowCrt][0]) and \
(c2[row][1] == c2[rowCrt][1]):
row += 1;
pass;
else:
c2F.append(c2[row].tolist());
c2iF.append(c2i[row]);
#rowFirst += 1;
break
row += 1;
"""
#print "unique(): c2F = %s" % (str(c2F));
#print "unique(): c2iF = %s" % (str(c2iF));
c2F = np.array(c2F);
c2iF = np.array(c2iF);
return c2F, c2iF;
def hamming(N):
"""
Alex: replaced Matlab "Signal Processing Toolbox"'s hamming() with my own
simple definition - inspired from
http://www.mathworks.com/matlabcentral/newsreader/view_thread/102510
"""
t = np.array( range(N) )
b = np.zeros( (N) )
if N == 0:
return b;
elif N == 1:
b[0] = 1;
return b;
#print "hamming(): b.shape = %s" % str(b.shape);
#print "hamming(): t.shape = %s" % str(t.shape);
#b[t] = 0.54 - 0.46 * math.cos(2 * math.pi * (t - 1) / (N - 1));
b[t] = 0.54 - 0.46 * np.cos(2 * math.pi * t / float(N - 1));
return b;
"""
h is a vector... - see use below filter2(b, ...)
From Matlab help:
Syntax
Y = filter2(h,X)
Y = filter2(h,X,shape)
Description
Y = filter2(h,X) filters
the data in X with the two-dimensional FIR filter
in the matrix h. It computes the result, Y,
using two-dimensional correlation, and returns the central part of
the correlation that is the same size as X.Y = filter2(h,X,shape) returns
the part of Y specified by the shape parameter. shape is
a string with one of these values:
Given a matrix X and a two-dimensional FIR
filter h, filter2 rotates
your filter matrix 180 degrees to create a convolution kernel. It
then calls conv2, the two-dimensional convolution
function, to implement the filtering operation.filter2 uses conv2 to
compute the full two-dimensional convolution of the FIR filter with
the input matrix. By default, filter2 then extracts
the central part of the convolution that is the same size as the input
matrix, and returns this as the result. If the shape parameter
specifies an alternate part of the convolution for the result, filter2 returns
the appropriate part.
"""
# https://stackoverflow.com/questions/16278938/convert-matlab-to-opencv-in-python
def filter2(window, src):
assert len(window.shape) == 1
# In certain cases it's unusual that we have a window that is 1D and x is 2D
#common.DebugPrint("filter2(): src.shape = %s" % str(src.shape))
#common.DebugPrint("filter2(): window.shape = %s" % str(window.shape))
#common.DebugPrint("filter2(): src = %s" % str(src))
#common.DebugPrint("filter2(): window = %s" % str(window))
# From http://docs.opencv.org/modules/imgproc/doc/filtering.html#cv.Filter2D
#cv2.filter2D(src, ddepth, kernel[, dst[, anchor[, delta[, borderType]]]]) -> dst
#res = cv2.filter2D(src=window, ddepth=-1, kernel=x)
#res = cv2.filter2D(src=x, ddepth=-1, kernel=window, borderType=cv2.BORDER_REFLECT) #cv2.BORDER_CONSTANT) #cv2.BORDER_ISOLATED) #cv2.BORDER_TRANSPARENT)
"""
# OpenCV's formula to compute filter2 is dst(x,y)= \sum...
As we can see they consider the matrix being in column-major order, so we need to transpose the matrices
Doing so we obtain the right values at the 4 borders.
"""
src = src.T;
#window = window.T
# Note: CvPoint is (x, y)
res = cv2.filter2D(src=src, ddepth=-1, kernel=window, anchor=(-1, -1), \
borderType=cv2.BORDER_ISOLATED); #BORDER_DEFAULT) #BORDER_CONSTANT) #cv2.BORDER_TRANSPARENT)
res = res.T;
if False:
# Alex's implementation following http://docs.opencv.org/modules/imgproc/doc/filtering.html#filter2d
dst = np.zeros( (src.shape[0], src.shape[1]), dtype=np.float64);
for y in range(src.shape[1]):
for x in range(src.shape[0]):
for xp in range(window.shape[0]):
"""
if (y >= src.shape[0]) or (x + xp - 1 >= src.shape[1]) or \
(x + xp - 1 < 0):
"""
if (y >= src.shape[1]) or (x + xp - 1 >= src.shape[0]) or \
(x + xp - 1 < 0):
pass;
else:
#dst[y, x] += window[xp] * src[y, x + xp - 1];
dst[x, y] += window[xp] * src[x + xp - 1, y];
res = dst;
return res;
"""
"""
if False:
range1 = src.shape[0] - window.shape[0] + 1;
#range2 = src.shape[1] - window.shape[1] + 1;
range2 = src.shape[1] - window.shape[0] + 1;
if range2 < 0:
range2 = 1;
res = np.zeros((range1, range2), dtype=np.float64);
for i in range(range1):
for j in range(range2):
#common.DebugPrint("filter2(): j = %d" % j)
#res[i, j] = np.sum(np.multiply(x[i: 11 + i, j: 11 + j], window))
res[i, j] = np.sum( \
np.multiply(src[i: window.shape[0] + i, j: window.shape[0] + j], window));
# From https://codereview.stackexchange.com/questions/31089/optimizing-numpy-code - optimized version using as_strided and sum instead of nested loops
if False:
# Gives exception: "ValueError: negative dimensions are not allowed"
x1 = np.lib.stride_tricks.as_strided(x, \
((src.shape[0] - 10) / 1, (src.shape[1] - 10) / 1, 11, 11), \
(src.strides[0] * 1, src.strides[1] * 1, \
src.strides[0], src.strides[1])) * window;
res = x1.sum((2, 3));
return res;
def gradient(img, spaceX=1, spaceY=1, spaceZ=1):
assert (img.ndim == 2) or (img.ndim == 3);
#if img.ndim == 3:
# assert spaceZ != None
"""
From Matlab help:
Description:
FX = gradient(F), where F is
a vector, returns the one-dimensional numerical gradient of F.
Here FX corresponds to deltaF/deltax,
the differences in x (horizontal) direction. [FX,FY] = gradient(F),
where F is a matrix, returns the x and y components
of the two-dimensional numerical gradient. FX corresponds
to deltaF/deltax, the
differences in x (horizontal) direction. FY corresponds
to deltaF/deltay, the
differences in the y (vertical) direction. The
spacing between points in each direction is assumed to be one.
[FX,FY,FZ,...] = gradient(F),
where F has N dimensions, returns
the N components of the gradient of F.
There are two ways to control the spacing between values in F:
A single spacing value, h, specifies
the spacing between points in every direction.
N spacing values (h1,h2,...)
specifies the spacing for each dimension of F.
Scalar spacing parameters specify a constant spacing for each dimension.
Vector parameters specify the coordinates of the values along corresponding
dimensions of F. In this case, the length of the
vector must match the size of the corresponding dimension.
Note:
The first output FX is always the gradient
along the 2nd dimension of F, going across columns.
The second output FY is always the gradient along
the 1st dimension of F, going across rows. For
the third output FZ and the outputs that follow,
the Nth output is the gradient along the Nth dimension of F.
[...] = gradient(F,h1,h2,...) with N spacing
parameters specifies the spacing for each dimension of F.
"""
"""
The best documentation is at:
http://answers.opencv.org/question/16422/matlab-gradient-to-c/
Note: There they mention also
#!!!!See also
http://stackoverflow.com/questions/17977936/matlab-gradient-equivalent-in-opencv
http://stackoverflow.com/questions/9964340/how-to-extract-numerical-gradient-matrix-from-the-image-matrix-in-opencv
http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_gradients/py_gradients.html
"""
#print "img = %s" % str(img);
"""
!!!!TODO: try to implement a ~different gradient using OpenCV's Sobel,
or other parallelizable function - I think gradient() will be a hotspot
of the application.
"""
if False:
# From http://answers.opencv.org/question/16422/matlab-gradient-to-c/
"""
Result is VERY wrong compared to Matlab's x,y = gradient.
"""
#sobelx = cv2.Sobel(src=img, ddepth=cv2.CV_8U, dx=1, dy=0, ksize=5);
#sobelx = cv2.Sobel(src=img, ddepth=-1, dx=1, dy=0, ksize=5);
#sobelx = cv2.Sobel(src=img, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=5);
sobelx = cv2.Sobel(src=img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=5);
#sobely = cv2.Sobel(src=img, ddepth=cv2.CV_8U, dx=0, dy=1, ksize=5);
#sobely = cv2.Sobel(src=img, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=5);
sobely = cv2.Sobel(src=img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=5);
#sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5);
print "sobelx = %s" % str(sobelx);
print "sobely = %s" % str(sobely);
if False:
# Following example from http://answers.opencv.org/question/16422/matlab-gradient-to-c/ :
grad_x = cv2.Sobel(src=img, ddepth=cv2.CV_64F, dx=1, dy=0);
#cv2.convertScaleAbs(src=grad_x, dst=abs_grad_x) #, alpha[, beta ]]])
abs_grad_x = cv2.convertScaleAbs(src=grad_x); #, alpha[, beta ]]])
grad_y = cv2.Sobel(src=img, ddepth=cv2.CV_64F, dx=0, dy=1);
abs_grad_y = cv2.convertScaleAbs(src=grad_y); #, alpha[, beta ]]])
#cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype ]])
grad = cv2.addWeighted(src1=abs_grad_x, alpha=0.5, src2=abs_grad_y, beta=0.5, gamma=0.0);
print "grad = %s" % str(grad);
# Inspired heavily from the C++ code available at
# http://answers.opencv.org/question/16422/matlab-gradient-to-c/:
#/// Internal method to get numerical gradient for x components.
#/// @param[in] mat Specify input matrix.
#/// @param[in] spacing Specify input space.
def gradientX(mat, spacing):
grad = np.zeros( (mat.shape[0], mat.shape[1]), dtype=mat.dtype );
#const int maxCols = mat.cols;
#const int maxRows = mat.rows;
maxRows, maxCols = mat.shape;
#/* get gradients in each border */
#/* first col */
#Mat col = (-mat.col(0) + mat.col(1))/(float)spacing;
col = (-mat[:, 0] + mat[:, 1]) / float(spacing);
# Rect() is explained for example at http://docs.opencv.org/modules/core/doc/drawing_functions.html - basically we denote a rectange: col_ul, row_ul and then delta_col, delta_row
#col.copyTo(grad(Rect(0,0,1,maxRows)));
#grad[: maxRows, : 1] = col; # Gives exception: "ValueError: output operand requires a reduction, but reduction is not enabled"
grad[0: maxRows, 0: 1] = col.reshape( (col.size, 1) ); #.copy();
#/* last col */
#col = (-mat.col(maxCols-2) + mat.col(maxCols-1))/(float)spacing;
col = (-mat[:, maxCols - 2] + mat[:, maxCols - 1]) / float(spacing);
#col.copyTo(grad(Rect(maxCols-1,0,1,maxRows)));
#grad[0: maxRows, maxCols - 1: maxCols] = col; # Gives exception: "ValueError: output operand requires a reduction, but reduction is not enabled"
grad[0: maxRows, maxCols - 1: maxCols] = col.reshape( (col.size, 1) ); #.copy();
#/* centered elements */
#Mat centeredMat = mat(Rect(0,0,maxCols-2,maxRows));
centeredMat = mat[0: maxRows, 0: maxCols - 2];
#Mat offsetMat = mat(Rect(2,0,maxCols-2,maxRows));
offsetMat = mat[0:maxRows, 2: maxCols];
#Mat resultCenteredMat = (-centeredMat + offsetMat)/(((float)spacing)*2.0);
resultCenteredMat = (-centeredMat + offsetMat) / (float(spacing) * 2.0);
#resultCenteredMat.copyTo(grad(Rect(1,0,maxCols-2, maxRows)));
grad[0: maxRows, 1: maxCols - 1] = resultCenteredMat; #.copy();
return grad;
#/// Internal method to get numerical gradient for y components.
#/// @param[in] mat Specify input matrix.
#/// @param[in] spacing Specify input space.
def gradientY(mat, spacing):
#Mat grad = Mat::zeros(mat.cols,mat.rows,CV_32F);
grad = np.zeros( (mat.shape[0], mat.shape[1]), dtype=mat.dtype );
#const int maxCols = mat.cols;
#const int maxRows = mat.rows;
maxRows, maxCols = mat.shape;
#/* get gradients in each border */
#/* first row */
#Mat row = (-mat.row(0) + mat.row(1))/(float)spacing;
row = (-mat[0, :] + mat[1, :]) / float(spacing);
#row.copyTo(grad(Rect(0,0,maxCols,1)));
#grad[: maxCols, : 1] = row; # Gives exception: "ValueError: output operand requires a reduction, but reduction is not enabled"
grad[0: 1, 0: maxCols] = row.reshape( (1, row.size) ); #.copy();
#if False:
if common.MY_DEBUG_STDOUT:
common.DebugPrint("gradientY(): spacing = %s" % str(spacing));
common.DebugPrint("grad[0: 1, 0: maxCols].shape = %s" % str(grad[0: 1, 0: maxCols].shape));
common.DebugPrint("row.shape = %s" % str(row.shape));
common.DebugPrint("row = %s" % str(row));
#/* last row */
#row = (-mat.row(maxRows-2) + mat.row(maxRows-1))/(float)spacing;
row = (-mat[maxRows - 2, :] + mat[maxRows - 1, :]) / float(spacing);
#row.copyTo(grad(Rect(0,maxRows-1,maxCols,1)));
grad[maxRows - 1: maxRows, 0: maxCols] = row; #.copy();
#/* centered elements */
#Mat centeredMat = mat(Rect(0,0,maxCols,maxRows-2));
centeredMat = mat[0: maxRows - 2, 0: maxCols];
#Mat offsetMat = mat(Rect(0,2,maxCols,maxRows-2));
offsetMat = mat[2: maxRows, 0: maxCols];
#Mat resultCenteredMat = (-centeredMat + offsetMat)/(((float)spacing)*2.0);
resultCenteredMat = (-centeredMat + offsetMat) / (float(spacing) * 2.0);
#resultCenteredMat.copyTo(grad(Rect(0,1,maxCols, maxRows-2)));
grad[1: maxRows - 1, 0: maxCols] = resultCenteredMat; #.copy();
return grad;
def gradientZ(mat, indexZ, spacing, grad):
"""
Since we know we have a 3D array we work on planes (2d subelements),
not on 1D elements (rows and columns).
"""
if common.MY_DEBUG_STDOUT:
common.DebugPrint("Entered gradientZ(indexZ=%d)" % indexZ);
maxRows, maxCols, maxZs = mat.shape;
# get gradients in each border
# first Z plane
plane = (-mat[:, :, 0] + mat[:, :, 1]) / float(spacing);
#grad[0: maxRows, 0: maxCols, 0] = plane; #.reshape( (maxRows, maxCols) ); #plane.reshape( (mat.shape[0], mat.shape[1]) );
grad[:, :, 0] = plane;
#if False:
if common.MY_DEBUG_STDOUT:
common.DebugPrint("gradientY(): spacing = %s" % str(spacing));
common.DebugPrint("grad[0: 1, 0: maxCols].shape = %s" % str(grad[0: 1, 0: maxCols].shape));
common.DebugPrint("row.shape = %s" % str(row.shape));
common.DebugPrint("row = %s" % str(row));
# last Z plane
plane = (-mat[:, :, maxZs - 2] + mat[:, :, maxZs - 1]) / float(spacing);
#grad[0: maxRows, 0: maxCols, maxZs - 1] = plane;
grad[:, :, maxZs - 1] = plane;
# centered elements
centeredMat = mat[:, :, 0: maxZs - 2];
offsetMat = mat[:, :, 2: maxZs];
resultCenteredMat = (-centeredMat + offsetMat) / (float(spacing) * 2.0);
#grad[1: maxRows - 1, 0: maxCols] = resultCenteredMat;
grad[:, :, 1: maxZs - 1] = resultCenteredMat;
return grad;
if img.ndim == 3:
# The shape of the
gradX = np.zeros( (img.shape[0], img.shape[1], img.shape[2]), dtype=img.dtype );
gradY = np.zeros( (img.shape[0], img.shape[1], img.shape[2]), dtype=img.dtype );
gradZ = np.zeros( (img.shape[0], img.shape[1], img.shape[2]), dtype=img.dtype );
for i in range(img.shape[2]):
gradX1 = gradientX(img[:, :, i], spaceX);
gradX[:, :, i] = gradX1;
gradY1 = gradientY(img[:, :, i], spaceY);
gradY[:, :, i] = gradY1;
gradientZ(img, i, spaceZ, gradZ);
return (gradX, gradY, gradZ);
#Mat gradX = gradientX(img,spaceX);
gradX = gradientX(img, spaceX);
#common.DebugPrint("gradient(): returned from gradientX");
#Mat gradY = gradientY(img,spaceY);
gradY = gradientY(img, spaceY);
#pair<Mat,Mat> retValue(gradX,gradY);
#return retValue;
return (gradX, gradY);
def meshgrid(range1, range2):
"""
From http://www.mathworks.com/help/matlab/ref/meshgrid.html:
[X,Y] = meshgrid(xgv,ygv) replicates the grid vectors xgv and ygv
to produce a full grid.
This grid is represented by the output coordinate arrays X and Y.
The output coordinate arrays X and Y contain copies of the grid
vectors xgv and ygv respectively.
The sizes of the output arrays are determined by the length of
the grid vectors. For grid vectors xgv and ygv of length M and N
respectively, X and Y will have N rows and M columns.
Examples
2-D Grid From Vectors
Create a full grid from two monotonically increasing grid vectors:
[X,Y] = meshgrid(1:3,10:14)
X =
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
Y =
10 10 10
11 11 11
12 12 12
13 13 13
14 14 14
"""
#y, x = np.mgrid[range2, range1];
#x, y = np.meshgrid(range(1, 4), range(10, 15));
#assert len(range1) == len(range2);
x, y = np.meshgrid(range1, range2); #NOT working: copy=False);
return x, y;
def fspecial(type, p2, p3):
# See
# http://stackoverflow.com/questions/16278938/convert-matlab-to-opencv-in-python
# and http://blog.csdn.net/sunxin7557701/article/details/17163263
# and http://stackoverflow.com/questions/23471083/create-2d-log-kernel-in-opencv-like-fspecial-in-matlab
"""
% Alex: the code is taken from the Matlab, (type fspecial)
siz = (p2-1)/2;
std = p3;
% Alex: adapted this, since siz is scalar in our case
%[x,y] = meshgrid(-siz(2):siz(2),-siz(1):siz(1));
[x,y] = meshgrid(-siz:siz,-siz:siz);
arg = -(x.*x + y.*y)/(2*std*std);
h = exp(arg);
h(h<eps*max(h(:))) = 0;
sumh = sum(h(:));
if sumh ~= 0,
h = h/sumh;
end;
"""
assert (type == "gaussian") or (type == "ga");
siz = int((p2 - 1) / 2);
std = p3;
#% Alex: adapted this, since siz is scalar in our case
x, y = meshgrid(range(-siz, siz + 1), range(-siz, siz + 1));
arg = -(x * x + y * y) / (2.0 * std * std);
h = np.exp(arg);
h[h < eps() * h.max()] = 0;
sumh = h.sum();
#if sumh != 0:
if abs(sumh) > 1.e-6:
h = h / sumh;
return h;
def imfilter(A, H, options=None):
# We could raise an exception if somebody uses this function:
#assert False;
#return A;
"""
From http://nf.nci.org.au/facilities/software/Matlab/toolbox/images/imfilter.html
imfilter
Multidimensional image filtering
Syntax
B = imfilter(A,H)
B = imfilter(A,H,option1,option2,...)
Description
B = imfilter(A,H) filters the multidimensional array A with the multidimensional filter H.
The array, A, can be a nonsparse numeric array of any class and dimension.
The result, B, has the same size and class as A.
Each element of the output, B, is computed using double-precision floating point.
If A is an integer array, then output elements that exceed the range of
the integer type are truncated, and fractional values are rounded.
B = imfilter(A,H,option1,option2,...) performs multidimensional filtering
according to the specified options. Option arguments can have the
following values.
Boundary Options Option
Description
X
Input array values outside the bounds of the array are implicitly
assumed to have the value X. When no boundary option is specified,
imfilter uses X = 0.
'symmetric'
Input array values outside the bounds of the array are computed by
mirror-reflecting the array across the array border.
'replicate'
Input array values outside the bounds of the array are assumed to
equal the nearest array border value.
'circular'
Input array values outside the bounds of the array are computed by
implicitly assuming the input array is periodic.
Output Size Options Option
Description
'same'
The output array is the same size as the input array.
This is the default behavior when no output size options are specified.
'full'
The output array is the full filtered result, and so is larger than the input array.
"""
# From http://answers.opencv.org/question/8783/implement-imfiltermatlab-with-opencv/
"""
Point anchor( 0 ,0 );
double delta = 0;
float data[2][5] = {{11,11,11,11,11},{11,11,11,11,11}};
float kernel[2][2] = {{2,2},{2,2}};
Mat src = Mat(2, 5, CV_32FC1, &data);
Mat ker = Mat(2, 2, CV_32FC1, &kernel);
Mat dst = Mat(src.size(), src.type());
Ptr<FilterEngine> fe = createLinearFilter(src.type(), ker.type(), ker, anchor,
delta, BORDER_CONSTANT, BORDER_CONSTANT, Scalar(0));
fe->apply(src, dst);
cout << dst << endl;
"""
"""
See
https://stackoverflow.com/questions/18628373/imfilter-equivalent-in-opencv
http://answers.opencv.org/question/20785/replicate-with-mask-in-opencv/
<<The kernel is the "mask" that i want to move in the convolution and the "anchor" is the middle of this matrix. CvType.CV_32FC1 means that the values inside the result matrix could be also negative, and "BORDER_REPLICATE" just fill the edge with zeroes.>>
(not relevant: https://stackoverflow.com/questions/18628373/imfilter-equivalent-in-opencv )
"""
"""
# The Matlab code we try to emulate is:
bx = imfilter(gray_image,mask, 'replicate');
"""
"""
Point anchor(0, 0);
float delta = 0.0;
cv::filter2D(gray_img, bx, CV_32FC1, mask, anchor, delta, BORDER_REPLICATE);
"""
# Note: CvPoint is (x, y)
"""
From http://docs.opencv.org/modules/imgproc/doc/filtering.html#filter2d :
Convolves an image with the kernel.
Parameters:
kernel - convolution kernel (or rather a correlation kernel),
a single-channel floating point matrix;
if you want to apply different kernels to different channels,
split the image into separate color planes using split() and
process them individually.
anchor - anchor of the kernel that indicates the relative position of
a filtered point within the kernel;
the anchor should lie within the kernel;
default value (-1,-1) means that the anchor is at the kernel
center.
delta - optional value added to the filtered pixels before storing
them in dst.
borderType - pixel extrapolation method
(see borderInterpolate() for details).
"""
res = cv2.filter2D(src=A, ddepth=-1, kernel=H, anchor=(-1, -1), \
borderType=cv2.BORDER_REPLICATE); #BORDER_ISOLATED); #BORDER_DEFAULT) #BORDER_CONSTANT) #cv2.BORDER_TRANSPARENT)
return res;
def bwlabel_and_find(BW):
# NOTE: this is a similar, but not identical implementation
assert False; #!!!!TODO: not implemented
"""
From http://www.mathworks.com/help/images/ref/bwlabel.html
Label connected components in 2-D binary image
L = bwlabel(BW, n)
[L, num] = bwlabel(BW, n)
Description
L = bwlabel(BW, n) returns a matrix L, of the same size as BW, containing labels for the connected objects in BW. The variable n can have a value of either 4 or 8, where 4 specifies 4-connected objects and 8 specifies 8-connected objects. If the argument is omitted, it defaults to 8.
The elements of L are integer values greater than or equal to 0. The pixels labeled 0 are the background. The pixels labeled 1 make up one object; the pixels labeled 2 make up a second object; and so on.
[L, num] = bwlabel(BW, n) returns in num the number of connected objects found in BW.
The functions bwlabel, bwlabeln, and bwconncomp all compute connected components for binary images. bwconncomp replaces the use of bwlabel and bwlabeln. It uses significantly less memory and is sometimes faster than the other functions.
Create a small binary image to use for this example.
BW = logical ([1 1 1 0 0 0 0 0
1 1 1 0 1 1 0 0
1 1 1 0 1 1 0 0
1 1 1 0 0 0 1 0
1 1 1 0 0 0 1 0
1 1 1 0 0 0 1 0
1 1 1 0 0 1 1 0
1 1 1 0 0 0 0 0]);
Create the label matrix using 4-connected objects.
L = bwlabel(BW,4)
L =
1 1 1 0 0 0 0 0
1 1 1 0 2 2 0 0
1 1 1 0 2 2 0 0
1 1 1 0 0 0 3 0
1 1 1 0 0 0 3 0
1 1 1 0 0 0 3 0
1 1 1 0 0 3 3 0
1 1 1 0 0 0 0 0
Use the find command to get the row and column coordinates of the object labeled "2".
[r, c] = find(L==2);
rc = [r c]
rc =
2 5
3 5
2 6
3 6
"""
"""
From http://stackoverflow.com/questions/20357337/opencv-alternative-for-matlabs-bwlabel
This isn't exactly the same as bwlabel, but may be close enough.
One possible alternative is to use findContours and/or drawContours, as explained in the docs.
"""
# From http://stackoverflow.com/questions/12688524/connected-components-in-opencv
pass;
class TestSuite(unittest.TestCase):
def testUnique1(self):
l = [[1, 2], [1, 3], [1, 2]];
l = np.array(l);
lF, liF = unique(l);
#common.DebugPrint("lF = %s" % str(lF));
#common.DebugPrint("liF = %s" % str(liF));
res = np.array([[1, 2], [1, 3]]);
aZero = res - lF;
resi = np.array([0, 1]);
aZeroi = resi - liF;
# State our expectation
#self.assertTrue(lF == res);
self.assertTrue( (aZero == 0).all() and \
(aZeroi == 0).all())
def testUnique2(self):
l = [[1, 2], [1, 2]];
l = np.array(l);
lF, liF = unique(l);
#common.DebugPrint("lF = %s" % str(lF));
#common.DebugPrint("liF = %s" % str(liF));
res = np.array([[1, 2]]);
aZero = res - lF;
resi = np.array([0]);
aZeroi = resi - liF;
# State our expectation
#self.assertTrue(lF == res);
self.assertTrue( (aZero == 0).all() and \
(aZeroi == 0).all())
def testUnique3(self):
l = [[1, 3], [1, 2], [0, 7], [5, 9], [1, 2], [100, 0], [5, 10]];
l = np.array(l);
lF, liF = unique(l);
#common.DebugPrint("lF = %s" % str(lF));
#common.DebugPrint("liF = %s" % str(liF));
res = np.array([[[0, 7], [1, 2], [1, 3], [5, 9], [5, 10], [100, 0]]]);
aZero = res - lF;
resi = np.array([2, 1, 0, 3, 6, 5]);
aZeroi = resi - liF;
# State our expectation
#self.assertTrue(lF == res);
self.assertTrue( (aZero == 0).all() and \
(aZeroi == 0).all())
#################################################
def testHamming(self):
# Test 1
#print "hamming(11) = %s" % str(hamming(11))
h11 = hamming(11);
#h11 = [ 0.08 0.16785218 0.39785218 0.68214782 0.91214782 1.
# 0.91214782 0.68214782 0.39785218 0.16785218 0.08 ]
h11Good = np.array([0.0800, 0.1679, 0.3979, 0.6821, 0.9121, 1.0000, \
0.9121, 0.6821, 0.3979, 0.1679, 0.0800]);
aZero = h11 - h11Good;
#print "h11 = %s" % str(h11);
#print "aZero = %s" % str(aZero);
#assert (aZero < 1.0e-3).all();
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
h0 = hamming(0);
#print "h0 = %s" % str(h0);
self.assertTrue(h0.size == 0);
h1 = hamming(1);
#print "h1 = %s" % str(h1);
h1Good = np.array([1.0]);
aZero = h1 - h1Good;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
h2 = hamming(2);
#print "h2 = %s" % str(h2);
h2Good = np.array([0.08, 0.08]);
aZero = h2 - h2Good;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
h100 = hamming(100);
#print "h100 = %s" % str(h100);
h100Good = np.array([ \
0.0800, 0.0809, 0.0837, 0.0883, 0.0947, 0.1030, 0.1130, 0.1247, \
0.1380, 0.1530, 0.1696, 0.1876, 0.2071, 0.2279, 0.2499, 0.2732, \
0.2975, 0.3228, 0.3489, 0.3758, 0.4034, 0.4316, 0.4601, 0.4890, \
0.5181, 0.5473, 0.5765, 0.6055, 0.6342, 0.6626, 0.6905, 0.7177, \
0.7443, 0.7700, 0.7948, 0.8186, 0.8412, 0.8627, 0.8828, 0.9016, \
0.9189, 0.9347, 0.9489, 0.9614, 0.9723, 0.9814, 0.9887, 0.9942, \
0.9979, 0.9998, 0.9998, 0.9979, 0.9942, 0.9887, 0.9814, 0.9723, \
0.9614, 0.9489, 0.9347, 0.9189, 0.9016, 0.8828, 0.8627, 0.8412, \
0.8186, 0.7948, 0.7700, 0.7443, 0.7177, 0.6905, 0.6626, 0.6342, \
0.6055, 0.5765, 0.5473, 0.5181, 0.4890, 0.4601, 0.4316, 0.4034, \
0.3758, 0.3489, 0.3228, 0.2975, 0.2732, 0.2499, 0.2279, 0.2071, \
0.1876, 0.1696, 0.1530, 0.1380, 0.1247, 0.1130, 0.1030, 0.0947, \
0.0883, 0.0837, 0.0809, 0.0800]);
aZero = h100 - h100Good;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
def testHammingOld(self):
# Test 1
#print "hamming(11) = %s" % str(hamming(11))
h11 = hamming(11);
#h11 = [ 0.08 0.16785218 0.39785218 0.68214782 0.91214782 1.
# 0.91214782 0.68214782 0.39785218 0.16785218 0.08 ]
h11Good = np.array([0.0800, 0.1679, 0.3979, 0.6821, 0.9121, 1.0000, \
0.9121, 0.6821, 0.3979, 0.1679, 0.0800]);
aZero = h11 - h11Good;
#print "h11 = %s" % str(h11);
#print "aZero = %s" % str(aZero);
#assert (aZero < 1.0e-3).all();
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
def testFilter2(self):
#window = hamming(11)
window = np.array( [1, 2, 4] );
x = np.ones( (23, 8) );
res = filter2(window, x);
#print "filter2(window, x) = %s" % str(res);
resGood = [[6, 7, 7, 7, 7, 7, 7, 3]] * 23;
resGood = np.array(resGood);
aZero = res - resGood;
#assert (aZero == 0).all();
self.assertTrue((aZero == 0).all());
def testHist(self):
print "Entered testHist()."
howMany = [56, 38, 54, 28, 32, 40, 38, 32, 54, 62, 46, 42]
RD_start = 2001
RD_end = 2012
l = []
#for i in range(rd_start, rd_end + 1):
for i in range(RD_end - RD_start + 1):
l += [RD_start + i] * howMany[i]
#common.DebugPrint("l = %s" % str(l))
assert len(l) == 522
l = np.array(l)
rr = np.array(range(RD_start, RD_end + 1))
n_d = [56, 38, 54, 28, 32, 40, 38, 32, 54, 62, 46, 42]
# Test 1
#print "hamming(11) = %s" % str(hamming(11))
res = hist(l, rr);
aZero = res - n_d
#print "h11 = %s" % str(h11)
#print "aZero = %s" % str(aZero)
if False:
assert (aZero == 0).all()
# State our expectation
self.assertTrue((aZero == 0).all())
def testGradient(self):
# Testing bidimensional gradient:
"""
From http://answers.opencv.org/question/16422/matlab-gradient-to-c/
A =
1 3
4 2
[dx dy] = gradient(A, 4, 4)
Output:
dx =
0.5000 0.5000
-0.5000 -0.5000
dy =
0.7500 -0.2500
0.7500 -0.2500
"""
A = np.array([ \
[1.0, 3.0],
[4.0, 2.0]]);
dx, dy = gradient(A, 4, 4);
dxGood = np.array([ \
[0.5000, 0.5000],
[-0.5000, -0.5000]]);
dyGood = np.array([ \
[0.7500, -0.2500],
[0.7500, -0.2500]]);
aZero = dx - dxGood;
#common.DebugPrint("testGradient(): dx = %s" % str(dx));
#common.DebugPrint("testGradient(): aZero = %s" % str(aZero));
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
aZero = dy - dyGood;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
#common.DebugPrint("For A = %s we have the following gradients:" % str(A));
#common.DebugPrint("dx = %s" % str(dx));
#common.DebugPrint("dy = %s" % str(dy));
dx, dy = gradient(A, 1, 1);
"""
The Matlab results are:
dx =
2 2
-2 -2
dy =
3 -1
3 -1
"""
dxGood = np.array([ \
[2, 2],
[-2, -2]]);
dyGood = np.array([ \
[3, -1],
[3, -1]]);
aZero = dx - dxGood;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
aZero = dy - dyGood;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
A = np.array([ \
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]]);
dx, dy = gradient(A, 4, 4);
"""
The Matlab results are:
dx =
0.2500 0.2500 0.2500
0.2500 0.2500 0.2500
0.2500 0.2500 0.2500
dy =
0.7500 0.7500 0.7500
0.7500 0.7500 0.7500
0.7500 0.7500 0.7500
"""
dxGood = np.array([ \
[0.2500, 0.2500, 0.2500],
[0.2500, 0.2500, 0.2500],
[0.2500, 0.2500, 0.2500]]);
dyGood = np.array([ \
[0.7500, 0.7500, 0.7500],
[0.7500, 0.7500, 0.7500],
[0.7500, 0.7500, 0.7500]]);
aZero = dx - dxGood;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
aZero = dy - dyGood;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
#common.DebugPrint("For A = %s we have the following gradients:" % str(A));
#common.DebugPrint("dx = %s" % str(dx));
#common.DebugPrint("dy = %s" % str(dy));
# Testing threedimensional gradient (for subframe sequences):
A3d = np.zeros( (3, 3, 4) );
for i in range(A3d.shape[2]):
A3d[:, :, i] = A + (i + 1) * np.eye(A3d.shape[0]);
#dx, dy, dz = gradient(A3d, 4, 4, 4);
dx, dy, dz = gradient(A3d, 1, 1, 1);
common.DebugPrint("For A3d = %s we have the following gradients:" % Repr3DMatrix(A3d)); #str(A3d));
#common.DebugPrint("dx = %s" % str(dx));
common.DebugPrint("dx = %s" % Repr3DMatrix(dx));
#common.DebugPrint("dy = %s" % str(dy));
common.DebugPrint("dy = %s" % Repr3DMatrix(dy));
#common.DebugPrint("dz = %s" % str(dz));
common.DebugPrint("dz = %s" % Repr3DMatrix(dz));
"""
The following Matlab program:
A1 = [1 2 3; 4 5 6; 7 8 9];
%A = zeros(3,3,3);
%A(:,:,1) = A1;
%A(:,:,2) = A1;
%A(:,:,3) = A1;
%[vx, vy, vt] = gradient(A);
A = zeros(3,3,4);
A(:,:,1) = A1 + 1*eye(3);
A(:,:,2) = A1 + 2*eye(3);
A(:,:,3) = A1 + 3*eye(3);
A(:,:,4) = A1 + 4*eye(3);
Trial>> [vx, vy, vt] = gradient(A)
vx(:,:,1) =
0 0.5000 1.0000
2.0000 1.0000 0
1.0000 1.5000 2.0000
vx(:,:,2) =
-1 0 1
3 1 -1
1 2 3
vx(:,:,3) =
-2.0000 -0.5000 1.0000
4.0000 1.0000 -2.0000
1.0000 2.5000 4.0000
vx(:,:,4) =
-3 -1 1
5 1 -3
1 3 5
vy(:,:,1) =
2.0000 4.0000 3.0000
2.5000 3.0000 3.5000
3.0000 2.0000 4.0000
vy(:,:,2) =
1 5 3
2 3 4
3 1 5
vy(:,:,3) =
0 6.0000 3.0000
1.5000 3.0000 4.5000
3.0000 0 6.0000
vy(:,:,4) =
-1 7 3
1 3 5
3 -1 7
vt(:,:,1) =
1 0 0
0 1 0
0 0 1
vt(:,:,2) =
1 0 0
0 1 0
0 0 1
vt(:,:,3) =
1 0 0
0 1 0
0 0 1
vt(:,:,4) =
1 0 0
0 1 0
0 0 1
"""
def testMeshgrid(self):
"""
From ...
[X,Y] = meshgrid(1:3,10:14)
X =
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
Y =
10 10 10
11 11 11
12 12 12
13 13 13
14 14 14
"""
resX, resY = meshgrid( range(1, 3 + 1) , range(10, 14 + 1));
goodX = np.array( [ \
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]);
goodY = np.array( [ \
[10, 10, 10],
[11, 11, 11],
[12, 12, 12],
[13, 13, 13],
[14, 14, 14]]);
aZero = resX - goodX;
self.assertTrue((aZero == 0).all());
aZero = resY - goodY;
self.assertTrue((aZero == 0).all());
def testFspecial(self):
# Tests are generated first with Matlab
si = 2.4;
#%p2 = max(1,fix(6*si)+1);
p2 = 15.0;
p3 = si;
res = fspecial("gaussian", p2, p3);
common.DebugPrint("testFspecial(): res.shape = %s" % str(res.shape));
common.DebugPrint("testFspecial(): res = %s" % str(res));
#Result from Matlab:
resGood = np.array([ \
[0.0000, 0.0000, 0.0000, 0.0001, 0.0002, 0.0003, 0.0004, 0.0004,
0.0004, 0.0003, 0.0002, 0.0001, 0.0000, 0.0000, 0.0000],
[0.0000, 0.0001, 0.0001, 0.0003, 0.0006, 0.0009, 0.0011, 0.0012,
0.0011, 0.0009, 0.0006, 0.0003, 0.0001, 0.0001, 0.0000],
[0.0000, 0.0001, 0.0004, 0.0008, 0.0014, 0.0022, 0.0029, 0.0032,
0.0029, 0.0022, 0.0014, 0.0008, 0.0004, 0.0001, 0.0000],
[0.0001, 0.0003, 0.0008, 0.0017, 0.0032, 0.0049, 0.0063, 0.0069,
0.0063, 0.0049, 0.0032, 0.0017, 0.0008, 0.0003, 0.0001],
[0.0002, 0.0006, 0.0014, 0.0032, 0.0058, 0.0090, 0.0116, 0.0127,
0.0116, 0.0090, 0.0058, 0.0032, 0.0014, 0.0006, 0.0002],
[0.0003, 0.0009, 0.0022, 0.0049, 0.0090, 0.0138, 0.0180, 0.0196,
0.0180, 0.0138, 0.0090, 0.0049, 0.0022, 0.0009, 0.0003],
[0.0004, 0.0011, 0.0029, 0.0063, 0.0116, 0.0180, 0.0233, 0.0254,
0.0233, 0.0180, 0.0116, 0.0063, 0.0029, 0.0011, 0.0004],
[0.0004, 0.0012, 0.0032, 0.0069, 0.0127, 0.0196, 0.0254, 0.0277,
0.0254, 0.0196, 0.0127, 0.0069, 0.0032, 0.0012, 0.0004],
[0.0004, 0.0011, 0.0029, 0.0063, 0.0116, 0.0180, 0.0233, 0.0254,
0.0233, 0.0180, 0.0116, 0.0063, 0.0029, 0.0011, 0.0004],
[0.0003, 0.0009, 0.0022, 0.0049, 0.0090, 0.0138, 0.0180, 0.0196,
0.0180, 0.0138, 0.0090, 0.0049, 0.0022, 0.0009, 0.0003],
[0.0002, 0.0006, 0.0014, 0.0032, 0.0058, 0.0090, 0.0116, 0.0127,
0.0116, 0.0090, 0.0058, 0.0032, 0.0014, 0.0006, 0.0002],
[0.0001, 0.0003, 0.0008, 0.0017, 0.0032, 0.0049, 0.0063, 0.0069,
0.0063, 0.0049, 0.0032, 0.0017, 0.0008, 0.0003, 0.0001],
[0.0000, 0.0001, 0.0004, 0.0008, 0.0014, 0.0022, 0.0029, 0.0032,
0.0029, 0.0022, 0.0014, 0.0008, 0.0004, 0.0001, 0.0000],
[0.0000, 0.0001, 0.0001, 0.0003, 0.0006, 0.0009, 0.0011, 0.0012,
0.0011, 0.0009, 0.0006, 0.0003, 0.0001, 0.0001, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0001, 0.0002, 0.0003, 0.0004, 0.0004,
0.0004, 0.0003, 0.0002, 0.0001, 0.0000, 0.0000, 0.0000]]);
aZero = np.abs(res - resGood);
common.DebugPrint("aZero = %s" % str(aZero));
self.assertTrue((aZero < 1e-4).all());
def testImfilter(self):
# Not tested, since not implemented
"""
A = np.array([ \
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]]);
res = imfilter(A, np.array([6])); #imfilter(A, 6, 1);
#common.DebugPrint("res from imfilter() = %s" % str(res));
# This is the result from Matlab
resGood = np.array([ \
[11, 12, 11],
[11, 12, 11],
[11, 12, 11]]);
"""
"""
To test well imfilter use a filter, as given in ecc_homo_spacetime.imgaussian():
H = np.exp(-(x ** 2 / (2.0 * pow(sigma, 2))));
H = H / H[:].sum();
Hx = H.reshape( (H.size, 1) );
res = imfilter(I, Hx, "same", "replicate");
"""
A = np.array( [ \
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]);
res = imfilter(np.ones((4, 4)), A, 'replicate');
resGood = 45 * np.ones((4, 4));
aZero = np.abs(res - resGood);
#common.DebugPrint("aZero = %s" % str(aZero));
self.assertTrue((aZero < 1e-4).all());
B = np.array( [ \
[1, 2],
[3, 4]]);
res = imfilter(np.ones((4, 4)), B, 'replicate');
#common.DebugPrint("testImfilter(): res = %s" % str(res));
resGood = np.array([ \
[10, 10, 10, 10],
[10, 10, 10, 10],
[10, 10, 10, 10],
[10, 10, 10, 10]]);
aZero = np.abs(res - resGood);
#common.DebugPrint("aZero = %s" % str(aZero));
self.assertTrue((aZero < 1e-4).all());
C = np.array( [ \
[1, 2],
[2, 1]]);
res = imfilter(np.ones((5, 5)), C, 'replicate');
#common.DebugPrint("testImfilter(): res = %s" % str(res));
resGood = np.array([ \
[6, 6, 6, 6, 6],
[6, 6, 6, 6, 6],
[6, 6, 6, 6, 6],
[6, 6, 6, 6, 6],
[6, 6, 6, 6, 6]]);
aZero = np.abs(res - resGood);
#common.DebugPrint("aZero = %s" % str(aZero));
self.assertTrue((aZero < 1e-4).all());
def testInterp2(self):
"""
V = np.array( [ \
[ 2, 8, 6],
[ 8, 10, 12],
[14, 16, 18]]);
"""
if False:
V = np.array( [ \
[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]]);
V = np.array( [ \
[ 1, 5, 3],
[ 4, 7, 6],
[ 7, 10, 9]]);
V = V.astype(np.float64);
#if False:
if True:
# Testing out of bound
Xq = np.array( [ \
[ 1.7, 2.7, 3.7],
[ 1.4, 2.5, 3],
[ 1, 2, 3]]);
else:
# Testing element coordinates not "in its square" - elem [0,2]
Xq = np.array( [ \
[ 1.7, 2.7, 2.9],
[ 1.4, 2.5, 3],
[ 1, 2, 3]]);
Yq = np.array( [ \
[ 1.3, 1, 1],
[ 2, 2, 2],
[ 3, 3, 3]]);
Xq -= 1; # In Python we start from index 0
Yq -= 1; # In Python we start from index 0
itype = "linear";
# interp2_nested_loops() is deemed to be correct
Xq = Xq.astype(np.float64);
Yq = Yq.astype(np.float64);
#res = interp2_nested_loops(V, Xq, Yq, itype);
res = interp2(V, Xq, Yq, itype);
#if False:
if True:
if False:
# For the (nonfunctioning) implementation with cv.remap()
common.DebugPrint("interp2() returned %s" % str(ConvertCvMatToNPArray(res)));
else:
common.DebugPrint("interp2() returned %s" % str(res));
goodRes = np.array( [ \
[ 4.49, 3.6, np.nan],
[ 5.2 , 6.5, 6. ],
[ 7. , 10., 9. ]]);
"""
#common.DebugPrint("interp2() returned %s" % str(dir(res)));
for r in range(res.rows):
for c in range(res.cols):
# NOT GOOD: common.DebugPrint("%.5f " % res[r][c][0]),
#common.DebugPrint("%.5f " % res.__getitem__((r, c))),
common.DebugPrint("%.5f " % res[r, c]),
pass
print
#common.DebugPrint("interp2() returned %s" % str(res.tostring())); # Prints binary data...
"""
aZero = res - goodRes;
#common.DebugPrint("interp2() returned %s" % str(aZero));
self.assertTrue(np.isnan(res[0, 2]) and np.isnan(goodRes[0, 2]));
aZero[0, 2] = 0.0;
self.assertTrue((np.abs(aZero) < 1.e-5).all());
res = interp2(V, Xq, Yq, itype);
"""
This is one (~small) test that my BAD vectorized interp2()
implementation failed.
"""
V = np.array([ \
[ 138., 131., 123., 118., 121., 130., 142., 150., 142., 142.],
[ 109., 75., 43., 45., 80., 115., 128., 126., 142., 142.],
[ 136., 142., 146., 146., 142., 139., 142., 145., 142., 142.],
[ 130., 135., 140., 143., 142., 140., 140., 140., 142., 142.],
[ 133., 124., 117., 122., 136., 147., 150., 147., 142., 142.],
[ 130., 144., 157., 154., 142., 132., 132., 138., 142., 142.],
[ 137., 143., 147., 143., 135., 132., 138., 146., 142., 142.],
[ 142., 144., 144., 137., 130., 131., 140., 150., 142., 142.],
[ 143., 143., 143., 143., 143., 143., 143., 143., 143., 143.],
[ 143., 143., 143., 143., 143., 143., 143., 143., 143., 143.]]);
Xq = np.array([ \
[ 0.6977, 1.6883, 2.679, 3.6698, 4.6606, 5.6515, 6.6424, 7.6334, 8.6245, 9.6156],
[ 0.6951, 1.6857, 2.6764, 3.6672, 4.658, 5.6488, 6.6398, 7.6308, 8.6218, 9.6129],
[ 0.6925, 1.6831, 2.6738, 3.6645, 4.6553, 5.6462, 6.6371, 7.6281, 8.6191, 9.6102],
[ 0.6899, 1.6805, 2.6712, 3.6619, 4.6527, 5.6436, 6.6345, 7.6254, 8.6165, 9.6076],
[ 0.6872, 1.6779, 2.6685, 3.6593, 4.6501, 5.6409, 6.6318, 7.6228, 8.6138, 9.6049],
[ 0.6846, 1.6752, 2.6659, 3.6566, 4.6474, 5.6383, 6.6292, 7.6201, 8.6111, 9.6022],
[ 0.682, 1.6726, 2.6633, 3.654, 4.6448, 5.6356, 6.6265, 7.6175, 8.6085, 9.5995],
[ 0.6794, 1.67, 2.6607, 3.6514, 4.6422, 5.633, 6.6239, 7.6148, 8.6058, 9.5969],
[ 0.6768, 1.6674, 2.6581, 3.6488, 4.6395, 5.6303, 6.6212, 7.6121, 8.6031, 9.5942],
[ 0.6742, 1.6648, 2.6554, 3.6461, 4.6369, 5.6277, 6.6186, 7.6095, 8.6005, 9.5915]]);
Yq = np.array([ \
[ 0.0144, 0.0115, 0.0086, 0.0057, 0.0027,-0.0002,-0.0031,-0.006, -0.0089,-0.0119],
[ 1.0134, 1.0105, 1.0076, 1.0048, 1.0019, 0.999, 0.9961, 0.9932, 0.9903, 0.9874],
[ 2.0124, 2.0096, 2.0067, 2.0038, 2.001, 1.9981, 1.9953, 1.9924, 1.9895, 1.9867],
[ 3.0114, 3.0086, 3.0057, 3.0029, 3.0001, 2.9972, 2.9944, 2.9916, 2.9888, 2.9859],
[ 4.0104, 4.0076, 4.0048, 4.002, 3.9992, 3.9964, 3.9936, 3.9908, 3.988, 3.9852],
[ 5.0093, 5.0065, 5.0038, 5.001, 4.9982, 4.9955, 4.9927, 4.9899, 4.9871, 4.9844],
[ 6.0082, 6.0055, 6.0028, 6., 5.9973, 5.9945, 5.9918, 5.9891, 5.9863, 5.9836],
[ 7.0072, 7.0045, 7.0017, 6.999, 6.9963, 6.9936, 6.9909, 6.9882, 6.9855, 6.9827],
[ 8.0061, 8.0034, 8.0007, 7.998, 7.9953, 7.9927, 7.99, 7.9873, 7.9846, 7.9819],
[ 9.005, 9.0023, 8.9997, 8.997, 8.9943, 8.9917, 8.989, 8.9864, 8.9837, 8.9811]]);
if False:
# Measuring the performance of interp2().
t1 = float(cv2.getTickCount());
for i in range(10000):
interp2(V, Xq, Yq, itype);
t2 = float(cv2.getTickCount());
myTime = (t2 - t1) / cv2.getTickFrequency();
common.DebugPrint("testInterp2(): interp2() " \
"took %.6f [sec]" % myTime);
# IMPORTANT test
if True:
#V1 = np.empty();
V = imresize(V, scale=100);
Xq = imresize(Xq, scale=100);
Yq = imresize(Yq, scale=100);
res = interp2(V, Xq, Yq, itype);
#common.DebugPrint("interp2() returned %s" % str(res));
resGood = interp2_vectorized(V, Xq, Yq, itype);
#common.DebugPrint("interp2_vectorized() returned %s" % str(res));
self.assertTrue(CompareMatricesWithNanElements(res, resGood));
if False: # These are just performance tests (compare times of running unit-tests)
V = np.zeros( (1920, 1080) );
Xq = np.zeros( (1920, 1080) );
Yq = np.zeros( (1920, 1080) );
res = interp2(V, Xq, Yq, itype);
res = interp2(V, Xq, Yq, itype);
res = interp2_vectorized(V, Xq, Yq, itype);
res = interp2_vectorized(V, Xq, Yq, itype);
def testKron(self):
# Taken from the Matlab help:
A = np.eye(4);
B = np.array([[1, -1], [-1, 1]]);
res = kron(A, B);
resGood = np.array( [ \
[ 1, -1, 0, 0, 0, 0, 0, 0],
[-1, 1, 0, 0, 0, 0, 0, 0],
[ 0, 0, 1, -1, 0, 0, 0, 0],
[ 0, 0, -1, 1, 0, 0, 0, 0],
[ 0, 0, 0, 0, 1, -1, 0, 0],
[ 0, 0, 0, 0, -1, 1, 0, 0],
[ 0, 0, 0, 0, 0, 0, 1, -1],
[ 0, 0, 0, 0, 0, 0, -1, 1]]);
aZero = res - resGood;
self.assertTrue((aZero == 0).all());
A = np.array( [[1, 2, 3], [4, 5, 6]] );
#A = np.r_[np.array([1, 2, 3]), np.array([4, 5, 6])];
#A = np.ravel(A);
B = np.ones( (2, 2) );
#common.DebugPrint("testKron(): B = %s[END]" % str(B));
#common.DebugPrint("testKron(): B.shape = %s[END]" % str(B.shape));
res = np.kron(A, B);
resGood = np.array( [ \
[1, 1, 2, 2, 3, 3],
[1, 1, 2, 2, 3, 3],
[4, 4, 5, 5, 6, 6],
[4, 4, 5, 5, 6, 6]] );
#common.DebugPrint("testKron(): A = %s" % str(A));
#common.DebugPrint("testKron(): res = %s" % str(res));
aZero = res - resGood;
self.assertTrue((aZero == 0).all());
def testSub2ind(self):
# Taken from the Matlab help of sub2ind
A = np.empty((3, 4, 2));
r = np.array([3, 2, 3, 1, 2]);
c = np.array([3, 4, 1, 3, 4]);
d3 = np.array([2, 1, 2, 2, 1]);
r -= 1;
c -= 1;
d3 -= 1;
res = sub2ind(matrixSize=A.shape, rowSub=r, colSub=c, dim3Sub=d3);
# Taken from the Matlab help of sub2ind
resGood = np.array([21, 11, 15, 19, 11]);
resGood -= 1;
#common.DebugPrint("testSub2ind(): res = %s" % str(res));
aZero = res - resGood;
self.assertTrue((aZero == 0).all());
def testOrdfilt2(self):
A = np.array([ \
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]]);
A = A.astype(np.float64);
#res = ordfilt2_4_nested_loops(A, 9, np.ones((3, 3)));
res = ordfilt2(A, 9, np.ones((3, 3)));
common.DebugPrint("testOrdfilt2(): res = %s" % str(res));
resGood = np.array([ \
[ 6, 7, 8, 8],
[10, 11, 12, 12],
[14, 15, 16, 16],
[14, 15, 16, 16]]);
aZero = res - resGood;
#self.assertTrue(np.abs(aZero == 0).all());
self.assertTrue(np.abs(aZero < 1.0e-4).all());
"""
>> A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
>> ordfilt2(A, 0, ones(3))
ans =
1.0e-307 *
0.4450 0.4450 0.4450 0.4450
0.4450 0.4450 0.4450 0.4450
0.4450 0.4450 0.4450 0.4450
0.4450 0.4450 0.4450 0.4450
>> ordfilt2(A, 1, ones(3))
ans =
0 0 0 0
0 1 2 0
0 5 6 0
0 0 0 0
>> ordfilt2(A, 2, ones(3))
ans =
0 0 0 0
0 2 3 0
0 6 7 0
0 0 0 0
>> ordfilt2(A, 3, ones(3))
ans =
0 0 0 0
0 3 4 0
0 7 8 0
0 0 0 0
>> ordfilt2(A, 4, ones(3))
ans =
0 1 2 0
1 5 6 3
5 9 10 7
0 9 10 0
>> ordfilt2(A, 5, ones(3))
ans =
0 2 3 0
2 6 7 4
6 10 11 8
0 10 11 0
>> ordfilt2(A, 6, ones(3))
ans =
1 3 4 3
5 7 8 7
9 11 12 11
9 11 12 11
>> ordfilt2(A, 7, ones(3))
ans =
2 5 6 4
6 9 10 8
10 13 14 12
10 13 14 12
>> ordfilt2(A, 8, ones(3))
ans =
5 6 7 7
9 10 11 11
13 14 15 15
13 14 15 15
>> ordfilt2(A, 9, ones(3))
ans =
6 7 8 8
10 11 12 12
14 15 16 16
14 15 16 16
>> ordfilt2(A, 10, ones(3))
ans =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
"""
if __name__ == '__main__':
# See http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html
np.set_printoptions(precision=4, suppress=True, \
threshold=1000000, linewidth=5000);
unittest.main();
| 36.327229 | 292 | 0.511732 |
import cv2
import math
import numpy as np
from numpy import linalg as npla
import sys
import scipy.interpolate
import scipy.sparse
import weave
import unittest
import common
import config
def CompareMatricesWithNanElements(M1, M2):
assert M1.shape == M2.shape;
assert M1.ndim == 2;
for r in range(M1.shape[0]):
for c in range(M2.shape[0]):
if np.isnan(M1[r, c]):
if not np.isnan(M2[r, c]):
return False;
else:
if M1[r, c] != M2[r, c]:
return False;
return True;
def ConvertCvMatToNPArray(cvmat):
m = [];
for r in range(cvmat.rows):
mR = [cvmat[r, c] for c in range(cvmat.cols)];
m.append(mR);
return np.array(m);
def Repr3DMatrix(m):
assert m.ndim == 3;
res = "";
for i in range(m.shape[2]):
res += ("\n[:, :, %d] = " % i) + str(m[:, :, i]);
return res;
"""
From http://www.mathworks.com/help/matlab/matlab_prog/symbol-reference.html:
Dot-Dot-Dot (Ellipsis) - ...
A series of three consecutive periods (...) is the line continuation operator in MATLAB.
Line Continuation
Continue any MATLAB command or expression by placing an ellipsis at the end of the line to be continued:
"""
def fix(x):
"""
From http://www.mathworks.com/help/matlab/ref/fix.html
fix
Round toward zero
Syntax:
B = fix(A)
Description:
B = fix(A) rounds the elements of A toward zero,
resulting in an array of integers.
For complex A, the imaginary and real parts are
rounded independently.
Examples:
a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i]
a =
Columns 1 through 4
-1.9000 -0.2000 3.4000 5.6000
Columns 5 through 6
7.0000 2.4000 + 3.6000i
fix(a)
ans =
Columns 1 through 4
-1.0000 0 3.0000 5.0000
Columns 5 through 6
7.0000 2.0000 + 3.0000i
"""
if x < 0:
return math.ceil(x);
else:
return math.floor(x);
def eps(val=1.0):
"""
Following http://wiki.scipy.org/NumPy_for_Matlab_Users,
eps is equivalent to spacing(1).
Note: Matlab's double precision is numpy's float64.
"""
"""
From NumPy help (see also
http://docs.scipy.org/doc/numpy/reference/generated/numpy.finfo.html)
>>> np.info(np.spacing)
spacing(x[, out])
Return the distance between x and the nearest adjacent number.
Parameters
----------
x1: array_like
Values to find the spacing of.
Returns
-------
out : array_like
The spacing of values of `x1`.
Notes
-----
It can be considered as a generalization of EPS:
``spacing(np.float64(1)) == np.finfo(np.float64).eps``, and there
should not be any representable number between ``x + spacing(x)`` and
x for any finite x.
Spacing of +- inf and nan is nan.
"""
"""
From http://www.mathworks.com/help/matlab/ref/eps.html
"""
epsRes = np.spacing(val);
return epsRes;
def max(A):
"""
From http://www.mathworks.com/help/matlab/ref/max.html:
C = max(A) returns the largest elements along different dimensions of an array.
If A is a vector, max(A) returns the largest element in A.
[C,I] = max(...) finds the indices of the maximum values of A,
and returns them in output vector I.
If there are several identical maximum values,
the index of the first one found is returned.
"""
assert A.ndim == 1;
for i in range(A.shape[0]):
if np.isnan(A[i]):
A[i] = -1.0e-300;
C = np.max(A);
I = np.nonzero(A == C)[0];
if False:
common.DebugPrint("MatlabMax(): a = %s" % str(A));
common.DebugPrint("MatlabMax(): C = %s" % str(C));
common.DebugPrint("MatlabMax(): I.shape = %s" % str(I.shape));
I = I[0];
return C, I;
def fliplr(M):
return M[:, ::-1];
"""
We convert a tuple of (2 or 3) array indices (or array or indices) into a
linear (scalar) index (respectively, array of linear indice)
"""
def sub2ind(matrixSize, rowSub, colSub, dim3Sub=None):
"""
Note that this is a limited implementation of Matlab's sub2ind,
in the sense we support only 2 and 3 dimensions.
BUT it is easy to generalize it.
"""
assert (len(matrixSize) == 2) or (len(matrixSize) == 3);
"""
Inspired from https://stackoverflow.com/questions/15230179/how-to-get-the-linear-index-for-a-numpy-array-sub2ind
(see also http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel_multi_index.html)
From Matlab help of sub2ind (http://www.mathworks.com/help/matlab/ref/sub2ind.html):
Convert subscripts to linear indices
Syntax
linearInd = sub2ind(matrixSize, rowSub, colSub)
linearInd = sub2ind(arraySize, dim1Sub, dim2Sub, dim3Sub, ...)
# Determines whether the multi-index should be viewed as indexing in
# C (row-major) order or FORTRAN (column-major) order.
"""
#return np.ravel_multi_index((rowSub - 1, colSub - 1), dims=matrixSize, order="F");
if dim3Sub == None:
res = np.ravel_multi_index((rowSub, colSub), dims=matrixSize, order="F");
else:
res = np.ravel_multi_index((rowSub, colSub, dim3Sub), dims=matrixSize, order="F");
return res;
def find(X):
"""
find Find indices of nonzero elements.
I = find(X) returns the linear indices corresponding to
the nonzero entries of the array X. X may be a logical expression.
Use IND2SUB(SIZE(X),I) to calculate multiple subscripts from
the linear indices I.
I = find(X,K) returns at most the first K indices corresponding to
the nonzero entries of the array X. K must be a positive integer,
but can be of any numeric type.
I = find(X,K,'first') is the same as I = find(X,K).
I = find(X,K,'last') returns at most the last K indices corresponding
to the nonzero entries of the array X.
[I,J] = find(X,...) returns the row and column indices instead of
linear indices into X. This syntax is especially useful when working
with sparse matrices. If X is an N-dimensional array where N > 2, then
J is a linear index over the N-1 trailing dimensions of X.
[I,J,V] = find(X,...) also returns a vector V containing the values
that correspond to the row and column indices I and J.
Example:
A = magic(3)
find(A > 5)
finds the linear indices of the 4 entries of the matrix A that are
greater than 5.
[rows,cols,vals] = find(speye(5))
finds the row and column indices and nonzero values of the 5-by-5
sparse identity matrix.
See also sparse, ind2sub, relop, nonzeros.
"""
"""
Alex: caution needs to be taken when translating
find() - in Matlab when find() is supposed to return 1 array the
indices are of the elements numbered in
Fortran order (column-major order), while np.nonzero() returns
invariably a tuple of 2 arrays, the first for the rows, the second
for the columns;
but when find is supposed to return 2 arrays, for row and
column we don't need to worry about this.
"""
"""
Retrieving indices in "Fortran" (column-major) order, like in Matlab.
We do this in order to get the harris points sorted like in Matlab.
"""
c, r = np.nonzero(X.T);
return sub2ind(c, r, X.shape);
"""
This version is at least 50 times faster than ordfilt2_vectorized().
It is very efficient. It also makes a few assumptions which were
respected in the code of Evangelidis - check below.
"""
def ordfilt2(A, order, domain):
"""
common.DebugPrint("Entered Matlab.ordfilt2(order=%d, domain=%s): " \
"A.dtype = %s" % \
(order, str(domain), str(A.dtype)));
"""
common.DebugPrint("Entered Matlab.ordfilt2(order=%d): " \
"A.dtype = %s" % \
(order, str(A.dtype)));
assert A.ndim == 2;
assert domain.shape[0] == domain.shape[1];
assert order == domain.shape[0] * domain.shape[0];
assert np.abs((domain - 1.0) < 1.0e-5).all();
"""
(Documented from http://stackoverflow.com/questions/16685071/implementation-of-matlab-api-ordfilt2-in-opencv)
See http://docs.opencv.org/modules/imgproc/doc/filtering.html#dilate
cv2.dilate(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) -> dst
Inspired from
http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html#dilation
"""
kernel = np.ones(domain.shape, np.uint8);
res = cv2.dilate(A, kernel, iterations=1);
return res;
if False:
if (order == 0):
res = cv2.dilate(A, kernel, iterations=1);
return res;
if False:
res = np.empty(A.shape, dtype=np.float64);
else:
res = np.empty(A.shape, dtype=A.dtype);
"""
PyArray_Descr *PyArray_DESCR(PyArrayObject* arr)
Returns a borrowed reference to the dtype property of the array.
PyArray_Descr *PyArray_DTYPE(PyArrayObject* arr)
New in version 1.7.
A synonym for PyArray_DESCR, named to be consistent with the .dtype. usage within Python.
"""
if False:
assert A.dtype == np.float64;
assert res.dtype == np.float64;
else:
assert (A.dtype == np.float32) or (A.dtype == np.float64);
assert res.dtype == A.dtype;
if A.dtype == np.float32:
dtypeSize = 4;
elif A.dtype == np.float64:
dtypeSize = 8;
common.DebugPrint("Matlab.ordfilt2(): dtypeSize = %d" % dtypeSize);
assert A.strides == (A.shape[1] * dtypeSize, dtypeSize);
assert res.strides == (res.shape[1] * dtypeSize, dtypeSize);
CPP_code = """
int r, c;
int rd, cd;
int rdu, cdu;
int center = domain_array->dimensions[0] / 2;
int numRows, numCols;
//int myMax;
double myMax;
// On various alternatives of accessing the elements of np.array: https://stackoverflow.com/questions/7744149/typecasting-pyarrayobject-data-to-a-c-array
//#define elem(row, col) (((double *)npa_array->data)[(row) * npa_array->dimensions[1] + (col)])
#define MYMIN(a, b) ((a) < (b) ? (a) : (b))
#define MYMAX(a, b) ((a) > (b) ? (a) : (b))
//assert(A_array->ndims == 2);
numRows = A_array->dimensions[0];
numCols = A_array->dimensions[1];
#define elemA(row, col) (((double *)A_array->data)[(row) * numCols + (col)])
#define elemRes(row, col) (((double *)res_array->data)[(row) * numCols + (col)])
//#define elemA(row, col) (((int *)A_array->data)[(row) * numCols + (col)])
//#define elemRes(row, col) (((int *)res_array->data)[(row) * numCols + (col)])
//#define elemA(row, col) (((long long *)A_array->data)[(row) * numCols + (col)])
//#define elemRes(row, col) (((long long *)res_array->data)[(row) * numCols + (col)])
/*
for (r = 0; r < numRows; r++) {
for (c = 0; c < numCols; c++) {
printf("A[%d, %d] = %lld ", r, c, elemA(r, c));
}
printf("%c", 10);
}
*/
for (r = 0; r < numRows; r++) {
for (c = 0; c < numCols; c++) {
if (r - center < 0)
rd = 0;
else
rd = -center;
myMax = -1;
rdu = MYMIN(center, numRows - r - 1);
for (; rd <= rdu; rd++) {
cd = -center;
if (c - center < 0)
cd = 0;
else
cd = -center;
cdu = MYMIN(center, numCols - c - 1);
for (; cd <= cdu; cd++) {
//printf("r=%d, c=%d, rd = %d, cd = %d\\n", r, c, rd, cd);
myMax = MYMAX(myMax, elemA(r + rd, c + cd));
}
}
elemRes(r, c) = myMax;
}
}
//printf("res[1, 0] = %d", elemRes(1, 0));
//printf("sum = %.2f, npa = %d", sum, PyArray_NDIM(A_array));
printf("A.shape = %ld, %ld\\n", A_array->dimensions[0], A_array->dimensions[1]);
//printf("npa[0, 0] = %.3f", ((double *)PyArray_DATA(A_array))[0]);
//printf("npa[0, 0] = %.3f", ((double *)A_array->data)[0]);
//printf("npa[1, 0] = %.3f", ((double *)A_array->data)[200]);
//printf("npa[1, 0] = %.3f", *((double *)PyArray_GETPTR2(A_array, 1, 0)));
//printf("res[1, 0] = %.3f", *((int *)PyArray_GETPTR2(res_array, 1, 0)));
"""
if A.dtype == np.float32:
CPP_code = CPP_code.replace("double", "float");
scipy.weave.inline(CPP_code, ['A', 'res', 'domain']);
return res;
def ordfilt2_vectorized(A, order, domain):
"""
OUR ordfilt2 IMPLEMENTATION IS LIMITED w.r.t. the one in Matlab
- SEE below for details!
"""
"""
From http://www.mathworks.com/help/images/ref/ordfilt2.html
2-D order-statistic filtering
expand all in page
Syntax
B = ordfilt2(A, order, domain)
B = ordfilt2(A, order, domain, S)
B = ordfilt2(..., padopt)
Description
B = ordfilt2(A, order, domain) replaces each element in A by the
orderth element in the sorted set of neighbors specified
by the nonzero elements in domain.
B = ordfilt2(A, order, domain, S) where S is the same size as domain,
uses the values of S corresponding to the nonzero values of
domain as additive offsets.
B = ordfilt2(..., padopt) controls how the matrix boundaries are padded.
Set padopt to 'zeros' (the default) or 'symmetric'.
If padopt is 'zeros', A is padded with 0's at the boundaries.
If padopt is 'symmetric', A is symmetrically extended at the
boundaries.
Class Support
The class of A can be logical, uint8, uint16, or double.
The class of B is the same as the class of A, unless the additive
offset form of ordfilt2 is used, in which case the class of B
is double.
Examples
This examples uses a maximum filter with a [5 5] neighborhood.
This is equivalent to imdilate(image,strel('square',5)).
A = imread('snowflakes.png');
B = ordfilt2(A,25,true(5));
figure, imshow(A), figure, imshow(B)
References
[1] Haralick, Robert M., and Linda G. Shapiro, Computer and Robot Vision,
Volume I, Addison-Wesley, 1992.
[2] Huang, T.S., G.J.Yang, and G.Y.Tang.
"A fast two-dimensional median filtering algorithm.",
IEEE transactions on Acoustics, Speech and Signal Processing,
Vol ASSP 27, No. 1, February 1979
From type ordfilt2 (extra info):
%
% Remarks
% -------
% DOMAIN is equivalent to the structuring element used for
% binary image operations. It is a matrix containing only 1's
% and 0's; the 1's define the neighborhood for the filtering
% operation.
%
% For example, B=ORDFILT2(A,5,ONES(3,3)) implements a 3-by-3
% median filter; B=ORDFILT2(A,1,ONES(3,3)) implements a 3-by-3
% minimum filter; and B=ORDFILT2(A,9,ONES(3,3)) implements a
% 3-by-3 maximum filter. B=ORDFILT2(A,4,[0 1 0; 1 0 1; 0 1 0])
% replaces each element in A by the maximum of its north, east,
% south, and west neighbors.
%
% See also MEDFILT2.
% Copyright 1993-2011 The MathWorks, Inc.
"""
"""
OUR ordfilt2 IMPLEMENTATION IS LIMITED w.r.t. the one in Matlab.
We assume that:
- the matrix A contains only positive elements;
- domain is all ones and;
- order = num. elements of domain - i.e., we look for the
maximum in the domain.
To use their terminology we implement ONLY a N-by-N neighborhood
maximum filter, where N = domain.shape[0] == domain.shape[1].
To implement a generic order-th filter we can use:
- k-th order statistic algorithm - time complexity O(N lg N)
OR
- use a MIN-heap of size k - time complexity O(k lg k)
We can alternate using one or the other depending on the values of
k and N :))
"""
res = np.empty(A.shape);
assert domain.shape[0] == domain.shape[1];
assert order == domain.shape[0] * domain.shape[1];
center = domain.shape[0] / 2;
common.DebugPrint("Matlab.ordfilt2(): domain.shape = %s" % str(domain.shape));
common.DebugPrint("Matlab.ordfilt2(): center = %s" % str(center));
numRows, numCols = A.shape;
common.DebugPrint("ordfilt2(): (numRows, numCols) = %s" % \
str((numRows, numCols)));
c, r = np.meshgrid(range(numCols), range(numRows));
common.DebugPrint("Matlab.ordfilt2(): c.shape = %s" % str(c.shape));
common.DebugPrint("Matlab.ordfilt2(): r.shape = %s" % str(r.shape));
assert c.shape == A.shape;
assert r.shape == A.shape;
res = np.zeros(A.shape);
nonZeroDomain = np.nonzero(domain == 1);
"""
rd = -center;
while (rd <= center):
cd = -center;
while (cd <= center):
if domain[rd + center, cd + center] == 1:
"""
if True:
if True:
for i in range(len(nonZeroDomain[0])):
rd = nonZeroDomain[0][i] - center;
cd = nonZeroDomain[1][i] - center;
"""
if True:
common.DebugPrint("ordfilt2(): (rd, cd) = %s" % \
str((rd, cd)));
common.DebugPrint("ordfilt2(): r + rd = %s" % str(r + rd));
"""
rf = r + rd;
cf = c + cd;
"""
if True:
common.DebugPrint("ordfilt2(): rf = %s" % str(rf));
common.DebugPrint("ordfilt2(): cf = %s" % str(cf));
#common.DebugPrint("ordfilt2(): rf[rf < 0] = %s" % str(rf[rf < 0]));
"""
indRZeroBelow = np.nonzero(rf < 0);
indRZeroAbove = np.nonzero(rf >= numRows);
indCZeroBelow = np.nonzero(cf < 0);
indCZeroAbove = np.nonzero(cf >= numCols);
"""
Note: if we give negative values in matrices as indices,
it acts as PADOPT=='symmetric' in ordfilt2.
BUT if we have values in rf or cf > N then A[rf, cf]
gives exception like:
"IndexError: index (4) out of range (0<=index<3) in dimension 1"
"""
rf[indRZeroAbove] = 0;
cf[indCZeroAbove] = 0;
"""
if True:
common.DebugPrint("ordfilt2(): rf = %s" % str(rf));
common.DebugPrint("ordfilt2(): cf = %s" % str(cf));
"""
crtD = A[rf, cf];
indicesR = np.r_[indRZeroBelow[0], indRZeroAbove[0], \
indCZeroBelow[0], indCZeroAbove[0]];
indicesC = np.r_[indRZeroBelow[1], indRZeroAbove[1], \
indCZeroBelow[1], indCZeroAbove[1]];
crtD[indicesR, indicesC] = 0.0;
"""
if True:
#common.DebugPrint("ordfilt2(): A[r + rd, c + cd] = %s" % \
# str(A[r + rd, c + cd]));
common.DebugPrint("ordfilt2(): crtD = %s" % str(crtD));
"""
res = np.maximum(res, crtD);
def ordfilt2_4_nested_loops(A, order, domain):
import __builtin__
res = np.empty(A.shape);
assert domain.shape[0] == domain.shape[1];
assert order == domain.shape[0] * domain.shape[1];
center = domain.shape[0] / 2;
common.DebugPrint("Matlab.ordfilt2(): domain.shape = %s" % str(domain.shape));
common.DebugPrint("Matlab.ordfilt2(): center = %s" % str(center));
numRows, numCols = A.shape;
common.DebugPrint("ordfilt2(): (numRows, numCols) = %s" % \
str((numRows, numCols)));
r = 0;
while (r < numRows):
c = 0;
while (c < numCols):
"""
rd = -center;
if r + rd < 0: # rd < -r
rd = 0; #-r;
"""
if r - center < 0:
rd = 0;
else:
rd = -center;
myMax = -1;
rdu = min(center, A.shape[0] - r - 1);
while (rd <= rdu):
cd = -center;
"""
if c + cd < 0: # cd < -c
cd = 0; #-c;
"""
if c - center < 0:
cd = 0;
else:
cd = -center;
cdu = min(center, A.shape[1] - c - 1);
while (cd <= cdu):
if False:
common.DebugPrint("ordfilt2(): (r, c) = %s" % str((r, c)));
common.DebugPrint("ordfilt2(): (r+rd, c+cd) = %s" % \
str((r+rd, c+cd)));
myMax = __builtin__.max(myMax, A[r + rd, c + cd]);
if False:
common.DebugPrint("ordfilt2(): (r, c) = %s" % str((r, c)));
common.DebugPrint("ordfilt2(): (r+rd, c+cd) = %s" % \
str((r+rd, c+cd)));
common.DebugPrint("ordfilt2(): A[r + rd, c + cd] = %s" % \
str(A[r + rd, c + cd]));
common.DebugPrint("ordfilt2(): myMax = %s" % str(myMax));
cd += 1;
rd += 1;
res[r, c] = myMax;
c += 1;
r += 1;
return res;
def mean2(x):
"""
function y = mean2(x) %#codegen
%MEAN2 Average or mean of matrix elements.
% B = MEAN2(A) computes the mean of the values in A.
%
% Class Support
% -------------
% A can be numeric or logical. B is a scalar of class double.
%
% Example
% -------
% I = imread('liftingbody.png');
% val = mean2(I)
%
% See also MEAN, STD, STD2.
% Copyright 1993-2013 The MathWorks, Inc.
y = sum(x(:),'double') / numel(x);
"""
y = float(x.sum()) / x.size;
return y;
def testEqualMatrices(res, res2):
rows, cols = res.shape;
numMismatches = 0;
for r in range(rows):
for c in range(cols):
if np.isnan(res[r, c]) or np.isnan(res[r, c]):
if not (np.isnan(res2[r, c]) and np.isnan(res[r, c])):
numMismatches += 1;
common.DebugPrint("testEqualMatrices(): Mismatching nan at r=%d, c=%d, res2[r,c]=%s, res[r,c]=%s" % \
(r, c, str(res2[r, c]), str(res[r, c])));
elif (abs(res2[r, c] - res[r, c]) > 1.e-4):
numMismatches += 1;
common.DebugPrint("testEqualMatrices(): Mismatching vals at r=%d, c=%d, res2[r,c]=%s, res[r,c]=%s" % \
(r, c, str(res2[r, c]), str(res[r, c])));
if numMismatches > 0:
common.DebugPrint("testEqualMatrices(): Mismatch with canonical implementation!!!! numMismatches = %d" % numMismatches);
return numMismatches
def interp2(V, Xq, Yq, interpolationMethod="linear"):
common.DebugPrint("Entered Matlab.interp2(): " \
"V.dtype = %s" % \
(str(V.dtype)));
if False:
res = np.empty(V.shape, dtype=np.float64);
else:
res = np.empty(V.shape, dtype=V.dtype);
"""
PyArray_Descr *PyArray_DESCR(PyArrayObject* arr)
Returns a borrowed reference to the dtype property of the array.
PyArray_Descr *PyArray_DTYPE(PyArrayObject* arr)
New in version 1.7.
A synonym for PyArray_DESCR, named to be consistent with the .dtype. usage within Python.
"""
if common.MY_DEBUG_STDOUT:
common.DebugPrint("interp2(): V.strides = %s" % str(V.strides));
common.DebugPrint("interp2(): V.shape = %s" % str(V.shape));
common.DebugPrint("interp2(): V.dtype = %s" % str(V.dtype));
common.DebugPrint("interp2(): Xq.strides = %s" % str(Xq.strides));
common.DebugPrint("interp2(): Xq.shape = %s" % str(Xq.shape));
common.DebugPrint("interp2(): Xq.dtype = %s" % str(Xq.dtype));
common.DebugPrint("interp2(): Yq.strides = %s" % str(Yq.strides));
common.DebugPrint("interp2(): Yq.shape = %s" % str(Yq.shape));
common.DebugPrint("interp2(): Yq.dtype = %s" % str(Yq.dtype));
common.DebugPrint("interp2(): res.strides = %s" % str(res.strides));
common.DebugPrint("interp2(): res.shape = %s" % str(res.shape));
common.DebugPrint("interp2(): res.dtype = %s" % str(res.dtype));
if False:
assert V.dtype == np.float64;
assert Xq.dtype == np.float64;
assert Yq.dtype == np.float64;
else:
if common.MY_DEBUG_STDOUT:
common.DebugPrint("interp2(): V.dtype (again) = %s" % str(V.dtype));
common.DebugPrint("interp2(): V.dtype == np.float32 is %s" % str(V.dtype == np.float32));
common.DebugPrint("interp2(): V.dtype == float is %s" % str(V.dtype == float));
"""
if False:
"""
assert (V.dtype == np.float32) or (V.dtype == np.float64);
assert Xq.dtype == V.dtype;
assert Yq.dtype == V.dtype;
assert V.ndim == 2;
assert Xq.ndim == 2;
assert Yq.ndim == 2;
if V.dtype == np.float32:
dtypeSize = 4;
elif V.dtype == np.float64:
dtypeSize = 8;
assert V.strides == (V.shape[1] * dtypeSize, dtypeSize);
assert res.strides == (res.shape[1] * dtypeSize, dtypeSize);
"""
# We check if we have the matrices in column-major order (Fortran) style
assert Xq.strides == (dtypeSize, Xq.shape[0] * dtypeSize);
assert Yq.strides == (dtypeSize, Yq.shape[0] * dtypeSize);
"""
assert interpolationMethod == "linear";
CPP_code2_prefix_Row_Major_Order = """
#define elemXq(row, col) (((double *)Xq_array->data)[(row) * numC + (col)])
#define elemYq(row, col) (((double *)Yq_array->data)[(row) * numC + (col)])
"""
CPP_code2_prefix_Fortran_Major_Order = """
#define elemXq(row, col) (((double *)Xq_array->data)[(col) * numR + (row)])
#define elemYq(row, col) (((double *)Yq_array->data)[(col) * numR + (row)])
"""
if (Xq.strides == (dtypeSize, Xq.shape[0] * dtypeSize)):
assert Yq.strides == (dtypeSize, Yq.shape[0] * dtypeSize);
CPP_prefix = CPP_code2_prefix_Fortran_Major_Order;
else:
CPP_prefix = CPP_code2_prefix_Row_Major_Order;
CPP_code2 = """
int r, c;
int rp, cp;
int numR, numC;
double x, y;
double x1, y1;
double val;
numR = V_array->dimensions[0];
numC = V_array->dimensions[1];
#define elemV(row, col) (((double *)V_array->data)[(row) * numC + (col)])
#define elemRes(row, col) (((double *)res_array->data)[(row) * numC + (col)])
for (r = 0; r < numR; r++) {
for (c = 0; c < numC; c++) {
x = elemXq(r, c);
y = elemYq(r, c);
//printf("interp2(): (initial) x = %.5f, y = %.5f\\n", x, y);
if ((x < 0.0) or (y < 0.0) or (x >= numC) or (y >= numR)) {
elemRes(r, c) = NAN;
continue;
}
// Need to check in which square unit (x, y) falls into
rp = (int)y;
cp = (int)x;
// Adjust (x, y) relative to this particular unit square where it falls into
y -= rp;
x -= cp;
assert((x <= 1) && (x >= 0));
assert((y <= 1) && (y >= 0));
//printf("interp2(): x = %.5f, y = %.5f\\n", x, y);
if ((x == 0.0) && (y == 0.0)) {
val = elemV(r, c);
}
else {
/*
common.DebugPrint("interp2(): r = %d, c = %d" % (r, c));
common.DebugPrint(" rp = %d, cp = %d" % (rp, cp));
common.DebugPrint(" x = %.3f, y = %.3f" % (x, y));
*/
// First index of f is the col, 2nd index is row
/*
f00 = V[rp, cp];
f01 = V[rp + 1, cp];
f10 = V[rp, cp + 1];
f11 = V[rp + 1, cp + 1];
# As said in https://en.wikipedia.org/wiki/Bilinear_interpolation
val = f00 * (1 - x) * (1 - y) + f10 * x * (1 - y) + \
f01 * (1 - x) * y + f11 * x * y;
*/
x1 = 1 - x;
y1 = 1 - y;
if (
//(rp < numR) &&
(rp >= 0) &&
//(cp < numC) &&
(cp >= 0) &&
(cp + 1 < numC) &&
//(cp + 1 >= 0) &&
(rp + 1 < numR) &&
//(rp + 1 >= 0) &&
(cp + 1 < numC)
//&& (cp + 1 >= 0)
)
{
/*
printf("interp2(): elemV(rp, cp) = %.5f\\n", elemV(rp, cp));
printf("interp2(): elemV(rp, cp + 1) = %.5f\\n", elemV(rp, cp + 1));
printf("interp2(): elemV(rp + 1, cp) = %.5f\\n", elemV(rp + 1, cp));
printf("interp2(): elemV(rp + 1, cp + 1) = %.5f\\n", elemV(rp + 1, cp + 1));
printf("interp2(): at val, x = %.5f, y = %.5f\\n", x, y);
printf("interp2(): at val, x1 = %.5f, y1 = %.5f\\n", x1, y1);
*/
val = elemV(rp, cp) * x1 * y1 + elemV(rp, cp + 1) * x * y1 +
elemV(rp + 1, cp) * x1 * y + elemV(rp + 1, cp + 1) * x * y;
}
else {
// If out of the array bounds, assign NaN
/*
This portion of code can be executed even
if we checked for out-of-bounds of (x,y).
*/
// From http://www.cplusplus.com/reference/cmath/NAN/
val = NAN;
}
}
elemRes(r, c) = val;
}
}
"""
CPP_code = CPP_prefix + CPP_code2;
if V.dtype == np.float32:
CPP_code = CPP_code.replace("double", "float");
scipy.weave.inline(CPP_code, ["V", "Xq", "Yq", "res"]);
return res;
def interp2_vectorized(V, Xq, Yq, interpolationMethod="linear"):
"""
From http://www.mathworks.com/help/matlab/ref/interp2.html :
Vq = interp2(V,Xq,Yq) assumes a default grid of sample points.
The default grid points cover the rectangular region,
X=1:n and Y=1:m, where [m,n] = size(V).
Use this syntax to when you want to conserve memory and are
not concerned about the absolute distances between points.
Vq = interp2(X,Y,V,Xq,Yq) returns interpolated values of a function
of two variables at specific query points using linear interpolation.
The results always pass through the original sampling of the function.
X and Y contain the coordinates of the sample points.
V contains the corresponding function values at each sample point.
Xq and Yq contain the coordinates of the query points.
Vq = interp2(___,method) specifies an optional, trailing input
argument that you can pass with any of the previous syntaxes.
The method argument can be any of the following strings that
specify alternative interpolation methods:
'linear', 'nearest', 'cubic', or 'spline'.
The default method is 'linear'.
Alex:
So, we give the query coordinates xi, yi and
bidimensional function wimg_time
"""
assert interpolationMethod == "linear";
if False:
common.DebugPrint("interp2(): V.shape = %s" % str(V.shape));
common.DebugPrint("interp2(): Xq[:20, :20] = %s" % str(Xq[:20, :20]));
common.DebugPrint("interp2(): Xq.shape = %s" % str(Xq.shape));
common.DebugPrint("interp2(): Yq[:20, :20] = %s" % str(Yq[:20, :20]));
common.DebugPrint("interp2(): Yq.shape = %s" % str(Yq.shape));
"""
From https://en.wikipedia.org/wiki/Bilinear_interpolation
- unit square case
If we choose a coordinate system in which the four points where
f is known are (0, 0), (0, 1), (1, 0), and (1, 1), then the
interpolation formula simplifies to
f(x, y) = f(0, 0) (1-x) (1-y) + f(1, 0) x (1-y) + f(0, 1)(1-x)y + f(1, 1) xy
Or equivalently, in matrix operations:
f(x,y) = [1-x, x] [f(0,0) f(0,1); f(1,0) f(1,1)] [1-y; y]
One could use the more complex, (yet more accurate I guess),
barycentric interpolation from
http://classes.soe.ucsc.edu/cmps160/Fall10/resources/barycentricInterpolation.pdf
"""
res = np.zeros( V.shape );
numR, numC = V.shape;
yM = Yq.copy();
xM = Xq.copy();
indY = np.nonzero( np.logical_or(yM < 0, yM > numR - 1) );
yM[indY] = 0.0;
indX = np.nonzero( np.logical_or(xM < 0, xM > numC - 1) );
xM[indX] = 0.0;
rpM = yM.astype(int);
cpM = xM.astype(int);
yM = yM - rpM;
xM = xM - cpM;
y1M = 1.0 - yM;
x1M = 1.0 - xM;
if False:
common.DebugPrint("interp2(): yM = %s" % str(yM));
common.DebugPrint("interp2(): xM = %s" % str(xM));
common.DebugPrint("interp2(): y1M = %s" % str(y1M));
common.DebugPrint("interp2(): x1M = %s" % str(x1M));
zeroRow = np.zeros( (1, V.shape[1]) ); #+ np.nan;
zeroCol = np.zeros( (V.shape[0], 1) ); #+ np.nan;
"""
if False:
V4 = np.zeros((V.shape[0], V.shape[1])); #+ np.nan;
V4[:-1, :-1] = V[1:, 1:] * xM * yM;
else:
zeroCol1 = np.zeros((V.shape[0] - 1, 1)); #+ np.nan;
#V4 = np.c_[V[1:, 1:] * xM[:-1, :-1] * yM[:-1, :-1], zeroCol1];
#V4 = np.r_[V4, zeroRow];
V4 = np.hstack( (V[1:, 1:] * xM[:-1, :-1] * yM[:-1, :-1], zeroCol1) );
V4 = np.vstack( (V4, zeroRow) );
"""
"""
Note that each element in Xq and Yq is NOT just x \in [0,1) away from the
value col, respectively raw of that element.
Therefore, we need to compute for each result element res[r, c] its
four neighbors: V00[r, c], V01[r, c], V10[r, c], V11[r, c].
"""
V00 = V[rpM, cpM];
# When FASTER is true we have an improvement of 1.13 secs / 10000.
FASTER = False; #True;
if FASTER:
V01 = np.zeros(V.shape);
V01[:, :-1] = V[:, 1:];
V01 = V01[rpM, cpM];
else:
V01 = np.c_[V[:,1:], zeroCol][rpM, cpM];
if FASTER:
V10 = np.zeros(V.shape);
V10[:-1, :] = V[1:, :];
V10 = V10[rpM, cpM];
else:
V10 = np.r_[V[1:,:], zeroRow][rpM, cpM];
if FASTER:
V11 = np.zeros(V.shape);
V11[:-1, :-1] = V[1:, 1:];
V11 = V11[rpM, cpM];
else:
zeroCol1 = np.zeros((V.shape[0] - 1, 1));
V11 = np.c_[V[1:, 1:], zeroCol1];
V11 = np.r_[V11, zeroRow][rpM, cpM];
if False:
V01 = np.c_[V00[:,1:], zeroCol];
V10 = np.r_[V00[1:,:], zeroRow];
#
V11 = np.c_[V00[1:, 1:], zeroCol1];
V11 = np.r_[V11, zeroRow];
if False:
common.DebugPrint("interp2(): V = %s" % str(V));
common.DebugPrint("interp2(): rpM = %s" % str(rpM));
common.DebugPrint("interp2(): cpM = %s" % str(cpM));
common.DebugPrint("interp2(): V00 = %s" % str(V00));
common.DebugPrint("interp2(): V01 = %s" % str(V01));
common.DebugPrint("interp2(): V10 = %s" % str(V10));
common.DebugPrint("interp2(): V11 = %s" % str(V11));
#common.DebugPrint("interp2(): xM = %s" % str(V11));
"""
x = Xq[r, c];
y = Yq[r, c];
rp = int(y);
cp = int(x);
y -= rp;
x -= cp;
x1 = 1 - x;
y1 = 1 - y;
val = V[rp, cp] * x1 * y1 + \
V[rp, cp + 1] * x * y1 + \
V[rp + 1, cp] * x1 * y + \
V[rp + 1, cp + 1] * x * y;
"""
if False:
common.DebugPrint("V[:,1:].shape = %s" % str(V[:,1:].shape));
common.DebugPrint("xM[:,:-1].shape = %s" % str(xM[:,:-1].shape));
common.DebugPrint("y1M[:,:-1].shape = %s" % str(y1M[:,:-1].shape));
common.DebugPrint("nanCol.shape = %s" % str(nanCol.shape));
common.DebugPrint("V[1:,:].shape = %s" % str(V[1:,:].shape));
common.DebugPrint("x1M[:-1,:].shape = %s" % str(x1M[:-1,:].shape));
common.DebugPrint("yM[:-1,:].shape = %s" % str(yM[:-1,:].shape));
common.DebugPrint("nanRow.shape = %s" % str(nanRow.shape));
if False:
res = V00 * x1M * y1M + \
np.c_[V01[:,1:] * xM[:,:-1] * y1M[:,:-1], zeroCol] + \
np.r_[V10[1:,:] * x1M[:-1,:] * yM[:-1,:], zeroRow] + \
V11;
res = V00 * x1M * y1M + \
V01 * xM * y1M + \
V10 * x1M * yM + \
V11 * xM * yM;
if False:
#common.DebugPrint("Yq = %s" % str(Yq));
ind = np.nonzero( np.logical_or(Yq < 0, Yq > numR - 1) );
#common.DebugPrint("ind from Yq = %s" % str(ind));
res[ind] = np.nan;
#common.DebugPrint("Xq = %s" % str(Xq));
ind = np.nonzero( np.logical_or(Xq < 0, Xq > numC - 1) );
#common.DebugPrint("ind from Xq = %s" % str(ind));
res[ind] = np.nan;
res[indY] = np.nan;
res[indX] = np.nan;
"""
# Following is a DIDACTIC example of ONE bilinear interpolation:
x = Xq[0, 0]; # - 1;
y = Yq[0, 0]; # - 1;
# First index of f is the col, 2nd index is row
f00 = V[0, 0];
f01 = V[1, 0];
f10 = V[0, 1];
f11 = V[1, 1];
# As said, https://en.wikipedia.org/wiki/Bilinear_interpolation
val = f00 * (1 - x) * (1 - y) + f10 * x * (1 - y) + f01 * (1 - x) * y + f11 * x * y;
common.DebugPrint("interp2-related: val (bilinear interpolation) = %.5f" % val);
"""
"""
# Another a bit more complex formula for bilinear interpolation,
for the general (NOT unit square) case:
from http://www.ajdesigner.com/phpinterpolation/bilinear_interpolation_equation.php#ajscroll
# it has even a calculator
x1 = 0.0;
x2 = 1.0;
y1 = 0.0;
y2 = 1.0;
Q11 = V[0, 0];
Q12 = V[1, 0];
Q21 = V[0, 1];
Q22 = V[1, 1];
common.DebugPrint("Q11 = %s" % str(Q11));
common.DebugPrint("Q21 = %s" % str(Q21));
common.DebugPrint("Q12 = %s" % str(Q12));
common.DebugPrint("Q22 = %s" % str(Q22));
nom = (x2 - x1) * (y2 - y1);
common.DebugPrint("interp2-related: nom (bilinear interpolation) = %.5f" % nom);
val2 = (x2 - x) * (y2 - y) / ( (x2 - x1) * (y2 - y1) ) * Q11 + \
(x - x1) * (y2 - y) / ( (x2 - x1) * (y2 - y1) ) * Q21 + \
(x2 - x) * (y - y1) / ( (x2 - x1) * (y2 - y1) ) * Q12 + \
(x - x1) * (y - y1) / ( (x2 - x1) * (y2 - y1) ) * Q22;
common.DebugPrint("interp2-related: val2 (bilinear interpolation) = %.5f" % val2);
"""
return res;
def interp2VectorizedWithTest(V, Xq, Yq, interpolationMethod="linear"):
common.DebugPrint("Entered interp2VectorizedWithTest()");
res = interp2Orig(V, Xq, Yq, interpolationMethod);
res2 = interp2_nested_loops(V, Xq, Yq, interpolationMethod);
resN = testEqualMatrices(res, res2);
if resN != 0:
common.DebugPrint("testEqualMatrices(): V.shape = %s" % str(V.shape));
common.DebugPrint("testEqualMatrices(): V = %s" % str(V));
common.DebugPrint("testEqualMatrices(): Xq.shape = %s" % str(Xq.shape));
common.DebugPrint("testEqualMatrices(): Xq = %s" % str(Xq));
common.DebugPrint("testEqualMatrices(): Yq.shape = %s" % str(Yq.shape));
common.DebugPrint("testEqualMatrices(): Yq = %s" % str(Yq));
return res;
#TEST_INTERP2 = True
TEST_INTERP2 = False
if TEST_INTERP2:
interp2Orig = interp2;
interp2 = interp2VectorizedWithTest;
else:
interp2Orig = interp2;
# TODO: remove
# This implementation is BAD: it assumes each query is placed in "its own square"
def interp2_BAD(V, Xq, Yq, interpolationMethod="linear"):
common.DebugPrint("Entered interp2().");
#common.DebugPrint("interp2(): Xq = %s" % str(Xq));
"""
From http://www.mathworks.com/help/matlab/ref/interp2.html :
Vq = interp2(V,Xq,Yq) assumes a default grid of sample points.
The default grid points cover the rectangular region,
X=1:n and Y=1:m, where [m,n] = size(V).
Use this syntax to when you want to conserve memory and are
not concerned about the absolute distances between points.
Vq = interp2(X,Y,V,Xq,Yq) returns interpolated values of a function
of two variables at specific query points using linear interpolation.
The results always pass through the original sampling of the function.
X and Y contain the coordinates of the sample points.
V contains the corresponding function values at each sample point.
Xq and Yq contain the coordinates of the query points.
Vq = interp2(___,method) specifies an optional, trailing input
argument that you can pass with any of the previous syntaxes.
The method argument can be any of the following strings that
specify alternative interpolation methods:
'linear', 'nearest', 'cubic', or 'spline'.
The default method is 'linear'.
Alex:
So, we give the query coordinates xi, yi and
bidimensional function wimg_time
"""
assert interpolationMethod == "linear"; # Bilinear interpolation
if False:
common.DebugPrint("interp2(): V.shape = %s" % str(V.shape));
common.DebugPrint("interp2(): Xq[:20, :20] = %s" % str(Xq[:20, :20]));
common.DebugPrint("interp2(): Xq.shape = %s" % str(Xq.shape));
common.DebugPrint("interp2(): Yq[:20, :20] = %s" % str(Yq[:20, :20]));
common.DebugPrint("interp2(): Yq.shape = %s" % str(Yq.shape));
"""
From https://en.wikipedia.org/wiki/Bilinear_interpolation
- unit square case
If we choose a coordinate system in which the four points where
f is known are (0, 0), (0, 1), (1, 0), and (1, 1), then the
interpolation formula simplifies to
f(x, y) = f(0, 0) (1-x) (1-y) + f(1, 0) x (1-y) + f(0, 1)(1-x)y + f(1, 1) xy
Or equivalently, in matrix operations:
f(x,y) = [1-x, x] [f(0,0) f(0,1); f(1,0) f(1,1)] [1-y; y]
One could use the more complex, (yet more accurate I guess),
barycentric interpolation from
http://classes.soe.ucsc.edu/cmps160/Fall10/resources/barycentricInterpolation.pdf
"""
res = np.zeros( V.shape );
numR, numC = V.shape;
yM = Yq.copy();
xM = Xq.copy();
rpM = yM.astype(int);
cpM = xM.astype(int);
#y = Yq[r, c];
#x = Xq[r, c];
yM = yM - rpM;
xM = xM - cpM;
y1M = 1.0 - yM;
x1M = 1.0 - xM;
common.DebugPrint("interp2(): yM = %s" % str(yM));
common.DebugPrint("interp2(): xM = %s" % str(xM));
common.DebugPrint("interp2(): y1M = %s" % str(y1M));
common.DebugPrint("interp2(): x1M = %s" % str(x1M));
# nan is stronger than any other number - can't mix with other numbers
zeroRow = np.zeros( (1, V.shape[1]) );
zeroCol = np.zeros( (V.shape[0], 1) );
if False:
V4 = np.zeros((V.shape[0], V.shape[1]));
V4[:-1, :-1] = V[1:, 1:] * xM * yM;
else:
zeroCol1 = np.zeros((V.shape[0] - 1, 1));
V4 = np.hstack( (V[1:, 1:] * xM[:-1, :-1] * yM[:-1, :-1], zeroCol1) );
V4 = np.vstack( (V4, zeroRow) );
"""
x = Xq[r, c];
y = Yq[r, c];
rp = int(y);
cp = int(x);
y -= rp;
x -= cp;
x1 = 1 - x;
y1 = 1 - y;
val = V[rp, cp] * x1 * y1 + \
V[rp, cp + 1] * x * y1 + \
V[rp + 1, cp] * x1 * y + \
V[rp + 1, cp + 1] * x * y;
"""
if False:
common.DebugPrint("V[:,1:].shape = %s" % str(V[:,1:].shape));
common.DebugPrint("xM[:,:-1].shape = %s" % str(xM[:,:-1].shape));
common.DebugPrint("y1M[:,:-1].shape = %s" % str(y1M[:,:-1].shape));
common.DebugPrint("nanCol.shape = %s" % str(nanCol.shape));
common.DebugPrint("V[1:,:].shape = %s" % str(V[1:,:].shape));
common.DebugPrint("x1M[:-1,:].shape = %s" % str(x1M[:-1,:].shape));
common.DebugPrint("yM[:-1,:].shape = %s" % str(yM[:-1,:].shape));
common.DebugPrint("nanRow.shape = %s" % str(nanRow.shape));
res = V * x1M * y1M + \
np.c_[V[:,1:] * xM[:,:-1] * y1M[:,:-1], zeroCol] + \
np.r_[V[1:,:] * x1M[:-1,:] * yM[:-1,:], zeroRow] + \
V4;
ind = np.nonzero( np.logical_or(Yq < 0, Yq > numR - 1) );
res[ind] = np.nan;
ind = np.nonzero( np.logical_or(Xq < 0, Xq > numC - 1) );
res[ind] = np.nan;
return res;
"""
This implementation is for the sake of documenting the algorithm,
but is VERY VERY slow - 1.55 secs / call for resolution of 320x240.
(So we will need to implement it in C++ in OpenCV, preferably vectorized :) .)
"""
def interp2_nested_loops(V, Xq, Yq, interpolationMethod="linear"):
assert interpolationMethod == "linear";
"""
From https://en.wikipedia.org/wiki/Bilinear_interpolation
- unit square case
If we choose a coordinate system in which the four points where
f is known are (0, 0), (0, 1), (1, 0), and (1, 1), then the
interpolation formula simplifies to
f(x, y) = f(0, 0) (1-x) (1-y) + f(1, 0) x (1-y) + f(0, 1)(1-x)y + f(1, 1) xy
Or equivalently, in matrix operations:
f(x,y) = [1-x, x] [f(0,0) f(0,1); f(1,0) f(1,1)] [1-y; y]
One could use the more complex, (yet more accurate I guess),
barycentric Interpolation from
http://classes.soe.ucsc.edu/cmps160/Fall10/resources/barycentricInterpolation.pdf
"""
res = np.zeros( V.shape );
numR, numC = V.shape;
for r in range(numR):
for c in range(numC):
x = Xq[r, c];
y = Yq[r, c];
if (x < 0.0) or (y < 0.0) or (x >= numC) or (y >= numR):
res[r, c] = np.nan;
continue;
rp = int(y);
cp = int(x);
y -= rp;
x -= cp;
if not((y <= 1) and (y >= 0)) or \
not((x <= 1) and (x >= 0)):
common.DebugPrint("interp2(): r = %d, c = %d" % (r, c));
common.DebugPrint(" rp = %d, cp = %d" % (rp, cp));
common.DebugPrint(" x = %.3f, y = %.3f" % (x, y));
common.DebugPrint(" Xq[r, c] = %.3f, Yq[r, c] = %.3f" % \
(Xq[r, c], Yq[r, c]));
assert (x <= 1) and (x >= 0);
assert (y <= 1) and (y >= 0);
if (x == 0.0) and (y == 0.0):
val = V[r, c];
else:
"""
common.DebugPrint("interp2(): r = %d, c = %d" % (r, c));
common.DebugPrint(" rp = %d, cp = %d" % (rp, cp));
common.DebugPrint(" x = %.3f, y = %.3f" % (x, y));
"""
try:
"""
f00 = V[rp, cp];
f01 = V[rp + 1, cp];
f10 = V[rp, cp + 1];
f11 = V[rp + 1, cp + 1];
# As said in https://en.wikipedia.org/wiki/Bilinear_interpolation
val = f00 * (1 - x) * (1 - y) + f10 * x * (1 - y) + \
f01 * (1 - x) * y + f11 * x * y;
"""
x1 = 1 - x;
y1 = 1 - y;
val = V[rp, cp] * x1 * y1 + V[rp, cp + 1] * x * y1 + \
V[rp + 1, cp] * x1 * y + V[rp + 1, cp + 1] * x * y;
except:
"""
This portion of code can be executed even
if we checked for out-of-bounds of (x,y).
"""
val = np.nan;
res[r, c] = val;
return res;
"""
This is a slightly optimized version of the interp2_nested_loops.
1.135 secs / call for resolution of 320x240.
The gain in performance is around 27% .
"""
def interp2_1loop(V, Xq, Yq, interpolationMethod="linear"):
assert interpolationMethod == "linear";
res = np.zeros( V.shape );
numR, numC = V.shape;
numPixels = numR * numC;
i = 0;
r = 0;
c = -1;
while i < numPixels:
i += 1;
c += 1;
if c == numC:
c = 0;
r += 1;
x = Xq[r, c];
y = Yq[r, c];
if (x < 0.0) or (y < 0.0) or (x >= numC) or (y >= numR):
res[r, c] = np.nan;
continue;
rp = int(y);
cp = int(x);
y -= rp;
x -= cp;
"""
if not((y <= 1) and (y >= 0)) or \
not((x <= 1) and (x >= 0)):
common.DebugPrint("interp2(): r = %d, c = %d" % (r, c));
common.DebugPrint(" rp = %d, cp = %d" % (rp, cp));
common.DebugPrint(" x = %.3f, y = %.3f" % (x, y));
common.DebugPrint(" Xq[r, c] = %.3f, Yq[r, c] = %.3f" % \
(Xq[r, c], Yq[r, c]));
#sys.stdout.flush();
"""
if (x == 0.0) and (y == 0.0):
val = V[r, c];
else:
"""
common.DebugPrint("interp2(): r = %d, c = %d" % (r, c));
common.DebugPrint(" rp = %d, cp = %d" % (rp, cp));
common.DebugPrint(" x = %.3f, y = %.3f" % (x, y));
"""
try:
"""
f00 = V[rp, cp];
f01 = V[rp + 1, cp];
f10 = V[rp, cp + 1];
f11 = V[rp + 1, cp + 1];
# As said in https://en.wikipedia.org/wiki/Bilinear_interpolation
val = f00 * (1 - x) * (1 - y) + f10 * x * (1 - y) + \
f01 * (1 - x) * y + f11 * x * y;
"""
x1 = 1 - x;
y1 = 1 - y;
val = V[rp, cp] * x1 * y1 + V[rp, cp + 1] * x * y1 + \
V[rp + 1, cp] * x1 * y + V[rp + 1, cp + 1] * x * y;
except:
"""
This portion of code can be executed even
if we checked for out-of-bounds of (x,y).
"""
val = np.nan;
res[r, c] = val;
return res;
def interp2_scipy(V, Xq, Yq, interpolationMethod="linear"):
assert interpolationMethod == "linear";
i] * V.shape[1]] for i in range(V.shape[0])]);
yList = [];
for i in range(V.shape[0]):
yList += [i] * V.shape[1];
#yVals = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]);
xVals = np.array(range(V.shape[1]) * V.shape[0]);
else:
yVals = np.array(range(V.shape[0]));
xVals = np.array(range(V.shape[1]));
f = scipy.interpolate.interp2d(x=xVals, y=yVals, z=V, \
kind="linear", copy=False); # Gives strange errors: "cubic");
# We flatten the query matrices to 1D arrays:
Xqf = np.ravel(Xq);
Yqf = np.ravel(Yq);
if False:
# Copied from scipy\interpolate\fitpack.py
Xqf = np.atleast_1d(Xqf);
Yqf = np.atleast_1d(Yqf);
Xqf,Yqf = map(np.atleast_1d,[Xqf,Yqf]);
if False:
common.DebugPrint("interp2(): xVals = %s" % str(xVals));
common.DebugPrint("interp2(): yVals = %s" % str(yVals));
common.DebugPrint("interp2(): Xqf = %s" % str(Xqf));
common.DebugPrint("interp2(): Xqf.shape = %s" % str(Xqf.shape));
common.DebugPrint("interp2(): len(Xqf.shape) = %s" % str(len(Xqf.shape)));
common.DebugPrint("interp2(): Yqf = %s" % str(Yqf));
common.DebugPrint("interp2(): Yqf.shape = %s" % str(Yqf.shape));
common.DebugPrint("interp2(): len(Yqf.shape) = %s" % str(len(Yqf.shape)));
#zNew = f(Xq, Yq); # ValueError: First two entries should be rank-1 arrays.
if False:
# It is more efficient like this - but the SciPy implementation (v0.11, at least ) has bugsTODO
# Don't understand/see a reason why - I reported to scipy community on forum
zNew = f(Xqf, Yqf);
else:
zNew = np.zeros( V.shape );
numRows, numCols = V.shape;
r =0; c = 0;
for i in range(len(Xqf)):
zNew[r, c] = f(Xqf[i], Yqf[i]);
c += 1;
if c == numCols:
r += 1;
c = 0;
erp2_OpenCV(V, Xq, Yq, interpolationMethod="linear"):
assert interpolationMethod == "linear";
;
The function remap supposes that you're working on exactly the grid where
f is defined so no need to pass the x,y monotonic coordinates.
I'm almost sure that the matrices cannot be CV_64F (double) so, take that
into account.>>
Alex: VERY GOOD explanation:
<<interp2 is interpolator - if you get x,y and f values for some mesh
it gives you the value f2 for x2 and y2.
remap - wraps your mesh by moving x and y coordinates acording to the
deformation maps.
if you want interpolate regular mesh then use scaling (cv::resize for example).
If data is scattered then you can use Delaunay triangulation and then
barycentric interpolation as variant or inverse distance weighting.>>
"""
#OpenCV Error: Assertion failed (ifunc != 0) in unknown function, file ..\..\..\src\opencv\modules\imgproc\src\imgwarp.cpp, line 2973
# error: ..\..\..\src\opencv\modules\imgproc\src\imgwarp.cpp:2973: error: (-215) ifunc != 0
V = V.astype(float);
#Xq = cv.fromarray(Xq);
#Yq = cv.fromarray(Yq);
#Xq = Xq.astype(float);
#Yq = Yq.astype(float);
common.DebugPrint("cv2.INTER_LINEAR = %s" % str(cv2.INTER_LINEAR));
# Inspired from https://stackoverflow.com/questions/12535715/set-type-for-fromarray-in-opencv-for-python
r, c = Xq.shape[0], Xq.shape[1];
Xq_32FC1 = cv.CreateMat(r, c, cv.CV_32FC1);
cv.Convert(cv.fromarray(Xq), Xq_32FC1);
r, c = Yq.shape[0], Yq.shape[1];
Yq_32FC1 = cv.CreateMat(r, c, cv.CV_32FC1);
cv.Convert(cv.fromarray(Yq), Yq_32FC1);
if common.MY_DEBUG_STDOUT:
common.DebugPrint("interp2_OpenCV(): Xq_32FC1 = %s" % str(ConvertCvMatToNPArray(Xq_32FC1)));
common.DebugPrint("interp2_OpenCV(): Yq_32FC1 = %s" % str(ConvertCvMatToNPArray(Yq_32FC1)));
"""
From http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=remap#remap
cv2.remap(src, map1, map2, interpolation[, dst[, borderMode[, borderValue ] ] ])
"""
"""
Gives error:
OpenCV Error: Assertion failed (((map1.type() == CV_32FC2 || map1.type() == CV_16SC2) && !map2.data) || (map1.type() == CV_32FC1
&& map2.type() == CV_32FC1)) in unknown function, file ..\..\..\src\opencv\modules\imgproc\src\imgwarp.cpp, line 2988
dst = cv2.remap(src=V, map1=Xq, map2=Yq, interpolation=cv2.INTER_LINEAR);
"""
# Gives error: TypeError: map1 is not a numpy array, neither a scalar
#dst = cv2.remap(src=V, map1=Xq_32FC1, map2=Xq_32FC1, interpolation=cv2.INTER_LINEAR);
# From http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=remap#remap
dst = cv.fromarray(V.copy());
cv.Remap(src=cv.fromarray(V), dst=dst, \
mapx=Xq_32FC1, mapy=Yq_32FC1, \
flags=cv.CV_INTER_LINEAR); #CV_INTER_NN, CV_INTER_AREA, CV_INTER_CUBIC
if False:
dst = cv.fromarray(V.copy());
"""
Gives error:
OpenCV Error: Assertion failed (((map1.type() == CV_32FC2 || map1.type() == CV_16SC2) && !map2.data) || (map1.type() == CV_32FC1
&& map2.type() == CV_32FC1)) in unknown function, file ..\..\..\src\opencv\modules\imgproc\src\imgwarp.cpp, line 2988
"""
# From http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=remap#remap
cv.Remap(src=cv.fromarray(V), dst=dst, \
mapx=cv.fromarray(Xq), mapy=cv.fromarray(Yq), \
flags=cv.CV_INTER_LINEAR); #flags=CV_INNER_LINEAR+CV_WARP_FILL_OUTLIERS, fillval=(0, 0, 0, 0))
return dst;
###############################################################################
###############################################################################
###############################################################################
###############################################################################
"""
# From Matlab help (also http://www.mathworks.com/help/images/ref/imresize.html) :
B = imresize(A, scale) returns image B that is scale times
the size of A. The input image A can be a grayscale, RGB, or binary image. If scale is
between 0 and 1.0, B is smaller than A.
If scale is greater than 1.0, B is larger than A.
B = imresize(A, [numrows numcols]) returns
image B that has the number of rows and columns
specified by [numrows numcols]. Either numrows or numcols may
be NaN, in which case imresize computes
the number of rows or columns automatically to preserve the image
aspect ratio.
Options:
- 'nearest' Nearest-neighbor interpolation; the output pixel is assigned
the value of the pixel that the point falls within. No other pixels
are considered.
- 'bicubic' Bicubic interpolation (the default); the output pixel
value is a weighted average of pixels in the nearest 4-by-4 neighborhood
Example of standard imresize() in Matlab:
Trial>> img=ones(240, 320);
Trial>> img(92,192) = 0;
Trial>> res=imresize(img, [11, 11]) % this is default, bicubic interpolation
res(3,7)=1.0001
res(4,7)=0.9995
res(5,7)=0.9987
res(6,7)=1.0001
res(5,8)=0.9999
all other elems of res are 1.0000
What is surprising is that in this case, instead of let's say having
res(4,7) = 0.99 and the rest 1, we have like above.
This could indicate that because of antialiasing we have in the original image
a 100x100 stretch to the neighboring 1s influenced due to the 0 at img(92,192).
This is highly unlikely the case, therefore DOES imresize() scale down using
"pyramids", i.e., a few intermediate scale-downs to reach the desired
destination size?
Trial>> res=imresize(img, [11, 11], 'bilinear')
res(4,7)=0.9996
res(5,7)=0.9990
res(5,8)=0.9999
all other elems of res are 1.0000
Trial>> res=imresize(img, [11, 11], 'nearest')
all elems of res are 1
"""
def imresize(A, scale=None, newSize=None, interpolationMethod=cv2.INTER_CUBIC):
assert (scale != None) or (newSize != None);
assert not ((scale != None) and (newSize != None));
common.DebugPrint("Entered imresize(A.shape=%s, scale=%s, newSize=%s)" % \
(str(A.shape), str(scale), str(newSize)));
if scale != None:
newSize = (int(A.shape[0] * scale), int(A.shape[1] * scale));
newSize = (newSize[1], newSize[0]);
"""
NOTE: the image returned by cv2.resize after INTER_CUBIC contains slightly
different results compared to Matlab's imresize(, 'bicubic').
# From http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html#resize
cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation ]]]]) -> dst
interpolation - interpolation method:
- INTER_NEAREST - a nearest-neighbor interpolation
- INTER_LINEAR - a bilinear interpolation (used by default)
- INTER_AREA - resampling using pixel area relation.
It may be a preferred method for image decimation,
as it gives moire'-free results. But when the image is zoomed,
it is similar to the INTER_NEAREST method.
- INTER_CUBIC - a bicubic interpolation over 4x4 pixel neighborhood
- INTER_LANCZOS4 - a Lanczos interpolation over 8x8 pixel neighborhood
"""
if True:
"""
NOTE:
From http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.html
"Scaling is just resizing of the image.
OpenCV comes with a function cv2.resize() for this purpose.
The size of the image can be specified manually,
or you can specify the scaling factor.
Different interpolation methods are used.
Preferable interpolation methods are cv2.INTER_AREA for shrinking and
cv2.INTER_CUBIC (slow) & cv2.INTER_LINEAR for zooming.
By default, interpolation method used is cv2.INTER_LINEAR for all
resizing purposes."
"""
if newSize[0] >= A.shape[0]:
"""
common.DebugPrint("imresize(): issue - A.shape=%s, newSize=%s" % \
(str(A.shape), newSize));
"""
res = cv2.resize(A, newSize, interpolation=cv2.INTER_LINEAR);
else:
"""
This is a ~bit equivalent with Matlab's imresize w.r.t. antialiasing:
- even for 1 pixel 0 surrounded only by 1s, when we reduce
the image, that 0 contributes a bit to the result of resize()
in only a pixel (not a square of pixels like in Matlab).
See test_OpenCV.py for behavior of resize(..., INTER_AREA)
"""
res = cv2.resize(A, newSize, interpolation=cv2.INTER_AREA);
else:
"""
NOTE: As said above INTER_CUBIC interp. method is slow and does not do
anti-aliasing at all (while Matlab's imresize does antialiasing).
"""
res = cv2.resize(A, newSize, interpolation=interpolationMethod);
return res;
"""
From Matlab help (http://www.mathworks.com/help/matlab/ref/hist.html):
"hist(data) creates a histogram bar plot of data.
Elements in data are sorted into 10 equally spaced bins along the x-axis
between the minimum and maximum values of data."
"hist(data,xvalues) uses the values in vector xvalues to determine the bin
intervals and sorts data into the number of bins
determined by length(xvalues). To specify the bin
centers, set xvalues equal to a vector of evenly
spaced values. The first and last bins extend to cover the minimum
and maximum values in data."
"nelements = hist(___) returns a row vector, nelements, indicating the number of elements in each bin."
"""
"""
From https://stackoverflow.com/questions/18065951/why-does-numpy-histogram-python-leave-off-one-element-as-compared-to-hist-in-m:
<<Note that in matlab's hist(x, vec), vec difines the bin-centers, while in
matlab histc(x, vec) vec defines the bin-edges of the histogram.
Numpy's histogram seems to work with bin-edges.
Is this difference important to you?
It should be easy to convert from one to the other, and you might have to
add an extra Inf to the end of the bin-edges to get it to return the
extra bin you want.
More or less like this (untested):
For sure it does not cover all the edge-cases that matlab's hist provides,
but you get the idea.>>
"""
def hist(x, binCenters):
#!!!!TODO: verify if it covers all the edge-cases that matlab's hist provides
binEdges = np.r_[-np.Inf, 0.5 * (binCenters[:-1] + binCenters[1:]), np.Inf]
counts, edges = np.histogram(x, binEdges)
return counts
def kron(A, B):
"""
From Matlab help:
kron
Kronecker tensor product
K = kron(A,B)
example
Description
example
K = kron(A,B)
returns the Kronecker tensor product of matrices A and B.
If A is an m-by-n matrix
and B is a p-by-q matrix,
then kron(A,B) is an m*p-by-n*q matrix
formed by taking all possible products between the elements of A and
the matrix B.
% KRON(X,Y) is the Kronecker tensor product of X and Y.
% The result is a large matrix formed by taking all possible
% products between the elements of X and those of Y. For
% example, if X is 2 by 3, then KRON(X,Y) is
%
% [ X(1,1)*Y X(1,2)*Y X(1,3)*Y
% X(2,1)*Y X(2,2)*Y X(2,3)*Y ]
%
% If either X or Y is sparse, only nonzero elements are multiplied
% in the computation, and the result is sparse.
"""
res = np.kron(A, B);
"""
Note: it seems that np.kron might be failing to compute exactly what
Matlab kron() computes.
See https://stackoverflow.com/questions/17035767/kronecker-product-in-python-and-matlab.
Following https://stackoverflow.com/questions/17035767/kronecker-product-in-python-and-matlab
we can get the right result.??
# See http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.kron.html
res = scipy.sparse.kron(A, B);
"""
return res;
"""
Matlab unique from http://www.mathworks.com/help/matlab/ref/unique.html:
C = unique(A) returns the same data as in A, but with no repetitions.
If A is a numeric array, logical array, character array, categorical array, or a cell array of strings, then unique returns the unique values in A. The values of C are in sorted order.
If A is a table, then unique returns the unique rows in A. The rows of table C are in sorted order.
example
C = unique(A,'rows') treats each row of A as a single entity and returns the unique rows of A. The rows of the array C are in sorted order.
The 'rows' option does not support cell arrays.
[C,ia,ic] = unique(A) also returns index vectors ia and ic.
If A is a numeric array, logical array, character array, categorical array, or a cell array of strings, then C = A(ia) and A = C(ic).
If A is a table, then C = A(ia,:) and A = C(ic,:).
[C,ia,ic] = unique(A,'rows') also returns index vectors ia and ic, such that C = A(ia,:) and A = C(ic,:).
"""
def unique(c2):
c2lSorted = [];
for i, e in enumerate(c2l):
e.append(i);
c2lSorted.append(e);
c2lSorted.sort();
c2lSortedIndex = [];
for e in c2lSorted:
c2lSortedIndex.append(e[2]);
"""
np.argsort() is a crappy function in the end...
Unfortunately I don't understand the output of np.argsort() when a is
bi/multi-dimensional... - and it's not my fault - see
http://stackoverflow.com/questions/12496531/sort-numpy-float-array-column-by-column
and http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html
"""
if False:
c2i = np.argsort(a=c2, axis=0, kind="quicksort");
assert len(c2i) == len(c2);
if common.MY_DEBUG_STDOUT:
common.DebugPrint("unique(): c2i = %s" % str(c2i));
c2i = c2i[:, 0];
c2i = np.array(c2lSortedIndex);
try:
c2 = c2[c2i];
except:
return np.array([]), np.array([]);
c2F = [];
c2iF = [];
row = 0;
while row < c2i.size:
c2F.append(c2[row].tolist());
c2iF.append(c2i[row]);
if row + 1 < c2i.size:
rowCrt = row + 1;
while rowCrt < c2i.size:
"""
# This comparison is NOT general - it assumes
# np.dims(c2) == (X, 2).
if (c2[row][0] == c2[rowCrt][0]) and \
(c2[row][1] == c2[rowCrt][1]):
"""
"""
Test that the 2 rows are identical
(each pair of corresponding elements are equal)
"""
if (c2[row] == c2[rowCrt]).all():
pass;
else:
break;
rowCrt += 1;
row = rowCrt;
else:
row += 1;
"""
#for row in range(c2i.size - 1):
while row < c2i.size:
#print "row = %d" % row
if row == c2i.size - 1:
c2F.append(c2[row].tolist());
c2iF.append(c2i[row]);
for rowCrt in range(row + 1, c2i.size):
#print "rowCrt = %d" % rowCrt
if (c2[row][0] == c2[rowCrt][0]) and \
(c2[row][1] == c2[rowCrt][1]):
row += 1;
pass;
else:
c2F.append(c2[row].tolist());
c2iF.append(c2i[row]);
#rowFirst += 1;
break
row += 1;
"""
c2F = np.array(c2F);
c2iF = np.array(c2iF);
return c2F, c2iF;
def hamming(N):
"""
Alex: replaced Matlab "Signal Processing Toolbox"'s hamming() with my own
simple definition - inspired from
http://www.mathworks.com/matlabcentral/newsreader/view_thread/102510
"""
t = np.array( range(N) )
b = np.zeros( (N) )
if N == 0:
return b;
elif N == 1:
b[0] = 1;
return b;
#print "hamming(): b.shape = %s" % str(b.shape);
#print "hamming(): t.shape = %s" % str(t.shape);
#b[t] = 0.54 - 0.46 * math.cos(2 * math.pi * (t - 1) / (N - 1));
b[t] = 0.54 - 0.46 * np.cos(2 * math.pi * t / float(N - 1));
return b;
"""
h is a vector... - see use below filter2(b, ...)
From Matlab help:
Syntax
Y = filter2(h,X)
Y = filter2(h,X,shape)
Description
Y = filter2(h,X) filters
the data in X with the two-dimensional FIR filter
in the matrix h. It computes the result, Y,
using two-dimensional correlation, and returns the central part of
the correlation that is the same size as X.Y = filter2(h,X,shape) returns
the part of Y specified by the shape parameter. shape is
a string with one of these values:
Given a matrix X and a two-dimensional FIR
filter h, filter2 rotates
your filter matrix 180 degrees to create a convolution kernel. It
then calls conv2, the two-dimensional convolution
function, to implement the filtering operation.filter2 uses conv2 to
compute the full two-dimensional convolution of the FIR filter with
the input matrix. By default, filter2 then extracts
the central part of the convolution that is the same size as the input
matrix, and returns this as the result. If the shape parameter
specifies an alternate part of the convolution for the result, filter2 returns
the appropriate part.
"""
# https://stackoverflow.com/questions/16278938/convert-matlab-to-opencv-in-python
def filter2(window, src):
assert len(window.shape) == 1
# In certain cases it's unusual that we have a window that is 1D and x is 2D
jor order, so we need to transpose the matrices
Doing so we obtain the right values at the 4 borders.
"""
src = src.T;
#window = window.T
# Note: CvPoint is (x, y)
res = cv2.filter2D(src=src, ddepth=-1, kernel=window, anchor=(-1, -1), \
borderType=cv2.BORDER_ISOLATED); #BORDER_DEFAULT) #BORDER_CONSTANT) #cv2.BORDER_TRANSPARENT)
res = res.T;
if False:
# Alex's implementation following http://docs.opencv.org/modules/imgproc/doc/filtering.html
dst = np.zeros( (src.shape[0], src.shape[1]), dtype=np.float64);
for y in range(src.shape[1]):
for x in range(src.shape[0]):
for xp in range(window.shape[0]):
"""
if (y >= src.shape[0]) or (x + xp - 1 >= src.shape[1]) or \
(x + xp - 1 < 0):
"""
if (y >= src.shape[1]) or (x + xp - 1 >= src.shape[0]) or \
(x + xp - 1 < 0):
pass;
else:
dst[x, y] += window[xp] * src[x + xp - 1, y];
res = dst;
return res;
"""
"""
if False:
range1 = src.shape[0] - window.shape[0] + 1;
range2 = src.shape[1] - window.shape[0] + 1;
if range2 < 0:
range2 = 1;
res = np.zeros((range1, range2), dtype=np.float64);
for i in range(range1):
for j in range(range2):
res[i, j] = np.sum( \
np.multiply(src[i: window.shape[0] + i, j: window.shape[0] + j], window));
if False:
x1 = np.lib.stride_tricks.as_strided(x, \
((src.shape[0] - 10) / 1, (src.shape[1] - 10) / 1, 11, 11), \
(src.strides[0] * 1, src.strides[1] * 1, \
src.strides[0], src.strides[1])) * window;
res = x1.sum((2, 3));
return res;
def gradient(img, spaceX=1, spaceY=1, spaceZ=1):
assert (img.ndim == 2) or (img.ndim == 3);
"""
From Matlab help:
Description:
FX = gradient(F), where F is
a vector, returns the one-dimensional numerical gradient of F.
Here FX corresponds to deltaF/deltax,
the differences in x (horizontal) direction. [FX,FY] = gradient(F),
where F is a matrix, returns the x and y components
of the two-dimensional numerical gradient. FX corresponds
to deltaF/deltax, the
differences in x (horizontal) direction. FY corresponds
to deltaF/deltay, the
differences in the y (vertical) direction. The
spacing between points in each direction is assumed to be one.
[FX,FY,FZ,...] = gradient(F),
where F has N dimensions, returns
the N components of the gradient of F.
There are two ways to control the spacing between values in F:
A single spacing value, h, specifies
the spacing between points in every direction.
N spacing values (h1,h2,...)
specifies the spacing for each dimension of F.
Scalar spacing parameters specify a constant spacing for each dimension.
Vector parameters specify the coordinates of the values along corresponding
dimensions of F. In this case, the length of the
vector must match the size of the corresponding dimension.
Note:
The first output FX is always the gradient
along the 2nd dimension of F, going across columns.
The second output FY is always the gradient along
the 1st dimension of F, going across rows. For
the third output FZ and the outputs that follow,
the Nth output is the gradient along the Nth dimension of F.
[...] = gradient(F,h1,h2,...) with N spacing
parameters specifies the spacing for each dimension of F.
"""
"""
The best documentation is at:
http://answers.opencv.org/question/16422/matlab-gradient-to-c/
Note: There they mention also
#!!!!See also
http://stackoverflow.com/questions/17977936/matlab-gradient-equivalent-in-opencv
http://stackoverflow.com/questions/9964340/how-to-extract-numerical-gradient-matrix-from-the-image-matrix-in-opencv
http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_gradients/py_gradients.html
"""
"""
!!!!TODO: try to implement a ~different gradient using OpenCV's Sobel,
or other parallelizable function - I think gradient() will be a hotspot
of the application.
"""
if False:
# From http://answers.opencv.org/question/16422/matlab-gradient-to-c/
"""
Result is VERY wrong compared to Matlab's x,y = gradient.
"""
sobelx = cv2.Sobel(src=img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=5);
sobely = cv2.Sobel(src=img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=5);
print "sobelx = %s" % str(sobelx);
print "sobely = %s" % str(sobely);
if False:
grad_x = cv2.Sobel(src=img, ddepth=cv2.CV_64F, dx=1, dy=0);
= cv2.convertScaleAbs(src=grad_x);
grad_y = cv2.Sobel(src=img, ddepth=cv2.CV_64F, dx=0, dy=1);
abs_grad_y = cv2.convertScaleAbs(src=grad_y);
grad = cv2.addWeighted(src1=abs_grad_x, alpha=0.5, src2=abs_grad_y, beta=0.5, gamma=0.0);
print "grad = %s" % str(grad);
def gradientX(mat, spacing):
grad = np.zeros( (mat.shape[0], mat.shape[1]), dtype=mat.dtype );
maxRows, maxCols = mat.shape;
col = (-mat[:, 0] + mat[:, 1]) / float(spacing);
(-mat[:, maxCols - 2] + mat[:, maxCols - 1]) / float(spacing);
centeredMat = mat[0: maxRows, 0: maxCols - 2];
offsetMat = mat[0:maxRows, 2: maxCols];
resultCenteredMat = (-centeredMat + offsetMat) / (float(spacing) * 2.0);
grad[0: maxRows, 1: maxCols - 1] = resultCenteredMat;
return grad;
def gradientY(mat, spacing):
grad = np.zeros( (mat.shape[0], mat.shape[1]), dtype=mat.dtype );
maxRows, maxCols = mat.shape;
row = (-mat[0, :] + mat[1, :]) / float(spacing);
OUT:
common.DebugPrint("gradientY(): spacing = %s" % str(spacing));
common.DebugPrint("grad[0: 1, 0: maxCols].shape = %s" % str(grad[0: 1, 0: maxCols].shape));
common.DebugPrint("row.shape = %s" % str(row.shape));
common.DebugPrint("row = %s" % str(row));
row = (-mat[maxRows - 2, :] + mat[maxRows - 1, :]) / float(spacing);
grad[maxRows - 1: maxRows, 0: maxCols] = row;
centeredMat = mat[0: maxRows - 2, 0: maxCols];
offsetMat = mat[2: maxRows, 0: maxCols];
resultCenteredMat = (-centeredMat + offsetMat) / (float(spacing) * 2.0);
grad[1: maxRows - 1, 0: maxCols] = resultCenteredMat;
return grad;
def gradientZ(mat, indexZ, spacing, grad):
"""
Since we know we have a 3D array we work on planes (2d subelements),
not on 1D elements (rows and columns).
"""
if common.MY_DEBUG_STDOUT:
common.DebugPrint("Entered gradientZ(indexZ=%d)" % indexZ);
maxRows, maxCols, maxZs = mat.shape;
plane = (-mat[:, :, 0] + mat[:, :, 1]) / float(spacing);
% str(spacing));
common.DebugPrint("grad[0: 1, 0: maxCols].shape = %s" % str(grad[0: 1, 0: maxCols].shape));
common.DebugPrint("row.shape = %s" % str(row.shape));
common.DebugPrint("row = %s" % str(row));
plane = (-mat[:, :, maxZs - 2] + mat[:, :, maxZs - 1]) / float(spacing);
grad[:, :, maxZs - 1] = plane;
centeredMat = mat[:, :, 0: maxZs - 2];
offsetMat = mat[:, :, 2: maxZs];
resultCenteredMat = (-centeredMat + offsetMat) / (float(spacing) * 2.0);
grad[:, :, 1: maxZs - 1] = resultCenteredMat;
return grad;
if img.ndim == 3:
gradX = np.zeros( (img.shape[0], img.shape[1], img.shape[2]), dtype=img.dtype );
gradY = np.zeros( (img.shape[0], img.shape[1], img.shape[2]), dtype=img.dtype );
gradZ = np.zeros( (img.shape[0], img.shape[1], img.shape[2]), dtype=img.dtype );
for i in range(img.shape[2]):
gradX1 = gradientX(img[:, :, i], spaceX);
gradX[:, :, i] = gradX1;
gradY1 = gradientY(img[:, :, i], spaceY);
gradY[:, :, i] = gradY1;
gradientZ(img, i, spaceZ, gradZ);
return (gradX, gradY, gradZ);
gradX = gradientX(img, spaceX);
gradY = gradientY(img, spaceY);
return (gradX, gradY);
def meshgrid(range1, range2):
"""
From http://www.mathworks.com/help/matlab/ref/meshgrid.html:
[X,Y] = meshgrid(xgv,ygv) replicates the grid vectors xgv and ygv
to produce a full grid.
This grid is represented by the output coordinate arrays X and Y.
The output coordinate arrays X and Y contain copies of the grid
vectors xgv and ygv respectively.
The sizes of the output arrays are determined by the length of
the grid vectors. For grid vectors xgv and ygv of length M and N
respectively, X and Y will have N rows and M columns.
Examples
2-D Grid From Vectors
Create a full grid from two monotonically increasing grid vectors:
[X,Y] = meshgrid(1:3,10:14)
X =
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
Y =
10 10 10
11 11 11
12 12 12
13 13 13
14 14 14
"""
x, y = np.meshgrid(range1, range2);
return x, y;
def fspecial(type, p2, p3):
"""
% Alex: the code is taken from the Matlab, (type fspecial)
siz = (p2-1)/2;
std = p3;
% Alex: adapted this, since siz is scalar in our case
%[x,y] = meshgrid(-siz(2):siz(2),-siz(1):siz(1));
[x,y] = meshgrid(-siz:siz,-siz:siz);
arg = -(x.*x + y.*y)/(2*std*std);
h = exp(arg);
h(h<eps*max(h(:))) = 0;
sumh = sum(h(:));
if sumh ~= 0,
h = h/sumh;
end;
"""
assert (type == "gaussian") or (type == "ga");
siz = int((p2 - 1) / 2);
std = p3;
x, y = meshgrid(range(-siz, siz + 1), range(-siz, siz + 1));
arg = -(x * x + y * y) / (2.0 * std * std);
h = np.exp(arg);
h[h < eps() * h.max()] = 0;
sumh = h.sum();
if abs(sumh) > 1.e-6:
h = h / sumh;
return h;
def imfilter(A, H, options=None):
"""
From http://nf.nci.org.au/facilities/software/Matlab/toolbox/images/imfilter.html
imfilter
Multidimensional image filtering
Syntax
B = imfilter(A,H)
B = imfilter(A,H,option1,option2,...)
Description
B = imfilter(A,H) filters the multidimensional array A with the multidimensional filter H.
The array, A, can be a nonsparse numeric array of any class and dimension.
The result, B, has the same size and class as A.
Each element of the output, B, is computed using double-precision floating point.
If A is an integer array, then output elements that exceed the range of
the integer type are truncated, and fractional values are rounded.
B = imfilter(A,H,option1,option2,...) performs multidimensional filtering
according to the specified options. Option arguments can have the
following values.
Boundary Options Option
Description
X
Input array values outside the bounds of the array are implicitly
assumed to have the value X. When no boundary option is specified,
imfilter uses X = 0.
'symmetric'
Input array values outside the bounds of the array are computed by
mirror-reflecting the array across the array border.
'replicate'
Input array values outside the bounds of the array are assumed to
equal the nearest array border value.
'circular'
Input array values outside the bounds of the array are computed by
implicitly assuming the input array is periodic.
Output Size Options Option
Description
'same'
The output array is the same size as the input array.
This is the default behavior when no output size options are specified.
'full'
The output array is the full filtered result, and so is larger than the input array.
"""
"""
Point anchor( 0 ,0 );
double delta = 0;
float data[2][5] = {{11,11,11,11,11},{11,11,11,11,11}};
float kernel[2][2] = {{2,2},{2,2}};
Mat src = Mat(2, 5, CV_32FC1, &data);
Mat ker = Mat(2, 2, CV_32FC1, &kernel);
Mat dst = Mat(src.size(), src.type());
Ptr<FilterEngine> fe = createLinearFilter(src.type(), ker.type(), ker, anchor,
delta, BORDER_CONSTANT, BORDER_CONSTANT, Scalar(0));
fe->apply(src, dst);
cout << dst << endl;
"""
"""
See
https://stackoverflow.com/questions/18628373/imfilter-equivalent-in-opencv
http://answers.opencv.org/question/20785/replicate-with-mask-in-opencv/
<<The kernel is the "mask" that i want to move in the convolution and the "anchor" is the middle of this matrix. CvType.CV_32FC1 means that the values inside the result matrix could be also negative, and "BORDER_REPLICATE" just fill the edge with zeroes.>>
(not relevant: https://stackoverflow.com/questions/18628373/imfilter-equivalent-in-opencv )
"""
"""
# The Matlab code we try to emulate is:
bx = imfilter(gray_image,mask, 'replicate');
"""
"""
Point anchor(0, 0);
float delta = 0.0;
cv::filter2D(gray_img, bx, CV_32FC1, mask, anchor, delta, BORDER_REPLICATE);
"""
"""
From http://docs.opencv.org/modules/imgproc/doc/filtering.html#filter2d :
Convolves an image with the kernel.
Parameters:
kernel - convolution kernel (or rather a correlation kernel),
a single-channel floating point matrix;
if you want to apply different kernels to different channels,
split the image into separate color planes using split() and
process them individually.
anchor - anchor of the kernel that indicates the relative position of
a filtered point within the kernel;
the anchor should lie within the kernel;
default value (-1,-1) means that the anchor is at the kernel
center.
delta - optional value added to the filtered pixels before storing
them in dst.
borderType - pixel extrapolation method
(see borderInterpolate() for details).
"""
res = cv2.filter2D(src=A, ddepth=-1, kernel=H, anchor=(-1, -1), \
borderType=cv2.BORDER_REPLICATE); ref/bwlabel.html
Label connected components in 2-D binary image
L = bwlabel(BW, n)
[L, num] = bwlabel(BW, n)
Description
L = bwlabel(BW, n) returns a matrix L, of the same size as BW, containing labels for the connected objects in BW. The variable n can have a value of either 4 or 8, where 4 specifies 4-connected objects and 8 specifies 8-connected objects. If the argument is omitted, it defaults to 8.
The elements of L are integer values greater than or equal to 0. The pixels labeled 0 are the background. The pixels labeled 1 make up one object; the pixels labeled 2 make up a second object; and so on.
[L, num] = bwlabel(BW, n) returns in num the number of connected objects found in BW.
The functions bwlabel, bwlabeln, and bwconncomp all compute connected components for binary images. bwconncomp replaces the use of bwlabel and bwlabeln. It uses significantly less memory and is sometimes faster than the other functions.
Create a small binary image to use for this example.
BW = logical ([1 1 1 0 0 0 0 0
1 1 1 0 1 1 0 0
1 1 1 0 1 1 0 0
1 1 1 0 0 0 1 0
1 1 1 0 0 0 1 0
1 1 1 0 0 0 1 0
1 1 1 0 0 1 1 0
1 1 1 0 0 0 0 0]);
Create the label matrix using 4-connected objects.
L = bwlabel(BW,4)
L =
1 1 1 0 0 0 0 0
1 1 1 0 2 2 0 0
1 1 1 0 2 2 0 0
1 1 1 0 0 0 3 0
1 1 1 0 0 0 3 0
1 1 1 0 0 0 3 0
1 1 1 0 0 3 3 0
1 1 1 0 0 0 0 0
Use the find command to get the row and column coordinates of the object labeled "2".
[r, c] = find(L==2);
rc = [r c]
rc =
2 5
3 5
2 6
3 6
"""
"""
From http://stackoverflow.com/questions/20357337/opencv-alternative-for-matlabs-bwlabel
This isn't exactly the same as bwlabel, but may be close enough.
One possible alternative is to use findContours and/or drawContours, as explained in the docs.
"""
# From http://stackoverflow.com/questions/12688524/connected-components-in-opencv
pass;
class TestSuite(unittest.TestCase):
def testUnique1(self):
l = [[1, 2], [1, 3], [1, 2]];
l = np.array(l);
lF, liF = unique(l);
#common.DebugPrint("lF = %s" % str(lF));
#common.DebugPrint("liF = %s" % str(liF));
res = np.array([[1, 2], [1, 3]]);
aZero = res - lF;
resi = np.array([0, 1]);
aZeroi = resi - liF;
# State our expectation
#self.assertTrue(lF == res);
self.assertTrue( (aZero == 0).all() and \
(aZeroi == 0).all())
def testUnique2(self):
l = [[1, 2], [1, 2]];
l = np.array(l);
lF, liF = unique(l);
#common.DebugPrint("lF = %s" % str(lF));
#common.DebugPrint("liF = %s" % str(liF));
res = np.array([[1, 2]]);
aZero = res - lF;
resi = np.array([0]);
aZeroi = resi - liF;
# State our expectation
#self.assertTrue(lF == res);
self.assertTrue( (aZero == 0).all() and \
(aZeroi == 0).all())
def testUnique3(self):
l = [[1, 3], [1, 2], [0, 7], [5, 9], [1, 2], [100, 0], [5, 10]];
l = np.array(l);
lF, liF = unique(l);
#common.DebugPrint("lF = %s" % str(lF));
#common.DebugPrint("liF = %s" % str(liF));
res = np.array([[[0, 7], [1, 2], [1, 3], [5, 9], [5, 10], [100, 0]]]);
aZero = res - lF;
resi = np.array([2, 1, 0, 3, 6, 5]);
aZeroi = resi - liF;
# State our expectation
#self.assertTrue(lF == res);
self.assertTrue( (aZero == 0).all() and \
(aZeroi == 0).all())
#################################################
def testHamming(self):
# Test 1
#print "hamming(11) = %s" % str(hamming(11))
h11 = hamming(11);
#h11 = [ 0.08 0.16785218 0.39785218 0.68214782 0.91214782 1.
# 0.91214782 0.68214782 0.39785218 0.16785218 0.08 ]
h11Good = np.array([0.0800, 0.1679, 0.3979, 0.6821, 0.9121, 1.0000, \
0.9121, 0.6821, 0.3979, 0.1679, 0.0800]);
aZero = h11 - h11Good;
#print "h11 = %s" % str(h11);
#print "aZero = %s" % str(aZero);
#assert (aZero < 1.0e-3).all();
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
h0 = hamming(0);
#print "h0 = %s" % str(h0);
self.assertTrue(h0.size == 0);
h1 = hamming(1);
#print "h1 = %s" % str(h1);
h1Good = np.array([1.0]);
aZero = h1 - h1Good;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
h2 = hamming(2);
#print "h2 = %s" % str(h2);
h2Good = np.array([0.08, 0.08]);
aZero = h2 - h2Good;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
h100 = hamming(100);
#print "h100 = %s" % str(h100);
h100Good = np.array([ \
0.0800, 0.0809, 0.0837, 0.0883, 0.0947, 0.1030, 0.1130, 0.1247, \
0.1380, 0.1530, 0.1696, 0.1876, 0.2071, 0.2279, 0.2499, 0.2732, \
0.2975, 0.3228, 0.3489, 0.3758, 0.4034, 0.4316, 0.4601, 0.4890, \
0.5181, 0.5473, 0.5765, 0.6055, 0.6342, 0.6626, 0.6905, 0.7177, \
0.7443, 0.7700, 0.7948, 0.8186, 0.8412, 0.8627, 0.8828, 0.9016, \
0.9189, 0.9347, 0.9489, 0.9614, 0.9723, 0.9814, 0.9887, 0.9942, \
0.9979, 0.9998, 0.9998, 0.9979, 0.9942, 0.9887, 0.9814, 0.9723, \
0.9614, 0.9489, 0.9347, 0.9189, 0.9016, 0.8828, 0.8627, 0.8412, \
0.8186, 0.7948, 0.7700, 0.7443, 0.7177, 0.6905, 0.6626, 0.6342, \
0.6055, 0.5765, 0.5473, 0.5181, 0.4890, 0.4601, 0.4316, 0.4034, \
0.3758, 0.3489, 0.3228, 0.2975, 0.2732, 0.2499, 0.2279, 0.2071, \
0.1876, 0.1696, 0.1530, 0.1380, 0.1247, 0.1130, 0.1030, 0.0947, \
0.0883, 0.0837, 0.0809, 0.0800]);
aZero = h100 - h100Good;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
def testHammingOld(self):
# Test 1
#print "hamming(11) = %s" % str(hamming(11))
h11 = hamming(11);
#h11 = [ 0.08 0.16785218 0.39785218 0.68214782 0.91214782 1.
# 0.91214782 0.68214782 0.39785218 0.16785218 0.08 ]
h11Good = np.array([0.0800, 0.1679, 0.3979, 0.6821, 0.9121, 1.0000, \
0.9121, 0.6821, 0.3979, 0.1679, 0.0800]);
aZero = h11 - h11Good;
#print "h11 = %s" % str(h11);
#print "aZero = %s" % str(aZero);
#assert (aZero < 1.0e-3).all();
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
def testFilter2(self):
#window = hamming(11)
window = np.array( [1, 2, 4] );
x = np.ones( (23, 8) );
res = filter2(window, x);
#print "filter2(window, x) = %s" % str(res);
resGood = [[6, 7, 7, 7, 7, 7, 7, 3]] * 23;
resGood = np.array(resGood);
aZero = res - resGood;
#assert (aZero == 0).all();
self.assertTrue((aZero == 0).all());
def testHist(self):
print "Entered testHist()."
howMany = [56, 38, 54, 28, 32, 40, 38, 32, 54, 62, 46, 42]
RD_start = 2001
RD_end = 2012
l = []
#for i in range(rd_start, rd_end + 1):
for i in range(RD_end - RD_start + 1):
l += [RD_start + i] * howMany[i]
#common.DebugPrint("l = %s" % str(l))
assert len(l) == 522
l = np.array(l)
rr = np.array(range(RD_start, RD_end + 1))
n_d = [56, 38, 54, 28, 32, 40, 38, 32, 54, 62, 46, 42]
# Test 1
#print "hamming(11) = %s" % str(hamming(11))
res = hist(l, rr);
aZero = res - n_d
#print "h11 = %s" % str(h11)
#print "aZero = %s" % str(aZero)
if False:
assert (aZero == 0).all()
# State our expectation
self.assertTrue((aZero == 0).all())
def testGradient(self):
# Testing bidimensional gradient:
"""
From http://answers.opencv.org/question/16422/matlab-gradient-to-c/
A =
1 3
4 2
[dx dy] = gradient(A, 4, 4)
Output:
dx =
0.5000 0.5000
-0.5000 -0.5000
dy =
0.7500 -0.2500
0.7500 -0.2500
"""
A = np.array([ \
[1.0, 3.0],
[4.0, 2.0]]);
dx, dy = gradient(A, 4, 4);
dxGood = np.array([ \
[0.5000, 0.5000],
[-0.5000, -0.5000]]);
dyGood = np.array([ \
[0.7500, -0.2500],
[0.7500, -0.2500]]);
aZero = dx - dxGood;
#common.DebugPrint("testGradient(): dx = %s" % str(dx));
#common.DebugPrint("testGradient(): aZero = %s" % str(aZero));
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
aZero = dy - dyGood;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
#common.DebugPrint("For A = %s we have the following gradients:" % str(A));
#common.DebugPrint("dx = %s" % str(dx));
#common.DebugPrint("dy = %s" % str(dy));
dx, dy = gradient(A, 1, 1);
"""
The Matlab results are:
dx =
2 2
-2 -2
dy =
3 -1
3 -1
"""
dxGood = np.array([ \
[2, 2],
[-2, -2]]);
dyGood = np.array([ \
[3, -1],
[3, -1]]);
aZero = dx - dxGood;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
aZero = dy - dyGood;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
A = np.array([ \
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]]);
dx, dy = gradient(A, 4, 4);
"""
The Matlab results are:
dx =
0.2500 0.2500 0.2500
0.2500 0.2500 0.2500
0.2500 0.2500 0.2500
dy =
0.7500 0.7500 0.7500
0.7500 0.7500 0.7500
0.7500 0.7500 0.7500
"""
dxGood = np.array([ \
[0.2500, 0.2500, 0.2500],
[0.2500, 0.2500, 0.2500],
[0.2500, 0.2500, 0.2500]]);
dyGood = np.array([ \
[0.7500, 0.7500, 0.7500],
[0.7500, 0.7500, 0.7500],
[0.7500, 0.7500, 0.7500]]);
aZero = dx - dxGood;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
aZero = dy - dyGood;
self.assertTrue((np.abs(aZero) < 1.0e-3).all());
#common.DebugPrint("For A = %s we have the following gradients:" % str(A));
#common.DebugPrint("dx = %s" % str(dx));
#common.DebugPrint("dy = %s" % str(dy));
# Testing threedimensional gradient (for subframe sequences):
A3d = np.zeros( (3, 3, 4) );
for i in range(A3d.shape[2]):
A3d[:, :, i] = A + (i + 1) * np.eye(A3d.shape[0]);
#dx, dy, dz = gradient(A3d, 4, 4, 4);
dx, dy, dz = gradient(A3d, 1, 1, 1);
common.DebugPrint("For A3d = %s we have the following gradients:" % Repr3DMatrix(A3d)); #str(A3d));
#common.DebugPrint("dx = %s" % str(dx));
common.DebugPrint("dx = %s" % Repr3DMatrix(dx));
#common.DebugPrint("dy = %s" % str(dy));
common.DebugPrint("dy = %s" % Repr3DMatrix(dy));
#common.DebugPrint("dz = %s" % str(dz));
common.DebugPrint("dz = %s" % Repr3DMatrix(dz));
"""
The following Matlab program:
A1 = [1 2 3; 4 5 6; 7 8 9];
%A = zeros(3,3,3);
%A(:,:,1) = A1;
%A(:,:,2) = A1;
%A(:,:,3) = A1;
%[vx, vy, vt] = gradient(A);
A = zeros(3,3,4);
A(:,:,1) = A1 + 1*eye(3);
A(:,:,2) = A1 + 2*eye(3);
A(:,:,3) = A1 + 3*eye(3);
A(:,:,4) = A1 + 4*eye(3);
Trial>> [vx, vy, vt] = gradient(A)
vx(:,:,1) =
0 0.5000 1.0000
2.0000 1.0000 0
1.0000 1.5000 2.0000
vx(:,:,2) =
-1 0 1
3 1 -1
1 2 3
vx(:,:,3) =
-2.0000 -0.5000 1.0000
4.0000 1.0000 -2.0000
1.0000 2.5000 4.0000
vx(:,:,4) =
-3 -1 1
5 1 -3
1 3 5
vy(:,:,1) =
2.0000 4.0000 3.0000
2.5000 3.0000 3.5000
3.0000 2.0000 4.0000
vy(:,:,2) =
1 5 3
2 3 4
3 1 5
vy(:,:,3) =
0 6.0000 3.0000
1.5000 3.0000 4.5000
3.0000 0 6.0000
vy(:,:,4) =
-1 7 3
1 3 5
3 -1 7
vt(:,:,1) =
1 0 0
0 1 0
0 0 1
vt(:,:,2) =
1 0 0
0 1 0
0 0 1
vt(:,:,3) =
1 0 0
0 1 0
0 0 1
vt(:,:,4) =
1 0 0
0 1 0
0 0 1
"""
def testMeshgrid(self):
"""
From ...
[X,Y] = meshgrid(1:3,10:14)
X =
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
Y =
10 10 10
11 11 11
12 12 12
13 13 13
14 14 14
"""
resX, resY = meshgrid( range(1, 3 + 1) , range(10, 14 + 1));
goodX = np.array( [ \
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]);
goodY = np.array( [ \
[10, 10, 10],
[11, 11, 11],
[12, 12, 12],
[13, 13, 13],
[14, 14, 14]]);
aZero = resX - goodX;
self.assertTrue((aZero == 0).all());
aZero = resY - goodY;
self.assertTrue((aZero == 0).all());
def testFspecial(self):
# Tests are generated first with Matlab
si = 2.4;
#%p2 = max(1,fix(6*si)+1);
p2 = 15.0;
p3 = si;
res = fspecial("gaussian", p2, p3);
common.DebugPrint("testFspecial(): res.shape = %s" % str(res.shape));
common.DebugPrint("testFspecial(): res = %s" % str(res));
#Result from Matlab:
resGood = np.array([ \
[0.0000, 0.0000, 0.0000, 0.0001, 0.0002, 0.0003, 0.0004, 0.0004,
0.0004, 0.0003, 0.0002, 0.0001, 0.0000, 0.0000, 0.0000],
[0.0000, 0.0001, 0.0001, 0.0003, 0.0006, 0.0009, 0.0011, 0.0012,
0.0011, 0.0009, 0.0006, 0.0003, 0.0001, 0.0001, 0.0000],
[0.0000, 0.0001, 0.0004, 0.0008, 0.0014, 0.0022, 0.0029, 0.0032,
0.0029, 0.0022, 0.0014, 0.0008, 0.0004, 0.0001, 0.0000],
[0.0001, 0.0003, 0.0008, 0.0017, 0.0032, 0.0049, 0.0063, 0.0069,
0.0063, 0.0049, 0.0032, 0.0017, 0.0008, 0.0003, 0.0001],
[0.0002, 0.0006, 0.0014, 0.0032, 0.0058, 0.0090, 0.0116, 0.0127,
0.0116, 0.0090, 0.0058, 0.0032, 0.0014, 0.0006, 0.0002],
[0.0003, 0.0009, 0.0022, 0.0049, 0.0090, 0.0138, 0.0180, 0.0196,
0.0180, 0.0138, 0.0090, 0.0049, 0.0022, 0.0009, 0.0003],
[0.0004, 0.0011, 0.0029, 0.0063, 0.0116, 0.0180, 0.0233, 0.0254,
0.0233, 0.0180, 0.0116, 0.0063, 0.0029, 0.0011, 0.0004],
[0.0004, 0.0012, 0.0032, 0.0069, 0.0127, 0.0196, 0.0254, 0.0277,
0.0254, 0.0196, 0.0127, 0.0069, 0.0032, 0.0012, 0.0004],
[0.0004, 0.0011, 0.0029, 0.0063, 0.0116, 0.0180, 0.0233, 0.0254,
0.0233, 0.0180, 0.0116, 0.0063, 0.0029, 0.0011, 0.0004],
[0.0003, 0.0009, 0.0022, 0.0049, 0.0090, 0.0138, 0.0180, 0.0196,
0.0180, 0.0138, 0.0090, 0.0049, 0.0022, 0.0009, 0.0003],
[0.0002, 0.0006, 0.0014, 0.0032, 0.0058, 0.0090, 0.0116, 0.0127,
0.0116, 0.0090, 0.0058, 0.0032, 0.0014, 0.0006, 0.0002],
[0.0001, 0.0003, 0.0008, 0.0017, 0.0032, 0.0049, 0.0063, 0.0069,
0.0063, 0.0049, 0.0032, 0.0017, 0.0008, 0.0003, 0.0001],
[0.0000, 0.0001, 0.0004, 0.0008, 0.0014, 0.0022, 0.0029, 0.0032,
0.0029, 0.0022, 0.0014, 0.0008, 0.0004, 0.0001, 0.0000],
[0.0000, 0.0001, 0.0001, 0.0003, 0.0006, 0.0009, 0.0011, 0.0012,
0.0011, 0.0009, 0.0006, 0.0003, 0.0001, 0.0001, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0001, 0.0002, 0.0003, 0.0004, 0.0004,
0.0004, 0.0003, 0.0002, 0.0001, 0.0000, 0.0000, 0.0000]]);
aZero = np.abs(res - resGood);
common.DebugPrint("aZero = %s" % str(aZero));
self.assertTrue((aZero < 1e-4).all());
def testImfilter(self):
# Not tested, since not implemented
"""
A = np.array([ \
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]]);
res = imfilter(A, np.array([6])); #imfilter(A, 6, 1);
#common.DebugPrint("res from imfilter() = %s" % str(res));
# This is the result from Matlab
resGood = np.array([ \
[11, 12, 11],
[11, 12, 11],
[11, 12, 11]]);
"""
"""
To test well imfilter use a filter, as given in ecc_homo_spacetime.imgaussian():
H = np.exp(-(x ** 2 / (2.0 * pow(sigma, 2))));
H = H / H[:].sum();
Hx = H.reshape( (H.size, 1) );
res = imfilter(I, Hx, "same", "replicate");
"""
A = np.array( [ \
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]);
res = imfilter(np.ones((4, 4)), A, 'replicate');
resGood = 45 * np.ones((4, 4));
aZero = np.abs(res - resGood);
#common.DebugPrint("aZero = %s" % str(aZero));
self.assertTrue((aZero < 1e-4).all());
B = np.array( [ \
[1, 2],
[3, 4]]);
res = imfilter(np.ones((4, 4)), B, 'replicate');
#common.DebugPrint("testImfilter(): res = %s" % str(res));
resGood = np.array([ \
[10, 10, 10, 10],
[10, 10, 10, 10],
[10, 10, 10, 10],
[10, 10, 10, 10]]);
aZero = np.abs(res - resGood);
#common.DebugPrint("aZero = %s" % str(aZero));
self.assertTrue((aZero < 1e-4).all());
C = np.array( [ \
[1, 2],
[2, 1]]);
res = imfilter(np.ones((5, 5)), C, 'replicate');
#common.DebugPrint("testImfilter(): res = %s" % str(res));
resGood = np.array([ \
[6, 6, 6, 6, 6],
[6, 6, 6, 6, 6],
[6, 6, 6, 6, 6],
[6, 6, 6, 6, 6],
[6, 6, 6, 6, 6]]);
aZero = np.abs(res - resGood);
#common.DebugPrint("aZero = %s" % str(aZero));
self.assertTrue((aZero < 1e-4).all());
def testInterp2(self):
"""
V = np.array( [ \
[ 2, 8, 6],
[ 8, 10, 12],
[14, 16, 18]]);
"""
if False:
V = np.array( [ \
[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]]);
V = np.array( [ \
[ 1, 5, 3],
[ 4, 7, 6],
[ 7, 10, 9]]);
V = V.astype(np.float64);
#if False:
if True:
# Testing out of bound
Xq = np.array( [ \
[ 1.7, 2.7, 3.7],
[ 1.4, 2.5, 3],
[ 1, 2, 3]]);
else:
# Testing element coordinates not "in its square" - elem [0,2]
Xq = np.array( [ \
[ 1.7, 2.7, 2.9],
[ 1.4, 2.5, 3],
[ 1, 2, 3]]);
Yq = np.array( [ \
[ 1.3, 1, 1],
[ 2, 2, 2],
[ 3, 3, 3]]);
Xq -= 1; # In Python we start from index 0
Yq -= 1; # In Python we start from index 0
itype = "linear";
# interp2_nested_loops() is deemed to be correct
Xq = Xq.astype(np.float64);
Yq = Yq.astype(np.float64);
#res = interp2_nested_loops(V, Xq, Yq, itype);
res = interp2(V, Xq, Yq, itype);
#if False:
if True:
if False:
# For the (nonfunctioning) implementation with cv.remap()
common.DebugPrint("interp2() returned %s" % str(ConvertCvMatToNPArray(res)));
else:
common.DebugPrint("interp2() returned %s" % str(res));
goodRes = np.array( [ \
[ 4.49, 3.6, np.nan],
[ 5.2 , 6.5, 6. ],
[ 7. , 10., 9. ]]);
"""
#common.DebugPrint("interp2() returned %s" % str(dir(res)));
for r in range(res.rows):
for c in range(res.cols):
# NOT GOOD: common.DebugPrint("%.5f " % res[r][c][0]),
#common.DebugPrint("%.5f " % res.__getitem__((r, c))),
common.DebugPrint("%.5f " % res[r, c]),
pass
print
#common.DebugPrint("interp2() returned %s" % str(res.tostring())); # Prints binary data...
"""
aZero = res - goodRes;
#common.DebugPrint("interp2() returned %s" % str(aZero));
self.assertTrue(np.isnan(res[0, 2]) and np.isnan(goodRes[0, 2]));
aZero[0, 2] = 0.0;
self.assertTrue((np.abs(aZero) < 1.e-5).all());
res = interp2(V, Xq, Yq, itype);
"""
This is one (~small) test that my BAD vectorized interp2()
implementation failed.
"""
V = np.array([ \
[ 138., 131., 123., 118., 121., 130., 142., 150., 142., 142.],
[ 109., 75., 43., 45., 80., 115., 128., 126., 142., 142.],
[ 136., 142., 146., 146., 142., 139., 142., 145., 142., 142.],
[ 130., 135., 140., 143., 142., 140., 140., 140., 142., 142.],
[ 133., 124., 117., 122., 136., 147., 150., 147., 142., 142.],
[ 130., 144., 157., 154., 142., 132., 132., 138., 142., 142.],
[ 137., 143., 147., 143., 135., 132., 138., 146., 142., 142.],
[ 142., 144., 144., 137., 130., 131., 140., 150., 142., 142.],
[ 143., 143., 143., 143., 143., 143., 143., 143., 143., 143.],
[ 143., 143., 143., 143., 143., 143., 143., 143., 143., 143.]]);
Xq = np.array([ \
[ 0.6977, 1.6883, 2.679, 3.6698, 4.6606, 5.6515, 6.6424, 7.6334, 8.6245, 9.6156],
[ 0.6951, 1.6857, 2.6764, 3.6672, 4.658, 5.6488, 6.6398, 7.6308, 8.6218, 9.6129],
[ 0.6925, 1.6831, 2.6738, 3.6645, 4.6553, 5.6462, 6.6371, 7.6281, 8.6191, 9.6102],
[ 0.6899, 1.6805, 2.6712, 3.6619, 4.6527, 5.6436, 6.6345, 7.6254, 8.6165, 9.6076],
[ 0.6872, 1.6779, 2.6685, 3.6593, 4.6501, 5.6409, 6.6318, 7.6228, 8.6138, 9.6049],
[ 0.6846, 1.6752, 2.6659, 3.6566, 4.6474, 5.6383, 6.6292, 7.6201, 8.6111, 9.6022],
[ 0.682, 1.6726, 2.6633, 3.654, 4.6448, 5.6356, 6.6265, 7.6175, 8.6085, 9.5995],
[ 0.6794, 1.67, 2.6607, 3.6514, 4.6422, 5.633, 6.6239, 7.6148, 8.6058, 9.5969],
[ 0.6768, 1.6674, 2.6581, 3.6488, 4.6395, 5.6303, 6.6212, 7.6121, 8.6031, 9.5942],
[ 0.6742, 1.6648, 2.6554, 3.6461, 4.6369, 5.6277, 6.6186, 7.6095, 8.6005, 9.5915]]);
Yq = np.array([ \
[ 0.0144, 0.0115, 0.0086, 0.0057, 0.0027,-0.0002,-0.0031,-0.006, -0.0089,-0.0119],
[ 1.0134, 1.0105, 1.0076, 1.0048, 1.0019, 0.999, 0.9961, 0.9932, 0.9903, 0.9874],
[ 2.0124, 2.0096, 2.0067, 2.0038, 2.001, 1.9981, 1.9953, 1.9924, 1.9895, 1.9867],
[ 3.0114, 3.0086, 3.0057, 3.0029, 3.0001, 2.9972, 2.9944, 2.9916, 2.9888, 2.9859],
[ 4.0104, 4.0076, 4.0048, 4.002, 3.9992, 3.9964, 3.9936, 3.9908, 3.988, 3.9852],
[ 5.0093, 5.0065, 5.0038, 5.001, 4.9982, 4.9955, 4.9927, 4.9899, 4.9871, 4.9844],
[ 6.0082, 6.0055, 6.0028, 6., 5.9973, 5.9945, 5.9918, 5.9891, 5.9863, 5.9836],
[ 7.0072, 7.0045, 7.0017, 6.999, 6.9963, 6.9936, 6.9909, 6.9882, 6.9855, 6.9827],
[ 8.0061, 8.0034, 8.0007, 7.998, 7.9953, 7.9927, 7.99, 7.9873, 7.9846, 7.9819],
[ 9.005, 9.0023, 8.9997, 8.997, 8.9943, 8.9917, 8.989, 8.9864, 8.9837, 8.9811]]);
if False:
# Measuring the performance of interp2().
t1 = float(cv2.getTickCount());
for i in range(10000):
interp2(V, Xq, Yq, itype);
t2 = float(cv2.getTickCount());
myTime = (t2 - t1) / cv2.getTickFrequency();
common.DebugPrint("testInterp2(): interp2() " \
"took %.6f [sec]" % myTime);
# IMPORTANT test
if True:
#V1 = np.empty();
V = imresize(V, scale=100);
Xq = imresize(Xq, scale=100);
Yq = imresize(Yq, scale=100);
res = interp2(V, Xq, Yq, itype);
#common.DebugPrint("interp2() returned %s" % str(res));
resGood = interp2_vectorized(V, Xq, Yq, itype);
#common.DebugPrint("interp2_vectorized() returned %s" % str(res));
self.assertTrue(CompareMatricesWithNanElements(res, resGood));
if False: # These are just performance tests (compare times of running unit-tests)
V = np.zeros( (1920, 1080) );
Xq = np.zeros( (1920, 1080) );
Yq = np.zeros( (1920, 1080) );
res = interp2(V, Xq, Yq, itype);
res = interp2(V, Xq, Yq, itype);
res = interp2_vectorized(V, Xq, Yq, itype);
res = interp2_vectorized(V, Xq, Yq, itype);
def testKron(self):
# Taken from the Matlab help:
A = np.eye(4);
B = np.array([[1, -1], [-1, 1]]);
res = kron(A, B);
resGood = np.array( [ \
[ 1, -1, 0, 0, 0, 0, 0, 0],
[-1, 1, 0, 0, 0, 0, 0, 0],
[ 0, 0, 1, -1, 0, 0, 0, 0],
[ 0, 0, -1, 1, 0, 0, 0, 0],
[ 0, 0, 0, 0, 1, -1, 0, 0],
[ 0, 0, 0, 0, -1, 1, 0, 0],
[ 0, 0, 0, 0, 0, 0, 1, -1],
[ 0, 0, 0, 0, 0, 0, -1, 1]]);
aZero = res - resGood;
self.assertTrue((aZero == 0).all());
A = np.array( [[1, 2, 3], [4, 5, 6]] );
#A = np.r_[np.array([1, 2, 3]), np.array([4, 5, 6])];
#A = np.ravel(A);
B = np.ones( (2, 2) );
#common.DebugPrint("testKron(): B = %s[END]" % str(B));
#common.DebugPrint("testKron(): B.shape = %s[END]" % str(B.shape));
res = np.kron(A, B);
resGood = np.array( [ \
[1, 1, 2, 2, 3, 3],
[1, 1, 2, 2, 3, 3],
[4, 4, 5, 5, 6, 6],
[4, 4, 5, 5, 6, 6]] );
#common.DebugPrint("testKron(): A = %s" % str(A));
#common.DebugPrint("testKron(): res = %s" % str(res));
aZero = res - resGood;
self.assertTrue((aZero == 0).all());
def testSub2ind(self):
# Taken from the Matlab help of sub2ind
A = np.empty((3, 4, 2));
r = np.array([3, 2, 3, 1, 2]);
c = np.array([3, 4, 1, 3, 4]);
d3 = np.array([2, 1, 2, 2, 1]);
r -= 1;
c -= 1;
d3 -= 1;
res = sub2ind(matrixSize=A.shape, rowSub=r, colSub=c, dim3Sub=d3);
# Taken from the Matlab help of sub2ind
resGood = np.array([21, 11, 15, 19, 11]);
resGood -= 1;
#common.DebugPrint("testSub2ind(): res = %s" % str(res));
aZero = res - resGood;
self.assertTrue((aZero == 0).all());
def testOrdfilt2(self):
A = np.array([ \
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]]);
A = A.astype(np.float64);
#res = ordfilt2_4_nested_loops(A, 9, np.ones((3, 3)));
res = ordfilt2(A, 9, np.ones((3, 3)));
common.DebugPrint("testOrdfilt2(): res = %s" % str(res));
resGood = np.array([ \
[ 6, 7, 8, 8],
[10, 11, 12, 12],
[14, 15, 16, 16],
[14, 15, 16, 16]]);
aZero = res - resGood;
#self.assertTrue(np.abs(aZero == 0).all());
self.assertTrue(np.abs(aZero < 1.0e-4).all());
"""
>> A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
>> ordfilt2(A, 0, ones(3))
ans =
1.0e-307 *
0.4450 0.4450 0.4450 0.4450
0.4450 0.4450 0.4450 0.4450
0.4450 0.4450 0.4450 0.4450
0.4450 0.4450 0.4450 0.4450
>> ordfilt2(A, 1, ones(3))
ans =
0 0 0 0
0 1 2 0
0 5 6 0
0 0 0 0
>> ordfilt2(A, 2, ones(3))
ans =
0 0 0 0
0 2 3 0
0 6 7 0
0 0 0 0
>> ordfilt2(A, 3, ones(3))
ans =
0 0 0 0
0 3 4 0
0 7 8 0
0 0 0 0
>> ordfilt2(A, 4, ones(3))
ans =
0 1 2 0
1 5 6 3
5 9 10 7
0 9 10 0
>> ordfilt2(A, 5, ones(3))
ans =
0 2 3 0
2 6 7 4
6 10 11 8
0 10 11 0
>> ordfilt2(A, 6, ones(3))
ans =
1 3 4 3
5 7 8 7
9 11 12 11
9 11 12 11
>> ordfilt2(A, 7, ones(3))
ans =
2 5 6 4
6 9 10 8
10 13 14 12
10 13 14 12
>> ordfilt2(A, 8, ones(3))
ans =
5 6 7 7
9 10 11 11
13 14 15 15
13 14 15 15
>> ordfilt2(A, 9, ones(3))
ans =
6 7 8 8
10 11 12 12
14 15 16 16
14 15 16 16
>> ordfilt2(A, 10, ones(3))
ans =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
"""
if __name__ == '__main__':
# See http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html
np.set_printoptions(precision=4, suppress=True, \
threshold=1000000, linewidth=5000);
unittest.main();
| false | true |
f7f6c322fd3a70cf309ceed53f2bfc38a4df9bef | 12,369 | py | Python | hassio/snapshots/__init__.py | luca-simonetti/hassio | 53dab4ee450f321a60b9ae818d1bc80dbb8ee78b | [
"Apache-2.0"
] | null | null | null | hassio/snapshots/__init__.py | luca-simonetti/hassio | 53dab4ee450f321a60b9ae818d1bc80dbb8ee78b | [
"Apache-2.0"
] | null | null | null | hassio/snapshots/__init__.py | luca-simonetti/hassio | 53dab4ee450f321a60b9ae818d1bc80dbb8ee78b | [
"Apache-2.0"
] | null | null | null | """Snapshot system control."""
import asyncio
import logging
from pathlib import Path
from .snapshot import Snapshot
from .utils import create_slug
from ..const import (
FOLDER_HOMEASSISTANT, SNAPSHOT_FULL, SNAPSHOT_PARTIAL)
from ..coresys import CoreSysAttributes
from ..utils.dt import utcnow
_LOGGER = logging.getLogger(__name__)
class SnapshotManager(CoreSysAttributes):
"""Manage snapshots."""
def __init__(self, coresys):
"""Initialize a snapshot manager."""
self.coresys = coresys
self.snapshots_obj = {}
self.lock = asyncio.Lock(loop=coresys.loop)
@property
def list_snapshots(self):
"""Return a list of all snapshot object."""
return set(self.snapshots_obj.values())
def get(self, slug):
"""Return snapshot object."""
return self.snapshots_obj.get(slug)
def _create_snapshot(self, name, sys_type, password):
"""Initialize a new snapshot object from name."""
date_str = utcnow().isoformat()
slug = create_slug(name, date_str)
tar_file = Path(self.sys_config.path_backup, f"{slug}.tar")
# init object
snapshot = Snapshot(self.coresys, tar_file)
snapshot.new(slug, name, date_str, sys_type, password)
# set general data
snapshot.store_homeassistant()
snapshot.store_repositories()
return snapshot
def load(self):
"""Load exists snapshots data.
Return a coroutine.
"""
return self.reload()
async def reload(self):
"""Load exists backups."""
self.snapshots_obj = {}
async def _load_snapshot(tar_file):
"""Internal function to load snapshot."""
snapshot = Snapshot(self.coresys, tar_file)
if await snapshot.load():
self.snapshots_obj[snapshot.slug] = snapshot
tasks = [_load_snapshot(tar_file) for tar_file in
self.sys_config.path_backup.glob("*.tar")]
_LOGGER.info("Found %d snapshot files", len(tasks))
if tasks:
await asyncio.wait(tasks)
def remove(self, snapshot):
"""Remove a snapshot."""
try:
snapshot.tarfile.unlink()
self.snapshots_obj.pop(snapshot.slug, None)
_LOGGER.info("Removed snapshot file %s", snapshot.slug)
except OSError as err:
_LOGGER.error("Can't remove snapshot %s: %s", snapshot.slug, err)
return False
return True
async def import_snapshot(self, tar_file):
"""Check snapshot tarfile and import it."""
snapshot = Snapshot(self.coresys, tar_file)
# Read meta data
if not await snapshot.load():
return None
# Already exists?
if snapshot.slug in self.snapshots_obj:
_LOGGER.error("Snapshot %s already exists!", snapshot.slug)
return None
# Move snapshot to backup
tar_origin = Path(self.sys_config.path_backup, f"{snapshot.slug}.tar")
try:
snapshot.tarfile.rename(tar_origin)
except OSError as err:
_LOGGER.error("Can't move snapshot file to storage: %s", err)
return None
# Load new snapshot
snapshot = Snapshot(self.coresys, tar_origin)
if not await snapshot.load():
return None
_LOGGER.info("Success import %s", snapshot.slug)
self.snapshots_obj[snapshot.slug] = snapshot
return snapshot
async def do_snapshot_full(self, name="", password=None):
"""Create a full snapshot."""
if self.lock.locked():
_LOGGER.error("It is already a snapshot/restore process running")
return None
snapshot = self._create_snapshot(name, SNAPSHOT_FULL, password)
_LOGGER.info("Full-Snapshot %s start", snapshot.slug)
try:
self.sys_scheduler.suspend = True
await self.lock.acquire()
async with snapshot:
# Snapshot add-ons
_LOGGER.info("Snapshot %s store Add-ons", snapshot.slug)
await snapshot.store_addons()
# Snapshot folders
_LOGGER.info("Snapshot %s store folders", snapshot.slug)
await snapshot.store_folders()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Snapshot %s error", snapshot.slug)
return None
else:
_LOGGER.info("Full-Snapshot %s done", snapshot.slug)
self.snapshots_obj[snapshot.slug] = snapshot
return snapshot
finally:
self.sys_scheduler.suspend = False
self.lock.release()
async def do_snapshot_partial(self, name="", addons=None, folders=None,
password=None):
"""Create a partial snapshot."""
if self.lock.locked():
_LOGGER.error("It is already a snapshot/restore process running")
return None
addons = addons or []
folders = folders or []
snapshot = self._create_snapshot(name, SNAPSHOT_PARTIAL, password)
_LOGGER.info("Partial-Snapshot %s start", snapshot.slug)
try:
self.sys_scheduler.suspend = True
await self.lock.acquire()
async with snapshot:
# Snapshot add-ons
addon_list = []
for addon_slug in addons:
addon = self.sys_addons.get(addon_slug)
if addon and addon.is_installed:
addon_list.append(addon)
continue
_LOGGER.warning(
"Add-on %s not found/installed", addon_slug)
if addon_list:
_LOGGER.info("Snapshot %s store Add-ons", snapshot.slug)
await snapshot.store_addons(addon_list)
# Snapshot folders
if folders:
_LOGGER.info("Snapshot %s store folders", snapshot.slug)
await snapshot.store_folders(folders)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Snapshot %s error", snapshot.slug)
return None
else:
_LOGGER.info("Partial-Snapshot %s done", snapshot.slug)
self.snapshots_obj[snapshot.slug] = snapshot
return snapshot
finally:
self.sys_scheduler.suspend = False
self.lock.release()
async def do_restore_full(self, snapshot, password=None):
"""Restore a snapshot."""
if self.lock.locked():
_LOGGER.error("It is already a snapshot/restore process running")
return False
if snapshot.sys_type != SNAPSHOT_FULL:
_LOGGER.error("Restore %s is only a partial snapshot!",
snapshot.slug)
return False
if snapshot.protected and not snapshot.set_password(password):
_LOGGER.error("Invalid password for snapshot %s", snapshot.slug)
return False
_LOGGER.info("Full-Restore %s start", snapshot.slug)
try:
self.sys_scheduler.suspend = True
await self.lock.acquire()
async with snapshot:
tasks = []
# Stop Home-Assistant / Add-ons
await self.sys_core.shutdown()
# Restore folders
_LOGGER.info("Restore %s run folders", snapshot.slug)
await snapshot.restore_folders()
# Start homeassistant restore
_LOGGER.info("Restore %s run Home-Assistant", snapshot.slug)
snapshot.restore_homeassistant()
task_hass = self.sys_create_task(self.sys_homeassistant.update(
snapshot.homeassistant_version))
# Restore repositories
_LOGGER.info("Restore %s run Repositories", snapshot.slug)
await snapshot.restore_repositories()
# Delete delta add-ons
tasks.clear()
for addon in self.sys_addons.list_installed:
if addon.slug not in snapshot.addon_list:
tasks.append(addon.uninstall())
if tasks:
_LOGGER.info("Restore %s remove add-ons", snapshot.slug)
await asyncio.wait(tasks)
# Restore add-ons
_LOGGER.info("Restore %s old add-ons", snapshot.slug)
await snapshot.restore_addons()
# finish homeassistant task
_LOGGER.info("Restore %s wait until homeassistant ready",
snapshot.slug)
await task_hass
await self.sys_homeassistant.start()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Restore %s error", snapshot.slug)
return False
else:
_LOGGER.info("Full-Restore %s done", snapshot.slug)
return True
finally:
self.sys_scheduler.suspend = False
self.lock.release()
async def do_restore_partial(self, snapshot, homeassistant=False,
addons=None, folders=None, password=None):
"""Restore a snapshot."""
if self.lock.locked():
_LOGGER.error("It is already a snapshot/restore process running")
return False
if snapshot.protected and not snapshot.set_password(password):
_LOGGER.error("Invalid password for snapshot %s", snapshot.slug)
return False
addons = addons or []
folders = folders or []
_LOGGER.info("Partial-Restore %s start", snapshot.slug)
try:
self.sys_scheduler.suspend = True
await self.lock.acquire()
async with snapshot:
# Stop Home-Assistant if they will be restored later
if homeassistant and FOLDER_HOMEASSISTANT in folders:
await self.sys_homeassistant.stop()
snapshot.restore_homeassistant()
# Process folders
if folders:
_LOGGER.info("Restore %s run folders", snapshot.slug)
await snapshot.restore_folders(folders)
# Process Home-Assistant
task_hass = None
if homeassistant:
_LOGGER.info("Restore %s run Home-Assistant",
snapshot.slug)
task_hass = self.sys_create_task(
self.sys_homeassistant.update(
snapshot.homeassistant_version))
# Process Add-ons
addon_list = []
for slug in addons:
addon = self.sys_addons.get(slug)
if addon:
addon_list.append(addon)
continue
_LOGGER.warning("Can't restore addon %s", snapshot.slug)
if addon_list:
_LOGGER.info("Restore %s old add-ons", snapshot.slug)
await snapshot.restore_addons(addon_list)
# Make sure homeassistant run agen
if task_hass:
_LOGGER.info("Restore %s wait for Home-Assistant",
snapshot.slug)
await task_hass
# Do we need start HomeAssistant?
if not await self.sys_homeassistant.is_running():
await self.sys_homeassistant.start()
# Check If we can access to API / otherwise restart
if not await self.sys_homeassistant.check_api_state():
_LOGGER.warning("Need restart HomeAssistant for API")
await self.sys_homeassistant.restart()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Restore %s error", snapshot.slug)
return False
else:
_LOGGER.info("Partial-Restore %s done", snapshot.slug)
return True
finally:
self.sys_scheduler.suspend = False
self.lock.release()
| 35.239316 | 79 | 0.565608 | import asyncio
import logging
from pathlib import Path
from .snapshot import Snapshot
from .utils import create_slug
from ..const import (
FOLDER_HOMEASSISTANT, SNAPSHOT_FULL, SNAPSHOT_PARTIAL)
from ..coresys import CoreSysAttributes
from ..utils.dt import utcnow
_LOGGER = logging.getLogger(__name__)
class SnapshotManager(CoreSysAttributes):
def __init__(self, coresys):
self.coresys = coresys
self.snapshots_obj = {}
self.lock = asyncio.Lock(loop=coresys.loop)
@property
def list_snapshots(self):
return set(self.snapshots_obj.values())
def get(self, slug):
return self.snapshots_obj.get(slug)
def _create_snapshot(self, name, sys_type, password):
date_str = utcnow().isoformat()
slug = create_slug(name, date_str)
tar_file = Path(self.sys_config.path_backup, f"{slug}.tar")
snapshot = Snapshot(self.coresys, tar_file)
snapshot.new(slug, name, date_str, sys_type, password)
snapshot.store_homeassistant()
snapshot.store_repositories()
return snapshot
def load(self):
return self.reload()
async def reload(self):
self.snapshots_obj = {}
async def _load_snapshot(tar_file):
snapshot = Snapshot(self.coresys, tar_file)
if await snapshot.load():
self.snapshots_obj[snapshot.slug] = snapshot
tasks = [_load_snapshot(tar_file) for tar_file in
self.sys_config.path_backup.glob("*.tar")]
_LOGGER.info("Found %d snapshot files", len(tasks))
if tasks:
await asyncio.wait(tasks)
def remove(self, snapshot):
try:
snapshot.tarfile.unlink()
self.snapshots_obj.pop(snapshot.slug, None)
_LOGGER.info("Removed snapshot file %s", snapshot.slug)
except OSError as err:
_LOGGER.error("Can't remove snapshot %s: %s", snapshot.slug, err)
return False
return True
async def import_snapshot(self, tar_file):
snapshot = Snapshot(self.coresys, tar_file)
# Read meta data
if not await snapshot.load():
return None
# Already exists?
if snapshot.slug in self.snapshots_obj:
_LOGGER.error("Snapshot %s already exists!", snapshot.slug)
return None
# Move snapshot to backup
tar_origin = Path(self.sys_config.path_backup, f"{snapshot.slug}.tar")
try:
snapshot.tarfile.rename(tar_origin)
except OSError as err:
_LOGGER.error("Can't move snapshot file to storage: %s", err)
return None
snapshot = Snapshot(self.coresys, tar_origin)
if not await snapshot.load():
return None
_LOGGER.info("Success import %s", snapshot.slug)
self.snapshots_obj[snapshot.slug] = snapshot
return snapshot
async def do_snapshot_full(self, name="", password=None):
if self.lock.locked():
_LOGGER.error("It is already a snapshot/restore process running")
return None
snapshot = self._create_snapshot(name, SNAPSHOT_FULL, password)
_LOGGER.info("Full-Snapshot %s start", snapshot.slug)
try:
self.sys_scheduler.suspend = True
await self.lock.acquire()
async with snapshot:
_LOGGER.info("Snapshot %s store Add-ons", snapshot.slug)
await snapshot.store_addons()
_LOGGER.info("Snapshot %s store folders", snapshot.slug)
await snapshot.store_folders()
except Exception:
_LOGGER.exception("Snapshot %s error", snapshot.slug)
return None
else:
_LOGGER.info("Full-Snapshot %s done", snapshot.slug)
self.snapshots_obj[snapshot.slug] = snapshot
return snapshot
finally:
self.sys_scheduler.suspend = False
self.lock.release()
async def do_snapshot_partial(self, name="", addons=None, folders=None,
password=None):
if self.lock.locked():
_LOGGER.error("It is already a snapshot/restore process running")
return None
addons = addons or []
folders = folders or []
snapshot = self._create_snapshot(name, SNAPSHOT_PARTIAL, password)
_LOGGER.info("Partial-Snapshot %s start", snapshot.slug)
try:
self.sys_scheduler.suspend = True
await self.lock.acquire()
async with snapshot:
addon_list = []
for addon_slug in addons:
addon = self.sys_addons.get(addon_slug)
if addon and addon.is_installed:
addon_list.append(addon)
continue
_LOGGER.warning(
"Add-on %s not found/installed", addon_slug)
if addon_list:
_LOGGER.info("Snapshot %s store Add-ons", snapshot.slug)
await snapshot.store_addons(addon_list)
if folders:
_LOGGER.info("Snapshot %s store folders", snapshot.slug)
await snapshot.store_folders(folders)
except Exception:
_LOGGER.exception("Snapshot %s error", snapshot.slug)
return None
else:
_LOGGER.info("Partial-Snapshot %s done", snapshot.slug)
self.snapshots_obj[snapshot.slug] = snapshot
return snapshot
finally:
self.sys_scheduler.suspend = False
self.lock.release()
async def do_restore_full(self, snapshot, password=None):
if self.lock.locked():
_LOGGER.error("It is already a snapshot/restore process running")
return False
if snapshot.sys_type != SNAPSHOT_FULL:
_LOGGER.error("Restore %s is only a partial snapshot!",
snapshot.slug)
return False
if snapshot.protected and not snapshot.set_password(password):
_LOGGER.error("Invalid password for snapshot %s", snapshot.slug)
return False
_LOGGER.info("Full-Restore %s start", snapshot.slug)
try:
self.sys_scheduler.suspend = True
await self.lock.acquire()
async with snapshot:
tasks = []
await self.sys_core.shutdown()
_LOGGER.info("Restore %s run folders", snapshot.slug)
await snapshot.restore_folders()
_LOGGER.info("Restore %s run Home-Assistant", snapshot.slug)
snapshot.restore_homeassistant()
task_hass = self.sys_create_task(self.sys_homeassistant.update(
snapshot.homeassistant_version))
_LOGGER.info("Restore %s run Repositories", snapshot.slug)
await snapshot.restore_repositories()
tasks.clear()
for addon in self.sys_addons.list_installed:
if addon.slug not in snapshot.addon_list:
tasks.append(addon.uninstall())
if tasks:
_LOGGER.info("Restore %s remove add-ons", snapshot.slug)
await asyncio.wait(tasks)
_LOGGER.info("Restore %s old add-ons", snapshot.slug)
await snapshot.restore_addons()
_LOGGER.info("Restore %s wait until homeassistant ready",
snapshot.slug)
await task_hass
await self.sys_homeassistant.start()
except Exception:
_LOGGER.exception("Restore %s error", snapshot.slug)
return False
else:
_LOGGER.info("Full-Restore %s done", snapshot.slug)
return True
finally:
self.sys_scheduler.suspend = False
self.lock.release()
async def do_restore_partial(self, snapshot, homeassistant=False,
addons=None, folders=None, password=None):
if self.lock.locked():
_LOGGER.error("It is already a snapshot/restore process running")
return False
if snapshot.protected and not snapshot.set_password(password):
_LOGGER.error("Invalid password for snapshot %s", snapshot.slug)
return False
addons = addons or []
folders = folders or []
_LOGGER.info("Partial-Restore %s start", snapshot.slug)
try:
self.sys_scheduler.suspend = True
await self.lock.acquire()
async with snapshot:
if homeassistant and FOLDER_HOMEASSISTANT in folders:
await self.sys_homeassistant.stop()
snapshot.restore_homeassistant()
if folders:
_LOGGER.info("Restore %s run folders", snapshot.slug)
await snapshot.restore_folders(folders)
task_hass = None
if homeassistant:
_LOGGER.info("Restore %s run Home-Assistant",
snapshot.slug)
task_hass = self.sys_create_task(
self.sys_homeassistant.update(
snapshot.homeassistant_version))
addon_list = []
for slug in addons:
addon = self.sys_addons.get(slug)
if addon:
addon_list.append(addon)
continue
_LOGGER.warning("Can't restore addon %s", snapshot.slug)
if addon_list:
_LOGGER.info("Restore %s old add-ons", snapshot.slug)
await snapshot.restore_addons(addon_list)
# Make sure homeassistant run agen
if task_hass:
_LOGGER.info("Restore %s wait for Home-Assistant",
snapshot.slug)
await task_hass
# Do we need start HomeAssistant?
if not await self.sys_homeassistant.is_running():
await self.sys_homeassistant.start()
# Check If we can access to API / otherwise restart
if not await self.sys_homeassistant.check_api_state():
_LOGGER.warning("Need restart HomeAssistant for API")
await self.sys_homeassistant.restart()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Restore %s error", snapshot.slug)
return False
else:
_LOGGER.info("Partial-Restore %s done", snapshot.slug)
return True
finally:
self.sys_scheduler.suspend = False
self.lock.release()
| true | true |
f7f6c324bbd19d2ced992119d04f69dab735fa1c | 2,794 | py | Python | tests/test_functional.py | m4rc1e/fontdiffenator | 1c49ead4e6e16e3aa4c227ceea8c1aa2de92f3a7 | [
"Apache-2.0"
] | 59 | 2017-10-14T11:17:44.000Z | 2022-03-19T17:46:02.000Z | tests/test_functional.py | m4rc1e/fontdiffenator | 1c49ead4e6e16e3aa4c227ceea8c1aa2de92f3a7 | [
"Apache-2.0"
] | 57 | 2017-10-31T03:40:40.000Z | 2022-01-14T19:02:28.000Z | tests/test_functional.py | m4rc1e/fontdiffenator | 1c49ead4e6e16e3aa4c227ceea8c1aa2de92f3a7 | [
"Apache-2.0"
] | 11 | 2017-10-12T18:13:36.000Z | 2020-07-21T15:28:46.000Z | """Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
This test is slow and should be run on challenging fonts.
"""
from diffenator import CHOICES
from itertools import permutations
import subprocess
from glob import glob
import os
import unittest
import tempfile
import shutil
class TestFunctionality(unittest.TestCase):
def setUp(self):
self._path = os.path.dirname(__file__)
font_paths = glob(os.path.join(self._path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
cbdt_font_paths = glob(os.path.join(self._path, 'data', 'cbdt_test', '*.ttf'))
self.cbdt_font_path_combos = permutations(cbdt_font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
gif_dir = tempfile.mktemp()
subprocess.call([
"diffenator",
font_a_path,
font_b_path,
"-r", gif_dir])
gifs = [f for f in os.listdir(gif_dir) if f.endswith(".gif")]
self.assertNotEqual(gifs, [])
shutil.rmtree(gif_dir)
def test_cbdt_diff(self):
for font_a_path, font_b_path in self.cbdt_font_path_combos:
gif_dir = tempfile.mktemp()
subprocess.call([
"diffenator",
font_a_path,
font_b_path,
"-r", gif_dir])
gifs = [f for f in os.listdir(gif_dir) if f.endswith(".gif")]
self.assertNotEqual(gifs, [])
shutil.rmtree(gif_dir)
def test_diff_vf_vs_static(self):
font_a_path = os.path.join(self._path, 'data', 'vf_test', 'Fahkwang-VF.ttf')
font_b_path = os.path.join(self._path, 'data', 'vf_test', 'Fahkwang-Light.ttf')
cmd = subprocess.check_output([
"diffenator",
font_a_path,
font_b_path
])
self.assertNotEqual(cmd, None)
def test_cbdt_dump(self):
font_path = os.path.join(self._path, 'data', 'cbdt_test', 'NotoColorEmoji-u11-u1F349.ttf')
for category in CHOICES:
cmd = subprocess.check_output([
"dumper",
font_path,
category,
])
self.assertNotEqual(cmd, None)
def test_dump(self):
font_path = os.path.join(self._path, 'data', 'Play-Regular.ttf')
for category in CHOICES:
cmd = subprocess.check_output([
"dumper",
font_path,
category,
])
self.assertNotEqual(cmd, None)
if __name__ == '__main__':
unittest.main()
| 31.044444 | 98 | 0.58733 | from diffenator import CHOICES
from itertools import permutations
import subprocess
from glob import glob
import os
import unittest
import tempfile
import shutil
class TestFunctionality(unittest.TestCase):
def setUp(self):
self._path = os.path.dirname(__file__)
font_paths = glob(os.path.join(self._path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
cbdt_font_paths = glob(os.path.join(self._path, 'data', 'cbdt_test', '*.ttf'))
self.cbdt_font_path_combos = permutations(cbdt_font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
gif_dir = tempfile.mktemp()
subprocess.call([
"diffenator",
font_a_path,
font_b_path,
"-r", gif_dir])
gifs = [f for f in os.listdir(gif_dir) if f.endswith(".gif")]
self.assertNotEqual(gifs, [])
shutil.rmtree(gif_dir)
def test_cbdt_diff(self):
for font_a_path, font_b_path in self.cbdt_font_path_combos:
gif_dir = tempfile.mktemp()
subprocess.call([
"diffenator",
font_a_path,
font_b_path,
"-r", gif_dir])
gifs = [f for f in os.listdir(gif_dir) if f.endswith(".gif")]
self.assertNotEqual(gifs, [])
shutil.rmtree(gif_dir)
def test_diff_vf_vs_static(self):
font_a_path = os.path.join(self._path, 'data', 'vf_test', 'Fahkwang-VF.ttf')
font_b_path = os.path.join(self._path, 'data', 'vf_test', 'Fahkwang-Light.ttf')
cmd = subprocess.check_output([
"diffenator",
font_a_path,
font_b_path
])
self.assertNotEqual(cmd, None)
def test_cbdt_dump(self):
font_path = os.path.join(self._path, 'data', 'cbdt_test', 'NotoColorEmoji-u11-u1F349.ttf')
for category in CHOICES:
cmd = subprocess.check_output([
"dumper",
font_path,
category,
])
self.assertNotEqual(cmd, None)
def test_dump(self):
font_path = os.path.join(self._path, 'data', 'Play-Regular.ttf')
for category in CHOICES:
cmd = subprocess.check_output([
"dumper",
font_path,
category,
])
self.assertNotEqual(cmd, None)
if __name__ == '__main__':
unittest.main()
| true | true |
f7f6c34cc7803fffa8cbb3f06f263cc3bcdc9485 | 989 | py | Python | em_pe/models/__init__.py | markoris/EM_PE | d65811e269e4befec94429387bdef0bc76cfb8cf | [
"MIT"
] | 2 | 2019-06-14T20:59:47.000Z | 2021-06-22T14:15:59.000Z | em_pe/models/__init__.py | markoris/EM_PE | d65811e269e4befec94429387bdef0bc76cfb8cf | [
"MIT"
] | null | null | null | em_pe/models/__init__.py | markoris/EM_PE | d65811e269e4befec94429387bdef0bc76cfb8cf | [
"MIT"
] | 4 | 2021-06-14T00:18:25.000Z | 2021-11-02T20:41:42.000Z | from .interpolated_model import *
from .kilonova import *
from .kilonova_3c import *
from .kn_interp import *
from .kn_interp_angle import *
from .parameters import *
model_dict = {
"interpolated":interpolated,
"kilonova":kilonova,
"kilonova_3c":kilonova_3c,
"kn_interp":kn_interp,
"kn_interp_angle":kn_interp_angle
}
param_dict = {
"dist":Distance,
"mej":EjectaMass,
"mej_red":EjectaMassRed,
"mej_purple":EjectaMassPurple,
"mej_blue":EjectaMassBlue,
"mej_dyn":DynamicalEjectaMass,
"mej_wind":WindEjectaMass,
"vej":EjectaVelocity,
"vej_red":EjectaVelocityRed,
"vej_purple":EjectaVelocityPurple,
"vej_blue":EjectaVelocityBlue,
"vej_dyn":DynamicalEjectaVelocity,
"vej_wind":WindEjectaVelocity,
"Tc_red":TcRed,
"Tc_purple":TcPurple,
"Tc_blue":TcBlue,
"kappa":Kappa,
"sigma":Sigma,
"theta":Theta
}
| 26.026316 | 42 | 0.632963 | from .interpolated_model import *
from .kilonova import *
from .kilonova_3c import *
from .kn_interp import *
from .kn_interp_angle import *
from .parameters import *
model_dict = {
"interpolated":interpolated,
"kilonova":kilonova,
"kilonova_3c":kilonova_3c,
"kn_interp":kn_interp,
"kn_interp_angle":kn_interp_angle
}
param_dict = {
"dist":Distance,
"mej":EjectaMass,
"mej_red":EjectaMassRed,
"mej_purple":EjectaMassPurple,
"mej_blue":EjectaMassBlue,
"mej_dyn":DynamicalEjectaMass,
"mej_wind":WindEjectaMass,
"vej":EjectaVelocity,
"vej_red":EjectaVelocityRed,
"vej_purple":EjectaVelocityPurple,
"vej_blue":EjectaVelocityBlue,
"vej_dyn":DynamicalEjectaVelocity,
"vej_wind":WindEjectaVelocity,
"Tc_red":TcRed,
"Tc_purple":TcPurple,
"Tc_blue":TcBlue,
"kappa":Kappa,
"sigma":Sigma,
"theta":Theta
}
| true | true |
f7f6c372646958e537fb2ce7a160783f2f418999 | 22,400 | py | Python | napari/layers/image/image.py | shanaxel42/napari | d182b3694deb185afcf8b6ae2e87cccb78d7f82b | [
"BSD-3-Clause"
] | null | null | null | napari/layers/image/image.py | shanaxel42/napari | d182b3694deb185afcf8b6ae2e87cccb78d7f82b | [
"BSD-3-Clause"
] | 1 | 2020-06-19T21:38:50.000Z | 2020-06-20T19:57:39.000Z | napari/layers/image/image.py | shanaxel42/napari | d182b3694deb185afcf8b6ae2e87cccb78d7f82b | [
"BSD-3-Clause"
] | null | null | null | import types
import warnings
from base64 import b64encode
from xml.etree.ElementTree import Element
import numpy as np
from imageio import imwrite
from scipy import ndimage as ndi
from ...utils.colormaps import AVAILABLE_COLORMAPS
from ...utils.event import Event
from ...utils.status_messages import format_float
from ..base import Layer
from ..layer_utils import calc_data_range
from ..intensity_mixin import IntensityVisualizationMixin
from ._constants import Interpolation, Rendering
from .image_utils import get_pyramid_and_rgb
# Mixin must come before Layer
class Image(IntensityVisualizationMixin, Layer):
"""Image layer.
Parameters
----------
data : array or list of array
Image data. Can be N dimensional. If the last dimension has length
3 or 4 can be interpreted as RGB or RGBA if rgb is `True`. If a
list and arrays are decreasing in shape then the data is treated as
an image pyramid.
rgb : bool
Whether the image is rgb RGB or RGBA. If not specified by user and
the last dimension of the data has length 3 or 4 it will be set as
`True`. If `False` the image is interpreted as a luminance image.
is_pyramid : bool
Whether the data is an image pyramid or not. Pyramid data is
represented by a list of array like image data. If not specified by
the user and if the data is a list of arrays that decrease in shape
then it will be taken to be a pyramid. The first image in the list
should be the largest.
colormap : str, vispy.Color.Colormap, tuple, dict
Colormap to use for luminance images. If a string must be the name
of a supported colormap from vispy or matplotlib. If a tuple the
first value must be a string to assign as a name to a colormap and
the second item must be a Colormap. If a dict the key must be a
string to assign as a name to a colormap and the value must be a
Colormap.
contrast_limits : list (2,)
Color limits to be used for determining the colormap bounds for
luminance images. If not passed is calculated as the min and max of
the image.
gamma : float
Gamma correction for determining colormap linearity. Defaults to 1.
interpolation : str
Interpolation mode used by vispy. Must be one of our supported
modes.
rendering : str
Rendering mode used by vispy. Must be one of our supported
modes.
iso_threshold : float
Threshold for isosurface.
attenuation : float
Attenuation rate for attenuated maximum intensity projection.
name : str
Name of the layer.
metadata : dict
Layer metadata.
scale : tuple of float
Scale factors for the layer.
translate : tuple of float
Translation values for the layer.
opacity : float
Opacity of the layer visual, between 0.0 and 1.0.
blending : str
One of a list of preset blending modes that determines how RGB and
alpha values of the layer visual get mixed. Allowed values are
{'opaque', 'translucent', and 'additive'}.
visible : bool
Whether the layer visual is currently being displayed.
Attributes
----------
data : array
Image data. Can be N dimensional. If the last dimension has length
3 or 4 can be interpreted as RGB or RGBA if rgb is `True`. If a list
and arrays are decreaing in shape then the data is treated as an
image pyramid.
metadata : dict
Image metadata.
rgb : bool
Whether the image is rgb RGB or RGBA if rgb. If not
specified by user and the last dimension of the data has length 3 or 4
it will be set as `True`. If `False` the image is interpreted as a
luminance image.
is_pyramid : bool
Whether the data is an image pyramid or not. Pyramid data is
represented by a list of array like image data. The first image in the
list should be the largest.
colormap : 2-tuple of str, vispy.color.Colormap
The first is the name of the current colormap, and the second value is
the colormap. Colormaps are used for luminance images, if the image is
rgb the colormap is ignored.
colormaps : tuple of str
Names of the available colormaps.
contrast_limits : list (2,) of float
Color limits to be used for determining the colormap bounds for
luminance images. If the image is rgb the contrast_limits is ignored.
contrast_limits_range : list (2,) of float
Range for the color limits for luminace images. If the image is
rgb the contrast_limits_range is ignored.
gamma : float
Gamma correction for determining colormap linearity.
interpolation : str
Interpolation mode used by vispy. Must be one of our supported
modes.
rendering : str
Rendering mode used by vispy. Must be one of our supported
modes.
iso_threshold : float
Threshold for isosurface.
attenuation : float
Attenuation rate for attenuated maximum intensity projection.
Extended Summary
----------
_data_view : array (N, M), (N, M, 3), or (N, M, 4)
Image data for the currently viewed slice. Must be 2D image data, but
can be multidimensional for RGB or RGBA images if multidimensional is
`True`.
_colorbar : array
Colorbar for current colormap.
"""
_colormaps = AVAILABLE_COLORMAPS
_max_tile_shape = 1600
def __init__(
self,
data,
*,
rgb=None,
is_pyramid=None,
colormap='gray',
contrast_limits=None,
gamma=1,
interpolation='nearest',
rendering='mip',
iso_threshold=0.5,
attenuation=0.5,
name=None,
metadata=None,
scale=None,
translate=None,
opacity=1,
blending='translucent',
visible=True,
):
if isinstance(data, types.GeneratorType):
data = list(data)
ndim, rgb, is_pyramid, data_pyramid = get_pyramid_and_rgb(
data, pyramid=is_pyramid, rgb=rgb
)
super().__init__(
data,
ndim,
name=name,
metadata=metadata,
scale=scale,
translate=translate,
opacity=opacity,
blending=blending,
visible=visible,
)
self.events.add(
interpolation=Event,
rendering=Event,
iso_threshold=Event,
attenuation=Event,
)
# Set data
self.is_pyramid = is_pyramid
self.rgb = rgb
self._data = data
self._data_pyramid = data_pyramid
self._top_left = np.zeros(ndim, dtype=int)
if self.is_pyramid:
self._data_level = len(data_pyramid) - 1
else:
self._data_level = 0
# Intitialize image views and thumbnails with zeros
if self.rgb:
self._data_view = np.zeros(
(1,) * self.dims.ndisplay + (self.shape[-1],)
)
else:
self._data_view = np.zeros((1,) * self.dims.ndisplay)
self._data_raw = self._data_view
self._data_thumbnail = self._data_view
# Set contrast_limits and colormaps
self._gamma = gamma
self._iso_threshold = iso_threshold
self._attenuation = attenuation
if contrast_limits is None:
self.contrast_limits_range = self._calc_data_range()
else:
self.contrast_limits_range = contrast_limits
self._contrast_limits = tuple(self.contrast_limits_range)
self.colormap = colormap
self.contrast_limits = self._contrast_limits
self.interpolation = interpolation
self.rendering = rendering
# Trigger generation of view slice and thumbnail
self._update_dims()
def _calc_data_range(self):
if self.is_pyramid:
input_data = self._data_pyramid[-1]
else:
input_data = self.data
return calc_data_range(input_data)
@property
def dtype(self):
return self.data[0].dtype if self.is_pyramid else self.data.dtype
@property
def data(self):
"""array: Image data."""
return self._data
@data.setter
def data(self, data):
ndim, rgb, is_pyramid, data_pyramid = get_pyramid_and_rgb(
data, pyramid=self.is_pyramid, rgb=self.rgb
)
self.is_pyramid = is_pyramid
self.rgb = rgb
self._data = data
self._data_pyramid = data_pyramid
self._update_dims()
self.events.data()
def _get_ndim(self):
"""Determine number of dimensions of the layer."""
return len(self.level_shapes[0])
def _get_extent(self):
return tuple((0, m) for m in self.level_shapes[0])
@property
def data_level(self):
"""int: Current level of pyramid, or 0 if image."""
return self._data_level
@data_level.setter
def data_level(self, level):
if self._data_level == level:
return
self._data_level = level
self.refresh()
@property
def level_shapes(self):
"""array: Shapes of each level of the pyramid or just of image."""
if self.is_pyramid:
if self.rgb:
shapes = [im.shape[:-1] for im in self._data_pyramid]
else:
shapes = [im.shape for im in self._data_pyramid]
else:
if self.rgb:
shapes = [self.data.shape[:-1]]
else:
shapes = [self.data.shape]
return np.array(shapes)
@property
def level_downsamples(self):
"""list: Downsample factors for each level of the pyramid."""
return np.divide(self.level_shapes[0], self.level_shapes)
@property
def top_left(self):
"""tuple: Location of top left canvas pixel in image."""
return self._top_left
@top_left.setter
def top_left(self, top_left):
if np.all(self._top_left == top_left):
return
self._top_left = top_left.astype(int)
self.refresh()
@property
def iso_threshold(self):
"""float: threshold for isosurface."""
return self._iso_threshold
@iso_threshold.setter
def iso_threshold(self, value):
self.status = format_float(value)
self._iso_threshold = value
self._update_thumbnail()
self.events.iso_threshold()
@property
def attenuation(self):
"""float: attenuation rate for attenuated_mip rendering."""
return self._attenuation
@attenuation.setter
def attenuation(self, value):
self.status = format_float(value)
self._attenuation = value
self._update_thumbnail()
self.events.attenuation()
@property
def interpolation(self):
"""{
'bessel', 'bicubic', 'bilinear', 'blackman', 'catrom', 'gaussian',
'hamming', 'hanning', 'hermite', 'kaiser', 'lanczos', 'mitchell',
'nearest', 'spline16', 'spline36'
}: Equipped interpolation method's name.
"""
return str(self._interpolation)
@interpolation.setter
def interpolation(self, interpolation):
self._interpolation = Interpolation(interpolation)
self.events.interpolation()
@property
def rendering(self):
"""Rendering: Rendering mode.
Selects a preset rendering mode in vispy that determines how
volume is displayed
* translucent: voxel colors are blended along the view ray until
the result is opaque.
* mip: maxiumum intensity projection. Cast a ray and display the
maximum value that was encountered.
* additive: voxel colors are added along the view ray until
the result is saturated.
* iso: isosurface. Cast a ray until a certain threshold is
encountered. At that location, lighning calculations are
performed to give the visual appearance of a surface.
* attenuated_mip: attenuated maxiumum intensity projection. Cast a
ray and attenuate values based on integral of encountered values,
display the maximum value that was encountered after attenuation.
This will make nearer objects appear more prominent.
"""
return str(self._rendering)
@rendering.setter
def rendering(self, rendering):
self._rendering = Rendering(rendering)
self.events.rendering()
def _get_state(self):
"""Get dictionary of layer state.
Returns
-------
state : dict
Dictionary of layer state.
"""
state = self._get_base_state()
state.update(
{
'rgb': self.rgb,
'is_pyramid': self.is_pyramid,
'colormap': self.colormap[0],
'contrast_limits': self.contrast_limits,
'interpolation': self.interpolation,
'rendering': self.rendering,
'iso_threshold': self.iso_threshold,
'attenuation': self.attenuation,
'gamma': self.gamma,
'data': self.data,
}
)
return state
def _raw_to_displayed(self, raw):
"""Determine displayed image from raw image.
For normal image layers, just return the actual image.
Parameters
-------
raw : array
Raw array.
Returns
-------
image : array
Displayed array.
"""
image = raw
return image
def _set_view_slice(self):
"""Set the view given the indices to slice with."""
not_disp = self.dims.not_displayed
if self.rgb:
# if rgb need to keep the final axis fixed during the
# transpose. The index of the final axis depends on how many
# axes are displayed.
order = self.dims.displayed_order + (
max(self.dims.displayed_order) + 1,
)
else:
order = self.dims.displayed_order
if self.is_pyramid:
# If 3d redering just show lowest level of pyramid
if self.dims.ndisplay == 3:
self.data_level = len(self._data_pyramid) - 1
# Slice currently viewed level
level = self.data_level
indices = np.array(self.dims.indices)
downsampled_indices = (
indices[not_disp] / self.level_downsamples[level, not_disp]
)
downsampled_indices = np.round(
downsampled_indices.astype(float)
).astype(int)
downsampled_indices = np.clip(
downsampled_indices, 0, self.level_shapes[level, not_disp] - 1
)
indices[not_disp] = downsampled_indices
disp_shape = self.level_shapes[level, self.dims.displayed]
scale = np.ones(self.ndim)
for d in self.dims.displayed:
scale[d] = self.level_downsamples[self.data_level][d]
self._transform_view.scale = scale
if np.any(disp_shape > self._max_tile_shape):
for d in self.dims.displayed:
indices[d] = slice(
self._top_left[d],
self._top_left[d] + self._max_tile_shape,
1,
)
self._transform_view.translate = (
self._top_left * self.scale * self._transform_view.scale
)
else:
self._transform_view.translate = [0] * self.ndim
image = np.asarray(
self._data_pyramid[level][tuple(indices)]
).transpose(order)
if level == len(self._data_pyramid) - 1:
thumbnail = image
else:
# Slice thumbnail
indices = np.array(self.dims.indices)
downsampled_indices = (
indices[not_disp] / self.level_downsamples[-1, not_disp]
)
downsampled_indices = np.round(
downsampled_indices.astype(float)
).astype(int)
downsampled_indices = np.clip(
downsampled_indices, 0, self.level_shapes[-1, not_disp] - 1
)
indices[not_disp] = downsampled_indices
thumbnail = np.asarray(
self._data_pyramid[-1][tuple(indices)]
).transpose(order)
else:
self._transform_view.scale = np.ones(self.dims.ndim)
image = np.asarray(self.data[self.dims.indices]).transpose(order)
thumbnail = image
if self.rgb and image.dtype.kind == 'f':
self._data_raw = np.clip(image, 0, 1)
self._data_view = self._raw_to_displayed(self._data_raw)
self._data_thumbnail = self._raw_to_displayed(
np.clip(thumbnail, 0, 1)
)
else:
self._data_raw = image
self._data_view = self._raw_to_displayed(self._data_raw)
self._data_thumbnail = self._raw_to_displayed(thumbnail)
if self.is_pyramid:
self.events.scale()
self.events.translate()
def _update_thumbnail(self):
"""Update thumbnail with current image data and colormap."""
if self.dims.ndisplay == 3 and self.dims.ndim > 2:
image = np.max(self._data_thumbnail, axis=0)
else:
image = self._data_thumbnail
# float16 not supported by ndi.zoom
dtype = np.dtype(image.dtype)
if dtype in [np.dtype(np.float16)]:
image = image.astype(np.float32)
raw_zoom_factor = np.divide(
self._thumbnail_shape[:2], image.shape[:2]
).min()
new_shape = np.clip(
raw_zoom_factor * np.array(image.shape[:2]),
1, # smallest side should be 1 pixel wide
self._thumbnail_shape[:2],
)
zoom_factor = tuple(new_shape / image.shape[:2])
if self.rgb:
# warning filter can be removed with scipy 1.4
with warnings.catch_warnings():
warnings.simplefilter("ignore")
downsampled = ndi.zoom(
image, zoom_factor + (1,), prefilter=False, order=0
)
if image.shape[2] == 4: # image is RGBA
colormapped = np.copy(downsampled)
colormapped[..., 3] = downsampled[..., 3] * self.opacity
if downsampled.dtype == np.uint8:
colormapped = colormapped.astype(np.uint8)
else: # image is RGB
if downsampled.dtype == np.uint8:
alpha = np.full(
downsampled.shape[:2] + (1,),
int(255 * self.opacity),
dtype=np.uint8,
)
else:
alpha = np.full(downsampled.shape[:2] + (1,), self.opacity)
colormapped = np.concatenate([downsampled, alpha], axis=2)
else:
# warning filter can be removed with scipy 1.4
with warnings.catch_warnings():
warnings.simplefilter("ignore")
downsampled = ndi.zoom(
image, zoom_factor, prefilter=False, order=0
)
low, high = self.contrast_limits
downsampled = np.clip(downsampled, low, high)
color_range = high - low
if color_range != 0:
downsampled = (downsampled - low) / color_range
downsampled = downsampled ** self.gamma
color_array = self.colormap[1][downsampled.ravel()]
colormapped = color_array.rgba.reshape(downsampled.shape + (4,))
colormapped[..., 3] *= self.opacity
self.thumbnail = colormapped
def _get_value(self):
"""Returns coordinates, values, and a string for a given mouse position
and set of indices.
Returns
----------
value : tuple
Value of the data at the coord.
"""
coord = np.round(self.coordinates).astype(int)
if self.rgb:
shape = self._data_raw.shape[:-1]
else:
shape = self._data_raw.shape
if all(0 <= c < s for c, s in zip(coord[self.dims.displayed], shape)):
value = self._data_raw[tuple(coord[self.dims.displayed])]
else:
value = None
if self.is_pyramid:
value = (self.data_level, value)
return value
def to_xml_list(self):
"""Generates a list with a single xml element that defines the
currently viewed image as a png according to the svg specification.
Returns
----------
xml : list of xml.etree.ElementTree.Element
List of a single xml element specifying the currently viewed image
as a png according to the svg specification.
"""
if self.dims.ndisplay == 3:
image = np.max(self._data_thumbnail, axis=0)
else:
image = self._data_thumbnail
image = np.clip(
image, self.contrast_limits[0], self.contrast_limits[1]
)
image = image - self.contrast_limits[0]
color_range = self.contrast_limits[1] - self.contrast_limits[0]
if color_range != 0:
image = image / color_range
mapped_image = self.colormap[1][image.ravel()]
mapped_image = mapped_image.RGBA.reshape(image.shape + (4,))
image_str = imwrite('<bytes>', mapped_image, format='png')
image_str = "data:image/png;base64," + str(b64encode(image_str))[2:-1]
props = {'xlink:href': image_str}
width = str(self.shape[self.dims.displayed[1]])
height = str(self.shape[self.dims.displayed[0]])
opacity = str(self.opacity)
xml = Element(
'image', width=width, height=height, opacity=opacity, **props
)
return [xml]
| 35.84 | 79 | 0.588661 | import types
import warnings
from base64 import b64encode
from xml.etree.ElementTree import Element
import numpy as np
from imageio import imwrite
from scipy import ndimage as ndi
from ...utils.colormaps import AVAILABLE_COLORMAPS
from ...utils.event import Event
from ...utils.status_messages import format_float
from ..base import Layer
from ..layer_utils import calc_data_range
from ..intensity_mixin import IntensityVisualizationMixin
from ._constants import Interpolation, Rendering
from .image_utils import get_pyramid_and_rgb
class Image(IntensityVisualizationMixin, Layer):
_colormaps = AVAILABLE_COLORMAPS
_max_tile_shape = 1600
def __init__(
self,
data,
*,
rgb=None,
is_pyramid=None,
colormap='gray',
contrast_limits=None,
gamma=1,
interpolation='nearest',
rendering='mip',
iso_threshold=0.5,
attenuation=0.5,
name=None,
metadata=None,
scale=None,
translate=None,
opacity=1,
blending='translucent',
visible=True,
):
if isinstance(data, types.GeneratorType):
data = list(data)
ndim, rgb, is_pyramid, data_pyramid = get_pyramid_and_rgb(
data, pyramid=is_pyramid, rgb=rgb
)
super().__init__(
data,
ndim,
name=name,
metadata=metadata,
scale=scale,
translate=translate,
opacity=opacity,
blending=blending,
visible=visible,
)
self.events.add(
interpolation=Event,
rendering=Event,
iso_threshold=Event,
attenuation=Event,
)
self.is_pyramid = is_pyramid
self.rgb = rgb
self._data = data
self._data_pyramid = data_pyramid
self._top_left = np.zeros(ndim, dtype=int)
if self.is_pyramid:
self._data_level = len(data_pyramid) - 1
else:
self._data_level = 0
if self.rgb:
self._data_view = np.zeros(
(1,) * self.dims.ndisplay + (self.shape[-1],)
)
else:
self._data_view = np.zeros((1,) * self.dims.ndisplay)
self._data_raw = self._data_view
self._data_thumbnail = self._data_view
self._gamma = gamma
self._iso_threshold = iso_threshold
self._attenuation = attenuation
if contrast_limits is None:
self.contrast_limits_range = self._calc_data_range()
else:
self.contrast_limits_range = contrast_limits
self._contrast_limits = tuple(self.contrast_limits_range)
self.colormap = colormap
self.contrast_limits = self._contrast_limits
self.interpolation = interpolation
self.rendering = rendering
self._update_dims()
def _calc_data_range(self):
if self.is_pyramid:
input_data = self._data_pyramid[-1]
else:
input_data = self.data
return calc_data_range(input_data)
@property
def dtype(self):
return self.data[0].dtype if self.is_pyramid else self.data.dtype
@property
def data(self):
return self._data
@data.setter
def data(self, data):
ndim, rgb, is_pyramid, data_pyramid = get_pyramid_and_rgb(
data, pyramid=self.is_pyramid, rgb=self.rgb
)
self.is_pyramid = is_pyramid
self.rgb = rgb
self._data = data
self._data_pyramid = data_pyramid
self._update_dims()
self.events.data()
def _get_ndim(self):
return len(self.level_shapes[0])
def _get_extent(self):
return tuple((0, m) for m in self.level_shapes[0])
@property
def data_level(self):
return self._data_level
@data_level.setter
def data_level(self, level):
if self._data_level == level:
return
self._data_level = level
self.refresh()
@property
def level_shapes(self):
if self.is_pyramid:
if self.rgb:
shapes = [im.shape[:-1] for im in self._data_pyramid]
else:
shapes = [im.shape for im in self._data_pyramid]
else:
if self.rgb:
shapes = [self.data.shape[:-1]]
else:
shapes = [self.data.shape]
return np.array(shapes)
@property
def level_downsamples(self):
return np.divide(self.level_shapes[0], self.level_shapes)
@property
def top_left(self):
return self._top_left
@top_left.setter
def top_left(self, top_left):
if np.all(self._top_left == top_left):
return
self._top_left = top_left.astype(int)
self.refresh()
@property
def iso_threshold(self):
return self._iso_threshold
@iso_threshold.setter
def iso_threshold(self, value):
self.status = format_float(value)
self._iso_threshold = value
self._update_thumbnail()
self.events.iso_threshold()
@property
def attenuation(self):
return self._attenuation
@attenuation.setter
def attenuation(self, value):
self.status = format_float(value)
self._attenuation = value
self._update_thumbnail()
self.events.attenuation()
@property
def interpolation(self):
return str(self._interpolation)
@interpolation.setter
def interpolation(self, interpolation):
self._interpolation = Interpolation(interpolation)
self.events.interpolation()
@property
def rendering(self):
return str(self._rendering)
@rendering.setter
def rendering(self, rendering):
self._rendering = Rendering(rendering)
self.events.rendering()
def _get_state(self):
state = self._get_base_state()
state.update(
{
'rgb': self.rgb,
'is_pyramid': self.is_pyramid,
'colormap': self.colormap[0],
'contrast_limits': self.contrast_limits,
'interpolation': self.interpolation,
'rendering': self.rendering,
'iso_threshold': self.iso_threshold,
'attenuation': self.attenuation,
'gamma': self.gamma,
'data': self.data,
}
)
return state
def _raw_to_displayed(self, raw):
image = raw
return image
def _set_view_slice(self):
not_disp = self.dims.not_displayed
if self.rgb:
order = self.dims.displayed_order + (
max(self.dims.displayed_order) + 1,
)
else:
order = self.dims.displayed_order
if self.is_pyramid:
if self.dims.ndisplay == 3:
self.data_level = len(self._data_pyramid) - 1
level = self.data_level
indices = np.array(self.dims.indices)
downsampled_indices = (
indices[not_disp] / self.level_downsamples[level, not_disp]
)
downsampled_indices = np.round(
downsampled_indices.astype(float)
).astype(int)
downsampled_indices = np.clip(
downsampled_indices, 0, self.level_shapes[level, not_disp] - 1
)
indices[not_disp] = downsampled_indices
disp_shape = self.level_shapes[level, self.dims.displayed]
scale = np.ones(self.ndim)
for d in self.dims.displayed:
scale[d] = self.level_downsamples[self.data_level][d]
self._transform_view.scale = scale
if np.any(disp_shape > self._max_tile_shape):
for d in self.dims.displayed:
indices[d] = slice(
self._top_left[d],
self._top_left[d] + self._max_tile_shape,
1,
)
self._transform_view.translate = (
self._top_left * self.scale * self._transform_view.scale
)
else:
self._transform_view.translate = [0] * self.ndim
image = np.asarray(
self._data_pyramid[level][tuple(indices)]
).transpose(order)
if level == len(self._data_pyramid) - 1:
thumbnail = image
else:
indices = np.array(self.dims.indices)
downsampled_indices = (
indices[not_disp] / self.level_downsamples[-1, not_disp]
)
downsampled_indices = np.round(
downsampled_indices.astype(float)
).astype(int)
downsampled_indices = np.clip(
downsampled_indices, 0, self.level_shapes[-1, not_disp] - 1
)
indices[not_disp] = downsampled_indices
thumbnail = np.asarray(
self._data_pyramid[-1][tuple(indices)]
).transpose(order)
else:
self._transform_view.scale = np.ones(self.dims.ndim)
image = np.asarray(self.data[self.dims.indices]).transpose(order)
thumbnail = image
if self.rgb and image.dtype.kind == 'f':
self._data_raw = np.clip(image, 0, 1)
self._data_view = self._raw_to_displayed(self._data_raw)
self._data_thumbnail = self._raw_to_displayed(
np.clip(thumbnail, 0, 1)
)
else:
self._data_raw = image
self._data_view = self._raw_to_displayed(self._data_raw)
self._data_thumbnail = self._raw_to_displayed(thumbnail)
if self.is_pyramid:
self.events.scale()
self.events.translate()
def _update_thumbnail(self):
if self.dims.ndisplay == 3 and self.dims.ndim > 2:
image = np.max(self._data_thumbnail, axis=0)
else:
image = self._data_thumbnail
dtype = np.dtype(image.dtype)
if dtype in [np.dtype(np.float16)]:
image = image.astype(np.float32)
raw_zoom_factor = np.divide(
self._thumbnail_shape[:2], image.shape[:2]
).min()
new_shape = np.clip(
raw_zoom_factor * np.array(image.shape[:2]),
1,
self._thumbnail_shape[:2],
)
zoom_factor = tuple(new_shape / image.shape[:2])
if self.rgb:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
downsampled = ndi.zoom(
image, zoom_factor + (1,), prefilter=False, order=0
)
if image.shape[2] == 4:
colormapped = np.copy(downsampled)
colormapped[..., 3] = downsampled[..., 3] * self.opacity
if downsampled.dtype == np.uint8:
colormapped = colormapped.astype(np.uint8)
else:
if downsampled.dtype == np.uint8:
alpha = np.full(
downsampled.shape[:2] + (1,),
int(255 * self.opacity),
dtype=np.uint8,
)
else:
alpha = np.full(downsampled.shape[:2] + (1,), self.opacity)
colormapped = np.concatenate([downsampled, alpha], axis=2)
else:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
downsampled = ndi.zoom(
image, zoom_factor, prefilter=False, order=0
)
low, high = self.contrast_limits
downsampled = np.clip(downsampled, low, high)
color_range = high - low
if color_range != 0:
downsampled = (downsampled - low) / color_range
downsampled = downsampled ** self.gamma
color_array = self.colormap[1][downsampled.ravel()]
colormapped = color_array.rgba.reshape(downsampled.shape + (4,))
colormapped[..., 3] *= self.opacity
self.thumbnail = colormapped
def _get_value(self):
coord = np.round(self.coordinates).astype(int)
if self.rgb:
shape = self._data_raw.shape[:-1]
else:
shape = self._data_raw.shape
if all(0 <= c < s for c, s in zip(coord[self.dims.displayed], shape)):
value = self._data_raw[tuple(coord[self.dims.displayed])]
else:
value = None
if self.is_pyramid:
value = (self.data_level, value)
return value
def to_xml_list(self):
if self.dims.ndisplay == 3:
image = np.max(self._data_thumbnail, axis=0)
else:
image = self._data_thumbnail
image = np.clip(
image, self.contrast_limits[0], self.contrast_limits[1]
)
image = image - self.contrast_limits[0]
color_range = self.contrast_limits[1] - self.contrast_limits[0]
if color_range != 0:
image = image / color_range
mapped_image = self.colormap[1][image.ravel()]
mapped_image = mapped_image.RGBA.reshape(image.shape + (4,))
image_str = imwrite('<bytes>', mapped_image, format='png')
image_str = "data:image/png;base64," + str(b64encode(image_str))[2:-1]
props = {'xlink:href': image_str}
width = str(self.shape[self.dims.displayed[1]])
height = str(self.shape[self.dims.displayed[0]])
opacity = str(self.opacity)
xml = Element(
'image', width=width, height=height, opacity=opacity, **props
)
return [xml]
| true | true |
f7f6c390b7d7bbb8fca2e648af804e8194a7f300 | 3,487 | py | Python | setup.py | auvipy/django-vanilla-views | 26cc09258bcd3d8be3f11d91b11077092f627218 | [
"BSD-2-Clause"
] | null | null | null | setup.py | auvipy/django-vanilla-views | 26cc09258bcd3d8be3f11d91b11077092f627218 | [
"BSD-2-Clause"
] | null | null | null | setup.py | auvipy/django-vanilla-views | 26cc09258bcd3d8be3f11d91b11077092f627218 | [
"BSD-2-Clause"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from setuptools import setup
import re
import os
import sys
name = 'django-vanilla-views'
package = 'vanilla'
description = 'Beautifully simple class based views.'
url = 'http://django-vanilla-views.org'
author = 'Tom Christie'
author_email = 'tom@tomchristie.com'
license = 'BSD'
install_requires = [
'six',
]
long_description = """Django's generic class based view implementation is unneccesarily complicated.
Django vanilla views gives you all the same functionality, in a vastly simplified, easier-to-use package, including:
* No mixin classes.
* No calls to super().
* A sane class hierarchy.
* A stripped down API.
* Simpler method implementations, with less magical behavior.
Remember, even though the API has been greatly simplified, everything you're able to do with Django's existing implementation is also supported in django-vanilla-views."""
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = open(os.path.join(package, '__init__.py')).read()
return re.search("^__version__ = ['\"]([^'\"]+)['\"]", init_py, re.MULTILINE).group(1)
def get_packages(package):
"""
Return root package and all sub-packages.
"""
return [dirpath
for dirpath, dirnames, filenames in os.walk(package)
if os.path.exists(os.path.join(dirpath, '__init__.py'))]
def get_package_data(package):
"""
Return all files under the root package, that are not in a
package themselves.
"""
walk = [(dirpath.replace(package + os.sep, '', 1), filenames)
for dirpath, dirnames, filenames in os.walk(package)
if not os.path.exists(os.path.join(dirpath, '__init__.py'))]
filepaths = []
for base, filenames in walk:
filepaths.extend([os.path.join(base, filename)
for filename in filenames])
return {package: filepaths}
if sys.argv[-1] == 'publish':
os.system("python setup.py sdist bdist_wheel upload")
args = {'version': get_version(package)}
print("You probably want to also tag the version now:")
print(" git tag -a %(version)s -m 'version %(version)s'" % args)
print(" git push --tags")
sys.exit()
setup(
name=name,
version=get_version(package),
url=url,
license=license,
description=description,
long_description=long_description,
author=author,
author_email=author_email,
license_file="LICENSE",
packages=get_packages(package),
package_data=get_package_data(package),
project_urls={
"Changelog": "http://django-vanilla-views.org/topics/release-notes",
"Repository": "https://github.com/tomchristie/django-vanilla-views/",
},
python_requires=">=3.5",
install_requires=install_requires,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Framework :: Django :: 2.1',
'Framework :: Django :: 2.2',
'Framework :: Django :: 3.0',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP',
]
)
| 31.414414 | 171 | 0.65271 |
from __future__ import print_function
from setuptools import setup
import re
import os
import sys
name = 'django-vanilla-views'
package = 'vanilla'
description = 'Beautifully simple class based views.'
url = 'http://django-vanilla-views.org'
author = 'Tom Christie'
author_email = 'tom@tomchristie.com'
license = 'BSD'
install_requires = [
'six',
]
long_description = """Django's generic class based view implementation is unneccesarily complicated.
Django vanilla views gives you all the same functionality, in a vastly simplified, easier-to-use package, including:
* No mixin classes.
* No calls to super().
* A sane class hierarchy.
* A stripped down API.
* Simpler method implementations, with less magical behavior.
Remember, even though the API has been greatly simplified, everything you're able to do with Django's existing implementation is also supported in django-vanilla-views."""
def get_version(package):
init_py = open(os.path.join(package, '__init__.py')).read()
return re.search("^__version__ = ['\"]([^'\"]+)['\"]", init_py, re.MULTILINE).group(1)
def get_packages(package):
return [dirpath
for dirpath, dirnames, filenames in os.walk(package)
if os.path.exists(os.path.join(dirpath, '__init__.py'))]
def get_package_data(package):
walk = [(dirpath.replace(package + os.sep, '', 1), filenames)
for dirpath, dirnames, filenames in os.walk(package)
if not os.path.exists(os.path.join(dirpath, '__init__.py'))]
filepaths = []
for base, filenames in walk:
filepaths.extend([os.path.join(base, filename)
for filename in filenames])
return {package: filepaths}
if sys.argv[-1] == 'publish':
os.system("python setup.py sdist bdist_wheel upload")
args = {'version': get_version(package)}
print("You probably want to also tag the version now:")
print(" git tag -a %(version)s -m 'version %(version)s'" % args)
print(" git push --tags")
sys.exit()
setup(
name=name,
version=get_version(package),
url=url,
license=license,
description=description,
long_description=long_description,
author=author,
author_email=author_email,
license_file="LICENSE",
packages=get_packages(package),
package_data=get_package_data(package),
project_urls={
"Changelog": "http://django-vanilla-views.org/topics/release-notes",
"Repository": "https://github.com/tomchristie/django-vanilla-views/",
},
python_requires=">=3.5",
install_requires=install_requires,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Framework :: Django :: 2.1',
'Framework :: Django :: 2.2',
'Framework :: Django :: 3.0',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP',
]
)
| true | true |
f7f6c45ae21eb8b93a278267acc1dacabe838435 | 415 | py | Python | trove_dashboard/dashboard.py | rmyers/trove-dashboard | 94089c8eeb1a5ae41a89e0955d0eabbdfcccda51 | [
"Apache-2.0"
] | null | null | null | trove_dashboard/dashboard.py | rmyers/trove-dashboard | 94089c8eeb1a5ae41a89e0955d0eabbdfcccda51 | [
"Apache-2.0"
] | null | null | null | trove_dashboard/dashboard.py | rmyers/trove-dashboard | 94089c8eeb1a5ae41a89e0955d0eabbdfcccda51 | [
"Apache-2.0"
] | null | null | null | from django.utils.translation import ugettext_lazy as _
import horizon
class TrovePanels(horizon.PanelGroup):
slug = "database"
name = _("Manage Databases")
panels = ['databases', 'database_backups', 'empty']
class Dbaas(horizon.Dashboard):
name = _("Databases")
slug = "database"
panels = [TrovePanels]
default_panel = 'empty'
supports_tenants = True
horizon.register(Dbaas)
| 19.761905 | 55 | 0.696386 | from django.utils.translation import ugettext_lazy as _
import horizon
class TrovePanels(horizon.PanelGroup):
slug = "database"
name = _("Manage Databases")
panels = ['databases', 'database_backups', 'empty']
class Dbaas(horizon.Dashboard):
name = _("Databases")
slug = "database"
panels = [TrovePanels]
default_panel = 'empty'
supports_tenants = True
horizon.register(Dbaas)
| true | true |
f7f6c5ad402d0c22f5b95dbf41ba373bf71eff97 | 8,707 | py | Python | amqtt/mqtt/protocol/broker_handler.py | FlyingDiver/amqtt | 09ac98d39a711dcff0d8f22686916e1c2495144b | [
"MIT"
] | null | null | null | amqtt/mqtt/protocol/broker_handler.py | FlyingDiver/amqtt | 09ac98d39a711dcff0d8f22686916e1c2495144b | [
"MIT"
] | null | null | null | amqtt/mqtt/protocol/broker_handler.py | FlyingDiver/amqtt | 09ac98d39a711dcff0d8f22686916e1c2495144b | [
"MIT"
] | null | null | null | # Copyright (c) 2015 Nicolas JOUANIN
#
# See the file license.txt for copying permission.
from asyncio import futures, Queue
from amqtt.mqtt.protocol.handler import ProtocolHandler
from amqtt.mqtt.connack import (
CONNECTION_ACCEPTED,
UNACCEPTABLE_PROTOCOL_VERSION,
IDENTIFIER_REJECTED,
BAD_USERNAME_PASSWORD,
NOT_AUTHORIZED,
ConnackPacket,
)
from amqtt.mqtt.connect import ConnectPacket
from amqtt.mqtt.pingreq import PingReqPacket
from amqtt.mqtt.pingresp import PingRespPacket
from amqtt.mqtt.subscribe import SubscribePacket
from amqtt.mqtt.suback import SubackPacket
from amqtt.mqtt.unsubscribe import UnsubscribePacket
from amqtt.mqtt.unsuback import UnsubackPacket
from amqtt.utils import format_client_message
from amqtt.session import Session
from amqtt.plugins.manager import PluginManager
from amqtt.adapters import ReaderAdapter, WriterAdapter
from amqtt.errors import MQTTException
from .handler import EVENT_MQTT_PACKET_RECEIVED, EVENT_MQTT_PACKET_SENT
class BrokerProtocolHandler(ProtocolHandler):
def __init__(
self, plugins_manager: PluginManager, session: Session = None, loop=None
):
super().__init__(plugins_manager, session, loop)
self._disconnect_waiter = None
self._pending_subscriptions = Queue()
self._pending_unsubscriptions = Queue()
async def start(self):
await super().start()
if self._disconnect_waiter is None:
self._disconnect_waiter = futures.Future()
async def stop(self):
await super().stop()
if self._disconnect_waiter is not None and not self._disconnect_waiter.done():
self._disconnect_waiter.set_result(None)
async def wait_disconnect(self):
return await self._disconnect_waiter
def handle_write_timeout(self):
pass
def handle_read_timeout(self):
if self._disconnect_waiter is not None and not self._disconnect_waiter.done():
self._disconnect_waiter.set_result(None)
async def handle_disconnect(self, disconnect):
self.logger.debug("Client disconnecting")
if self._disconnect_waiter and not self._disconnect_waiter.done():
self.logger.debug("Setting waiter result to %r" % disconnect)
self._disconnect_waiter.set_result(disconnect)
async def handle_connection_closed(self):
await self.handle_disconnect(None)
async def handle_connect(self, connect: ConnectPacket):
# Broker handler shouldn't received CONNECT message during messages handling
# as CONNECT messages are managed by the broker on client connection
self.logger.error(
"%s [MQTT-3.1.0-2] %s : CONNECT message received during messages handling"
% (self.session.client_id, format_client_message(self.session))
)
if self._disconnect_waiter is not None and not self._disconnect_waiter.done():
self._disconnect_waiter.set_result(None)
async def handle_pingreq(self, pingreq: PingReqPacket):
await self._send_packet(PingRespPacket.build())
async def handle_subscribe(self, subscribe: SubscribePacket):
subscription = {
"packet_id": subscribe.variable_header.packet_id,
"topics": subscribe.payload.topics,
}
await self._pending_subscriptions.put(subscription)
async def handle_unsubscribe(self, unsubscribe: UnsubscribePacket):
unsubscription = {
"packet_id": unsubscribe.variable_header.packet_id,
"topics": unsubscribe.payload.topics,
}
await self._pending_unsubscriptions.put(unsubscription)
async def get_next_pending_subscription(self):
subscription = await self._pending_subscriptions.get()
return subscription
async def get_next_pending_unsubscription(self):
unsubscription = await self._pending_unsubscriptions.get()
return unsubscription
async def mqtt_acknowledge_subscription(self, packet_id, return_codes):
suback = SubackPacket.build(packet_id, return_codes)
await self._send_packet(suback)
async def mqtt_acknowledge_unsubscription(self, packet_id):
unsuback = UnsubackPacket.build(packet_id)
await self._send_packet(unsuback)
async def mqtt_connack_authorize(self, authorize: bool):
if authorize:
connack = ConnackPacket.build(self.session.parent, CONNECTION_ACCEPTED)
else:
connack = ConnackPacket.build(self.session.parent, NOT_AUTHORIZED)
await self._send_packet(connack)
@classmethod
async def init_from_connect(
cls, reader: ReaderAdapter, writer: WriterAdapter, plugins_manager, loop=None
):
"""
:param reader:
:param writer:
:param plugins_manager:
:param loop:
:return:
"""
remote_address, remote_port = writer.get_peer_info()
connect = await ConnectPacket.from_stream(reader)
await plugins_manager.fire_event(EVENT_MQTT_PACKET_RECEIVED, packet=connect)
# this shouldn't be required anymore since broker generates for each client a random client_id if not provided
# [MQTT-3.1.3-6]
if connect.payload.client_id is None:
raise MQTTException("[[MQTT-3.1.3-3]] : Client identifier must be present")
if connect.variable_header.will_flag:
if (
connect.payload.will_topic is None
or connect.payload.will_message is None
):
raise MQTTException(
"will flag set, but will topic/message not present in payload"
)
if connect.variable_header.reserved_flag:
raise MQTTException("[MQTT-3.1.2-3] CONNECT reserved flag must be set to 0")
if connect.proto_name != "MQTT":
raise MQTTException(
'[MQTT-3.1.2-1] Incorrect protocol name: "%s"' % connect.proto_name
)
connack = None
error_msg = None
if connect.proto_level != 4:
# only MQTT 3.1.1 supported
error_msg = "Invalid protocol from %s: %d" % (
format_client_message(address=remote_address, port=remote_port),
connect.proto_level,
)
connack = ConnackPacket.build(
0, UNACCEPTABLE_PROTOCOL_VERSION
) # [MQTT-3.2.2-4] session_parent=0
elif not connect.username_flag and connect.password_flag:
connack = ConnackPacket.build(0, BAD_USERNAME_PASSWORD) # [MQTT-3.1.2-22]
elif connect.username_flag and connect.username is None:
error_msg = "Invalid username from %s" % (
format_client_message(address=remote_address, port=remote_port)
)
connack = ConnackPacket.build(
0, BAD_USERNAME_PASSWORD
) # [MQTT-3.2.2-4] session_parent=0
elif connect.password_flag and connect.password is None:
error_msg = "Invalid password %s" % (
format_client_message(address=remote_address, port=remote_port)
)
connack = ConnackPacket.build(
0, BAD_USERNAME_PASSWORD
) # [MQTT-3.2.2-4] session_parent=0
elif connect.clean_session_flag is False and (
connect.payload.client_id_is_random
):
error_msg = (
"[MQTT-3.1.3-8] [MQTT-3.1.3-9] %s: No client Id provided (cleansession=0)"
% (format_client_message(address=remote_address, port=remote_port))
)
connack = ConnackPacket.build(0, IDENTIFIER_REJECTED)
if connack is not None:
await plugins_manager.fire_event(EVENT_MQTT_PACKET_SENT, packet=connack)
await connack.to_stream(writer)
await writer.close()
raise MQTTException(error_msg)
incoming_session = Session()
incoming_session.client_id = connect.client_id
incoming_session.clean_session = connect.clean_session_flag
incoming_session.will_flag = connect.will_flag
incoming_session.will_retain = connect.will_retain_flag
incoming_session.will_qos = connect.will_qos
incoming_session.will_topic = connect.will_topic
incoming_session.will_message = connect.will_message
incoming_session.username = connect.username
incoming_session.password = connect.password
if connect.keep_alive > 0:
incoming_session.keep_alive = connect.keep_alive
else:
incoming_session.keep_alive = 0
handler = cls(plugins_manager, loop=loop)
return handler, incoming_session
| 41.265403 | 118 | 0.676238 |
from asyncio import futures, Queue
from amqtt.mqtt.protocol.handler import ProtocolHandler
from amqtt.mqtt.connack import (
CONNECTION_ACCEPTED,
UNACCEPTABLE_PROTOCOL_VERSION,
IDENTIFIER_REJECTED,
BAD_USERNAME_PASSWORD,
NOT_AUTHORIZED,
ConnackPacket,
)
from amqtt.mqtt.connect import ConnectPacket
from amqtt.mqtt.pingreq import PingReqPacket
from amqtt.mqtt.pingresp import PingRespPacket
from amqtt.mqtt.subscribe import SubscribePacket
from amqtt.mqtt.suback import SubackPacket
from amqtt.mqtt.unsubscribe import UnsubscribePacket
from amqtt.mqtt.unsuback import UnsubackPacket
from amqtt.utils import format_client_message
from amqtt.session import Session
from amqtt.plugins.manager import PluginManager
from amqtt.adapters import ReaderAdapter, WriterAdapter
from amqtt.errors import MQTTException
from .handler import EVENT_MQTT_PACKET_RECEIVED, EVENT_MQTT_PACKET_SENT
class BrokerProtocolHandler(ProtocolHandler):
def __init__(
self, plugins_manager: PluginManager, session: Session = None, loop=None
):
super().__init__(plugins_manager, session, loop)
self._disconnect_waiter = None
self._pending_subscriptions = Queue()
self._pending_unsubscriptions = Queue()
async def start(self):
await super().start()
if self._disconnect_waiter is None:
self._disconnect_waiter = futures.Future()
async def stop(self):
await super().stop()
if self._disconnect_waiter is not None and not self._disconnect_waiter.done():
self._disconnect_waiter.set_result(None)
async def wait_disconnect(self):
return await self._disconnect_waiter
def handle_write_timeout(self):
pass
def handle_read_timeout(self):
if self._disconnect_waiter is not None and not self._disconnect_waiter.done():
self._disconnect_waiter.set_result(None)
async def handle_disconnect(self, disconnect):
self.logger.debug("Client disconnecting")
if self._disconnect_waiter and not self._disconnect_waiter.done():
self.logger.debug("Setting waiter result to %r" % disconnect)
self._disconnect_waiter.set_result(disconnect)
async def handle_connection_closed(self):
await self.handle_disconnect(None)
async def handle_connect(self, connect: ConnectPacket):
# as CONNECT messages are managed by the broker on client connection
self.logger.error(
"%s [MQTT-3.1.0-2] %s : CONNECT message received during messages handling"
% (self.session.client_id, format_client_message(self.session))
)
if self._disconnect_waiter is not None and not self._disconnect_waiter.done():
self._disconnect_waiter.set_result(None)
async def handle_pingreq(self, pingreq: PingReqPacket):
await self._send_packet(PingRespPacket.build())
async def handle_subscribe(self, subscribe: SubscribePacket):
subscription = {
"packet_id": subscribe.variable_header.packet_id,
"topics": subscribe.payload.topics,
}
await self._pending_subscriptions.put(subscription)
async def handle_unsubscribe(self, unsubscribe: UnsubscribePacket):
unsubscription = {
"packet_id": unsubscribe.variable_header.packet_id,
"topics": unsubscribe.payload.topics,
}
await self._pending_unsubscriptions.put(unsubscription)
async def get_next_pending_subscription(self):
subscription = await self._pending_subscriptions.get()
return subscription
async def get_next_pending_unsubscription(self):
unsubscription = await self._pending_unsubscriptions.get()
return unsubscription
async def mqtt_acknowledge_subscription(self, packet_id, return_codes):
suback = SubackPacket.build(packet_id, return_codes)
await self._send_packet(suback)
async def mqtt_acknowledge_unsubscription(self, packet_id):
unsuback = UnsubackPacket.build(packet_id)
await self._send_packet(unsuback)
async def mqtt_connack_authorize(self, authorize: bool):
if authorize:
connack = ConnackPacket.build(self.session.parent, CONNECTION_ACCEPTED)
else:
connack = ConnackPacket.build(self.session.parent, NOT_AUTHORIZED)
await self._send_packet(connack)
@classmethod
async def init_from_connect(
cls, reader: ReaderAdapter, writer: WriterAdapter, plugins_manager, loop=None
):
remote_address, remote_port = writer.get_peer_info()
connect = await ConnectPacket.from_stream(reader)
await plugins_manager.fire_event(EVENT_MQTT_PACKET_RECEIVED, packet=connect)
# this shouldn't be required anymore since broker generates for each client a random client_id if not provided
if connect.payload.client_id is None:
raise MQTTException("[[MQTT-3.1.3-3]] : Client identifier must be present")
if connect.variable_header.will_flag:
if (
connect.payload.will_topic is None
or connect.payload.will_message is None
):
raise MQTTException(
"will flag set, but will topic/message not present in payload"
)
if connect.variable_header.reserved_flag:
raise MQTTException("[MQTT-3.1.2-3] CONNECT reserved flag must be set to 0")
if connect.proto_name != "MQTT":
raise MQTTException(
'[MQTT-3.1.2-1] Incorrect protocol name: "%s"' % connect.proto_name
)
connack = None
error_msg = None
if connect.proto_level != 4:
error_msg = "Invalid protocol from %s: %d" % (
format_client_message(address=remote_address, port=remote_port),
connect.proto_level,
)
connack = ConnackPacket.build(
0, UNACCEPTABLE_PROTOCOL_VERSION
)
elif not connect.username_flag and connect.password_flag:
connack = ConnackPacket.build(0, BAD_USERNAME_PASSWORD)
elif connect.username_flag and connect.username is None:
error_msg = "Invalid username from %s" % (
format_client_message(address=remote_address, port=remote_port)
)
connack = ConnackPacket.build(
0, BAD_USERNAME_PASSWORD
)
elif connect.password_flag and connect.password is None:
error_msg = "Invalid password %s" % (
format_client_message(address=remote_address, port=remote_port)
)
connack = ConnackPacket.build(
0, BAD_USERNAME_PASSWORD
)
elif connect.clean_session_flag is False and (
connect.payload.client_id_is_random
):
error_msg = (
"[MQTT-3.1.3-8] [MQTT-3.1.3-9] %s: No client Id provided (cleansession=0)"
% (format_client_message(address=remote_address, port=remote_port))
)
connack = ConnackPacket.build(0, IDENTIFIER_REJECTED)
if connack is not None:
await plugins_manager.fire_event(EVENT_MQTT_PACKET_SENT, packet=connack)
await connack.to_stream(writer)
await writer.close()
raise MQTTException(error_msg)
incoming_session = Session()
incoming_session.client_id = connect.client_id
incoming_session.clean_session = connect.clean_session_flag
incoming_session.will_flag = connect.will_flag
incoming_session.will_retain = connect.will_retain_flag
incoming_session.will_qos = connect.will_qos
incoming_session.will_topic = connect.will_topic
incoming_session.will_message = connect.will_message
incoming_session.username = connect.username
incoming_session.password = connect.password
if connect.keep_alive > 0:
incoming_session.keep_alive = connect.keep_alive
else:
incoming_session.keep_alive = 0
handler = cls(plugins_manager, loop=loop)
return handler, incoming_session
| true | true |
f7f6c5cf445890674eedaeff97274259e6b8b73a | 3,991 | py | Python | .history/my_classes/FirstClassFunctions/reducing_functions_20210707183124.py | minefarmer/deep-Dive-1 | b0675b853180c5b5781888266ea63a3793b8d855 | [
"Unlicense"
] | null | null | null | .history/my_classes/FirstClassFunctions/reducing_functions_20210707183124.py | minefarmer/deep-Dive-1 | b0675b853180c5b5781888266ea63a3793b8d855 | [
"Unlicense"
] | null | null | null | .history/my_classes/FirstClassFunctions/reducing_functions_20210707183124.py | minefarmer/deep-Dive-1 | b0675b853180c5b5781888266ea63a3793b8d855 | [
"Unlicense"
] | null | null | null | """Reducing Functions in Python
These are functions that recombine an iterable recursively, ending up with a single return value
Also called accumulators, aggregators, or folding functions
Example: Finding the maximum value in an iterable
a0, a1, a2, ...,, aN-1
max(a, b) _> maximum of a and b
result =a0
result = max(result, a1)
result = max(result, a2)
...
result = max(result, an-1)
# max value in a0, a1, a2, ..., an-1
the special case of sequences
(i.e. we can use indexes to access elements in the sequence)
Using a loop
"""
from msilib import sequence
from unittest import result
l = l[5, 8, 6, 10, 9] # result = 5
max_value = lambda a, b: a if a > b else b # result = max(5, 8) = 8
def max_sequence(sequence): # result = max(5, 6) = 8
result = sequence[0]
for e in sequence[1:]: # result = max(5, 10) = 10
result = max_value(result, e) # result = max(5, 10) = 10
return result # result -> 10
Notice the sequence of steps:
l = l[5, 8, 6, 10, 9] # result = 5
max_value = lambda a, b: a if a > b else b # result = max(5, 8) = 8
def max_sequence(sequence): # result = max(5, 6) = 8
result = sequence[0]
for e in sequence[1:]: # result = max(5, 10) = 10
result = max_value(result, e) # result = max(5, 10) = 10
return result # result -> 10
l = [5, 8, 6, 10, 9]
^ | | | |
| | |
5 | |
\ | |
max(5, 8) | | |
8 |
\ |
\ |
max(8, 6)
8 | |
\
max(8, 10)
10
\ |
max(10, 9)
10
result -> 10
To caculate the min: # I just need to change (max) to (min)
l = l[5, 8, 6, 10, 9] # result = 5
min_value = lambda a, b: a if a > b else b # result = max(5, 8) = 8
def min_sequence(sequence): # result = max(5, 6) = 8
result = sequence[0]
for e in sequence[1:]: # result = max(5, 10) = 10
result = min_value(result, e) # result = max(5, 10) = 10
return result # result -> 10
# I could just write:
def _reduce(fn, sequence):
result = sequence[0
for x in sequence[1:]]:
result = fn(result, x)
return result
_reduce(lambda a, b: a if a > b else b, l) # maximum
_reduce(lambda a, b: a if a < b else b, l) # minimum
# Adding all the elements to a list
add = lambda a, b: a+b
# result = 5
l = [5, 8, 6, 10, 9]
# result = add(5, 8) = 13
# result = add(13, 6) = 19
def _reduce(fn, sequence): # result = add(19, 10) = 29
result = sequence[0]
for x in sequence[1:]: # result = add(29. 9) = 38
result = fn(result, x)
return result # result = 38
_reduce(add. l)
""" The functools module
Pthon implements a reduce function that will handle any iterable, but works similarly to what I just saw.
"""
from functools import reduce
l = [5, 8, 6, 10, 9]
reduce(lambda a, b: a if a > b else b, l) # max -> 10
reduce(lambda a, b: a if a < b else b, l) # min -> 5
reduce(lambda a, b: a if a + b, l) # sum -> 38
# reduce works on any iterable
reduce(lambda a, b: a if a < b else b, {10, 5, 2, 4}) # 2
reduce(lambda a, b: a if a < b else b, 'python') # h
reduce(lambda a, b: a + ' ' + b else b, ('python', 'is', 'awesome')) # 'python is awesome'
""" Built-in Reducing Functions
Python provides several common reducing functions:
min min([5, 8, 6, 10, 9]) # 5
min min([5, 8, 6, 10, 9])
"""
| 25.748387 | 105 | 0.482085 | """Reducing Functions in Python
These are functions that recombine an iterable recursively, ending up with a single return value
Also called accumulators, aggregators, or folding functions
Example: Finding the maximum value in an iterable
a0, a1, a2, ...,, aN-1
max(a, b) _> maximum of a and b
result =a0
result = max(result, a1)
result = max(result, a2)
...
result = max(result, an-1)
# max value in a0, a1, a2, ..., an-1
the special case of sequences
(i.e. we can use indexes to access elements in the sequence)
Using a loop
"""
from msilib import sequence
from unittest import result
l = l[5, 8, 6, 10, 9]
max_value = lambda a, b: a if a > b else b
def max_sequence(sequence):
result = sequence[0]
for e in sequence[1:]:
result = max_value(result, e)
return result
Notice the sequence of steps:
l = l[5, 8, 6, 10, 9]
max_value = lambda a, b: a if a > b else b
def max_sequence(sequence):
result = sequence[0]
for e in sequence[1:]:
result = max_value(result, e)
return result
l = [5, 8, 6, 10, 9]
^ | | | |
| | |
5 | |
\ | |
max(5, 8) | | |
8 |
\ |
\ |
max(8, 6)
8 | |
\
max(8, 10)
10
\ |
max(10, 9)
10
result -> 10
To caculate the min:
l = l[5, 8, 6, 10, 9]
min_value = lambda a, b: a if a > b else b
def min_sequence(sequence):
result = sequence[0]
for e in sequence[1:]:
result = min_value(result, e)
return result
def _reduce(fn, sequence):
result = sequence[0
for x in sequence[1:]]:
result = fn(result, x)
return result
_reduce(lambda a, b: a if a > b else b, l)
_reduce(lambda a, b: a if a < b else b, l)
add = lambda a, b: a+b
l = [5, 8, 6, 10, 9]
def _reduce(fn, sequence):
result = sequence[0]
for x in sequence[1:]:
result = fn(result, x)
return result
_reduce(add. l)
""" The functools module
Pthon implements a reduce function that will handle any iterable, but works similarly to what I just saw.
"""
from functools import reduce
l = [5, 8, 6, 10, 9]
reduce(lambda a, b: a if a > b else b, l)
reduce(lambda a, b: a if a < b else b, l)
reduce(lambda a, b: a if a + b, l)
reduce(lambda a, b: a if a < b else b, {10, 5, 2, 4})
reduce(lambda a, b: a if a < b else b, 'python')
reduce(lambda a, b: a + ' ' + b else b, ('python', 'is', 'awesome'))
""" Built-in Reducing Functions
Python provides several common reducing functions:
min min([5, 8, 6, 10, 9]) # 5
min min([5, 8, 6, 10, 9])
"""
| false | true |
f7f6c6a331bc7bd58aa72b2e88dde06462ff7a26 | 94 | py | Python | petisco/__init__.py | jlamoso/petisco | bd71d28a5c0ba6ea789fa7c1529e7a2d108da53f | [
"MIT"
] | null | null | null | petisco/__init__.py | jlamoso/petisco | bd71d28a5c0ba6ea789fa7c1529e7a2d108da53f | [
"MIT"
] | null | null | null | petisco/__init__.py | jlamoso/petisco | bd71d28a5c0ba6ea789fa7c1529e7a2d108da53f | [
"MIT"
] | null | null | null | from petisco.public_api import *
from petisco import public_api
__all__ = public_api.__all__
| 18.8 | 32 | 0.829787 | from petisco.public_api import *
from petisco import public_api
__all__ = public_api.__all__
| true | true |
f7f6c8a904e43536e57b6317a1ee0247677d3e6c | 2,033 | py | Python | Unidad_6/informe_funciones.py | bloisejuli/curso_python_UNSAM | cfb6e6a8368ce239b5ff0ba0236dbf8c79772374 | [
"MIT"
] | null | null | null | Unidad_6/informe_funciones.py | bloisejuli/curso_python_UNSAM | cfb6e6a8368ce239b5ff0ba0236dbf8c79772374 | [
"MIT"
] | null | null | null | Unidad_6/informe_funciones.py | bloisejuli/curso_python_UNSAM | cfb6e6a8368ce239b5ff0ba0236dbf8c79772374 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 13 11:30:06 2021
@author: bloisejuli
"""
# informe_funciones
#%%
# Ejercicio 6.11:
# Modificá este programa informe_funciones.py del Ejercicio 6.5 de modo que todo el procesamiento de archivos de entrada de datos se
# haga usando funciones del módulo fileparse. Para lograr eso, importá fileparse como un módulo y cambiá las funciones leer_camion()
# y leer_precios() para que usen la función parse_csv().
import fileparse
def hacer_informe(camion, precios):
lista = []
diccionario_precios = dict(precios)
for lote in camion:
precio_venta = diccionario_precios[lote['nombre']]
cambio = precio_venta - lote['precio']
t = (lote['nombre'], lote['cajones'], precio_venta, cambio)
lista.append(t)
return lista
def leer_camion(nombre_archivo):
return fileparse.parse_csv(nombre_archivo, select=['nombre','cajones','precio'], types=[str,int,float])
def leer_precios (nombre_archivo):
return fileparse.parse_csv(nombre_archivo, types=[str,float], has_headers=False)
def imprimir_informe(informe):
headers = ('Nombre', 'Cajones', 'Precio', 'Cambio')
print('')
for titulo in headers:
print(f'{titulo:>10s}', end= ' ')
print('')
linea = '-'*10
print(f'{linea:>10s} {linea:>10s} {linea:>10s} {linea:>10s}', end='')
print('')
for nombre, cajones, precio, cambio in informe:
s = f'${precio:>.2f}'
print(f'{nombre:>10s} {cajones:>10d} {s:>10s} {cambio:>10.2f}')
#%%
def informe_camion(nombre_archivo_camion, nombre_archivo_precios):
precios_camion = leer_camion(nombre_archivo_camion)
precios_venta = leer_precios(nombre_archivo_precios)
informe = hacer_informe(precios_camion, precios_venta)
imprimir_informe(informe)
#%%
def main():
nombre_archivo_camion = '../Data/camion.csv'
nombre_archivo_precios = '../Data/precios.csv'
informe_camion(nombre_archivo_camion, nombre_archivo_precios)
| 29.897059 | 133 | 0.681751 |
import fileparse
def hacer_informe(camion, precios):
lista = []
diccionario_precios = dict(precios)
for lote in camion:
precio_venta = diccionario_precios[lote['nombre']]
cambio = precio_venta - lote['precio']
t = (lote['nombre'], lote['cajones'], precio_venta, cambio)
lista.append(t)
return lista
def leer_camion(nombre_archivo):
return fileparse.parse_csv(nombre_archivo, select=['nombre','cajones','precio'], types=[str,int,float])
def leer_precios (nombre_archivo):
return fileparse.parse_csv(nombre_archivo, types=[str,float], has_headers=False)
def imprimir_informe(informe):
headers = ('Nombre', 'Cajones', 'Precio', 'Cambio')
print('')
for titulo in headers:
print(f'{titulo:>10s}', end= ' ')
print('')
linea = '-'*10
print(f'{linea:>10s} {linea:>10s} {linea:>10s} {linea:>10s}', end='')
print('')
for nombre, cajones, precio, cambio in informe:
s = f'${precio:>.2f}'
print(f'{nombre:>10s} {cajones:>10d} {s:>10s} {cambio:>10.2f}')
def informe_camion(nombre_archivo_camion, nombre_archivo_precios):
precios_camion = leer_camion(nombre_archivo_camion)
precios_venta = leer_precios(nombre_archivo_precios)
informe = hacer_informe(precios_camion, precios_venta)
imprimir_informe(informe)
def main():
nombre_archivo_camion = '../Data/camion.csv'
nombre_archivo_precios = '../Data/precios.csv'
informe_camion(nombre_archivo_camion, nombre_archivo_precios)
| true | true |
f7f6c92aa86566efa77bdcc908152fdc1e659e38 | 4,202 | py | Python | _build/jupyter_execute/Score_LendingClub.py | Strabes/h2o-prod | 2bfd4c87302c2ca3219b0bc313f13c9e787d84ad | [
"MIT"
] | null | null | null | _build/jupyter_execute/Score_LendingClub.py | Strabes/h2o-prod | 2bfd4c87302c2ca3219b0bc313f13c9e787d84ad | [
"MIT"
] | null | null | null | _build/jupyter_execute/Score_LendingClub.py | Strabes/h2o-prod | 2bfd4c87302c2ca3219b0bc313f13c9e787d84ad | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# coding: utf-8
# # MOJO Scoring: Two Approaches
#
# Now we will use the model we built on the Lending Club data to score the test cases we pickled. To mimick the scoring performance we would experience if the model were implemented in a real-time environment, we will score the records one at a time. We will use the MOJO we downloaded from H2O to score these records in two different ways:
#
# 1. Use the `mojo_predict_pandas` method from the `h2o.utils.shared_utils` to score one record at a time
#
# 2. Use the java application we just built to score one record at a time. To do so, we will first initialize a java virtual machine using python's `subprocess` package. This JVM will instantiate an instance of our scoring class, which loads the model just once at initialization. As we will see, loading the model once is far more efficient than repeatedly calling `mojo_predict_pandas`, which reloads the model for each call. We will then establish a gateway to our JVM using `JavaGateway` from `py4j` and score our test cases one at a time.
#
# Timing of these two approaches will show that the second approach is far faster than the first approach. On my machine, the first approach takes more than 300 *milliseconds* per record whereas the second approach takes less than 100 *microseconds* per record. For many real-time production applications, the difference between the second approach and the first approach is the difference between easily hitting an SLA and almost always failing to hit the SLA.
# ### Imports
# In[1]:
import os, sys, json, pickle
import pandas as pd
import subprocess
from ast import literal_eval
from py4j.java_gateway import JavaGateway
from h2o.utils import shared_utils as su
# ### Read in our pickled test cases and feature engineering pipeline
# In[2]:
test_data = pd.read_pickle('test_cases.pkl')
# In[3]:
with open('pipeline.pkl','rb') as f:
p = pickle.load(f)
# In[4]:
test_data.head()
# ### Apply feature engineering
#
# In real-time production scoring, these transformations would constribute to the end-to-end runtime of the application and therefore influence whether scoring achieves its SLA. Here we are primarily interested in the time it takes to score with the MOJO itself under the two approaches outlined above. Therefore, we do not include this in the timing.
# In[5]:
test_data_prepped = (
p.transform(test_data)
.reset_index(drop=True)
.drop(labels = 'loan_status',axis=1))
# In[6]:
test_data_prepped.head()
# In[7]:
predictors = test_data_prepped.columns.to_list()
# ### Scoring Approach 1: `h2o`'s `mojo_predict_pandas` method
# In[8]:
mojo_zip_path = 'lendingclub-app/src/main/resources/final_gbm.zip'
genmodel_jar_path = 'h2o-genmodel.jar'
records = [test_data_prepped.iloc[[i]] for i in range(test_data_prepped.shape[0])]
# In[9]:
get_ipython().run_cell_magic('timeit', '', '\nresults = []\n\nfor record in records:\n pred = su.mojo_predict_pandas(\n record,\n mojo_zip_path,\n genmodel_jar_path)\n results.append(pred)')
# In[10]:
results = []
for record in records:
pred = su.mojo_predict_pandas(
record,
mojo_zip_path,
genmodel_jar_path)
results.append(pred)
# In[11]:
# Predictions:
pd.concat(results)
# ### Scoring Approach 2: Our Java Application
# In[12]:
## Start JVM using subprocess
cmd = "java -cp " + "lendingclub-app/target/" + "lendingclub-app-1.0-SNAPSHOT-jar-with-dependencies.jar " + "com.lendingclub.app.MojoScoringEntryPoint"
jvm = subprocess.Popen(cmd)
# In[13]:
## Establish gateway with the JVM
gateway = JavaGateway()
mojoscorer = gateway.entry_point.getScorer()
# In[14]:
## Construct cases as list of JSON objects
cases = test_data_prepped[predictors].to_dict(orient='records')
cases = [json.dumps(case) for case in cases]
# In[15]:
get_ipython().run_cell_magic('timeit', '', 'results = []\n\nfor case in cases:\n results.append(literal_eval(mojoscorer.predict(case)))')
# In[16]:
results = []
for case in cases:
results.append(literal_eval(mojoscorer.predict(case)))
pd.DataFrame(results)
# In[17]:
## Kill JVM
jvm.kill()
| 25.779141 | 543 | 0.730604 |
o approaches will show that the second approach is far faster than the first approach. On my machine, the first approach takes more than 300 *milliseconds* per record whereas the second approach takes less than 100 *microseconds* per record. For many real-time production applications, the difference between the second approach and the first approach is the difference between easily hitting an SLA and almost always failing to hit the SLA.
# ### Imports
# In[1]:
import os, sys, json, pickle
import pandas as pd
import subprocess
from ast import literal_eval
from py4j.java_gateway import JavaGateway
from h2o.utils import shared_utils as su
# ### Read in our pickled test cases and feature engineering pipeline
# In[2]:
test_data = pd.read_pickle('test_cases.pkl')
# In[3]:
with open('pipeline.pkl','rb') as f:
p = pickle.load(f)
# In[4]:
test_data.head()
# ### Apply feature engineering
#
# In real-time production scoring, these transformations would constribute to the end-to-end runtime of the application and therefore influence whether scoring achieves its SLA. Here we are primarily interested in the time it takes to score with the MOJO itself under the two approaches outlined above. Therefore, we do not include this in the timing.
# In[5]:
test_data_prepped = (
p.transform(test_data)
.reset_index(drop=True)
.drop(labels = 'loan_status',axis=1))
# In[6]:
test_data_prepped.head()
# In[7]:
predictors = test_data_prepped.columns.to_list()
# ### Scoring Approach 1: `h2o`'s `mojo_predict_pandas` method
mojo_zip_path = 'lendingclub-app/src/main/resources/final_gbm.zip'
genmodel_jar_path = 'h2o-genmodel.jar'
records = [test_data_prepped.iloc[[i]] for i in range(test_data_prepped.shape[0])]
get_ipython().run_cell_magic('timeit', '', '\nresults = []\n\nfor record in records:\n pred = su.mojo_predict_pandas(\n record,\n mojo_zip_path,\n genmodel_jar_path)\n results.append(pred)')
results = []
for record in records:
pred = su.mojo_predict_pandas(
record,
mojo_zip_path,
genmodel_jar_path)
results.append(pred)
pd.concat(results)
"
jvm = subprocess.Popen(cmd)
orer = gateway.entry_point.getScorer()
o_dict(orient='records')
cases = [json.dumps(case) for case in cases]
get_ipython().run_cell_magic('timeit', '', 'results = []\n\nfor case in cases:\n results.append(literal_eval(mojoscorer.predict(case)))')
results = []
for case in cases:
results.append(literal_eval(mojoscorer.predict(case)))
pd.DataFrame(results)
()
| true | true |
f7f6c989ff519dba14d2c18b438ca455be92fccb | 2,584 | py | Python | rssynergia/base_diagnostics/write_bunch.py | radiasoft/rs_synergia | b43509de7f4a938354dc127762d8e723463e0e95 | [
"Apache-2.0"
] | null | null | null | rssynergia/base_diagnostics/write_bunch.py | radiasoft/rs_synergia | b43509de7f4a938354dc127762d8e723463e0e95 | [
"Apache-2.0"
] | null | null | null | rssynergia/base_diagnostics/write_bunch.py | radiasoft/rs_synergia | b43509de7f4a938354dc127762d8e723463e0e95 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""?
:copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import synergia
import numpy as np
import h5py
def write_bunch(bunch, file_name = 'particles.h5' , reference_particle = None, txt = False):
'''
Write a Synergia bunch to file, mimicing the style of the bunch diagnostics. Defaults to .h5 output.
Assumes that the main processor has access to all particles.
Unlike the standard bunch_diagnostics, this method outputs the beam attributes as h5 attributes rather than as datasets.
Arguments:
- bunch (synergia.bunch.bunch.Bunch): A Synergia bunch object to be written to file
- fn (Optional[String]): File name for saving the bunch - defaults to 'particles.h5'
- txt (Optional[Bool]): Whether to write to a .txt file - defaults to False
'''
particles = bunch.get_local_particles()
num_particles = particles.shape[0]
#Define attributes for the bunch - this requires a reference particle or other context
#check to see if reference particle is passed
if reference_particle is not None:
charge = reference_particle.get_charge()
mass = reference_particle.get_total_energy()/reference_particle.get_gamma()
pz = reference_particle.get_momentum()
else:
#pass defaults
charge = 1
mass = 0.9382723128
pz = 10.
#specify these as 0 because particle distribution is uncoupled from simulation
rep = 0
s_n = 0
tlen = 0
if txt:
#txt file write is straightforward numpy save
np.savetxt(file_name,particles)
else:
#write to HDF-5 by default
#Create h5 file
dump_file = h5py.File(file_name, 'w')
#specify attributes
dump_file.attrs['charge'] = charge #Particle charge in units of proton charge
dump_file.attrs['mass'] = mass #Particle equivalent mass in GeV
dump_file.attrs['pz'] = pz #Reference particle momentum in GeV/c
dump_file.attrs['s_n'] = s_n #Current s value (between 0 and lattice length), defaults to 0
dump_file.attrs['tlen'] = tlen #Total length traversed during simulation, defaults to 0
dump_file.attrs['rep'] = rep #Current repetition, defaults to 0
#write particle phase space array as a single dataset
ptcl_data = dump_file.create_dataset('particles', (num_particles,7))
ptcl_data[:] = particles
dump_file.close()
| 35.39726 | 124 | 0.684598 |
from __future__ import absolute_import, division, print_function
import synergia
import numpy as np
import h5py
def write_bunch(bunch, file_name = 'particles.h5' , reference_particle = None, txt = False):
particles = bunch.get_local_particles()
num_particles = particles.shape[0]
if reference_particle is not None:
charge = reference_particle.get_charge()
mass = reference_particle.get_total_energy()/reference_particle.get_gamma()
pz = reference_particle.get_momentum()
else:
charge = 1
mass = 0.9382723128
pz = 10.
rep = 0
s_n = 0
tlen = 0
if txt:
np.savetxt(file_name,particles)
else:
dump_file = h5py.File(file_name, 'w')
dump_file.attrs['charge'] = charge
dump_file.attrs['mass'] = mass
dump_file.attrs['pz'] = pz
dump_file.attrs['s_n'] = s_n
dump_file.attrs['tlen'] = tlen
dump_file.attrs['rep'] = rep
ptcl_data = dump_file.create_dataset('particles', (num_particles,7))
ptcl_data[:] = particles
dump_file.close()
| true | true |
f7f6c98e0c53caad5004c87b6ef0eb722f38a59a | 257,660 | py | Python | instances/passenger_demand/pas-20210422-1717-int12e/38.py | LHcau/scheduling-shared-passenger-and-freight-transport-on-a-fixed-infrastructure | bba1e6af5bc8d9deaa2dc3b83f6fe9ddf15d2a11 | [
"BSD-3-Clause"
] | null | null | null | instances/passenger_demand/pas-20210422-1717-int12e/38.py | LHcau/scheduling-shared-passenger-and-freight-transport-on-a-fixed-infrastructure | bba1e6af5bc8d9deaa2dc3b83f6fe9ddf15d2a11 | [
"BSD-3-Clause"
] | null | null | null | instances/passenger_demand/pas-20210422-1717-int12e/38.py | LHcau/scheduling-shared-passenger-and-freight-transport-on-a-fixed-infrastructure | bba1e6af5bc8d9deaa2dc3b83f6fe9ddf15d2a11 | [
"BSD-3-Clause"
] | null | null | null |
"""
PASSENGERS
"""
numPassengers = 22850
passenger_arriving = (
(6, 7, 10, 5, 3, 2, 1, 1, 4, 1, 1, 0, 0, 4, 6, 6, 2, 4, 0, 3, 0, 1, 2, 0, 0, 0), # 0
(8, 8, 6, 3, 2, 2, 2, 4, 3, 0, 0, 1, 0, 9, 8, 7, 1, 1, 5, 3, 0, 2, 2, 2, 1, 0), # 1
(8, 8, 12, 3, 3, 2, 1, 1, 0, 1, 2, 0, 0, 5, 7, 2, 2, 8, 3, 3, 2, 2, 0, 1, 0, 0), # 2
(6, 4, 4, 9, 4, 3, 0, 1, 3, 2, 0, 1, 0, 10, 6, 4, 7, 9, 4, 2, 0, 1, 0, 1, 1, 0), # 3
(2, 6, 7, 10, 6, 2, 6, 4, 2, 2, 2, 1, 0, 8, 6, 2, 3, 5, 3, 4, 1, 0, 0, 0, 0, 0), # 4
(6, 8, 10, 8, 4, 2, 4, 4, 4, 1, 1, 0, 0, 7, 6, 7, 4, 4, 3, 3, 2, 4, 3, 2, 0, 0), # 5
(8, 5, 8, 13, 2, 4, 1, 5, 4, 5, 0, 0, 0, 13, 12, 5, 5, 7, 1, 2, 1, 2, 4, 3, 1, 0), # 6
(8, 16, 9, 7, 3, 1, 3, 3, 5, 2, 0, 1, 0, 10, 5, 9, 4, 8, 8, 4, 3, 3, 3, 1, 0, 0), # 7
(8, 9, 10, 10, 5, 5, 3, 3, 2, 1, 6, 2, 0, 8, 4, 5, 5, 7, 4, 5, 3, 6, 4, 0, 0, 0), # 8
(7, 14, 8, 7, 4, 4, 4, 8, 5, 1, 1, 0, 0, 6, 9, 6, 4, 6, 6, 1, 3, 2, 4, 2, 2, 0), # 9
(13, 10, 7, 8, 12, 3, 0, 1, 3, 0, 1, 2, 0, 7, 6, 5, 4, 5, 5, 3, 1, 6, 3, 2, 1, 0), # 10
(6, 12, 12, 12, 7, 3, 6, 6, 1, 0, 3, 3, 0, 8, 8, 8, 9, 10, 8, 4, 2, 6, 6, 3, 0, 0), # 11
(11, 14, 14, 7, 8, 3, 4, 1, 4, 2, 5, 0, 0, 12, 8, 5, 4, 10, 8, 4, 5, 5, 4, 1, 1, 0), # 12
(12, 12, 4, 12, 6, 1, 2, 3, 3, 3, 1, 2, 0, 8, 6, 12, 6, 7, 3, 6, 3, 8, 6, 0, 1, 0), # 13
(8, 5, 7, 6, 10, 1, 4, 7, 6, 1, 0, 0, 0, 12, 11, 10, 5, 5, 1, 3, 2, 4, 4, 2, 1, 0), # 14
(13, 11, 8, 5, 10, 10, 4, 11, 4, 2, 1, 3, 0, 16, 9, 7, 8, 14, 4, 4, 3, 2, 3, 1, 1, 0), # 15
(15, 14, 11, 7, 8, 4, 0, 10, 6, 2, 0, 0, 0, 10, 8, 5, 4, 11, 11, 8, 2, 3, 2, 2, 1, 0), # 16
(9, 13, 10, 13, 7, 3, 4, 6, 4, 3, 2, 2, 0, 15, 11, 8, 5, 9, 8, 7, 2, 2, 4, 2, 1, 0), # 17
(12, 9, 15, 13, 9, 5, 4, 2, 1, 0, 1, 2, 0, 10, 6, 9, 5, 10, 5, 7, 4, 2, 1, 0, 3, 0), # 18
(7, 23, 15, 13, 7, 6, 9, 5, 3, 2, 1, 1, 0, 10, 9, 5, 7, 14, 10, 4, 4, 3, 3, 1, 0, 0), # 19
(13, 14, 6, 5, 11, 7, 7, 4, 7, 1, 3, 1, 0, 11, 13, 13, 12, 6, 7, 3, 1, 3, 5, 1, 1, 0), # 20
(13, 10, 18, 6, 13, 7, 9, 6, 8, 2, 3, 2, 0, 12, 17, 8, 12, 7, 9, 6, 7, 5, 4, 2, 0, 0), # 21
(13, 7, 12, 12, 13, 7, 5, 1, 8, 1, 1, 1, 0, 16, 11, 4, 6, 15, 5, 7, 4, 5, 5, 3, 1, 0), # 22
(9, 13, 6, 11, 8, 3, 8, 4, 7, 3, 1, 2, 0, 11, 11, 5, 6, 15, 4, 4, 3, 3, 4, 3, 0, 0), # 23
(14, 12, 11, 8, 9, 2, 4, 2, 6, 1, 0, 3, 0, 14, 11, 7, 6, 16, 6, 5, 2, 3, 7, 2, 2, 0), # 24
(10, 13, 4, 12, 10, 2, 1, 3, 4, 3, 0, 2, 0, 7, 9, 9, 11, 8, 8, 2, 1, 8, 3, 1, 0, 0), # 25
(11, 9, 13, 11, 9, 4, 4, 5, 7, 0, 2, 4, 0, 18, 12, 7, 9, 14, 7, 3, 3, 5, 4, 3, 1, 0), # 26
(11, 14, 11, 7, 8, 5, 5, 4, 5, 4, 2, 0, 0, 9, 7, 7, 8, 14, 6, 4, 2, 10, 2, 0, 4, 0), # 27
(12, 5, 11, 11, 5, 4, 4, 6, 3, 2, 3, 2, 0, 15, 13, 11, 5, 11, 10, 4, 5, 3, 3, 2, 0, 0), # 28
(8, 16, 6, 13, 13, 5, 3, 5, 8, 1, 3, 0, 0, 12, 8, 5, 7, 12, 4, 5, 4, 9, 4, 4, 1, 0), # 29
(14, 11, 13, 15, 11, 0, 6, 4, 6, 3, 1, 1, 0, 10, 10, 8, 3, 14, 4, 3, 3, 9, 3, 2, 2, 0), # 30
(9, 6, 11, 15, 12, 2, 1, 5, 5, 2, 0, 0, 0, 5, 6, 3, 5, 11, 7, 3, 1, 3, 5, 2, 1, 0), # 31
(11, 10, 10, 13, 8, 4, 7, 4, 8, 3, 5, 1, 0, 10, 7, 10, 7, 11, 3, 5, 2, 4, 2, 3, 2, 0), # 32
(13, 7, 8, 6, 14, 7, 4, 8, 12, 0, 2, 1, 0, 12, 7, 11, 5, 7, 3, 5, 2, 5, 1, 1, 1, 0), # 33
(16, 13, 18, 13, 9, 7, 4, 2, 5, 2, 2, 1, 0, 16, 11, 12, 7, 10, 8, 3, 3, 8, 2, 2, 0, 0), # 34
(10, 13, 13, 12, 9, 6, 4, 3, 3, 0, 2, 4, 0, 6, 11, 9, 6, 11, 4, 4, 2, 6, 2, 0, 1, 0), # 35
(14, 17, 11, 10, 11, 1, 4, 9, 5, 3, 3, 1, 0, 12, 6, 5, 5, 11, 2, 5, 4, 4, 1, 5, 0, 0), # 36
(9, 9, 6, 7, 5, 5, 2, 6, 5, 3, 0, 1, 0, 12, 9, 6, 7, 15, 8, 1, 2, 3, 7, 2, 0, 0), # 37
(14, 8, 10, 9, 14, 3, 4, 4, 5, 2, 1, 1, 0, 9, 9, 8, 8, 8, 4, 5, 3, 2, 6, 1, 0, 0), # 38
(10, 14, 9, 12, 8, 4, 1, 4, 5, 2, 1, 0, 0, 7, 10, 12, 5, 5, 8, 5, 1, 4, 3, 4, 1, 0), # 39
(13, 8, 7, 6, 13, 6, 5, 2, 6, 3, 0, 1, 0, 16, 17, 6, 11, 9, 5, 5, 4, 5, 1, 1, 1, 0), # 40
(9, 14, 11, 10, 6, 3, 2, 1, 8, 2, 1, 2, 0, 7, 10, 5, 8, 7, 6, 6, 7, 6, 1, 2, 2, 0), # 41
(15, 9, 7, 17, 8, 8, 7, 3, 8, 2, 1, 1, 0, 9, 12, 10, 9, 12, 7, 9, 4, 5, 5, 3, 1, 0), # 42
(14, 9, 9, 12, 9, 4, 6, 2, 9, 2, 0, 1, 0, 7, 14, 17, 7, 7, 6, 4, 2, 5, 4, 1, 2, 0), # 43
(7, 11, 13, 9, 5, 5, 6, 2, 5, 0, 1, 1, 0, 10, 5, 9, 9, 10, 8, 5, 5, 7, 3, 2, 1, 0), # 44
(10, 9, 10, 13, 15, 3, 5, 6, 6, 1, 2, 2, 0, 12, 10, 11, 7, 10, 2, 6, 5, 5, 2, 5, 1, 0), # 45
(12, 9, 14, 10, 14, 3, 4, 5, 1, 4, 1, 0, 0, 8, 6, 9, 9, 12, 6, 4, 5, 7, 2, 2, 1, 0), # 46
(15, 11, 19, 10, 9, 4, 5, 2, 7, 0, 3, 0, 0, 14, 15, 4, 4, 12, 7, 3, 5, 2, 2, 4, 0, 0), # 47
(11, 7, 12, 9, 13, 2, 5, 5, 5, 1, 0, 3, 0, 17, 16, 6, 5, 7, 9, 5, 2, 3, 4, 2, 2, 0), # 48
(17, 12, 11, 12, 10, 4, 7, 6, 6, 3, 1, 0, 0, 16, 12, 8, 7, 11, 7, 5, 4, 4, 5, 0, 1, 0), # 49
(15, 11, 9, 17, 10, 9, 3, 6, 8, 5, 1, 0, 0, 17, 10, 5, 3, 5, 5, 4, 2, 2, 6, 2, 0, 0), # 50
(8, 8, 4, 19, 10, 6, 3, 3, 5, 3, 2, 1, 0, 9, 14, 12, 7, 9, 3, 2, 0, 10, 1, 1, 0, 0), # 51
(16, 10, 11, 8, 10, 3, 7, 1, 3, 3, 2, 0, 0, 14, 12, 9, 9, 9, 5, 2, 5, 0, 5, 0, 1, 0), # 52
(15, 9, 7, 9, 7, 2, 8, 5, 4, 2, 3, 1, 0, 15, 13, 7, 5, 9, 7, 5, 4, 7, 3, 3, 1, 0), # 53
(13, 6, 11, 13, 8, 3, 5, 3, 8, 2, 0, 0, 0, 10, 11, 6, 8, 9, 5, 4, 2, 5, 3, 1, 0, 0), # 54
(9, 13, 13, 16, 4, 5, 4, 6, 2, 0, 3, 3, 0, 10, 18, 8, 9, 8, 4, 4, 3, 4, 2, 2, 0, 0), # 55
(12, 12, 9, 9, 13, 1, 5, 4, 3, 2, 4, 0, 0, 10, 14, 6, 4, 14, 7, 8, 3, 9, 3, 2, 2, 0), # 56
(17, 14, 8, 10, 11, 6, 5, 5, 4, 5, 0, 1, 0, 15, 10, 6, 6, 10, 8, 5, 2, 9, 7, 0, 1, 0), # 57
(11, 13, 10, 13, 12, 4, 1, 3, 3, 1, 2, 1, 0, 9, 7, 11, 8, 7, 3, 2, 3, 6, 3, 2, 1, 0), # 58
(10, 16, 10, 11, 10, 8, 9, 3, 4, 4, 2, 1, 0, 13, 12, 10, 7, 10, 9, 3, 7, 4, 4, 2, 1, 0), # 59
(11, 6, 12, 10, 7, 8, 5, 2, 4, 3, 1, 0, 0, 14, 8, 8, 7, 11, 8, 3, 2, 2, 7, 0, 4, 0), # 60
(14, 8, 10, 9, 14, 2, 1, 5, 6, 1, 2, 1, 0, 14, 16, 5, 10, 8, 5, 8, 3, 6, 0, 2, 0, 0), # 61
(15, 11, 9, 7, 11, 6, 2, 4, 3, 1, 0, 3, 0, 6, 8, 3, 7, 13, 10, 5, 3, 5, 7, 1, 2, 0), # 62
(15, 10, 5, 4, 6, 4, 4, 2, 5, 3, 2, 0, 0, 15, 8, 6, 3, 6, 6, 3, 5, 0, 5, 1, 0, 0), # 63
(16, 4, 11, 5, 6, 4, 2, 2, 1, 3, 0, 1, 0, 9, 9, 3, 9, 4, 5, 1, 7, 6, 3, 2, 2, 0), # 64
(14, 14, 6, 9, 8, 4, 7, 2, 6, 4, 1, 1, 0, 10, 7, 10, 7, 9, 5, 2, 3, 3, 3, 4, 0, 0), # 65
(12, 12, 12, 11, 12, 5, 8, 4, 6, 0, 2, 1, 0, 11, 5, 6, 4, 10, 6, 1, 3, 6, 2, 1, 1, 0), # 66
(7, 6, 14, 13, 11, 4, 3, 2, 7, 3, 4, 0, 0, 13, 8, 6, 3, 14, 2, 3, 1, 7, 6, 3, 2, 0), # 67
(14, 12, 10, 7, 6, 6, 10, 7, 8, 3, 0, 1, 0, 10, 10, 6, 8, 13, 4, 6, 5, 4, 4, 0, 0, 0), # 68
(17, 16, 5, 10, 10, 2, 7, 2, 7, 1, 3, 1, 0, 18, 13, 7, 7, 7, 3, 6, 5, 9, 1, 2, 0, 0), # 69
(12, 9, 9, 15, 10, 3, 4, 3, 4, 3, 2, 1, 0, 10, 15, 11, 2, 9, 7, 9, 3, 6, 4, 1, 0, 0), # 70
(9, 11, 6, 11, 16, 4, 2, 0, 5, 4, 1, 2, 0, 14, 12, 5, 5, 8, 5, 1, 5, 7, 6, 4, 0, 0), # 71
(18, 7, 13, 16, 11, 6, 5, 2, 7, 2, 2, 0, 0, 14, 13, 6, 3, 9, 4, 5, 2, 3, 3, 0, 2, 0), # 72
(11, 7, 10, 8, 9, 5, 7, 5, 3, 1, 1, 1, 0, 16, 6, 9, 9, 7, 5, 6, 4, 6, 5, 3, 1, 0), # 73
(14, 6, 7, 9, 8, 2, 3, 3, 7, 1, 1, 1, 0, 12, 16, 9, 4, 12, 3, 4, 1, 5, 5, 1, 3, 0), # 74
(10, 12, 10, 12, 18, 8, 3, 5, 4, 1, 1, 1, 0, 11, 7, 10, 5, 6, 4, 3, 3, 7, 5, 2, 0, 0), # 75
(16, 13, 13, 4, 11, 5, 7, 1, 6, 2, 2, 1, 0, 15, 7, 4, 7, 9, 3, 3, 1, 4, 9, 2, 1, 0), # 76
(15, 11, 12, 13, 12, 5, 4, 4, 0, 1, 1, 0, 0, 13, 8, 15, 6, 12, 3, 2, 9, 5, 1, 2, 2, 0), # 77
(11, 6, 9, 9, 11, 2, 7, 2, 7, 3, 1, 1, 0, 11, 15, 9, 8, 8, 3, 5, 2, 2, 3, 2, 0, 0), # 78
(7, 14, 10, 9, 1, 2, 5, 7, 3, 1, 3, 0, 0, 11, 15, 9, 9, 13, 6, 4, 4, 4, 2, 1, 0, 0), # 79
(12, 8, 14, 4, 5, 2, 8, 1, 5, 3, 2, 0, 0, 9, 13, 4, 3, 11, 1, 4, 1, 3, 3, 2, 0, 0), # 80
(16, 12, 4, 19, 10, 4, 4, 1, 3, 2, 0, 2, 0, 7, 8, 9, 4, 9, 6, 7, 8, 6, 1, 5, 2, 0), # 81
(10, 10, 8, 7, 6, 3, 4, 3, 3, 2, 3, 1, 0, 9, 10, 7, 7, 9, 3, 3, 6, 5, 2, 4, 0, 0), # 82
(11, 12, 11, 11, 4, 3, 0, 3, 5, 3, 2, 0, 0, 13, 10, 6, 7, 9, 4, 3, 1, 6, 3, 1, 1, 0), # 83
(10, 8, 6, 12, 11, 3, 3, 5, 6, 3, 0, 3, 0, 16, 6, 7, 9, 12, 7, 2, 1, 4, 6, 2, 1, 0), # 84
(11, 6, 9, 8, 8, 1, 3, 2, 6, 2, 1, 1, 0, 18, 11, 6, 11, 12, 8, 5, 2, 5, 4, 5, 0, 0), # 85
(10, 11, 8, 5, 7, 2, 3, 1, 1, 5, 1, 0, 0, 16, 8, 9, 5, 11, 7, 1, 2, 8, 1, 1, 1, 0), # 86
(13, 8, 5, 11, 11, 5, 6, 1, 5, 1, 0, 3, 0, 10, 10, 7, 2, 9, 2, 3, 4, 4, 4, 2, 0, 0), # 87
(14, 13, 8, 9, 12, 5, 4, 7, 5, 2, 2, 0, 0, 12, 14, 9, 6, 7, 4, 6, 2, 4, 5, 3, 1, 0), # 88
(10, 10, 5, 19, 11, 5, 2, 1, 5, 4, 0, 2, 0, 12, 10, 11, 9, 10, 9, 5, 4, 1, 2, 5, 0, 0), # 89
(9, 15, 12, 3, 7, 2, 9, 1, 2, 1, 2, 0, 0, 15, 10, 5, 6, 10, 4, 3, 6, 3, 2, 1, 2, 0), # 90
(13, 7, 4, 10, 10, 5, 2, 1, 5, 3, 1, 3, 0, 12, 10, 5, 4, 8, 7, 4, 6, 0, 2, 2, 0, 0), # 91
(12, 11, 12, 7, 11, 4, 4, 3, 3, 2, 1, 0, 0, 13, 12, 9, 8, 8, 5, 2, 3, 3, 3, 0, 1, 0), # 92
(7, 12, 5, 4, 11, 6, 2, 4, 5, 4, 2, 1, 0, 8, 12, 11, 8, 7, 4, 6, 5, 6, 3, 6, 0, 0), # 93
(8, 13, 10, 13, 17, 1, 1, 1, 4, 1, 2, 0, 0, 14, 12, 4, 4, 15, 3, 1, 3, 5, 6, 4, 0, 0), # 94
(10, 10, 17, 8, 7, 4, 1, 3, 3, 0, 1, 1, 0, 14, 10, 8, 5, 10, 1, 6, 2, 3, 6, 2, 2, 0), # 95
(10, 9, 13, 11, 13, 2, 6, 4, 1, 0, 0, 1, 0, 13, 10, 16, 3, 15, 4, 5, 5, 3, 3, 7, 2, 0), # 96
(7, 6, 8, 14, 8, 3, 3, 3, 4, 0, 3, 0, 0, 20, 5, 8, 5, 9, 5, 6, 4, 6, 5, 5, 1, 0), # 97
(13, 7, 10, 8, 11, 7, 1, 3, 5, 0, 1, 1, 0, 13, 17, 7, 6, 12, 2, 3, 5, 5, 4, 3, 0, 0), # 98
(10, 7, 16, 7, 12, 5, 3, 4, 8, 3, 2, 0, 0, 19, 9, 12, 7, 11, 6, 1, 3, 5, 2, 0, 0, 0), # 99
(14, 13, 9, 7, 6, 3, 0, 2, 3, 2, 0, 0, 0, 13, 10, 6, 4, 7, 6, 3, 4, 3, 3, 1, 2, 0), # 100
(12, 14, 5, 8, 5, 6, 5, 5, 2, 2, 3, 0, 0, 14, 7, 7, 4, 9, 3, 2, 3, 8, 3, 3, 1, 0), # 101
(8, 8, 11, 14, 11, 3, 2, 1, 8, 1, 4, 1, 0, 19, 8, 6, 6, 5, 3, 4, 2, 2, 4, 3, 1, 0), # 102
(12, 11, 8, 13, 5, 3, 1, 3, 5, 1, 3, 1, 0, 12, 11, 6, 6, 6, 4, 3, 1, 6, 2, 0, 1, 0), # 103
(15, 10, 9, 8, 4, 5, 3, 3, 2, 3, 0, 2, 0, 15, 11, 11, 5, 12, 3, 2, 3, 4, 3, 3, 1, 0), # 104
(17, 11, 8, 15, 7, 8, 5, 3, 5, 2, 2, 0, 0, 10, 11, 11, 4, 12, 5, 5, 6, 3, 5, 0, 1, 0), # 105
(15, 7, 12, 11, 14, 4, 5, 2, 5, 0, 0, 1, 0, 7, 9, 7, 2, 9, 3, 4, 3, 6, 6, 1, 1, 0), # 106
(11, 12, 4, 7, 17, 4, 4, 2, 6, 2, 0, 0, 0, 16, 9, 9, 4, 4, 9, 7, 4, 1, 4, 1, 1, 0), # 107
(12, 6, 12, 9, 9, 3, 5, 2, 7, 1, 0, 0, 0, 18, 4, 12, 3, 5, 5, 1, 5, 10, 7, 0, 0, 0), # 108
(10, 5, 9, 11, 10, 4, 2, 1, 8, 3, 1, 0, 0, 11, 6, 9, 5, 9, 5, 6, 2, 4, 6, 3, 0, 0), # 109
(8, 8, 7, 10, 14, 2, 3, 7, 7, 4, 1, 0, 0, 11, 11, 8, 9, 5, 4, 7, 2, 2, 5, 0, 3, 0), # 110
(5, 10, 7, 10, 12, 1, 3, 6, 6, 1, 2, 0, 0, 18, 10, 6, 5, 13, 4, 4, 3, 7, 0, 2, 0, 0), # 111
(12, 13, 3, 3, 10, 4, 7, 2, 1, 1, 2, 2, 0, 12, 6, 3, 10, 7, 1, 1, 4, 4, 2, 1, 1, 0), # 112
(12, 6, 8, 11, 8, 4, 4, 6, 5, 2, 2, 0, 0, 5, 9, 9, 6, 7, 6, 3, 3, 1, 3, 3, 0, 0), # 113
(9, 8, 8, 15, 8, 0, 4, 4, 4, 1, 2, 1, 0, 6, 15, 5, 3, 16, 5, 4, 3, 3, 4, 1, 2, 0), # 114
(6, 6, 10, 13, 9, 3, 2, 4, 4, 2, 1, 2, 0, 12, 13, 9, 1, 10, 6, 6, 0, 5, 3, 0, 0, 0), # 115
(11, 5, 9, 10, 8, 4, 5, 4, 3, 0, 0, 0, 0, 10, 7, 9, 8, 9, 5, 1, 0, 3, 2, 3, 1, 0), # 116
(14, 5, 11, 14, 12, 3, 2, 1, 10, 0, 0, 0, 0, 14, 5, 7, 5, 12, 3, 4, 0, 6, 2, 1, 1, 0), # 117
(9, 13, 5, 10, 7, 4, 5, 1, 6, 1, 1, 1, 0, 11, 11, 4, 3, 9, 4, 3, 2, 5, 3, 2, 0, 0), # 118
(11, 6, 8, 12, 10, 1, 2, 4, 2, 0, 1, 1, 0, 9, 8, 4, 5, 9, 4, 1, 3, 4, 2, 3, 1, 0), # 119
(17, 5, 7, 9, 10, 3, 4, 1, 3, 2, 3, 2, 0, 9, 10, 8, 6, 7, 4, 3, 3, 8, 3, 0, 0, 0), # 120
(10, 13, 6, 3, 11, 5, 3, 1, 2, 1, 3, 0, 0, 10, 11, 9, 4, 6, 6, 3, 1, 2, 0, 1, 0, 0), # 121
(13, 7, 11, 11, 12, 4, 2, 2, 2, 0, 2, 0, 0, 12, 11, 9, 3, 4, 8, 4, 4, 6, 3, 1, 1, 0), # 122
(17, 9, 14, 18, 6, 8, 1, 5, 5, 2, 1, 2, 0, 14, 8, 8, 7, 7, 0, 3, 4, 2, 4, 2, 1, 0), # 123
(10, 2, 9, 11, 8, 7, 6, 2, 2, 3, 2, 1, 0, 10, 10, 6, 8, 7, 3, 5, 4, 4, 1, 3, 1, 0), # 124
(10, 7, 20, 8, 7, 6, 4, 4, 3, 2, 1, 0, 0, 11, 7, 11, 2, 11, 6, 3, 5, 1, 3, 2, 1, 0), # 125
(7, 7, 9, 5, 11, 3, 2, 0, 5, 1, 1, 1, 0, 8, 8, 4, 6, 6, 3, 1, 1, 2, 2, 2, 1, 0), # 126
(11, 12, 4, 10, 12, 2, 6, 3, 1, 1, 2, 0, 0, 16, 11, 12, 4, 9, 4, 3, 7, 6, 8, 2, 0, 0), # 127
(13, 7, 8, 11, 6, 3, 1, 4, 1, 1, 2, 2, 0, 17, 10, 4, 2, 7, 5, 6, 2, 3, 1, 2, 0, 0), # 128
(11, 9, 10, 11, 15, 2, 3, 0, 3, 1, 1, 1, 0, 12, 6, 7, 6, 11, 5, 4, 2, 2, 4, 2, 2, 0), # 129
(8, 2, 10, 10, 7, 2, 4, 3, 5, 3, 2, 0, 0, 10, 8, 5, 5, 6, 3, 6, 1, 6, 3, 1, 0, 0), # 130
(14, 10, 8, 9, 11, 2, 7, 4, 4, 1, 0, 1, 0, 16, 6, 7, 6, 9, 4, 0, 3, 2, 2, 0, 2, 0), # 131
(14, 8, 3, 13, 8, 2, 1, 5, 3, 4, 1, 1, 0, 7, 7, 6, 6, 7, 4, 3, 4, 3, 2, 1, 1, 0), # 132
(15, 8, 7, 9, 8, 3, 5, 3, 7, 1, 1, 2, 0, 14, 10, 4, 8, 9, 2, 5, 0, 5, 4, 0, 0, 0), # 133
(14, 12, 7, 9, 7, 2, 3, 5, 3, 1, 2, 1, 0, 7, 13, 11, 3, 11, 4, 3, 1, 4, 3, 3, 2, 0), # 134
(11, 7, 12, 6, 5, 5, 6, 1, 6, 2, 0, 0, 0, 7, 8, 10, 6, 11, 1, 5, 2, 4, 4, 2, 1, 0), # 135
(14, 8, 9, 14, 3, 6, 2, 3, 6, 3, 2, 1, 0, 10, 11, 8, 4, 4, 2, 1, 3, 3, 3, 0, 0, 0), # 136
(12, 6, 10, 7, 9, 3, 4, 2, 6, 3, 2, 3, 0, 11, 7, 6, 6, 5, 10, 6, 1, 3, 2, 2, 0, 0), # 137
(11, 7, 5, 8, 7, 6, 2, 2, 9, 0, 1, 2, 0, 19, 9, 2, 4, 7, 7, 3, 2, 7, 4, 2, 0, 0), # 138
(12, 6, 10, 10, 10, 4, 3, 3, 5, 0, 0, 0, 0, 9, 8, 9, 4, 6, 6, 1, 5, 5, 4, 4, 2, 0), # 139
(5, 9, 8, 7, 11, 3, 4, 3, 3, 0, 2, 0, 0, 11, 10, 5, 6, 3, 2, 3, 5, 1, 6, 2, 2, 0), # 140
(10, 6, 4, 8, 7, 5, 4, 3, 2, 3, 3, 1, 0, 3, 11, 10, 6, 10, 2, 2, 3, 5, 6, 2, 2, 0), # 141
(11, 6, 4, 3, 11, 4, 2, 3, 3, 2, 2, 2, 0, 11, 7, 8, 4, 8, 4, 1, 5, 3, 3, 0, 3, 0), # 142
(12, 5, 11, 9, 5, 6, 1, 4, 6, 5, 1, 2, 0, 16, 6, 6, 7, 4, 2, 3, 3, 4, 2, 1, 0, 0), # 143
(12, 9, 11, 7, 7, 3, 3, 4, 4, 1, 1, 3, 0, 7, 8, 12, 3, 6, 5, 5, 3, 1, 4, 2, 2, 0), # 144
(9, 6, 6, 7, 7, 11, 4, 2, 7, 1, 1, 0, 0, 11, 8, 7, 3, 7, 7, 6, 3, 7, 2, 1, 1, 0), # 145
(13, 8, 9, 7, 5, 5, 5, 5, 4, 4, 0, 0, 0, 5, 10, 4, 8, 7, 7, 4, 2, 7, 2, 0, 3, 0), # 146
(8, 9, 11, 9, 5, 1, 5, 2, 2, 2, 0, 0, 0, 9, 8, 5, 9, 6, 4, 4, 4, 1, 3, 1, 1, 0), # 147
(9, 12, 7, 13, 4, 2, 2, 4, 5, 1, 1, 3, 0, 15, 4, 5, 2, 12, 4, 1, 5, 2, 6, 2, 0, 0), # 148
(9, 8, 10, 11, 11, 2, 6, 3, 3, 1, 0, 0, 0, 8, 7, 9, 3, 7, 2, 4, 3, 4, 2, 0, 0, 0), # 149
(14, 5, 11, 7, 4, 3, 1, 8, 4, 1, 0, 1, 0, 9, 7, 10, 4, 9, 6, 1, 3, 5, 1, 0, 2, 0), # 150
(9, 8, 8, 17, 7, 4, 4, 2, 6, 1, 2, 0, 0, 6, 5, 3, 7, 2, 1, 2, 1, 5, 4, 0, 0, 0), # 151
(9, 1, 6, 8, 5, 5, 2, 1, 5, 0, 1, 0, 0, 13, 8, 7, 7, 9, 5, 4, 3, 1, 2, 2, 0, 0), # 152
(7, 4, 10, 12, 10, 5, 2, 4, 5, 6, 0, 0, 0, 10, 4, 9, 3, 12, 2, 1, 2, 0, 4, 1, 0, 0), # 153
(3, 5, 8, 8, 7, 4, 2, 1, 2, 1, 3, 0, 0, 14, 4, 8, 7, 6, 4, 5, 2, 4, 3, 1, 0, 0), # 154
(11, 7, 5, 10, 8, 5, 3, 2, 5, 2, 2, 1, 0, 10, 8, 7, 4, 9, 3, 3, 6, 1, 3, 0, 2, 0), # 155
(6, 8, 9, 9, 7, 4, 2, 3, 0, 0, 3, 0, 0, 13, 8, 1, 2, 2, 8, 0, 2, 1, 1, 2, 0, 0), # 156
(4, 9, 8, 4, 4, 3, 5, 5, 1, 2, 2, 1, 0, 12, 10, 12, 5, 8, 5, 6, 3, 5, 4, 0, 0, 0), # 157
(7, 6, 7, 6, 4, 3, 1, 0, 7, 1, 0, 0, 0, 16, 6, 5, 6, 5, 5, 3, 1, 1, 5, 0, 0, 0), # 158
(8, 4, 8, 5, 6, 2, 3, 1, 2, 1, 1, 0, 0, 10, 9, 9, 5, 5, 5, 2, 4, 3, 2, 0, 0, 0), # 159
(10, 2, 7, 9, 4, 5, 2, 2, 5, 1, 0, 0, 0, 10, 6, 5, 4, 7, 5, 3, 4, 4, 2, 3, 0, 0), # 160
(7, 5, 8, 4, 7, 1, 1, 4, 4, 0, 0, 1, 0, 5, 2, 4, 2, 3, 2, 2, 2, 5, 3, 0, 1, 0), # 161
(10, 8, 9, 7, 5, 2, 2, 2, 2, 0, 2, 0, 0, 6, 4, 7, 3, 5, 5, 1, 2, 5, 2, 2, 0, 0), # 162
(8, 8, 4, 7, 6, 1, 4, 2, 2, 1, 2, 1, 0, 5, 8, 2, 4, 13, 5, 6, 2, 3, 3, 0, 2, 0), # 163
(12, 2, 7, 7, 9, 3, 1, 4, 2, 0, 0, 0, 0, 14, 5, 8, 12, 6, 5, 2, 2, 4, 2, 2, 0, 0), # 164
(10, 5, 3, 9, 4, 6, 5, 4, 4, 1, 0, 0, 0, 8, 5, 9, 3, 9, 6, 1, 4, 1, 0, 1, 0, 0), # 165
(7, 3, 7, 4, 7, 3, 0, 3, 4, 2, 1, 1, 0, 14, 5, 1, 1, 8, 5, 3, 2, 2, 1, 1, 1, 0), # 166
(7, 4, 2, 4, 6, 1, 2, 2, 5, 1, 2, 0, 0, 8, 13, 3, 2, 4, 3, 3, 2, 8, 0, 1, 2, 0), # 167
(7, 4, 7, 1, 7, 4, 5, 3, 1, 1, 2, 1, 0, 13, 5, 5, 1, 3, 4, 1, 2, 2, 3, 1, 0, 0), # 168
(7, 9, 3, 5, 11, 2, 4, 2, 3, 0, 0, 0, 0, 6, 10, 3, 4, 7, 5, 1, 2, 2, 2, 3, 0, 0), # 169
(8, 7, 9, 9, 9, 1, 6, 2, 8, 2, 4, 0, 0, 8, 10, 4, 2, 9, 3, 4, 2, 3, 4, 2, 1, 0), # 170
(7, 4, 5, 9, 2, 0, 2, 0, 3, 1, 0, 1, 0, 8, 7, 8, 5, 6, 0, 2, 2, 3, 2, 0, 1, 0), # 171
(5, 4, 6, 2, 2, 2, 4, 0, 0, 2, 0, 0, 0, 8, 2, 6, 2, 5, 2, 4, 0, 4, 1, 1, 1, 0), # 172
(10, 4, 7, 6, 4, 4, 2, 2, 1, 1, 0, 0, 0, 8, 2, 6, 4, 7, 2, 3, 1, 3, 7, 0, 1, 0), # 173
(6, 1, 4, 7, 5, 1, 0, 1, 0, 0, 0, 0, 0, 5, 4, 4, 0, 5, 5, 2, 2, 1, 2, 1, 0, 0), # 174
(4, 1, 5, 8, 5, 6, 3, 1, 6, 0, 2, 1, 0, 9, 8, 2, 1, 7, 2, 1, 3, 3, 1, 1, 1, 0), # 175
(11, 4, 7, 5, 5, 2, 0, 1, 3, 2, 1, 0, 0, 7, 7, 3, 1, 3, 1, 1, 2, 2, 3, 1, 0, 0), # 176
(2, 5, 5, 1, 4, 2, 0, 1, 2, 1, 1, 1, 0, 6, 4, 0, 6, 7, 0, 1, 3, 2, 0, 1, 0, 0), # 177
(4, 2, 1, 5, 1, 2, 0, 0, 3, 1, 2, 0, 0, 3, 5, 3, 1, 3, 1, 0, 3, 1, 2, 1, 0, 0), # 178
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # 179
)
station_arriving_intensity = (
(6.025038694046121, 6.630346271631799, 6.253539875535008, 7.457601328636119, 6.665622729131534, 3.766385918444806, 4.9752427384486975, 5.583811407575308, 7.308118874601608, 4.749618018626843, 5.046318196662723, 5.877498093967408, 6.100656255094035), # 0
(6.425192582423969, 7.06807283297371, 6.666415909596182, 7.950173103931939, 7.106988404969084, 4.015180300851067, 5.303362729516432, 5.951416467486849, 7.79069439159949, 5.062776830732579, 5.3797153631473575, 6.265459992977225, 6.503749976927826), # 1
(6.8240676107756775, 7.504062205069175, 7.077650742656896, 8.440785245597752, 7.546755568499692, 4.262982137414934, 5.630182209552845, 6.317550297485303, 8.271344168253059, 5.3746965300246545, 5.711787778531575, 6.651879182463666, 6.905237793851628), # 2
(7.220109351775874, 7.936584602323736, 7.485613043183825, 8.927491689038488, 7.983194011202282, 4.508808747102135, 5.954404369977547, 6.680761388993408, 8.74816219310531, 5.684139238111417, 6.041218094192859, 7.035222821916553, 7.30352736750507), # 3
(7.611763378099177, 8.363910239142928, 7.8886714796436435, 9.408346369659084, 8.41457352455579, 4.751677448878401, 6.27473240221015, 7.039598233433898, 9.219242454699248, 5.9898670766012145, 6.36668896150869, 7.413958070825716, 7.69702635952778), # 4
(7.9974752624202115, 8.784309329932306, 8.285194720503021, 9.881403222864472, 8.839163900039136, 4.990605561709457, 6.589869497670269, 7.392609322229511, 9.682678941577871, 6.290642167102395, 6.686883031856559, 7.786552088680978, 8.084142431559393), # 5
(8.375690577413598, 9.196052089097401, 8.673551434228639, 10.344716184059582, 9.255234929131252, 5.224610404561036, 6.898518847777515, 7.738343146802986, 10.136565642284177, 6.58522663122331, 7.000482956613939, 8.15147203497217, 8.463283245239527), # 6
(8.744854895753962, 9.597408731043757, 9.052110289287162, 10.796339188649354, 9.661056403311065, 5.452709296398865, 7.199383643951502, 8.075348198577062, 10.578996545361173, 6.872382590572303, 7.306171387158321, 8.507185069189115, 8.832856462207822), # 7
(9.103413790115921, 9.986649470176918, 9.419239954145274, 11.234326172038713, 10.054898114057503, 5.673919556188667, 7.491167077611837, 8.402172968974469, 11.008065639351846, 7.150872166757728, 7.602630974867185, 8.852158350821643, 9.1912697441039), # 8
(9.449812833174102, 10.362044520902426, 9.773309097269644, 11.656731069632603, 10.43502985284949, 5.88725850289618, 7.772572340178144, 8.717365949417955, 11.421866912799208, 7.419457481387929, 7.888544371118013, 9.184859039359576, 9.536930752567395), # 9
(9.782497597603118, 10.721864097625819, 10.11268638712695, 12.061607816835945, 10.79972141116596, 6.091743455487129, 8.042302623070025, 9.019475631330252, 11.818494354246257, 7.676900656071257, 8.162594227288288, 9.503754294292742, 9.868247149237932), # 10
(10.099913656077605, 11.064378414752648, 10.435740492183857, 12.447010349053675, 11.14724258048584, 6.286391732927242, 8.2990611177071, 9.307050506134097, 12.196041952235992, 7.921963812416062, 8.423463194755499, 9.807311275110973, 10.183626595755133), # 11
(10.400506581272174, 11.387857686688436, 10.740840080907047, 12.810992601690733, 11.475863152288053, 6.470220654182243, 8.541551015508974, 9.578639065252224, 12.552603695311413, 8.153409072030685, 8.669833924897121, 10.093997141304081, 10.48147675375864), # 12
(10.68272194586145, 11.690572127838744, 11.026353821763193, 13.151608510152052, 11.78385291805152, 6.642247538217868, 8.768475507895266, 9.832789800107378, 12.886273572015517, 8.369998556523484, 8.900389069090641, 10.362279052361904, 10.760205284888082), # 13
(10.945005322520059, 11.970791952609106, 11.290650383218976, 13.46691200984255, 12.069481669255188, 6.801489703999841, 8.978537786285592, 10.068051202122295, 13.195145570891304, 8.5704943875028, 9.113811278713541, 10.610624167774272, 11.018219850783076), # 14
(11.185802283922625, 12.22678737540506, 11.53209843374105, 13.754957036167182, 12.33101919737797, 6.946964470493895, 9.17044104209955, 10.282971762719706, 13.477313680481783, 8.753658686576989, 9.308783205143303, 10.837499647031004, 11.253928113083257), # 15
(11.40355840274376, 12.456828610632158, 11.749066641796109, 14.01379752453086, 12.5667352938988, 7.077689156665751, 9.34288846675677, 10.476099973322352, 13.730871889329944, 8.918253575354395, 9.483987499757415, 11.041372649621927, 11.465737733428254), # 16
(11.59671925165809, 12.659185872695934, 11.939923675850823, 14.241487410338534, 12.774899750296605, 7.192681081481142, 9.494583251676852, 10.64598432535298, 13.95391418597878, 9.06304117544336, 9.638106813933359, 11.220710335036866, 11.652056373457699), # 17
(11.763730403340244, 12.832129376001928, 12.103038204371856, 14.436080628995134, 12.953782358050306, 7.290957563905803, 9.62422858827942, 10.791173310234312, 14.144534558971316, 9.186783608452243, 9.76982379904861, 11.373979862765658, 11.811291694811214), # 18
(11.903037430464838, 12.973929334955693, 12.236778895825895, 14.595631115905576, 13.101652908638838, 7.37153592290545, 9.730527667984072, 10.910215419389093, 14.300826996850533, 9.288242995989393, 9.877821106480653, 11.499648392298115, 11.941851359128435), # 19
(12.013085905706498, 13.082855963962754, 12.339514418679602, 14.718192806474825, 13.216781193541133, 7.4334334774458215, 9.812183682210435, 11.00165914424006, 14.420885488159437, 9.36618145966315, 9.96078138760698, 11.59618308312407, 12.042143028048988), # 20
(12.09232140173984, 13.15717947742867, 12.409613441399662, 14.801819636107782, 13.297437004236105, 7.475667546492642, 9.86789982237811, 11.064052976209947, 14.502804021441024, 9.419361121081865, 10.01738729380507, 11.662051094733352, 12.110574363212494), # 21
(12.139189491239494, 13.195170089758973, 12.445444632452743, 14.844565540209402, 13.341890132202689, 7.497255449011639, 9.89637927990672, 11.095945406721498, 14.544676585238298, 9.44654410185389, 10.046321476452407, 11.695719586615787, 12.145553026258591), # 22
(12.156472036011166, 13.199668312757202, 12.449907818930042, 14.849916975308643, 13.353278467239116, 7.5, 9.899764802711205, 11.099392592592592, 14.54991148148148, 9.44975072702332, 10.049949644594088, 11.69987709190672, 12.15), # 23
(12.169214895640982, 13.197044444444446, 12.449177777777777, 14.849258333333335, 13.359729136337823, 7.5, 9.8979045751634, 11.0946, 14.549209999999999, 9.44778074074074, 10.049549494949495, 11.698903703703703, 12.15), # 24
(12.181688676253897, 13.191872427983538, 12.447736625514404, 14.84795524691358, 13.366037934713404, 7.5, 9.894238683127572, 11.085185185185185, 14.547824074074073, 9.443902606310013, 10.048756079311634, 11.696982167352537, 12.15), # 25
(12.19389242285764, 13.184231275720165, 12.445604115226338, 14.846022530864197, 13.372204642105325, 7.5, 9.888824061970466, 11.071325925925926, 14.54577148148148, 9.438180850480109, 10.047576580621024, 11.694138820301784, 12.15), # 26
(12.205825180459962, 13.174199999999997, 12.4428, 14.843474999999998, 13.378229038253057, 7.5, 9.881717647058824, 11.0532, 14.54307, 9.430679999999999, 10.046018181818182, 11.6904, 12.15), # 27
(12.217485994068602, 13.161857613168722, 12.439344032921811, 14.8403274691358, 13.384110902896081, 7.5, 9.87297637375938, 11.030985185185186, 14.539737407407406, 9.421464581618656, 10.04408806584362, 11.685792043895749, 12.15), # 28
(12.2288739086913, 13.147283127572017, 12.43525596707819, 14.83659475308642, 13.389850015773865, 7.5, 9.862657177438878, 11.004859259259257, 14.535791481481482, 9.410599122085047, 10.041793415637859, 11.680341289437584, 12.15), # 29
(12.239987969335797, 13.130555555555555, 12.430555555555555, 14.832291666666666, 13.395446156625884, 7.5, 9.850816993464052, 10.974999999999998, 14.53125, 9.398148148148149, 10.039141414141413, 11.674074074074072, 12.15), # 30
(12.25082722100983, 13.11175390946502, 12.42526255144033, 14.827433024691356, 13.400899105191609, 7.5, 9.837512757201647, 10.941585185185184, 14.52613074074074, 9.384176186556926, 10.0361392442948, 11.667016735253773, 12.15), # 31
(12.261390708721144, 13.09095720164609, 12.419396707818928, 14.822033641975308, 13.406208641210513, 7.5, 9.822801404018398, 10.904792592592594, 14.520451481481482, 9.368747764060357, 10.032794089038532, 11.659195610425241, 12.15), # 32
(12.271677477477477, 13.068244444444444, 12.412977777777778, 14.816108333333332, 13.411374544422076, 7.5, 9.806739869281046, 10.8648, 14.51423, 9.351927407407407, 10.02911313131313, 11.650637037037034, 12.15), # 33
(12.28168657228657, 13.04369465020576, 12.406025514403291, 14.809671913580246, 13.416396594565759, 7.5, 9.789385088356331, 10.821785185185183, 14.507484074074075, 9.33377964334705, 10.025103554059108, 11.641367352537722, 12.15), # 34
(12.291417038156167, 13.01738683127572, 12.398559670781895, 14.802739197530862, 13.421274571381044, 7.5, 9.77079399661099, 10.775925925925925, 14.500231481481482, 9.314368998628257, 10.020772540216983, 11.631412894375858, 12.15), # 35
(12.300867920094007, 12.989399999999998, 12.3906, 14.795324999999998, 13.426008254607403, 7.5, 9.751023529411764, 10.727400000000001, 14.492489999999998, 9.293759999999999, 10.016127272727273, 11.620800000000001, 12.15), # 36
(12.310038263107828, 12.95981316872428, 12.382166255144032, 14.787444135802469, 13.430597423984304, 7.5, 9.730130622125392, 10.676385185185184, 14.484277407407406, 9.272017174211248, 10.01117493453049, 11.609555006858711, 12.15), # 37
(12.31892711220537, 12.928705349794239, 12.37327818930041, 14.779111419753086, 13.435041859251228, 7.5, 9.708172210118615, 10.62305925925926, 14.475611481481481, 9.249205048010975, 10.005922708567153, 11.597704252400549, 12.15), # 38
(12.327533512394384, 12.896155555555554, 12.363955555555556, 14.770341666666667, 13.439341340147644, 7.5, 9.68520522875817, 10.567599999999999, 14.466510000000001, 9.225388148148149, 10.000377777777777, 11.585274074074073, 12.15), # 39
(12.335856508682596, 12.86224279835391, 12.354218106995884, 14.761149691358025, 13.443495646413021, 7.5, 9.661286613410796, 10.510185185185186, 14.456990740740741, 9.200631001371743, 9.99454732510288, 11.572290809327848, 12.15), # 40
(12.343895146077754, 12.82704609053498, 12.344085596707819, 14.751550308641974, 13.447504557786841, 7.5, 9.636473299443233, 10.450992592592593, 14.44707148148148, 9.174998134430727, 9.988438533482979, 11.558780795610424, 12.15), # 41
(12.3516484695876, 12.790644444444444, 12.333577777777778, 14.741558333333334, 13.45136785400857, 7.5, 9.610822222222222, 10.3902, 14.436770000000001, 9.148554074074074, 9.982058585858585, 11.54477037037037, 12.15), # 42
(12.35911552421987, 12.753116872427984, 12.322714403292181, 14.731188580246913, 13.455085314817683, 7.5, 9.584390317114499, 10.327985185185186, 14.426104074074072, 9.121363347050755, 9.97541466517022, 11.530285871056241, 12.15), # 43
(12.366295354982311, 12.714542386831276, 12.31151522633745, 14.72045586419753, 13.458656719953654, 7.5, 9.557234519486807, 10.264525925925927, 14.415091481481479, 9.09349048010974, 9.968513954358398, 11.515353635116599, 12.15), # 44
(12.37318700688266, 12.674999999999999, 12.299999999999999, 14.709375, 13.462081849155954, 7.5, 9.529411764705882, 10.2, 14.403749999999999, 9.065, 9.961363636363636, 11.499999999999998, 12.15), # 45
(12.379789524928656, 12.634568724279836, 12.288188477366253, 14.697960802469135, 13.465360482164058, 7.5, 9.500978988138465, 10.134585185185186, 14.392097407407405, 9.035956433470506, 9.953970894126448, 11.484251303155007, 12.15), # 46
(12.386101954128042, 12.59332757201646, 12.276100411522634, 14.686228086419751, 13.46849239871744, 7.5, 9.471993125151295, 10.068459259259258, 14.380151481481482, 9.006424307270233, 9.946342910587354, 11.468133882030179, 12.15), # 47
(12.392123339488554, 12.551355555555554, 12.263755555555555, 14.674191666666667, 13.471477378555573, 7.5, 9.442511111111111, 10.001800000000001, 14.367930000000001, 8.976468148148147, 9.938486868686867, 11.451674074074074, 12.15), # 48
(12.397852726017943, 12.508731687242797, 12.251173662551441, 14.661866358024692, 13.474315201417928, 7.5, 9.412589881384651, 9.934785185185184, 14.355450740740741, 8.946152482853224, 9.930409951365506, 11.434898216735254, 12.15), # 49
(12.403289158723938, 12.46553497942387, 12.23837448559671, 14.649266975308642, 13.477005647043978, 7.5, 9.38228637133866, 9.867592592592592, 14.342731481481481, 8.91554183813443, 9.922119341563786, 11.417832647462278, 12.15), # 50
(12.408431682614292, 12.421844444444444, 12.225377777777776, 14.636408333333332, 13.479548495173196, 7.5, 9.351657516339868, 9.8004, 14.329790000000001, 8.88470074074074, 9.913622222222223, 11.400503703703704, 12.15), # 51
(12.413279342696734, 12.377739094650208, 12.21220329218107, 14.62330524691358, 13.481943525545056, 7.5, 9.320760251755022, 9.733385185185183, 14.316644074074073, 8.853693717421125, 9.904925776281331, 11.382937722908094, 12.15), # 52
(12.417831183979011, 12.333297942386832, 12.198870781893005, 14.609972530864196, 13.484190517899036, 7.5, 9.28965151295086, 9.666725925925926, 14.303311481481483, 8.822585294924554, 9.89603718668163, 11.365161042524004, 12.15), # 53
(12.42208625146886, 12.2886, 12.185399999999998, 14.596425, 13.486289251974602, 7.5, 9.258388235294117, 9.600599999999998, 14.28981, 8.79144, 9.886963636363634, 11.347199999999999, 12.15), # 54
(12.426043590174027, 12.24372427983539, 12.171810699588478, 14.5826774691358, 13.488239507511228, 7.5, 9.227027354151536, 9.535185185185185, 14.276157407407407, 8.760322359396433, 9.877712308267864, 11.329080932784636, 12.15), # 55
(12.429702245102245, 12.198749794238683, 12.158122633744856, 14.568744753086419, 13.49004106424839, 7.5, 9.195625804889858, 9.470659259259259, 14.262371481481482, 8.729296899862826, 9.868290385334829, 11.310830178326475, 12.15), # 56
(12.433061261261258, 12.153755555555556, 12.144355555555556, 14.554641666666665, 13.49169370192556, 7.5, 9.164240522875817, 9.407200000000001, 14.24847, 8.698428148148148, 9.85870505050505, 11.292474074074073, 12.15), # 57
(12.436119683658815, 12.108820576131688, 12.130529218106995, 14.540383024691355, 13.493197200282209, 7.5, 9.132928443476155, 9.344985185185184, 14.23447074074074, 8.667780631001373, 9.848963486719043, 11.274038957475994, 12.15), # 58
(12.438876557302644, 12.064023868312757, 12.116663374485597, 14.525983641975307, 13.494551339057814, 7.5, 9.101746502057614, 9.284192592592593, 14.220391481481482, 8.637418875171468, 9.839072876917319, 11.255551165980796, 12.15), # 59
(12.441330927200491, 12.019444444444444, 12.102777777777776, 14.511458333333334, 13.495755897991843, 7.5, 9.070751633986927, 9.225, 14.20625, 8.607407407407408, 9.829040404040404, 11.237037037037037, 12.15), # 60
(12.443481838360098, 11.975161316872429, 12.08889218106996, 14.496821913580245, 13.496810656823774, 7.5, 9.040000774630839, 9.167585185185185, 14.192064074074073, 8.577810754458161, 9.818873251028807, 11.218522908093279, 12.15), # 61
(12.445328335789204, 11.931253497942386, 12.075026337448561, 14.482089197530865, 13.497715395293081, 7.5, 9.009550859356088, 9.112125925925925, 14.177851481481481, 8.548693443072702, 9.808578600823045, 11.20003511659808, 12.15), # 62
(12.44686946449555, 11.887799999999999, 12.0612, 14.467275, 13.498469893139227, 7.5, 8.979458823529411, 9.0588, 14.16363, 8.520119999999999, 9.798163636363636, 11.1816, 12.15), # 63
(12.448104269486876, 11.844879835390946, 12.047432921810698, 14.452394135802468, 13.499073930101698, 7.5, 8.94978160251755, 9.007785185185186, 14.149417407407407, 8.492154951989026, 9.787635540591094, 11.1632438957476, 12.15), # 64
(12.449031795770926, 11.802572016460903, 12.033744855967079, 14.437461419753085, 13.49952728591996, 7.5, 8.920576131687243, 8.959259259259259, 14.135231481481481, 8.464862825788751, 9.777001496445942, 11.144993141289435, 12.15), # 65
(12.449651088355436, 11.760955555555556, 12.020155555555556, 14.422491666666666, 13.499829740333487, 7.5, 8.891899346405228, 8.913400000000001, 14.12109, 8.438308148148147, 9.766268686868687, 11.126874074074076, 12.15), # 66
(12.44996119224815, 11.720109465020576, 12.00668477366255, 14.407499691358023, 13.499981073081754, 7.5, 8.863808182038246, 8.870385185185187, 14.10701074074074, 8.412555445816187, 9.755444294799851, 11.108913031550067, 12.15), # 67
(12.44974993737699, 11.679898367184387, 11.993287139917694, 14.392370088566828, 13.499853546356814, 7.49986081390032, 8.836218233795575, 8.830012620027434, 14.092905418381346, 8.3875445299766, 9.74434318624845, 11.09103602627969, 12.149850180041152), # 68
(12.447770048309177, 11.639094623655915, 11.979586111111109, 14.376340217391302, 13.498692810457515, 7.49876049382716, 8.808321817615935, 8.790118518518518, 14.078157407407408, 8.362567668845314, 9.731835406698563, 11.072662768031188, 12.148663194444444), # 69
(12.443862945070673, 11.597510951812026, 11.965522119341562, 14.35930454911433, 13.49639917695473, 7.496593507087334, 8.779992161473643, 8.75034293552812, 14.062683470507546, 8.33750342935528, 9.717778663831295, 11.05370731355137, 12.14631880144033), # 70
(12.438083592771514, 11.555172202309835, 11.951100102880657, 14.341288204508858, 13.493001694504963, 7.49339497027892, 8.751241991446784, 8.710699039780522, 14.046506652949246, 8.312352431211167, 9.702224844940634, 11.034183524655257, 12.142847865226338), # 71
(12.430486956521738, 11.51210322580645, 11.936324999999998, 14.322316304347826, 13.488529411764706, 7.4892, 8.722084033613445, 8.671199999999999, 14.02965, 8.287115294117646, 9.685225837320575, 11.014105263157894, 12.13828125), # 72
(12.421128001431383, 11.46832887295898, 11.921201748971193, 14.302413969404187, 13.48301137739046, 7.48404371284865, 8.69253101405171, 8.631858984910837, 14.012136556927299, 8.261792637779392, 9.666833528265105, 10.993486390874303, 12.132649819958848), # 73
(12.410061692610485, 11.423873994424532, 11.905735288065841, 14.281606320450885, 13.47647664003873, 7.477961225422954, 8.662595658839667, 8.59268916323731, 13.993989368998628, 8.236385081901073, 9.647099805068226, 10.972340769619521, 12.125984439300412), # 74
(12.397342995169081, 11.378763440860213, 11.889930555555553, 14.25991847826087, 13.468954248366014, 7.470987654320988, 8.6322906940554, 8.553703703703704, 13.97523148148148, 8.210893246187362, 9.626076555023921, 10.950682261208575, 12.118315972222222), # 75
(12.383026874217212, 11.33302206292314, 11.873792489711933, 14.237375563607086, 13.460473251028805, 7.463158116140832, 8.601628845776993, 8.514915775034293, 13.955885939643347, 8.185317750342934, 9.60381566542619, 10.928524727456498, 12.10967528292181), # 76
(12.367168294864912, 11.286674711270411, 11.857326028806582, 14.214002697262478, 13.451062696683609, 7.454507727480566, 8.570622840082535, 8.476338545953361, 13.935975788751714, 8.15965921407246, 9.580369023569023, 10.905882030178327, 12.10009323559671), # 77
(12.349822222222222, 11.23974623655914, 11.84053611111111, 14.189824999999999, 13.440751633986928, 7.445071604938271, 8.53928540305011, 8.437985185185186, 13.915524074074073, 8.133918257080609, 9.55578851674641, 10.882768031189086, 12.089600694444444), # 78
(12.331043621399177, 11.192261489446436, 11.823427674897118, 14.164867592592591, 13.429569111595256, 7.434884865112025, 8.5076292607578, 8.399868861454047, 13.894553840877913, 8.108095499072055, 9.530126032252346, 10.859196592303805, 12.07822852366255), # 79
(12.310887457505816, 11.144245320589407, 11.806005658436213, 14.139155595813206, 13.417544178165095, 7.423982624599908, 8.475667139283697, 8.362002743484226, 13.873088134430727, 8.082191559751472, 9.503433457380826, 10.835181575337522, 12.066007587448558), # 80
(12.289408695652174, 11.09572258064516, 11.788274999999999, 14.112714130434783, 13.40470588235294, 7.412399999999999, 8.443411764705882, 8.3244, 13.851149999999999, 8.05620705882353, 9.475762679425838, 10.810736842105262, 12.052968749999998), # 81
(12.26666230094829, 11.046718120270809, 11.770240637860082, 14.085568317230273, 13.391083272815298, 7.40017210791038, 8.410875863102444, 8.28707379972565, 13.828762482853223, 8.030142615992899, 9.447165585681375, 10.785876254422064, 12.039142875514404), # 82
(12.242703238504205, 10.997256790123457, 11.751907510288065, 14.057743276972623, 13.376705398208665, 7.387334064929126, 8.378072160551463, 8.250037311385459, 13.805948628257887, 8.003998850964253, 9.417694063441433, 10.760613674102954, 12.0245608281893), # 83
(12.21758647342995, 10.947363440860215, 11.733280555555554, 14.029264130434782, 13.361601307189543, 7.373920987654321, 8.345013383131029, 8.213303703703703, 13.78273148148148, 7.977776383442266, 9.3874, 10.734962962962962, 12.009253472222222), # 84
(12.191366970835569, 10.897062923138192, 11.714364711934154, 14.000155998389696, 13.345800048414427, 7.359967992684042, 8.311712256919229, 8.176886145404664, 13.759134087791493, 7.951475833131606, 9.356335282651072, 10.708937982817124, 11.9932516718107), # 85
(12.164099695831096, 10.846380087614497, 11.695164917695474, 13.970444001610307, 13.32933067053982, 7.34551019661637, 8.278181507994145, 8.14079780521262, 13.73517949245542, 7.925097819736949, 9.32455179868864, 10.682552595480471, 11.976586291152262), # 86
(12.135839613526569, 10.795339784946236, 11.67568611111111, 13.940153260869563, 13.312222222222223, 7.330582716049382, 8.244433862433862, 8.10505185185185, 13.710890740740743, 7.8986429629629615, 9.292101435406698, 10.655820662768031, 11.959288194444444), # 87
(12.106641689032028, 10.74396686579052, 11.655933230452675, 13.90930889694042, 13.29450375211813, 7.315220667581161, 8.210482046316468, 8.069661454046638, 13.686290877914953, 7.8721118825143215, 9.259036080099238, 10.628756046494837, 11.941388245884776), # 88
(12.076560887457505, 10.69228618080446, 11.63591121399177, 13.877936030595812, 13.276204308884047, 7.299459167809785, 8.176338785720048, 8.034639780521262, 13.661402949245542, 7.845505198095699, 9.225407620060253, 10.601372608475922, 11.922917309670781), # 89
(12.045652173913043, 10.640322580645162, 11.615625, 13.846059782608696, 13.257352941176471, 7.283333333333333, 8.142016806722689, 7.999999999999999, 13.636250000000002, 7.818823529411764, 9.191267942583732, 10.573684210526315, 11.90390625), # 90
(12.013970513508676, 10.588100915969731, 11.59507952674897, 13.813705273752015, 13.237978697651899, 7.266878280749885, 8.107528835402473, 7.965755281207133, 13.610855075445818, 7.79206749616719, 9.15666893496367, 10.54570471446105, 11.884385931069957), # 91
(11.981570871354446, 10.535646037435285, 11.574279732510288, 13.78089762479871, 13.218110626966835, 7.250129126657521, 8.07288759783749, 7.9319187928669415, 13.585241220850481, 7.7652377180666505, 9.121662484494063, 10.517447982095156, 11.864387217078187), # 92
(11.948508212560386, 10.482982795698925, 11.553230555555555, 13.74766195652174, 13.197777777777778, 7.2331209876543205, 8.03810582010582, 7.898503703703704, 13.55943148148148, 7.738334814814813, 9.0863004784689, 10.488927875243665, 11.84394097222222), # 93
(11.914837502236535, 10.43013604141776, 11.531936934156379, 13.714023389694042, 13.177009198741224, 7.215888980338362, 8.003196228285553, 7.865523182441701, 13.53344890260631, 7.7113594061163555, 9.050634804182172, 10.460158255721609, 11.823078060699588), # 94
(11.880613705492932, 10.377130625248904, 11.510403806584362, 13.680007045088566, 13.155833938513677, 7.198468221307727, 7.968171548454772, 7.832990397805213, 13.507316529492455, 7.684312111675945, 9.014717348927874, 10.431152985344015, 11.801829346707818), # 95
(11.845891787439614, 10.323991397849465, 11.488636111111111, 13.645638043478261, 13.134281045751633, 7.180893827160493, 7.933044506691564, 7.800918518518519, 13.481057407407405, 7.657193551198256, 8.9786, 10.401925925925926, 11.780225694444445), # 96
(11.810726713186616, 10.270743209876544, 11.466638786008229, 13.610941505636069, 13.112379569111596, 7.163200914494741, 7.897827829074016, 7.769320713305898, 13.454694581618655, 7.63000434438796, 8.942334644692538, 10.372490939282363, 11.758297968106996), # 97
(11.775173447843981, 10.217410911987256, 11.444416769547324, 13.575942552334944, 13.090158557250062, 7.145424599908551, 7.86253424168021, 7.738210150891632, 13.428251097393689, 7.602745110949729, 8.905973170299486, 10.342861887228358, 11.736077031893004), # 98
(11.739286956521738, 10.16401935483871, 11.421975, 13.540666304347825, 13.06764705882353, 7.1276, 7.827176470588236, 7.707599999999999, 13.40175, 7.575416470588234, 8.869567464114832, 10.313052631578946, 11.71359375), # 99
(11.703122204329933, 10.110593389088011, 11.39931841563786, 13.505137882447665, 13.044874122488501, 7.109762231367169, 7.791767241876174, 7.677503429355281, 13.375214334705076, 7.548019043008149, 8.833169413432572, 10.28307703414916, 11.690878986625515), # 100
(11.6667341563786, 10.057157865392274, 11.376451954732511, 13.469382407407409, 13.021868796901476, 7.091946410608139, 7.756319281622114, 7.647933607681755, 13.348667146776405, 7.5205534479141445, 8.796830905546694, 10.252948956754024, 11.667963605967076), # 101
(11.630177777777778, 10.003737634408603, 11.353380555555555, 13.433425, 12.998660130718955, 7.074187654320988, 7.720845315904139, 7.618903703703703, 13.32213148148148, 7.4930203050108934, 8.760603827751195, 10.222682261208577, 11.644878472222222), # 102
(11.593508033637502, 9.950357546794105, 11.3301091563786, 13.39729078099839, 12.975277172597435, 7.056521079103795, 7.685358070800336, 7.590426886145404, 13.295630384087792, 7.465420234003066, 8.724540067340067, 10.192290809327847, 11.621654449588474), # 103
(11.556779889067812, 9.897042453205893, 11.30664269547325, 13.361004871175522, 12.951748971193416, 7.03898180155464, 7.649870272388791, 7.562516323731138, 13.269186899862826, 7.437753854595336, 8.6886915116073, 10.161788462926864, 11.598322402263374), # 104
(11.520048309178742, 9.843817204301073, 11.28298611111111, 13.324592391304348, 12.928104575163397, 7.021604938271605, 7.614394646747589, 7.535185185185185, 13.242824074074074, 7.410021786492375, 8.653110047846889, 10.131189083820663, 11.574913194444443), # 105
(11.483368259080336, 9.790706650736759, 11.259144341563784, 13.288078462157811, 12.904373033163884, 7.004425605852766, 7.578943919954813, 7.508446639231824, 13.216564951989024, 7.382224649398854, 8.617847563352825, 10.100506533824273, 11.551457690329217), # 106
(11.446794703882626, 9.737735643170053, 11.235122325102882, 13.251488204508856, 12.880583393851365, 6.987478920896206, 7.543530818088553, 7.482313854595337, 13.190432578875171, 7.354363063019446, 8.582955945419101, 10.069754674752724, 11.527986754115226), # 107
(11.410382608695652, 9.684929032258065, 11.210925000000001, 13.214846739130435, 12.856764705882352, 6.9708, 7.508168067226889, 7.4568, 13.16445, 7.326437647058824, 8.548487081339712, 10.038947368421054, 11.504531250000001), # 108
(11.374186938629451, 9.632311668657906, 11.18655730452675, 13.178179186795488, 12.832946017913338, 6.954423959762231, 7.472868393447913, 7.431918244170096, 13.138640260631002, 7.298449021221656, 8.514492858408648, 10.008098476644285, 11.48112204218107), # 109
(11.338262658794058, 9.579908403026684, 11.162024176954734, 13.141510668276974, 12.809156378600823, 6.938385916780978, 7.437644522829707, 7.407681755829903, 13.113026406035663, 7.270397805212619, 8.4810251639199, 9.977221861237457, 11.457789994855966), # 110
(11.302664734299517, 9.527744086021507, 11.137330555555558, 13.104866304347826, 12.785424836601306, 6.922720987654322, 7.402509181450357, 7.384103703703703, 13.087631481481482, 7.242284618736383, 8.448135885167463, 9.946331384015595, 11.434565972222222), # 111
(11.26744813025586, 9.47584356829948, 11.112481378600824, 13.068271215780998, 12.76178044057129, 6.907464288980339, 7.367475095387949, 7.361197256515775, 13.062478532235938, 7.214110081497618, 8.41587690944533, 9.915440906793732, 11.411480838477365), # 112
(11.232605068443652, 9.424318342543142, 11.087541393902482, 13.031800658990448, 12.738210816208445, 6.892643723057416, 7.332631156388123, 7.339023082536727, 13.037655373510344, 7.185965683935275, 8.38430868738344, 9.884631523805313, 11.388532681011865), # 113
(11.197777077480078, 9.373676620230642, 11.062854810025941, 12.995747305532804, 12.71447202547959, 6.8782255302358815, 7.298421850092694, 7.317853511406144, 13.013542842855673, 7.158378201495339, 8.353493204535836, 9.85429460653557, 11.365530496992042), # 114
(11.162861883604794, 9.323936638419655, 11.038436319248781, 12.960101406218135, 12.69048921346632, 6.864172214998518, 7.264871580229873, 7.297683185134451, 12.990149974402547, 7.131390393585692, 8.323385413712511, 9.824445099070621, 11.342407957992451), # 115
(11.127815847885161, 9.275025937550042, 11.014238627980648, 12.924799380319685, 12.666226231660534, 6.8504506527445175, 7.231925781033471, 7.278456375478791, 12.967417607073395, 7.104952030139456, 8.293927117525778, 9.795027836984815, 11.319128711707068), # 116
(11.092595331388527, 9.226872058061664, 10.990214442631183, 12.889777647110693, 12.641646931554133, 6.837027718873069, 7.199529886737303, 7.260117354196302, 12.945286579790643, 7.079012881089755, 8.26506011858794, 9.7659876558525, 11.295656405829869), # 117
(11.057156695182252, 9.179402540394388, 10.96631646961004, 12.8549726258644, 12.61671516463901, 6.8238702887833655, 7.167629331575178, 7.2426103930441155, 12.923697731476722, 7.053522716369711, 8.236726219511308, 9.737269391248018, 11.271954688054828), # 118
(11.02145630033369, 9.132544924988075, 10.942497415326867, 12.820320735854047, 12.591394782407065, 6.810945237874599, 7.136169549780907, 7.225879763779374, 12.902591901054052, 7.028431305912446, 8.208867222908193, 9.708817878745721, 11.247987206075917), # 119
(10.985450507910194, 9.08622675228259, 10.918709986191313, 12.785758396352874, 12.565649636350196, 6.7982194415459585, 7.105095975588303, 7.209869738159211, 12.88190992744507, 7.003688419651087, 8.181424931390898, 9.680577953919956, 11.223717607587115), # 120
(10.949095678979122, 9.040375562717795, 10.894906888613024, 12.75122202663412, 12.539443577960302, 6.7856597751966365, 7.0743540432311764, 7.1945245879407675, 12.861592649572199, 6.979243827518755, 8.154341147571738, 9.652494452345065, 11.199109540282393), # 121
(10.912348174607825, 8.994918896733553, 10.871040829001652, 12.716648045971025, 12.512740458729281, 6.773233114225823, 7.043889186943341, 7.179788584881178, 12.841580906357867, 6.955047299448572, 8.127557674063022, 9.6245122095954, 11.174126651855724), # 122
(10.875164355863662, 8.949784294769728, 10.847064513766842, 12.681972873636832, 12.485504130149028, 6.76090633403271, 7.013646840958606, 7.16560600073758, 12.821815536724504, 6.931048605373665, 8.101016313477052, 9.596576061245305, 11.148732590001085), # 123
(10.837500583813984, 8.904899297266184, 10.822930649318243, 12.647132928904783, 12.457698443711445, 6.748646310016486, 6.983572439510783, 7.151921107267111, 12.802237379594539, 6.9071975152271525, 8.074658868426143, 9.56863084286913, 11.122891002412453), # 124
(10.79931321952615, 8.860191444662783, 10.798591942065508, 12.612064631048112, 12.429287250908427, 6.736419917576347, 6.953611416833687, 7.138678176226909, 12.78278727389039, 6.88344379894216, 8.048427141522602, 9.540621390041217, 11.096565536783794), # 125
(10.760558624067514, 8.815588277399392, 10.774001098418278, 12.576704399340064, 12.400234403231872, 6.724194032111481, 6.923709207161124, 7.12582147937411, 12.763406058534501, 6.859737226451811, 8.022262935378736, 9.51249253833592, 11.069719840809094), # 126
(10.721193158505432, 8.771017335915868, 10.749110824786205, 12.540988653053878, 12.370503752173677, 6.711935529021078, 6.893811244726913, 7.113295288465854, 12.744034572449289, 6.836027567689229, 7.9961080526068535, 9.484189123327578, 11.042317562182317), # 127
(10.681173183907255, 8.72640616065208, 10.72387382757894, 12.504853811462798, 12.340059149225747, 6.699611283704333, 6.863862963764858, 7.101043875259275, 12.72461365455718, 6.8122645925875345, 7.969904295819269, 9.455655980590546, 11.014322348597444), # 128
(10.640455061340337, 8.681682292047888, 10.698242813206127, 12.468236293840057, 12.308864445879973, 6.687188171560433, 6.833809798508775, 7.089011511511512, 12.705084143780608, 6.788398071079854, 7.943593467628284, 9.426837945699162, 10.985697847748446), # 129
(10.598995151872039, 8.63677327054316, 10.672170488077414, 12.431072519458903, 12.276883493628256, 6.6746330679885695, 6.803597183192475, 7.077142468979701, 12.685386879042001, 6.764377773099308, 7.9171173706462135, 9.397679854227782, 10.956407707329298), # 130
(10.556749816569713, 8.591606636577751, 10.645609558602457, 12.39329890759257, 12.244080143962494, 6.661912848387936, 6.773170552049771, 7.06538101942098, 12.665462699263783, 6.740153468579022, 7.890417807485361, 9.36812654175075, 10.926415575033973), # 131
(10.51367541650071, 8.546109930591532, 10.618512731190895, 12.354851877514305, 12.210418248374584, 6.648994388157723, 6.7424753393144705, 7.053671434592488, 12.645252443368385, 6.715674927452118, 7.863436580758037, 9.33812284384241, 10.89568509855645), # 132
(10.469728312732395, 8.500210693024362, 10.59083271225238, 12.315667848497341, 12.175861658356423, 6.63584456269712, 6.711456979220387, 7.041957986251359, 12.624696950278231, 6.690891919651718, 7.8361154930765515, 9.307613596077111, 10.864179925590703), # 133
(10.424864866332113, 8.453836464316106, 10.562522208196564, 12.275683239814922, 12.14037422539991, 6.622430247405318, 6.6800609060013345, 7.0301849461547326, 12.603737058915753, 6.665754215110948, 7.808396347053214, 9.2765436340292, 10.831863703830699), # 134
(10.379041438367224, 8.406914784906629, 10.53353392543309, 12.234834470740294, 12.103919800996945, 6.60871831768151, 6.648232553891121, 7.018296586059743, 12.582313608203375, 6.640211583762931, 7.78022094530033, 9.244857793273022, 10.798700080970423), # 135
(10.332214389905081, 8.35937319523579, 10.50382057037161, 12.193057960546687, 12.066462236639419, 6.594675648924887, 6.615917357123561, 7.0062371777235315, 12.560367437063528, 6.6142137955407865, 7.751531090430213, 9.212500909382928, 10.764652704703844), # 136
(10.28434008201304, 8.311139235743456, 10.473334849421772, 12.150290128507349, 12.027965383819241, 6.580269116534637, 6.583060749932466, 6.993950992903235, 12.537839384418639, 6.587710620377641, 7.722268585055167, 9.179417817933263, 10.729685222724932), # 137
(10.235374875758456, 8.26214044686949, 10.442029468993221, 12.106467393895516, 11.988393094028302, 6.565465595909957, 6.5496081665516455, 6.981382303355987, 12.514670289191137, 6.560651828206615, 7.692375231787501, 9.145553354498373, 10.693761282727667), # 138
(10.185275132208682, 8.212304369053752, 10.409857135495608, 12.06152617598443, 11.947709218758497, 6.550231962450032, 6.515505041214911, 6.968475380838929, 12.490800990303445, 6.532987188960836, 7.661792833239527, 9.110852354652607, 10.656844532406023), # 139
(10.133997212431076, 8.16155854273611, 10.376770555338585, 12.015402894047332, 11.905877609501735, 6.534535091554055, 6.480696808156076, 6.955174497109195, 12.466172326677999, 6.5046664725734225, 7.630463192023552, 9.07525965397031, 10.618898619453978), # 140
(10.081497477492995, 8.109830508356424, 10.342722434931792, 11.968033967357464, 11.862862117749904, 6.518341858621218, 6.445128901608954, 6.9414239239239235, 12.440725137237216, 6.4756394489775015, 7.598328110751885, 9.03872008802583, 10.579887191565495), # 141
(10.027732288461786, 8.057047806354559, 10.307665480684884, 11.919355815188064, 11.818626594994903, 6.501619139050712, 6.408746755807351, 6.927167933040253, 12.41440026090353, 6.445855888106193, 7.565329392036836, 9.001178492393512, 10.539773896434559), # 142
(9.972658006404808, 8.003137977170377, 10.27155239900751, 11.86930485681237, 11.773134892728635, 6.484333808241727, 6.371495804985082, 6.912350796215319, 12.387138536599375, 6.415265559892623, 7.531408838490711, 8.962579702647707, 10.49852238175514), # 143
(9.916230992389421, 7.948028561243743, 10.234335896309313, 11.817817511503627, 11.726350862442994, 6.466452741593456, 6.333321483375959, 6.896916785206259, 12.358880803247171, 6.383818234269912, 7.496508252725821, 8.922868554362758, 10.456096295221217), # 144
(9.858407607482972, 7.891647099014518, 10.195968678999947, 11.764830198535073, 11.67823835562988, 6.4479428145050885, 6.294169225213792, 6.880810171770211, 12.329567899769344, 6.351463681171185, 7.460569437354474, 8.881989883113016, 10.41245928452676), # 145
(9.79914421275282, 7.83392113092257, 10.156403453489059, 11.71027933717995, 11.62876122378119, 6.428770902375816, 6.253984464732396, 6.863975227664311, 12.299140665088327, 6.318151670529565, 7.423534194988978, 8.839888524472823, 10.367574997365741), # 146
(9.73839716926632, 7.774778197407756, 10.115592926186292, 11.654101346711496, 11.577883318388821, 6.4089038806048295, 6.212712636165577, 6.846356224645698, 12.267539938126548, 6.283831972278175, 7.385344328241643, 8.796509314016532, 10.321407081432142), # 147
(9.676122838090825, 7.714145838909944, 10.0734898035013, 11.596232646402955, 11.525568490944673, 6.38830862459132, 6.170299173747152, 6.827897434471509, 12.234706557806435, 6.248454356350137, 7.345941639724779, 8.751797087318483, 10.27391918441993), # 148
(9.612277580293695, 7.651951595868995, 10.030046791843732, 11.536609655527563, 11.471780592940645, 6.366952009734479, 6.126689511710929, 6.80854312889888, 12.200581363050405, 6.211968592678576, 7.3052679320506915, 8.705696679953029, 10.225074954023084), # 149
(9.546817756942277, 7.588123008724775, 9.985216597623232, 11.475168793358565, 11.416483475868631, 6.344800911433499, 6.08182908429072, 6.788237579684948, 12.165105192780901, 6.174324451196612, 7.2632650078316905, 8.658152927494514, 10.174838037935576), # 150
(9.47969972910393, 7.522587617917144, 9.93895192724945, 11.411846479169196, 11.359640991220532, 6.321822205087566, 6.03566332572034, 6.7669250585868514, 12.128218885920345, 6.135471701837373, 7.2198746696800855, 8.609110665517285, 10.123172083851381), # 151
(9.41087985784601, 7.455272963885967, 9.89120548713204, 11.346579132232701, 11.301216990488243, 6.297982766095876, 5.9881376702335976, 6.744549837361729, 12.089863281391164, 6.095360114533979, 7.175038720208185, 8.558514729595691, 10.070040739464476), # 152
(9.340314504235872, 7.386106587071107, 9.841929983680641, 11.279303171822319, 11.241175325163667, 6.273249469857618, 5.939197552064303, 6.721056187766714, 12.049979218115787, 6.053939459219555, 7.128698962028299, 8.506309955304076, 10.015407652468832), # 153
(9.267960029340873, 7.315016027912428, 9.79107812330491, 11.209955017211291, 11.179479846738696, 6.247589191771985, 5.888788405446274, 6.696388381558948, 12.008507535016639, 6.011159505827223, 7.080797197752734, 8.45244117821679, 9.959236470558428), # 154
(9.193772794228362, 7.241928826849794, 9.73860261241449, 11.138471087672853, 11.116094406705235, 6.220968807238165, 5.836855664613313, 6.670490690495563, 11.965389071016153, 5.966970024290105, 7.0312752299938, 8.396853233908178, 9.901490841427231), # 155
(9.117709159965697, 7.166772524323065, 9.684456157419032, 11.06478780248025, 11.050982856555176, 6.193355191655353, 5.7833447637992395, 6.643307386333702, 11.920564665036752, 5.921320784541327, 6.980074861363805, 8.339490957952586, 9.842134412769221), # 156
(9.039725487620235, 7.089474660772107, 9.628591464728181, 10.988841580906724, 10.984109047780422, 6.164715220422736, 5.728201137237862, 6.614782740830498, 11.873975156000865, 5.874161556514009, 6.927137894475059, 8.280299185924363, 9.781130832278372), # 157
(8.957617135686286, 7.008543744926709, 9.568310344682827, 10.907723497981491, 10.912417327045196, 6.133229371580532, 5.6701280651134285, 6.582956342819247, 11.821994509918916, 5.824039099549372, 6.870714903046731, 8.217119477033206, 9.715783031298415), # 158
(8.858744120374082, 6.915678383519373, 9.488085382083584, 10.804772590546143, 10.818229571737954, 6.088427577608523, 5.601855316062859, 6.536656239317259, 11.743712713466573, 5.762737192918494, 6.800900322742793, 8.13763502841973, 9.630513176304232), # 159
(8.741846513885172, 6.810116074248857, 9.386305149547066, 10.67829301249063, 10.699704157616154, 6.0292095552572205, 5.5226924980605405, 6.4747190274328155, 11.636910272674381, 5.689446782235472, 6.716711410331447, 8.040602338665416, 9.523704730672296), # 160
(8.607866465503152, 6.692545041696563, 9.26405636629237, 10.529487004508074, 10.558071749138534, 5.956292689884377, 5.433217735208252, 6.397920639731736, 11.50299572039882, 5.604789831805125, 6.618889985519648, 7.926920962689085, 9.396448853782916), # 161
(8.457746124511628, 6.563653510443886, 9.122425751538595, 10.359556807291591, 10.394563010763845, 5.870394366847746, 5.334009151607771, 6.307037008779842, 11.343377589496363, 5.509388305932277, 6.508177868014344, 7.797490455409552, 9.2498367050164), # 162
(8.292427640194196, 6.424129705072228, 8.962500024504841, 10.16970466153432, 10.210408606950825, 5.772231971505087, 5.22564487136088, 6.20284406714295, 11.159464412823487, 5.40386416892175, 6.38531687752249, 7.653210371745638, 9.084959443753055), # 163
(8.11285316183446, 6.2746618501629845, 8.785365904410211, 9.961132807929381, 10.006839202158226, 5.662522889214155, 5.108703018569359, 6.086117747386882, 10.952664723236667, 5.2888393850783615, 6.251048833751035, 7.494980266616163, 8.902908229373192), # 164
(7.9199648387160195, 6.115938170297558, 8.592110110473802, 9.735043487169902, 9.785085460844789, 5.541984505332703, 4.983761717334986, 5.957633982077455, 10.724387053592375, 5.164935918706936, 6.106115556406933, 7.323699694939943, 8.704774221257123), # 165
(7.714704820122476, 5.948646890057345, 8.383819361914712, 9.492638939949002, 9.546378047469256, 5.41133420521849, 4.851399091759543, 5.818168703780493, 10.476039936747087, 5.0327757341122945, 5.9512588651971345, 7.140268211635801, 8.491648578785155), # 166
(7.498015255337426, 5.773476234023744, 8.161580377952045, 9.235121406959811, 9.291947626490375, 5.27128937422927, 4.712193265944809, 5.668497845061811, 10.209031905557278, 4.892980795599256, 5.787220579828592, 6.94558537162255, 8.264622461337595), # 167
(7.2708382936444735, 5.591114426778154, 7.926479877804897, 8.963693128895455, 9.02302486236689, 5.122567397722799, 4.5667223639925645, 5.509397338487231, 9.924771492879426, 4.746173067472646, 5.614742520008257, 6.740550729819013, 8.024787028294753), # 168
(7.034116084327218, 5.402249692901975, 7.67960458069237, 8.67955634644906, 8.740840419557543, 4.965885661056833, 4.4155645100045895, 5.341643116622574, 9.624667231570005, 4.592974514037284, 5.434566505443081, 6.526063841144007, 7.773233439036942), # 169
(6.78879077666926, 5.207570256976605, 7.422041205833562, 8.383913300313743, 8.44662496252108, 4.8019615495891275, 4.259297828082663, 5.166011112033656, 9.310127654485486, 4.434007099597989, 5.247434355840019, 6.3030242605163505, 7.5110528529444665), # 170
(6.5358045199542, 5.007764343583441, 7.154876472447573, 8.077966231182643, 8.141609155716246, 4.631512448677438, 4.098500442328566, 4.983277257286299, 8.982561294482347, 4.269892788459586, 5.054087890906017, 6.072331542854863, 7.239336429397638), # 171
(6.276099463465638, 4.803520177303883, 6.879197099753504, 7.762917379748876, 7.827023663601784, 4.45525574367952, 3.9337504768440783, 4.794217484946325, 8.643376684417062, 4.101253544926895, 4.855268930348032, 5.834885243078365, 6.959175327776763), # 172
(6.010617756487176, 4.59552598271933, 6.596089806970453, 7.43996898670557, 7.504099150636442, 4.27390881995313, 3.7656260557309795, 4.599607727579548, 8.293982357146106, 3.9287113333047374, 4.651719293873013, 5.59158491610567, 6.671660707462155), # 173
(5.740301548302412, 4.384469984411181, 6.306641313317521, 7.110323292745848, 7.174066281278959, 4.088189062856022, 3.5947053030910503, 4.400223917751792, 7.935786845525956, 3.752888117897936, 4.444180801187913, 5.3433301168556016, 6.37788372783412), # 174
(5.466092988194946, 4.171040406960834, 6.01193833801381, 6.775182538562841, 6.838155719988083, 3.898813857745954, 3.421566343026069, 4.196841988028875, 7.570198682413086, 3.574405863011309, 4.233395271999683, 5.091020400246977, 6.078935548272969), # 175
(5.188934225448382, 3.9559254749496873, 5.713067600278413, 6.43574896484967, 6.497598131222556, 3.7065005899806795, 3.2467872996378175, 3.9902378709766184, 7.1986264006639695, 3.3938865329496806, 4.020104526015276, 4.835555321198615, 5.7759073281590085), # 176
(4.909767409346319, 3.7398134129591414, 5.411115819330436, 6.09322481229946, 6.1536241794411275, 3.511966644917956, 3.0709462970280748, 3.781187499160839, 6.822478533135084, 3.2119520920178695, 3.8050503829416424, 4.5778344346293345, 5.4698902268725496), # 177
(4.629534689172356, 3.5233924455705936, 5.107169714388976, 5.748812321605339, 5.807464529102536, 3.3159294079155393, 2.894621459298621, 3.5704668051473587, 6.443163612682903, 3.0292245045207, 3.588974662485735, 4.318757295457952, 5.161975403793902), # 178
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 179
)
passenger_arriving_acc = (
(6, 7, 10, 5, 3, 2, 1, 1, 4, 1, 1, 0, 0, 4, 6, 6, 2, 4, 0, 3, 0, 1, 2, 0, 0, 0), # 0
(14, 15, 16, 8, 5, 4, 3, 5, 7, 1, 1, 1, 0, 13, 14, 13, 3, 5, 5, 6, 0, 3, 4, 2, 1, 0), # 1
(22, 23, 28, 11, 8, 6, 4, 6, 7, 2, 3, 1, 0, 18, 21, 15, 5, 13, 8, 9, 2, 5, 4, 3, 1, 0), # 2
(28, 27, 32, 20, 12, 9, 4, 7, 10, 4, 3, 2, 0, 28, 27, 19, 12, 22, 12, 11, 2, 6, 4, 4, 2, 0), # 3
(30, 33, 39, 30, 18, 11, 10, 11, 12, 6, 5, 3, 0, 36, 33, 21, 15, 27, 15, 15, 3, 6, 4, 4, 2, 0), # 4
(36, 41, 49, 38, 22, 13, 14, 15, 16, 7, 6, 3, 0, 43, 39, 28, 19, 31, 18, 18, 5, 10, 7, 6, 2, 0), # 5
(44, 46, 57, 51, 24, 17, 15, 20, 20, 12, 6, 3, 0, 56, 51, 33, 24, 38, 19, 20, 6, 12, 11, 9, 3, 0), # 6
(52, 62, 66, 58, 27, 18, 18, 23, 25, 14, 6, 4, 0, 66, 56, 42, 28, 46, 27, 24, 9, 15, 14, 10, 3, 0), # 7
(60, 71, 76, 68, 32, 23, 21, 26, 27, 15, 12, 6, 0, 74, 60, 47, 33, 53, 31, 29, 12, 21, 18, 10, 3, 0), # 8
(67, 85, 84, 75, 36, 27, 25, 34, 32, 16, 13, 6, 0, 80, 69, 53, 37, 59, 37, 30, 15, 23, 22, 12, 5, 0), # 9
(80, 95, 91, 83, 48, 30, 25, 35, 35, 16, 14, 8, 0, 87, 75, 58, 41, 64, 42, 33, 16, 29, 25, 14, 6, 0), # 10
(86, 107, 103, 95, 55, 33, 31, 41, 36, 16, 17, 11, 0, 95, 83, 66, 50, 74, 50, 37, 18, 35, 31, 17, 6, 0), # 11
(97, 121, 117, 102, 63, 36, 35, 42, 40, 18, 22, 11, 0, 107, 91, 71, 54, 84, 58, 41, 23, 40, 35, 18, 7, 0), # 12
(109, 133, 121, 114, 69, 37, 37, 45, 43, 21, 23, 13, 0, 115, 97, 83, 60, 91, 61, 47, 26, 48, 41, 18, 8, 0), # 13
(117, 138, 128, 120, 79, 38, 41, 52, 49, 22, 23, 13, 0, 127, 108, 93, 65, 96, 62, 50, 28, 52, 45, 20, 9, 0), # 14
(130, 149, 136, 125, 89, 48, 45, 63, 53, 24, 24, 16, 0, 143, 117, 100, 73, 110, 66, 54, 31, 54, 48, 21, 10, 0), # 15
(145, 163, 147, 132, 97, 52, 45, 73, 59, 26, 24, 16, 0, 153, 125, 105, 77, 121, 77, 62, 33, 57, 50, 23, 11, 0), # 16
(154, 176, 157, 145, 104, 55, 49, 79, 63, 29, 26, 18, 0, 168, 136, 113, 82, 130, 85, 69, 35, 59, 54, 25, 12, 0), # 17
(166, 185, 172, 158, 113, 60, 53, 81, 64, 29, 27, 20, 0, 178, 142, 122, 87, 140, 90, 76, 39, 61, 55, 25, 15, 0), # 18
(173, 208, 187, 171, 120, 66, 62, 86, 67, 31, 28, 21, 0, 188, 151, 127, 94, 154, 100, 80, 43, 64, 58, 26, 15, 0), # 19
(186, 222, 193, 176, 131, 73, 69, 90, 74, 32, 31, 22, 0, 199, 164, 140, 106, 160, 107, 83, 44, 67, 63, 27, 16, 0), # 20
(199, 232, 211, 182, 144, 80, 78, 96, 82, 34, 34, 24, 0, 211, 181, 148, 118, 167, 116, 89, 51, 72, 67, 29, 16, 0), # 21
(212, 239, 223, 194, 157, 87, 83, 97, 90, 35, 35, 25, 0, 227, 192, 152, 124, 182, 121, 96, 55, 77, 72, 32, 17, 0), # 22
(221, 252, 229, 205, 165, 90, 91, 101, 97, 38, 36, 27, 0, 238, 203, 157, 130, 197, 125, 100, 58, 80, 76, 35, 17, 0), # 23
(235, 264, 240, 213, 174, 92, 95, 103, 103, 39, 36, 30, 0, 252, 214, 164, 136, 213, 131, 105, 60, 83, 83, 37, 19, 0), # 24
(245, 277, 244, 225, 184, 94, 96, 106, 107, 42, 36, 32, 0, 259, 223, 173, 147, 221, 139, 107, 61, 91, 86, 38, 19, 0), # 25
(256, 286, 257, 236, 193, 98, 100, 111, 114, 42, 38, 36, 0, 277, 235, 180, 156, 235, 146, 110, 64, 96, 90, 41, 20, 0), # 26
(267, 300, 268, 243, 201, 103, 105, 115, 119, 46, 40, 36, 0, 286, 242, 187, 164, 249, 152, 114, 66, 106, 92, 41, 24, 0), # 27
(279, 305, 279, 254, 206, 107, 109, 121, 122, 48, 43, 38, 0, 301, 255, 198, 169, 260, 162, 118, 71, 109, 95, 43, 24, 0), # 28
(287, 321, 285, 267, 219, 112, 112, 126, 130, 49, 46, 38, 0, 313, 263, 203, 176, 272, 166, 123, 75, 118, 99, 47, 25, 0), # 29
(301, 332, 298, 282, 230, 112, 118, 130, 136, 52, 47, 39, 0, 323, 273, 211, 179, 286, 170, 126, 78, 127, 102, 49, 27, 0), # 30
(310, 338, 309, 297, 242, 114, 119, 135, 141, 54, 47, 39, 0, 328, 279, 214, 184, 297, 177, 129, 79, 130, 107, 51, 28, 0), # 31
(321, 348, 319, 310, 250, 118, 126, 139, 149, 57, 52, 40, 0, 338, 286, 224, 191, 308, 180, 134, 81, 134, 109, 54, 30, 0), # 32
(334, 355, 327, 316, 264, 125, 130, 147, 161, 57, 54, 41, 0, 350, 293, 235, 196, 315, 183, 139, 83, 139, 110, 55, 31, 0), # 33
(350, 368, 345, 329, 273, 132, 134, 149, 166, 59, 56, 42, 0, 366, 304, 247, 203, 325, 191, 142, 86, 147, 112, 57, 31, 0), # 34
(360, 381, 358, 341, 282, 138, 138, 152, 169, 59, 58, 46, 0, 372, 315, 256, 209, 336, 195, 146, 88, 153, 114, 57, 32, 0), # 35
(374, 398, 369, 351, 293, 139, 142, 161, 174, 62, 61, 47, 0, 384, 321, 261, 214, 347, 197, 151, 92, 157, 115, 62, 32, 0), # 36
(383, 407, 375, 358, 298, 144, 144, 167, 179, 65, 61, 48, 0, 396, 330, 267, 221, 362, 205, 152, 94, 160, 122, 64, 32, 0), # 37
(397, 415, 385, 367, 312, 147, 148, 171, 184, 67, 62, 49, 0, 405, 339, 275, 229, 370, 209, 157, 97, 162, 128, 65, 32, 0), # 38
(407, 429, 394, 379, 320, 151, 149, 175, 189, 69, 63, 49, 0, 412, 349, 287, 234, 375, 217, 162, 98, 166, 131, 69, 33, 0), # 39
(420, 437, 401, 385, 333, 157, 154, 177, 195, 72, 63, 50, 0, 428, 366, 293, 245, 384, 222, 167, 102, 171, 132, 70, 34, 0), # 40
(429, 451, 412, 395, 339, 160, 156, 178, 203, 74, 64, 52, 0, 435, 376, 298, 253, 391, 228, 173, 109, 177, 133, 72, 36, 0), # 41
(444, 460, 419, 412, 347, 168, 163, 181, 211, 76, 65, 53, 0, 444, 388, 308, 262, 403, 235, 182, 113, 182, 138, 75, 37, 0), # 42
(458, 469, 428, 424, 356, 172, 169, 183, 220, 78, 65, 54, 0, 451, 402, 325, 269, 410, 241, 186, 115, 187, 142, 76, 39, 0), # 43
(465, 480, 441, 433, 361, 177, 175, 185, 225, 78, 66, 55, 0, 461, 407, 334, 278, 420, 249, 191, 120, 194, 145, 78, 40, 0), # 44
(475, 489, 451, 446, 376, 180, 180, 191, 231, 79, 68, 57, 0, 473, 417, 345, 285, 430, 251, 197, 125, 199, 147, 83, 41, 0), # 45
(487, 498, 465, 456, 390, 183, 184, 196, 232, 83, 69, 57, 0, 481, 423, 354, 294, 442, 257, 201, 130, 206, 149, 85, 42, 0), # 46
(502, 509, 484, 466, 399, 187, 189, 198, 239, 83, 72, 57, 0, 495, 438, 358, 298, 454, 264, 204, 135, 208, 151, 89, 42, 0), # 47
(513, 516, 496, 475, 412, 189, 194, 203, 244, 84, 72, 60, 0, 512, 454, 364, 303, 461, 273, 209, 137, 211, 155, 91, 44, 0), # 48
(530, 528, 507, 487, 422, 193, 201, 209, 250, 87, 73, 60, 0, 528, 466, 372, 310, 472, 280, 214, 141, 215, 160, 91, 45, 0), # 49
(545, 539, 516, 504, 432, 202, 204, 215, 258, 92, 74, 60, 0, 545, 476, 377, 313, 477, 285, 218, 143, 217, 166, 93, 45, 0), # 50
(553, 547, 520, 523, 442, 208, 207, 218, 263, 95, 76, 61, 0, 554, 490, 389, 320, 486, 288, 220, 143, 227, 167, 94, 45, 0), # 51
(569, 557, 531, 531, 452, 211, 214, 219, 266, 98, 78, 61, 0, 568, 502, 398, 329, 495, 293, 222, 148, 227, 172, 94, 46, 0), # 52
(584, 566, 538, 540, 459, 213, 222, 224, 270, 100, 81, 62, 0, 583, 515, 405, 334, 504, 300, 227, 152, 234, 175, 97, 47, 0), # 53
(597, 572, 549, 553, 467, 216, 227, 227, 278, 102, 81, 62, 0, 593, 526, 411, 342, 513, 305, 231, 154, 239, 178, 98, 47, 0), # 54
(606, 585, 562, 569, 471, 221, 231, 233, 280, 102, 84, 65, 0, 603, 544, 419, 351, 521, 309, 235, 157, 243, 180, 100, 47, 0), # 55
(618, 597, 571, 578, 484, 222, 236, 237, 283, 104, 88, 65, 0, 613, 558, 425, 355, 535, 316, 243, 160, 252, 183, 102, 49, 0), # 56
(635, 611, 579, 588, 495, 228, 241, 242, 287, 109, 88, 66, 0, 628, 568, 431, 361, 545, 324, 248, 162, 261, 190, 102, 50, 0), # 57
(646, 624, 589, 601, 507, 232, 242, 245, 290, 110, 90, 67, 0, 637, 575, 442, 369, 552, 327, 250, 165, 267, 193, 104, 51, 0), # 58
(656, 640, 599, 612, 517, 240, 251, 248, 294, 114, 92, 68, 0, 650, 587, 452, 376, 562, 336, 253, 172, 271, 197, 106, 52, 0), # 59
(667, 646, 611, 622, 524, 248, 256, 250, 298, 117, 93, 68, 0, 664, 595, 460, 383, 573, 344, 256, 174, 273, 204, 106, 56, 0), # 60
(681, 654, 621, 631, 538, 250, 257, 255, 304, 118, 95, 69, 0, 678, 611, 465, 393, 581, 349, 264, 177, 279, 204, 108, 56, 0), # 61
(696, 665, 630, 638, 549, 256, 259, 259, 307, 119, 95, 72, 0, 684, 619, 468, 400, 594, 359, 269, 180, 284, 211, 109, 58, 0), # 62
(711, 675, 635, 642, 555, 260, 263, 261, 312, 122, 97, 72, 0, 699, 627, 474, 403, 600, 365, 272, 185, 284, 216, 110, 58, 0), # 63
(727, 679, 646, 647, 561, 264, 265, 263, 313, 125, 97, 73, 0, 708, 636, 477, 412, 604, 370, 273, 192, 290, 219, 112, 60, 0), # 64
(741, 693, 652, 656, 569, 268, 272, 265, 319, 129, 98, 74, 0, 718, 643, 487, 419, 613, 375, 275, 195, 293, 222, 116, 60, 0), # 65
(753, 705, 664, 667, 581, 273, 280, 269, 325, 129, 100, 75, 0, 729, 648, 493, 423, 623, 381, 276, 198, 299, 224, 117, 61, 0), # 66
(760, 711, 678, 680, 592, 277, 283, 271, 332, 132, 104, 75, 0, 742, 656, 499, 426, 637, 383, 279, 199, 306, 230, 120, 63, 0), # 67
(774, 723, 688, 687, 598, 283, 293, 278, 340, 135, 104, 76, 0, 752, 666, 505, 434, 650, 387, 285, 204, 310, 234, 120, 63, 0), # 68
(791, 739, 693, 697, 608, 285, 300, 280, 347, 136, 107, 77, 0, 770, 679, 512, 441, 657, 390, 291, 209, 319, 235, 122, 63, 0), # 69
(803, 748, 702, 712, 618, 288, 304, 283, 351, 139, 109, 78, 0, 780, 694, 523, 443, 666, 397, 300, 212, 325, 239, 123, 63, 0), # 70
(812, 759, 708, 723, 634, 292, 306, 283, 356, 143, 110, 80, 0, 794, 706, 528, 448, 674, 402, 301, 217, 332, 245, 127, 63, 0), # 71
(830, 766, 721, 739, 645, 298, 311, 285, 363, 145, 112, 80, 0, 808, 719, 534, 451, 683, 406, 306, 219, 335, 248, 127, 65, 0), # 72
(841, 773, 731, 747, 654, 303, 318, 290, 366, 146, 113, 81, 0, 824, 725, 543, 460, 690, 411, 312, 223, 341, 253, 130, 66, 0), # 73
(855, 779, 738, 756, 662, 305, 321, 293, 373, 147, 114, 82, 0, 836, 741, 552, 464, 702, 414, 316, 224, 346, 258, 131, 69, 0), # 74
(865, 791, 748, 768, 680, 313, 324, 298, 377, 148, 115, 83, 0, 847, 748, 562, 469, 708, 418, 319, 227, 353, 263, 133, 69, 0), # 75
(881, 804, 761, 772, 691, 318, 331, 299, 383, 150, 117, 84, 0, 862, 755, 566, 476, 717, 421, 322, 228, 357, 272, 135, 70, 0), # 76
(896, 815, 773, 785, 703, 323, 335, 303, 383, 151, 118, 84, 0, 875, 763, 581, 482, 729, 424, 324, 237, 362, 273, 137, 72, 0), # 77
(907, 821, 782, 794, 714, 325, 342, 305, 390, 154, 119, 85, 0, 886, 778, 590, 490, 737, 427, 329, 239, 364, 276, 139, 72, 0), # 78
(914, 835, 792, 803, 715, 327, 347, 312, 393, 155, 122, 85, 0, 897, 793, 599, 499, 750, 433, 333, 243, 368, 278, 140, 72, 0), # 79
(926, 843, 806, 807, 720, 329, 355, 313, 398, 158, 124, 85, 0, 906, 806, 603, 502, 761, 434, 337, 244, 371, 281, 142, 72, 0), # 80
(942, 855, 810, 826, 730, 333, 359, 314, 401, 160, 124, 87, 0, 913, 814, 612, 506, 770, 440, 344, 252, 377, 282, 147, 74, 0), # 81
(952, 865, 818, 833, 736, 336, 363, 317, 404, 162, 127, 88, 0, 922, 824, 619, 513, 779, 443, 347, 258, 382, 284, 151, 74, 0), # 82
(963, 877, 829, 844, 740, 339, 363, 320, 409, 165, 129, 88, 0, 935, 834, 625, 520, 788, 447, 350, 259, 388, 287, 152, 75, 0), # 83
(973, 885, 835, 856, 751, 342, 366, 325, 415, 168, 129, 91, 0, 951, 840, 632, 529, 800, 454, 352, 260, 392, 293, 154, 76, 0), # 84
(984, 891, 844, 864, 759, 343, 369, 327, 421, 170, 130, 92, 0, 969, 851, 638, 540, 812, 462, 357, 262, 397, 297, 159, 76, 0), # 85
(994, 902, 852, 869, 766, 345, 372, 328, 422, 175, 131, 92, 0, 985, 859, 647, 545, 823, 469, 358, 264, 405, 298, 160, 77, 0), # 86
(1007, 910, 857, 880, 777, 350, 378, 329, 427, 176, 131, 95, 0, 995, 869, 654, 547, 832, 471, 361, 268, 409, 302, 162, 77, 0), # 87
(1021, 923, 865, 889, 789, 355, 382, 336, 432, 178, 133, 95, 0, 1007, 883, 663, 553, 839, 475, 367, 270, 413, 307, 165, 78, 0), # 88
(1031, 933, 870, 908, 800, 360, 384, 337, 437, 182, 133, 97, 0, 1019, 893, 674, 562, 849, 484, 372, 274, 414, 309, 170, 78, 0), # 89
(1040, 948, 882, 911, 807, 362, 393, 338, 439, 183, 135, 97, 0, 1034, 903, 679, 568, 859, 488, 375, 280, 417, 311, 171, 80, 0), # 90
(1053, 955, 886, 921, 817, 367, 395, 339, 444, 186, 136, 100, 0, 1046, 913, 684, 572, 867, 495, 379, 286, 417, 313, 173, 80, 0), # 91
(1065, 966, 898, 928, 828, 371, 399, 342, 447, 188, 137, 100, 0, 1059, 925, 693, 580, 875, 500, 381, 289, 420, 316, 173, 81, 0), # 92
(1072, 978, 903, 932, 839, 377, 401, 346, 452, 192, 139, 101, 0, 1067, 937, 704, 588, 882, 504, 387, 294, 426, 319, 179, 81, 0), # 93
(1080, 991, 913, 945, 856, 378, 402, 347, 456, 193, 141, 101, 0, 1081, 949, 708, 592, 897, 507, 388, 297, 431, 325, 183, 81, 0), # 94
(1090, 1001, 930, 953, 863, 382, 403, 350, 459, 193, 142, 102, 0, 1095, 959, 716, 597, 907, 508, 394, 299, 434, 331, 185, 83, 0), # 95
(1100, 1010, 943, 964, 876, 384, 409, 354, 460, 193, 142, 103, 0, 1108, 969, 732, 600, 922, 512, 399, 304, 437, 334, 192, 85, 0), # 96
(1107, 1016, 951, 978, 884, 387, 412, 357, 464, 193, 145, 103, 0, 1128, 974, 740, 605, 931, 517, 405, 308, 443, 339, 197, 86, 0), # 97
(1120, 1023, 961, 986, 895, 394, 413, 360, 469, 193, 146, 104, 0, 1141, 991, 747, 611, 943, 519, 408, 313, 448, 343, 200, 86, 0), # 98
(1130, 1030, 977, 993, 907, 399, 416, 364, 477, 196, 148, 104, 0, 1160, 1000, 759, 618, 954, 525, 409, 316, 453, 345, 200, 86, 0), # 99
(1144, 1043, 986, 1000, 913, 402, 416, 366, 480, 198, 148, 104, 0, 1173, 1010, 765, 622, 961, 531, 412, 320, 456, 348, 201, 88, 0), # 100
(1156, 1057, 991, 1008, 918, 408, 421, 371, 482, 200, 151, 104, 0, 1187, 1017, 772, 626, 970, 534, 414, 323, 464, 351, 204, 89, 0), # 101
(1164, 1065, 1002, 1022, 929, 411, 423, 372, 490, 201, 155, 105, 0, 1206, 1025, 778, 632, 975, 537, 418, 325, 466, 355, 207, 90, 0), # 102
(1176, 1076, 1010, 1035, 934, 414, 424, 375, 495, 202, 158, 106, 0, 1218, 1036, 784, 638, 981, 541, 421, 326, 472, 357, 207, 91, 0), # 103
(1191, 1086, 1019, 1043, 938, 419, 427, 378, 497, 205, 158, 108, 0, 1233, 1047, 795, 643, 993, 544, 423, 329, 476, 360, 210, 92, 0), # 104
(1208, 1097, 1027, 1058, 945, 427, 432, 381, 502, 207, 160, 108, 0, 1243, 1058, 806, 647, 1005, 549, 428, 335, 479, 365, 210, 93, 0), # 105
(1223, 1104, 1039, 1069, 959, 431, 437, 383, 507, 207, 160, 109, 0, 1250, 1067, 813, 649, 1014, 552, 432, 338, 485, 371, 211, 94, 0), # 106
(1234, 1116, 1043, 1076, 976, 435, 441, 385, 513, 209, 160, 109, 0, 1266, 1076, 822, 653, 1018, 561, 439, 342, 486, 375, 212, 95, 0), # 107
(1246, 1122, 1055, 1085, 985, 438, 446, 387, 520, 210, 160, 109, 0, 1284, 1080, 834, 656, 1023, 566, 440, 347, 496, 382, 212, 95, 0), # 108
(1256, 1127, 1064, 1096, 995, 442, 448, 388, 528, 213, 161, 109, 0, 1295, 1086, 843, 661, 1032, 571, 446, 349, 500, 388, 215, 95, 0), # 109
(1264, 1135, 1071, 1106, 1009, 444, 451, 395, 535, 217, 162, 109, 0, 1306, 1097, 851, 670, 1037, 575, 453, 351, 502, 393, 215, 98, 0), # 110
(1269, 1145, 1078, 1116, 1021, 445, 454, 401, 541, 218, 164, 109, 0, 1324, 1107, 857, 675, 1050, 579, 457, 354, 509, 393, 217, 98, 0), # 111
(1281, 1158, 1081, 1119, 1031, 449, 461, 403, 542, 219, 166, 111, 0, 1336, 1113, 860, 685, 1057, 580, 458, 358, 513, 395, 218, 99, 0), # 112
(1293, 1164, 1089, 1130, 1039, 453, 465, 409, 547, 221, 168, 111, 0, 1341, 1122, 869, 691, 1064, 586, 461, 361, 514, 398, 221, 99, 0), # 113
(1302, 1172, 1097, 1145, 1047, 453, 469, 413, 551, 222, 170, 112, 0, 1347, 1137, 874, 694, 1080, 591, 465, 364, 517, 402, 222, 101, 0), # 114
(1308, 1178, 1107, 1158, 1056, 456, 471, 417, 555, 224, 171, 114, 0, 1359, 1150, 883, 695, 1090, 597, 471, 364, 522, 405, 222, 101, 0), # 115
(1319, 1183, 1116, 1168, 1064, 460, 476, 421, 558, 224, 171, 114, 0, 1369, 1157, 892, 703, 1099, 602, 472, 364, 525, 407, 225, 102, 0), # 116
(1333, 1188, 1127, 1182, 1076, 463, 478, 422, 568, 224, 171, 114, 0, 1383, 1162, 899, 708, 1111, 605, 476, 364, 531, 409, 226, 103, 0), # 117
(1342, 1201, 1132, 1192, 1083, 467, 483, 423, 574, 225, 172, 115, 0, 1394, 1173, 903, 711, 1120, 609, 479, 366, 536, 412, 228, 103, 0), # 118
(1353, 1207, 1140, 1204, 1093, 468, 485, 427, 576, 225, 173, 116, 0, 1403, 1181, 907, 716, 1129, 613, 480, 369, 540, 414, 231, 104, 0), # 119
(1370, 1212, 1147, 1213, 1103, 471, 489, 428, 579, 227, 176, 118, 0, 1412, 1191, 915, 722, 1136, 617, 483, 372, 548, 417, 231, 104, 0), # 120
(1380, 1225, 1153, 1216, 1114, 476, 492, 429, 581, 228, 179, 118, 0, 1422, 1202, 924, 726, 1142, 623, 486, 373, 550, 417, 232, 104, 0), # 121
(1393, 1232, 1164, 1227, 1126, 480, 494, 431, 583, 228, 181, 118, 0, 1434, 1213, 933, 729, 1146, 631, 490, 377, 556, 420, 233, 105, 0), # 122
(1410, 1241, 1178, 1245, 1132, 488, 495, 436, 588, 230, 182, 120, 0, 1448, 1221, 941, 736, 1153, 631, 493, 381, 558, 424, 235, 106, 0), # 123
(1420, 1243, 1187, 1256, 1140, 495, 501, 438, 590, 233, 184, 121, 0, 1458, 1231, 947, 744, 1160, 634, 498, 385, 562, 425, 238, 107, 0), # 124
(1430, 1250, 1207, 1264, 1147, 501, 505, 442, 593, 235, 185, 121, 0, 1469, 1238, 958, 746, 1171, 640, 501, 390, 563, 428, 240, 108, 0), # 125
(1437, 1257, 1216, 1269, 1158, 504, 507, 442, 598, 236, 186, 122, 0, 1477, 1246, 962, 752, 1177, 643, 502, 391, 565, 430, 242, 109, 0), # 126
(1448, 1269, 1220, 1279, 1170, 506, 513, 445, 599, 237, 188, 122, 0, 1493, 1257, 974, 756, 1186, 647, 505, 398, 571, 438, 244, 109, 0), # 127
(1461, 1276, 1228, 1290, 1176, 509, 514, 449, 600, 238, 190, 124, 0, 1510, 1267, 978, 758, 1193, 652, 511, 400, 574, 439, 246, 109, 0), # 128
(1472, 1285, 1238, 1301, 1191, 511, 517, 449, 603, 239, 191, 125, 0, 1522, 1273, 985, 764, 1204, 657, 515, 402, 576, 443, 248, 111, 0), # 129
(1480, 1287, 1248, 1311, 1198, 513, 521, 452, 608, 242, 193, 125, 0, 1532, 1281, 990, 769, 1210, 660, 521, 403, 582, 446, 249, 111, 0), # 130
(1494, 1297, 1256, 1320, 1209, 515, 528, 456, 612, 243, 193, 126, 0, 1548, 1287, 997, 775, 1219, 664, 521, 406, 584, 448, 249, 113, 0), # 131
(1508, 1305, 1259, 1333, 1217, 517, 529, 461, 615, 247, 194, 127, 0, 1555, 1294, 1003, 781, 1226, 668, 524, 410, 587, 450, 250, 114, 0), # 132
(1523, 1313, 1266, 1342, 1225, 520, 534, 464, 622, 248, 195, 129, 0, 1569, 1304, 1007, 789, 1235, 670, 529, 410, 592, 454, 250, 114, 0), # 133
(1537, 1325, 1273, 1351, 1232, 522, 537, 469, 625, 249, 197, 130, 0, 1576, 1317, 1018, 792, 1246, 674, 532, 411, 596, 457, 253, 116, 0), # 134
(1548, 1332, 1285, 1357, 1237, 527, 543, 470, 631, 251, 197, 130, 0, 1583, 1325, 1028, 798, 1257, 675, 537, 413, 600, 461, 255, 117, 0), # 135
(1562, 1340, 1294, 1371, 1240, 533, 545, 473, 637, 254, 199, 131, 0, 1593, 1336, 1036, 802, 1261, 677, 538, 416, 603, 464, 255, 117, 0), # 136
(1574, 1346, 1304, 1378, 1249, 536, 549, 475, 643, 257, 201, 134, 0, 1604, 1343, 1042, 808, 1266, 687, 544, 417, 606, 466, 257, 117, 0), # 137
(1585, 1353, 1309, 1386, 1256, 542, 551, 477, 652, 257, 202, 136, 0, 1623, 1352, 1044, 812, 1273, 694, 547, 419, 613, 470, 259, 117, 0), # 138
(1597, 1359, 1319, 1396, 1266, 546, 554, 480, 657, 257, 202, 136, 0, 1632, 1360, 1053, 816, 1279, 700, 548, 424, 618, 474, 263, 119, 0), # 139
(1602, 1368, 1327, 1403, 1277, 549, 558, 483, 660, 257, 204, 136, 0, 1643, 1370, 1058, 822, 1282, 702, 551, 429, 619, 480, 265, 121, 0), # 140
(1612, 1374, 1331, 1411, 1284, 554, 562, 486, 662, 260, 207, 137, 0, 1646, 1381, 1068, 828, 1292, 704, 553, 432, 624, 486, 267, 123, 0), # 141
(1623, 1380, 1335, 1414, 1295, 558, 564, 489, 665, 262, 209, 139, 0, 1657, 1388, 1076, 832, 1300, 708, 554, 437, 627, 489, 267, 126, 0), # 142
(1635, 1385, 1346, 1423, 1300, 564, 565, 493, 671, 267, 210, 141, 0, 1673, 1394, 1082, 839, 1304, 710, 557, 440, 631, 491, 268, 126, 0), # 143
(1647, 1394, 1357, 1430, 1307, 567, 568, 497, 675, 268, 211, 144, 0, 1680, 1402, 1094, 842, 1310, 715, 562, 443, 632, 495, 270, 128, 0), # 144
(1656, 1400, 1363, 1437, 1314, 578, 572, 499, 682, 269, 212, 144, 0, 1691, 1410, 1101, 845, 1317, 722, 568, 446, 639, 497, 271, 129, 0), # 145
(1669, 1408, 1372, 1444, 1319, 583, 577, 504, 686, 273, 212, 144, 0, 1696, 1420, 1105, 853, 1324, 729, 572, 448, 646, 499, 271, 132, 0), # 146
(1677, 1417, 1383, 1453, 1324, 584, 582, 506, 688, 275, 212, 144, 0, 1705, 1428, 1110, 862, 1330, 733, 576, 452, 647, 502, 272, 133, 0), # 147
(1686, 1429, 1390, 1466, 1328, 586, 584, 510, 693, 276, 213, 147, 0, 1720, 1432, 1115, 864, 1342, 737, 577, 457, 649, 508, 274, 133, 0), # 148
(1695, 1437, 1400, 1477, 1339, 588, 590, 513, 696, 277, 213, 147, 0, 1728, 1439, 1124, 867, 1349, 739, 581, 460, 653, 510, 274, 133, 0), # 149
(1709, 1442, 1411, 1484, 1343, 591, 591, 521, 700, 278, 213, 148, 0, 1737, 1446, 1134, 871, 1358, 745, 582, 463, 658, 511, 274, 135, 0), # 150
(1718, 1450, 1419, 1501, 1350, 595, 595, 523, 706, 279, 215, 148, 0, 1743, 1451, 1137, 878, 1360, 746, 584, 464, 663, 515, 274, 135, 0), # 151
(1727, 1451, 1425, 1509, 1355, 600, 597, 524, 711, 279, 216, 148, 0, 1756, 1459, 1144, 885, 1369, 751, 588, 467, 664, 517, 276, 135, 0), # 152
(1734, 1455, 1435, 1521, 1365, 605, 599, 528, 716, 285, 216, 148, 0, 1766, 1463, 1153, 888, 1381, 753, 589, 469, 664, 521, 277, 135, 0), # 153
(1737, 1460, 1443, 1529, 1372, 609, 601, 529, 718, 286, 219, 148, 0, 1780, 1467, 1161, 895, 1387, 757, 594, 471, 668, 524, 278, 135, 0), # 154
(1748, 1467, 1448, 1539, 1380, 614, 604, 531, 723, 288, 221, 149, 0, 1790, 1475, 1168, 899, 1396, 760, 597, 477, 669, 527, 278, 137, 0), # 155
(1754, 1475, 1457, 1548, 1387, 618, 606, 534, 723, 288, 224, 149, 0, 1803, 1483, 1169, 901, 1398, 768, 597, 479, 670, 528, 280, 137, 0), # 156
(1758, 1484, 1465, 1552, 1391, 621, 611, 539, 724, 290, 226, 150, 0, 1815, 1493, 1181, 906, 1406, 773, 603, 482, 675, 532, 280, 137, 0), # 157
(1765, 1490, 1472, 1558, 1395, 624, 612, 539, 731, 291, 226, 150, 0, 1831, 1499, 1186, 912, 1411, 778, 606, 483, 676, 537, 280, 137, 0), # 158
(1773, 1494, 1480, 1563, 1401, 626, 615, 540, 733, 292, 227, 150, 0, 1841, 1508, 1195, 917, 1416, 783, 608, 487, 679, 539, 280, 137, 0), # 159
(1783, 1496, 1487, 1572, 1405, 631, 617, 542, 738, 293, 227, 150, 0, 1851, 1514, 1200, 921, 1423, 788, 611, 491, 683, 541, 283, 137, 0), # 160
(1790, 1501, 1495, 1576, 1412, 632, 618, 546, 742, 293, 227, 151, 0, 1856, 1516, 1204, 923, 1426, 790, 613, 493, 688, 544, 283, 138, 0), # 161
(1800, 1509, 1504, 1583, 1417, 634, 620, 548, 744, 293, 229, 151, 0, 1862, 1520, 1211, 926, 1431, 795, 614, 495, 693, 546, 285, 138, 0), # 162
(1808, 1517, 1508, 1590, 1423, 635, 624, 550, 746, 294, 231, 152, 0, 1867, 1528, 1213, 930, 1444, 800, 620, 497, 696, 549, 285, 140, 0), # 163
(1820, 1519, 1515, 1597, 1432, 638, 625, 554, 748, 294, 231, 152, 0, 1881, 1533, 1221, 942, 1450, 805, 622, 499, 700, 551, 287, 140, 0), # 164
(1830, 1524, 1518, 1606, 1436, 644, 630, 558, 752, 295, 231, 152, 0, 1889, 1538, 1230, 945, 1459, 811, 623, 503, 701, 551, 288, 140, 0), # 165
(1837, 1527, 1525, 1610, 1443, 647, 630, 561, 756, 297, 232, 153, 0, 1903, 1543, 1231, 946, 1467, 816, 626, 505, 703, 552, 289, 141, 0), # 166
(1844, 1531, 1527, 1614, 1449, 648, 632, 563, 761, 298, 234, 153, 0, 1911, 1556, 1234, 948, 1471, 819, 629, 507, 711, 552, 290, 143, 0), # 167
(1851, 1535, 1534, 1615, 1456, 652, 637, 566, 762, 299, 236, 154, 0, 1924, 1561, 1239, 949, 1474, 823, 630, 509, 713, 555, 291, 143, 0), # 168
(1858, 1544, 1537, 1620, 1467, 654, 641, 568, 765, 299, 236, 154, 0, 1930, 1571, 1242, 953, 1481, 828, 631, 511, 715, 557, 294, 143, 0), # 169
(1866, 1551, 1546, 1629, 1476, 655, 647, 570, 773, 301, 240, 154, 0, 1938, 1581, 1246, 955, 1490, 831, 635, 513, 718, 561, 296, 144, 0), # 170
(1873, 1555, 1551, 1638, 1478, 655, 649, 570, 776, 302, 240, 155, 0, 1946, 1588, 1254, 960, 1496, 831, 637, 515, 721, 563, 296, 145, 0), # 171
(1878, 1559, 1557, 1640, 1480, 657, 653, 570, 776, 304, 240, 155, 0, 1954, 1590, 1260, 962, 1501, 833, 641, 515, 725, 564, 297, 146, 0), # 172
(1888, 1563, 1564, 1646, 1484, 661, 655, 572, 777, 305, 240, 155, 0, 1962, 1592, 1266, 966, 1508, 835, 644, 516, 728, 571, 297, 147, 0), # 173
(1894, 1564, 1568, 1653, 1489, 662, 655, 573, 777, 305, 240, 155, 0, 1967, 1596, 1270, 966, 1513, 840, 646, 518, 729, 573, 298, 147, 0), # 174
(1898, 1565, 1573, 1661, 1494, 668, 658, 574, 783, 305, 242, 156, 0, 1976, 1604, 1272, 967, 1520, 842, 647, 521, 732, 574, 299, 148, 0), # 175
(1909, 1569, 1580, 1666, 1499, 670, 658, 575, 786, 307, 243, 156, 0, 1983, 1611, 1275, 968, 1523, 843, 648, 523, 734, 577, 300, 148, 0), # 176
(1911, 1574, 1585, 1667, 1503, 672, 658, 576, 788, 308, 244, 157, 0, 1989, 1615, 1275, 974, 1530, 843, 649, 526, 736, 577, 301, 148, 0), # 177
(1915, 1576, 1586, 1672, 1504, 674, 658, 576, 791, 309, 246, 157, 0, 1992, 1620, 1278, 975, 1533, 844, 649, 529, 737, 579, 302, 148, 0), # 178
(1915, 1576, 1586, 1672, 1504, 674, 658, 576, 791, 309, 246, 157, 0, 1992, 1620, 1278, 975, 1533, 844, 649, 529, 737, 579, 302, 148, 0), # 179
)
passenger_arriving_rate = (
(6.025038694046121, 6.077817415662483, 5.211283229612507, 5.593200996477089, 4.443748486087689, 2.197058452426137, 2.4876213692243487, 2.3265880864897115, 2.4360396248672025, 1.187404504656711, 0.8410530327771206, 0.4897915078306174, 0.0, 6.100656255094035, 5.38770658613679, 4.205265163885603, 3.562213513970132, 4.872079249734405, 3.257223321085596, 2.4876213692243487, 1.5693274660186693, 2.2218742430438443, 1.8644003321590301, 1.0422566459225016, 0.5525288559693167, 0.0), # 0
(6.425192582423969, 6.479066763559234, 5.555346591330152, 5.9626298279489545, 4.737992269979389, 2.342188508829789, 2.651681364758216, 2.479756861452854, 2.5968981305331633, 1.265694207683145, 0.8966192271912263, 0.5221216660814355, 0.0, 6.503749976927826, 5.743338326895789, 4.483096135956131, 3.7970826230494343, 5.193796261066327, 3.4716596060339957, 2.651681364758216, 1.6729917920212778, 2.3689961349896946, 1.9875432759829852, 1.1110693182660305, 0.589006069414476, 0.0), # 1
(6.8240676107756775, 6.878723687980077, 5.8980422855474135, 6.330588934198314, 5.031170378999795, 2.4867395801587113, 2.8150911047764224, 2.6323126239522097, 2.7571147227510195, 1.3436741325061639, 0.9519646297552626, 0.5543232652053055, 0.0, 6.905237793851628, 6.09755591725836, 4.759823148776313, 4.031022397518491, 5.514229445502039, 3.6852376735330936, 2.8150911047764224, 1.7762425572562224, 2.5155851894998973, 2.1101963113994384, 1.179608457109483, 0.625338517089098, 0.0), # 2
(7.220109351775874, 7.275202552130091, 6.238010869319854, 6.695618766778866, 5.322129340801521, 2.6301384358095787, 2.9772021849887733, 2.7836505787472534, 2.9160540643684367, 1.4210348095278544, 1.0068696823654766, 0.5862685684930461, 0.0, 7.30352736750507, 6.448954253423507, 5.0343484118273825, 4.263104428583563, 5.8321081287368735, 3.8971108102461547, 2.9772021849887733, 1.8786703112925562, 2.6610646704007603, 2.2318729222596225, 1.247602173863971, 0.6613820501936447, 0.0), # 3
(7.611763378099177, 7.666917719214351, 6.573892899703036, 7.056259777244312, 5.609715683037193, 2.7718118451790676, 3.137366201105075, 2.9331659305974576, 3.0730808182330827, 1.4974667691503039, 1.0611148269181152, 0.6178298392354764, 0.0, 7.69702635952778, 6.79612823159024, 5.305574134590575, 4.492400307450911, 6.146161636466165, 4.10643230283644, 3.137366201105075, 1.9798656036993338, 2.8048578415185963, 2.3520865924147714, 1.3147785799406073, 0.6969925199285775, 0.0), # 4
(7.9974752624202115, 8.052283552437947, 6.904328933752518, 7.411052417148355, 5.892775933359424, 2.9111865776638504, 3.2949347488351344, 3.080253884262296, 3.2275596471926233, 1.5726605417755992, 1.1144805053094267, 0.6488793407234149, 0.0, 8.084142431559393, 7.137672747957563, 5.572402526547132, 4.7179816253267965, 6.455119294385247, 4.312355437967215, 3.2949347488351344, 2.079418984045607, 2.946387966679712, 2.4703508057161185, 1.3808657867505036, 0.7320257774943589, 0.0), # 5
(8.375690577413598, 8.42971441500595, 7.227959528523866, 7.758537138044686, 6.170156619420834, 3.047689402660605, 3.4492594238887575, 3.2243096445012442, 3.3788552140947257, 1.6463066578058279, 1.1667471594356567, 0.6792893362476808, 0.0, 8.463283245239527, 7.472182698724488, 5.833735797178282, 4.938919973417482, 6.757710428189451, 4.514033502301742, 3.4492594238887575, 2.176921001900432, 3.085078309710417, 2.586179046014896, 1.4455919057047733, 0.7663376740914501, 0.0), # 6
(8.744854895753962, 8.797624670123444, 7.543425241072636, 8.097254391487015, 6.440704268874043, 3.1807470895660046, 3.599691821975751, 3.3647284160737763, 3.5263321817870574, 1.7180956476430762, 1.2176952311930538, 0.708932089099093, 0.0, 8.832856462207822, 7.798252980090021, 6.088476155965268, 5.154286942929227, 7.052664363574115, 4.7106197825032865, 3.599691821975751, 2.2719622068328604, 3.2203521344370216, 2.699084797162339, 1.508685048214527, 0.7997840609203132, 0.0), # 7
(9.103413790115921, 9.154428680995508, 7.849366628454395, 8.425744629029035, 6.703265409371668, 3.309786407776723, 3.7455835388059184, 3.5009054037393623, 3.669355213117282, 1.7877180416894325, 1.2671051624778642, 0.7376798625684703, 0.0, 9.1912697441039, 8.114478488253173, 6.335525812389321, 5.363154125068296, 7.338710426234564, 4.901267565235107, 3.7455835388059184, 2.3641331484119448, 3.351632704685834, 2.8085815430096788, 1.5698733256908792, 0.8322207891814098, 0.0), # 8
(9.449812833174102, 9.498540810827224, 8.144424247724704, 8.742548302224453, 6.956686568566327, 3.4342341266894385, 3.886286170089072, 3.6322358122574814, 3.8072889709330693, 1.8548643703469827, 1.3147573951863356, 0.7654049199466314, 0.0, 9.536930752567395, 8.419454119412945, 6.573786975931678, 5.564593111040947, 7.614577941866139, 5.0851301371604745, 3.886286170089072, 2.453024376206742, 3.4783432842831634, 2.914182767408151, 1.6288848495449408, 0.8635037100752023, 0.0), # 9
(9.782497597603118, 9.828375422823667, 8.427238655939124, 9.046205862626959, 7.19981427411064, 3.5535170157008253, 4.021151311535013, 3.7581148463876053, 3.9394981180820854, 1.9192251640178146, 1.3604323712147148, 0.7919795245243952, 0.0, 9.868247149237932, 8.711774769768347, 6.802161856073574, 5.757675492053442, 7.878996236164171, 5.261360784942648, 4.021151311535013, 2.5382264397863037, 3.59990713705532, 3.015401954208987, 1.685447731187825, 0.8934886748021517, 0.0), # 10
(10.099913656077605, 10.142346880189926, 8.696450410153215, 9.335257761790256, 7.431495053657226, 3.667061844207558, 4.14953055885355, 3.8779377108892072, 4.065347317411997, 1.980490953104016, 1.40391053245925, 0.8172759395925812, 0.0, 10.183626595755133, 8.99003533551839, 7.019552662296249, 5.9414728593120465, 8.130694634823994, 5.42911279524489, 4.14953055885355, 2.619329888719684, 3.715747526828613, 3.1117525872634197, 1.7392900820306432, 0.9220315345627208, 0.0), # 11
(10.400506581272174, 10.438869546131066, 8.95070006742254, 9.60824445126805, 7.650575434858702, 3.7742953816063087, 4.270775507754487, 3.99109961052176, 4.184201231770471, 2.0383522680076718, 1.444972320816187, 0.8411664284420068, 0.0, 10.48147675375864, 9.252830712862075, 7.224861604080934, 6.115056804023014, 8.368402463540942, 5.587539454730464, 4.270775507754487, 2.6959252725759346, 3.825287717429351, 3.2027481504226842, 1.790140013484508, 0.9489881405573698, 0.0), # 12
(10.68272194586145, 10.716357783852182, 9.188628184802662, 9.863706382614039, 7.85590194536768, 3.8746443972937565, 4.384237753947633, 4.096995750044741, 4.295424524005172, 2.0924996391308714, 1.4833981781817738, 0.8635232543634921, 0.0, 10.760205284888082, 9.498755797998411, 7.416990890908868, 6.277498917392613, 8.590849048010345, 5.735794050062637, 4.384237753947633, 2.7676031409241117, 3.92795097268384, 3.287902127538014, 1.8377256369605324, 0.974214343986562, 0.0), # 13
(10.945005322520059, 10.973225956558347, 9.408875319349146, 10.100184007381912, 8.046321112836791, 3.967535660666574, 4.489268893142796, 4.195021334217623, 4.398381856963768, 2.1426235968757004, 1.518968546452257, 0.8842186806478561, 0.0, 11.018219850783076, 9.726405487126415, 7.594842732261284, 6.4278707906271, 8.796763713927536, 5.873029867904672, 4.489268893142796, 2.833954043333267, 4.023160556418396, 3.3667280024606385, 1.8817750638698296, 0.997565996050759, 0.0), # 14
(11.185802283922625, 11.207888427454638, 9.610082028117542, 10.316217777125386, 8.220679464918646, 4.052395941121439, 4.585220521049775, 4.284571567799878, 4.4924378934939275, 2.1884146716442476, 1.551463867523884, 0.9031249705859171, 0.0, 11.253928113083257, 9.934374676445087, 7.757319337619419, 6.565244014932741, 8.984875786987855, 5.998400194919829, 4.585220521049775, 2.894568529372456, 4.110339732459323, 3.4387392590417964, 1.9220164056235085, 1.0188989479504218, 0.0), # 15
(11.40355840274376, 11.418759559746144, 9.790888868163425, 10.510348143398145, 8.377823529265866, 4.128652008055021, 4.671444233378385, 4.36504165555098, 4.5769572964433145, 2.2295633938385993, 1.5806645832929027, 0.920114387468494, 0.0, 11.465737733428254, 10.121258262153432, 7.9033229164645125, 6.688690181515796, 9.153914592886629, 6.111058317771373, 4.671444233378385, 2.9490371486107296, 4.188911764632933, 3.503449381132716, 1.958177773632685, 1.0380690508860133, 0.0), # 16
(11.59671925165809, 11.604253716637938, 9.949936396542352, 10.6811155577539, 8.51659983353107, 4.1957306308639994, 4.747291625838426, 4.435826802230409, 4.651304728659593, 2.2657602938608403, 1.60635113565556, 0.9350591945864056, 0.0, 11.652056373457699, 10.28565114045046, 8.031755678277799, 6.79728088158252, 9.302609457319186, 6.2101575231225725, 4.747291625838426, 2.9969504506171427, 4.258299916765535, 3.5603718525846344, 1.9899872793084707, 1.0549321560579947, 0.0), # 17
(11.763730403340244, 11.7627852613351, 10.08586517030988, 10.82706047174635, 8.63585490536687, 4.253058578945052, 4.81211429413971, 4.49632221259763, 4.7148448529904385, 2.2966959021130613, 1.6283039665081016, 0.9478316552304716, 0.0, 11.811291694811214, 10.426148207535187, 8.141519832540508, 6.890087706339182, 9.429689705980877, 6.294851097636682, 4.81211429413971, 3.0378989849607514, 4.317927452683435, 3.6090201572487843, 2.0171730340619765, 1.0693441146668274, 0.0), # 18
(11.903037430464838, 11.892768557042718, 10.197315746521578, 10.946723336929182, 8.734435272425891, 4.300062621694845, 4.865263833992036, 4.5459230914121225, 4.766942332283511, 2.3220607489973486, 1.6463035177467755, 0.9583040326915097, 0.0, 11.941851359128435, 10.541344359606605, 8.231517588733878, 6.9661822469920445, 9.533884664567022, 6.364292327976972, 4.865263833992036, 3.071473301210604, 4.367217636212946, 3.648907778976395, 2.039463149304316, 1.0811607779129746, 0.0), # 19
(12.013085905706498, 11.992617966965858, 10.282928682233003, 11.038644604856119, 8.811187462360754, 4.336169528510063, 4.9060918411052175, 4.5840246434333585, 4.806961829386479, 2.341545364915788, 1.66013023126783, 0.9663485902603393, 0.0, 12.042143028048988, 10.62983449286373, 8.30065115633915, 7.024636094747362, 9.613923658772958, 6.417634500806702, 4.9060918411052175, 3.097263948935759, 4.405593731180377, 3.679548201618707, 2.0565857364466007, 1.0902379969968963, 0.0), # 20
(12.09232140173984, 12.060747854309614, 10.341344534499719, 11.101364727080837, 8.86495800282407, 4.360806068787375, 4.933949911189055, 4.6100220734208115, 4.834268007147008, 2.3548402802704667, 1.669564548967512, 0.9718375912277795, 0.0, 12.110574363212494, 10.690213503505571, 8.34782274483756, 7.064520840811399, 9.668536014294016, 6.454030902789136, 4.933949911189055, 3.1148614777052677, 4.432479001412035, 3.7004549090269463, 2.068268906899944, 1.096431623119056, 0.0), # 21
(12.139189491239494, 12.095572582279058, 10.371203860377285, 11.133424155157051, 8.894593421468459, 4.373399011923457, 4.94818963995336, 4.623310586133957, 4.848225528412765, 2.361636025463473, 1.674386912742068, 0.9746432988846491, 0.0, 12.145553026258591, 10.721076287731139, 8.37193456371034, 7.084908076390418, 9.69645105682553, 6.47263482058754, 4.94818963995336, 3.1238564370881834, 4.447296710734229, 3.7111413850523514, 2.0742407720754574, 1.0995975074799145, 0.0), # 22
(12.156472036011166, 12.099695953360769, 10.374923182441702, 11.137437731481482, 8.902185644826076, 4.375, 4.949882401355603, 4.624746913580247, 4.8499704938271595, 2.3624376817558304, 1.6749916074323483, 0.9749897576588934, 0.0, 12.15, 10.724887334247827, 8.37495803716174, 7.087313045267489, 9.699940987654319, 6.474645679012346, 4.949882401355603, 3.125, 4.451092822413038, 3.7124792438271617, 2.0749846364883404, 1.0999723593964337, 0.0), # 23
(12.169214895640982, 12.09729074074074, 10.374314814814815, 11.13694375, 8.906486090891882, 4.375, 4.9489522875817, 4.62275, 4.849736666666666, 2.3619451851851854, 1.6749249158249162, 0.9749086419753087, 0.0, 12.15, 10.723995061728393, 8.37462457912458, 7.085835555555555, 9.699473333333332, 6.47185, 4.9489522875817, 3.125, 4.453243045445941, 3.7123145833333346, 2.074862962962963, 1.099753703703704, 0.0), # 24
(12.181688676253897, 12.092549725651576, 10.373113854595337, 11.135966435185185, 8.910691956475603, 4.375, 4.947119341563786, 4.618827160493828, 4.8492746913580245, 2.3609756515775038, 1.6747926798852726, 0.9747485139460449, 0.0, 12.15, 10.722233653406493, 8.373963399426362, 7.08292695473251, 9.698549382716049, 6.466358024691359, 4.947119341563786, 3.125, 4.455345978237801, 3.711988811728396, 2.0746227709190674, 1.0993227023319616, 0.0), # 25
(12.19389242285764, 12.085545336076818, 10.371336762688616, 11.134516898148147, 8.914803094736882, 4.375, 4.944412030985233, 4.613052469135803, 4.84859049382716, 2.3595452126200276, 1.674596096770171, 0.9745115683584822, 0.0, 12.15, 10.719627251943303, 8.372980483850855, 7.078635637860081, 9.69718098765432, 6.458273456790124, 4.944412030985233, 3.125, 4.457401547368441, 3.71150563271605, 2.0742673525377233, 1.0986859396433473, 0.0), # 26
(12.205825180459962, 12.076349999999996, 10.369, 11.132606249999998, 8.918819358835371, 4.375, 4.940858823529412, 4.6055, 4.84769, 2.35767, 1.674336363636364, 0.9742000000000002, 0.0, 12.15, 10.7162, 8.371681818181818, 7.073009999999999, 9.69538, 6.4477, 4.940858823529412, 3.125, 4.459409679417686, 3.7108687500000004, 2.0738000000000003, 1.09785, 0.0), # 27
(12.217485994068602, 12.065036145404662, 10.366120027434842, 11.13024560185185, 8.92274060193072, 4.375, 4.93648818687969, 4.596243827160494, 4.846579135802468, 2.3553661454046644, 1.6740146776406037, 0.9738160036579792, 0.0, 12.15, 10.711976040237769, 8.370073388203018, 7.066098436213991, 9.693158271604936, 6.434741358024692, 4.93648818687969, 3.125, 4.46137030096536, 3.710081867283951, 2.073224005486969, 1.0968214677640604, 0.0), # 28
(12.2288739086913, 12.051676200274349, 10.362713305898492, 11.127446064814816, 8.926566677182576, 4.375, 4.931328588719439, 4.585358024691358, 4.845263827160494, 2.3526497805212623, 1.6736322359396434, 0.9733617741197987, 0.0, 12.15, 10.706979515317785, 8.368161179698216, 7.057949341563786, 9.690527654320988, 6.419501234567901, 4.931328588719439, 3.125, 4.463283338591288, 3.709148688271606, 2.0725426611796984, 1.0956069272976683, 0.0), # 29
(12.239987969335797, 12.036342592592591, 10.358796296296296, 11.12421875, 8.930297437750589, 4.375, 4.925408496732026, 4.572916666666666, 4.84375, 2.3495370370370376, 1.6731902356902357, 0.9728395061728394, 0.0, 12.15, 10.701234567901233, 8.365951178451178, 7.048611111111112, 9.6875, 6.402083333333333, 4.925408496732026, 3.125, 4.4651487188752945, 3.7080729166666675, 2.0717592592592595, 1.094212962962963, 0.0), # 30
(12.25082722100983, 12.019107750342934, 10.354385459533608, 11.120574768518516, 8.933932736794405, 4.375, 4.918756378600824, 4.558993827160494, 4.842043580246913, 2.346044046639232, 1.6726898740491336, 0.9722513946044812, 0.0, 12.15, 10.694765340649292, 8.363449370245666, 7.038132139917694, 9.684087160493826, 6.382591358024691, 4.918756378600824, 3.125, 4.466966368397203, 3.70685825617284, 2.070877091906722, 1.0926461591220853, 0.0), # 31
(12.261390708721144, 12.000044101508914, 10.349497256515773, 11.11652523148148, 8.937472427473676, 4.375, 4.911400702009199, 4.543663580246914, 4.84015049382716, 2.3421869410150897, 1.672132348173089, 0.9715996342021036, 0.0, 12.15, 10.687595976223138, 8.360661740865444, 7.026560823045267, 9.68030098765432, 6.36112901234568, 4.911400702009199, 3.125, 4.468736213736838, 3.705508410493828, 2.069899451303155, 1.0909131001371744, 0.0), # 32
(12.271677477477477, 11.979224074074073, 10.344148148148149, 11.11208125, 8.94091636294805, 4.375, 4.903369934640523, 4.527, 4.838076666666666, 2.3379818518518523, 1.6715188552188551, 0.9708864197530863, 0.0, 12.15, 10.679750617283949, 8.357594276094275, 7.013945555555555, 9.676153333333332, 6.3378000000000005, 4.903369934640523, 3.125, 4.470458181474025, 3.704027083333334, 2.06882962962963, 1.0890203703703705, 0.0), # 33
(12.28168657228657, 11.956720096021947, 10.338354595336076, 11.107253935185184, 8.944264396377172, 4.375, 4.894692544178166, 4.509077160493827, 4.835828024691358, 2.333444910836763, 1.670850592343185, 0.9701139460448103, 0.0, 12.15, 10.671253406492912, 8.354252961715924, 7.000334732510288, 9.671656049382715, 6.312708024691357, 4.894692544178166, 3.125, 4.472132198188586, 3.7024179783950624, 2.0676709190672153, 1.0869745541838134, 0.0), # 34
(12.291417038156167, 11.932604595336077, 10.332133058984912, 11.102054398148146, 8.947516380920696, 4.375, 4.885396998305495, 4.489969135802469, 4.83341049382716, 2.328592249657065, 1.6701287567028307, 0.969284407864655, 0.0, 12.15, 10.662128486511202, 8.350643783514153, 6.985776748971193, 9.66682098765432, 6.285956790123457, 4.885396998305495, 3.125, 4.473758190460348, 3.7006847993827163, 2.0664266117969827, 1.0847822359396435, 0.0), # 35
(12.300867920094007, 11.906949999999998, 10.3255, 11.096493749999999, 8.950672169738269, 4.375, 4.875511764705882, 4.46975, 4.830829999999999, 2.32344, 1.6693545454545458, 0.9684000000000001, 0.0, 12.15, 10.6524, 8.346772727272727, 6.970319999999999, 9.661659999999998, 6.257650000000001, 4.875511764705882, 3.125, 4.475336084869134, 3.6988312500000005, 2.0651, 1.08245, 0.0), # 36
(12.310038263107828, 11.879828737997256, 10.318471879286694, 11.090583101851852, 8.953731615989536, 4.375, 4.865065311062696, 4.448493827160494, 4.828092469135802, 2.3180042935528125, 1.668529155755082, 0.9674629172382261, 0.0, 12.15, 10.642092089620485, 8.34264577877541, 6.954012880658436, 9.656184938271604, 6.227891358024691, 4.865065311062696, 3.125, 4.476865807994768, 3.696861033950618, 2.063694375857339, 1.0799844307270234, 0.0), # 37
(12.31892711220537, 11.851313237311386, 10.311065157750342, 11.084333564814814, 8.956694572834152, 4.375, 4.854086105059308, 4.426274691358025, 4.825203827160493, 2.312301262002744, 1.6676537847611925, 0.9664753543667125, 0.0, 12.15, 10.631228898033836, 8.33826892380596, 6.936903786008231, 9.650407654320986, 6.196784567901235, 4.854086105059308, 3.125, 4.478347286417076, 3.6947778549382724, 2.0622130315500686, 1.0773921124828534, 0.0), # 38
(12.327533512394384, 11.821475925925924, 10.303296296296297, 11.07775625, 8.959560893431762, 4.375, 4.842602614379085, 4.4031666666666665, 4.82217, 2.3063470370370376, 1.6667296296296297, 0.9654395061728396, 0.0, 12.15, 10.619834567901233, 8.333648148148148, 6.919041111111111, 9.64434, 6.164433333333333, 4.842602614379085, 3.125, 4.479780446715881, 3.6925854166666676, 2.0606592592592596, 1.0746796296296297, 0.0), # 39
(12.335856508682596, 11.790389231824417, 10.295181755829903, 11.070862268518518, 8.962330430942014, 4.375, 4.830643306705398, 4.3792438271604945, 4.818996913580246, 2.3001577503429362, 1.6657578875171468, 0.9643575674439875, 0.0, 12.15, 10.60793324188386, 8.328789437585733, 6.900473251028807, 9.637993827160493, 6.1309413580246925, 4.830643306705398, 3.125, 4.481165215471007, 3.690287422839507, 2.059036351165981, 1.0718535665294926, 0.0), # 40
(12.343895146077754, 11.758125582990397, 10.286737997256516, 11.06366273148148, 8.96500303852456, 4.375, 4.818236649721617, 4.354580246913581, 4.81569049382716, 2.293749533607682, 1.6647397555804966, 0.9632317329675355, 0.0, 12.15, 10.595549062642888, 8.323698777902482, 6.881248600823045, 9.63138098765432, 6.096412345679013, 4.818236649721617, 3.125, 4.48250151926228, 3.6878875771604944, 2.0573475994513033, 1.0689205075445818, 0.0), # 41
(12.3516484695876, 11.724757407407406, 10.277981481481483, 11.056168750000001, 8.967578569339047, 4.375, 4.805411111111111, 4.32925, 4.812256666666666, 2.287138518518519, 1.663676430976431, 0.9620641975308644, 0.0, 12.15, 10.582706172839506, 8.318382154882155, 6.861415555555555, 9.624513333333333, 6.06095, 4.805411111111111, 3.125, 4.483789284669523, 3.6853895833333343, 2.055596296296297, 1.0658870370370372, 0.0), # 42
(12.35911552421987, 11.690357133058985, 10.268928669410151, 11.048391435185184, 8.970056876545122, 4.375, 4.7921951585572495, 4.3033271604938275, 4.80870135802469, 2.280340836762689, 1.6625691108617036, 0.9608571559213536, 0.0, 12.15, 10.569428715134888, 8.312845554308517, 6.841022510288067, 9.61740271604938, 6.024658024691359, 4.7921951585572495, 3.125, 4.485028438272561, 3.682797145061729, 2.0537857338820307, 1.062759739368999, 0.0), # 43
(12.366295354982311, 11.65499718792867, 10.259596021947875, 11.040341898148148, 8.972437813302435, 4.375, 4.778617259743403, 4.2768858024691365, 4.805030493827159, 2.2733726200274353, 1.6614189923930665, 0.9596128029263833, 0.0, 12.15, 10.555740832190216, 8.307094961965332, 6.820117860082305, 9.610060987654318, 5.987640123456791, 4.778617259743403, 3.125, 4.486218906651217, 3.6801139660493836, 2.0519192043895753, 1.0595451989026066, 0.0), # 44
(12.37318700688266, 11.618749999999999, 10.25, 11.03203125, 8.974721232770635, 4.375, 4.764705882352941, 4.25, 4.80125, 2.2662500000000003, 1.6602272727272729, 0.9583333333333333, 0.0, 12.15, 10.541666666666664, 8.301136363636363, 6.79875, 9.6025, 5.95, 4.764705882352941, 3.125, 4.487360616385318, 3.677343750000001, 2.0500000000000003, 1.0562500000000001, 0.0), # 45
(12.379789524928656, 11.581687997256516, 10.240157064471878, 11.023470601851852, 8.976906988109372, 4.375, 4.750489494069233, 4.222743827160494, 4.797365802469135, 2.258989108367627, 1.6589951490210748, 0.9570209419295841, 0.0, 12.15, 10.527230361225422, 8.294975745105374, 6.77696732510288, 9.59473160493827, 5.9118413580246925, 4.750489494069233, 3.125, 4.488453494054686, 3.6744902006172846, 2.048031412894376, 1.0528807270233198, 0.0), # 46
(12.386101954128042, 11.543883607681755, 10.230083676268862, 11.014671064814813, 8.978994932478294, 4.375, 4.7359965625756475, 4.195191358024691, 4.793383827160493, 2.2516060768175588, 1.657723818431226, 0.955677823502515, 0.0, 12.15, 10.512456058527663, 8.288619092156129, 6.754818230452675, 9.586767654320987, 5.873267901234568, 4.7359965625756475, 3.125, 4.489497466239147, 3.6715570216049387, 2.046016735253773, 1.049443964334705, 0.0), # 47
(12.392123339488554, 11.505409259259258, 10.219796296296296, 11.00564375, 8.980984919037049, 4.375, 4.7212555555555555, 4.167416666666667, 4.78931, 2.244117037037037, 1.656414478114478, 0.9543061728395063, 0.0, 12.15, 10.497367901234567, 8.28207239057239, 6.73235111111111, 9.57862, 5.834383333333334, 4.7212555555555555, 3.125, 4.490492459518524, 3.6685479166666677, 2.0439592592592595, 1.0459462962962964, 0.0), # 48
(12.397852726017943, 11.466337379972563, 10.209311385459534, 10.996399768518518, 8.982876800945284, 4.375, 4.706294940692326, 4.139493827160494, 4.78515024691358, 2.2365381207133064, 1.6550683252275846, 0.9529081847279379, 0.0, 12.15, 10.481990032007316, 8.275341626137923, 6.709614362139918, 9.57030049382716, 5.795291358024691, 4.706294940692326, 3.125, 4.491438400472642, 3.665466589506174, 2.0418622770919073, 1.0423943072702333, 0.0), # 49
(12.403289158723938, 11.426740397805213, 10.198645404663925, 10.986950231481481, 8.984670431362652, 4.375, 4.69114318566933, 4.111496913580247, 4.78091049382716, 2.228885459533608, 1.6536865569272978, 0.9514860539551899, 0.0, 12.15, 10.466346593507089, 8.268432784636488, 6.686656378600823, 9.56182098765432, 5.756095679012346, 4.69114318566933, 3.125, 4.492335215681326, 3.6623167438271613, 2.0397290809327853, 1.038794581618656, 0.0), # 50
(12.408431682614292, 11.38669074074074, 10.187814814814814, 10.977306249999998, 8.986365663448797, 4.375, 4.675828758169934, 4.0835, 4.776596666666666, 2.2211751851851855, 1.6522703703703707, 0.9500419753086421, 0.0, 12.15, 10.450461728395062, 8.261351851851853, 6.663525555555555, 9.553193333333333, 5.7169, 4.675828758169934, 3.125, 4.493182831724399, 3.659102083333334, 2.037562962962963, 1.0351537037037037, 0.0), # 51
(12.413279342696734, 11.34626083676269, 10.176836076817558, 10.967478935185184, 8.98796235036337, 4.375, 4.660380125877511, 4.055577160493827, 4.772214691358024, 2.2134234293552817, 1.6508209627135553, 0.9485781435756746, 0.0, 12.15, 10.434359579332419, 8.254104813567777, 6.640270288065844, 9.544429382716048, 5.677808024691357, 4.660380125877511, 3.125, 4.493981175181685, 3.655826311728396, 2.035367215363512, 1.0314782578875175, 0.0), # 52
(12.417831183979011, 11.305523113854596, 10.165725651577505, 10.957479398148147, 8.989460345266023, 4.375, 4.64482575647543, 4.0278024691358025, 4.767770493827161, 2.205646323731139, 1.6493395311136052, 0.9470967535436672, 0.0, 12.15, 10.418064288980338, 8.246697655568026, 6.616938971193416, 9.535540987654322, 5.638923456790124, 4.64482575647543, 3.125, 4.4947301726330116, 3.65249313271605, 2.0331451303155013, 1.0277748285322361, 0.0), # 53
(12.42208625146886, 11.26455, 10.154499999999999, 10.94731875, 8.9908595013164, 4.375, 4.629194117647058, 4.000249999999999, 4.7632699999999994, 2.1978600000000004, 1.6478272727272725, 0.9456, 0.0, 12.15, 10.401599999999998, 8.239136363636362, 6.593579999999999, 9.526539999999999, 5.60035, 4.629194117647058, 3.125, 4.4954297506582, 3.649106250000001, 2.0309, 1.0240500000000001, 0.0), # 54
(12.426043590174027, 11.223413923182441, 10.143175582990398, 10.93700810185185, 8.992159671674152, 4.375, 4.613513677075768, 3.9729938271604937, 4.758719135802469, 2.1900805898491087, 1.6462853847113108, 0.9440900777320531, 0.0, 12.15, 10.384990855052584, 8.231426923556553, 6.570241769547325, 9.517438271604938, 5.562191358024691, 4.613513677075768, 3.125, 4.496079835837076, 3.645669367283951, 2.02863511659808, 1.0203103566529494, 0.0), # 55
(12.429702245102245, 11.182187311385459, 10.131768861454047, 10.926558564814814, 8.993360709498926, 4.375, 4.597812902444929, 3.946108024691358, 4.754123827160494, 2.182324224965707, 1.6447150642224717, 0.9425691815272064, 0.0, 12.15, 10.368260996799268, 8.223575321112358, 6.54697267489712, 9.508247654320988, 5.524551234567902, 4.597812902444929, 3.125, 4.496680354749463, 3.6421861882716056, 2.02635377229081, 1.0165624828532238, 0.0), # 56
(12.433061261261258, 11.140942592592593, 10.120296296296297, 10.915981249999998, 8.994462467950372, 4.375, 4.582120261437908, 3.9196666666666675, 4.74949, 2.1746070370370374, 1.6431175084175085, 0.9410395061728396, 0.0, 12.15, 10.351434567901233, 8.215587542087542, 6.523821111111111, 9.49898, 5.487533333333334, 4.582120261437908, 3.125, 4.497231233975186, 3.638660416666667, 2.0240592592592597, 1.0128129629629632, 0.0), # 57
(12.436119683658815, 11.09975219478738, 10.108774348422497, 10.905287268518517, 8.995464800188138, 4.375, 4.5664642217380775, 3.8937438271604936, 4.744823580246913, 2.1669451577503436, 1.641493914453174, 0.939503246456333, 0.0, 12.15, 10.334535711019662, 8.20746957226587, 6.50083547325103, 9.489647160493826, 5.451241358024691, 4.5664642217380775, 3.125, 4.497732400094069, 3.6350957561728396, 2.0217548696844996, 1.0090683813443075, 0.0), # 58
(12.438876557302644, 11.05868854595336, 10.097219478737998, 10.89448773148148, 8.996367559371876, 4.375, 4.550873251028807, 3.868413580246914, 4.74013049382716, 2.1593547187928674, 1.63984547948622, 0.9379625971650665, 0.0, 12.15, 10.31758856881573, 8.1992273974311, 6.478064156378601, 9.48026098765432, 5.41577901234568, 4.550873251028807, 3.125, 4.498183779685938, 3.6314959104938276, 2.0194438957476, 1.0053353223593966, 0.0), # 59
(12.441330927200491, 11.017824074074072, 10.085648148148147, 10.88359375, 8.997170598661228, 4.375, 4.535375816993463, 3.84375, 4.735416666666667, 2.1518518518518523, 1.6381734006734008, 0.9364197530864199, 0.0, 12.15, 10.300617283950617, 8.190867003367003, 6.455555555555556, 9.470833333333333, 5.3812500000000005, 4.535375816993463, 3.125, 4.498585299330614, 3.6278645833333343, 2.0171296296296295, 1.0016203703703705, 0.0), # 60
(12.443481838360098, 10.977231207133059, 10.0740768175583, 10.872616435185183, 8.997873771215849, 4.375, 4.520000387315419, 3.819827160493827, 4.730688024691357, 2.1444526886145407, 1.6364788751714678, 0.9348769090077733, 0.0, 12.15, 10.283645999085506, 8.182394375857339, 6.4333580658436205, 9.461376049382714, 5.347758024691358, 4.520000387315419, 3.125, 4.498936885607924, 3.624205478395062, 2.0148153635116604, 0.9979301097393691, 0.0), # 61
(12.445328335789204, 10.936982373113853, 10.062521947873801, 10.861566898148148, 8.998476930195388, 4.375, 4.504775429678044, 3.796719135802469, 4.72595049382716, 2.137173360768176, 1.6347631001371743, 0.9333362597165068, 0.0, 12.15, 10.266698856881574, 8.17381550068587, 6.411520082304527, 9.45190098765432, 5.315406790123457, 4.504775429678044, 3.125, 4.499238465097694, 3.620522299382717, 2.0125043895747603, 0.9942711248285323, 0.0), # 62
(12.44686946449555, 10.897149999999998, 10.051, 10.85045625, 8.998979928759484, 4.375, 4.4897294117647055, 3.7745, 4.721209999999999, 2.13003, 1.6330272727272728, 0.9318000000000001, 0.0, 12.15, 10.249799999999999, 8.165136363636364, 6.390089999999999, 9.442419999999998, 5.2843, 4.4897294117647055, 3.125, 4.499489964379742, 3.616818750000001, 2.0102, 0.99065, 0.0), # 63
(12.448104269486876, 10.857806515775033, 10.039527434842249, 10.839295601851852, 8.999382620067799, 4.375, 4.474890801258775, 3.7532438271604947, 4.716472469135802, 2.123038737997257, 1.6312725900985157, 0.9302703246456334, 0.0, 12.15, 10.232973571101967, 8.156362950492579, 6.369116213991769, 9.432944938271604, 5.254541358024692, 4.474890801258775, 3.125, 4.499691310033899, 3.613098533950618, 2.00790548696845, 0.9870733196159123, 0.0), # 64
(12.449031795770926, 10.819024348422495, 10.0281207133059, 10.828096064814813, 8.999684857279973, 4.375, 4.4602880658436215, 3.7330246913580245, 4.711743827160493, 2.1162157064471883, 1.6295002494076571, 0.9287494284407863, 0.0, 12.15, 10.216243712848648, 8.147501247038285, 6.348647119341564, 9.423487654320986, 5.226234567901234, 4.4602880658436215, 3.125, 4.499842428639987, 3.609365354938272, 2.0056241426611803, 0.9835476680384088, 0.0), # 65
(12.449651088355436, 10.780875925925926, 10.016796296296297, 10.81686875, 8.999886493555657, 4.375, 4.445949673202614, 3.7139166666666674, 4.70703, 2.1095770370370373, 1.6277114478114478, 0.9272395061728398, 0.0, 12.15, 10.199634567901235, 8.138557239057238, 6.328731111111111, 9.41406, 5.199483333333334, 4.445949673202614, 3.125, 4.499943246777828, 3.6056229166666673, 2.0033592592592595, 0.9800796296296298, 0.0), # 66
(12.44996119224815, 10.743433676268861, 10.005570644718793, 10.805624768518516, 8.999987382054503, 4.375, 4.431904091019123, 3.695993827160495, 4.702336913580247, 2.103138861454047, 1.625907382466642, 0.9257427526291724, 0.0, 12.15, 10.183170278920894, 8.12953691233321, 6.30941658436214, 9.404673827160494, 5.1743913580246925, 4.431904091019123, 3.125, 4.499993691027251, 3.6018749228395066, 2.0011141289437586, 0.9766757887517148, 0.0), # 67
(12.44974993737699, 10.706573503252354, 9.994405949931412, 10.794277566425121, 8.999902364237876, 4.37491880810852, 4.418109116897788, 3.6791719250114308, 4.6976351394604485, 2.0968861324941503, 1.624057197708075, 0.9242530021899743, 0.0, 12.149850180041152, 10.166783024089716, 8.120285988540376, 6.290658397482449, 9.395270278920897, 5.1508406950160035, 4.418109116897788, 3.1249420057918, 4.499951182118938, 3.598092522141708, 1.9988811899862826, 0.9733248639320324, 0.0), # 68
(12.447770048309177, 10.669170071684588, 9.982988425925925, 10.782255163043477, 8.999128540305009, 4.374276954732511, 4.404160908807968, 3.6625493827160494, 4.692719135802469, 2.090641917211329, 1.621972567783094, 0.9227218973359325, 0.0, 12.148663194444444, 10.149940870695255, 8.10986283891547, 6.271925751633985, 9.385438271604938, 5.127569135802469, 4.404160908807968, 3.1244835390946504, 4.499564270152504, 3.5940850543478264, 1.996597685185185, 0.9699245519713263, 0.0), # 69
(12.443862945070673, 10.63105170582769, 9.971268432784635, 10.769478411835749, 8.997599451303152, 4.373012879134278, 4.389996080736822, 3.645976223136717, 4.687561156835848, 2.0843758573388205, 1.619629777305216, 0.921142276129281, 0.0, 12.14631880144033, 10.13256503742209, 8.09814888652608, 6.25312757201646, 9.375122313671696, 5.104366712391404, 4.389996080736822, 3.123580627953056, 4.498799725651576, 3.5898261372785836, 1.9942536865569274, 0.9664592459843356, 0.0), # 70
(12.438083592771514, 10.592241185450682, 9.959250085733881, 10.755966153381644, 8.995334463003308, 4.371147065996037, 4.375620995723392, 3.629457933241884, 4.682168884316415, 2.078088107802792, 1.6170374741567726, 0.9195152937212715, 0.0, 12.142847865226338, 10.114668230933985, 8.085187370783862, 6.234264323408375, 9.36433776863283, 5.081241106538638, 4.375620995723392, 3.1222479042828835, 4.497667231501654, 3.5853220511272155, 1.9918500171467763, 0.962931016859153, 0.0), # 71
(12.430486956521738, 10.552761290322579, 9.946937499999999, 10.74173722826087, 8.99235294117647, 4.3687000000000005, 4.3610420168067225, 3.6129999999999995, 4.67655, 2.071778823529412, 1.614204306220096, 0.917842105263158, 0.0, 12.13828125, 10.096263157894736, 8.07102153110048, 6.215336470588234, 9.3531, 5.058199999999999, 4.3610420168067225, 3.1205000000000003, 4.496176470588235, 3.5805790760869574, 1.9893874999999999, 0.959341935483871, 0.0), # 72
(12.421128001431383, 10.512634800212398, 9.934334790809327, 10.72681047705314, 8.98867425159364, 4.36569216582838, 4.346265507025855, 3.5966079103795154, 4.670712185642433, 2.0654481594448484, 1.6111389213775176, 0.916123865906192, 0.0, 12.132649819958848, 10.07736252496811, 8.055694606887588, 6.196344478334543, 9.341424371284866, 5.035251074531322, 4.346265507025855, 3.118351547020271, 4.49433712579682, 3.5756034923510476, 1.9868669581618656, 0.9556940727465817, 0.0), # 73
(12.410061692610485, 10.471884494889155, 9.921446073388202, 10.711204740338164, 8.984317760025819, 4.3621440481633895, 4.331297829419833, 3.5802871513488794, 4.664663122999542, 2.0590962704752687, 1.607849967511371, 0.9143617308016269, 0.0, 12.125984439300412, 10.057979038817894, 8.039249837556856, 6.177288811425805, 9.329326245999084, 5.012402011888431, 4.331297829419833, 3.115817177259564, 4.4921588800129095, 3.5704015801127222, 1.9842892146776405, 0.9519894995353778, 0.0), # 74
(12.397342995169081, 10.430533154121862, 9.908275462962962, 10.694938858695652, 8.97930283224401, 4.358076131687243, 4.3161453470277, 3.5640432098765435, 4.6584104938271595, 2.052723311546841, 1.604346092503987, 0.9125568551007147, 0.0, 12.118315972222222, 10.038125406107861, 8.021730462519935, 6.158169934640522, 9.316820987654319, 4.989660493827161, 4.3161453470277, 3.112911522633745, 4.489651416122005, 3.5649796195652184, 1.9816550925925924, 0.9482302867383512, 0.0), # 75
(12.383026874217212, 10.388603557679545, 9.894827074759945, 10.678031672705314, 8.973648834019203, 4.353508901082153, 4.300814422888497, 3.5478815729309554, 4.651961979881115, 2.046329437585734, 1.6006359442376985, 0.9107103939547083, 0.0, 12.10967528292181, 10.01781433350179, 8.003179721188491, 6.138988312757201, 9.30392395976223, 4.967034202103338, 4.300814422888497, 3.1096492150586803, 4.486824417009601, 3.5593438909017725, 1.978965414951989, 0.9444185052435952, 0.0), # 76
(12.367168294864912, 10.34611848533121, 9.881105024005485, 10.660502022946858, 8.967375131122406, 4.34846284103033, 4.285311420041268, 3.531807727480567, 4.645325262917238, 2.0399148035181156, 1.5967281705948373, 0.9088235025148608, 0.0, 12.10009323559671, 9.997058527663466, 7.983640852974187, 6.119744410554345, 9.290650525834476, 4.944530818472794, 4.285311420041268, 3.106044886450236, 4.483687565561203, 3.5535006743156203, 1.9762210048010973, 0.9405562259392011, 0.0), # 77
(12.349822222222222, 10.30310071684588, 9.867113425925925, 10.64236875, 8.960501089324618, 4.3429584362139915, 4.269642701525055, 3.5158271604938274, 4.638508024691357, 2.0334795642701526, 1.5926314194577353, 0.9068973359324239, 0.0, 12.089600694444444, 9.975870695256662, 7.963157097288676, 6.100438692810457, 9.277016049382715, 4.922158024691359, 4.269642701525055, 3.1021131687242796, 4.480250544662309, 3.5474562500000006, 1.9734226851851853, 0.9366455197132618, 0.0), # 78
(12.331043621399177, 10.259573031992566, 9.8528563957476, 10.623650694444443, 8.953046074396838, 4.337016171315348, 4.2538146303789, 3.4999453589391867, 4.631517946959304, 2.0270238747680143, 1.5883543387087244, 0.9049330493586505, 0.0, 12.07822852366255, 9.954263542945155, 7.941771693543622, 6.081071624304041, 9.263035893918609, 4.899923502514861, 4.2538146303789, 3.097868693796677, 4.476523037198419, 3.5412168981481487, 1.97057127914952, 0.9326884574538697, 0.0), # 79
(12.310887457505816, 10.215558210540289, 9.838338048696844, 10.604366696859904, 8.945029452110063, 4.330656531016613, 4.2378335696418485, 3.4841678097850943, 4.624362711476909, 2.0205478899378684, 1.5839055762301377, 0.9029317979447936, 0.0, 12.066007587448558, 9.932249777392729, 7.919527881150689, 6.061643669813604, 9.248725422953818, 4.877834933699132, 4.2378335696418485, 3.093326093583295, 4.4725147260550315, 3.5347888989533023, 1.967667609739369, 0.9286871100491174, 0.0), # 80
(12.289408695652174, 10.171079032258064, 9.8235625, 10.584535597826088, 8.936470588235293, 4.3239, 4.221705882352941, 3.4685000000000006, 4.617049999999999, 2.014051764705883, 1.5792937799043065, 0.9008947368421053, 0.0, 12.052968749999998, 9.909842105263158, 7.8964688995215315, 6.042155294117647, 9.234099999999998, 4.855900000000001, 4.221705882352941, 3.0885, 4.468235294117647, 3.5281785326086967, 1.9647125, 0.9246435483870968, 0.0), # 81
(12.26666230094829, 10.126158276914907, 9.808533864883403, 10.564176237922705, 8.927388848543531, 4.316767062947722, 4.205437931551222, 3.4529474165523544, 4.6095874942844075, 2.007535653998225, 1.5745275976135626, 0.8988230212018388, 0.0, 12.039142875514404, 9.887053233220225, 7.8726379880678135, 6.022606961994674, 9.219174988568815, 4.834126383173296, 4.205437931551222, 3.0834050449626584, 4.4636944242717655, 3.521392079307569, 1.9617067729766806, 0.9205598433559008, 0.0), # 82
(12.242703238504205, 10.080818724279835, 9.793256258573388, 10.543307457729467, 8.917803598805776, 4.30927820454199, 4.189036080275732, 3.4375155464106077, 4.6019828760859625, 2.0009997127410637, 1.569615677240239, 0.8967178061752463, 0.0, 12.0245608281893, 9.863895867927708, 7.848078386201194, 6.00299913822319, 9.203965752171925, 4.812521764974851, 4.189036080275732, 3.078055860387136, 4.458901799402888, 3.5144358192431566, 1.9586512517146777, 0.9164380658436215, 0.0), # 83
(12.21758647342995, 10.035083154121864, 9.777733796296296, 10.521948097826087, 8.907734204793028, 4.301453909465021, 4.1725066915655145, 3.4222098765432096, 4.5942438271604935, 1.994444095860567, 1.5645666666666667, 0.8945802469135803, 0.0, 12.009253472222222, 9.840382716049382, 7.8228333333333335, 5.9833322875817, 9.188487654320987, 4.791093827160494, 4.1725066915655145, 3.0724670781893004, 4.453867102396514, 3.5073160326086965, 1.9555467592592592, 0.9122802867383514, 0.0), # 84
(12.191366970835569, 9.988974346210009, 9.761970593278463, 10.500116998792272, 8.897200032276285, 4.293314662399025, 4.1558561284596145, 3.4070358939186103, 4.58637802926383, 1.9878689582829019, 1.5593892137751788, 0.8924114985680938, 0.0, 11.9932516718107, 9.81652648424903, 7.796946068875894, 5.963606874848704, 9.17275605852766, 4.769850251486054, 4.1558561284596145, 3.0666533302850176, 4.448600016138142, 3.500038999597425, 1.9523941186556926, 0.9080885769281828, 0.0), # 85
(12.164099695831096, 9.942515080313289, 9.745970764746229, 10.477833001207731, 8.886220447026545, 4.284880948026216, 4.139090753997072, 3.391999085505258, 4.578393164151806, 1.9812744549342376, 1.5540919664481068, 0.8902127162900394, 0.0, 11.976586291152262, 9.792339879190433, 7.770459832240534, 5.943823364802712, 9.156786328303612, 4.748798719707362, 4.139090753997072, 3.0606292485901543, 4.443110223513273, 3.4926110004025777, 1.9491941529492458, 0.9038650073012082, 0.0), # 86
(12.135839613526569, 9.895728136200717, 9.729738425925925, 10.455114945652172, 8.874814814814815, 4.276173251028807, 4.122216931216931, 3.3771049382716045, 4.570296913580247, 1.9746607407407408, 1.5486835725677832, 0.8879850552306694, 0.0, 11.959288194444444, 9.76783560753736, 7.743417862838915, 5.923982222222222, 9.140593827160494, 4.727946913580246, 4.122216931216931, 3.054409465020576, 4.437407407407408, 3.4850383152173916, 1.9459476851851853, 0.8996116487455198, 0.0), # 87
(12.106641689032028, 9.84863629364131, 9.713277692043896, 10.431981672705316, 8.863002501412087, 4.2672120560890106, 4.105241023158234, 3.3623589391860995, 4.562096959304984, 1.9680279706285808, 1.5431726800165397, 0.8857296705412365, 0.0, 11.941388245884776, 9.743026375953601, 7.715863400082698, 5.904083911885741, 9.124193918609969, 4.707302514860539, 4.105241023158234, 3.0480086114921505, 4.431501250706043, 3.477327224235106, 1.9426555384087794, 0.8953305721492102, 0.0), # 88
(12.076560887457505, 9.801262332404088, 9.696592678326475, 10.40845202294686, 8.850802872589364, 4.258017847889041, 4.088169392860024, 3.3477665752171926, 4.553800983081847, 1.9613762995239252, 1.537567936676709, 0.8834477173729935, 0.0, 11.922917309670781, 9.717924891102928, 7.687839683383544, 5.884128898571774, 9.107601966163694, 4.68687320530407, 4.088169392860024, 3.041441319920744, 4.425401436294682, 3.469484007648954, 1.9393185356652953, 0.8910238484003719, 0.0), # 89
(12.045652173913043, 9.753629032258065, 9.6796875, 10.384544836956522, 8.838235294117647, 4.248611111111111, 4.071008403361344, 3.333333333333333, 4.545416666666667, 1.9547058823529415, 1.5318779904306221, 0.881140350877193, 0.0, 11.90390625, 9.692543859649122, 7.65938995215311, 5.864117647058823, 9.090833333333334, 4.666666666666666, 4.071008403361344, 3.0347222222222223, 4.419117647058823, 3.461514945652175, 1.9359375, 0.8866935483870969, 0.0), # 90
(12.013970513508676, 9.705759172972254, 9.662566272290809, 10.360278955314012, 8.825319131767932, 4.239012330437433, 4.053764417701236, 3.319064700502972, 4.536951691815272, 1.948016874041798, 1.526111489160612, 0.8788087262050875, 0.0, 11.884385931069957, 9.66689598825596, 7.630557445803059, 5.844050622125392, 9.073903383630544, 4.646690580704161, 4.053764417701236, 3.027865950312452, 4.412659565883966, 3.4534263184380047, 1.9325132544581618, 0.8823417429974777, 0.0), # 91
(11.981570871354446, 9.657675534315677, 9.64523311042524, 10.335673218599032, 8.812073751311223, 4.2292419905502205, 4.036443798918745, 3.304966163694559, 4.528413740283494, 1.941309429516663, 1.5202770807490107, 0.8764539985079298, 0.0, 11.864387217078187, 9.640993983587226, 7.601385403745053, 5.823928288549988, 9.056827480566987, 4.626952629172383, 4.036443798918745, 3.0208871361073006, 4.406036875655611, 3.4452244061996784, 1.9290466220850482, 0.8779705031196072, 0.0), # 92
(11.948508212560386, 9.609400896057348, 9.62769212962963, 10.310746467391306, 8.798518518518518, 4.219320576131687, 4.01905291005291, 3.2910432098765434, 4.51981049382716, 1.9345837037037037, 1.5143834130781502, 0.8740773229369722, 0.0, 11.84394097222222, 9.614850552306692, 7.57191706539075, 5.80375111111111, 9.03962098765432, 4.607460493827161, 4.01905291005291, 3.0138004115226336, 4.399259259259259, 3.436915489130436, 1.925538425925926, 0.8735818996415772, 0.0), # 93
(11.914837502236535, 9.56095803796628, 9.609947445130317, 10.285517542270531, 8.784672799160816, 4.209268571864045, 4.0015981141427766, 3.277301326017376, 4.511149634202103, 1.9278398515290893, 1.5084391340303622, 0.8716798546434675, 0.0, 11.823078060699588, 9.588478401078142, 7.54219567015181, 5.783519554587267, 9.022299268404206, 4.588221856424326, 4.0015981141427766, 3.0066204084743178, 4.392336399580408, 3.4285058474235113, 1.9219894890260634, 0.8691780034514802, 0.0), # 94
(11.880613705492932, 9.512369739811495, 9.592003172153635, 10.260005283816424, 8.770555959009117, 4.199106462429508, 3.984085774227386, 3.2637459990855056, 4.5024388431641515, 1.9210780279189867, 1.5024528914879791, 0.869262748778668, 0.0, 11.801829346707818, 9.561890236565347, 7.512264457439896, 5.763234083756959, 9.004877686328303, 4.569244398719708, 3.984085774227386, 2.9993617588782198, 4.385277979504559, 3.4200017612721423, 1.9184006344307272, 0.8647608854374088, 0.0), # 95
(11.845891787439614, 9.463658781362009, 9.573863425925927, 10.234228532608697, 8.756187363834421, 4.188854732510288, 3.966522253345782, 3.250382716049383, 4.493685802469135, 1.9142983877995645, 1.4964333333333335, 0.8668271604938274, 0.0, 11.780225694444445, 9.5350987654321, 7.482166666666667, 5.742895163398693, 8.98737160493827, 4.5505358024691365, 3.966522253345782, 2.9920390946502056, 4.3780936819172105, 3.411409510869566, 1.9147726851851854, 0.8603326164874555, 0.0), # 96
(11.810726713186616, 9.414847942386832, 9.555532321673525, 10.208206129227051, 8.74158637940773, 4.178533866788599, 3.948913914537008, 3.237216963877458, 4.484898193872885, 1.9075010860969905, 1.4903891074487565, 0.864374244940197, 0.0, 11.758297968106996, 9.508116694342165, 7.451945537243782, 5.7225032582909705, 8.96979638774577, 4.532103749428441, 3.948913914537008, 2.984667047706142, 4.370793189703865, 3.402735376409018, 1.911106464334705, 0.8558952674897121, 0.0), # 97
(11.775173447843981, 9.365960002654985, 9.53701397462277, 10.181956914251208, 8.72677237150004, 4.168164349946655, 3.931267120840105, 3.22425422953818, 4.476083699131229, 1.9006862777374327, 1.484328861716581, 0.8619051572690299, 0.0, 11.736077031893004, 9.480956729959328, 7.421644308582906, 5.702058833212297, 8.952167398262459, 4.513955921353452, 3.931267120840105, 2.9772602499618963, 4.36338618575002, 3.3939856380837368, 1.9074027949245542, 0.8514509093322715, 0.0), # 98
(11.739286956521738, 9.317017741935484, 9.5183125, 10.15549972826087, 8.711764705882352, 4.157766666666667, 3.913588235294118, 3.2115, 4.46725, 1.893854117647059, 1.4782612440191387, 0.859421052631579, 0.0, 11.71359375, 9.453631578947368, 7.391306220095694, 5.681562352941175, 8.9345, 4.4961, 3.913588235294118, 2.9698333333333333, 4.355882352941176, 3.385166576086957, 1.9036625000000003, 0.8470016129032258, 0.0), # 99
(11.703122204329933, 9.268043939997343, 9.49943201303155, 10.128853411835749, 8.696582748325667, 4.147361301630848, 3.895883620938087, 3.1989597622313672, 4.458404778235025, 1.8870047607520377, 1.4721949022387621, 0.8569230861790968, 0.0, 11.690878986625515, 9.426153947970063, 7.36097451119381, 5.661014282256112, 8.91680955647005, 4.4785436671239145, 3.895883620938087, 2.9624009297363205, 4.348291374162834, 3.376284470611917, 1.89988640260631, 0.8425494490906678, 0.0), # 100
(11.6667341563786, 9.219061376609584, 9.480376628943759, 10.102036805555556, 8.681245864600983, 4.136968739521414, 3.878159640811057, 3.1866390032007312, 4.449555715592135, 1.8801383619785366, 1.4661384842577825, 0.8544124130628354, 0.0, 11.667963605967076, 9.398536543691188, 7.330692421288911, 5.640415085935608, 8.89911143118427, 4.461294604481024, 3.878159640811057, 2.9549776710867244, 4.340622932300492, 3.367345601851853, 1.8960753257887522, 0.8380964887826896, 0.0), # 101
(11.630177777777778, 9.170092831541218, 9.461150462962962, 10.07506875, 8.665773420479303, 4.126609465020577, 3.8604226579520695, 3.174543209876543, 4.44071049382716, 1.8732550762527238, 1.4601006379585326, 0.8518901884340482, 0.0, 11.644878472222222, 9.37079207277453, 7.300503189792663, 5.61976522875817, 8.88142098765432, 4.44436049382716, 3.8604226579520695, 2.947578189300412, 4.332886710239651, 3.358356250000001, 1.8922300925925928, 0.8336448028673837, 0.0), # 102
(11.593508033637502, 9.121161084561264, 9.4417576303155, 10.047968085748792, 8.650184781731623, 4.116303962810547, 3.842679035400168, 3.162677869227252, 4.43187679469593, 1.8663550585007669, 1.4540900112233446, 0.8493575674439874, 0.0, 11.621654449588474, 9.342933241883859, 7.270450056116723, 5.599065175502299, 8.86375358939186, 4.427749016918153, 3.842679035400168, 2.940217116293248, 4.325092390865811, 3.3493226952495982, 1.8883515260631, 0.8291964622328422, 0.0), # 103
(11.556779889067812, 9.072288915438735, 9.422202246227709, 10.020753653381641, 8.634499314128943, 4.10607271757354, 3.8249351361943953, 3.151048468221308, 4.423062299954275, 1.8594384636488344, 1.44811525193455, 0.8468157052439055, 0.0, 11.598322402263374, 9.314972757682959, 7.24057625967275, 5.578315390946502, 8.84612459990855, 4.411467855509831, 3.8249351361943953, 2.9329090839811003, 4.317249657064472, 3.3402512177938815, 1.884440449245542, 0.8247535377671579, 0.0), # 104
(11.520048309178742, 9.023499103942651, 9.402488425925926, 9.99344429347826, 8.618736383442265, 4.09593621399177, 3.8071973233737944, 3.1396604938271606, 4.414274691358024, 1.8525054466230941, 1.4421850079744816, 0.8442657569850553, 0.0, 11.574913194444443, 9.286923326835607, 7.210925039872408, 5.557516339869281, 8.828549382716048, 4.395524691358025, 3.8071973233737944, 2.9256687242798356, 4.309368191721132, 3.331148097826088, 1.8804976851851853, 0.8203181003584229, 0.0), # 105
(11.483368259080336, 8.974814429842029, 9.382620284636488, 9.966058846618358, 8.602915355442589, 4.0859149367474465, 3.7894719599774067, 3.12851943301326, 4.405521650663008, 1.8455561623497139, 1.436307927225471, 0.8417088778186895, 0.0, 11.551457690329217, 9.258797656005584, 7.181539636127354, 5.53666848704914, 8.811043301326016, 4.379927206218564, 3.7894719599774067, 2.918510669105319, 4.301457677721294, 3.3220196155394537, 1.8765240569272976, 0.81589222089473, 0.0), # 106
(11.446794703882626, 8.926257672905882, 9.362601937585735, 9.938616153381641, 8.58705559590091, 4.076029370522787, 3.7717654090442765, 3.117630772748057, 4.396810859625057, 1.838590765754862, 1.4304926575698504, 0.8391462228960604, 0.0, 11.527986754115226, 9.230608451856664, 7.152463287849251, 5.515772297264585, 8.793621719250114, 4.36468308184728, 3.7717654090442765, 2.911449550373419, 4.293527797950455, 3.312872051127215, 1.8725203875171472, 0.8114779702641711, 0.0), # 107
(11.410382608695652, 8.877851612903227, 9.3424375, 9.911135054347826, 8.571176470588235, 4.0663, 3.7540840336134447, 3.107, 4.3881499999999996, 1.8316094117647064, 1.4247478468899522, 0.8365789473684213, 0.0, 11.504531250000001, 9.202368421052633, 7.12373923444976, 5.494828235294118, 8.776299999999999, 4.3498, 3.7540840336134447, 2.9045, 4.285588235294117, 3.3037116847826096, 1.8684875000000005, 0.8070774193548388, 0.0), # 108
(11.374186938629451, 8.82961902960308, 9.322131087105625, 9.883634390096615, 8.555297345275559, 4.056747309861302, 3.7364341967239567, 3.0966326017375403, 4.379546753543667, 1.8246122553054145, 1.4190821430681082, 0.8340082063870239, 0.0, 11.48112204218107, 9.174090270257262, 7.09541071534054, 5.473836765916242, 8.759093507087334, 4.335285642432557, 3.7364341967239567, 2.8976766499009297, 4.277648672637779, 3.294544796698873, 1.864426217421125, 0.8026926390548256, 0.0), # 109
(11.338262658794058, 8.78158270277446, 9.301686814128946, 9.85613300120773, 8.539437585733882, 4.047391784788904, 3.7188222614148536, 3.0865340649291264, 4.371008802011888, 1.8175994513031553, 1.4135041939866502, 0.8314351551031215, 0.0, 11.457789994855966, 9.145786706134334, 7.067520969933251, 5.452798353909465, 8.742017604023776, 4.321147690900777, 3.7188222614148536, 2.8909941319920742, 4.269718792866941, 3.2853776670692443, 1.8603373628257893, 0.7983257002522237, 0.0), # 110
(11.302664734299517, 8.733765412186381, 9.281108796296298, 9.82864972826087, 8.523616557734204, 4.038253909465022, 3.7012545907251786, 3.0767098765432097, 4.3625438271604935, 1.8105711546840961, 1.4080226475279107, 0.8288609486679663, 0.0, 11.434565972222222, 9.117470435347629, 7.040113237639553, 5.431713464052287, 8.725087654320987, 4.307393827160493, 3.7012545907251786, 2.8844670781893007, 4.261808278867102, 3.2762165760869575, 1.8562217592592598, 0.7939786738351257, 0.0), # 111
(11.26744813025586, 8.686189937607857, 9.26040114883402, 9.801203411835749, 8.507853627047526, 4.029354168571865, 3.6837375476939744, 3.0671655235482396, 4.354159510745312, 1.803527520374405, 1.402646151574222, 0.8262867422328111, 0.0, 11.411480838477365, 9.08915416456092, 7.013230757871109, 5.4105825611232135, 8.708319021490624, 4.294031732967535, 3.6837375476939744, 2.8781101204084747, 4.253926813523763, 3.2670678039452503, 1.8520802297668042, 0.7896536306916234, 0.0), # 112
(11.232605068443652, 8.638958480664547, 9.239617828252069, 9.773850494242836, 8.492140544138962, 4.02070883845016, 3.6663155781940615, 3.057926284390303, 4.3458851245034475, 1.7964914209838192, 1.3973847812305735, 0.8237192936504428, 0.0, 11.388532681011865, 9.06091223015487, 6.9869239061528665, 5.389474262951456, 8.691770249006895, 4.281096798146424, 3.6663155781940615, 2.8719348846072568, 4.246070272069481, 3.257950164747613, 1.8479235656504138, 0.7853598618785952, 0.0), # 113
(11.197777077480078, 8.592536901878088, 9.219045675021619, 9.746810479149604, 8.47631468365306, 4.012298225970931, 3.649210925046347, 3.04910562975256, 4.337847614285224, 1.7895945503738353, 1.3922488674226394, 0.8211912172112975, 0.0, 11.365530496992042, 9.033103389324271, 6.961244337113197, 5.368783651121505, 8.675695228570447, 4.268747881653584, 3.649210925046347, 2.8659273042649507, 4.23815734182653, 3.248936826383202, 1.8438091350043238, 0.7811397183525536, 0.0), # 114
(11.162861883604794, 8.546941918551349, 9.198696932707318, 9.7200760546636, 8.46032614231088, 4.004100458749136, 3.6324357901149367, 3.0407013271393546, 4.330049991467515, 1.7828475983964234, 1.3872309022854188, 0.8187037582558852, 0.0, 11.342407957992451, 9.005741340814735, 6.936154511427093, 5.348542795189269, 8.66009998293503, 4.256981857995097, 3.6324357901149367, 2.8600717562493823, 4.23016307115544, 3.2400253515545345, 1.8397393865414637, 0.7769947198683046, 0.0), # 115
(11.127815847885161, 8.502107109420871, 9.178532189983873, 9.693599535239764, 8.444150821107023, 3.9960962141009686, 3.6159628905167356, 3.0326901564494966, 4.322472535691132, 1.7762380075348645, 1.3823211862542963, 0.8162523197487347, 0.0, 11.319128711707068, 8.97877551723608, 6.911605931271482, 5.328714022604592, 8.644945071382264, 4.245766219029295, 3.6159628905167356, 2.854354438643549, 4.222075410553511, 3.231199845079922, 1.835706437996775, 0.7729188281291702, 0.0), # 116
(11.092595331388527, 8.457966053223192, 9.158512035525986, 9.66733323533302, 8.427764621036088, 3.988266169342624, 3.5997649433686516, 3.0250488975817924, 4.315095526596881, 1.769753220272439, 1.3775100197646568, 0.8138323046543751, 0.0, 11.295656405829869, 8.952155351198124, 6.887550098823283, 5.309259660817316, 8.630191053193762, 4.23506845661451, 3.5997649433686516, 2.8487615495304452, 4.213882310518044, 3.222444411777674, 1.8317024071051975, 0.768906004838472, 0.0), # 117
(11.057156695182252, 8.414452328694855, 9.138597058008367, 9.6412294693983, 8.411143443092673, 3.980591001790297, 3.583814665787589, 3.0177543304350483, 4.307899243825574, 1.7633806790924282, 1.3727877032518847, 0.811439115937335, 0.0, 11.271954688054828, 8.925830275310684, 6.863938516259424, 5.290142037277283, 8.615798487651148, 4.224856062609067, 3.583814665787589, 2.843279286993069, 4.205571721546336, 3.213743156466101, 1.8277194116016737, 0.7649502116995325, 0.0), # 118
(11.02145630033369, 8.3714995145724, 9.118747846105723, 9.615240551890535, 8.394263188271376, 3.973051388760183, 3.5680847748904534, 3.0107832349080725, 4.300863967018017, 1.757107826478112, 1.3681445371513656, 0.8090681565621435, 0.0, 11.247987206075917, 8.899749722183577, 6.840722685756828, 5.271323479434335, 8.601727934036035, 4.215096528871301, 3.5680847748904534, 2.8378938491144163, 4.197131594135688, 3.2050801839635126, 1.8237495692211447, 0.761045410415673, 0.0), # 119
(10.985450507910194, 8.329041189592374, 9.098924988492762, 9.589318797264655, 8.377099757566796, 3.965628007568476, 3.5525479877941515, 3.0041123908996714, 4.293969975815023, 1.7509221049127721, 1.3635708218984832, 0.8067148294933297, 0.0, 11.223717607587115, 8.873863124426626, 6.817854109492416, 5.252766314738315, 8.587939951630046, 4.20575734725954, 3.5525479877941515, 2.8325914339774827, 4.188549878783398, 3.1964395990882193, 1.8197849976985525, 0.7571855626902159, 0.0), # 120
(10.949095678979122, 8.287010932491311, 9.079089073844187, 9.56341651997559, 8.359629051973535, 3.9583015355313718, 3.5371770216155882, 2.9977185783086533, 4.2871975498573995, 1.7448109568796892, 1.3590568579286233, 0.8043745376954222, 0.0, 11.199109540282393, 8.848119914649644, 6.795284289643115, 5.234432870639067, 8.574395099714799, 4.196806009632114, 3.5371770216155882, 2.8273582396652652, 4.179814525986767, 3.1878055066585307, 1.8158178147688375, 0.753364630226483, 0.0), # 121
(10.912348174607825, 8.245342322005756, 9.059200690834711, 9.537486034478269, 8.341826972486187, 3.951052649965064, 3.5219445934716704, 2.9915785770338243, 4.2805269687859555, 1.7387618248621435, 1.3545929456771704, 0.8020426841329501, 0.0, 11.174126651855724, 8.82246952546245, 6.772964728385852, 5.216285474586429, 8.561053937571911, 4.1882100078473545, 3.5219445934716704, 2.8221804642607595, 4.170913486243093, 3.1791620114927572, 1.8118401381669422, 0.7495765747277962, 0.0), # 122
(10.875164355863662, 8.20396893687225, 9.039220428139036, 9.511479655227625, 8.323669420099352, 3.9438620281857477, 3.506823420479303, 2.9856691669739917, 4.273938512241501, 1.7327621513434166, 1.3501693855795087, 0.7997146717704421, 0.0, 11.148732590001085, 8.796861389474863, 6.750846927897544, 5.1982864540302485, 8.547877024483002, 4.1799368337635885, 3.506823420479303, 2.8170443058469625, 4.161834710049676, 3.170493218409209, 1.8078440856278073, 0.7458153578974774, 0.0), # 123
(10.837500583813984, 8.162824355827334, 9.01910887443187, 9.485349696678588, 8.30513229580763, 3.9367103475096172, 3.4917862197553915, 2.979967128027963, 4.267412459864846, 1.7267993788067886, 1.345776478071024, 0.7973859035724276, 0.0, 11.122891002412453, 8.771244939296702, 6.728882390355119, 5.180398136420364, 8.534824919729692, 4.171953979239149, 3.4917862197553915, 2.8119359625068694, 4.152566147903815, 3.1617832322261967, 1.803821774886374, 0.7420749414388487, 0.0), # 124
(10.79931321952615, 8.121842157607551, 8.998826618387923, 9.459048473286083, 8.286191500605618, 3.9295782852528696, 3.4768057084168436, 2.9744492400945455, 4.260929091296797, 1.7208609497355405, 1.3414045235871004, 0.7950517825034348, 0.0, 11.096565536783794, 8.745569607537782, 6.707022617935502, 5.16258284920662, 8.521858182593594, 4.164228936132364, 3.4768057084168436, 2.806841632323478, 4.143095750302809, 3.153016157762029, 1.799765323677585, 0.7383492870552321, 0.0), # 125
(10.760558624067514, 8.080955920949442, 8.978334248681898, 9.432528299505048, 8.266822935487914, 3.9224465187316975, 3.461854603580562, 2.969092283072546, 4.254468686178167, 1.7149343066129532, 1.3370438225631227, 0.7927077115279934, 0.0, 11.069719840809094, 8.719784826807926, 6.685219112815614, 5.144802919838858, 8.508937372356334, 4.156729196301565, 3.461854603580562, 2.801747513379784, 4.133411467743957, 3.144176099835017, 1.79566684973638, 0.7346323564499494, 0.0), # 126
(10.721193158505432, 8.040099224589545, 8.957592353988504, 9.405741489790408, 8.247002501449117, 3.915295725262296, 3.4469056223634564, 2.9638730368607726, 4.248011524149763, 1.7090068919223076, 1.3326846754344757, 0.7903490936106315, 0.0, 11.042317562182317, 8.693840029716947, 6.6634233771723785, 5.127020675766921, 8.496023048299525, 4.149422251605082, 3.4469056223634564, 2.7966398037587825, 4.1235012507245585, 3.1352471632634704, 1.7915184707977012, 0.7309181113263225, 0.0), # 127
(10.681173183907255, 7.999205647264407, 8.93656152298245, 9.3786403585971, 8.226706099483831, 3.908106582160861, 3.431931481882429, 2.958768281358031, 4.241537884852393, 1.703066148146884, 1.328317382636545, 0.7879713317158789, 0.0, 11.014322348597444, 8.667684648874667, 6.641586913182724, 5.109198444440651, 8.483075769704786, 4.1422755939012434, 3.431931481882429, 2.791504701543472, 4.1133530497419155, 3.1262134528657004, 1.7873123045964903, 0.7272005133876734, 0.0), # 128
(10.640455061340337, 7.958208767710564, 8.91520234433844, 9.351177220380043, 8.205909630586648, 3.9008597667435865, 3.4169048992543876, 2.95375479646313, 4.235028047926869, 1.697099517769964, 1.3239322446047141, 0.7855698288082636, 0.0, 10.985697847748446, 8.641268116890899, 6.619661223023571, 5.0912985533098905, 8.470056095853739, 4.135256715048382, 3.4169048992543876, 2.7863284048168473, 4.102954815293324, 3.117059073460015, 1.783040468867688, 0.7234735243373241, 0.0), # 129
(10.598995151872039, 7.917042164664562, 8.893475406731179, 9.323304389594178, 8.18458899575217, 3.893535956326666, 3.4017985915962377, 2.948809362074875, 4.228462293014, 1.6910944432748274, 1.3195195617743691, 0.7831399878523152, 0.0, 10.956407707329298, 8.614539866375466, 6.5975978088718445, 5.073283329824481, 8.456924586028, 4.128333106904826, 3.4017985915962377, 2.781097111661904, 4.092294497876085, 3.1077681298647266, 1.7786950813462359, 0.7197311058785967, 0.0), # 130
(10.556749816569713, 7.8756394168629384, 8.87134129883538, 9.294974180694428, 8.162720095974995, 3.886115828226296, 3.3865852760248853, 2.943908758092075, 4.221820899754594, 1.685038367144756, 1.3150696345808937, 0.7806772118125626, 0.0, 10.926415575033973, 8.587449329938186, 6.575348172904468, 5.055115101434266, 8.443641799509187, 4.121472261328905, 3.3865852760248853, 2.77579702016164, 4.081360047987498, 3.0983247268981433, 1.7742682597670765, 0.7159672197148127, 0.0), # 131
(10.51367541650071, 7.833934103042237, 8.848760609325746, 9.266138908135728, 8.140278832249722, 3.878580059758672, 3.3712376696572353, 2.9390297644135366, 4.215084147789462, 1.6789187318630299, 1.310572763459673, 0.7781769036535342, 0.0, 10.89568509855645, 8.559945940188875, 6.552863817298364, 5.0367561955890885, 8.430168295578923, 4.114641670178951, 3.3712376696572353, 2.770414328399051, 4.070139416124861, 3.088712969378577, 1.7697521218651495, 0.7121758275492944, 0.0), # 132
(10.469728312732395, 7.791859801938998, 8.825693926876983, 9.236750886373006, 8.117241105570947, 3.870909328239987, 3.3557284896101933, 2.934149160938066, 4.2082323167594105, 1.67272297991293, 1.306019248846092, 0.7756344663397593, 0.0, 10.864179925590703, 8.531979129737351, 6.53009624423046, 5.018168939738788, 8.416464633518821, 4.107808825313293, 3.3557284896101933, 2.764935234457133, 4.058620552785474, 3.078916962124336, 1.765138785375397, 0.7083508910853636, 0.0), # 133
(10.424864866332113, 7.749350092289764, 8.802101840163804, 9.206762429861191, 8.093582816933273, 3.863084310986436, 3.3400304530006673, 2.929243727564472, 4.201245686305251, 1.6664385537777375, 1.3013993911755357, 0.7730453028357667, 0.0, 10.831863703830699, 8.503498331193432, 6.506996955877678, 4.9993156613332115, 8.402491372610502, 4.100941218590261, 3.3400304530006673, 2.7593459364188826, 4.046791408466636, 3.0689208099537315, 1.7604203680327608, 0.7044863720263422, 0.0), # 134
(10.379041438367224, 7.706338552831077, 8.777944937860909, 9.17612585305522, 8.069279867331296, 3.8550856853142146, 3.3241162769455603, 2.92429024419156, 4.194104536067791, 1.6600528959407332, 1.2967034908833885, 0.7704048161060852, 0.0, 10.798700080970423, 8.474452977166937, 6.483517454416942, 4.980158687822199, 8.388209072135583, 4.094006341868184, 3.3241162769455603, 2.753632632367296, 4.034639933665648, 3.0587086176850744, 1.755588987572182, 0.7005762320755525, 0.0), # 135
(10.332214389905081, 7.6627587622994735, 8.753183808643008, 9.144793470410015, 8.044308157759612, 3.8468941285395175, 3.3079586785617807, 2.9192654907181383, 4.186789145687842, 1.653553448885197, 1.2919218484050357, 0.7677084091152441, 0.0, 10.764652704703844, 8.444792500267685, 6.459609242025177, 4.96066034665559, 8.373578291375685, 4.086971687005394, 3.3079586785617807, 2.7477815203853697, 4.022154078879806, 3.0482644901366727, 1.750636761728602, 0.6966144329363159, 0.0), # 136
(10.28434008201304, 7.618544299431501, 8.72777904118481, 9.112717596380511, 8.018643589212827, 3.838490317978539, 3.291530374966233, 2.9141462470430146, 4.179279794806213, 1.6469276550944107, 1.2870447641758613, 0.764951484827772, 0.0, 10.729685222724932, 8.41446633310549, 6.435223820879306, 4.940782965283231, 8.358559589612426, 4.079804745860221, 3.291530374966233, 2.741778798556099, 4.0093217946064135, 3.037572532126838, 1.7455558082369622, 0.6925949363119547, 0.0), # 137
(10.235374875758456, 7.573628742963698, 8.701691224161017, 9.079850545421637, 7.992262062685534, 3.8298549309474748, 3.2748040832758227, 2.908909293064995, 4.1715567630637125, 1.6401629570516543, 1.2820625386312503, 0.7621294462081979, 0.0, 10.693761282727667, 8.383423908290176, 6.410312693156252, 4.920488871154961, 8.343113526127425, 4.0724730102909925, 3.2748040832758227, 2.735610664962482, 3.996131031342767, 3.02661684847388, 1.7403382448322038, 0.6885117039057909, 0.0), # 138
(10.185275132208682, 7.527945671632606, 8.67488094624634, 9.046144631988323, 7.965139479172331, 3.8209686447625186, 3.2577525206074553, 2.903531408682887, 4.163600330101148, 1.6332467972402094, 1.276965472206588, 0.7592376962210506, 0.0, 10.656844532406023, 8.351614658431556, 6.38482736103294, 4.899740391720627, 8.327200660202296, 4.064943972156042, 3.2577525206074553, 2.729263317687513, 3.9825697395861654, 3.0153815439961082, 1.7349761892492683, 0.6843586974211461, 0.0), # 139
(10.133997212431076, 7.481428664174767, 8.647308796115487, 9.011552170535499, 7.937251739667823, 3.811812136739866, 3.240348404078038, 2.897989373795498, 4.155390775559333, 1.626166618143356, 1.2717438653372588, 0.7562716378308593, 0.0, 10.618898619453978, 8.31898801613945, 6.358719326686294, 4.878499854430067, 8.310781551118666, 4.0571851233136975, 3.240348404078038, 2.7227229548141896, 3.9686258698339114, 3.003850723511834, 1.7294617592230976, 0.6801298785613425, 0.0), # 140
(10.081497477492995, 7.4340112993267216, 8.61893536244316, 8.976025475518098, 7.908574745166602, 3.802366084195711, 3.222564450804477, 2.892259968301635, 4.146908379079072, 1.6189098622443758, 1.2663880184586478, 0.7532266740021526, 0.0, 10.579887191565495, 8.285493414023676, 6.331940092293238, 4.856729586733126, 8.293816758158144, 4.049163955622289, 3.222564450804477, 2.7159757744255075, 3.954287372583301, 2.9920084918393663, 1.7237870724886322, 0.675819209029702, 0.0), # 141
(10.027732288461786, 7.385627155825012, 8.58972123390407, 8.939516861391049, 7.879084396663268, 3.792611164446249, 3.2043733779036754, 2.8863199721001056, 4.138133420301177, 1.6114639720265487, 1.2608882320061394, 0.7500982076994595, 0.0, 10.539773896434559, 8.251080284694053, 6.304441160030697, 4.834391916079644, 8.276266840602354, 4.040847960940148, 3.2043733779036754, 2.7090079746044635, 3.939542198331634, 2.9798389537970165, 1.7179442467808141, 0.6714206505295467, 0.0), # 142
(9.972658006404808, 7.336209812406179, 8.559626999172925, 8.901978642609278, 7.848756595152423, 3.7825280548076745, 3.185747902492541, 2.880146165089716, 4.129046178866458, 1.6038163899731561, 1.2552348064151186, 0.746881641887309, 0.0, 10.49852238175514, 8.215698060760397, 6.276174032075593, 4.811449169919467, 8.258092357732917, 4.032204631125603, 3.185747902492541, 2.701805753434053, 3.9243782975762116, 2.967326214203093, 1.7119253998345851, 0.6669281647641981, 0.0), # 143
(9.916230992389421, 7.285692847806764, 8.528613246924428, 8.86336313362772, 7.817567241628662, 3.772097432596183, 3.1666607416879793, 2.8737153271692746, 4.119626934415724, 1.5959545585674784, 1.2494180421209704, 0.7435723795302299, 0.0, 10.456096295221217, 8.179296174832528, 6.247090210604851, 4.787863675702434, 8.239253868831447, 4.023201458036985, 3.1666607416879793, 2.6943553089972734, 3.908783620814331, 2.954454377875907, 1.7057226493848856, 0.6623357134369786, 0.0), # 144
(9.858407607482972, 7.234009840763308, 8.496640565833289, 8.823622648901305, 7.785492237086586, 3.7612999751279688, 3.147084612606896, 2.867004238237588, 4.109855966589781, 1.5878659202927967, 1.2434282395590792, 0.7401658235927514, 0.0, 10.41245928452676, 8.141824059520264, 6.217141197795395, 4.763597760878389, 8.219711933179562, 4.013805933532623, 3.147084612606896, 2.6866428393771202, 3.892746118543293, 2.9412075496337686, 1.699328113166658, 0.6576372582512099, 0.0), # 145
(9.79914421275282, 7.181094370012356, 8.463669544574216, 8.782709502884963, 7.752507482520793, 3.750116359719226, 3.126992232366198, 2.8599896781934633, 4.099713555029442, 1.5795379176323916, 1.2372556991648298, 0.7366573770394019, 0.0, 10.367574997365741, 8.103231147433421, 6.186278495824149, 4.738613752897173, 8.199427110058885, 4.0039855494708485, 3.126992232366198, 2.67865454265659, 3.8762537412603963, 2.927569834294988, 1.6927339089148434, 0.6528267609102142, 0.0), # 146
(9.73839716926632, 7.126880014290443, 8.42966077182191, 8.740576010033621, 7.71858887892588, 3.7385272636861506, 3.1063563180827884, 2.8526484269357075, 4.0891799793755155, 1.570957993069544, 1.2308907213736073, 0.7330424428347111, 0.0, 10.321407081432142, 8.06346687118182, 6.154453606868036, 4.712873979208631, 8.178359958751031, 3.9937077977099906, 3.1063563180827884, 2.670376616918679, 3.85929443946294, 2.9135253366778744, 1.6859321543643822, 0.6478981831173131, 0.0), # 147
(9.676122838090825, 7.071300352334116, 8.394574836251083, 8.697174484802217, 7.6837123272964485, 3.726513364344937, 3.085149586873576, 2.8449572643631287, 4.078235519268811, 1.5621135890875346, 1.2243236066207965, 0.729316423943207, 0.0, 10.27391918441993, 8.022480663375276, 6.1216180331039824, 4.686340767262602, 8.156471038537623, 3.9829401701083804, 3.085149586873576, 2.6617952602463837, 3.8418561636482242, 2.899058161600739, 1.6789149672502168, 0.6428454865758287, 0.0), # 148
(9.612277580293695, 7.014288962879912, 8.358372326536443, 8.652457241645672, 7.647853728627096, 3.71405533901178, 3.0633447558554643, 2.8368929703745334, 4.0668604543501345, 1.5529921481696445, 1.2175446553417821, 0.7254747233294191, 0.0, 10.225074954023084, 7.980221956623609, 6.08772327670891, 4.658976444508932, 8.133720908700269, 3.971650158524347, 3.0633447558554643, 2.6528966707226997, 3.823926864313548, 2.8841524138818913, 1.671674465307289, 0.637662632989083, 0.0), # 149
(9.546817756942277, 6.955779424664377, 8.321013831352694, 8.606376595018924, 7.610988983912421, 3.7011338650028747, 3.04091454214536, 2.828432324868728, 4.0550350642603, 1.5435811127991534, 1.2105441679719486, 0.7215127439578762, 0.0, 10.174838037935576, 7.936640183536638, 6.0527208398597425, 4.630743338397459, 8.1100701285206, 3.95980525481622, 3.04091454214536, 2.6436670464306244, 3.8054944919562104, 2.8687921983396416, 1.6642027662705388, 0.632343584060398, 0.0), # 150
(9.47969972910393, 6.895705316424048, 8.282459939374542, 8.558884859376896, 7.573093994147021, 3.6877296196344136, 3.01783166286017, 2.8195521077445216, 4.042739628640115, 1.5338679254593437, 1.203312444946681, 0.7174258887931072, 0.0, 10.123172083851381, 7.891684776724178, 6.016562224733405, 4.601603776378029, 8.08547925728023, 3.9473729508423303, 3.01783166286017, 2.6340925854531525, 3.7865469970735104, 2.8529616197922993, 1.6564919878749085, 0.6268823014930954, 0.0), # 151
(9.41087985784601, 6.83400021689547, 8.242671239276701, 8.509934349174525, 7.534144660325495, 3.6738232802225945, 2.9940688351167988, 2.8102290989007206, 4.029954427130388, 1.5238400286334952, 1.1958397867013644, 0.713209560799641, 0.0, 10.070040739464476, 7.84530516879605, 5.979198933506821, 4.5715200859004845, 8.059908854260776, 3.9343207384610093, 2.9940688351167988, 2.6241594858732817, 3.7670723301627476, 2.836644783058176, 1.6485342478553402, 0.6212727469904974, 0.0), # 152
(9.340314504235872, 6.770597704815181, 8.201608319733868, 8.459477378866739, 7.4941168834424445, 3.659395524083611, 2.9695987760321514, 2.800440078236131, 4.016659739371929, 1.513484864804889, 1.1881164936713833, 0.7088591629420063, 0.0, 10.015407652468832, 7.797450792362069, 5.940582468356916, 4.5404545944146655, 8.033319478743858, 3.9206161095305836, 2.9695987760321514, 2.6138539457740078, 3.7470584417212223, 2.81982579295558, 1.6403216639467737, 0.6155088822559257, 0.0), # 153
(9.267960029340873, 6.705431358919725, 8.159231769420758, 8.407466262908468, 7.4529865644924636, 3.644427028533658, 2.944394202723137, 2.7901618256495615, 4.002835845005546, 1.5027898764568062, 1.1801328662921224, 0.7043700981847325, 0.0, 9.959236470558428, 7.748071080032056, 5.900664331460612, 4.508369629370417, 8.005671690011091, 3.9062265559093863, 2.944394202723137, 2.603162163238327, 3.7264932822462318, 2.802488754302823, 1.631846353884152, 0.6095846689927024, 0.0), # 154
(9.193772794228362, 6.638434757945644, 8.115502177012075, 8.35385331575464, 7.4107296044701565, 3.62889847088893, 2.9184278323066564, 2.779371121039818, 3.988463023672051, 1.4917425060725265, 1.1718792049989668, 0.6997377694923482, 0.0, 9.901490841427231, 7.6971154644158295, 5.859396024994833, 4.4752275182175785, 7.976926047344102, 3.8911195694557454, 2.9184278323066564, 2.5920703363492357, 3.7053648022350782, 2.7846177719182137, 1.6231004354024152, 0.6034940689041496, 0.0), # 155
(9.117709159965697, 6.569541480629476, 8.070380131182526, 8.298590851860187, 7.367321904370117, 3.612790528465623, 2.8916723818996197, 2.7680447443057092, 3.9735215550122502, 1.480330196135332, 1.163345810227301, 0.6949575798293822, 0.0, 9.842134412769221, 7.644533378123204, 5.816729051136504, 4.440990588405995, 7.9470431100245005, 3.875262642027993, 2.8916723818996197, 2.5805646631897305, 3.6836609521850585, 2.766196950620063, 1.6140760262365055, 0.5972310436935888, 0.0), # 156
(9.039725487620235, 6.498685105707764, 8.023826220606818, 8.241631185680044, 7.322739365186948, 3.59608387857993, 2.864100568618931, 2.756159475346041, 3.957991718666955, 1.4685403891285025, 1.1545229824125098, 0.6900249321603636, 0.0, 9.781130832278372, 7.590274253763999, 5.772614912062549, 4.405621167385506, 7.91598343733391, 3.8586232654844577, 2.864100568618931, 2.568631341842807, 3.661369682593474, 2.7472103952266815, 1.6047652441213638, 0.5907895550643424, 0.0), # 157
(8.957617135686286, 6.424498432849483, 7.973591953902356, 8.180792623486118, 7.274944884696797, 3.5777171334219773, 2.8350640325567142, 2.742898476174686, 3.9406648366396384, 1.4560097748873433, 1.1451191505077887, 0.6847599564194339, 0.0, 9.715783031298415, 7.532359520613772, 5.7255957525389425, 4.368029324662029, 7.881329673279277, 3.840057866644561, 2.8350640325567142, 2.555512238158555, 3.6374724423483986, 2.7269308744953733, 1.5947183907804712, 0.5840453120772259, 0.0), # 158
(8.858744120374082, 6.3393718515594255, 7.906737818402987, 8.103579442909608, 7.212153047825302, 3.551582753604972, 2.8009276580314295, 2.7236067663821912, 3.9145709044888575, 1.4406842982296237, 1.133483387123799, 0.6781362523683109, 0.0, 9.630513176304232, 7.459498776051419, 5.667416935618994, 4.322052894688871, 7.829141808977715, 3.813049472935068, 2.8009276580314295, 2.5368448240035515, 3.606076523912651, 2.7011931476365363, 1.5813475636805976, 0.5763065319599479, 0.0), # 159
(8.741846513885172, 6.242606401394785, 7.821920957955889, 8.008719759367974, 7.133136105077435, 3.517038907233379, 2.7613462490302703, 2.6977995947636733, 3.8789700908914604, 1.4223616955588683, 1.119451901721908, 0.6700501948887847, 0.0, 9.523704730672296, 7.370552143776631, 5.59725950860954, 4.267085086676604, 7.757940181782921, 3.7769194326691427, 2.7613462490302703, 2.512170648023842, 3.5665680525387176, 2.669573253122658, 1.5643841915911778, 0.5675096728540715, 0.0), # 160
(8.607866465503152, 6.134832954888515, 7.7200469719103095, 7.897115253381055, 7.038714499425689, 3.4745040690992197, 2.716608867604126, 2.66580026655489, 3.8343319067996067, 1.4011974579512814, 1.1031483309199415, 0.6605767468907572, 0.0, 9.396448853782916, 7.266344215798328, 5.515741654599707, 4.203592373853843, 7.668663813599213, 3.7321203731768464, 2.716608867604126, 2.481788620785157, 3.5193572497128445, 2.632371751127019, 1.5440093943820619, 0.557712086808047, 0.0), # 161
(8.457746124511628, 6.016682384573562, 7.602021459615496, 7.769667605468694, 6.929708673842563, 3.424396713994519, 2.6670045758038854, 2.627932086991601, 3.781125863165454, 1.3773470764830695, 1.0846963113357242, 0.6497908712841294, 0.0, 9.2498367050164, 7.147699584125422, 5.42348155667862, 4.132041229449208, 7.562251726330908, 3.6791049217882414, 2.6670045758038854, 2.4459976528532277, 3.4648543369212814, 2.5898892018228983, 1.5204042919230993, 0.5469711258703239, 0.0), # 162
(8.292427640194196, 5.888785562982875, 7.468750020420702, 7.6272784961507405, 6.806939071300549, 3.367135316711301, 2.61282243568044, 2.5845183613095624, 3.719821470941162, 1.3509660422304377, 1.0642194795870819, 0.6377675309788032, 0.0, 9.084959443753055, 7.015442840766835, 5.321097397935408, 4.052898126691312, 7.439642941882324, 3.6183257058333878, 2.61282243568044, 2.405096654793786, 3.4034695356502747, 2.5424261653835805, 1.4937500040841403, 0.5353441420893524, 0.0), # 163
(8.11285316183446, 5.751773362649402, 7.321138253675176, 7.470849605947036, 6.67122613477215, 3.3031383520415907, 2.5543515092846794, 2.5358823947445344, 3.650888241078889, 1.3222098462695906, 1.0418414722918394, 0.6245816888846804, 0.0, 8.902908229373192, 6.870398577731482, 5.209207361459196, 3.966629538808771, 7.301776482157778, 3.550235352642348, 2.5543515092846794, 2.3593845371725646, 3.335613067386075, 2.4902832019823458, 1.4642276507350354, 0.5228884875135821, 0.0), # 164
(7.9199648387160195, 5.606276656106095, 7.160091758728169, 7.301282615377426, 6.5233903072298585, 3.2328242947774104, 2.491880858667493, 2.482347492532273, 3.5747956845307916, 1.2912339796767343, 1.0176859260678224, 0.610308307911662, 0.0, 8.704774221257123, 6.713391387028281, 5.088429630339111, 3.873701939030202, 7.149591369061583, 3.4752864895451823, 2.491880858667493, 2.309160210555293, 3.2616951536149292, 2.433760871792476, 1.432018351745634, 0.5096615141914632, 0.0), # 165
(7.714704820122476, 5.452926315885899, 6.9865161349289275, 7.119479204961751, 6.364252031646171, 3.156611619710786, 2.4256995458797714, 2.4242369599085385, 3.492013312249029, 1.2581939335280738, 0.9918764775328559, 0.5950223509696502, 0.0, 8.491648578785155, 6.545245860666151, 4.959382387664279, 3.7745818005842207, 6.984026624498058, 3.393931743871954, 2.4256995458797714, 2.254722585507704, 3.1821260158230853, 2.373159734987251, 1.3973032269857855, 0.4957205741714455, 0.0), # 166
(7.498015255337426, 5.292353214521765, 6.801316981626705, 6.926341055219858, 6.194631750993583, 3.074918801633741, 2.3560966329724047, 2.361874102109088, 3.403010635185759, 1.2232451988998143, 0.9645367633047655, 0.5787987809685459, 0.0, 8.264622461337595, 6.366786590654004, 4.822683816523827, 3.669735596699442, 6.806021270371518, 3.3066237429527234, 2.3560966329724047, 2.196370572595529, 3.0973158754967915, 2.308780351739953, 1.360263396325341, 0.4811230195019787, 0.0), # 167
(7.2708382936444735, 5.125188224546641, 6.605399898170748, 6.722769846671591, 6.015349908244593, 2.9881643153382993, 2.2833611819962822, 2.2955822243696797, 3.308257164293142, 1.1865432668681617, 0.9357904200013762, 0.5617125608182512, 0.0, 8.024787028294753, 6.178838169000762, 4.678952100006881, 3.559629800604484, 6.616514328586284, 3.2138151141175517, 2.2833611819962822, 2.1344030823844995, 3.0076749541222965, 2.2409232822238643, 1.3210799796341497, 0.46592620223151293, 0.0), # 168
(7.034116084327218, 4.952062218493477, 6.399670483910309, 6.509667259836794, 5.827226946371695, 2.8967666356164865, 2.2077822550022947, 2.2256846319260726, 3.2082224105233346, 1.1482436285093212, 0.9057610842405137, 0.5438386534286673, 0.0, 7.773233439036942, 5.982225187715339, 4.528805421202568, 3.444730885527963, 6.416444821046669, 3.1159584846965016, 2.2077822550022947, 2.0691190254403473, 2.9136134731858476, 2.1698890866122653, 1.2799340967820618, 0.450187474408498, 0.0), # 169
(6.78879077666926, 4.773606068895221, 6.185034338194635, 6.2879349752353075, 5.631083308347386, 2.8011442372603246, 2.1296489140413315, 2.1525046300140236, 3.103375884828495, 1.1085017748994974, 0.8745723926400033, 0.525252021709696, 0.0, 7.5110528529444665, 5.777772238806654, 4.372861963200016, 3.325505324698492, 6.20675176965699, 3.013506482019633, 2.1296489140413315, 2.0008173123288033, 2.815541654173693, 2.0959783250784363, 1.2370068676389272, 0.4339641880813838, 0.0), # 170
(6.5358045199542, 4.59045064828482, 5.962397060372978, 6.058474673386982, 5.427739437144163, 2.701715595061839, 2.049250221164283, 2.0763655238692915, 2.994187098160782, 1.0674731971148967, 0.8423479818176697, 0.5060276285712387, 0.0, 7.239336429397638, 5.566303914283624, 4.211739909088348, 3.2024195913446896, 5.988374196321564, 2.906911733417008, 2.049250221164283, 1.9297968536155994, 2.7138697185720817, 2.019491557795661, 1.1924794120745956, 0.4173136952986201, 0.0), # 171
(6.276099463465638, 4.403226829195226, 5.7326642497945866, 5.822188034811656, 5.218015775734522, 2.5988991838130535, 1.9668752384220392, 1.9975906187276353, 2.881125561472354, 1.025313386231724, 0.8092114883913387, 0.4862404369231972, 0.0, 6.959175327776763, 5.348644806155168, 4.046057441956694, 3.075940158695172, 5.762251122944708, 2.7966268662186895, 1.9668752384220392, 1.8563565598664666, 2.609007887867261, 1.9407293449372194, 1.1465328499589174, 0.40029334810865697, 0.0), # 172
(6.010617756487176, 4.212565484159386, 5.4967415058087115, 5.579976740029178, 5.002732767090961, 2.4931134783059927, 1.8828130278654898, 1.916503219824812, 2.7646607857153684, 0.9821778333261846, 0.7752865489788355, 0.4659654096754725, 0.0, 6.671660707462155, 5.125619506430197, 3.8764327448941778, 2.9465334999785533, 5.529321571430737, 2.6831045077547366, 1.8828130278654898, 1.7807953416471376, 2.5013663835454807, 1.859992246676393, 1.0993483011617424, 0.38296049855994424, 0.0), # 173
(5.740301548302412, 4.019097485710249, 5.2555344277646014, 5.332742469559387, 4.782710854185972, 2.3847769533326795, 1.7973526515455251, 1.8334266323965802, 2.645262281841985, 0.9382220294744842, 0.7406968001979856, 0.44527750973796687, 0.0, 6.37788372783412, 4.898052607117634, 3.7034840009899272, 2.814666088423452, 5.29052456368397, 2.5667972853552126, 1.7973526515455251, 1.7034121095233423, 2.391355427092986, 1.7775808231864625, 1.0511068855529204, 0.3653724987009318, 0.0), # 174
(5.466092988194946, 3.823453706380764, 5.009948615011508, 5.08138690392213, 4.558770479992055, 2.2743080836851397, 1.7107831715130346, 1.748684161678698, 2.5233995608043616, 0.8936014657528275, 0.7055658786666139, 0.4242517000205815, 0.0, 6.078935548272969, 4.666768700226395, 3.5278293933330693, 2.680804397258482, 5.046799121608723, 2.4481578263501773, 1.7107831715130346, 1.6245057740608142, 2.2793852399960275, 1.6937956346407106, 1.0019897230023018, 0.3475867005800695, 0.0), # 175
(5.188934225448382, 3.62626501870388, 4.760889666898678, 4.8268117236372525, 4.331732087481704, 2.1621253441553967, 1.6233936498189088, 1.6625991129069244, 2.3995421335546565, 0.8484716332374204, 0.670017421002546, 0.4029629434332179, 0.0, 5.7759073281590085, 4.432592377765396, 3.35008710501273, 2.5454148997122603, 4.799084267109313, 2.327638758069694, 1.6233936498189088, 1.5443752458252833, 2.165866043740852, 1.6089372412124179, 0.9521779333797357, 0.3296604562458073, 0.0), # 176
(4.909767409346319, 3.4281622952125463, 4.5092631827753635, 4.569918609224595, 4.102416119627418, 2.0486472095354746, 1.5354731485140374, 1.5754947913170163, 2.2741595110450277, 0.8029880230044676, 0.6341750638236071, 0.3814862028857779, 0.0, 5.4698902268725496, 4.196348231743556, 3.1708753191180357, 2.408964069013402, 4.548319022090055, 2.2056927078438227, 1.5354731485140374, 1.4633194353824817, 2.051208059813709, 1.5233062030748654, 0.9018526365550728, 0.31165111774659515, 0.0), # 177
(4.629534689172356, 3.2297764084397107, 4.255974761990814, 4.311609241204004, 3.8716430194016906, 1.9342921546173981, 1.4473107296493104, 1.4876945021447328, 2.147721204227634, 0.7573061261301752, 0.5981624437476226, 0.3598964412881627, 0.0, 5.161975403793902, 3.958860854169789, 2.9908122187381125, 2.271918378390525, 4.295442408455268, 2.082772303002626, 1.4473107296493104, 1.3816372532981414, 1.9358215097008453, 1.437203080401335, 0.8511949523981628, 0.29361603713088286, 0.0), # 178
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 179
)
passenger_allighting_rate = (
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 0
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 1
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 2
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 3
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 4
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 5
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 6
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 7
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 8
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 9
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 10
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 11
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 12
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 13
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 14
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 15
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 16
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 17
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 18
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 19
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 20
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 21
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 22
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 23
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 24
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 25
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 26
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 27
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 28
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 29
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 30
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 31
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 32
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 33
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 34
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 35
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 36
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 37
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 38
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 39
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 40
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 41
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 42
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 43
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 44
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 45
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 46
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 47
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 48
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 49
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 50
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 51
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 52
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 53
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 54
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 55
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 56
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 57
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 58
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 59
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 60
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 61
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 62
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 63
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 64
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 65
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 66
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 67
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 68
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 69
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 70
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 71
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 72
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 73
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 74
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 75
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 76
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 77
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 78
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 79
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 80
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 81
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 82
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 83
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 84
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 85
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 86
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 87
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 88
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 89
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 90
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 91
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 92
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 93
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 94
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 95
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 96
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 97
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 98
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 99
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 100
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 101
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 102
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 103
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 104
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 105
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 106
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 107
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 108
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 109
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 110
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 111
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 112
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 113
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 114
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 115
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 116
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 117
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 118
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 119
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 120
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 121
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 122
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 123
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 124
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 125
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 126
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 127
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 128
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 129
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 130
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 131
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 132
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 133
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 134
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 135
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 136
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 137
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 138
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 139
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 140
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 141
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 142
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 143
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 144
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 145
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 146
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 147
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 148
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 149
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 150
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 151
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 152
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 153
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 154
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 155
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 156
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 157
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 158
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 159
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 160
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 161
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 162
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 163
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 164
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 165
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 166
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 167
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 168
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 169
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 170
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 171
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 172
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 173
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 174
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 175
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 176
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 177
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 178
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1), # 179
)
"""
parameters for reproducibiliy. More information: https://numpy.org/doc/stable/reference/random/parallel.html
"""
#initial entropy
entropy = 8991598675325360468762009371570610170
#index for seed sequence child
child_seed_index = (
1, # 0
37, # 1
)
| 275.572193 | 493 | 0.768982 |
numPassengers = 22850
passenger_arriving = (
(6, 7, 10, 5, 3, 2, 1, 1, 4, 1, 1, 0, 0, 4, 6, 6, 2, 4, 0, 3, 0, 1, 2, 0, 0, 0),
(8, 8, 6, 3, 2, 2, 2, 4, 3, 0, 0, 1, 0, 9, 8, 7, 1, 1, 5, 3, 0, 2, 2, 2, 1, 0),
(8, 8, 12, 3, 3, 2, 1, 1, 0, 1, 2, 0, 0, 5, 7, 2, 2, 8, 3, 3, 2, 2, 0, 1, 0, 0),
(6, 4, 4, 9, 4, 3, 0, 1, 3, 2, 0, 1, 0, 10, 6, 4, 7, 9, 4, 2, 0, 1, 0, 1, 1, 0),
(2, 6, 7, 10, 6, 2, 6, 4, 2, 2, 2, 1, 0, 8, 6, 2, 3, 5, 3, 4, 1, 0, 0, 0, 0, 0),
(6, 8, 10, 8, 4, 2, 4, 4, 4, 1, 1, 0, 0, 7, 6, 7, 4, 4, 3, 3, 2, 4, 3, 2, 0, 0),
(8, 5, 8, 13, 2, 4, 1, 5, 4, 5, 0, 0, 0, 13, 12, 5, 5, 7, 1, 2, 1, 2, 4, 3, 1, 0),
(8, 16, 9, 7, 3, 1, 3, 3, 5, 2, 0, 1, 0, 10, 5, 9, 4, 8, 8, 4, 3, 3, 3, 1, 0, 0),
(8, 9, 10, 10, 5, 5, 3, 3, 2, 1, 6, 2, 0, 8, 4, 5, 5, 7, 4, 5, 3, 6, 4, 0, 0, 0),
(7, 14, 8, 7, 4, 4, 4, 8, 5, 1, 1, 0, 0, 6, 9, 6, 4, 6, 6, 1, 3, 2, 4, 2, 2, 0),
(13, 10, 7, 8, 12, 3, 0, 1, 3, 0, 1, 2, 0, 7, 6, 5, 4, 5, 5, 3, 1, 6, 3, 2, 1, 0),
(6, 12, 12, 12, 7, 3, 6, 6, 1, 0, 3, 3, 0, 8, 8, 8, 9, 10, 8, 4, 2, 6, 6, 3, 0, 0),
(11, 14, 14, 7, 8, 3, 4, 1, 4, 2, 5, 0, 0, 12, 8, 5, 4, 10, 8, 4, 5, 5, 4, 1, 1, 0),
(12, 12, 4, 12, 6, 1, 2, 3, 3, 3, 1, 2, 0, 8, 6, 12, 6, 7, 3, 6, 3, 8, 6, 0, 1, 0),
(8, 5, 7, 6, 10, 1, 4, 7, 6, 1, 0, 0, 0, 12, 11, 10, 5, 5, 1, 3, 2, 4, 4, 2, 1, 0),
(13, 11, 8, 5, 10, 10, 4, 11, 4, 2, 1, 3, 0, 16, 9, 7, 8, 14, 4, 4, 3, 2, 3, 1, 1, 0),
(15, 14, 11, 7, 8, 4, 0, 10, 6, 2, 0, 0, 0, 10, 8, 5, 4, 11, 11, 8, 2, 3, 2, 2, 1, 0),
(9, 13, 10, 13, 7, 3, 4, 6, 4, 3, 2, 2, 0, 15, 11, 8, 5, 9, 8, 7, 2, 2, 4, 2, 1, 0),
(12, 9, 15, 13, 9, 5, 4, 2, 1, 0, 1, 2, 0, 10, 6, 9, 5, 10, 5, 7, 4, 2, 1, 0, 3, 0),
(7, 23, 15, 13, 7, 6, 9, 5, 3, 2, 1, 1, 0, 10, 9, 5, 7, 14, 10, 4, 4, 3, 3, 1, 0, 0),
(13, 14, 6, 5, 11, 7, 7, 4, 7, 1, 3, 1, 0, 11, 13, 13, 12, 6, 7, 3, 1, 3, 5, 1, 1, 0),
(13, 10, 18, 6, 13, 7, 9, 6, 8, 2, 3, 2, 0, 12, 17, 8, 12, 7, 9, 6, 7, 5, 4, 2, 0, 0),
(13, 7, 12, 12, 13, 7, 5, 1, 8, 1, 1, 1, 0, 16, 11, 4, 6, 15, 5, 7, 4, 5, 5, 3, 1, 0),
(9, 13, 6, 11, 8, 3, 8, 4, 7, 3, 1, 2, 0, 11, 11, 5, 6, 15, 4, 4, 3, 3, 4, 3, 0, 0),
(14, 12, 11, 8, 9, 2, 4, 2, 6, 1, 0, 3, 0, 14, 11, 7, 6, 16, 6, 5, 2, 3, 7, 2, 2, 0),
(10, 13, 4, 12, 10, 2, 1, 3, 4, 3, 0, 2, 0, 7, 9, 9, 11, 8, 8, 2, 1, 8, 3, 1, 0, 0),
(11, 9, 13, 11, 9, 4, 4, 5, 7, 0, 2, 4, 0, 18, 12, 7, 9, 14, 7, 3, 3, 5, 4, 3, 1, 0),
(11, 14, 11, 7, 8, 5, 5, 4, 5, 4, 2, 0, 0, 9, 7, 7, 8, 14, 6, 4, 2, 10, 2, 0, 4, 0),
(12, 5, 11, 11, 5, 4, 4, 6, 3, 2, 3, 2, 0, 15, 13, 11, 5, 11, 10, 4, 5, 3, 3, 2, 0, 0),
(8, 16, 6, 13, 13, 5, 3, 5, 8, 1, 3, 0, 0, 12, 8, 5, 7, 12, 4, 5, 4, 9, 4, 4, 1, 0),
(14, 11, 13, 15, 11, 0, 6, 4, 6, 3, 1, 1, 0, 10, 10, 8, 3, 14, 4, 3, 3, 9, 3, 2, 2, 0),
(9, 6, 11, 15, 12, 2, 1, 5, 5, 2, 0, 0, 0, 5, 6, 3, 5, 11, 7, 3, 1, 3, 5, 2, 1, 0),
(11, 10, 10, 13, 8, 4, 7, 4, 8, 3, 5, 1, 0, 10, 7, 10, 7, 11, 3, 5, 2, 4, 2, 3, 2, 0),
(13, 7, 8, 6, 14, 7, 4, 8, 12, 0, 2, 1, 0, 12, 7, 11, 5, 7, 3, 5, 2, 5, 1, 1, 1, 0),
(16, 13, 18, 13, 9, 7, 4, 2, 5, 2, 2, 1, 0, 16, 11, 12, 7, 10, 8, 3, 3, 8, 2, 2, 0, 0),
(10, 13, 13, 12, 9, 6, 4, 3, 3, 0, 2, 4, 0, 6, 11, 9, 6, 11, 4, 4, 2, 6, 2, 0, 1, 0),
(14, 17, 11, 10, 11, 1, 4, 9, 5, 3, 3, 1, 0, 12, 6, 5, 5, 11, 2, 5, 4, 4, 1, 5, 0, 0),
(9, 9, 6, 7, 5, 5, 2, 6, 5, 3, 0, 1, 0, 12, 9, 6, 7, 15, 8, 1, 2, 3, 7, 2, 0, 0),
(14, 8, 10, 9, 14, 3, 4, 4, 5, 2, 1, 1, 0, 9, 9, 8, 8, 8, 4, 5, 3, 2, 6, 1, 0, 0),
(10, 14, 9, 12, 8, 4, 1, 4, 5, 2, 1, 0, 0, 7, 10, 12, 5, 5, 8, 5, 1, 4, 3, 4, 1, 0),
(13, 8, 7, 6, 13, 6, 5, 2, 6, 3, 0, 1, 0, 16, 17, 6, 11, 9, 5, 5, 4, 5, 1, 1, 1, 0),
(9, 14, 11, 10, 6, 3, 2, 1, 8, 2, 1, 2, 0, 7, 10, 5, 8, 7, 6, 6, 7, 6, 1, 2, 2, 0),
(15, 9, 7, 17, 8, 8, 7, 3, 8, 2, 1, 1, 0, 9, 12, 10, 9, 12, 7, 9, 4, 5, 5, 3, 1, 0),
(14, 9, 9, 12, 9, 4, 6, 2, 9, 2, 0, 1, 0, 7, 14, 17, 7, 7, 6, 4, 2, 5, 4, 1, 2, 0),
(7, 11, 13, 9, 5, 5, 6, 2, 5, 0, 1, 1, 0, 10, 5, 9, 9, 10, 8, 5, 5, 7, 3, 2, 1, 0),
(10, 9, 10, 13, 15, 3, 5, 6, 6, 1, 2, 2, 0, 12, 10, 11, 7, 10, 2, 6, 5, 5, 2, 5, 1, 0),
(12, 9, 14, 10, 14, 3, 4, 5, 1, 4, 1, 0, 0, 8, 6, 9, 9, 12, 6, 4, 5, 7, 2, 2, 1, 0),
(15, 11, 19, 10, 9, 4, 5, 2, 7, 0, 3, 0, 0, 14, 15, 4, 4, 12, 7, 3, 5, 2, 2, 4, 0, 0),
(11, 7, 12, 9, 13, 2, 5, 5, 5, 1, 0, 3, 0, 17, 16, 6, 5, 7, 9, 5, 2, 3, 4, 2, 2, 0),
(17, 12, 11, 12, 10, 4, 7, 6, 6, 3, 1, 0, 0, 16, 12, 8, 7, 11, 7, 5, 4, 4, 5, 0, 1, 0),
(15, 11, 9, 17, 10, 9, 3, 6, 8, 5, 1, 0, 0, 17, 10, 5, 3, 5, 5, 4, 2, 2, 6, 2, 0, 0),
(8, 8, 4, 19, 10, 6, 3, 3, 5, 3, 2, 1, 0, 9, 14, 12, 7, 9, 3, 2, 0, 10, 1, 1, 0, 0),
(16, 10, 11, 8, 10, 3, 7, 1, 3, 3, 2, 0, 0, 14, 12, 9, 9, 9, 5, 2, 5, 0, 5, 0, 1, 0),
(15, 9, 7, 9, 7, 2, 8, 5, 4, 2, 3, 1, 0, 15, 13, 7, 5, 9, 7, 5, 4, 7, 3, 3, 1, 0),
(13, 6, 11, 13, 8, 3, 5, 3, 8, 2, 0, 0, 0, 10, 11, 6, 8, 9, 5, 4, 2, 5, 3, 1, 0, 0),
(9, 13, 13, 16, 4, 5, 4, 6, 2, 0, 3, 3, 0, 10, 18, 8, 9, 8, 4, 4, 3, 4, 2, 2, 0, 0),
(12, 12, 9, 9, 13, 1, 5, 4, 3, 2, 4, 0, 0, 10, 14, 6, 4, 14, 7, 8, 3, 9, 3, 2, 2, 0),
(17, 14, 8, 10, 11, 6, 5, 5, 4, 5, 0, 1, 0, 15, 10, 6, 6, 10, 8, 5, 2, 9, 7, 0, 1, 0),
(11, 13, 10, 13, 12, 4, 1, 3, 3, 1, 2, 1, 0, 9, 7, 11, 8, 7, 3, 2, 3, 6, 3, 2, 1, 0),
(10, 16, 10, 11, 10, 8, 9, 3, 4, 4, 2, 1, 0, 13, 12, 10, 7, 10, 9, 3, 7, 4, 4, 2, 1, 0),
(11, 6, 12, 10, 7, 8, 5, 2, 4, 3, 1, 0, 0, 14, 8, 8, 7, 11, 8, 3, 2, 2, 7, 0, 4, 0),
(14, 8, 10, 9, 14, 2, 1, 5, 6, 1, 2, 1, 0, 14, 16, 5, 10, 8, 5, 8, 3, 6, 0, 2, 0, 0),
(15, 11, 9, 7, 11, 6, 2, 4, 3, 1, 0, 3, 0, 6, 8, 3, 7, 13, 10, 5, 3, 5, 7, 1, 2, 0),
(15, 10, 5, 4, 6, 4, 4, 2, 5, 3, 2, 0, 0, 15, 8, 6, 3, 6, 6, 3, 5, 0, 5, 1, 0, 0),
(16, 4, 11, 5, 6, 4, 2, 2, 1, 3, 0, 1, 0, 9, 9, 3, 9, 4, 5, 1, 7, 6, 3, 2, 2, 0),
(14, 14, 6, 9, 8, 4, 7, 2, 6, 4, 1, 1, 0, 10, 7, 10, 7, 9, 5, 2, 3, 3, 3, 4, 0, 0),
(12, 12, 12, 11, 12, 5, 8, 4, 6, 0, 2, 1, 0, 11, 5, 6, 4, 10, 6, 1, 3, 6, 2, 1, 1, 0),
(7, 6, 14, 13, 11, 4, 3, 2, 7, 3, 4, 0, 0, 13, 8, 6, 3, 14, 2, 3, 1, 7, 6, 3, 2, 0),
(14, 12, 10, 7, 6, 6, 10, 7, 8, 3, 0, 1, 0, 10, 10, 6, 8, 13, 4, 6, 5, 4, 4, 0, 0, 0),
(17, 16, 5, 10, 10, 2, 7, 2, 7, 1, 3, 1, 0, 18, 13, 7, 7, 7, 3, 6, 5, 9, 1, 2, 0, 0),
(12, 9, 9, 15, 10, 3, 4, 3, 4, 3, 2, 1, 0, 10, 15, 11, 2, 9, 7, 9, 3, 6, 4, 1, 0, 0),
(9, 11, 6, 11, 16, 4, 2, 0, 5, 4, 1, 2, 0, 14, 12, 5, 5, 8, 5, 1, 5, 7, 6, 4, 0, 0),
(18, 7, 13, 16, 11, 6, 5, 2, 7, 2, 2, 0, 0, 14, 13, 6, 3, 9, 4, 5, 2, 3, 3, 0, 2, 0),
(11, 7, 10, 8, 9, 5, 7, 5, 3, 1, 1, 1, 0, 16, 6, 9, 9, 7, 5, 6, 4, 6, 5, 3, 1, 0),
(14, 6, 7, 9, 8, 2, 3, 3, 7, 1, 1, 1, 0, 12, 16, 9, 4, 12, 3, 4, 1, 5, 5, 1, 3, 0),
(10, 12, 10, 12, 18, 8, 3, 5, 4, 1, 1, 1, 0, 11, 7, 10, 5, 6, 4, 3, 3, 7, 5, 2, 0, 0),
(16, 13, 13, 4, 11, 5, 7, 1, 6, 2, 2, 1, 0, 15, 7, 4, 7, 9, 3, 3, 1, 4, 9, 2, 1, 0),
(15, 11, 12, 13, 12, 5, 4, 4, 0, 1, 1, 0, 0, 13, 8, 15, 6, 12, 3, 2, 9, 5, 1, 2, 2, 0),
(11, 6, 9, 9, 11, 2, 7, 2, 7, 3, 1, 1, 0, 11, 15, 9, 8, 8, 3, 5, 2, 2, 3, 2, 0, 0),
(7, 14, 10, 9, 1, 2, 5, 7, 3, 1, 3, 0, 0, 11, 15, 9, 9, 13, 6, 4, 4, 4, 2, 1, 0, 0),
(12, 8, 14, 4, 5, 2, 8, 1, 5, 3, 2, 0, 0, 9, 13, 4, 3, 11, 1, 4, 1, 3, 3, 2, 0, 0),
(16, 12, 4, 19, 10, 4, 4, 1, 3, 2, 0, 2, 0, 7, 8, 9, 4, 9, 6, 7, 8, 6, 1, 5, 2, 0),
(10, 10, 8, 7, 6, 3, 4, 3, 3, 2, 3, 1, 0, 9, 10, 7, 7, 9, 3, 3, 6, 5, 2, 4, 0, 0),
(11, 12, 11, 11, 4, 3, 0, 3, 5, 3, 2, 0, 0, 13, 10, 6, 7, 9, 4, 3, 1, 6, 3, 1, 1, 0),
(10, 8, 6, 12, 11, 3, 3, 5, 6, 3, 0, 3, 0, 16, 6, 7, 9, 12, 7, 2, 1, 4, 6, 2, 1, 0),
(11, 6, 9, 8, 8, 1, 3, 2, 6, 2, 1, 1, 0, 18, 11, 6, 11, 12, 8, 5, 2, 5, 4, 5, 0, 0),
(10, 11, 8, 5, 7, 2, 3, 1, 1, 5, 1, 0, 0, 16, 8, 9, 5, 11, 7, 1, 2, 8, 1, 1, 1, 0),
(13, 8, 5, 11, 11, 5, 6, 1, 5, 1, 0, 3, 0, 10, 10, 7, 2, 9, 2, 3, 4, 4, 4, 2, 0, 0),
(14, 13, 8, 9, 12, 5, 4, 7, 5, 2, 2, 0, 0, 12, 14, 9, 6, 7, 4, 6, 2, 4, 5, 3, 1, 0),
(10, 10, 5, 19, 11, 5, 2, 1, 5, 4, 0, 2, 0, 12, 10, 11, 9, 10, 9, 5, 4, 1, 2, 5, 0, 0),
(9, 15, 12, 3, 7, 2, 9, 1, 2, 1, 2, 0, 0, 15, 10, 5, 6, 10, 4, 3, 6, 3, 2, 1, 2, 0),
(13, 7, 4, 10, 10, 5, 2, 1, 5, 3, 1, 3, 0, 12, 10, 5, 4, 8, 7, 4, 6, 0, 2, 2, 0, 0),
(12, 11, 12, 7, 11, 4, 4, 3, 3, 2, 1, 0, 0, 13, 12, 9, 8, 8, 5, 2, 3, 3, 3, 0, 1, 0),
(7, 12, 5, 4, 11, 6, 2, 4, 5, 4, 2, 1, 0, 8, 12, 11, 8, 7, 4, 6, 5, 6, 3, 6, 0, 0),
(8, 13, 10, 13, 17, 1, 1, 1, 4, 1, 2, 0, 0, 14, 12, 4, 4, 15, 3, 1, 3, 5, 6, 4, 0, 0),
(10, 10, 17, 8, 7, 4, 1, 3, 3, 0, 1, 1, 0, 14, 10, 8, 5, 10, 1, 6, 2, 3, 6, 2, 2, 0),
(10, 9, 13, 11, 13, 2, 6, 4, 1, 0, 0, 1, 0, 13, 10, 16, 3, 15, 4, 5, 5, 3, 3, 7, 2, 0),
(7, 6, 8, 14, 8, 3, 3, 3, 4, 0, 3, 0, 0, 20, 5, 8, 5, 9, 5, 6, 4, 6, 5, 5, 1, 0),
(13, 7, 10, 8, 11, 7, 1, 3, 5, 0, 1, 1, 0, 13, 17, 7, 6, 12, 2, 3, 5, 5, 4, 3, 0, 0),
(10, 7, 16, 7, 12, 5, 3, 4, 8, 3, 2, 0, 0, 19, 9, 12, 7, 11, 6, 1, 3, 5, 2, 0, 0, 0),
(14, 13, 9, 7, 6, 3, 0, 2, 3, 2, 0, 0, 0, 13, 10, 6, 4, 7, 6, 3, 4, 3, 3, 1, 2, 0),
(12, 14, 5, 8, 5, 6, 5, 5, 2, 2, 3, 0, 0, 14, 7, 7, 4, 9, 3, 2, 3, 8, 3, 3, 1, 0),
(8, 8, 11, 14, 11, 3, 2, 1, 8, 1, 4, 1, 0, 19, 8, 6, 6, 5, 3, 4, 2, 2, 4, 3, 1, 0),
(12, 11, 8, 13, 5, 3, 1, 3, 5, 1, 3, 1, 0, 12, 11, 6, 6, 6, 4, 3, 1, 6, 2, 0, 1, 0),
(15, 10, 9, 8, 4, 5, 3, 3, 2, 3, 0, 2, 0, 15, 11, 11, 5, 12, 3, 2, 3, 4, 3, 3, 1, 0),
(17, 11, 8, 15, 7, 8, 5, 3, 5, 2, 2, 0, 0, 10, 11, 11, 4, 12, 5, 5, 6, 3, 5, 0, 1, 0),
(15, 7, 12, 11, 14, 4, 5, 2, 5, 0, 0, 1, 0, 7, 9, 7, 2, 9, 3, 4, 3, 6, 6, 1, 1, 0),
(11, 12, 4, 7, 17, 4, 4, 2, 6, 2, 0, 0, 0, 16, 9, 9, 4, 4, 9, 7, 4, 1, 4, 1, 1, 0),
(12, 6, 12, 9, 9, 3, 5, 2, 7, 1, 0, 0, 0, 18, 4, 12, 3, 5, 5, 1, 5, 10, 7, 0, 0, 0),
(10, 5, 9, 11, 10, 4, 2, 1, 8, 3, 1, 0, 0, 11, 6, 9, 5, 9, 5, 6, 2, 4, 6, 3, 0, 0),
(8, 8, 7, 10, 14, 2, 3, 7, 7, 4, 1, 0, 0, 11, 11, 8, 9, 5, 4, 7, 2, 2, 5, 0, 3, 0),
(5, 10, 7, 10, 12, 1, 3, 6, 6, 1, 2, 0, 0, 18, 10, 6, 5, 13, 4, 4, 3, 7, 0, 2, 0, 0),
(12, 13, 3, 3, 10, 4, 7, 2, 1, 1, 2, 2, 0, 12, 6, 3, 10, 7, 1, 1, 4, 4, 2, 1, 1, 0),
(12, 6, 8, 11, 8, 4, 4, 6, 5, 2, 2, 0, 0, 5, 9, 9, 6, 7, 6, 3, 3, 1, 3, 3, 0, 0),
(9, 8, 8, 15, 8, 0, 4, 4, 4, 1, 2, 1, 0, 6, 15, 5, 3, 16, 5, 4, 3, 3, 4, 1, 2, 0),
(6, 6, 10, 13, 9, 3, 2, 4, 4, 2, 1, 2, 0, 12, 13, 9, 1, 10, 6, 6, 0, 5, 3, 0, 0, 0),
(11, 5, 9, 10, 8, 4, 5, 4, 3, 0, 0, 0, 0, 10, 7, 9, 8, 9, 5, 1, 0, 3, 2, 3, 1, 0),
(14, 5, 11, 14, 12, 3, 2, 1, 10, 0, 0, 0, 0, 14, 5, 7, 5, 12, 3, 4, 0, 6, 2, 1, 1, 0),
(9, 13, 5, 10, 7, 4, 5, 1, 6, 1, 1, 1, 0, 11, 11, 4, 3, 9, 4, 3, 2, 5, 3, 2, 0, 0),
(11, 6, 8, 12, 10, 1, 2, 4, 2, 0, 1, 1, 0, 9, 8, 4, 5, 9, 4, 1, 3, 4, 2, 3, 1, 0),
(17, 5, 7, 9, 10, 3, 4, 1, 3, 2, 3, 2, 0, 9, 10, 8, 6, 7, 4, 3, 3, 8, 3, 0, 0, 0),
(10, 13, 6, 3, 11, 5, 3, 1, 2, 1, 3, 0, 0, 10, 11, 9, 4, 6, 6, 3, 1, 2, 0, 1, 0, 0),
(13, 7, 11, 11, 12, 4, 2, 2, 2, 0, 2, 0, 0, 12, 11, 9, 3, 4, 8, 4, 4, 6, 3, 1, 1, 0),
(17, 9, 14, 18, 6, 8, 1, 5, 5, 2, 1, 2, 0, 14, 8, 8, 7, 7, 0, 3, 4, 2, 4, 2, 1, 0),
(10, 2, 9, 11, 8, 7, 6, 2, 2, 3, 2, 1, 0, 10, 10, 6, 8, 7, 3, 5, 4, 4, 1, 3, 1, 0),
(10, 7, 20, 8, 7, 6, 4, 4, 3, 2, 1, 0, 0, 11, 7, 11, 2, 11, 6, 3, 5, 1, 3, 2, 1, 0),
(7, 7, 9, 5, 11, 3, 2, 0, 5, 1, 1, 1, 0, 8, 8, 4, 6, 6, 3, 1, 1, 2, 2, 2, 1, 0),
(11, 12, 4, 10, 12, 2, 6, 3, 1, 1, 2, 0, 0, 16, 11, 12, 4, 9, 4, 3, 7, 6, 8, 2, 0, 0),
(13, 7, 8, 11, 6, 3, 1, 4, 1, 1, 2, 2, 0, 17, 10, 4, 2, 7, 5, 6, 2, 3, 1, 2, 0, 0),
(11, 9, 10, 11, 15, 2, 3, 0, 3, 1, 1, 1, 0, 12, 6, 7, 6, 11, 5, 4, 2, 2, 4, 2, 2, 0),
(8, 2, 10, 10, 7, 2, 4, 3, 5, 3, 2, 0, 0, 10, 8, 5, 5, 6, 3, 6, 1, 6, 3, 1, 0, 0),
(14, 10, 8, 9, 11, 2, 7, 4, 4, 1, 0, 1, 0, 16, 6, 7, 6, 9, 4, 0, 3, 2, 2, 0, 2, 0),
(14, 8, 3, 13, 8, 2, 1, 5, 3, 4, 1, 1, 0, 7, 7, 6, 6, 7, 4, 3, 4, 3, 2, 1, 1, 0),
(15, 8, 7, 9, 8, 3, 5, 3, 7, 1, 1, 2, 0, 14, 10, 4, 8, 9, 2, 5, 0, 5, 4, 0, 0, 0),
(14, 12, 7, 9, 7, 2, 3, 5, 3, 1, 2, 1, 0, 7, 13, 11, 3, 11, 4, 3, 1, 4, 3, 3, 2, 0),
(11, 7, 12, 6, 5, 5, 6, 1, 6, 2, 0, 0, 0, 7, 8, 10, 6, 11, 1, 5, 2, 4, 4, 2, 1, 0),
(14, 8, 9, 14, 3, 6, 2, 3, 6, 3, 2, 1, 0, 10, 11, 8, 4, 4, 2, 1, 3, 3, 3, 0, 0, 0),
(12, 6, 10, 7, 9, 3, 4, 2, 6, 3, 2, 3, 0, 11, 7, 6, 6, 5, 10, 6, 1, 3, 2, 2, 0, 0),
(11, 7, 5, 8, 7, 6, 2, 2, 9, 0, 1, 2, 0, 19, 9, 2, 4, 7, 7, 3, 2, 7, 4, 2, 0, 0),
(12, 6, 10, 10, 10, 4, 3, 3, 5, 0, 0, 0, 0, 9, 8, 9, 4, 6, 6, 1, 5, 5, 4, 4, 2, 0),
(5, 9, 8, 7, 11, 3, 4, 3, 3, 0, 2, 0, 0, 11, 10, 5, 6, 3, 2, 3, 5, 1, 6, 2, 2, 0),
(10, 6, 4, 8, 7, 5, 4, 3, 2, 3, 3, 1, 0, 3, 11, 10, 6, 10, 2, 2, 3, 5, 6, 2, 2, 0),
(11, 6, 4, 3, 11, 4, 2, 3, 3, 2, 2, 2, 0, 11, 7, 8, 4, 8, 4, 1, 5, 3, 3, 0, 3, 0),
(12, 5, 11, 9, 5, 6, 1, 4, 6, 5, 1, 2, 0, 16, 6, 6, 7, 4, 2, 3, 3, 4, 2, 1, 0, 0),
(12, 9, 11, 7, 7, 3, 3, 4, 4, 1, 1, 3, 0, 7, 8, 12, 3, 6, 5, 5, 3, 1, 4, 2, 2, 0),
(9, 6, 6, 7, 7, 11, 4, 2, 7, 1, 1, 0, 0, 11, 8, 7, 3, 7, 7, 6, 3, 7, 2, 1, 1, 0),
(13, 8, 9, 7, 5, 5, 5, 5, 4, 4, 0, 0, 0, 5, 10, 4, 8, 7, 7, 4, 2, 7, 2, 0, 3, 0),
(8, 9, 11, 9, 5, 1, 5, 2, 2, 2, 0, 0, 0, 9, 8, 5, 9, 6, 4, 4, 4, 1, 3, 1, 1, 0),
(9, 12, 7, 13, 4, 2, 2, 4, 5, 1, 1, 3, 0, 15, 4, 5, 2, 12, 4, 1, 5, 2, 6, 2, 0, 0),
(9, 8, 10, 11, 11, 2, 6, 3, 3, 1, 0, 0, 0, 8, 7, 9, 3, 7, 2, 4, 3, 4, 2, 0, 0, 0),
(14, 5, 11, 7, 4, 3, 1, 8, 4, 1, 0, 1, 0, 9, 7, 10, 4, 9, 6, 1, 3, 5, 1, 0, 2, 0),
(9, 8, 8, 17, 7, 4, 4, 2, 6, 1, 2, 0, 0, 6, 5, 3, 7, 2, 1, 2, 1, 5, 4, 0, 0, 0),
(9, 1, 6, 8, 5, 5, 2, 1, 5, 0, 1, 0, 0, 13, 8, 7, 7, 9, 5, 4, 3, 1, 2, 2, 0, 0),
(7, 4, 10, 12, 10, 5, 2, 4, 5, 6, 0, 0, 0, 10, 4, 9, 3, 12, 2, 1, 2, 0, 4, 1, 0, 0),
(3, 5, 8, 8, 7, 4, 2, 1, 2, 1, 3, 0, 0, 14, 4, 8, 7, 6, 4, 5, 2, 4, 3, 1, 0, 0),
(11, 7, 5, 10, 8, 5, 3, 2, 5, 2, 2, 1, 0, 10, 8, 7, 4, 9, 3, 3, 6, 1, 3, 0, 2, 0),
(6, 8, 9, 9, 7, 4, 2, 3, 0, 0, 3, 0, 0, 13, 8, 1, 2, 2, 8, 0, 2, 1, 1, 2, 0, 0),
(4, 9, 8, 4, 4, 3, 5, 5, 1, 2, 2, 1, 0, 12, 10, 12, 5, 8, 5, 6, 3, 5, 4, 0, 0, 0),
(7, 6, 7, 6, 4, 3, 1, 0, 7, 1, 0, 0, 0, 16, 6, 5, 6, 5, 5, 3, 1, 1, 5, 0, 0, 0),
(8, 4, 8, 5, 6, 2, 3, 1, 2, 1, 1, 0, 0, 10, 9, 9, 5, 5, 5, 2, 4, 3, 2, 0, 0, 0),
(10, 2, 7, 9, 4, 5, 2, 2, 5, 1, 0, 0, 0, 10, 6, 5, 4, 7, 5, 3, 4, 4, 2, 3, 0, 0),
(7, 5, 8, 4, 7, 1, 1, 4, 4, 0, 0, 1, 0, 5, 2, 4, 2, 3, 2, 2, 2, 5, 3, 0, 1, 0),
(10, 8, 9, 7, 5, 2, 2, 2, 2, 0, 2, 0, 0, 6, 4, 7, 3, 5, 5, 1, 2, 5, 2, 2, 0, 0),
(8, 8, 4, 7, 6, 1, 4, 2, 2, 1, 2, 1, 0, 5, 8, 2, 4, 13, 5, 6, 2, 3, 3, 0, 2, 0),
(12, 2, 7, 7, 9, 3, 1, 4, 2, 0, 0, 0, 0, 14, 5, 8, 12, 6, 5, 2, 2, 4, 2, 2, 0, 0),
(10, 5, 3, 9, 4, 6, 5, 4, 4, 1, 0, 0, 0, 8, 5, 9, 3, 9, 6, 1, 4, 1, 0, 1, 0, 0),
(7, 3, 7, 4, 7, 3, 0, 3, 4, 2, 1, 1, 0, 14, 5, 1, 1, 8, 5, 3, 2, 2, 1, 1, 1, 0),
(7, 4, 2, 4, 6, 1, 2, 2, 5, 1, 2, 0, 0, 8, 13, 3, 2, 4, 3, 3, 2, 8, 0, 1, 2, 0),
(7, 4, 7, 1, 7, 4, 5, 3, 1, 1, 2, 1, 0, 13, 5, 5, 1, 3, 4, 1, 2, 2, 3, 1, 0, 0),
(7, 9, 3, 5, 11, 2, 4, 2, 3, 0, 0, 0, 0, 6, 10, 3, 4, 7, 5, 1, 2, 2, 2, 3, 0, 0),
(8, 7, 9, 9, 9, 1, 6, 2, 8, 2, 4, 0, 0, 8, 10, 4, 2, 9, 3, 4, 2, 3, 4, 2, 1, 0),
(7, 4, 5, 9, 2, 0, 2, 0, 3, 1, 0, 1, 0, 8, 7, 8, 5, 6, 0, 2, 2, 3, 2, 0, 1, 0),
(5, 4, 6, 2, 2, 2, 4, 0, 0, 2, 0, 0, 0, 8, 2, 6, 2, 5, 2, 4, 0, 4, 1, 1, 1, 0),
(10, 4, 7, 6, 4, 4, 2, 2, 1, 1, 0, 0, 0, 8, 2, 6, 4, 7, 2, 3, 1, 3, 7, 0, 1, 0),
(6, 1, 4, 7, 5, 1, 0, 1, 0, 0, 0, 0, 0, 5, 4, 4, 0, 5, 5, 2, 2, 1, 2, 1, 0, 0),
(4, 1, 5, 8, 5, 6, 3, 1, 6, 0, 2, 1, 0, 9, 8, 2, 1, 7, 2, 1, 3, 3, 1, 1, 1, 0),
(11, 4, 7, 5, 5, 2, 0, 1, 3, 2, 1, 0, 0, 7, 7, 3, 1, 3, 1, 1, 2, 2, 3, 1, 0, 0),
(2, 5, 5, 1, 4, 2, 0, 1, 2, 1, 1, 1, 0, 6, 4, 0, 6, 7, 0, 1, 3, 2, 0, 1, 0, 0),
(4, 2, 1, 5, 1, 2, 0, 0, 3, 1, 2, 0, 0, 3, 5, 3, 1, 3, 1, 0, 3, 1, 2, 1, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
)
station_arriving_intensity = (
(6.025038694046121, 6.630346271631799, 6.253539875535008, 7.457601328636119, 6.665622729131534, 3.766385918444806, 4.9752427384486975, 5.583811407575308, 7.308118874601608, 4.749618018626843, 5.046318196662723, 5.877498093967408, 6.100656255094035),
(6.425192582423969, 7.06807283297371, 6.666415909596182, 7.950173103931939, 7.106988404969084, 4.015180300851067, 5.303362729516432, 5.951416467486849, 7.79069439159949, 5.062776830732579, 5.3797153631473575, 6.265459992977225, 6.503749976927826),
(6.8240676107756775, 7.504062205069175, 7.077650742656896, 8.440785245597752, 7.546755568499692, 4.262982137414934, 5.630182209552845, 6.317550297485303, 8.271344168253059, 5.3746965300246545, 5.711787778531575, 6.651879182463666, 6.905237793851628),
(7.220109351775874, 7.936584602323736, 7.485613043183825, 8.927491689038488, 7.983194011202282, 4.508808747102135, 5.954404369977547, 6.680761388993408, 8.74816219310531, 5.684139238111417, 6.041218094192859, 7.035222821916553, 7.30352736750507),
(7.611763378099177, 8.363910239142928, 7.8886714796436435, 9.408346369659084, 8.41457352455579, 4.751677448878401, 6.27473240221015, 7.039598233433898, 9.219242454699248, 5.9898670766012145, 6.36668896150869, 7.413958070825716, 7.69702635952778),
(7.9974752624202115, 8.784309329932306, 8.285194720503021, 9.881403222864472, 8.839163900039136, 4.990605561709457, 6.589869497670269, 7.392609322229511, 9.682678941577871, 6.290642167102395, 6.686883031856559, 7.786552088680978, 8.084142431559393),
(8.375690577413598, 9.196052089097401, 8.673551434228639, 10.344716184059582, 9.255234929131252, 5.224610404561036, 6.898518847777515, 7.738343146802986, 10.136565642284177, 6.58522663122331, 7.000482956613939, 8.15147203497217, 8.463283245239527),
(8.744854895753962, 9.597408731043757, 9.052110289287162, 10.796339188649354, 9.661056403311065, 5.452709296398865, 7.199383643951502, 8.075348198577062, 10.578996545361173, 6.872382590572303, 7.306171387158321, 8.507185069189115, 8.832856462207822),
(9.103413790115921, 9.986649470176918, 9.419239954145274, 11.234326172038713, 10.054898114057503, 5.673919556188667, 7.491167077611837, 8.402172968974469, 11.008065639351846, 7.150872166757728, 7.602630974867185, 8.852158350821643, 9.1912697441039),
(9.449812833174102, 10.362044520902426, 9.773309097269644, 11.656731069632603, 10.43502985284949, 5.88725850289618, 7.772572340178144, 8.717365949417955, 11.421866912799208, 7.419457481387929, 7.888544371118013, 9.184859039359576, 9.536930752567395),
(9.782497597603118, 10.721864097625819, 10.11268638712695, 12.061607816835945, 10.79972141116596, 6.091743455487129, 8.042302623070025, 9.019475631330252, 11.818494354246257, 7.676900656071257, 8.162594227288288, 9.503754294292742, 9.868247149237932),
(10.099913656077605, 11.064378414752648, 10.435740492183857, 12.447010349053675, 11.14724258048584, 6.286391732927242, 8.2990611177071, 9.307050506134097, 12.196041952235992, 7.921963812416062, 8.423463194755499, 9.807311275110973, 10.183626595755133),
(10.400506581272174, 11.387857686688436, 10.740840080907047, 12.810992601690733, 11.475863152288053, 6.470220654182243, 8.541551015508974, 9.578639065252224, 12.552603695311413, 8.153409072030685, 8.669833924897121, 10.093997141304081, 10.48147675375864),
(10.68272194586145, 11.690572127838744, 11.026353821763193, 13.151608510152052, 11.78385291805152, 6.642247538217868, 8.768475507895266, 9.832789800107378, 12.886273572015517, 8.369998556523484, 8.900389069090641, 10.362279052361904, 10.760205284888082),
(10.945005322520059, 11.970791952609106, 11.290650383218976, 13.46691200984255, 12.069481669255188, 6.801489703999841, 8.978537786285592, 10.068051202122295, 13.195145570891304, 8.5704943875028, 9.113811278713541, 10.610624167774272, 11.018219850783076),
(11.185802283922625, 12.22678737540506, 11.53209843374105, 13.754957036167182, 12.33101919737797, 6.946964470493895, 9.17044104209955, 10.282971762719706, 13.477313680481783, 8.753658686576989, 9.308783205143303, 10.837499647031004, 11.253928113083257),
(11.40355840274376, 12.456828610632158, 11.749066641796109, 14.01379752453086, 12.5667352938988, 7.077689156665751, 9.34288846675677, 10.476099973322352, 13.730871889329944, 8.918253575354395, 9.483987499757415, 11.041372649621927, 11.465737733428254),
(11.59671925165809, 12.659185872695934, 11.939923675850823, 14.241487410338534, 12.774899750296605, 7.192681081481142, 9.494583251676852, 10.64598432535298, 13.95391418597878, 9.06304117544336, 9.638106813933359, 11.220710335036866, 11.652056373457699),
(11.763730403340244, 12.832129376001928, 12.103038204371856, 14.436080628995134, 12.953782358050306, 7.290957563905803, 9.62422858827942, 10.791173310234312, 14.144534558971316, 9.186783608452243, 9.76982379904861, 11.373979862765658, 11.811291694811214),
(11.903037430464838, 12.973929334955693, 12.236778895825895, 14.595631115905576, 13.101652908638838, 7.37153592290545, 9.730527667984072, 10.910215419389093, 14.300826996850533, 9.288242995989393, 9.877821106480653, 11.499648392298115, 11.941851359128435),
(12.013085905706498, 13.082855963962754, 12.339514418679602, 14.718192806474825, 13.216781193541133, 7.4334334774458215, 9.812183682210435, 11.00165914424006, 14.420885488159437, 9.36618145966315, 9.96078138760698, 11.59618308312407, 12.042143028048988),
(12.09232140173984, 13.15717947742867, 12.409613441399662, 14.801819636107782, 13.297437004236105, 7.475667546492642, 9.86789982237811, 11.064052976209947, 14.502804021441024, 9.419361121081865, 10.01738729380507, 11.662051094733352, 12.110574363212494),
(12.139189491239494, 13.195170089758973, 12.445444632452743, 14.844565540209402, 13.341890132202689, 7.497255449011639, 9.89637927990672, 11.095945406721498, 14.544676585238298, 9.44654410185389, 10.046321476452407, 11.695719586615787, 12.145553026258591),
(12.156472036011166, 13.199668312757202, 12.449907818930042, 14.849916975308643, 13.353278467239116, 7.5, 9.899764802711205, 11.099392592592592, 14.54991148148148, 9.44975072702332, 10.049949644594088, 11.69987709190672, 12.15),
(12.169214895640982, 13.197044444444446, 12.449177777777777, 14.849258333333335, 13.359729136337823, 7.5, 9.8979045751634, 11.0946, 14.549209999999999, 9.44778074074074, 10.049549494949495, 11.698903703703703, 12.15),
(12.181688676253897, 13.191872427983538, 12.447736625514404, 14.84795524691358, 13.366037934713404, 7.5, 9.894238683127572, 11.085185185185185, 14.547824074074073, 9.443902606310013, 10.048756079311634, 11.696982167352537, 12.15),
(12.19389242285764, 13.184231275720165, 12.445604115226338, 14.846022530864197, 13.372204642105325, 7.5, 9.888824061970466, 11.071325925925926, 14.54577148148148, 9.438180850480109, 10.047576580621024, 11.694138820301784, 12.15),
(12.205825180459962, 13.174199999999997, 12.4428, 14.843474999999998, 13.378229038253057, 7.5, 9.881717647058824, 11.0532, 14.54307, 9.430679999999999, 10.046018181818182, 11.6904, 12.15),
(12.217485994068602, 13.161857613168722, 12.439344032921811, 14.8403274691358, 13.384110902896081, 7.5, 9.87297637375938, 11.030985185185186, 14.539737407407406, 9.421464581618656, 10.04408806584362, 11.685792043895749, 12.15),
(12.2288739086913, 13.147283127572017, 12.43525596707819, 14.83659475308642, 13.389850015773865, 7.5, 9.862657177438878, 11.004859259259257, 14.535791481481482, 9.410599122085047, 10.041793415637859, 11.680341289437584, 12.15),
(12.239987969335797, 13.130555555555555, 12.430555555555555, 14.832291666666666, 13.395446156625884, 7.5, 9.850816993464052, 10.974999999999998, 14.53125, 9.398148148148149, 10.039141414141413, 11.674074074074072, 12.15),
(12.25082722100983, 13.11175390946502, 12.42526255144033, 14.827433024691356, 13.400899105191609, 7.5, 9.837512757201647, 10.941585185185184, 14.52613074074074, 9.384176186556926, 10.0361392442948, 11.667016735253773, 12.15),
(12.261390708721144, 13.09095720164609, 12.419396707818928, 14.822033641975308, 13.406208641210513, 7.5, 9.822801404018398, 10.904792592592594, 14.520451481481482, 9.368747764060357, 10.032794089038532, 11.659195610425241, 12.15),
(12.271677477477477, 13.068244444444444, 12.412977777777778, 14.816108333333332, 13.411374544422076, 7.5, 9.806739869281046, 10.8648, 14.51423, 9.351927407407407, 10.02911313131313, 11.650637037037034, 12.15),
(12.28168657228657, 13.04369465020576, 12.406025514403291, 14.809671913580246, 13.416396594565759, 7.5, 9.789385088356331, 10.821785185185183, 14.507484074074075, 9.33377964334705, 10.025103554059108, 11.641367352537722, 12.15),
(12.291417038156167, 13.01738683127572, 12.398559670781895, 14.802739197530862, 13.421274571381044, 7.5, 9.77079399661099, 10.775925925925925, 14.500231481481482, 9.314368998628257, 10.020772540216983, 11.631412894375858, 12.15),
(12.300867920094007, 12.989399999999998, 12.3906, 14.795324999999998, 13.426008254607403, 7.5, 9.751023529411764, 10.727400000000001, 14.492489999999998, 9.293759999999999, 10.016127272727273, 11.620800000000001, 12.15),
(12.310038263107828, 12.95981316872428, 12.382166255144032, 14.787444135802469, 13.430597423984304, 7.5, 9.730130622125392, 10.676385185185184, 14.484277407407406, 9.272017174211248, 10.01117493453049, 11.609555006858711, 12.15),
(12.31892711220537, 12.928705349794239, 12.37327818930041, 14.779111419753086, 13.435041859251228, 7.5, 9.708172210118615, 10.62305925925926, 14.475611481481481, 9.249205048010975, 10.005922708567153, 11.597704252400549, 12.15),
(12.327533512394384, 12.896155555555554, 12.363955555555556, 14.770341666666667, 13.439341340147644, 7.5, 9.68520522875817, 10.567599999999999, 14.466510000000001, 9.225388148148149, 10.000377777777777, 11.585274074074073, 12.15),
(12.335856508682596, 12.86224279835391, 12.354218106995884, 14.761149691358025, 13.443495646413021, 7.5, 9.661286613410796, 10.510185185185186, 14.456990740740741, 9.200631001371743, 9.99454732510288, 11.572290809327848, 12.15),
(12.343895146077754, 12.82704609053498, 12.344085596707819, 14.751550308641974, 13.447504557786841, 7.5, 9.636473299443233, 10.450992592592593, 14.44707148148148, 9.174998134430727, 9.988438533482979, 11.558780795610424, 12.15),
(12.3516484695876, 12.790644444444444, 12.333577777777778, 14.741558333333334, 13.45136785400857, 7.5, 9.610822222222222, 10.3902, 14.436770000000001, 9.148554074074074, 9.982058585858585, 11.54477037037037, 12.15),
(12.35911552421987, 12.753116872427984, 12.322714403292181, 14.731188580246913, 13.455085314817683, 7.5, 9.584390317114499, 10.327985185185186, 14.426104074074072, 9.121363347050755, 9.97541466517022, 11.530285871056241, 12.15),
(12.366295354982311, 12.714542386831276, 12.31151522633745, 14.72045586419753, 13.458656719953654, 7.5, 9.557234519486807, 10.264525925925927, 14.415091481481479, 9.09349048010974, 9.968513954358398, 11.515353635116599, 12.15),
(12.37318700688266, 12.674999999999999, 12.299999999999999, 14.709375, 13.462081849155954, 7.5, 9.529411764705882, 10.2, 14.403749999999999, 9.065, 9.961363636363636, 11.499999999999998, 12.15),
(12.379789524928656, 12.634568724279836, 12.288188477366253, 14.697960802469135, 13.465360482164058, 7.5, 9.500978988138465, 10.134585185185186, 14.392097407407405, 9.035956433470506, 9.953970894126448, 11.484251303155007, 12.15),
(12.386101954128042, 12.59332757201646, 12.276100411522634, 14.686228086419751, 13.46849239871744, 7.5, 9.471993125151295, 10.068459259259258, 14.380151481481482, 9.006424307270233, 9.946342910587354, 11.468133882030179, 12.15),
(12.392123339488554, 12.551355555555554, 12.263755555555555, 14.674191666666667, 13.471477378555573, 7.5, 9.442511111111111, 10.001800000000001, 14.367930000000001, 8.976468148148147, 9.938486868686867, 11.451674074074074, 12.15),
(12.397852726017943, 12.508731687242797, 12.251173662551441, 14.661866358024692, 13.474315201417928, 7.5, 9.412589881384651, 9.934785185185184, 14.355450740740741, 8.946152482853224, 9.930409951365506, 11.434898216735254, 12.15),
(12.403289158723938, 12.46553497942387, 12.23837448559671, 14.649266975308642, 13.477005647043978, 7.5, 9.38228637133866, 9.867592592592592, 14.342731481481481, 8.91554183813443, 9.922119341563786, 11.417832647462278, 12.15),
(12.408431682614292, 12.421844444444444, 12.225377777777776, 14.636408333333332, 13.479548495173196, 7.5, 9.351657516339868, 9.8004, 14.329790000000001, 8.88470074074074, 9.913622222222223, 11.400503703703704, 12.15),
(12.413279342696734, 12.377739094650208, 12.21220329218107, 14.62330524691358, 13.481943525545056, 7.5, 9.320760251755022, 9.733385185185183, 14.316644074074073, 8.853693717421125, 9.904925776281331, 11.382937722908094, 12.15),
(12.417831183979011, 12.333297942386832, 12.198870781893005, 14.609972530864196, 13.484190517899036, 7.5, 9.28965151295086, 9.666725925925926, 14.303311481481483, 8.822585294924554, 9.89603718668163, 11.365161042524004, 12.15),
(12.42208625146886, 12.2886, 12.185399999999998, 14.596425, 13.486289251974602, 7.5, 9.258388235294117, 9.600599999999998, 14.28981, 8.79144, 9.886963636363634, 11.347199999999999, 12.15),
(12.426043590174027, 12.24372427983539, 12.171810699588478, 14.5826774691358, 13.488239507511228, 7.5, 9.227027354151536, 9.535185185185185, 14.276157407407407, 8.760322359396433, 9.877712308267864, 11.329080932784636, 12.15),
(12.429702245102245, 12.198749794238683, 12.158122633744856, 14.568744753086419, 13.49004106424839, 7.5, 9.195625804889858, 9.470659259259259, 14.262371481481482, 8.729296899862826, 9.868290385334829, 11.310830178326475, 12.15),
(12.433061261261258, 12.153755555555556, 12.144355555555556, 14.554641666666665, 13.49169370192556, 7.5, 9.164240522875817, 9.407200000000001, 14.24847, 8.698428148148148, 9.85870505050505, 11.292474074074073, 12.15),
(12.436119683658815, 12.108820576131688, 12.130529218106995, 14.540383024691355, 13.493197200282209, 7.5, 9.132928443476155, 9.344985185185184, 14.23447074074074, 8.667780631001373, 9.848963486719043, 11.274038957475994, 12.15),
(12.438876557302644, 12.064023868312757, 12.116663374485597, 14.525983641975307, 13.494551339057814, 7.5, 9.101746502057614, 9.284192592592593, 14.220391481481482, 8.637418875171468, 9.839072876917319, 11.255551165980796, 12.15),
(12.441330927200491, 12.019444444444444, 12.102777777777776, 14.511458333333334, 13.495755897991843, 7.5, 9.070751633986927, 9.225, 14.20625, 8.607407407407408, 9.829040404040404, 11.237037037037037, 12.15),
(12.443481838360098, 11.975161316872429, 12.08889218106996, 14.496821913580245, 13.496810656823774, 7.5, 9.040000774630839, 9.167585185185185, 14.192064074074073, 8.577810754458161, 9.818873251028807, 11.218522908093279, 12.15),
(12.445328335789204, 11.931253497942386, 12.075026337448561, 14.482089197530865, 13.497715395293081, 7.5, 9.009550859356088, 9.112125925925925, 14.177851481481481, 8.548693443072702, 9.808578600823045, 11.20003511659808, 12.15),
(12.44686946449555, 11.887799999999999, 12.0612, 14.467275, 13.498469893139227, 7.5, 8.979458823529411, 9.0588, 14.16363, 8.520119999999999, 9.798163636363636, 11.1816, 12.15),
(12.448104269486876, 11.844879835390946, 12.047432921810698, 14.452394135802468, 13.499073930101698, 7.5, 8.94978160251755, 9.007785185185186, 14.149417407407407, 8.492154951989026, 9.787635540591094, 11.1632438957476, 12.15),
(12.449031795770926, 11.802572016460903, 12.033744855967079, 14.437461419753085, 13.49952728591996, 7.5, 8.920576131687243, 8.959259259259259, 14.135231481481481, 8.464862825788751, 9.777001496445942, 11.144993141289435, 12.15),
(12.449651088355436, 11.760955555555556, 12.020155555555556, 14.422491666666666, 13.499829740333487, 7.5, 8.891899346405228, 8.913400000000001, 14.12109, 8.438308148148147, 9.766268686868687, 11.126874074074076, 12.15),
(12.44996119224815, 11.720109465020576, 12.00668477366255, 14.407499691358023, 13.499981073081754, 7.5, 8.863808182038246, 8.870385185185187, 14.10701074074074, 8.412555445816187, 9.755444294799851, 11.108913031550067, 12.15),
(12.44974993737699, 11.679898367184387, 11.993287139917694, 14.392370088566828, 13.499853546356814, 7.49986081390032, 8.836218233795575, 8.830012620027434, 14.092905418381346, 8.3875445299766, 9.74434318624845, 11.09103602627969, 12.149850180041152),
(12.447770048309177, 11.639094623655915, 11.979586111111109, 14.376340217391302, 13.498692810457515, 7.49876049382716, 8.808321817615935, 8.790118518518518, 14.078157407407408, 8.362567668845314, 9.731835406698563, 11.072662768031188, 12.148663194444444),
(12.443862945070673, 11.597510951812026, 11.965522119341562, 14.35930454911433, 13.49639917695473, 7.496593507087334, 8.779992161473643, 8.75034293552812, 14.062683470507546, 8.33750342935528, 9.717778663831295, 11.05370731355137, 12.14631880144033),
(12.438083592771514, 11.555172202309835, 11.951100102880657, 14.341288204508858, 13.493001694504963, 7.49339497027892, 8.751241991446784, 8.710699039780522, 14.046506652949246, 8.312352431211167, 9.702224844940634, 11.034183524655257, 12.142847865226338),
(12.430486956521738, 11.51210322580645, 11.936324999999998, 14.322316304347826, 13.488529411764706, 7.4892, 8.722084033613445, 8.671199999999999, 14.02965, 8.287115294117646, 9.685225837320575, 11.014105263157894, 12.13828125),
(12.421128001431383, 11.46832887295898, 11.921201748971193, 14.302413969404187, 13.48301137739046, 7.48404371284865, 8.69253101405171, 8.631858984910837, 14.012136556927299, 8.261792637779392, 9.666833528265105, 10.993486390874303, 12.132649819958848),
(12.410061692610485, 11.423873994424532, 11.905735288065841, 14.281606320450885, 13.47647664003873, 7.477961225422954, 8.662595658839667, 8.59268916323731, 13.993989368998628, 8.236385081901073, 9.647099805068226, 10.972340769619521, 12.125984439300412),
(12.397342995169081, 11.378763440860213, 11.889930555555553, 14.25991847826087, 13.468954248366014, 7.470987654320988, 8.6322906940554, 8.553703703703704, 13.97523148148148, 8.210893246187362, 9.626076555023921, 10.950682261208575, 12.118315972222222),
(12.383026874217212, 11.33302206292314, 11.873792489711933, 14.237375563607086, 13.460473251028805, 7.463158116140832, 8.601628845776993, 8.514915775034293, 13.955885939643347, 8.185317750342934, 9.60381566542619, 10.928524727456498, 12.10967528292181),
(12.367168294864912, 11.286674711270411, 11.857326028806582, 14.214002697262478, 13.451062696683609, 7.454507727480566, 8.570622840082535, 8.476338545953361, 13.935975788751714, 8.15965921407246, 9.580369023569023, 10.905882030178327, 12.10009323559671),
(12.349822222222222, 11.23974623655914, 11.84053611111111, 14.189824999999999, 13.440751633986928, 7.445071604938271, 8.53928540305011, 8.437985185185186, 13.915524074074073, 8.133918257080609, 9.55578851674641, 10.882768031189086, 12.089600694444444),
(12.331043621399177, 11.192261489446436, 11.823427674897118, 14.164867592592591, 13.429569111595256, 7.434884865112025, 8.5076292607578, 8.399868861454047, 13.894553840877913, 8.108095499072055, 9.530126032252346, 10.859196592303805, 12.07822852366255),
(12.310887457505816, 11.144245320589407, 11.806005658436213, 14.139155595813206, 13.417544178165095, 7.423982624599908, 8.475667139283697, 8.362002743484226, 13.873088134430727, 8.082191559751472, 9.503433457380826, 10.835181575337522, 12.066007587448558),
(12.289408695652174, 11.09572258064516, 11.788274999999999, 14.112714130434783, 13.40470588235294, 7.412399999999999, 8.443411764705882, 8.3244, 13.851149999999999, 8.05620705882353, 9.475762679425838, 10.810736842105262, 12.052968749999998),
(12.26666230094829, 11.046718120270809, 11.770240637860082, 14.085568317230273, 13.391083272815298, 7.40017210791038, 8.410875863102444, 8.28707379972565, 13.828762482853223, 8.030142615992899, 9.447165585681375, 10.785876254422064, 12.039142875514404),
(12.242703238504205, 10.997256790123457, 11.751907510288065, 14.057743276972623, 13.376705398208665, 7.387334064929126, 8.378072160551463, 8.250037311385459, 13.805948628257887, 8.003998850964253, 9.417694063441433, 10.760613674102954, 12.0245608281893),
(12.21758647342995, 10.947363440860215, 11.733280555555554, 14.029264130434782, 13.361601307189543, 7.373920987654321, 8.345013383131029, 8.213303703703703, 13.78273148148148, 7.977776383442266, 9.3874, 10.734962962962962, 12.009253472222222),
(12.191366970835569, 10.897062923138192, 11.714364711934154, 14.000155998389696, 13.345800048414427, 7.359967992684042, 8.311712256919229, 8.176886145404664, 13.759134087791493, 7.951475833131606, 9.356335282651072, 10.708937982817124, 11.9932516718107),
(12.164099695831096, 10.846380087614497, 11.695164917695474, 13.970444001610307, 13.32933067053982, 7.34551019661637, 8.278181507994145, 8.14079780521262, 13.73517949245542, 7.925097819736949, 9.32455179868864, 10.682552595480471, 11.976586291152262),
(12.135839613526569, 10.795339784946236, 11.67568611111111, 13.940153260869563, 13.312222222222223, 7.330582716049382, 8.244433862433862, 8.10505185185185, 13.710890740740743, 7.8986429629629615, 9.292101435406698, 10.655820662768031, 11.959288194444444),
(12.106641689032028, 10.74396686579052, 11.655933230452675, 13.90930889694042, 13.29450375211813, 7.315220667581161, 8.210482046316468, 8.069661454046638, 13.686290877914953, 7.8721118825143215, 9.259036080099238, 10.628756046494837, 11.941388245884776),
(12.076560887457505, 10.69228618080446, 11.63591121399177, 13.877936030595812, 13.276204308884047, 7.299459167809785, 8.176338785720048, 8.034639780521262, 13.661402949245542, 7.845505198095699, 9.225407620060253, 10.601372608475922, 11.922917309670781),
(12.045652173913043, 10.640322580645162, 11.615625, 13.846059782608696, 13.257352941176471, 7.283333333333333, 8.142016806722689, 7.999999999999999, 13.636250000000002, 7.818823529411764, 9.191267942583732, 10.573684210526315, 11.90390625),
(12.013970513508676, 10.588100915969731, 11.59507952674897, 13.813705273752015, 13.237978697651899, 7.266878280749885, 8.107528835402473, 7.965755281207133, 13.610855075445818, 7.79206749616719, 9.15666893496367, 10.54570471446105, 11.884385931069957),
(11.981570871354446, 10.535646037435285, 11.574279732510288, 13.78089762479871, 13.218110626966835, 7.250129126657521, 8.07288759783749, 7.9319187928669415, 13.585241220850481, 7.7652377180666505, 9.121662484494063, 10.517447982095156, 11.864387217078187),
(11.948508212560386, 10.482982795698925, 11.553230555555555, 13.74766195652174, 13.197777777777778, 7.2331209876543205, 8.03810582010582, 7.898503703703704, 13.55943148148148, 7.738334814814813, 9.0863004784689, 10.488927875243665, 11.84394097222222),
(11.914837502236535, 10.43013604141776, 11.531936934156379, 13.714023389694042, 13.177009198741224, 7.215888980338362, 8.003196228285553, 7.865523182441701, 13.53344890260631, 7.7113594061163555, 9.050634804182172, 10.460158255721609, 11.823078060699588),
(11.880613705492932, 10.377130625248904, 11.510403806584362, 13.680007045088566, 13.155833938513677, 7.198468221307727, 7.968171548454772, 7.832990397805213, 13.507316529492455, 7.684312111675945, 9.014717348927874, 10.431152985344015, 11.801829346707818),
(11.845891787439614, 10.323991397849465, 11.488636111111111, 13.645638043478261, 13.134281045751633, 7.180893827160493, 7.933044506691564, 7.800918518518519, 13.481057407407405, 7.657193551198256, 8.9786, 10.401925925925926, 11.780225694444445),
(11.810726713186616, 10.270743209876544, 11.466638786008229, 13.610941505636069, 13.112379569111596, 7.163200914494741, 7.897827829074016, 7.769320713305898, 13.454694581618655, 7.63000434438796, 8.942334644692538, 10.372490939282363, 11.758297968106996),
(11.775173447843981, 10.217410911987256, 11.444416769547324, 13.575942552334944, 13.090158557250062, 7.145424599908551, 7.86253424168021, 7.738210150891632, 13.428251097393689, 7.602745110949729, 8.905973170299486, 10.342861887228358, 11.736077031893004),
(11.739286956521738, 10.16401935483871, 11.421975, 13.540666304347825, 13.06764705882353, 7.1276, 7.827176470588236, 7.707599999999999, 13.40175, 7.575416470588234, 8.869567464114832, 10.313052631578946, 11.71359375),
(11.703122204329933, 10.110593389088011, 11.39931841563786, 13.505137882447665, 13.044874122488501, 7.109762231367169, 7.791767241876174, 7.677503429355281, 13.375214334705076, 7.548019043008149, 8.833169413432572, 10.28307703414916, 11.690878986625515),
(11.6667341563786, 10.057157865392274, 11.376451954732511, 13.469382407407409, 13.021868796901476, 7.091946410608139, 7.756319281622114, 7.647933607681755, 13.348667146776405, 7.5205534479141445, 8.796830905546694, 10.252948956754024, 11.667963605967076),
(11.630177777777778, 10.003737634408603, 11.353380555555555, 13.433425, 12.998660130718955, 7.074187654320988, 7.720845315904139, 7.618903703703703, 13.32213148148148, 7.4930203050108934, 8.760603827751195, 10.222682261208577, 11.644878472222222),
(11.593508033637502, 9.950357546794105, 11.3301091563786, 13.39729078099839, 12.975277172597435, 7.056521079103795, 7.685358070800336, 7.590426886145404, 13.295630384087792, 7.465420234003066, 8.724540067340067, 10.192290809327847, 11.621654449588474),
(11.556779889067812, 9.897042453205893, 11.30664269547325, 13.361004871175522, 12.951748971193416, 7.03898180155464, 7.649870272388791, 7.562516323731138, 13.269186899862826, 7.437753854595336, 8.6886915116073, 10.161788462926864, 11.598322402263374),
(11.520048309178742, 9.843817204301073, 11.28298611111111, 13.324592391304348, 12.928104575163397, 7.021604938271605, 7.614394646747589, 7.535185185185185, 13.242824074074074, 7.410021786492375, 8.653110047846889, 10.131189083820663, 11.574913194444443),
(11.483368259080336, 9.790706650736759, 11.259144341563784, 13.288078462157811, 12.904373033163884, 7.004425605852766, 7.578943919954813, 7.508446639231824, 13.216564951989024, 7.382224649398854, 8.617847563352825, 10.100506533824273, 11.551457690329217),
(11.446794703882626, 9.737735643170053, 11.235122325102882, 13.251488204508856, 12.880583393851365, 6.987478920896206, 7.543530818088553, 7.482313854595337, 13.190432578875171, 7.354363063019446, 8.582955945419101, 10.069754674752724, 11.527986754115226),
(11.410382608695652, 9.684929032258065, 11.210925000000001, 13.214846739130435, 12.856764705882352, 6.9708, 7.508168067226889, 7.4568, 13.16445, 7.326437647058824, 8.548487081339712, 10.038947368421054, 11.504531250000001),
(11.374186938629451, 9.632311668657906, 11.18655730452675, 13.178179186795488, 12.832946017913338, 6.954423959762231, 7.472868393447913, 7.431918244170096, 13.138640260631002, 7.298449021221656, 8.514492858408648, 10.008098476644285, 11.48112204218107),
(11.338262658794058, 9.579908403026684, 11.162024176954734, 13.141510668276974, 12.809156378600823, 6.938385916780978, 7.437644522829707, 7.407681755829903, 13.113026406035663, 7.270397805212619, 8.4810251639199, 9.977221861237457, 11.457789994855966),
(11.302664734299517, 9.527744086021507, 11.137330555555558, 13.104866304347826, 12.785424836601306, 6.922720987654322, 7.402509181450357, 7.384103703703703, 13.087631481481482, 7.242284618736383, 8.448135885167463, 9.946331384015595, 11.434565972222222),
(11.26744813025586, 9.47584356829948, 11.112481378600824, 13.068271215780998, 12.76178044057129, 6.907464288980339, 7.367475095387949, 7.361197256515775, 13.062478532235938, 7.214110081497618, 8.41587690944533, 9.915440906793732, 11.411480838477365),
(11.232605068443652, 9.424318342543142, 11.087541393902482, 13.031800658990448, 12.738210816208445, 6.892643723057416, 7.332631156388123, 7.339023082536727, 13.037655373510344, 7.185965683935275, 8.38430868738344, 9.884631523805313, 11.388532681011865),
(11.197777077480078, 9.373676620230642, 11.062854810025941, 12.995747305532804, 12.71447202547959, 6.8782255302358815, 7.298421850092694, 7.317853511406144, 13.013542842855673, 7.158378201495339, 8.353493204535836, 9.85429460653557, 11.365530496992042),
(11.162861883604794, 9.323936638419655, 11.038436319248781, 12.960101406218135, 12.69048921346632, 6.864172214998518, 7.264871580229873, 7.297683185134451, 12.990149974402547, 7.131390393585692, 8.323385413712511, 9.824445099070621, 11.342407957992451),
(11.127815847885161, 9.275025937550042, 11.014238627980648, 12.924799380319685, 12.666226231660534, 6.8504506527445175, 7.231925781033471, 7.278456375478791, 12.967417607073395, 7.104952030139456, 8.293927117525778, 9.795027836984815, 11.319128711707068),
(11.092595331388527, 9.226872058061664, 10.990214442631183, 12.889777647110693, 12.641646931554133, 6.837027718873069, 7.199529886737303, 7.260117354196302, 12.945286579790643, 7.079012881089755, 8.26506011858794, 9.7659876558525, 11.295656405829869),
(11.057156695182252, 9.179402540394388, 10.96631646961004, 12.8549726258644, 12.61671516463901, 6.8238702887833655, 7.167629331575178, 7.2426103930441155, 12.923697731476722, 7.053522716369711, 8.236726219511308, 9.737269391248018, 11.271954688054828),
(11.02145630033369, 9.132544924988075, 10.942497415326867, 12.820320735854047, 12.591394782407065, 6.810945237874599, 7.136169549780907, 7.225879763779374, 12.902591901054052, 7.028431305912446, 8.208867222908193, 9.708817878745721, 11.247987206075917),
(10.985450507910194, 9.08622675228259, 10.918709986191313, 12.785758396352874, 12.565649636350196, 6.7982194415459585, 7.105095975588303, 7.209869738159211, 12.88190992744507, 7.003688419651087, 8.181424931390898, 9.680577953919956, 11.223717607587115),
(10.949095678979122, 9.040375562717795, 10.894906888613024, 12.75122202663412, 12.539443577960302, 6.7856597751966365, 7.0743540432311764, 7.1945245879407675, 12.861592649572199, 6.979243827518755, 8.154341147571738, 9.652494452345065, 11.199109540282393),
(10.912348174607825, 8.994918896733553, 10.871040829001652, 12.716648045971025, 12.512740458729281, 6.773233114225823, 7.043889186943341, 7.179788584881178, 12.841580906357867, 6.955047299448572, 8.127557674063022, 9.6245122095954, 11.174126651855724),
(10.875164355863662, 8.949784294769728, 10.847064513766842, 12.681972873636832, 12.485504130149028, 6.76090633403271, 7.013646840958606, 7.16560600073758, 12.821815536724504, 6.931048605373665, 8.101016313477052, 9.596576061245305, 11.148732590001085),
(10.837500583813984, 8.904899297266184, 10.822930649318243, 12.647132928904783, 12.457698443711445, 6.748646310016486, 6.983572439510783, 7.151921107267111, 12.802237379594539, 6.9071975152271525, 8.074658868426143, 9.56863084286913, 11.122891002412453),
(10.79931321952615, 8.860191444662783, 10.798591942065508, 12.612064631048112, 12.429287250908427, 6.736419917576347, 6.953611416833687, 7.138678176226909, 12.78278727389039, 6.88344379894216, 8.048427141522602, 9.540621390041217, 11.096565536783794),
(10.760558624067514, 8.815588277399392, 10.774001098418278, 12.576704399340064, 12.400234403231872, 6.724194032111481, 6.923709207161124, 7.12582147937411, 12.763406058534501, 6.859737226451811, 8.022262935378736, 9.51249253833592, 11.069719840809094),
(10.721193158505432, 8.771017335915868, 10.749110824786205, 12.540988653053878, 12.370503752173677, 6.711935529021078, 6.893811244726913, 7.113295288465854, 12.744034572449289, 6.836027567689229, 7.9961080526068535, 9.484189123327578, 11.042317562182317),
(10.681173183907255, 8.72640616065208, 10.72387382757894, 12.504853811462798, 12.340059149225747, 6.699611283704333, 6.863862963764858, 7.101043875259275, 12.72461365455718, 6.8122645925875345, 7.969904295819269, 9.455655980590546, 11.014322348597444),
(10.640455061340337, 8.681682292047888, 10.698242813206127, 12.468236293840057, 12.308864445879973, 6.687188171560433, 6.833809798508775, 7.089011511511512, 12.705084143780608, 6.788398071079854, 7.943593467628284, 9.426837945699162, 10.985697847748446),
(10.598995151872039, 8.63677327054316, 10.672170488077414, 12.431072519458903, 12.276883493628256, 6.6746330679885695, 6.803597183192475, 7.077142468979701, 12.685386879042001, 6.764377773099308, 7.9171173706462135, 9.397679854227782, 10.956407707329298),
(10.556749816569713, 8.591606636577751, 10.645609558602457, 12.39329890759257, 12.244080143962494, 6.661912848387936, 6.773170552049771, 7.06538101942098, 12.665462699263783, 6.740153468579022, 7.890417807485361, 9.36812654175075, 10.926415575033973),
(10.51367541650071, 8.546109930591532, 10.618512731190895, 12.354851877514305, 12.210418248374584, 6.648994388157723, 6.7424753393144705, 7.053671434592488, 12.645252443368385, 6.715674927452118, 7.863436580758037, 9.33812284384241, 10.89568509855645),
(10.469728312732395, 8.500210693024362, 10.59083271225238, 12.315667848497341, 12.175861658356423, 6.63584456269712, 6.711456979220387, 7.041957986251359, 12.624696950278231, 6.690891919651718, 7.8361154930765515, 9.307613596077111, 10.864179925590703),
(10.424864866332113, 8.453836464316106, 10.562522208196564, 12.275683239814922, 12.14037422539991, 6.622430247405318, 6.6800609060013345, 7.0301849461547326, 12.603737058915753, 6.665754215110948, 7.808396347053214, 9.2765436340292, 10.831863703830699),
(10.379041438367224, 8.406914784906629, 10.53353392543309, 12.234834470740294, 12.103919800996945, 6.60871831768151, 6.648232553891121, 7.018296586059743, 12.582313608203375, 6.640211583762931, 7.78022094530033, 9.244857793273022, 10.798700080970423),
(10.332214389905081, 8.35937319523579, 10.50382057037161, 12.193057960546687, 12.066462236639419, 6.594675648924887, 6.615917357123561, 7.0062371777235315, 12.560367437063528, 6.6142137955407865, 7.751531090430213, 9.212500909382928, 10.764652704703844),
(10.28434008201304, 8.311139235743456, 10.473334849421772, 12.150290128507349, 12.027965383819241, 6.580269116534637, 6.583060749932466, 6.993950992903235, 12.537839384418639, 6.587710620377641, 7.722268585055167, 9.179417817933263, 10.729685222724932),
(10.235374875758456, 8.26214044686949, 10.442029468993221, 12.106467393895516, 11.988393094028302, 6.565465595909957, 6.5496081665516455, 6.981382303355987, 12.514670289191137, 6.560651828206615, 7.692375231787501, 9.145553354498373, 10.693761282727667),
(10.185275132208682, 8.212304369053752, 10.409857135495608, 12.06152617598443, 11.947709218758497, 6.550231962450032, 6.515505041214911, 6.968475380838929, 12.490800990303445, 6.532987188960836, 7.661792833239527, 9.110852354652607, 10.656844532406023),
(10.133997212431076, 8.16155854273611, 10.376770555338585, 12.015402894047332, 11.905877609501735, 6.534535091554055, 6.480696808156076, 6.955174497109195, 12.466172326677999, 6.5046664725734225, 7.630463192023552, 9.07525965397031, 10.618898619453978),
(10.081497477492995, 8.109830508356424, 10.342722434931792, 11.968033967357464, 11.862862117749904, 6.518341858621218, 6.445128901608954, 6.9414239239239235, 12.440725137237216, 6.4756394489775015, 7.598328110751885, 9.03872008802583, 10.579887191565495),
(10.027732288461786, 8.057047806354559, 10.307665480684884, 11.919355815188064, 11.818626594994903, 6.501619139050712, 6.408746755807351, 6.927167933040253, 12.41440026090353, 6.445855888106193, 7.565329392036836, 9.001178492393512, 10.539773896434559),
(9.972658006404808, 8.003137977170377, 10.27155239900751, 11.86930485681237, 11.773134892728635, 6.484333808241727, 6.371495804985082, 6.912350796215319, 12.387138536599375, 6.415265559892623, 7.531408838490711, 8.962579702647707, 10.49852238175514),
(9.916230992389421, 7.948028561243743, 10.234335896309313, 11.817817511503627, 11.726350862442994, 6.466452741593456, 6.333321483375959, 6.896916785206259, 12.358880803247171, 6.383818234269912, 7.496508252725821, 8.922868554362758, 10.456096295221217),
(9.858407607482972, 7.891647099014518, 10.195968678999947, 11.764830198535073, 11.67823835562988, 6.4479428145050885, 6.294169225213792, 6.880810171770211, 12.329567899769344, 6.351463681171185, 7.460569437354474, 8.881989883113016, 10.41245928452676),
(9.79914421275282, 7.83392113092257, 10.156403453489059, 11.71027933717995, 11.62876122378119, 6.428770902375816, 6.253984464732396, 6.863975227664311, 12.299140665088327, 6.318151670529565, 7.423534194988978, 8.839888524472823, 10.367574997365741),
(9.73839716926632, 7.774778197407756, 10.115592926186292, 11.654101346711496, 11.577883318388821, 6.4089038806048295, 6.212712636165577, 6.846356224645698, 12.267539938126548, 6.283831972278175, 7.385344328241643, 8.796509314016532, 10.321407081432142),
(9.676122838090825, 7.714145838909944, 10.0734898035013, 11.596232646402955, 11.525568490944673, 6.38830862459132, 6.170299173747152, 6.827897434471509, 12.234706557806435, 6.248454356350137, 7.345941639724779, 8.751797087318483, 10.27391918441993),
(9.612277580293695, 7.651951595868995, 10.030046791843732, 11.536609655527563, 11.471780592940645, 6.366952009734479, 6.126689511710929, 6.80854312889888, 12.200581363050405, 6.211968592678576, 7.3052679320506915, 8.705696679953029, 10.225074954023084),
(9.546817756942277, 7.588123008724775, 9.985216597623232, 11.475168793358565, 11.416483475868631, 6.344800911433499, 6.08182908429072, 6.788237579684948, 12.165105192780901, 6.174324451196612, 7.2632650078316905, 8.658152927494514, 10.174838037935576),
(9.47969972910393, 7.522587617917144, 9.93895192724945, 11.411846479169196, 11.359640991220532, 6.321822205087566, 6.03566332572034, 6.7669250585868514, 12.128218885920345, 6.135471701837373, 7.2198746696800855, 8.609110665517285, 10.123172083851381),
(9.41087985784601, 7.455272963885967, 9.89120548713204, 11.346579132232701, 11.301216990488243, 6.297982766095876, 5.9881376702335976, 6.744549837361729, 12.089863281391164, 6.095360114533979, 7.175038720208185, 8.558514729595691, 10.070040739464476),
(9.340314504235872, 7.386106587071107, 9.841929983680641, 11.279303171822319, 11.241175325163667, 6.273249469857618, 5.939197552064303, 6.721056187766714, 12.049979218115787, 6.053939459219555, 7.128698962028299, 8.506309955304076, 10.015407652468832),
(9.267960029340873, 7.315016027912428, 9.79107812330491, 11.209955017211291, 11.179479846738696, 6.247589191771985, 5.888788405446274, 6.696388381558948, 12.008507535016639, 6.011159505827223, 7.080797197752734, 8.45244117821679, 9.959236470558428),
(9.193772794228362, 7.241928826849794, 9.73860261241449, 11.138471087672853, 11.116094406705235, 6.220968807238165, 5.836855664613313, 6.670490690495563, 11.965389071016153, 5.966970024290105, 7.0312752299938, 8.396853233908178, 9.901490841427231),
(9.117709159965697, 7.166772524323065, 9.684456157419032, 11.06478780248025, 11.050982856555176, 6.193355191655353, 5.7833447637992395, 6.643307386333702, 11.920564665036752, 5.921320784541327, 6.980074861363805, 8.339490957952586, 9.842134412769221),
(9.039725487620235, 7.089474660772107, 9.628591464728181, 10.988841580906724, 10.984109047780422, 6.164715220422736, 5.728201137237862, 6.614782740830498, 11.873975156000865, 5.874161556514009, 6.927137894475059, 8.280299185924363, 9.781130832278372),
(8.957617135686286, 7.008543744926709, 9.568310344682827, 10.907723497981491, 10.912417327045196, 6.133229371580532, 5.6701280651134285, 6.582956342819247, 11.821994509918916, 5.824039099549372, 6.870714903046731, 8.217119477033206, 9.715783031298415),
(8.858744120374082, 6.915678383519373, 9.488085382083584, 10.804772590546143, 10.818229571737954, 6.088427577608523, 5.601855316062859, 6.536656239317259, 11.743712713466573, 5.762737192918494, 6.800900322742793, 8.13763502841973, 9.630513176304232),
(8.741846513885172, 6.810116074248857, 9.386305149547066, 10.67829301249063, 10.699704157616154, 6.0292095552572205, 5.5226924980605405, 6.4747190274328155, 11.636910272674381, 5.689446782235472, 6.716711410331447, 8.040602338665416, 9.523704730672296),
(8.607866465503152, 6.692545041696563, 9.26405636629237, 10.529487004508074, 10.558071749138534, 5.956292689884377, 5.433217735208252, 6.397920639731736, 11.50299572039882, 5.604789831805125, 6.618889985519648, 7.926920962689085, 9.396448853782916),
(8.457746124511628, 6.563653510443886, 9.122425751538595, 10.359556807291591, 10.394563010763845, 5.870394366847746, 5.334009151607771, 6.307037008779842, 11.343377589496363, 5.509388305932277, 6.508177868014344, 7.797490455409552, 9.2498367050164),
(8.292427640194196, 6.424129705072228, 8.962500024504841, 10.16970466153432, 10.210408606950825, 5.772231971505087, 5.22564487136088, 6.20284406714295, 11.159464412823487, 5.40386416892175, 6.38531687752249, 7.653210371745638, 9.084959443753055),
(8.11285316183446, 6.2746618501629845, 8.785365904410211, 9.961132807929381, 10.006839202158226, 5.662522889214155, 5.108703018569359, 6.086117747386882, 10.952664723236667, 5.2888393850783615, 6.251048833751035, 7.494980266616163, 8.902908229373192),
(7.9199648387160195, 6.115938170297558, 8.592110110473802, 9.735043487169902, 9.785085460844789, 5.541984505332703, 4.983761717334986, 5.957633982077455, 10.724387053592375, 5.164935918706936, 6.106115556406933, 7.323699694939943, 8.704774221257123),
(7.714704820122476, 5.948646890057345, 8.383819361914712, 9.492638939949002, 9.546378047469256, 5.41133420521849, 4.851399091759543, 5.818168703780493, 10.476039936747087, 5.0327757341122945, 5.9512588651971345, 7.140268211635801, 8.491648578785155),
(7.498015255337426, 5.773476234023744, 8.161580377952045, 9.235121406959811, 9.291947626490375, 5.27128937422927, 4.712193265944809, 5.668497845061811, 10.209031905557278, 4.892980795599256, 5.787220579828592, 6.94558537162255, 8.264622461337595),
(7.2708382936444735, 5.591114426778154, 7.926479877804897, 8.963693128895455, 9.02302486236689, 5.122567397722799, 4.5667223639925645, 5.509397338487231, 9.924771492879426, 4.746173067472646, 5.614742520008257, 6.740550729819013, 8.024787028294753),
(7.034116084327218, 5.402249692901975, 7.67960458069237, 8.67955634644906, 8.740840419557543, 4.965885661056833, 4.4155645100045895, 5.341643116622574, 9.624667231570005, 4.592974514037284, 5.434566505443081, 6.526063841144007, 7.773233439036942),
(6.78879077666926, 5.207570256976605, 7.422041205833562, 8.383913300313743, 8.44662496252108, 4.8019615495891275, 4.259297828082663, 5.166011112033656, 9.310127654485486, 4.434007099597989, 5.247434355840019, 6.3030242605163505, 7.5110528529444665),
(6.5358045199542, 5.007764343583441, 7.154876472447573, 8.077966231182643, 8.141609155716246, 4.631512448677438, 4.098500442328566, 4.983277257286299, 8.982561294482347, 4.269892788459586, 5.054087890906017, 6.072331542854863, 7.239336429397638),
(6.276099463465638, 4.803520177303883, 6.879197099753504, 7.762917379748876, 7.827023663601784, 4.45525574367952, 3.9337504768440783, 4.794217484946325, 8.643376684417062, 4.101253544926895, 4.855268930348032, 5.834885243078365, 6.959175327776763),
(6.010617756487176, 4.59552598271933, 6.596089806970453, 7.43996898670557, 7.504099150636442, 4.27390881995313, 3.7656260557309795, 4.599607727579548, 8.293982357146106, 3.9287113333047374, 4.651719293873013, 5.59158491610567, 6.671660707462155),
(5.740301548302412, 4.384469984411181, 6.306641313317521, 7.110323292745848, 7.174066281278959, 4.088189062856022, 3.5947053030910503, 4.400223917751792, 7.935786845525956, 3.752888117897936, 4.444180801187913, 5.3433301168556016, 6.37788372783412),
(5.466092988194946, 4.171040406960834, 6.01193833801381, 6.775182538562841, 6.838155719988083, 3.898813857745954, 3.421566343026069, 4.196841988028875, 7.570198682413086, 3.574405863011309, 4.233395271999683, 5.091020400246977, 6.078935548272969),
(5.188934225448382, 3.9559254749496873, 5.713067600278413, 6.43574896484967, 6.497598131222556, 3.7065005899806795, 3.2467872996378175, 3.9902378709766184, 7.1986264006639695, 3.3938865329496806, 4.020104526015276, 4.835555321198615, 5.7759073281590085),
(4.909767409346319, 3.7398134129591414, 5.411115819330436, 6.09322481229946, 6.1536241794411275, 3.511966644917956, 3.0709462970280748, 3.781187499160839, 6.822478533135084, 3.2119520920178695, 3.8050503829416424, 4.5778344346293345, 5.4698902268725496),
(4.629534689172356, 3.5233924455705936, 5.107169714388976, 5.748812321605339, 5.807464529102536, 3.3159294079155393, 2.894621459298621, 3.5704668051473587, 6.443163612682903, 3.0292245045207, 3.588974662485735, 4.318757295457952, 5.161975403793902),
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
)
passenger_arriving_acc = (
(6, 7, 10, 5, 3, 2, 1, 1, 4, 1, 1, 0, 0, 4, 6, 6, 2, 4, 0, 3, 0, 1, 2, 0, 0, 0),
(14, 15, 16, 8, 5, 4, 3, 5, 7, 1, 1, 1, 0, 13, 14, 13, 3, 5, 5, 6, 0, 3, 4, 2, 1, 0),
(22, 23, 28, 11, 8, 6, 4, 6, 7, 2, 3, 1, 0, 18, 21, 15, 5, 13, 8, 9, 2, 5, 4, 3, 1, 0),
(28, 27, 32, 20, 12, 9, 4, 7, 10, 4, 3, 2, 0, 28, 27, 19, 12, 22, 12, 11, 2, 6, 4, 4, 2, 0),
(30, 33, 39, 30, 18, 11, 10, 11, 12, 6, 5, 3, 0, 36, 33, 21, 15, 27, 15, 15, 3, 6, 4, 4, 2, 0),
(36, 41, 49, 38, 22, 13, 14, 15, 16, 7, 6, 3, 0, 43, 39, 28, 19, 31, 18, 18, 5, 10, 7, 6, 2, 0),
(44, 46, 57, 51, 24, 17, 15, 20, 20, 12, 6, 3, 0, 56, 51, 33, 24, 38, 19, 20, 6, 12, 11, 9, 3, 0),
(52, 62, 66, 58, 27, 18, 18, 23, 25, 14, 6, 4, 0, 66, 56, 42, 28, 46, 27, 24, 9, 15, 14, 10, 3, 0),
(60, 71, 76, 68, 32, 23, 21, 26, 27, 15, 12, 6, 0, 74, 60, 47, 33, 53, 31, 29, 12, 21, 18, 10, 3, 0),
(67, 85, 84, 75, 36, 27, 25, 34, 32, 16, 13, 6, 0, 80, 69, 53, 37, 59, 37, 30, 15, 23, 22, 12, 5, 0),
(80, 95, 91, 83, 48, 30, 25, 35, 35, 16, 14, 8, 0, 87, 75, 58, 41, 64, 42, 33, 16, 29, 25, 14, 6, 0),
(86, 107, 103, 95, 55, 33, 31, 41, 36, 16, 17, 11, 0, 95, 83, 66, 50, 74, 50, 37, 18, 35, 31, 17, 6, 0),
(97, 121, 117, 102, 63, 36, 35, 42, 40, 18, 22, 11, 0, 107, 91, 71, 54, 84, 58, 41, 23, 40, 35, 18, 7, 0),
(109, 133, 121, 114, 69, 37, 37, 45, 43, 21, 23, 13, 0, 115, 97, 83, 60, 91, 61, 47, 26, 48, 41, 18, 8, 0),
(117, 138, 128, 120, 79, 38, 41, 52, 49, 22, 23, 13, 0, 127, 108, 93, 65, 96, 62, 50, 28, 52, 45, 20, 9, 0),
(130, 149, 136, 125, 89, 48, 45, 63, 53, 24, 24, 16, 0, 143, 117, 100, 73, 110, 66, 54, 31, 54, 48, 21, 10, 0),
(145, 163, 147, 132, 97, 52, 45, 73, 59, 26, 24, 16, 0, 153, 125, 105, 77, 121, 77, 62, 33, 57, 50, 23, 11, 0),
(154, 176, 157, 145, 104, 55, 49, 79, 63, 29, 26, 18, 0, 168, 136, 113, 82, 130, 85, 69, 35, 59, 54, 25, 12, 0),
(166, 185, 172, 158, 113, 60, 53, 81, 64, 29, 27, 20, 0, 178, 142, 122, 87, 140, 90, 76, 39, 61, 55, 25, 15, 0),
(173, 208, 187, 171, 120, 66, 62, 86, 67, 31, 28, 21, 0, 188, 151, 127, 94, 154, 100, 80, 43, 64, 58, 26, 15, 0),
(186, 222, 193, 176, 131, 73, 69, 90, 74, 32, 31, 22, 0, 199, 164, 140, 106, 160, 107, 83, 44, 67, 63, 27, 16, 0),
(199, 232, 211, 182, 144, 80, 78, 96, 82, 34, 34, 24, 0, 211, 181, 148, 118, 167, 116, 89, 51, 72, 67, 29, 16, 0),
(212, 239, 223, 194, 157, 87, 83, 97, 90, 35, 35, 25, 0, 227, 192, 152, 124, 182, 121, 96, 55, 77, 72, 32, 17, 0),
(221, 252, 229, 205, 165, 90, 91, 101, 97, 38, 36, 27, 0, 238, 203, 157, 130, 197, 125, 100, 58, 80, 76, 35, 17, 0),
(235, 264, 240, 213, 174, 92, 95, 103, 103, 39, 36, 30, 0, 252, 214, 164, 136, 213, 131, 105, 60, 83, 83, 37, 19, 0),
(245, 277, 244, 225, 184, 94, 96, 106, 107, 42, 36, 32, 0, 259, 223, 173, 147, 221, 139, 107, 61, 91, 86, 38, 19, 0),
(256, 286, 257, 236, 193, 98, 100, 111, 114, 42, 38, 36, 0, 277, 235, 180, 156, 235, 146, 110, 64, 96, 90, 41, 20, 0),
(267, 300, 268, 243, 201, 103, 105, 115, 119, 46, 40, 36, 0, 286, 242, 187, 164, 249, 152, 114, 66, 106, 92, 41, 24, 0),
(279, 305, 279, 254, 206, 107, 109, 121, 122, 48, 43, 38, 0, 301, 255, 198, 169, 260, 162, 118, 71, 109, 95, 43, 24, 0),
(287, 321, 285, 267, 219, 112, 112, 126, 130, 49, 46, 38, 0, 313, 263, 203, 176, 272, 166, 123, 75, 118, 99, 47, 25, 0),
(301, 332, 298, 282, 230, 112, 118, 130, 136, 52, 47, 39, 0, 323, 273, 211, 179, 286, 170, 126, 78, 127, 102, 49, 27, 0),
(310, 338, 309, 297, 242, 114, 119, 135, 141, 54, 47, 39, 0, 328, 279, 214, 184, 297, 177, 129, 79, 130, 107, 51, 28, 0),
(321, 348, 319, 310, 250, 118, 126, 139, 149, 57, 52, 40, 0, 338, 286, 224, 191, 308, 180, 134, 81, 134, 109, 54, 30, 0),
(334, 355, 327, 316, 264, 125, 130, 147, 161, 57, 54, 41, 0, 350, 293, 235, 196, 315, 183, 139, 83, 139, 110, 55, 31, 0),
(350, 368, 345, 329, 273, 132, 134, 149, 166, 59, 56, 42, 0, 366, 304, 247, 203, 325, 191, 142, 86, 147, 112, 57, 31, 0),
(360, 381, 358, 341, 282, 138, 138, 152, 169, 59, 58, 46, 0, 372, 315, 256, 209, 336, 195, 146, 88, 153, 114, 57, 32, 0),
(374, 398, 369, 351, 293, 139, 142, 161, 174, 62, 61, 47, 0, 384, 321, 261, 214, 347, 197, 151, 92, 157, 115, 62, 32, 0),
(383, 407, 375, 358, 298, 144, 144, 167, 179, 65, 61, 48, 0, 396, 330, 267, 221, 362, 205, 152, 94, 160, 122, 64, 32, 0),
(397, 415, 385, 367, 312, 147, 148, 171, 184, 67, 62, 49, 0, 405, 339, 275, 229, 370, 209, 157, 97, 162, 128, 65, 32, 0),
(407, 429, 394, 379, 320, 151, 149, 175, 189, 69, 63, 49, 0, 412, 349, 287, 234, 375, 217, 162, 98, 166, 131, 69, 33, 0),
(420, 437, 401, 385, 333, 157, 154, 177, 195, 72, 63, 50, 0, 428, 366, 293, 245, 384, 222, 167, 102, 171, 132, 70, 34, 0),
(429, 451, 412, 395, 339, 160, 156, 178, 203, 74, 64, 52, 0, 435, 376, 298, 253, 391, 228, 173, 109, 177, 133, 72, 36, 0),
(444, 460, 419, 412, 347, 168, 163, 181, 211, 76, 65, 53, 0, 444, 388, 308, 262, 403, 235, 182, 113, 182, 138, 75, 37, 0),
(458, 469, 428, 424, 356, 172, 169, 183, 220, 78, 65, 54, 0, 451, 402, 325, 269, 410, 241, 186, 115, 187, 142, 76, 39, 0),
(465, 480, 441, 433, 361, 177, 175, 185, 225, 78, 66, 55, 0, 461, 407, 334, 278, 420, 249, 191, 120, 194, 145, 78, 40, 0),
(475, 489, 451, 446, 376, 180, 180, 191, 231, 79, 68, 57, 0, 473, 417, 345, 285, 430, 251, 197, 125, 199, 147, 83, 41, 0),
(487, 498, 465, 456, 390, 183, 184, 196, 232, 83, 69, 57, 0, 481, 423, 354, 294, 442, 257, 201, 130, 206, 149, 85, 42, 0),
(502, 509, 484, 466, 399, 187, 189, 198, 239, 83, 72, 57, 0, 495, 438, 358, 298, 454, 264, 204, 135, 208, 151, 89, 42, 0),
(513, 516, 496, 475, 412, 189, 194, 203, 244, 84, 72, 60, 0, 512, 454, 364, 303, 461, 273, 209, 137, 211, 155, 91, 44, 0),
(530, 528, 507, 487, 422, 193, 201, 209, 250, 87, 73, 60, 0, 528, 466, 372, 310, 472, 280, 214, 141, 215, 160, 91, 45, 0),
(545, 539, 516, 504, 432, 202, 204, 215, 258, 92, 74, 60, 0, 545, 476, 377, 313, 477, 285, 218, 143, 217, 166, 93, 45, 0),
(553, 547, 520, 523, 442, 208, 207, 218, 263, 95, 76, 61, 0, 554, 490, 389, 320, 486, 288, 220, 143, 227, 167, 94, 45, 0),
(569, 557, 531, 531, 452, 211, 214, 219, 266, 98, 78, 61, 0, 568, 502, 398, 329, 495, 293, 222, 148, 227, 172, 94, 46, 0),
(584, 566, 538, 540, 459, 213, 222, 224, 270, 100, 81, 62, 0, 583, 515, 405, 334, 504, 300, 227, 152, 234, 175, 97, 47, 0),
(597, 572, 549, 553, 467, 216, 227, 227, 278, 102, 81, 62, 0, 593, 526, 411, 342, 513, 305, 231, 154, 239, 178, 98, 47, 0),
(606, 585, 562, 569, 471, 221, 231, 233, 280, 102, 84, 65, 0, 603, 544, 419, 351, 521, 309, 235, 157, 243, 180, 100, 47, 0),
(618, 597, 571, 578, 484, 222, 236, 237, 283, 104, 88, 65, 0, 613, 558, 425, 355, 535, 316, 243, 160, 252, 183, 102, 49, 0),
(635, 611, 579, 588, 495, 228, 241, 242, 287, 109, 88, 66, 0, 628, 568, 431, 361, 545, 324, 248, 162, 261, 190, 102, 50, 0),
(646, 624, 589, 601, 507, 232, 242, 245, 290, 110, 90, 67, 0, 637, 575, 442, 369, 552, 327, 250, 165, 267, 193, 104, 51, 0),
(656, 640, 599, 612, 517, 240, 251, 248, 294, 114, 92, 68, 0, 650, 587, 452, 376, 562, 336, 253, 172, 271, 197, 106, 52, 0),
(667, 646, 611, 622, 524, 248, 256, 250, 298, 117, 93, 68, 0, 664, 595, 460, 383, 573, 344, 256, 174, 273, 204, 106, 56, 0),
(681, 654, 621, 631, 538, 250, 257, 255, 304, 118, 95, 69, 0, 678, 611, 465, 393, 581, 349, 264, 177, 279, 204, 108, 56, 0),
(696, 665, 630, 638, 549, 256, 259, 259, 307, 119, 95, 72, 0, 684, 619, 468, 400, 594, 359, 269, 180, 284, 211, 109, 58, 0),
(711, 675, 635, 642, 555, 260, 263, 261, 312, 122, 97, 72, 0, 699, 627, 474, 403, 600, 365, 272, 185, 284, 216, 110, 58, 0),
(727, 679, 646, 647, 561, 264, 265, 263, 313, 125, 97, 73, 0, 708, 636, 477, 412, 604, 370, 273, 192, 290, 219, 112, 60, 0),
(741, 693, 652, 656, 569, 268, 272, 265, 319, 129, 98, 74, 0, 718, 643, 487, 419, 613, 375, 275, 195, 293, 222, 116, 60, 0),
(753, 705, 664, 667, 581, 273, 280, 269, 325, 129, 100, 75, 0, 729, 648, 493, 423, 623, 381, 276, 198, 299, 224, 117, 61, 0),
(760, 711, 678, 680, 592, 277, 283, 271, 332, 132, 104, 75, 0, 742, 656, 499, 426, 637, 383, 279, 199, 306, 230, 120, 63, 0),
(774, 723, 688, 687, 598, 283, 293, 278, 340, 135, 104, 76, 0, 752, 666, 505, 434, 650, 387, 285, 204, 310, 234, 120, 63, 0),
(791, 739, 693, 697, 608, 285, 300, 280, 347, 136, 107, 77, 0, 770, 679, 512, 441, 657, 390, 291, 209, 319, 235, 122, 63, 0),
(803, 748, 702, 712, 618, 288, 304, 283, 351, 139, 109, 78, 0, 780, 694, 523, 443, 666, 397, 300, 212, 325, 239, 123, 63, 0),
(812, 759, 708, 723, 634, 292, 306, 283, 356, 143, 110, 80, 0, 794, 706, 528, 448, 674, 402, 301, 217, 332, 245, 127, 63, 0),
(830, 766, 721, 739, 645, 298, 311, 285, 363, 145, 112, 80, 0, 808, 719, 534, 451, 683, 406, 306, 219, 335, 248, 127, 65, 0),
(841, 773, 731, 747, 654, 303, 318, 290, 366, 146, 113, 81, 0, 824, 725, 543, 460, 690, 411, 312, 223, 341, 253, 130, 66, 0),
(855, 779, 738, 756, 662, 305, 321, 293, 373, 147, 114, 82, 0, 836, 741, 552, 464, 702, 414, 316, 224, 346, 258, 131, 69, 0),
(865, 791, 748, 768, 680, 313, 324, 298, 377, 148, 115, 83, 0, 847, 748, 562, 469, 708, 418, 319, 227, 353, 263, 133, 69, 0),
(881, 804, 761, 772, 691, 318, 331, 299, 383, 150, 117, 84, 0, 862, 755, 566, 476, 717, 421, 322, 228, 357, 272, 135, 70, 0),
(896, 815, 773, 785, 703, 323, 335, 303, 383, 151, 118, 84, 0, 875, 763, 581, 482, 729, 424, 324, 237, 362, 273, 137, 72, 0),
(907, 821, 782, 794, 714, 325, 342, 305, 390, 154, 119, 85, 0, 886, 778, 590, 490, 737, 427, 329, 239, 364, 276, 139, 72, 0),
(914, 835, 792, 803, 715, 327, 347, 312, 393, 155, 122, 85, 0, 897, 793, 599, 499, 750, 433, 333, 243, 368, 278, 140, 72, 0),
(926, 843, 806, 807, 720, 329, 355, 313, 398, 158, 124, 85, 0, 906, 806, 603, 502, 761, 434, 337, 244, 371, 281, 142, 72, 0),
(942, 855, 810, 826, 730, 333, 359, 314, 401, 160, 124, 87, 0, 913, 814, 612, 506, 770, 440, 344, 252, 377, 282, 147, 74, 0),
(952, 865, 818, 833, 736, 336, 363, 317, 404, 162, 127, 88, 0, 922, 824, 619, 513, 779, 443, 347, 258, 382, 284, 151, 74, 0),
(963, 877, 829, 844, 740, 339, 363, 320, 409, 165, 129, 88, 0, 935, 834, 625, 520, 788, 447, 350, 259, 388, 287, 152, 75, 0),
(973, 885, 835, 856, 751, 342, 366, 325, 415, 168, 129, 91, 0, 951, 840, 632, 529, 800, 454, 352, 260, 392, 293, 154, 76, 0),
(984, 891, 844, 864, 759, 343, 369, 327, 421, 170, 130, 92, 0, 969, 851, 638, 540, 812, 462, 357, 262, 397, 297, 159, 76, 0),
(994, 902, 852, 869, 766, 345, 372, 328, 422, 175, 131, 92, 0, 985, 859, 647, 545, 823, 469, 358, 264, 405, 298, 160, 77, 0),
(1007, 910, 857, 880, 777, 350, 378, 329, 427, 176, 131, 95, 0, 995, 869, 654, 547, 832, 471, 361, 268, 409, 302, 162, 77, 0),
(1021, 923, 865, 889, 789, 355, 382, 336, 432, 178, 133, 95, 0, 1007, 883, 663, 553, 839, 475, 367, 270, 413, 307, 165, 78, 0),
(1031, 933, 870, 908, 800, 360, 384, 337, 437, 182, 133, 97, 0, 1019, 893, 674, 562, 849, 484, 372, 274, 414, 309, 170, 78, 0),
(1040, 948, 882, 911, 807, 362, 393, 338, 439, 183, 135, 97, 0, 1034, 903, 679, 568, 859, 488, 375, 280, 417, 311, 171, 80, 0),
(1053, 955, 886, 921, 817, 367, 395, 339, 444, 186, 136, 100, 0, 1046, 913, 684, 572, 867, 495, 379, 286, 417, 313, 173, 80, 0),
(1065, 966, 898, 928, 828, 371, 399, 342, 447, 188, 137, 100, 0, 1059, 925, 693, 580, 875, 500, 381, 289, 420, 316, 173, 81, 0),
(1072, 978, 903, 932, 839, 377, 401, 346, 452, 192, 139, 101, 0, 1067, 937, 704, 588, 882, 504, 387, 294, 426, 319, 179, 81, 0),
(1080, 991, 913, 945, 856, 378, 402, 347, 456, 193, 141, 101, 0, 1081, 949, 708, 592, 897, 507, 388, 297, 431, 325, 183, 81, 0),
(1090, 1001, 930, 953, 863, 382, 403, 350, 459, 193, 142, 102, 0, 1095, 959, 716, 597, 907, 508, 394, 299, 434, 331, 185, 83, 0),
(1100, 1010, 943, 964, 876, 384, 409, 354, 460, 193, 142, 103, 0, 1108, 969, 732, 600, 922, 512, 399, 304, 437, 334, 192, 85, 0),
(1107, 1016, 951, 978, 884, 387, 412, 357, 464, 193, 145, 103, 0, 1128, 974, 740, 605, 931, 517, 405, 308, 443, 339, 197, 86, 0),
(1120, 1023, 961, 986, 895, 394, 413, 360, 469, 193, 146, 104, 0, 1141, 991, 747, 611, 943, 519, 408, 313, 448, 343, 200, 86, 0),
(1130, 1030, 977, 993, 907, 399, 416, 364, 477, 196, 148, 104, 0, 1160, 1000, 759, 618, 954, 525, 409, 316, 453, 345, 200, 86, 0),
(1144, 1043, 986, 1000, 913, 402, 416, 366, 480, 198, 148, 104, 0, 1173, 1010, 765, 622, 961, 531, 412, 320, 456, 348, 201, 88, 0),
(1156, 1057, 991, 1008, 918, 408, 421, 371, 482, 200, 151, 104, 0, 1187, 1017, 772, 626, 970, 534, 414, 323, 464, 351, 204, 89, 0),
(1164, 1065, 1002, 1022, 929, 411, 423, 372, 490, 201, 155, 105, 0, 1206, 1025, 778, 632, 975, 537, 418, 325, 466, 355, 207, 90, 0),
(1176, 1076, 1010, 1035, 934, 414, 424, 375, 495, 202, 158, 106, 0, 1218, 1036, 784, 638, 981, 541, 421, 326, 472, 357, 207, 91, 0),
(1191, 1086, 1019, 1043, 938, 419, 427, 378, 497, 205, 158, 108, 0, 1233, 1047, 795, 643, 993, 544, 423, 329, 476, 360, 210, 92, 0),
(1208, 1097, 1027, 1058, 945, 427, 432, 381, 502, 207, 160, 108, 0, 1243, 1058, 806, 647, 1005, 549, 428, 335, 479, 365, 210, 93, 0),
(1223, 1104, 1039, 1069, 959, 431, 437, 383, 507, 207, 160, 109, 0, 1250, 1067, 813, 649, 1014, 552, 432, 338, 485, 371, 211, 94, 0),
(1234, 1116, 1043, 1076, 976, 435, 441, 385, 513, 209, 160, 109, 0, 1266, 1076, 822, 653, 1018, 561, 439, 342, 486, 375, 212, 95, 0),
(1246, 1122, 1055, 1085, 985, 438, 446, 387, 520, 210, 160, 109, 0, 1284, 1080, 834, 656, 1023, 566, 440, 347, 496, 382, 212, 95, 0),
(1256, 1127, 1064, 1096, 995, 442, 448, 388, 528, 213, 161, 109, 0, 1295, 1086, 843, 661, 1032, 571, 446, 349, 500, 388, 215, 95, 0),
(1264, 1135, 1071, 1106, 1009, 444, 451, 395, 535, 217, 162, 109, 0, 1306, 1097, 851, 670, 1037, 575, 453, 351, 502, 393, 215, 98, 0),
(1269, 1145, 1078, 1116, 1021, 445, 454, 401, 541, 218, 164, 109, 0, 1324, 1107, 857, 675, 1050, 579, 457, 354, 509, 393, 217, 98, 0),
(1281, 1158, 1081, 1119, 1031, 449, 461, 403, 542, 219, 166, 111, 0, 1336, 1113, 860, 685, 1057, 580, 458, 358, 513, 395, 218, 99, 0),
(1293, 1164, 1089, 1130, 1039, 453, 465, 409, 547, 221, 168, 111, 0, 1341, 1122, 869, 691, 1064, 586, 461, 361, 514, 398, 221, 99, 0),
(1302, 1172, 1097, 1145, 1047, 453, 469, 413, 551, 222, 170, 112, 0, 1347, 1137, 874, 694, 1080, 591, 465, 364, 517, 402, 222, 101, 0),
(1308, 1178, 1107, 1158, 1056, 456, 471, 417, 555, 224, 171, 114, 0, 1359, 1150, 883, 695, 1090, 597, 471, 364, 522, 405, 222, 101, 0),
(1319, 1183, 1116, 1168, 1064, 460, 476, 421, 558, 224, 171, 114, 0, 1369, 1157, 892, 703, 1099, 602, 472, 364, 525, 407, 225, 102, 0),
(1333, 1188, 1127, 1182, 1076, 463, 478, 422, 568, 224, 171, 114, 0, 1383, 1162, 899, 708, 1111, 605, 476, 364, 531, 409, 226, 103, 0),
(1342, 1201, 1132, 1192, 1083, 467, 483, 423, 574, 225, 172, 115, 0, 1394, 1173, 903, 711, 1120, 609, 479, 366, 536, 412, 228, 103, 0),
(1353, 1207, 1140, 1204, 1093, 468, 485, 427, 576, 225, 173, 116, 0, 1403, 1181, 907, 716, 1129, 613, 480, 369, 540, 414, 231, 104, 0),
(1370, 1212, 1147, 1213, 1103, 471, 489, 428, 579, 227, 176, 118, 0, 1412, 1191, 915, 722, 1136, 617, 483, 372, 548, 417, 231, 104, 0),
(1380, 1225, 1153, 1216, 1114, 476, 492, 429, 581, 228, 179, 118, 0, 1422, 1202, 924, 726, 1142, 623, 486, 373, 550, 417, 232, 104, 0),
(1393, 1232, 1164, 1227, 1126, 480, 494, 431, 583, 228, 181, 118, 0, 1434, 1213, 933, 729, 1146, 631, 490, 377, 556, 420, 233, 105, 0),
(1410, 1241, 1178, 1245, 1132, 488, 495, 436, 588, 230, 182, 120, 0, 1448, 1221, 941, 736, 1153, 631, 493, 381, 558, 424, 235, 106, 0),
(1420, 1243, 1187, 1256, 1140, 495, 501, 438, 590, 233, 184, 121, 0, 1458, 1231, 947, 744, 1160, 634, 498, 385, 562, 425, 238, 107, 0),
(1430, 1250, 1207, 1264, 1147, 501, 505, 442, 593, 235, 185, 121, 0, 1469, 1238, 958, 746, 1171, 640, 501, 390, 563, 428, 240, 108, 0),
(1437, 1257, 1216, 1269, 1158, 504, 507, 442, 598, 236, 186, 122, 0, 1477, 1246, 962, 752, 1177, 643, 502, 391, 565, 430, 242, 109, 0),
(1448, 1269, 1220, 1279, 1170, 506, 513, 445, 599, 237, 188, 122, 0, 1493, 1257, 974, 756, 1186, 647, 505, 398, 571, 438, 244, 109, 0),
(1461, 1276, 1228, 1290, 1176, 509, 514, 449, 600, 238, 190, 124, 0, 1510, 1267, 978, 758, 1193, 652, 511, 400, 574, 439, 246, 109, 0),
(1472, 1285, 1238, 1301, 1191, 511, 517, 449, 603, 239, 191, 125, 0, 1522, 1273, 985, 764, 1204, 657, 515, 402, 576, 443, 248, 111, 0),
(1480, 1287, 1248, 1311, 1198, 513, 521, 452, 608, 242, 193, 125, 0, 1532, 1281, 990, 769, 1210, 660, 521, 403, 582, 446, 249, 111, 0),
(1494, 1297, 1256, 1320, 1209, 515, 528, 456, 612, 243, 193, 126, 0, 1548, 1287, 997, 775, 1219, 664, 521, 406, 584, 448, 249, 113, 0),
(1508, 1305, 1259, 1333, 1217, 517, 529, 461, 615, 247, 194, 127, 0, 1555, 1294, 1003, 781, 1226, 668, 524, 410, 587, 450, 250, 114, 0),
(1523, 1313, 1266, 1342, 1225, 520, 534, 464, 622, 248, 195, 129, 0, 1569, 1304, 1007, 789, 1235, 670, 529, 410, 592, 454, 250, 114, 0),
(1537, 1325, 1273, 1351, 1232, 522, 537, 469, 625, 249, 197, 130, 0, 1576, 1317, 1018, 792, 1246, 674, 532, 411, 596, 457, 253, 116, 0),
(1548, 1332, 1285, 1357, 1237, 527, 543, 470, 631, 251, 197, 130, 0, 1583, 1325, 1028, 798, 1257, 675, 537, 413, 600, 461, 255, 117, 0),
(1562, 1340, 1294, 1371, 1240, 533, 545, 473, 637, 254, 199, 131, 0, 1593, 1336, 1036, 802, 1261, 677, 538, 416, 603, 464, 255, 117, 0),
(1574, 1346, 1304, 1378, 1249, 536, 549, 475, 643, 257, 201, 134, 0, 1604, 1343, 1042, 808, 1266, 687, 544, 417, 606, 466, 257, 117, 0),
(1585, 1353, 1309, 1386, 1256, 542, 551, 477, 652, 257, 202, 136, 0, 1623, 1352, 1044, 812, 1273, 694, 547, 419, 613, 470, 259, 117, 0),
(1597, 1359, 1319, 1396, 1266, 546, 554, 480, 657, 257, 202, 136, 0, 1632, 1360, 1053, 816, 1279, 700, 548, 424, 618, 474, 263, 119, 0),
(1602, 1368, 1327, 1403, 1277, 549, 558, 483, 660, 257, 204, 136, 0, 1643, 1370, 1058, 822, 1282, 702, 551, 429, 619, 480, 265, 121, 0),
(1612, 1374, 1331, 1411, 1284, 554, 562, 486, 662, 260, 207, 137, 0, 1646, 1381, 1068, 828, 1292, 704, 553, 432, 624, 486, 267, 123, 0),
(1623, 1380, 1335, 1414, 1295, 558, 564, 489, 665, 262, 209, 139, 0, 1657, 1388, 1076, 832, 1300, 708, 554, 437, 627, 489, 267, 126, 0),
(1635, 1385, 1346, 1423, 1300, 564, 565, 493, 671, 267, 210, 141, 0, 1673, 1394, 1082, 839, 1304, 710, 557, 440, 631, 491, 268, 126, 0),
(1647, 1394, 1357, 1430, 1307, 567, 568, 497, 675, 268, 211, 144, 0, 1680, 1402, 1094, 842, 1310, 715, 562, 443, 632, 495, 270, 128, 0),
(1656, 1400, 1363, 1437, 1314, 578, 572, 499, 682, 269, 212, 144, 0, 1691, 1410, 1101, 845, 1317, 722, 568, 446, 639, 497, 271, 129, 0),
(1669, 1408, 1372, 1444, 1319, 583, 577, 504, 686, 273, 212, 144, 0, 1696, 1420, 1105, 853, 1324, 729, 572, 448, 646, 499, 271, 132, 0),
(1677, 1417, 1383, 1453, 1324, 584, 582, 506, 688, 275, 212, 144, 0, 1705, 1428, 1110, 862, 1330, 733, 576, 452, 647, 502, 272, 133, 0),
(1686, 1429, 1390, 1466, 1328, 586, 584, 510, 693, 276, 213, 147, 0, 1720, 1432, 1115, 864, 1342, 737, 577, 457, 649, 508, 274, 133, 0),
(1695, 1437, 1400, 1477, 1339, 588, 590, 513, 696, 277, 213, 147, 0, 1728, 1439, 1124, 867, 1349, 739, 581, 460, 653, 510, 274, 133, 0),
(1709, 1442, 1411, 1484, 1343, 591, 591, 521, 700, 278, 213, 148, 0, 1737, 1446, 1134, 871, 1358, 745, 582, 463, 658, 511, 274, 135, 0),
(1718, 1450, 1419, 1501, 1350, 595, 595, 523, 706, 279, 215, 148, 0, 1743, 1451, 1137, 878, 1360, 746, 584, 464, 663, 515, 274, 135, 0),
(1727, 1451, 1425, 1509, 1355, 600, 597, 524, 711, 279, 216, 148, 0, 1756, 1459, 1144, 885, 1369, 751, 588, 467, 664, 517, 276, 135, 0),
(1734, 1455, 1435, 1521, 1365, 605, 599, 528, 716, 285, 216, 148, 0, 1766, 1463, 1153, 888, 1381, 753, 589, 469, 664, 521, 277, 135, 0),
(1737, 1460, 1443, 1529, 1372, 609, 601, 529, 718, 286, 219, 148, 0, 1780, 1467, 1161, 895, 1387, 757, 594, 471, 668, 524, 278, 135, 0),
(1748, 1467, 1448, 1539, 1380, 614, 604, 531, 723, 288, 221, 149, 0, 1790, 1475, 1168, 899, 1396, 760, 597, 477, 669, 527, 278, 137, 0),
(1754, 1475, 1457, 1548, 1387, 618, 606, 534, 723, 288, 224, 149, 0, 1803, 1483, 1169, 901, 1398, 768, 597, 479, 670, 528, 280, 137, 0),
(1758, 1484, 1465, 1552, 1391, 621, 611, 539, 724, 290, 226, 150, 0, 1815, 1493, 1181, 906, 1406, 773, 603, 482, 675, 532, 280, 137, 0),
(1765, 1490, 1472, 1558, 1395, 624, 612, 539, 731, 291, 226, 150, 0, 1831, 1499, 1186, 912, 1411, 778, 606, 483, 676, 537, 280, 137, 0),
(1773, 1494, 1480, 1563, 1401, 626, 615, 540, 733, 292, 227, 150, 0, 1841, 1508, 1195, 917, 1416, 783, 608, 487, 679, 539, 280, 137, 0),
(1783, 1496, 1487, 1572, 1405, 631, 617, 542, 738, 293, 227, 150, 0, 1851, 1514, 1200, 921, 1423, 788, 611, 491, 683, 541, 283, 137, 0),
(1790, 1501, 1495, 1576, 1412, 632, 618, 546, 742, 293, 227, 151, 0, 1856, 1516, 1204, 923, 1426, 790, 613, 493, 688, 544, 283, 138, 0),
(1800, 1509, 1504, 1583, 1417, 634, 620, 548, 744, 293, 229, 151, 0, 1862, 1520, 1211, 926, 1431, 795, 614, 495, 693, 546, 285, 138, 0),
(1808, 1517, 1508, 1590, 1423, 635, 624, 550, 746, 294, 231, 152, 0, 1867, 1528, 1213, 930, 1444, 800, 620, 497, 696, 549, 285, 140, 0),
(1820, 1519, 1515, 1597, 1432, 638, 625, 554, 748, 294, 231, 152, 0, 1881, 1533, 1221, 942, 1450, 805, 622, 499, 700, 551, 287, 140, 0),
(1830, 1524, 1518, 1606, 1436, 644, 630, 558, 752, 295, 231, 152, 0, 1889, 1538, 1230, 945, 1459, 811, 623, 503, 701, 551, 288, 140, 0),
(1837, 1527, 1525, 1610, 1443, 647, 630, 561, 756, 297, 232, 153, 0, 1903, 1543, 1231, 946, 1467, 816, 626, 505, 703, 552, 289, 141, 0),
(1844, 1531, 1527, 1614, 1449, 648, 632, 563, 761, 298, 234, 153, 0, 1911, 1556, 1234, 948, 1471, 819, 629, 507, 711, 552, 290, 143, 0),
(1851, 1535, 1534, 1615, 1456, 652, 637, 566, 762, 299, 236, 154, 0, 1924, 1561, 1239, 949, 1474, 823, 630, 509, 713, 555, 291, 143, 0),
(1858, 1544, 1537, 1620, 1467, 654, 641, 568, 765, 299, 236, 154, 0, 1930, 1571, 1242, 953, 1481, 828, 631, 511, 715, 557, 294, 143, 0),
(1866, 1551, 1546, 1629, 1476, 655, 647, 570, 773, 301, 240, 154, 0, 1938, 1581, 1246, 955, 1490, 831, 635, 513, 718, 561, 296, 144, 0),
(1873, 1555, 1551, 1638, 1478, 655, 649, 570, 776, 302, 240, 155, 0, 1946, 1588, 1254, 960, 1496, 831, 637, 515, 721, 563, 296, 145, 0),
(1878, 1559, 1557, 1640, 1480, 657, 653, 570, 776, 304, 240, 155, 0, 1954, 1590, 1260, 962, 1501, 833, 641, 515, 725, 564, 297, 146, 0),
(1888, 1563, 1564, 1646, 1484, 661, 655, 572, 777, 305, 240, 155, 0, 1962, 1592, 1266, 966, 1508, 835, 644, 516, 728, 571, 297, 147, 0),
(1894, 1564, 1568, 1653, 1489, 662, 655, 573, 777, 305, 240, 155, 0, 1967, 1596, 1270, 966, 1513, 840, 646, 518, 729, 573, 298, 147, 0),
(1898, 1565, 1573, 1661, 1494, 668, 658, 574, 783, 305, 242, 156, 0, 1976, 1604, 1272, 967, 1520, 842, 647, 521, 732, 574, 299, 148, 0),
(1909, 1569, 1580, 1666, 1499, 670, 658, 575, 786, 307, 243, 156, 0, 1983, 1611, 1275, 968, 1523, 843, 648, 523, 734, 577, 300, 148, 0),
(1911, 1574, 1585, 1667, 1503, 672, 658, 576, 788, 308, 244, 157, 0, 1989, 1615, 1275, 974, 1530, 843, 649, 526, 736, 577, 301, 148, 0),
(1915, 1576, 1586, 1672, 1504, 674, 658, 576, 791, 309, 246, 157, 0, 1992, 1620, 1278, 975, 1533, 844, 649, 529, 737, 579, 302, 148, 0),
(1915, 1576, 1586, 1672, 1504, 674, 658, 576, 791, 309, 246, 157, 0, 1992, 1620, 1278, 975, 1533, 844, 649, 529, 737, 579, 302, 148, 0),
)
passenger_arriving_rate = (
(6.025038694046121, 6.077817415662483, 5.211283229612507, 5.593200996477089, 4.443748486087689, 2.197058452426137, 2.4876213692243487, 2.3265880864897115, 2.4360396248672025, 1.187404504656711, 0.8410530327771206, 0.4897915078306174, 0.0, 6.100656255094035, 5.38770658613679, 4.205265163885603, 3.562213513970132, 4.872079249734405, 3.257223321085596, 2.4876213692243487, 1.5693274660186693, 2.2218742430438443, 1.8644003321590301, 1.0422566459225016, 0.5525288559693167, 0.0),
(6.425192582423969, 6.479066763559234, 5.555346591330152, 5.9626298279489545, 4.737992269979389, 2.342188508829789, 2.651681364758216, 2.479756861452854, 2.5968981305331633, 1.265694207683145, 0.8966192271912263, 0.5221216660814355, 0.0, 6.503749976927826, 5.743338326895789, 4.483096135956131, 3.7970826230494343, 5.193796261066327, 3.4716596060339957, 2.651681364758216, 1.6729917920212778, 2.3689961349896946, 1.9875432759829852, 1.1110693182660305, 0.589006069414476, 0.0),
(6.8240676107756775, 6.878723687980077, 5.8980422855474135, 6.330588934198314, 5.031170378999795, 2.4867395801587113, 2.8150911047764224, 2.6323126239522097, 2.7571147227510195, 1.3436741325061639, 0.9519646297552626, 0.5543232652053055, 0.0, 6.905237793851628, 6.09755591725836, 4.759823148776313, 4.031022397518491, 5.514229445502039, 3.6852376735330936, 2.8150911047764224, 1.7762425572562224, 2.5155851894998973, 2.1101963113994384, 1.179608457109483, 0.625338517089098, 0.0),
(7.220109351775874, 7.275202552130091, 6.238010869319854, 6.695618766778866, 5.322129340801521, 2.6301384358095787, 2.9772021849887733, 2.7836505787472534, 2.9160540643684367, 1.4210348095278544, 1.0068696823654766, 0.5862685684930461, 0.0, 7.30352736750507, 6.448954253423507, 5.0343484118273825, 4.263104428583563, 5.8321081287368735, 3.8971108102461547, 2.9772021849887733, 1.8786703112925562, 2.6610646704007603, 2.2318729222596225, 1.247602173863971, 0.6613820501936447, 0.0),
(7.611763378099177, 7.666917719214351, 6.573892899703036, 7.056259777244312, 5.609715683037193, 2.7718118451790676, 3.137366201105075, 2.9331659305974576, 3.0730808182330827, 1.4974667691503039, 1.0611148269181152, 0.6178298392354764, 0.0, 7.69702635952778, 6.79612823159024, 5.305574134590575, 4.492400307450911, 6.146161636466165, 4.10643230283644, 3.137366201105075, 1.9798656036993338, 2.8048578415185963, 2.3520865924147714, 1.3147785799406073, 0.6969925199285775, 0.0),
(7.9974752624202115, 8.052283552437947, 6.904328933752518, 7.411052417148355, 5.892775933359424, 2.9111865776638504, 3.2949347488351344, 3.080253884262296, 3.2275596471926233, 1.5726605417755992, 1.1144805053094267, 0.6488793407234149, 0.0, 8.084142431559393, 7.137672747957563, 5.572402526547132, 4.7179816253267965, 6.455119294385247, 4.312355437967215, 3.2949347488351344, 2.079418984045607, 2.946387966679712, 2.4703508057161185, 1.3808657867505036, 0.7320257774943589, 0.0),
(8.375690577413598, 8.42971441500595, 7.227959528523866, 7.758537138044686, 6.170156619420834, 3.047689402660605, 3.4492594238887575, 3.2243096445012442, 3.3788552140947257, 1.6463066578058279, 1.1667471594356567, 0.6792893362476808, 0.0, 8.463283245239527, 7.472182698724488, 5.833735797178282, 4.938919973417482, 6.757710428189451, 4.514033502301742, 3.4492594238887575, 2.176921001900432, 3.085078309710417, 2.586179046014896, 1.4455919057047733, 0.7663376740914501, 0.0),
(8.744854895753962, 8.797624670123444, 7.543425241072636, 8.097254391487015, 6.440704268874043, 3.1807470895660046, 3.599691821975751, 3.3647284160737763, 3.5263321817870574, 1.7180956476430762, 1.2176952311930538, 0.708932089099093, 0.0, 8.832856462207822, 7.798252980090021, 6.088476155965268, 5.154286942929227, 7.052664363574115, 4.7106197825032865, 3.599691821975751, 2.2719622068328604, 3.2203521344370216, 2.699084797162339, 1.508685048214527, 0.7997840609203132, 0.0),
(9.103413790115921, 9.154428680995508, 7.849366628454395, 8.425744629029035, 6.703265409371668, 3.309786407776723, 3.7455835388059184, 3.5009054037393623, 3.669355213117282, 1.7877180416894325, 1.2671051624778642, 0.7376798625684703, 0.0, 9.1912697441039, 8.114478488253173, 6.335525812389321, 5.363154125068296, 7.338710426234564, 4.901267565235107, 3.7455835388059184, 2.3641331484119448, 3.351632704685834, 2.8085815430096788, 1.5698733256908792, 0.8322207891814098, 0.0),
(9.449812833174102, 9.498540810827224, 8.144424247724704, 8.742548302224453, 6.956686568566327, 3.4342341266894385, 3.886286170089072, 3.6322358122574814, 3.8072889709330693, 1.8548643703469827, 1.3147573951863356, 0.7654049199466314, 0.0, 9.536930752567395, 8.419454119412945, 6.573786975931678, 5.564593111040947, 7.614577941866139, 5.0851301371604745, 3.886286170089072, 2.453024376206742, 3.4783432842831634, 2.914182767408151, 1.6288848495449408, 0.8635037100752023, 0.0),
(9.782497597603118, 9.828375422823667, 8.427238655939124, 9.046205862626959, 7.19981427411064, 3.5535170157008253, 4.021151311535013, 3.7581148463876053, 3.9394981180820854, 1.9192251640178146, 1.3604323712147148, 0.7919795245243952, 0.0, 9.868247149237932, 8.711774769768347, 6.802161856073574, 5.757675492053442, 7.878996236164171, 5.261360784942648, 4.021151311535013, 2.5382264397863037, 3.59990713705532, 3.015401954208987, 1.685447731187825, 0.8934886748021517, 0.0),
(10.099913656077605, 10.142346880189926, 8.696450410153215, 9.335257761790256, 7.431495053657226, 3.667061844207558, 4.14953055885355, 3.8779377108892072, 4.065347317411997, 1.980490953104016, 1.40391053245925, 0.8172759395925812, 0.0, 10.183626595755133, 8.99003533551839, 7.019552662296249, 5.9414728593120465, 8.130694634823994, 5.42911279524489, 4.14953055885355, 2.619329888719684, 3.715747526828613, 3.1117525872634197, 1.7392900820306432, 0.9220315345627208, 0.0),
(10.400506581272174, 10.438869546131066, 8.95070006742254, 9.60824445126805, 7.650575434858702, 3.7742953816063087, 4.270775507754487, 3.99109961052176, 4.184201231770471, 2.0383522680076718, 1.444972320816187, 0.8411664284420068, 0.0, 10.48147675375864, 9.252830712862075, 7.224861604080934, 6.115056804023014, 8.368402463540942, 5.587539454730464, 4.270775507754487, 2.6959252725759346, 3.825287717429351, 3.2027481504226842, 1.790140013484508, 0.9489881405573698, 0.0),
(10.68272194586145, 10.716357783852182, 9.188628184802662, 9.863706382614039, 7.85590194536768, 3.8746443972937565, 4.384237753947633, 4.096995750044741, 4.295424524005172, 2.0924996391308714, 1.4833981781817738, 0.8635232543634921, 0.0, 10.760205284888082, 9.498755797998411, 7.416990890908868, 6.277498917392613, 8.590849048010345, 5.735794050062637, 4.384237753947633, 2.7676031409241117, 3.92795097268384, 3.287902127538014, 1.8377256369605324, 0.974214343986562, 0.0),
(10.945005322520059, 10.973225956558347, 9.408875319349146, 10.100184007381912, 8.046321112836791, 3.967535660666574, 4.489268893142796, 4.195021334217623, 4.398381856963768, 2.1426235968757004, 1.518968546452257, 0.8842186806478561, 0.0, 11.018219850783076, 9.726405487126415, 7.594842732261284, 6.4278707906271, 8.796763713927536, 5.873029867904672, 4.489268893142796, 2.833954043333267, 4.023160556418396, 3.3667280024606385, 1.8817750638698296, 0.997565996050759, 0.0),
(11.185802283922625, 11.207888427454638, 9.610082028117542, 10.316217777125386, 8.220679464918646, 4.052395941121439, 4.585220521049775, 4.284571567799878, 4.4924378934939275, 2.1884146716442476, 1.551463867523884, 0.9031249705859171, 0.0, 11.253928113083257, 9.934374676445087, 7.757319337619419, 6.565244014932741, 8.984875786987855, 5.998400194919829, 4.585220521049775, 2.894568529372456, 4.110339732459323, 3.4387392590417964, 1.9220164056235085, 1.0188989479504218, 0.0),
(11.40355840274376, 11.418759559746144, 9.790888868163425, 10.510348143398145, 8.377823529265866, 4.128652008055021, 4.671444233378385, 4.36504165555098, 4.5769572964433145, 2.2295633938385993, 1.5806645832929027, 0.920114387468494, 0.0, 11.465737733428254, 10.121258262153432, 7.9033229164645125, 6.688690181515796, 9.153914592886629, 6.111058317771373, 4.671444233378385, 2.9490371486107296, 4.188911764632933, 3.503449381132716, 1.958177773632685, 1.0380690508860133, 0.0),
(11.59671925165809, 11.604253716637938, 9.949936396542352, 10.6811155577539, 8.51659983353107, 4.1957306308639994, 4.747291625838426, 4.435826802230409, 4.651304728659593, 2.2657602938608403, 1.60635113565556, 0.9350591945864056, 0.0, 11.652056373457699, 10.28565114045046, 8.031755678277799, 6.79728088158252, 9.302609457319186, 6.2101575231225725, 4.747291625838426, 2.9969504506171427, 4.258299916765535, 3.5603718525846344, 1.9899872793084707, 1.0549321560579947, 0.0),
(11.763730403340244, 11.7627852613351, 10.08586517030988, 10.82706047174635, 8.63585490536687, 4.253058578945052, 4.81211429413971, 4.49632221259763, 4.7148448529904385, 2.2966959021130613, 1.6283039665081016, 0.9478316552304716, 0.0, 11.811291694811214, 10.426148207535187, 8.141519832540508, 6.890087706339182, 9.429689705980877, 6.294851097636682, 4.81211429413971, 3.0378989849607514, 4.317927452683435, 3.6090201572487843, 2.0171730340619765, 1.0693441146668274, 0.0),
(11.903037430464838, 11.892768557042718, 10.197315746521578, 10.946723336929182, 8.734435272425891, 4.300062621694845, 4.865263833992036, 4.5459230914121225, 4.766942332283511, 2.3220607489973486, 1.6463035177467755, 0.9583040326915097, 0.0, 11.941851359128435, 10.541344359606605, 8.231517588733878, 6.9661822469920445, 9.533884664567022, 6.364292327976972, 4.865263833992036, 3.071473301210604, 4.367217636212946, 3.648907778976395, 2.039463149304316, 1.0811607779129746, 0.0),
(12.013085905706498, 11.992617966965858, 10.282928682233003, 11.038644604856119, 8.811187462360754, 4.336169528510063, 4.9060918411052175, 4.5840246434333585, 4.806961829386479, 2.341545364915788, 1.66013023126783, 0.9663485902603393, 0.0, 12.042143028048988, 10.62983449286373, 8.30065115633915, 7.024636094747362, 9.613923658772958, 6.417634500806702, 4.9060918411052175, 3.097263948935759, 4.405593731180377, 3.679548201618707, 2.0565857364466007, 1.0902379969968963, 0.0),
(12.09232140173984, 12.060747854309614, 10.341344534499719, 11.101364727080837, 8.86495800282407, 4.360806068787375, 4.933949911189055, 4.6100220734208115, 4.834268007147008, 2.3548402802704667, 1.669564548967512, 0.9718375912277795, 0.0, 12.110574363212494, 10.690213503505571, 8.34782274483756, 7.064520840811399, 9.668536014294016, 6.454030902789136, 4.933949911189055, 3.1148614777052677, 4.432479001412035, 3.7004549090269463, 2.068268906899944, 1.096431623119056, 0.0),
(12.139189491239494, 12.095572582279058, 10.371203860377285, 11.133424155157051, 8.894593421468459, 4.373399011923457, 4.94818963995336, 4.623310586133957, 4.848225528412765, 2.361636025463473, 1.674386912742068, 0.9746432988846491, 0.0, 12.145553026258591, 10.721076287731139, 8.37193456371034, 7.084908076390418, 9.69645105682553, 6.47263482058754, 4.94818963995336, 3.1238564370881834, 4.447296710734229, 3.7111413850523514, 2.0742407720754574, 1.0995975074799145, 0.0),
(12.156472036011166, 12.099695953360769, 10.374923182441702, 11.137437731481482, 8.902185644826076, 4.375, 4.949882401355603, 4.624746913580247, 4.8499704938271595, 2.3624376817558304, 1.6749916074323483, 0.9749897576588934, 0.0, 12.15, 10.724887334247827, 8.37495803716174, 7.087313045267489, 9.699940987654319, 6.474645679012346, 4.949882401355603, 3.125, 4.451092822413038, 3.7124792438271617, 2.0749846364883404, 1.0999723593964337, 0.0),
(12.169214895640982, 12.09729074074074, 10.374314814814815, 11.13694375, 8.906486090891882, 4.375, 4.9489522875817, 4.62275, 4.849736666666666, 2.3619451851851854, 1.6749249158249162, 0.9749086419753087, 0.0, 12.15, 10.723995061728393, 8.37462457912458, 7.085835555555555, 9.699473333333332, 6.47185, 4.9489522875817, 3.125, 4.453243045445941, 3.7123145833333346, 2.074862962962963, 1.099753703703704, 0.0),
(12.181688676253897, 12.092549725651576, 10.373113854595337, 11.135966435185185, 8.910691956475603, 4.375, 4.947119341563786, 4.618827160493828, 4.8492746913580245, 2.3609756515775038, 1.6747926798852726, 0.9747485139460449, 0.0, 12.15, 10.722233653406493, 8.373963399426362, 7.08292695473251, 9.698549382716049, 6.466358024691359, 4.947119341563786, 3.125, 4.455345978237801, 3.711988811728396, 2.0746227709190674, 1.0993227023319616, 0.0),
(12.19389242285764, 12.085545336076818, 10.371336762688616, 11.134516898148147, 8.914803094736882, 4.375, 4.944412030985233, 4.613052469135803, 4.84859049382716, 2.3595452126200276, 1.674596096770171, 0.9745115683584822, 0.0, 12.15, 10.719627251943303, 8.372980483850855, 7.078635637860081, 9.69718098765432, 6.458273456790124, 4.944412030985233, 3.125, 4.457401547368441, 3.71150563271605, 2.0742673525377233, 1.0986859396433473, 0.0),
(12.205825180459962, 12.076349999999996, 10.369, 11.132606249999998, 8.918819358835371, 4.375, 4.940858823529412, 4.6055, 4.84769, 2.35767, 1.674336363636364, 0.9742000000000002, 0.0, 12.15, 10.7162, 8.371681818181818, 7.073009999999999, 9.69538, 6.4477, 4.940858823529412, 3.125, 4.459409679417686, 3.7108687500000004, 2.0738000000000003, 1.09785, 0.0),
(12.217485994068602, 12.065036145404662, 10.366120027434842, 11.13024560185185, 8.92274060193072, 4.375, 4.93648818687969, 4.596243827160494, 4.846579135802468, 2.3553661454046644, 1.6740146776406037, 0.9738160036579792, 0.0, 12.15, 10.711976040237769, 8.370073388203018, 7.066098436213991, 9.693158271604936, 6.434741358024692, 4.93648818687969, 3.125, 4.46137030096536, 3.710081867283951, 2.073224005486969, 1.0968214677640604, 0.0),
(12.2288739086913, 12.051676200274349, 10.362713305898492, 11.127446064814816, 8.926566677182576, 4.375, 4.931328588719439, 4.585358024691358, 4.845263827160494, 2.3526497805212623, 1.6736322359396434, 0.9733617741197987, 0.0, 12.15, 10.706979515317785, 8.368161179698216, 7.057949341563786, 9.690527654320988, 6.419501234567901, 4.931328588719439, 3.125, 4.463283338591288, 3.709148688271606, 2.0725426611796984, 1.0956069272976683, 0.0),
(12.239987969335797, 12.036342592592591, 10.358796296296296, 11.12421875, 8.930297437750589, 4.375, 4.925408496732026, 4.572916666666666, 4.84375, 2.3495370370370376, 1.6731902356902357, 0.9728395061728394, 0.0, 12.15, 10.701234567901233, 8.365951178451178, 7.048611111111112, 9.6875, 6.402083333333333, 4.925408496732026, 3.125, 4.4651487188752945, 3.7080729166666675, 2.0717592592592595, 1.094212962962963, 0.0),
(12.25082722100983, 12.019107750342934, 10.354385459533608, 11.120574768518516, 8.933932736794405, 4.375, 4.918756378600824, 4.558993827160494, 4.842043580246913, 2.346044046639232, 1.6726898740491336, 0.9722513946044812, 0.0, 12.15, 10.694765340649292, 8.363449370245666, 7.038132139917694, 9.684087160493826, 6.382591358024691, 4.918756378600824, 3.125, 4.466966368397203, 3.70685825617284, 2.070877091906722, 1.0926461591220853, 0.0),
(12.261390708721144, 12.000044101508914, 10.349497256515773, 11.11652523148148, 8.937472427473676, 4.375, 4.911400702009199, 4.543663580246914, 4.84015049382716, 2.3421869410150897, 1.672132348173089, 0.9715996342021036, 0.0, 12.15, 10.687595976223138, 8.360661740865444, 7.026560823045267, 9.68030098765432, 6.36112901234568, 4.911400702009199, 3.125, 4.468736213736838, 3.705508410493828, 2.069899451303155, 1.0909131001371744, 0.0),
(12.271677477477477, 11.979224074074073, 10.344148148148149, 11.11208125, 8.94091636294805, 4.375, 4.903369934640523, 4.527, 4.838076666666666, 2.3379818518518523, 1.6715188552188551, 0.9708864197530863, 0.0, 12.15, 10.679750617283949, 8.357594276094275, 7.013945555555555, 9.676153333333332, 6.3378000000000005, 4.903369934640523, 3.125, 4.470458181474025, 3.704027083333334, 2.06882962962963, 1.0890203703703705, 0.0),
(12.28168657228657, 11.956720096021947, 10.338354595336076, 11.107253935185184, 8.944264396377172, 4.375, 4.894692544178166, 4.509077160493827, 4.835828024691358, 2.333444910836763, 1.670850592343185, 0.9701139460448103, 0.0, 12.15, 10.671253406492912, 8.354252961715924, 7.000334732510288, 9.671656049382715, 6.312708024691357, 4.894692544178166, 3.125, 4.472132198188586, 3.7024179783950624, 2.0676709190672153, 1.0869745541838134, 0.0),
(12.291417038156167, 11.932604595336077, 10.332133058984912, 11.102054398148146, 8.947516380920696, 4.375, 4.885396998305495, 4.489969135802469, 4.83341049382716, 2.328592249657065, 1.6701287567028307, 0.969284407864655, 0.0, 12.15, 10.662128486511202, 8.350643783514153, 6.985776748971193, 9.66682098765432, 6.285956790123457, 4.885396998305495, 3.125, 4.473758190460348, 3.7006847993827163, 2.0664266117969827, 1.0847822359396435, 0.0),
(12.300867920094007, 11.906949999999998, 10.3255, 11.096493749999999, 8.950672169738269, 4.375, 4.875511764705882, 4.46975, 4.830829999999999, 2.32344, 1.6693545454545458, 0.9684000000000001, 0.0, 12.15, 10.6524, 8.346772727272727, 6.970319999999999, 9.661659999999998, 6.257650000000001, 4.875511764705882, 3.125, 4.475336084869134, 3.6988312500000005, 2.0651, 1.08245, 0.0),
(12.310038263107828, 11.879828737997256, 10.318471879286694, 11.090583101851852, 8.953731615989536, 4.375, 4.865065311062696, 4.448493827160494, 4.828092469135802, 2.3180042935528125, 1.668529155755082, 0.9674629172382261, 0.0, 12.15, 10.642092089620485, 8.34264577877541, 6.954012880658436, 9.656184938271604, 6.227891358024691, 4.865065311062696, 3.125, 4.476865807994768, 3.696861033950618, 2.063694375857339, 1.0799844307270234, 0.0),
(12.31892711220537, 11.851313237311386, 10.311065157750342, 11.084333564814814, 8.956694572834152, 4.375, 4.854086105059308, 4.426274691358025, 4.825203827160493, 2.312301262002744, 1.6676537847611925, 0.9664753543667125, 0.0, 12.15, 10.631228898033836, 8.33826892380596, 6.936903786008231, 9.650407654320986, 6.196784567901235, 4.854086105059308, 3.125, 4.478347286417076, 3.6947778549382724, 2.0622130315500686, 1.0773921124828534, 0.0),
(12.327533512394384, 11.821475925925924, 10.303296296296297, 11.07775625, 8.959560893431762, 4.375, 4.842602614379085, 4.4031666666666665, 4.82217, 2.3063470370370376, 1.6667296296296297, 0.9654395061728396, 0.0, 12.15, 10.619834567901233, 8.333648148148148, 6.919041111111111, 9.64434, 6.164433333333333, 4.842602614379085, 3.125, 4.479780446715881, 3.6925854166666676, 2.0606592592592596, 1.0746796296296297, 0.0),
(12.335856508682596, 11.790389231824417, 10.295181755829903, 11.070862268518518, 8.962330430942014, 4.375, 4.830643306705398, 4.3792438271604945, 4.818996913580246, 2.3001577503429362, 1.6657578875171468, 0.9643575674439875, 0.0, 12.15, 10.60793324188386, 8.328789437585733, 6.900473251028807, 9.637993827160493, 6.1309413580246925, 4.830643306705398, 3.125, 4.481165215471007, 3.690287422839507, 2.059036351165981, 1.0718535665294926, 0.0),
(12.343895146077754, 11.758125582990397, 10.286737997256516, 11.06366273148148, 8.96500303852456, 4.375, 4.818236649721617, 4.354580246913581, 4.81569049382716, 2.293749533607682, 1.6647397555804966, 0.9632317329675355, 0.0, 12.15, 10.595549062642888, 8.323698777902482, 6.881248600823045, 9.63138098765432, 6.096412345679013, 4.818236649721617, 3.125, 4.48250151926228, 3.6878875771604944, 2.0573475994513033, 1.0689205075445818, 0.0),
(12.3516484695876, 11.724757407407406, 10.277981481481483, 11.056168750000001, 8.967578569339047, 4.375, 4.805411111111111, 4.32925, 4.812256666666666, 2.287138518518519, 1.663676430976431, 0.9620641975308644, 0.0, 12.15, 10.582706172839506, 8.318382154882155, 6.861415555555555, 9.624513333333333, 6.06095, 4.805411111111111, 3.125, 4.483789284669523, 3.6853895833333343, 2.055596296296297, 1.0658870370370372, 0.0),
(12.35911552421987, 11.690357133058985, 10.268928669410151, 11.048391435185184, 8.970056876545122, 4.375, 4.7921951585572495, 4.3033271604938275, 4.80870135802469, 2.280340836762689, 1.6625691108617036, 0.9608571559213536, 0.0, 12.15, 10.569428715134888, 8.312845554308517, 6.841022510288067, 9.61740271604938, 6.024658024691359, 4.7921951585572495, 3.125, 4.485028438272561, 3.682797145061729, 2.0537857338820307, 1.062759739368999, 0.0),
(12.366295354982311, 11.65499718792867, 10.259596021947875, 11.040341898148148, 8.972437813302435, 4.375, 4.778617259743403, 4.2768858024691365, 4.805030493827159, 2.2733726200274353, 1.6614189923930665, 0.9596128029263833, 0.0, 12.15, 10.555740832190216, 8.307094961965332, 6.820117860082305, 9.610060987654318, 5.987640123456791, 4.778617259743403, 3.125, 4.486218906651217, 3.6801139660493836, 2.0519192043895753, 1.0595451989026066, 0.0),
(12.37318700688266, 11.618749999999999, 10.25, 11.03203125, 8.974721232770635, 4.375, 4.764705882352941, 4.25, 4.80125, 2.2662500000000003, 1.6602272727272729, 0.9583333333333333, 0.0, 12.15, 10.541666666666664, 8.301136363636363, 6.79875, 9.6025, 5.95, 4.764705882352941, 3.125, 4.487360616385318, 3.677343750000001, 2.0500000000000003, 1.0562500000000001, 0.0),
(12.379789524928656, 11.581687997256516, 10.240157064471878, 11.023470601851852, 8.976906988109372, 4.375, 4.750489494069233, 4.222743827160494, 4.797365802469135, 2.258989108367627, 1.6589951490210748, 0.9570209419295841, 0.0, 12.15, 10.527230361225422, 8.294975745105374, 6.77696732510288, 9.59473160493827, 5.9118413580246925, 4.750489494069233, 3.125, 4.488453494054686, 3.6744902006172846, 2.048031412894376, 1.0528807270233198, 0.0),
(12.386101954128042, 11.543883607681755, 10.230083676268862, 11.014671064814813, 8.978994932478294, 4.375, 4.7359965625756475, 4.195191358024691, 4.793383827160493, 2.2516060768175588, 1.657723818431226, 0.955677823502515, 0.0, 12.15, 10.512456058527663, 8.288619092156129, 6.754818230452675, 9.586767654320987, 5.873267901234568, 4.7359965625756475, 3.125, 4.489497466239147, 3.6715570216049387, 2.046016735253773, 1.049443964334705, 0.0),
(12.392123339488554, 11.505409259259258, 10.219796296296296, 11.00564375, 8.980984919037049, 4.375, 4.7212555555555555, 4.167416666666667, 4.78931, 2.244117037037037, 1.656414478114478, 0.9543061728395063, 0.0, 12.15, 10.497367901234567, 8.28207239057239, 6.73235111111111, 9.57862, 5.834383333333334, 4.7212555555555555, 3.125, 4.490492459518524, 3.6685479166666677, 2.0439592592592595, 1.0459462962962964, 0.0),
(12.397852726017943, 11.466337379972563, 10.209311385459534, 10.996399768518518, 8.982876800945284, 4.375, 4.706294940692326, 4.139493827160494, 4.78515024691358, 2.2365381207133064, 1.6550683252275846, 0.9529081847279379, 0.0, 12.15, 10.481990032007316, 8.275341626137923, 6.709614362139918, 9.57030049382716, 5.795291358024691, 4.706294940692326, 3.125, 4.491438400472642, 3.665466589506174, 2.0418622770919073, 1.0423943072702333, 0.0),
(12.403289158723938, 11.426740397805213, 10.198645404663925, 10.986950231481481, 8.984670431362652, 4.375, 4.69114318566933, 4.111496913580247, 4.78091049382716, 2.228885459533608, 1.6536865569272978, 0.9514860539551899, 0.0, 12.15, 10.466346593507089, 8.268432784636488, 6.686656378600823, 9.56182098765432, 5.756095679012346, 4.69114318566933, 3.125, 4.492335215681326, 3.6623167438271613, 2.0397290809327853, 1.038794581618656, 0.0),
(12.408431682614292, 11.38669074074074, 10.187814814814814, 10.977306249999998, 8.986365663448797, 4.375, 4.675828758169934, 4.0835, 4.776596666666666, 2.2211751851851855, 1.6522703703703707, 0.9500419753086421, 0.0, 12.15, 10.450461728395062, 8.261351851851853, 6.663525555555555, 9.553193333333333, 5.7169, 4.675828758169934, 3.125, 4.493182831724399, 3.659102083333334, 2.037562962962963, 1.0351537037037037, 0.0),
(12.413279342696734, 11.34626083676269, 10.176836076817558, 10.967478935185184, 8.98796235036337, 4.375, 4.660380125877511, 4.055577160493827, 4.772214691358024, 2.2134234293552817, 1.6508209627135553, 0.9485781435756746, 0.0, 12.15, 10.434359579332419, 8.254104813567777, 6.640270288065844, 9.544429382716048, 5.677808024691357, 4.660380125877511, 3.125, 4.493981175181685, 3.655826311728396, 2.035367215363512, 1.0314782578875175, 0.0),
(12.417831183979011, 11.305523113854596, 10.165725651577505, 10.957479398148147, 8.989460345266023, 4.375, 4.64482575647543, 4.0278024691358025, 4.767770493827161, 2.205646323731139, 1.6493395311136052, 0.9470967535436672, 0.0, 12.15, 10.418064288980338, 8.246697655568026, 6.616938971193416, 9.535540987654322, 5.638923456790124, 4.64482575647543, 3.125, 4.4947301726330116, 3.65249313271605, 2.0331451303155013, 1.0277748285322361, 0.0),
(12.42208625146886, 11.26455, 10.154499999999999, 10.94731875, 8.9908595013164, 4.375, 4.629194117647058, 4.000249999999999, 4.7632699999999994, 2.1978600000000004, 1.6478272727272725, 0.9456, 0.0, 12.15, 10.401599999999998, 8.239136363636362, 6.593579999999999, 9.526539999999999, 5.60035, 4.629194117647058, 3.125, 4.4954297506582, 3.649106250000001, 2.0309, 1.0240500000000001, 0.0),
(12.426043590174027, 11.223413923182441, 10.143175582990398, 10.93700810185185, 8.992159671674152, 4.375, 4.613513677075768, 3.9729938271604937, 4.758719135802469, 2.1900805898491087, 1.6462853847113108, 0.9440900777320531, 0.0, 12.15, 10.384990855052584, 8.231426923556553, 6.570241769547325, 9.517438271604938, 5.562191358024691, 4.613513677075768, 3.125, 4.496079835837076, 3.645669367283951, 2.02863511659808, 1.0203103566529494, 0.0),
(12.429702245102245, 11.182187311385459, 10.131768861454047, 10.926558564814814, 8.993360709498926, 4.375, 4.597812902444929, 3.946108024691358, 4.754123827160494, 2.182324224965707, 1.6447150642224717, 0.9425691815272064, 0.0, 12.15, 10.368260996799268, 8.223575321112358, 6.54697267489712, 9.508247654320988, 5.524551234567902, 4.597812902444929, 3.125, 4.496680354749463, 3.6421861882716056, 2.02635377229081, 1.0165624828532238, 0.0),
(12.433061261261258, 11.140942592592593, 10.120296296296297, 10.915981249999998, 8.994462467950372, 4.375, 4.582120261437908, 3.9196666666666675, 4.74949, 2.1746070370370374, 1.6431175084175085, 0.9410395061728396, 0.0, 12.15, 10.351434567901233, 8.215587542087542, 6.523821111111111, 9.49898, 5.487533333333334, 4.582120261437908, 3.125, 4.497231233975186, 3.638660416666667, 2.0240592592592597, 1.0128129629629632, 0.0),
(12.436119683658815, 11.09975219478738, 10.108774348422497, 10.905287268518517, 8.995464800188138, 4.375, 4.5664642217380775, 3.8937438271604936, 4.744823580246913, 2.1669451577503436, 1.641493914453174, 0.939503246456333, 0.0, 12.15, 10.334535711019662, 8.20746957226587, 6.50083547325103, 9.489647160493826, 5.451241358024691, 4.5664642217380775, 3.125, 4.497732400094069, 3.6350957561728396, 2.0217548696844996, 1.0090683813443075, 0.0),
(12.438876557302644, 11.05868854595336, 10.097219478737998, 10.89448773148148, 8.996367559371876, 4.375, 4.550873251028807, 3.868413580246914, 4.74013049382716, 2.1593547187928674, 1.63984547948622, 0.9379625971650665, 0.0, 12.15, 10.31758856881573, 8.1992273974311, 6.478064156378601, 9.48026098765432, 5.41577901234568, 4.550873251028807, 3.125, 4.498183779685938, 3.6314959104938276, 2.0194438957476, 1.0053353223593966, 0.0),
(12.441330927200491, 11.017824074074072, 10.085648148148147, 10.88359375, 8.997170598661228, 4.375, 4.535375816993463, 3.84375, 4.735416666666667, 2.1518518518518523, 1.6381734006734008, 0.9364197530864199, 0.0, 12.15, 10.300617283950617, 8.190867003367003, 6.455555555555556, 9.470833333333333, 5.3812500000000005, 4.535375816993463, 3.125, 4.498585299330614, 3.6278645833333343, 2.0171296296296295, 1.0016203703703705, 0.0),
(12.443481838360098, 10.977231207133059, 10.0740768175583, 10.872616435185183, 8.997873771215849, 4.375, 4.520000387315419, 3.819827160493827, 4.730688024691357, 2.1444526886145407, 1.6364788751714678, 0.9348769090077733, 0.0, 12.15, 10.283645999085506, 8.182394375857339, 6.4333580658436205, 9.461376049382714, 5.347758024691358, 4.520000387315419, 3.125, 4.498936885607924, 3.624205478395062, 2.0148153635116604, 0.9979301097393691, 0.0),
(12.445328335789204, 10.936982373113853, 10.062521947873801, 10.861566898148148, 8.998476930195388, 4.375, 4.504775429678044, 3.796719135802469, 4.72595049382716, 2.137173360768176, 1.6347631001371743, 0.9333362597165068, 0.0, 12.15, 10.266698856881574, 8.17381550068587, 6.411520082304527, 9.45190098765432, 5.315406790123457, 4.504775429678044, 3.125, 4.499238465097694, 3.620522299382717, 2.0125043895747603, 0.9942711248285323, 0.0),
(12.44686946449555, 10.897149999999998, 10.051, 10.85045625, 8.998979928759484, 4.375, 4.4897294117647055, 3.7745, 4.721209999999999, 2.13003, 1.6330272727272728, 0.9318000000000001, 0.0, 12.15, 10.249799999999999, 8.165136363636364, 6.390089999999999, 9.442419999999998, 5.2843, 4.4897294117647055, 3.125, 4.499489964379742, 3.616818750000001, 2.0102, 0.99065, 0.0),
(12.448104269486876, 10.857806515775033, 10.039527434842249, 10.839295601851852, 8.999382620067799, 4.375, 4.474890801258775, 3.7532438271604947, 4.716472469135802, 2.123038737997257, 1.6312725900985157, 0.9302703246456334, 0.0, 12.15, 10.232973571101967, 8.156362950492579, 6.369116213991769, 9.432944938271604, 5.254541358024692, 4.474890801258775, 3.125, 4.499691310033899, 3.613098533950618, 2.00790548696845, 0.9870733196159123, 0.0),
(12.449031795770926, 10.819024348422495, 10.0281207133059, 10.828096064814813, 8.999684857279973, 4.375, 4.4602880658436215, 3.7330246913580245, 4.711743827160493, 2.1162157064471883, 1.6295002494076571, 0.9287494284407863, 0.0, 12.15, 10.216243712848648, 8.147501247038285, 6.348647119341564, 9.423487654320986, 5.226234567901234, 4.4602880658436215, 3.125, 4.499842428639987, 3.609365354938272, 2.0056241426611803, 0.9835476680384088, 0.0),
(12.449651088355436, 10.780875925925926, 10.016796296296297, 10.81686875, 8.999886493555657, 4.375, 4.445949673202614, 3.7139166666666674, 4.70703, 2.1095770370370373, 1.6277114478114478, 0.9272395061728398, 0.0, 12.15, 10.199634567901235, 8.138557239057238, 6.328731111111111, 9.41406, 5.199483333333334, 4.445949673202614, 3.125, 4.499943246777828, 3.6056229166666673, 2.0033592592592595, 0.9800796296296298, 0.0),
(12.44996119224815, 10.743433676268861, 10.005570644718793, 10.805624768518516, 8.999987382054503, 4.375, 4.431904091019123, 3.695993827160495, 4.702336913580247, 2.103138861454047, 1.625907382466642, 0.9257427526291724, 0.0, 12.15, 10.183170278920894, 8.12953691233321, 6.30941658436214, 9.404673827160494, 5.1743913580246925, 4.431904091019123, 3.125, 4.499993691027251, 3.6018749228395066, 2.0011141289437586, 0.9766757887517148, 0.0),
(12.44974993737699, 10.706573503252354, 9.994405949931412, 10.794277566425121, 8.999902364237876, 4.37491880810852, 4.418109116897788, 3.6791719250114308, 4.6976351394604485, 2.0968861324941503, 1.624057197708075, 0.9242530021899743, 0.0, 12.149850180041152, 10.166783024089716, 8.120285988540376, 6.290658397482449, 9.395270278920897, 5.1508406950160035, 4.418109116897788, 3.1249420057918, 4.499951182118938, 3.598092522141708, 1.9988811899862826, 0.9733248639320324, 0.0),
(12.447770048309177, 10.669170071684588, 9.982988425925925, 10.782255163043477, 8.999128540305009, 4.374276954732511, 4.404160908807968, 3.6625493827160494, 4.692719135802469, 2.090641917211329, 1.621972567783094, 0.9227218973359325, 0.0, 12.148663194444444, 10.149940870695255, 8.10986283891547, 6.271925751633985, 9.385438271604938, 5.127569135802469, 4.404160908807968, 3.1244835390946504, 4.499564270152504, 3.5940850543478264, 1.996597685185185, 0.9699245519713263, 0.0),
(12.443862945070673, 10.63105170582769, 9.971268432784635, 10.769478411835749, 8.997599451303152, 4.373012879134278, 4.389996080736822, 3.645976223136717, 4.687561156835848, 2.0843758573388205, 1.619629777305216, 0.921142276129281, 0.0, 12.14631880144033, 10.13256503742209, 8.09814888652608, 6.25312757201646, 9.375122313671696, 5.104366712391404, 4.389996080736822, 3.123580627953056, 4.498799725651576, 3.5898261372785836, 1.9942536865569274, 0.9664592459843356, 0.0),
(12.438083592771514, 10.592241185450682, 9.959250085733881, 10.755966153381644, 8.995334463003308, 4.371147065996037, 4.375620995723392, 3.629457933241884, 4.682168884316415, 2.078088107802792, 1.6170374741567726, 0.9195152937212715, 0.0, 12.142847865226338, 10.114668230933985, 8.085187370783862, 6.234264323408375, 9.36433776863283, 5.081241106538638, 4.375620995723392, 3.1222479042828835, 4.497667231501654, 3.5853220511272155, 1.9918500171467763, 0.962931016859153, 0.0),
(12.430486956521738, 10.552761290322579, 9.946937499999999, 10.74173722826087, 8.99235294117647, 4.3687000000000005, 4.3610420168067225, 3.6129999999999995, 4.67655, 2.071778823529412, 1.614204306220096, 0.917842105263158, 0.0, 12.13828125, 10.096263157894736, 8.07102153110048, 6.215336470588234, 9.3531, 5.058199999999999, 4.3610420168067225, 3.1205000000000003, 4.496176470588235, 3.5805790760869574, 1.9893874999999999, 0.959341935483871, 0.0),
(12.421128001431383, 10.512634800212398, 9.934334790809327, 10.72681047705314, 8.98867425159364, 4.36569216582838, 4.346265507025855, 3.5966079103795154, 4.670712185642433, 2.0654481594448484, 1.6111389213775176, 0.916123865906192, 0.0, 12.132649819958848, 10.07736252496811, 8.055694606887588, 6.196344478334543, 9.341424371284866, 5.035251074531322, 4.346265507025855, 3.118351547020271, 4.49433712579682, 3.5756034923510476, 1.9868669581618656, 0.9556940727465817, 0.0),
(12.410061692610485, 10.471884494889155, 9.921446073388202, 10.711204740338164, 8.984317760025819, 4.3621440481633895, 4.331297829419833, 3.5802871513488794, 4.664663122999542, 2.0590962704752687, 1.607849967511371, 0.9143617308016269, 0.0, 12.125984439300412, 10.057979038817894, 8.039249837556856, 6.177288811425805, 9.329326245999084, 5.012402011888431, 4.331297829419833, 3.115817177259564, 4.4921588800129095, 3.5704015801127222, 1.9842892146776405, 0.9519894995353778, 0.0),
(12.397342995169081, 10.430533154121862, 9.908275462962962, 10.694938858695652, 8.97930283224401, 4.358076131687243, 4.3161453470277, 3.5640432098765435, 4.6584104938271595, 2.052723311546841, 1.604346092503987, 0.9125568551007147, 0.0, 12.118315972222222, 10.038125406107861, 8.021730462519935, 6.158169934640522, 9.316820987654319, 4.989660493827161, 4.3161453470277, 3.112911522633745, 4.489651416122005, 3.5649796195652184, 1.9816550925925924, 0.9482302867383512, 0.0),
(12.383026874217212, 10.388603557679545, 9.894827074759945, 10.678031672705314, 8.973648834019203, 4.353508901082153, 4.300814422888497, 3.5478815729309554, 4.651961979881115, 2.046329437585734, 1.6006359442376985, 0.9107103939547083, 0.0, 12.10967528292181, 10.01781433350179, 8.003179721188491, 6.138988312757201, 9.30392395976223, 4.967034202103338, 4.300814422888497, 3.1096492150586803, 4.486824417009601, 3.5593438909017725, 1.978965414951989, 0.9444185052435952, 0.0),
(12.367168294864912, 10.34611848533121, 9.881105024005485, 10.660502022946858, 8.967375131122406, 4.34846284103033, 4.285311420041268, 3.531807727480567, 4.645325262917238, 2.0399148035181156, 1.5967281705948373, 0.9088235025148608, 0.0, 12.10009323559671, 9.997058527663466, 7.983640852974187, 6.119744410554345, 9.290650525834476, 4.944530818472794, 4.285311420041268, 3.106044886450236, 4.483687565561203, 3.5535006743156203, 1.9762210048010973, 0.9405562259392011, 0.0),
(12.349822222222222, 10.30310071684588, 9.867113425925925, 10.64236875, 8.960501089324618, 4.3429584362139915, 4.269642701525055, 3.5158271604938274, 4.638508024691357, 2.0334795642701526, 1.5926314194577353, 0.9068973359324239, 0.0, 12.089600694444444, 9.975870695256662, 7.963157097288676, 6.100438692810457, 9.277016049382715, 4.922158024691359, 4.269642701525055, 3.1021131687242796, 4.480250544662309, 3.5474562500000006, 1.9734226851851853, 0.9366455197132618, 0.0),
(12.331043621399177, 10.259573031992566, 9.8528563957476, 10.623650694444443, 8.953046074396838, 4.337016171315348, 4.2538146303789, 3.4999453589391867, 4.631517946959304, 2.0270238747680143, 1.5883543387087244, 0.9049330493586505, 0.0, 12.07822852366255, 9.954263542945155, 7.941771693543622, 6.081071624304041, 9.263035893918609, 4.899923502514861, 4.2538146303789, 3.097868693796677, 4.476523037198419, 3.5412168981481487, 1.97057127914952, 0.9326884574538697, 0.0),
(12.310887457505816, 10.215558210540289, 9.838338048696844, 10.604366696859904, 8.945029452110063, 4.330656531016613, 4.2378335696418485, 3.4841678097850943, 4.624362711476909, 2.0205478899378684, 1.5839055762301377, 0.9029317979447936, 0.0, 12.066007587448558, 9.932249777392729, 7.919527881150689, 6.061643669813604, 9.248725422953818, 4.877834933699132, 4.2378335696418485, 3.093326093583295, 4.4725147260550315, 3.5347888989533023, 1.967667609739369, 0.9286871100491174, 0.0),
(12.289408695652174, 10.171079032258064, 9.8235625, 10.584535597826088, 8.936470588235293, 4.3239, 4.221705882352941, 3.4685000000000006, 4.617049999999999, 2.014051764705883, 1.5792937799043065, 0.9008947368421053, 0.0, 12.052968749999998, 9.909842105263158, 7.8964688995215315, 6.042155294117647, 9.234099999999998, 4.855900000000001, 4.221705882352941, 3.0885, 4.468235294117647, 3.5281785326086967, 1.9647125, 0.9246435483870968, 0.0),
(12.26666230094829, 10.126158276914907, 9.808533864883403, 10.564176237922705, 8.927388848543531, 4.316767062947722, 4.205437931551222, 3.4529474165523544, 4.6095874942844075, 2.007535653998225, 1.5745275976135626, 0.8988230212018388, 0.0, 12.039142875514404, 9.887053233220225, 7.8726379880678135, 6.022606961994674, 9.219174988568815, 4.834126383173296, 4.205437931551222, 3.0834050449626584, 4.4636944242717655, 3.521392079307569, 1.9617067729766806, 0.9205598433559008, 0.0),
(12.242703238504205, 10.080818724279835, 9.793256258573388, 10.543307457729467, 8.917803598805776, 4.30927820454199, 4.189036080275732, 3.4375155464106077, 4.6019828760859625, 2.0009997127410637, 1.569615677240239, 0.8967178061752463, 0.0, 12.0245608281893, 9.863895867927708, 7.848078386201194, 6.00299913822319, 9.203965752171925, 4.812521764974851, 4.189036080275732, 3.078055860387136, 4.458901799402888, 3.5144358192431566, 1.9586512517146777, 0.9164380658436215, 0.0),
(12.21758647342995, 10.035083154121864, 9.777733796296296, 10.521948097826087, 8.907734204793028, 4.301453909465021, 4.1725066915655145, 3.4222098765432096, 4.5942438271604935, 1.994444095860567, 1.5645666666666667, 0.8945802469135803, 0.0, 12.009253472222222, 9.840382716049382, 7.8228333333333335, 5.9833322875817, 9.188487654320987, 4.791093827160494, 4.1725066915655145, 3.0724670781893004, 4.453867102396514, 3.5073160326086965, 1.9555467592592592, 0.9122802867383514, 0.0),
(12.191366970835569, 9.988974346210009, 9.761970593278463, 10.500116998792272, 8.897200032276285, 4.293314662399025, 4.1558561284596145, 3.4070358939186103, 4.58637802926383, 1.9878689582829019, 1.5593892137751788, 0.8924114985680938, 0.0, 11.9932516718107, 9.81652648424903, 7.796946068875894, 5.963606874848704, 9.17275605852766, 4.769850251486054, 4.1558561284596145, 3.0666533302850176, 4.448600016138142, 3.500038999597425, 1.9523941186556926, 0.9080885769281828, 0.0),
(12.164099695831096, 9.942515080313289, 9.745970764746229, 10.477833001207731, 8.886220447026545, 4.284880948026216, 4.139090753997072, 3.391999085505258, 4.578393164151806, 1.9812744549342376, 1.5540919664481068, 0.8902127162900394, 0.0, 11.976586291152262, 9.792339879190433, 7.770459832240534, 5.943823364802712, 9.156786328303612, 4.748798719707362, 4.139090753997072, 3.0606292485901543, 4.443110223513273, 3.4926110004025777, 1.9491941529492458, 0.9038650073012082, 0.0),
(12.135839613526569, 9.895728136200717, 9.729738425925925, 10.455114945652172, 8.874814814814815, 4.276173251028807, 4.122216931216931, 3.3771049382716045, 4.570296913580247, 1.9746607407407408, 1.5486835725677832, 0.8879850552306694, 0.0, 11.959288194444444, 9.76783560753736, 7.743417862838915, 5.923982222222222, 9.140593827160494, 4.727946913580246, 4.122216931216931, 3.054409465020576, 4.437407407407408, 3.4850383152173916, 1.9459476851851853, 0.8996116487455198, 0.0),
(12.106641689032028, 9.84863629364131, 9.713277692043896, 10.431981672705316, 8.863002501412087, 4.2672120560890106, 4.105241023158234, 3.3623589391860995, 4.562096959304984, 1.9680279706285808, 1.5431726800165397, 0.8857296705412365, 0.0, 11.941388245884776, 9.743026375953601, 7.715863400082698, 5.904083911885741, 9.124193918609969, 4.707302514860539, 4.105241023158234, 3.0480086114921505, 4.431501250706043, 3.477327224235106, 1.9426555384087794, 0.8953305721492102, 0.0),
(12.076560887457505, 9.801262332404088, 9.696592678326475, 10.40845202294686, 8.850802872589364, 4.258017847889041, 4.088169392860024, 3.3477665752171926, 4.553800983081847, 1.9613762995239252, 1.537567936676709, 0.8834477173729935, 0.0, 11.922917309670781, 9.717924891102928, 7.687839683383544, 5.884128898571774, 9.107601966163694, 4.68687320530407, 4.088169392860024, 3.041441319920744, 4.425401436294682, 3.469484007648954, 1.9393185356652953, 0.8910238484003719, 0.0),
(12.045652173913043, 9.753629032258065, 9.6796875, 10.384544836956522, 8.838235294117647, 4.248611111111111, 4.071008403361344, 3.333333333333333, 4.545416666666667, 1.9547058823529415, 1.5318779904306221, 0.881140350877193, 0.0, 11.90390625, 9.692543859649122, 7.65938995215311, 5.864117647058823, 9.090833333333334, 4.666666666666666, 4.071008403361344, 3.0347222222222223, 4.419117647058823, 3.461514945652175, 1.9359375, 0.8866935483870969, 0.0),
(12.013970513508676, 9.705759172972254, 9.662566272290809, 10.360278955314012, 8.825319131767932, 4.239012330437433, 4.053764417701236, 3.319064700502972, 4.536951691815272, 1.948016874041798, 1.526111489160612, 0.8788087262050875, 0.0, 11.884385931069957, 9.66689598825596, 7.630557445803059, 5.844050622125392, 9.073903383630544, 4.646690580704161, 4.053764417701236, 3.027865950312452, 4.412659565883966, 3.4534263184380047, 1.9325132544581618, 0.8823417429974777, 0.0),
(11.981570871354446, 9.657675534315677, 9.64523311042524, 10.335673218599032, 8.812073751311223, 4.2292419905502205, 4.036443798918745, 3.304966163694559, 4.528413740283494, 1.941309429516663, 1.5202770807490107, 0.8764539985079298, 0.0, 11.864387217078187, 9.640993983587226, 7.601385403745053, 5.823928288549988, 9.056827480566987, 4.626952629172383, 4.036443798918745, 3.0208871361073006, 4.406036875655611, 3.4452244061996784, 1.9290466220850482, 0.8779705031196072, 0.0),
(11.948508212560386, 9.609400896057348, 9.62769212962963, 10.310746467391306, 8.798518518518518, 4.219320576131687, 4.01905291005291, 3.2910432098765434, 4.51981049382716, 1.9345837037037037, 1.5143834130781502, 0.8740773229369722, 0.0, 11.84394097222222, 9.614850552306692, 7.57191706539075, 5.80375111111111, 9.03962098765432, 4.607460493827161, 4.01905291005291, 3.0138004115226336, 4.399259259259259, 3.436915489130436, 1.925538425925926, 0.8735818996415772, 0.0),
(11.914837502236535, 9.56095803796628, 9.609947445130317, 10.285517542270531, 8.784672799160816, 4.209268571864045, 4.0015981141427766, 3.277301326017376, 4.511149634202103, 1.9278398515290893, 1.5084391340303622, 0.8716798546434675, 0.0, 11.823078060699588, 9.588478401078142, 7.54219567015181, 5.783519554587267, 9.022299268404206, 4.588221856424326, 4.0015981141427766, 3.0066204084743178, 4.392336399580408, 3.4285058474235113, 1.9219894890260634, 0.8691780034514802, 0.0),
(11.880613705492932, 9.512369739811495, 9.592003172153635, 10.260005283816424, 8.770555959009117, 4.199106462429508, 3.984085774227386, 3.2637459990855056, 4.5024388431641515, 1.9210780279189867, 1.5024528914879791, 0.869262748778668, 0.0, 11.801829346707818, 9.561890236565347, 7.512264457439896, 5.763234083756959, 9.004877686328303, 4.569244398719708, 3.984085774227386, 2.9993617588782198, 4.385277979504559, 3.4200017612721423, 1.9184006344307272, 0.8647608854374088, 0.0),
(11.845891787439614, 9.463658781362009, 9.573863425925927, 10.234228532608697, 8.756187363834421, 4.188854732510288, 3.966522253345782, 3.250382716049383, 4.493685802469135, 1.9142983877995645, 1.4964333333333335, 0.8668271604938274, 0.0, 11.780225694444445, 9.5350987654321, 7.482166666666667, 5.742895163398693, 8.98737160493827, 4.5505358024691365, 3.966522253345782, 2.9920390946502056, 4.3780936819172105, 3.411409510869566, 1.9147726851851854, 0.8603326164874555, 0.0),
(11.810726713186616, 9.414847942386832, 9.555532321673525, 10.208206129227051, 8.74158637940773, 4.178533866788599, 3.948913914537008, 3.237216963877458, 4.484898193872885, 1.9075010860969905, 1.4903891074487565, 0.864374244940197, 0.0, 11.758297968106996, 9.508116694342165, 7.451945537243782, 5.7225032582909705, 8.96979638774577, 4.532103749428441, 3.948913914537008, 2.984667047706142, 4.370793189703865, 3.402735376409018, 1.911106464334705, 0.8558952674897121, 0.0),
(11.775173447843981, 9.365960002654985, 9.53701397462277, 10.181956914251208, 8.72677237150004, 4.168164349946655, 3.931267120840105, 3.22425422953818, 4.476083699131229, 1.9006862777374327, 1.484328861716581, 0.8619051572690299, 0.0, 11.736077031893004, 9.480956729959328, 7.421644308582906, 5.702058833212297, 8.952167398262459, 4.513955921353452, 3.931267120840105, 2.9772602499618963, 4.36338618575002, 3.3939856380837368, 1.9074027949245542, 0.8514509093322715, 0.0),
(11.739286956521738, 9.317017741935484, 9.5183125, 10.15549972826087, 8.711764705882352, 4.157766666666667, 3.913588235294118, 3.2115, 4.46725, 1.893854117647059, 1.4782612440191387, 0.859421052631579, 0.0, 11.71359375, 9.453631578947368, 7.391306220095694, 5.681562352941175, 8.9345, 4.4961, 3.913588235294118, 2.9698333333333333, 4.355882352941176, 3.385166576086957, 1.9036625000000003, 0.8470016129032258, 0.0),
(11.703122204329933, 9.268043939997343, 9.49943201303155, 10.128853411835749, 8.696582748325667, 4.147361301630848, 3.895883620938087, 3.1989597622313672, 4.458404778235025, 1.8870047607520377, 1.4721949022387621, 0.8569230861790968, 0.0, 11.690878986625515, 9.426153947970063, 7.36097451119381, 5.661014282256112, 8.91680955647005, 4.4785436671239145, 3.895883620938087, 2.9624009297363205, 4.348291374162834, 3.376284470611917, 1.89988640260631, 0.8425494490906678, 0.0),
(11.6667341563786, 9.219061376609584, 9.480376628943759, 10.102036805555556, 8.681245864600983, 4.136968739521414, 3.878159640811057, 3.1866390032007312, 4.449555715592135, 1.8801383619785366, 1.4661384842577825, 0.8544124130628354, 0.0, 11.667963605967076, 9.398536543691188, 7.330692421288911, 5.640415085935608, 8.89911143118427, 4.461294604481024, 3.878159640811057, 2.9549776710867244, 4.340622932300492, 3.367345601851853, 1.8960753257887522, 0.8380964887826896, 0.0),
(11.630177777777778, 9.170092831541218, 9.461150462962962, 10.07506875, 8.665773420479303, 4.126609465020577, 3.8604226579520695, 3.174543209876543, 4.44071049382716, 1.8732550762527238, 1.4601006379585326, 0.8518901884340482, 0.0, 11.644878472222222, 9.37079207277453, 7.300503189792663, 5.61976522875817, 8.88142098765432, 4.44436049382716, 3.8604226579520695, 2.947578189300412, 4.332886710239651, 3.358356250000001, 1.8922300925925928, 0.8336448028673837, 0.0),
(11.593508033637502, 9.121161084561264, 9.4417576303155, 10.047968085748792, 8.650184781731623, 4.116303962810547, 3.842679035400168, 3.162677869227252, 4.43187679469593, 1.8663550585007669, 1.4540900112233446, 0.8493575674439874, 0.0, 11.621654449588474, 9.342933241883859, 7.270450056116723, 5.599065175502299, 8.86375358939186, 4.427749016918153, 3.842679035400168, 2.940217116293248, 4.325092390865811, 3.3493226952495982, 1.8883515260631, 0.8291964622328422, 0.0),
(11.556779889067812, 9.072288915438735, 9.422202246227709, 10.020753653381641, 8.634499314128943, 4.10607271757354, 3.8249351361943953, 3.151048468221308, 4.423062299954275, 1.8594384636488344, 1.44811525193455, 0.8468157052439055, 0.0, 11.598322402263374, 9.314972757682959, 7.24057625967275, 5.578315390946502, 8.84612459990855, 4.411467855509831, 3.8249351361943953, 2.9329090839811003, 4.317249657064472, 3.3402512177938815, 1.884440449245542, 0.8247535377671579, 0.0),
(11.520048309178742, 9.023499103942651, 9.402488425925926, 9.99344429347826, 8.618736383442265, 4.09593621399177, 3.8071973233737944, 3.1396604938271606, 4.414274691358024, 1.8525054466230941, 1.4421850079744816, 0.8442657569850553, 0.0, 11.574913194444443, 9.286923326835607, 7.210925039872408, 5.557516339869281, 8.828549382716048, 4.395524691358025, 3.8071973233737944, 2.9256687242798356, 4.309368191721132, 3.331148097826088, 1.8804976851851853, 0.8203181003584229, 0.0),
(11.483368259080336, 8.974814429842029, 9.382620284636488, 9.966058846618358, 8.602915355442589, 4.0859149367474465, 3.7894719599774067, 3.12851943301326, 4.405521650663008, 1.8455561623497139, 1.436307927225471, 0.8417088778186895, 0.0, 11.551457690329217, 9.258797656005584, 7.181539636127354, 5.53666848704914, 8.811043301326016, 4.379927206218564, 3.7894719599774067, 2.918510669105319, 4.301457677721294, 3.3220196155394537, 1.8765240569272976, 0.81589222089473, 0.0),
(11.446794703882626, 8.926257672905882, 9.362601937585735, 9.938616153381641, 8.58705559590091, 4.076029370522787, 3.7717654090442765, 3.117630772748057, 4.396810859625057, 1.838590765754862, 1.4304926575698504, 0.8391462228960604, 0.0, 11.527986754115226, 9.230608451856664, 7.152463287849251, 5.515772297264585, 8.793621719250114, 4.36468308184728, 3.7717654090442765, 2.911449550373419, 4.293527797950455, 3.312872051127215, 1.8725203875171472, 0.8114779702641711, 0.0),
(11.410382608695652, 8.877851612903227, 9.3424375, 9.911135054347826, 8.571176470588235, 4.0663, 3.7540840336134447, 3.107, 4.3881499999999996, 1.8316094117647064, 1.4247478468899522, 0.8365789473684213, 0.0, 11.504531250000001, 9.202368421052633, 7.12373923444976, 5.494828235294118, 8.776299999999999, 4.3498, 3.7540840336134447, 2.9045, 4.285588235294117, 3.3037116847826096, 1.8684875000000005, 0.8070774193548388, 0.0),
(11.374186938629451, 8.82961902960308, 9.322131087105625, 9.883634390096615, 8.555297345275559, 4.056747309861302, 3.7364341967239567, 3.0966326017375403, 4.379546753543667, 1.8246122553054145, 1.4190821430681082, 0.8340082063870239, 0.0, 11.48112204218107, 9.174090270257262, 7.09541071534054, 5.473836765916242, 8.759093507087334, 4.335285642432557, 3.7364341967239567, 2.8976766499009297, 4.277648672637779, 3.294544796698873, 1.864426217421125, 0.8026926390548256, 0.0),
(11.338262658794058, 8.78158270277446, 9.301686814128946, 9.85613300120773, 8.539437585733882, 4.047391784788904, 3.7188222614148536, 3.0865340649291264, 4.371008802011888, 1.8175994513031553, 1.4135041939866502, 0.8314351551031215, 0.0, 11.457789994855966, 9.145786706134334, 7.067520969933251, 5.452798353909465, 8.742017604023776, 4.321147690900777, 3.7188222614148536, 2.8909941319920742, 4.269718792866941, 3.2853776670692443, 1.8603373628257893, 0.7983257002522237, 0.0),
(11.302664734299517, 8.733765412186381, 9.281108796296298, 9.82864972826087, 8.523616557734204, 4.038253909465022, 3.7012545907251786, 3.0767098765432097, 4.3625438271604935, 1.8105711546840961, 1.4080226475279107, 0.8288609486679663, 0.0, 11.434565972222222, 9.117470435347629, 7.040113237639553, 5.431713464052287, 8.725087654320987, 4.307393827160493, 3.7012545907251786, 2.8844670781893007, 4.261808278867102, 3.2762165760869575, 1.8562217592592598, 0.7939786738351257, 0.0),
(11.26744813025586, 8.686189937607857, 9.26040114883402, 9.801203411835749, 8.507853627047526, 4.029354168571865, 3.6837375476939744, 3.0671655235482396, 4.354159510745312, 1.803527520374405, 1.402646151574222, 0.8262867422328111, 0.0, 11.411480838477365, 9.08915416456092, 7.013230757871109, 5.4105825611232135, 8.708319021490624, 4.294031732967535, 3.6837375476939744, 2.8781101204084747, 4.253926813523763, 3.2670678039452503, 1.8520802297668042, 0.7896536306916234, 0.0),
(11.232605068443652, 8.638958480664547, 9.239617828252069, 9.773850494242836, 8.492140544138962, 4.02070883845016, 3.6663155781940615, 3.057926284390303, 4.3458851245034475, 1.7964914209838192, 1.3973847812305735, 0.8237192936504428, 0.0, 11.388532681011865, 9.06091223015487, 6.9869239061528665, 5.389474262951456, 8.691770249006895, 4.281096798146424, 3.6663155781940615, 2.8719348846072568, 4.246070272069481, 3.257950164747613, 1.8479235656504138, 0.7853598618785952, 0.0),
(11.197777077480078, 8.592536901878088, 9.219045675021619, 9.746810479149604, 8.47631468365306, 4.012298225970931, 3.649210925046347, 3.04910562975256, 4.337847614285224, 1.7895945503738353, 1.3922488674226394, 0.8211912172112975, 0.0, 11.365530496992042, 9.033103389324271, 6.961244337113197, 5.368783651121505, 8.675695228570447, 4.268747881653584, 3.649210925046347, 2.8659273042649507, 4.23815734182653, 3.248936826383202, 1.8438091350043238, 0.7811397183525536, 0.0),
(11.162861883604794, 8.546941918551349, 9.198696932707318, 9.7200760546636, 8.46032614231088, 4.004100458749136, 3.6324357901149367, 3.0407013271393546, 4.330049991467515, 1.7828475983964234, 1.3872309022854188, 0.8187037582558852, 0.0, 11.342407957992451, 9.005741340814735, 6.936154511427093, 5.348542795189269, 8.66009998293503, 4.256981857995097, 3.6324357901149367, 2.8600717562493823, 4.23016307115544, 3.2400253515545345, 1.8397393865414637, 0.7769947198683046, 0.0),
(11.127815847885161, 8.502107109420871, 9.178532189983873, 9.693599535239764, 8.444150821107023, 3.9960962141009686, 3.6159628905167356, 3.0326901564494966, 4.322472535691132, 1.7762380075348645, 1.3823211862542963, 0.8162523197487347, 0.0, 11.319128711707068, 8.97877551723608, 6.911605931271482, 5.328714022604592, 8.644945071382264, 4.245766219029295, 3.6159628905167356, 2.854354438643549, 4.222075410553511, 3.231199845079922, 1.835706437996775, 0.7729188281291702, 0.0),
(11.092595331388527, 8.457966053223192, 9.158512035525986, 9.66733323533302, 8.427764621036088, 3.988266169342624, 3.5997649433686516, 3.0250488975817924, 4.315095526596881, 1.769753220272439, 1.3775100197646568, 0.8138323046543751, 0.0, 11.295656405829869, 8.952155351198124, 6.887550098823283, 5.309259660817316, 8.630191053193762, 4.23506845661451, 3.5997649433686516, 2.8487615495304452, 4.213882310518044, 3.222444411777674, 1.8317024071051975, 0.768906004838472, 0.0),
(11.057156695182252, 8.414452328694855, 9.138597058008367, 9.6412294693983, 8.411143443092673, 3.980591001790297, 3.583814665787589, 3.0177543304350483, 4.307899243825574, 1.7633806790924282, 1.3727877032518847, 0.811439115937335, 0.0, 11.271954688054828, 8.925830275310684, 6.863938516259424, 5.290142037277283, 8.615798487651148, 4.224856062609067, 3.583814665787589, 2.843279286993069, 4.205571721546336, 3.213743156466101, 1.8277194116016737, 0.7649502116995325, 0.0),
(11.02145630033369, 8.3714995145724, 9.118747846105723, 9.615240551890535, 8.394263188271376, 3.973051388760183, 3.5680847748904534, 3.0107832349080725, 4.300863967018017, 1.757107826478112, 1.3681445371513656, 0.8090681565621435, 0.0, 11.247987206075917, 8.899749722183577, 6.840722685756828, 5.271323479434335, 8.601727934036035, 4.215096528871301, 3.5680847748904534, 2.8378938491144163, 4.197131594135688, 3.2050801839635126, 1.8237495692211447, 0.761045410415673, 0.0),
(10.985450507910194, 8.329041189592374, 9.098924988492762, 9.589318797264655, 8.377099757566796, 3.965628007568476, 3.5525479877941515, 3.0041123908996714, 4.293969975815023, 1.7509221049127721, 1.3635708218984832, 0.8067148294933297, 0.0, 11.223717607587115, 8.873863124426626, 6.817854109492416, 5.252766314738315, 8.587939951630046, 4.20575734725954, 3.5525479877941515, 2.8325914339774827, 4.188549878783398, 3.1964395990882193, 1.8197849976985525, 0.7571855626902159, 0.0),
(10.949095678979122, 8.287010932491311, 9.079089073844187, 9.56341651997559, 8.359629051973535, 3.9583015355313718, 3.5371770216155882, 2.9977185783086533, 4.2871975498573995, 1.7448109568796892, 1.3590568579286233, 0.8043745376954222, 0.0, 11.199109540282393, 8.848119914649644, 6.795284289643115, 5.234432870639067, 8.574395099714799, 4.196806009632114, 3.5371770216155882, 2.8273582396652652, 4.179814525986767, 3.1878055066585307, 1.8158178147688375, 0.753364630226483, 0.0),
(10.912348174607825, 8.245342322005756, 9.059200690834711, 9.537486034478269, 8.341826972486187, 3.951052649965064, 3.5219445934716704, 2.9915785770338243, 4.2805269687859555, 1.7387618248621435, 1.3545929456771704, 0.8020426841329501, 0.0, 11.174126651855724, 8.82246952546245, 6.772964728385852, 5.216285474586429, 8.561053937571911, 4.1882100078473545, 3.5219445934716704, 2.8221804642607595, 4.170913486243093, 3.1791620114927572, 1.8118401381669422, 0.7495765747277962, 0.0),
(10.875164355863662, 8.20396893687225, 9.039220428139036, 9.511479655227625, 8.323669420099352, 3.9438620281857477, 3.506823420479303, 2.9856691669739917, 4.273938512241501, 1.7327621513434166, 1.3501693855795087, 0.7997146717704421, 0.0, 11.148732590001085, 8.796861389474863, 6.750846927897544, 5.1982864540302485, 8.547877024483002, 4.1799368337635885, 3.506823420479303, 2.8170443058469625, 4.161834710049676, 3.170493218409209, 1.8078440856278073, 0.7458153578974774, 0.0),
(10.837500583813984, 8.162824355827334, 9.01910887443187, 9.485349696678588, 8.30513229580763, 3.9367103475096172, 3.4917862197553915, 2.979967128027963, 4.267412459864846, 1.7267993788067886, 1.345776478071024, 0.7973859035724276, 0.0, 11.122891002412453, 8.771244939296702, 6.728882390355119, 5.180398136420364, 8.534824919729692, 4.171953979239149, 3.4917862197553915, 2.8119359625068694, 4.152566147903815, 3.1617832322261967, 1.803821774886374, 0.7420749414388487, 0.0),
(10.79931321952615, 8.121842157607551, 8.998826618387923, 9.459048473286083, 8.286191500605618, 3.9295782852528696, 3.4768057084168436, 2.9744492400945455, 4.260929091296797, 1.7208609497355405, 1.3414045235871004, 0.7950517825034348, 0.0, 11.096565536783794, 8.745569607537782, 6.707022617935502, 5.16258284920662, 8.521858182593594, 4.164228936132364, 3.4768057084168436, 2.806841632323478, 4.143095750302809, 3.153016157762029, 1.799765323677585, 0.7383492870552321, 0.0),
(10.760558624067514, 8.080955920949442, 8.978334248681898, 9.432528299505048, 8.266822935487914, 3.9224465187316975, 3.461854603580562, 2.969092283072546, 4.254468686178167, 1.7149343066129532, 1.3370438225631227, 0.7927077115279934, 0.0, 11.069719840809094, 8.719784826807926, 6.685219112815614, 5.144802919838858, 8.508937372356334, 4.156729196301565, 3.461854603580562, 2.801747513379784, 4.133411467743957, 3.144176099835017, 1.79566684973638, 0.7346323564499494, 0.0),
(10.721193158505432, 8.040099224589545, 8.957592353988504, 9.405741489790408, 8.247002501449117, 3.915295725262296, 3.4469056223634564, 2.9638730368607726, 4.248011524149763, 1.7090068919223076, 1.3326846754344757, 0.7903490936106315, 0.0, 11.042317562182317, 8.693840029716947, 6.6634233771723785, 5.127020675766921, 8.496023048299525, 4.149422251605082, 3.4469056223634564, 2.7966398037587825, 4.1235012507245585, 3.1352471632634704, 1.7915184707977012, 0.7309181113263225, 0.0),
(10.681173183907255, 7.999205647264407, 8.93656152298245, 9.3786403585971, 8.226706099483831, 3.908106582160861, 3.431931481882429, 2.958768281358031, 4.241537884852393, 1.703066148146884, 1.328317382636545, 0.7879713317158789, 0.0, 11.014322348597444, 8.667684648874667, 6.641586913182724, 5.109198444440651, 8.483075769704786, 4.1422755939012434, 3.431931481882429, 2.791504701543472, 4.1133530497419155, 3.1262134528657004, 1.7873123045964903, 0.7272005133876734, 0.0),
(10.640455061340337, 7.958208767710564, 8.91520234433844, 9.351177220380043, 8.205909630586648, 3.9008597667435865, 3.4169048992543876, 2.95375479646313, 4.235028047926869, 1.697099517769964, 1.3239322446047141, 0.7855698288082636, 0.0, 10.985697847748446, 8.641268116890899, 6.619661223023571, 5.0912985533098905, 8.470056095853739, 4.135256715048382, 3.4169048992543876, 2.7863284048168473, 4.102954815293324, 3.117059073460015, 1.783040468867688, 0.7234735243373241, 0.0),
(10.598995151872039, 7.917042164664562, 8.893475406731179, 9.323304389594178, 8.18458899575217, 3.893535956326666, 3.4017985915962377, 2.948809362074875, 4.228462293014, 1.6910944432748274, 1.3195195617743691, 0.7831399878523152, 0.0, 10.956407707329298, 8.614539866375466, 6.5975978088718445, 5.073283329824481, 8.456924586028, 4.128333106904826, 3.4017985915962377, 2.781097111661904, 4.092294497876085, 3.1077681298647266, 1.7786950813462359, 0.7197311058785967, 0.0),
(10.556749816569713, 7.8756394168629384, 8.87134129883538, 9.294974180694428, 8.162720095974995, 3.886115828226296, 3.3865852760248853, 2.943908758092075, 4.221820899754594, 1.685038367144756, 1.3150696345808937, 0.7806772118125626, 0.0, 10.926415575033973, 8.587449329938186, 6.575348172904468, 5.055115101434266, 8.443641799509187, 4.121472261328905, 3.3865852760248853, 2.77579702016164, 4.081360047987498, 3.0983247268981433, 1.7742682597670765, 0.7159672197148127, 0.0),
(10.51367541650071, 7.833934103042237, 8.848760609325746, 9.266138908135728, 8.140278832249722, 3.878580059758672, 3.3712376696572353, 2.9390297644135366, 4.215084147789462, 1.6789187318630299, 1.310572763459673, 0.7781769036535342, 0.0, 10.89568509855645, 8.559945940188875, 6.552863817298364, 5.0367561955890885, 8.430168295578923, 4.114641670178951, 3.3712376696572353, 2.770414328399051, 4.070139416124861, 3.088712969378577, 1.7697521218651495, 0.7121758275492944, 0.0),
(10.469728312732395, 7.791859801938998, 8.825693926876983, 9.236750886373006, 8.117241105570947, 3.870909328239987, 3.3557284896101933, 2.934149160938066, 4.2082323167594105, 1.67272297991293, 1.306019248846092, 0.7756344663397593, 0.0, 10.864179925590703, 8.531979129737351, 6.53009624423046, 5.018168939738788, 8.416464633518821, 4.107808825313293, 3.3557284896101933, 2.764935234457133, 4.058620552785474, 3.078916962124336, 1.765138785375397, 0.7083508910853636, 0.0),
(10.424864866332113, 7.749350092289764, 8.802101840163804, 9.206762429861191, 8.093582816933273, 3.863084310986436, 3.3400304530006673, 2.929243727564472, 4.201245686305251, 1.6664385537777375, 1.3013993911755357, 0.7730453028357667, 0.0, 10.831863703830699, 8.503498331193432, 6.506996955877678, 4.9993156613332115, 8.402491372610502, 4.100941218590261, 3.3400304530006673, 2.7593459364188826, 4.046791408466636, 3.0689208099537315, 1.7604203680327608, 0.7044863720263422, 0.0),
(10.379041438367224, 7.706338552831077, 8.777944937860909, 9.17612585305522, 8.069279867331296, 3.8550856853142146, 3.3241162769455603, 2.92429024419156, 4.194104536067791, 1.6600528959407332, 1.2967034908833885, 0.7704048161060852, 0.0, 10.798700080970423, 8.474452977166937, 6.483517454416942, 4.980158687822199, 8.388209072135583, 4.094006341868184, 3.3241162769455603, 2.753632632367296, 4.034639933665648, 3.0587086176850744, 1.755588987572182, 0.7005762320755525, 0.0),
(10.332214389905081, 7.6627587622994735, 8.753183808643008, 9.144793470410015, 8.044308157759612, 3.8468941285395175, 3.3079586785617807, 2.9192654907181383, 4.186789145687842, 1.653553448885197, 1.2919218484050357, 0.7677084091152441, 0.0, 10.764652704703844, 8.444792500267685, 6.459609242025177, 4.96066034665559, 8.373578291375685, 4.086971687005394, 3.3079586785617807, 2.7477815203853697, 4.022154078879806, 3.0482644901366727, 1.750636761728602, 0.6966144329363159, 0.0),
(10.28434008201304, 7.618544299431501, 8.72777904118481, 9.112717596380511, 8.018643589212827, 3.838490317978539, 3.291530374966233, 2.9141462470430146, 4.179279794806213, 1.6469276550944107, 1.2870447641758613, 0.764951484827772, 0.0, 10.729685222724932, 8.41446633310549, 6.435223820879306, 4.940782965283231, 8.358559589612426, 4.079804745860221, 3.291530374966233, 2.741778798556099, 4.0093217946064135, 3.037572532126838, 1.7455558082369622, 0.6925949363119547, 0.0),
(10.235374875758456, 7.573628742963698, 8.701691224161017, 9.079850545421637, 7.992262062685534, 3.8298549309474748, 3.2748040832758227, 2.908909293064995, 4.1715567630637125, 1.6401629570516543, 1.2820625386312503, 0.7621294462081979, 0.0, 10.693761282727667, 8.383423908290176, 6.410312693156252, 4.920488871154961, 8.343113526127425, 4.0724730102909925, 3.2748040832758227, 2.735610664962482, 3.996131031342767, 3.02661684847388, 1.7403382448322038, 0.6885117039057909, 0.0),
(10.185275132208682, 7.527945671632606, 8.67488094624634, 9.046144631988323, 7.965139479172331, 3.8209686447625186, 3.2577525206074553, 2.903531408682887, 4.163600330101148, 1.6332467972402094, 1.276965472206588, 0.7592376962210506, 0.0, 10.656844532406023, 8.351614658431556, 6.38482736103294, 4.899740391720627, 8.327200660202296, 4.064943972156042, 3.2577525206074553, 2.729263317687513, 3.9825697395861654, 3.0153815439961082, 1.7349761892492683, 0.6843586974211461, 0.0),
(10.133997212431076, 7.481428664174767, 8.647308796115487, 9.011552170535499, 7.937251739667823, 3.811812136739866, 3.240348404078038, 2.897989373795498, 4.155390775559333, 1.626166618143356, 1.2717438653372588, 0.7562716378308593, 0.0, 10.618898619453978, 8.31898801613945, 6.358719326686294, 4.878499854430067, 8.310781551118666, 4.0571851233136975, 3.240348404078038, 2.7227229548141896, 3.9686258698339114, 3.003850723511834, 1.7294617592230976, 0.6801298785613425, 0.0),
(10.081497477492995, 7.4340112993267216, 8.61893536244316, 8.976025475518098, 7.908574745166602, 3.802366084195711, 3.222564450804477, 2.892259968301635, 4.146908379079072, 1.6189098622443758, 1.2663880184586478, 0.7532266740021526, 0.0, 10.579887191565495, 8.285493414023676, 6.331940092293238, 4.856729586733126, 8.293816758158144, 4.049163955622289, 3.222564450804477, 2.7159757744255075, 3.954287372583301, 2.9920084918393663, 1.7237870724886322, 0.675819209029702, 0.0),
(10.027732288461786, 7.385627155825012, 8.58972123390407, 8.939516861391049, 7.879084396663268, 3.792611164446249, 3.2043733779036754, 2.8863199721001056, 4.138133420301177, 1.6114639720265487, 1.2608882320061394, 0.7500982076994595, 0.0, 10.539773896434559, 8.251080284694053, 6.304441160030697, 4.834391916079644, 8.276266840602354, 4.040847960940148, 3.2043733779036754, 2.7090079746044635, 3.939542198331634, 2.9798389537970165, 1.7179442467808141, 0.6714206505295467, 0.0),
(9.972658006404808, 7.336209812406179, 8.559626999172925, 8.901978642609278, 7.848756595152423, 3.7825280548076745, 3.185747902492541, 2.880146165089716, 4.129046178866458, 1.6038163899731561, 1.2552348064151186, 0.746881641887309, 0.0, 10.49852238175514, 8.215698060760397, 6.276174032075593, 4.811449169919467, 8.258092357732917, 4.032204631125603, 3.185747902492541, 2.701805753434053, 3.9243782975762116, 2.967326214203093, 1.7119253998345851, 0.6669281647641981, 0.0),
(9.916230992389421, 7.285692847806764, 8.528613246924428, 8.86336313362772, 7.817567241628662, 3.772097432596183, 3.1666607416879793, 2.8737153271692746, 4.119626934415724, 1.5959545585674784, 1.2494180421209704, 0.7435723795302299, 0.0, 10.456096295221217, 8.179296174832528, 6.247090210604851, 4.787863675702434, 8.239253868831447, 4.023201458036985, 3.1666607416879793, 2.6943553089972734, 3.908783620814331, 2.954454377875907, 1.7057226493848856, 0.6623357134369786, 0.0),
(9.858407607482972, 7.234009840763308, 8.496640565833289, 8.823622648901305, 7.785492237086586, 3.7612999751279688, 3.147084612606896, 2.867004238237588, 4.109855966589781, 1.5878659202927967, 1.2434282395590792, 0.7401658235927514, 0.0, 10.41245928452676, 8.141824059520264, 6.217141197795395, 4.763597760878389, 8.219711933179562, 4.013805933532623, 3.147084612606896, 2.6866428393771202, 3.892746118543293, 2.9412075496337686, 1.699328113166658, 0.6576372582512099, 0.0),
(9.79914421275282, 7.181094370012356, 8.463669544574216, 8.782709502884963, 7.752507482520793, 3.750116359719226, 3.126992232366198, 2.8599896781934633, 4.099713555029442, 1.5795379176323916, 1.2372556991648298, 0.7366573770394019, 0.0, 10.367574997365741, 8.103231147433421, 6.186278495824149, 4.738613752897173, 8.199427110058885, 4.0039855494708485, 3.126992232366198, 2.67865454265659, 3.8762537412603963, 2.927569834294988, 1.6927339089148434, 0.6528267609102142, 0.0),
(9.73839716926632, 7.126880014290443, 8.42966077182191, 8.740576010033621, 7.71858887892588, 3.7385272636861506, 3.1063563180827884, 2.8526484269357075, 4.0891799793755155, 1.570957993069544, 1.2308907213736073, 0.7330424428347111, 0.0, 10.321407081432142, 8.06346687118182, 6.154453606868036, 4.712873979208631, 8.178359958751031, 3.9937077977099906, 3.1063563180827884, 2.670376616918679, 3.85929443946294, 2.9135253366778744, 1.6859321543643822, 0.6478981831173131, 0.0),
(9.676122838090825, 7.071300352334116, 8.394574836251083, 8.697174484802217, 7.6837123272964485, 3.726513364344937, 3.085149586873576, 2.8449572643631287, 4.078235519268811, 1.5621135890875346, 1.2243236066207965, 0.729316423943207, 0.0, 10.27391918441993, 8.022480663375276, 6.1216180331039824, 4.686340767262602, 8.156471038537623, 3.9829401701083804, 3.085149586873576, 2.6617952602463837, 3.8418561636482242, 2.899058161600739, 1.6789149672502168, 0.6428454865758287, 0.0),
(9.612277580293695, 7.014288962879912, 8.358372326536443, 8.652457241645672, 7.647853728627096, 3.71405533901178, 3.0633447558554643, 2.8368929703745334, 4.0668604543501345, 1.5529921481696445, 1.2175446553417821, 0.7254747233294191, 0.0, 10.225074954023084, 7.980221956623609, 6.08772327670891, 4.658976444508932, 8.133720908700269, 3.971650158524347, 3.0633447558554643, 2.6528966707226997, 3.823926864313548, 2.8841524138818913, 1.671674465307289, 0.637662632989083, 0.0),
(9.546817756942277, 6.955779424664377, 8.321013831352694, 8.606376595018924, 7.610988983912421, 3.7011338650028747, 3.04091454214536, 2.828432324868728, 4.0550350642603, 1.5435811127991534, 1.2105441679719486, 0.7215127439578762, 0.0, 10.174838037935576, 7.936640183536638, 6.0527208398597425, 4.630743338397459, 8.1100701285206, 3.95980525481622, 3.04091454214536, 2.6436670464306244, 3.8054944919562104, 2.8687921983396416, 1.6642027662705388, 0.632343584060398, 0.0),
(9.47969972910393, 6.895705316424048, 8.282459939374542, 8.558884859376896, 7.573093994147021, 3.6877296196344136, 3.01783166286017, 2.8195521077445216, 4.042739628640115, 1.5338679254593437, 1.203312444946681, 0.7174258887931072, 0.0, 10.123172083851381, 7.891684776724178, 6.016562224733405, 4.601603776378029, 8.08547925728023, 3.9473729508423303, 3.01783166286017, 2.6340925854531525, 3.7865469970735104, 2.8529616197922993, 1.6564919878749085, 0.6268823014930954, 0.0),
(9.41087985784601, 6.83400021689547, 8.242671239276701, 8.509934349174525, 7.534144660325495, 3.6738232802225945, 2.9940688351167988, 2.8102290989007206, 4.029954427130388, 1.5238400286334952, 1.1958397867013644, 0.713209560799641, 0.0, 10.070040739464476, 7.84530516879605, 5.979198933506821, 4.5715200859004845, 8.059908854260776, 3.9343207384610093, 2.9940688351167988, 2.6241594858732817, 3.7670723301627476, 2.836644783058176, 1.6485342478553402, 0.6212727469904974, 0.0),
(9.340314504235872, 6.770597704815181, 8.201608319733868, 8.459477378866739, 7.4941168834424445, 3.659395524083611, 2.9695987760321514, 2.800440078236131, 4.016659739371929, 1.513484864804889, 1.1881164936713833, 0.7088591629420063, 0.0, 10.015407652468832, 7.797450792362069, 5.940582468356916, 4.5404545944146655, 8.033319478743858, 3.9206161095305836, 2.9695987760321514, 2.6138539457740078, 3.7470584417212223, 2.81982579295558, 1.6403216639467737, 0.6155088822559257, 0.0),
(9.267960029340873, 6.705431358919725, 8.159231769420758, 8.407466262908468, 7.4529865644924636, 3.644427028533658, 2.944394202723137, 2.7901618256495615, 4.002835845005546, 1.5027898764568062, 1.1801328662921224, 0.7043700981847325, 0.0, 9.959236470558428, 7.748071080032056, 5.900664331460612, 4.508369629370417, 8.005671690011091, 3.9062265559093863, 2.944394202723137, 2.603162163238327, 3.7264932822462318, 2.802488754302823, 1.631846353884152, 0.6095846689927024, 0.0),
(9.193772794228362, 6.638434757945644, 8.115502177012075, 8.35385331575464, 7.4107296044701565, 3.62889847088893, 2.9184278323066564, 2.779371121039818, 3.988463023672051, 1.4917425060725265, 1.1718792049989668, 0.6997377694923482, 0.0, 9.901490841427231, 7.6971154644158295, 5.859396024994833, 4.4752275182175785, 7.976926047344102, 3.8911195694557454, 2.9184278323066564, 2.5920703363492357, 3.7053648022350782, 2.7846177719182137, 1.6231004354024152, 0.6034940689041496, 0.0),
(9.117709159965697, 6.569541480629476, 8.070380131182526, 8.298590851860187, 7.367321904370117, 3.612790528465623, 2.8916723818996197, 2.7680447443057092, 3.9735215550122502, 1.480330196135332, 1.163345810227301, 0.6949575798293822, 0.0, 9.842134412769221, 7.644533378123204, 5.816729051136504, 4.440990588405995, 7.9470431100245005, 3.875262642027993, 2.8916723818996197, 2.5805646631897305, 3.6836609521850585, 2.766196950620063, 1.6140760262365055, 0.5972310436935888, 0.0),
(9.039725487620235, 6.498685105707764, 8.023826220606818, 8.241631185680044, 7.322739365186948, 3.59608387857993, 2.864100568618931, 2.756159475346041, 3.957991718666955, 1.4685403891285025, 1.1545229824125098, 0.6900249321603636, 0.0, 9.781130832278372, 7.590274253763999, 5.772614912062549, 4.405621167385506, 7.91598343733391, 3.8586232654844577, 2.864100568618931, 2.568631341842807, 3.661369682593474, 2.7472103952266815, 1.6047652441213638, 0.5907895550643424, 0.0),
(8.957617135686286, 6.424498432849483, 7.973591953902356, 8.180792623486118, 7.274944884696797, 3.5777171334219773, 2.8350640325567142, 2.742898476174686, 3.9406648366396384, 1.4560097748873433, 1.1451191505077887, 0.6847599564194339, 0.0, 9.715783031298415, 7.532359520613772, 5.7255957525389425, 4.368029324662029, 7.881329673279277, 3.840057866644561, 2.8350640325567142, 2.555512238158555, 3.6374724423483986, 2.7269308744953733, 1.5947183907804712, 0.5840453120772259, 0.0),
(8.858744120374082, 6.3393718515594255, 7.906737818402987, 8.103579442909608, 7.212153047825302, 3.551582753604972, 2.8009276580314295, 2.7236067663821912, 3.9145709044888575, 1.4406842982296237, 1.133483387123799, 0.6781362523683109, 0.0, 9.630513176304232, 7.459498776051419, 5.667416935618994, 4.322052894688871, 7.829141808977715, 3.813049472935068, 2.8009276580314295, 2.5368448240035515, 3.606076523912651, 2.7011931476365363, 1.5813475636805976, 0.5763065319599479, 0.0),
(8.741846513885172, 6.242606401394785, 7.821920957955889, 8.008719759367974, 7.133136105077435, 3.517038907233379, 2.7613462490302703, 2.6977995947636733, 3.8789700908914604, 1.4223616955588683, 1.119451901721908, 0.6700501948887847, 0.0, 9.523704730672296, 7.370552143776631, 5.59725950860954, 4.267085086676604, 7.757940181782921, 3.7769194326691427, 2.7613462490302703, 2.512170648023842, 3.5665680525387176, 2.669573253122658, 1.5643841915911778, 0.5675096728540715, 0.0),
(8.607866465503152, 6.134832954888515, 7.7200469719103095, 7.897115253381055, 7.038714499425689, 3.4745040690992197, 2.716608867604126, 2.66580026655489, 3.8343319067996067, 1.4011974579512814, 1.1031483309199415, 0.6605767468907572, 0.0, 9.396448853782916, 7.266344215798328, 5.515741654599707, 4.203592373853843, 7.668663813599213, 3.7321203731768464, 2.716608867604126, 2.481788620785157, 3.5193572497128445, 2.632371751127019, 1.5440093943820619, 0.557712086808047, 0.0),
(8.457746124511628, 6.016682384573562, 7.602021459615496, 7.769667605468694, 6.929708673842563, 3.424396713994519, 2.6670045758038854, 2.627932086991601, 3.781125863165454, 1.3773470764830695, 1.0846963113357242, 0.6497908712841294, 0.0, 9.2498367050164, 7.147699584125422, 5.42348155667862, 4.132041229449208, 7.562251726330908, 3.6791049217882414, 2.6670045758038854, 2.4459976528532277, 3.4648543369212814, 2.5898892018228983, 1.5204042919230993, 0.5469711258703239, 0.0),
(8.292427640194196, 5.888785562982875, 7.468750020420702, 7.6272784961507405, 6.806939071300549, 3.367135316711301, 2.61282243568044, 2.5845183613095624, 3.719821470941162, 1.3509660422304377, 1.0642194795870819, 0.6377675309788032, 0.0, 9.084959443753055, 7.015442840766835, 5.321097397935408, 4.052898126691312, 7.439642941882324, 3.6183257058333878, 2.61282243568044, 2.405096654793786, 3.4034695356502747, 2.5424261653835805, 1.4937500040841403, 0.5353441420893524, 0.0),
(8.11285316183446, 5.751773362649402, 7.321138253675176, 7.470849605947036, 6.67122613477215, 3.3031383520415907, 2.5543515092846794, 2.5358823947445344, 3.650888241078889, 1.3222098462695906, 1.0418414722918394, 0.6245816888846804, 0.0, 8.902908229373192, 6.870398577731482, 5.209207361459196, 3.966629538808771, 7.301776482157778, 3.550235352642348, 2.5543515092846794, 2.3593845371725646, 3.335613067386075, 2.4902832019823458, 1.4642276507350354, 0.5228884875135821, 0.0),
(7.9199648387160195, 5.606276656106095, 7.160091758728169, 7.301282615377426, 6.5233903072298585, 3.2328242947774104, 2.491880858667493, 2.482347492532273, 3.5747956845307916, 1.2912339796767343, 1.0176859260678224, 0.610308307911662, 0.0, 8.704774221257123, 6.713391387028281, 5.088429630339111, 3.873701939030202, 7.149591369061583, 3.4752864895451823, 2.491880858667493, 2.309160210555293, 3.2616951536149292, 2.433760871792476, 1.432018351745634, 0.5096615141914632, 0.0),
(7.714704820122476, 5.452926315885899, 6.9865161349289275, 7.119479204961751, 6.364252031646171, 3.156611619710786, 2.4256995458797714, 2.4242369599085385, 3.492013312249029, 1.2581939335280738, 0.9918764775328559, 0.5950223509696502, 0.0, 8.491648578785155, 6.545245860666151, 4.959382387664279, 3.7745818005842207, 6.984026624498058, 3.393931743871954, 2.4256995458797714, 2.254722585507704, 3.1821260158230853, 2.373159734987251, 1.3973032269857855, 0.4957205741714455, 0.0),
(7.498015255337426, 5.292353214521765, 6.801316981626705, 6.926341055219858, 6.194631750993583, 3.074918801633741, 2.3560966329724047, 2.361874102109088, 3.403010635185759, 1.2232451988998143, 0.9645367633047655, 0.5787987809685459, 0.0, 8.264622461337595, 6.366786590654004, 4.822683816523827, 3.669735596699442, 6.806021270371518, 3.3066237429527234, 2.3560966329724047, 2.196370572595529, 3.0973158754967915, 2.308780351739953, 1.360263396325341, 0.4811230195019787, 0.0),
(7.2708382936444735, 5.125188224546641, 6.605399898170748, 6.722769846671591, 6.015349908244593, 2.9881643153382993, 2.2833611819962822, 2.2955822243696797, 3.308257164293142, 1.1865432668681617, 0.9357904200013762, 0.5617125608182512, 0.0, 8.024787028294753, 6.178838169000762, 4.678952100006881, 3.559629800604484, 6.616514328586284, 3.2138151141175517, 2.2833611819962822, 2.1344030823844995, 3.0076749541222965, 2.2409232822238643, 1.3210799796341497, 0.46592620223151293, 0.0),
(7.034116084327218, 4.952062218493477, 6.399670483910309, 6.509667259836794, 5.827226946371695, 2.8967666356164865, 2.2077822550022947, 2.2256846319260726, 3.2082224105233346, 1.1482436285093212, 0.9057610842405137, 0.5438386534286673, 0.0, 7.773233439036942, 5.982225187715339, 4.528805421202568, 3.444730885527963, 6.416444821046669, 3.1159584846965016, 2.2077822550022947, 2.0691190254403473, 2.9136134731858476, 2.1698890866122653, 1.2799340967820618, 0.450187474408498, 0.0),
(6.78879077666926, 4.773606068895221, 6.185034338194635, 6.2879349752353075, 5.631083308347386, 2.8011442372603246, 2.1296489140413315, 2.1525046300140236, 3.103375884828495, 1.1085017748994974, 0.8745723926400033, 0.525252021709696, 0.0, 7.5110528529444665, 5.777772238806654, 4.372861963200016, 3.325505324698492, 6.20675176965699, 3.013506482019633, 2.1296489140413315, 2.0008173123288033, 2.815541654173693, 2.0959783250784363, 1.2370068676389272, 0.4339641880813838, 0.0),
(6.5358045199542, 4.59045064828482, 5.962397060372978, 6.058474673386982, 5.427739437144163, 2.701715595061839, 2.049250221164283, 2.0763655238692915, 2.994187098160782, 1.0674731971148967, 0.8423479818176697, 0.5060276285712387, 0.0, 7.239336429397638, 5.566303914283624, 4.211739909088348, 3.2024195913446896, 5.988374196321564, 2.906911733417008, 2.049250221164283, 1.9297968536155994, 2.7138697185720817, 2.019491557795661, 1.1924794120745956, 0.4173136952986201, 0.0),
(6.276099463465638, 4.403226829195226, 5.7326642497945866, 5.822188034811656, 5.218015775734522, 2.5988991838130535, 1.9668752384220392, 1.9975906187276353, 2.881125561472354, 1.025313386231724, 0.8092114883913387, 0.4862404369231972, 0.0, 6.959175327776763, 5.348644806155168, 4.046057441956694, 3.075940158695172, 5.762251122944708, 2.7966268662186895, 1.9668752384220392, 1.8563565598664666, 2.609007887867261, 1.9407293449372194, 1.1465328499589174, 0.40029334810865697, 0.0),
(6.010617756487176, 4.212565484159386, 5.4967415058087115, 5.579976740029178, 5.002732767090961, 2.4931134783059927, 1.8828130278654898, 1.916503219824812, 2.7646607857153684, 0.9821778333261846, 0.7752865489788355, 0.4659654096754725, 0.0, 6.671660707462155, 5.125619506430197, 3.8764327448941778, 2.9465334999785533, 5.529321571430737, 2.6831045077547366, 1.8828130278654898, 1.7807953416471376, 2.5013663835454807, 1.859992246676393, 1.0993483011617424, 0.38296049855994424, 0.0),
(5.740301548302412, 4.019097485710249, 5.2555344277646014, 5.332742469559387, 4.782710854185972, 2.3847769533326795, 1.7973526515455251, 1.8334266323965802, 2.645262281841985, 0.9382220294744842, 0.7406968001979856, 0.44527750973796687, 0.0, 6.37788372783412, 4.898052607117634, 3.7034840009899272, 2.814666088423452, 5.29052456368397, 2.5667972853552126, 1.7973526515455251, 1.7034121095233423, 2.391355427092986, 1.7775808231864625, 1.0511068855529204, 0.3653724987009318, 0.0),
(5.466092988194946, 3.823453706380764, 5.009948615011508, 5.08138690392213, 4.558770479992055, 2.2743080836851397, 1.7107831715130346, 1.748684161678698, 2.5233995608043616, 0.8936014657528275, 0.7055658786666139, 0.4242517000205815, 0.0, 6.078935548272969, 4.666768700226395, 3.5278293933330693, 2.680804397258482, 5.046799121608723, 2.4481578263501773, 1.7107831715130346, 1.6245057740608142, 2.2793852399960275, 1.6937956346407106, 1.0019897230023018, 0.3475867005800695, 0.0),
(5.188934225448382, 3.62626501870388, 4.760889666898678, 4.8268117236372525, 4.331732087481704, 2.1621253441553967, 1.6233936498189088, 1.6625991129069244, 2.3995421335546565, 0.8484716332374204, 0.670017421002546, 0.4029629434332179, 0.0, 5.7759073281590085, 4.432592377765396, 3.35008710501273, 2.5454148997122603, 4.799084267109313, 2.327638758069694, 1.6233936498189088, 1.5443752458252833, 2.165866043740852, 1.6089372412124179, 0.9521779333797357, 0.3296604562458073, 0.0),
(4.909767409346319, 3.4281622952125463, 4.5092631827753635, 4.569918609224595, 4.102416119627418, 2.0486472095354746, 1.5354731485140374, 1.5754947913170163, 2.2741595110450277, 0.8029880230044676, 0.6341750638236071, 0.3814862028857779, 0.0, 5.4698902268725496, 4.196348231743556, 3.1708753191180357, 2.408964069013402, 4.548319022090055, 2.2056927078438227, 1.5354731485140374, 1.4633194353824817, 2.051208059813709, 1.5233062030748654, 0.9018526365550728, 0.31165111774659515, 0.0),
(4.629534689172356, 3.2297764084397107, 4.255974761990814, 4.311609241204004, 3.8716430194016906, 1.9342921546173981, 1.4473107296493104, 1.4876945021447328, 2.147721204227634, 0.7573061261301752, 0.5981624437476226, 0.3598964412881627, 0.0, 5.161975403793902, 3.958860854169789, 2.9908122187381125, 2.271918378390525, 4.295442408455268, 2.082772303002626, 1.4473107296493104, 1.3816372532981414, 1.9358215097008453, 1.437203080401335, 0.8511949523981628, 0.29361603713088286, 0.0),
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
)
passenger_allighting_rate = (
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
(0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1, 0, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 0.07692307692307693, 1),
)
entropy = 8991598675325360468762009371570610170
child_seed_index = (
1,
37,
)
| true | true |
f7f6ca3d940008955346754a5a0651e2c5a556da | 446 | py | Python | project/Support/Code/Sheets/for_project.py | fael07/Django-Helper | bcc9de58f0453452b017b2e219130fbf5a3d48d7 | [
"MIT"
] | null | null | null | project/Support/Code/Sheets/for_project.py | fael07/Django-Helper | bcc9de58f0453452b017b2e219130fbf5a3d48d7 | [
"MIT"
] | null | null | null | project/Support/Code/Sheets/for_project.py | fael07/Django-Helper | bcc9de58f0453452b017b2e219130fbf5a3d48d7 | [
"MIT"
] | null | null | null | from models.eraser import *
from models.project import *
from models.editor import Editor
from time import sleep
bp = r'C:\Users\G-fire\OneDrive\Documentos\Django\TESTE\project' # base_path
project_name = 'TESTAGEM'
project = DjangoProject(bp, project_name)
#* APÓS CRIAÇÃO
# delete_comments_by_folder(bp, project_name)
# sleep(1)
# project.adapt_urls_py()
# sleep(1)
# project.insert_important_comments()
# sleep(1)
# project.adapt_settings() | 24.777778 | 76 | 0.775785 | from models.eraser import *
from models.project import *
from models.editor import Editor
from time import sleep
bp = r'C:\Users\G-fire\OneDrive\Documentos\Django\TESTE\project'
project_name = 'TESTAGEM'
project = DjangoProject(bp, project_name)
| true | true |
f7f6ca8c00e797acf12df6f0b376bddf69c35cdb | 158 | py | Python | encuestas/apps.py | jjmartinr01/gauss3 | 1c71c44430e0f15fb2f3f83d32ad66bb1b7e3e94 | [
"MIT"
] | null | null | null | encuestas/apps.py | jjmartinr01/gauss3 | 1c71c44430e0f15fb2f3f83d32ad66bb1b7e3e94 | [
"MIT"
] | null | null | null | encuestas/apps.py | jjmartinr01/gauss3 | 1c71c44430e0f15fb2f3f83d32ad66bb1b7e3e94 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class EncuestasConfig(AppConfig):
name = 'encuestas'
| 17.555556 | 39 | 0.740506 |
from __future__ import unicode_literals
from django.apps import AppConfig
class EncuestasConfig(AppConfig):
name = 'encuestas'
| true | true |
f7f6cae6323a7b5de6bd3040ce4efd5c06b261f8 | 432 | py | Python | day_25/day_25.py | GuillaumeGandon/advent-of-code-2015 | ff4201a9a27d1ca7f687a613eeec72dd12fe1487 | [
"MIT"
] | null | null | null | day_25/day_25.py | GuillaumeGandon/advent-of-code-2015 | ff4201a9a27d1ca7f687a613eeec72dd12fe1487 | [
"MIT"
] | null | null | null | day_25/day_25.py | GuillaumeGandon/advent-of-code-2015 | ff4201a9a27d1ca7f687a613eeec72dd12fe1487 | [
"MIT"
] | null | null | null | import re
FIRST_CODE = 20151125
MULTIPLIER = 252533
DIVIDER = 33554393
targeted_row, targeted_col = map(int, re.findall(r'\d+', open('input').read()))
row, col = 1, 1
tmp = FIRST_CODE
while 1:
if row == 1:
row, col = col + 1, 1
else:
row -= 1
col += 1
tmp = tmp * MULTIPLIER % DIVIDER
if row == targeted_row and col == targeted_col:
print(f"Answer part one: {tmp}")
break
| 19.636364 | 79 | 0.583333 | import re
FIRST_CODE = 20151125
MULTIPLIER = 252533
DIVIDER = 33554393
targeted_row, targeted_col = map(int, re.findall(r'\d+', open('input').read()))
row, col = 1, 1
tmp = FIRST_CODE
while 1:
if row == 1:
row, col = col + 1, 1
else:
row -= 1
col += 1
tmp = tmp * MULTIPLIER % DIVIDER
if row == targeted_row and col == targeted_col:
print(f"Answer part one: {tmp}")
break
| true | true |
f7f6cbc40c5863876a5cae50579ed294c83da538 | 45,079 | py | Python | cogs/reportsupport.py | GabrielFS1/sloth-bot | 1e606f1f3a998ee94a0c83ac343eac3a420a085c | [
"MIT"
] | null | null | null | cogs/reportsupport.py | GabrielFS1/sloth-bot | 1e606f1f3a998ee94a0c83ac343eac3a420a085c | [
"MIT"
] | null | null | null | cogs/reportsupport.py | GabrielFS1/sloth-bot | 1e606f1f3a998ee94a0c83ac343eac3a420a085c | [
"MIT"
] | 1 | 2021-05-28T21:34:42.000Z | 2021-05-28T21:34:42.000Z | import discord
from discord import member
from discord.ext import commands
from mysqldb import *
import asyncio
from extra.useful_variables import list_of_commands
from extra.prompt.menu import Confirm
from extra.view import ReportSupportView
from typing import List, Dict, Optional
import os
case_cat_id = int(os.getenv('CASE_CAT_ID'))
reportsupport_channel_id = int(os.getenv('REPORT_CHANNEL_ID'))
dnk_id = int(os.getenv('DNK_ID'))
moderator_role_id = int(os.getenv('MOD_ROLE_ID'))
admin_role_id = int(os.getenv('ADMIN_ROLE_ID'))
lesson_management_role_id = int(os.getenv('LESSON_MANAGEMENT_ROLE_ID'))
staff_vc_id = int(os.getenv('STAFF_VC_ID'))
allowed_roles = [
int(os.getenv('OWNER_ROLE_ID')), admin_role_id,
moderator_role_id]
from extra.reportsupport.applications import ApplicationsTable
from extra.reportsupport.verify import Verify
from extra.reportsupport.openchannels import OpenChannels
report_support_classes: List[commands.Cog] = [
ApplicationsTable, Verify, OpenChannels
]
class ReportSupport(*report_support_classes):
""" A cog related to the system of reports and some other things. """
def __init__(self, client) -> None:
# super(ReportSupport, self).__init__(client)
self.client = client
self.cosmos_id: int = int(os.getenv('COSMOS_ID'))
self.muffin_id: int = int(os.getenv('MUFFIN_ID'))
self.cache = {}
self.report_cache = {}
@commands.Cog.listener()
async def on_ready(self) -> None:
self.client.add_view(view=ReportSupportView(self.client))
print('ReportSupport cog is online!')
async def handle_application(self, guild, payload) -> None:
""" Handles teacher applications.
:param guild: The server in which the application is running.
:param payload: Data about the Staff member who is opening the application. """
emoji = str(payload.emoji)
if emoji == '✅':
# Gets the teacher app and does the magic
if not (app := await self.get_application_by_message(payload.message_id)):
return
# Checks if the person has not an open interview channel already
if not app[3]:
# Creates an interview room with the teacher and sends their application there (you can z!close there)
return await self.create_interview_room(guild, app)
elif emoji == '❌':
# Tries to delete the teacher app from the db, in case it is registered
app = await self.get_application_by_message(payload.message_id)
if app and not app[3]:
await self.delete_application(payload.message_id)
interview_info = self.interview_info[app[2]]
app_channel = self.client.get_channel(interview_info['app'])
app_msg = await app_channel.fetch_message(payload.message_id)
await app_msg.add_reaction('🔏')
if applicant := discord.utils.get(guild.members, id=app[1]):
return await applicant.send(embed=discord.Embed(description=interview_info['message']))
async def send_teacher_application(self, member) -> None:
""" Sends a teacher application form to the user.
:param member: The member to send the application to. """
def msg_check(message):
if message.author == member and not message.guild:
if len(message.content) <= 100:
return True
else:
self.client.loop.create_task(member.send("**Your answer must be within 100 characters**"))
else:
return False
def check_reaction(r, u):
return u.id == member.id and not r.message.guild and str(r.emoji) in ['✅', '❌']
terms_embed = discord.Embed(
title="Terms of Application",
description="""Hello there!
Thank you for applying for teaching here,
Before you can formally start applying to teach in The Language Sloth, there are a couple things we would like you to know. The Language Sloth is a free of charge language learning platform which is meant to be accessible and open for anyone who is interested in languages from any background. We do not charge for any kind of service, nor do we pay for any services for starting teachers. We are a community that shares the same interest: Languages.
We do not require professional teaching skills, anyone can teach their native language, however, we have a set numbers of requirements for our teachers
Entry requirements:
》Must be at least 16 years of age
》Must have at least a conversational level of English
》Must have clear microphone audio
》Must commit 40 minutes per week
》Must prepare their own material weekly
``` ✅ To agree with our terms```""",
color=member.color
)
terms = await member.send(embed=terms_embed)
await terms.add_reaction('✅')
await terms.add_reaction('❌')
# Waits for reaction confirmation to the terms of application
terms_r = await self.get_reaction(member, check_reaction)
if terms_r is None:
self.cache[member.id] = 0
return
if terms_r != '✅':
self.cache[member.id] = 0
return await member.send(f"**Thank you anyways, bye!**")
embed = discord.Embed(title=f"__Teacher Application__")
embed.set_footer(text=f"by {member}", icon_url=member.display_avatar)
embed.description = '''
- Hello, there you've reacted to apply to become a teacher.
To apply please answer to these following questions with One message at a time
Question one:
What language are you applying to teach?'''
q1 = await member.send(embed=embed)
a1 = await self.get_message_content(member, msg_check)
if not a1:
return
embed.description = '''
- Why do you want to teach that language on the language sloth?
Please answer with one message.'''
q2 = await member.send(embed=embed)
a2 = await self.get_message_content(member, msg_check)
if not a2:
return
embed.description = '''
- On The Language Sloth, our classes happen once a week at the same time weekly.
Please let us know when would be the best time for you to teach,
E.A: Thursdays 3 pm CET, you can specify your timezone.
Again remember to answer with one message.'''
q3 = await member.send(embed=embed)
a3 = await self.get_message_content(member, msg_check)
if not a3:
return
embed.description = '''
- Let's talk about your English level, how do you consider your English level?
Are you able to teach lessons in English?
Please answer using one message only'''
q4 = await member.send(embed=embed)
a4 = await self.get_message_content(member, msg_check)
if not a4:
return
embed.description = '''- Have you ever taught people before?'''
q5 = await member.send(embed=embed)
a5 = await self.get_message_content(member, msg_check)
if not a5:
return
embed.description = '''- Inform a short description for your class.'''
q6 = await member.send(embed=embed)
a6 = await self.get_message_content(member, msg_check)
if not a6:
return
embed.description = '''- How old are you?'''
q7 = await member.send(embed=embed)
a7 = await self.get_message_content(member, msg_check)
if not a7:
return
# Get user's native roles
user_native_roles = []
for role in member.roles:
if str(role.name).lower().startswith('native'):
user_native_roles.append(role.name.title())
# Application result
app = f"""```ini\n[Username]: {member} ({member.id})\n[Joined the server]: {member.joined_at.strftime("%a, %d %B %y, %I %M %p UTC")}\n[Applying to teach]: {a1.title()}\n[Native roles]: {', '.join(user_native_roles)}\n[Motivation for teaching]: {a2.capitalize()}\n[Applying to teach on]: {a3.upper()}\n[English level]: {a4.capitalize()}\n[Experience teaching]: {a5.capitalize()}\n[Description]:{a6.capitalize()}\n[Age]: {a7}```"""
await member.send(app)
embed.description = '''
Are you sure you want to apply this? :white_check_mark: to send and :x: to Cancel
'''
app_conf = await member.send(embed=embed)
await app_conf.add_reaction('✅')
await app_conf.add_reaction('❌')
# Waits for reaction confirmation
r = await self.get_reaction(member, check_reaction)
if r is None:
return
if r == '✅':
embed.description = "**Application successfully made, please, be patient now!**"
await member.send(embed=embed)
teacher_app_channel = await self.client.fetch_channel(self.teacher_app_channel_id)
muffin = discord.utils.get(teacher_app_channel.guild.members, id=self.muffin_id)
app = await teacher_app_channel.send(content=f"{muffin.mention}, {member.mention}\n{app}")
await app.add_reaction('✅')
await app.add_reaction('❌')
# Saves in the database
await self.insert_application(app.id, member.id, 'teacher')
else:
self.cache[member.id] = 0
return await member.send("**Thank you anyways!**")
async def send_moderator_application(self, member):
""" Sends a moderator application form to the user.
:param member: The member to send the application to. """
def msg_check(message):
if message.author == member and not message.guild:
if len(message.content) <= 100:
return True
else:
self.client.loop.create_task(member.send("**Your answer must be within 100 characters**"))
else:
return False
def check_reaction(r, u):
return u.id == member.id and not r.message.guild and str(r.emoji) in ['✅', '❌']
terms_embed = discord.Embed(
title="Terms of Application",
description="""Hello there!
Before you can formally start applying for Staff in The Language Sloth, there are a couple requirements we would like you to know we feel necessity for:
Entry requirements:
```》Must be at least 18 years of age
》Must have at least a conversational level of English
》Must be an active member
》Be a member of the server for at least a month
》Must not have any warnings in the past 3 months.```""",
color=member.color
)
terms = await member.send(embed=terms_embed)
await terms.add_reaction('✅')
await terms.add_reaction('❌')
# Waits for reaction confirmation to the terms of application
terms_r = await self.get_reaction(member, check_reaction)
if terms_r is None:
self.cache[member.id] = 0
return
if terms_r != '✅':
self.cache[member.id] = 0
return await member.send(f"**Thanks anyways, bye!**")
embed = discord.Embed(title=f"__Moderator Application__")
embed.set_footer(text=f"by {member}", icon_url=member.display_avatar)
embed.description = "- What's your age?"
await member.send(embed=embed)
a1 = await self.get_message_content(member, msg_check)
if not a1: return
embed.description = """
- Hello, there you've reacted to apply to become a moderator.
To apply please answer to these following questions with One message at a time
Question one:
Do you have any experience moderating Discord servers?"""
q2 = await member.send(embed=embed)
a2 = await self.get_message_content(member, msg_check)
if not a2: return
embed.description = """
- What is your gender?
Please answer with one message."""
await member.send(embed=embed)
a3 = await self.get_message_content(member, msg_check)
if not a3: return
embed.description = """
- What's your English level? Are you able to express yourself using English?
Please answer using one message only."""
await member.send(embed=embed)
a4 = await self.get_message_content(member, msg_check)
if not a4: return
embed.description = """
- Why are you applying to be Staff? What is your motivation?
Please answer using one message only."""
await member.send(embed=embed)
a5 = await self.get_message_content(member, msg_check)
if not a5: return
embed.description = """- How do you think The Language Sloth could be a better community?
Please answer using one message only."""
await member.send(embed=embed)
a6 = await self.get_message_content(member, msg_check)
if not a6: return
embed.description = """- How active are you on Discord in general?
Please answer using one message only."""
await member.send(embed=embed)
a7 = await self.get_message_content(member, msg_check)
if not a7: return
embed.description = """- What is your time zone?
Please answer using one message only.."""
await member.send(embed=embed)
a8 = await self.get_message_content(member, msg_check)
if not a8: return
embed.description = "- What is your country of origin?"
await member.send(embed=embed)
a9 = await self.get_message_content(member, msg_check)
if not a9: return
embed.description = "- Tell us about yourself?"
await member.send(embed=embed)
a10 = await self.get_message_content(member, msg_check)
if not a10: return
# Get user's native roles
user_native_roles = []
for role in member.roles:
if str(role.name).lower().startswith('native'):
user_native_roles.append(role.name.title())
# Application result
app = f"""```ini\n[Username]: {member} ({member.id})
[Joined the server]: {member.joined_at.strftime("%a, %d %B %y, %I %M %p UTC")}
[Native roles]: {', '.join(user_native_roles)}
[Age]: {a1}
[Experience moderating]: {a2.capitalize()}
[Gender]: {a3.title()}
[English level]: {a4.capitalize()}
[Reason & Motivation]: {a5.capitalize()}
[How we can improve Sloth]: {a6.capitalize()}
[Activity Status]: {a7.capitalize()}
[Timezone]: {a8.title()}
[Origin Country]: {a9.title()}
[About]: {a10.capitalize()}```"""
await member.send(app)
embed.description = """
Are you sure you want to apply this? :white_check_mark: to send and :x: to Cancel
"""
app_conf = await member.send(embed=embed)
await app_conf.add_reaction('✅')
await app_conf.add_reaction('❌')
# Waits for reaction confirmation
r = await self.get_reaction(member, check_reaction)
if r is None:
return
if r == '✅':
# ""
embed.description = """**Application successfully made, please, be patient now.**
We will let you know when we need a new mod. We check apps when we need it!"""
await member.send(embed=embed)
moderator_app_channel = await self.client.fetch_channel(self.moderator_app_channel_id)
cosmos = discord.utils.get(moderator_app_channel.guild.members, id=self.cosmos_id)
app = await moderator_app_channel.send(content=f"{cosmos.mention}, {member.mention}\n{app}")
await app.add_reaction('✅')
await app.add_reaction('❌')
# Saves in the database
await self.insert_application(app.id, member.id, 'moderator')
else:
self.cache[member.id] = 0
return await member.send("**Thank you anyways!**")
async def send_event_manager_application(self, member):
""" Sends a event manager application form to the user.
:param member: The member to send the application to. """
def msg_check(message):
if message.author == member and not message.guild:
if len(message.content) <= 100:
return True
else:
self.client.loop.create_task(member.send("**Your answer must be within 100 characters**"))
else:
return False
def check_reaction(r, u):
return u.id == member.id and not r.message.guild and str(r.emoji) in ['✅', '❌']
terms_embed = discord.Embed(
title="Terms of Application",
description="""Hello there!
Thank you for applying for hosting events here,
Before you can formally start applying to host events in The Language Sloth, there are a couple things we would like you to know. The Language Sloth is a free of charge language learning platform which is meant to be accessible and open for anyone who is interested in languages from any background. We do not charge for any kind of service, nor do we pay for any services for hosting events. We are a community that shares the same interest: Languages.
We do not require professional skills, however, we have a set numbers of requirements for our event managers
Entry requirements:
》Must be at least 16 years of age
》Must have at least a conversational level of English
》Must have clear microphone audio
》Must prepare their own material weekly
``` ✅ To agree with our terms```""",
color=member.color
)
terms = await member.send(embed=terms_embed)
await terms.add_reaction('✅')
await terms.add_reaction('❌')
# Waits for reaction confirmation to the terms of application
terms_r = await self.get_reaction(member, check_reaction)
if terms_r is None:
self.cache[member.id] = 0
return
if terms_r != '✅':
self.cache[member.id] = 0
return await member.send(f"**Thank you anyways, bye!**")
embed = discord.Embed(title=f"__Teacher Application__")
embed.set_footer(text=f"by {member}", icon_url=member.display_avatar)
embed.title = "Event manager Application"
embed.description = '''
- Hello, there you've reacted to apply to become an event manager.
To apply please answer to these following questions with One message at a time
Question one:
What is your event called?'''
q1 = await member.send(embed=embed)
a1 = await self.get_message_content(member, msg_check)
if not a1:
return
embed.description = '''
- Why do you want to host that event on the language sloth?
Please answer with one message.'''
q2 = await member.send(embed=embed)
a2 = await self.get_message_content(member, msg_check)
if not a2:
return
embed.description = '''
- Please let us know when would be the best time for you to host events
E.A: Thursdays 3 pm CET, you can specify your timezone.
Again remember to answer with one message.'''
q3 = await member.send(embed=embed)
a3 = await self.get_message_content(member, msg_check)
if not a3:
return
embed.description = """
- Let's talk about your English level, how do you consider your English level?
Are you able to host events in English? If not, in which language would you be hosting?
Please answer using one message only"""
q4 = await member.send(embed=embed)
a4 = await self.get_message_content(member, msg_check)
if not a4:
return
embed.description = "- Have you ever hosted events before? If yes, please describe!"
q5 = await member.send(embed=embed)
a5 = await self.get_message_content(member, msg_check)
if not a5:
return
embed.description = "- Inform a short description for your event/events."
q6 = await member.send(embed=embed)
a6 = await self.get_message_content(member, msg_check)
if not a6:
return
embed.description = "- How old are you?"
q7 = await member.send(embed=embed)
a7 = await self.get_message_content(member, msg_check)
if not a7:
return
# Get user's native roles
user_native_roles = []
for role in member.roles:
if str(role.name).lower().startswith('native'):
user_native_roles.append(role.name.title())
# Application result
app = f"""```ini\n[Username]: {member} ({member.id})\n[Joined the server]: {member.joined_at.strftime("%a, %d %B %y, %I %M %p UTC")}\n[Applying to host]: {a1.title()}\n[Native roles]: {', '.join(user_native_roles)}\n[Motivation for hosting]: {a2.capitalize()}\n[Applying to host on]: {a3.upper()}\n[English level]: {a4.capitalize()}\n[Experience hosting]: {a5.capitalize()}\n[Description]:{a6.capitalize()}\n[Age]: {a7}```"""
await member.send(app)
embed.description = '''
Are you sure you want to apply this? :white_check_mark: to send and :x: to Cancel
'''
app_conf = await member.send(embed=embed)
await app_conf.add_reaction('✅')
await app_conf.add_reaction('❌')
# Waits for reaction confirmation
r = await self.get_reaction(member, check_reaction)
if r is None:
return
if r == '✅':
embed.description = "**Application successfully made, please, be patient now!**"
await member.send(embed=embed)
event_manager_channel = await self.client.fetch_channel(self.event_manager_app_channel_id)
app = await event_manager_channel.send(content=f"{member.mention}\n{app}")
await app.add_reaction('✅')
await app.add_reaction('❌')
# Saves in the database
await self.insert_application(app.id, member.id, 'event_manager')
else:
self.cache[member.id] = 0
return await member.send("**Thank you anyways!**")
async def send_verified_selfies_verification(self, interaction: discord.Interaction) -> None:
""" Sends a message to the user asking for them to send a selfie in order for them
to get the verified selfies role.
:param interaction: The interaction object. """
guild = interaction.guild
member = interaction.user
def msg_check(message):
if message.author == member and not message.guild:
if len(message.content) <= 100:
return True
else:
self.client.loop.create_task(member.send("**Your answer must be within 100 characters**"))
else:
return False
embed = discord.Embed(
title=f"__Verify__",
description=f"""You have opened a verification request, if you would like to verify:\n
**1.** Take a clear picture of yourself holding a piece of paper with today's date and time of verification, and your Discord server name written on it. Image links won't work, only image uploads!\n(You have 5 minutes to do so)"""
)
embed.set_footer(text=f"by {member}", icon_url=member.display_avatar)
embed.set_image(url="https://cdn.discordapp.com/attachments/562019472257318943/882352621116096542/slothfacepopoo.png")
await member.send(embed=embed)
while True:
msg = await self.get_message(member, msg_check, 300)
if msg is None:
return await member.send(f"**Timeout, you didn't answer in time, try again later!**")
attachments = [att for att in msg.attachments if att.content_type.startswith('image')]
if msg.content.lower() == 'quit':
return await member.send(f"**Bye!**")
if not attachments:
await member.send(f"**No uploaded pic detected, send it again or type `quit` to stop this!**")
continue
break
# Sends verified request to admins
verify_embed = discord.Embed(
title=f"__Verification Request__",
description=f"{member} ({member.id})",
color=member.color,
timestamp=interaction.message.created_at
)
verify_embed.set_thumbnail(url=member.display_avatar)
verify_embed.set_image(url=attachments[0])
verify_req_channel_id = discord.utils.get(guild.text_channels, id=self.verify_reqs_channel_id)
verify_msg = await verify_req_channel_id.send(content=member.mention, embed=verify_embed)
await verify_msg.add_reaction('✅')
await verify_msg.add_reaction('❌')
# Saves
await self.insert_application(verify_msg.id, member.id, 'verify')
return await member.send(f"**Request sent, you will get notified here if you get accepted or declined! ✅**")
# - Report someone
async def report_someone(self, interaction: discord.Interaction):
member = interaction.user
guild = interaction.guild
if open_channel := await self.member_has_open_channel(member.id):
if open_channel := discord.utils.get(guild.text_channels, id=open_channel[1]):
embed = discord.Embed(title="Error!", description=f"**You already have an open channel! ({open_channel.mention})**", color=discord.Color.red())
await interaction.followup.send(embed=embed, ephemeral=True)
return False
else:
await self.remove_user_open_channel(member.id)
# Report someone
case_cat = discord.utils.get(guild.categories, id=case_cat_id)
counter = await self.get_case_number()
moderator = discord.utils.get(guild.roles, id=moderator_role_id)
cosmos = discord.utils.get(guild.members, id=self.cosmos_id)
overwrites = {guild.default_role: discord.PermissionOverwrite(
read_messages=False, send_messages=False, connect=False, view_channel=False),
member: discord.PermissionOverwrite(
read_messages=True, send_messages=True, connect=False, view_channel=True),
moderator: discord.PermissionOverwrite(
read_messages=True, send_messages=True, connect=False, view_channel=True, manage_messages=True)}
try:
the_channel = await guild.create_text_channel(name=f"case-{counter[0][0]}", category=case_cat, overwrites=overwrites)
except Exception:
await interaction.followup.send("**Something went wrong with it, please contact an admin!**", ephemeral=True)
raise Exception
else:
created_embed = discord.Embed(
title="Report room created!",
description=f"**Go to {the_channel.mention}!**",
color=discord.Color.green())
await interaction.followup.send(embed=created_embed, ephemeral=True)
await self.insert_user_open_channel(member.id, the_channel.id)
await self.increase_case_number()
embed = discord.Embed(title="Report Support!", description=f"Please, {member.mention}, try to explain what happened and who you want to report.",
color=discord.Color.red())
message = await the_channel.send(content=f"{member.mention}, {moderator.mention}, {cosmos.mention}", embed=embed)
ctx = await self.client.get_context(message)
return await self.client.get_cog('Tools').vc(ctx, member=member)
# - Report someone
async def generic_help(self, interaction: discord.Interaction, type_help: str, message: str, ping: bool = True) -> None:
""" Opens a generic help channel.
:param interaction: The interaction that generated this action.
:param type_help: The kind of general help.
:param message: The text message to send in the room.
:param ping: Whether mods should be pinged for this. """
member = interaction.user
guild = interaction.guild
if open_channel := await self.member_has_open_channel(member.id):
if open_channel := discord.utils.get(guild.text_channels, id=open_channel[1]):
embed = discord.Embed(title="Error!", description=f"**You already have an open channel! ({open_channel.mention})**", color=discord.Color.red())
await interaction.followup.send(embed=embed, ephemeral=True)
return False
else:
await self.remove_user_open_channel(member.id)
# General help
case_cat = discord.utils.get(guild.categories, id=case_cat_id)
moderator = discord.utils.get(guild.roles, id=moderator_role_id)
overwrites = {guild.default_role: discord.PermissionOverwrite(
read_messages=False, send_messages=False, connect=False, view_channel=False),
member: discord.PermissionOverwrite(
read_messages=True, send_messages=True, connect=False, view_channel=True),
moderator: discord.PermissionOverwrite(
read_messages=True, send_messages=True, connect=False, view_channel=True, manage_messages=True)}
try:
the_channel = await guild.create_text_channel(name=f"{'-'.join(type_help.split())}", category=case_cat, overwrites=overwrites)
except:
await interaction.followup.send("**Something went wrong with it, please contact an admin!**", ephemeral=True)
raise Exception
else:
created_embed = discord.Embed(
title=f"Room for `{type_help}` created!",
description=f"**Go to {the_channel.mention}!**",
color=discord.Color.green())
await interaction.followup.send(embed=created_embed, ephemeral=True)
await self.insert_user_open_channel(member.id, the_channel.id)
embed = discord.Embed(title=f"{type_help.title()}!", description=message, color=discord.Color.red())
if ping:
await the_channel.send(content=f"{member.mention}, {moderator.mention}", embed=embed)
else:
await the_channel.send(content=member.mention, embed=embed)
async def get_message_content(self, member, check, timeout: Optional[int] = 300) -> str:
""" Gets a message content.
:param member: The member to get the message from.
:param check: The check for the event.
:param timeout: Timeout for getting the message. [Optional] """
try:
message = await self.client.wait_for('message', timeout=timeout,
check=check)
except asyncio.TimeoutError:
await member.send("**Timeout! Try again.**")
return None
else:
content = message.content
return content
async def get_message(self, member, check, timeout: Optional[int] = 300) -> discord.Message:
""" Gets a message.
:param member: The member to get the message from.
:param check: The check for the event.
:param timeout: Timeout for getting the message. [Optional] """
try:
message = await self.client.wait_for('message', timeout=timeout,
check=check)
except asyncio.TimeoutError:
await member.send("**Timeout! Try again.**")
return None
else:
return message
async def get_reaction(self, member, check, timeout: int = 300):
try:
reaction, _ = await self.client.wait_for('reaction_add',
timeout=timeout, check=check)
except asyncio.TimeoutError:
await member.send("**Timeout! Try again.**")
return None
else:
return str(reaction.emoji)
@commands.command(aliases=['permit_case', 'allow_case', 'add_witness', 'witness', 'aw'])
@commands.has_any_role(*allowed_roles)
async def allow_witness(self, ctx, member: discord.Member = None):
""" Allows a witness to join a case channel.
:param member: The member to allow. """
if not member:
return await ctx.send("**Inform a witness to allow!**")
user_channel = await self.get_case_channel(ctx.channel.id)
if user_channel:
confirm = await Confirm(f"**Are you sure you want to allow {member.mention} as a witness in this case channel, {ctx.author.mention}?**").prompt(ctx)
if not confirm:
return await ctx.send(f"**Not allowing them, then!**")
channel = discord.utils.get(ctx.guild.channels, id=user_channel[0][1])
try:
await channel.set_permissions(
member, read_messages=True, send_messages=True, connect=True, speak=True, view_channel=True)
except Exception:
pass
return await ctx.send(f"**{member.mention} has been allowed here!**")
else:
await ctx.send(f"**This is not a case channel, {ctx.author.mention}!**")
@commands.command(aliases=['forbid_case', 'delete_witness', 'remve_witness', 'fw'])
@commands.has_any_role(*allowed_roles)
async def forbid_witness(self, ctx, member: discord.Member = None):
""" Forbids a witness from a case channel.
:param member: The member to forbid. """
if not member:
return await ctx.send("**Inform a witness to forbid!**")
user_channel = await self.get_case_channel(ctx.channel.id)
if user_channel:
confirm = await Confirm(f"**Are you sure you want to forbid {member.mention} from being a witness in this case channel, {ctx.author.mention}?**").prompt(ctx)
if not confirm:
return await ctx.send(f"**Not forbidding them, then!**")
channel = discord.utils.get(ctx.guild.channels, id=user_channel[0][1])
try:
await channel.set_permissions(
member, read_messages=False, send_messages=False, connect=False, speak=False, view_channel=False)
except Exception:
pass
return await ctx.send(f"**{member.mention} has been forbidden here!**")
else:
await ctx.send(f"**This is not a case channel, {ctx.author.mention}!**")
@commands.command(aliases=['delete_channel', 'archive'])
@commands.has_any_role(*allowed_roles)
async def close_channel(self, ctx):
""" (MOD) Closes a Case-Channel. """
user_channel = await self.get_case_channel(ctx.channel.id)
if not user_channel:
return await ctx.send(f"**What do you think that you are doing? You cannot delete this channel, {ctx.author.mention}!**")
channel = discord.utils.get(ctx.guild.text_channels, id=user_channel[0][1])
embed = discord.Embed(title="Confirmation",
description="Are you sure that you want to delete this channel?",
color=ctx.author.color,
timestamp=ctx.message.created_at)
confirmation = await ctx.send(content=ctx.author.mention, embed=embed)
await confirmation.add_reaction('✅')
await confirmation.add_reaction('❌')
try:
reaction, user = await self.client.wait_for('reaction_add', timeout=20,
check=lambda r, u: u == ctx.author and r.message.channel == ctx.channel and str(r.emoji) in ['✅', '❌'])
except asyncio.TimeoutError:
embed = discord.Embed(title="Confirmation",
description="You took too long to answer the question; not deleting it!",
color=discord.Color.red(),
timestamp=ctx.message.created_at)
return await confirmation.edit(content=ctx.author.mention, embed=embed)
else:
if str(reaction.emoji) == '✅':
embed.description = f"**Channel {ctx.channel.mention} is being deleted...**"
await confirmation.edit(content=ctx.author.mention, embed=embed)
await asyncio.sleep(3)
await channel.delete()
await self.remove_user_open_channel(user_channel[0][0])
else:
embed.description = "Not deleting it!"
await confirmation.edit(content='', embed=embed)
async def dnk_embed(self, member):
def check(r, u):
return u == member and str(r.message.id) == str(the_msg.id) and str(r.emoji) in ['⬅️', '➡️']
command_index = 0
initial_embed = discord.Embed(title="__Table of Commands and their Prices__",
description="These are a few of commands and features that DNK can do.",
color=discord.Color.blue())
the_msg = await member.send(embed=initial_embed)
await the_msg.add_reaction('⬅️')
await the_msg.add_reaction('➡️')
while True:
embed = discord.Embed(title=f"__Table of Commands and their Prices__ ({command_index+1}/{len(list_of_commands)})",
description="These are a few of commands and features that DNK can do.",
color=discord.Color.blue())
embed.add_field(name=list_of_commands[command_index][0],
value=list_of_commands[command_index][1])
await the_msg.edit(embed=embed)
try:
pending_tasks = [self.client.wait_for('reaction_add', check=check),
self.client.wait_for('reaction_remove', check=check)]
done_tasks, pending_tasks = await asyncio.wait(pending_tasks, timeout=60, return_when=asyncio.FIRST_COMPLETED)
if not done_tasks:
raise asyncio.TimeoutError
for task in pending_tasks:
task.cancel()
except asyncio.TimeoutError:
await the_msg.remove_reaction('⬅️', self.client.user)
await the_msg.remove_reaction('➡️', self.client.user)
break
else:
for task in done_tasks:
reaction, user = await task
if str(reaction.emoji) == "➡️":
# await the_msg.remove_reaction(reaction.emoji, member)
if command_index < (len(list_of_commands) - 1):
command_index += 1
continue
elif str(reaction.emoji) == "⬅️":
# await the_msg.remove_reaction(reaction.emoji, member)
if command_index > 0:
command_index -= 1
continue
# Discord methods
async def create_interview_room(self, guild: discord.Guild, app: List[str]) -> None:
""" Creates an interview room for the given application.
:param guild: The server in which the interview will be.
:param app: The applicant info. """
applicant = discord.utils.get(guild.members, id=app[1])
interview_info = self.interview_info.get(app[2])
# Create Private Thread for the user
app_parent = self.client.get_channel(interview_info['parent'])
#delete this later
message = None
# message = await app_parent.send('Uncomment this in your development environment')
txt_channel = await app_parent.create_thread(name=f"{applicant.display_name}'s-interview", message=message, reason=f"{app[2].title()} Interview Room")
# Add permissions for the user in the interview room
parent_channel = self.client.get_channel(interview_info['parent'])
interview_vc = self.client.get_channel(interview_info['interview'])
# Updates the applicant's application in the database, adding the channels ids
await self.update_application(applicant.id, txt_channel.id, interview_vc.id, app[2])
# Set channel perms for the user.
await parent_channel.set_permissions(applicant, read_messages=True, send_messages=False, view_channel=True)
await interview_vc.set_permissions(applicant, speak=True, connect=True, view_channel=True)
app_embed = discord.Embed(
title=f"{applicant.name}'s Interview",
description=f"""
Hello, {applicant.mention}, we have received and reviewed your `{app[2].title().replace('_', ' ')}` application. In order to explain how our system works we have to schedule a voice conversation with you.
When would be the best time to talk to one of our staff?""",
color=applicant.color)
formatted_pings = await self.format_application_pings(guild, interview_info['pings'])
await txt_channel.send(content=f"{formatted_pings}, {applicant.mention}", embed=app_embed)
# In-game commands
@commands.command()
@commands.has_permissions(administrator=True)
async def close_app(self, ctx) -> None:
""" (ADMIN) Closes an application channel. """
member = ctx.author
channel = ctx.channel
guild = ctx.guild
if not (app := await self.get_application_by_channel(channel.id)):
return await ctx.send(f"**This is not an application channel, {member.mention}!**")
interview_info = self.interview_info[app[2]]
all_apps_channel = discord.utils.get(guild.text_channels, id=interview_info['app'])
confirm = await Confirm(f"**Are you sure that you want to delete this application channel, {member.mention}?**").prompt(ctx)
if not confirm:
return await ctx.send(f"**Not deleting it, then, {member.mention}!**")
applicant = guild.get_member(app[1])
parent_channel = discord.utils.get(guild.text_channels, id=interview_info['parent'])
interview_vc = discord.utils.get(guild.voice_channels, id=interview_info['interview'])
try:
await parent_channel.set_permissions(applicant, overwrite=None)
await interview_vc.set_permissions(applicant, overwrite=None)
except:
pass
await channel.delete()
await self.delete_application(app[0])
try:
msg = await all_apps_channel.fetch_message(app[0])
await msg.add_reaction('🔒')
except:
pass
async def audio(self, member: discord.Member, audio_name: str) -> None:
""" Plays an audio.
:param member: A member to get guild context from.
:param audio_name: The name of the audio to play. """
# Resolves bot's channel state
staff_vc = self.client.get_channel(staff_vc_id)
bot_state = member.guild.voice_client
try:
if bot_state and bot_state.channel and bot_state.channel != staff_vc:
await bot_state.disconnect()
await bot_state.move_to(staff_vc)
elif not bot_state:
voicechannel = discord.utils.get(member.guild.channels, id=staff_vc.id)
vc = await voicechannel.connect()
await asyncio.sleep(2)
voice_client: discord.VoiceClient = discord.utils.get(self.client.voice_clients, guild=member.guild)
# Plays / and they don't stop commin' /
if voice_client and not voice_client.is_playing():
audio_source = discord.FFmpegPCMAudio(f'tts/{audio_name}.mp3')
voice_client.play(audio_source, after=lambda e: print("Finished Warning Staff!"))
else:
print('couldnt play it!')
except Exception as e:
print(e)
return
@commands.command(aliases=['make_report_msg', 'reportmsg', 'report_msg', 'supportmsg', 'support_msg'])
@commands.has_permissions(administrator=True)
async def make_report_support_message(self, ctx) -> None:
""" (ADM) Makes a Report-Support message. """
guild = ctx.guild
embed = discord.Embed(
title="__Report-Support Section__",
description="""Welcome to the Report-Support section, here you can easily find your way into things and/or get help with whatever problem you may be experiencing.""",
color=ctx.author.color,
timestamp=ctx.message.created_at,
url="https://thelanguagesloth.com"
)
embed.set_author(name=self.client.user.display_name, url=self.client.user.display_avatar, icon_url=self.client.user.display_avatar)
embed.set_thumbnail(url=guild.icon.url)
embed.set_footer(text=guild.name, icon_url=guild.icon.url)
view = ReportSupportView(self.client)
await ctx.send("\u200b", embed=embed, view=view)
self.client.add_view(view=view)
def setup(client):
client.add_cog(ReportSupport(client))
| 44.899402 | 465 | 0.629473 | import discord
from discord import member
from discord.ext import commands
from mysqldb import *
import asyncio
from extra.useful_variables import list_of_commands
from extra.prompt.menu import Confirm
from extra.view import ReportSupportView
from typing import List, Dict, Optional
import os
case_cat_id = int(os.getenv('CASE_CAT_ID'))
reportsupport_channel_id = int(os.getenv('REPORT_CHANNEL_ID'))
dnk_id = int(os.getenv('DNK_ID'))
moderator_role_id = int(os.getenv('MOD_ROLE_ID'))
admin_role_id = int(os.getenv('ADMIN_ROLE_ID'))
lesson_management_role_id = int(os.getenv('LESSON_MANAGEMENT_ROLE_ID'))
staff_vc_id = int(os.getenv('STAFF_VC_ID'))
allowed_roles = [
int(os.getenv('OWNER_ROLE_ID')), admin_role_id,
moderator_role_id]
from extra.reportsupport.applications import ApplicationsTable
from extra.reportsupport.verify import Verify
from extra.reportsupport.openchannels import OpenChannels
report_support_classes: List[commands.Cog] = [
ApplicationsTable, Verify, OpenChannels
]
class ReportSupport(*report_support_classes):
def __init__(self, client) -> None:
self.client = client
self.cosmos_id: int = int(os.getenv('COSMOS_ID'))
self.muffin_id: int = int(os.getenv('MUFFIN_ID'))
self.cache = {}
self.report_cache = {}
@commands.Cog.listener()
async def on_ready(self) -> None:
self.client.add_view(view=ReportSupportView(self.client))
print('ReportSupport cog is online!')
async def handle_application(self, guild, payload) -> None:
emoji = str(payload.emoji)
if emoji == '✅':
if not (app := await self.get_application_by_message(payload.message_id)):
return
if not app[3]:
return await self.create_interview_room(guild, app)
elif emoji == '❌':
app = await self.get_application_by_message(payload.message_id)
if app and not app[3]:
await self.delete_application(payload.message_id)
interview_info = self.interview_info[app[2]]
app_channel = self.client.get_channel(interview_info['app'])
app_msg = await app_channel.fetch_message(payload.message_id)
await app_msg.add_reaction('🔏')
if applicant := discord.utils.get(guild.members, id=app[1]):
return await applicant.send(embed=discord.Embed(description=interview_info['message']))
async def send_teacher_application(self, member) -> None:
def msg_check(message):
if message.author == member and not message.guild:
if len(message.content) <= 100:
return True
else:
self.client.loop.create_task(member.send("**Your answer must be within 100 characters**"))
else:
return False
def check_reaction(r, u):
return u.id == member.id and not r.message.guild and str(r.emoji) in ['✅', '❌']
terms_embed = discord.Embed(
title="Terms of Application",
description="""Hello there!
Thank you for applying for teaching here,
Before you can formally start applying to teach in The Language Sloth, there are a couple things we would like you to know. The Language Sloth is a free of charge language learning platform which is meant to be accessible and open for anyone who is interested in languages from any background. We do not charge for any kind of service, nor do we pay for any services for starting teachers. We are a community that shares the same interest: Languages.
We do not require professional teaching skills, anyone can teach their native language, however, we have a set numbers of requirements for our teachers
Entry requirements:
》Must be at least 16 years of age
》Must have at least a conversational level of English
》Must have clear microphone audio
》Must commit 40 minutes per week
》Must prepare their own material weekly
``` ✅ To agree with our terms```""",
color=member.color
)
terms = await member.send(embed=terms_embed)
await terms.add_reaction('✅')
await terms.add_reaction('❌')
terms_r = await self.get_reaction(member, check_reaction)
if terms_r is None:
self.cache[member.id] = 0
return
if terms_r != '✅':
self.cache[member.id] = 0
return await member.send(f"**Thank you anyways, bye!**")
embed = discord.Embed(title=f"__Teacher Application__")
embed.set_footer(text=f"by {member}", icon_url=member.display_avatar)
embed.description = '''
- Hello, there you've reacted to apply to become a teacher.
To apply please answer to these following questions with One message at a time
Question one:
What language are you applying to teach?'''
q1 = await member.send(embed=embed)
a1 = await self.get_message_content(member, msg_check)
if not a1:
return
embed.description = '''
- Why do you want to teach that language on the language sloth?
Please answer with one message.'''
q2 = await member.send(embed=embed)
a2 = await self.get_message_content(member, msg_check)
if not a2:
return
embed.description = '''
- On The Language Sloth, our classes happen once a week at the same time weekly.
Please let us know when would be the best time for you to teach,
E.A: Thursdays 3 pm CET, you can specify your timezone.
Again remember to answer with one message.'''
q3 = await member.send(embed=embed)
a3 = await self.get_message_content(member, msg_check)
if not a3:
return
embed.description = '''
- Let's talk about your English level, how do you consider your English level?
Are you able to teach lessons in English?
Please answer using one message only'''
q4 = await member.send(embed=embed)
a4 = await self.get_message_content(member, msg_check)
if not a4:
return
embed.description = '''- Have you ever taught people before?'''
q5 = await member.send(embed=embed)
a5 = await self.get_message_content(member, msg_check)
if not a5:
return
embed.description = '''- Inform a short description for your class.'''
q6 = await member.send(embed=embed)
a6 = await self.get_message_content(member, msg_check)
if not a6:
return
embed.description = '''- How old are you?'''
q7 = await member.send(embed=embed)
a7 = await self.get_message_content(member, msg_check)
if not a7:
return
user_native_roles = []
for role in member.roles:
if str(role.name).lower().startswith('native'):
user_native_roles.append(role.name.title())
# Application result
app = f"""```ini\n[Username]: {member} ({member.id})\n[Joined the server]: {member.joined_at.strftime("%a, %d %B %y, %I %M %p UTC")}\n[Applying to teach]: {a1.title()}\n[Native roles]: {', '.join(user_native_roles)}\n[Motivation for teaching]: {a2.capitalize()}\n[Applying to teach on]: {a3.upper()}\n[English level]: {a4.capitalize()}\n[Experience teaching]: {a5.capitalize()}\n[Description]:{a6.capitalize()}\n[Age]: {a7}```"""
await member.send(app)
embed.description = '''
Are you sure you want to apply this? :white_check_mark: to send and :x: to Cancel
'''
app_conf = await member.send(embed=embed)
await app_conf.add_reaction('✅')
await app_conf.add_reaction('❌')
# Waits for reaction confirmation
r = await self.get_reaction(member, check_reaction)
if r is None:
return
if r == '✅':
embed.description = "**Application successfully made, please, be patient now!**"
await member.send(embed=embed)
teacher_app_channel = await self.client.fetch_channel(self.teacher_app_channel_id)
muffin = discord.utils.get(teacher_app_channel.guild.members, id=self.muffin_id)
app = await teacher_app_channel.send(content=f"{muffin.mention}, {member.mention}\n{app}")
await app.add_reaction('✅')
await app.add_reaction('❌')
# Saves in the database
await self.insert_application(app.id, member.id, 'teacher')
else:
self.cache[member.id] = 0
return await member.send("**Thank you anyways!**")
async def send_moderator_application(self, member):
def msg_check(message):
if message.author == member and not message.guild:
if len(message.content) <= 100:
return True
else:
self.client.loop.create_task(member.send("**Your answer must be within 100 characters**"))
else:
return False
def check_reaction(r, u):
return u.id == member.id and not r.message.guild and str(r.emoji) in ['✅', '❌']
terms_embed = discord.Embed(
title="Terms of Application",
description="""Hello there!
Before you can formally start applying for Staff in The Language Sloth, there are a couple requirements we would like you to know we feel necessity for:
Entry requirements:
```》Must be at least 18 years of age
》Must have at least a conversational level of English
》Must be an active member
》Be a member of the server for at least a month
》Must not have any warnings in the past 3 months.```""",
color=member.color
)
terms = await member.send(embed=terms_embed)
await terms.add_reaction('✅')
await terms.add_reaction('❌')
# Waits for reaction confirmation to the terms of application
terms_r = await self.get_reaction(member, check_reaction)
if terms_r is None:
self.cache[member.id] = 0
return
if terms_r != '✅':
self.cache[member.id] = 0
return await member.send(f"**Thanks anyways, bye!**")
embed = discord.Embed(title=f"__Moderator Application__")
embed.set_footer(text=f"by {member}", icon_url=member.display_avatar)
embed.description = "- What's your age?"
await member.send(embed=embed)
a1 = await self.get_message_content(member, msg_check)
if not a1: return
embed.description = """
- Hello, there you've reacted to apply to become a moderator.
To apply please answer to these following questions with One message at a time
Question one:
Do you have any experience moderating Discord servers?"""
q2 = await member.send(embed=embed)
a2 = await self.get_message_content(member, msg_check)
if not a2: return
embed.description = """
- What is your gender?
Please answer with one message."""
await member.send(embed=embed)
a3 = await self.get_message_content(member, msg_check)
if not a3: return
embed.description = """
- What's your English level? Are you able to express yourself using English?
Please answer using one message only."""
await member.send(embed=embed)
a4 = await self.get_message_content(member, msg_check)
if not a4: return
embed.description = """
- Why are you applying to be Staff? What is your motivation?
Please answer using one message only."""
await member.send(embed=embed)
a5 = await self.get_message_content(member, msg_check)
if not a5: return
embed.description = """- How do you think The Language Sloth could be a better community?
Please answer using one message only."""
await member.send(embed=embed)
a6 = await self.get_message_content(member, msg_check)
if not a6: return
embed.description = """- How active are you on Discord in general?
Please answer using one message only."""
await member.send(embed=embed)
a7 = await self.get_message_content(member, msg_check)
if not a7: return
embed.description = """- What is your time zone?
Please answer using one message only.."""
await member.send(embed=embed)
a8 = await self.get_message_content(member, msg_check)
if not a8: return
embed.description = "- What is your country of origin?"
await member.send(embed=embed)
a9 = await self.get_message_content(member, msg_check)
if not a9: return
embed.description = "- Tell us about yourself?"
await member.send(embed=embed)
a10 = await self.get_message_content(member, msg_check)
if not a10: return
user_native_roles = []
for role in member.roles:
if str(role.name).lower().startswith('native'):
user_native_roles.append(role.name.title())
# Application result
app = f"""```ini\n[Username]: {member} ({member.id})
[Joined the server]: {member.joined_at.strftime("%a, %d %B %y, %I %M %p UTC")}
[Native roles]: {', '.join(user_native_roles)}
[Age]: {a1}
[Experience moderating]: {a2.capitalize()}
[Gender]: {a3.title()}
[English level]: {a4.capitalize()}
[Reason & Motivation]: {a5.capitalize()}
[How we can improve Sloth]: {a6.capitalize()}
[Activity Status]: {a7.capitalize()}
[Timezone]: {a8.title()}
[Origin Country]: {a9.title()}
[About]: {a10.capitalize()}```"""
await member.send(app)
embed.description = """
Are you sure you want to apply this? :white_check_mark: to send and :x: to Cancel
"""
app_conf = await member.send(embed=embed)
await app_conf.add_reaction('✅')
await app_conf.add_reaction('❌')
# Waits for reaction confirmation
r = await self.get_reaction(member, check_reaction)
if r is None:
return
if r == '✅':
# ""
embed.description = """**Application successfully made, please, be patient now.**
We will let you know when we need a new mod. We check apps when we need it!"""
await member.send(embed=embed)
moderator_app_channel = await self.client.fetch_channel(self.moderator_app_channel_id)
cosmos = discord.utils.get(moderator_app_channel.guild.members, id=self.cosmos_id)
app = await moderator_app_channel.send(content=f"{cosmos.mention}, {member.mention}\n{app}")
await app.add_reaction('✅')
await app.add_reaction('❌')
# Saves in the database
await self.insert_application(app.id, member.id, 'moderator')
else:
self.cache[member.id] = 0
return await member.send("**Thank you anyways!**")
async def send_event_manager_application(self, member):
def msg_check(message):
if message.author == member and not message.guild:
if len(message.content) <= 100:
return True
else:
self.client.loop.create_task(member.send("**Your answer must be within 100 characters**"))
else:
return False
def check_reaction(r, u):
return u.id == member.id and not r.message.guild and str(r.emoji) in ['✅', '❌']
terms_embed = discord.Embed(
title="Terms of Application",
description="""Hello there!
Thank you for applying for hosting events here,
Before you can formally start applying to host events in The Language Sloth, there are a couple things we would like you to know. The Language Sloth is a free of charge language learning platform which is meant to be accessible and open for anyone who is interested in languages from any background. We do not charge for any kind of service, nor do we pay for any services for hosting events. We are a community that shares the same interest: Languages.
We do not require professional skills, however, we have a set numbers of requirements for our event managers
Entry requirements:
》Must be at least 16 years of age
》Must have at least a conversational level of English
》Must have clear microphone audio
》Must prepare their own material weekly
``` ✅ To agree with our terms```""",
color=member.color
)
terms = await member.send(embed=terms_embed)
await terms.add_reaction('✅')
await terms.add_reaction('❌')
# Waits for reaction confirmation to the terms of application
terms_r = await self.get_reaction(member, check_reaction)
if terms_r is None:
self.cache[member.id] = 0
return
if terms_r != '✅':
self.cache[member.id] = 0
return await member.send(f"**Thank you anyways, bye!**")
embed = discord.Embed(title=f"__Teacher Application__")
embed.set_footer(text=f"by {member}", icon_url=member.display_avatar)
embed.title = "Event manager Application"
embed.description = '''
- Hello, there you've reacted to apply to become an event manager.
To apply please answer to these following questions with One message at a time
Question one:
What is your event called?'''
q1 = await member.send(embed=embed)
a1 = await self.get_message_content(member, msg_check)
if not a1:
return
embed.description = '''
- Why do you want to host that event on the language sloth?
Please answer with one message.'''
q2 = await member.send(embed=embed)
a2 = await self.get_message_content(member, msg_check)
if not a2:
return
embed.description = '''
- Please let us know when would be the best time for you to host events
E.A: Thursdays 3 pm CET, you can specify your timezone.
Again remember to answer with one message.'''
q3 = await member.send(embed=embed)
a3 = await self.get_message_content(member, msg_check)
if not a3:
return
embed.description = """
- Let's talk about your English level, how do you consider your English level?
Are you able to host events in English? If not, in which language would you be hosting?
Please answer using one message only"""
q4 = await member.send(embed=embed)
a4 = await self.get_message_content(member, msg_check)
if not a4:
return
embed.description = "- Have you ever hosted events before? If yes, please describe!"
q5 = await member.send(embed=embed)
a5 = await self.get_message_content(member, msg_check)
if not a5:
return
embed.description = "- Inform a short description for your event/events."
q6 = await member.send(embed=embed)
a6 = await self.get_message_content(member, msg_check)
if not a6:
return
embed.description = "- How old are you?"
q7 = await member.send(embed=embed)
a7 = await self.get_message_content(member, msg_check)
if not a7:
return
# Get user's native roles
user_native_roles = []
for role in member.roles:
if str(role.name).lower().startswith('native'):
user_native_roles.append(role.name.title())
app = f"""```ini\n[Username]: {member} ({member.id})\n[Joined the server]: {member.joined_at.strftime("%a, %d %B %y, %I %M %p UTC")}\n[Applying to host]: {a1.title()}\n[Native roles]: {', '.join(user_native_roles)}\n[Motivation for hosting]: {a2.capitalize()}\n[Applying to host on]: {a3.upper()}\n[English level]: {a4.capitalize()}\n[Experience hosting]: {a5.capitalize()}\n[Description]:{a6.capitalize()}\n[Age]: {a7}```"""
await member.send(app)
embed.description = '''
Are you sure you want to apply this? :white_check_mark: to send and :x: to Cancel
'''
app_conf = await member.send(embed=embed)
await app_conf.add_reaction('✅')
await app_conf.add_reaction('❌')
r = await self.get_reaction(member, check_reaction)
if r is None:
return
if r == '✅':
embed.description = "**Application successfully made, please, be patient now!**"
await member.send(embed=embed)
event_manager_channel = await self.client.fetch_channel(self.event_manager_app_channel_id)
app = await event_manager_channel.send(content=f"{member.mention}\n{app}")
await app.add_reaction('✅')
await app.add_reaction('❌')
await self.insert_application(app.id, member.id, 'event_manager')
else:
self.cache[member.id] = 0
return await member.send("**Thank you anyways!**")
async def send_verified_selfies_verification(self, interaction: discord.Interaction) -> None:
guild = interaction.guild
member = interaction.user
def msg_check(message):
if message.author == member and not message.guild:
if len(message.content) <= 100:
return True
else:
self.client.loop.create_task(member.send("**Your answer must be within 100 characters**"))
else:
return False
embed = discord.Embed(
title=f"__Verify__",
description=f"""You have opened a verification request, if you would like to verify:\n
**1.** Take a clear picture of yourself holding a piece of paper with today's date and time of verification, and your Discord server name written on it. Image links won't work, only image uploads!\n(You have 5 minutes to do so)"""
)
embed.set_footer(text=f"by {member}", icon_url=member.display_avatar)
embed.set_image(url="https://cdn.discordapp.com/attachments/562019472257318943/882352621116096542/slothfacepopoo.png")
await member.send(embed=embed)
while True:
msg = await self.get_message(member, msg_check, 300)
if msg is None:
return await member.send(f"**Timeout, you didn't answer in time, try again later!**")
attachments = [att for att in msg.attachments if att.content_type.startswith('image')]
if msg.content.lower() == 'quit':
return await member.send(f"**Bye!**")
if not attachments:
await member.send(f"**No uploaded pic detected, send it again or type `quit` to stop this!**")
continue
break
# Sends verified request to admins
verify_embed = discord.Embed(
title=f"__Verification Request__",
description=f"{member} ({member.id})",
color=member.color,
timestamp=interaction.message.created_at
)
verify_embed.set_thumbnail(url=member.display_avatar)
verify_embed.set_image(url=attachments[0])
verify_req_channel_id = discord.utils.get(guild.text_channels, id=self.verify_reqs_channel_id)
verify_msg = await verify_req_channel_id.send(content=member.mention, embed=verify_embed)
await verify_msg.add_reaction('✅')
await verify_msg.add_reaction('❌')
# Saves
await self.insert_application(verify_msg.id, member.id, 'verify')
return await member.send(f"**Request sent, you will get notified here if you get accepted or declined! ✅**")
# - Report someone
async def report_someone(self, interaction: discord.Interaction):
member = interaction.user
guild = interaction.guild
if open_channel := await self.member_has_open_channel(member.id):
if open_channel := discord.utils.get(guild.text_channels, id=open_channel[1]):
embed = discord.Embed(title="Error!", description=f"**You already have an open channel! ({open_channel.mention})**", color=discord.Color.red())
await interaction.followup.send(embed=embed, ephemeral=True)
return False
else:
await self.remove_user_open_channel(member.id)
# Report someone
case_cat = discord.utils.get(guild.categories, id=case_cat_id)
counter = await self.get_case_number()
moderator = discord.utils.get(guild.roles, id=moderator_role_id)
cosmos = discord.utils.get(guild.members, id=self.cosmos_id)
overwrites = {guild.default_role: discord.PermissionOverwrite(
read_messages=False, send_messages=False, connect=False, view_channel=False),
member: discord.PermissionOverwrite(
read_messages=True, send_messages=True, connect=False, view_channel=True),
moderator: discord.PermissionOverwrite(
read_messages=True, send_messages=True, connect=False, view_channel=True, manage_messages=True)}
try:
the_channel = await guild.create_text_channel(name=f"case-{counter[0][0]}", category=case_cat, overwrites=overwrites)
except Exception:
await interaction.followup.send("**Something went wrong with it, please contact an admin!**", ephemeral=True)
raise Exception
else:
created_embed = discord.Embed(
title="Report room created!",
description=f"**Go to {the_channel.mention}!**",
color=discord.Color.green())
await interaction.followup.send(embed=created_embed, ephemeral=True)
await self.insert_user_open_channel(member.id, the_channel.id)
await self.increase_case_number()
embed = discord.Embed(title="Report Support!", description=f"Please, {member.mention}, try to explain what happened and who you want to report.",
color=discord.Color.red())
message = await the_channel.send(content=f"{member.mention}, {moderator.mention}, {cosmos.mention}", embed=embed)
ctx = await self.client.get_context(message)
return await self.client.get_cog('Tools').vc(ctx, member=member)
# - Report someone
async def generic_help(self, interaction: discord.Interaction, type_help: str, message: str, ping: bool = True) -> None:
member = interaction.user
guild = interaction.guild
if open_channel := await self.member_has_open_channel(member.id):
if open_channel := discord.utils.get(guild.text_channels, id=open_channel[1]):
embed = discord.Embed(title="Error!", description=f"**You already have an open channel! ({open_channel.mention})**", color=discord.Color.red())
await interaction.followup.send(embed=embed, ephemeral=True)
return False
else:
await self.remove_user_open_channel(member.id)
# General help
case_cat = discord.utils.get(guild.categories, id=case_cat_id)
moderator = discord.utils.get(guild.roles, id=moderator_role_id)
overwrites = {guild.default_role: discord.PermissionOverwrite(
read_messages=False, send_messages=False, connect=False, view_channel=False),
member: discord.PermissionOverwrite(
read_messages=True, send_messages=True, connect=False, view_channel=True),
moderator: discord.PermissionOverwrite(
read_messages=True, send_messages=True, connect=False, view_channel=True, manage_messages=True)}
try:
the_channel = await guild.create_text_channel(name=f"{'-'.join(type_help.split())}", category=case_cat, overwrites=overwrites)
except:
await interaction.followup.send("**Something went wrong with it, please contact an admin!**", ephemeral=True)
raise Exception
else:
created_embed = discord.Embed(
title=f"Room for `{type_help}` created!",
description=f"**Go to {the_channel.mention}!**",
color=discord.Color.green())
await interaction.followup.send(embed=created_embed, ephemeral=True)
await self.insert_user_open_channel(member.id, the_channel.id)
embed = discord.Embed(title=f"{type_help.title()}!", description=message, color=discord.Color.red())
if ping:
await the_channel.send(content=f"{member.mention}, {moderator.mention}", embed=embed)
else:
await the_channel.send(content=member.mention, embed=embed)
async def get_message_content(self, member, check, timeout: Optional[int] = 300) -> str:
try:
message = await self.client.wait_for('message', timeout=timeout,
check=check)
except asyncio.TimeoutError:
await member.send("**Timeout! Try again.**")
return None
else:
content = message.content
return content
async def get_message(self, member, check, timeout: Optional[int] = 300) -> discord.Message:
try:
message = await self.client.wait_for('message', timeout=timeout,
check=check)
except asyncio.TimeoutError:
await member.send("**Timeout! Try again.**")
return None
else:
return message
async def get_reaction(self, member, check, timeout: int = 300):
try:
reaction, _ = await self.client.wait_for('reaction_add',
timeout=timeout, check=check)
except asyncio.TimeoutError:
await member.send("**Timeout! Try again.**")
return None
else:
return str(reaction.emoji)
@commands.command(aliases=['permit_case', 'allow_case', 'add_witness', 'witness', 'aw'])
@commands.has_any_role(*allowed_roles)
async def allow_witness(self, ctx, member: discord.Member = None):
if not member:
return await ctx.send("**Inform a witness to allow!**")
user_channel = await self.get_case_channel(ctx.channel.id)
if user_channel:
confirm = await Confirm(f"**Are you sure you want to allow {member.mention} as a witness in this case channel, {ctx.author.mention}?**").prompt(ctx)
if not confirm:
return await ctx.send(f"**Not allowing them, then!**")
channel = discord.utils.get(ctx.guild.channels, id=user_channel[0][1])
try:
await channel.set_permissions(
member, read_messages=True, send_messages=True, connect=True, speak=True, view_channel=True)
except Exception:
pass
return await ctx.send(f"**{member.mention} has been allowed here!**")
else:
await ctx.send(f"**This is not a case channel, {ctx.author.mention}!**")
@commands.command(aliases=['forbid_case', 'delete_witness', 'remve_witness', 'fw'])
@commands.has_any_role(*allowed_roles)
async def forbid_witness(self, ctx, member: discord.Member = None):
if not member:
return await ctx.send("**Inform a witness to forbid!**")
user_channel = await self.get_case_channel(ctx.channel.id)
if user_channel:
confirm = await Confirm(f"**Are you sure you want to forbid {member.mention} from being a witness in this case channel, {ctx.author.mention}?**").prompt(ctx)
if not confirm:
return await ctx.send(f"**Not forbidding them, then!**")
channel = discord.utils.get(ctx.guild.channels, id=user_channel[0][1])
try:
await channel.set_permissions(
member, read_messages=False, send_messages=False, connect=False, speak=False, view_channel=False)
except Exception:
pass
return await ctx.send(f"**{member.mention} has been forbidden here!**")
else:
await ctx.send(f"**This is not a case channel, {ctx.author.mention}!**")
@commands.command(aliases=['delete_channel', 'archive'])
@commands.has_any_role(*allowed_roles)
async def close_channel(self, ctx):
user_channel = await self.get_case_channel(ctx.channel.id)
if not user_channel:
return await ctx.send(f"**What do you think that you are doing? You cannot delete this channel, {ctx.author.mention}!**")
channel = discord.utils.get(ctx.guild.text_channels, id=user_channel[0][1])
embed = discord.Embed(title="Confirmation",
description="Are you sure that you want to delete this channel?",
color=ctx.author.color,
timestamp=ctx.message.created_at)
confirmation = await ctx.send(content=ctx.author.mention, embed=embed)
await confirmation.add_reaction('✅')
await confirmation.add_reaction('❌')
try:
reaction, user = await self.client.wait_for('reaction_add', timeout=20,
check=lambda r, u: u == ctx.author and r.message.channel == ctx.channel and str(r.emoji) in ['✅', '❌'])
except asyncio.TimeoutError:
embed = discord.Embed(title="Confirmation",
description="You took too long to answer the question; not deleting it!",
color=discord.Color.red(),
timestamp=ctx.message.created_at)
return await confirmation.edit(content=ctx.author.mention, embed=embed)
else:
if str(reaction.emoji) == '✅':
embed.description = f"**Channel {ctx.channel.mention} is being deleted...**"
await confirmation.edit(content=ctx.author.mention, embed=embed)
await asyncio.sleep(3)
await channel.delete()
await self.remove_user_open_channel(user_channel[0][0])
else:
embed.description = "Not deleting it!"
await confirmation.edit(content='', embed=embed)
async def dnk_embed(self, member):
def check(r, u):
return u == member and str(r.message.id) == str(the_msg.id) and str(r.emoji) in ['⬅️', '➡️']
command_index = 0
initial_embed = discord.Embed(title="__Table of Commands and their Prices__",
description="These are a few of commands and features that DNK can do.",
color=discord.Color.blue())
the_msg = await member.send(embed=initial_embed)
await the_msg.add_reaction('⬅️')
await the_msg.add_reaction('➡️')
while True:
embed = discord.Embed(title=f"__Table of Commands and their Prices__ ({command_index+1}/{len(list_of_commands)})",
description="These are a few of commands and features that DNK can do.",
color=discord.Color.blue())
embed.add_field(name=list_of_commands[command_index][0],
value=list_of_commands[command_index][1])
await the_msg.edit(embed=embed)
try:
pending_tasks = [self.client.wait_for('reaction_add', check=check),
self.client.wait_for('reaction_remove', check=check)]
done_tasks, pending_tasks = await asyncio.wait(pending_tasks, timeout=60, return_when=asyncio.FIRST_COMPLETED)
if not done_tasks:
raise asyncio.TimeoutError
for task in pending_tasks:
task.cancel()
except asyncio.TimeoutError:
await the_msg.remove_reaction('⬅️', self.client.user)
await the_msg.remove_reaction('➡️', self.client.user)
break
else:
for task in done_tasks:
reaction, user = await task
if str(reaction.emoji) == "➡️":
# await the_msg.remove_reaction(reaction.emoji, member)
if command_index < (len(list_of_commands) - 1):
command_index += 1
continue
elif str(reaction.emoji) == "⬅️":
# await the_msg.remove_reaction(reaction.emoji, member)
if command_index > 0:
command_index -= 1
continue
# Discord methods
async def create_interview_room(self, guild: discord.Guild, app: List[str]) -> None:
applicant = discord.utils.get(guild.members, id=app[1])
interview_info = self.interview_info.get(app[2])
# Create Private Thread for the user
app_parent = self.client.get_channel(interview_info['parent'])
#delete this later
message = None
# message = await app_parent.send('Uncomment this in your development environment')
txt_channel = await app_parent.create_thread(name=f"{applicant.display_name}'s-interview", message=message, reason=f"{app[2].title()} Interview Room")
parent_channel = self.client.get_channel(interview_info['parent'])
interview_vc = self.client.get_channel(interview_info['interview'])
await self.update_application(applicant.id, txt_channel.id, interview_vc.id, app[2])
# Set channel perms for the user.
await parent_channel.set_permissions(applicant, read_messages=True, send_messages=False, view_channel=True)
await interview_vc.set_permissions(applicant, speak=True, connect=True, view_channel=True)
app_embed = discord.Embed(
title=f"{applicant.name}'s Interview",
description=f"""
Hello, {applicant.mention}, we have received and reviewed your `{app[2].title().replace('_', ' ')}` application. In order to explain how our system works we have to schedule a voice conversation with you.
When would be the best time to talk to one of our staff?""",
color=applicant.color)
formatted_pings = await self.format_application_pings(guild, interview_info['pings'])
await txt_channel.send(content=f"{formatted_pings}, {applicant.mention}", embed=app_embed)
@commands.command()
@commands.has_permissions(administrator=True)
async def close_app(self, ctx) -> None:
member = ctx.author
channel = ctx.channel
guild = ctx.guild
if not (app := await self.get_application_by_channel(channel.id)):
return await ctx.send(f"**This is not an application channel, {member.mention}!**")
interview_info = self.interview_info[app[2]]
all_apps_channel = discord.utils.get(guild.text_channels, id=interview_info['app'])
confirm = await Confirm(f"**Are you sure that you want to delete this application channel, {member.mention}?**").prompt(ctx)
if not confirm:
return await ctx.send(f"**Not deleting it, then, {member.mention}!**")
applicant = guild.get_member(app[1])
parent_channel = discord.utils.get(guild.text_channels, id=interview_info['parent'])
interview_vc = discord.utils.get(guild.voice_channels, id=interview_info['interview'])
try:
await parent_channel.set_permissions(applicant, overwrite=None)
await interview_vc.set_permissions(applicant, overwrite=None)
except:
pass
await channel.delete()
await self.delete_application(app[0])
try:
msg = await all_apps_channel.fetch_message(app[0])
await msg.add_reaction('🔒')
except:
pass
async def audio(self, member: discord.Member, audio_name: str) -> None:
staff_vc = self.client.get_channel(staff_vc_id)
bot_state = member.guild.voice_client
try:
if bot_state and bot_state.channel and bot_state.channel != staff_vc:
await bot_state.disconnect()
await bot_state.move_to(staff_vc)
elif not bot_state:
voicechannel = discord.utils.get(member.guild.channels, id=staff_vc.id)
vc = await voicechannel.connect()
await asyncio.sleep(2)
voice_client: discord.VoiceClient = discord.utils.get(self.client.voice_clients, guild=member.guild)
# Plays / and they don't stop commin' /
if voice_client and not voice_client.is_playing():
audio_source = discord.FFmpegPCMAudio(f'tts/{audio_name}.mp3')
voice_client.play(audio_source, after=lambda e: print("Finished Warning Staff!"))
else:
print('couldnt play it!')
except Exception as e:
print(e)
return
@commands.command(aliases=['make_report_msg', 'reportmsg', 'report_msg', 'supportmsg', 'support_msg'])
@commands.has_permissions(administrator=True)
async def make_report_support_message(self, ctx) -> None:
guild = ctx.guild
embed = discord.Embed(
title="__Report-Support Section__",
description="""Welcome to the Report-Support section, here you can easily find your way into things and/or get help with whatever problem you may be experiencing.""",
color=ctx.author.color,
timestamp=ctx.message.created_at,
url="https://thelanguagesloth.com"
)
embed.set_author(name=self.client.user.display_name, url=self.client.user.display_avatar, icon_url=self.client.user.display_avatar)
embed.set_thumbnail(url=guild.icon.url)
embed.set_footer(text=guild.name, icon_url=guild.icon.url)
view = ReportSupportView(self.client)
await ctx.send("\u200b", embed=embed, view=view)
self.client.add_view(view=view)
def setup(client):
client.add_cog(ReportSupport(client))
| true | true |
f7f6cc4c4d028ea869bdd4efeda508d0bb804297 | 3,037 | py | Python | rasa/nlu/utils/hugging_face/registry.py | tienhoang1994/rasa | a977a8f1fb2308bebe7becd2c024765528296bd6 | [
"Apache-2.0"
] | 3,603 | 2017-05-21T18:34:55.000Z | 2019-04-16T11:58:09.000Z | rasa/nlu/utils/hugging_face/registry.py | tienhoang1994/rasa | a977a8f1fb2308bebe7becd2c024765528296bd6 | [
"Apache-2.0"
] | 2,782 | 2017-05-21T20:36:15.000Z | 2019-04-16T14:35:20.000Z | rasa/nlu/utils/hugging_face/registry.py | tienhoang1994/rasa | a977a8f1fb2308bebe7becd2c024765528296bd6 | [
"Apache-2.0"
] | 1,337 | 2017-05-21T18:10:33.000Z | 2019-04-16T09:14:42.000Z | import logging
from typing import Dict, Text, Type
# Explicitly set logging level for this module before any import
# because otherwise it logs tensorflow/pytorch versions
logging.getLogger("transformers.file_utils").setLevel(logging.WARNING)
from transformers import ( # noqa: F401, E402
TFPreTrainedModel,
TFBertModel,
TFOpenAIGPTModel,
TFGPT2Model,
TFXLNetModel,
# TFXLMModel,
TFDistilBertModel,
TFRobertaModel,
PreTrainedTokenizer,
BertTokenizer,
OpenAIGPTTokenizer,
GPT2Tokenizer,
XLNetTokenizer,
# XLMTokenizer,
DistilBertTokenizer,
RobertaTokenizer,
)
from rasa.nlu.utils.hugging_face.transformers_pre_post_processors import ( # noqa: F401, E402, E501
bert_tokens_pre_processor,
gpt_tokens_pre_processor,
xlnet_tokens_pre_processor,
roberta_tokens_pre_processor,
bert_embeddings_post_processor,
gpt_embeddings_post_processor,
xlnet_embeddings_post_processor,
roberta_embeddings_post_processor,
bert_tokens_cleaner,
openaigpt_tokens_cleaner,
gpt2_tokens_cleaner,
xlnet_tokens_cleaner,
)
model_class_dict: Dict[Text, Type[TFPreTrainedModel]] = {
"bert": TFBertModel,
"gpt": TFOpenAIGPTModel,
"gpt2": TFGPT2Model,
"xlnet": TFXLNetModel,
# "xlm": TFXLMModel, # Currently doesn't work because of a bug in transformers
# library https://github.com/huggingface/transformers/issues/2729
"distilbert": TFDistilBertModel,
"roberta": TFRobertaModel,
}
model_tokenizer_dict: Dict[Text, Type[PreTrainedTokenizer]] = {
"bert": BertTokenizer,
"gpt": OpenAIGPTTokenizer,
"gpt2": GPT2Tokenizer,
"xlnet": XLNetTokenizer,
# "xlm": XLMTokenizer,
"distilbert": DistilBertTokenizer,
"roberta": RobertaTokenizer,
}
model_weights_defaults = {
"bert": "rasa/LaBSE",
"gpt": "openai-gpt",
"gpt2": "gpt2",
"xlnet": "xlnet-base-cased",
# "xlm": "xlm-mlm-enfr-1024",
"distilbert": "distilbert-base-uncased",
"roberta": "roberta-base",
}
model_special_tokens_pre_processors = {
"bert": bert_tokens_pre_processor,
"gpt": gpt_tokens_pre_processor,
"gpt2": gpt_tokens_pre_processor,
"xlnet": xlnet_tokens_pre_processor,
# "xlm": xlm_tokens_pre_processor,
"distilbert": bert_tokens_pre_processor,
"roberta": roberta_tokens_pre_processor,
}
model_tokens_cleaners = {
"bert": bert_tokens_cleaner,
"gpt": openaigpt_tokens_cleaner,
"gpt2": gpt2_tokens_cleaner,
"xlnet": xlnet_tokens_cleaner,
# "xlm": xlm_tokens_pre_processor,
"distilbert": bert_tokens_cleaner, # uses the same as BERT
"roberta": gpt2_tokens_cleaner, # Uses the same as GPT2
}
model_embeddings_post_processors = {
"bert": bert_embeddings_post_processor,
"gpt": gpt_embeddings_post_processor,
"gpt2": gpt_embeddings_post_processor,
"xlnet": xlnet_embeddings_post_processor,
# "xlm": xlm_embeddings_post_processor,
"distilbert": bert_embeddings_post_processor,
"roberta": roberta_embeddings_post_processor,
}
| 30.37 | 100 | 0.731643 | import logging
from typing import Dict, Text, Type
logging.getLogger("transformers.file_utils").setLevel(logging.WARNING)
from transformers import (
TFPreTrainedModel,
TFBertModel,
TFOpenAIGPTModel,
TFGPT2Model,
TFXLNetModel,
TFDistilBertModel,
TFRobertaModel,
PreTrainedTokenizer,
BertTokenizer,
OpenAIGPTTokenizer,
GPT2Tokenizer,
XLNetTokenizer,
DistilBertTokenizer,
RobertaTokenizer,
)
from rasa.nlu.utils.hugging_face.transformers_pre_post_processors import (
bert_tokens_pre_processor,
gpt_tokens_pre_processor,
xlnet_tokens_pre_processor,
roberta_tokens_pre_processor,
bert_embeddings_post_processor,
gpt_embeddings_post_processor,
xlnet_embeddings_post_processor,
roberta_embeddings_post_processor,
bert_tokens_cleaner,
openaigpt_tokens_cleaner,
gpt2_tokens_cleaner,
xlnet_tokens_cleaner,
)
model_class_dict: Dict[Text, Type[TFPreTrainedModel]] = {
"bert": TFBertModel,
"gpt": TFOpenAIGPTModel,
"gpt2": TFGPT2Model,
"xlnet": TFXLNetModel,
s/issues/2729
"distilbert": TFDistilBertModel,
"roberta": TFRobertaModel,
}
model_tokenizer_dict: Dict[Text, Type[PreTrainedTokenizer]] = {
"bert": BertTokenizer,
"gpt": OpenAIGPTTokenizer,
"gpt2": GPT2Tokenizer,
"xlnet": XLNetTokenizer,
# "xlm": XLMTokenizer,
"distilbert": DistilBertTokenizer,
"roberta": RobertaTokenizer,
}
model_weights_defaults = {
"bert": "rasa/LaBSE",
"gpt": "openai-gpt",
"gpt2": "gpt2",
"xlnet": "xlnet-base-cased",
# "xlm": "xlm-mlm-enfr-1024",
"distilbert": "distilbert-base-uncased",
"roberta": "roberta-base",
}
model_special_tokens_pre_processors = {
"bert": bert_tokens_pre_processor,
"gpt": gpt_tokens_pre_processor,
"gpt2": gpt_tokens_pre_processor,
"xlnet": xlnet_tokens_pre_processor,
# "xlm": xlm_tokens_pre_processor,
"distilbert": bert_tokens_pre_processor,
"roberta": roberta_tokens_pre_processor,
}
model_tokens_cleaners = {
"bert": bert_tokens_cleaner,
"gpt": openaigpt_tokens_cleaner,
"gpt2": gpt2_tokens_cleaner,
"xlnet": xlnet_tokens_cleaner,
# "xlm": xlm_tokens_pre_processor,
"distilbert": bert_tokens_cleaner, # uses the same as BERT
"roberta": gpt2_tokens_cleaner, # Uses the same as GPT2
}
model_embeddings_post_processors = {
"bert": bert_embeddings_post_processor,
"gpt": gpt_embeddings_post_processor,
"gpt2": gpt_embeddings_post_processor,
"xlnet": xlnet_embeddings_post_processor,
# "xlm": xlm_embeddings_post_processor,
"distilbert": bert_embeddings_post_processor,
"roberta": roberta_embeddings_post_processor,
}
| true | true |
f7f6cc6e8791eb239b3360a4cd1522a216954415 | 891 | bzl | Python | google/cloud/storage/benchmarks/storage_benchmarks_unit_tests.bzl | utgarda/google-cloud-cpp | c4fd446d2c9e1428bcec10917f269f8e5c0a8bc0 | [
"Apache-2.0"
] | 1 | 2020-10-30T09:05:17.000Z | 2020-10-30T09:05:17.000Z | google/cloud/storage/benchmarks/storage_benchmarks_unit_tests.bzl | utgarda/google-cloud-cpp | c4fd446d2c9e1428bcec10917f269f8e5c0a8bc0 | [
"Apache-2.0"
] | 2 | 2020-10-06T15:50:06.000Z | 2020-11-24T16:21:28.000Z | google/cloud/storage/benchmarks/storage_benchmarks_unit_tests.bzl | utgarda/google-cloud-cpp | c4fd446d2c9e1428bcec10917f269f8e5c0a8bc0 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# DO NOT EDIT -- GENERATED BY CMake -- Change the CMakeLists.txt file if needed
"""Automatically generated unit tests list - DO NOT EDIT."""
storage_benchmarks_unit_tests = [
"benchmark_make_random_test.cc",
"benchmark_parser_test.cc",
"throughput_options_test.cc",
"throughput_result_test.cc",
]
| 35.64 | 79 | 0.751964 |
storage_benchmarks_unit_tests = [
"benchmark_make_random_test.cc",
"benchmark_parser_test.cc",
"throughput_options_test.cc",
"throughput_result_test.cc",
]
| true | true |
f7f6cca04cfde110b554b151101dcbf51385de3d | 1,595 | py | Python | environment/fake_gym/fake_gym.py | id9502/RLFrame | a6fe99c6578e74f74767720b9212365e10f0cefd | [
"MIT"
] | 8 | 2020-02-09T03:33:50.000Z | 2022-01-05T06:35:28.000Z | environment/fake_gym/fake_gym.py | id9502/RLFrame | a6fe99c6578e74f74767720b9212365e10f0cefd | [
"MIT"
] | null | null | null | environment/fake_gym/fake_gym.py | id9502/RLFrame | a6fe99c6578e74f74767720b9212365e10f0cefd | [
"MIT"
] | 2 | 2020-02-10T03:21:31.000Z | 2020-03-22T15:40:37.000Z | import gym
from core.common.types import StepDict
from core.environment.environment import Environment
class FakeGymEnv(Environment):
def __init__(self, task_name: str):
super(FakeGymEnv, self).__init__(task_name)
self._render = False
self._env = gym.make(task_name)
self._info["action dim"] = self._env.action_space.shape
self._info["action low"] = self._env.action_space.low
self._info["action high"] = self._env.action_space.high
self._info["state dim"] = self._env.observation_space.shape
self._info["state low"] = self._env.observation_space.low
self._info["state high"] = self._env.observation_space.high
self._info["reward low"] = self._env.reward_range[0]
self._info["reward high"] = self._env.reward_range[1]
self._env.close()
self._env = None
pass
def init(self, display: bool = False) -> bool:
self._render = display
self._env = gym.make(self._task_name)
return True
def finalize(self) -> bool:
if self._env is not None:
self._env.close()
self._env = None
return True
def reset(self, random: bool = True) -> StepDict:
s = self._env.reset()
return {'s': s}
def step(self, last_step: StepDict) -> (StepDict, StepDict, bool):
s, r, done, info = self._env.step(last_step['a'])
if self._render:
self._env.render()
last_step['r'] = r
last_step["info"] = info
next_step = {'s': s}
return last_step, next_step, done
| 33.229167 | 70 | 0.616301 | import gym
from core.common.types import StepDict
from core.environment.environment import Environment
class FakeGymEnv(Environment):
def __init__(self, task_name: str):
super(FakeGymEnv, self).__init__(task_name)
self._render = False
self._env = gym.make(task_name)
self._info["action dim"] = self._env.action_space.shape
self._info["action low"] = self._env.action_space.low
self._info["action high"] = self._env.action_space.high
self._info["state dim"] = self._env.observation_space.shape
self._info["state low"] = self._env.observation_space.low
self._info["state high"] = self._env.observation_space.high
self._info["reward low"] = self._env.reward_range[0]
self._info["reward high"] = self._env.reward_range[1]
self._env.close()
self._env = None
pass
def init(self, display: bool = False) -> bool:
self._render = display
self._env = gym.make(self._task_name)
return True
def finalize(self) -> bool:
if self._env is not None:
self._env.close()
self._env = None
return True
def reset(self, random: bool = True) -> StepDict:
s = self._env.reset()
return {'s': s}
def step(self, last_step: StepDict) -> (StepDict, StepDict, bool):
s, r, done, info = self._env.step(last_step['a'])
if self._render:
self._env.render()
last_step['r'] = r
last_step["info"] = info
next_step = {'s': s}
return last_step, next_step, done
| true | true |
f7f6ceda5d7240a774e782f3a92e9b21c1cb00bf | 4,468 | py | Python | v3/GetReleasePackage.py | Onevizion/api-samples | 24a43d12f1a5be9f51f35cdd3b644a867d77419f | [
"MIT"
] | null | null | null | v3/GetReleasePackage.py | Onevizion/api-samples | 24a43d12f1a5be9f51f35cdd3b644a867d77419f | [
"MIT"
] | null | null | null | v3/GetReleasePackage.py | Onevizion/api-samples | 24a43d12f1a5be9f51f35cdd3b644a867d77419f | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import pysftp
import onevizion
import json
import os
import operator
from collections import OrderedDict
# Handle command arguments
import argparse
Description="""Compiles a complete upgrade package for getting a OneVizion system from a given current version to a desired New version. It does so by using the OneVizion Releases SFTP site given to a client by a OneVizion administrator.
"""
EpiLog = onevizion.PasswordExample + """\n\n
"""
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description=Description,epilog=EpiLog)
parser.add_argument(
"-V",
"--version",
metavar="WantedVersion",
help="Version to be copied to SFTP",
default=""
)
parser.add_argument(
"-C",
"--currentversion",
metavar="CurrentVersion",
help="Current Version to be compared for scripts to be copied to SFTP",
default="DEFAULT"
)
parser.add_argument(
"-v",
"--verbose",
action='count',
default=0,
help="Print extra debug messages and save to a file. Attach file to email if sent."
)
parser.add_argument(
"-p",
"--parameters",
metavar="ParametersFile",
help="JSON file where parameters are stored.",
default="Parameters.json"
)
args = parser.parse_args()
ParamtersFile = args.parameters
ThisVersion = args.version
CurrentVersion = args.currentversion
#Set some standard OneVizion Parameters
onevizion.Config["Verbosity"]=args.verbose
onevizion.Config["SMTPToken"]="SMTP"
Params = onevizion.GetParameters(ParamtersFile)
Message = onevizion.Message
Trace = onevizion.Config["Trace"]
def VersionSplit(ThisVersion):
"""
Splits up a String Version number (e.g: '8.59.10') into a numerical array for numeric sorting.
"""
VersionBreak=ThisVersion.split(".")
VersionParts=[]
VersionParts.append(int(VersionBreak[0]))
VersionParts.append(int(VersionBreak[1]))
RelVer = VersionBreak[2].split('-RC')
VersionParts.append(int(RelVer[0]))
if len(RelVer) == 2:
VersionParts.append(int(RelVer[1]))
return VersionParts
# Get the SFTP login from a local Parameters.json file
sftpHost = Params['ReleaseSFTP']['Host']
sftpUserName = Params['ReleaseSFTP']['UserName']
sftpPassword = Params['ReleaseSFTP']['Password']
# Get list of Folders for releases to extrapalate all releases given.
Message("Connecting to %s"%(sftpHost))
with pysftp.Connection(sftpHost, username=sftpUserName, password=sftpPassword) as sftp:
sftp.chdir("releases")
ReleasesList = sftp.listdir()
Message(json.dumps(ReleasesList,indent=2),2)
# Build List of Versions from sftp directory and sort numerically to get proper order
Versions = []
for Version in ReleasesList:
Versions.append(VersionSplit(Version))
Versions.sort(key=operator.itemgetter(0,1,2))
# Rebuild the now numerically ordered vesions list back into a lit of Strings.
VersionsStr = []
for Version in Versions:
VersionsStr.append("%d.%d.%d"%(Version[0],Version[1],Version[2]))
Message(json.dumps(VersionsStr,indent=2), 2)
# Break out an ordered list of only the needed version updates.
NeededVersions = []
for i in range(VersionsStr.index(CurrentVersion)+1,VersionsStr.index(ThisVersion)+1):
NeededVersions.append(VersionsStr[i])
Message("{NumVers} upgrades to apply.".format(NumVers=len(NeededVersions)))
Message(json.dumps(NeededVersions,indent=2), 1)
#Build a local folder in which to place the downloaded files
VersionRootFolder = "{CurVer}-to-{ThisVer}".format(CurVer=CurrentVersion,ThisVer=ThisVersion)
if not os.path.exists(VersionRootFolder):
os.makedirs(VersionRootFolder)
if not os.path.exists(VersionRootFolder+"/db"):
os.makedirs(VersionRootFolder+"/db")
if not os.path.exists(VersionRootFolder+"/db/rollback"):
os.makedirs(VersionRootFolder+"/db/rollback")
# Download all the needed script files and executables
Message("Downloading files to folder {RootDir}".format(RootDir=VersionRootFolder))
with pysftp.Connection(sftpHost, username=sftpUserName, password=sftpPassword) as sftp:
for Ver in NeededVersions:
Message("Downloading Scripts for Version {Ver}".format(Ver=Ver),1)
sftp.get_d(
remotedir="releases/{Ver}/db".format(Ver=Ver),
localdir=VersionRootFolder+"/db"
)
sftp.get_d(
remotedir="releases/{Ver}/db/rollback".format(Ver=Ver),
localdir=VersionRootFolder+"/db/rollback"
)
Message("Downloading Executables for Version {Ver}".format(Ver=ThisVersion),1)
sftp.get_d(
remotedir="releases/{Ver}".format(Ver=ThisVersion),
localdir=VersionRootFolder
)
Message("Downloads Complete.")
| 31.027778 | 238 | 0.760967 |
import pysftp
import onevizion
import json
import os
import operator
from collections import OrderedDict
import argparse
Description="""Compiles a complete upgrade package for getting a OneVizion system from a given current version to a desired New version. It does so by using the OneVizion Releases SFTP site given to a client by a OneVizion administrator.
"""
EpiLog = onevizion.PasswordExample + """\n\n
"""
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description=Description,epilog=EpiLog)
parser.add_argument(
"-V",
"--version",
metavar="WantedVersion",
help="Version to be copied to SFTP",
default=""
)
parser.add_argument(
"-C",
"--currentversion",
metavar="CurrentVersion",
help="Current Version to be compared for scripts to be copied to SFTP",
default="DEFAULT"
)
parser.add_argument(
"-v",
"--verbose",
action='count',
default=0,
help="Print extra debug messages and save to a file. Attach file to email if sent."
)
parser.add_argument(
"-p",
"--parameters",
metavar="ParametersFile",
help="JSON file where parameters are stored.",
default="Parameters.json"
)
args = parser.parse_args()
ParamtersFile = args.parameters
ThisVersion = args.version
CurrentVersion = args.currentversion
onevizion.Config["Verbosity"]=args.verbose
onevizion.Config["SMTPToken"]="SMTP"
Params = onevizion.GetParameters(ParamtersFile)
Message = onevizion.Message
Trace = onevizion.Config["Trace"]
def VersionSplit(ThisVersion):
VersionBreak=ThisVersion.split(".")
VersionParts=[]
VersionParts.append(int(VersionBreak[0]))
VersionParts.append(int(VersionBreak[1]))
RelVer = VersionBreak[2].split('-RC')
VersionParts.append(int(RelVer[0]))
if len(RelVer) == 2:
VersionParts.append(int(RelVer[1]))
return VersionParts
sftpHost = Params['ReleaseSFTP']['Host']
sftpUserName = Params['ReleaseSFTP']['UserName']
sftpPassword = Params['ReleaseSFTP']['Password']
Message("Connecting to %s"%(sftpHost))
with pysftp.Connection(sftpHost, username=sftpUserName, password=sftpPassword) as sftp:
sftp.chdir("releases")
ReleasesList = sftp.listdir()
Message(json.dumps(ReleasesList,indent=2),2)
Versions = []
for Version in ReleasesList:
Versions.append(VersionSplit(Version))
Versions.sort(key=operator.itemgetter(0,1,2))
VersionsStr = []
for Version in Versions:
VersionsStr.append("%d.%d.%d"%(Version[0],Version[1],Version[2]))
Message(json.dumps(VersionsStr,indent=2), 2)
NeededVersions = []
for i in range(VersionsStr.index(CurrentVersion)+1,VersionsStr.index(ThisVersion)+1):
NeededVersions.append(VersionsStr[i])
Message("{NumVers} upgrades to apply.".format(NumVers=len(NeededVersions)))
Message(json.dumps(NeededVersions,indent=2), 1)
VersionRootFolder = "{CurVer}-to-{ThisVer}".format(CurVer=CurrentVersion,ThisVer=ThisVersion)
if not os.path.exists(VersionRootFolder):
os.makedirs(VersionRootFolder)
if not os.path.exists(VersionRootFolder+"/db"):
os.makedirs(VersionRootFolder+"/db")
if not os.path.exists(VersionRootFolder+"/db/rollback"):
os.makedirs(VersionRootFolder+"/db/rollback")
Message("Downloading files to folder {RootDir}".format(RootDir=VersionRootFolder))
with pysftp.Connection(sftpHost, username=sftpUserName, password=sftpPassword) as sftp:
for Ver in NeededVersions:
Message("Downloading Scripts for Version {Ver}".format(Ver=Ver),1)
sftp.get_d(
remotedir="releases/{Ver}/db".format(Ver=Ver),
localdir=VersionRootFolder+"/db"
)
sftp.get_d(
remotedir="releases/{Ver}/db/rollback".format(Ver=Ver),
localdir=VersionRootFolder+"/db/rollback"
)
Message("Downloading Executables for Version {Ver}".format(Ver=ThisVersion),1)
sftp.get_d(
remotedir="releases/{Ver}".format(Ver=ThisVersion),
localdir=VersionRootFolder
)
Message("Downloads Complete.")
| true | true |
f7f6cef86a6f4bc309971d1eace5ce21af7ea457 | 18,342 | py | Python | ftp_server.py | g04630910/pythonftpserver | 9771cd9b6ed8a8c3b0f56eee4758debb82dea958 | [
"Apache-2.0"
] | 3 | 2020-07-17T09:37:50.000Z | 2020-07-18T11:23:24.000Z | ftp_server.py | g04630910/pythonftpserver | 9771cd9b6ed8a8c3b0f56eee4758debb82dea958 | [
"Apache-2.0"
] | null | null | null | ftp_server.py | g04630910/pythonftpserver | 9771cd9b6ed8a8c3b0f56eee4758debb82dea958 | [
"Apache-2.0"
] | 2 | 2020-07-18T00:17:22.000Z | 2020-07-18T04:55:45.000Z | #-*-coding:utf-8-*-
import socket, threading, os, sys, time, datetime
import hashlib, platform, stat
from os.path import join, getsize
listen_ip = "0.0.0.0"
listen_port = 21
conn_list = []
root_dir = "C://Autodesk"
if sys.version_info < (3, 0):
root_dir = root_dir.decode('utf-8').encode('gb2312')#目录 windows目录下使用这个
#root_dir = "/"#Linux utf8系统使用这个
max_connections = 500
conn_timeout = 120
class FtpConnection(threading.Thread):
def __init__(self, fd):
threading.Thread.__init__(self)
self.fd = fd
self.running = True
self.setDaemon(True)
self.alive_time = time.time()
self.option_utf8 = False
self.identified = False
self.option_pasv = True
self.username = ""
self.file_pos = 0
self.u_username = "wmfy808"#帐号
self.u_passwd="123456"#密码
self.u_limit_size=5*1024*1024*1024#限制目录大小为5G
self.u_permission = "read,write,modify"#权限
def process(self, cmd, arg):
cmd = cmd.upper();
arg2 = []
if self.option_utf8:
if sys.version_info < (3, 0):
arg = unicode(arg, "utf8").encode(sys.getfilesystemencoding())
print ("<<", cmd, arg, self.fd)
# Ftp Command
if cmd == "BYE" or cmd == "QUIT":
if os.path.exists(root_dir + "/xxftp.goodbye"):
self.message(221, open(root_dir + "/xxftp.goodbye").read())
else:
self.message(221, "Bye!")
self.running = False
return
elif cmd == "USER":
# Set Anonymous User
if arg == "": arg = "anonymous"
for c in arg:
if not c.isalpha() and not c.isdigit() and c!="_":
self.message(530, "Incorrect username.")
return
self.username = arg
self.home_dir = root_dir
self.curr_dir = "/"
self.curr_dir, self.full_path, permission, self.vdir_list, \
limit_size, is_virtual = self.parse_path("/")
if not os.path.isdir(self.home_dir):
self.message(530, "path " + self.home_dir + " not exists.")
return
self.pass_path = self.home_dir + "/.xxftp/password"
if os.path.isfile(self.pass_path):
self.message(331, "Password required for " + self.username)
else:
self.message(230, "Identified!")
self.identified = True
return
elif cmd == "PASS":
if open(self.pass_path).read() == hashlib.md5(arg).hexdigest():
self.message(230, "Identified!")
self.identified = True
else:
self.message(530, "Not identified!")
self.identified = False
return
elif not self.identified:
self.message(530, "Please login with USER and PASS.")
return
self.alive_time = time.time()
finish = True
if cmd == "NOOP":
self.message(200, "ok")
elif cmd == "TYPE":
self.message(200, "Type set to "+arg[0])
elif cmd == "SYST":
self.message(200, "UNIX")
elif cmd == "EPSV" or cmd == "PASV":
self.option_pasv = True
try:
self.data_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.data_fd.bind((listen_ip, 0))
self.data_fd.listen(1)
ip, port = self.data_fd.getsockname()
if cmd == "EPSV":
self.message(229, "Entering Extended Passive Mode (|||" + str(port) + "|)")
else:
ipnum = socket.inet_aton(ip)
self.message(227, "Entering Passive Mode (%s,%u,%u)." %
(",".join(ip.split(".")), (port>>8&0xff), (port&0xff)))
except:
self.message(500, "failed to create data socket.")
elif cmd == "EPRT":
self.message(500, "implement EPRT later...")
elif cmd == "PORT":
self.option_pasv = False
self.data_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = arg.split(",")
self.data_ip = ".".join(s[:4])
self.data_port = int(s[4])*256 + int(s[5])
self.message(200, "ok")
elif cmd == "MFMT":
if arg !="":
print (arg[0])
self.message(213, "modify="+"; /deprecated.php")
elif cmd == "PWD" or cmd == "XPWD":
if self.curr_dir == "": self.curr_dir = "/"
self.message(257, '"''' + self.curr_dir + '"')
elif cmd == "LIST" or cmd == "NLST" or cmd == "MLST":
if arg != "" and arg[0] == "-": arg = "" # omit parameters
remote, local, perm, vdir_list, limit_size, is_virtual = self.parse_path(arg)
#print local
if not os.path.exists(local):
self.message(550, "failed.")
return
if not self.establish(): return
self.message(150, "ok")
for v in vdir_list:
f = v[0]
if self.option_utf8:
if sys.version_info < (3, 0):
f = unicode(f, sys.getfilesystemencoding()).encode("utf8")
if cmd == "NLST":
info = f + "\r\n"
else:
info = "d%s%s------- %04u %8s %8s %8lu %s %s\r\n" % (
"r" if "read" in perm else "-",
"w" if "write" in perm else "-",
1, "0", "0", 0,
time.strftime("%b %d %Y", time.localtime(time.time())),
f)
if sys.version_info < (3, 0):
self.data_fd.send(info)
else:
self.data_fd.send(info.encode())
for f in os.listdir(local):
if f[0] == ".": continue
path = local + "/" + f
if self.option_utf8:
if sys.version_info < (3, 0):
f = unicode(f, sys.getfilesystemencoding()).encode("utf8")
if cmd == "NLST":
info = f + "\r\n"
else:
st = os.stat(path)
filesize = 0
if os.path.isfile(path):
filesize = st[stat.ST_SIZE]
else:
filesize = self.getdirsize(path)
info = "%s%s%s------- %04u %8s %8s %8lu %s %s\r\n" % (
"-" if os.path.isfile(path) else "d",
"r" if "read" in perm else "-",
"w" if "write" in perm else "-",
1, "0", "0", filesize,
time.strftime("%b %d %Y", time.localtime(st[stat.ST_MTIME])),
f)
if sys.version_info < (3, 0):
self.data_fd.send(info)
else:
self.data_fd.send(info.encode())
self.message(226, "Limit size: " + str(limit_size))
self.data_fd.close()
self.data_fd = 0
elif cmd == "REST":
self.file_pos = int(arg)
self.message(250, "ok")
elif cmd == "FEAT":
features = "211-Features:\r\nSITES\r\nEPRT\r\nEPSV\r\nMDTM\r\nPASV\r\n"\
"REST STREAM\r\nSIZE\r\nUTF8\r\n211 End\r\n"
if sys.version_info < (3, 0):
self.fd.send(features)
else:
self.fd.send(features.encode())
elif cmd == "OPTS":
arg = arg.upper()
if arg == "UTF8 ON":
self.option_utf8 = True
self.message(200, "ok")
elif arg == "UTF8 OFF":
self.option_utf8 = False
self.message(200, "ok")
else:
self.message(500, "unrecognized option")
elif cmd == "CDUP":
finish = False
arg = ".."
cmd = "CWD"
else:
finish = False
if finish: return
# Parse argument ( It's a path )
if arg == "":
self.message(500, "where's my argument?")
return
if (cmd == "MDTM"):
arg2 = arg.split()
remote, local, permission, vdir_list, limit_size, is_virtual = \
self.parse_path(arg2[1])
else:
remote, local, permission, vdir_list, limit_size, is_virtual = \
self.parse_path(arg)
# can not do anything to virtual directory
if is_virtual: permission = "none"
can_read, can_write, can_modify = "read" in permission, "write" in permission, "modify" in permission
newpath = local
try:
if cmd == "CWD":
#print remote
print ("kyky",newpath);
if(os.path.isdir(newpath)):
self.curr_dir = remote
self.full_path = newpath
self.message(250, '"''"' + remote + '"')
else:
self.message(550, newpath)
elif cmd == "MDTM":
timeArray = time.strptime(arg2[0], "%Y%m%d%H%M%S")
timeStamp = int(time.mktime(timeArray))
#print timeArray.tm_year
if os.path.exists(newpath):
os.utime(newpath, (timeStamp,timeStamp))
self.message(213, time.strftime("%Y%m%d%I%M%S", time.localtime(
os.path.getmtime(newpath))))
else:
self.message(550, "failed")
elif cmd == "SIZE":
if (os.path.exists(newpath)):
self.message(231, os.path.getsize(newpath))
else:
self.message(231, 0)
elif cmd == "XMKD" or cmd == "MKD":
if not can_modify:
self.message(550, "permission denied.")
return
os.mkdir(newpath)
self.message(257, "created successfully")
elif cmd == "RNFR":
if not can_modify:
self.message(550, "permission denied.")
return
self.temp_path = newpath
self.message(350, "rename from " + remote)
elif cmd == "RNTO":
os.rename(self.temp_path, newpath)
self.message(250, "RNTO to " + remote)
elif cmd == "XRMD" or cmd == "RMD":
if not can_modify:
self.message(550, "permission denied.")
return
os.rmdir(newpath)
self.message(250, "ok")
elif cmd == "DELE":
if not can_modify:
self.message(550, "permission denied.")
return
os.remove(newpath)
self.message(250, "ok")
elif cmd == "RETR":
if not os.path.isfile(newpath):
self.message(550, "failed")
return
if not can_read:
self.message(550, "permission denied.")
return
if not self.establish(): return
self.message(150, "ok")
if self.file_pos >0:
with open(newpath, 'rb') as f:
f.seek(self.file_pos)
while True:
data = f.read(1024)
if data:
self.data_fd.send(data)
else:
break
f.close()
else:
f = open(newpath, "rb")
while self.running:
self.alive_time = time.time()
data = f.read(8192)
if len(data) == 0: break
self.data_fd.send(data)
f.close()
self.data_fd.close()
self.data_fd = 0
self.message(226, "ok")
elif cmd == "STOR" or cmd == "APPE":
if not can_write:
self.message(550, "permission denied.")
return
if os.path.exists(newpath) and not can_modify:
self.message(550, "permission denied.")
return
# Check space size remained!
used_size = 0
if limit_size > 0:
used_size = self.get_dir_size(os.path.dirname(newpath))
if not self.establish(): return
self.message(150, "Opening data channel for file upload to server of\"" + remote + " \"")
if os.path.exists(newpath) and self.file_pos > 0:
print ("kkkkk")
has_size = self.file_pos
with open(newpath, 'ab') as f:
f.seek(has_size)
while True:
data = self.data_fd.recv(1024)
if len(data) == 0: break
if limit_size > 0:
used_size = used_size + len(data)
if used_size > limit_size: break
f.write(data)
f.close()
else:
print ("qqqqq",self.file_pos)
f = open(newpath, "wb" )
while self.running:
self.alive_time = time.time()
data = self.data_fd.recv(8192)
if len(data) == 0: break
if limit_size > 0:
used_size = used_size + len(data)
if used_size > limit_size: break
f.write(data)
f.close()
self.data_fd.close()
self.data_fd = 0
self.file_pos = 0
if limit_size > 0 and used_size > limit_size:
self.message(550, "Exceeding user space limit: " + str(limit_size) + " bytes")
else:
self.message(226, "Successfully transferred \""+remote+"\"")
else:
self.message(500, cmd + " not implemented")
except BaseException as ex:
print (ex)
self.message(550, "failed.")
def establish(self):
if self.data_fd == 0:
self.message(500, "no data connection")
return False
if self.option_pasv:
fd = self.data_fd.accept()[0]
self.data_fd.close()
self.data_fd = fd
else:
try:
self.data_fd.connect((self.data_ip, self.data_port))
except:
self.message(500, "failed to establish data connection")
return False
return True
def getdirsize(self, dir):
size = 0
for root, dirs, files in os.walk(dir):
try:
size += sum([getsize(join(root, name)) for name in files])
except:
print ("error file")
return size
def read_virtual(self, path):
vdir_list = []
path = path + "/.xxftp/virtual"
if os.path.isfile(path):
for v in open(path, "r").readlines():
items = v.split()
items[1] = items[1].replace("$root", root_dir)
vdir_list.append(items)
return vdir_list
def get_dir_size(self, folder):
size = 0
folder = root_dir
for path, dirs, files in os.walk(folder):
for f in files:
size += os.path.getsize(os.path.join(path, f))
print (folder)
return size
def read_size(self, path):
size = 0
path = path + "/.xxftp/size"
if os.path.isfile(path):
size = int(open(path, "r").readline())
return size
def read_permission(self, path):
permission = "read,write,modify"
path = path + "/.xxftp/permission"
if os.path.isfile(path):
permission = open(path, "r").readline()
return permission
def parse_path(self, path):
path = path.replace("/\"", "")
if path == "": path = "."
if path[0] != "/":
path = self.curr_dir + "/" + path
s = os.path.normpath(path).replace("\\", "/").split("/")
local = self.home_dir
#print local
# reset directory permission
vdir_list = self.read_virtual(local)
limit_size = self.u_limit_size
permission = self.u_permission
remote = ""
is_virtual = False
for name in s:
name = name.lstrip(".")
if name == "": continue
remote = remote + "/" + name
is_virtual = False
for v in vdir_list:
if v[0] == name:
permission = v[2]
local = v[1]
limit_size = self.read_size(local)
is_virtual = True
if not is_virtual: local = local + "/" + name
#local = local.replace("/\"", "/")
vdir_list = self.read_virtual(local)
return (remote, local, permission, vdir_list, limit_size, is_virtual)
def run(self):
''''' Connection Process '''
#try:
if len(conn_list) > max_connections:
self.message(500, "too many connections!")
self.fd.close()
self.running = False
return
# Welcome Message
if os.path.exists(root_dir + "/xxftp.welcome"):
self.message(220, open(root_dir + "/xxftp.welcome").read())
else:
self.message(220, "xxftp(Python) www.xiaoxia.org")
# Command Loop
line = ""
while self.running:
data = 0
if sys.version_info < (3, 0):
data = self.fd.recv(4096)
else:
data = self.fd.recv(4096).decode()
if len(data) == 0: break
line += data
if line[-2:] != "\r\n": continue
line = line[:-2]
space = line.find(" ")
if space == -1:
self.process(line, "")
else:
self.process(line[:space], line[space+1:])
line = ""
#except:
#print ("error", sys.exc_info())
self.running = False
self.fd.close()
print ("connection end", self.fd, "user", self.username)
del self.fd
def message(self, code, s):
''''' Send Ftp Message '''
s = str(s).replace("\r", "")
ss = s.split("\n")
#r = ""
if len(ss) > 1:
r = (str(code) + "-") + ("\r\n" + str(code) + "-").join(ss[:-1])
r += "\r\n" + str(code) + " " + ss[-1] + "\r\n"
else:
r = str(code) + " " + ss[0] + "\r\n"
if self.option_utf8:
if sys.version_info < (3, 0):
r = unicode(r, sys.getfilesystemencoding()).encode("utf8")
if sys.version_info < (3, 0):
self.fd.send(r)
else:
self.fd.send(r.encode())
def server_listen():
global conn_list
listen_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_fd.bind((listen_ip, listen_port))
listen_fd.listen(1024)
conn_lock = threading.Lock()
print ("ftpd is listening on ", listen_ip + ":" + str(listen_port))
while True:
conn_fd, remote_addr = listen_fd.accept()
print ("connection from ", remote_addr, "conn_list", len(conn_list))
conn = FtpConnection(conn_fd)
conn.start()
conn_lock.acquire()
conn_list.append(conn)
# check timeout
try:
curr_time = time.time()
for conn in conn_list:
if int(curr_time - conn.alive_time) > conn_timeout:
if conn.running == True:
conn.fd.shutdown(socket.SHUT_RDWR)
conn.running = False
del conn
if conn.running == False:
del conn
conn_list = [conn for conn in conn_list if conn.running]
except:
print (sys.exc_info())
conn_lock.release()
def main():
server_listen()
if __name__ == "__main__":
main() | 34.156425 | 107 | 0.522735 |
import socket, threading, os, sys, time, datetime
import hashlib, platform, stat
from os.path import join, getsize
listen_ip = "0.0.0.0"
listen_port = 21
conn_list = []
root_dir = "C://Autodesk"
if sys.version_info < (3, 0):
root_dir = root_dir.decode('utf-8').encode('gb2312')
= 500
conn_timeout = 120
class FtpConnection(threading.Thread):
def __init__(self, fd):
threading.Thread.__init__(self)
self.fd = fd
self.running = True
self.setDaemon(True)
self.alive_time = time.time()
self.option_utf8 = False
self.identified = False
self.option_pasv = True
self.username = ""
self.file_pos = 0
self.u_username = "wmfy808"
self.u_passwd="123456"
self.u_limit_size=5*1024*1024*1024
self.u_permission = "read,write,modify"
def process(self, cmd, arg):
cmd = cmd.upper();
arg2 = []
if self.option_utf8:
if sys.version_info < (3, 0):
arg = unicode(arg, "utf8").encode(sys.getfilesystemencoding())
print ("<<", cmd, arg, self.fd)
if cmd == "BYE" or cmd == "QUIT":
if os.path.exists(root_dir + "/xxftp.goodbye"):
self.message(221, open(root_dir + "/xxftp.goodbye").read())
else:
self.message(221, "Bye!")
self.running = False
return
elif cmd == "USER":
if arg == "": arg = "anonymous"
for c in arg:
if not c.isalpha() and not c.isdigit() and c!="_":
self.message(530, "Incorrect username.")
return
self.username = arg
self.home_dir = root_dir
self.curr_dir = "/"
self.curr_dir, self.full_path, permission, self.vdir_list, \
limit_size, is_virtual = self.parse_path("/")
if not os.path.isdir(self.home_dir):
self.message(530, "path " + self.home_dir + " not exists.")
return
self.pass_path = self.home_dir + "/.xxftp/password"
if os.path.isfile(self.pass_path):
self.message(331, "Password required for " + self.username)
else:
self.message(230, "Identified!")
self.identified = True
return
elif cmd == "PASS":
if open(self.pass_path).read() == hashlib.md5(arg).hexdigest():
self.message(230, "Identified!")
self.identified = True
else:
self.message(530, "Not identified!")
self.identified = False
return
elif not self.identified:
self.message(530, "Please login with USER and PASS.")
return
self.alive_time = time.time()
finish = True
if cmd == "NOOP":
self.message(200, "ok")
elif cmd == "TYPE":
self.message(200, "Type set to "+arg[0])
elif cmd == "SYST":
self.message(200, "UNIX")
elif cmd == "EPSV" or cmd == "PASV":
self.option_pasv = True
try:
self.data_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.data_fd.bind((listen_ip, 0))
self.data_fd.listen(1)
ip, port = self.data_fd.getsockname()
if cmd == "EPSV":
self.message(229, "Entering Extended Passive Mode (|||" + str(port) + "|)")
else:
ipnum = socket.inet_aton(ip)
self.message(227, "Entering Passive Mode (%s,%u,%u)." %
(",".join(ip.split(".")), (port>>8&0xff), (port&0xff)))
except:
self.message(500, "failed to create data socket.")
elif cmd == "EPRT":
self.message(500, "implement EPRT later...")
elif cmd == "PORT":
self.option_pasv = False
self.data_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = arg.split(",")
self.data_ip = ".".join(s[:4])
self.data_port = int(s[4])*256 + int(s[5])
self.message(200, "ok")
elif cmd == "MFMT":
if arg !="":
print (arg[0])
self.message(213, "modify="+"; /deprecated.php")
elif cmd == "PWD" or cmd == "XPWD":
if self.curr_dir == "": self.curr_dir = "/"
self.message(257, '"''' + self.curr_dir + '"')
elif cmd == "LIST" or cmd == "NLST" or cmd == "MLST":
if arg != "" and arg[0] == "-": arg = "" # omit parameters
remote, local, perm, vdir_list, limit_size, is_virtual = self.parse_path(arg)
#print local
if not os.path.exists(local):
self.message(550, "failed.")
return
if not self.establish(): return
self.message(150, "ok")
for v in vdir_list:
f = v[0]
if self.option_utf8:
if sys.version_info < (3, 0):
f = unicode(f, sys.getfilesystemencoding()).encode("utf8")
if cmd == "NLST":
info = f + "\r\n"
else:
info = "d%s%s------- %04u %8s %8s %8lu %s %s\r\n" % (
"r" if "read" in perm else "-",
"w" if "write" in perm else "-",
1, "0", "0", 0,
time.strftime("%b %d %Y", time.localtime(time.time())),
f)
if sys.version_info < (3, 0):
self.data_fd.send(info)
else:
self.data_fd.send(info.encode())
for f in os.listdir(local):
if f[0] == ".": continue
path = local + "/" + f
if self.option_utf8:
if sys.version_info < (3, 0):
f = unicode(f, sys.getfilesystemencoding()).encode("utf8")
if cmd == "NLST":
info = f + "\r\n"
else:
st = os.stat(path)
filesize = 0
if os.path.isfile(path):
filesize = st[stat.ST_SIZE]
else:
filesize = self.getdirsize(path)
info = "%s%s%s------- %04u %8s %8s %8lu %s %s\r\n" % (
"-" if os.path.isfile(path) else "d",
"r" if "read" in perm else "-",
"w" if "write" in perm else "-",
1, "0", "0", filesize,
time.strftime("%b %d %Y", time.localtime(st[stat.ST_MTIME])),
f)
if sys.version_info < (3, 0):
self.data_fd.send(info)
else:
self.data_fd.send(info.encode())
self.message(226, "Limit size: " + str(limit_size))
self.data_fd.close()
self.data_fd = 0
elif cmd == "REST":
self.file_pos = int(arg)
self.message(250, "ok")
elif cmd == "FEAT":
features = "211-Features:\r\nSITES\r\nEPRT\r\nEPSV\r\nMDTM\r\nPASV\r\n"\
"REST STREAM\r\nSIZE\r\nUTF8\r\n211 End\r\n"
if sys.version_info < (3, 0):
self.fd.send(features)
else:
self.fd.send(features.encode())
elif cmd == "OPTS":
arg = arg.upper()
if arg == "UTF8 ON":
self.option_utf8 = True
self.message(200, "ok")
elif arg == "UTF8 OFF":
self.option_utf8 = False
self.message(200, "ok")
else:
self.message(500, "unrecognized option")
elif cmd == "CDUP":
finish = False
arg = ".."
cmd = "CWD"
else:
finish = False
if finish: return
# Parse argument ( It's a path )
if arg == "":
self.message(500, "where's my argument?")
return
if (cmd == "MDTM"):
arg2 = arg.split()
remote, local, permission, vdir_list, limit_size, is_virtual = \
self.parse_path(arg2[1])
else:
remote, local, permission, vdir_list, limit_size, is_virtual = \
self.parse_path(arg)
# can not do anything to virtual directory
if is_virtual: permission = "none"
can_read, can_write, can_modify = "read" in permission, "write" in permission, "modify" in permission
newpath = local
try:
if cmd == "CWD":
#print remote
print ("kyky",newpath);
if(os.path.isdir(newpath)):
self.curr_dir = remote
self.full_path = newpath
self.message(250, '"''"' + remote + '"')
else:
self.message(550, newpath)
elif cmd == "MDTM":
timeArray = time.strptime(arg2[0], "%Y%m%d%H%M%S")
timeStamp = int(time.mktime(timeArray))
#print timeArray.tm_year
if os.path.exists(newpath):
os.utime(newpath, (timeStamp,timeStamp))
self.message(213, time.strftime("%Y%m%d%I%M%S", time.localtime(
os.path.getmtime(newpath))))
else:
self.message(550, "failed")
elif cmd == "SIZE":
if (os.path.exists(newpath)):
self.message(231, os.path.getsize(newpath))
else:
self.message(231, 0)
elif cmd == "XMKD" or cmd == "MKD":
if not can_modify:
self.message(550, "permission denied.")
return
os.mkdir(newpath)
self.message(257, "created successfully")
elif cmd == "RNFR":
if not can_modify:
self.message(550, "permission denied.")
return
self.temp_path = newpath
self.message(350, "rename from " + remote)
elif cmd == "RNTO":
os.rename(self.temp_path, newpath)
self.message(250, "RNTO to " + remote)
elif cmd == "XRMD" or cmd == "RMD":
if not can_modify:
self.message(550, "permission denied.")
return
os.rmdir(newpath)
self.message(250, "ok")
elif cmd == "DELE":
if not can_modify:
self.message(550, "permission denied.")
return
os.remove(newpath)
self.message(250, "ok")
elif cmd == "RETR":
if not os.path.isfile(newpath):
self.message(550, "failed")
return
if not can_read:
self.message(550, "permission denied.")
return
if not self.establish(): return
self.message(150, "ok")
if self.file_pos >0:
with open(newpath, 'rb') as f:
f.seek(self.file_pos)
while True:
data = f.read(1024)
if data:
self.data_fd.send(data)
else:
break
f.close()
else:
f = open(newpath, "rb")
while self.running:
self.alive_time = time.time()
data = f.read(8192)
if len(data) == 0: break
self.data_fd.send(data)
f.close()
self.data_fd.close()
self.data_fd = 0
self.message(226, "ok")
elif cmd == "STOR" or cmd == "APPE":
if not can_write:
self.message(550, "permission denied.")
return
if os.path.exists(newpath) and not can_modify:
self.message(550, "permission denied.")
return
# Check space size remained!
used_size = 0
if limit_size > 0:
used_size = self.get_dir_size(os.path.dirname(newpath))
if not self.establish(): return
self.message(150, "Opening data channel for file upload to server of\"" + remote + " \"")
if os.path.exists(newpath) and self.file_pos > 0:
print ("kkkkk")
has_size = self.file_pos
with open(newpath, 'ab') as f:
f.seek(has_size)
while True:
data = self.data_fd.recv(1024)
if len(data) == 0: break
if limit_size > 0:
used_size = used_size + len(data)
if used_size > limit_size: break
f.write(data)
f.close()
else:
print ("qqqqq",self.file_pos)
f = open(newpath, "wb" )
while self.running:
self.alive_time = time.time()
data = self.data_fd.recv(8192)
if len(data) == 0: break
if limit_size > 0:
used_size = used_size + len(data)
if used_size > limit_size: break
f.write(data)
f.close()
self.data_fd.close()
self.data_fd = 0
self.file_pos = 0
if limit_size > 0 and used_size > limit_size:
self.message(550, "Exceeding user space limit: " + str(limit_size) + " bytes")
else:
self.message(226, "Successfully transferred \""+remote+"\"")
else:
self.message(500, cmd + " not implemented")
except BaseException as ex:
print (ex)
self.message(550, "failed.")
def establish(self):
if self.data_fd == 0:
self.message(500, "no data connection")
return False
if self.option_pasv:
fd = self.data_fd.accept()[0]
self.data_fd.close()
self.data_fd = fd
else:
try:
self.data_fd.connect((self.data_ip, self.data_port))
except:
self.message(500, "failed to establish data connection")
return False
return True
def getdirsize(self, dir):
size = 0
for root, dirs, files in os.walk(dir):
try:
size += sum([getsize(join(root, name)) for name in files])
except:
print ("error file")
return size
def read_virtual(self, path):
vdir_list = []
path = path + "/.xxftp/virtual"
if os.path.isfile(path):
for v in open(path, "r").readlines():
items = v.split()
items[1] = items[1].replace("$root", root_dir)
vdir_list.append(items)
return vdir_list
def get_dir_size(self, folder):
size = 0
folder = root_dir
for path, dirs, files in os.walk(folder):
for f in files:
size += os.path.getsize(os.path.join(path, f))
print (folder)
return size
def read_size(self, path):
size = 0
path = path + "/.xxftp/size"
if os.path.isfile(path):
size = int(open(path, "r").readline())
return size
def read_permission(self, path):
permission = "read,write,modify"
path = path + "/.xxftp/permission"
if os.path.isfile(path):
permission = open(path, "r").readline()
return permission
def parse_path(self, path):
path = path.replace("/\"", "")
if path == "": path = "."
if path[0] != "/":
path = self.curr_dir + "/" + path
s = os.path.normpath(path).replace("\\", "/").split("/")
local = self.home_dir
#print local
# reset directory permission
vdir_list = self.read_virtual(local)
limit_size = self.u_limit_size
permission = self.u_permission
remote = ""
is_virtual = False
for name in s:
name = name.lstrip(".")
if name == "": continue
remote = remote + "/" + name
is_virtual = False
for v in vdir_list:
if v[0] == name:
permission = v[2]
local = v[1]
limit_size = self.read_size(local)
is_virtual = True
if not is_virtual: local = local + "/" + name
#local = local.replace("/\"", "/")
vdir_list = self.read_virtual(local)
return (remote, local, permission, vdir_list, limit_size, is_virtual)
def run(self):
#try:
if len(conn_list) > max_connections:
self.message(500, "too many connections!")
self.fd.close()
self.running = False
return
# Welcome Message
if os.path.exists(root_dir + "/xxftp.welcome"):
self.message(220, open(root_dir + "/xxftp.welcome").read())
else:
self.message(220, "xxftp(Python) www.xiaoxia.org")
# Command Loop
line = ""
while self.running:
data = 0
if sys.version_info < (3, 0):
data = self.fd.recv(4096)
else:
data = self.fd.recv(4096).decode()
if len(data) == 0: break
line += data
if line[-2:] != "\r\n": continue
line = line[:-2]
space = line.find(" ")
if space == -1:
self.process(line, "")
else:
self.process(line[:space], line[space+1:])
line = ""
#except:
#print ("error", sys.exc_info())
self.running = False
self.fd.close()
print ("connection end", self.fd, "user", self.username)
del self.fd
def message(self, code, s):
s = str(s).replace("\r", "")
ss = s.split("\n")
#r = ""
if len(ss) > 1:
r = (str(code) + "-") + ("\r\n" + str(code) + "-").join(ss[:-1])
r += "\r\n" + str(code) + " " + ss[-1] + "\r\n"
else:
r = str(code) + " " + ss[0] + "\r\n"
if self.option_utf8:
if sys.version_info < (3, 0):
r = unicode(r, sys.getfilesystemencoding()).encode("utf8")
if sys.version_info < (3, 0):
self.fd.send(r)
else:
self.fd.send(r.encode())
def server_listen():
global conn_list
listen_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_fd.bind((listen_ip, listen_port))
listen_fd.listen(1024)
conn_lock = threading.Lock()
print ("ftpd is listening on ", listen_ip + ":" + str(listen_port))
while True:
conn_fd, remote_addr = listen_fd.accept()
print ("connection from ", remote_addr, "conn_list", len(conn_list))
conn = FtpConnection(conn_fd)
conn.start()
conn_lock.acquire()
conn_list.append(conn)
# check timeout
try:
curr_time = time.time()
for conn in conn_list:
if int(curr_time - conn.alive_time) > conn_timeout:
if conn.running == True:
conn.fd.shutdown(socket.SHUT_RDWR)
conn.running = False
del conn
if conn.running == False:
del conn
conn_list = [conn for conn in conn_list if conn.running]
except:
print (sys.exc_info())
conn_lock.release()
def main():
server_listen()
if __name__ == "__main__":
main() | true | true |
f7f6cf472459aa536ed7e9c4a984ef860a11181b | 888 | py | Python | django_quote_service/users/tests/test_urls.py | andrlik/django_quote_service | c114537789523db88fe68f75f4de8c29b2b90bd9 | [
"BSD-3-Clause"
] | 1 | 2022-02-13T02:25:23.000Z | 2022-02-13T02:25:23.000Z | django_quote_service/users/tests/test_urls.py | andrlik/django_quote_service | c114537789523db88fe68f75f4de8c29b2b90bd9 | [
"BSD-3-Clause"
] | 38 | 2022-02-09T22:37:46.000Z | 2022-03-28T15:28:05.000Z | django_quote_service/users/tests/test_urls.py | andrlik/django_quote_service | c114537789523db88fe68f75f4de8c29b2b90bd9 | [
"BSD-3-Clause"
] | null | null | null | import pytest
from django.urls import resolve, reverse
pytestmark = pytest.mark.django_db
def test_detail(user, client):
assert (
reverse("users:detail", kwargs={"username": user.username})
== f"/users/{user.username}/"
)
assert resolve(f"/users/{user.username}/").view_name == "users:detail"
client.force_login(user=user)
r = client.get(reverse("users:detail", kwargs={"username": user.username}))
assert r.status_code == 200
def test_update(client, user):
assert reverse("users:update") == "/users/~update/"
assert resolve("/users/~update/").view_name == "users:update"
client.force_login(user=user)
r = client.get(reverse("users:update"))
assert r.status_code == 200
def test_redirect():
assert reverse("users:redirect") == "/users/~redirect/"
assert resolve("/users/~redirect/").view_name == "users:redirect"
| 30.62069 | 79 | 0.673423 | import pytest
from django.urls import resolve, reverse
pytestmark = pytest.mark.django_db
def test_detail(user, client):
assert (
reverse("users:detail", kwargs={"username": user.username})
== f"/users/{user.username}/"
)
assert resolve(f"/users/{user.username}/").view_name == "users:detail"
client.force_login(user=user)
r = client.get(reverse("users:detail", kwargs={"username": user.username}))
assert r.status_code == 200
def test_update(client, user):
assert reverse("users:update") == "/users/~update/"
assert resolve("/users/~update/").view_name == "users:update"
client.force_login(user=user)
r = client.get(reverse("users:update"))
assert r.status_code == 200
def test_redirect():
assert reverse("users:redirect") == "/users/~redirect/"
assert resolve("/users/~redirect/").view_name == "users:redirect"
| true | true |
f7f6d2eac0f1fd225391459eed084fb49ff92141 | 1,785 | py | Python | profiles_api/migrations/0001_initial.py | preacher2041/mythmaker-api | cb7025ac6f171b48457655e7087731142ecc5ab9 | [
"MIT"
] | null | null | null | profiles_api/migrations/0001_initial.py | preacher2041/mythmaker-api | cb7025ac6f171b48457655e7087731142ecc5ab9 | [
"MIT"
] | null | null | null | profiles_api/migrations/0001_initial.py | preacher2041/mythmaker-api | cb7025ac6f171b48457655e7087731142ecc5ab9 | [
"MIT"
] | null | null | null | # Generated by Django 2.2 on 2022-03-14 10:59
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(max_length=50, unique=True)),
('email', models.EmailField(max_length=255, unique=True)),
('first_name', models.CharField(max_length=50)),
('last_name', models.CharField(max_length=50)),
('is_active', models.BooleanField(default=True)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
| 51 | 266 | 0.637535 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(max_length=50, unique=True)),
('email', models.EmailField(max_length=255, unique=True)),
('first_name', models.CharField(max_length=50)),
('last_name', models.CharField(max_length=50)),
('is_active', models.BooleanField(default=True)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
| true | true |
f7f6d37b92d625b023b0779d675637286e39833e | 345 | py | Python | flask/app/utils.py | sreejeet/ams-api | c8df3a550734fcf5796197dc2016630e7f218754 | [
"MIT"
] | 3 | 2019-06-08T07:13:03.000Z | 2019-06-09T08:02:52.000Z | flask/app/utils.py | sreejeet/ams-api | c8df3a550734fcf5796197dc2016630e7f218754 | [
"MIT"
] | null | null | null | flask/app/utils.py | sreejeet/ams-api | c8df3a550734fcf5796197dc2016630e7f218754 | [
"MIT"
] | null | null | null | import re
import datetime
def convertToDate(date:str):
return datetime.datetime.strptime(date, '%Y-%m-%d')
def convertFromDate(date:datetime.date):
return date.strftime('%Y-%m-%d')
def checkBatch(batch:str):
if re.match('\d\d\d\d[-]\d\d\d\d',batch):
return batch
raise ValueError('Invalid batch. Use format YYYY-YYYY') | 26.538462 | 59 | 0.681159 | import re
import datetime
def convertToDate(date:str):
return datetime.datetime.strptime(date, '%Y-%m-%d')
def convertFromDate(date:datetime.date):
return date.strftime('%Y-%m-%d')
def checkBatch(batch:str):
if re.match('\d\d\d\d[-]\d\d\d\d',batch):
return batch
raise ValueError('Invalid batch. Use format YYYY-YYYY') | true | true |
f7f6d42a446f9f5dcac9e420e7d213d987dd69c2 | 807 | py | Python | tests/core.py | myusuf3/octogit | 4eebd844e44c4b8da3f49bac0e70fc12375c2f94 | [
"MIT"
] | 41 | 2015-02-17T22:48:59.000Z | 2021-10-17T14:15:29.000Z | tests/core.py | myusuf3/octogit | 4eebd844e44c4b8da3f49bac0e70fc12375c2f94 | [
"MIT"
] | 7 | 2017-03-02T09:02:21.000Z | 2018-10-24T18:59:03.000Z | tests/core.py | myusuf3/octogit | 4eebd844e44c4b8da3f49bac0e70fc12375c2f94 | [
"MIT"
] | 9 | 2015-06-09T17:00:15.000Z | 2018-10-03T04:38:16.000Z | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
import unittest
from octogit.core import get_single_issue
class UTF8Support(unittest.TestCase):
def assertNotRaises(self, exception_type, called_func, kwargs):
try:
called_func(**kwargs)
except Exception as e:
if isinstance(e, exception_type):
self.fail(e)
else:
pass
def test_assert_not_raises_UnicodeEncodeError(self):
self.assertNotRaises(UnicodeEncodeError, get_single_issue,
kwargs={'user':'cesarFrias', 'repo':'pomodoro4linux',
'number':2})
if __name__ == '__main__':
unittest.main()
| 26.9 | 79 | 0.664188 |
import unittest
from octogit.core import get_single_issue
class UTF8Support(unittest.TestCase):
def assertNotRaises(self, exception_type, called_func, kwargs):
try:
called_func(**kwargs)
except Exception as e:
if isinstance(e, exception_type):
self.fail(e)
else:
pass
def test_assert_not_raises_UnicodeEncodeError(self):
self.assertNotRaises(UnicodeEncodeError, get_single_issue,
kwargs={'user':'cesarFrias', 'repo':'pomodoro4linux',
'number':2})
if __name__ == '__main__':
unittest.main()
| true | true |
f7f6d457253fd2e89e3664981e2246817a4f2804 | 5,467 | py | Python | squidpy/im/_process.py | marcovarrone/squidpy | fb68a913db0e0daaabeab69df308461ecaba1268 | [
"BSD-3-Clause"
] | 1 | 2021-07-27T07:01:00.000Z | 2021-07-27T07:01:00.000Z | squidpy/im/_process.py | marcovarrone/squidpy | fb68a913db0e0daaabeab69df308461ecaba1268 | [
"BSD-3-Clause"
] | null | null | null | squidpy/im/_process.py | marcovarrone/squidpy | fb68a913db0e0daaabeab69df308461ecaba1268 | [
"BSD-3-Clause"
] | null | null | null | from types import MappingProxyType
from typing import Any, Union, Mapping, Callable, Optional, Sequence
from scanpy import logging as logg
from dask import delayed
from scipy.ndimage.filters import gaussian_filter as scipy_gf
import numpy as np
import dask.array as da
from skimage.color import rgb2gray
from skimage.util.dtype import img_as_float32
from dask_image.ndfilters import gaussian_filter as dask_gf
from squidpy._docs import d, inject_docs
from squidpy.im._container import ImageContainer
from squidpy._constants._constants import Processing
from squidpy._constants._pkg_constants import Key
__all__ = ["process"]
def to_grayscale(img: Union[np.ndarray, da.Array]) -> Union[np.ndarray, da.Array]:
if img.shape[-1] != 3:
raise ValueError(f"Expected channel dimension to be `3`, found `{img.shape[-1]}`.")
if isinstance(img, da.Array):
img = da.from_delayed(delayed(img_as_float32)(img), shape=img.shape, dtype=np.float32)
coeffs = np.array([0.2125, 0.7154, 0.0721], dtype=img.dtype)
return img @ coeffs
return rgb2gray(img)
@d.dedent
@inject_docs(p=Processing)
def process(
img: ImageContainer,
layer: Optional[str] = None,
library_id: Optional[Union[str, Sequence[str]]] = None,
method: Union[str, Callable[..., np.ndarray]] = "smooth",
chunks: Optional[int] = None,
lazy: bool = False,
layer_added: Optional[str] = None,
channel_dim: Optional[str] = None,
copy: bool = False,
apply_kwargs: Mapping[str, Any] = MappingProxyType({}),
**kwargs: Any,
) -> Optional[ImageContainer]:
"""
Process an image by applying a transformation.
Parameters
----------
%(img_container)s
%(img_layer)s
%(library_id)s
If `None`, all Z-dimensions are processed at once, treating the image as a 3D volume.
method
Processing method to use. Valid options are:
- `{p.SMOOTH.s!r}` - :func:`skimage.filters.gaussian`.
- `{p.GRAY.s!r}` - :func:`skimage.color.rgb2gray`.
%(custom_fn)s
%(chunks_lazy)s
%(layer_added)s
If `None`, use ``'{{layer}}_{{method}}'``.
channel_dim
Name of the channel dimension of the new image layer. Default is the same as the original, if the
processing function does not change the number of channels, and ``'{{channel}}_{{processing}}'`` otherwise.
%(copy_cont)s
apply_kwargs
Keyword arguments for :meth:`squidpy.im.ImageContainer.apply`.
kwargs
Keyword arguments for ``method``.
Returns
-------
If ``copy = True``, returns a new container with the processed image in ``'{{layer_added}}'``.
Otherwise, modifies the ``img`` with the following key:
- :class:`squidpy.im.ImageContainer` ``['{{layer_added}}']`` - the processed image.
Raises
------
NotImplementedError
If ``method`` has not been implemented.
"""
layer = img._get_layer(layer)
method = Processing(method) if isinstance(method, (str, Processing)) else method # type: ignore[assignment]
apply_kwargs = dict(apply_kwargs)
apply_kwargs["lazy"] = lazy
if channel_dim is None:
channel_dim = img[layer].dims[-1]
layer_new = Key.img.process(method, layer, layer_added=layer_added)
if callable(method):
callback = method
elif method == Processing.SMOOTH: # type: ignore[comparison-overlap]
if library_id is None:
expected_ndim = 4
kwargs.setdefault("sigma", [1, 1, 0, 0]) # y, x, z, c
else:
expected_ndim = 3
kwargs.setdefault("sigma", [1, 1, 0]) # y, x, c
sigma = kwargs["sigma"]
if isinstance(sigma, int):
kwargs["sigma"] = sigma = [sigma, sigma] + [0] * (expected_ndim - 2)
if len(sigma) != expected_ndim:
raise ValueError(f"Expected `sigma` to be of length `{expected_ndim}`, found `{len(sigma)}`.")
if chunks is not None:
# dask_image already handles map_overlap
chunks_, chunks = chunks, None
callback = lambda arr, **kwargs: dask_gf(da.asarray(arr).rechunk(chunks_), **kwargs) # noqa: E731
else:
callback = scipy_gf
elif method == Processing.GRAY: # type: ignore[comparison-overlap]
apply_kwargs["drop_axis"] = 3
callback = to_grayscale
else:
raise NotImplementedError(f"Method `{method}` is not yet implemented.")
# to which library_ids should this function be applied?
if library_id is not None:
callback = {lid: callback for lid in img._get_library_ids(library_id)} # type: ignore[assignment]
start = logg.info(f"Processing image using `{method}` method")
res: ImageContainer = img.apply(
callback, layer=layer, copy=True, drop=copy, chunks=chunks, fn_kwargs=kwargs, **apply_kwargs
)
# if the method changes the number of channels
if res[layer].shape[-1] != img[layer].shape[-1]:
modifier = "_".join(layer_new.split("_")[1:]) if layer_added is None else layer_added
channel_dim = f"{channel_dim}_{modifier}"
res._data = res.data.rename({res[layer].dims[-1]: channel_dim})
logg.info("Finish", time=start)
if copy:
return res.rename(layer, layer_new)
img.add_img(
img=res[layer],
layer=layer_new,
copy=False,
lazy=lazy,
dims=res[layer].dims,
library_id=img[layer].coords["z"].values,
)
| 34.821656 | 115 | 0.645875 | from types import MappingProxyType
from typing import Any, Union, Mapping, Callable, Optional, Sequence
from scanpy import logging as logg
from dask import delayed
from scipy.ndimage.filters import gaussian_filter as scipy_gf
import numpy as np
import dask.array as da
from skimage.color import rgb2gray
from skimage.util.dtype import img_as_float32
from dask_image.ndfilters import gaussian_filter as dask_gf
from squidpy._docs import d, inject_docs
from squidpy.im._container import ImageContainer
from squidpy._constants._constants import Processing
from squidpy._constants._pkg_constants import Key
__all__ = ["process"]
def to_grayscale(img: Union[np.ndarray, da.Array]) -> Union[np.ndarray, da.Array]:
if img.shape[-1] != 3:
raise ValueError(f"Expected channel dimension to be `3`, found `{img.shape[-1]}`.")
if isinstance(img, da.Array):
img = da.from_delayed(delayed(img_as_float32)(img), shape=img.shape, dtype=np.float32)
coeffs = np.array([0.2125, 0.7154, 0.0721], dtype=img.dtype)
return img @ coeffs
return rgb2gray(img)
@d.dedent
@inject_docs(p=Processing)
def process(
img: ImageContainer,
layer: Optional[str] = None,
library_id: Optional[Union[str, Sequence[str]]] = None,
method: Union[str, Callable[..., np.ndarray]] = "smooth",
chunks: Optional[int] = None,
lazy: bool = False,
layer_added: Optional[str] = None,
channel_dim: Optional[str] = None,
copy: bool = False,
apply_kwargs: Mapping[str, Any] = MappingProxyType({}),
**kwargs: Any,
) -> Optional[ImageContainer]:
layer = img._get_layer(layer)
method = Processing(method) if isinstance(method, (str, Processing)) else method
apply_kwargs = dict(apply_kwargs)
apply_kwargs["lazy"] = lazy
if channel_dim is None:
channel_dim = img[layer].dims[-1]
layer_new = Key.img.process(method, layer, layer_added=layer_added)
if callable(method):
callback = method
elif method == Processing.SMOOTH:
if library_id is None:
expected_ndim = 4
kwargs.setdefault("sigma", [1, 1, 0, 0])
else:
expected_ndim = 3
kwargs.setdefault("sigma", [1, 1, 0])
sigma = kwargs["sigma"]
if isinstance(sigma, int):
kwargs["sigma"] = sigma = [sigma, sigma] + [0] * (expected_ndim - 2)
if len(sigma) != expected_ndim:
raise ValueError(f"Expected `sigma` to be of length `{expected_ndim}`, found `{len(sigma)}`.")
if chunks is not None:
chunks_, chunks = chunks, None
callback = lambda arr, **kwargs: dask_gf(da.asarray(arr).rechunk(chunks_), **kwargs)
else:
callback = scipy_gf
elif method == Processing.GRAY:
apply_kwargs["drop_axis"] = 3
callback = to_grayscale
else:
raise NotImplementedError(f"Method `{method}` is not yet implemented.")
if library_id is not None:
callback = {lid: callback for lid in img._get_library_ids(library_id)}
start = logg.info(f"Processing image using `{method}` method")
res: ImageContainer = img.apply(
callback, layer=layer, copy=True, drop=copy, chunks=chunks, fn_kwargs=kwargs, **apply_kwargs
)
if res[layer].shape[-1] != img[layer].shape[-1]:
modifier = "_".join(layer_new.split("_")[1:]) if layer_added is None else layer_added
channel_dim = f"{channel_dim}_{modifier}"
res._data = res.data.rename({res[layer].dims[-1]: channel_dim})
logg.info("Finish", time=start)
if copy:
return res.rename(layer, layer_new)
img.add_img(
img=res[layer],
layer=layer_new,
copy=False,
lazy=lazy,
dims=res[layer].dims,
library_id=img[layer].coords["z"].values,
)
| true | true |
f7f6d55b30743e7f725f4ec15b9157b07eb682ad | 2,812 | py | Python | knoepfe/key.py | lnqs/knoepfe | 0136775e23536e95d49efc5a21806f83a490c45f | [
"Apache-2.0"
] | null | null | null | knoepfe/key.py | lnqs/knoepfe | 0136775e23536e95d49efc5a21806f83a490c45f | [
"Apache-2.0"
] | null | null | null | knoepfe/key.py | lnqs/knoepfe | 0136775e23536e95d49efc5a21806f83a490c45f | [
"Apache-2.0"
] | null | null | null | from contextlib import contextmanager
from pathlib import Path
from typing import Iterator, Literal, Tuple
from PIL import Image, ImageDraw, ImageFont
from PIL.ImageFont import FreeTypeFont
from StreamDeck.Devices import StreamDeck
from StreamDeck.ImageHelpers import PILHelper
Align = Literal["left", "center", "right"]
VAlign = Literal["top", "middle", "bottom"]
ICONS = dict(
line.split(" ")
for line in Path(__file__)
.parent.joinpath("MaterialIcons-Regular.codepoints")
.read_text()
.split("\n")
if line
)
class Renderer:
def __init__(self) -> None:
self.image = Image.new("RGB", (96, 96))
def text(self, text: str, size: int = 24, color: str | None = None) -> "Renderer":
return self._render_text("text", text, size, color)
def icon(self, text: str, color: str | None = None) -> "Renderer":
return self._render_text("icon", text, 86, color)
def icon_and_text(
self, icon: str, text: str, color: str | None = None
) -> "Renderer":
self._render_text("icon", icon, 86, color, "top")
self._render_text("text", text, 16, color, "bottom")
return self
def _render_text(
self,
type: Literal["text", "icon"],
text: str,
size: int,
color: str | None,
valign: VAlign = "middle",
) -> "Renderer":
font = self._get_font(type, size)
draw = ImageDraw.Draw(self.image)
text_width, text_height = draw.textsize(text, font=font)
x, y = self._aligned(text_width, text_height, "center", valign)
draw.text((x, y), text=text, font=font, fill=color, align="center")
return self
def _aligned(self, w: int, h: int, align: Align, valign: VAlign) -> Tuple[int, int]:
x, y = 0, 0
if align == "center":
x = self.image.width // 2 - w // 2
elif align == "right":
x = self.image.width - w
if valign == "middle":
y = self.image.height // 2 - h // 2
elif valign == "bottom":
y = self.image.height - h - 6
return x, y
def _get_font(self, type: Literal["text", "icon"], size: int) -> FreeTypeFont:
font_file = (
"Roboto-Regular.ttf" if type == "text" else "MaterialIcons-Regular.ttf"
)
font_path = Path(__file__).parent.joinpath(font_file)
return ImageFont.truetype(str(font_path), size)
class Key:
def __init__(self, device: StreamDeck, index: int) -> None:
self.device = device
self.index = index
@contextmanager
def renderer(self) -> Iterator[Renderer]:
r = Renderer()
yield r
image = PILHelper.to_native_format(self.device, r.image)
with self.device:
self.device.set_key_image(self.index, image)
| 30.565217 | 88 | 0.598862 | from contextlib import contextmanager
from pathlib import Path
from typing import Iterator, Literal, Tuple
from PIL import Image, ImageDraw, ImageFont
from PIL.ImageFont import FreeTypeFont
from StreamDeck.Devices import StreamDeck
from StreamDeck.ImageHelpers import PILHelper
Align = Literal["left", "center", "right"]
VAlign = Literal["top", "middle", "bottom"]
ICONS = dict(
line.split(" ")
for line in Path(__file__)
.parent.joinpath("MaterialIcons-Regular.codepoints")
.read_text()
.split("\n")
if line
)
class Renderer:
def __init__(self) -> None:
self.image = Image.new("RGB", (96, 96))
def text(self, text: str, size: int = 24, color: str | None = None) -> "Renderer":
return self._render_text("text", text, size, color)
def icon(self, text: str, color: str | None = None) -> "Renderer":
return self._render_text("icon", text, 86, color)
def icon_and_text(
self, icon: str, text: str, color: str | None = None
) -> "Renderer":
self._render_text("icon", icon, 86, color, "top")
self._render_text("text", text, 16, color, "bottom")
return self
def _render_text(
self,
type: Literal["text", "icon"],
text: str,
size: int,
color: str | None,
valign: VAlign = "middle",
) -> "Renderer":
font = self._get_font(type, size)
draw = ImageDraw.Draw(self.image)
text_width, text_height = draw.textsize(text, font=font)
x, y = self._aligned(text_width, text_height, "center", valign)
draw.text((x, y), text=text, font=font, fill=color, align="center")
return self
def _aligned(self, w: int, h: int, align: Align, valign: VAlign) -> Tuple[int, int]:
x, y = 0, 0
if align == "center":
x = self.image.width // 2 - w // 2
elif align == "right":
x = self.image.width - w
if valign == "middle":
y = self.image.height // 2 - h // 2
elif valign == "bottom":
y = self.image.height - h - 6
return x, y
def _get_font(self, type: Literal["text", "icon"], size: int) -> FreeTypeFont:
font_file = (
"Roboto-Regular.ttf" if type == "text" else "MaterialIcons-Regular.ttf"
)
font_path = Path(__file__).parent.joinpath(font_file)
return ImageFont.truetype(str(font_path), size)
class Key:
def __init__(self, device: StreamDeck, index: int) -> None:
self.device = device
self.index = index
@contextmanager
def renderer(self) -> Iterator[Renderer]:
r = Renderer()
yield r
image = PILHelper.to_native_format(self.device, r.image)
with self.device:
self.device.set_key_image(self.index, image)
| true | true |
f7f6d5e3d840a89de5a37387e28c31f1b32c67db | 2,575 | py | Python | var/spack/repos/builtin/packages/mrcpp/package.py | MiddelkoopT/spack | 4d94c4c4600f42a7a3bb3d06ec879140bc259304 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 9 | 2018-04-18T07:51:40.000Z | 2021-09-10T03:56:57.000Z | var/spack/repos/builtin/packages/mrcpp/package.py | abouteiller/spack | 95f54195021d3d32dec75bed6d8dbbaeac3d921f | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 907 | 2018-04-18T11:17:57.000Z | 2022-03-31T13:20:25.000Z | var/spack/repos/builtin/packages/mrcpp/package.py | abouteiller/spack | 95f54195021d3d32dec75bed6d8dbbaeac3d921f | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 29 | 2018-11-05T16:14:23.000Z | 2022-02-03T16:07:09.000Z | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Mrcpp(CMakePackage):
"""The MultiResolution Computation Program Package (MRCPP) is a general purpose
numerical mathematics library based on multiresolution analysis and the
multiwavelet basis which provide low-scaling algorithms as well as rigorous
error control in numerical computations."""
homepage = "https://mrcpp.readthedocs.io/en/latest/"
url = "https://github.com/MRChemSoft/mrcpp/archive/v1.3.6.tar.gz"
maintainers = ["robertodr", "stigrj", "ilfreddy"]
version('1.3.6',
sha256='2502e71f086a8bb5ea635d0c6b86e7ff60220a45583e96a08b3cfe7c9db4cecf')
version('1.3.5',
sha256='3072cf60db6fa1e621bc6e6dfb6d35f9367a44d9d312a4b8c455894769140aed')
version('1.3.4',
sha256='fe6d1ad5804f605c7ba0da6831a8dc7fed72de6f2476b162961038aaa2321656')
version('1.3.3',
sha256='78c43161d0a4deffaf5d199e77535f6acbd88cc718ebc342d6ec9d72165c243e')
version('1.3.2',
sha256='61ffdfa36af37168090ba9d85550ca4072eb11ebfe3613da32e9c462351c9813')
version('1.3.1',
sha256='6ab05bc760c5d4f3f2925c87a0db8eab3417d959c747b27bac7a2fe5d3d6f7d1')
version('1.3.0',
sha256='74122ec2f2399472381df31f77ce0decbadd9d2f76e2aef6b07c815cc319ac52')
version('1.2.0',
sha256='faa6088ed20fb853bd0de4fe9cd578630d183f69e004601d4e464fe737e9f32d')
version('1.1.0',
sha256='e9ffb87eccbd45305f822a0b46b875788b70386b3c1d38add6540dc4e0327ab2')
version('1.0.2',
sha256='d2b26f7d7b16fa67f16788119abc0f6c7562cb37ece9ba075c116463dcf19df3')
version('1.0.1',
sha256='b4d7120545da3531bc7aa0a4cb4eb579fdbe1f8e5d32b1fd1086976583e3e27c')
version('1.0.0',
sha256='0858146141d3a60232e8874380390f9e9fa0b1bd6e67099d5833704478213efd')
variant("openmp", default=True, description="Enable OpenMP support.")
variant("mpi", default=True, description="Enable MPI support")
depends_on("mpi", when="+mpi")
depends_on("cmake@3.11:", type="build")
depends_on("eigen")
def cmake_args(self):
args = [
"-DENABLE_OPENMP={0}".format("ON" if "+openmp" in
self.spec else "OFF"),
"-DENABLE_MPI={0}".format("ON" if "+mpi" in self.spec else "OFF"),
"-DENABLE_TESTS=OFF",
]
return args
| 42.213115 | 86 | 0.699417 |
from spack import *
class Mrcpp(CMakePackage):
homepage = "https://mrcpp.readthedocs.io/en/latest/"
url = "https://github.com/MRChemSoft/mrcpp/archive/v1.3.6.tar.gz"
maintainers = ["robertodr", "stigrj", "ilfreddy"]
version('1.3.6',
sha256='2502e71f086a8bb5ea635d0c6b86e7ff60220a45583e96a08b3cfe7c9db4cecf')
version('1.3.5',
sha256='3072cf60db6fa1e621bc6e6dfb6d35f9367a44d9d312a4b8c455894769140aed')
version('1.3.4',
sha256='fe6d1ad5804f605c7ba0da6831a8dc7fed72de6f2476b162961038aaa2321656')
version('1.3.3',
sha256='78c43161d0a4deffaf5d199e77535f6acbd88cc718ebc342d6ec9d72165c243e')
version('1.3.2',
sha256='61ffdfa36af37168090ba9d85550ca4072eb11ebfe3613da32e9c462351c9813')
version('1.3.1',
sha256='6ab05bc760c5d4f3f2925c87a0db8eab3417d959c747b27bac7a2fe5d3d6f7d1')
version('1.3.0',
sha256='74122ec2f2399472381df31f77ce0decbadd9d2f76e2aef6b07c815cc319ac52')
version('1.2.0',
sha256='faa6088ed20fb853bd0de4fe9cd578630d183f69e004601d4e464fe737e9f32d')
version('1.1.0',
sha256='e9ffb87eccbd45305f822a0b46b875788b70386b3c1d38add6540dc4e0327ab2')
version('1.0.2',
sha256='d2b26f7d7b16fa67f16788119abc0f6c7562cb37ece9ba075c116463dcf19df3')
version('1.0.1',
sha256='b4d7120545da3531bc7aa0a4cb4eb579fdbe1f8e5d32b1fd1086976583e3e27c')
version('1.0.0',
sha256='0858146141d3a60232e8874380390f9e9fa0b1bd6e67099d5833704478213efd')
variant("openmp", default=True, description="Enable OpenMP support.")
variant("mpi", default=True, description="Enable MPI support")
depends_on("mpi", when="+mpi")
depends_on("cmake@3.11:", type="build")
depends_on("eigen")
def cmake_args(self):
args = [
"-DENABLE_OPENMP={0}".format("ON" if "+openmp" in
self.spec else "OFF"),
"-DENABLE_MPI={0}".format("ON" if "+mpi" in self.spec else "OFF"),
"-DENABLE_TESTS=OFF",
]
return args
| true | true |
f7f6d61310e547d67f40fd655c0777975ed2e29c | 366 | py | Python | admin_offices/migrations/0004_remove_adminoffice_job_title.py | SteveWaweru/mfl_api | 695001fb48cb1b15661cd480831ae33fe6374532 | [
"MIT"
] | null | null | null | admin_offices/migrations/0004_remove_adminoffice_job_title.py | SteveWaweru/mfl_api | 695001fb48cb1b15661cd480831ae33fe6374532 | [
"MIT"
] | null | null | null | admin_offices/migrations/0004_remove_adminoffice_job_title.py | SteveWaweru/mfl_api | 695001fb48cb1b15661cd480831ae33fe6374532 | [
"MIT"
] | 4 | 2017-09-04T09:04:35.000Z | 2022-02-14T23:59:28.000Z | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('admin_offices', '0003_auto_20160520_0757'),
]
operations = [
migrations.RemoveField(
model_name='adminoffice',
name='job_title',
),
]
| 19.263158 | 53 | 0.617486 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('admin_offices', '0003_auto_20160520_0757'),
]
operations = [
migrations.RemoveField(
model_name='adminoffice',
name='job_title',
),
]
| true | true |
f7f6d634755557a9833d700e4688d2d70a838e34 | 6,259 | py | Python | evmscript_parser/core/ABI/provider.py | DmitIv/EVMScriptParser | 2a565cffb9cd890b9ded1978727364270150a72a | [
"MIT"
] | null | null | null | evmscript_parser/core/ABI/provider.py | DmitIv/EVMScriptParser | 2a565cffb9cd890b9ded1978727364270150a72a | [
"MIT"
] | null | null | null | evmscript_parser/core/ABI/provider.py | DmitIv/EVMScriptParser | 2a565cffb9cd890b9ded1978727364270150a72a | [
"MIT"
] | null | null | null | """
Base class for ABI hierarchy.
"""
import logging
from abc import ABC, abstractmethod
from typing import Tuple
from evmscript_parser.core.exceptions import (
ABILocalFileNotExisted, ABIEtherscanNetworkError, ABIEtherscanStatusCode
)
from .storage import (
ABIKey, ABI,
CachedStorage
)
from .utilities.etherscan import (
get_abi, get_implementation_address, DEFAULT_NET
)
from .utilities.local import (
get_all_files, read_abi_from_json
)
from .utilities.processing import (
index_function_description
)
# ============================================================================
# ============================== ABI =========================================
# ============================================================================
class ABIProvider(ABC):
"""
Base class for ABI providers.
"""
def __call__(self, key: ABIKey) -> ABI:
"""Return ABI for key."""
return self.get_abi(key)
@abstractmethod
def get_abi(self, key: ABIKey) -> ABI:
"""Return ABI."""
pass
class ABIProviderEtherscanAPI(ABIProvider):
"""
Getting ABI from Etherscan API.
"""
def __init__(self, api_key: str, net: str = DEFAULT_NET):
"""Prepare provider with concrete APi key and net."""
self._api_key = api_key
self._net = net
self._retries = 3
def get_abi(self, key: ABIKey) -> ABI:
"""
Return ABI from Etherscan API.
:param key: str, address of contract.
:return: abi
:exception ABIEtherscanNetworkError in case of error at network layer.
:exception ABIEtherscanStatusCode in case of error in api calls.
"""
abi = get_abi(
self._api_key, key.ContractAddress,
self._net, self._retries
)
proxy_type_code = 1
implementation_code = 2
status = 0
for entry in abi:
name = entry.get('name', 'unknown')
if name == 'proxyType':
status |= proxy_type_code
elif name == 'implementation':
status |= implementation_code
if status == 3:
logging.debug(
f'Proxy punching for {key} '
f'in {self._net}'
)
address = get_implementation_address(
key.ContractAddress, abi, self._net
)
abi = get_abi(
self._api_key, address,
self._net, self._retries
)
break
return ABI(raw=abi, func_storage=index_function_description(abi))
class ABIProviderLocalDirectory(ABIProvider):
"""
Getting ABI from local files of interfaces.
"""
def __init__(self, interfaces_directory: str):
"""Prepare mapping from files names to paths."""
interfaces = get_all_files(
interfaces_directory, '*.json'
)
self._interfaces = {}
for interface in interfaces.values():
abi = read_abi_from_json(interface)
indexed_func_descriptions = index_function_description(
abi
)
for sign in indexed_func_descriptions:
self._interfaces[sign] = ABI(
raw=abi,
func_storage=indexed_func_descriptions
)
def get_abi(self, key: ABIKey) -> ABI:
"""
Return ABI from interface file.
:param key: str, name of interface file.
:return: abi
:exception ABILocalFileNotExisted in case of interface file does not
exist.
"""
if key.FunctionSignature in self._interfaces:
return self._interfaces[key.FunctionSignature]
raise ABILocalFileNotExisted(key.FunctionSignature)
class ABIProviderCombined(
ABIProviderEtherscanAPI, ABIProviderLocalDirectory
):
"""
Combined getting ABI.
Try to get ABI from Etherscan API.
In case of failure, read ABI from local file.
"""
def __init__(self, api_key: str, net: str, interfaces_directory: str):
"""Prepare instances of API and local files providers."""
ABIProviderEtherscanAPI.__init__(self, api_key, net)
ABIProviderLocalDirectory.__init__(self, interfaces_directory)
def get_abi(self, key: ABIKey) -> ABI:
"""
Return ABI.
:param key: Tuple[str, str], pair of address of contract
and interface file.
:return: abi
:exception ABILocalFileNotExisted in case of interface file does not
exist.
"""
try:
return ABIProviderEtherscanAPI.get_abi(self, key)
except (ABIEtherscanNetworkError, ABIEtherscanStatusCode) as err:
logging.debug(f'Fail on getting ABI from API: {str(err)}')
return ABIProviderLocalDirectory.get_abi(self, key)
def get_cached_etherscan_api(
api_key: str, net: str
) -> CachedStorage[ABIKey, ABI]:
"""
Return prepared instance of CachedStorage with API provider.
:param api_key: str, Etherscan API token.
:param net: str, the name of target network.
:return: CachedStorage[ABIKey, ABI]
"""
return CachedStorage(ABIProviderEtherscanAPI(api_key, net))
def get_cached_local_interfaces(
interfaces_directory: str
) -> CachedStorage[ABIKey, ABI]:
"""
Return prepared instance of CachedStorage with local files provider.
:param interfaces_directory: str, path to directory with interfaces.
:return: CachedStorage[ABIKey, ABI]
"""
return CachedStorage(ABIProviderLocalDirectory(interfaces_directory))
def get_cached_combined(
api_key: str, net: str,
interfaces_directory: str
) -> CachedStorage[Tuple[ABIKey, ABIKey], ABI]:
"""
Return prepared instance of CachedStorage with combined provider.
:param api_key: str, Etherscan API token.
:param net: str, the name of target network.
:param interfaces_directory: str, path to directory with interfaces.
:return: CachedStorage[ABIKey, ABI]
"""
return CachedStorage(ABIProviderCombined(
api_key, net, interfaces_directory
))
| 29.663507 | 78 | 0.598019 | import logging
from abc import ABC, abstractmethod
from typing import Tuple
from evmscript_parser.core.exceptions import (
ABILocalFileNotExisted, ABIEtherscanNetworkError, ABIEtherscanStatusCode
)
from .storage import (
ABIKey, ABI,
CachedStorage
)
from .utilities.etherscan import (
get_abi, get_implementation_address, DEFAULT_NET
)
from .utilities.local import (
get_all_files, read_abi_from_json
)
from .utilities.processing import (
index_function_description
)
class ABIProvider(ABC):
def __call__(self, key: ABIKey) -> ABI:
return self.get_abi(key)
@abstractmethod
def get_abi(self, key: ABIKey) -> ABI:
pass
class ABIProviderEtherscanAPI(ABIProvider):
def __init__(self, api_key: str, net: str = DEFAULT_NET):
self._api_key = api_key
self._net = net
self._retries = 3
def get_abi(self, key: ABIKey) -> ABI:
abi = get_abi(
self._api_key, key.ContractAddress,
self._net, self._retries
)
proxy_type_code = 1
implementation_code = 2
status = 0
for entry in abi:
name = entry.get('name', 'unknown')
if name == 'proxyType':
status |= proxy_type_code
elif name == 'implementation':
status |= implementation_code
if status == 3:
logging.debug(
f'Proxy punching for {key} '
f'in {self._net}'
)
address = get_implementation_address(
key.ContractAddress, abi, self._net
)
abi = get_abi(
self._api_key, address,
self._net, self._retries
)
break
return ABI(raw=abi, func_storage=index_function_description(abi))
class ABIProviderLocalDirectory(ABIProvider):
def __init__(self, interfaces_directory: str):
interfaces = get_all_files(
interfaces_directory, '*.json'
)
self._interfaces = {}
for interface in interfaces.values():
abi = read_abi_from_json(interface)
indexed_func_descriptions = index_function_description(
abi
)
for sign in indexed_func_descriptions:
self._interfaces[sign] = ABI(
raw=abi,
func_storage=indexed_func_descriptions
)
def get_abi(self, key: ABIKey) -> ABI:
if key.FunctionSignature in self._interfaces:
return self._interfaces[key.FunctionSignature]
raise ABILocalFileNotExisted(key.FunctionSignature)
class ABIProviderCombined(
ABIProviderEtherscanAPI, ABIProviderLocalDirectory
):
def __init__(self, api_key: str, net: str, interfaces_directory: str):
ABIProviderEtherscanAPI.__init__(self, api_key, net)
ABIProviderLocalDirectory.__init__(self, interfaces_directory)
def get_abi(self, key: ABIKey) -> ABI:
try:
return ABIProviderEtherscanAPI.get_abi(self, key)
except (ABIEtherscanNetworkError, ABIEtherscanStatusCode) as err:
logging.debug(f'Fail on getting ABI from API: {str(err)}')
return ABIProviderLocalDirectory.get_abi(self, key)
def get_cached_etherscan_api(
api_key: str, net: str
) -> CachedStorage[ABIKey, ABI]:
return CachedStorage(ABIProviderEtherscanAPI(api_key, net))
def get_cached_local_interfaces(
interfaces_directory: str
) -> CachedStorage[ABIKey, ABI]:
return CachedStorage(ABIProviderLocalDirectory(interfaces_directory))
def get_cached_combined(
api_key: str, net: str,
interfaces_directory: str
) -> CachedStorage[Tuple[ABIKey, ABIKey], ABI]:
return CachedStorage(ABIProviderCombined(
api_key, net, interfaces_directory
))
| true | true |
f7f6d63bbef3de8049e7d0b06f2f285a54ea9b5a | 17,590 | py | Python | venv/lib/python3.6/site-packages/sqlalchemy/testing/assertions.py | aitoehigie/britecore_flask | eef1873dbe6b2cc21f770bc6dec783007ae4493b | [
"MIT"
] | null | null | null | venv/lib/python3.6/site-packages/sqlalchemy/testing/assertions.py | aitoehigie/britecore_flask | eef1873dbe6b2cc21f770bc6dec783007ae4493b | [
"MIT"
] | 1 | 2021-06-01T23:32:38.000Z | 2021-06-01T23:32:38.000Z | venv/lib/python3.6/site-packages/sqlalchemy/testing/assertions.py | aitoehigie/britecore_flask | eef1873dbe6b2cc21f770bc6dec783007ae4493b | [
"MIT"
] | null | null | null | # testing/assertions.py
# Copyright (C) 2005-2018 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from __future__ import absolute_import
from . import util as testutil
from sqlalchemy import pool, orm, util
from sqlalchemy.engine import default, url
from sqlalchemy.util import decorator, compat
from sqlalchemy import types as sqltypes, schema, exc as sa_exc
import warnings
import re
from .exclusions import db_spec
from . import assertsql
from . import config
from .util import fail
import contextlib
from . import mock
def expect_warnings(*messages, **kw):
"""Context manager which expects one or more warnings.
With no arguments, squelches all SAWarnings emitted via
sqlalchemy.util.warn and sqlalchemy.util.warn_limited. Otherwise
pass string expressions that will match selected warnings via regex;
all non-matching warnings are sent through.
The expect version **asserts** that the warnings were in fact seen.
Note that the test suite sets SAWarning warnings to raise exceptions.
"""
return _expect_warnings(sa_exc.SAWarning, messages, **kw)
@contextlib.contextmanager
def expect_warnings_on(db, *messages, **kw):
"""Context manager which expects one or more warnings on specific
dialects.
The expect version **asserts** that the warnings were in fact seen.
"""
spec = db_spec(db)
if isinstance(db, util.string_types) and not spec(config._current):
yield
else:
with expect_warnings(*messages, **kw):
yield
def emits_warning(*messages):
"""Decorator form of expect_warnings().
Note that emits_warning does **not** assert that the warnings
were in fact seen.
"""
@decorator
def decorate(fn, *args, **kw):
with expect_warnings(assert_=False, *messages):
return fn(*args, **kw)
return decorate
def expect_deprecated(*messages, **kw):
return _expect_warnings(sa_exc.SADeprecationWarning, messages, **kw)
def emits_warning_on(db, *messages):
"""Mark a test as emitting a warning on a specific dialect.
With no arguments, squelches all SAWarning failures. Or pass one or more
strings; these will be matched to the root of the warning description by
warnings.filterwarnings().
Note that emits_warning_on does **not** assert that the warnings
were in fact seen.
"""
@decorator
def decorate(fn, *args, **kw):
with expect_warnings_on(db, assert_=False, *messages):
return fn(*args, **kw)
return decorate
def uses_deprecated(*messages):
"""Mark a test as immune from fatal deprecation warnings.
With no arguments, squelches all SADeprecationWarning failures.
Or pass one or more strings; these will be matched to the root
of the warning description by warnings.filterwarnings().
As a special case, you may pass a function name prefixed with //
and it will be re-written as needed to match the standard warning
verbiage emitted by the sqlalchemy.util.deprecated decorator.
Note that uses_deprecated does **not** assert that the warnings
were in fact seen.
"""
@decorator
def decorate(fn, *args, **kw):
with expect_deprecated(*messages, assert_=False):
return fn(*args, **kw)
return decorate
@contextlib.contextmanager
def _expect_warnings(exc_cls, messages, regex=True, assert_=True, py2konly=False):
if regex:
filters = [re.compile(msg, re.I | re.S) for msg in messages]
else:
filters = messages
seen = set(filters)
real_warn = warnings.warn
def our_warn(msg, *arg, **kw):
if isinstance(msg, exc_cls):
exception = msg
msg = str(exception)
elif arg:
exception = arg[0]
else:
exception = None
if not exception or not issubclass(exception, exc_cls):
return real_warn(msg, *arg, **kw)
if not filters:
return
for filter_ in filters:
if (regex and filter_.match(msg)) or (not regex and filter_ == msg):
seen.discard(filter_)
break
else:
real_warn(msg, *arg, **kw)
with mock.patch("warnings.warn", our_warn):
yield
if assert_ and (not py2konly or not compat.py3k):
assert not seen, "Warnings were not seen: %s" % ", ".join(
"%r" % (s.pattern if regex else s) for s in seen
)
def global_cleanup_assertions():
"""Check things that have to be finalized at the end of a test suite.
Hardcoded at the moment, a modular system can be built here
to support things like PG prepared transactions, tables all
dropped, etc.
"""
_assert_no_stray_pool_connections()
_STRAY_CONNECTION_FAILURES = 0
def _assert_no_stray_pool_connections():
global _STRAY_CONNECTION_FAILURES
# lazy gc on cPython means "do nothing." pool connections
# shouldn't be in cycles, should go away.
testutil.lazy_gc()
# however, once in awhile, on an EC2 machine usually,
# there's a ref in there. usually just one.
if pool._refs:
# OK, let's be somewhat forgiving.
_STRAY_CONNECTION_FAILURES += 1
print("Encountered a stray connection in test cleanup: %s" % str(pool._refs))
# then do a real GC sweep. We shouldn't even be here
# so a single sweep should really be doing it, otherwise
# there's probably a real unreachable cycle somewhere.
testutil.gc_collect()
# if we've already had two of these occurrences, or
# after a hard gc sweep we still have pool._refs?!
# now we have to raise.
if pool._refs:
err = str(pool._refs)
# but clean out the pool refs collection directly,
# reset the counter,
# so the error doesn't at least keep happening.
pool._refs.clear()
_STRAY_CONNECTION_FAILURES = 0
warnings.warn(
"Stray connection refused to leave " "after gc.collect(): %s" % err
)
elif _STRAY_CONNECTION_FAILURES > 10:
assert False, "Encountered more than 10 stray connections"
_STRAY_CONNECTION_FAILURES = 0
def eq_regex(a, b, msg=None):
assert re.match(b, a), msg or "%r !~ %r" % (a, b)
def eq_(a, b, msg=None):
"""Assert a == b, with repr messaging on failure."""
assert a == b, msg or "%r != %r" % (a, b)
def ne_(a, b, msg=None):
"""Assert a != b, with repr messaging on failure."""
assert a != b, msg or "%r == %r" % (a, b)
def le_(a, b, msg=None):
"""Assert a <= b, with repr messaging on failure."""
assert a <= b, msg or "%r != %r" % (a, b)
def is_true(a, msg=None):
is_(a, True, msg=msg)
def is_false(a, msg=None):
is_(a, False, msg=msg)
def is_(a, b, msg=None):
"""Assert a is b, with repr messaging on failure."""
assert a is b, msg or "%r is not %r" % (a, b)
def is_not_(a, b, msg=None):
"""Assert a is not b, with repr messaging on failure."""
assert a is not b, msg or "%r is %r" % (a, b)
def in_(a, b, msg=None):
"""Assert a in b, with repr messaging on failure."""
assert a in b, msg or "%r not in %r" % (a, b)
def not_in_(a, b, msg=None):
"""Assert a in not b, with repr messaging on failure."""
assert a not in b, msg or "%r is in %r" % (a, b)
def startswith_(a, fragment, msg=None):
"""Assert a.startswith(fragment), with repr messaging on failure."""
assert a.startswith(fragment), msg or "%r does not start with %r" % (a, fragment)
def eq_ignore_whitespace(a, b, msg=None):
a = re.sub(r"^\s+?|\n", "", a)
a = re.sub(r" {2,}", " ", a)
b = re.sub(r"^\s+?|\n", "", b)
b = re.sub(r" {2,}", " ", b)
assert a == b, msg or "%r != %r" % (a, b)
def assert_raises(except_cls, callable_, *args, **kw):
try:
callable_(*args, **kw)
success = False
except except_cls:
success = True
# assert outside the block so it works for AssertionError too !
assert success, "Callable did not raise an exception"
def assert_raises_message(except_cls, msg, callable_, *args, **kwargs):
try:
callable_(*args, **kwargs)
assert False, "Callable did not raise an exception"
except except_cls as e:
assert re.search(msg, util.text_type(e), re.UNICODE), "%r !~ %s" % (msg, e)
print(util.text_type(e).encode("utf-8"))
class AssertsCompiledSQL(object):
def assert_compile(
self,
clause,
result,
params=None,
checkparams=None,
dialect=None,
checkpositional=None,
check_prefetch=None,
use_default_dialect=False,
allow_dialect_select=False,
literal_binds=False,
schema_translate_map=None,
):
if use_default_dialect:
dialect = default.DefaultDialect()
elif allow_dialect_select:
dialect = None
else:
if dialect is None:
dialect = getattr(self, "__dialect__", None)
if dialect is None:
dialect = config.db.dialect
elif dialect == "default":
dialect = default.DefaultDialect()
elif dialect == "default_enhanced":
dialect = default.StrCompileDialect()
elif isinstance(dialect, util.string_types):
dialect = url.URL(dialect).get_dialect()()
kw = {}
compile_kwargs = {}
if schema_translate_map:
kw["schema_translate_map"] = schema_translate_map
if params is not None:
kw["column_keys"] = list(params)
if literal_binds:
compile_kwargs["literal_binds"] = True
if isinstance(clause, orm.Query):
context = clause._compile_context()
context.statement.use_labels = True
clause = context.statement
elif isinstance(clause, orm.persistence.BulkUD):
with mock.patch.object(clause, "_execute_stmt") as stmt_mock:
clause.exec_()
clause = stmt_mock.mock_calls[0][1][0]
if compile_kwargs:
kw["compile_kwargs"] = compile_kwargs
c = clause.compile(dialect=dialect, **kw)
param_str = repr(getattr(c, "params", {}))
if util.py3k:
param_str = param_str.encode("utf-8").decode("ascii", "ignore")
print(("\nSQL String:\n" + util.text_type(c) + param_str).encode("utf-8"))
else:
print("\nSQL String:\n" + util.text_type(c).encode("utf-8") + param_str)
cc = re.sub(r"[\n\t]", "", util.text_type(c))
eq_(cc, result, "%r != %r on dialect %r" % (cc, result, dialect))
if checkparams is not None:
eq_(c.construct_params(params), checkparams)
if checkpositional is not None:
p = c.construct_params(params)
eq_(tuple([p[x] for x in c.positiontup]), checkpositional)
if check_prefetch is not None:
eq_(c.prefetch, check_prefetch)
class ComparesTables(object):
def assert_tables_equal(self, table, reflected_table, strict_types=False):
assert len(table.c) == len(reflected_table.c)
for c, reflected_c in zip(table.c, reflected_table.c):
eq_(c.name, reflected_c.name)
assert reflected_c is reflected_table.c[c.name]
eq_(c.primary_key, reflected_c.primary_key)
eq_(c.nullable, reflected_c.nullable)
if strict_types:
msg = "Type '%s' doesn't correspond to type '%s'"
assert isinstance(reflected_c.type, type(c.type)), msg % (
reflected_c.type,
c.type,
)
else:
self.assert_types_base(reflected_c, c)
if isinstance(c.type, sqltypes.String):
eq_(c.type.length, reflected_c.type.length)
eq_(
{f.column.name for f in c.foreign_keys},
{f.column.name for f in reflected_c.foreign_keys},
)
if c.server_default:
assert isinstance(reflected_c.server_default, schema.FetchedValue)
assert len(table.primary_key) == len(reflected_table.primary_key)
for c in table.primary_key:
assert reflected_table.primary_key.columns[c.name] is not None
def assert_types_base(self, c1, c2):
assert c1.type._compare_type_affinity(c2.type), (
"On column %r, type '%s' doesn't correspond to type '%s'"
% (c1.name, c1.type, c2.type)
)
class AssertsExecutionResults(object):
def assert_result(self, result, class_, *objects):
result = list(result)
print(repr(result))
self.assert_list(result, class_, objects)
def assert_list(self, result, class_, list):
self.assert_(
len(result) == len(list),
"result list is not the same size as test list, "
+ "for class "
+ class_.__name__,
)
for i in range(0, len(list)):
self.assert_row(class_, result[i], list[i])
def assert_row(self, class_, rowobj, desc):
self.assert_(rowobj.__class__ is class_, "item class is not " + repr(class_))
for key, value in desc.items():
if isinstance(value, tuple):
if isinstance(value[1], list):
self.assert_list(getattr(rowobj, key), value[0], value[1])
else:
self.assert_row(value[0], getattr(rowobj, key), value[1])
else:
self.assert_(
getattr(rowobj, key) == value,
"attribute %s value %s does not match %s"
% (key, getattr(rowobj, key), value),
)
def assert_unordered_result(self, result, cls, *expected):
"""As assert_result, but the order of objects is not considered.
The algorithm is very expensive but not a big deal for the small
numbers of rows that the test suite manipulates.
"""
class immutabledict(dict):
def __hash__(self):
return id(self)
found = util.IdentitySet(result)
expected = {immutabledict(e) for e in expected}
for wrong in util.itertools_filterfalse(lambda o: isinstance(o, cls), found):
fail(
'Unexpected type "%s", expected "%s"'
% (type(wrong).__name__, cls.__name__)
)
if len(found) != len(expected):
fail(
'Unexpected object count "%s", expected "%s"'
% (len(found), len(expected))
)
NOVALUE = object()
def _compare_item(obj, spec):
for key, value in spec.items():
if isinstance(value, tuple):
try:
self.assert_unordered_result(
getattr(obj, key), value[0], *value[1]
)
except AssertionError:
return False
else:
if getattr(obj, key, NOVALUE) != value:
return False
return True
for expected_item in expected:
for found_item in found:
if _compare_item(found_item, expected_item):
found.remove(found_item)
break
else:
fail(
"Expected %s instance with attributes %s not found."
% (cls.__name__, repr(expected_item))
)
return True
def sql_execution_asserter(self, db=None):
if db is None:
from . import db as db
return assertsql.assert_engine(db)
def assert_sql_execution(self, db, callable_, *rules):
with self.sql_execution_asserter(db) as asserter:
result = callable_()
asserter.assert_(*rules)
return result
def assert_sql(self, db, callable_, rules):
newrules = []
for rule in rules:
if isinstance(rule, dict):
newrule = assertsql.AllOf(
*[assertsql.CompiledSQL(k, v) for k, v in rule.items()]
)
else:
newrule = assertsql.CompiledSQL(*rule)
newrules.append(newrule)
return self.assert_sql_execution(db, callable_, *newrules)
def assert_sql_count(self, db, callable_, count):
self.assert_sql_execution(db, callable_, assertsql.CountStatements(count))
def assert_multiple_sql_count(self, dbs, callable_, counts):
recs = [
(self.sql_execution_asserter(db), db, count)
for (db, count) in zip(dbs, counts)
]
asserters = []
for ctx, db, count in recs:
asserters.append(ctx.__enter__())
try:
return callable_()
finally:
for asserter, (ctx, db, count) in zip(asserters, recs):
ctx.__exit__(None, None, None)
asserter.assert_(assertsql.CountStatements(count))
@contextlib.contextmanager
def assert_execution(self, db, *rules):
with self.sql_execution_asserter(db) as asserter:
yield
asserter.assert_(*rules)
def assert_statement_count(self, db, count):
return self.assert_execution(db, assertsql.CountStatements(count))
| 31.808318 | 86 | 0.599147 |
from __future__ import absolute_import
from . import util as testutil
from sqlalchemy import pool, orm, util
from sqlalchemy.engine import default, url
from sqlalchemy.util import decorator, compat
from sqlalchemy import types as sqltypes, schema, exc as sa_exc
import warnings
import re
from .exclusions import db_spec
from . import assertsql
from . import config
from .util import fail
import contextlib
from . import mock
def expect_warnings(*messages, **kw):
return _expect_warnings(sa_exc.SAWarning, messages, **kw)
@contextlib.contextmanager
def expect_warnings_on(db, *messages, **kw):
spec = db_spec(db)
if isinstance(db, util.string_types) and not spec(config._current):
yield
else:
with expect_warnings(*messages, **kw):
yield
def emits_warning(*messages):
@decorator
def decorate(fn, *args, **kw):
with expect_warnings(assert_=False, *messages):
return fn(*args, **kw)
return decorate
def expect_deprecated(*messages, **kw):
return _expect_warnings(sa_exc.SADeprecationWarning, messages, **kw)
def emits_warning_on(db, *messages):
@decorator
def decorate(fn, *args, **kw):
with expect_warnings_on(db, assert_=False, *messages):
return fn(*args, **kw)
return decorate
def uses_deprecated(*messages):
@decorator
def decorate(fn, *args, **kw):
with expect_deprecated(*messages, assert_=False):
return fn(*args, **kw)
return decorate
@contextlib.contextmanager
def _expect_warnings(exc_cls, messages, regex=True, assert_=True, py2konly=False):
if regex:
filters = [re.compile(msg, re.I | re.S) for msg in messages]
else:
filters = messages
seen = set(filters)
real_warn = warnings.warn
def our_warn(msg, *arg, **kw):
if isinstance(msg, exc_cls):
exception = msg
msg = str(exception)
elif arg:
exception = arg[0]
else:
exception = None
if not exception or not issubclass(exception, exc_cls):
return real_warn(msg, *arg, **kw)
if not filters:
return
for filter_ in filters:
if (regex and filter_.match(msg)) or (not regex and filter_ == msg):
seen.discard(filter_)
break
else:
real_warn(msg, *arg, **kw)
with mock.patch("warnings.warn", our_warn):
yield
if assert_ and (not py2konly or not compat.py3k):
assert not seen, "Warnings were not seen: %s" % ", ".join(
"%r" % (s.pattern if regex else s) for s in seen
)
def global_cleanup_assertions():
_assert_no_stray_pool_connections()
_STRAY_CONNECTION_FAILURES = 0
def _assert_no_stray_pool_connections():
global _STRAY_CONNECTION_FAILURES
testutil.lazy_gc()
# however, once in awhile, on an EC2 machine usually,
# there's a ref in there. usually just one.
if pool._refs:
_STRAY_CONNECTION_FAILURES += 1
print("Encountered a stray connection in test cleanup: %s" % str(pool._refs))
# then do a real GC sweep. We shouldn't even be here
testutil.gc_collect()
# if we've already had two of these occurrences, or
if pool._refs:
err = str(pool._refs)
pool._refs.clear()
_STRAY_CONNECTION_FAILURES = 0
warnings.warn(
"Stray connection refused to leave " "after gc.collect(): %s" % err
)
elif _STRAY_CONNECTION_FAILURES > 10:
assert False, "Encountered more than 10 stray connections"
_STRAY_CONNECTION_FAILURES = 0
def eq_regex(a, b, msg=None):
assert re.match(b, a), msg or "%r !~ %r" % (a, b)
def eq_(a, b, msg=None):
assert a == b, msg or "%r != %r" % (a, b)
def ne_(a, b, msg=None):
assert a != b, msg or "%r == %r" % (a, b)
def le_(a, b, msg=None):
assert a <= b, msg or "%r != %r" % (a, b)
def is_true(a, msg=None):
is_(a, True, msg=msg)
def is_false(a, msg=None):
is_(a, False, msg=msg)
def is_(a, b, msg=None):
assert a is b, msg or "%r is not %r" % (a, b)
def is_not_(a, b, msg=None):
assert a is not b, msg or "%r is %r" % (a, b)
def in_(a, b, msg=None):
assert a in b, msg or "%r not in %r" % (a, b)
def not_in_(a, b, msg=None):
assert a not in b, msg or "%r is in %r" % (a, b)
def startswith_(a, fragment, msg=None):
assert a.startswith(fragment), msg or "%r does not start with %r" % (a, fragment)
def eq_ignore_whitespace(a, b, msg=None):
a = re.sub(r"^\s+?|\n", "", a)
a = re.sub(r" {2,}", " ", a)
b = re.sub(r"^\s+?|\n", "", b)
b = re.sub(r" {2,}", " ", b)
assert a == b, msg or "%r != %r" % (a, b)
def assert_raises(except_cls, callable_, *args, **kw):
try:
callable_(*args, **kw)
success = False
except except_cls:
success = True
# assert outside the block so it works for AssertionError too !
assert success, "Callable did not raise an exception"
def assert_raises_message(except_cls, msg, callable_, *args, **kwargs):
try:
callable_(*args, **kwargs)
assert False, "Callable did not raise an exception"
except except_cls as e:
assert re.search(msg, util.text_type(e), re.UNICODE), "%r !~ %s" % (msg, e)
print(util.text_type(e).encode("utf-8"))
class AssertsCompiledSQL(object):
def assert_compile(
self,
clause,
result,
params=None,
checkparams=None,
dialect=None,
checkpositional=None,
check_prefetch=None,
use_default_dialect=False,
allow_dialect_select=False,
literal_binds=False,
schema_translate_map=None,
):
if use_default_dialect:
dialect = default.DefaultDialect()
elif allow_dialect_select:
dialect = None
else:
if dialect is None:
dialect = getattr(self, "__dialect__", None)
if dialect is None:
dialect = config.db.dialect
elif dialect == "default":
dialect = default.DefaultDialect()
elif dialect == "default_enhanced":
dialect = default.StrCompileDialect()
elif isinstance(dialect, util.string_types):
dialect = url.URL(dialect).get_dialect()()
kw = {}
compile_kwargs = {}
if schema_translate_map:
kw["schema_translate_map"] = schema_translate_map
if params is not None:
kw["column_keys"] = list(params)
if literal_binds:
compile_kwargs["literal_binds"] = True
if isinstance(clause, orm.Query):
context = clause._compile_context()
context.statement.use_labels = True
clause = context.statement
elif isinstance(clause, orm.persistence.BulkUD):
with mock.patch.object(clause, "_execute_stmt") as stmt_mock:
clause.exec_()
clause = stmt_mock.mock_calls[0][1][0]
if compile_kwargs:
kw["compile_kwargs"] = compile_kwargs
c = clause.compile(dialect=dialect, **kw)
param_str = repr(getattr(c, "params", {}))
if util.py3k:
param_str = param_str.encode("utf-8").decode("ascii", "ignore")
print(("\nSQL String:\n" + util.text_type(c) + param_str).encode("utf-8"))
else:
print("\nSQL String:\n" + util.text_type(c).encode("utf-8") + param_str)
cc = re.sub(r"[\n\t]", "", util.text_type(c))
eq_(cc, result, "%r != %r on dialect %r" % (cc, result, dialect))
if checkparams is not None:
eq_(c.construct_params(params), checkparams)
if checkpositional is not None:
p = c.construct_params(params)
eq_(tuple([p[x] for x in c.positiontup]), checkpositional)
if check_prefetch is not None:
eq_(c.prefetch, check_prefetch)
class ComparesTables(object):
def assert_tables_equal(self, table, reflected_table, strict_types=False):
assert len(table.c) == len(reflected_table.c)
for c, reflected_c in zip(table.c, reflected_table.c):
eq_(c.name, reflected_c.name)
assert reflected_c is reflected_table.c[c.name]
eq_(c.primary_key, reflected_c.primary_key)
eq_(c.nullable, reflected_c.nullable)
if strict_types:
msg = "Type '%s' doesn't correspond to type '%s'"
assert isinstance(reflected_c.type, type(c.type)), msg % (
reflected_c.type,
c.type,
)
else:
self.assert_types_base(reflected_c, c)
if isinstance(c.type, sqltypes.String):
eq_(c.type.length, reflected_c.type.length)
eq_(
{f.column.name for f in c.foreign_keys},
{f.column.name for f in reflected_c.foreign_keys},
)
if c.server_default:
assert isinstance(reflected_c.server_default, schema.FetchedValue)
assert len(table.primary_key) == len(reflected_table.primary_key)
for c in table.primary_key:
assert reflected_table.primary_key.columns[c.name] is not None
def assert_types_base(self, c1, c2):
assert c1.type._compare_type_affinity(c2.type), (
"On column %r, type '%s' doesn't correspond to type '%s'"
% (c1.name, c1.type, c2.type)
)
class AssertsExecutionResults(object):
def assert_result(self, result, class_, *objects):
result = list(result)
print(repr(result))
self.assert_list(result, class_, objects)
def assert_list(self, result, class_, list):
self.assert_(
len(result) == len(list),
"result list is not the same size as test list, "
+ "for class "
+ class_.__name__,
)
for i in range(0, len(list)):
self.assert_row(class_, result[i], list[i])
def assert_row(self, class_, rowobj, desc):
self.assert_(rowobj.__class__ is class_, "item class is not " + repr(class_))
for key, value in desc.items():
if isinstance(value, tuple):
if isinstance(value[1], list):
self.assert_list(getattr(rowobj, key), value[0], value[1])
else:
self.assert_row(value[0], getattr(rowobj, key), value[1])
else:
self.assert_(
getattr(rowobj, key) == value,
"attribute %s value %s does not match %s"
% (key, getattr(rowobj, key), value),
)
def assert_unordered_result(self, result, cls, *expected):
class immutabledict(dict):
def __hash__(self):
return id(self)
found = util.IdentitySet(result)
expected = {immutabledict(e) for e in expected}
for wrong in util.itertools_filterfalse(lambda o: isinstance(o, cls), found):
fail(
'Unexpected type "%s", expected "%s"'
% (type(wrong).__name__, cls.__name__)
)
if len(found) != len(expected):
fail(
'Unexpected object count "%s", expected "%s"'
% (len(found), len(expected))
)
NOVALUE = object()
def _compare_item(obj, spec):
for key, value in spec.items():
if isinstance(value, tuple):
try:
self.assert_unordered_result(
getattr(obj, key), value[0], *value[1]
)
except AssertionError:
return False
else:
if getattr(obj, key, NOVALUE) != value:
return False
return True
for expected_item in expected:
for found_item in found:
if _compare_item(found_item, expected_item):
found.remove(found_item)
break
else:
fail(
"Expected %s instance with attributes %s not found."
% (cls.__name__, repr(expected_item))
)
return True
def sql_execution_asserter(self, db=None):
if db is None:
from . import db as db
return assertsql.assert_engine(db)
def assert_sql_execution(self, db, callable_, *rules):
with self.sql_execution_asserter(db) as asserter:
result = callable_()
asserter.assert_(*rules)
return result
def assert_sql(self, db, callable_, rules):
newrules = []
for rule in rules:
if isinstance(rule, dict):
newrule = assertsql.AllOf(
*[assertsql.CompiledSQL(k, v) for k, v in rule.items()]
)
else:
newrule = assertsql.CompiledSQL(*rule)
newrules.append(newrule)
return self.assert_sql_execution(db, callable_, *newrules)
def assert_sql_count(self, db, callable_, count):
self.assert_sql_execution(db, callable_, assertsql.CountStatements(count))
def assert_multiple_sql_count(self, dbs, callable_, counts):
recs = [
(self.sql_execution_asserter(db), db, count)
for (db, count) in zip(dbs, counts)
]
asserters = []
for ctx, db, count in recs:
asserters.append(ctx.__enter__())
try:
return callable_()
finally:
for asserter, (ctx, db, count) in zip(asserters, recs):
ctx.__exit__(None, None, None)
asserter.assert_(assertsql.CountStatements(count))
@contextlib.contextmanager
def assert_execution(self, db, *rules):
with self.sql_execution_asserter(db) as asserter:
yield
asserter.assert_(*rules)
def assert_statement_count(self, db, count):
return self.assert_execution(db, assertsql.CountStatements(count))
| true | true |
f7f6d6a17f7bb8d45a8f9163f3ce1655635202fd | 3,076 | py | Python | mototour/mototour/settings.py | andersonnrc/desafio-oncase | d92873b15636ef6c73330480d41e29e2d94afe2c | [
"MIT"
] | null | null | null | mototour/mototour/settings.py | andersonnrc/desafio-oncase | d92873b15636ef6c73330480d41e29e2d94afe2c | [
"MIT"
] | null | null | null | mototour/mototour/settings.py | andersonnrc/desafio-oncase | d92873b15636ef6c73330480d41e29e2d94afe2c | [
"MIT"
] | null | null | null | # Scrapy settings for mototour project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'mototour'
SPIDER_MODULES = ['mototour.spiders']
NEWSPIDER_MODULE = 'mototour.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'mototour (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'mototour.middlewares.MototourSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'mototour.middlewares.MototourDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'mototour.pipelines.MototourPipeline': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
| 34.561798 | 103 | 0.778609 |
BOT_NAME = 'mototour'
SPIDER_MODULES = ['mototour.spiders']
NEWSPIDER_MODULE = 'mototour.spiders'
ROBOTSTXT_OBEY = True
ITEM_PIPELINES = {
'mototour.pipelines.MototourPipeline': 300,
}
| true | true |
f7f6d7309de07b524ec57805dc8338422f8d65c1 | 538 | py | Python | DS&Algo Programs in Python/vowelcounter.py | prathimacode-hub/HacktoberFest-2020 | c18bbb42a5e78f6a7dbfc15fbafd127e738f53f7 | [
"MIT"
] | 386 | 2020-05-08T16:05:16.000Z | 2021-10-05T17:39:14.000Z | DS&Algo Programs in Python/vowelcounter.py | prathimacode-hub/HacktoberFest-2020 | c18bbb42a5e78f6a7dbfc15fbafd127e738f53f7 | [
"MIT"
] | 830 | 2020-08-31T17:16:45.000Z | 2021-10-06T14:14:23.000Z | DS&Algo Programs in Python/vowelcounter.py | prathimacode-hub/HacktoberFest-2020 | c18bbb42a5e78f6a7dbfc15fbafd127e738f53f7 | [
"MIT"
] | 923 | 2020-05-29T15:04:29.000Z | 2021-10-06T15:18:01.000Z | def countVowels(S):
total_size = len(S)
vowels = 0
for char in S:
if char in 'aeiouAEIOU':
vowels = vowels + 1
consonants = total_size - vowels
if vowels > consonants:
print('There are more vowels than consonants in the string ' + S)
elif vowels == consonants:
print('Both vowels and consonants are equal in the string ' + S)
else:
print('There are more consonants than vowels in the string ' + S)
countVowels('hello')
countVowels('hi')
countVowels('aeiocc')
| 26.9 | 73 | 0.626394 | def countVowels(S):
total_size = len(S)
vowels = 0
for char in S:
if char in 'aeiouAEIOU':
vowels = vowels + 1
consonants = total_size - vowels
if vowels > consonants:
print('There are more vowels than consonants in the string ' + S)
elif vowels == consonants:
print('Both vowels and consonants are equal in the string ' + S)
else:
print('There are more consonants than vowels in the string ' + S)
countVowels('hello')
countVowels('hi')
countVowels('aeiocc')
| true | true |
f7f6d7d1fffc8c378a542755772e1b0be9fae9ab | 23,104 | py | Python | python_modules/dagster/dagster/core/execution/results.py | asamoal/dagster | 08fad28e4b608608ce090ce2e8a52c2cf9dd1b64 | [
"Apache-2.0"
] | null | null | null | python_modules/dagster/dagster/core/execution/results.py | asamoal/dagster | 08fad28e4b608608ce090ce2e8a52c2cf9dd1b64 | [
"Apache-2.0"
] | null | null | null | python_modules/dagster/dagster/core/execution/results.py | asamoal/dagster | 08fad28e4b608608ce090ce2e8a52c2cf9dd1b64 | [
"Apache-2.0"
] | null | null | null | from collections import defaultdict
import dagster._check as check
from dagster.core.definitions import GraphDefinition, Node, NodeHandle, PipelineDefinition
from dagster.core.definitions.utils import DEFAULT_OUTPUT
from dagster.core.errors import DagsterInvariantViolationError
from dagster.core.events import DagsterEvent, DagsterEventType
from dagster.core.execution.plan.outputs import StepOutputHandle
from dagster.core.execution.plan.step import StepKind
from dagster.core.execution.plan.utils import build_resources_for_manager
def _construct_events_by_step_key(event_list):
events_by_step_key = defaultdict(list)
for event in event_list:
events_by_step_key[event.step_key].append(event)
return dict(events_by_step_key)
class GraphExecutionResult:
def __init__(
self,
container,
event_list,
reconstruct_context,
pipeline_def,
handle=None,
output_capture=None,
):
self.container = check.inst_param(container, "container", GraphDefinition)
self.event_list = check.list_param(event_list, "step_event_list", of_type=DagsterEvent)
self.reconstruct_context = check.callable_param(reconstruct_context, "reconstruct_context")
self.pipeline_def = check.inst_param(pipeline_def, "pipeline_def", PipelineDefinition)
self.handle = check.opt_inst_param(handle, "handle", NodeHandle)
self.output_capture = check.opt_dict_param(
output_capture, "output_capture", key_type=StepOutputHandle
)
self._events_by_step_key = _construct_events_by_step_key(event_list)
@property
def success(self):
"""bool: Whether all steps in the execution were successful."""
return all([not event.is_failure for event in self.event_list])
@property
def step_event_list(self):
"""List[DagsterEvent] The full list of events generated by steps in the execution.
Excludes events generated by the pipeline lifecycle, e.g., ``PIPELINE_START``.
"""
return [event for event in self.event_list if event.is_step_event]
@property
def events_by_step_key(self):
return self._events_by_step_key
def result_for_solid(self, name):
"""Get the result of a top level solid.
Args:
name (str): The name of the top-level solid or aliased solid for which to retrieve the
result.
Returns:
Union[CompositeSolidExecutionResult, SolidExecutionResult]: The result of the solid
execution within the pipeline.
"""
if not self.container.has_solid_named(name):
raise DagsterInvariantViolationError(
"Tried to get result for solid '{name}' in '{container}'. No such top level "
"solid.".format(name=name, container=self.container.name)
)
return self.result_for_handle(NodeHandle(name, None))
def output_for_solid(self, handle_str, output_name=DEFAULT_OUTPUT):
"""Get the output of a solid by its solid handle string and output name.
Args:
handle_str (str): The string handle for the solid.
output_name (str): Optional. The name of the output, default to DEFAULT_OUTPUT.
Returns:
The output value for the handle and output_name.
"""
check.str_param(handle_str, "handle_str")
check.str_param(output_name, "output_name")
return self.result_for_handle(NodeHandle.from_string(handle_str)).output_value(output_name)
@property
def solid_result_list(self):
"""List[Union[CompositeSolidExecutionResult, SolidExecutionResult]]: The results for each
top level solid."""
return [self.result_for_solid(solid.name) for solid in self.container.solids]
def _result_for_handle(self, solid, handle):
if not solid:
raise DagsterInvariantViolationError(
"Can not find solid handle {handle_str}.".format(handle_str=handle.to_string())
)
events_by_kind = defaultdict(list)
if solid.is_graph:
events = []
for event in self.event_list:
if event.is_step_event:
if event.solid_handle.is_or_descends_from(handle.with_ancestor(self.handle)):
events_by_kind[event.step_kind].append(event)
events.append(event)
return CompositeSolidExecutionResult(
solid,
events,
events_by_kind,
self.reconstruct_context,
self.pipeline_def,
handle=handle.with_ancestor(self.handle),
output_capture=self.output_capture,
)
else:
for event in self.event_list:
if event.is_step_event:
if event.solid_handle.is_or_descends_from(handle.with_ancestor(self.handle)):
events_by_kind[event.step_kind].append(event)
return SolidExecutionResult(
solid,
events_by_kind,
self.reconstruct_context,
self.pipeline_def,
output_capture=self.output_capture,
)
def result_for_handle(self, handle):
"""Get the result of a solid by its solid handle.
This allows indexing into top-level solids to retrieve the results of children of
composite solids.
Args:
handle (Union[str,NodeHandle]): The handle for the solid.
Returns:
Union[CompositeSolidExecutionResult, SolidExecutionResult]: The result of the given
solid.
"""
if isinstance(handle, str):
handle = NodeHandle.from_string(handle)
else:
check.inst_param(handle, "handle", NodeHandle)
solid = self.container.get_solid(handle)
return self._result_for_handle(solid, handle)
class PipelineExecutionResult(GraphExecutionResult):
"""The result of executing a pipeline.
Returned by :py:func:`execute_pipeline`. Users should not instantiate this class directly.
"""
def __init__(
self,
pipeline_def,
run_id,
event_list,
reconstruct_context,
output_capture=None,
):
self.run_id = check.str_param(run_id, "run_id")
check.inst_param(pipeline_def, "pipeline_def", PipelineDefinition)
super(PipelineExecutionResult, self).__init__(
container=pipeline_def.graph,
event_list=event_list,
reconstruct_context=reconstruct_context,
pipeline_def=pipeline_def,
output_capture=output_capture,
)
class CompositeSolidExecutionResult(GraphExecutionResult):
"""Execution result for a composite solid in a pipeline.
Users should not instantiate this class directly.
"""
def __init__(
self,
solid,
event_list,
step_events_by_kind,
reconstruct_context,
pipeline_def,
handle=None,
output_capture=None,
):
check.inst_param(solid, "solid", Node)
check.invariant(
solid.is_graph,
desc="Tried to instantiate a CompositeSolidExecutionResult with a noncomposite solid",
)
self.solid = solid
self.step_events_by_kind = check.dict_param(
step_events_by_kind, "step_events_by_kind", key_type=StepKind, value_type=list
)
self.output_capture = check.opt_dict_param(
output_capture, "output_capture", key_type=StepOutputHandle
)
super(CompositeSolidExecutionResult, self).__init__(
container=solid.definition,
event_list=event_list,
reconstruct_context=reconstruct_context,
pipeline_def=pipeline_def,
handle=handle,
output_capture=output_capture,
)
def output_values_for_solid(self, name):
check.str_param(name, "name")
return self.result_for_solid(name).output_values
def output_values_for_handle(self, handle_str):
check.str_param(handle_str, "handle_str")
return self.result_for_handle(handle_str).output_values
def output_value_for_solid(self, name, output_name=DEFAULT_OUTPUT):
check.str_param(name, "name")
check.str_param(output_name, "output_name")
return self.result_for_solid(name).output_value(output_name)
def output_value_for_handle(self, handle_str, output_name=DEFAULT_OUTPUT):
check.str_param(handle_str, "handle_str")
check.str_param(output_name, "output_name")
return self.result_for_handle(handle_str).output_value(output_name)
@property
def output_values(self):
values = {}
for output_name in self.solid.definition.output_dict:
output_mapping = self.solid.definition.get_output_mapping(output_name)
inner_solid_values = self._result_for_handle(
self.solid.definition.solid_named(output_mapping.maps_from.solid_name),
NodeHandle(output_mapping.maps_from.solid_name, None),
).output_values
if inner_solid_values is not None: # may be None if inner solid was skipped
if output_mapping.maps_from.output_name in inner_solid_values:
values[output_name] = inner_solid_values[output_mapping.maps_from.output_name]
return values
def output_value(self, output_name=DEFAULT_OUTPUT):
check.str_param(output_name, "output_name")
if not self.solid.definition.has_output(output_name):
raise DagsterInvariantViolationError(
"Output '{output_name}' not defined in composite solid '{solid}': "
"{outputs_clause}. If you were expecting this output to be present, you may "
"be missing an output_mapping from an inner solid to its enclosing composite "
"solid.".format(
output_name=output_name,
solid=self.solid.name,
outputs_clause="found outputs {output_names}".format(
output_names=str(list(self.solid.definition.output_dict.keys()))
)
if self.solid.definition.output_dict
else "no output mappings were defined",
)
)
output_mapping = self.solid.definition.get_output_mapping(output_name)
return self._result_for_handle(
self.solid.definition.solid_named(output_mapping.maps_from.solid_name),
NodeHandle(output_mapping.maps_from.solid_name, None),
).output_value(output_mapping.maps_from.output_name)
class SolidExecutionResult:
"""Execution result for a leaf solid in a pipeline.
Users should not instantiate this class.
"""
def __init__(
self, solid, step_events_by_kind, reconstruct_context, pipeline_def, output_capture=None
):
check.inst_param(solid, "solid", Node)
check.invariant(
not solid.is_graph,
desc="Tried to instantiate a SolidExecutionResult with a composite solid",
)
self.solid = solid
self.step_events_by_kind = check.dict_param(
step_events_by_kind, "step_events_by_kind", key_type=StepKind, value_type=list
)
self.reconstruct_context = check.callable_param(reconstruct_context, "reconstruct_context")
self.output_capture = check.opt_dict_param(output_capture, "output_capture")
self.pipeline_def = check.inst_param(pipeline_def, "pipeline_def", PipelineDefinition)
@property
def compute_input_event_dict(self):
"""Dict[str, DagsterEvent]: All events of type ``STEP_INPUT``, keyed by input name."""
return {se.event_specific_data.input_name: se for se in self.input_events_during_compute}
@property
def input_events_during_compute(self):
"""List[DagsterEvent]: All events of type ``STEP_INPUT``."""
return self._compute_steps_of_type(DagsterEventType.STEP_INPUT)
def get_output_event_for_compute(self, output_name="result"):
"""The ``STEP_OUTPUT`` event for the given output name.
Throws if not present.
Args:
output_name (Optional[str]): The name of the output. (default: 'result')
Returns:
DagsterEvent: The corresponding event.
"""
events = self.get_output_events_for_compute(output_name)
check.invariant(
len(events) == 1, "Multiple output events returned, use get_output_events_for_compute"
)
return events[0]
@property
def compute_output_events_dict(self):
"""Dict[str, List[DagsterEvent]]: All events of type ``STEP_OUTPUT``, keyed by output name"""
results = defaultdict(list)
for se in self.output_events_during_compute:
results[se.step_output_data.output_name].append(se)
return dict(results)
def get_output_events_for_compute(self, output_name="result"):
"""The ``STEP_OUTPUT`` event for the given output name.
Throws if not present.
Args:
output_name (Optional[str]): The name of the output. (default: 'result')
Returns:
List[DagsterEvent]: The corresponding events.
"""
return self.compute_output_events_dict[output_name]
@property
def output_events_during_compute(self):
"""List[DagsterEvent]: All events of type ``STEP_OUTPUT``."""
return self._compute_steps_of_type(DagsterEventType.STEP_OUTPUT)
@property
def compute_step_events(self):
"""List[DagsterEvent]: All events generated by execution of the solid compute function."""
return self.step_events_by_kind.get(StepKind.COMPUTE, [])
@property
def step_events(self):
return self.compute_step_events
@property
def materializations_during_compute(self):
"""List[Materialization]: All materializations yielded by the solid."""
return [
mat_event.event_specific_data.materialization
for mat_event in self.materialization_events_during_compute
]
@property
def materialization_events_during_compute(self):
"""List[DagsterEvent]: All events of type ``ASSET_MATERIALIZATION``."""
return self._compute_steps_of_type(DagsterEventType.ASSET_MATERIALIZATION)
@property
def expectation_events_during_compute(self):
"""List[DagsterEvent]: All events of type ``STEP_EXPECTATION_RESULT``."""
return self._compute_steps_of_type(DagsterEventType.STEP_EXPECTATION_RESULT)
def _compute_steps_of_type(self, dagster_event_type):
return list(
filter(lambda se: se.event_type == dagster_event_type, self.compute_step_events)
)
@property
def expectation_results_during_compute(self):
"""List[ExpectationResult]: All expectation results yielded by the solid"""
return [
expt_event.event_specific_data.expectation_result
for expt_event in self.expectation_events_during_compute
]
def get_step_success_event(self):
"""DagsterEvent: The ``STEP_SUCCESS`` event, throws if not present."""
for step_event in self.compute_step_events:
if step_event.event_type == DagsterEventType.STEP_SUCCESS:
return step_event
check.failed("Step success not found for solid {}".format(self.solid.name))
@property
def compute_step_failure_event(self):
"""DagsterEvent: The ``STEP_FAILURE`` event, throws if it did not fail."""
if self.success:
raise DagsterInvariantViolationError(
"Cannot call compute_step_failure_event if successful"
)
step_failure_events = self._compute_steps_of_type(DagsterEventType.STEP_FAILURE)
check.invariant(len(step_failure_events) == 1)
return step_failure_events[0]
@property
def success(self):
"""bool: Whether solid execution was successful."""
any_success = False
for step_event in self.compute_step_events:
if step_event.event_type == DagsterEventType.STEP_FAILURE:
return False
if step_event.event_type == DagsterEventType.STEP_SUCCESS:
any_success = True
return any_success
@property
def skipped(self):
"""bool: Whether solid execution was skipped."""
return all(
[
step_event.event_type == DagsterEventType.STEP_SKIPPED
for step_event in self.compute_step_events
]
)
@property
def output_values(self):
"""Union[None, Dict[str, Union[Any, Dict[str, Any]]]: The computed output values.
Returns ``None`` if execution did not succeed.
Returns a dictionary where keys are output names and the values are:
* the output values in the normal case
* a dictionary from mapping key to corresponding value in the mapped case
Note that accessing this property will reconstruct the pipeline context (including, e.g.,
resources) to retrieve materialized output values.
"""
if not self.success or not self.compute_step_events:
return None
results = {}
with self.reconstruct_context() as context:
for compute_step_event in self.compute_step_events:
if compute_step_event.is_successful_output:
output = compute_step_event.step_output_data
step = context.execution_plan.get_step_by_key(compute_step_event.step_key)
value = self._get_value(context.for_step(step), output)
check.invariant(
not (output.mapping_key and step.get_mapping_key()),
"Not set up to handle mapped outputs downstream of mapped steps",
)
mapping_key = output.mapping_key or step.get_mapping_key()
if mapping_key:
if results.get(output.output_name) is None:
results[output.output_name] = {mapping_key: value}
else:
results[output.output_name][mapping_key] = value
else:
results[output.output_name] = value
return results
def output_value(self, output_name=DEFAULT_OUTPUT):
"""Get a computed output value.
Note that calling this method will reconstruct the pipeline context (including, e.g.,
resources) to retrieve materialized output values.
Args:
output_name(str): The output name for which to retrieve the value. (default: 'result')
Returns:
Union[None, Any, Dict[str, Any]]: ``None`` if execution did not succeed, the output value
in the normal case, and a dict of mapping keys to values in the mapped case.
"""
check.str_param(output_name, "output_name")
if not self.solid.definition.has_output(output_name):
raise DagsterInvariantViolationError(
"Output '{output_name}' not defined in solid '{solid}': found outputs "
"{output_names}".format(
output_name=output_name,
solid=self.solid.name,
output_names=str(list(self.solid.definition.output_dict.keys())),
)
)
if not self.success:
return None
with self.reconstruct_context() as context:
found = False
result = None
for compute_step_event in self.compute_step_events:
if (
compute_step_event.is_successful_output
and compute_step_event.step_output_data.output_name == output_name
):
found = True
output = compute_step_event.step_output_data
step = context.execution_plan.get_step_by_key(compute_step_event.step_key)
value = self._get_value(context.for_step(step), output)
check.invariant(
not (output.mapping_key and step.get_mapping_key()),
"Not set up to handle mapped outputs downstream of mapped steps",
)
mapping_key = output.mapping_key or step.get_mapping_key()
if mapping_key:
if result is None:
result = {mapping_key: value}
else:
result[
mapping_key
] = value # pylint:disable=unsupported-assignment-operation
else:
result = value
if found:
return result
raise DagsterInvariantViolationError(
(
"Did not find result {output_name} in solid {self.solid.name} "
"execution result"
).format(output_name=output_name, self=self)
)
def _get_value(self, context, step_output_data):
step_output_handle = step_output_data.step_output_handle
# output capture dictionary will only have values in the in process case, but will not have
# values from steps launched via step launcher.
if self.output_capture and step_output_handle in self.output_capture:
return self.output_capture[step_output_handle]
manager = context.get_io_manager(step_output_handle)
manager_key = context.execution_plan.get_manager_key(step_output_handle, self.pipeline_def)
res = manager.load_input(
context.for_input_manager(
name=None,
config=None,
metadata=None,
dagster_type=self.solid.output_def_named(step_output_data.output_name).dagster_type,
source_handle=step_output_handle,
resource_config=context.resolved_run_config.resources[manager_key].config,
resources=build_resources_for_manager(manager_key, context),
)
)
return res
@property
def failure_data(self):
"""Union[None, StepFailureData]: Any data corresponding to this step's failure, if it
failed."""
for step_event in self.compute_step_events:
if step_event.event_type == DagsterEventType.STEP_FAILURE:
return step_event.step_failure_data
@property
def retry_attempts(self) -> int:
"""Number of times this step retried"""
count = 0
for step_event in self.compute_step_events:
if step_event.event_type == DagsterEventType.STEP_RESTARTED:
count += 1
return count
| 39.426621 | 101 | 0.639673 | from collections import defaultdict
import dagster._check as check
from dagster.core.definitions import GraphDefinition, Node, NodeHandle, PipelineDefinition
from dagster.core.definitions.utils import DEFAULT_OUTPUT
from dagster.core.errors import DagsterInvariantViolationError
from dagster.core.events import DagsterEvent, DagsterEventType
from dagster.core.execution.plan.outputs import StepOutputHandle
from dagster.core.execution.plan.step import StepKind
from dagster.core.execution.plan.utils import build_resources_for_manager
def _construct_events_by_step_key(event_list):
events_by_step_key = defaultdict(list)
for event in event_list:
events_by_step_key[event.step_key].append(event)
return dict(events_by_step_key)
class GraphExecutionResult:
def __init__(
self,
container,
event_list,
reconstruct_context,
pipeline_def,
handle=None,
output_capture=None,
):
self.container = check.inst_param(container, "container", GraphDefinition)
self.event_list = check.list_param(event_list, "step_event_list", of_type=DagsterEvent)
self.reconstruct_context = check.callable_param(reconstruct_context, "reconstruct_context")
self.pipeline_def = check.inst_param(pipeline_def, "pipeline_def", PipelineDefinition)
self.handle = check.opt_inst_param(handle, "handle", NodeHandle)
self.output_capture = check.opt_dict_param(
output_capture, "output_capture", key_type=StepOutputHandle
)
self._events_by_step_key = _construct_events_by_step_key(event_list)
@property
def success(self):
return all([not event.is_failure for event in self.event_list])
@property
def step_event_list(self):
return [event for event in self.event_list if event.is_step_event]
@property
def events_by_step_key(self):
return self._events_by_step_key
def result_for_solid(self, name):
if not self.container.has_solid_named(name):
raise DagsterInvariantViolationError(
"Tried to get result for solid '{name}' in '{container}'. No such top level "
"solid.".format(name=name, container=self.container.name)
)
return self.result_for_handle(NodeHandle(name, None))
def output_for_solid(self, handle_str, output_name=DEFAULT_OUTPUT):
check.str_param(handle_str, "handle_str")
check.str_param(output_name, "output_name")
return self.result_for_handle(NodeHandle.from_string(handle_str)).output_value(output_name)
@property
def solid_result_list(self):
return [self.result_for_solid(solid.name) for solid in self.container.solids]
def _result_for_handle(self, solid, handle):
if not solid:
raise DagsterInvariantViolationError(
"Can not find solid handle {handle_str}.".format(handle_str=handle.to_string())
)
events_by_kind = defaultdict(list)
if solid.is_graph:
events = []
for event in self.event_list:
if event.is_step_event:
if event.solid_handle.is_or_descends_from(handle.with_ancestor(self.handle)):
events_by_kind[event.step_kind].append(event)
events.append(event)
return CompositeSolidExecutionResult(
solid,
events,
events_by_kind,
self.reconstruct_context,
self.pipeline_def,
handle=handle.with_ancestor(self.handle),
output_capture=self.output_capture,
)
else:
for event in self.event_list:
if event.is_step_event:
if event.solid_handle.is_or_descends_from(handle.with_ancestor(self.handle)):
events_by_kind[event.step_kind].append(event)
return SolidExecutionResult(
solid,
events_by_kind,
self.reconstruct_context,
self.pipeline_def,
output_capture=self.output_capture,
)
def result_for_handle(self, handle):
if isinstance(handle, str):
handle = NodeHandle.from_string(handle)
else:
check.inst_param(handle, "handle", NodeHandle)
solid = self.container.get_solid(handle)
return self._result_for_handle(solid, handle)
class PipelineExecutionResult(GraphExecutionResult):
def __init__(
self,
pipeline_def,
run_id,
event_list,
reconstruct_context,
output_capture=None,
):
self.run_id = check.str_param(run_id, "run_id")
check.inst_param(pipeline_def, "pipeline_def", PipelineDefinition)
super(PipelineExecutionResult, self).__init__(
container=pipeline_def.graph,
event_list=event_list,
reconstruct_context=reconstruct_context,
pipeline_def=pipeline_def,
output_capture=output_capture,
)
class CompositeSolidExecutionResult(GraphExecutionResult):
def __init__(
self,
solid,
event_list,
step_events_by_kind,
reconstruct_context,
pipeline_def,
handle=None,
output_capture=None,
):
check.inst_param(solid, "solid", Node)
check.invariant(
solid.is_graph,
desc="Tried to instantiate a CompositeSolidExecutionResult with a noncomposite solid",
)
self.solid = solid
self.step_events_by_kind = check.dict_param(
step_events_by_kind, "step_events_by_kind", key_type=StepKind, value_type=list
)
self.output_capture = check.opt_dict_param(
output_capture, "output_capture", key_type=StepOutputHandle
)
super(CompositeSolidExecutionResult, self).__init__(
container=solid.definition,
event_list=event_list,
reconstruct_context=reconstruct_context,
pipeline_def=pipeline_def,
handle=handle,
output_capture=output_capture,
)
def output_values_for_solid(self, name):
check.str_param(name, "name")
return self.result_for_solid(name).output_values
def output_values_for_handle(self, handle_str):
check.str_param(handle_str, "handle_str")
return self.result_for_handle(handle_str).output_values
def output_value_for_solid(self, name, output_name=DEFAULT_OUTPUT):
check.str_param(name, "name")
check.str_param(output_name, "output_name")
return self.result_for_solid(name).output_value(output_name)
def output_value_for_handle(self, handle_str, output_name=DEFAULT_OUTPUT):
check.str_param(handle_str, "handle_str")
check.str_param(output_name, "output_name")
return self.result_for_handle(handle_str).output_value(output_name)
@property
def output_values(self):
values = {}
for output_name in self.solid.definition.output_dict:
output_mapping = self.solid.definition.get_output_mapping(output_name)
inner_solid_values = self._result_for_handle(
self.solid.definition.solid_named(output_mapping.maps_from.solid_name),
NodeHandle(output_mapping.maps_from.solid_name, None),
).output_values
if inner_solid_values is not None:
if output_mapping.maps_from.output_name in inner_solid_values:
values[output_name] = inner_solid_values[output_mapping.maps_from.output_name]
return values
def output_value(self, output_name=DEFAULT_OUTPUT):
check.str_param(output_name, "output_name")
if not self.solid.definition.has_output(output_name):
raise DagsterInvariantViolationError(
"Output '{output_name}' not defined in composite solid '{solid}': "
"{outputs_clause}. If you were expecting this output to be present, you may "
"be missing an output_mapping from an inner solid to its enclosing composite "
"solid.".format(
output_name=output_name,
solid=self.solid.name,
outputs_clause="found outputs {output_names}".format(
output_names=str(list(self.solid.definition.output_dict.keys()))
)
if self.solid.definition.output_dict
else "no output mappings were defined",
)
)
output_mapping = self.solid.definition.get_output_mapping(output_name)
return self._result_for_handle(
self.solid.definition.solid_named(output_mapping.maps_from.solid_name),
NodeHandle(output_mapping.maps_from.solid_name, None),
).output_value(output_mapping.maps_from.output_name)
class SolidExecutionResult:
def __init__(
self, solid, step_events_by_kind, reconstruct_context, pipeline_def, output_capture=None
):
check.inst_param(solid, "solid", Node)
check.invariant(
not solid.is_graph,
desc="Tried to instantiate a SolidExecutionResult with a composite solid",
)
self.solid = solid
self.step_events_by_kind = check.dict_param(
step_events_by_kind, "step_events_by_kind", key_type=StepKind, value_type=list
)
self.reconstruct_context = check.callable_param(reconstruct_context, "reconstruct_context")
self.output_capture = check.opt_dict_param(output_capture, "output_capture")
self.pipeline_def = check.inst_param(pipeline_def, "pipeline_def", PipelineDefinition)
@property
def compute_input_event_dict(self):
return {se.event_specific_data.input_name: se for se in self.input_events_during_compute}
@property
def input_events_during_compute(self):
return self._compute_steps_of_type(DagsterEventType.STEP_INPUT)
def get_output_event_for_compute(self, output_name="result"):
events = self.get_output_events_for_compute(output_name)
check.invariant(
len(events) == 1, "Multiple output events returned, use get_output_events_for_compute"
)
return events[0]
@property
def compute_output_events_dict(self):
results = defaultdict(list)
for se in self.output_events_during_compute:
results[se.step_output_data.output_name].append(se)
return dict(results)
def get_output_events_for_compute(self, output_name="result"):
return self.compute_output_events_dict[output_name]
@property
def output_events_during_compute(self):
return self._compute_steps_of_type(DagsterEventType.STEP_OUTPUT)
@property
def compute_step_events(self):
return self.step_events_by_kind.get(StepKind.COMPUTE, [])
@property
def step_events(self):
return self.compute_step_events
@property
def materializations_during_compute(self):
return [
mat_event.event_specific_data.materialization
for mat_event in self.materialization_events_during_compute
]
@property
def materialization_events_during_compute(self):
return self._compute_steps_of_type(DagsterEventType.ASSET_MATERIALIZATION)
@property
def expectation_events_during_compute(self):
return self._compute_steps_of_type(DagsterEventType.STEP_EXPECTATION_RESULT)
def _compute_steps_of_type(self, dagster_event_type):
return list(
filter(lambda se: se.event_type == dagster_event_type, self.compute_step_events)
)
@property
def expectation_results_during_compute(self):
return [
expt_event.event_specific_data.expectation_result
for expt_event in self.expectation_events_during_compute
]
def get_step_success_event(self):
for step_event in self.compute_step_events:
if step_event.event_type == DagsterEventType.STEP_SUCCESS:
return step_event
check.failed("Step success not found for solid {}".format(self.solid.name))
@property
def compute_step_failure_event(self):
if self.success:
raise DagsterInvariantViolationError(
"Cannot call compute_step_failure_event if successful"
)
step_failure_events = self._compute_steps_of_type(DagsterEventType.STEP_FAILURE)
check.invariant(len(step_failure_events) == 1)
return step_failure_events[0]
@property
def success(self):
any_success = False
for step_event in self.compute_step_events:
if step_event.event_type == DagsterEventType.STEP_FAILURE:
return False
if step_event.event_type == DagsterEventType.STEP_SUCCESS:
any_success = True
return any_success
@property
def skipped(self):
return all(
[
step_event.event_type == DagsterEventType.STEP_SKIPPED
for step_event in self.compute_step_events
]
)
@property
def output_values(self):
if not self.success or not self.compute_step_events:
return None
results = {}
with self.reconstruct_context() as context:
for compute_step_event in self.compute_step_events:
if compute_step_event.is_successful_output:
output = compute_step_event.step_output_data
step = context.execution_plan.get_step_by_key(compute_step_event.step_key)
value = self._get_value(context.for_step(step), output)
check.invariant(
not (output.mapping_key and step.get_mapping_key()),
"Not set up to handle mapped outputs downstream of mapped steps",
)
mapping_key = output.mapping_key or step.get_mapping_key()
if mapping_key:
if results.get(output.output_name) is None:
results[output.output_name] = {mapping_key: value}
else:
results[output.output_name][mapping_key] = value
else:
results[output.output_name] = value
return results
def output_value(self, output_name=DEFAULT_OUTPUT):
check.str_param(output_name, "output_name")
if not self.solid.definition.has_output(output_name):
raise DagsterInvariantViolationError(
"Output '{output_name}' not defined in solid '{solid}': found outputs "
"{output_names}".format(
output_name=output_name,
solid=self.solid.name,
output_names=str(list(self.solid.definition.output_dict.keys())),
)
)
if not self.success:
return None
with self.reconstruct_context() as context:
found = False
result = None
for compute_step_event in self.compute_step_events:
if (
compute_step_event.is_successful_output
and compute_step_event.step_output_data.output_name == output_name
):
found = True
output = compute_step_event.step_output_data
step = context.execution_plan.get_step_by_key(compute_step_event.step_key)
value = self._get_value(context.for_step(step), output)
check.invariant(
not (output.mapping_key and step.get_mapping_key()),
"Not set up to handle mapped outputs downstream of mapped steps",
)
mapping_key = output.mapping_key or step.get_mapping_key()
if mapping_key:
if result is None:
result = {mapping_key: value}
else:
result[
mapping_key
] = value
else:
result = value
if found:
return result
raise DagsterInvariantViolationError(
(
"Did not find result {output_name} in solid {self.solid.name} "
"execution result"
).format(output_name=output_name, self=self)
)
def _get_value(self, context, step_output_data):
step_output_handle = step_output_data.step_output_handle
if self.output_capture and step_output_handle in self.output_capture:
return self.output_capture[step_output_handle]
manager = context.get_io_manager(step_output_handle)
manager_key = context.execution_plan.get_manager_key(step_output_handle, self.pipeline_def)
res = manager.load_input(
context.for_input_manager(
name=None,
config=None,
metadata=None,
dagster_type=self.solid.output_def_named(step_output_data.output_name).dagster_type,
source_handle=step_output_handle,
resource_config=context.resolved_run_config.resources[manager_key].config,
resources=build_resources_for_manager(manager_key, context),
)
)
return res
@property
def failure_data(self):
for step_event in self.compute_step_events:
if step_event.event_type == DagsterEventType.STEP_FAILURE:
return step_event.step_failure_data
@property
def retry_attempts(self) -> int:
count = 0
for step_event in self.compute_step_events:
if step_event.event_type == DagsterEventType.STEP_RESTARTED:
count += 1
return count
| true | true |
f7f6d8e7fd959f789b5934802eca42d7c19b3bc8 | 716 | py | Python | guitarfan/__init__.py | timgates42/GuitarFan | 1a6d6bcc7708cbb214648e7f5657728f6c27c48a | [
"MIT"
] | 48 | 2015-02-02T02:25:07.000Z | 2022-03-11T12:39:39.000Z | guitarfan/__init__.py | timgates42/GuitarFan | 1a6d6bcc7708cbb214648e7f5657728f6c27c48a | [
"MIT"
] | 2 | 2015-09-13T14:00:41.000Z | 2021-08-04T16:28:25.000Z | guitarfan/__init__.py | timgates42/GuitarFan | 1a6d6bcc7708cbb214648e7f5657728f6c27c48a | [
"MIT"
] | 16 | 2015-01-09T08:15:13.000Z | 2020-06-20T11:07:49.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask
def create_app(config):
# init Flask application object
app = Flask(__name__)
app.config.from_object(config)
# init flask-login
from guitarfan.extensions.flasklogin import login_manager
login_manager.init_app(app)
# init flask-sqlalchemy
from guitarfan.extensions.flasksqlalchemy import db
db.app = app # if without it, db query operation will throw exception in Form class
db.init_app(app)
# init flask-cache
from guitarfan.extensions.flaskcache import cache
cache.init_app(app)
# register all blueprints
import controlers
controlers.Register_Blueprints(app)
return app
| 24.689655 | 87 | 0.72067 |
from flask import Flask
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
from guitarfan.extensions.flasklogin import login_manager
login_manager.init_app(app)
from guitarfan.extensions.flasksqlalchemy import db
db.app = app
db.init_app(app)
from guitarfan.extensions.flaskcache import cache
cache.init_app(app)
import controlers
controlers.Register_Blueprints(app)
return app
| true | true |
f7f6d93bc2c5a101572a4ef4baa16802cd9cb9bd | 1,886 | py | Python | engine/parser/knowledgeParser.py | ariyo21/Expert-System | 75a76940f9ad12c45a51b4cd34df361857a2a741 | [
"MIT"
] | 5 | 2020-11-07T14:41:16.000Z | 2022-01-18T19:50:52.000Z | engine/parser/knowledgeParser.py | ariyo21/Expert-System | 75a76940f9ad12c45a51b4cd34df361857a2a741 | [
"MIT"
] | null | null | null | engine/parser/knowledgeParser.py | ariyo21/Expert-System | 75a76940f9ad12c45a51b4cd34df361857a2a741 | [
"MIT"
] | 4 | 2020-11-19T11:24:44.000Z | 2021-05-11T11:16:59.000Z | """
This file will parse the input text file and get important
knowledge from it and create a database known as Knowledge Base
"""
import json
import os
from engine.components.knowledge import Knowledge
from engine.logger.logger import Log
class KnowledgeBaseParser:
"""
Class the parse the file and create the Knowledge object list
Attributes
----------
__knowledgeBase : list
list of the Knowledge objects
"""
def __init__(self):
self.__knowledgeBase = list()
def __parseInputFile(self, inputFile):
"""
Reads the `knowledge.json` and retrieves the target and the rules for the target
Parameters
----------
inputFile : str
name and path of the file to parsse
Returns
-------
list
list of the Knowledge objects
"""
# checking if the file exists
if os.path.isfile(inputFile) is False:
Log.e(f"Knowledge file {inputFile} does not exists")
return
# reading the file
with open(inputFile, "r") as file:
file = json.load(file)
for knowledge in file['target']:
knowledgeBase = Knowledge()
for rule in knowledge['rules']:
knowledgeBase.addRule(target=knowledge['name'],
rule=knowledge['rules'][rule])
self.__knowledgeBase.append(knowledgeBase)
return self.__knowledgeBase
def getKnowledgeBase(self, inputFile):
"""
Parsing the input file and returning the list
Parameters
----------
inputFile : str
name and path of the file to parse
Returns
-------
list
list of the Knowledge objects
"""
return self.__parseInputFile(inputFile)
| 25.835616 | 88 | 0.572641 |
import json
import os
from engine.components.knowledge import Knowledge
from engine.logger.logger import Log
class KnowledgeBaseParser:
def __init__(self):
self.__knowledgeBase = list()
def __parseInputFile(self, inputFile):
if os.path.isfile(inputFile) is False:
Log.e(f"Knowledge file {inputFile} does not exists")
return
with open(inputFile, "r") as file:
file = json.load(file)
for knowledge in file['target']:
knowledgeBase = Knowledge()
for rule in knowledge['rules']:
knowledgeBase.addRule(target=knowledge['name'],
rule=knowledge['rules'][rule])
self.__knowledgeBase.append(knowledgeBase)
return self.__knowledgeBase
def getKnowledgeBase(self, inputFile):
return self.__parseInputFile(inputFile)
| true | true |
f7f6d971b09ead6fa597d2f35d468e7a5cb1af79 | 1,127 | py | Python | build-2048-in-python/colors.py | dapopov-st/python-youtube-code | 770c9291988898f259ad28bbab5989acee8fb830 | [
"MIT"
] | 262 | 2020-03-17T03:24:35.000Z | 2022-03-22T12:50:02.000Z | build-2048-in-python/colors.py | dapopov-st/python-youtube-code | 770c9291988898f259ad28bbab5989acee8fb830 | [
"MIT"
] | 14 | 2020-07-12T14:17:36.000Z | 2022-03-21T09:38:45.000Z | build-2048-in-python/colors.py | dapopov-st/python-youtube-code | 770c9291988898f259ad28bbab5989acee8fb830 | [
"MIT"
] | 583 | 2020-02-12T17:54:21.000Z | 2022-03-30T03:59:21.000Z | GRID_COLOR = "#a39489"
EMPTY_CELL_COLOR = "#c2b3a9"
SCORE_LABEL_FONT = ("Verdana", 20)
SCORE_FONT = ("Helvetica", 32, "bold")
GAME_OVER_FONT = ("Helvetica", 48, "bold")
GAME_OVER_FONT_COLOR = "#ffffff"
WINNER_BG = "#ffcc00"
LOSER_BG = "#a39489"
CELL_COLORS = {
2: "#fcefe6",
4: "#f2e8cb",
8: "#f5b682",
16: "#f29446",
32: "#ff775c",
64: "#e64c2e",
128: "#ede291",
256: "#fce130",
512: "#ffdb4a",
1024: "#f0b922",
2048: "#fad74d"
}
CELL_NUMBER_COLORS = {
2: "#695c57",
4: "#695c57",
8: "#ffffff",
16: "#ffffff",
32: "#ffffff",
64: "#ffffff",
128: "#ffffff",
256: "#ffffff",
512: "#ffffff",
1024: "#ffffff",
2048: "#ffffff"
}
CELL_NUMBER_FONTS = {
2: ("Helvetica", 55, "bold"),
4: ("Helvetica", 55, "bold"),
8: ("Helvetica", 55, "bold"),
16: ("Helvetica", 50, "bold"),
32: ("Helvetica", 50, "bold"),
64: ("Helvetica", 50, "bold"),
128: ("Helvetica", 45, "bold"),
256: ("Helvetica", 45, "bold"),
512: ("Helvetica", 45, "bold"),
1024: ("Helvetica", 40, "bold"),
2048: ("Helvetica", 40, "bold")
}
| 22.098039 | 42 | 0.526176 | GRID_COLOR = "#a39489"
EMPTY_CELL_COLOR = "#c2b3a9"
SCORE_LABEL_FONT = ("Verdana", 20)
SCORE_FONT = ("Helvetica", 32, "bold")
GAME_OVER_FONT = ("Helvetica", 48, "bold")
GAME_OVER_FONT_COLOR = "#ffffff"
WINNER_BG = "#ffcc00"
LOSER_BG = "#a39489"
CELL_COLORS = {
2: "#fcefe6",
4: "#f2e8cb",
8: "#f5b682",
16: "#f29446",
32: "#ff775c",
64: "#e64c2e",
128: "#ede291",
256: "#fce130",
512: "#ffdb4a",
1024: "#f0b922",
2048: "#fad74d"
}
CELL_NUMBER_COLORS = {
2: "#695c57",
4: "#695c57",
8: "#ffffff",
16: "#ffffff",
32: "#ffffff",
64: "#ffffff",
128: "#ffffff",
256: "#ffffff",
512: "#ffffff",
1024: "#ffffff",
2048: "#ffffff"
}
CELL_NUMBER_FONTS = {
2: ("Helvetica", 55, "bold"),
4: ("Helvetica", 55, "bold"),
8: ("Helvetica", 55, "bold"),
16: ("Helvetica", 50, "bold"),
32: ("Helvetica", 50, "bold"),
64: ("Helvetica", 50, "bold"),
128: ("Helvetica", 45, "bold"),
256: ("Helvetica", 45, "bold"),
512: ("Helvetica", 45, "bold"),
1024: ("Helvetica", 40, "bold"),
2048: ("Helvetica", 40, "bold")
}
| true | true |
f7f6dace762cd8a557e4b3fcbafd764ea20e3d96 | 9,953 | py | Python | networkx/readwrite/tests/test_shp.py | armando1793/networkx | 48326e1761c08d7a073aec53f7a644baf2249ef6 | [
"BSD-3-Clause"
] | 445 | 2019-01-26T13:50:26.000Z | 2022-03-18T05:17:38.000Z | networkx/readwrite/tests/test_shp.py | armando1793/networkx | 48326e1761c08d7a073aec53f7a644baf2249ef6 | [
"BSD-3-Clause"
] | 242 | 2019-01-29T15:48:27.000Z | 2022-03-31T22:09:21.000Z | networkx/readwrite/tests/test_shp.py | armando1793/networkx | 48326e1761c08d7a073aec53f7a644baf2249ef6 | [
"BSD-3-Clause"
] | 31 | 2019-03-10T09:51:27.000Z | 2022-02-14T23:11:12.000Z | """Unit tests for shp.
"""
import os
import tempfile
from nose import SkipTest
from nose.tools import assert_equal
from nose.tools import raises
import networkx as nx
class TestShp(object):
@classmethod
def setupClass(cls):
global ogr
try:
from osgeo import ogr
except ImportError:
raise SkipTest('ogr not available.')
def deletetmp(self, drv, *paths):
for p in paths:
if os.path.exists(p):
drv.DeleteDataSource(p)
def setUp(self):
def createlayer(driver, layerType=ogr.wkbLineString):
lyr = driver.CreateLayer("edges", None, layerType)
namedef = ogr.FieldDefn("Name", ogr.OFTString)
namedef.SetWidth(32)
lyr.CreateField(namedef)
return lyr
drv = ogr.GetDriverByName("ESRI Shapefile")
testdir = os.path.join(tempfile.gettempdir(), 'shpdir')
shppath = os.path.join(tempfile.gettempdir(), 'tmpshp.shp')
multi_shppath = os.path.join(tempfile.gettempdir(), 'tmp_mshp.shp')
self.deletetmp(drv, testdir, shppath, multi_shppath)
os.mkdir(testdir)
self.names = ['a', 'b', 'c', 'c'] # edgenames
self.paths = ([(1.0, 1.0), (2.0, 2.0)],
[(2.0, 2.0), (3.0, 3.0)],
[(0.9, 0.9), (4.0, 0.9), (4.0, 2.0)])
self.simplified_names = ['a', 'b', 'c'] # edgenames
self.simplified_paths = ([(1.0, 1.0), (2.0, 2.0)],
[(2.0, 2.0), (3.0, 3.0)],
[(0.9, 0.9), (4.0, 2.0)])
self.multi_names = ['a', 'a', 'a', 'a'] # edgenames
shp = drv.CreateDataSource(shppath)
lyr = createlayer(shp)
for path, name in zip(self.paths, self.names):
feat = ogr.Feature(lyr.GetLayerDefn())
g = ogr.Geometry(ogr.wkbLineString)
for p in path:
g.AddPoint_2D(*p)
feat.SetGeometry(g)
feat.SetField("Name", name)
lyr.CreateFeature(feat)
# create single record multiline shapefile for testing
multi_shp = drv.CreateDataSource(multi_shppath)
multi_lyr = createlayer(multi_shp, ogr.wkbMultiLineString)
multi_g = ogr.Geometry(ogr.wkbMultiLineString)
for path in self.paths:
g = ogr.Geometry(ogr.wkbLineString)
for p in path:
g.AddPoint_2D(*p)
multi_g.AddGeometry(g)
multi_feat = ogr.Feature(multi_lyr.GetLayerDefn())
multi_feat.SetGeometry(multi_g)
multi_feat.SetField("Name", 'a')
multi_lyr.CreateFeature(multi_feat)
self.shppath = shppath
self.multi_shppath = multi_shppath
self.testdir = testdir
self.drv = drv
def testload(self):
def compare_graph_paths_names(g, paths, names):
expected = nx.DiGraph()
for p in paths:
nx.add_path(expected, p)
assert_equal(sorted(expected.nodes), sorted(g.nodes))
assert_equal(sorted(expected.edges()), sorted(g.edges()))
g_names = [g.get_edge_data(s, e)['Name'] for s, e in g.edges()]
assert_equal(names, sorted(g_names))
# simplified
G = nx.read_shp(self.shppath)
compare_graph_paths_names(G, self.simplified_paths,
self.simplified_names)
# unsimplified
G = nx.read_shp(self.shppath, simplify=False)
compare_graph_paths_names(G, self.paths, self.names)
# multiline unsimplified
G = nx.read_shp(self.multi_shppath, simplify=False)
compare_graph_paths_names(G, self.paths, self.multi_names)
def checkgeom(self, lyr, expected):
feature = lyr.GetNextFeature()
actualwkt = []
while feature:
actualwkt.append(feature.GetGeometryRef().ExportToWkt())
feature = lyr.GetNextFeature()
assert_equal(sorted(expected), sorted(actualwkt))
def test_geometryexport(self):
expectedpoints_simple = (
"POINT (1 1)",
"POINT (2 2)",
"POINT (3 3)",
"POINT (0.9 0.9)",
"POINT (4 2)"
)
expectedlines_simple = (
"LINESTRING (1 1,2 2)",
"LINESTRING (2 2,3 3)",
"LINESTRING (0.9 0.9,4.0 0.9,4 2)"
)
expectedpoints = (
"POINT (1 1)",
"POINT (2 2)",
"POINT (3 3)",
"POINT (0.9 0.9)",
"POINT (4.0 0.9)",
"POINT (4 2)"
)
expectedlines = (
"LINESTRING (1 1,2 2)",
"LINESTRING (2 2,3 3)",
"LINESTRING (0.9 0.9,4.0 0.9)",
"LINESTRING (4.0 0.9,4 2)"
)
tpath = os.path.join(tempfile.gettempdir(), 'shpdir')
G = nx.read_shp(self.shppath)
nx.write_shp(G, tpath)
shpdir = ogr.Open(tpath)
self.checkgeom(shpdir.GetLayerByName("nodes"), expectedpoints_simple)
self.checkgeom(shpdir.GetLayerByName("edges"), expectedlines_simple)
# Test unsimplified
# Nodes should have additional point,
# edges should be 'flattened'
G = nx.read_shp(self.shppath, simplify=False)
nx.write_shp(G, tpath)
shpdir = ogr.Open(tpath)
self.checkgeom(shpdir.GetLayerByName("nodes"), expectedpoints)
self.checkgeom(shpdir.GetLayerByName("edges"), expectedlines)
def test_attributeexport(self):
def testattributes(lyr, graph):
feature = lyr.GetNextFeature()
while feature:
coords = []
ref = feature.GetGeometryRef()
last = ref.GetPointCount() - 1
edge_nodes = (ref.GetPoint_2D(0), ref.GetPoint_2D(last))
name = feature.GetFieldAsString('Name')
assert_equal(graph.get_edge_data(*edge_nodes)['Name'], name)
feature = lyr.GetNextFeature()
tpath = os.path.join(tempfile.gettempdir(), 'shpdir')
G = nx.read_shp(self.shppath)
nx.write_shp(G, tpath)
shpdir = ogr.Open(tpath)
edges = shpdir.GetLayerByName("edges")
testattributes(edges, G)
# Test export of node attributes in nx.write_shp (#2778)
def test_nodeattributeexport(self):
tpath = os.path.join(tempfile.gettempdir(), 'shpdir')
G = nx.DiGraph()
A = (0, 0)
B = (1, 1)
C = (2, 2)
G.add_edge(A, B)
G.add_edge(A, C)
label = 'node_label'
for n, d in G.nodes(data=True):
d['label'] = label
nx.write_shp(G, tpath)
H = nx.read_shp(tpath)
for n, d in H.nodes(data=True):
assert_equal(d['label'], label)
def test_wkt_export(self):
G = nx.DiGraph()
tpath = os.path.join(tempfile.gettempdir(), 'shpdir')
points = (
"POINT (0.9 0.9)",
"POINT (4 2)"
)
line = (
"LINESTRING (0.9 0.9,4 2)",
)
G.add_node(1, Wkt=points[0])
G.add_node(2, Wkt=points[1])
G.add_edge(1, 2, Wkt=line[0])
try:
nx.write_shp(G, tpath)
except Exception as e:
assert False, e
shpdir = ogr.Open(tpath)
self.checkgeom(shpdir.GetLayerByName("nodes"), points)
self.checkgeom(shpdir.GetLayerByName("edges"), line)
def tearDown(self):
self.deletetmp(self.drv, self.testdir, self.shppath)
@raises(RuntimeError)
def test_read_shp_nofile():
try:
from osgeo import ogr
except ImportError:
raise SkipTest('ogr not available.')
G = nx.read_shp("hopefully_this_file_will_not_be_available")
class TestMissingGeometry(object):
@classmethod
def setup_class(cls):
global ogr
try:
from osgeo import ogr
except ImportError:
raise SkipTest('ogr not available.')
def setUp(self):
self.setup_path()
self.delete_shapedir()
self.create_shapedir()
def tearDown(self):
self.delete_shapedir()
def setup_path(self):
self.path = os.path.join(tempfile.gettempdir(), 'missing_geometry')
def create_shapedir(self):
drv = ogr.GetDriverByName("ESRI Shapefile")
shp = drv.CreateDataSource(self.path)
lyr = shp.CreateLayer("nodes", None, ogr.wkbPoint)
feature = ogr.Feature(lyr.GetLayerDefn())
feature.SetGeometry(None)
lyr.CreateFeature(feature)
feature.Destroy()
def delete_shapedir(self):
drv = ogr.GetDriverByName("ESRI Shapefile")
if os.path.exists(self.path):
drv.DeleteDataSource(self.path)
@raises(nx.NetworkXError)
def test_missing_geometry(self):
G = nx.read_shp(self.path)
class TestMissingAttrWrite(object):
@classmethod
def setup_class(cls):
global ogr
try:
from osgeo import ogr
except ImportError:
raise SkipTest('ogr not available.')
def setUp(self):
self.setup_path()
self.delete_shapedir()
def tearDown(self):
self.delete_shapedir()
def setup_path(self):
self.path = os.path.join(tempfile.gettempdir(), 'missing_attributes')
def delete_shapedir(self):
drv = ogr.GetDriverByName("ESRI Shapefile")
if os.path.exists(self.path):
drv.DeleteDataSource(self.path)
def test_missing_attributes(self):
G = nx.DiGraph()
A = (0, 0)
B = (1, 1)
C = (2, 2)
G.add_edge(A, B, foo=100)
G.add_edge(A, C)
nx.write_shp(G, self.path)
H = nx.read_shp(self.path)
for u, v, d in H.edges(data=True):
if u == A and v == B:
assert_equal(d['foo'], 100)
if u == A and v == C:
assert_equal(d['foo'], None)
| 31.103125 | 77 | 0.560233 |
import os
import tempfile
from nose import SkipTest
from nose.tools import assert_equal
from nose.tools import raises
import networkx as nx
class TestShp(object):
@classmethod
def setupClass(cls):
global ogr
try:
from osgeo import ogr
except ImportError:
raise SkipTest('ogr not available.')
def deletetmp(self, drv, *paths):
for p in paths:
if os.path.exists(p):
drv.DeleteDataSource(p)
def setUp(self):
def createlayer(driver, layerType=ogr.wkbLineString):
lyr = driver.CreateLayer("edges", None, layerType)
namedef = ogr.FieldDefn("Name", ogr.OFTString)
namedef.SetWidth(32)
lyr.CreateField(namedef)
return lyr
drv = ogr.GetDriverByName("ESRI Shapefile")
testdir = os.path.join(tempfile.gettempdir(), 'shpdir')
shppath = os.path.join(tempfile.gettempdir(), 'tmpshp.shp')
multi_shppath = os.path.join(tempfile.gettempdir(), 'tmp_mshp.shp')
self.deletetmp(drv, testdir, shppath, multi_shppath)
os.mkdir(testdir)
self.names = ['a', 'b', 'c', 'c']
self.paths = ([(1.0, 1.0), (2.0, 2.0)],
[(2.0, 2.0), (3.0, 3.0)],
[(0.9, 0.9), (4.0, 0.9), (4.0, 2.0)])
self.simplified_names = ['a', 'b', 'c']
self.simplified_paths = ([(1.0, 1.0), (2.0, 2.0)],
[(2.0, 2.0), (3.0, 3.0)],
[(0.9, 0.9), (4.0, 2.0)])
self.multi_names = ['a', 'a', 'a', 'a']
shp = drv.CreateDataSource(shppath)
lyr = createlayer(shp)
for path, name in zip(self.paths, self.names):
feat = ogr.Feature(lyr.GetLayerDefn())
g = ogr.Geometry(ogr.wkbLineString)
for p in path:
g.AddPoint_2D(*p)
feat.SetGeometry(g)
feat.SetField("Name", name)
lyr.CreateFeature(feat)
multi_shp = drv.CreateDataSource(multi_shppath)
multi_lyr = createlayer(multi_shp, ogr.wkbMultiLineString)
multi_g = ogr.Geometry(ogr.wkbMultiLineString)
for path in self.paths:
g = ogr.Geometry(ogr.wkbLineString)
for p in path:
g.AddPoint_2D(*p)
multi_g.AddGeometry(g)
multi_feat = ogr.Feature(multi_lyr.GetLayerDefn())
multi_feat.SetGeometry(multi_g)
multi_feat.SetField("Name", 'a')
multi_lyr.CreateFeature(multi_feat)
self.shppath = shppath
self.multi_shppath = multi_shppath
self.testdir = testdir
self.drv = drv
def testload(self):
def compare_graph_paths_names(g, paths, names):
expected = nx.DiGraph()
for p in paths:
nx.add_path(expected, p)
assert_equal(sorted(expected.nodes), sorted(g.nodes))
assert_equal(sorted(expected.edges()), sorted(g.edges()))
g_names = [g.get_edge_data(s, e)['Name'] for s, e in g.edges()]
assert_equal(names, sorted(g_names))
G = nx.read_shp(self.shppath)
compare_graph_paths_names(G, self.simplified_paths,
self.simplified_names)
G = nx.read_shp(self.shppath, simplify=False)
compare_graph_paths_names(G, self.paths, self.names)
G = nx.read_shp(self.multi_shppath, simplify=False)
compare_graph_paths_names(G, self.paths, self.multi_names)
def checkgeom(self, lyr, expected):
feature = lyr.GetNextFeature()
actualwkt = []
while feature:
actualwkt.append(feature.GetGeometryRef().ExportToWkt())
feature = lyr.GetNextFeature()
assert_equal(sorted(expected), sorted(actualwkt))
def test_geometryexport(self):
expectedpoints_simple = (
"POINT (1 1)",
"POINT (2 2)",
"POINT (3 3)",
"POINT (0.9 0.9)",
"POINT (4 2)"
)
expectedlines_simple = (
"LINESTRING (1 1,2 2)",
"LINESTRING (2 2,3 3)",
"LINESTRING (0.9 0.9,4.0 0.9,4 2)"
)
expectedpoints = (
"POINT (1 1)",
"POINT (2 2)",
"POINT (3 3)",
"POINT (0.9 0.9)",
"POINT (4.0 0.9)",
"POINT (4 2)"
)
expectedlines = (
"LINESTRING (1 1,2 2)",
"LINESTRING (2 2,3 3)",
"LINESTRING (0.9 0.9,4.0 0.9)",
"LINESTRING (4.0 0.9,4 2)"
)
tpath = os.path.join(tempfile.gettempdir(), 'shpdir')
G = nx.read_shp(self.shppath)
nx.write_shp(G, tpath)
shpdir = ogr.Open(tpath)
self.checkgeom(shpdir.GetLayerByName("nodes"), expectedpoints_simple)
self.checkgeom(shpdir.GetLayerByName("edges"), expectedlines_simple)
G = nx.read_shp(self.shppath, simplify=False)
nx.write_shp(G, tpath)
shpdir = ogr.Open(tpath)
self.checkgeom(shpdir.GetLayerByName("nodes"), expectedpoints)
self.checkgeom(shpdir.GetLayerByName("edges"), expectedlines)
def test_attributeexport(self):
def testattributes(lyr, graph):
feature = lyr.GetNextFeature()
while feature:
coords = []
ref = feature.GetGeometryRef()
last = ref.GetPointCount() - 1
edge_nodes = (ref.GetPoint_2D(0), ref.GetPoint_2D(last))
name = feature.GetFieldAsString('Name')
assert_equal(graph.get_edge_data(*edge_nodes)['Name'], name)
feature = lyr.GetNextFeature()
tpath = os.path.join(tempfile.gettempdir(), 'shpdir')
G = nx.read_shp(self.shppath)
nx.write_shp(G, tpath)
shpdir = ogr.Open(tpath)
edges = shpdir.GetLayerByName("edges")
testattributes(edges, G)
ef test_nodeattributeexport(self):
tpath = os.path.join(tempfile.gettempdir(), 'shpdir')
G = nx.DiGraph()
A = (0, 0)
B = (1, 1)
C = (2, 2)
G.add_edge(A, B)
G.add_edge(A, C)
label = 'node_label'
for n, d in G.nodes(data=True):
d['label'] = label
nx.write_shp(G, tpath)
H = nx.read_shp(tpath)
for n, d in H.nodes(data=True):
assert_equal(d['label'], label)
def test_wkt_export(self):
G = nx.DiGraph()
tpath = os.path.join(tempfile.gettempdir(), 'shpdir')
points = (
"POINT (0.9 0.9)",
"POINT (4 2)"
)
line = (
"LINESTRING (0.9 0.9,4 2)",
)
G.add_node(1, Wkt=points[0])
G.add_node(2, Wkt=points[1])
G.add_edge(1, 2, Wkt=line[0])
try:
nx.write_shp(G, tpath)
except Exception as e:
assert False, e
shpdir = ogr.Open(tpath)
self.checkgeom(shpdir.GetLayerByName("nodes"), points)
self.checkgeom(shpdir.GetLayerByName("edges"), line)
def tearDown(self):
self.deletetmp(self.drv, self.testdir, self.shppath)
@raises(RuntimeError)
def test_read_shp_nofile():
try:
from osgeo import ogr
except ImportError:
raise SkipTest('ogr not available.')
G = nx.read_shp("hopefully_this_file_will_not_be_available")
class TestMissingGeometry(object):
@classmethod
def setup_class(cls):
global ogr
try:
from osgeo import ogr
except ImportError:
raise SkipTest('ogr not available.')
def setUp(self):
self.setup_path()
self.delete_shapedir()
self.create_shapedir()
def tearDown(self):
self.delete_shapedir()
def setup_path(self):
self.path = os.path.join(tempfile.gettempdir(), 'missing_geometry')
def create_shapedir(self):
drv = ogr.GetDriverByName("ESRI Shapefile")
shp = drv.CreateDataSource(self.path)
lyr = shp.CreateLayer("nodes", None, ogr.wkbPoint)
feature = ogr.Feature(lyr.GetLayerDefn())
feature.SetGeometry(None)
lyr.CreateFeature(feature)
feature.Destroy()
def delete_shapedir(self):
drv = ogr.GetDriverByName("ESRI Shapefile")
if os.path.exists(self.path):
drv.DeleteDataSource(self.path)
@raises(nx.NetworkXError)
def test_missing_geometry(self):
G = nx.read_shp(self.path)
class TestMissingAttrWrite(object):
@classmethod
def setup_class(cls):
global ogr
try:
from osgeo import ogr
except ImportError:
raise SkipTest('ogr not available.')
def setUp(self):
self.setup_path()
self.delete_shapedir()
def tearDown(self):
self.delete_shapedir()
def setup_path(self):
self.path = os.path.join(tempfile.gettempdir(), 'missing_attributes')
def delete_shapedir(self):
drv = ogr.GetDriverByName("ESRI Shapefile")
if os.path.exists(self.path):
drv.DeleteDataSource(self.path)
def test_missing_attributes(self):
G = nx.DiGraph()
A = (0, 0)
B = (1, 1)
C = (2, 2)
G.add_edge(A, B, foo=100)
G.add_edge(A, C)
nx.write_shp(G, self.path)
H = nx.read_shp(self.path)
for u, v, d in H.edges(data=True):
if u == A and v == B:
assert_equal(d['foo'], 100)
if u == A and v == C:
assert_equal(d['foo'], None)
| true | true |
f7f6dad6661895a8beb7329860e3f672e76293c7 | 1,648 | py | Python | ch_7/Heaviside_class2.py | ProhardONE/python_primer | 211e37c1f2fd169269fc4f3c08e8b7e5225f2ad0 | [
"MIT"
] | 51 | 2016-04-05T16:56:11.000Z | 2022-02-08T00:08:47.000Z | ch_7/Heaviside_class2.py | zhangxiao921207/python_primer | 211e37c1f2fd169269fc4f3c08e8b7e5225f2ad0 | [
"MIT"
] | null | null | null | ch_7/Heaviside_class2.py | zhangxiao921207/python_primer | 211e37c1f2fd169269fc4f3c08e8b7e5225f2ad0 | [
"MIT"
] | 47 | 2016-05-02T07:51:37.000Z | 2022-02-08T01:28:15.000Z | # Exercise 7.20
# Author: Noah Waterfield Price
import numpy as np
import operator
class Heaviside:
def __init__(self, eps=None):
self.eps = eps
def __call__(self, x):
if isinstance(x, (float, int)):
return self.heaviside_scalar(x, self.eps)
else:
return self.heaviside_vec(x, self.eps)
@staticmethod
def heaviside_scalar(x, eps):
if eps is None:
if x < 0:
return 0
elif x >= 0:
return 1
else:
e = eps
if x < -e:
return 0
elif -e <= x <= e:
return 0.5 + x / (2 * e) + \
1 / (2 * np.pi) * np.sin(np.pi * x / e)
elif x > e:
return 1
@staticmethod
def heaviside_vec(x, eps):
r = np.zeros(len(x))
if eps is None:
r[x < 0] = 0.0
r[x >= 0] = 1.0
return r
else:
e = eps
cond = operator.and_(-e <= x, x <= e)
r = np.zeros(len(x))
r[x < -e] = 0.0
r[cond] = 0.5 + x[cond] / (2 * e) + \
1 / (2 * np.pi) * np.sin(np.pi * x[cond] / e)
r[x > e] = 1.0
return r
H = Heaviside()
x = np.linspace(-1, 1, 11)
print H(x)
H = Heaviside(eps=0.8)
print H(x)
"""
Sample run:
python Heaviside_class2.py
[ 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1.]
[ 0.00000000e+00 -1.94908592e-17 1.24604605e-02 9.08450569e-02
2.62460460e-01 5.00000000e-01 7.37539540e-01 9.09154943e-01
9.87539540e-01 1.00000000e+00 1.00000000e+00]
"""
| 24.235294 | 68 | 0.453883 |
import numpy as np
import operator
class Heaviside:
def __init__(self, eps=None):
self.eps = eps
def __call__(self, x):
if isinstance(x, (float, int)):
return self.heaviside_scalar(x, self.eps)
else:
return self.heaviside_vec(x, self.eps)
@staticmethod
def heaviside_scalar(x, eps):
if eps is None:
if x < 0:
return 0
elif x >= 0:
return 1
else:
e = eps
if x < -e:
return 0
elif -e <= x <= e:
return 0.5 + x / (2 * e) + \
1 / (2 * np.pi) * np.sin(np.pi * x / e)
elif x > e:
return 1
@staticmethod
def heaviside_vec(x, eps):
r = np.zeros(len(x))
if eps is None:
r[x < 0] = 0.0
r[x >= 0] = 1.0
return r
else:
e = eps
cond = operator.and_(-e <= x, x <= e)
r = np.zeros(len(x))
r[x < -e] = 0.0
r[cond] = 0.5 + x[cond] / (2 * e) + \
1 / (2 * np.pi) * np.sin(np.pi * x[cond] / e)
r[x > e] = 1.0
return r
H = Heaviside()
x = np.linspace(-1, 1, 11)
print H(x)
H = Heaviside(eps=0.8)
print H(x)
"""
Sample run:
python Heaviside_class2.py
[ 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1.]
[ 0.00000000e+00 -1.94908592e-17 1.24604605e-02 9.08450569e-02
2.62460460e-01 5.00000000e-01 7.37539540e-01 9.09154943e-01
9.87539540e-01 1.00000000e+00 1.00000000e+00]
"""
| false | true |
f7f6dbf48233d0c348e94c8a5fa3f1b1e624e66e | 3,892 | py | Python | Trabalho LSTM/trabalho_LSTM.py | Jovioluiz/IA | 35247c782747a972e73a723608e71faa70cb6916 | [
"MIT"
] | null | null | null | Trabalho LSTM/trabalho_LSTM.py | Jovioluiz/IA | 35247c782747a972e73a723608e71faa70cb6916 | [
"MIT"
] | null | null | null | Trabalho LSTM/trabalho_LSTM.py | Jovioluiz/IA | 35247c782747a972e73a723608e71faa70cb6916 | [
"MIT"
] | null | null | null | import pandas as pd
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
import plotly.graph_objects as go
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# %matplotlib inline
DataSet=pd.read_csv('cotacao_ouro_teste.csv')
fig = go.Figure(data=[go.Candlestick(x=DataSet['Date'],
open=DataSet['Open'], high=DataSet['High'],
low=DataSet['Low'], close=DataSet['Close'])
])
fig.update_layout(xaxis_rangeslider_visible=False)
# fig.show()
DataSet=pd.read_csv('cotacao_ouro_treino2.csv')
DataSet=DataSet.dropna()
DataSet.head()
DataSet.describe()
plt.scatter(DataSet['Date'], DataSet['Open'],)
plt.show()
base_treinamento = DataSet.iloc[:, 1:2].values
#DataSet.drop(['Date','Close','High','Low', 'Volume'],axis=1,inplace=True)
from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler(feature_range=(0, 1))
DataScaled = scaler.fit_transform(base_treinamento)
print(DataScaled)
previsores = []
preco_real = []
NRecursao = 90
DataSetLen = len(DataScaled)
print(DataSetLen)
for i in range(NRecursao, DataSetLen):
previsores.append(DataScaled[i-NRecursao:i,0])
preco_real.append(DataScaled[i,0])
previsores, preco_real = np.array(previsores), np.array(preco_real)
previsores.shape
previsores = np.reshape(previsores, (previsores.shape[0], previsores.shape[1], 1))
previsores.shape
print(previsores)
# Camada de entrada
regressor = Sequential()
regressor.add(LSTM(units = 100, return_sequences = True, input_shape = (previsores.shape[1], 1)))
regressor.add(Dropout(0.3))
# Cada Oculta 1
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.3))
# Cada Oculta 2
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.3))
# Cada Oculta 3
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.3))
# Camada de Saída
regressor.add(Dense(units = 1, activation = 'linear'))
regressor.compile(optimizer = 'rmsprop', loss = 'mean_squared_error',
metrics = ['mean_absolute_error'])
regressor.fit(previsores, preco_real, epochs = 500, batch_size = 32)
DataSet_teste=pd.read_csv('cotacao_ouro_teste.csv')
preco_real_teste = DataSet_teste.iloc[:, 1:2].values
base_completa = pd.concat((DataSet['Open'], DataSet_teste['Open']), axis = 0)
entradas = base_completa[len(base_completa) - len(DataSet_teste) - NRecursao:].values
entradas = entradas.reshape(-1, 1)
entradas = scaler.transform(entradas)
DataSetTestLen = len(DataSet_teste)
NPredictions = 90
X_teste = []
for i in range(NRecursao, DataSetTestLen + NRecursao):
X_teste.append(entradas[i - NRecursao:i, 0])
X_teste = np.array(X_teste)
X_teste = np.reshape(X_teste, (X_teste.shape[0], X_teste.shape[1], 1))
previsoes = regressor.predict(X_teste)
previsoes = scaler.inverse_transform(previsoes)
RNN=[]
predictions_teste=X_teste[0].T
predictions_teste=np.reshape(predictions_teste, (predictions_teste.shape[0], predictions_teste.shape[1], 1))
predictions_teste[0][NRecursao-1][0]=regressor.predict(predictions_teste)[0][0]
RNN.append(regressor.predict(predictions_teste)[0])
for i in range(NPredictions-1):
predictions_teste=np.roll(predictions_teste,-1)
predictions_teste[0][NRecursao-1][0]=regressor.predict(predictions_teste)[0][0]
RNN.append(regressor.predict(predictions_teste)[0])
RNN = scaler.inverse_transform(RNN)
print(RNN.mean())
print(previsoes.mean())
print(preco_real_teste.mean())
plt.plot(preco_real_teste, color = 'red', label = 'Preço real')
plt.plot(previsoes, color = 'blue', label = 'Previsões')
# plt.plot(RNN, color = 'green', label = 'RNN')
plt.title('Cotação Ouro')
plt.xlabel('Tempo')
plt.ylabel('Valor')
plt.legend()
plt.show() | 29.484848 | 109 | 0.715057 | import pandas as pd
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
import plotly.graph_objects as go
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
DataSet=pd.read_csv('cotacao_ouro_teste.csv')
fig = go.Figure(data=[go.Candlestick(x=DataSet['Date'],
open=DataSet['Open'], high=DataSet['High'],
low=DataSet['Low'], close=DataSet['Close'])
])
fig.update_layout(xaxis_rangeslider_visible=False)
DataSet=pd.read_csv('cotacao_ouro_treino2.csv')
DataSet=DataSet.dropna()
DataSet.head()
DataSet.describe()
plt.scatter(DataSet['Date'], DataSet['Open'],)
plt.show()
base_treinamento = DataSet.iloc[:, 1:2].values
from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler(feature_range=(0, 1))
DataScaled = scaler.fit_transform(base_treinamento)
print(DataScaled)
previsores = []
preco_real = []
NRecursao = 90
DataSetLen = len(DataScaled)
print(DataSetLen)
for i in range(NRecursao, DataSetLen):
previsores.append(DataScaled[i-NRecursao:i,0])
preco_real.append(DataScaled[i,0])
previsores, preco_real = np.array(previsores), np.array(preco_real)
previsores.shape
previsores = np.reshape(previsores, (previsores.shape[0], previsores.shape[1], 1))
previsores.shape
print(previsores)
regressor = Sequential()
regressor.add(LSTM(units = 100, return_sequences = True, input_shape = (previsores.shape[1], 1)))
regressor.add(Dropout(0.3))
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.3))
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.3))
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.3))
regressor.add(Dense(units = 1, activation = 'linear'))
regressor.compile(optimizer = 'rmsprop', loss = 'mean_squared_error',
metrics = ['mean_absolute_error'])
regressor.fit(previsores, preco_real, epochs = 500, batch_size = 32)
DataSet_teste=pd.read_csv('cotacao_ouro_teste.csv')
preco_real_teste = DataSet_teste.iloc[:, 1:2].values
base_completa = pd.concat((DataSet['Open'], DataSet_teste['Open']), axis = 0)
entradas = base_completa[len(base_completa) - len(DataSet_teste) - NRecursao:].values
entradas = entradas.reshape(-1, 1)
entradas = scaler.transform(entradas)
DataSetTestLen = len(DataSet_teste)
NPredictions = 90
X_teste = []
for i in range(NRecursao, DataSetTestLen + NRecursao):
X_teste.append(entradas[i - NRecursao:i, 0])
X_teste = np.array(X_teste)
X_teste = np.reshape(X_teste, (X_teste.shape[0], X_teste.shape[1], 1))
previsoes = regressor.predict(X_teste)
previsoes = scaler.inverse_transform(previsoes)
RNN=[]
predictions_teste=X_teste[0].T
predictions_teste=np.reshape(predictions_teste, (predictions_teste.shape[0], predictions_teste.shape[1], 1))
predictions_teste[0][NRecursao-1][0]=regressor.predict(predictions_teste)[0][0]
RNN.append(regressor.predict(predictions_teste)[0])
for i in range(NPredictions-1):
predictions_teste=np.roll(predictions_teste,-1)
predictions_teste[0][NRecursao-1][0]=regressor.predict(predictions_teste)[0][0]
RNN.append(regressor.predict(predictions_teste)[0])
RNN = scaler.inverse_transform(RNN)
print(RNN.mean())
print(previsoes.mean())
print(preco_real_teste.mean())
plt.plot(preco_real_teste, color = 'red', label = 'Preço real')
plt.plot(previsoes, color = 'blue', label = 'Previsões')
plt.title('Cotação Ouro')
plt.xlabel('Tempo')
plt.ylabel('Valor')
plt.legend()
plt.show() | true | true |
f7f6dbf5fe7cad837dc8c7956be0493f3d25aa71 | 247 | py | Python | openstack_dashboard/enabled/ossobv_alter_project_default.py | ossobv/horizon | d3f498137d1586f9cfc26961262fdc11b866293f | [
"Apache-2.0"
] | null | null | null | openstack_dashboard/enabled/ossobv_alter_project_default.py | ossobv/horizon | d3f498137d1586f9cfc26961262fdc11b866293f | [
"Apache-2.0"
] | 2 | 2019-11-20T11:45:44.000Z | 2020-02-24T08:40:08.000Z | openstack_dashboard/enabled/ossobv_alter_project_default.py | ossobv/horizon | d3f498137d1586f9cfc26961262fdc11b866293f | [
"Apache-2.0"
] | null | null | null | # Panel settings: /project/<default>/api_access
PANEL_DASHBOARD = 'project'
PANEL_GROUP = 'default'
PANEL = 'api_access'
# The default _was_ "overview", but that gives 403s.
# Make this the default in this dashboard.
DEFAULT_PANEL = 'api_access'
| 27.444444 | 52 | 0.757085 |
PANEL_DASHBOARD = 'project'
PANEL_GROUP = 'default'
PANEL = 'api_access'
DEFAULT_PANEL = 'api_access'
| true | true |
f7f6dd037627972b6b332ba032ce417fe74e1c56 | 1,317 | py | Python | theapplication/migrations/0031_auto_20181223_2334.py | uncommonhacks/reg | 0906bc293899eae6e2b3637a99761703444175af | [
"MIT"
] | null | null | null | theapplication/migrations/0031_auto_20181223_2334.py | uncommonhacks/reg | 0906bc293899eae6e2b3637a99761703444175af | [
"MIT"
] | 23 | 2018-09-06T14:26:37.000Z | 2020-06-05T19:10:38.000Z | theapplication/migrations/0031_auto_20181223_2334.py | uncommonhacks/reg | 0906bc293899eae6e2b3637a99761703444175af | [
"MIT"
] | null | null | null | # Generated by Django 2.1.2 on 2018-12-23 23:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("theapplication", "0030_auto_20181223_2100")]
operations = [
migrations.AlterField(
model_name="confirmation",
name="dietary_restrictions",
field=models.CharField(
max_length=1000, verbose_name="Do you have any dietary restrictions?"
),
),
migrations.AlterField(
model_name="confirmation",
name="notes",
field=models.TextField(
max_length=1500,
null=True,
verbose_name="Anything else we should know? (health information, accommodations, etc.)",
),
),
migrations.AlterField(
model_name="confirmation",
name="shirt_size",
field=models.CharField(
choices=[
("XS", "XS"),
("S_", "S"),
("M_", "M"),
("L_", "L"),
("1X", "XL"),
("2X", "XXL"),
],
max_length=2,
null=True,
verbose_name="Shirt Size",
),
),
]
| 29.266667 | 104 | 0.463933 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("theapplication", "0030_auto_20181223_2100")]
operations = [
migrations.AlterField(
model_name="confirmation",
name="dietary_restrictions",
field=models.CharField(
max_length=1000, verbose_name="Do you have any dietary restrictions?"
),
),
migrations.AlterField(
model_name="confirmation",
name="notes",
field=models.TextField(
max_length=1500,
null=True,
verbose_name="Anything else we should know? (health information, accommodations, etc.)",
),
),
migrations.AlterField(
model_name="confirmation",
name="shirt_size",
field=models.CharField(
choices=[
("XS", "XS"),
("S_", "S"),
("M_", "M"),
("L_", "L"),
("1X", "XL"),
("2X", "XXL"),
],
max_length=2,
null=True,
verbose_name="Shirt Size",
),
),
]
| true | true |
f7f6dd67b6a1640ac93ee0f56304231641c4c068 | 5,418 | py | Python | recipes/pulseaudio/all/conanfile.py | Elnee/conan-center-index | b926bc4896fc3dee917e4543e4f50d6526e710e7 | [
"MIT"
] | 1 | 2022-02-08T23:30:18.000Z | 2022-02-08T23:30:18.000Z | recipes/pulseaudio/all/conanfile.py | Elnee/conan-center-index | b926bc4896fc3dee917e4543e4f50d6526e710e7 | [
"MIT"
] | 3 | 2019-11-18T18:42:06.000Z | 2021-08-16T14:34:05.000Z | recipes/pulseaudio/all/conanfile.py | Elnee/conan-center-index | b926bc4896fc3dee917e4543e4f50d6526e710e7 | [
"MIT"
] | null | null | null | from conans import ConanFile, tools, AutoToolsBuildEnvironment
from conans.errors import ConanInvalidConfiguration
import os
required_conan_version = ">=1.32.0"
class PulseAudioConan(ConanFile):
name = "pulseaudio"
description = "PulseAudio is a sound system for POSIX OSes, meaning that it is a proxy for sound applications."
topics = ("conan", "pulseaudio", "sound")
url = "https://github.com/conan-io/conan-center-index"
homepage = "http://pulseaudio.org/"
license = "LGPL-2.1"
generators = "pkg_config"
settings = "os", "arch", "compiler", "build_type"
options = {
"shared": [True, False],
"fPIC": [True, False],
"with_alsa": [True, False],
"with_glib": [True, False],
"with_fftw": [True, False],
"with_x11": [True, False],
"with_openssl": [True, False],
"with_dbus": [True, False],
}
default_options = {
"shared": False,
"fPIC": True,
"with_alsa": True,
"with_glib": False,
"with_fftw": False,
"with_x11": True,
"with_openssl": True,
"with_dbus": False,
}
_autotools = None
@property
def _source_subfolder(self):
return "source_subfolder"
def config_options(self):
if self.settings.os == "Windows":
del self.options.fPIC
def configure(self):
if self.settings.os != "Linux":
raise ConanInvalidConfiguration("pulseaudio supports only linux currently")
if self.options.shared:
del self.options.fPIC
del self.settings.compiler.libcxx
del self.settings.compiler.cppstd
if not self.options.with_dbus:
del self.options.with_fftw
def requirements(self):
self.requires("libsndfile/1.0.31")
self.requires("libcap/2.48")
if self.options.with_alsa:
self.requires("libalsa/1.2.4")
if self.options.with_glib:
self.requires("glib/2.68.2")
if self.options.get_safe("with_fftw"):
self.requires("fftw/3.3.9")
if self.options.with_x11:
self.requires("xorg/system")
if self.options.with_openssl:
self.requires("openssl/1.1.1k")
if self.options.with_dbus:
self.requires("dbus/1.12.20")
def validate(self):
if self.options.get_safe("with_fftw") and self.options["fftw"].precision != "single":
raise ConanInvalidConfiguration("Pulse audio cannot use fftw %s precision."
"Either set option fftw:precision=single"
"or pulseaudio:with_fftw=False"
% self.options["fftw"].precision)
def build_requirements(self):
self.build_requires("gettext/0.20.1")
self.build_requires("libtool/2.4.6")
self.build_requires("pkgconf/1.7.4")
def source(self):
tools.get(**self.conan_data["sources"][self.version], strip_root=True, destination=self._source_subfolder)
def _configure_autotools(self):
if not self._autotools:
self._autotools = AutoToolsBuildEnvironment(self)
args=[]
for lib in ["alsa", "x11", "openssl", "dbus"]:
args.append("--%s-%s" % ("enable" if getattr(self.options, "with_" + lib) else "disable", lib))
args.append("--%s-glib2" % ("enable" if self.options.with_glib else "disable"))
args.append("--%s-fftw" % ("with" if self.options.get_safe("with_fftw") else "without"))
if self.options.shared:
args.extend(["--enable-shared=yes", "--enable-static=no"])
else:
args.extend(["--enable-shared=no", "--enable-static=yes"])
args.append("--with-udev-rules-dir=%s" % os.path.join(self.package_folder, "bin", "udev", "rules.d"))
args.append("--with-systemduserunitdir=%s" % os.path.join(self.build_folder, "ignore"))
self._autotools.configure(args=args, configure_dir=self._source_subfolder)
return self._autotools
def build(self):
with tools.run_environment(self):
autotools = self._configure_autotools()
autotools.make()
def package(self):
self.copy(pattern="LICENSE", dst="licenses", src=self._source_subfolder)
with tools.run_environment(self):
autotools = self._configure_autotools()
autotools.install()
tools.rmdir(os.path.join(self.package_folder, "etc"))
tools.rmdir(os.path.join(self.package_folder, "share"))
tools.rmdir(os.path.join(self.package_folder, "lib", "cmake"))
tools.rmdir(os.path.join(self.package_folder, "lib", "pkgconfig"))
tools.remove_files_by_mask(self.package_folder, "*.la")
def package_info(self):
self.cpp_info.libdirs = ["lib", os.path.join("lib", "pulseaudio")]
if self.options.with_glib:
self.cpp_info.libs.append("pulse-mainloop-glib")
self.cpp_info.libs.extend(["pulse-simple", "pulse"])
if not self.options.shared:
self.cpp_info.libs.append("pulsecommon-%s" % self.version)
self.cpp_info.defines = ["_REENTRANT"]
self.cpp_info.names["pkg_config"] = "libpulse"
# FIXME: add cmake generators when conan can generate PULSEAUDIO_INCLUDE_DIR PULSEAUDIO_LIBRARY vars
| 40.432836 | 115 | 0.605943 | from conans import ConanFile, tools, AutoToolsBuildEnvironment
from conans.errors import ConanInvalidConfiguration
import os
required_conan_version = ">=1.32.0"
class PulseAudioConan(ConanFile):
name = "pulseaudio"
description = "PulseAudio is a sound system for POSIX OSes, meaning that it is a proxy for sound applications."
topics = ("conan", "pulseaudio", "sound")
url = "https://github.com/conan-io/conan-center-index"
homepage = "http://pulseaudio.org/"
license = "LGPL-2.1"
generators = "pkg_config"
settings = "os", "arch", "compiler", "build_type"
options = {
"shared": [True, False],
"fPIC": [True, False],
"with_alsa": [True, False],
"with_glib": [True, False],
"with_fftw": [True, False],
"with_x11": [True, False],
"with_openssl": [True, False],
"with_dbus": [True, False],
}
default_options = {
"shared": False,
"fPIC": True,
"with_alsa": True,
"with_glib": False,
"with_fftw": False,
"with_x11": True,
"with_openssl": True,
"with_dbus": False,
}
_autotools = None
@property
def _source_subfolder(self):
return "source_subfolder"
def config_options(self):
if self.settings.os == "Windows":
del self.options.fPIC
def configure(self):
if self.settings.os != "Linux":
raise ConanInvalidConfiguration("pulseaudio supports only linux currently")
if self.options.shared:
del self.options.fPIC
del self.settings.compiler.libcxx
del self.settings.compiler.cppstd
if not self.options.with_dbus:
del self.options.with_fftw
def requirements(self):
self.requires("libsndfile/1.0.31")
self.requires("libcap/2.48")
if self.options.with_alsa:
self.requires("libalsa/1.2.4")
if self.options.with_glib:
self.requires("glib/2.68.2")
if self.options.get_safe("with_fftw"):
self.requires("fftw/3.3.9")
if self.options.with_x11:
self.requires("xorg/system")
if self.options.with_openssl:
self.requires("openssl/1.1.1k")
if self.options.with_dbus:
self.requires("dbus/1.12.20")
def validate(self):
if self.options.get_safe("with_fftw") and self.options["fftw"].precision != "single":
raise ConanInvalidConfiguration("Pulse audio cannot use fftw %s precision."
"Either set option fftw:precision=single"
"or pulseaudio:with_fftw=False"
% self.options["fftw"].precision)
def build_requirements(self):
self.build_requires("gettext/0.20.1")
self.build_requires("libtool/2.4.6")
self.build_requires("pkgconf/1.7.4")
def source(self):
tools.get(**self.conan_data["sources"][self.version], strip_root=True, destination=self._source_subfolder)
def _configure_autotools(self):
if not self._autotools:
self._autotools = AutoToolsBuildEnvironment(self)
args=[]
for lib in ["alsa", "x11", "openssl", "dbus"]:
args.append("--%s-%s" % ("enable" if getattr(self.options, "with_" + lib) else "disable", lib))
args.append("--%s-glib2" % ("enable" if self.options.with_glib else "disable"))
args.append("--%s-fftw" % ("with" if self.options.get_safe("with_fftw") else "without"))
if self.options.shared:
args.extend(["--enable-shared=yes", "--enable-static=no"])
else:
args.extend(["--enable-shared=no", "--enable-static=yes"])
args.append("--with-udev-rules-dir=%s" % os.path.join(self.package_folder, "bin", "udev", "rules.d"))
args.append("--with-systemduserunitdir=%s" % os.path.join(self.build_folder, "ignore"))
self._autotools.configure(args=args, configure_dir=self._source_subfolder)
return self._autotools
def build(self):
with tools.run_environment(self):
autotools = self._configure_autotools()
autotools.make()
def package(self):
self.copy(pattern="LICENSE", dst="licenses", src=self._source_subfolder)
with tools.run_environment(self):
autotools = self._configure_autotools()
autotools.install()
tools.rmdir(os.path.join(self.package_folder, "etc"))
tools.rmdir(os.path.join(self.package_folder, "share"))
tools.rmdir(os.path.join(self.package_folder, "lib", "cmake"))
tools.rmdir(os.path.join(self.package_folder, "lib", "pkgconfig"))
tools.remove_files_by_mask(self.package_folder, "*.la")
def package_info(self):
self.cpp_info.libdirs = ["lib", os.path.join("lib", "pulseaudio")]
if self.options.with_glib:
self.cpp_info.libs.append("pulse-mainloop-glib")
self.cpp_info.libs.extend(["pulse-simple", "pulse"])
if not self.options.shared:
self.cpp_info.libs.append("pulsecommon-%s" % self.version)
self.cpp_info.defines = ["_REENTRANT"]
self.cpp_info.names["pkg_config"] = "libpulse"
| true | true |
f7f6ddb8b76814137c734ecfff942fe96e26f769 | 295 | py | Python | src/auth/authorization.py | Guria/script-server | 851effb3dd92092ea3bc34a65d9ece541bf4f9cb | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | src/auth/authorization.py | Guria/script-server | 851effb3dd92092ea3bc34a65d9ece541bf4f9cb | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | src/auth/authorization.py | Guria/script-server | 851effb3dd92092ea3bc34a65d9ece541bf4f9cb | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | class ListBasedAuthorizer:
def __init__(self, allowed_users) -> None:
self.allowed_users = allowed_users
def is_allowed(self, username):
return username in self.allowed_users
class AnyUserAuthorizer:
@staticmethod
def is_allowed(username):
return True
| 22.692308 | 46 | 0.708475 | class ListBasedAuthorizer:
def __init__(self, allowed_users) -> None:
self.allowed_users = allowed_users
def is_allowed(self, username):
return username in self.allowed_users
class AnyUserAuthorizer:
@staticmethod
def is_allowed(username):
return True
| true | true |
f7f6e0bd8609c6075ef48c48b6b4f696fdded0e3 | 179,978 | py | Python | pandapower/create.py | hmaschke/pandapower-1 | 2e93969050d3d468ce57f73d358e97fabc6e5141 | [
"BSD-3-Clause"
] | 2 | 2019-11-01T11:01:41.000Z | 2022-02-07T12:55:55.000Z | pandapower/create.py | hmaschke/pandapower-1 | 2e93969050d3d468ce57f73d358e97fabc6e5141 | [
"BSD-3-Clause"
] | null | null | null | pandapower/create.py | hmaschke/pandapower-1 | 2e93969050d3d468ce57f73d358e97fabc6e5141 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright (c) 2016-2022 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
from operator import itemgetter
import pandas as pd
from numpy import nan, isnan, arange, dtype, isin, any as np_any, zeros, array, bool_, \
all as np_all, float64, intersect1d
from packaging import version
from pandapower import __version__
from pandapower.auxiliary import pandapowerNet, get_free_id, _preserve_dtypes
from pandapower.results import reset_results
from pandapower.std_types import add_basic_std_types, load_std_type, check_entry_in_std_type
import numpy as np
try:
import pandaplan.core.pplog as logging
except ImportError:
import logging
logger = logging.getLogger(__name__)
def create_empty_network(name="", f_hz=50., sn_mva=1, add_stdtypes=True):
"""
This function initializes the pandapower datastructure.
OPTIONAL:
**f_hz** (float, 50.) - power system frequency in hertz
**name** (string, None) - name for the network
**sn_mva** (float, 1e3) - reference apparent power for per unit system
**add_stdtypes** (boolean, True) - Includes standard types to net
OUTPUT:
**net** (attrdict) - PANDAPOWER attrdict with empty tables:
EXAMPLE:
net = create_empty_network()
"""
net = pandapowerNet({
# structure data
"bus": [('name', dtype(object)),
('vn_kv', 'f8'),
('type', dtype(object)),
('zone', dtype(object)),
('in_service', 'bool'), ],
"load": [("name", dtype(object)),
("bus", "u4"),
("p_mw", "f8"),
("q_mvar", "f8"),
("const_z_percent", "f8"),
("const_i_percent", "f8"),
("sn_mva", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("type", dtype(object))],
"sgen": [("name", dtype(object)),
("bus", "i8"),
("p_mw", "f8"),
("q_mvar", "f8"),
("sn_mva", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("type", dtype(object)),
("current_source", "bool")],
"motor": [("name", dtype(object)),
("bus", "i8"),
("pn_mech_mw", "f8"),
("loading_percent", "f8"),
("cos_phi", "f8"),
("cos_phi_n", "f8"),
("efficiency_percent", "f8"),
("efficiency_n_percent", "f8"),
("lrc_pu", "f8"),
("vn_kv", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("rx", 'f8')
],
"asymmetric_load": [("name", dtype(object)),
("bus", "u4"),
("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8"),
("sn_mva", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("type", dtype(object))],
"asymmetric_sgen": [("name", dtype(object)),
("bus", "i8"),
("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8"),
("sn_mva", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("type", dtype(object)),
("current_source", "bool")],
"storage": [("name", dtype(object)),
("bus", "i8"),
("p_mw", "f8"),
("q_mvar", "f8"),
("sn_mva", "f8"),
("soc_percent", "f8"),
("min_e_mwh", "f8"),
("max_e_mwh", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("type", dtype(object))],
"gen": [("name", dtype(object)),
("bus", "u4"),
("p_mw", "f8"),
("vm_pu", "f8"),
("sn_mva", "f8"),
("min_q_mvar", "f8"),
("max_q_mvar", "f8"),
("scaling", "f8"),
("slack", "bool"),
("in_service", 'bool'),
("slack_weight", 'f8'),
("type", dtype(object))],
"switch": [("bus", "i8"),
("element", "i8"),
("et", dtype(object)),
("type", dtype(object)),
("closed", "bool"),
("name", dtype(object)),
("z_ohm", "f8")],
"shunt": [("bus", "u4"),
("name", dtype(object)),
("q_mvar", "f8"),
("p_mw", "f8"),
("vn_kv", "f8"),
("step", "u4"),
("max_step", "u4"),
("in_service", "bool")],
"ext_grid": [("name", dtype(object)),
("bus", "u4"),
("vm_pu", "f8"),
("va_degree", "f8"),
("slack_weight", 'f8'),
("in_service", 'bool')],
"line": [("name", dtype(object)),
("std_type", dtype(object)),
("from_bus", "u4"),
("to_bus", "u4"),
("length_km", "f8"),
("r_ohm_per_km", "f8"),
("x_ohm_per_km", "f8"),
("c_nf_per_km", "f8"),
("g_us_per_km", "f8"),
("max_i_ka", "f8"),
("df", "f8"),
("parallel", "u4"),
("type", dtype(object)),
("in_service", 'bool')],
"trafo": [("name", dtype(object)),
("std_type", dtype(object)),
("hv_bus", "u4"),
("lv_bus", "u4"),
("sn_mva", "f8"),
("vn_hv_kv", "f8"),
("vn_lv_kv", "f8"),
("vk_percent", "f8"),
("vkr_percent", "f8"),
("pfe_kw", "f8"),
("i0_percent", "f8"),
("shift_degree", "f8"),
("tap_side", dtype(object)),
("tap_neutral", "i4"),
("tap_min", "i4"),
("tap_max", "i4"),
("tap_step_percent", "f8"),
("tap_step_degree", "f8"),
("tap_pos", "i4"),
("tap_phase_shifter", 'bool'),
("parallel", "u4"),
("df", "f8"),
("in_service", 'bool')],
"trafo3w": [("name", dtype(object)),
("std_type", dtype(object)),
("hv_bus", "u4"),
("mv_bus", "u4"),
("lv_bus", "u4"),
("sn_hv_mva", "f8"),
("sn_mv_mva", "f8"),
("sn_lv_mva", "f8"),
("vn_hv_kv", "f8"),
("vn_mv_kv", "f8"),
("vn_lv_kv", "f8"),
("vk_hv_percent", "f8"),
("vk_mv_percent", "f8"),
("vk_lv_percent", "f8"),
("vkr_hv_percent", "f8"),
("vkr_mv_percent", "f8"),
("vkr_lv_percent", "f8"),
("pfe_kw", "f8"),
("i0_percent", "f8"),
("shift_mv_degree", "f8"),
("shift_lv_degree", "f8"),
("tap_side", dtype(object)),
("tap_neutral", "i4"),
("tap_min", "i4"),
("tap_max", "i4"),
("tap_step_percent", "f8"),
("tap_step_degree", "f8"),
("tap_pos", "i4"),
("tap_at_star_point", 'bool'),
("in_service", 'bool')],
"impedance": [("name", dtype(object)),
("from_bus", "u4"),
("to_bus", "u4"),
("rft_pu", "f8"),
("xft_pu", "f8"),
("rtf_pu", "f8"),
("xtf_pu", "f8"),
("sn_mva", "f8"),
("in_service", 'bool')],
"dcline": [("name", dtype(object)),
("from_bus", "u4"),
("to_bus", "u4"),
("p_mw", "f8"),
("loss_percent", 'f8'),
("loss_mw", 'f8'),
("vm_from_pu", "f8"),
("vm_to_pu", "f8"),
("max_p_mw", "f8"),
("min_q_from_mvar", "f8"),
("min_q_to_mvar", "f8"),
("max_q_from_mvar", "f8"),
("max_q_to_mvar", "f8"),
("in_service", 'bool')],
"ward": [("name", dtype(object)),
("bus", "u4"),
("ps_mw", "f8"),
("qs_mvar", "f8"),
("qz_mvar", "f8"),
("pz_mw", "f8"),
("in_service", "bool")],
"xward": [("name", dtype(object)),
("bus", "u4"),
("ps_mw", "f8"),
("qs_mvar", "f8"),
("qz_mvar", "f8"),
("pz_mw", "f8"),
("r_ohm", "f8"),
("x_ohm", "f8"),
("vm_pu", "f8"),
("slack_weight", 'f8'),
("in_service", "bool")],
"measurement": [("name", dtype(object)),
("measurement_type", dtype(object)),
("element_type", dtype(object)),
("element", "uint32"),
("value", "float64"),
("std_dev", "float64"),
("side", dtype(object))],
"pwl_cost": [("power_type", dtype(object)),
("element", "u4"),
("et", dtype(object)),
("points", dtype(object))],
"poly_cost": [("element", "u4"),
("et", dtype(object)),
("cp0_eur", dtype("f8")),
("cp1_eur_per_mw", dtype("f8")),
("cp2_eur_per_mw2", dtype("f8")),
("cq0_eur", dtype("f8")),
("cq1_eur_per_mvar", dtype("f8")),
("cq2_eur_per_mvar2", dtype("f8"))
],
'characteristic': [
('object', dtype(object))
],
'controller': [
('object', dtype(object)),
('in_service', "bool"),
('order', "float64"),
('level', dtype(object)),
('initial_run', "bool"),
("recycle", dtype(object))
],
# geodata
"line_geodata": [("coords", dtype(object))],
"bus_geodata": [("x", "f8"), ("y", "f8"), ("coords", dtype(object))],
# result tables
"_empty_res_bus": [("vm_pu", "f8"),
("va_degree", "f8"),
("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_ext_grid": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_line": [("p_from_mw", "f8"),
("q_from_mvar", "f8"),
("p_to_mw", "f8"),
("q_to_mvar", "f8"),
("pl_mw", "f8"),
("ql_mvar", "f8"),
("i_from_ka", "f8"),
("i_to_ka", "f8"),
("i_ka", "f8"),
("vm_from_pu", "f8"),
("va_from_degree", "f8"),
("vm_to_pu", "f8"),
("va_to_degree", "f8"),
("loading_percent", "f8")],
"_empty_res_trafo": [("p_hv_mw", "f8"),
("q_hv_mvar", "f8"),
("p_lv_mw", "f8"),
("q_lv_mvar", "f8"),
("pl_mw", "f8"),
("ql_mvar", "f8"),
("i_hv_ka", "f8"),
("i_lv_ka", "f8"),
("vm_hv_pu", "f8"),
("va_hv_degree", "f8"),
("vm_lv_pu", "f8"),
("va_lv_degree", "f8"),
("loading_percent", "f8")],
"_empty_res_load": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_asymmetric_load": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_asymmetric_sgen": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_motor": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_sgen": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_shunt": [("p_mw", "f8"),
("q_mvar", "f8"),
("vm_pu", "f8")],
"_empty_res_impedance": [("p_from_mw", "f8"),
("q_from_mvar", "f8"),
("p_to_mw", "f8"),
("q_to_mvar", "f8"),
("pl_mw", "f8"),
("ql_mvar", "f8"),
("i_from_ka", "f8"),
("i_to_ka", "f8")],
"_empty_res_dcline": [("p_from_mw", "f8"),
("q_from_mvar", "f8"),
("p_to_mw", "f8"),
("q_to_mvar", "f8"),
("pl_mw", "f8"),
("vm_from_pu", "f8"),
("va_from_degree", "f8"),
("vm_to_pu", "f8"),
("va_to_degree", "f8")],
"_empty_res_ward": [("p_mw", "f8"),
("q_mvar", "f8"),
("vm_pu", "f8")],
"_empty_res_xward": [("p_mw", "f8"),
("q_mvar", "f8"),
("vm_pu", "f8"),
("va_internal_degree", "f8"),
("vm_internal_pu", "f8")],
"_empty_res_trafo_3ph": [("p_a_hv_mw", "f8"),
("q_a_hv_mvar", "f8"),
("p_b_hv_mw", "f8"),
("q_b_hv_mvar", "f8"),
("p_c_hv_mw", "f8"),
("q_c_hv_mvar", "f8"),
("p_a_lv_mw", "f8"),
("q_a_lv_mvar", "f8"),
("p_b_lv_mw", "f8"),
("q_b_lv_mvar", "f8"),
("p_c_lv_mw", "f8"),
("q_c_lv_mvar", "f8"),
("p_a_l_mw", "f8"),
("q_a_l_mvar", "f8"),
("p_b_l_mw", "f8"),
("q_b_l_mvar", "f8"),
("p_c_l_mw", "f8"),
("q_c_l_mvar", "f8"),
("i_a_hv_ka", "f8"),
("i_a_lv_ka", "f8"),
("i_b_hv_ka", "f8"),
("i_b_lv_ka", "f8"),
("i_c_hv_ka", "f8"),
("i_c_lv_ka", "f8"),
# ("i_n_hv_ka", "f8"),
# ("i_n_lv_ka", "f8"),
("loading_a_percent", "f8"),
("loading_b_percent", "f8"),
("loading_c_percent", "f8"),
("loading_percent", "f8")],
"_empty_res_trafo3w": [("p_hv_mw", "f8"),
("q_hv_mvar", "f8"),
("p_mv_mw", "f8"),
("q_mv_mvar", "f8"),
("p_lv_mw", "f8"),
("q_lv_mvar", "f8"),
("pl_mw", "f8"),
("ql_mvar", "f8"),
("i_hv_ka", "f8"),
("i_mv_ka", "f8"),
("i_lv_ka", "f8"),
("vm_hv_pu", "f8"),
("va_hv_degree", "f8"),
("vm_mv_pu", "f8"),
("va_mv_degree", "f8"),
("vm_lv_pu", "f8"),
("va_lv_degree", "f8"),
("va_internal_degree", "f8"),
("vm_internal_pu", "f8"),
("loading_percent", "f8")],
"_empty_res_bus_3ph": [("vm_a_pu", "f8"),
("va_a_degree", "f8"),
("vm_b_pu", "f8"),
("va_b_degree", "f8"),
("vm_c_pu", "f8"),
("va_c_degree", "f8"),
("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8")],
"_empty_res_ext_grid_3ph": [("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8")],
"_empty_res_line_3ph": [("p_a_from_mw", "f8"),
("q_a_from_mvar", "f8"),
("p_b_from_mw", "f8"),
("q_b_from_mvar", "f8"),
("q_c_from_mvar", "f8"),
("p_a_to_mw", "f8"),
("q_a_to_mvar", "f8"),
("p_b_to_mw", "f8"),
("q_b_to_mvar", "f8"),
("p_c_to_mw", "f8"),
("q_c_to_mvar", "f8"),
("p_a_l_mw", "f8"),
("q_a_l_mvar", "f8"),
("p_b_l_mw", "f8"),
("q_b_l_mvar", "f8"),
("p_c_l_mw", "f8"),
("q_c_l_mvar", "f8"),
("i_a_from_ka", "f8"),
("i_a_to_ka", "f8"),
("i_b_from_ka", "f8"),
("i_b_to_ka", "f8"),
("i_c_from_ka", "f8"),
("i_c_to_ka", "f8"),
("i_a_ka", "f8"),
("i_b_ka", "f8"),
("i_c_ka", "f8"),
("i_n_from_ka", "f8"),
("i_n_to_ka", "f8"),
("i_n_ka", "f8"),
("loading_a_percent", "f8"),
("loading_b_percent", "f8"),
("loading_c_percent", "f8")],
"_empty_res_asymmetric_load_3ph": [("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8")],
"_empty_res_asymmetric_sgen_3ph": [("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8")],
"_empty_res_storage": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_storage_3ph": [("p_a_mw", "f8"), ("p_b_mw", "f8"), ("p_c_mw", "f8"),
("q_a_mvar", "f8"), ("q_b_mvar", "f8"), ("q_c_mvar", "f8")],
"_empty_res_gen": [("p_mw", "f8"),
("q_mvar", "f8"),
("va_degree", "f8"),
("vm_pu", "f8")],
# internal
"_ppc": None,
"_ppc0": None,
"_ppc1": None,
"_ppc2": None,
"_is_elements": None,
"_pd2ppc_lookups": {"bus": None,
"ext_grid": None,
"gen": None,
"branch": None},
"version": __version__,
"converged": False,
"name": name,
"f_hz": f_hz,
"sn_mva": sn_mva
})
net._empty_res_load_3ph = net._empty_res_load
net._empty_res_sgen_3ph = net._empty_res_sgen
net._empty_res_storage_3ph = net._empty_res_storage
for s in net:
if isinstance(net[s], list):
net[s] = pd.DataFrame(zeros(0, dtype=net[s]), index=pd.Index([], dtype=np.int64))
if add_stdtypes:
add_basic_std_types(net)
else:
net.std_types = {"line": {}, "trafo": {}, "trafo3w": {}}
for mode in ["pf", "se", "sc", "pf_3ph"]:
reset_results(net, mode)
net['user_pf_options'] = dict()
return net
def create_bus(net, vn_kv, name=None, index=None, geodata=None, type="b", zone=None,
in_service=True, max_vm_pu=nan, min_vm_pu=nan, coords=None, **kwargs):
"""
Adds one bus in table net["bus"].
Busses are the nodes of the network that all other elements connect to.
INPUT:
**net** (pandapowerNet) - The pandapower network in which the element is created
OPTIONAL:
**name** (string, default None) - the name for this bus
**index** (int, default None) - Force a specified ID if it is available. If None, the \
index one higher than the highest already existing index is selected.
**vn_kv** (float) - The grid voltage level.
**geodata** ((x,y)-tuple, default None) - coordinates used for plotting
**type** (string, default "b") - Type of the bus. "n" - node,
"b" - busbar, "m" - muff
**zone** (string, None) - grid region
**in_service** (boolean) - True for in_service or False for out of service
**max_vm_pu** (float, NAN) - Maximum bus voltage in p.u. - necessary for OPF
**min_vm_pu** (float, NAN) - Minimum bus voltage in p.u. - necessary for OPF
**coords** (list (len=2) of tuples (len=2), default None) - busbar coordinates to plot
the bus with multiple points. coords is typically a list of tuples (start and endpoint of
the busbar) - Example: [(x1, y1), (x2, y2)]
OUTPUT:
**index** (int) - The unique ID of the created element
EXAMPLE:
create_bus(net, name = "bus1")
"""
index = _get_index_with_check(net, "bus", index)
entries = dict(zip(["name", "vn_kv", "type", "zone", "in_service"],
[name, vn_kv, type, zone, bool(in_service)]))
_set_entries(net, "bus", index, True, **entries, **kwargs)
if geodata is not None:
if len(geodata) != 2:
raise UserWarning("geodata must be given as (x, y) tuple")
net["bus_geodata"].loc[index, ["x", "y"]] = geodata
if coords is not None:
net["bus_geodata"].at[index, "coords"] = coords
# column needed by OPF. 0. and 2. are the default maximum / minimum voltages
_create_column_and_set_value(net, index, min_vm_pu, "min_vm_pu", "bus", default_val=0.)
_create_column_and_set_value(net, index, max_vm_pu, "max_vm_pu", "bus", default_val=2.)
return index
def create_buses(net, nr_buses, vn_kv, index=None, name=None, type="b", geodata=None,
zone=None, in_service=True, max_vm_pu=None, min_vm_pu=None, coords=None, **kwargs):
"""
Adds several buses in table net["bus"] at once.
Busses are the nodal points of the network that all other elements connect to.
Input:
**net** (pandapowerNet) - The pandapower network in which the element is created
**nr_buses** (int) - The number of buses that is created
OPTIONAL:
**name** (string, default None) - the name for this bus
**index** (int, default None) - Force specified IDs if available. If None, the indices \
higher than the highest already existing index are selected.
**vn_kv** (float) - The grid voltage level.
**geodata** ((x,y)-tuple or list of tuples with length == nr_buses, default None) -
coordinates used for plotting
**type** (string, default "b") - Type of the bus. "n" - auxilary node,
"b" - busbar, "m" - muff
**zone** (string, None) - grid region
**in_service** (boolean) - True for in_service or False for out of service
**max_vm_pu** (float, NAN) - Maximum bus voltage in p.u. - necessary for OPF
**min_vm_pu** (float, NAN) - Minimum bus voltage in p.u. - necessary for OPF
**coords** (list (len=nr_buses) of list (len=2) of tuples (len=2), default None) - busbar
coordinates to plot the bus with multiple points. coords is typically a list of tuples
(start and endpoint of the busbar) - Example for 3 buses:
[[(x11, y11), (x12, y12)], [(x21, y21), (x22, y22)], [(x31, y31), (x32, y32)]]
OUTPUT:
**index** (int) - The unique indices ID of the created elements
EXAMPLE:
create_bus(net, name = "bus1")
"""
index = _get_multiple_index_with_check(net, "bus", index, nr_buses)
entries = {"vn_kv": vn_kv, "type": type, "zone": zone, "in_service": in_service, "name": name}
_add_series_to_entries(entries, index, "min_vm_pu", min_vm_pu)
_add_series_to_entries(entries, index, "max_vm_pu", max_vm_pu)
_set_multiple_entries(net, "bus", index, **entries, **kwargs)
if geodata is not None:
# works with a 2-tuple or a matching array
net.bus_geodata = pd.concat([net.bus_geodata,
pd.DataFrame(zeros((len(index), len(net.bus_geodata.columns)), dtype=int),
index=index, columns=net.bus_geodata.columns)])
net.bus_geodata.loc[index, :] = nan
net.bus_geodata.loc[index, ["x", "y"]] = geodata
if coords is not None:
net.bus_geodata = pd.concat([net.bus_geodata, pd.DataFrame(index=index, columns=net.bus_geodata.columns)])
net["bus_geodata"].loc[index, "coords"] = coords
return index
def create_load(net, bus, p_mw, q_mvar=0, const_z_percent=0, const_i_percent=0, sn_mva=nan,
name=None, scaling=1., index=None, in_service=True, type='wye', max_p_mw=nan,
min_p_mw=nan, max_q_mvar=nan, min_q_mvar=nan, controllable=nan):
"""
Adds one load in table net["load"].
All loads are modelled in the consumer system, meaning load is positive and generation is
negative active power. Please pay attention to the correct signing of the reactive power as
well.
INPUT:
**net** - The net within this load should be created
**bus** (int) - The bus id to which the load is connected
OPTIONAL:
**p_mw** (float, default 0) - The active power of the load
- postive value -> load
- negative value -> generation
**q_mvar** (float, default 0) - The reactive power of the load
**const_z_percent** (float, default 0) - percentage of p_mw and q_mvar that will be \
associated to constant impedance load at rated voltage
**const_i_percent** (float, default 0) - percentage of p_mw and q_mvar that will be \
associated to constant current load at rated voltage
**sn_mva** (float, default None) - Nominal power of the load
**name** (string, default None) - The name for this load
**scaling** (float, default 1.) - An OPTIONAL scaling factor to be set customly.
Multiplys with p_mw and q_mvar.
**type** (string, 'wye') - type variable to classify the load: wye/delta
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**in_service** (boolean) - True for in_service or False for out of service
**max_p_mw** (float, default NaN) - Maximum active power load - necessary for controllable \
loads in for OPF
**min_p_mw** (float, default NaN) - Minimum active power load - necessary for controllable \
loads in for OPF
**max_q_mvar** (float, default NaN) - Maximum reactive power load - necessary for \
controllable loads in for OPF
**min_q_mvar** (float, default NaN) - Minimum reactive power load - necessary for \
controllable loads in OPF
**controllable** (boolean, default NaN) - States, whether a load is controllable or not. \
Only respected for OPF; defaults to False if "controllable" column exists in DataFrame
OUTPUT:
**index** (int) - The unique ID of the created element
EXAMPLE:
create_load(net, bus=0, p_mw=10., q_mvar=2.)
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "load", index)
entries = dict(zip(["name", "bus", "p_mw", "const_z_percent", "const_i_percent", "scaling",
"q_mvar", "sn_mva", "in_service", "type"],
[name, bus, p_mw, const_z_percent, const_i_percent, scaling, q_mvar, sn_mva,
bool(in_service), type]))
_set_entries(net, "load", index, True, **entries)
_create_column_and_set_value(net, index, min_p_mw, "min_p_mw", "load")
_create_column_and_set_value(net, index, max_p_mw, "max_p_mw", "load")
_create_column_and_set_value(net, index, min_q_mvar, "min_q_mvar", "load")
_create_column_and_set_value(net, index, max_q_mvar, "max_q_mvar", "load")
_create_column_and_set_value(net, index, controllable, "controllable", "load", dtyp=bool_,
default_val=False, default_for_nan=True)
return index
def create_loads(net, buses, p_mw, q_mvar=0, const_z_percent=0, const_i_percent=0, sn_mva=nan,
name=None, scaling=1., index=None, in_service=True, type=None, max_p_mw=None,
min_p_mw=None, max_q_mvar=None, min_q_mvar=None, controllable=None, **kwargs):
"""
Adds a number of loads in table net["load"].
All loads are modelled in the consumer system, meaning load is positive and generation is
negative active power. Please pay attention to the correct signing of the reactive power as
well.
INPUT:
**net** - The net within this load should be created
**buses** (list of int) - A list of bus ids to which the loads are connected
OPTIONAL:
**p_mw** (list of floats) - The active power of the loads
- postive value -> load
- negative value -> generation
**q_mvar** (list of floats, default 0) - The reactive power of the loads
**const_z_percent** (list of floats, default 0) - percentage of p_mw and q_mvar that will \
be associated to constant impedance loads at rated voltage
**const_i_percent** (list of floats, default 0) - percentage of p_mw and q_mvar that will \
be associated to constant current load at rated voltage
**sn_mva** (list of floats, default None) - Nominal power of the loads
**name** (list of strings, default None) - The name for this load
**scaling** (list of floats, default 1.) - An OPTIONAL scaling factor to be set customly.
Multiplys with p_mw and q_mvar.
**type** (string, None) - type variable to classify the load
**index** (list of int, None) - Force a specified ID if it is available. If None, the index\
is set to a range between one higher than the highest already existing index and the \
length of loads that shall be created.
**in_service** (list of boolean) - True for in_service or False for out of service
**max_p_mw** (list of floats, default NaN) - Maximum active power load - necessary for \
controllable loads in for OPF
**min_p_mw** (list of floats, default NaN) - Minimum active power load - necessary for \
controllable loads in for OPF
**max_q_mvar** (list of floats, default NaN) - Maximum reactive power load - necessary for \
controllable loads in for OPF
**min_q_mvar** (list of floats, default NaN) - Minimum reactive power load - necessary for \
controllable loads in OPF
**controllable** (list of boolean, default NaN) - States, whether a load is controllable \
or not. Only respected for OPF
Defaults to False if "controllable" column exists in DataFrame
OUTPUT:
**index** (int) - The unique IDs of the created elements
EXAMPLE:
create_loads(net, buses=[0, 2], p_mw=[10., 5.], q_mvar=[2., 0.])
"""
_check_multiple_node_elements(net, buses)
index = _get_multiple_index_with_check(net, "load", index, len(buses))
entries = {"bus": buses, "p_mw": p_mw, "q_mvar": q_mvar, "sn_mva": sn_mva,
"const_z_percent": const_z_percent, "const_i_percent": const_i_percent,
"scaling": scaling, "in_service": in_service, "name": name, "type": type}
_add_series_to_entries(entries, index, "min_p_mw", min_p_mw)
_add_series_to_entries(entries, index, "max_p_mw", max_p_mw)
_add_series_to_entries(entries, index, "min_q_mvar", min_q_mvar)
_add_series_to_entries(entries, index, "max_q_mvar", max_q_mvar)
_add_series_to_entries(entries, index, "controllable", controllable, dtyp=bool_,
default_val=False)
_set_multiple_entries(net, "load", index, **entries, **kwargs)
return index
def create_asymmetric_load(net, bus, p_a_mw=0, p_b_mw=0, p_c_mw=0, q_a_mvar=0, q_b_mvar=0,
q_c_mvar=0, sn_mva=nan, name=None, scaling=1., index=None,
in_service=True, type="wye"):
"""
Adds one 3 phase load in table net["asymmetric_load"].
All loads are modelled in the consumer system, meaning load is positive and generation is
negative active power. Please pay attention to the correct signing of the reactive power as
well.
INPUT:
**net** - The net within this load should be created
**bus** (int) - The bus id to which the load is connected
OPTIONAL:
**p_a_mw** (float, default 0) - The active power for Phase A load
**p_b_mw** (float, default 0) - The active power for Phase B load
**p_c_mw** (float, default 0) - The active power for Phase C load
**q_a_mvar** float, default 0) - The reactive power for Phase A load
**q_b_mvar** float, default 0) - The reactive power for Phase B load
**q_c_mvar** (float, default 0) - The reactive power for Phase C load
**sn_kva** (float, default: None) - Nominal power of the load
**name** (string, default: None) - The name for this load
**scaling** (float, default: 1.) - An OPTIONAL scaling factor to be set customly
Multiplys with p_mw and q_mvar of all phases.
**type** (string,default: wye) - type variable to classify three ph load: delta/wye
**index** (int,default: None) - Force a specified ID if it is available. If None, the index\
one higher than the highest already existing index is selected.
**in_service** (boolean) - True for in_service or False for out of service
OUTPUT:
**index** (int) - The unique ID of the created element
EXAMPLE:
**create_asymmetric_load(net, bus=0, p_c_mw = 9., q_c_mvar = 1.8)**
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "asymmetric_load", index, name="3 phase asymmetric_load")
entries = dict(zip(["name", "bus", "p_a_mw", "p_b_mw", "p_c_mw", "scaling", "q_a_mvar",
"q_b_mvar", "q_c_mvar", "sn_mva", "in_service", "type"],
[name, bus, p_a_mw, p_b_mw, p_c_mw, scaling, q_a_mvar, q_b_mvar, q_c_mvar,
sn_mva, bool(in_service), type]))
_set_entries(net, "asymmetric_load", index, True, **entries)
return index
# =============================================================================
# def create_impedance_load(net, bus, r_A , r_B , r_C, x_A=0, x_B=0, x_C=0,
# sn_mva=nan, name=None, scaling=1.,
# index=None, in_service=True, type=None,
# ):
# """
# Creates a constant impedance load element ABC.
#
# INPUT:
# **net** - The net within this constant impedance load should be created
#
# **bus** (int) - The bus id to which the load is connected
#
# **sn_mva** (float) - rated power of the load
#
# **r_A** (float) - Resistance in Phase A
# **r_B** (float) - Resistance in Phase B
# **r_C** (float) - Resistance in Phase C
# **x_A** (float) - Reactance in Phase A
# **x_B** (float) - Reactance in Phase B
# **x_C** (float) - Reactance in Phase C
#
#
# **kwargs are passed on to the create_load function
#
# OUTPUT:
# **index** (int) - The unique ID of the created load
#
# Load elements are modeled from a consumer point of view. Active power will therefore always be
# positive, reactive power will be positive for under-excited behavior (Q absorption, decreases voltage) and negative for over-excited behavior (Q injection, increases voltage)
# """
# if bus not in net["bus"].index.values:
# raise UserWarning("Cannot attach to bus %s, bus does not exist" % bus)
#
# if index is None:
# index = get_free_id(net["asymmetric_load"])
# if index in net["impedance_load"].index:
# raise UserWarning("A 3 phase asymmetric_load with the id %s already exists" % index)
#
# # store dtypes
# dtypes = net.impedance_load.dtypes
#
# net.impedance_load.loc[index, ["name", "bus", "r_A","r_B","r_C", "scaling",
# "x_A","x_B","x_C","sn_mva", "in_service", "type"]] = \
# [name, bus, r_A,r_B,r_C, scaling,
# x_A,x_B,x_C,sn_mva, bool(in_service), type]
#
# # and preserve dtypes
# _preserve_dtypes(net.impedance_load, dtypes)
#
# return index
#
# =============================================================================
def create_load_from_cosphi(net, bus, sn_mva, cos_phi, mode, **kwargs):
"""
Creates a load element from rated power and power factor cos(phi).
INPUT:
**net** - The net within this static generator should be created
**bus** (int) - The bus id to which the load is connected
**sn_mva** (float) - rated power of the load
**cos_phi** (float) - power factor cos_phi
**mode** (str) - "underexcited" (Q absorption, decreases voltage) or "overexcited" (Q injection, increases voltage)
OPTIONAL:
same as in create_load, keyword arguments are passed to the create_load function
OUTPUT:
**index** (int) - The unique ID of the created load
Load elements are modeled from a consumer point of view. Active power will therefore always be
positive, reactive power will be positive for underexcited behavior (Q absorption, decreases voltage) and negative for
overexcited behavior (Q injection, increases voltage).
"""
from pandapower.toolbox import pq_from_cosphi
p_mw, q_mvar = pq_from_cosphi(sn_mva, cos_phi, qmode=mode, pmode="load")
return create_load(net, bus, sn_mva=sn_mva, p_mw=p_mw, q_mvar=q_mvar, **kwargs)
def create_sgen(net, bus, p_mw, q_mvar=0, sn_mva=nan, name=None, index=None,
scaling=1., type='wye', in_service=True, max_p_mw=nan, min_p_mw=nan,
max_q_mvar=nan, min_q_mvar=nan, controllable=nan, k=nan, rx=nan,
current_source=True):
"""
Adds one static generator in table net["sgen"].
Static generators are modelled as positive and constant PQ power. This element is used to model
generators with a constant active and reactive power feed-in. If you want to model a voltage
controlled generator, use the generator element instead.
gen, sgen and ext_grid in the grid are modelled in the generator system!
If you want to model the generation of power, you have to assign a positive active power
to the generator. Please pay attention to the correct signing of the
reactive power as well (positive for injection and negative for consumption).
INPUT:
**net** - The net within this static generator should be created
**bus** (int) - The bus id to which the static generator is connected
**p_mw** (float) - The active power of the static generator (positive for generation!)
OPTIONAL:
**q_mvar** (float, 0) - The reactive power of the sgen
**sn_mva** (float, None) - Nominal power of the sgen
**name** (string, None) - The name for this sgen
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**scaling** (float, 1.) - An OPTIONAL scaling factor to be set customly.
Multiplys with p_mw and q_mvar.
**type** (string, None) - Three phase Connection type of the static generator: wye/delta
**in_service** (boolean) - True for in_service or False for out of service
**max_p_mw** (float, NaN) - Maximum active power injection - necessary for \
controllable sgens in OPF
**min_p_mw** (float, NaN) - Minimum active power injection - necessary for \
controllable sgens in OPF
**max_q_mvar** (float, NaN) - Maximum reactive power injection - necessary for \
controllable sgens in OPF
**min_q_mvar** (float, NaN) - Minimum reactive power injection - necessary for \
controllable sgens in OPF
**controllable** (bool, NaN) - Whether this generator is controllable by the optimal \
powerflow; defaults to False if "controllable" column exists in DataFrame
**k** (float, NaN) - Ratio of nominal current to short circuit current
**rx** (float, NaN) - R/X ratio for short circuit impedance. Only relevant if type is \
specified as motor so that sgen is treated as asynchronous motor
**current_source** (bool, True) - Model this sgen as a current source during short-\
circuit calculations; useful in some cases, for example the simulation of full-\
size converters per IEC 60909-0:2016.
OUTPUT:
**index** (int) - The unique ID of the created sgen
EXAMPLE:
create_sgen(net, 1, p_mw = -120)
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "sgen", index, name="static generator")
entries = dict(zip(["name", "bus", "p_mw", "scaling", "q_mvar", "sn_mva", "in_service", "type",
"current_source"], [name, bus, p_mw, scaling, q_mvar, sn_mva,
bool(in_service), type, current_source]))
_set_entries(net, "sgen", index, True, **entries)
_create_column_and_set_value(net, index, min_p_mw, "min_p_mw", "sgen")
_create_column_and_set_value(net, index, max_p_mw, "max_p_mw", "sgen")
_create_column_and_set_value(net, index, min_q_mvar, "min_q_mvar", "sgen")
_create_column_and_set_value(net, index, max_q_mvar, "max_q_mvar", "sgen")
_create_column_and_set_value(net, index, k, "k", "sgen")
_create_column_and_set_value(net, index, rx, "rx", "sgen")
_create_column_and_set_value(net, index, controllable, "controllable", "sgen", dtyp=bool_,
default_val=False, default_for_nan=True)
return index
def create_sgens(net, buses, p_mw, q_mvar=0, sn_mva=nan, name=None, index=None,
scaling=1., type='wye', in_service=True, max_p_mw=None, min_p_mw=None,
max_q_mvar=None, min_q_mvar=None, controllable=None, k=None, rx=None,
current_source=True, **kwargs):
"""
Adds a number of sgens in table net["sgen"].
Static generators are modelled as positive and constant PQ power. This element is used to model
generators with a constant active and reactive power feed-in. If you want to model a voltage
controlled generator, use the generator element instead.
INPUT:
**net** - The net within this load should be created
**buses** (list of int) - A list of bus ids to which the loads are connected
OPTIONAL:
**p_mw** (list of floats) - The active power of the sgens
- postive value -> generation
- negative value -> load
**q_mvar** (list of floats, default 0) - The reactive power of the sgens
**sn_mva** (list of floats, default None) - Nominal power of the sgens
**name** (list of strings, default None) - The name for this sgen
**scaling** (list of floats, default 1.) - An OPTIONAL scaling factor to be set customly.
Multiplys with p_mw and q_mvar.
**type** (string, None) - type variable to classify the sgen
**index** (list of int, None) - Force a specified ID if it is available. If None, the index\
is set to a range between one higher than the highest already existing index and the \
length of sgens that shall be created.
**in_service** (list of boolean) - True for in_service or False for out of service
**max_p_mw** (list of floats, default NaN) - Maximum active power sgen - necessary for \
controllable sgens in for OPF
**min_p_mw** (list of floats, default NaN) - Minimum active power sgen - necessary for \
controllable sgens in for OPF
**max_q_mvar** (list of floats, default NaN) - Maximum reactive power sgen - necessary for \
controllable sgens in for OPF
**min_q_mvar** (list of floats, default NaN) - Minimum reactive power sgen - necessary for \
controllable sgens in OPF
**controllable** (list of boolean, default NaN) - States, whether a sgen is controllable \
or not. Only respected for OPF
Defaults to False if "controllable" column exists in DataFrame
**k** (list of floats, None) - Ratio of nominal current to short circuit current
**rx** (list of floats, NaN) - R/X ratio for short circuit impedance. Only relevant if type\
is specified as motor so that sgen is treated as asynchronous motor
**current_source** (list of bool, True) - Model this sgen as a current source during short-\
circuit calculations; useful in some cases, for example the simulation of full-\
size converters per IEC 60909-0:2016.
OUTPUT:
**index** (int) - The unique IDs of the created elements
EXAMPLE:
create_sgens(net, buses=[0, 2], p_mw=[10., 5.], q_mvar=[2., 0.])
"""
_check_multiple_node_elements(net, buses)
index = _get_multiple_index_with_check(net, "sgen", index, len(buses))
entries = {"bus": buses, "p_mw": p_mw, "q_mvar": q_mvar, "sn_mva": sn_mva, "scaling": scaling,
"in_service": in_service, "name": name, "type": type,
'current_source': current_source}
_add_series_to_entries(entries, index, "min_p_mw", min_p_mw)
_add_series_to_entries(entries, index, "max_p_mw", max_p_mw)
_add_series_to_entries(entries, index, "min_q_mvar", min_q_mvar)
_add_series_to_entries(entries, index, "max_q_mvar", max_q_mvar)
_add_series_to_entries(entries, index, "k", k)
_add_series_to_entries(entries, index, "rx", rx)
_add_series_to_entries(entries, index, "controllable", controllable, dtyp=bool_,
default_val=False)
_set_multiple_entries(net, "sgen", index, **entries, **kwargs)
return index
# =============================================================================
# Create 3ph Sgen
# =============================================================================
def create_asymmetric_sgen(net, bus, p_a_mw=0, p_b_mw=0, p_c_mw=0, q_a_mvar=0, q_b_mvar=0,
q_c_mvar=0, sn_mva=nan,
name=None, index=None, scaling=1., type='wye', in_service=True):
"""
Adds one static generator in table net["asymmetric_sgen"].
Static generators are modelled as negative PQ loads. This element is used to model generators
with a constant active and reactive power feed-in. Positive active power means generation.
INPUT:
**net** - The net within this static generator should be created
**bus** (int) - The bus id to which the static generator is connected
OPTIONAL:
**p_a_mw** (float, default 0) - The active power of the static generator : Phase A
**p_b_mw** (float, default 0) - The active power of the static generator : Phase B
**p_c_mw** (float, default 0) - The active power of the static generator : Phase C
**q_a_mvar** (float, default 0) - The reactive power of the sgen : Phase A
**q_b_mvar** (float, default 0) - The reactive power of the sgen : Phase B
**q_c_mvar** (float, default 0) - The reactive power of the sgen : Phase C
**sn_mva** (float, default None) - Nominal power of the sgen
**name** (string, default None) - The name for this sgen
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**scaling** (float, 1.) - An OPTIONAL scaling factor to be set customly.
Multiplys with p_mw and q_mvar of all phases.
**type** (string, 'wye') - Three phase Connection type of the static generator: wye/delta
**in_service** (boolean) - True for in_service or False for out of service
OUTPUT:
**index** (int) - The unique ID of the created sgen
EXAMPLE:
create_asymmetric_sgen(net, 1, p_b_mw=0.12)
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "asymmetric_sgen", index,
name="3 phase asymmetric static generator")
entries = dict(zip(["name", "bus", "p_a_mw", "p_b_mw", "p_c_mw", "scaling", "q_a_mvar",
"q_b_mvar", "q_c_mvar", "sn_mva", "in_service", "type"],
[name, bus, p_a_mw, p_b_mw, p_c_mw, scaling, q_a_mvar, q_b_mvar, q_c_mvar,
sn_mva, bool(in_service), type]))
_set_entries(net, "asymmetric_sgen", index, True, **entries)
return index
def create_sgen_from_cosphi(net, bus, sn_mva, cos_phi, mode, **kwargs):
"""
Creates an sgen element from rated power and power factor cos(phi).
INPUT:
**net** - The net within this static generator should be created
**bus** (int) - The bus id to which the static generator is connected
**sn_mva** (float) - rated power of the generator
**cos_phi** (float) - power factor cos_phi
**mode** (str) - "underexcited" (Q absorption, decreases voltage) or "overexcited" (Q injection, increases voltage)
OUTPUT:
**index** (int) - The unique ID of the created sgen
gen, sgen, and ext_grid are modelled in the generator point of view. Active power
will therefore be postive for generation, and reactive power will be negative for
underexcited behavior (Q absorption, decreases voltage) and
positive for for overexcited behavior (Q injection, increases voltage).
"""
from pandapower.toolbox import pq_from_cosphi
p_mw, q_mvar = pq_from_cosphi(sn_mva, cos_phi, qmode=mode, pmode="gen")
return create_sgen(net, bus, sn_mva=sn_mva, p_mw=p_mw, q_mvar=q_mvar, **kwargs)
def create_storage(net, bus, p_mw, max_e_mwh, q_mvar=0, sn_mva=nan, soc_percent=nan, min_e_mwh=0.0,
name=None, index=None, scaling=1., type=None, in_service=True, max_p_mw=nan,
min_p_mw=nan, max_q_mvar=nan, min_q_mvar=nan, controllable=nan):
"""
Adds a storage to the network.
In order to simulate a storage system it is possible to use sgens or loads to model the
discharging or charging state. The power of a storage can be positive or negative, so the use
of either a sgen or a load is (per definition of the elements) not correct.
To overcome this issue, a storage element can be created.
As pandapower is not a time dependend simulation tool and there is no time domain parameter in
default power flow calculations, the state of charge (SOC) is not updated during any power flow
calculation.
The implementation of energy content related parameters in the storage element allows to create
customized, time dependend simulations by running several power flow calculations and updating
variables manually.
INPUT:
**net** - The net within this storage should be created
**bus** (int) - The bus id to which the storage is connected
**p_mw** (float) - The momentary active power of the storage \
(positive for charging, negative for discharging)
**max_e_mwh** (float) - The maximum energy content of the storage \
(maximum charge level)
OPTIONAL:
**q_mvar** (float, default 0) - The reactive power of the storage
**sn_mva** (float, default None) - Nominal power of the storage
**soc_percent** (float, NaN) - The state of charge of the storage
**min_e_mwh** (float, 0) - The minimum energy content of the storage \
(minimum charge level)
**name** (string, default None) - The name for this storage
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**scaling** (float, 1.) - An OPTIONAL scaling factor to be set customly.
Multiplys with p_mw and q_mvar.
**type** (string, None) - type variable to classify the storage
**in_service** (boolean) - True for in_service or False for out of service
**max_p_mw** (float, NaN) - Maximum active power injection - necessary for a \
controllable storage in OPF
**min_p_mw** (float, NaN) - Minimum active power injection - necessary for a \
controllable storage in OPF
**max_q_mvar** (float, NaN) - Maximum reactive power injection - necessary for a \
controllable storage in OPF
**min_q_mvar** (float, NaN) - Minimum reactive power injection - necessary for a \
controllable storage in OPF
**controllable** (bool, NaN) - Whether this storage is controllable by the optimal \
powerflow; defaults to False if "controllable" column exists in DataFrame
OUTPUT:
**index** (int) - The unique ID of the created storage
EXAMPLE:
create_storage(net, 1, p_mw = -30, max_e_mwh = 60, soc_percent = 1.0, min_e_mwh = 5)
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "storage", index)
entries = dict(zip(["name", "bus", "p_mw", "q_mvar", "sn_mva", "scaling", "soc_percent",
"min_e_mwh", "max_e_mwh", "in_service", "type"],
[name, bus, p_mw, q_mvar, sn_mva, scaling, soc_percent, min_e_mwh, max_e_mwh,
bool(in_service), type]))
_set_entries(net, "storage", index, True, **entries)
# check for OPF parameters and add columns to network table
_create_column_and_set_value(net, index, min_p_mw, "min_p_mw", "storage")
_create_column_and_set_value(net, index, max_p_mw, "max_p_mw", "storage")
_create_column_and_set_value(net, index, min_q_mvar, "min_q_mvar", "storage")
_create_column_and_set_value(net, index, max_q_mvar, "max_q_mvar", "storage")
_create_column_and_set_value(net, index, controllable, "controllable", "storage",
dtyp=bool_, default_val=False, default_for_nan=True)
return index
def create_gen(net, bus, p_mw, vm_pu=1., sn_mva=nan, name=None, index=None, max_q_mvar=nan,
min_q_mvar=nan, min_p_mw=nan, max_p_mw=nan, min_vm_pu=nan, max_vm_pu=nan,
scaling=1., type=None, slack=False, controllable=nan, vn_kv=nan,
xdss_pu=nan, rdss_ohm=nan, cos_phi=nan, pg_percent=nan, power_station_trafo=None,
in_service=True, slack_weight=0.0):
"""
Adds a generator to the network.
Generators are always modelled as voltage controlled PV nodes, which is why the input parameter
is active power and a voltage set point. If you want to model a generator as PQ load with fixed
reactive power and variable voltage, please use a static generator instead.
INPUT:
**net** - The net within this generator should be created
**bus** (int) - The bus id to which the generator is connected
OPTIONAL:
**p_mw** (float, default 0) - The active power of the generator (positive for generation!)
**vm_pu** (float, default 0) - The voltage set point of the generator.
**sn_mva** (float, None) - Nominal power of the generator
**name** (string, None) - The name for this generator
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**scaling** (float, 1.0) - scaling factor which for the active power of the generator
**type** (string, None) - type variable to classify generators
**controllable** (bool, NaN) - True: p_mw, q_mvar and vm_pu limits are enforced for this \
generator in OPF
False: p_mw and vm_pu setpoints are enforced and *limits are ignored*.
defaults to True if "controllable" column exists in DataFrame
**slack_weight** (float, default 0.0) - Contribution factor for distributed slack power
flow calculation (active power balancing)
powerflow
**vn_kv** (float, NaN) - Rated voltage of the generator for short-circuit calculation
**xdss_pu** (float, NaN) - Subtransient generator reactance for short-circuit calculation
**rdss_ohm** (float, NaN) - Subtransient generator resistance for short-circuit calculation
**cos_phi** (float, NaN) - Rated cosine phi of the generator for short-circuit calculation
**pg_percent** (float, NaN) - Rated pg (voltage control range) of the generator for
short-circuit calculation
**power_station_trafo** (int, None) - Index of the power station transformer for
short-circuit calculation
**in_service** (bool, True) - True for in_service or False for out of service
**max_p_mw** (float, default NaN) - Maximum active power injection - necessary for OPF
**min_p_mw** (float, default NaN) - Minimum active power injection - necessary for OPF
**max_q_mvar** (float, default NaN) - Maximum reactive power injection - necessary for OPF
**min_q_mvar** (float, default NaN) - Minimum reactive power injection - necessary for OPF
**min_vm_pu** (float, default NaN) - Minimum voltage magnitude. If not set the bus voltage \
limit is taken.
- necessary for OPF.
**max_vm_pu** (float, default NaN) - Maximum voltage magnitude. If not set the bus voltage\
limit is taken.
- necessary for OPF
OUTPUT:
**index** (int) - The unique ID of the created generator
EXAMPLE:
create_gen(net, 1, p_mw = 120, vm_pu = 1.02)
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "gen", index, name="generator")
columns = ["name", "bus", "p_mw", "vm_pu", "sn_mva", "type", "slack", "in_service",
"scaling", "slack_weight"]
variables = [name, bus, p_mw, vm_pu, sn_mva, type, slack, bool(in_service), scaling,
slack_weight]
_set_entries(net, "gen", index, True, **dict(zip(columns, variables)))
# OPF limits
if not isnan(controllable):
if "controllable" not in net.gen.columns:
net.gen.loc[:, "controllable"] = pd.Series(dtype=bool, data=True)
net.gen.at[index, "controllable"] = bool(controllable)
elif "controllable" in net.gen.columns:
net.gen.at[index, "controllable"] = True
# P limits for OPF if controllable == True
_create_column_and_set_value(net, index, min_p_mw, "min_p_mw", "gen")
_create_column_and_set_value(net, index, max_p_mw, "max_p_mw", "gen")
# Q limits for OPF if controllable == True
_create_column_and_set_value(net, index, min_q_mvar, "min_q_mvar", "gen")
_create_column_and_set_value(net, index, max_q_mvar, "max_q_mvar", "gen")
# V limits for OPF if controllable == True
_create_column_and_set_value(net, index, max_vm_pu, "max_vm_pu", "gen", default_val=2.)
_create_column_and_set_value(net, index, min_vm_pu, "min_vm_pu", "gen", default_val=0.)
# Short circuit calculation variables
_create_column_and_set_value(net, index, vn_kv, "vn_kv", "gen")
_create_column_and_set_value(net, index, cos_phi, "cos_phi", "gen")
_create_column_and_set_value(net, index, xdss_pu, "xdss_pu", "gen")
_create_column_and_set_value(net, index, rdss_ohm, "rdss_ohm", "gen")
_create_column_and_set_value(net, index, pg_percent, "pg_percent", "gen")
_create_column_and_set_value(net, index, power_station_trafo,
"power_station_trafo", "gen")
return index
def create_gens(net, buses, p_mw, vm_pu=1., sn_mva=nan, name=None, index=None, max_q_mvar=None,
min_q_mvar=None, min_p_mw=None, max_p_mw=None, min_vm_pu=None, max_vm_pu=None,
scaling=1., type=None, slack=False, controllable=None, vn_kv=None,
xdss_pu=None, rdss_ohm=None, cos_phi=None, pg_percent=None, power_station_trafo=None,
in_service=True, slack_weight=0.0, **kwargs):
"""
Adds generators to the specified buses network.
Generators are always modelled as voltage controlled PV nodes, which is why the input parameter
is active power and a voltage set point. If you want to model a generator as PQ load with fixed
reactive power and variable voltage, please use a static generator instead.
INPUT:
**net** - The net within this generator should be created
**buses** (list of int) - The bus ids to which the generators are connected
OPTIONAL:
**p_mw** (list of float, default 0) - The active power of the generator (positive for \
generation!)
**vm_pu** (list of float, default 0) - The voltage set point of the generator.
**sn_mva** (list of float, None) - Nominal power of the generator
**name** (list of string, None) - The name for this generator
**index** (list of int, None) - Force a specified ID if it is available. If None, the index\
one higher than the highest already existing index is selected.
**scaling** (list of float, 1.0) - scaling factor which for the active power of the\
generator
**type** (list of string, None) - type variable to classify generators
**controllable** (bool, NaN) - True: p_mw, q_mvar and vm_pu limits are enforced for this \
generator in OPF
False: p_mw and vm_pu setpoints are enforced and \
*limits are ignored*.
defaults to True if "controllable" column exists in DataFrame
powerflow
**vn_kv** (list of float, NaN) - Rated voltage of the generator for short-circuit \
calculation
**xdss_pu** (list of float, NaN) - Subtransient generator reactance for short-circuit \
calculation
**rdss_ohm** (list of float, NaN) - Subtransient generator resistance for short-circuit \
calculation
**cos_phi** (list of float, NaN) - Rated cosine phi of the generator for short-circuit \
calculation
**pg_percent** (float, NaN) - Rated pg (voltage control range) of the generator for \
short-circuit calculation
**power_station_trafo** (int, None) - Index of the power station transformer for short-circuit calculation
**in_service** (bool, True) - True for in_service or False for out of service
**slack_weight** (float, default 0.0) - Contribution factor for distributed slack power flow calculation (active power balancing)
**max_p_mw** (list of float, default NaN) - Maximum active power injection - necessary for\
OPF
**min_p_mw** (list of float, default NaN) - Minimum active power injection - necessary for \
OPF
**max_q_mvar** (list of float, default NaN) - Maximum reactive power injection - necessary\
for OPF
**min_q_mvar** (list of float, default NaN) - Minimum reactive power injection - necessary \
for OPF
**min_vm_pu** (list of float, default NaN) - Minimum voltage magnitude. If not set the \
bus voltage limit is taken.
- necessary for OPF.
**max_vm_pu** (list of float, default NaN) - Maximum voltage magnitude. If not set the bus\
voltage limit is taken.
- necessary for OPF
OUTPUT:
**index** (int) - The unique ID of the created generator
EXAMPLE:
create_gen(net, 1, p_mw = 120, vm_pu = 1.02)
"""
_check_multiple_node_elements(net, buses)
index = _get_multiple_index_with_check(net, "gen", index, len(buses))
entries = {"bus": buses, "p_mw": p_mw, "vm_pu": vm_pu, "sn_mva": sn_mva, "scaling": scaling,
"in_service": in_service, "slack_weight": slack_weight, "name": name, "type": type, "slack": slack}
_add_series_to_entries(entries, index, "min_p_mw", min_p_mw)
_add_series_to_entries(entries, index, "max_p_mw", max_p_mw)
_add_series_to_entries(entries, index, "min_q_mvar", min_q_mvar)
_add_series_to_entries(entries, index, "max_q_mvar", max_q_mvar)
_add_series_to_entries(entries, index, "min_vm_pu", min_vm_pu)
_add_series_to_entries(entries, index, "max_vm_pu", max_vm_pu)
_add_series_to_entries(entries, index, "vn_kv", vn_kv)
_add_series_to_entries(entries, index, "cos_phi", cos_phi)
_add_series_to_entries(entries, index, "xdss_pu", xdss_pu)
_add_series_to_entries(entries, index, "rdss_ohm", rdss_ohm)
_add_series_to_entries(entries, index, "pg_percent", pg_percent)
_add_series_to_entries(entries, index, "power_station_trafo", power_station_trafo)
_add_series_to_entries(entries, index, "controllable", controllable, dtyp=bool_,
default_val=False)
_set_multiple_entries(net, "gen", index, **entries, **kwargs)
return index
def create_motor(net, bus, pn_mech_mw, cos_phi, efficiency_percent=100., loading_percent=100.,
name=None, lrc_pu=nan, scaling=1.0, vn_kv=nan, rx=nan, index=None, in_service=True,
cos_phi_n=nan, efficiency_n_percent=nan):
"""
Adds a motor to the network.
INPUT:
**net** - The net within this motor should be created
**bus** (int) - The bus id to which the motor is connected
**pn_mech_mw** (float) - Mechanical rated power of the motor
**cos_phi** (float, nan) - cosine phi at current operating point
OPTIONAL:
**name** (string, None) - The name for this motor
**efficiency_percent** (float, 100) - Efficiency in percent at current operating point
**loading_percent** (float, 100) - The mechanical loading in percentage of the rated \
mechanical power
**scaling** (float, 1.0) - scaling factor which for the active power of the motor
**cos_phi_n** (float, nan) - cosine phi at rated power of the motor for short-circuit \
calculation
**efficiency_n_percent** (float, 100) - Efficiency in percent at rated power for \
short-circuit calculation
**lrc_pu** (float, nan) - locked rotor current in relation to the rated motor current
**rx** (float, nan) - R/X ratio of the motor for short-circuit calculation.
**vn_kv** (float, NaN) - Rated voltage of the motor for short-circuit calculation
**in_service** (bool, True) - True for in_service or False for out of service
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
OUTPUT:
**index** (int) - The unique ID of the created motor
EXAMPLE:
create_motor(net, 1, pn_mech_mw = 0.120, cos_ph=0.9, vn_kv=0.6, efficiency_percent=90, \
loading_percent=40, lrc_pu=6.0)
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "motor", index)
columns = ["name", "bus", "pn_mech_mw", "cos_phi", "cos_phi_n", "vn_kv", "rx",
"efficiency_n_percent", "efficiency_percent", "loading_percent",
"lrc_pu", "scaling", "in_service"]
variables = [name, bus, pn_mech_mw, cos_phi, cos_phi_n, vn_kv, rx, efficiency_n_percent,
efficiency_percent, loading_percent, lrc_pu, scaling, bool(in_service)]
_set_entries(net, "motor", index, **dict(zip(columns, variables)))
return index
def create_ext_grid(net, bus, vm_pu=1.0, va_degree=0., name=None, in_service=True,
s_sc_max_mva=nan, s_sc_min_mva=nan, rx_max=nan, rx_min=nan,
max_p_mw=nan, min_p_mw=nan, max_q_mvar=nan, min_q_mvar=nan,
index=None, r0x0_max=nan, x0x_max=nan, controllable=nan,
slack_weight=1.0, **kwargs):
"""
Creates an external grid connection.
External grids represent the higher level power grid connection and are modelled as the slack
bus in the power flow calculation.
INPUT:
**net** - pandapower network
**bus** (int) - bus where the slack is connected
OPTIONAL:
**vm_pu** (float, default 1.0) - voltage at the slack node in per unit
**va_degree** (float, default 0.) - voltage angle at the slack node in degrees*
**name** (string, default None) - name of of the external grid
**in_service** (boolean) - True for in_service or False for out of service
**s_sc_max_mva** (float, NaN) - maximal short circuit apparent power to calculate internal \
impedance of ext_grid for short circuit calculations
**s_sc_min_mva** (float, NaN) - minimal short circuit apparent power to calculate internal \
impedance of ext_grid for short circuit calculations
**rx_max** (float, NaN) - maximal R/X-ratio to calculate internal impedance of ext_grid \
for short circuit calculations
**rx_min** (float, NaN) - minimal R/X-ratio to calculate internal impedance of ext_grid \
for short circuit calculations
**max_p_mw** (float, NaN) - Maximum active power injection. Only respected for OPF
**min_p_mw** (float, NaN) - Minimum active power injection. Only respected for OPF
**max_q_mvar** (float, NaN) - Maximum reactive power injection. Only respected for OPF
**min_q_mvar** (float, NaN) - Minimum reactive power injection. Only respected for OPF
**r0x0_max** (float, NaN) - maximal R/X-ratio to calculate Zero sequence
internal impedance of ext_grid
**x0x_max** (float, NaN) - maximal X0/X-ratio to calculate Zero sequence
internal impedance of ext_grid
**slack_weight** (float, default 1.0) - Contribution factor for distributed slack power flow calculation (active power balancing)
** only considered in loadflow if calculate_voltage_angles = True
**controllable** (bool, NaN) - True: p_mw, q_mvar and vm_pu limits are enforced for the \
ext_grid in OPF. The voltage limits set in the \
ext_grid bus are enforced.
False: p_mw and vm_pu setpoints are enforced and *limits are\
ignored*. The vm_pu setpoint is enforced and limits \
of the bus table are ignored.
defaults to False if "controllable" column exists in\
DataFrame
EXAMPLE:
create_ext_grid(net, 1, voltage = 1.03)
For three phase load flow
create_ext_grid(net, 1, voltage=1.03, s_sc_max_mva=1000, rx_max=0.1, r0x0_max=0.1,\
x0x_max=1.0)
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "ext_grid", index, name="external grid")
entries = dict(zip(["bus", "name", "vm_pu", "va_degree", "in_service", "slack_weight"],
[bus, name, vm_pu, va_degree, bool(in_service), slack_weight]))
_set_entries(net, "ext_grid", index, **entries, **kwargs)
# OPF limits
_create_column_and_set_value(net, index, s_sc_max_mva, "s_sc_max_mva", "ext_grid")
_create_column_and_set_value(net, index, s_sc_min_mva, "s_sc_min_mva", "ext_grid")
_create_column_and_set_value(net, index, rx_min, "rx_min", "ext_grid")
_create_column_and_set_value(net, index, rx_max, "rx_max", "ext_grid")
_create_column_and_set_value(net, index, min_p_mw, "min_p_mw", "ext_grid")
_create_column_and_set_value(net, index, max_p_mw, "max_p_mw", "ext_grid")
_create_column_and_set_value(net, index, min_q_mvar, "min_q_mvar", "ext_grid")
_create_column_and_set_value(net, index, max_q_mvar, "max_q_mvar", "ext_grid")
_create_column_and_set_value(net, index, x0x_max, "x0x_max", "ext_grid")
_create_column_and_set_value(net, index, r0x0_max, "r0x0_max", "ext_grid")
_create_column_and_set_value(net, index, controllable, "controllable", "ext_grid",
dtyp=bool_, default_val=False, default_for_nan=True)
return index
def create_line(net, from_bus, to_bus, length_km, std_type, name=None, index=None, geodata=None,
df=1., parallel=1, in_service=True, max_loading_percent=nan, alpha=nan,
temperature_degree_celsius=nan):
"""
Creates a line element in net["line"]
The line parameters are defined through the standard type library.
INPUT:
**net** - The net within this line should be created
**from_bus** (int) - ID of the bus on one side which the line will be connected with
**to_bus** (int) - ID of the bus on the other side which the line will be connected with
**length_km** (float) - The line length in km
**std_type** (string) - Name of a standard linetype :
- Pre-defined in standard_linetypes
**or**
- Customized std_type made using **create_std_type()**
OPTIONAL:
**name** (string, None) - A custom name for this line
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**geodata**
(array, default None, shape= (,2L)) -
The linegeodata of the line. The first row should be the coordinates
of bus a and the last should be the coordinates of bus b. The points
in the middle represent the bending points of the line
**in_service** (boolean, True) - True for in_service or False for out of service
**df** (float, 1) - derating factor: maximal current of line in relation to nominal current\
of line (from 0 to 1)
**parallel** (integer, 1) - number of parallel line systems
**max_loading_percent (float)** - maximum current loading (only needed for OPF)
OUTPUT:
**index** (int) - The unique ID of the created line
EXAMPLE:
create_line(net, "line1", from_bus = 0, to_bus = 1, length_km=0.1, std_type="NAYY 4x50 SE")
"""
# check if bus exist to attach the line to
_check_branch_element(net, "Line", index, from_bus, to_bus)
index = _get_index_with_check(net, "line", index)
v = {
"name": name, "length_km": length_km, "from_bus": from_bus,
"to_bus": to_bus, "in_service": bool(in_service), "std_type": std_type,
"df": df, "parallel": parallel
}
lineparam = load_std_type(net, std_type, "line")
v.update({param: lineparam[param] for param in ["r_ohm_per_km", "x_ohm_per_km", "c_nf_per_km",
"max_i_ka"]})
if "r0_ohm_per_km" in lineparam:
v.update({param: lineparam[param] for param in ["r0_ohm_per_km", "x0_ohm_per_km", "c0_nf_per_km"]})
v["g_us_per_km"] = lineparam["g_us_per_km"] if "g_us_per_km" in lineparam else 0.
if "type" in lineparam:
v["type"] = lineparam["type"]
# if net.line column already has alpha, add it from std_type
if "alpha" in net.line.columns and "alpha" in lineparam:
v["alpha"] = lineparam["alpha"]
_set_entries(net, "line", index, **v)
if geodata is not None:
net["line_geodata"].loc[index, "coords"] = None
net["line_geodata"].at[index, "coords"] = geodata
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "line")
_create_column_and_set_value(net, index, alpha, "alpha", "line")
_create_column_and_set_value(net, index, temperature_degree_celsius,
"temperature_degree_celsius", "line")
return index
def create_lines(net, from_buses, to_buses, length_km, std_type, name=None, index=None,
geodata=None, df=1., parallel=1, in_service=True, max_loading_percent=None):
""" Convenience function for creating many lines at once. Parameters 'from_buses' and 'to_buses'
must be arrays of equal length. Other parameters may be either arrays of the same length or
single or values. In any case the line parameters are defined through a single standard
type, so all lines have the same standard type.
INPUT:
**net** - The net within this line should be created
**from_buses** (list of int) - ID of the bus on one side which the line will be \
connected with
**to_buses** (list of int) - ID of the bus on the other side which the line will be \
connected with
**length_km** (list of float) - The line length in km
**std_type** (string) - The linetype of the lines.
OPTIONAL:
**name** (list of string, None) - A custom name for this line
**index** (list of int, None) - Force a specified ID if it is available. If None, the\
index one higher than the highest already existing index is selected.
**geodata**
(list of arrays, default None, shape of arrays (,2L)) -
The linegeodata of the line. The first row should be the coordinates
of bus a and the last should be the coordinates of bus b. The points
in the middle represent the bending points of the line
**in_service** (list of boolean, True) - True for in_service or False for out of service
**df** (list of float, 1) - derating factor: maximal current of line in relation to \
nominal current of line (from 0 to 1)
**parallel** (list of integer, 1) - number of parallel line systems
**max_loading_percent (list of float)** - maximum current loading (only needed for OPF)
OUTPUT:
**index** (list of int) - The unique ID of the created line
EXAMPLE:
create_line(net, "line1", from_bus=0, to_bus=1, length_km=0.1, std_type="NAYY 4x50 SE")
"""
_check_multiple_branch_elements(net, from_buses, to_buses, "Lines")
index = _get_multiple_index_with_check(net, "line", index, len(from_buses))
entries = {"from_bus": from_buses, "to_bus": to_buses, "length_km": length_km,
"std_type": std_type, "name": name, "df": df, "parallel": parallel,
"in_service": in_service}
# add std type data
if isinstance(std_type, str):
lineparam = load_std_type(net, std_type, "line")
entries["r_ohm_per_km"] = lineparam["r_ohm_per_km"]
entries["x_ohm_per_km"] = lineparam["x_ohm_per_km"]
entries["c_nf_per_km"] = lineparam["c_nf_per_km"]
entries["max_i_ka"] = lineparam["max_i_ka"]
entries["g_us_per_km"] = lineparam["g_us_per_km"] if "g_us_per_km" in lineparam else 0.
if "type" in lineparam:
entries["type"] = lineparam["type"]
else:
lineparam = list(map(load_std_type, [net] * len(std_type), std_type, ['line'] * len(std_type)))
entries["r_ohm_per_km"] = list(map(itemgetter("r_ohm_per_km"), lineparam))
entries["x_ohm_per_km"] = list(map(itemgetter("x_ohm_per_km"), lineparam))
entries["c_nf_per_km"] = list(map(itemgetter("c_nf_per_km"), lineparam))
entries["max_i_ka"] = list(map(itemgetter("max_i_ka"), lineparam))
entries["g_us_per_km"] = list(map(check_entry_in_std_type, lineparam, ["g_us_per_km"] * len(lineparam),
[0.] * len(lineparam)))
entries["type"] = list(map(check_entry_in_std_type, lineparam, ["type"] * len(lineparam),
[None] * len(lineparam)))
_add_series_to_entries(entries, index, "max_loading_percent", max_loading_percent)
_set_multiple_entries(net, "line", index, **entries)
if geodata is not None:
_add_multiple_branch_geodata(net, "line", geodata, index)
return index
def create_line_from_parameters(net, from_bus, to_bus, length_km, r_ohm_per_km, x_ohm_per_km,
c_nf_per_km, max_i_ka, name=None, index=None, type=None,
geodata=None, in_service=True, df=1., parallel=1, g_us_per_km=0.,
max_loading_percent=nan, alpha=nan,
temperature_degree_celsius=nan, r0_ohm_per_km=nan,
x0_ohm_per_km=nan, c0_nf_per_km=nan, g0_us_per_km=0,
endtemp_degree=nan, **kwargs):
"""
Creates a line element in net["line"] from line parameters.
INPUT:
**net** - The net within this line should be created
**from_bus** (int) - ID of the bus on one side which the line will be connected with
**to_bus** (int) - ID of the bus on the other side which the line will be connected with
**length_km** (float) - The line length in km
**r_ohm_per_km** (float) - line resistance in ohm per km
**x_ohm_per_km** (float) - line reactance in ohm per km
**c_nf_per_km** (float) - line capacitance (line-to-earth) in nano Farad per km
**r0_ohm_per_km** (float) - zero sequence line resistance in ohm per km
**x0_ohm_per_km** (float) - zero sequence line reactance in ohm per km
**c0_nf_per_km** (float) - zero sequence line capacitance in nano Farad per km
**max_i_ka** (float) - maximum thermal current in kilo Ampere
OPTIONAL:
**name** (string, None) - A custom name for this line
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**in_service** (boolean, True) - True for in_service or False for out of service
**type** (str, None) - type of line ("ol" for overhead line or "cs" for cable system)
**df** (float, 1) - derating factor: maximal current of line in relation to nominal current\
of line (from 0 to 1)
**g_us_per_km** (float, 0) - dielectric conductance in micro Siemens per km
**g0_us_per_km** (float, 0) - zero sequence dielectric conductance in micro Siemens per km
**parallel** (integer, 1) - number of parallel line systems
**geodata**
(array, default None, shape= (,2L)) -
The linegeodata of the line. The first row should be the coordinates
of bus a and the last should be the coordinates of bus b. The points
in the middle represent the bending points of the line
**max_loading_percent (float)** - maximum current loading (only needed for OPF)
OUTPUT:
**index** (int) - The unique ID of the created line
EXAMPLE:
create_line_from_parameters(net, "line1", from_bus = 0, to_bus = 1, lenght_km=0.1,
r_ohm_per_km = .01, x_ohm_per_km = 0.05, c_nf_per_km = 10,
max_i_ka = 0.4)
"""
# check if bus exist to attach the line to
_check_branch_element(net, "Line", index, from_bus, to_bus)
index = _get_index_with_check(net, "line", index)
v = {
"name": name, "length_km": length_km, "from_bus": from_bus,
"to_bus": to_bus, "in_service": bool(in_service), "std_type": None,
"df": df, "r_ohm_per_km": r_ohm_per_km, "x_ohm_per_km": x_ohm_per_km,
"c_nf_per_km": c_nf_per_km, "max_i_ka": max_i_ka, "parallel": parallel, "type": type,
"g_us_per_km": g_us_per_km
}
_set_entries(net, "line", index, **v, **kwargs)
nan_0_values = [isnan(r0_ohm_per_km), isnan(x0_ohm_per_km), isnan(c0_nf_per_km)]
if not np_any(nan_0_values):
_create_column_and_set_value(net, index, r0_ohm_per_km, "r0_ohm_per_km", "line")
_create_column_and_set_value(net, index, x0_ohm_per_km, "x0_ohm_per_km", "line")
_create_column_and_set_value(net, index, c0_nf_per_km, "c0_nf_per_km", "line")
_create_column_and_set_value(net, index, g0_us_per_km, "g0_us_per_km", "line",
default_val=0.)
elif not np_all(nan_0_values):
logger.warning("Zero sequence values are given for only some parameters. Please specify "
"them for all parameters, otherwise they are not set!")
if geodata is not None:
net["line_geodata"].loc[index, "coords"] = None
net["line_geodata"].at[index, "coords"] = geodata
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "line")
_create_column_and_set_value(net, index, alpha, "alpha", "line")
_create_column_and_set_value(net, index, temperature_degree_celsius,
"temperature_degree_celsius", "line")
_create_column_and_set_value(net, index, endtemp_degree, "endtemp_degree", "line")
return index
def create_lines_from_parameters(net, from_buses, to_buses, length_km, r_ohm_per_km, x_ohm_per_km,
c_nf_per_km, max_i_ka, name=None, index=None, type=None,
geodata=None, in_service=True, df=1., parallel=1, g_us_per_km=0.,
max_loading_percent=None, alpha=None,
temperature_degree_celsius=None, r0_ohm_per_km=None,
x0_ohm_per_km=None, c0_nf_per_km=None, g0_us_per_km=None,
**kwargs):
"""
Convenience function for creating many lines at once. Parameters 'from_buses' and 'to_buses'
must be arrays of equal length. Other parameters may be either arrays of the same length or
single or values.
INPUT:
**net** - The net within this line should be created
**from_bus** (list of int) - ID of the bus on one side which the line will be connected with
**to_bus** (list of int) - ID of the bus on the other side which the line will be connected\
with
**length_km** (list of float) - The line length in km
**r_ohm_per_km** (list of float) - line resistance in ohm per km
**x_ohm_per_km** (list of float) - line reactance in ohm per km
**c_nf_per_km** (list of float) - line capacitance in nano Farad per km
**r0_ohm_per_km** (list of float) - zero sequence line resistance in ohm per km
**x0_ohm_per_km** (list of float) - zero sequence line reactance in ohm per km
**c0_nf_per_km** (list of float) - zero sequence line capacitance in nano Farad per km
**max_i_ka** (list of float) - maximum thermal current in kilo Ampere
OPTIONAL:
**name** (string, None) - A custom name for this line
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**in_service** (boolean, True) - True for in_service or False for out of service
**type** (str, None) - type of line ("ol" for overhead line or "cs" for cable system)
**df** (float, 1) - derating factor: maximal current of line in relation to nominal current\
of line (from 0 to 1)
**g_us_per_km** (float, 0) - dielectric conductance in micro Siemens per km
**g0_us_per_km** (float, 0) - zero sequence dielectric conductance in micro Siemens per km
**parallel** (integer, 1) - number of parallel line systems
**geodata**
(array, default None, shape= (,2L)) -
The linegeodata of the line. The first row should be the coordinates
of bus a and the last should be the coordinates of bus b. The points
in the middle represent the bending points of the line
**max_loading_percent (float)** - maximum current loading (only needed for OPF)
OUTPUT:
**index** (int) - The unique ID of the created line
EXAMPLE:
create_line_from_parameters(net, "line1", from_bus = 0, to_bus = 1, lenght_km=0.1,
r_ohm_per_km = .01, x_ohm_per_km = 0.05, c_nf_per_km = 10,
max_i_ka = 0.4)
"""
_check_multiple_branch_elements(net, from_buses, to_buses, "Lines")
index = _get_multiple_index_with_check(net, "line", index, len(from_buses))
entries = {"from_bus": from_buses, "to_bus": to_buses, "length_km": length_km, "type": type,
"r_ohm_per_km": r_ohm_per_km, "x_ohm_per_km": x_ohm_per_km,
"c_nf_per_km": c_nf_per_km, "max_i_ka": max_i_ka, "g_us_per_km": g_us_per_km,
"name": name, "df": df, "parallel": parallel, "in_service": in_service}
_add_series_to_entries(entries, index, "max_loading_percent", max_loading_percent)
_add_series_to_entries(entries, index, "r0_ohm_per_km", r0_ohm_per_km)
_add_series_to_entries(entries, index, "x0_ohm_per_km", x0_ohm_per_km)
_add_series_to_entries(entries, index, "c0_nf_per_km", c0_nf_per_km)
_add_series_to_entries(entries, index, "g0_us_per_km", g0_us_per_km)
_add_series_to_entries(entries, index, "temperature_degree_celsius", temperature_degree_celsius)
_add_series_to_entries(entries, index, "alpha", alpha)
_set_multiple_entries(net, "line", index, **entries, **kwargs)
if geodata is not None:
_add_multiple_branch_geodata(net, "line", geodata, index)
return index
def create_transformer(net, hv_bus, lv_bus, std_type, name=None, tap_pos=nan, in_service=True,
index=None, max_loading_percent=nan, parallel=1, df=1.,
tap_dependent_impedance=None, vk_percent_characteristic=None,
vkr_percent_characteristic=None):
"""
Creates a two-winding transformer in table net["trafo"].
The trafo parameters are defined through the standard type library.
INPUT:
**net** - The net within this transformer should be created
**hv_bus** (int) - The bus on the high-voltage side on which the transformer will be \
connected to
**lv_bus** (int) - The bus on the low-voltage side on which the transformer will be \
connected to
**std_type** - The used standard type from the standard type library
**Zero sequence parameters** (Added through std_type For Three phase load flow) :
**vk0_percent** - zero sequence relative short-circuit voltage
**vkr0_percent** - real part of zero sequence relative short-circuit voltage
**mag0_percent** - ratio between magnetizing and short circuit impedance (zero sequence)
z_mag0 / z0
**mag0_rx** - zero sequence magnetizing r/x ratio
**si0_hv_partial** - zero sequence short circuit impedance distribution in hv side
OPTIONAL:
**name** (string, None) - A custom name for this transformer
**tap_pos** (int, nan) - current tap position of the transformer. Defaults to the medium \
position (tap_neutral)
**in_service** (boolean, True) - True for in_service or False for out of service
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**max_loading_percent (float)** - maximum current loading (only needed for OPF)
**parallel** (integer) - number of parallel transformers
**df** (float) - derating factor: maximal current of transformer in relation to nominal \
current of transformer (from 0 to 1)
**tap_dependent_impedance** (boolean) - True if transformer impedance must be adjusted dependent \
on the tap position of the trabnsformer. Requires the additional columns \
"vk_percent_characteristic" and "vkr_percent_characteristic" that reference the index of the \
characteristic from the table net.characteristic. A convenience function \
pandapower.control.create_trafo_characteristics can be used to create the SplineCharacteristic \
objects, add the relevant columns and set up the references to the characteristics. \
The function pandapower.control.trafo_characteristics_diagnostic can be used for sanity checks.
**vk_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
OUTPUT:
**index** (int) - The unique ID of the created transformer
EXAMPLE:
create_transformer(net, hv_bus = 0, lv_bus = 1, name = "trafo1", std_type = \
"0.4 MVA 10/0.4 kV")
"""
# Check if bus exist to attach the trafo to
_check_branch_element(net, "Trafo", index, hv_bus, lv_bus)
index = _get_index_with_check(net, "trafo", index, name="transformer")
if df <= 0:
raise UserWarning("derating factor df must be positive: df = %.3f" % df)
v = {
"name": name, "hv_bus": hv_bus, "lv_bus": lv_bus,
"in_service": bool(in_service), "std_type": std_type
}
ti = load_std_type(net, std_type, "trafo")
updates = {
"sn_mva": ti["sn_mva"],
"vn_hv_kv": ti["vn_hv_kv"],
"vn_lv_kv": ti["vn_lv_kv"],
"vk_percent": ti["vk_percent"],
"vkr_percent": ti["vkr_percent"],
"pfe_kw": ti["pfe_kw"],
"i0_percent": ti["i0_percent"],
"parallel": parallel,
"df": df,
"shift_degree": ti["shift_degree"] if "shift_degree" in ti else 0,
"tap_phase_shifter": ti["tap_phase_shifter"] if "tap_phase_shifter" in ti
and pd.notnull(
ti["tap_phase_shifter"]) else False
}
for zero_param in ['vk0_percent', 'vkr0_percent', 'mag0_percent', 'mag0_rx', 'si0_hv_partial']:
if zero_param in ti:
updates[zero_param] = ti[zero_param]
v.update(updates)
for tp in ("tap_neutral", "tap_max", "tap_min", "tap_side", "tap_step_percent",
"tap_step_degree"):
if tp in ti:
v[tp] = ti[tp]
if ("tap_neutral" in v) and (tap_pos is nan):
v["tap_pos"] = v["tap_neutral"]
else:
v["tap_pos"] = tap_pos
if isinstance(tap_pos, float):
net.trafo.tap_pos = net.trafo.tap_pos.astype(float)
_set_entries(net, "trafo", index, **v)
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "trafo")
if tap_dependent_impedance is not None:
_create_column_and_set_value(net, index, tap_dependent_impedance, "tap_dependent_impedance", "trafo", bool_, False, True)
if vk_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_percent_characteristic, "vk_percent_characteristic", "trafo", "Int64") # Int64Dtype
if vkr_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_percent_characteristic, "vkr_percent_characteristic", "trafo", "Int64")
# tap_phase_shifter default False
net.trafo.tap_phase_shifter.fillna(False, inplace=True)
return index
def create_transformer_from_parameters(net, hv_bus, lv_bus, sn_mva, vn_hv_kv, vn_lv_kv,
vkr_percent, vk_percent, pfe_kw, i0_percent,
shift_degree=0,
tap_side=None, tap_neutral=nan, tap_max=nan,
tap_min=nan, tap_step_percent=nan, tap_step_degree=nan,
tap_pos=nan, tap_phase_shifter=False, in_service=True,
name=None, vector_group=None, index=None,
max_loading_percent=nan, parallel=1,
df=1., vk0_percent=nan, vkr0_percent=nan,
mag0_percent=nan, mag0_rx=nan,
si0_hv_partial=nan,
pt_percent=nan, oltc=False, tap_dependent_impedance=None,
vk_percent_characteristic=None,
vkr_percent_characteristic=None, **kwargs):
"""
Creates a two-winding transformer in table net["trafo"].
The trafo parameters are defined through the standard type library.
INPUT:
**net** - The net within this transformer should be created
**hv_bus** (int) - The bus on the high-voltage side on which the transformer will be \
connected to
**lv_bus** (int) - The bus on the low-voltage side on which the transformer will be \
connected to
**sn_mva** (float) - rated apparent power
**vn_hv_kv** (float) - rated voltage on high voltage side
**vn_lv_kv** (float) - rated voltage on low voltage side
**vkr_percent** (float) - real part of relative short-circuit voltage
**vk_percent** (float) - relative short-circuit voltage
**pfe_kw** (float) - iron losses in kW
**i0_percent** (float) - open loop losses in percent of rated current
**vector_group** (String) - Vector group of the transformer
HV side is Uppercase letters
and LV side is lower case
**vk0_percent** (float) - zero sequence relative short-circuit voltage
**vkr0_percent** - real part of zero sequence relative short-circuit voltage
**mag0_percent** - zero sequence magnetizing impedance/ vk0
**mag0_rx** - zero sequence magnitizing R/X ratio
**si0_hv_partial** - Distribution of zero sequence leakage impedances for HV side
OPTIONAL:
**in_service** (boolean) - True for in_service or False for out of service
**parallel** (integer) - number of parallel transformers
**name** (string) - A custom name for this transformer
**shift_degree** (float) - Angle shift over the transformer*
**tap_side** (string) - position of tap changer ("hv", "lv")
**tap_pos** (int, nan) - current tap position of the transformer. Defaults to the medium \
position (tap_neutral)
**tap_neutral** (int, nan) - tap position where the transformer ratio is equal to the \
ratio of the rated voltages
**tap_max** (int, nan) - maximal allowed tap position
**tap_min** (int, nan): minimal allowed tap position
**tap_step_percent** (float) - tap step size for voltage magnitude in percent
**tap_step_degree** (float) - tap step size for voltage angle in degree*
**tap_phase_shifter** (bool) - whether the transformer is an ideal phase shifter*
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**max_loading_percent (float)** - maximum current loading (only needed for OPF)
**df** (float) - derating factor: maximal current of transformer in relation to nominal \
current of transformer (from 0 to 1)
**tap_dependent_impedance** (boolean) - True if transformer impedance must be adjusted dependent \
on the tap position of the trabnsformer. Requires the additional columns \
"vk_percent_characteristic" and "vkr_percent_characteristic" that reference the index of the \
characteristic from the table net.characteristic. A convenience function \
pandapower.control.create_trafo_characteristics can be used to create the SplineCharacteristic \
objects, add the relevant columns and set up the references to the characteristics. \
The function pandapower.control.trafo_characteristics_diagnostic can be used for sanity checks.
**vk_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**pt_percent** (float, nan) - (short circuit only)
**oltc** (bool, False) - (short circuit only)
** only considered in loadflow if calculate_voltage_angles = True
OUTPUT:
**index** (int) - The unique ID of the created transformer
EXAMPLE:
create_transformer_from_parameters(net, hv_bus=0, lv_bus=1, name="trafo1", sn_mva=40, \
vn_hv_kv=110, vn_lv_kv=10, vk_percent=10, vkr_percent=0.3, pfe_kw=30, \
i0_percent=0.1, shift_degree=30)
"""
# Check if bus exist to attach the trafo to
_check_branch_element(net, "Trafo", index, hv_bus, lv_bus)
index = _get_index_with_check(net, "trafo", index, name="transformer")
if df <= 0:
raise UserWarning("derating factor df must be positive: df = %.3f" % df)
if tap_pos is nan:
tap_pos = tap_neutral
# store dtypes
v = {
"name": name, "hv_bus": hv_bus, "lv_bus": lv_bus,
"in_service": bool(in_service), "std_type": None, "sn_mva": sn_mva, "vn_hv_kv": vn_hv_kv,
"vn_lv_kv": vn_lv_kv, "vk_percent": vk_percent, "vkr_percent": vkr_percent,
"pfe_kw": pfe_kw, "i0_percent": i0_percent, "tap_neutral": tap_neutral,
"tap_max": tap_max, "tap_min": tap_min, "shift_degree": shift_degree,
"tap_side": tap_side, "tap_step_percent": tap_step_percent, "tap_step_degree": tap_step_degree,
"tap_phase_shifter": tap_phase_shifter, "parallel": parallel, "df": df,
"pt_percent": pt_percent, "oltc": oltc
}
if ("tap_neutral" in v) and (tap_pos is nan):
v["tap_pos"] = v["tap_neutral"]
else:
v["tap_pos"] = tap_pos
if type(tap_pos) == float:
net.trafo.tap_pos = net.trafo.tap_pos.astype(float)
_set_entries(net, "trafo", index, **v, **kwargs)
if tap_dependent_impedance is not None:
_create_column_and_set_value(net, index, tap_dependent_impedance, "tap_dependent_impedance", "trafo", bool_, False, True)
if vk_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_percent_characteristic, "vk_percent_characteristic", "trafo", "Int64")
if vkr_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_percent_characteristic, "vkr_percent_characteristic", "trafo", "Int64")
if not (isnan(vk0_percent) and isnan(vkr0_percent) and isnan(mag0_percent)
and isnan(mag0_rx) and isnan(si0_hv_partial) and vector_group is None):
_create_column_and_set_value(net, index, vk0_percent, "vk0_percent", "trafo")
_create_column_and_set_value(net, index, vkr0_percent, "vkr0_percent", "trafo")
_create_column_and_set_value(net, index, mag0_percent, "mag0_percent", "trafo")
_create_column_and_set_value(net, index, mag0_rx, "mag0_rx", "trafo")
_create_column_and_set_value(net, index, si0_hv_partial, "si0_hv_partial", "trafo")
_create_column_and_set_value(net, index, vector_group, "vector_group", "trafo", dtyp=str,
default_val=None)
_create_column_and_set_value(net, index, pt_percent, "pt_percent", "trafo")
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "trafo")
return index
def create_transformers_from_parameters(net, hv_buses, lv_buses, sn_mva, vn_hv_kv, vn_lv_kv,
vkr_percent, vk_percent, pfe_kw, i0_percent, shift_degree=0,
tap_side=None, tap_neutral=nan, tap_max=nan, tap_min=nan,
tap_step_percent=nan, tap_step_degree=nan, tap_pos=nan,
tap_phase_shifter=False, in_service=True, name=None,
vector_group=None, index=None, max_loading_percent=None,
parallel=1, df=1., vk0_percent=None, vkr0_percent=None,
mag0_percent=None, mag0_rx=None, si0_hv_partial=None,
pt_percent=nan, oltc=False, tap_dependent_impedance=None,
vk_percent_characteristic=None,
vkr_percent_characteristic=None, **kwargs):
"""
Creates several two-winding transformers in table net["trafo"].
The trafo parameters are defined through the standard type library.
INPUT:
**net** - The net within this transformer should be created
**hv_bus** (list of int) - The bus on the high-voltage side on which the transformer will \
be connected to
**lv_bus** (list of int) - The bus on the low-voltage side on which the transformer will \
be connected to
**sn_mva** (list of float) - rated apparent power
**vn_hv_kv** (list of float) - rated voltage on high voltage side
**vn_lv_kv** (list of float) - rated voltage on low voltage side
**vkr_percent** (list of float) - real part of relative short-circuit voltage
**vk_percent** (list of float) - relative short-circuit voltage
**pfe_kw** (list of float) - iron losses in kW
**i0_percent** (list of float) - open loop losses in percent of rated current
**vector_group** (list of String) - Vector group of the transformer
HV side is Uppercase letters
and LV side is lower case
**vk0_percent** (list of float) - zero sequence relative short-circuit voltage
**vkr0_percent** - (list of float) real part of zero sequence relative short-circuit voltage
**mag0_percent** - (list of float) zero sequence magnetizing impedance/ vk0
**mag0_rx** - (list of float) zero sequence magnitizing R/X ratio
**si0_hv_partial** - (list of float) Distribution of zero sequence leakage impedances for \
HV side
OPTIONAL:
**in_service** (boolean) - True for in_service or False for out of service
**parallel** (integer) - number of parallel transformers
**name** (string) - A custom name for this transformer
**shift_degree** (float) - Angle shift over the transformer*
**tap_side** (string) - position of tap changer ("hv", "lv")
**tap_pos** (int, nan) - current tap position of the transformer. Defaults to the medium \
position (tap_neutral)
**tap_neutral** (int, nan) - tap position where the transformer ratio is equal to the ratio\
of the rated voltages
**tap_max** (int, nan) - maximal allowed tap position
**tap_min** (int, nan): minimal allowed tap position
**tap_step_percent** (float) - tap step size for voltage magnitude in percent
**tap_step_degree** (float) - tap step size for voltage angle in degree*
**tap_phase_shifter** (bool) - whether the transformer is an ideal phase shifter*
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**max_loading_percent (float)** - maximum current loading (only needed for OPF)
**df** (float) - derating factor: maximal current of transformer in relation to nominal \
current of transformer (from 0 to 1)
**tap_dependent_impedance** (boolean) - True if transformer impedance must be adjusted dependent \
on the tap position of the trabnsformer. Requires the additional columns \
"vk_percent_characteristic" and "vkr_percent_characteristic" that reference the index of the \
characteristic from the table net.characteristic. A convenience function \
pandapower.control.create_trafo_characteristics can be used to create the SplineCharacteristic \
objects, add the relevant columns and set up the references to the characteristics. \
The function pandapower.control.trafo_characteristics_diagnostic can be used for sanity checks.
**vk_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**pt_percent** (float, nan) - (short circuit only)
**oltc** (bool, False) - (short circuit only)
** only considered in loadflow if calculate_voltage_angles = True
OUTPUT:
**index** (int) - The unique ID of the created transformer
EXAMPLE:
create_transformer_from_parameters(net, hv_bus=0, lv_bus=1, name="trafo1", sn_mva=40, \
vn_hv_kv=110, vn_lv_kv=10, vk_percent=10, vkr_percent=0.3, pfe_kw=30, \
i0_percent=0.1, shift_degree=30)
"""
_check_multiple_branch_elements(net, hv_buses, lv_buses, "Transformers")
index = _get_multiple_index_with_check(net, "trafo", index, len(hv_buses))
tp_neutral = pd.Series(tap_neutral, index=index, dtype=float64)
tp_pos = pd.Series(tap_pos, index=index, dtype=float64).fillna(tp_neutral)
entries = {"name": name, "hv_bus": hv_buses, "lv_bus": lv_buses,
"in_service": array(in_service).astype(bool_), "std_type": None, "sn_mva": sn_mva,
"vn_hv_kv": vn_hv_kv, "vn_lv_kv": vn_lv_kv, "vk_percent": vk_percent,
"vkr_percent": vkr_percent, "pfe_kw": pfe_kw, "i0_percent": i0_percent,
"tap_neutral": tp_neutral, "tap_max": tap_max, "tap_min": tap_min,
"shift_degree": shift_degree, "tap_pos": tp_pos, "tap_side": tap_side,
"tap_step_percent": tap_step_percent, "tap_step_degree": tap_step_degree,
"tap_phase_shifter": tap_phase_shifter, "parallel": parallel, "df": df,
"pt_percent": pt_percent, "oltc": oltc}
if tap_dependent_impedance is not None:
_add_series_to_entries(entries, index, "tap_dependent_impedance", tap_dependent_impedance, dtype=bool_, default_val=False)
if vk_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vk_percent_characteristic", vk_percent_characteristic, "Int64")
if vkr_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vkr_percent_characteristic", vkr_percent_characteristic, "Int64")
_add_series_to_entries(entries, index, "vk0_percent", vk0_percent)
_add_series_to_entries(entries, index, "vkr0_percent", vkr0_percent)
_add_series_to_entries(entries, index, "mag0_percent", mag0_percent)
_add_series_to_entries(entries, index, "mag0_rx", mag0_rx)
_add_series_to_entries(entries, index, "si0_hv_partial", si0_hv_partial)
_add_series_to_entries(entries, index, "max_loading_percent", max_loading_percent)
_add_series_to_entries(entries, index, "vector_group", vector_group, dtyp=str)
_add_series_to_entries(entries, index, "pt_percent", pt_percent)
_set_multiple_entries(net, "trafo", index, **entries, **kwargs)
return index
def create_transformer3w(net, hv_bus, mv_bus, lv_bus, std_type, name=None, tap_pos=nan,
in_service=True, index=None, max_loading_percent=nan,
tap_at_star_point=False, tap_dependent_impedance=None,
vk_hv_percent_characteristic=None, vkr_hv_percent_characteristic=None,
vk_mv_percent_characteristic=None, vkr_mv_percent_characteristic=None,
vk_lv_percent_characteristic=None, vkr_lv_percent_characteristic=None):
"""
Creates a three-winding transformer in table net["trafo3w"].
The trafo parameters are defined through the standard type library.
INPUT:
**net** - The net within this transformer should be created
**hv_bus** (int) - The bus on the high-voltage side on which the transformer will be \
connected to
**mv_bus** (int) - The medium voltage bus on which the transformer will be connected to
**lv_bus** (int) - The bus on the low-voltage side on which the transformer will be \
connected to
**std_type** - The used standard type from the standard type library
OPTIONAL:
**name** (string) - A custom name for this transformer
**tap_pos** (int, nan) - current tap position of the transformer. Defaults to the medium \
position (tap_neutral)
**tap_at_star_point** (boolean) - Whether tap changer is located at the star point of the \
3W-transformer or at the bus
**in_service** (boolean) - True for in_service or False for out of service
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**max_loading_percent (float)** - maximum current loading (only needed for OPF)
**tap_at_star_point (bool)** - whether tap changer is modelled at star point or at the bus
**tap_dependent_impedance** (boolean) - True if transformer impedance must be adjusted dependent \
on the tap position of the trabnsformer. Requires the additional columns \
"vk_percent_characteristic" and "vkr_percent_characteristic" that reference the index of the \
characteristic from the table net.characteristic. A convenience function \
pandapower.control.create_trafo_characteristics can be used to create the SplineCharacteristic \
objects, add the relevant columns and set up the references to the characteristics. \
The function pandapower.control.trafo_characteristics_diagnostic can be used for sanity checks.
**vk_hv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_hv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vk_mv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_mv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vk_lv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_lv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
OUTPUT:
**index** (int) - The unique ID of the created transformer
EXAMPLE:
create_transformer3w(net, hv_bus = 0, mv_bus = 1, lv_bus = 2, name = "trafo1", std_type = \
"63/25/38 MVA 110/20/10 kV")
"""
# Check if bus exist to attach the trafo to
for b in [hv_bus, mv_bus, lv_bus]:
if b not in net["bus"].index.values:
raise UserWarning("Trafo tries to attach to bus %s" % b)
v = {
"name": name, "hv_bus": hv_bus, "mv_bus": mv_bus, "lv_bus": lv_bus,
"in_service": bool(in_service), "std_type": std_type
}
ti = load_std_type(net, std_type, "trafo3w")
index = _get_index_with_check(net, "trafo3w", index, "three winding transformer")
v.update({
"sn_hv_mva": ti["sn_hv_mva"],
"sn_mv_mva": ti["sn_mv_mva"],
"sn_lv_mva": ti["sn_lv_mva"],
"vn_hv_kv": ti["vn_hv_kv"],
"vn_mv_kv": ti["vn_mv_kv"],
"vn_lv_kv": ti["vn_lv_kv"],
"vk_hv_percent": ti["vk_hv_percent"],
"vk_mv_percent": ti["vk_mv_percent"],
"vk_lv_percent": ti["vk_lv_percent"],
"vkr_hv_percent": ti["vkr_hv_percent"],
"vkr_mv_percent": ti["vkr_mv_percent"],
"vkr_lv_percent": ti["vkr_lv_percent"],
"pfe_kw": ti["pfe_kw"],
"i0_percent": ti["i0_percent"],
"shift_mv_degree": ti["shift_mv_degree"] if "shift_mv_degree" in ti else 0,
"shift_lv_degree": ti["shift_lv_degree"] if "shift_lv_degree" in ti else 0,
"tap_at_star_point": tap_at_star_point
})
for tp in (
"tap_neutral", "tap_max", "tap_min", "tap_side", "tap_step_percent", "tap_step_degree"):
if tp in ti:
v.update({tp: ti[tp]})
if ("tap_neutral" in v) and (tap_pos is nan):
v["tap_pos"] = v["tap_neutral"]
else:
v["tap_pos"] = tap_pos
if type(tap_pos) == float:
net.trafo3w.tap_pos = net.trafo3w.tap_pos.astype(float)
dd = pd.DataFrame(v, index=[index])
# todo: drop __version__ checks
if version.parse(pd.__version__) < version.parse("0.21"):
net["trafo3w"] = net["trafo3w"].append(dd).reindex_axis(net["trafo3w"].columns, axis=1)
elif version.parse(pd.__version__) < version.parse("0.23"):
net["trafo3w"] = net["trafo3w"].append(dd).reindex(net["trafo3w"].columns, axis=1)
else:
net["trafo3w"] = net["trafo3w"].append(dd, sort=True).reindex(net["trafo3w"].columns,
axis=1)
# todo: append -> concat:
# net["trafo3w"] = pd.concat([net["trafo3w"], dd], sort=True).reindex(net["trafo3w"].columns, axis=1)
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "trafo3w")
if tap_dependent_impedance is not None:
_create_column_and_set_value(net, index, tap_dependent_impedance, "tap_dependent_impedance", "trafo", bool_, False, True)
if vk_hv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_hv_percent_characteristic, "vk_hv_percent_characteristic", "trafo", "Int64")
if vkr_hv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_hv_percent_characteristic, "vkr_hv_percent_characteristic", "trafo", "Int64")
if vk_mv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_mv_percent_characteristic, "vk_mv_percent_characteristic", "trafo", "Int64")
if vkr_mv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_mv_percent_characteristic, "vkr_mv_percent_characteristic", "trafo", "Int64")
if vk_lv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_lv_percent_characteristic, "vk_lv_percent_characteristic", "trafo", "Int64")
if vkr_lv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_lv_percent_characteristic, "vkr_lv_percent_characteristic", "trafo", "Int64")
return index
def create_transformer3w_from_parameters(net, hv_bus, mv_bus, lv_bus, vn_hv_kv, vn_mv_kv, vn_lv_kv,
sn_hv_mva, sn_mv_mva, sn_lv_mva, vk_hv_percent,
vk_mv_percent, vk_lv_percent, vkr_hv_percent,
vkr_mv_percent, vkr_lv_percent, pfe_kw, i0_percent,
shift_mv_degree=0., shift_lv_degree=0., tap_side=None,
tap_step_percent=nan, tap_step_degree=nan, tap_pos=nan,
tap_neutral=nan, tap_max=nan,
tap_min=nan, name=None, in_service=True, index=None,
max_loading_percent=nan, tap_at_star_point=False,
vk0_hv_percent=nan, vk0_mv_percent=nan, vk0_lv_percent=nan,
vkr0_hv_percent=nan, vkr0_mv_percent=nan, vkr0_lv_percent=nan,
vector_group=None, tap_dependent_impedance=None,
vk_hv_percent_characteristic=None, vkr_hv_percent_characteristic=None,
vk_mv_percent_characteristic=None, vkr_mv_percent_characteristic=None,
vk_lv_percent_characteristic=None, vkr_lv_percent_characteristic=None):
"""
Adds a three-winding transformer in table net["trafo3w"].
The model currently only supports one tap-changer per 3W Transformer.
Input:
**net** (pandapowerNet) - The net within this transformer should be created
**hv_bus** (int) - The bus on the high-voltage side on which the transformer will be \
connected to
**mv_bus** (int) - The bus on the middle-voltage side on which the transformer will be \
connected to
**lv_bus** (int) - The bus on the low-voltage side on which the transformer will be \
connected to
**vn_hv_kv** (float) rated voltage on high voltage side
**vn_mv_kv** (float) rated voltage on medium voltage side
**vn_lv_kv** (float) rated voltage on low voltage side
**sn_hv_mva** (float) - rated apparent power on high voltage side
**sn_mv_mva** (float) - rated apparent power on medium voltage side
**sn_lv_mva** (float) - rated apparent power on low voltage side
**vk_hv_percent** (float) - short circuit voltage from high to medium voltage
**vk_mv_percent** (float) - short circuit voltage from medium to low voltage
**vk_lv_percent** (float) - short circuit voltage from high to low voltage
**vkr_hv_percent** (float) - real part of short circuit voltage from high to medium voltage
**vkr_mv_percent** (float) - real part of short circuit voltage from medium to low voltage
**vkr_lv_percent** (float) - real part of short circuit voltage from high to low voltage
**pfe_kw** (float) - iron losses in kW
**i0_percent** (float) - open loop losses
OPTIONAL:
**shift_mv_degree** (float, 0) - angle shift to medium voltage side*
**shift_lv_degree** (float, 0) - angle shift to low voltage side*
**tap_step_percent** (float) - Tap step in percent
**tap_step_degree** (float) - Tap phase shift angle in degrees
**tap_side** (string, None) - "hv", "mv", "lv"
**tap_neutral** (int, nan) - default tap position
**tap_min** (int, nan) - Minimum tap position
**tap_max** (int, nan) - Maximum tap position
**tap_pos** (int, nan) - current tap position of the transformer. Defaults to the \
medium position (tap_neutral)
**tap_at_star_point** (boolean) - Whether tap changer is located at the star point of the \
3W-transformer or at the bus
**name** (string, None) - Name of the 3-winding transformer
**in_service** (boolean, True) - True for in_service or False for out of service
**max_loading_percent (float)** - maximum current loading (only needed for OPF)
**tap_dependent_impedance** (boolean) - True if transformer impedance must be adjusted dependent \
on the tap position of the trabnsformer. Requires the additional columns \
"vk_percent_characteristic" and "vkr_percent_characteristic" that reference the index of the \
characteristic from the table net.characteristic. A convenience function \
pandapower.control.create_trafo_characteristics can be used to create the SplineCharacteristic \
objects, add the relevant columns and set up the references to the characteristics. \
The function pandapower.control.trafo_characteristics_diagnostic can be used for sanity checks.
**vk_hv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_hv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vk_mv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_mv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vk_lv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_lv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vk0_hv_percent** (float) - zero sequence short circuit voltage from high to medium voltage
**vk0_mv_percent** (float) - zero sequence short circuit voltage from medium to low voltage
**vk0_lv_percent** (float) - zero sequence short circuit voltage from high to low voltage
**vkr0_hv_percent** (float) - zero sequence real part of short circuit voltage from high to medium voltage
**vkr0_mv_percent** (float) - zero sequence real part of short circuit voltage from medium to low voltage
**vkr0_lv_percent** (float) - zero sequence real part of short circuit voltage from high to low voltage
**vector_group** (list of String) - Vector group of the transformer3w
OUTPUT:
**trafo_id** - The unique trafo_id of the created 3W transformer
Example:
create_transformer3w_from_parameters(net, hv_bus=0, mv_bus=1, lv_bus=2, name="trafo1",
sn_hv_mva=40, sn_mv_mva=20, sn_lv_mva=20, vn_hv_kv=110, vn_mv_kv=20, vn_lv_kv=10,
vk_hv_percent=10,vk_mv_percent=11, vk_lv_percent=12, vkr_hv_percent=0.3,
vkr_mv_percent=0.31, vkr_lv_percent=0.32, pfe_kw=30, i0_percent=0.1, shift_mv_degree=30,
shift_lv_degree=30)
"""
# Check if bus exist to attach the trafo to
for b in [hv_bus, mv_bus, lv_bus]:
if b not in net["bus"].index.values:
raise UserWarning("Trafo tries to attach to non-existent bus %s" % b)
index = _get_index_with_check(net, "trafo3w", index, "three winding transformer")
if tap_pos is nan:
tap_pos = tap_neutral
columns = ["lv_bus", "mv_bus", "hv_bus", "vn_hv_kv", "vn_mv_kv", "vn_lv_kv", "sn_hv_mva",
"sn_mv_mva", "sn_lv_mva", "vk_hv_percent", "vk_mv_percent", "vk_lv_percent",
"vkr_hv_percent", "vkr_mv_percent", "vkr_lv_percent", "pfe_kw", "i0_percent",
"shift_mv_degree", "shift_lv_degree", "tap_side", "tap_step_percent",
"tap_step_degree", "tap_pos", "tap_neutral", "tap_max", "tap_min", "in_service",
"name", "std_type", "tap_at_star_point", "vk0_hv_percent", "vk0_mv_percent", "vk0_lv_percent",
"vkr0_hv_percent", "vkr0_mv_percent", "vkr0_lv_percent", "vector_group"]
values = [lv_bus, mv_bus, hv_bus, vn_hv_kv, vn_mv_kv, vn_lv_kv, sn_hv_mva, sn_mv_mva, sn_lv_mva,
vk_hv_percent, vk_mv_percent, vk_lv_percent, vkr_hv_percent, vkr_mv_percent,
vkr_lv_percent, pfe_kw, i0_percent, shift_mv_degree, shift_lv_degree, tap_side,
tap_step_percent, tap_step_degree, tap_pos, tap_neutral, tap_max, tap_min,
bool(in_service), name, None, tap_at_star_point,
vk0_hv_percent, vk0_mv_percent, vk0_lv_percent,
vkr0_hv_percent, vkr0_mv_percent, vkr0_lv_percent, vector_group]
_set_entries(net, "trafo3w", index, **dict(zip(columns, values)))
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "trafo3w")
if tap_dependent_impedance is not None:
_create_column_and_set_value(net, index, tap_dependent_impedance, "tap_dependent_impedance", "trafo", bool_, False, True)
if vk_hv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_hv_percent_characteristic, "vk_hv_percent_characteristic", "trafo", "Int64")
if vkr_hv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_hv_percent_characteristic, "vkr_hv_percent_characteristic", "trafo", "Int64")
if vk_mv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_mv_percent_characteristic, "vk_mv_percent_characteristic", "trafo", "Int64")
if vkr_mv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_mv_percent_characteristic, "vkr_mv_percent_characteristic", "trafo", "Int64")
if vk_lv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_lv_percent_characteristic, "vk_lv_percent_characteristic", "trafo", "Int64")
if vkr_lv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_lv_percent_characteristic, "vkr_lv_percent_characteristic", "trafo", "Int64")
return index
def create_transformers3w_from_parameters(net, hv_buses, mv_buses, lv_buses, vn_hv_kv, vn_mv_kv,
vn_lv_kv, sn_hv_mva, sn_mv_mva, sn_lv_mva, vk_hv_percent,
vk_mv_percent, vk_lv_percent, vkr_hv_percent,
vkr_mv_percent, vkr_lv_percent, pfe_kw, i0_percent,
shift_mv_degree=0., shift_lv_degree=0., tap_side=None,
tap_step_percent=nan, tap_step_degree=nan, tap_pos=nan,
tap_neutral=nan, tap_max=nan, tap_min=nan, name=None,
in_service=True, index=None, max_loading_percent=None,
tap_at_star_point=False,
vk0_hv_percent=nan, vk0_mv_percent=nan, vk0_lv_percent=nan,
vkr0_hv_percent=nan, vkr0_mv_percent=nan, vkr0_lv_percent=nan,
vector_group=None, tap_dependent_impedance=None,
vk_hv_percent_characteristic=None, vkr_hv_percent_characteristic=None,
vk_mv_percent_characteristic=None, vkr_mv_percent_characteristic=None,
vk_lv_percent_characteristic=None, vkr_lv_percent_characteristic=None, **kwargs):
"""
Adds a three-winding transformer in table net["trafo3w"].
Input:
**net** (pandapowerNet) - The net within this transformer should be created
**hv_bus** (list) - The bus on the high-voltage side on which the transformer will be \
connected to
**mv_bus** (list) - The bus on the middle-voltage side on which the transformer will be \
connected to
**lv_bus** (list) - The bus on the low-voltage side on which the transformer will be \
connected to
**vn_hv_kv** (float or list) rated voltage on high voltage side
**vn_mv_kv** (float or list) rated voltage on medium voltage side
**vn_lv_kv** (float or list) rated voltage on low voltage side
**sn_hv_mva** (float or list) - rated apparent power on high voltage side
**sn_mv_mva** (float or list) - rated apparent power on medium voltage side
**sn_lv_mva** (float or list) - rated apparent power on low voltage side
**vk_hv_percent** (float or list) - short circuit voltage from high to medium voltage
**vk_mv_percent** (float or list) - short circuit voltage from medium to low voltage
**vk_lv_percent** (float or list) - short circuit voltage from high to low voltage
**vkr_hv_percent** (float or list) - real part of short circuit voltage from high to medium\
voltage
**vkr_mv_percent** (float or list) - real part of short circuit voltage from medium to low\
voltage
**vkr_lv_percent** (float or list) - real part of short circuit voltage from high to low\
voltage
**pfe_kw** (float or list) - iron losses in kW
**i0_percent** (float or list) - open loop losses
OPTIONAL:
**shift_mv_degree** (float or list, 0) - angle shift to medium voltage side*
**shift_lv_degree** (float or list, 0) - angle shift to low voltage side*
**tap_step_percent** (float or list) - Tap step in percent
**tap_step_degree** (float or list) - Tap phase shift angle in degrees
**tap_side** (string, None) - "hv", "mv", "lv"
**tap_neutral** (int, nan) - default tap position
**tap_min** (int, nan) - Minimum tap position
**tap_max** (int, nan) - Maximum tap position
**tap_pos** (int, nan) - current tap position of the transformer. Defaults to the \
medium position (tap_neutral)
**tap_at_star_point** (boolean) - Whether tap changer is located at the star point of the \
3W-transformer or at the bus
**name** (string, None) - Name of the 3-winding transformer
**in_service** (boolean, True) - True for in_service or False for out of service
** only considered in loadflow if calculate_voltage_angles = True
**The model currently only supports one tap-changer per 3W Transformer.
**max_loading_percent (float)** - maximum current loading (only needed for OPF)
**tap_dependent_impedance** (boolean) - True if transformer impedance must be adjusted dependent \
on the tap position of the trabnsformer. Requires the additional columns \
"vk_percent_characteristic" and "vkr_percent_characteristic" that reference the index of the \
characteristic from the table net.characteristic. A convenience function \
pandapower.control.create_trafo_characteristics can be used to create the SplineCharacteristic \
objects, add the relevant columns and set up the references to the characteristics. \
The function pandapower.control.trafo_characteristics_diagnostic can be used for sanity checks.
**vk_hv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_hv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vk_mv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_mv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vk_lv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vkr_lv_percent_characteristic** (int) - index of the characteristic from net.characteristic for \
the adjustment of the parameter "vk_percent" for the calculation of tap dependent impedance.
**vk0_hv_percent** (float) - zero sequence short circuit voltage from high to medium voltage
**vk0_mv_percent** (float) - zero sequence short circuit voltage from medium to low voltage
**vk0_lv_percent** (float) - zero sequence short circuit voltage from high to low voltage
**vkr0_hv_percent** (float) - zero sequence real part of short circuit voltage from high to medium voltage
**vkr0_mv_percent** (float) - zero sequence real part of short circuit voltage from medium to low voltage
**vkr0_lv_percent** (float) - zero sequence real part of short circuit voltage from high to low voltage
**vector_group** (list of String) - Vector group of the transformer3w
OUTPUT:
**trafo_id** - List of trafo_ids of the created 3W transformers
Example:
create_transformer3w_from_parameters(net, hv_bus=0, mv_bus=1, lv_bus=2, name="trafo1",
sn_hv_mva=40, sn_mv_mva=20, sn_lv_mva=20, vn_hv_kv=110, vn_mv_kv=20, vn_lv_kv=10,
vk_hv_percent=10,vk_mv_percent=11, vk_lv_percent=12, vkr_hv_percent=0.3,
vkr_mv_percent=0.31, vkr_lv_percent=0.32, pfe_kw=30, i0_percent=0.1, shift_mv_degree=30,
shift_lv_degree=30)
"""
index = _get_multiple_index_with_check(net, "trafo3w", index, len(hv_buses),
name="Three winding transformers")
if not np_all(isin(hv_buses, net.bus.index)):
bus_not_exist = set(hv_buses) - set(net.bus.index)
raise UserWarning("Transformers trying to attach to non existing buses %s" % bus_not_exist)
if not np_all(isin(mv_buses, net.bus.index)):
bus_not_exist = set(mv_buses) - set(net.bus.index)
raise UserWarning("Transformers trying to attach to non existing buses %s" % bus_not_exist)
if not np_all(isin(lv_buses, net.bus.index)):
bus_not_exist = set(lv_buses) - set(net.bus.index)
raise UserWarning("Transformers trying to attach to non existing buses %s" % bus_not_exist)
tp_neutral = pd.Series(tap_neutral, index=index, dtype=float64)
tp_pos = pd.Series(tap_pos, index=index, dtype=float64).fillna(tp_neutral)
entries = {"lv_bus": lv_buses, "mv_bus": mv_buses, "hv_bus": hv_buses, "vn_hv_kv": vn_hv_kv,
"vn_mv_kv": vn_mv_kv, "vn_lv_kv": vn_lv_kv, "sn_hv_mva": sn_hv_mva,
"sn_mv_mva": sn_mv_mva, "sn_lv_mva": sn_lv_mva, "vk_hv_percent": vk_hv_percent,
"vk_mv_percent": vk_mv_percent, "vk_lv_percent": vk_lv_percent,
"vkr_hv_percent": vkr_hv_percent, "vkr_mv_percent": vkr_mv_percent,
"vkr_lv_percent": vkr_lv_percent, "pfe_kw": pfe_kw, "i0_percent": i0_percent,
"shift_mv_degree": shift_mv_degree, "shift_lv_degree": shift_lv_degree,
"tap_side": tap_side, "tap_step_percent": tap_step_percent,
"tap_step_degree": tap_step_degree, "tap_pos": tp_pos, "tap_neutral": tp_neutral,
"tap_max": tap_max, "tap_min": tap_min,
"in_service": array(in_service).astype(bool_), "name": name,
"tap_at_star_point": array(tap_at_star_point).astype(bool_), "std_type": None,
"vk0_hv_percent": vk0_hv_percent, "vk0_mv_percent": vk0_mv_percent,
"vk0_lv_percent": vk0_lv_percent, "vkr0_hv_percent": vkr0_hv_percent,
"vkr0_mv_percent": vkr0_mv_percent, "vkr0_lv_percent": vkr0_lv_percent,
"vector_group": vector_group}
_add_series_to_entries(entries, index, "max_loading_percent", max_loading_percent)
if tap_dependent_impedance is not None:
_add_series_to_entries(entries, index, "tap_dependent_impedance", tap_dependent_impedance, dtype=bool_, default_val=False)
if vk_hv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vk_hv_percent_characteristic", vk_hv_percent_characteristic, "Int64")
if vkr_hv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vkr_hv_percent_characteristic", vkr_hv_percent_characteristic, "Int64")
if vk_mv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vk_mv_percent_characteristic", vk_mv_percent_characteristic, "Int64")
if vkr_mv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vkr_mv_percent_characteristic", vkr_mv_percent_characteristic, "Int64")
if vk_lv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vk_lv_percent_characteristic", vk_lv_percent_characteristic, "Int64")
if vkr_lv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vkr_lv_percent_characteristic", vkr_lv_percent_characteristic, "Int64")
_set_multiple_entries(net, "trafo3w", index, **entries, **kwargs)
return index
def create_switch(net, bus, element, et, closed=True, type=None, name=None, index=None, z_ohm=0):
"""
Adds a switch in the net["switch"] table.
Switches can be either between two buses (bus-bus switch) or at the end of a line or transformer
element (bus-element switch).
Two buses that are connected through a closed bus-bus switches are fused in the power flow if
the switch is closed or separated if the switch is open.
An element that is connected to a bus through a bus-element switch is connected to the bus
if the switch is closed or disconnected if the switch is open.
INPUT:
**net** (pandapowerNet) - The net within which this switch should be created
**bus** - The bus that the switch is connected to
**element** - index of the element: bus id if et == "b", line id if et == "l", trafo id if \
et == "t"
**et** - (string) element type: "l" = switch between bus and line, "t" = switch between
bus and transformer, "t3" = switch between bus and transformer3w, "b" = switch between
two buses
OPTIONAL:
**closed** (boolean, True) - switch position: False = open, True = closed
**type** (int, None) - indicates the type of switch: "LS" = Load Switch, "CB" = \
Circuit Breaker, "LBS" = Load Break Switch or "DS" = Disconnecting Switch
**z_ohm** (float, 0) - indicates the resistance of the switch, which has effect only on
bus-bus switches, if sets to 0, the buses will be fused like before, if larger than
0 a branch will be created for the switch which has also effects on the bus mapping
**name** (string, default None) - The name for this switch
OUTPUT:
**sid** - The unique switch_id of the created switch
EXAMPLE:
create_switch(net, bus = 0, element = 1, et = 'b', type ="LS", z_ohm = 0.1)
create_switch(net, bus = 0, element = 1, et = 'l')
"""
_check_node_element(net, bus)
if et == "l":
elm_tab = 'line'
if element not in net[elm_tab].index:
raise UserWarning("Unknown line index")
if (not net[elm_tab]["from_bus"].loc[element] == bus and
not net[elm_tab]["to_bus"].loc[element] == bus):
raise UserWarning("Line %s not connected to bus %s" % (element, bus))
elif et == "t":
elm_tab = 'trafo'
if element not in net[elm_tab].index:
raise UserWarning("Unknown bus index")
if (not net[elm_tab]["hv_bus"].loc[element] == bus and
not net[elm_tab]["lv_bus"].loc[element] == bus):
raise UserWarning("Trafo %s not connected to bus %s" % (element, bus))
elif et == "t3":
elm_tab = 'trafo3w'
if element not in net[elm_tab].index:
raise UserWarning("Unknown trafo3w index")
if (not net[elm_tab]["hv_bus"].loc[element] == bus and
not net[elm_tab]["mv_bus"].loc[element] == bus and
not net[elm_tab]["lv_bus"].loc[element] == bus):
raise UserWarning("Trafo3w %s not connected to bus %s" % (element, bus))
elif et == "b":
_check_node_element(net, element)
else:
raise UserWarning("Unknown element type")
index = _get_index_with_check(net, "switch", index)
entries = dict(zip(["bus", "element", "et", "closed", "type", "name", "z_ohm"],
[bus, element, et, closed, type, name, z_ohm]))
_set_entries(net, "switch", index, **entries)
return index
def create_switches(net, buses, elements, et, closed=True, type=None, name=None, index=None,
z_ohm=0, **kwargs):
"""
Adds a switch in the net["switch"] table.
Switches can be either between two buses (bus-bus switch) or at the end of a line or transformer
element (bus-element switch).
Two buses that are connected through a closed bus-bus switches are fused in the power flow if
the switch is closed or separated if the switch is open.
An element that is connected to a bus through a bus-element switch is connected to the bus
if the switch is closed or disconnected if the switch is open.
INPUT:
**net** (pandapowerNet) - The net within which this switch should be created
**buses** (list)- The bus that the switch is connected to
**element** (list)- index of the element: bus id if et == "b", line id if et == "l", \
trafo id if et == "t"
**et** - (list) element type: "l" = switch between bus and line, "t" = switch between
bus and transformer, "t3" = switch between bus and transformer3w, "b" = switch between
two buses
OPTIONAL:
**closed** (boolean, True) - switch position: False = open, True = closed
**type** (int, None) - indicates the type of switch: "LS" = Load Switch, "CB" = \
Circuit Breaker, "LBS" = Load Break Switch or "DS" = Disconnecting Switch
**z_ohm** (float, 0) - indicates the resistance of the switch, which has effect only on
bus-bus switches, if sets to 0, the buses will be fused like before, if larger than
0 a branch will be created for the switch which has also effects on the bus mapping
**name** (string, default None) - The name for this switch
OUTPUT:
**sid** - The unique switch_id of the created switch
EXAMPLE:
create_switch(net, bus = 0, element = 1, et = 'b', type ="LS", z_ohm = 0.1)
create_switch(net, bus = 0, element = 1, et = 'l')
"""
index = _get_multiple_index_with_check(net, "switch", index, len(buses), name="Switches")
_check_multiple_node_elements(net, buses)
for element, elm_type, bus in zip(elements, et, buses):
if elm_type == "l":
elm_tab = 'line'
if element not in net[elm_tab].index:
raise UserWarning("Line %s does not exist" % element)
if (not net[elm_tab]["from_bus"].loc[element] == bus and
not net[elm_tab]["to_bus"].loc[element] == bus):
raise UserWarning("Line %s not connected to bus %s" % (element, bus))
elif elm_type == "t":
elm_tab = 'trafo'
if element not in net[elm_tab].index:
raise UserWarning("Trafo %s does not exist" % element)
if (not net[elm_tab]["hv_bus"].loc[element] == bus and
not net[elm_tab]["lv_bus"].loc[element] == bus):
raise UserWarning("Trafo %s not connected to bus %s" % (element, bus))
elif elm_type == "t3":
elm_tab = 'trafo3w'
if element not in net[elm_tab].index:
raise UserWarning("Trafo3w %s does not exist" % element)
if (not net[elm_tab]["hv_bus"].loc[element] == bus and
not net[elm_tab]["mv_bus"].loc[element] == bus and
not net[elm_tab]["lv_bus"].loc[element] == bus):
raise UserWarning("Trafo3w %s not connected to bus %s" % (element, bus))
elif elm_type == "b":
_check_node_element(net, element)
else:
raise UserWarning("Unknown element type")
entries = {"bus": buses, "element": elements, "et": et, "closed": closed, "type": type,
"name": name, "z_ohm": z_ohm}
_set_multiple_entries(net, "switch", index, **entries, **kwargs)
return index
def create_shunt(net, bus, q_mvar, p_mw=0., vn_kv=None, step=1, max_step=1, name=None,
in_service=True, index=None):
"""
Creates a shunt element
INPUT:
**net** (pandapowerNet) - The pandapower network in which the element is created
**bus** - bus number of bus to whom the shunt is connected to
**p_mw** - shunt active power in MW at v= 1.0 p.u.
**q_mvar** - shunt susceptance in MVAr at v= 1.0 p.u.
OPTIONAL:
**vn_kv** (float, None) - rated voltage of the shunt. Defaults to rated voltage of \
connected bus
**step** (int, 1) - step of shunt with which power values are multiplied
**max_step** (boolean, True) - True for in_service or False for out of service
**name** (str, None) - element name
**in_service** (boolean, True) - True for in_service or False for out of service
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
OUTPUT:
**index** (int) - The unique ID of the created shunt
EXAMPLE:
create_shunt(net, 0, 20)
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "shunt", index)
if vn_kv is None:
vn_kv = net.bus.vn_kv.at[bus]
entries = dict(zip(["bus", "name", "p_mw", "q_mvar", "vn_kv", "step", "max_step", "in_service"],
[bus, name, p_mw, q_mvar, vn_kv, step, max_step, in_service]))
_set_entries(net, "shunt", index, **entries)
return index
def create_shunt_as_capacitor(net, bus, q_mvar, loss_factor, **kwargs):
"""
Creates a shunt element representing a capacitor bank.
INPUT:
**net** (pandapowerNet) - The pandapower network in which the element is created
**bus** - bus number of bus to whom the shunt is connected to
**q_mvar** (float) - reactive power of the capacitor bank at rated voltage
**loss_factor** (float) - loss factor tan(delta) of the capacitor bank
OPTIONAL:
same as in create_shunt, keyword arguments are passed to the create_shunt function
OUTPUT:
**index** (int) - The unique ID of the created shunt
"""
q_mvar = -abs(q_mvar) # q is always negative for capacitor
p_mw = abs(q_mvar * loss_factor) # p is always positive for active power losses
return create_shunt(net, bus, q_mvar=q_mvar, p_mw=p_mw, **kwargs)
def create_impedance(net, from_bus, to_bus, rft_pu, xft_pu, sn_mva, rtf_pu=None, xtf_pu=None,
name=None, in_service=True, index=None):
"""
Creates an per unit impedance element
INPUT:
**net** (pandapowerNet) - The pandapower network in which the element is created
**from_bus** (int) - starting bus of the impedance
**to_bus** (int) - ending bus of the impedance
**r_pu** (float) - real part of the impedance in per unit
**x_pu** (float) - imaginary part of the impedance in per unit
**sn_mva** (float) - rated power of the impedance in MVA
OUTPUT:
impedance id
"""
index = _get_index_with_check(net, "impedance", index)
_check_branch_element(net, "Impedance", index, from_bus, to_bus)
if rtf_pu is None:
rtf_pu = rft_pu
if xtf_pu is None:
xtf_pu = xft_pu
columns = ["from_bus", "to_bus", "rft_pu", "xft_pu", "rtf_pu", "xtf_pu", "name", "sn_mva",
"in_service"]
values = [from_bus, to_bus, rft_pu, xft_pu, rtf_pu, xtf_pu, name, sn_mva, in_service]
_set_entries(net, "impedance", index, **dict(zip(columns, values)))
return index
def create_series_reactor_as_impedance(net, from_bus, to_bus, r_ohm, x_ohm, sn_mva,
name=None, in_service=True, index=None):
"""
Creates a series reactor as per-unit impedance
:param net: (pandapowerNet) - The pandapower network in which the element is created
:param from_bus: (int) - starting bus of the series reactor
:param to_bus: (int) - ending bus of the series reactor
:param r_ohm: (float) - real part of the impedance in Ohm
:param x_ohm: (float) - imaginary part of the impedance in Ohm
:param sn_mva: (float) - rated power of the series reactor in MVA
:param name:
:type name:
:param in_service:
:type in_service:
:param index:
:type index:
:return: index of the created element
"""
if net.bus.at[from_bus, 'vn_kv'] == net.bus.at[to_bus, 'vn_kv']:
vn_kv = net.bus.at[from_bus, 'vn_kv']
else:
raise UserWarning('Unable to infer rated voltage vn_kv for series reactor %s due to '
'different rated voltages of from_bus %d (%.3f p.u.) and '
'to_bus %d (%.3f p.u.)' % (name, from_bus, net.bus.at[from_bus, 'vn_kv'],
to_bus, net.bus.at[to_bus, 'vn_kv']))
base_z_ohm = vn_kv ** 2 / sn_mva
rft_pu = r_ohm / base_z_ohm
xft_pu = x_ohm / base_z_ohm
index = create_impedance(net, from_bus=from_bus, to_bus=to_bus, rft_pu=rft_pu, xft_pu=xft_pu,
sn_mva=sn_mva, name=name, in_service=in_service, index=index)
return index
def create_ward(net, bus, ps_mw, qs_mvar, pz_mw, qz_mvar, name=None, in_service=True, index=None):
"""
Creates a ward equivalent.
A ward equivalent is a combination of an impedance load and a PQ load.
INPUT:
**net** (pandapowernet) - The pandapower net within the element should be created
**bus** (int) - bus of the ward equivalent
**ps_mw** (float) - active power of the PQ load
**qs_mvar** (float) - reactive power of the PQ load
**pz_mw** (float) - active power of the impedance load in MW at 1.pu voltage
**qz_mvar** (float) - reactive power of the impedance load in MVar at 1.pu voltage
OUTPUT:
ward id
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "ward", index, "ward equivalent")
entries = dict(zip(["bus", "ps_mw", "qs_mvar", "pz_mw", "qz_mvar", "name", "in_service"],
[bus, ps_mw, qs_mvar, pz_mw, qz_mvar, name, in_service]))
_set_entries(net, "ward", index, **entries)
return index
def create_xward(net, bus, ps_mw, qs_mvar, pz_mw, qz_mvar, r_ohm, x_ohm, vm_pu, in_service=True,
name=None, index=None, slack_weight=0.0):
"""
Creates an extended ward equivalent.
A ward equivalent is a combination of an impedance load, a PQ load and as voltage source with
an internal impedance.
INPUT:
**net** - The pandapower net within the impedance should be created
**bus** (int) - bus of the ward equivalent
**ps_mw** (float) - active power of the PQ load
**qs_mvar** (float) - reactive power of the PQ load
**pz_mw** (float) - active power of the impedance load in MW at 1.pu voltage
**qz_mvar** (float) - reactive power of the impedance load in MVar at 1.pu voltage
**r_ohm** (float) - internal resistance of the voltage source
**x_ohm** (float) - internal reactance of the voltage source
**vm_pu** (float) - voltage magnitude at the additional PV-node
**slack_weight** (float, default 1.0) - Contribution factor for distributed slack power flow calculation (active power balancing)
OUTPUT:
xward id
"""
_check_node_element(net, bus)
index = _get_index_with_check(net, "xward", index, "extended ward equivalent")
columns = ["bus", "ps_mw", "qs_mvar", "pz_mw", "qz_mvar", "r_ohm", "x_ohm", "vm_pu", "name",
"slack_weight", "in_service"]
values = [bus, ps_mw, qs_mvar, pz_mw, qz_mvar, r_ohm, x_ohm, vm_pu, name, slack_weight, in_service]
_set_entries(net, "xward", index, **dict(zip(columns, values)))
return index
def create_dcline(net, from_bus, to_bus, p_mw, loss_percent, loss_mw, vm_from_pu, vm_to_pu,
index=None, name=None, max_p_mw=nan, min_q_from_mvar=nan, min_q_to_mvar=nan,
max_q_from_mvar=nan, max_q_to_mvar=nan, in_service=True):
"""
Creates a dc line.
INPUT:
**from_bus** (int) - ID of the bus on one side which the line will be connected with
**to_bus** (int) - ID of the bus on the other side which the line will be connected with
**p_mw** - (float) Active power transmitted from 'from_bus' to 'to_bus'
**loss_percent** - (float) Relative transmission loss in percent of active power
transmission
**loss_mw** - (float) Total transmission loss in MW
**vm_from_pu** - (float) Voltage setpoint at from bus
**vm_to_pu** - (float) Voltage setpoint at to bus
OPTIONAL:
**index** (int, None) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**name** (str, None) - A custom name for this dc line
**in_service** (boolean) - True for in_service or False for out of service
**max_p_mw** - Maximum active power flow. Only respected for OPF
**min_q_from_mvar** - Minimum reactive power at from bus. Necessary for OPF
**min_q_to_mvar** - Minimum reactive power at to bus. Necessary for OPF
**max_q_from_mvar** - Maximum reactive power at from bus. Necessary for OPF
**max_q_to_mvar** - Maximum reactive power at to bus. Necessary for OPF
OUTPUT:
**index** (int) - The unique ID of the created element
EXAMPLE:
create_dcline(net, from_bus=0, to_bus=1, p_mw=1e4, loss_percent=1.2, loss_mw=25, \
vm_from_pu=1.01, vm_to_pu=1.02)
"""
index = _get_index_with_check(net, "dcline", index)
_check_branch_element(net, "DCLine", index, from_bus, to_bus)
columns = ["name", "from_bus", "to_bus", "p_mw", "loss_percent", "loss_mw", "vm_from_pu",
"vm_to_pu", "max_p_mw", "min_q_from_mvar", "min_q_to_mvar", "max_q_from_mvar",
"max_q_to_mvar", "in_service"]
values = [name, from_bus, to_bus, p_mw, loss_percent, loss_mw, vm_from_pu, vm_to_pu, max_p_mw,
min_q_from_mvar, min_q_to_mvar, max_q_from_mvar, max_q_to_mvar, in_service]
_set_entries(net, "dcline", index, **dict(zip(columns, values)))
return index
def create_measurement(net, meas_type, element_type, value, std_dev, element, side=None,
check_existing=True, index=None, name=None):
"""
Creates a measurement, which is used by the estimation module. Possible types of measurements
are: v, p, q, i, va, ia
INPUT:
**meas_type** (string) - Type of measurement. "v", "p", "q", "i", "va", "ia" are possible
**element_type** (string) - Clarifies which element is measured. "bus", "line",
"trafo", and "trafo3w" are possible
**value** (float) - Measurement value. Units are "MW" for P, "MVar" for Q, "p.u." for V,
"kA" for I. Bus power measurement is in load reference system, which is consistent to
the rest of pandapower.
**std_dev** (float) - Standard deviation in the same unit as the measurement
**element** (int) - Index of the measured element (either bus index, line index,\
trafo index, trafo3w index)
**side** (int, string, default: None) - Only used for measured lines or transformers. Side \
defines at which end of the branch the measurement is gathered. For lines this may be \
"from", "to" to denote the side with the from_bus or to_bus. It can also the be index \
of the from_bus or to_bus. For transformers, it can be "hv", "mv" or "lv" or the \
corresponding bus index, respectively
OPTIONAL:
**check_existing** (bool, default: None) - Check for and replace existing measurements for\
this bus, type and element_type. Set it to false for performance improvements which can\
cause unsafe behavior
**index** (int, default: None) - Index of the measurement in the measurement table. Should\
not exist already.
**name** (str, default: None) - Name of measurement
OUTPUT:
(int) Index of measurement
EXAMPLES:
2 MW load measurement with 0.05 MW standard deviation on bus 0:
create_measurement(net, "p", "bus", 0, 2., 0.05.)
4.5 MVar line measurement with 0.1 MVar standard deviation on the "to_bus" side of line 2
create_measurement(net, "q", "line", 2, 4.5, 0.1, "to")
"""
if meas_type not in ("v", "p", "q", "i", "va", "ia"):
raise UserWarning("Invalid measurement type ({})".format(meas_type))
if side is None and element_type in ("line", "trafo"):
raise UserWarning("The element type '{element_type}' requires a value in 'side'")
if meas_type in ("v", "va"):
element_type = "bus"
if element_type not in ("bus", "line", "trafo", "trafo3w"):
raise UserWarning("Invalid element type ({})".format(element_type))
if element is not None and element not in net[element_type].index.values:
raise UserWarning("{} with index={} does not exist".format(element_type.capitalize(),
element))
index = _get_index_with_check(net, "measurement", index)
if meas_type in ("i", "ia") and element_type == "bus":
raise UserWarning("Line current measurements cannot be placed at buses")
if meas_type in ("v", "va") and element_type in ("line", "trafo", "trafo3w"):
raise UserWarning(
"Voltage measurements can only be placed at buses, not at {}".format(element_type))
if check_existing:
if side is None:
existing = net.measurement[(net.measurement.measurement_type == meas_type) &
(net.measurement.element_type == element_type) &
(net.measurement.element == element) &
(pd.isnull(net.measurement.side))].index
else:
existing = net.measurement[(net.measurement.measurement_type == meas_type) &
(net.measurement.element_type == element_type) &
(net.measurement.element == element) &
(net.measurement.side == side)].index
if len(existing) == 1:
index = existing[0]
elif len(existing) > 1:
raise UserWarning("More than one measurement of this type exists")
columns = ["name", "measurement_type", "element_type", "element", "value", "std_dev", "side"]
values = [name, meas_type.lower(), element_type, element, value, std_dev, side]
_set_entries(net, "measurement", index, **dict(zip(columns, values)))
return index
def create_pwl_cost(net, element, et, points, power_type="p", index=None, check=True):
"""
Creates an entry for piecewise linear costs for an element. The currently supported elements are
- Generator
- External Grid
- Static Generator
- Load
- Dcline
- Storage
INPUT:
**element** (int) - ID of the element in the respective element table
**et** (string) - element type, one of "gen", "sgen", "ext_grid", "load",
"dcline", "storage"]
**points** - (list) list of lists with [[p1, p2, c1], [p2, p3, c2], ...] where c(n) \
defines the costs between p(n) and p(n+1)
OPTIONAL:
**type** - (string) - Type of cost ["p", "q"] are allowed for active or reactive power
**index** (int, index) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**check** (bool, True) - raises UserWarning if costs already exist to this element.
OUTPUT:
**index** (int) - The unique ID of created cost entry
EXAMPLE:
The cost function is given by the x-values p1 and p2 with the slope m between those points.\
The constant part b of a linear function y = m*x + b can be neglected for OPF purposes. \
The intervals have to be continuous (the starting point of an interval has to be equal to \
the end point of the previous interval).
To create a gen with costs of 1€/MW between 0 and 20 MW and 2€/MW between 20 and 30:
create_pwl_cost(net, 0, "gen", [[0, 20, 1], [20, 30, 2]])
"""
element = element if not hasattr(element, "__iter__") else element[0]
if check and _cost_existance_check(net, element, et, power_type=power_type):
raise UserWarning("There already exist costs for %s %i" % (et, element))
index = _get_index_with_check(net, "pwl_cost", index, "piecewise_linear_cost")
entries = dict(zip(["power_type", "element", "et", "points"],
[power_type, element, et, points]))
_set_entries(net, "pwl_cost", index, **entries)
return index
def create_poly_cost(net, element, et, cp1_eur_per_mw, cp0_eur=0, cq1_eur_per_mvar=0,
cq0_eur=0, cp2_eur_per_mw2=0, cq2_eur_per_mvar2=0, index=None, check=True):
"""
Creates an entry for polynimoal costs for an element. The currently supported elements are:
- Generator ("gen")
- External Grid ("ext_grid")
- Static Generator ("sgen")
- Load ("load")
- Dcline ("dcline")
- Storage ("storage")
INPUT:
**element** (int) - ID of the element in the respective element table
**et** (string) - Type of element ["gen", "sgen", "ext_grid", "load", "dcline", "storage"] \
are possible
**cp1_eur_per_mw** (float) - Linear costs per MW
**cp0_eur=0** (float) - Offset active power costs in euro
**cq1_eur_per_mvar=0** (float) - Linear costs per Mvar
**cq0_eur=0** (float) - Offset reactive power costs in euro
**cp2_eur_per_mw2=0** (float) - Quadratic costs per MW
**cq2_eur_per_mvar2=0** (float) - Quadratic costs per Mvar
OPTIONAL:
**index** (int, index) - Force a specified ID if it is available. If None, the index one \
higher than the highest already existing index is selected.
**check** (bool, True) - raises UserWarning if costs already exist to this element.
OUTPUT:
**index** (int) - The unique ID of created cost entry
EXAMPLE:
The polynomial cost function is given by the linear and quadratic cost coefficients.
create_poly_cost(net, 0, "load", cp1_eur_per_mw = 0.1)
"""
element = element if not hasattr(element, "__iter__") else element[0]
if check and _cost_existance_check(net, element, et):
raise UserWarning("There already exist costs for %s %i" % (et, element))
index = _get_index_with_check(net, "poly_cost", index)
columns = ["element", "et", "cp0_eur", "cp1_eur_per_mw", "cq0_eur", "cq1_eur_per_mvar",
"cp2_eur_per_mw2", "cq2_eur_per_mvar2"]
variables = [element, et, cp0_eur, cp1_eur_per_mw, cq0_eur, cq1_eur_per_mvar,
cp2_eur_per_mw2, cq2_eur_per_mvar2]
_set_entries(net, "poly_cost", index, **dict(zip(columns, variables)))
return index
def _get_index_with_check(net, table, index, name=None):
if name is None:
name = table
if index is None:
index = get_free_id(net[table])
if index in net[table].index:
raise UserWarning("A %s with the id %s already exists" % (name, index))
return index
def _cost_existance_check(net, element, et, power_type=None):
if power_type is None:
return (bool(net.poly_cost.shape[0]) and
np_any((net.poly_cost.element == element).values &
(net.poly_cost.et == et).values)) \
or (bool(net.pwl_cost.shape[0]) and
np_any((net.pwl_cost.element == element).values &
(net.pwl_cost.et == et).values))
else:
return (bool(net.poly_cost.shape[0]) and
np_any((net.poly_cost.element == element).values &
(net.poly_cost.et == et).values)) \
or (bool(net.pwl_cost.shape[0]) and
np_any((net.pwl_cost.element == element).values &
(net.pwl_cost.et == et).values &
(net.pwl_cost.power_type == power_type).values))
def _get_multiple_index_with_check(net, table, index, number, name=None):
if name is None:
name = table.capitalize() + "s"
if index is None:
bid = get_free_id(net[table])
return arange(bid, bid + number, 1)
contained = isin(net[table].index.values, index)
if np_any(contained):
raise UserWarning("%s with indexes %s already exist."
% (name, net[table].index.values[contained]))
return index
def _check_node_element(net, node, node_table="bus"):
if node not in net[node_table].index.values:
raise UserWarning("Cannot attach to %s %s, %s does not exist"
% (node_table, node, node_table))
def _check_multiple_node_elements(net, nodes, node_table="bus", name="buses"):
if np_any(~isin(nodes, net[node_table].index.values)):
node_not_exist = set(nodes) - set(net[node_table].index.values)
raise UserWarning("Cannot attach to %s %s, they do not exist" % (name, node_not_exist))
def _check_branch_element(net, element_name, index, from_node, to_node, node_name="bus",
plural="es"):
missing_nodes = {from_node, to_node} - set(net[node_name].index.values)
if missing_nodes:
raise UserWarning("%s %d tries to attach to non-existing %s(%s) %s"
% (element_name.capitalize(), index, node_name, plural, missing_nodes))
def _check_multiple_branch_elements(net, from_nodes, to_nodes, element_name, node_name="bus",
plural="es"):
all_nodes = array(list(from_nodes) + list(to_nodes))
if np_any(~isin(all_nodes, net[node_name].index.values)):
node_not_exist = set(all_nodes) - set(net[node_name].index)
raise UserWarning("%s trying to attach to non existing %s%s %s"
% (element_name, node_name, plural, node_not_exist))
def _create_column_and_set_value(net, index, variable, column, element, dtyp=float64,
default_val=nan, default_for_nan=False):
# if variable (e.g. p_mw) is not None and column (e.g. "p_mw") doesn't exist in element
# (e.g. "gen") table
# create this column and write the value of variable to the index of this element
try:
set_value = not (isnan(variable) or variable is None)
except TypeError:
set_value = True
if set_value:
if column not in net[element].columns:
# this part is for compatibility with pandas < 1.0, can be removed if pandas >= 1.0 is required in setup.py
if isinstance(default_val, str) \
and version.parse(pd.__version__) < version.parse("1.0"):
net[element].loc[:, column] = pd.Series([default_val] * len(net[element]),
dtype=dtyp)
else:
net[element].loc[:, column] = pd.Series(data=default_val, index=net[element].index, dtype=dtyp)
net[element].at[index, column] = variable
elif default_for_nan and column in net[element].columns:
net[element].at[index, column] = default_val
return net
def _add_series_to_entries(entries, index, column, values, dtyp=float64, default_val=nan):
if values is not None:
try:
fill_default = not isnan(default_val)
except TypeError:
fill_default = True
if isinstance(values, str) and version.parse(pd.__version__) < version.parse("1.0"):
s = pd.Series([values] * len(index), index=index, dtype=dtyp)
else:
s = pd.Series(values, index=index, dtype=dtyp)
if fill_default:
s = s.fillna(default_val)
entries[column] = s
def _add_multiple_branch_geodata(net, table, geodata, index):
geo_table = "%s_geodata" % table
dtypes = net[geo_table].dtypes
df = pd.DataFrame(index=index, columns=net[geo_table].columns)
# works with single or multiple lists of coordinates
if len(geodata[0]) == 2 and not hasattr(geodata[0][0], "__iter__"):
# geodata is a single list of coordinates
df["coords"] = [geodata] * len(index)
else:
# geodata is multiple lists of coordinates
df["coords"] = geodata
# todo: drop version checks
if version.parse(pd.__version__) >= version.parse("0.23"):
net[geo_table] = pd.concat([net[geo_table],df], sort=False)
else:
# prior to pandas 0.23 there was no explicit parameter (instead it was standard behavior)
net[geo_table] = net[geo_table].append(df)
_preserve_dtypes(net[geo_table], dtypes)
def _set_entries(net, table, index, preserve_dtypes=True, **entries):
dtypes = None
if preserve_dtypes:
# only get dtypes of columns that are set and that are already present in the table
dtypes = net[table][intersect1d(net[table].columns, list(entries.keys()))].dtypes
for col, val in entries.items():
net[table].at[index, col] = val
# and preserve dtypes
if preserve_dtypes:
_preserve_dtypes(net[table], dtypes)
def _set_multiple_entries(net, table, index, preserve_dtypes=True, **entries):
dtypes = None
if preserve_dtypes:
# store dtypes
dtypes = net[table].dtypes
def check_entry(val):
if isinstance(val, pd.Series) and not np_all(isin(val.index, index)):
return val.values
elif isinstance(val, set) and len(val) == len(index):
return list(val)
return val
entries = {k: check_entry(v) for k, v in entries.items()}
dd = pd.DataFrame(index=index, columns=net[table].columns)
dd = dd.assign(**entries)
# extend the table by the frame we just created
if version.parse(pd.__version__) >= version.parse("0.23"):
net[table] = pd.concat([net[table],dd], sort=False)
else:
# prior to pandas 0.23 there was no explicit parameter (instead it was standard behavior)
net[table] = net[table].append(dd)
# and preserve dtypes
if preserve_dtypes:
_preserve_dtypes(net[table], dtypes)
| 45.186543 | 180 | 0.599734 |
from operator import itemgetter
import pandas as pd
from numpy import nan, isnan, arange, dtype, isin, any as np_any, zeros, array, bool_, \
all as np_all, float64, intersect1d
from packaging import version
from pandapower import __version__
from pandapower.auxiliary import pandapowerNet, get_free_id, _preserve_dtypes
from pandapower.results import reset_results
from pandapower.std_types import add_basic_std_types, load_std_type, check_entry_in_std_type
import numpy as np
try:
import pandaplan.core.pplog as logging
except ImportError:
import logging
logger = logging.getLogger(__name__)
def create_empty_network(name="", f_hz=50., sn_mva=1, add_stdtypes=True):
net = pandapowerNet({
"bus": [('name', dtype(object)),
('vn_kv', 'f8'),
('type', dtype(object)),
('zone', dtype(object)),
('in_service', 'bool'), ],
"load": [("name", dtype(object)),
("bus", "u4"),
("p_mw", "f8"),
("q_mvar", "f8"),
("const_z_percent", "f8"),
("const_i_percent", "f8"),
("sn_mva", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("type", dtype(object))],
"sgen": [("name", dtype(object)),
("bus", "i8"),
("p_mw", "f8"),
("q_mvar", "f8"),
("sn_mva", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("type", dtype(object)),
("current_source", "bool")],
"motor": [("name", dtype(object)),
("bus", "i8"),
("pn_mech_mw", "f8"),
("loading_percent", "f8"),
("cos_phi", "f8"),
("cos_phi_n", "f8"),
("efficiency_percent", "f8"),
("efficiency_n_percent", "f8"),
("lrc_pu", "f8"),
("vn_kv", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("rx", 'f8')
],
"asymmetric_load": [("name", dtype(object)),
("bus", "u4"),
("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8"),
("sn_mva", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("type", dtype(object))],
"asymmetric_sgen": [("name", dtype(object)),
("bus", "i8"),
("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8"),
("sn_mva", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("type", dtype(object)),
("current_source", "bool")],
"storage": [("name", dtype(object)),
("bus", "i8"),
("p_mw", "f8"),
("q_mvar", "f8"),
("sn_mva", "f8"),
("soc_percent", "f8"),
("min_e_mwh", "f8"),
("max_e_mwh", "f8"),
("scaling", "f8"),
("in_service", 'bool'),
("type", dtype(object))],
"gen": [("name", dtype(object)),
("bus", "u4"),
("p_mw", "f8"),
("vm_pu", "f8"),
("sn_mva", "f8"),
("min_q_mvar", "f8"),
("max_q_mvar", "f8"),
("scaling", "f8"),
("slack", "bool"),
("in_service", 'bool'),
("slack_weight", 'f8'),
("type", dtype(object))],
"switch": [("bus", "i8"),
("element", "i8"),
("et", dtype(object)),
("type", dtype(object)),
("closed", "bool"),
("name", dtype(object)),
("z_ohm", "f8")],
"shunt": [("bus", "u4"),
("name", dtype(object)),
("q_mvar", "f8"),
("p_mw", "f8"),
("vn_kv", "f8"),
("step", "u4"),
("max_step", "u4"),
("in_service", "bool")],
"ext_grid": [("name", dtype(object)),
("bus", "u4"),
("vm_pu", "f8"),
("va_degree", "f8"),
("slack_weight", 'f8'),
("in_service", 'bool')],
"line": [("name", dtype(object)),
("std_type", dtype(object)),
("from_bus", "u4"),
("to_bus", "u4"),
("length_km", "f8"),
("r_ohm_per_km", "f8"),
("x_ohm_per_km", "f8"),
("c_nf_per_km", "f8"),
("g_us_per_km", "f8"),
("max_i_ka", "f8"),
("df", "f8"),
("parallel", "u4"),
("type", dtype(object)),
("in_service", 'bool')],
"trafo": [("name", dtype(object)),
("std_type", dtype(object)),
("hv_bus", "u4"),
("lv_bus", "u4"),
("sn_mva", "f8"),
("vn_hv_kv", "f8"),
("vn_lv_kv", "f8"),
("vk_percent", "f8"),
("vkr_percent", "f8"),
("pfe_kw", "f8"),
("i0_percent", "f8"),
("shift_degree", "f8"),
("tap_side", dtype(object)),
("tap_neutral", "i4"),
("tap_min", "i4"),
("tap_max", "i4"),
("tap_step_percent", "f8"),
("tap_step_degree", "f8"),
("tap_pos", "i4"),
("tap_phase_shifter", 'bool'),
("parallel", "u4"),
("df", "f8"),
("in_service", 'bool')],
"trafo3w": [("name", dtype(object)),
("std_type", dtype(object)),
("hv_bus", "u4"),
("mv_bus", "u4"),
("lv_bus", "u4"),
("sn_hv_mva", "f8"),
("sn_mv_mva", "f8"),
("sn_lv_mva", "f8"),
("vn_hv_kv", "f8"),
("vn_mv_kv", "f8"),
("vn_lv_kv", "f8"),
("vk_hv_percent", "f8"),
("vk_mv_percent", "f8"),
("vk_lv_percent", "f8"),
("vkr_hv_percent", "f8"),
("vkr_mv_percent", "f8"),
("vkr_lv_percent", "f8"),
("pfe_kw", "f8"),
("i0_percent", "f8"),
("shift_mv_degree", "f8"),
("shift_lv_degree", "f8"),
("tap_side", dtype(object)),
("tap_neutral", "i4"),
("tap_min", "i4"),
("tap_max", "i4"),
("tap_step_percent", "f8"),
("tap_step_degree", "f8"),
("tap_pos", "i4"),
("tap_at_star_point", 'bool'),
("in_service", 'bool')],
"impedance": [("name", dtype(object)),
("from_bus", "u4"),
("to_bus", "u4"),
("rft_pu", "f8"),
("xft_pu", "f8"),
("rtf_pu", "f8"),
("xtf_pu", "f8"),
("sn_mva", "f8"),
("in_service", 'bool')],
"dcline": [("name", dtype(object)),
("from_bus", "u4"),
("to_bus", "u4"),
("p_mw", "f8"),
("loss_percent", 'f8'),
("loss_mw", 'f8'),
("vm_from_pu", "f8"),
("vm_to_pu", "f8"),
("max_p_mw", "f8"),
("min_q_from_mvar", "f8"),
("min_q_to_mvar", "f8"),
("max_q_from_mvar", "f8"),
("max_q_to_mvar", "f8"),
("in_service", 'bool')],
"ward": [("name", dtype(object)),
("bus", "u4"),
("ps_mw", "f8"),
("qs_mvar", "f8"),
("qz_mvar", "f8"),
("pz_mw", "f8"),
("in_service", "bool")],
"xward": [("name", dtype(object)),
("bus", "u4"),
("ps_mw", "f8"),
("qs_mvar", "f8"),
("qz_mvar", "f8"),
("pz_mw", "f8"),
("r_ohm", "f8"),
("x_ohm", "f8"),
("vm_pu", "f8"),
("slack_weight", 'f8'),
("in_service", "bool")],
"measurement": [("name", dtype(object)),
("measurement_type", dtype(object)),
("element_type", dtype(object)),
("element", "uint32"),
("value", "float64"),
("std_dev", "float64"),
("side", dtype(object))],
"pwl_cost": [("power_type", dtype(object)),
("element", "u4"),
("et", dtype(object)),
("points", dtype(object))],
"poly_cost": [("element", "u4"),
("et", dtype(object)),
("cp0_eur", dtype("f8")),
("cp1_eur_per_mw", dtype("f8")),
("cp2_eur_per_mw2", dtype("f8")),
("cq0_eur", dtype("f8")),
("cq1_eur_per_mvar", dtype("f8")),
("cq2_eur_per_mvar2", dtype("f8"))
],
'characteristic': [
('object', dtype(object))
],
'controller': [
('object', dtype(object)),
('in_service', "bool"),
('order', "float64"),
('level', dtype(object)),
('initial_run', "bool"),
("recycle", dtype(object))
],
"line_geodata": [("coords", dtype(object))],
"bus_geodata": [("x", "f8"), ("y", "f8"), ("coords", dtype(object))],
"_empty_res_bus": [("vm_pu", "f8"),
("va_degree", "f8"),
("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_ext_grid": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_line": [("p_from_mw", "f8"),
("q_from_mvar", "f8"),
("p_to_mw", "f8"),
("q_to_mvar", "f8"),
("pl_mw", "f8"),
("ql_mvar", "f8"),
("i_from_ka", "f8"),
("i_to_ka", "f8"),
("i_ka", "f8"),
("vm_from_pu", "f8"),
("va_from_degree", "f8"),
("vm_to_pu", "f8"),
("va_to_degree", "f8"),
("loading_percent", "f8")],
"_empty_res_trafo": [("p_hv_mw", "f8"),
("q_hv_mvar", "f8"),
("p_lv_mw", "f8"),
("q_lv_mvar", "f8"),
("pl_mw", "f8"),
("ql_mvar", "f8"),
("i_hv_ka", "f8"),
("i_lv_ka", "f8"),
("vm_hv_pu", "f8"),
("va_hv_degree", "f8"),
("vm_lv_pu", "f8"),
("va_lv_degree", "f8"),
("loading_percent", "f8")],
"_empty_res_load": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_asymmetric_load": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_asymmetric_sgen": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_motor": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_sgen": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_shunt": [("p_mw", "f8"),
("q_mvar", "f8"),
("vm_pu", "f8")],
"_empty_res_impedance": [("p_from_mw", "f8"),
("q_from_mvar", "f8"),
("p_to_mw", "f8"),
("q_to_mvar", "f8"),
("pl_mw", "f8"),
("ql_mvar", "f8"),
("i_from_ka", "f8"),
("i_to_ka", "f8")],
"_empty_res_dcline": [("p_from_mw", "f8"),
("q_from_mvar", "f8"),
("p_to_mw", "f8"),
("q_to_mvar", "f8"),
("pl_mw", "f8"),
("vm_from_pu", "f8"),
("va_from_degree", "f8"),
("vm_to_pu", "f8"),
("va_to_degree", "f8")],
"_empty_res_ward": [("p_mw", "f8"),
("q_mvar", "f8"),
("vm_pu", "f8")],
"_empty_res_xward": [("p_mw", "f8"),
("q_mvar", "f8"),
("vm_pu", "f8"),
("va_internal_degree", "f8"),
("vm_internal_pu", "f8")],
"_empty_res_trafo_3ph": [("p_a_hv_mw", "f8"),
("q_a_hv_mvar", "f8"),
("p_b_hv_mw", "f8"),
("q_b_hv_mvar", "f8"),
("p_c_hv_mw", "f8"),
("q_c_hv_mvar", "f8"),
("p_a_lv_mw", "f8"),
("q_a_lv_mvar", "f8"),
("p_b_lv_mw", "f8"),
("q_b_lv_mvar", "f8"),
("p_c_lv_mw", "f8"),
("q_c_lv_mvar", "f8"),
("p_a_l_mw", "f8"),
("q_a_l_mvar", "f8"),
("p_b_l_mw", "f8"),
("q_b_l_mvar", "f8"),
("p_c_l_mw", "f8"),
("q_c_l_mvar", "f8"),
("i_a_hv_ka", "f8"),
("i_a_lv_ka", "f8"),
("i_b_hv_ka", "f8"),
("i_b_lv_ka", "f8"),
("i_c_hv_ka", "f8"),
("i_c_lv_ka", "f8"),
("loading_a_percent", "f8"),
("loading_b_percent", "f8"),
("loading_c_percent", "f8"),
("loading_percent", "f8")],
"_empty_res_trafo3w": [("p_hv_mw", "f8"),
("q_hv_mvar", "f8"),
("p_mv_mw", "f8"),
("q_mv_mvar", "f8"),
("p_lv_mw", "f8"),
("q_lv_mvar", "f8"),
("pl_mw", "f8"),
("ql_mvar", "f8"),
("i_hv_ka", "f8"),
("i_mv_ka", "f8"),
("i_lv_ka", "f8"),
("vm_hv_pu", "f8"),
("va_hv_degree", "f8"),
("vm_mv_pu", "f8"),
("va_mv_degree", "f8"),
("vm_lv_pu", "f8"),
("va_lv_degree", "f8"),
("va_internal_degree", "f8"),
("vm_internal_pu", "f8"),
("loading_percent", "f8")],
"_empty_res_bus_3ph": [("vm_a_pu", "f8"),
("va_a_degree", "f8"),
("vm_b_pu", "f8"),
("va_b_degree", "f8"),
("vm_c_pu", "f8"),
("va_c_degree", "f8"),
("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8")],
"_empty_res_ext_grid_3ph": [("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8")],
"_empty_res_line_3ph": [("p_a_from_mw", "f8"),
("q_a_from_mvar", "f8"),
("p_b_from_mw", "f8"),
("q_b_from_mvar", "f8"),
("q_c_from_mvar", "f8"),
("p_a_to_mw", "f8"),
("q_a_to_mvar", "f8"),
("p_b_to_mw", "f8"),
("q_b_to_mvar", "f8"),
("p_c_to_mw", "f8"),
("q_c_to_mvar", "f8"),
("p_a_l_mw", "f8"),
("q_a_l_mvar", "f8"),
("p_b_l_mw", "f8"),
("q_b_l_mvar", "f8"),
("p_c_l_mw", "f8"),
("q_c_l_mvar", "f8"),
("i_a_from_ka", "f8"),
("i_a_to_ka", "f8"),
("i_b_from_ka", "f8"),
("i_b_to_ka", "f8"),
("i_c_from_ka", "f8"),
("i_c_to_ka", "f8"),
("i_a_ka", "f8"),
("i_b_ka", "f8"),
("i_c_ka", "f8"),
("i_n_from_ka", "f8"),
("i_n_to_ka", "f8"),
("i_n_ka", "f8"),
("loading_a_percent", "f8"),
("loading_b_percent", "f8"),
("loading_c_percent", "f8")],
"_empty_res_asymmetric_load_3ph": [("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8")],
"_empty_res_asymmetric_sgen_3ph": [("p_a_mw", "f8"),
("q_a_mvar", "f8"),
("p_b_mw", "f8"),
("q_b_mvar", "f8"),
("p_c_mw", "f8"),
("q_c_mvar", "f8")],
"_empty_res_storage": [("p_mw", "f8"),
("q_mvar", "f8")],
"_empty_res_storage_3ph": [("p_a_mw", "f8"), ("p_b_mw", "f8"), ("p_c_mw", "f8"),
("q_a_mvar", "f8"), ("q_b_mvar", "f8"), ("q_c_mvar", "f8")],
"_empty_res_gen": [("p_mw", "f8"),
("q_mvar", "f8"),
("va_degree", "f8"),
("vm_pu", "f8")],
"_ppc": None,
"_ppc0": None,
"_ppc1": None,
"_ppc2": None,
"_is_elements": None,
"_pd2ppc_lookups": {"bus": None,
"ext_grid": None,
"gen": None,
"branch": None},
"version": __version__,
"converged": False,
"name": name,
"f_hz": f_hz,
"sn_mva": sn_mva
})
net._empty_res_load_3ph = net._empty_res_load
net._empty_res_sgen_3ph = net._empty_res_sgen
net._empty_res_storage_3ph = net._empty_res_storage
for s in net:
if isinstance(net[s], list):
net[s] = pd.DataFrame(zeros(0, dtype=net[s]), index=pd.Index([], dtype=np.int64))
if add_stdtypes:
add_basic_std_types(net)
else:
net.std_types = {"line": {}, "trafo": {}, "trafo3w": {}}
for mode in ["pf", "se", "sc", "pf_3ph"]:
reset_results(net, mode)
net['user_pf_options'] = dict()
return net
def create_bus(net, vn_kv, name=None, index=None, geodata=None, type="b", zone=None,
in_service=True, max_vm_pu=nan, min_vm_pu=nan, coords=None, **kwargs):
index = _get_index_with_check(net, "bus", index)
entries = dict(zip(["name", "vn_kv", "type", "zone", "in_service"],
[name, vn_kv, type, zone, bool(in_service)]))
_set_entries(net, "bus", index, True, **entries, **kwargs)
if geodata is not None:
if len(geodata) != 2:
raise UserWarning("geodata must be given as (x, y) tuple")
net["bus_geodata"].loc[index, ["x", "y"]] = geodata
if coords is not None:
net["bus_geodata"].at[index, "coords"] = coords
_create_column_and_set_value(net, index, min_vm_pu, "min_vm_pu", "bus", default_val=0.)
_create_column_and_set_value(net, index, max_vm_pu, "max_vm_pu", "bus", default_val=2.)
return index
def create_buses(net, nr_buses, vn_kv, index=None, name=None, type="b", geodata=None,
zone=None, in_service=True, max_vm_pu=None, min_vm_pu=None, coords=None, **kwargs):
index = _get_multiple_index_with_check(net, "bus", index, nr_buses)
entries = {"vn_kv": vn_kv, "type": type, "zone": zone, "in_service": in_service, "name": name}
_add_series_to_entries(entries, index, "min_vm_pu", min_vm_pu)
_add_series_to_entries(entries, index, "max_vm_pu", max_vm_pu)
_set_multiple_entries(net, "bus", index, **entries, **kwargs)
if geodata is not None:
net.bus_geodata = pd.concat([net.bus_geodata,
pd.DataFrame(zeros((len(index), len(net.bus_geodata.columns)), dtype=int),
index=index, columns=net.bus_geodata.columns)])
net.bus_geodata.loc[index, :] = nan
net.bus_geodata.loc[index, ["x", "y"]] = geodata
if coords is not None:
net.bus_geodata = pd.concat([net.bus_geodata, pd.DataFrame(index=index, columns=net.bus_geodata.columns)])
net["bus_geodata"].loc[index, "coords"] = coords
return index
def create_load(net, bus, p_mw, q_mvar=0, const_z_percent=0, const_i_percent=0, sn_mva=nan,
name=None, scaling=1., index=None, in_service=True, type='wye', max_p_mw=nan,
min_p_mw=nan, max_q_mvar=nan, min_q_mvar=nan, controllable=nan):
_check_node_element(net, bus)
index = _get_index_with_check(net, "load", index)
entries = dict(zip(["name", "bus", "p_mw", "const_z_percent", "const_i_percent", "scaling",
"q_mvar", "sn_mva", "in_service", "type"],
[name, bus, p_mw, const_z_percent, const_i_percent, scaling, q_mvar, sn_mva,
bool(in_service), type]))
_set_entries(net, "load", index, True, **entries)
_create_column_and_set_value(net, index, min_p_mw, "min_p_mw", "load")
_create_column_and_set_value(net, index, max_p_mw, "max_p_mw", "load")
_create_column_and_set_value(net, index, min_q_mvar, "min_q_mvar", "load")
_create_column_and_set_value(net, index, max_q_mvar, "max_q_mvar", "load")
_create_column_and_set_value(net, index, controllable, "controllable", "load", dtyp=bool_,
default_val=False, default_for_nan=True)
return index
def create_loads(net, buses, p_mw, q_mvar=0, const_z_percent=0, const_i_percent=0, sn_mva=nan,
name=None, scaling=1., index=None, in_service=True, type=None, max_p_mw=None,
min_p_mw=None, max_q_mvar=None, min_q_mvar=None, controllable=None, **kwargs):
_check_multiple_node_elements(net, buses)
index = _get_multiple_index_with_check(net, "load", index, len(buses))
entries = {"bus": buses, "p_mw": p_mw, "q_mvar": q_mvar, "sn_mva": sn_mva,
"const_z_percent": const_z_percent, "const_i_percent": const_i_percent,
"scaling": scaling, "in_service": in_service, "name": name, "type": type}
_add_series_to_entries(entries, index, "min_p_mw", min_p_mw)
_add_series_to_entries(entries, index, "max_p_mw", max_p_mw)
_add_series_to_entries(entries, index, "min_q_mvar", min_q_mvar)
_add_series_to_entries(entries, index, "max_q_mvar", max_q_mvar)
_add_series_to_entries(entries, index, "controllable", controllable, dtyp=bool_,
default_val=False)
_set_multiple_entries(net, "load", index, **entries, **kwargs)
return index
def create_asymmetric_load(net, bus, p_a_mw=0, p_b_mw=0, p_c_mw=0, q_a_mvar=0, q_b_mvar=0,
q_c_mvar=0, sn_mva=nan, name=None, scaling=1., index=None,
in_service=True, type="wye"):
_check_node_element(net, bus)
index = _get_index_with_check(net, "asymmetric_load", index, name="3 phase asymmetric_load")
entries = dict(zip(["name", "bus", "p_a_mw", "p_b_mw", "p_c_mw", "scaling", "q_a_mvar",
"q_b_mvar", "q_c_mvar", "sn_mva", "in_service", "type"],
[name, bus, p_a_mw, p_b_mw, p_c_mw, scaling, q_a_mvar, q_b_mvar, q_c_mvar,
sn_mva, bool(in_service), type]))
_set_entries(net, "asymmetric_load", index, True, **entries)
return index
# Creates a constant impedance load element ABC.
#
# INPUT:
# **net** - The net within this constant impedance load should be created
#
# **bus** (int) - The bus id to which the load is connected
#
# **sn_mva** (float) - rated power of the load
#
# **r_A** (float) - Resistance in Phase A
# **r_B** (float) - Resistance in Phase B
# **r_C** (float) - Resistance in Phase C
# **x_A** (float) - Reactance in Phase A
# **x_B** (float) - Reactance in Phase B
# **x_C** (float) - Reactance in Phase C
#
#
# **kwargs are passed on to the create_load function
#
# OUTPUT:
# **index** (int) - The unique ID of the created load
#
# Load elements are modeled from a consumer point of view. Active power will therefore always be
# positive, reactive power will be positive for under-excited behavior (Q absorption, decreases voltage) and negative for over-excited behavior (Q injection, increases voltage)
# """
m_cosphi(net, bus, sn_mva, cos_phi, mode, **kwargs):
from pandapower.toolbox import pq_from_cosphi
p_mw, q_mvar = pq_from_cosphi(sn_mva, cos_phi, qmode=mode, pmode="load")
return create_load(net, bus, sn_mva=sn_mva, p_mw=p_mw, q_mvar=q_mvar, **kwargs)
def create_sgen(net, bus, p_mw, q_mvar=0, sn_mva=nan, name=None, index=None,
scaling=1., type='wye', in_service=True, max_p_mw=nan, min_p_mw=nan,
max_q_mvar=nan, min_q_mvar=nan, controllable=nan, k=nan, rx=nan,
current_source=True):
_check_node_element(net, bus)
index = _get_index_with_check(net, "sgen", index, name="static generator")
entries = dict(zip(["name", "bus", "p_mw", "scaling", "q_mvar", "sn_mva", "in_service", "type",
"current_source"], [name, bus, p_mw, scaling, q_mvar, sn_mva,
bool(in_service), type, current_source]))
_set_entries(net, "sgen", index, True, **entries)
_create_column_and_set_value(net, index, min_p_mw, "min_p_mw", "sgen")
_create_column_and_set_value(net, index, max_p_mw, "max_p_mw", "sgen")
_create_column_and_set_value(net, index, min_q_mvar, "min_q_mvar", "sgen")
_create_column_and_set_value(net, index, max_q_mvar, "max_q_mvar", "sgen")
_create_column_and_set_value(net, index, k, "k", "sgen")
_create_column_and_set_value(net, index, rx, "rx", "sgen")
_create_column_and_set_value(net, index, controllable, "controllable", "sgen", dtyp=bool_,
default_val=False, default_for_nan=True)
return index
def create_sgens(net, buses, p_mw, q_mvar=0, sn_mva=nan, name=None, index=None,
scaling=1., type='wye', in_service=True, max_p_mw=None, min_p_mw=None,
max_q_mvar=None, min_q_mvar=None, controllable=None, k=None, rx=None,
current_source=True, **kwargs):
_check_multiple_node_elements(net, buses)
index = _get_multiple_index_with_check(net, "sgen", index, len(buses))
entries = {"bus": buses, "p_mw": p_mw, "q_mvar": q_mvar, "sn_mva": sn_mva, "scaling": scaling,
"in_service": in_service, "name": name, "type": type,
'current_source': current_source}
_add_series_to_entries(entries, index, "min_p_mw", min_p_mw)
_add_series_to_entries(entries, index, "max_p_mw", max_p_mw)
_add_series_to_entries(entries, index, "min_q_mvar", min_q_mvar)
_add_series_to_entries(entries, index, "max_q_mvar", max_q_mvar)
_add_series_to_entries(entries, index, "k", k)
_add_series_to_entries(entries, index, "rx", rx)
_add_series_to_entries(entries, index, "controllable", controllable, dtyp=bool_,
default_val=False)
_set_multiple_entries(net, "sgen", index, **entries, **kwargs)
return index
def create_asymmetric_sgen(net, bus, p_a_mw=0, p_b_mw=0, p_c_mw=0, q_a_mvar=0, q_b_mvar=0,
q_c_mvar=0, sn_mva=nan,
name=None, index=None, scaling=1., type='wye', in_service=True):
_check_node_element(net, bus)
index = _get_index_with_check(net, "asymmetric_sgen", index,
name="3 phase asymmetric static generator")
entries = dict(zip(["name", "bus", "p_a_mw", "p_b_mw", "p_c_mw", "scaling", "q_a_mvar",
"q_b_mvar", "q_c_mvar", "sn_mva", "in_service", "type"],
[name, bus, p_a_mw, p_b_mw, p_c_mw, scaling, q_a_mvar, q_b_mvar, q_c_mvar,
sn_mva, bool(in_service), type]))
_set_entries(net, "asymmetric_sgen", index, True, **entries)
return index
def create_sgen_from_cosphi(net, bus, sn_mva, cos_phi, mode, **kwargs):
from pandapower.toolbox import pq_from_cosphi
p_mw, q_mvar = pq_from_cosphi(sn_mva, cos_phi, qmode=mode, pmode="gen")
return create_sgen(net, bus, sn_mva=sn_mva, p_mw=p_mw, q_mvar=q_mvar, **kwargs)
def create_storage(net, bus, p_mw, max_e_mwh, q_mvar=0, sn_mva=nan, soc_percent=nan, min_e_mwh=0.0,
name=None, index=None, scaling=1., type=None, in_service=True, max_p_mw=nan,
min_p_mw=nan, max_q_mvar=nan, min_q_mvar=nan, controllable=nan):
_check_node_element(net, bus)
index = _get_index_with_check(net, "storage", index)
entries = dict(zip(["name", "bus", "p_mw", "q_mvar", "sn_mva", "scaling", "soc_percent",
"min_e_mwh", "max_e_mwh", "in_service", "type"],
[name, bus, p_mw, q_mvar, sn_mva, scaling, soc_percent, min_e_mwh, max_e_mwh,
bool(in_service), type]))
_set_entries(net, "storage", index, True, **entries)
_create_column_and_set_value(net, index, min_p_mw, "min_p_mw", "storage")
_create_column_and_set_value(net, index, max_p_mw, "max_p_mw", "storage")
_create_column_and_set_value(net, index, min_q_mvar, "min_q_mvar", "storage")
_create_column_and_set_value(net, index, max_q_mvar, "max_q_mvar", "storage")
_create_column_and_set_value(net, index, controllable, "controllable", "storage",
dtyp=bool_, default_val=False, default_for_nan=True)
return index
def create_gen(net, bus, p_mw, vm_pu=1., sn_mva=nan, name=None, index=None, max_q_mvar=nan,
min_q_mvar=nan, min_p_mw=nan, max_p_mw=nan, min_vm_pu=nan, max_vm_pu=nan,
scaling=1., type=None, slack=False, controllable=nan, vn_kv=nan,
xdss_pu=nan, rdss_ohm=nan, cos_phi=nan, pg_percent=nan, power_station_trafo=None,
in_service=True, slack_weight=0.0):
_check_node_element(net, bus)
index = _get_index_with_check(net, "gen", index, name="generator")
columns = ["name", "bus", "p_mw", "vm_pu", "sn_mva", "type", "slack", "in_service",
"scaling", "slack_weight"]
variables = [name, bus, p_mw, vm_pu, sn_mva, type, slack, bool(in_service), scaling,
slack_weight]
_set_entries(net, "gen", index, True, **dict(zip(columns, variables)))
if not isnan(controllable):
if "controllable" not in net.gen.columns:
net.gen.loc[:, "controllable"] = pd.Series(dtype=bool, data=True)
net.gen.at[index, "controllable"] = bool(controllable)
elif "controllable" in net.gen.columns:
net.gen.at[index, "controllable"] = True
_create_column_and_set_value(net, index, min_p_mw, "min_p_mw", "gen")
_create_column_and_set_value(net, index, max_p_mw, "max_p_mw", "gen")
_create_column_and_set_value(net, index, min_q_mvar, "min_q_mvar", "gen")
_create_column_and_set_value(net, index, max_q_mvar, "max_q_mvar", "gen")
_create_column_and_set_value(net, index, max_vm_pu, "max_vm_pu", "gen", default_val=2.)
_create_column_and_set_value(net, index, min_vm_pu, "min_vm_pu", "gen", default_val=0.)
_create_column_and_set_value(net, index, vn_kv, "vn_kv", "gen")
_create_column_and_set_value(net, index, cos_phi, "cos_phi", "gen")
_create_column_and_set_value(net, index, xdss_pu, "xdss_pu", "gen")
_create_column_and_set_value(net, index, rdss_ohm, "rdss_ohm", "gen")
_create_column_and_set_value(net, index, pg_percent, "pg_percent", "gen")
_create_column_and_set_value(net, index, power_station_trafo,
"power_station_trafo", "gen")
return index
def create_gens(net, buses, p_mw, vm_pu=1., sn_mva=nan, name=None, index=None, max_q_mvar=None,
min_q_mvar=None, min_p_mw=None, max_p_mw=None, min_vm_pu=None, max_vm_pu=None,
scaling=1., type=None, slack=False, controllable=None, vn_kv=None,
xdss_pu=None, rdss_ohm=None, cos_phi=None, pg_percent=None, power_station_trafo=None,
in_service=True, slack_weight=0.0, **kwargs):
_check_multiple_node_elements(net, buses)
index = _get_multiple_index_with_check(net, "gen", index, len(buses))
entries = {"bus": buses, "p_mw": p_mw, "vm_pu": vm_pu, "sn_mva": sn_mva, "scaling": scaling,
"in_service": in_service, "slack_weight": slack_weight, "name": name, "type": type, "slack": slack}
_add_series_to_entries(entries, index, "min_p_mw", min_p_mw)
_add_series_to_entries(entries, index, "max_p_mw", max_p_mw)
_add_series_to_entries(entries, index, "min_q_mvar", min_q_mvar)
_add_series_to_entries(entries, index, "max_q_mvar", max_q_mvar)
_add_series_to_entries(entries, index, "min_vm_pu", min_vm_pu)
_add_series_to_entries(entries, index, "max_vm_pu", max_vm_pu)
_add_series_to_entries(entries, index, "vn_kv", vn_kv)
_add_series_to_entries(entries, index, "cos_phi", cos_phi)
_add_series_to_entries(entries, index, "xdss_pu", xdss_pu)
_add_series_to_entries(entries, index, "rdss_ohm", rdss_ohm)
_add_series_to_entries(entries, index, "pg_percent", pg_percent)
_add_series_to_entries(entries, index, "power_station_trafo", power_station_trafo)
_add_series_to_entries(entries, index, "controllable", controllable, dtyp=bool_,
default_val=False)
_set_multiple_entries(net, "gen", index, **entries, **kwargs)
return index
def create_motor(net, bus, pn_mech_mw, cos_phi, efficiency_percent=100., loading_percent=100.,
name=None, lrc_pu=nan, scaling=1.0, vn_kv=nan, rx=nan, index=None, in_service=True,
cos_phi_n=nan, efficiency_n_percent=nan):
_check_node_element(net, bus)
index = _get_index_with_check(net, "motor", index)
columns = ["name", "bus", "pn_mech_mw", "cos_phi", "cos_phi_n", "vn_kv", "rx",
"efficiency_n_percent", "efficiency_percent", "loading_percent",
"lrc_pu", "scaling", "in_service"]
variables = [name, bus, pn_mech_mw, cos_phi, cos_phi_n, vn_kv, rx, efficiency_n_percent,
efficiency_percent, loading_percent, lrc_pu, scaling, bool(in_service)]
_set_entries(net, "motor", index, **dict(zip(columns, variables)))
return index
def create_ext_grid(net, bus, vm_pu=1.0, va_degree=0., name=None, in_service=True,
s_sc_max_mva=nan, s_sc_min_mva=nan, rx_max=nan, rx_min=nan,
max_p_mw=nan, min_p_mw=nan, max_q_mvar=nan, min_q_mvar=nan,
index=None, r0x0_max=nan, x0x_max=nan, controllable=nan,
slack_weight=1.0, **kwargs):
_check_node_element(net, bus)
index = _get_index_with_check(net, "ext_grid", index, name="external grid")
entries = dict(zip(["bus", "name", "vm_pu", "va_degree", "in_service", "slack_weight"],
[bus, name, vm_pu, va_degree, bool(in_service), slack_weight]))
_set_entries(net, "ext_grid", index, **entries, **kwargs)
_create_column_and_set_value(net, index, s_sc_max_mva, "s_sc_max_mva", "ext_grid")
_create_column_and_set_value(net, index, s_sc_min_mva, "s_sc_min_mva", "ext_grid")
_create_column_and_set_value(net, index, rx_min, "rx_min", "ext_grid")
_create_column_and_set_value(net, index, rx_max, "rx_max", "ext_grid")
_create_column_and_set_value(net, index, min_p_mw, "min_p_mw", "ext_grid")
_create_column_and_set_value(net, index, max_p_mw, "max_p_mw", "ext_grid")
_create_column_and_set_value(net, index, min_q_mvar, "min_q_mvar", "ext_grid")
_create_column_and_set_value(net, index, max_q_mvar, "max_q_mvar", "ext_grid")
_create_column_and_set_value(net, index, x0x_max, "x0x_max", "ext_grid")
_create_column_and_set_value(net, index, r0x0_max, "r0x0_max", "ext_grid")
_create_column_and_set_value(net, index, controllable, "controllable", "ext_grid",
dtyp=bool_, default_val=False, default_for_nan=True)
return index
def create_line(net, from_bus, to_bus, length_km, std_type, name=None, index=None, geodata=None,
df=1., parallel=1, in_service=True, max_loading_percent=nan, alpha=nan,
temperature_degree_celsius=nan):
_check_branch_element(net, "Line", index, from_bus, to_bus)
index = _get_index_with_check(net, "line", index)
v = {
"name": name, "length_km": length_km, "from_bus": from_bus,
"to_bus": to_bus, "in_service": bool(in_service), "std_type": std_type,
"df": df, "parallel": parallel
}
lineparam = load_std_type(net, std_type, "line")
v.update({param: lineparam[param] for param in ["r_ohm_per_km", "x_ohm_per_km", "c_nf_per_km",
"max_i_ka"]})
if "r0_ohm_per_km" in lineparam:
v.update({param: lineparam[param] for param in ["r0_ohm_per_km", "x0_ohm_per_km", "c0_nf_per_km"]})
v["g_us_per_km"] = lineparam["g_us_per_km"] if "g_us_per_km" in lineparam else 0.
if "type" in lineparam:
v["type"] = lineparam["type"]
if "alpha" in net.line.columns and "alpha" in lineparam:
v["alpha"] = lineparam["alpha"]
_set_entries(net, "line", index, **v)
if geodata is not None:
net["line_geodata"].loc[index, "coords"] = None
net["line_geodata"].at[index, "coords"] = geodata
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "line")
_create_column_and_set_value(net, index, alpha, "alpha", "line")
_create_column_and_set_value(net, index, temperature_degree_celsius,
"temperature_degree_celsius", "line")
return index
def create_lines(net, from_buses, to_buses, length_km, std_type, name=None, index=None,
geodata=None, df=1., parallel=1, in_service=True, max_loading_percent=None):
_check_multiple_branch_elements(net, from_buses, to_buses, "Lines")
index = _get_multiple_index_with_check(net, "line", index, len(from_buses))
entries = {"from_bus": from_buses, "to_bus": to_buses, "length_km": length_km,
"std_type": std_type, "name": name, "df": df, "parallel": parallel,
"in_service": in_service}
if isinstance(std_type, str):
lineparam = load_std_type(net, std_type, "line")
entries["r_ohm_per_km"] = lineparam["r_ohm_per_km"]
entries["x_ohm_per_km"] = lineparam["x_ohm_per_km"]
entries["c_nf_per_km"] = lineparam["c_nf_per_km"]
entries["max_i_ka"] = lineparam["max_i_ka"]
entries["g_us_per_km"] = lineparam["g_us_per_km"] if "g_us_per_km" in lineparam else 0.
if "type" in lineparam:
entries["type"] = lineparam["type"]
else:
lineparam = list(map(load_std_type, [net] * len(std_type), std_type, ['line'] * len(std_type)))
entries["r_ohm_per_km"] = list(map(itemgetter("r_ohm_per_km"), lineparam))
entries["x_ohm_per_km"] = list(map(itemgetter("x_ohm_per_km"), lineparam))
entries["c_nf_per_km"] = list(map(itemgetter("c_nf_per_km"), lineparam))
entries["max_i_ka"] = list(map(itemgetter("max_i_ka"), lineparam))
entries["g_us_per_km"] = list(map(check_entry_in_std_type, lineparam, ["g_us_per_km"] * len(lineparam),
[0.] * len(lineparam)))
entries["type"] = list(map(check_entry_in_std_type, lineparam, ["type"] * len(lineparam),
[None] * len(lineparam)))
_add_series_to_entries(entries, index, "max_loading_percent", max_loading_percent)
_set_multiple_entries(net, "line", index, **entries)
if geodata is not None:
_add_multiple_branch_geodata(net, "line", geodata, index)
return index
def create_line_from_parameters(net, from_bus, to_bus, length_km, r_ohm_per_km, x_ohm_per_km,
c_nf_per_km, max_i_ka, name=None, index=None, type=None,
geodata=None, in_service=True, df=1., parallel=1, g_us_per_km=0.,
max_loading_percent=nan, alpha=nan,
temperature_degree_celsius=nan, r0_ohm_per_km=nan,
x0_ohm_per_km=nan, c0_nf_per_km=nan, g0_us_per_km=0,
endtemp_degree=nan, **kwargs):
_check_branch_element(net, "Line", index, from_bus, to_bus)
index = _get_index_with_check(net, "line", index)
v = {
"name": name, "length_km": length_km, "from_bus": from_bus,
"to_bus": to_bus, "in_service": bool(in_service), "std_type": None,
"df": df, "r_ohm_per_km": r_ohm_per_km, "x_ohm_per_km": x_ohm_per_km,
"c_nf_per_km": c_nf_per_km, "max_i_ka": max_i_ka, "parallel": parallel, "type": type,
"g_us_per_km": g_us_per_km
}
_set_entries(net, "line", index, **v, **kwargs)
nan_0_values = [isnan(r0_ohm_per_km), isnan(x0_ohm_per_km), isnan(c0_nf_per_km)]
if not np_any(nan_0_values):
_create_column_and_set_value(net, index, r0_ohm_per_km, "r0_ohm_per_km", "line")
_create_column_and_set_value(net, index, x0_ohm_per_km, "x0_ohm_per_km", "line")
_create_column_and_set_value(net, index, c0_nf_per_km, "c0_nf_per_km", "line")
_create_column_and_set_value(net, index, g0_us_per_km, "g0_us_per_km", "line",
default_val=0.)
elif not np_all(nan_0_values):
logger.warning("Zero sequence values are given for only some parameters. Please specify "
"them for all parameters, otherwise they are not set!")
if geodata is not None:
net["line_geodata"].loc[index, "coords"] = None
net["line_geodata"].at[index, "coords"] = geodata
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "line")
_create_column_and_set_value(net, index, alpha, "alpha", "line")
_create_column_and_set_value(net, index, temperature_degree_celsius,
"temperature_degree_celsius", "line")
_create_column_and_set_value(net, index, endtemp_degree, "endtemp_degree", "line")
return index
def create_lines_from_parameters(net, from_buses, to_buses, length_km, r_ohm_per_km, x_ohm_per_km,
c_nf_per_km, max_i_ka, name=None, index=None, type=None,
geodata=None, in_service=True, df=1., parallel=1, g_us_per_km=0.,
max_loading_percent=None, alpha=None,
temperature_degree_celsius=None, r0_ohm_per_km=None,
x0_ohm_per_km=None, c0_nf_per_km=None, g0_us_per_km=None,
**kwargs):
_check_multiple_branch_elements(net, from_buses, to_buses, "Lines")
index = _get_multiple_index_with_check(net, "line", index, len(from_buses))
entries = {"from_bus": from_buses, "to_bus": to_buses, "length_km": length_km, "type": type,
"r_ohm_per_km": r_ohm_per_km, "x_ohm_per_km": x_ohm_per_km,
"c_nf_per_km": c_nf_per_km, "max_i_ka": max_i_ka, "g_us_per_km": g_us_per_km,
"name": name, "df": df, "parallel": parallel, "in_service": in_service}
_add_series_to_entries(entries, index, "max_loading_percent", max_loading_percent)
_add_series_to_entries(entries, index, "r0_ohm_per_km", r0_ohm_per_km)
_add_series_to_entries(entries, index, "x0_ohm_per_km", x0_ohm_per_km)
_add_series_to_entries(entries, index, "c0_nf_per_km", c0_nf_per_km)
_add_series_to_entries(entries, index, "g0_us_per_km", g0_us_per_km)
_add_series_to_entries(entries, index, "temperature_degree_celsius", temperature_degree_celsius)
_add_series_to_entries(entries, index, "alpha", alpha)
_set_multiple_entries(net, "line", index, **entries, **kwargs)
if geodata is not None:
_add_multiple_branch_geodata(net, "line", geodata, index)
return index
def create_transformer(net, hv_bus, lv_bus, std_type, name=None, tap_pos=nan, in_service=True,
index=None, max_loading_percent=nan, parallel=1, df=1.,
tap_dependent_impedance=None, vk_percent_characteristic=None,
vkr_percent_characteristic=None):
_check_branch_element(net, "Trafo", index, hv_bus, lv_bus)
index = _get_index_with_check(net, "trafo", index, name="transformer")
if df <= 0:
raise UserWarning("derating factor df must be positive: df = %.3f" % df)
v = {
"name": name, "hv_bus": hv_bus, "lv_bus": lv_bus,
"in_service": bool(in_service), "std_type": std_type
}
ti = load_std_type(net, std_type, "trafo")
updates = {
"sn_mva": ti["sn_mva"],
"vn_hv_kv": ti["vn_hv_kv"],
"vn_lv_kv": ti["vn_lv_kv"],
"vk_percent": ti["vk_percent"],
"vkr_percent": ti["vkr_percent"],
"pfe_kw": ti["pfe_kw"],
"i0_percent": ti["i0_percent"],
"parallel": parallel,
"df": df,
"shift_degree": ti["shift_degree"] if "shift_degree" in ti else 0,
"tap_phase_shifter": ti["tap_phase_shifter"] if "tap_phase_shifter" in ti
and pd.notnull(
ti["tap_phase_shifter"]) else False
}
for zero_param in ['vk0_percent', 'vkr0_percent', 'mag0_percent', 'mag0_rx', 'si0_hv_partial']:
if zero_param in ti:
updates[zero_param] = ti[zero_param]
v.update(updates)
for tp in ("tap_neutral", "tap_max", "tap_min", "tap_side", "tap_step_percent",
"tap_step_degree"):
if tp in ti:
v[tp] = ti[tp]
if ("tap_neutral" in v) and (tap_pos is nan):
v["tap_pos"] = v["tap_neutral"]
else:
v["tap_pos"] = tap_pos
if isinstance(tap_pos, float):
net.trafo.tap_pos = net.trafo.tap_pos.astype(float)
_set_entries(net, "trafo", index, **v)
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "trafo")
if tap_dependent_impedance is not None:
_create_column_and_set_value(net, index, tap_dependent_impedance, "tap_dependent_impedance", "trafo", bool_, False, True)
if vk_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_percent_characteristic, "vk_percent_characteristic", "trafo", "Int64")
if vkr_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_percent_characteristic, "vkr_percent_characteristic", "trafo", "Int64")
net.trafo.tap_phase_shifter.fillna(False, inplace=True)
return index
def create_transformer_from_parameters(net, hv_bus, lv_bus, sn_mva, vn_hv_kv, vn_lv_kv,
vkr_percent, vk_percent, pfe_kw, i0_percent,
shift_degree=0,
tap_side=None, tap_neutral=nan, tap_max=nan,
tap_min=nan, tap_step_percent=nan, tap_step_degree=nan,
tap_pos=nan, tap_phase_shifter=False, in_service=True,
name=None, vector_group=None, index=None,
max_loading_percent=nan, parallel=1,
df=1., vk0_percent=nan, vkr0_percent=nan,
mag0_percent=nan, mag0_rx=nan,
si0_hv_partial=nan,
pt_percent=nan, oltc=False, tap_dependent_impedance=None,
vk_percent_characteristic=None,
vkr_percent_characteristic=None, **kwargs):
_check_branch_element(net, "Trafo", index, hv_bus, lv_bus)
index = _get_index_with_check(net, "trafo", index, name="transformer")
if df <= 0:
raise UserWarning("derating factor df must be positive: df = %.3f" % df)
if tap_pos is nan:
tap_pos = tap_neutral
v = {
"name": name, "hv_bus": hv_bus, "lv_bus": lv_bus,
"in_service": bool(in_service), "std_type": None, "sn_mva": sn_mva, "vn_hv_kv": vn_hv_kv,
"vn_lv_kv": vn_lv_kv, "vk_percent": vk_percent, "vkr_percent": vkr_percent,
"pfe_kw": pfe_kw, "i0_percent": i0_percent, "tap_neutral": tap_neutral,
"tap_max": tap_max, "tap_min": tap_min, "shift_degree": shift_degree,
"tap_side": tap_side, "tap_step_percent": tap_step_percent, "tap_step_degree": tap_step_degree,
"tap_phase_shifter": tap_phase_shifter, "parallel": parallel, "df": df,
"pt_percent": pt_percent, "oltc": oltc
}
if ("tap_neutral" in v) and (tap_pos is nan):
v["tap_pos"] = v["tap_neutral"]
else:
v["tap_pos"] = tap_pos
if type(tap_pos) == float:
net.trafo.tap_pos = net.trafo.tap_pos.astype(float)
_set_entries(net, "trafo", index, **v, **kwargs)
if tap_dependent_impedance is not None:
_create_column_and_set_value(net, index, tap_dependent_impedance, "tap_dependent_impedance", "trafo", bool_, False, True)
if vk_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_percent_characteristic, "vk_percent_characteristic", "trafo", "Int64")
if vkr_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_percent_characteristic, "vkr_percent_characteristic", "trafo", "Int64")
if not (isnan(vk0_percent) and isnan(vkr0_percent) and isnan(mag0_percent)
and isnan(mag0_rx) and isnan(si0_hv_partial) and vector_group is None):
_create_column_and_set_value(net, index, vk0_percent, "vk0_percent", "trafo")
_create_column_and_set_value(net, index, vkr0_percent, "vkr0_percent", "trafo")
_create_column_and_set_value(net, index, mag0_percent, "mag0_percent", "trafo")
_create_column_and_set_value(net, index, mag0_rx, "mag0_rx", "trafo")
_create_column_and_set_value(net, index, si0_hv_partial, "si0_hv_partial", "trafo")
_create_column_and_set_value(net, index, vector_group, "vector_group", "trafo", dtyp=str,
default_val=None)
_create_column_and_set_value(net, index, pt_percent, "pt_percent", "trafo")
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "trafo")
return index
def create_transformers_from_parameters(net, hv_buses, lv_buses, sn_mva, vn_hv_kv, vn_lv_kv,
vkr_percent, vk_percent, pfe_kw, i0_percent, shift_degree=0,
tap_side=None, tap_neutral=nan, tap_max=nan, tap_min=nan,
tap_step_percent=nan, tap_step_degree=nan, tap_pos=nan,
tap_phase_shifter=False, in_service=True, name=None,
vector_group=None, index=None, max_loading_percent=None,
parallel=1, df=1., vk0_percent=None, vkr0_percent=None,
mag0_percent=None, mag0_rx=None, si0_hv_partial=None,
pt_percent=nan, oltc=False, tap_dependent_impedance=None,
vk_percent_characteristic=None,
vkr_percent_characteristic=None, **kwargs):
_check_multiple_branch_elements(net, hv_buses, lv_buses, "Transformers")
index = _get_multiple_index_with_check(net, "trafo", index, len(hv_buses))
tp_neutral = pd.Series(tap_neutral, index=index, dtype=float64)
tp_pos = pd.Series(tap_pos, index=index, dtype=float64).fillna(tp_neutral)
entries = {"name": name, "hv_bus": hv_buses, "lv_bus": lv_buses,
"in_service": array(in_service).astype(bool_), "std_type": None, "sn_mva": sn_mva,
"vn_hv_kv": vn_hv_kv, "vn_lv_kv": vn_lv_kv, "vk_percent": vk_percent,
"vkr_percent": vkr_percent, "pfe_kw": pfe_kw, "i0_percent": i0_percent,
"tap_neutral": tp_neutral, "tap_max": tap_max, "tap_min": tap_min,
"shift_degree": shift_degree, "tap_pos": tp_pos, "tap_side": tap_side,
"tap_step_percent": tap_step_percent, "tap_step_degree": tap_step_degree,
"tap_phase_shifter": tap_phase_shifter, "parallel": parallel, "df": df,
"pt_percent": pt_percent, "oltc": oltc}
if tap_dependent_impedance is not None:
_add_series_to_entries(entries, index, "tap_dependent_impedance", tap_dependent_impedance, dtype=bool_, default_val=False)
if vk_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vk_percent_characteristic", vk_percent_characteristic, "Int64")
if vkr_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vkr_percent_characteristic", vkr_percent_characteristic, "Int64")
_add_series_to_entries(entries, index, "vk0_percent", vk0_percent)
_add_series_to_entries(entries, index, "vkr0_percent", vkr0_percent)
_add_series_to_entries(entries, index, "mag0_percent", mag0_percent)
_add_series_to_entries(entries, index, "mag0_rx", mag0_rx)
_add_series_to_entries(entries, index, "si0_hv_partial", si0_hv_partial)
_add_series_to_entries(entries, index, "max_loading_percent", max_loading_percent)
_add_series_to_entries(entries, index, "vector_group", vector_group, dtyp=str)
_add_series_to_entries(entries, index, "pt_percent", pt_percent)
_set_multiple_entries(net, "trafo", index, **entries, **kwargs)
return index
def create_transformer3w(net, hv_bus, mv_bus, lv_bus, std_type, name=None, tap_pos=nan,
in_service=True, index=None, max_loading_percent=nan,
tap_at_star_point=False, tap_dependent_impedance=None,
vk_hv_percent_characteristic=None, vkr_hv_percent_characteristic=None,
vk_mv_percent_characteristic=None, vkr_mv_percent_characteristic=None,
vk_lv_percent_characteristic=None, vkr_lv_percent_characteristic=None):
for b in [hv_bus, mv_bus, lv_bus]:
if b not in net["bus"].index.values:
raise UserWarning("Trafo tries to attach to bus %s" % b)
v = {
"name": name, "hv_bus": hv_bus, "mv_bus": mv_bus, "lv_bus": lv_bus,
"in_service": bool(in_service), "std_type": std_type
}
ti = load_std_type(net, std_type, "trafo3w")
index = _get_index_with_check(net, "trafo3w", index, "three winding transformer")
v.update({
"sn_hv_mva": ti["sn_hv_mva"],
"sn_mv_mva": ti["sn_mv_mva"],
"sn_lv_mva": ti["sn_lv_mva"],
"vn_hv_kv": ti["vn_hv_kv"],
"vn_mv_kv": ti["vn_mv_kv"],
"vn_lv_kv": ti["vn_lv_kv"],
"vk_hv_percent": ti["vk_hv_percent"],
"vk_mv_percent": ti["vk_mv_percent"],
"vk_lv_percent": ti["vk_lv_percent"],
"vkr_hv_percent": ti["vkr_hv_percent"],
"vkr_mv_percent": ti["vkr_mv_percent"],
"vkr_lv_percent": ti["vkr_lv_percent"],
"pfe_kw": ti["pfe_kw"],
"i0_percent": ti["i0_percent"],
"shift_mv_degree": ti["shift_mv_degree"] if "shift_mv_degree" in ti else 0,
"shift_lv_degree": ti["shift_lv_degree"] if "shift_lv_degree" in ti else 0,
"tap_at_star_point": tap_at_star_point
})
for tp in (
"tap_neutral", "tap_max", "tap_min", "tap_side", "tap_step_percent", "tap_step_degree"):
if tp in ti:
v.update({tp: ti[tp]})
if ("tap_neutral" in v) and (tap_pos is nan):
v["tap_pos"] = v["tap_neutral"]
else:
v["tap_pos"] = tap_pos
if type(tap_pos) == float:
net.trafo3w.tap_pos = net.trafo3w.tap_pos.astype(float)
dd = pd.DataFrame(v, index=[index])
if version.parse(pd.__version__) < version.parse("0.21"):
net["trafo3w"] = net["trafo3w"].append(dd).reindex_axis(net["trafo3w"].columns, axis=1)
elif version.parse(pd.__version__) < version.parse("0.23"):
net["trafo3w"] = net["trafo3w"].append(dd).reindex(net["trafo3w"].columns, axis=1)
else:
net["trafo3w"] = net["trafo3w"].append(dd, sort=True).reindex(net["trafo3w"].columns,
axis=1)
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "trafo3w")
if tap_dependent_impedance is not None:
_create_column_and_set_value(net, index, tap_dependent_impedance, "tap_dependent_impedance", "trafo", bool_, False, True)
if vk_hv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_hv_percent_characteristic, "vk_hv_percent_characteristic", "trafo", "Int64")
if vkr_hv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_hv_percent_characteristic, "vkr_hv_percent_characteristic", "trafo", "Int64")
if vk_mv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_mv_percent_characteristic, "vk_mv_percent_characteristic", "trafo", "Int64")
if vkr_mv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_mv_percent_characteristic, "vkr_mv_percent_characteristic", "trafo", "Int64")
if vk_lv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_lv_percent_characteristic, "vk_lv_percent_characteristic", "trafo", "Int64")
if vkr_lv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_lv_percent_characteristic, "vkr_lv_percent_characteristic", "trafo", "Int64")
return index
def create_transformer3w_from_parameters(net, hv_bus, mv_bus, lv_bus, vn_hv_kv, vn_mv_kv, vn_lv_kv,
sn_hv_mva, sn_mv_mva, sn_lv_mva, vk_hv_percent,
vk_mv_percent, vk_lv_percent, vkr_hv_percent,
vkr_mv_percent, vkr_lv_percent, pfe_kw, i0_percent,
shift_mv_degree=0., shift_lv_degree=0., tap_side=None,
tap_step_percent=nan, tap_step_degree=nan, tap_pos=nan,
tap_neutral=nan, tap_max=nan,
tap_min=nan, name=None, in_service=True, index=None,
max_loading_percent=nan, tap_at_star_point=False,
vk0_hv_percent=nan, vk0_mv_percent=nan, vk0_lv_percent=nan,
vkr0_hv_percent=nan, vkr0_mv_percent=nan, vkr0_lv_percent=nan,
vector_group=None, tap_dependent_impedance=None,
vk_hv_percent_characteristic=None, vkr_hv_percent_characteristic=None,
vk_mv_percent_characteristic=None, vkr_mv_percent_characteristic=None,
vk_lv_percent_characteristic=None, vkr_lv_percent_characteristic=None):
for b in [hv_bus, mv_bus, lv_bus]:
if b not in net["bus"].index.values:
raise UserWarning("Trafo tries to attach to non-existent bus %s" % b)
index = _get_index_with_check(net, "trafo3w", index, "three winding transformer")
if tap_pos is nan:
tap_pos = tap_neutral
columns = ["lv_bus", "mv_bus", "hv_bus", "vn_hv_kv", "vn_mv_kv", "vn_lv_kv", "sn_hv_mva",
"sn_mv_mva", "sn_lv_mva", "vk_hv_percent", "vk_mv_percent", "vk_lv_percent",
"vkr_hv_percent", "vkr_mv_percent", "vkr_lv_percent", "pfe_kw", "i0_percent",
"shift_mv_degree", "shift_lv_degree", "tap_side", "tap_step_percent",
"tap_step_degree", "tap_pos", "tap_neutral", "tap_max", "tap_min", "in_service",
"name", "std_type", "tap_at_star_point", "vk0_hv_percent", "vk0_mv_percent", "vk0_lv_percent",
"vkr0_hv_percent", "vkr0_mv_percent", "vkr0_lv_percent", "vector_group"]
values = [lv_bus, mv_bus, hv_bus, vn_hv_kv, vn_mv_kv, vn_lv_kv, sn_hv_mva, sn_mv_mva, sn_lv_mva,
vk_hv_percent, vk_mv_percent, vk_lv_percent, vkr_hv_percent, vkr_mv_percent,
vkr_lv_percent, pfe_kw, i0_percent, shift_mv_degree, shift_lv_degree, tap_side,
tap_step_percent, tap_step_degree, tap_pos, tap_neutral, tap_max, tap_min,
bool(in_service), name, None, tap_at_star_point,
vk0_hv_percent, vk0_mv_percent, vk0_lv_percent,
vkr0_hv_percent, vkr0_mv_percent, vkr0_lv_percent, vector_group]
_set_entries(net, "trafo3w", index, **dict(zip(columns, values)))
_create_column_and_set_value(net, index, max_loading_percent, "max_loading_percent", "trafo3w")
if tap_dependent_impedance is not None:
_create_column_and_set_value(net, index, tap_dependent_impedance, "tap_dependent_impedance", "trafo", bool_, False, True)
if vk_hv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_hv_percent_characteristic, "vk_hv_percent_characteristic", "trafo", "Int64")
if vkr_hv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_hv_percent_characteristic, "vkr_hv_percent_characteristic", "trafo", "Int64")
if vk_mv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_mv_percent_characteristic, "vk_mv_percent_characteristic", "trafo", "Int64")
if vkr_mv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_mv_percent_characteristic, "vkr_mv_percent_characteristic", "trafo", "Int64")
if vk_lv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vk_lv_percent_characteristic, "vk_lv_percent_characteristic", "trafo", "Int64")
if vkr_lv_percent_characteristic is not None:
_create_column_and_set_value(net, index, vkr_lv_percent_characteristic, "vkr_lv_percent_characteristic", "trafo", "Int64")
return index
def create_transformers3w_from_parameters(net, hv_buses, mv_buses, lv_buses, vn_hv_kv, vn_mv_kv,
vn_lv_kv, sn_hv_mva, sn_mv_mva, sn_lv_mva, vk_hv_percent,
vk_mv_percent, vk_lv_percent, vkr_hv_percent,
vkr_mv_percent, vkr_lv_percent, pfe_kw, i0_percent,
shift_mv_degree=0., shift_lv_degree=0., tap_side=None,
tap_step_percent=nan, tap_step_degree=nan, tap_pos=nan,
tap_neutral=nan, tap_max=nan, tap_min=nan, name=None,
in_service=True, index=None, max_loading_percent=None,
tap_at_star_point=False,
vk0_hv_percent=nan, vk0_mv_percent=nan, vk0_lv_percent=nan,
vkr0_hv_percent=nan, vkr0_mv_percent=nan, vkr0_lv_percent=nan,
vector_group=None, tap_dependent_impedance=None,
vk_hv_percent_characteristic=None, vkr_hv_percent_characteristic=None,
vk_mv_percent_characteristic=None, vkr_mv_percent_characteristic=None,
vk_lv_percent_characteristic=None, vkr_lv_percent_characteristic=None, **kwargs):
index = _get_multiple_index_with_check(net, "trafo3w", index, len(hv_buses),
name="Three winding transformers")
if not np_all(isin(hv_buses, net.bus.index)):
bus_not_exist = set(hv_buses) - set(net.bus.index)
raise UserWarning("Transformers trying to attach to non existing buses %s" % bus_not_exist)
if not np_all(isin(mv_buses, net.bus.index)):
bus_not_exist = set(mv_buses) - set(net.bus.index)
raise UserWarning("Transformers trying to attach to non existing buses %s" % bus_not_exist)
if not np_all(isin(lv_buses, net.bus.index)):
bus_not_exist = set(lv_buses) - set(net.bus.index)
raise UserWarning("Transformers trying to attach to non existing buses %s" % bus_not_exist)
tp_neutral = pd.Series(tap_neutral, index=index, dtype=float64)
tp_pos = pd.Series(tap_pos, index=index, dtype=float64).fillna(tp_neutral)
entries = {"lv_bus": lv_buses, "mv_bus": mv_buses, "hv_bus": hv_buses, "vn_hv_kv": vn_hv_kv,
"vn_mv_kv": vn_mv_kv, "vn_lv_kv": vn_lv_kv, "sn_hv_mva": sn_hv_mva,
"sn_mv_mva": sn_mv_mva, "sn_lv_mva": sn_lv_mva, "vk_hv_percent": vk_hv_percent,
"vk_mv_percent": vk_mv_percent, "vk_lv_percent": vk_lv_percent,
"vkr_hv_percent": vkr_hv_percent, "vkr_mv_percent": vkr_mv_percent,
"vkr_lv_percent": vkr_lv_percent, "pfe_kw": pfe_kw, "i0_percent": i0_percent,
"shift_mv_degree": shift_mv_degree, "shift_lv_degree": shift_lv_degree,
"tap_side": tap_side, "tap_step_percent": tap_step_percent,
"tap_step_degree": tap_step_degree, "tap_pos": tp_pos, "tap_neutral": tp_neutral,
"tap_max": tap_max, "tap_min": tap_min,
"in_service": array(in_service).astype(bool_), "name": name,
"tap_at_star_point": array(tap_at_star_point).astype(bool_), "std_type": None,
"vk0_hv_percent": vk0_hv_percent, "vk0_mv_percent": vk0_mv_percent,
"vk0_lv_percent": vk0_lv_percent, "vkr0_hv_percent": vkr0_hv_percent,
"vkr0_mv_percent": vkr0_mv_percent, "vkr0_lv_percent": vkr0_lv_percent,
"vector_group": vector_group}
_add_series_to_entries(entries, index, "max_loading_percent", max_loading_percent)
if tap_dependent_impedance is not None:
_add_series_to_entries(entries, index, "tap_dependent_impedance", tap_dependent_impedance, dtype=bool_, default_val=False)
if vk_hv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vk_hv_percent_characteristic", vk_hv_percent_characteristic, "Int64")
if vkr_hv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vkr_hv_percent_characteristic", vkr_hv_percent_characteristic, "Int64")
if vk_mv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vk_mv_percent_characteristic", vk_mv_percent_characteristic, "Int64")
if vkr_mv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vkr_mv_percent_characteristic", vkr_mv_percent_characteristic, "Int64")
if vk_lv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vk_lv_percent_characteristic", vk_lv_percent_characteristic, "Int64")
if vkr_lv_percent_characteristic is not None:
_add_series_to_entries(entries, index, "vkr_lv_percent_characteristic", vkr_lv_percent_characteristic, "Int64")
_set_multiple_entries(net, "trafo3w", index, **entries, **kwargs)
return index
def create_switch(net, bus, element, et, closed=True, type=None, name=None, index=None, z_ohm=0):
_check_node_element(net, bus)
if et == "l":
elm_tab = 'line'
if element not in net[elm_tab].index:
raise UserWarning("Unknown line index")
if (not net[elm_tab]["from_bus"].loc[element] == bus and
not net[elm_tab]["to_bus"].loc[element] == bus):
raise UserWarning("Line %s not connected to bus %s" % (element, bus))
elif et == "t":
elm_tab = 'trafo'
if element not in net[elm_tab].index:
raise UserWarning("Unknown bus index")
if (not net[elm_tab]["hv_bus"].loc[element] == bus and
not net[elm_tab]["lv_bus"].loc[element] == bus):
raise UserWarning("Trafo %s not connected to bus %s" % (element, bus))
elif et == "t3":
elm_tab = 'trafo3w'
if element not in net[elm_tab].index:
raise UserWarning("Unknown trafo3w index")
if (not net[elm_tab]["hv_bus"].loc[element] == bus and
not net[elm_tab]["mv_bus"].loc[element] == bus and
not net[elm_tab]["lv_bus"].loc[element] == bus):
raise UserWarning("Trafo3w %s not connected to bus %s" % (element, bus))
elif et == "b":
_check_node_element(net, element)
else:
raise UserWarning("Unknown element type")
index = _get_index_with_check(net, "switch", index)
entries = dict(zip(["bus", "element", "et", "closed", "type", "name", "z_ohm"],
[bus, element, et, closed, type, name, z_ohm]))
_set_entries(net, "switch", index, **entries)
return index
def create_switches(net, buses, elements, et, closed=True, type=None, name=None, index=None,
z_ohm=0, **kwargs):
index = _get_multiple_index_with_check(net, "switch", index, len(buses), name="Switches")
_check_multiple_node_elements(net, buses)
for element, elm_type, bus in zip(elements, et, buses):
if elm_type == "l":
elm_tab = 'line'
if element not in net[elm_tab].index:
raise UserWarning("Line %s does not exist" % element)
if (not net[elm_tab]["from_bus"].loc[element] == bus and
not net[elm_tab]["to_bus"].loc[element] == bus):
raise UserWarning("Line %s not connected to bus %s" % (element, bus))
elif elm_type == "t":
elm_tab = 'trafo'
if element not in net[elm_tab].index:
raise UserWarning("Trafo %s does not exist" % element)
if (not net[elm_tab]["hv_bus"].loc[element] == bus and
not net[elm_tab]["lv_bus"].loc[element] == bus):
raise UserWarning("Trafo %s not connected to bus %s" % (element, bus))
elif elm_type == "t3":
elm_tab = 'trafo3w'
if element not in net[elm_tab].index:
raise UserWarning("Trafo3w %s does not exist" % element)
if (not net[elm_tab]["hv_bus"].loc[element] == bus and
not net[elm_tab]["mv_bus"].loc[element] == bus and
not net[elm_tab]["lv_bus"].loc[element] == bus):
raise UserWarning("Trafo3w %s not connected to bus %s" % (element, bus))
elif elm_type == "b":
_check_node_element(net, element)
else:
raise UserWarning("Unknown element type")
entries = {"bus": buses, "element": elements, "et": et, "closed": closed, "type": type,
"name": name, "z_ohm": z_ohm}
_set_multiple_entries(net, "switch", index, **entries, **kwargs)
return index
def create_shunt(net, bus, q_mvar, p_mw=0., vn_kv=None, step=1, max_step=1, name=None,
in_service=True, index=None):
_check_node_element(net, bus)
index = _get_index_with_check(net, "shunt", index)
if vn_kv is None:
vn_kv = net.bus.vn_kv.at[bus]
entries = dict(zip(["bus", "name", "p_mw", "q_mvar", "vn_kv", "step", "max_step", "in_service"],
[bus, name, p_mw, q_mvar, vn_kv, step, max_step, in_service]))
_set_entries(net, "shunt", index, **entries)
return index
def create_shunt_as_capacitor(net, bus, q_mvar, loss_factor, **kwargs):
q_mvar = -abs(q_mvar)
p_mw = abs(q_mvar * loss_factor)
return create_shunt(net, bus, q_mvar=q_mvar, p_mw=p_mw, **kwargs)
def create_impedance(net, from_bus, to_bus, rft_pu, xft_pu, sn_mva, rtf_pu=None, xtf_pu=None,
name=None, in_service=True, index=None):
index = _get_index_with_check(net, "impedance", index)
_check_branch_element(net, "Impedance", index, from_bus, to_bus)
if rtf_pu is None:
rtf_pu = rft_pu
if xtf_pu is None:
xtf_pu = xft_pu
columns = ["from_bus", "to_bus", "rft_pu", "xft_pu", "rtf_pu", "xtf_pu", "name", "sn_mva",
"in_service"]
values = [from_bus, to_bus, rft_pu, xft_pu, rtf_pu, xtf_pu, name, sn_mva, in_service]
_set_entries(net, "impedance", index, **dict(zip(columns, values)))
return index
def create_series_reactor_as_impedance(net, from_bus, to_bus, r_ohm, x_ohm, sn_mva,
name=None, in_service=True, index=None):
if net.bus.at[from_bus, 'vn_kv'] == net.bus.at[to_bus, 'vn_kv']:
vn_kv = net.bus.at[from_bus, 'vn_kv']
else:
raise UserWarning('Unable to infer rated voltage vn_kv for series reactor %s due to '
'different rated voltages of from_bus %d (%.3f p.u.) and '
'to_bus %d (%.3f p.u.)' % (name, from_bus, net.bus.at[from_bus, 'vn_kv'],
to_bus, net.bus.at[to_bus, 'vn_kv']))
base_z_ohm = vn_kv ** 2 / sn_mva
rft_pu = r_ohm / base_z_ohm
xft_pu = x_ohm / base_z_ohm
index = create_impedance(net, from_bus=from_bus, to_bus=to_bus, rft_pu=rft_pu, xft_pu=xft_pu,
sn_mva=sn_mva, name=name, in_service=in_service, index=index)
return index
def create_ward(net, bus, ps_mw, qs_mvar, pz_mw, qz_mvar, name=None, in_service=True, index=None):
_check_node_element(net, bus)
index = _get_index_with_check(net, "ward", index, "ward equivalent")
entries = dict(zip(["bus", "ps_mw", "qs_mvar", "pz_mw", "qz_mvar", "name", "in_service"],
[bus, ps_mw, qs_mvar, pz_mw, qz_mvar, name, in_service]))
_set_entries(net, "ward", index, **entries)
return index
def create_xward(net, bus, ps_mw, qs_mvar, pz_mw, qz_mvar, r_ohm, x_ohm, vm_pu, in_service=True,
name=None, index=None, slack_weight=0.0):
_check_node_element(net, bus)
index = _get_index_with_check(net, "xward", index, "extended ward equivalent")
columns = ["bus", "ps_mw", "qs_mvar", "pz_mw", "qz_mvar", "r_ohm", "x_ohm", "vm_pu", "name",
"slack_weight", "in_service"]
values = [bus, ps_mw, qs_mvar, pz_mw, qz_mvar, r_ohm, x_ohm, vm_pu, name, slack_weight, in_service]
_set_entries(net, "xward", index, **dict(zip(columns, values)))
return index
def create_dcline(net, from_bus, to_bus, p_mw, loss_percent, loss_mw, vm_from_pu, vm_to_pu,
index=None, name=None, max_p_mw=nan, min_q_from_mvar=nan, min_q_to_mvar=nan,
max_q_from_mvar=nan, max_q_to_mvar=nan, in_service=True):
index = _get_index_with_check(net, "dcline", index)
_check_branch_element(net, "DCLine", index, from_bus, to_bus)
columns = ["name", "from_bus", "to_bus", "p_mw", "loss_percent", "loss_mw", "vm_from_pu",
"vm_to_pu", "max_p_mw", "min_q_from_mvar", "min_q_to_mvar", "max_q_from_mvar",
"max_q_to_mvar", "in_service"]
values = [name, from_bus, to_bus, p_mw, loss_percent, loss_mw, vm_from_pu, vm_to_pu, max_p_mw,
min_q_from_mvar, min_q_to_mvar, max_q_from_mvar, max_q_to_mvar, in_service]
_set_entries(net, "dcline", index, **dict(zip(columns, values)))
return index
def create_measurement(net, meas_type, element_type, value, std_dev, element, side=None,
check_existing=True, index=None, name=None):
if meas_type not in ("v", "p", "q", "i", "va", "ia"):
raise UserWarning("Invalid measurement type ({})".format(meas_type))
if side is None and element_type in ("line", "trafo"):
raise UserWarning("The element type '{element_type}' requires a value in 'side'")
if meas_type in ("v", "va"):
element_type = "bus"
if element_type not in ("bus", "line", "trafo", "trafo3w"):
raise UserWarning("Invalid element type ({})".format(element_type))
if element is not None and element not in net[element_type].index.values:
raise UserWarning("{} with index={} does not exist".format(element_type.capitalize(),
element))
index = _get_index_with_check(net, "measurement", index)
if meas_type in ("i", "ia") and element_type == "bus":
raise UserWarning("Line current measurements cannot be placed at buses")
if meas_type in ("v", "va") and element_type in ("line", "trafo", "trafo3w"):
raise UserWarning(
"Voltage measurements can only be placed at buses, not at {}".format(element_type))
if check_existing:
if side is None:
existing = net.measurement[(net.measurement.measurement_type == meas_type) &
(net.measurement.element_type == element_type) &
(net.measurement.element == element) &
(pd.isnull(net.measurement.side))].index
else:
existing = net.measurement[(net.measurement.measurement_type == meas_type) &
(net.measurement.element_type == element_type) &
(net.measurement.element == element) &
(net.measurement.side == side)].index
if len(existing) == 1:
index = existing[0]
elif len(existing) > 1:
raise UserWarning("More than one measurement of this type exists")
columns = ["name", "measurement_type", "element_type", "element", "value", "std_dev", "side"]
values = [name, meas_type.lower(), element_type, element, value, std_dev, side]
_set_entries(net, "measurement", index, **dict(zip(columns, values)))
return index
def create_pwl_cost(net, element, et, points, power_type="p", index=None, check=True):
element = element if not hasattr(element, "__iter__") else element[0]
if check and _cost_existance_check(net, element, et, power_type=power_type):
raise UserWarning("There already exist costs for %s %i" % (et, element))
index = _get_index_with_check(net, "pwl_cost", index, "piecewise_linear_cost")
entries = dict(zip(["power_type", "element", "et", "points"],
[power_type, element, et, points]))
_set_entries(net, "pwl_cost", index, **entries)
return index
def create_poly_cost(net, element, et, cp1_eur_per_mw, cp0_eur=0, cq1_eur_per_mvar=0,
cq0_eur=0, cp2_eur_per_mw2=0, cq2_eur_per_mvar2=0, index=None, check=True):
element = element if not hasattr(element, "__iter__") else element[0]
if check and _cost_existance_check(net, element, et):
raise UserWarning("There already exist costs for %s %i" % (et, element))
index = _get_index_with_check(net, "poly_cost", index)
columns = ["element", "et", "cp0_eur", "cp1_eur_per_mw", "cq0_eur", "cq1_eur_per_mvar",
"cp2_eur_per_mw2", "cq2_eur_per_mvar2"]
variables = [element, et, cp0_eur, cp1_eur_per_mw, cq0_eur, cq1_eur_per_mvar,
cp2_eur_per_mw2, cq2_eur_per_mvar2]
_set_entries(net, "poly_cost", index, **dict(zip(columns, variables)))
return index
def _get_index_with_check(net, table, index, name=None):
if name is None:
name = table
if index is None:
index = get_free_id(net[table])
if index in net[table].index:
raise UserWarning("A %s with the id %s already exists" % (name, index))
return index
def _cost_existance_check(net, element, et, power_type=None):
if power_type is None:
return (bool(net.poly_cost.shape[0]) and
np_any((net.poly_cost.element == element).values &
(net.poly_cost.et == et).values)) \
or (bool(net.pwl_cost.shape[0]) and
np_any((net.pwl_cost.element == element).values &
(net.pwl_cost.et == et).values))
else:
return (bool(net.poly_cost.shape[0]) and
np_any((net.poly_cost.element == element).values &
(net.poly_cost.et == et).values)) \
or (bool(net.pwl_cost.shape[0]) and
np_any((net.pwl_cost.element == element).values &
(net.pwl_cost.et == et).values &
(net.pwl_cost.power_type == power_type).values))
def _get_multiple_index_with_check(net, table, index, number, name=None):
if name is None:
name = table.capitalize() + "s"
if index is None:
bid = get_free_id(net[table])
return arange(bid, bid + number, 1)
contained = isin(net[table].index.values, index)
if np_any(contained):
raise UserWarning("%s with indexes %s already exist."
% (name, net[table].index.values[contained]))
return index
def _check_node_element(net, node, node_table="bus"):
if node not in net[node_table].index.values:
raise UserWarning("Cannot attach to %s %s, %s does not exist"
% (node_table, node, node_table))
def _check_multiple_node_elements(net, nodes, node_table="bus", name="buses"):
if np_any(~isin(nodes, net[node_table].index.values)):
node_not_exist = set(nodes) - set(net[node_table].index.values)
raise UserWarning("Cannot attach to %s %s, they do not exist" % (name, node_not_exist))
def _check_branch_element(net, element_name, index, from_node, to_node, node_name="bus",
plural="es"):
missing_nodes = {from_node, to_node} - set(net[node_name].index.values)
if missing_nodes:
raise UserWarning("%s %d tries to attach to non-existing %s(%s) %s"
% (element_name.capitalize(), index, node_name, plural, missing_nodes))
def _check_multiple_branch_elements(net, from_nodes, to_nodes, element_name, node_name="bus",
plural="es"):
all_nodes = array(list(from_nodes) + list(to_nodes))
if np_any(~isin(all_nodes, net[node_name].index.values)):
node_not_exist = set(all_nodes) - set(net[node_name].index)
raise UserWarning("%s trying to attach to non existing %s%s %s"
% (element_name, node_name, plural, node_not_exist))
def _create_column_and_set_value(net, index, variable, column, element, dtyp=float64,
default_val=nan, default_for_nan=False):
# (e.g. "gen") table
# create this column and write the value of variable to the index of this element
try:
set_value = not (isnan(variable) or variable is None)
except TypeError:
set_value = True
if set_value:
if column not in net[element].columns:
# this part is for compatibility with pandas < 1.0, can be removed if pandas >= 1.0 is required in setup.py
if isinstance(default_val, str) \
and version.parse(pd.__version__) < version.parse("1.0"):
net[element].loc[:, column] = pd.Series([default_val] * len(net[element]),
dtype=dtyp)
else:
net[element].loc[:, column] = pd.Series(data=default_val, index=net[element].index, dtype=dtyp)
net[element].at[index, column] = variable
elif default_for_nan and column in net[element].columns:
net[element].at[index, column] = default_val
return net
def _add_series_to_entries(entries, index, column, values, dtyp=float64, default_val=nan):
if values is not None:
try:
fill_default = not isnan(default_val)
except TypeError:
fill_default = True
if isinstance(values, str) and version.parse(pd.__version__) < version.parse("1.0"):
s = pd.Series([values] * len(index), index=index, dtype=dtyp)
else:
s = pd.Series(values, index=index, dtype=dtyp)
if fill_default:
s = s.fillna(default_val)
entries[column] = s
def _add_multiple_branch_geodata(net, table, geodata, index):
geo_table = "%s_geodata" % table
dtypes = net[geo_table].dtypes
df = pd.DataFrame(index=index, columns=net[geo_table].columns)
# works with single or multiple lists of coordinates
if len(geodata[0]) == 2 and not hasattr(geodata[0][0], "__iter__"):
# geodata is a single list of coordinates
df["coords"] = [geodata] * len(index)
else:
# geodata is multiple lists of coordinates
df["coords"] = geodata
# todo: drop version checks
if version.parse(pd.__version__) >= version.parse("0.23"):
net[geo_table] = pd.concat([net[geo_table],df], sort=False)
else:
# prior to pandas 0.23 there was no explicit parameter (instead it was standard behavior)
net[geo_table] = net[geo_table].append(df)
_preserve_dtypes(net[geo_table], dtypes)
def _set_entries(net, table, index, preserve_dtypes=True, **entries):
dtypes = None
if preserve_dtypes:
# only get dtypes of columns that are set and that are already present in the table
dtypes = net[table][intersect1d(net[table].columns, list(entries.keys()))].dtypes
for col, val in entries.items():
net[table].at[index, col] = val
# and preserve dtypes
if preserve_dtypes:
_preserve_dtypes(net[table], dtypes)
def _set_multiple_entries(net, table, index, preserve_dtypes=True, **entries):
dtypes = None
if preserve_dtypes:
# store dtypes
dtypes = net[table].dtypes
def check_entry(val):
if isinstance(val, pd.Series) and not np_all(isin(val.index, index)):
return val.values
elif isinstance(val, set) and len(val) == len(index):
return list(val)
return val
entries = {k: check_entry(v) for k, v in entries.items()}
dd = pd.DataFrame(index=index, columns=net[table].columns)
dd = dd.assign(**entries)
# extend the table by the frame we just created
if version.parse(pd.__version__) >= version.parse("0.23"):
net[table] = pd.concat([net[table],dd], sort=False)
else:
# prior to pandas 0.23 there was no explicit parameter (instead it was standard behavior)
net[table] = net[table].append(dd)
# and preserve dtypes
if preserve_dtypes:
_preserve_dtypes(net[table], dtypes)
| true | true |
f7f6e0bf5f26f32ffb30d75a580e53010f249db8 | 3,973 | py | Python | drfpasswordless/settings.py | git-athul/django-rest-framework-passwordless | 3eef7a56a03be64dc133c180b96700e7b43185e1 | [
"MIT"
] | 1 | 2020-10-11T10:17:54.000Z | 2020-10-11T10:17:54.000Z | drfpasswordless/settings.py | git-athul/django-rest-framework-passwordless | 3eef7a56a03be64dc133c180b96700e7b43185e1 | [
"MIT"
] | null | null | null | drfpasswordless/settings.py | git-athul/django-rest-framework-passwordless | 3eef7a56a03be64dc133c180b96700e7b43185e1 | [
"MIT"
] | null | null | null | from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'PASSWORDLESS_AUTH', None)
DEFAULTS = {
# Allowed auth types, can be EMAIL, MOBILE, or both.
'PASSWORDLESS_AUTH_TYPES': ['EMAIL'],
# URL Prefix for Authentication Endpoints
'PASSWORDLESS_AUTH_PREFIX': 'auth/',
# URL Prefix for Verification Endpoints
'PASSWORDLESS_VERIFY_PREFIX': 'auth/verify/',
# Amount of time that tokens last, in seconds
'PASSWORDLESS_TOKEN_EXPIRE_TIME': 15 * 60,
# The user's email field name
'PASSWORDLESS_USER_EMAIL_FIELD_NAME': 'email',
# The user's mobile field name
'PASSWORDLESS_USER_MOBILE_FIELD_NAME': 'mobile',
# Marks itself as verified the first time a user completes auth via token.
# Automatically unmarks itself if email is changed.
'PASSWORDLESS_USER_MARK_EMAIL_VERIFIED': False,
'PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME': 'email_verified',
# Marks itself as verified the first time a user completes auth via token.
# Automatically unmarks itself if mobile number is changed.
'PASSWORDLESS_USER_MARK_MOBILE_VERIFIED': False,
'PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME': 'mobile_verified',
# The email the callback token is sent from
'PASSWORDLESS_EMAIL_NOREPLY_ADDRESS': None,
# The email subject
'PASSWORDLESS_EMAIL_SUBJECT': "Your Login Token",
# A plaintext email message overridden by the html message. Takes one string.
'PASSWORDLESS_EMAIL_PLAINTEXT_MESSAGE': "Enter this token to sign in: %s",
# The email template name.
'PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE_NAME': "passwordless_default_token_email.html",
# Your twilio number that sends the callback tokens.
'PASSWORDLESS_MOBILE_NOREPLY_NUMBER': None,
# The message sent to mobile users logging in. Takes one string.
'PASSWORDLESS_MOBILE_MESSAGE': "Use this code to log in: %s",
# Registers previously unseen aliases as new users.
'PASSWORDLESS_REGISTER_NEW_USERS': True,
# Suppresses actual SMS for testing
'PASSWORDLESS_TEST_SUPPRESSION': False,
# Context Processors for Email Template
'PASSWORDLESS_CONTEXT_PROCESSORS': [],
# The verification email subject
'PASSWORDLESS_EMAIL_VERIFICATION_SUBJECT': "Your Verification Token",
# A plaintext verification email message overridden by the html message. Takes one string.
'PASSWORDLESS_EMAIL_VERIFICATION_PLAINTEXT_MESSAGE': "Enter this verification code: %s",
# The verification email template name.
'PASSWORDLESS_EMAIL_VERIFICATION_TOKEN_HTML_TEMPLATE_NAME': "passwordless_default_verification_token_email.html",
# The message sent to mobile users logging in. Takes one string.
'PASSWORDLESS_MOBILE_VERIFICATION_MESSAGE': "Enter this verification code: %s",
# Automatically send verification email or sms when a user changes their alias.
'PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN': False,
# What function is called to construct an authentication tokens when
# exchanging a passwordless token for a real user auth token.
'PASSWORDLESS_AUTH_TOKEN_CREATOR': 'drfpasswordless.utils.create_authentication_token',
# What function is called to construct a serializer for drf tokens when
# exchanging a passwordless token for a real user auth token.
'PASSWORDLESS_AUTH_TOKEN_SERIALIZER': 'drfpasswordless.serializers.TokenResponseSerializer',
# A dictionary of demo user's primary key mapped to their static pin
'PASSWORDLESS_DEMO_USERS': {},
'PASSWORDLESS_EMAIL_CALLBACK': 'drfpasswordless.utils.send_email_with_callback_token',
'PASSWORDLESS_SMS_CALLBACK': 'drfpasswordless.utils.send_sms_with_callback_token',
}
# List of settings that may be in string import notation.
IMPORT_STRINGS = (
'PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE',
'PASSWORDLESS_CONTEXT_PROCESSORS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS)
| 39.73 | 117 | 0.766172 | from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'PASSWORDLESS_AUTH', None)
DEFAULTS = {
'PASSWORDLESS_AUTH_TYPES': ['EMAIL'],
'PASSWORDLESS_AUTH_PREFIX': 'auth/',
'PASSWORDLESS_VERIFY_PREFIX': 'auth/verify/',
'PASSWORDLESS_TOKEN_EXPIRE_TIME': 15 * 60,
'PASSWORDLESS_USER_EMAIL_FIELD_NAME': 'email',
# The user's mobile field name
'PASSWORDLESS_USER_MOBILE_FIELD_NAME': 'mobile',
'PASSWORDLESS_USER_MARK_EMAIL_VERIFIED': False,
'PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME': 'email_verified',
'PASSWORDLESS_USER_MARK_MOBILE_VERIFIED': False,
'PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME': 'mobile_verified',
'PASSWORDLESS_EMAIL_NOREPLY_ADDRESS': None,
'PASSWORDLESS_EMAIL_SUBJECT': "Your Login Token",
'PASSWORDLESS_EMAIL_PLAINTEXT_MESSAGE': "Enter this token to sign in: %s",
'PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE_NAME': "passwordless_default_token_email.html",
'PASSWORDLESS_MOBILE_NOREPLY_NUMBER': None,
'PASSWORDLESS_MOBILE_MESSAGE': "Use this code to log in: %s",
'PASSWORDLESS_REGISTER_NEW_USERS': True,
'PASSWORDLESS_TEST_SUPPRESSION': False,
'PASSWORDLESS_CONTEXT_PROCESSORS': [],
'PASSWORDLESS_EMAIL_VERIFICATION_SUBJECT': "Your Verification Token",
'PASSWORDLESS_EMAIL_VERIFICATION_PLAINTEXT_MESSAGE': "Enter this verification code: %s",
'PASSWORDLESS_EMAIL_VERIFICATION_TOKEN_HTML_TEMPLATE_NAME': "passwordless_default_verification_token_email.html",
'PASSWORDLESS_MOBILE_VERIFICATION_MESSAGE': "Enter this verification code: %s",
'PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN': False,
'PASSWORDLESS_AUTH_TOKEN_CREATOR': 'drfpasswordless.utils.create_authentication_token',
'PASSWORDLESS_AUTH_TOKEN_SERIALIZER': 'drfpasswordless.serializers.TokenResponseSerializer',
'PASSWORDLESS_DEMO_USERS': {},
'PASSWORDLESS_EMAIL_CALLBACK': 'drfpasswordless.utils.send_email_with_callback_token',
'PASSWORDLESS_SMS_CALLBACK': 'drfpasswordless.utils.send_sms_with_callback_token',
}
# List of settings that may be in string import notation.
IMPORT_STRINGS = (
'PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE',
'PASSWORDLESS_CONTEXT_PROCESSORS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS)
| true | true |
f7f6e1f1aac678a00617e0693847b4346604a1ab | 5,708 | py | Python | python/paddle/fluid/tests/unittests/test_multiply.py | donproc/Paddle | 23261ff44ba46a507e72e2da7c83f7fede3486f7 | [
"Apache-2.0"
] | 1 | 2020-05-27T05:21:42.000Z | 2020-05-27T05:21:42.000Z | python/paddle/fluid/tests/unittests/test_multiply.py | randytli/Paddle | 75dadd586996c71cf5b088b6141b94705561773f | [
"Apache-2.0"
] | null | null | null | python/paddle/fluid/tests/unittests/test_multiply.py | randytli/Paddle | 75dadd586996c71cf5b088b6141b94705561773f | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2020 PaddlePaddle 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.
from __future__ import print_function
import paddle
import paddle.tensor as tensor
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard
import numpy as np
import unittest
class TestMultiplyAPI(unittest.TestCase):
"""TestMultiplyAPI."""
def __run_static_graph_case(self, x_data, y_data, axis=-1):
with program_guard(Program(), Program()):
x = paddle.nn.data(name='x', shape=x_data.shape, dtype=x_data.dtype)
y = paddle.nn.data(name='y', shape=y_data.shape, dtype=y_data.dtype)
res = tensor.multiply(x, y, axis=axis)
place = fluid.CUDAPlace(0) if fluid.core.is_compiled_with_cuda(
) else fluid.CPUPlace()
exe = fluid.Executor(place)
outs = exe.run(fluid.default_main_program(),
feed={'x': x_data,
'y': y_data},
fetch_list=[res])
res = outs[0]
return res
def __run_dynamic_graph_case(self, x_data, y_data, axis=-1):
paddle.disable_static()
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
res = paddle.multiply(x, y, axis=axis)
return res.numpy()
def test_multiply(self):
"""test_multiply."""
np.random.seed(7)
# test static computation graph: 1-d array
x_data = np.random.rand(200)
y_data = np.random.rand(200)
res = self.__run_static_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
# test static computation graph: 2-d array
x_data = np.random.rand(2, 500)
y_data = np.random.rand(2, 500)
res = self.__run_static_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
# test static computation graph: broadcast
x_data = np.random.rand(2, 500)
y_data = np.random.rand(500)
res = self.__run_static_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
# test static computation graph: broadcast with axis
x_data = np.random.rand(2, 300, 40)
y_data = np.random.rand(300)
res = self.__run_static_graph_case(x_data, y_data, axis=1)
expected = np.multiply(x_data, y_data[..., np.newaxis])
self.assertTrue(np.allclose(res, expected))
# test dynamic computation graph: 1-d array
x_data = np.random.rand(200)
y_data = np.random.rand(200)
res = self.__run_dynamic_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
# test dynamic computation graph: 2-d array
x_data = np.random.rand(20, 50)
y_data = np.random.rand(20, 50)
res = self.__run_dynamic_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
# test dynamic computation graph: broadcast
x_data = np.random.rand(2, 500)
y_data = np.random.rand(500)
res = self.__run_dynamic_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
# test dynamic computation graph: broadcast with axis
x_data = np.random.rand(2, 300, 40)
y_data = np.random.rand(300)
res = self.__run_dynamic_graph_case(x_data, y_data, axis=1)
expected = np.multiply(x_data, y_data[..., np.newaxis])
self.assertTrue(np.allclose(res, expected))
class TestMultiplyError(unittest.TestCase):
"""TestMultiplyError."""
def test_errors(self):
"""test_errors."""
# test static computation graph: dtype can not be int8
paddle.enable_static()
with program_guard(Program(), Program()):
x = paddle.nn.data(name='x', shape=[100], dtype=np.int8)
y = paddle.nn.data(name='y', shape=[100], dtype=np.int8)
self.assertRaises(TypeError, tensor.multiply, x, y)
# test static computation graph: inputs must be broadcastable
with program_guard(Program(), Program()):
x = paddle.nn.data(name='x', shape=[20, 50], dtype=np.float64)
y = paddle.nn.data(name='y', shape=[20], dtype=np.float64)
self.assertRaises(fluid.core.EnforceNotMet, tensor.multiply, x, y)
np.random.seed(7)
# test dynamic computation graph: dtype can not be int8
paddle.disable_static()
x_data = np.random.randn(200).astype(np.int8)
y_data = np.random.randn(200).astype(np.int8)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
self.assertRaises(fluid.core.EnforceNotMet, paddle.multiply, x, y)
# test dynamic computation graph: inputs must be broadcastable
x_data = np.random.rand(200, 5)
y_data = np.random.rand(200)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
self.assertRaises(fluid.core.EnforceNotMet, paddle.multiply, x, y)
if __name__ == '__main__':
unittest.main()
| 40.48227 | 80 | 0.644359 |
from __future__ import print_function
import paddle
import paddle.tensor as tensor
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard
import numpy as np
import unittest
class TestMultiplyAPI(unittest.TestCase):
def __run_static_graph_case(self, x_data, y_data, axis=-1):
with program_guard(Program(), Program()):
x = paddle.nn.data(name='x', shape=x_data.shape, dtype=x_data.dtype)
y = paddle.nn.data(name='y', shape=y_data.shape, dtype=y_data.dtype)
res = tensor.multiply(x, y, axis=axis)
place = fluid.CUDAPlace(0) if fluid.core.is_compiled_with_cuda(
) else fluid.CPUPlace()
exe = fluid.Executor(place)
outs = exe.run(fluid.default_main_program(),
feed={'x': x_data,
'y': y_data},
fetch_list=[res])
res = outs[0]
return res
def __run_dynamic_graph_case(self, x_data, y_data, axis=-1):
paddle.disable_static()
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
res = paddle.multiply(x, y, axis=axis)
return res.numpy()
def test_multiply(self):
np.random.seed(7)
x_data = np.random.rand(200)
y_data = np.random.rand(200)
res = self.__run_static_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
x_data = np.random.rand(2, 500)
y_data = np.random.rand(2, 500)
res = self.__run_static_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
x_data = np.random.rand(2, 500)
y_data = np.random.rand(500)
res = self.__run_static_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
x_data = np.random.rand(2, 300, 40)
y_data = np.random.rand(300)
res = self.__run_static_graph_case(x_data, y_data, axis=1)
expected = np.multiply(x_data, y_data[..., np.newaxis])
self.assertTrue(np.allclose(res, expected))
x_data = np.random.rand(200)
y_data = np.random.rand(200)
res = self.__run_dynamic_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
x_data = np.random.rand(20, 50)
y_data = np.random.rand(20, 50)
res = self.__run_dynamic_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
x_data = np.random.rand(2, 500)
y_data = np.random.rand(500)
res = self.__run_dynamic_graph_case(x_data, y_data)
self.assertTrue(np.allclose(res, np.multiply(x_data, y_data)))
x_data = np.random.rand(2, 300, 40)
y_data = np.random.rand(300)
res = self.__run_dynamic_graph_case(x_data, y_data, axis=1)
expected = np.multiply(x_data, y_data[..., np.newaxis])
self.assertTrue(np.allclose(res, expected))
class TestMultiplyError(unittest.TestCase):
def test_errors(self):
paddle.enable_static()
with program_guard(Program(), Program()):
x = paddle.nn.data(name='x', shape=[100], dtype=np.int8)
y = paddle.nn.data(name='y', shape=[100], dtype=np.int8)
self.assertRaises(TypeError, tensor.multiply, x, y)
with program_guard(Program(), Program()):
x = paddle.nn.data(name='x', shape=[20, 50], dtype=np.float64)
y = paddle.nn.data(name='y', shape=[20], dtype=np.float64)
self.assertRaises(fluid.core.EnforceNotMet, tensor.multiply, x, y)
np.random.seed(7)
paddle.disable_static()
x_data = np.random.randn(200).astype(np.int8)
y_data = np.random.randn(200).astype(np.int8)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
self.assertRaises(fluid.core.EnforceNotMet, paddle.multiply, x, y)
x_data = np.random.rand(200, 5)
y_data = np.random.rand(200)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
self.assertRaises(fluid.core.EnforceNotMet, paddle.multiply, x, y)
if __name__ == '__main__':
unittest.main()
| true | true |
f7f6e328446f45c4f66d5d598ec7961f03289976 | 1,442 | py | Python | v2.5.7/toontown/minigame/RingTrack.py | TTOFFLINE-LEAK/ttoffline | bb0e91704a755d34983e94288d50288e46b68380 | [
"MIT"
] | 4 | 2019-07-01T15:46:43.000Z | 2021-07-23T16:26:48.000Z | v1.0.0.test/toontown/minigame/RingTrack.py | TTOFFLINE-LEAK/ttoffline | bb0e91704a755d34983e94288d50288e46b68380 | [
"MIT"
] | 1 | 2019-06-29T03:40:05.000Z | 2021-06-13T01:15:16.000Z | v1.0.0.test/toontown/minigame/RingTrack.py | TTOFFLINE-LEAK/ttoffline | bb0e91704a755d34983e94288d50288e46b68380 | [
"MIT"
] | 4 | 2019-07-28T21:18:46.000Z | 2021-02-25T06:37:25.000Z | from direct.directnotify import DirectNotifyGlobal
import RingAction
class RingTrack:
notify = DirectNotifyGlobal.directNotify.newCategory('RingTrack')
def __init__(self, actions, actionDurations=None, reverseFlag=0):
if actionDurations == None:
actionDurations = [
1.0 / float(len(actions))] * len(actions)
sum = 0.0
for duration in actionDurations:
sum += duration
if sum != 1.0:
self.notify.warning('action lengths do not sum to 1.; sum=' + str(sum))
self.actions = actions
self.actionDurations = actionDurations
self.reverseFlag = reverseFlag
return
def eval(self, t):
t = float(t)
if self.reverseFlag:
t = 1.0 - t
actionStart = 0.0
for action, duration in zip(self.actions, self.actionDurations):
actionEnd = actionStart + duration
if t < actionEnd:
actionT = (t - actionStart) / duration
return action.eval(actionT)
actionStart = actionEnd
if t == actionStart:
self.notify.debug('time value is at end of ring track: ' + str(t) + ' == ' + str(actionStart))
else:
self.notify.debug('time value is beyond end of ring track: ' + str(t) + ' > ' + str(actionStart))
lastAction = self.actions[(len(self.actions) - 1)]
return lastAction.eval(1.0) | 36.974359 | 109 | 0.588072 | from direct.directnotify import DirectNotifyGlobal
import RingAction
class RingTrack:
notify = DirectNotifyGlobal.directNotify.newCategory('RingTrack')
def __init__(self, actions, actionDurations=None, reverseFlag=0):
if actionDurations == None:
actionDurations = [
1.0 / float(len(actions))] * len(actions)
sum = 0.0
for duration in actionDurations:
sum += duration
if sum != 1.0:
self.notify.warning('action lengths do not sum to 1.; sum=' + str(sum))
self.actions = actions
self.actionDurations = actionDurations
self.reverseFlag = reverseFlag
return
def eval(self, t):
t = float(t)
if self.reverseFlag:
t = 1.0 - t
actionStart = 0.0
for action, duration in zip(self.actions, self.actionDurations):
actionEnd = actionStart + duration
if t < actionEnd:
actionT = (t - actionStart) / duration
return action.eval(actionT)
actionStart = actionEnd
if t == actionStart:
self.notify.debug('time value is at end of ring track: ' + str(t) + ' == ' + str(actionStart))
else:
self.notify.debug('time value is beyond end of ring track: ' + str(t) + ' > ' + str(actionStart))
lastAction = self.actions[(len(self.actions) - 1)]
return lastAction.eval(1.0) | true | true |
f7f6e633dc0da02b64b4131dd1214559ad8cf299 | 12,021 | py | Python | hitch/key.py | hitchdev/seleniumdirector | bd108f22d5b9e0d18e9966cee0cff60ef82a609a | [
"MIT"
] | 5 | 2018-05-02T15:01:46.000Z | 2021-11-05T20:26:56.000Z | hitch/key.py | hitchdev/seleniumdirector | bd108f22d5b9e0d18e9966cee0cff60ef82a609a | [
"MIT"
] | null | null | null | hitch/key.py | hitchdev/seleniumdirector | bd108f22d5b9e0d18e9966cee0cff60ef82a609a | [
"MIT"
] | 1 | 2020-02-09T11:43:06.000Z | 2020-02-09T11:43:06.000Z | from hitchstory import StoryCollection, BaseEngine, HitchStoryException
from hitchstory import validate
from hitchstory import GivenDefinition, GivenProperty, InfoDefinition, InfoProperty
from hitchrun import expected
from commandlib import Command, CommandError, python
from strictyaml import Str, Map, MapPattern, Bool, Enum, Optional, load
from pathquery import pathquery
from hitchrun import DIR
from hitchrun.decorators import ignore_ctrlc
from hitchrunpy import (
ExamplePythonCode,
ExpectedExceptionMessageWasDifferent,
)
import hitchbuildpy
import dirtemplate
import signal
import hitchpylibrarytoolkit
from templex import Templex
PROJECT_NAME = "seleniumdirector"
toolkit = hitchpylibrarytoolkit.ProjectToolkit(
"seleniumdirector",
DIR,
)
def project_build(paths, python_version, selenium_version=None):
pylibrary = (
hitchbuildpy.PyLibrary(
name="py{0}".format(python_version),
base_python=hitchbuildpy.PyenvBuild(python_version).with_build_path(
paths.share
),
module_name="seleniumdirector",
library_src=paths.project,
)
.with_requirementstxt(paths.key / "debugrequirements.txt")
.with_build_path(paths.gen)
)
if selenium_version is not None:
pylibrary = pylibrary.with_packages("selenium=={0}".format(selenium_version))
pylibrary.ensure_built()
return pylibrary
class Engine(BaseEngine):
"""Python engine for running tests."""
given_definition = GivenDefinition(
python_version=GivenProperty(Str()),
selenium_version=GivenProperty(Str()),
website=GivenProperty(MapPattern(Str(), Str())),
selectors_yml=GivenProperty(Str()),
javascript=GivenProperty(Str()),
setup=GivenProperty(Str()),
code=GivenProperty(Str()),
)
info_definition = InfoDefinition(
status=InfoProperty(schema=Enum(["experimental", "stable"])),
docs=InfoProperty(schema=Str()),
)
def __init__(self, keypath, settings):
self.path = keypath
self.settings = settings
def set_up(self):
"""Set up your applications and the test environment."""
self.path.state = self.path.gen.joinpath("state")
if self.path.state.exists():
self.path.state.rmtree(ignore_errors=True)
self.path.state.mkdir()
self.path.profile = self.path.gen.joinpath("profile")
dirtemplate.DirTemplate(
"webapp", self.path.key / "htmltemplate", self.path.state
).with_vars(javascript=self.given.get("javascript", "")).with_files(
base_html={
filename: {"content": content}
for filename, content in self.given.get("website", {}).items()
}
).ensure_built()
self.path.state.joinpath("selectors.yml").write_text(
self.given["selectors.yml"]
)
self.server = (
python("-m", "http.server").in_dir(self.path.state / "webapp").pexpect()
)
self.server.expect("Serving HTTP on 0.0.0.0")
if not self.path.profile.exists():
self.path.profile.mkdir()
self.python = project_build(
self.path, self.given["python version"], self.given["selenium version"]
).bin.python
self.example_py_code = (
ExamplePythonCode(self.python, self.path.state)
.with_setup_code(self.given.get("setup", ""))
.with_terminal_size(160, 100)
.with_long_strings()
)
@validate(
code=Str(),
will_output=Map({"in python 2": Str(), "in python 3": Str()}) | Str(),
raises=Map(
{
Optional("type"): Map({"in python 2": Str(), "in python 3": Str()})
| Str(),
Optional("message"): Map({"in python 2": Str(), "in python 3": Str()})
| Str(),
}
),
in_interpreter=Bool(),
)
def run(self, code, will_output=None, raises=None, in_interpreter=False):
if in_interpreter:
code = "{0}\nprint(repr({1}))".format(
"\n".join(code.strip().split("\n")[:-1]), code.strip().split("\n")[-1]
)
to_run = self.example_py_code.with_code(code)
if self.settings.get("cprofile"):
to_run = to_run.with_cprofile(
self.path.profile.joinpath("{0}.dat".format(self.story.slug))
)
result = (
to_run.expect_exceptions().run() if raises is not None else to_run.run()
)
if will_output is not None:
actual_output = "\n".join(
[line.rstrip() for line in result.output.split("\n")]
)
try:
Templex(will_output).assert_match(actual_output)
except AssertionError:
if self.settings.get("rewrite"):
self.current_step.update(**{"will output": actual_output})
else:
raise
if raises is not None:
differential = False # Difference between python 2 and python 3 output?
exception_type = raises.get("type")
message = raises.get("message")
if exception_type is not None:
if not isinstance(exception_type, str):
differential = True
exception_type = (
exception_type["in python 2"]
if self.given["python version"].startswith("2")
else exception_type["in python 3"]
)
if message is not None:
if not isinstance(message, str):
differential = True
message = (
message["in python 2"]
if self.given["python version"].startswith("2")
else message["in python 3"]
)
try:
result.exception_was_raised(exception_type, message)
except ExpectedExceptionMessageWasDifferent:
if self.settings.get("rewrite") and not differential:
new_raises = raises.copy()
new_raises["message"] = result.exception.message
self.current_step.update(raises=new_raises)
else:
raise
def do_nothing(self):
pass
def pause(self, message="Pause"):
import IPython
IPython.embed()
def tear_down(self):
self.server.kill(signal.SIGTERM)
self.server.wait()
def _storybook(settings):
return StoryCollection(pathquery(DIR.key).ext("story"), Engine(DIR, settings))
def _current_version():
return DIR.project.joinpath("VERSION").bytes().decode("utf8").rstrip()
def _personal_settings():
settings_file = DIR.key.joinpath("personalsettings.yml")
if not settings_file.exists():
settings_file.write_text(
(
"engine:\n"
" rewrite: no\n"
" cprofile: no\n"
"params:\n"
" python version: 3.5.0\n"
)
)
return load(
settings_file.bytes().decode("utf8"),
Map(
{
"engine": Map({"rewrite": Bool(), "cprofile": Bool()}),
"params": Map({"python version": Str()}),
}
),
)
@expected(HitchStoryException)
def bdd(*keywords):
"""
Run stories matching keywords.
"""
settings = _personal_settings().data
_storybook(settings["engine"]).with_params(
**{"python version": settings["params"]["python version"]}
).only_uninherited().shortcut(*keywords).play()
@expected(HitchStoryException)
def rbdd(*keywords):
"""
Run stories matching keywords.
"""
settings = _personal_settings().data
settings["rewrite"] = True
_storybook(settings["engine"]).with_params(
**{"python version": settings["params"]["python version"]}
).only_uninherited().shortcut(*keywords).play()
@expected(HitchStoryException)
def regressfile(filename):
"""
Run all stories in filename 'filename' in python 2 and 3.
Rewrite stories if appropriate.
"""
_storybook({"rewrite": False}).in_filename(filename).with_params(
**{"python version": "2.7.10"}
).filter(lambda story: not story.info["fails on python 2"]).ordered_by_name().play()
_storybook({"rewrite": False}).with_params(
**{"python version": "3.5.0"}
).in_filename(filename).ordered_by_name().play()
@expected(HitchStoryException)
def regression():
"""
Run regression testing - lint and then run all tests.
"""
lint()
storybook = _storybook({}).only_uninherited()
storybook.with_params(**{"python version": "3.5.0"}).ordered_by_name().play()
def lint():
"""
Lint all code.
"""
toolkit.lint(exclude=["__init__.py"])
print("Lint success!")
def deploy(version):
"""
Deploy to pypi as specified version.
"""
NAME = "seleniumdirector"
git = Command("git").in_dir(DIR.project)
version_file = DIR.project.joinpath("VERSION")
old_version = version_file.bytes().decode("utf8")
if version_file.bytes().decode("utf8") != version:
DIR.project.joinpath("VERSION").write_text(version)
git("add", "VERSION").run()
git(
"commit", "-m", "RELEASE: Version {0} -> {1}".format(old_version, version)
).run()
git("push").run()
git("tag", "-a", version, "-m", "Version {0}".format(version)).run()
git("push", "origin", version).run()
else:
git("push").run()
# Set __version__ variable in __init__.py, build sdist and put it back
initpy = DIR.project.joinpath(NAME, "__init__.py")
original_initpy_contents = initpy.bytes().decode("utf8")
initpy.write_text(original_initpy_contents.replace("DEVELOPMENT_VERSION", version))
python("setup.py", "sdist").in_dir(DIR.project).run()
initpy.write_text(original_initpy_contents)
# Upload to pypi
python("-m", "twine", "upload", "dist/{0}-{1}.tar.gz".format(NAME, version)).in_dir(
DIR.project
).run()
@expected(dirtemplate.exceptions.DirTemplateException)
def docgen():
"""
Build documentation.
"""
toolkit.docgen(Engine(DIR, {}))
@expected(CommandError)
def doctests():
pylibrary = project_build(DIR, "2.7.10")
pylibrary.bin.python(
"-m", "doctest", "-v", DIR.project.joinpath("seleniumdirector", "utils.py")
).in_dir(DIR.project.joinpath("seleniumdirector")).run()
pylibrary = project_build(DIR, "3.5.0")
pylibrary.bin.python(
"-m", "doctest", "-v", DIR.project.joinpath("seleniumdirector", "utils.py")
).in_dir(DIR.project.joinpath("seleniumdirector")).run()
@ignore_ctrlc
def ipy():
"""
Run IPython in environment."
"""
Command(DIR.gen.joinpath("py3.5.0", "bin", "ipython")).run()
def hvenvup(package, directory):
"""
Install a new version of a package in the hitch venv.
"""
pip = Command(DIR.gen.joinpath("hvenv", "bin", "pip"))
pip("uninstall", package, "-y").run()
pip("install", DIR.project.joinpath(directory).abspath()).run()
def reformat():
"""
Reformat the code.
"""
toolkit.reformat()
def runserver():
"""
Run web server.
"""
python("-m", "http.server").in_dir(DIR.gen / "state" / "webapp").run()
def rerun(version="3.7.0"):
"""
Rerun last example code block with specified version of python.
"""
Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))(
DIR.gen.joinpath("state", "working", "examplepythoncode.py")
).in_dir(DIR.gen.joinpath("state", "working")).run()
@expected(dirtemplate.exceptions.DirTemplateException)
def readmegen():
"""
Build README.md and CHANGELOG.md.
"""
toolkit.docgen(Engine(DIR, {}))
| 30.823077 | 88 | 0.593461 | from hitchstory import StoryCollection, BaseEngine, HitchStoryException
from hitchstory import validate
from hitchstory import GivenDefinition, GivenProperty, InfoDefinition, InfoProperty
from hitchrun import expected
from commandlib import Command, CommandError, python
from strictyaml import Str, Map, MapPattern, Bool, Enum, Optional, load
from pathquery import pathquery
from hitchrun import DIR
from hitchrun.decorators import ignore_ctrlc
from hitchrunpy import (
ExamplePythonCode,
ExpectedExceptionMessageWasDifferent,
)
import hitchbuildpy
import dirtemplate
import signal
import hitchpylibrarytoolkit
from templex import Templex
PROJECT_NAME = "seleniumdirector"
toolkit = hitchpylibrarytoolkit.ProjectToolkit(
"seleniumdirector",
DIR,
)
def project_build(paths, python_version, selenium_version=None):
pylibrary = (
hitchbuildpy.PyLibrary(
name="py{0}".format(python_version),
base_python=hitchbuildpy.PyenvBuild(python_version).with_build_path(
paths.share
),
module_name="seleniumdirector",
library_src=paths.project,
)
.with_requirementstxt(paths.key / "debugrequirements.txt")
.with_build_path(paths.gen)
)
if selenium_version is not None:
pylibrary = pylibrary.with_packages("selenium=={0}".format(selenium_version))
pylibrary.ensure_built()
return pylibrary
class Engine(BaseEngine):
given_definition = GivenDefinition(
python_version=GivenProperty(Str()),
selenium_version=GivenProperty(Str()),
website=GivenProperty(MapPattern(Str(), Str())),
selectors_yml=GivenProperty(Str()),
javascript=GivenProperty(Str()),
setup=GivenProperty(Str()),
code=GivenProperty(Str()),
)
info_definition = InfoDefinition(
status=InfoProperty(schema=Enum(["experimental", "stable"])),
docs=InfoProperty(schema=Str()),
)
def __init__(self, keypath, settings):
self.path = keypath
self.settings = settings
def set_up(self):
self.path.state = self.path.gen.joinpath("state")
if self.path.state.exists():
self.path.state.rmtree(ignore_errors=True)
self.path.state.mkdir()
self.path.profile = self.path.gen.joinpath("profile")
dirtemplate.DirTemplate(
"webapp", self.path.key / "htmltemplate", self.path.state
).with_vars(javascript=self.given.get("javascript", "")).with_files(
base_html={
filename: {"content": content}
for filename, content in self.given.get("website", {}).items()
}
).ensure_built()
self.path.state.joinpath("selectors.yml").write_text(
self.given["selectors.yml"]
)
self.server = (
python("-m", "http.server").in_dir(self.path.state / "webapp").pexpect()
)
self.server.expect("Serving HTTP on 0.0.0.0")
if not self.path.profile.exists():
self.path.profile.mkdir()
self.python = project_build(
self.path, self.given["python version"], self.given["selenium version"]
).bin.python
self.example_py_code = (
ExamplePythonCode(self.python, self.path.state)
.with_setup_code(self.given.get("setup", ""))
.with_terminal_size(160, 100)
.with_long_strings()
)
@validate(
code=Str(),
will_output=Map({"in python 2": Str(), "in python 3": Str()}) | Str(),
raises=Map(
{
Optional("type"): Map({"in python 2": Str(), "in python 3": Str()})
| Str(),
Optional("message"): Map({"in python 2": Str(), "in python 3": Str()})
| Str(),
}
),
in_interpreter=Bool(),
)
def run(self, code, will_output=None, raises=None, in_interpreter=False):
if in_interpreter:
code = "{0}\nprint(repr({1}))".format(
"\n".join(code.strip().split("\n")[:-1]), code.strip().split("\n")[-1]
)
to_run = self.example_py_code.with_code(code)
if self.settings.get("cprofile"):
to_run = to_run.with_cprofile(
self.path.profile.joinpath("{0}.dat".format(self.story.slug))
)
result = (
to_run.expect_exceptions().run() if raises is not None else to_run.run()
)
if will_output is not None:
actual_output = "\n".join(
[line.rstrip() for line in result.output.split("\n")]
)
try:
Templex(will_output).assert_match(actual_output)
except AssertionError:
if self.settings.get("rewrite"):
self.current_step.update(**{"will output": actual_output})
else:
raise
if raises is not None:
differential = False
exception_type = raises.get("type")
message = raises.get("message")
if exception_type is not None:
if not isinstance(exception_type, str):
differential = True
exception_type = (
exception_type["in python 2"]
if self.given["python version"].startswith("2")
else exception_type["in python 3"]
)
if message is not None:
if not isinstance(message, str):
differential = True
message = (
message["in python 2"]
if self.given["python version"].startswith("2")
else message["in python 3"]
)
try:
result.exception_was_raised(exception_type, message)
except ExpectedExceptionMessageWasDifferent:
if self.settings.get("rewrite") and not differential:
new_raises = raises.copy()
new_raises["message"] = result.exception.message
self.current_step.update(raises=new_raises)
else:
raise
def do_nothing(self):
pass
def pause(self, message="Pause"):
import IPython
IPython.embed()
def tear_down(self):
self.server.kill(signal.SIGTERM)
self.server.wait()
def _storybook(settings):
return StoryCollection(pathquery(DIR.key).ext("story"), Engine(DIR, settings))
def _current_version():
return DIR.project.joinpath("VERSION").bytes().decode("utf8").rstrip()
def _personal_settings():
settings_file = DIR.key.joinpath("personalsettings.yml")
if not settings_file.exists():
settings_file.write_text(
(
"engine:\n"
" rewrite: no\n"
" cprofile: no\n"
"params:\n"
" python version: 3.5.0\n"
)
)
return load(
settings_file.bytes().decode("utf8"),
Map(
{
"engine": Map({"rewrite": Bool(), "cprofile": Bool()}),
"params": Map({"python version": Str()}),
}
),
)
@expected(HitchStoryException)
def bdd(*keywords):
settings = _personal_settings().data
_storybook(settings["engine"]).with_params(
**{"python version": settings["params"]["python version"]}
).only_uninherited().shortcut(*keywords).play()
@expected(HitchStoryException)
def rbdd(*keywords):
settings = _personal_settings().data
settings["rewrite"] = True
_storybook(settings["engine"]).with_params(
**{"python version": settings["params"]["python version"]}
).only_uninherited().shortcut(*keywords).play()
@expected(HitchStoryException)
def regressfile(filename):
_storybook({"rewrite": False}).in_filename(filename).with_params(
**{"python version": "2.7.10"}
).filter(lambda story: not story.info["fails on python 2"]).ordered_by_name().play()
_storybook({"rewrite": False}).with_params(
**{"python version": "3.5.0"}
).in_filename(filename).ordered_by_name().play()
@expected(HitchStoryException)
def regression():
lint()
storybook = _storybook({}).only_uninherited()
storybook.with_params(**{"python version": "3.5.0"}).ordered_by_name().play()
def lint():
toolkit.lint(exclude=["__init__.py"])
print("Lint success!")
def deploy(version):
NAME = "seleniumdirector"
git = Command("git").in_dir(DIR.project)
version_file = DIR.project.joinpath("VERSION")
old_version = version_file.bytes().decode("utf8")
if version_file.bytes().decode("utf8") != version:
DIR.project.joinpath("VERSION").write_text(version)
git("add", "VERSION").run()
git(
"commit", "-m", "RELEASE: Version {0} -> {1}".format(old_version, version)
).run()
git("push").run()
git("tag", "-a", version, "-m", "Version {0}".format(version)).run()
git("push", "origin", version).run()
else:
git("push").run()
initpy = DIR.project.joinpath(NAME, "__init__.py")
original_initpy_contents = initpy.bytes().decode("utf8")
initpy.write_text(original_initpy_contents.replace("DEVELOPMENT_VERSION", version))
python("setup.py", "sdist").in_dir(DIR.project).run()
initpy.write_text(original_initpy_contents)
python("-m", "twine", "upload", "dist/{0}-{1}.tar.gz".format(NAME, version)).in_dir(
DIR.project
).run()
@expected(dirtemplate.exceptions.DirTemplateException)
def docgen():
toolkit.docgen(Engine(DIR, {}))
@expected(CommandError)
def doctests():
pylibrary = project_build(DIR, "2.7.10")
pylibrary.bin.python(
"-m", "doctest", "-v", DIR.project.joinpath("seleniumdirector", "utils.py")
).in_dir(DIR.project.joinpath("seleniumdirector")).run()
pylibrary = project_build(DIR, "3.5.0")
pylibrary.bin.python(
"-m", "doctest", "-v", DIR.project.joinpath("seleniumdirector", "utils.py")
).in_dir(DIR.project.joinpath("seleniumdirector")).run()
@ignore_ctrlc
def ipy():
Command(DIR.gen.joinpath("py3.5.0", "bin", "ipython")).run()
def hvenvup(package, directory):
pip = Command(DIR.gen.joinpath("hvenv", "bin", "pip"))
pip("uninstall", package, "-y").run()
pip("install", DIR.project.joinpath(directory).abspath()).run()
def reformat():
toolkit.reformat()
def runserver():
python("-m", "http.server").in_dir(DIR.gen / "state" / "webapp").run()
def rerun(version="3.7.0"):
Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))(
DIR.gen.joinpath("state", "working", "examplepythoncode.py")
).in_dir(DIR.gen.joinpath("state", "working")).run()
@expected(dirtemplate.exceptions.DirTemplateException)
def readmegen():
toolkit.docgen(Engine(DIR, {}))
| true | true |
f7f6e6a650033f4a55d0f8aacd11b378b26c60f7 | 913 | py | Python | tests/loader/test_COGNETLoader.py | jinzhuoran/CogKGE | b0e819a1d34cf61a7d70c33808da3377b73c8fd6 | [
"MIT"
] | 18 | 2022-01-22T09:52:57.000Z | 2022-03-22T15:02:12.000Z | tests/loader/test_COGNETLoader.py | CogNLP/CogKGE | 70d851d6489600c1e90eb25b0388a3ceba2f078c | [
"MIT"
] | null | null | null | tests/loader/test_COGNETLoader.py | CogNLP/CogKGE | 70d851d6489600c1e90eb25b0388a3ceba2f078c | [
"MIT"
] | null | null | null |
from cogkge import *
import time
print("Testing COGNET680K dataloader...")
loader = COGNET680KLoader(dataset_path='/home/hongbang/CogKTR/dataset/',
download=True,
)
start_time = time.time()
train_data, valid_data, test_data = loader.load_all_data()
node_lut,relation_lut = loader.load_all_lut()
processor = COGNET680KProcessor(node_lut, relation_lut)
train_dataset = processor.process(train_data)
valid_dataset = processor.process(valid_data)
test_dataset = processor.process(test_data)
for i in range(2):
print(train_dataset[i])
print(valid_dataset[i])
print(test_dataset[i])
print("Train:{} Valid:{} Test:{}".format(len(train_dataset),
len(valid_dataset),
len(test_dataset)))
print("--- %s seconds ---" % (time.time() - start_time))
| 28.53125 | 73 | 0.62103 |
from cogkge import *
import time
print("Testing COGNET680K dataloader...")
loader = COGNET680KLoader(dataset_path='/home/hongbang/CogKTR/dataset/',
download=True,
)
start_time = time.time()
train_data, valid_data, test_data = loader.load_all_data()
node_lut,relation_lut = loader.load_all_lut()
processor = COGNET680KProcessor(node_lut, relation_lut)
train_dataset = processor.process(train_data)
valid_dataset = processor.process(valid_data)
test_dataset = processor.process(test_data)
for i in range(2):
print(train_dataset[i])
print(valid_dataset[i])
print(test_dataset[i])
print("Train:{} Valid:{} Test:{}".format(len(train_dataset),
len(valid_dataset),
len(test_dataset)))
print("--- %s seconds ---" % (time.time() - start_time))
| true | true |
f7f6e7a20caa1ba14899725c88f742d47a249690 | 79,843 | py | Python | swift/proxy/controllers/base.py | notmyname/swift | 340014ed224d506be5019fb4097eec9dedf3e5e1 | [
"Apache-2.0"
] | null | null | null | swift/proxy/controllers/base.py | notmyname/swift | 340014ed224d506be5019fb4097eec9dedf3e5e1 | [
"Apache-2.0"
] | null | null | null | swift/proxy/controllers/base.py | notmyname/swift | 340014ed224d506be5019fb4097eec9dedf3e5e1 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2010-2016 OpenStack Foundation
#
# 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.
# NOTE: swift_conn
# You'll see swift_conn passed around a few places in this file. This is the
# source bufferedhttp connection of whatever it is attached to.
# It is used when early termination of reading from the connection should
# happen, such as when a range request is satisfied but there's still more the
# source connection would like to send. To prevent having to read all the data
# that could be left, the source connection can be .close() and then reads
# commence to empty out any buffers.
# These shenanigans are to ensure all related objects can be garbage
# collected. We've seen objects hang around forever otherwise.
from six.moves.urllib.parse import quote
import os
import time
import functools
import inspect
import itertools
import operator
from copy import deepcopy
from sys import exc_info
from swift import gettext_ as _
from eventlet import sleep
from eventlet.timeout import Timeout
import six
from swift.common.wsgi import make_pre_authed_env
from swift.common.utils import Timestamp, config_true_value, \
public, split_path, list_from_csv, GreenthreadSafeIterator, \
GreenAsyncPile, quorum_size, parse_content_type, \
document_iters_to_http_response_body
from swift.common.bufferedhttp import http_connect
from swift.common.exceptions import ChunkReadTimeout, ChunkWriteTimeout, \
ConnectionTimeout, RangeAlreadyComplete
from swift.common.header_key_dict import HeaderKeyDict
from swift.common.http import is_informational, is_success, is_redirection, \
is_server_error, HTTP_OK, HTTP_PARTIAL_CONTENT, HTTP_MULTIPLE_CHOICES, \
HTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_SERVICE_UNAVAILABLE, \
HTTP_INSUFFICIENT_STORAGE, HTTP_UNAUTHORIZED, HTTP_CONTINUE, HTTP_GONE
from swift.common.swob import Request, Response, Range, \
HTTPException, HTTPRequestedRangeNotSatisfiable, HTTPServiceUnavailable, \
status_map
from swift.common.request_helpers import strip_sys_meta_prefix, \
strip_user_meta_prefix, is_user_meta, is_sys_meta, is_sys_or_user_meta, \
http_response_to_document_iters, is_object_transient_sysmeta, \
strip_object_transient_sysmeta_prefix
from swift.common.storage_policy import POLICIES
DEFAULT_RECHECK_ACCOUNT_EXISTENCE = 60 # seconds
DEFAULT_RECHECK_CONTAINER_EXISTENCE = 60 # seconds
def update_headers(response, headers):
"""
Helper function to update headers in the response.
:param response: swob.Response object
:param headers: dictionary headers
"""
if hasattr(headers, 'items'):
headers = headers.items()
for name, value in headers:
if name == 'etag':
response.headers[name] = value.replace('"', '')
elif name.lower() not in (
'date', 'content-length', 'content-type',
'connection', 'x-put-timestamp', 'x-delete-after'):
response.headers[name] = value
def source_key(resp):
"""
Provide the timestamp of the swift http response as a floating
point value. Used as a sort key.
:param resp: bufferedhttp response object
"""
return Timestamp(resp.getheader('x-backend-timestamp') or
resp.getheader('x-put-timestamp') or
resp.getheader('x-timestamp') or 0)
def delay_denial(func):
"""
Decorator to declare which methods should have any swift.authorize call
delayed. This is so the method can load the Request object up with
additional information that may be needed by the authorization system.
:param func: function for which authorization will be delayed
"""
func.delay_denial = True
return func
def _prep_headers_to_info(headers, server_type):
"""
Helper method that iterates once over a dict of headers,
converting all keys to lower case and separating
into subsets containing user metadata, system metadata
and other headers.
"""
meta = {}
sysmeta = {}
other = {}
for key, val in dict(headers).items():
lkey = key.lower()
if is_user_meta(server_type, lkey):
meta[strip_user_meta_prefix(server_type, lkey)] = val
elif is_sys_meta(server_type, lkey):
sysmeta[strip_sys_meta_prefix(server_type, lkey)] = val
else:
other[lkey] = val
return other, meta, sysmeta
def headers_to_account_info(headers, status_int=HTTP_OK):
"""
Construct a cacheable dict of account info based on response headers.
"""
headers, meta, sysmeta = _prep_headers_to_info(headers, 'account')
account_info = {
'status': status_int,
# 'container_count' anomaly:
# Previous code sometimes expects an int sometimes a string
# Current code aligns to str and None, yet translates to int in
# deprecated functions as needed
'container_count': headers.get('x-account-container-count'),
'total_object_count': headers.get('x-account-object-count'),
'bytes': headers.get('x-account-bytes-used'),
'meta': meta,
'sysmeta': sysmeta,
}
if is_success(status_int):
account_info['account_really_exists'] = not config_true_value(
headers.get('x-backend-fake-account-listing'))
return account_info
def headers_to_container_info(headers, status_int=HTTP_OK):
"""
Construct a cacheable dict of container info based on response headers.
"""
headers, meta, sysmeta = _prep_headers_to_info(headers, 'container')
return {
'status': status_int,
'read_acl': headers.get('x-container-read'),
'write_acl': headers.get('x-container-write'),
'sync_key': headers.get('x-container-sync-key'),
'object_count': headers.get('x-container-object-count'),
'bytes': headers.get('x-container-bytes-used'),
'versions': headers.get('x-versions-location'),
'storage_policy': headers.get('x-backend-storage-policy-index', '0'),
'cors': {
'allow_origin': meta.get('access-control-allow-origin'),
'expose_headers': meta.get('access-control-expose-headers'),
'max_age': meta.get('access-control-max-age')
},
'meta': meta,
'sysmeta': sysmeta,
}
def headers_to_object_info(headers, status_int=HTTP_OK):
"""
Construct a cacheable dict of object info based on response headers.
"""
headers, meta, sysmeta = _prep_headers_to_info(headers, 'object')
transient_sysmeta = {}
for key, val in six.iteritems(headers):
if is_object_transient_sysmeta(key):
key = strip_object_transient_sysmeta_prefix(key.lower())
transient_sysmeta[key] = val
info = {'status': status_int,
'length': headers.get('content-length'),
'type': headers.get('content-type'),
'etag': headers.get('etag'),
'meta': meta,
'sysmeta': sysmeta,
'transient_sysmeta': transient_sysmeta
}
return info
def cors_validation(func):
"""
Decorator to check if the request is a CORS request and if so, if it's
valid.
:param func: function to check
"""
@functools.wraps(func)
def wrapped(*a, **kw):
controller = a[0]
req = a[1]
# The logic here was interpreted from
# http://www.w3.org/TR/cors/#resource-requests
# Is this a CORS request?
req_origin = req.headers.get('Origin', None)
if req_origin:
# Yes, this is a CORS request so test if the origin is allowed
container_info = \
controller.container_info(controller.account_name,
controller.container_name, req)
cors_info = container_info.get('cors', {})
# Call through to the decorated method
resp = func(*a, **kw)
if controller.app.strict_cors_mode and \
not controller.is_origin_allowed(cors_info, req_origin):
return resp
# Expose,
# - simple response headers,
# http://www.w3.org/TR/cors/#simple-response-header
# - swift specific: etag, x-timestamp, x-trans-id
# - headers provided by the operator in cors_expose_headers
# - user metadata headers
# - headers provided by the user in
# x-container-meta-access-control-expose-headers
if 'Access-Control-Expose-Headers' not in resp.headers:
expose_headers = set([
'cache-control', 'content-language', 'content-type',
'expires', 'last-modified', 'pragma', 'etag',
'x-timestamp', 'x-trans-id', 'x-openstack-request-id'])
expose_headers.update(controller.app.cors_expose_headers)
for header in resp.headers:
if header.startswith('X-Container-Meta') or \
header.startswith('X-Object-Meta'):
expose_headers.add(header.lower())
if cors_info.get('expose_headers'):
expose_headers = expose_headers.union(
[header_line.strip().lower()
for header_line in
cors_info['expose_headers'].split(' ')
if header_line.strip()])
resp.headers['Access-Control-Expose-Headers'] = \
', '.join(expose_headers)
# The user agent won't process the response if the Allow-Origin
# header isn't included
if 'Access-Control-Allow-Origin' not in resp.headers:
if cors_info['allow_origin'] and \
cors_info['allow_origin'].strip() == '*':
resp.headers['Access-Control-Allow-Origin'] = '*'
else:
resp.headers['Access-Control-Allow-Origin'] = req_origin
return resp
else:
# Not a CORS request so make the call as normal
return func(*a, **kw)
return wrapped
def get_object_info(env, app, path=None, swift_source=None):
"""
Get the info structure for an object, based on env and app.
This is useful to middlewares.
.. note::
This call bypasses auth. Success does not imply that the request has
authorization to the object.
"""
(version, account, container, obj) = \
split_path(path or env['PATH_INFO'], 4, 4, True)
info = _get_object_info(app, env, account, container, obj,
swift_source=swift_source)
if info:
info = deepcopy(info)
else:
info = headers_to_object_info({}, 0)
for field in ('length',):
if info.get(field) is None:
info[field] = 0
else:
info[field] = int(info[field])
return info
def get_container_info(env, app, swift_source=None):
"""
Get the info structure for a container, based on env and app.
This is useful to middlewares.
.. note::
This call bypasses auth. Success does not imply that the request has
authorization to the container.
"""
(version, account, container, unused) = \
split_path(env['PATH_INFO'], 3, 4, True)
# Check in environment cache and in memcache (in that order)
info = _get_info_from_caches(app, env, account, container)
if not info:
# Cache miss; go HEAD the container and populate the caches
env.setdefault('swift.infocache', {})
# Before checking the container, make sure the account exists.
#
# If it is an autocreateable account, just assume it exists; don't
# HEAD the account, as a GET or HEAD response for an autocreateable
# account is successful whether the account actually has .db files
# on disk or not.
is_autocreate_account = account.startswith(
getattr(app, 'auto_create_account_prefix', '.'))
if not is_autocreate_account:
account_info = get_account_info(env, app, swift_source)
if not account_info or not is_success(account_info['status']):
return headers_to_container_info({}, 0)
req = _prepare_pre_auth_info_request(
env, ("/%s/%s/%s" % (version, account, container)),
(swift_source or 'GET_CONTAINER_INFO'))
resp = req.get_response(app)
# Check in infocache to see if the proxy (or anyone else) already
# populated the cache for us. If they did, just use what's there.
#
# See similar comment in get_account_info() for justification.
info = _get_info_from_infocache(env, account, container)
if info is None:
info = set_info_cache(app, env, account, container, resp)
if info:
info = deepcopy(info) # avoid mutating what's in swift.infocache
else:
info = headers_to_container_info({}, 0)
# Old data format in memcache immediately after a Swift upgrade; clean
# it up so consumers of get_container_info() aren't exposed to it.
if 'object_count' not in info and 'container_size' in info:
info['object_count'] = info.pop('container_size')
for field in ('storage_policy', 'bytes', 'object_count'):
if info.get(field) is None:
info[field] = 0
else:
info[field] = int(info[field])
return info
def get_account_info(env, app, swift_source=None):
"""
Get the info structure for an account, based on env and app.
This is useful to middlewares.
.. note::
This call bypasses auth. Success does not imply that the request has
authorization to the account.
:raises ValueError: when path doesn't contain an account
"""
(version, account, _junk, _junk) = \
split_path(env['PATH_INFO'], 2, 4, True)
# Check in environment cache and in memcache (in that order)
info = _get_info_from_caches(app, env, account)
# Cache miss; go HEAD the account and populate the caches
if not info:
env.setdefault('swift.infocache', {})
req = _prepare_pre_auth_info_request(
env, "/%s/%s" % (version, account),
(swift_source or 'GET_ACCOUNT_INFO'))
resp = req.get_response(app)
# Check in infocache to see if the proxy (or anyone else) already
# populated the cache for us. If they did, just use what's there.
#
# The point of this is to avoid setting the value in memcached
# twice. Otherwise, we're needlessly sending requests across the
# network.
#
# If the info didn't make it into the cache, we'll compute it from
# the response and populate the cache ourselves.
#
# Note that this is taking "exists in infocache" to imply "exists in
# memcache". That's because we're trying to avoid superfluous
# network traffic, and checking in memcache prior to setting in
# memcache would defeat the purpose.
info = _get_info_from_infocache(env, account)
if info is None:
info = set_info_cache(app, env, account, None, resp)
if info:
info = info.copy() # avoid mutating what's in swift.infocache
else:
info = headers_to_account_info({}, 0)
for field in ('container_count', 'bytes', 'total_object_count'):
if info.get(field) is None:
info[field] = 0
else:
info[field] = int(info[field])
return info
def get_cache_key(account, container=None, obj=None):
"""
Get the keys for both memcache and env['swift.infocache'] (cache_key)
where info about accounts, containers, and objects is cached
:param account: The name of the account
:param container: The name of the container (or None if account)
:param obj: The name of the object (or None if account or container)
:returns: a string cache_key
"""
if obj:
if not (account and container):
raise ValueError('Object cache key requires account and container')
cache_key = 'object/%s/%s/%s' % (account, container, obj)
elif container:
if not account:
raise ValueError('Container cache key requires account')
cache_key = 'container/%s/%s' % (account, container)
else:
cache_key = 'account/%s' % account
# Use a unique environment cache key per account and one container.
# This allows caching both account and container and ensures that when we
# copy this env to form a new request, it won't accidentally reuse the
# old container or account info
return cache_key
def set_info_cache(app, env, account, container, resp):
"""
Cache info in both memcache and env.
:param app: the application object
:param account: the unquoted account name
:param container: the unquoted container name or None
:param resp: the response received or None if info cache should be cleared
:returns: the info that was placed into the cache, or None if the
request status was not in (404, 410, 2xx).
"""
infocache = env.setdefault('swift.infocache', {})
cache_time = None
if container and resp:
cache_time = int(resp.headers.get(
'X-Backend-Recheck-Container-Existence',
DEFAULT_RECHECK_CONTAINER_EXISTENCE))
elif resp:
cache_time = int(resp.headers.get(
'X-Backend-Recheck-Account-Existence',
DEFAULT_RECHECK_ACCOUNT_EXISTENCE))
cache_key = get_cache_key(account, container)
if resp:
if resp.status_int in (HTTP_NOT_FOUND, HTTP_GONE):
cache_time *= 0.1
elif not is_success(resp.status_int):
cache_time = None
# Next actually set both memcache and the env cache
memcache = getattr(app, 'memcache', None) or env.get('swift.cache')
if cache_time is None:
infocache.pop(cache_key, None)
if memcache:
memcache.delete(cache_key)
return
if container:
info = headers_to_container_info(resp.headers, resp.status_int)
else:
info = headers_to_account_info(resp.headers, resp.status_int)
if memcache:
memcache.set(cache_key, info, time=cache_time)
infocache[cache_key] = info
return info
def set_object_info_cache(app, env, account, container, obj, resp):
"""
Cache object info in the WSGI environment, but not in memcache. Caching
in memcache would lead to cache pressure and mass evictions due to the
large number of objects in a typical Swift cluster. This is a
per-request cache only.
:param app: the application object
:param env: the environment used by the current request
:param account: the unquoted account name
:param container: the unquoted container name
:param obj: the unquoted object name
:param resp: a GET or HEAD response received from an object server, or
None if info cache should be cleared
:returns: the object info
"""
cache_key = get_cache_key(account, container, obj)
if 'swift.infocache' in env and not resp:
env['swift.infocache'].pop(cache_key, None)
return
info = headers_to_object_info(resp.headers, resp.status_int)
env.setdefault('swift.infocache', {})[cache_key] = info
return info
def clear_info_cache(app, env, account, container=None):
"""
Clear the cached info in both memcache and env
:param app: the application object
:param env: the WSGI environment
:param account: the account name
:param container: the containr name or None if setting info for containers
"""
set_info_cache(app, env, account, container, None)
def _get_info_from_infocache(env, account, container=None):
"""
Get cached account or container information from request-environment
cache (swift.infocache).
:param env: the environment used by the current request
:param account: the account name
:param container: the container name
:returns: a dictionary of cached info on cache hit, None on miss
"""
cache_key = get_cache_key(account, container)
if 'swift.infocache' in env and cache_key in env['swift.infocache']:
return env['swift.infocache'][cache_key]
return None
def _get_info_from_memcache(app, env, account, container=None):
"""
Get cached account or container information from memcache
:param app: the application object
:param env: the environment used by the current request
:param account: the account name
:param container: the container name
:returns: a dictionary of cached info on cache hit, None on miss. Also
returns None if memcache is not in use.
"""
cache_key = get_cache_key(account, container)
memcache = getattr(app, 'memcache', None) or env.get('swift.cache')
if memcache:
info = memcache.get(cache_key)
if info:
for key in info:
if isinstance(info[key], six.text_type):
info[key] = info[key].encode("utf-8")
elif isinstance(info[key], dict):
for subkey, value in info[key].items():
if isinstance(value, six.text_type):
info[key][subkey] = value.encode("utf-8")
env.setdefault('swift.infocache', {})[cache_key] = info
return info
return None
def _get_info_from_caches(app, env, account, container=None):
"""
Get the cached info from env or memcache (if used) in that order.
Used for both account and container info.
:param app: the application object
:param env: the environment used by the current request
:returns: the cached info or None if not cached
"""
info = _get_info_from_infocache(env, account, container)
if info is None:
info = _get_info_from_memcache(app, env, account, container)
return info
def _prepare_pre_auth_info_request(env, path, swift_source):
"""
Prepares a pre authed request to obtain info using a HEAD.
:param env: the environment used by the current request
:param path: The unquoted request path
:param swift_source: value for swift.source in WSGI environment
:returns: the pre authed request
"""
# Set the env for the pre_authed call without a query string
newenv = make_pre_authed_env(env, 'HEAD', path, agent='Swift',
query_string='', swift_source=swift_source)
# This is a sub request for container metadata- drop the Origin header from
# the request so the it is not treated as a CORS request.
newenv.pop('HTTP_ORIGIN', None)
# ACLs are only shown to account owners, so let's make sure this request
# looks like it came from the account owner.
newenv['swift_owner'] = True
# Note that Request.blank expects quoted path
return Request.blank(quote(path), environ=newenv)
def get_info(app, env, account, container=None, swift_source=None):
"""
Get info about accounts or containers
Note: This call bypasses auth. Success does not imply that the
request has authorization to the info.
:param app: the application object
:param env: the environment used by the current request
:param account: The unquoted name of the account
:param container: The unquoted name of the container (or None if account)
:param swift_source: swift source logged for any subrequests made while
retrieving the account or container info
:returns: information about the specified entity in a dictionary. See
get_account_info and get_container_info for details on what's in the
dictionary.
"""
env.setdefault('swift.infocache', {})
if container:
path = '/v1/%s/%s' % (account, container)
path_env = env.copy()
path_env['PATH_INFO'] = path
return get_container_info(path_env, app, swift_source=swift_source)
else:
# account info
path = '/v1/%s' % (account,)
path_env = env.copy()
path_env['PATH_INFO'] = path
return get_account_info(path_env, app, swift_source=swift_source)
def _get_object_info(app, env, account, container, obj, swift_source=None):
"""
Get the info about object
Note: This call bypasses auth. Success does not imply that the
request has authorization to the info.
:param app: the application object
:param env: the environment used by the current request
:param account: The unquoted name of the account
:param container: The unquoted name of the container
:param obj: The unquoted name of the object
:returns: the cached info or None if cannot be retrieved
"""
cache_key = get_cache_key(account, container, obj)
info = env.get('swift.infocache', {}).get(cache_key)
if info:
return info
# Not in cache, let's try the object servers
path = '/v1/%s/%s/%s' % (account, container, obj)
req = _prepare_pre_auth_info_request(env, path, swift_source)
resp = req.get_response(app)
# Unlike get_account_info() and get_container_info(), we don't save
# things in memcache, so we can store the info without network traffic,
# *and* the proxy doesn't cache object info for us, so there's no chance
# that the object info would be in the environment. Thus, we just
# compute the object info based on the response and stash it in
# swift.infocache.
info = set_object_info_cache(app, env, account, container, obj, resp)
return info
def close_swift_conn(src):
"""
Force close the http connection to the backend.
:param src: the response from the backend
"""
try:
# Since the backends set "Connection: close" in their response
# headers, the response object (src) is solely responsible for the
# socket. The connection object (src.swift_conn) has no references
# to the socket, so calling its close() method does nothing, and
# therefore we don't do it.
#
# Also, since calling the response's close() method might not
# close the underlying socket but only decrement some
# reference-counter, we have a special method here that really,
# really kills the underlying socket with a close() syscall.
src.nuke_from_orbit() # it's the only way to be sure
except Exception:
pass
def bytes_to_skip(record_size, range_start):
"""
Assume an object is composed of N records, where the first N-1 are all
the same size and the last is at most that large, but may be smaller.
When a range request is made, it might start with a partial record. This
must be discarded, lest the consumer get bad data. This is particularly
true of suffix-byte-range requests, e.g. "Range: bytes=-12345" where the
size of the object is unknown at the time the request is made.
This function computes the number of bytes that must be discarded to
ensure only whole records are yielded. Erasure-code decoding needs this.
This function could have been inlined, but it took enough tries to get
right that some targeted unit tests were desirable, hence its extraction.
"""
return (record_size - (range_start % record_size)) % record_size
class ResumingGetter(object):
def __init__(self, app, req, server_type, node_iter, partition, path,
backend_headers, concurrency=1, client_chunk_size=None,
newest=None, header_provider=None):
self.app = app
self.node_iter = node_iter
self.server_type = server_type
self.partition = partition
self.path = path
self.backend_headers = backend_headers
self.client_chunk_size = client_chunk_size
self.skip_bytes = 0
self.bytes_used_from_backend = 0
self.used_nodes = []
self.used_source_etag = ''
self.concurrency = concurrency
self.node = None
self.header_provider = header_provider
# stuff from request
self.req_method = req.method
self.req_path = req.path
self.req_query_string = req.query_string
if newest is None:
self.newest = config_true_value(req.headers.get('x-newest', 'f'))
else:
self.newest = newest
# populated when finding source
self.statuses = []
self.reasons = []
self.bodies = []
self.source_headers = []
self.sources = []
# populated from response headers
self.start_byte = self.end_byte = self.length = None
def fast_forward(self, num_bytes):
"""
Will skip num_bytes into the current ranges.
:params num_bytes: the number of bytes that have already been read on
this request. This will change the Range header
so that the next req will start where it left off.
:raises ValueError: if invalid range header
:raises HTTPRequestedRangeNotSatisfiable: if begin + num_bytes
> end of range + 1
:raises RangeAlreadyComplete: if begin + num_bytes == end of range + 1
"""
if 'Range' in self.backend_headers:
req_range = Range(self.backend_headers['Range'])
begin, end = req_range.ranges[0]
if begin is None:
# this is a -50 range req (last 50 bytes of file)
end -= num_bytes
if end == 0:
# we sent out exactly the first range's worth of bytes, so
# we're done with it
raise RangeAlreadyComplete()
else:
begin += num_bytes
if end is not None and begin == end + 1:
# we sent out exactly the first range's worth of bytes, so
# we're done with it
raise RangeAlreadyComplete()
if end is not None and (begin > end or end < 0):
raise HTTPRequestedRangeNotSatisfiable()
req_range.ranges = [(begin, end)] + req_range.ranges[1:]
self.backend_headers['Range'] = str(req_range)
else:
self.backend_headers['Range'] = 'bytes=%d-' % num_bytes
def pop_range(self):
"""
Remove the first byterange from our Range header.
This is used after a byterange has been completely sent to the
client; this way, should we need to resume the download from another
object server, we do not re-fetch byteranges that the client already
has.
If we have no Range header, this is a no-op.
"""
if 'Range' in self.backend_headers:
try:
req_range = Range(self.backend_headers['Range'])
except ValueError:
# there's a Range header, but it's garbage, so get rid of it
self.backend_headers.pop('Range')
return
begin, end = req_range.ranges.pop(0)
if len(req_range.ranges) > 0:
self.backend_headers['Range'] = str(req_range)
else:
self.backend_headers.pop('Range')
def learn_size_from_content_range(self, start, end, length):
"""
If client_chunk_size is set, makes sure we yield things starting on
chunk boundaries based on the Content-Range header in the response.
Sets our Range header's first byterange to the value learned from
the Content-Range header in the response; if we were given a
fully-specified range (e.g. "bytes=123-456"), this is a no-op.
If we were given a half-specified range (e.g. "bytes=123-" or
"bytes=-456"), then this changes the Range header to a
semantically-equivalent one *and* it lets us resume on a proper
boundary instead of just in the middle of a piece somewhere.
"""
if length == 0:
return
if self.client_chunk_size:
self.skip_bytes = bytes_to_skip(self.client_chunk_size, start)
if 'Range' in self.backend_headers:
try:
req_range = Range(self.backend_headers['Range'])
new_ranges = [(start, end)] + req_range.ranges[1:]
except ValueError:
new_ranges = [(start, end)]
else:
new_ranges = [(start, end)]
self.backend_headers['Range'] = (
"bytes=" + (",".join("%s-%s" % (s if s is not None else '',
e if e is not None else '')
for s, e in new_ranges)))
def is_good_source(self, src):
"""
Indicates whether or not the request made to the backend found
what it was looking for.
:param src: the response from the backend
:returns: True if found, False if not
"""
if self.server_type == 'Object' and src.status == 416:
return True
return is_success(src.status) or is_redirection(src.status)
def response_parts_iter(self, req):
source, node = self._get_source_and_node()
it = None
if source:
it = self._get_response_parts_iter(req, node, source)
return it
def _get_response_parts_iter(self, req, node, source):
# Someday we can replace this [mess] with python 3's "nonlocal"
source = [source]
node = [node]
try:
client_chunk_size = self.client_chunk_size
node_timeout = self.app.node_timeout
if self.server_type == 'Object':
node_timeout = self.app.recoverable_node_timeout
# This is safe; it sets up a generator but does not call next()
# on it, so no IO is performed.
parts_iter = [
http_response_to_document_iters(
source[0], read_chunk_size=self.app.object_chunk_size)]
def get_next_doc_part():
while True:
try:
# This call to next() performs IO when we have a
# multipart/byteranges response; it reads the MIME
# boundary and part headers.
#
# If we don't have a multipart/byteranges response,
# but just a 200 or a single-range 206, then this
# performs no IO, and either just returns source or
# raises StopIteration.
with ChunkReadTimeout(node_timeout):
# if StopIteration is raised, it escapes and is
# handled elsewhere
start_byte, end_byte, length, headers, part = next(
parts_iter[0])
return (start_byte, end_byte, length, headers, part)
except ChunkReadTimeout:
new_source, new_node = self._get_source_and_node()
if new_source:
self.app.exception_occurred(
node[0], _('Object'),
_('Trying to read during GET (retrying)'))
# Close-out the connection as best as possible.
if getattr(source[0], 'swift_conn', None):
close_swift_conn(source[0])
source[0] = new_source
node[0] = new_node
# This is safe; it sets up a generator but does
# not call next() on it, so no IO is performed.
parts_iter[0] = http_response_to_document_iters(
new_source,
read_chunk_size=self.app.object_chunk_size)
else:
raise StopIteration()
def iter_bytes_from_response_part(part_file):
nchunks = 0
buf = ''
while True:
try:
with ChunkReadTimeout(node_timeout):
chunk = part_file.read(self.app.object_chunk_size)
nchunks += 1
buf += chunk
except ChunkReadTimeout:
exc_type, exc_value, exc_traceback = exc_info()
if self.newest or self.server_type != 'Object':
six.reraise(exc_type, exc_value, exc_traceback)
try:
self.fast_forward(self.bytes_used_from_backend)
except (HTTPException, ValueError):
six.reraise(exc_type, exc_value, exc_traceback)
except RangeAlreadyComplete:
break
buf = ''
new_source, new_node = self._get_source_and_node()
if new_source:
self.app.exception_occurred(
node[0], _('Object'),
_('Trying to read during GET (retrying)'))
# Close-out the connection as best as possible.
if getattr(source[0], 'swift_conn', None):
close_swift_conn(source[0])
source[0] = new_source
node[0] = new_node
# This is safe; it just sets up a generator but
# does not call next() on it, so no IO is
# performed.
parts_iter[0] = http_response_to_document_iters(
new_source,
read_chunk_size=self.app.object_chunk_size)
try:
_junk, _junk, _junk, _junk, part_file = \
get_next_doc_part()
except StopIteration:
# Tried to find a new node from which to
# finish the GET, but failed. There's
# nothing more to do here.
return
else:
six.reraise(exc_type, exc_value, exc_traceback)
else:
if buf and self.skip_bytes:
if self.skip_bytes < len(buf):
buf = buf[self.skip_bytes:]
self.bytes_used_from_backend += self.skip_bytes
self.skip_bytes = 0
else:
self.skip_bytes -= len(buf)
self.bytes_used_from_backend += len(buf)
buf = ''
if not chunk:
if buf:
with ChunkWriteTimeout(
self.app.client_timeout):
self.bytes_used_from_backend += len(buf)
yield buf
buf = ''
break
if client_chunk_size is not None:
while len(buf) >= client_chunk_size:
client_chunk = buf[:client_chunk_size]
buf = buf[client_chunk_size:]
with ChunkWriteTimeout(
self.app.client_timeout):
self.bytes_used_from_backend += \
len(client_chunk)
yield client_chunk
else:
with ChunkWriteTimeout(self.app.client_timeout):
self.bytes_used_from_backend += len(buf)
yield buf
buf = ''
# This is for fairness; if the network is outpacing
# the CPU, we'll always be able to read and write
# data without encountering an EWOULDBLOCK, and so
# eventlet will not switch greenthreads on its own.
# We do it manually so that clients don't starve.
#
# The number 5 here was chosen by making stuff up.
# It's not every single chunk, but it's not too big
# either, so it seemed like it would probably be an
# okay choice.
#
# Note that we may trampoline to other greenthreads
# more often than once every 5 chunks, depending on
# how blocking our network IO is; the explicit sleep
# here simply provides a lower bound on the rate of
# trampolining.
if nchunks % 5 == 0:
sleep()
part_iter = None
try:
while True:
start_byte, end_byte, length, headers, part = \
get_next_doc_part()
self.learn_size_from_content_range(
start_byte, end_byte, length)
self.bytes_used_from_backend = 0
part_iter = iter_bytes_from_response_part(part)
yield {'start_byte': start_byte, 'end_byte': end_byte,
'entity_length': length, 'headers': headers,
'part_iter': part_iter}
self.pop_range()
except StopIteration:
req.environ['swift.non_client_disconnect'] = True
finally:
if part_iter:
part_iter.close()
except ChunkReadTimeout:
self.app.exception_occurred(node[0], _('Object'),
_('Trying to read during GET'))
raise
except ChunkWriteTimeout:
self.app.logger.warning(
_('Client did not read from proxy within %ss') %
self.app.client_timeout)
self.app.logger.increment('client_timeouts')
except GeneratorExit:
exc_type, exc_value, exc_traceback = exc_info()
warn = True
try:
req_range = Range(self.backend_headers['Range'])
except ValueError:
req_range = None
if req_range and len(req_range.ranges) == 1:
begin, end = req_range.ranges[0]
if end is not None and begin is not None:
if end - begin + 1 == self.bytes_used_from_backend:
warn = False
if not req.environ.get('swift.non_client_disconnect') and warn:
self.app.logger.warning(_('Client disconnected on read'))
six.reraise(exc_type, exc_value, exc_traceback)
except Exception:
self.app.logger.exception(_('Trying to send to client'))
raise
finally:
# Close-out the connection as best as possible.
if getattr(source[0], 'swift_conn', None):
close_swift_conn(source[0])
@property
def last_status(self):
if self.statuses:
return self.statuses[-1]
else:
return None
@property
def last_headers(self):
if self.source_headers:
return HeaderKeyDict(self.source_headers[-1])
else:
return None
def _make_node_request(self, node, node_timeout, logger_thread_locals):
self.app.logger.thread_locals = logger_thread_locals
if node in self.used_nodes:
return False
req_headers = dict(self.backend_headers)
# a request may be specialised with specific backend headers
if self.header_provider:
req_headers.update(self.header_provider())
start_node_timing = time.time()
try:
with ConnectionTimeout(self.app.conn_timeout):
conn = http_connect(
node['ip'], node['port'], node['device'],
self.partition, self.req_method, self.path,
headers=req_headers,
query_string=self.req_query_string)
self.app.set_node_timing(node, time.time() - start_node_timing)
with Timeout(node_timeout):
possible_source = conn.getresponse()
# See NOTE: swift_conn at top of file about this.
possible_source.swift_conn = conn
except (Exception, Timeout):
self.app.exception_occurred(
node, self.server_type,
_('Trying to %(method)s %(path)s') %
{'method': self.req_method, 'path': self.req_path})
return False
if self.is_good_source(possible_source):
# 404 if we know we don't have a synced copy
if not float(possible_source.getheader('X-PUT-Timestamp', 1)):
self.statuses.append(HTTP_NOT_FOUND)
self.reasons.append('')
self.bodies.append('')
self.source_headers.append([])
close_swift_conn(possible_source)
else:
if self.used_source_etag:
src_headers = dict(
(k.lower(), v) for k, v in
possible_source.getheaders())
if self.used_source_etag != src_headers.get(
'x-object-sysmeta-ec-etag',
src_headers.get('etag', '')).strip('"'):
self.statuses.append(HTTP_NOT_FOUND)
self.reasons.append('')
self.bodies.append('')
self.source_headers.append([])
return False
self.statuses.append(possible_source.status)
self.reasons.append(possible_source.reason)
self.bodies.append(None)
self.source_headers.append(possible_source.getheaders())
self.sources.append((possible_source, node))
if not self.newest: # one good source is enough
return True
else:
self.statuses.append(possible_source.status)
self.reasons.append(possible_source.reason)
self.bodies.append(possible_source.read())
self.source_headers.append(possible_source.getheaders())
if possible_source.status == HTTP_INSUFFICIENT_STORAGE:
self.app.error_limit(node, _('ERROR Insufficient Storage'))
elif is_server_error(possible_source.status):
self.app.error_occurred(
node, _('ERROR %(status)d %(body)s '
'From %(type)s Server') %
{'status': possible_source.status,
'body': self.bodies[-1][:1024],
'type': self.server_type})
return False
def _get_source_and_node(self):
self.statuses = []
self.reasons = []
self.bodies = []
self.source_headers = []
self.sources = []
nodes = GreenthreadSafeIterator(self.node_iter)
node_timeout = self.app.node_timeout
if self.server_type == 'Object' and not self.newest:
node_timeout = self.app.recoverable_node_timeout
pile = GreenAsyncPile(self.concurrency)
for node in nodes:
pile.spawn(self._make_node_request, node, node_timeout,
self.app.logger.thread_locals)
_timeout = self.app.concurrency_timeout \
if pile.inflight < self.concurrency else None
if pile.waitfirst(_timeout):
break
else:
# ran out of nodes, see if any stragglers will finish
any(pile)
if self.sources:
self.sources.sort(key=lambda s: source_key(s[0]))
source, node = self.sources.pop()
for src, _junk in self.sources:
close_swift_conn(src)
self.used_nodes.append(node)
src_headers = dict(
(k.lower(), v) for k, v in
source.getheaders())
# Save off the source etag so that, if we lose the connection
# and have to resume from a different node, we can be sure that
# we have the same object (replication) or a fragment archive
# from the same object (EC). Otherwise, if the cluster has two
# versions of the same object, we might end up switching between
# old and new mid-stream and giving garbage to the client.
self.used_source_etag = src_headers.get(
'x-object-sysmeta-ec-etag',
src_headers.get('etag', '')).strip('"')
self.node = node
return source, node
return None, None
class GetOrHeadHandler(ResumingGetter):
def _make_app_iter(self, req, node, source):
"""
Returns an iterator over the contents of the source (via its read
func). There is also quite a bit of cleanup to ensure garbage
collection works and the underlying socket of the source is closed.
:param req: incoming request object
:param source: The httplib.Response object this iterator should read
from.
:param node: The node the source is reading from, for logging purposes.
"""
ct = source.getheader('Content-Type')
if ct:
content_type, content_type_attrs = parse_content_type(ct)
is_multipart = content_type == 'multipart/byteranges'
else:
is_multipart = False
boundary = "dontcare"
if is_multipart:
# we need some MIME boundary; fortunately, the object server has
# furnished one for us, so we'll just re-use it
boundary = dict(content_type_attrs)["boundary"]
parts_iter = self._get_response_parts_iter(req, node, source)
def add_content_type(response_part):
response_part["content_type"] = \
HeaderKeyDict(response_part["headers"]).get("Content-Type")
return response_part
return document_iters_to_http_response_body(
(add_content_type(pi) for pi in parts_iter),
boundary, is_multipart, self.app.logger)
def get_working_response(self, req):
source, node = self._get_source_and_node()
res = None
if source:
res = Response(request=req)
res.status = source.status
update_headers(res, source.getheaders())
if req.method == 'GET' and \
source.status in (HTTP_OK, HTTP_PARTIAL_CONTENT):
res.app_iter = self._make_app_iter(req, node, source)
# See NOTE: swift_conn at top of file about this.
res.swift_conn = source.swift_conn
if not res.environ:
res.environ = {}
res.environ['swift_x_timestamp'] = \
source.getheader('x-timestamp')
res.accept_ranges = 'bytes'
res.content_length = source.getheader('Content-Length')
if source.getheader('Content-Type'):
res.charset = None
res.content_type = source.getheader('Content-Type')
return res
class NodeIter(object):
"""
Yields nodes for a ring partition, skipping over error
limited nodes and stopping at the configurable number of nodes. If a
node yielded subsequently gets error limited, an extra node will be
yielded to take its place.
Note that if you're going to iterate over this concurrently from
multiple greenthreads, you'll want to use a
swift.common.utils.GreenthreadSafeIterator to serialize access.
Otherwise, you may get ValueErrors from concurrent access. (You also
may not, depending on how logging is configured, the vagaries of
socket IO and eventlet, and the phase of the moon.)
:param app: a proxy app
:param ring: ring to get yield nodes from
:param partition: ring partition to yield nodes for
:param node_iter: optional iterable of nodes to try. Useful if you
want to filter or reorder the nodes.
:param policy: an instance of :class:`BaseStoragePolicy`. This should be
None for an account or container ring.
"""
def __init__(self, app, ring, partition, node_iter=None, policy=None):
self.app = app
self.ring = ring
self.partition = partition
part_nodes = ring.get_part_nodes(partition)
if node_iter is None:
node_iter = itertools.chain(
part_nodes, ring.get_more_nodes(partition))
num_primary_nodes = len(part_nodes)
self.nodes_left = self.app.request_node_count(num_primary_nodes)
self.expected_handoffs = self.nodes_left - num_primary_nodes
# Use of list() here forcibly yanks the first N nodes (the primary
# nodes) from node_iter, so the rest of its values are handoffs.
self.primary_nodes = self.app.sort_nodes(
list(itertools.islice(node_iter, num_primary_nodes)),
policy=policy)
self.handoff_iter = node_iter
self._node_provider = None
def __iter__(self):
self._node_iter = self._node_gen()
return self
def log_handoffs(self, handoffs):
"""
Log handoff requests if handoff logging is enabled and the
handoff was not expected.
We only log handoffs when we've pushed the handoff count further
than we would normally have expected under normal circumstances,
that is (request_node_count - num_primaries), when handoffs goes
higher than that it means one of the primaries must have been
skipped because of error limiting before we consumed all of our
nodes_left.
"""
if not self.app.log_handoffs:
return
extra_handoffs = handoffs - self.expected_handoffs
if extra_handoffs > 0:
self.app.logger.increment('handoff_count')
self.app.logger.warning(
'Handoff requested (%d)' % handoffs)
if (extra_handoffs == len(self.primary_nodes)):
# all the primaries were skipped, and handoffs didn't help
self.app.logger.increment('handoff_all_count')
def set_node_provider(self, callback):
"""
Install a callback function that will be used during a call to next()
to get an alternate node instead of returning the next node from the
iterator.
:param callback: A no argument function that should return a node dict
or None.
"""
self._node_provider = callback
def _node_gen(self):
for node in self.primary_nodes:
if not self.app.error_limited(node):
yield node
if not self.app.error_limited(node):
self.nodes_left -= 1
if self.nodes_left <= 0:
return
handoffs = 0
for node in self.handoff_iter:
if not self.app.error_limited(node):
handoffs += 1
self.log_handoffs(handoffs)
yield node
if not self.app.error_limited(node):
self.nodes_left -= 1
if self.nodes_left <= 0:
return
def next(self):
if self._node_provider:
# give node provider the opportunity to inject a node
node = self._node_provider()
if node:
return node
return next(self._node_iter)
def __next__(self):
return self.next()
class Controller(object):
"""Base WSGI controller class for the proxy"""
server_type = 'Base'
# Ensure these are all lowercase
pass_through_headers = []
def __init__(self, app):
"""
Creates a controller attached to an application instance
:param app: the application instance
"""
self.account_name = None
self.app = app
self.trans_id = '-'
self._allowed_methods = None
@property
def allowed_methods(self):
if self._allowed_methods is None:
self._allowed_methods = set()
all_methods = inspect.getmembers(self, predicate=inspect.ismethod)
for name, m in all_methods:
if getattr(m, 'publicly_accessible', False):
self._allowed_methods.add(name)
return self._allowed_methods
def _x_remove_headers(self):
"""
Returns a list of headers that must not be sent to the backend
:returns: a list of header
"""
return []
def transfer_headers(self, src_headers, dst_headers):
"""
Transfer legal headers from an original client request to dictionary
that will be used as headers by the backend request
:param src_headers: A dictionary of the original client request headers
:param dst_headers: A dictionary of the backend request headers
"""
st = self.server_type.lower()
x_remove = 'x-remove-%s-meta-' % st
dst_headers.update((k.lower().replace('-remove', '', 1), '')
for k in src_headers
if k.lower().startswith(x_remove) or
k.lower() in self._x_remove_headers())
dst_headers.update((k.lower(), v)
for k, v in src_headers.items()
if k.lower() in self.pass_through_headers or
is_sys_or_user_meta(st, k))
def generate_request_headers(self, orig_req=None, additional=None,
transfer=False):
"""
Create a list of headers to be used in backend requests
:param orig_req: the original request sent by the client to the proxy
:param additional: additional headers to send to the backend
:param transfer: If True, transfer headers from original client request
:returns: a dictionary of headers
"""
# Use the additional headers first so they don't overwrite the headers
# we require.
headers = HeaderKeyDict(additional) if additional else HeaderKeyDict()
if transfer:
self.transfer_headers(orig_req.headers, headers)
headers.setdefault('x-timestamp', Timestamp.now().internal)
if orig_req:
referer = orig_req.as_referer()
else:
referer = ''
headers['x-trans-id'] = self.trans_id
headers['connection'] = 'close'
headers['user-agent'] = 'proxy-server %s' % os.getpid()
headers['referer'] = referer
return headers
def account_info(self, account, req=None):
"""
Get account information, and also verify that the account exists.
:param account: name of the account to get the info for
:param req: caller's HTTP request context object (optional)
:returns: tuple of (account partition, account nodes, container_count)
or (None, None, None) if it does not exist
"""
partition, nodes = self.app.account_ring.get_nodes(account)
if req:
env = getattr(req, 'environ', {})
else:
env = {}
env.setdefault('swift.infocache', {})
path_env = env.copy()
path_env['PATH_INFO'] = "/v1/%s" % (account,)
info = get_account_info(path_env, self.app)
if (not info
or not is_success(info['status'])
or not info.get('account_really_exists', True)):
return None, None, None
container_count = info['container_count']
return partition, nodes, container_count
def container_info(self, account, container, req=None):
"""
Get container information and thusly verify container existence.
This will also verify account existence.
:param account: account name for the container
:param container: container name to look up
:param req: caller's HTTP request context object (optional)
:returns: dict containing at least container partition ('partition'),
container nodes ('containers'), container read
acl ('read_acl'), container write acl ('write_acl'),
and container sync key ('sync_key').
Values are set to None if the container does not exist.
"""
part, nodes = self.app.container_ring.get_nodes(account, container)
if req:
env = getattr(req, 'environ', {})
else:
env = {}
env.setdefault('swift.infocache', {})
path_env = env.copy()
path_env['PATH_INFO'] = "/v1/%s/%s" % (account, container)
info = get_container_info(path_env, self.app)
if not info or not is_success(info.get('status')):
info = headers_to_container_info({}, 0)
info['partition'] = None
info['nodes'] = None
else:
info['partition'] = part
info['nodes'] = nodes
return info
def _make_request(self, nodes, part, method, path, headers, query,
logger_thread_locals):
"""
Iterates over the given node iterator, sending an HTTP request to one
node at a time. The first non-informational, non-server-error
response is returned. If no non-informational, non-server-error
response is received from any of the nodes, returns None.
:param nodes: an iterator of the backend server and handoff servers
:param part: the partition number
:param method: the method to send to the backend
:param path: the path to send to the backend
(full path ends up being /<$device>/<$part>/<$path>)
:param headers: dictionary of headers
:param query: query string to send to the backend.
:param logger_thread_locals: The thread local values to be set on the
self.app.logger to retain transaction
logging information.
:returns: a swob.Response object, or None if no responses were received
"""
self.app.logger.thread_locals = logger_thread_locals
for node in nodes:
try:
start_node_timing = time.time()
with ConnectionTimeout(self.app.conn_timeout):
conn = http_connect(node['ip'], node['port'],
node['device'], part, method, path,
headers=headers, query_string=query)
conn.node = node
self.app.set_node_timing(node, time.time() - start_node_timing)
with Timeout(self.app.node_timeout):
resp = conn.getresponse()
if not is_informational(resp.status) and \
not is_server_error(resp.status):
return resp.status, resp.reason, resp.getheaders(), \
resp.read()
elif resp.status == HTTP_INSUFFICIENT_STORAGE:
self.app.error_limit(node,
_('ERROR Insufficient Storage'))
elif is_server_error(resp.status):
self.app.error_occurred(
node, _('ERROR %(status)d '
'Trying to %(method)s %(path)s'
' From %(type)s Server') % {
'status': resp.status,
'method': method,
'path': path,
'type': self.server_type})
except (Exception, Timeout):
self.app.exception_occurred(
node, self.server_type,
_('Trying to %(method)s %(path)s') %
{'method': method, 'path': path})
def make_requests(self, req, ring, part, method, path, headers,
query_string='', overrides=None, node_count=None,
node_iterator=None):
"""
Sends an HTTP request to multiple nodes and aggregates the results.
It attempts the primary nodes concurrently, then iterates over the
handoff nodes as needed.
:param req: a request sent by the client
:param ring: the ring used for finding backend servers
:param part: the partition number
:param method: the method to send to the backend
:param path: the path to send to the backend
(full path ends up being /<$device>/<$part>/<$path>)
:param headers: a list of dicts, where each dict represents one
backend request that should be made.
:param query_string: optional query string to send to the backend
:param overrides: optional return status override map used to override
the returned status of a request.
:param node_count: optional number of nodes to send request to.
:param node_iterator: optional node iterator.
:returns: a swob.Response object
"""
nodes = GreenthreadSafeIterator(
node_iterator or self.app.iter_nodes(ring, part)
)
node_number = node_count or len(ring.get_part_nodes(part))
pile = GreenAsyncPile(node_number)
for head in headers:
pile.spawn(self._make_request, nodes, part, method, path,
head, query_string, self.app.logger.thread_locals)
response = []
statuses = []
for resp in pile:
if not resp:
continue
response.append(resp)
statuses.append(resp[0])
if self.have_quorum(statuses, node_number):
break
# give any pending requests *some* chance to finish
finished_quickly = pile.waitall(self.app.post_quorum_timeout)
for resp in finished_quickly:
if not resp:
continue
response.append(resp)
statuses.append(resp[0])
while len(response) < node_number:
response.append((HTTP_SERVICE_UNAVAILABLE, '', '', ''))
statuses, reasons, resp_headers, bodies = zip(*response)
return self.best_response(req, statuses, reasons, bodies,
'%s %s' % (self.server_type, req.method),
overrides=overrides, headers=resp_headers)
def _quorum_size(self, n):
"""
Number of successful backend responses needed for the proxy to
consider the client request successful.
"""
return quorum_size(n)
def have_quorum(self, statuses, node_count, quorum=None):
"""
Given a list of statuses from several requests, determine if
a quorum response can already be decided.
:param statuses: list of statuses returned
:param node_count: number of nodes being queried (basically ring count)
:param quorum: number of statuses required for quorum
:returns: True or False, depending on if quorum is established
"""
if quorum is None:
quorum = self._quorum_size(node_count)
if len(statuses) >= quorum:
for hundred in (HTTP_CONTINUE, HTTP_OK, HTTP_MULTIPLE_CHOICES,
HTTP_BAD_REQUEST):
if sum(1 for s in statuses
if hundred <= s < hundred + 100) >= quorum:
return True
return False
def best_response(self, req, statuses, reasons, bodies, server_type,
etag=None, headers=None, overrides=None,
quorum_size=None):
"""
Given a list of responses from several servers, choose the best to
return to the API.
:param req: swob.Request object
:param statuses: list of statuses returned
:param reasons: list of reasons for each status
:param bodies: bodies of each response
:param server_type: type of server the responses came from
:param etag: etag
:param headers: headers of each response
:param overrides: overrides to apply when lacking quorum
:param quorum_size: quorum size to use
:returns: swob.Response object with the correct status, body, etc. set
"""
if quorum_size is None:
quorum_size = self._quorum_size(len(statuses))
resp = self._compute_quorum_response(
req, statuses, reasons, bodies, etag, headers,
quorum_size=quorum_size)
if overrides and not resp:
faked_up_status_indices = set()
transformed = []
for (i, (status, reason, hdrs, body)) in enumerate(zip(
statuses, reasons, headers, bodies)):
if status in overrides:
faked_up_status_indices.add(i)
transformed.append((overrides[status], '', '', ''))
else:
transformed.append((status, reason, hdrs, body))
statuses, reasons, headers, bodies = zip(*transformed)
resp = self._compute_quorum_response(
req, statuses, reasons, bodies, etag, headers,
indices_to_avoid=faked_up_status_indices,
quorum_size=quorum_size)
if not resp:
resp = HTTPServiceUnavailable(request=req)
self.app.logger.error(_('%(type)s returning 503 for %(statuses)s'),
{'type': server_type, 'statuses': statuses})
return resp
def _compute_quorum_response(self, req, statuses, reasons, bodies, etag,
headers, quorum_size, indices_to_avoid=()):
if not statuses:
return None
for hundred in (HTTP_OK, HTTP_MULTIPLE_CHOICES, HTTP_BAD_REQUEST):
hstatuses = \
[(i, s) for i, s in enumerate(statuses)
if hundred <= s < hundred + 100]
if len(hstatuses) >= quorum_size:
try:
status_index, status = max(
((i, stat) for i, stat in hstatuses
if i not in indices_to_avoid),
key=operator.itemgetter(1))
except ValueError:
# All statuses were indices to avoid
continue
resp = status_map[status](request=req)
resp.status = '%s %s' % (status, reasons[status_index])
resp.body = bodies[status_index]
if headers:
update_headers(resp, headers[status_index])
if etag:
resp.headers['etag'] = etag.strip('"')
return resp
return None
@public
def GET(self, req):
"""
Handler for HTTP GET requests.
:param req: The client request
:returns: the response to the client
"""
return self.GETorHEAD(req)
@public
def HEAD(self, req):
"""
Handler for HTTP HEAD requests.
:param req: The client request
:returns: the response to the client
"""
return self.GETorHEAD(req)
def autocreate_account(self, req, account):
"""
Autocreate an account
:param req: request leading to this autocreate
:param account: the unquoted account name
"""
partition, nodes = self.app.account_ring.get_nodes(account)
path = '/%s' % account
headers = {'X-Timestamp': Timestamp.now().internal,
'X-Trans-Id': self.trans_id,
'X-Openstack-Request-Id': self.trans_id,
'Connection': 'close'}
# transfer any x-account-sysmeta headers from original request
# to the autocreate PUT
headers.update((k, v)
for k, v in req.headers.items()
if is_sys_meta('account', k))
resp = self.make_requests(Request.blank('/v1' + path),
self.app.account_ring, partition, 'PUT',
path, [headers] * len(nodes))
if is_success(resp.status_int):
self.app.logger.info(_('autocreate account %r'), path)
clear_info_cache(self.app, req.environ, account)
else:
self.app.logger.warning(_('Could not autocreate account %r'),
path)
def GETorHEAD_base(self, req, server_type, node_iter, partition, path,
concurrency=1, client_chunk_size=None):
"""
Base handler for HTTP GET or HEAD requests.
:param req: swob.Request object
:param server_type: server type used in logging
:param node_iter: an iterator to obtain nodes from
:param partition: partition
:param path: path for the request
:param concurrency: number of requests to run concurrently
:param client_chunk_size: chunk size for response body iterator
:returns: swob.Response object
"""
backend_headers = self.generate_request_headers(
req, additional=req.headers)
handler = GetOrHeadHandler(self.app, req, self.server_type, node_iter,
partition, path, backend_headers,
concurrency,
client_chunk_size=client_chunk_size)
res = handler.get_working_response(req)
if not res:
res = self.best_response(
req, handler.statuses, handler.reasons, handler.bodies,
'%s %s' % (server_type, req.method),
headers=handler.source_headers)
# if a backend policy index is present in resp headers, translate it
# here with the friendly policy name
if 'X-Backend-Storage-Policy-Index' in res.headers and \
is_success(res.status_int):
policy = \
POLICIES.get_by_index(
res.headers['X-Backend-Storage-Policy-Index'])
if policy:
res.headers['X-Storage-Policy'] = policy.name
else:
self.app.logger.error(
'Could not translate %s (%r) from %r to policy',
'X-Backend-Storage-Policy-Index',
res.headers['X-Backend-Storage-Policy-Index'], path)
return res
def is_origin_allowed(self, cors_info, origin):
"""
Is the given Origin allowed to make requests to this resource
:param cors_info: the resource's CORS related metadata headers
:param origin: the origin making the request
:return: True or False
"""
allowed_origins = set()
if cors_info.get('allow_origin'):
allowed_origins.update(
[a.strip()
for a in cors_info['allow_origin'].split(' ')
if a.strip()])
if self.app.cors_allow_origin:
allowed_origins.update(self.app.cors_allow_origin)
return origin in allowed_origins or '*' in allowed_origins
@public
def OPTIONS(self, req):
"""
Base handler for OPTIONS requests
:param req: swob.Request object
:returns: swob.Response object
"""
# Prepare the default response
headers = {'Allow': ', '.join(self.allowed_methods)}
resp = Response(status=200, request=req, headers=headers)
# If this isn't a CORS pre-flight request then return now
req_origin_value = req.headers.get('Origin', None)
if not req_origin_value:
return resp
# This is a CORS preflight request so check it's allowed
try:
container_info = \
self.container_info(self.account_name,
self.container_name, req)
except AttributeError:
# This should only happen for requests to the Account. A future
# change could allow CORS requests to the Account level as well.
return resp
cors = container_info.get('cors', {})
# If the CORS origin isn't allowed return a 401
if not self.is_origin_allowed(cors, req_origin_value) or (
req.headers.get('Access-Control-Request-Method') not in
self.allowed_methods):
resp.status = HTTP_UNAUTHORIZED
return resp
# Populate the response with the CORS preflight headers
if cors.get('allow_origin') and \
cors.get('allow_origin').strip() == '*':
headers['access-control-allow-origin'] = '*'
else:
headers['access-control-allow-origin'] = req_origin_value
if 'vary' in headers:
headers['vary'] += ', Origin'
else:
headers['vary'] = 'Origin'
if cors.get('max_age') is not None:
headers['access-control-max-age'] = cors.get('max_age')
headers['access-control-allow-methods'] = \
', '.join(self.allowed_methods)
# Allow all headers requested in the request. The CORS
# specification does leave the door open for this, as mentioned in
# http://www.w3.org/TR/cors/#resource-preflight-requests
# Note: Since the list of headers can be unbounded
# simply returning headers can be enough.
allow_headers = set(
list_from_csv(req.headers.get('Access-Control-Request-Headers')))
if allow_headers:
headers['access-control-allow-headers'] = ', '.join(allow_headers)
if 'vary' in headers:
headers['vary'] += ', Access-Control-Request-Headers'
else:
headers['vary'] = 'Access-Control-Request-Headers'
resp.headers = headers
return resp
| 41.241219 | 79 | 0.585311 |
# source bufferedhttp connection of whatever it is attached to.
# It is used when early termination of reading from the connection should
# happen, such as when a range request is satisfied but there's still more the
from six.moves.urllib.parse import quote
import os
import time
import functools
import inspect
import itertools
import operator
from copy import deepcopy
from sys import exc_info
from swift import gettext_ as _
from eventlet import sleep
from eventlet.timeout import Timeout
import six
from swift.common.wsgi import make_pre_authed_env
from swift.common.utils import Timestamp, config_true_value, \
public, split_path, list_from_csv, GreenthreadSafeIterator, \
GreenAsyncPile, quorum_size, parse_content_type, \
document_iters_to_http_response_body
from swift.common.bufferedhttp import http_connect
from swift.common.exceptions import ChunkReadTimeout, ChunkWriteTimeout, \
ConnectionTimeout, RangeAlreadyComplete
from swift.common.header_key_dict import HeaderKeyDict
from swift.common.http import is_informational, is_success, is_redirection, \
is_server_error, HTTP_OK, HTTP_PARTIAL_CONTENT, HTTP_MULTIPLE_CHOICES, \
HTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_SERVICE_UNAVAILABLE, \
HTTP_INSUFFICIENT_STORAGE, HTTP_UNAUTHORIZED, HTTP_CONTINUE, HTTP_GONE
from swift.common.swob import Request, Response, Range, \
HTTPException, HTTPRequestedRangeNotSatisfiable, HTTPServiceUnavailable, \
status_map
from swift.common.request_helpers import strip_sys_meta_prefix, \
strip_user_meta_prefix, is_user_meta, is_sys_meta, is_sys_or_user_meta, \
http_response_to_document_iters, is_object_transient_sysmeta, \
strip_object_transient_sysmeta_prefix
from swift.common.storage_policy import POLICIES
DEFAULT_RECHECK_ACCOUNT_EXISTENCE = 60 # seconds
DEFAULT_RECHECK_CONTAINER_EXISTENCE = 60 # seconds
def update_headers(response, headers):
if hasattr(headers, 'items'):
headers = headers.items()
for name, value in headers:
if name == 'etag':
response.headers[name] = value.replace('"', '')
elif name.lower() not in (
'date', 'content-length', 'content-type',
'connection', 'x-put-timestamp', 'x-delete-after'):
response.headers[name] = value
def source_key(resp):
return Timestamp(resp.getheader('x-backend-timestamp') or
resp.getheader('x-put-timestamp') or
resp.getheader('x-timestamp') or 0)
def delay_denial(func):
func.delay_denial = True
return func
def _prep_headers_to_info(headers, server_type):
meta = {}
sysmeta = {}
other = {}
for key, val in dict(headers).items():
lkey = key.lower()
if is_user_meta(server_type, lkey):
meta[strip_user_meta_prefix(server_type, lkey)] = val
elif is_sys_meta(server_type, lkey):
sysmeta[strip_sys_meta_prefix(server_type, lkey)] = val
else:
other[lkey] = val
return other, meta, sysmeta
def headers_to_account_info(headers, status_int=HTTP_OK):
headers, meta, sysmeta = _prep_headers_to_info(headers, 'account')
account_info = {
'status': status_int,
# 'container_count' anomaly:
# Previous code sometimes expects an int sometimes a string
# Current code aligns to str and None, yet translates to int in
# deprecated functions as needed
'container_count': headers.get('x-account-container-count'),
'total_object_count': headers.get('x-account-object-count'),
'bytes': headers.get('x-account-bytes-used'),
'meta': meta,
'sysmeta': sysmeta,
}
if is_success(status_int):
account_info['account_really_exists'] = not config_true_value(
headers.get('x-backend-fake-account-listing'))
return account_info
def headers_to_container_info(headers, status_int=HTTP_OK):
headers, meta, sysmeta = _prep_headers_to_info(headers, 'container')
return {
'status': status_int,
'read_acl': headers.get('x-container-read'),
'write_acl': headers.get('x-container-write'),
'sync_key': headers.get('x-container-sync-key'),
'object_count': headers.get('x-container-object-count'),
'bytes': headers.get('x-container-bytes-used'),
'versions': headers.get('x-versions-location'),
'storage_policy': headers.get('x-backend-storage-policy-index', '0'),
'cors': {
'allow_origin': meta.get('access-control-allow-origin'),
'expose_headers': meta.get('access-control-expose-headers'),
'max_age': meta.get('access-control-max-age')
},
'meta': meta,
'sysmeta': sysmeta,
}
def headers_to_object_info(headers, status_int=HTTP_OK):
headers, meta, sysmeta = _prep_headers_to_info(headers, 'object')
transient_sysmeta = {}
for key, val in six.iteritems(headers):
if is_object_transient_sysmeta(key):
key = strip_object_transient_sysmeta_prefix(key.lower())
transient_sysmeta[key] = val
info = {'status': status_int,
'length': headers.get('content-length'),
'type': headers.get('content-type'),
'etag': headers.get('etag'),
'meta': meta,
'sysmeta': sysmeta,
'transient_sysmeta': transient_sysmeta
}
return info
def cors_validation(func):
@functools.wraps(func)
def wrapped(*a, **kw):
controller = a[0]
req = a[1]
# The logic here was interpreted from
# http://www.w3.org/TR/cors/#resource-requests
# Is this a CORS request?
req_origin = req.headers.get('Origin', None)
if req_origin:
# Yes, this is a CORS request so test if the origin is allowed
container_info = \
controller.container_info(controller.account_name,
controller.container_name, req)
cors_info = container_info.get('cors', {})
# Call through to the decorated method
resp = func(*a, **kw)
if controller.app.strict_cors_mode and \
not controller.is_origin_allowed(cors_info, req_origin):
return resp
# Expose,
# - simple response headers,
# http://www.w3.org/TR/cors/#simple-response-header
# - swift specific: etag, x-timestamp, x-trans-id
# - headers provided by the operator in cors_expose_headers
# - user metadata headers
# - headers provided by the user in
# x-container-meta-access-control-expose-headers
if 'Access-Control-Expose-Headers' not in resp.headers:
expose_headers = set([
'cache-control', 'content-language', 'content-type',
'expires', 'last-modified', 'pragma', 'etag',
'x-timestamp', 'x-trans-id', 'x-openstack-request-id'])
expose_headers.update(controller.app.cors_expose_headers)
for header in resp.headers:
if header.startswith('X-Container-Meta') or \
header.startswith('X-Object-Meta'):
expose_headers.add(header.lower())
if cors_info.get('expose_headers'):
expose_headers = expose_headers.union(
[header_line.strip().lower()
for header_line in
cors_info['expose_headers'].split(' ')
if header_line.strip()])
resp.headers['Access-Control-Expose-Headers'] = \
', '.join(expose_headers)
# The user agent won't process the response if the Allow-Origin
# header isn't included
if 'Access-Control-Allow-Origin' not in resp.headers:
if cors_info['allow_origin'] and \
cors_info['allow_origin'].strip() == '*':
resp.headers['Access-Control-Allow-Origin'] = '*'
else:
resp.headers['Access-Control-Allow-Origin'] = req_origin
return resp
else:
# Not a CORS request so make the call as normal
return func(*a, **kw)
return wrapped
def get_object_info(env, app, path=None, swift_source=None):
(version, account, container, obj) = \
split_path(path or env['PATH_INFO'], 4, 4, True)
info = _get_object_info(app, env, account, container, obj,
swift_source=swift_source)
if info:
info = deepcopy(info)
else:
info = headers_to_object_info({}, 0)
for field in ('length',):
if info.get(field) is None:
info[field] = 0
else:
info[field] = int(info[field])
return info
def get_container_info(env, app, swift_source=None):
(version, account, container, unused) = \
split_path(env['PATH_INFO'], 3, 4, True)
# Check in environment cache and in memcache (in that order)
info = _get_info_from_caches(app, env, account, container)
if not info:
# Cache miss; go HEAD the container and populate the caches
env.setdefault('swift.infocache', {})
# Before checking the container, make sure the account exists.
#
# If it is an autocreateable account, just assume it exists; don't
# HEAD the account, as a GET or HEAD response for an autocreateable
# account is successful whether the account actually has .db files
# on disk or not.
is_autocreate_account = account.startswith(
getattr(app, 'auto_create_account_prefix', '.'))
if not is_autocreate_account:
account_info = get_account_info(env, app, swift_source)
if not account_info or not is_success(account_info['status']):
return headers_to_container_info({}, 0)
req = _prepare_pre_auth_info_request(
env, ("/%s/%s/%s" % (version, account, container)),
(swift_source or 'GET_CONTAINER_INFO'))
resp = req.get_response(app)
# Check in infocache to see if the proxy (or anyone else) already
# populated the cache for us. If they did, just use what's there.
#
# See similar comment in get_account_info() for justification.
info = _get_info_from_infocache(env, account, container)
if info is None:
info = set_info_cache(app, env, account, container, resp)
if info:
info = deepcopy(info) # avoid mutating what's in swift.infocache
else:
info = headers_to_container_info({}, 0)
# Old data format in memcache immediately after a Swift upgrade; clean
# it up so consumers of get_container_info() aren't exposed to it.
if 'object_count' not in info and 'container_size' in info:
info['object_count'] = info.pop('container_size')
for field in ('storage_policy', 'bytes', 'object_count'):
if info.get(field) is None:
info[field] = 0
else:
info[field] = int(info[field])
return info
def get_account_info(env, app, swift_source=None):
(version, account, _junk, _junk) = \
split_path(env['PATH_INFO'], 2, 4, True)
# Check in environment cache and in memcache (in that order)
info = _get_info_from_caches(app, env, account)
# Cache miss; go HEAD the account and populate the caches
if not info:
env.setdefault('swift.infocache', {})
req = _prepare_pre_auth_info_request(
env, "/%s/%s" % (version, account),
(swift_source or 'GET_ACCOUNT_INFO'))
resp = req.get_response(app)
# Check in infocache to see if the proxy (or anyone else) already
# populated the cache for us. If they did, just use what's there.
#
# The point of this is to avoid setting the value in memcached
# twice. Otherwise, we're needlessly sending requests across the
# network.
#
# If the info didn't make it into the cache, we'll compute it from
# the response and populate the cache ourselves.
#
# Note that this is taking "exists in infocache" to imply "exists in
# memcache". That's because we're trying to avoid superfluous
# network traffic, and checking in memcache prior to setting in
# memcache would defeat the purpose.
info = _get_info_from_infocache(env, account)
if info is None:
info = set_info_cache(app, env, account, None, resp)
if info:
info = info.copy() # avoid mutating what's in swift.infocache
else:
info = headers_to_account_info({}, 0)
for field in ('container_count', 'bytes', 'total_object_count'):
if info.get(field) is None:
info[field] = 0
else:
info[field] = int(info[field])
return info
def get_cache_key(account, container=None, obj=None):
if obj:
if not (account and container):
raise ValueError('Object cache key requires account and container')
cache_key = 'object/%s/%s/%s' % (account, container, obj)
elif container:
if not account:
raise ValueError('Container cache key requires account')
cache_key = 'container/%s/%s' % (account, container)
else:
cache_key = 'account/%s' % account
# Use a unique environment cache key per account and one container.
# This allows caching both account and container and ensures that when we
# copy this env to form a new request, it won't accidentally reuse the
# old container or account info
return cache_key
def set_info_cache(app, env, account, container, resp):
infocache = env.setdefault('swift.infocache', {})
cache_time = None
if container and resp:
cache_time = int(resp.headers.get(
'X-Backend-Recheck-Container-Existence',
DEFAULT_RECHECK_CONTAINER_EXISTENCE))
elif resp:
cache_time = int(resp.headers.get(
'X-Backend-Recheck-Account-Existence',
DEFAULT_RECHECK_ACCOUNT_EXISTENCE))
cache_key = get_cache_key(account, container)
if resp:
if resp.status_int in (HTTP_NOT_FOUND, HTTP_GONE):
cache_time *= 0.1
elif not is_success(resp.status_int):
cache_time = None
# Next actually set both memcache and the env cache
memcache = getattr(app, 'memcache', None) or env.get('swift.cache')
if cache_time is None:
infocache.pop(cache_key, None)
if memcache:
memcache.delete(cache_key)
return
if container:
info = headers_to_container_info(resp.headers, resp.status_int)
else:
info = headers_to_account_info(resp.headers, resp.status_int)
if memcache:
memcache.set(cache_key, info, time=cache_time)
infocache[cache_key] = info
return info
def set_object_info_cache(app, env, account, container, obj, resp):
cache_key = get_cache_key(account, container, obj)
if 'swift.infocache' in env and not resp:
env['swift.infocache'].pop(cache_key, None)
return
info = headers_to_object_info(resp.headers, resp.status_int)
env.setdefault('swift.infocache', {})[cache_key] = info
return info
def clear_info_cache(app, env, account, container=None):
set_info_cache(app, env, account, container, None)
def _get_info_from_infocache(env, account, container=None):
cache_key = get_cache_key(account, container)
if 'swift.infocache' in env and cache_key in env['swift.infocache']:
return env['swift.infocache'][cache_key]
return None
def _get_info_from_memcache(app, env, account, container=None):
cache_key = get_cache_key(account, container)
memcache = getattr(app, 'memcache', None) or env.get('swift.cache')
if memcache:
info = memcache.get(cache_key)
if info:
for key in info:
if isinstance(info[key], six.text_type):
info[key] = info[key].encode("utf-8")
elif isinstance(info[key], dict):
for subkey, value in info[key].items():
if isinstance(value, six.text_type):
info[key][subkey] = value.encode("utf-8")
env.setdefault('swift.infocache', {})[cache_key] = info
return info
return None
def _get_info_from_caches(app, env, account, container=None):
info = _get_info_from_infocache(env, account, container)
if info is None:
info = _get_info_from_memcache(app, env, account, container)
return info
def _prepare_pre_auth_info_request(env, path, swift_source):
# Set the env for the pre_authed call without a query string
newenv = make_pre_authed_env(env, 'HEAD', path, agent='Swift',
query_string='', swift_source=swift_source)
# This is a sub request for container metadata- drop the Origin header from
# the request so the it is not treated as a CORS request.
newenv.pop('HTTP_ORIGIN', None)
# ACLs are only shown to account owners, so let's make sure this request
# looks like it came from the account owner.
newenv['swift_owner'] = True
# Note that Request.blank expects quoted path
return Request.blank(quote(path), environ=newenv)
def get_info(app, env, account, container=None, swift_source=None):
env.setdefault('swift.infocache', {})
if container:
path = '/v1/%s/%s' % (account, container)
path_env = env.copy()
path_env['PATH_INFO'] = path
return get_container_info(path_env, app, swift_source=swift_source)
else:
# account info
path = '/v1/%s' % (account,)
path_env = env.copy()
path_env['PATH_INFO'] = path
return get_account_info(path_env, app, swift_source=swift_source)
def _get_object_info(app, env, account, container, obj, swift_source=None):
cache_key = get_cache_key(account, container, obj)
info = env.get('swift.infocache', {}).get(cache_key)
if info:
return info
# Not in cache, let's try the object servers
path = '/v1/%s/%s/%s' % (account, container, obj)
req = _prepare_pre_auth_info_request(env, path, swift_source)
resp = req.get_response(app)
# Unlike get_account_info() and get_container_info(), we don't save
# things in memcache, so we can store the info without network traffic,
# *and* the proxy doesn't cache object info for us, so there's no chance
# that the object info would be in the environment. Thus, we just
# compute the object info based on the response and stash it in
# swift.infocache.
info = set_object_info_cache(app, env, account, container, obj, resp)
return info
def close_swift_conn(src):
try:
# Since the backends set "Connection: close" in their response
# headers, the response object (src) is solely responsible for the
# socket. The connection object (src.swift_conn) has no references
# to the socket, so calling its close() method does nothing, and
# therefore we don't do it.
#
# Also, since calling the response's close() method might not
# close the underlying socket but only decrement some
# reference-counter, we have a special method here that really,
# really kills the underlying socket with a close() syscall.
src.nuke_from_orbit() # it's the only way to be sure
except Exception:
pass
def bytes_to_skip(record_size, range_start):
return (record_size - (range_start % record_size)) % record_size
class ResumingGetter(object):
def __init__(self, app, req, server_type, node_iter, partition, path,
backend_headers, concurrency=1, client_chunk_size=None,
newest=None, header_provider=None):
self.app = app
self.node_iter = node_iter
self.server_type = server_type
self.partition = partition
self.path = path
self.backend_headers = backend_headers
self.client_chunk_size = client_chunk_size
self.skip_bytes = 0
self.bytes_used_from_backend = 0
self.used_nodes = []
self.used_source_etag = ''
self.concurrency = concurrency
self.node = None
self.header_provider = header_provider
# stuff from request
self.req_method = req.method
self.req_path = req.path
self.req_query_string = req.query_string
if newest is None:
self.newest = config_true_value(req.headers.get('x-newest', 'f'))
else:
self.newest = newest
# populated when finding source
self.statuses = []
self.reasons = []
self.bodies = []
self.source_headers = []
self.sources = []
# populated from response headers
self.start_byte = self.end_byte = self.length = None
def fast_forward(self, num_bytes):
if 'Range' in self.backend_headers:
req_range = Range(self.backend_headers['Range'])
begin, end = req_range.ranges[0]
if begin is None:
# this is a -50 range req (last 50 bytes of file)
end -= num_bytes
if end == 0:
# we sent out exactly the first range's worth of bytes, so
# we're done with it
raise RangeAlreadyComplete()
else:
begin += num_bytes
if end is not None and begin == end + 1:
# we sent out exactly the first range's worth of bytes, so
# we're done with it
raise RangeAlreadyComplete()
if end is not None and (begin > end or end < 0):
raise HTTPRequestedRangeNotSatisfiable()
req_range.ranges = [(begin, end)] + req_range.ranges[1:]
self.backend_headers['Range'] = str(req_range)
else:
self.backend_headers['Range'] = 'bytes=%d-' % num_bytes
def pop_range(self):
if 'Range' in self.backend_headers:
try:
req_range = Range(self.backend_headers['Range'])
except ValueError:
# there's a Range header, but it's garbage, so get rid of it
self.backend_headers.pop('Range')
return
begin, end = req_range.ranges.pop(0)
if len(req_range.ranges) > 0:
self.backend_headers['Range'] = str(req_range)
else:
self.backend_headers.pop('Range')
def learn_size_from_content_range(self, start, end, length):
if length == 0:
return
if self.client_chunk_size:
self.skip_bytes = bytes_to_skip(self.client_chunk_size, start)
if 'Range' in self.backend_headers:
try:
req_range = Range(self.backend_headers['Range'])
new_ranges = [(start, end)] + req_range.ranges[1:]
except ValueError:
new_ranges = [(start, end)]
else:
new_ranges = [(start, end)]
self.backend_headers['Range'] = (
"bytes=" + (",".join("%s-%s" % (s if s is not None else '',
e if e is not None else '')
for s, e in new_ranges)))
def is_good_source(self, src):
if self.server_type == 'Object' and src.status == 416:
return True
return is_success(src.status) or is_redirection(src.status)
def response_parts_iter(self, req):
source, node = self._get_source_and_node()
it = None
if source:
it = self._get_response_parts_iter(req, node, source)
return it
def _get_response_parts_iter(self, req, node, source):
# Someday we can replace this [mess] with python 3's "nonlocal"
source = [source]
node = [node]
try:
client_chunk_size = self.client_chunk_size
node_timeout = self.app.node_timeout
if self.server_type == 'Object':
node_timeout = self.app.recoverable_node_timeout
# This is safe; it sets up a generator but does not call next()
# on it, so no IO is performed.
parts_iter = [
http_response_to_document_iters(
source[0], read_chunk_size=self.app.object_chunk_size)]
def get_next_doc_part():
while True:
try:
# This call to next() performs IO when we have a
# multipart/byteranges response; it reads the MIME
# boundary and part headers.
#
# If we don't have a multipart/byteranges response,
# but just a 200 or a single-range 206, then this
# performs no IO, and either just returns source or
# raises StopIteration.
with ChunkReadTimeout(node_timeout):
# if StopIteration is raised, it escapes and is
# handled elsewhere
start_byte, end_byte, length, headers, part = next(
parts_iter[0])
return (start_byte, end_byte, length, headers, part)
except ChunkReadTimeout:
new_source, new_node = self._get_source_and_node()
if new_source:
self.app.exception_occurred(
node[0], _('Object'),
_('Trying to read during GET (retrying)'))
# Close-out the connection as best as possible.
if getattr(source[0], 'swift_conn', None):
close_swift_conn(source[0])
source[0] = new_source
node[0] = new_node
# This is safe; it sets up a generator but does
# not call next() on it, so no IO is performed.
parts_iter[0] = http_response_to_document_iters(
new_source,
read_chunk_size=self.app.object_chunk_size)
else:
raise StopIteration()
def iter_bytes_from_response_part(part_file):
nchunks = 0
buf = ''
while True:
try:
with ChunkReadTimeout(node_timeout):
chunk = part_file.read(self.app.object_chunk_size)
nchunks += 1
buf += chunk
except ChunkReadTimeout:
exc_type, exc_value, exc_traceback = exc_info()
if self.newest or self.server_type != 'Object':
six.reraise(exc_type, exc_value, exc_traceback)
try:
self.fast_forward(self.bytes_used_from_backend)
except (HTTPException, ValueError):
six.reraise(exc_type, exc_value, exc_traceback)
except RangeAlreadyComplete:
break
buf = ''
new_source, new_node = self._get_source_and_node()
if new_source:
self.app.exception_occurred(
node[0], _('Object'),
_('Trying to read during GET (retrying)'))
# Close-out the connection as best as possible.
if getattr(source[0], 'swift_conn', None):
close_swift_conn(source[0])
source[0] = new_source
node[0] = new_node
# This is safe; it just sets up a generator but
# does not call next() on it, so no IO is
# performed.
parts_iter[0] = http_response_to_document_iters(
new_source,
read_chunk_size=self.app.object_chunk_size)
try:
_junk, _junk, _junk, _junk, part_file = \
get_next_doc_part()
except StopIteration:
# Tried to find a new node from which to
# finish the GET, but failed. There's
# nothing more to do here.
return
else:
six.reraise(exc_type, exc_value, exc_traceback)
else:
if buf and self.skip_bytes:
if self.skip_bytes < len(buf):
buf = buf[self.skip_bytes:]
self.bytes_used_from_backend += self.skip_bytes
self.skip_bytes = 0
else:
self.skip_bytes -= len(buf)
self.bytes_used_from_backend += len(buf)
buf = ''
if not chunk:
if buf:
with ChunkWriteTimeout(
self.app.client_timeout):
self.bytes_used_from_backend += len(buf)
yield buf
buf = ''
break
if client_chunk_size is not None:
while len(buf) >= client_chunk_size:
client_chunk = buf[:client_chunk_size]
buf = buf[client_chunk_size:]
with ChunkWriteTimeout(
self.app.client_timeout):
self.bytes_used_from_backend += \
len(client_chunk)
yield client_chunk
else:
with ChunkWriteTimeout(self.app.client_timeout):
self.bytes_used_from_backend += len(buf)
yield buf
buf = ''
# This is for fairness; if the network is outpacing
# the CPU, we'll always be able to read and write
# data without encountering an EWOULDBLOCK, and so
# eventlet will not switch greenthreads on its own.
# We do it manually so that clients don't starve.
#
# The number 5 here was chosen by making stuff up.
# It's not every single chunk, but it's not too big
# either, so it seemed like it would probably be an
# okay choice.
#
# Note that we may trampoline to other greenthreads
# more often than once every 5 chunks, depending on
# how blocking our network IO is; the explicit sleep
# here simply provides a lower bound on the rate of
# trampolining.
if nchunks % 5 == 0:
sleep()
part_iter = None
try:
while True:
start_byte, end_byte, length, headers, part = \
get_next_doc_part()
self.learn_size_from_content_range(
start_byte, end_byte, length)
self.bytes_used_from_backend = 0
part_iter = iter_bytes_from_response_part(part)
yield {'start_byte': start_byte, 'end_byte': end_byte,
'entity_length': length, 'headers': headers,
'part_iter': part_iter}
self.pop_range()
except StopIteration:
req.environ['swift.non_client_disconnect'] = True
finally:
if part_iter:
part_iter.close()
except ChunkReadTimeout:
self.app.exception_occurred(node[0], _('Object'),
_('Trying to read during GET'))
raise
except ChunkWriteTimeout:
self.app.logger.warning(
_('Client did not read from proxy within %ss') %
self.app.client_timeout)
self.app.logger.increment('client_timeouts')
except GeneratorExit:
exc_type, exc_value, exc_traceback = exc_info()
warn = True
try:
req_range = Range(self.backend_headers['Range'])
except ValueError:
req_range = None
if req_range and len(req_range.ranges) == 1:
begin, end = req_range.ranges[0]
if end is not None and begin is not None:
if end - begin + 1 == self.bytes_used_from_backend:
warn = False
if not req.environ.get('swift.non_client_disconnect') and warn:
self.app.logger.warning(_('Client disconnected on read'))
six.reraise(exc_type, exc_value, exc_traceback)
except Exception:
self.app.logger.exception(_('Trying to send to client'))
raise
finally:
# Close-out the connection as best as possible.
if getattr(source[0], 'swift_conn', None):
close_swift_conn(source[0])
@property
def last_status(self):
if self.statuses:
return self.statuses[-1]
else:
return None
@property
def last_headers(self):
if self.source_headers:
return HeaderKeyDict(self.source_headers[-1])
else:
return None
def _make_node_request(self, node, node_timeout, logger_thread_locals):
self.app.logger.thread_locals = logger_thread_locals
if node in self.used_nodes:
return False
req_headers = dict(self.backend_headers)
# a request may be specialised with specific backend headers
if self.header_provider:
req_headers.update(self.header_provider())
start_node_timing = time.time()
try:
with ConnectionTimeout(self.app.conn_timeout):
conn = http_connect(
node['ip'], node['port'], node['device'],
self.partition, self.req_method, self.path,
headers=req_headers,
query_string=self.req_query_string)
self.app.set_node_timing(node, time.time() - start_node_timing)
with Timeout(node_timeout):
possible_source = conn.getresponse()
# See NOTE: swift_conn at top of file about this.
possible_source.swift_conn = conn
except (Exception, Timeout):
self.app.exception_occurred(
node, self.server_type,
_('Trying to %(method)s %(path)s') %
{'method': self.req_method, 'path': self.req_path})
return False
if self.is_good_source(possible_source):
# 404 if we know we don't have a synced copy
if not float(possible_source.getheader('X-PUT-Timestamp', 1)):
self.statuses.append(HTTP_NOT_FOUND)
self.reasons.append('')
self.bodies.append('')
self.source_headers.append([])
close_swift_conn(possible_source)
else:
if self.used_source_etag:
src_headers = dict(
(k.lower(), v) for k, v in
possible_source.getheaders())
if self.used_source_etag != src_headers.get(
'x-object-sysmeta-ec-etag',
src_headers.get('etag', '')).strip('"'):
self.statuses.append(HTTP_NOT_FOUND)
self.reasons.append('')
self.bodies.append('')
self.source_headers.append([])
return False
self.statuses.append(possible_source.status)
self.reasons.append(possible_source.reason)
self.bodies.append(None)
self.source_headers.append(possible_source.getheaders())
self.sources.append((possible_source, node))
if not self.newest: # one good source is enough
return True
else:
self.statuses.append(possible_source.status)
self.reasons.append(possible_source.reason)
self.bodies.append(possible_source.read())
self.source_headers.append(possible_source.getheaders())
if possible_source.status == HTTP_INSUFFICIENT_STORAGE:
self.app.error_limit(node, _('ERROR Insufficient Storage'))
elif is_server_error(possible_source.status):
self.app.error_occurred(
node, _('ERROR %(status)d %(body)s '
'From %(type)s Server') %
{'status': possible_source.status,
'body': self.bodies[-1][:1024],
'type': self.server_type})
return False
def _get_source_and_node(self):
self.statuses = []
self.reasons = []
self.bodies = []
self.source_headers = []
self.sources = []
nodes = GreenthreadSafeIterator(self.node_iter)
node_timeout = self.app.node_timeout
if self.server_type == 'Object' and not self.newest:
node_timeout = self.app.recoverable_node_timeout
pile = GreenAsyncPile(self.concurrency)
for node in nodes:
pile.spawn(self._make_node_request, node, node_timeout,
self.app.logger.thread_locals)
_timeout = self.app.concurrency_timeout \
if pile.inflight < self.concurrency else None
if pile.waitfirst(_timeout):
break
else:
# ran out of nodes, see if any stragglers will finish
any(pile)
if self.sources:
self.sources.sort(key=lambda s: source_key(s[0]))
source, node = self.sources.pop()
for src, _junk in self.sources:
close_swift_conn(src)
self.used_nodes.append(node)
src_headers = dict(
(k.lower(), v) for k, v in
source.getheaders())
# Save off the source etag so that, if we lose the connection
# and have to resume from a different node, we can be sure that
# we have the same object (replication) or a fragment archive
# from the same object (EC). Otherwise, if the cluster has two
# versions of the same object, we might end up switching between
# old and new mid-stream and giving garbage to the client.
self.used_source_etag = src_headers.get(
'x-object-sysmeta-ec-etag',
src_headers.get('etag', '')).strip('"')
self.node = node
return source, node
return None, None
class GetOrHeadHandler(ResumingGetter):
def _make_app_iter(self, req, node, source):
ct = source.getheader('Content-Type')
if ct:
content_type, content_type_attrs = parse_content_type(ct)
is_multipart = content_type == 'multipart/byteranges'
else:
is_multipart = False
boundary = "dontcare"
if is_multipart:
# we need some MIME boundary; fortunately, the object server has
# furnished one for us, so we'll just re-use it
boundary = dict(content_type_attrs)["boundary"]
parts_iter = self._get_response_parts_iter(req, node, source)
def add_content_type(response_part):
response_part["content_type"] = \
HeaderKeyDict(response_part["headers"]).get("Content-Type")
return response_part
return document_iters_to_http_response_body(
(add_content_type(pi) for pi in parts_iter),
boundary, is_multipart, self.app.logger)
def get_working_response(self, req):
source, node = self._get_source_and_node()
res = None
if source:
res = Response(request=req)
res.status = source.status
update_headers(res, source.getheaders())
if req.method == 'GET' and \
source.status in (HTTP_OK, HTTP_PARTIAL_CONTENT):
res.app_iter = self._make_app_iter(req, node, source)
# See NOTE: swift_conn at top of file about this.
res.swift_conn = source.swift_conn
if not res.environ:
res.environ = {}
res.environ['swift_x_timestamp'] = \
source.getheader('x-timestamp')
res.accept_ranges = 'bytes'
res.content_length = source.getheader('Content-Length')
if source.getheader('Content-Type'):
res.charset = None
res.content_type = source.getheader('Content-Type')
return res
class NodeIter(object):
def __init__(self, app, ring, partition, node_iter=None, policy=None):
self.app = app
self.ring = ring
self.partition = partition
part_nodes = ring.get_part_nodes(partition)
if node_iter is None:
node_iter = itertools.chain(
part_nodes, ring.get_more_nodes(partition))
num_primary_nodes = len(part_nodes)
self.nodes_left = self.app.request_node_count(num_primary_nodes)
self.expected_handoffs = self.nodes_left - num_primary_nodes
# Use of list() here forcibly yanks the first N nodes (the primary
# nodes) from node_iter, so the rest of its values are handoffs.
self.primary_nodes = self.app.sort_nodes(
list(itertools.islice(node_iter, num_primary_nodes)),
policy=policy)
self.handoff_iter = node_iter
self._node_provider = None
def __iter__(self):
self._node_iter = self._node_gen()
return self
def log_handoffs(self, handoffs):
if not self.app.log_handoffs:
return
extra_handoffs = handoffs - self.expected_handoffs
if extra_handoffs > 0:
self.app.logger.increment('handoff_count')
self.app.logger.warning(
'Handoff requested (%d)' % handoffs)
if (extra_handoffs == len(self.primary_nodes)):
# all the primaries were skipped, and handoffs didn't help
self.app.logger.increment('handoff_all_count')
def set_node_provider(self, callback):
self._node_provider = callback
def _node_gen(self):
for node in self.primary_nodes:
if not self.app.error_limited(node):
yield node
if not self.app.error_limited(node):
self.nodes_left -= 1
if self.nodes_left <= 0:
return
handoffs = 0
for node in self.handoff_iter:
if not self.app.error_limited(node):
handoffs += 1
self.log_handoffs(handoffs)
yield node
if not self.app.error_limited(node):
self.nodes_left -= 1
if self.nodes_left <= 0:
return
def next(self):
if self._node_provider:
# give node provider the opportunity to inject a node
node = self._node_provider()
if node:
return node
return next(self._node_iter)
def __next__(self):
return self.next()
class Controller(object):
server_type = 'Base'
# Ensure these are all lowercase
pass_through_headers = []
def __init__(self, app):
self.account_name = None
self.app = app
self.trans_id = '-'
self._allowed_methods = None
@property
def allowed_methods(self):
if self._allowed_methods is None:
self._allowed_methods = set()
all_methods = inspect.getmembers(self, predicate=inspect.ismethod)
for name, m in all_methods:
if getattr(m, 'publicly_accessible', False):
self._allowed_methods.add(name)
return self._allowed_methods
def _x_remove_headers(self):
return []
def transfer_headers(self, src_headers, dst_headers):
st = self.server_type.lower()
x_remove = 'x-remove-%s-meta-' % st
dst_headers.update((k.lower().replace('-remove', '', 1), '')
for k in src_headers
if k.lower().startswith(x_remove) or
k.lower() in self._x_remove_headers())
dst_headers.update((k.lower(), v)
for k, v in src_headers.items()
if k.lower() in self.pass_through_headers or
is_sys_or_user_meta(st, k))
def generate_request_headers(self, orig_req=None, additional=None,
transfer=False):
# Use the additional headers first so they don't overwrite the headers
# we require.
headers = HeaderKeyDict(additional) if additional else HeaderKeyDict()
if transfer:
self.transfer_headers(orig_req.headers, headers)
headers.setdefault('x-timestamp', Timestamp.now().internal)
if orig_req:
referer = orig_req.as_referer()
else:
referer = ''
headers['x-trans-id'] = self.trans_id
headers['connection'] = 'close'
headers['user-agent'] = 'proxy-server %s' % os.getpid()
headers['referer'] = referer
return headers
def account_info(self, account, req=None):
partition, nodes = self.app.account_ring.get_nodes(account)
if req:
env = getattr(req, 'environ', {})
else:
env = {}
env.setdefault('swift.infocache', {})
path_env = env.copy()
path_env['PATH_INFO'] = "/v1/%s" % (account,)
info = get_account_info(path_env, self.app)
if (not info
or not is_success(info['status'])
or not info.get('account_really_exists', True)):
return None, None, None
container_count = info['container_count']
return partition, nodes, container_count
def container_info(self, account, container, req=None):
part, nodes = self.app.container_ring.get_nodes(account, container)
if req:
env = getattr(req, 'environ', {})
else:
env = {}
env.setdefault('swift.infocache', {})
path_env = env.copy()
path_env['PATH_INFO'] = "/v1/%s/%s" % (account, container)
info = get_container_info(path_env, self.app)
if not info or not is_success(info.get('status')):
info = headers_to_container_info({}, 0)
info['partition'] = None
info['nodes'] = None
else:
info['partition'] = part
info['nodes'] = nodes
return info
def _make_request(self, nodes, part, method, path, headers, query,
logger_thread_locals):
self.app.logger.thread_locals = logger_thread_locals
for node in nodes:
try:
start_node_timing = time.time()
with ConnectionTimeout(self.app.conn_timeout):
conn = http_connect(node['ip'], node['port'],
node['device'], part, method, path,
headers=headers, query_string=query)
conn.node = node
self.app.set_node_timing(node, time.time() - start_node_timing)
with Timeout(self.app.node_timeout):
resp = conn.getresponse()
if not is_informational(resp.status) and \
not is_server_error(resp.status):
return resp.status, resp.reason, resp.getheaders(), \
resp.read()
elif resp.status == HTTP_INSUFFICIENT_STORAGE:
self.app.error_limit(node,
_('ERROR Insufficient Storage'))
elif is_server_error(resp.status):
self.app.error_occurred(
node, _('ERROR %(status)d '
'Trying to %(method)s %(path)s'
' From %(type)s Server') % {
'status': resp.status,
'method': method,
'path': path,
'type': self.server_type})
except (Exception, Timeout):
self.app.exception_occurred(
node, self.server_type,
_('Trying to %(method)s %(path)s') %
{'method': method, 'path': path})
def make_requests(self, req, ring, part, method, path, headers,
query_string='', overrides=None, node_count=None,
node_iterator=None):
nodes = GreenthreadSafeIterator(
node_iterator or self.app.iter_nodes(ring, part)
)
node_number = node_count or len(ring.get_part_nodes(part))
pile = GreenAsyncPile(node_number)
for head in headers:
pile.spawn(self._make_request, nodes, part, method, path,
head, query_string, self.app.logger.thread_locals)
response = []
statuses = []
for resp in pile:
if not resp:
continue
response.append(resp)
statuses.append(resp[0])
if self.have_quorum(statuses, node_number):
break
# give any pending requests *some* chance to finish
finished_quickly = pile.waitall(self.app.post_quorum_timeout)
for resp in finished_quickly:
if not resp:
continue
response.append(resp)
statuses.append(resp[0])
while len(response) < node_number:
response.append((HTTP_SERVICE_UNAVAILABLE, '', '', ''))
statuses, reasons, resp_headers, bodies = zip(*response)
return self.best_response(req, statuses, reasons, bodies,
'%s %s' % (self.server_type, req.method),
overrides=overrides, headers=resp_headers)
def _quorum_size(self, n):
return quorum_size(n)
def have_quorum(self, statuses, node_count, quorum=None):
if quorum is None:
quorum = self._quorum_size(node_count)
if len(statuses) >= quorum:
for hundred in (HTTP_CONTINUE, HTTP_OK, HTTP_MULTIPLE_CHOICES,
HTTP_BAD_REQUEST):
if sum(1 for s in statuses
if hundred <= s < hundred + 100) >= quorum:
return True
return False
def best_response(self, req, statuses, reasons, bodies, server_type,
etag=None, headers=None, overrides=None,
quorum_size=None):
if quorum_size is None:
quorum_size = self._quorum_size(len(statuses))
resp = self._compute_quorum_response(
req, statuses, reasons, bodies, etag, headers,
quorum_size=quorum_size)
if overrides and not resp:
faked_up_status_indices = set()
transformed = []
for (i, (status, reason, hdrs, body)) in enumerate(zip(
statuses, reasons, headers, bodies)):
if status in overrides:
faked_up_status_indices.add(i)
transformed.append((overrides[status], '', '', ''))
else:
transformed.append((status, reason, hdrs, body))
statuses, reasons, headers, bodies = zip(*transformed)
resp = self._compute_quorum_response(
req, statuses, reasons, bodies, etag, headers,
indices_to_avoid=faked_up_status_indices,
quorum_size=quorum_size)
if not resp:
resp = HTTPServiceUnavailable(request=req)
self.app.logger.error(_('%(type)s returning 503 for %(statuses)s'),
{'type': server_type, 'statuses': statuses})
return resp
def _compute_quorum_response(self, req, statuses, reasons, bodies, etag,
headers, quorum_size, indices_to_avoid=()):
if not statuses:
return None
for hundred in (HTTP_OK, HTTP_MULTIPLE_CHOICES, HTTP_BAD_REQUEST):
hstatuses = \
[(i, s) for i, s in enumerate(statuses)
if hundred <= s < hundred + 100]
if len(hstatuses) >= quorum_size:
try:
status_index, status = max(
((i, stat) for i, stat in hstatuses
if i not in indices_to_avoid),
key=operator.itemgetter(1))
except ValueError:
# All statuses were indices to avoid
continue
resp = status_map[status](request=req)
resp.status = '%s %s' % (status, reasons[status_index])
resp.body = bodies[status_index]
if headers:
update_headers(resp, headers[status_index])
if etag:
resp.headers['etag'] = etag.strip('"')
return resp
return None
@public
def GET(self, req):
return self.GETorHEAD(req)
@public
def HEAD(self, req):
return self.GETorHEAD(req)
def autocreate_account(self, req, account):
partition, nodes = self.app.account_ring.get_nodes(account)
path = '/%s' % account
headers = {'X-Timestamp': Timestamp.now().internal,
'X-Trans-Id': self.trans_id,
'X-Openstack-Request-Id': self.trans_id,
'Connection': 'close'}
headers.update((k, v)
for k, v in req.headers.items()
if is_sys_meta('account', k))
resp = self.make_requests(Request.blank('/v1' + path),
self.app.account_ring, partition, 'PUT',
path, [headers] * len(nodes))
if is_success(resp.status_int):
self.app.logger.info(_('autocreate account %r'), path)
clear_info_cache(self.app, req.environ, account)
else:
self.app.logger.warning(_('Could not autocreate account %r'),
path)
def GETorHEAD_base(self, req, server_type, node_iter, partition, path,
concurrency=1, client_chunk_size=None):
backend_headers = self.generate_request_headers(
req, additional=req.headers)
handler = GetOrHeadHandler(self.app, req, self.server_type, node_iter,
partition, path, backend_headers,
concurrency,
client_chunk_size=client_chunk_size)
res = handler.get_working_response(req)
if not res:
res = self.best_response(
req, handler.statuses, handler.reasons, handler.bodies,
'%s %s' % (server_type, req.method),
headers=handler.source_headers)
if 'X-Backend-Storage-Policy-Index' in res.headers and \
is_success(res.status_int):
policy = \
POLICIES.get_by_index(
res.headers['X-Backend-Storage-Policy-Index'])
if policy:
res.headers['X-Storage-Policy'] = policy.name
else:
self.app.logger.error(
'Could not translate %s (%r) from %r to policy',
'X-Backend-Storage-Policy-Index',
res.headers['X-Backend-Storage-Policy-Index'], path)
return res
def is_origin_allowed(self, cors_info, origin):
allowed_origins = set()
if cors_info.get('allow_origin'):
allowed_origins.update(
[a.strip()
for a in cors_info['allow_origin'].split(' ')
if a.strip()])
if self.app.cors_allow_origin:
allowed_origins.update(self.app.cors_allow_origin)
return origin in allowed_origins or '*' in allowed_origins
@public
def OPTIONS(self, req):
headers = {'Allow': ', '.join(self.allowed_methods)}
resp = Response(status=200, request=req, headers=headers)
req_origin_value = req.headers.get('Origin', None)
if not req_origin_value:
return resp
# This is a CORS preflight request so check it's allowed
try:
container_info = \
self.container_info(self.account_name,
self.container_name, req)
except AttributeError:
return resp
cors = container_info.get('cors', {})
if not self.is_origin_allowed(cors, req_origin_value) or (
req.headers.get('Access-Control-Request-Method') not in
self.allowed_methods):
resp.status = HTTP_UNAUTHORIZED
return resp
# Populate the response with the CORS preflight headers
if cors.get('allow_origin') and \
cors.get('allow_origin').strip() == '*':
headers['access-control-allow-origin'] = '*'
else:
headers['access-control-allow-origin'] = req_origin_value
if 'vary' in headers:
headers['vary'] += ', Origin'
else:
headers['vary'] = 'Origin'
if cors.get('max_age') is not None:
headers['access-control-max-age'] = cors.get('max_age')
headers['access-control-allow-methods'] = \
', '.join(self.allowed_methods)
# Allow all headers requested in the request. The CORS
# specification does leave the door open for this, as mentioned in
# http://www.w3.org/TR/cors/#resource-preflight-requests
# Note: Since the list of headers can be unbounded
# simply returning headers can be enough.
allow_headers = set(
list_from_csv(req.headers.get('Access-Control-Request-Headers')))
if allow_headers:
headers['access-control-allow-headers'] = ', '.join(allow_headers)
if 'vary' in headers:
headers['vary'] += ', Access-Control-Request-Headers'
else:
headers['vary'] = 'Access-Control-Request-Headers'
resp.headers = headers
return resp
| true | true |
f7f6e7de81ec1c076099b4d303b1801c57ff1cb0 | 52 | py | Python | teme/constants.py | MDS-PBSCB/teme | f750713801246bda523d372d3c953b3c2bed2e6c | [
"MIT"
] | null | null | null | teme/constants.py | MDS-PBSCB/teme | f750713801246bda523d372d3c953b3c2bed2e6c | [
"MIT"
] | null | null | null | teme/constants.py | MDS-PBSCB/teme | f750713801246bda523d372d3c953b3c2bed2e6c | [
"MIT"
] | null | null | null | MIN_RATING_STAR_VALUE = 1
MAX_RATING_STAR_VALUE = 5
| 17.333333 | 25 | 0.846154 | MIN_RATING_STAR_VALUE = 1
MAX_RATING_STAR_VALUE = 5
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.