hexsha
stringlengths
40
40
size
int64
7
1.04M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
247
max_stars_repo_name
stringlengths
4
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
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
247
max_issues_repo_name
stringlengths
4
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
247
max_forks_repo_name
stringlengths
4
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.04M
avg_line_length
float64
1.77
618k
max_line_length
int64
1
1.02M
alphanum_fraction
float64
0
1
original_content
stringlengths
7
1.04M
filtered:remove_function_no_docstring
int64
-102
942k
filtered:remove_class_no_docstring
int64
-354
977k
filtered:remove_delete_markers
int64
0
60.1k
f0462c83458067422ca6c7d9255e191202c7b8a6
627
py
Python
gui.py
clash402/snake-game
f069725313b19e5bf77166b5a540d61e0593213b
[ "MIT" ]
null
null
null
gui.py
clash402/snake-game
f069725313b19e5bf77166b5a540d61e0593213b
[ "MIT" ]
null
null
null
gui.py
clash402/snake-game
f069725313b19e5bf77166b5a540d61e0593213b
[ "MIT" ]
null
null
null
from turtle import Screen # Cannot inherit from Screen class in Turtle, so each Screen method must be recreated here # PUBLIC METHODS (recreated Screen methods)
24.115385
94
0.634769
from turtle import Screen class GUI: # Cannot inherit from Screen class in Turtle, so each Screen method must be recreated here def __init__(self): self.screen = Screen() self.screen.setup(width=600, height=600) self.screen.bgcolor("black") self.screen.title("Snake Game!") self.screen.tracer(0) # PUBLIC METHODS (recreated Screen methods) def listen(self): self.screen.listen() def onkey(self, fn, key): self.screen.onkey(fn, key) def update(self): self.screen.update() def exitonclick(self): self.screen.exitonclick()
311
-11
156
e6d8ca093ecb5d54bb7143209223467e14e9c539
28
py
Python
2020-04-16 - Python Medellin - Creating a chat service with WebSockets/Examples/Chat/app/models/__init__.py
williamegomezo/Talks
0b123c6c8dec9c1a2357c142b617109068caf060
[ "MIT" ]
2
2020-04-24T23:03:41.000Z
2020-11-10T15:08:38.000Z
2020-04-16 - Python Medellin - Creating a chat service with WebSockets/Examples/Chat/app/models/__init__.py
williamegomezo/Talks
0b123c6c8dec9c1a2357c142b617109068caf060
[ "MIT" ]
5
2021-03-10T11:42:15.000Z
2022-02-10T21:38:54.000Z
2020-04-16 - Python Medellin - Creating a chat service with WebSockets/Examples/Chat/app/models/__init__.py
williamegomezo/Talks
0b123c6c8dec9c1a2357c142b617109068caf060
[ "MIT" ]
4
2020-10-01T04:32:27.000Z
2022-02-14T15:08:16.000Z
from .user import Base, User
28
28
0.785714
from .user import Base, User
0
0
0
8a3df74e4b5fbe81ecc184e48fc757183d8b98da
2,639
py
Python
python_data/fintech/funnel_monitor_multiday_v3.py
younhapan/ystdoc
a3fee3c48fc4e35b26b70ab7d9f123be059a4a7a
[ "Apache-2.0" ]
null
null
null
python_data/fintech/funnel_monitor_multiday_v3.py
younhapan/ystdoc
a3fee3c48fc4e35b26b70ab7d9f123be059a4a7a
[ "Apache-2.0" ]
null
null
null
python_data/fintech/funnel_monitor_multiday_v3.py
younhapan/ystdoc
a3fee3c48fc4e35b26b70ab7d9f123be059a4a7a
[ "Apache-2.0" ]
null
null
null
# encoding: utf-8 from __future__ import division import sys import os import time import datetime import pandas as pd import numpy as np import math CURRENT_DIR = os.path.abspath(os.path.dirname(__file__)) ADD_PATH = "%s/../"%(CURRENT_DIR) sys.path.append(ADD_PATH) from tools.mail import MyEmail from tools.html import html_with_style DATA_PATH = "%s/../data/mysql" % (CURRENT_DIR) send_str = '' # load data for max_day if __name__ == '__main__': max_day = sys.argv[1] max_day = int(max_day) if max_day > 2: title = '订单漏斗汇总' df, day_list = load_data(max_day) elif max_day == 2: title = '订单漏斗监控' df, day_list = load_data(max_day) df = df.T mail = MyEmail() send_str += html_with_style(df) + '<br>' to_list = ['panyunxia@hinterstellar.com'] # to_list = ['zhouchong@hinterstellar.com', 'panyunxia@hinterstellar.com'] title = title + day_list[0] mail.sendemail(send_str, title , to_list)
35.186667
164
0.613869
# encoding: utf-8 from __future__ import division import sys import os import time import datetime import pandas as pd import numpy as np import math CURRENT_DIR = os.path.abspath(os.path.dirname(__file__)) ADD_PATH = "%s/../"%(CURRENT_DIR) sys.path.append(ADD_PATH) from tools.mail import MyEmail from tools.html import html_with_style DATA_PATH = "%s/../data/mysql" % (CURRENT_DIR) send_str = '' # load data for max_day def load_data(max_day): day_list = [] for i in range(1, max_day): dt = str(datetime.datetime.today() - datetime.timedelta(days=i))[0:10] day_list.append(dt) df_dts = [] for dt in day_list: try: df_regist_dt = pd.read_csv(DATA_PATH+'/regist.'+dt, encoding = 'utf-8') except: df_regist_dt = pd.DataFrame(data=[[dt, 0]], columns = ['create_date','regist_cnt']) try: df_funnel_dt = pd.read_csv(DATA_PATH+'/funnel.'+dt, encoding = 'utf-8') except: df_funnel_dt = pd.DataFrame(data=[[dt,0,0,0,0,0]], columns = ['create_date','apply_user','auto_passed','manual_passed','manual_failed','loan_success']) df_dt = pd.merge(df_regist_dt, df_funnel_dt, how = 'left', on = 'create_date') df_dts.append(df_dt) df = pd.concat(df_dts, axis = 0) df = df[['create_date', 'regist_cnt', 'apply_user', 'auto_passed', 'manual_passed', 'manual_failed', 'loan_success']] # mysql中数据有其他指标,只取特定几个 df.columns = ['日期', '注册人数', '申请人数', '机审通过人数', '人审通过人数', '人审拒绝人数', '放款人数'] df['C1'] = df['申请人数']/df['注册人数'] df['C2'] = df['机审通过人数']/df['申请人数'] df['C3'] = df['人审通过人数']/df['机审通过人数'] df['C4'] = df['放款人数']/df['人审通过人数'] df.replace(np.inf, 0, inplace = True) df.fillna(0, inplace = True) df[['C1','C2','C3','C4']] = df[['C1','C2','C3','C4']].applymap(lambda x: ('%.2f%%') %(x*100)) df = df[['日期','注册人数','C1','申请人数','C2','机审通过人数','C3','人审通过人数','人审拒绝人数','C4','放款人数']] df = pd.DataFrame(data = df.iloc[:,1:].values.tolist(), index = df['日期'].values.tolist(), columns = df.columns.values.tolist()[1:]) return df, day_list if __name__ == '__main__': max_day = sys.argv[1] max_day = int(max_day) if max_day > 2: title = '订单漏斗汇总' df, day_list = load_data(max_day) elif max_day == 2: title = '订单漏斗监控' df, day_list = load_data(max_day) df = df.T mail = MyEmail() send_str += html_with_style(df) + '<br>' to_list = ['panyunxia@hinterstellar.com'] # to_list = ['zhouchong@hinterstellar.com', 'panyunxia@hinterstellar.com'] title = title + day_list[0] mail.sendemail(send_str, title , to_list)
1,883
0
22
4826a6c5e8a399c116c685321697eb6d8aca5611
11,037
py
Python
neutron/tests/functional/services/trunk/drivers/openvswitch/agent/test_trunk_manager.py
brandonlogan/neutron
57364544aa8b0e7cd9d73550f287bcad574ba08c
[ "Apache-2.0" ]
1
2017-09-10T09:57:35.000Z
2017-09-10T09:57:35.000Z
neutron/tests/functional/services/trunk/drivers/openvswitch/agent/test_trunk_manager.py
brandonlogan/neutron
57364544aa8b0e7cd9d73550f287bcad574ba08c
[ "Apache-2.0" ]
null
null
null
neutron/tests/functional/services/trunk/drivers/openvswitch/agent/test_trunk_manager.py
brandonlogan/neutron
57364544aa8b0e7cd9d73550f287bcad574ba08c
[ "Apache-2.0" ]
1
2015-05-05T14:41:11.000Z
2015-05-05T14:41:11.000Z
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from oslo_log import log as logging from oslo_utils import uuidutils import testtools from neutron.common import utils as common_utils from neutron.services.trunk.drivers.openvswitch.agent import trunk_manager from neutron.services.trunk.drivers.openvswitch import utils from neutron.tests.common import conn_testers from neutron.tests.common import helpers from neutron.tests.common import net_helpers from neutron.tests.functional import base from neutron.tests.functional import constants as test_constants LOG = logging.getLogger(__name__) VLAN_RANGE = set(range(test_constants.VLAN_COUNT))
43.972112
79
0.655251
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from oslo_log import log as logging from oslo_utils import uuidutils import testtools from neutron.common import utils as common_utils from neutron.services.trunk.drivers.openvswitch.agent import trunk_manager from neutron.services.trunk.drivers.openvswitch import utils from neutron.tests.common import conn_testers from neutron.tests.common import helpers from neutron.tests.common import net_helpers from neutron.tests.functional import base from neutron.tests.functional import constants as test_constants LOG = logging.getLogger(__name__) VLAN_RANGE = set(range(test_constants.VLAN_COUNT)) class FakeOVSDBException(Exception): pass class TrunkParentPortTestCase(base.BaseSudoTestCase): def setUp(self): super(TrunkParentPortTestCase, self).setUp() trunk_id = uuidutils.generate_uuid() port_id = uuidutils.generate_uuid() port_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':')) self.trunk = trunk_manager.TrunkParentPort(trunk_id, port_id, port_mac) self.trunk.bridge = self.useFixture( net_helpers.OVSTrunkBridgeFixture( self.trunk.bridge.br_name)).bridge self.br_int = self.useFixture(net_helpers.OVSBridgeFixture()).bridge def test_plug(self): self.trunk.plug(self.br_int) self.assertIn(self.trunk.patch_port_trunk_name, self.trunk.bridge.get_port_name_list()) self.assertIn(self.trunk.patch_port_int_name, self.br_int.get_port_name_list()) def test_plug_failure_doesnt_create_ports(self): with mock.patch.object( self.trunk.bridge.ovsdb, 'db_set', side_effect=FakeOVSDBException): with testtools.ExpectedException(FakeOVSDBException): self.trunk.plug(self.br_int) self.assertNotIn(self.trunk.patch_port_trunk_name, self.trunk.bridge.get_port_name_list()) self.assertNotIn(self.trunk.patch_port_int_name, self.br_int.get_port_name_list()) def test_unplug(self): self.trunk.plug(self.br_int) self.trunk.unplug(self.br_int) self.assertFalse( self.trunk.bridge.bridge_exists(self.trunk.bridge.br_name)) self.assertNotIn(self.trunk.patch_port_int_name, self.br_int.get_port_name_list()) def test_unplug_failure_doesnt_delete_bridge(self): self.trunk.plug(self.br_int) with mock.patch.object( self.trunk.bridge.ovsdb, 'del_port', side_effect=FakeOVSDBException): with testtools.ExpectedException(FakeOVSDBException): self.trunk.unplug(self.br_int) self.assertTrue( self.trunk.bridge.bridge_exists(self.trunk.bridge.br_name)) self.assertIn(self.trunk.patch_port_trunk_name, self.trunk.bridge.get_port_name_list()) self.assertIn(self.trunk.patch_port_int_name, self.br_int.get_port_name_list()) class SubPortTestCase(base.BaseSudoTestCase): def setUp(self): super(SubPortTestCase, self).setUp() trunk_id = uuidutils.generate_uuid() port_id = uuidutils.generate_uuid() port_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':')) trunk_bridge_name = utils.gen_trunk_br_name(trunk_id) trunk_bridge = self.useFixture( net_helpers.OVSTrunkBridgeFixture(trunk_bridge_name)).bridge segmentation_id = helpers.get_not_used_vlan( trunk_bridge, VLAN_RANGE) self.subport = trunk_manager.SubPort( trunk_id, port_id, port_mac, segmentation_id) self.subport.bridge = trunk_bridge self.br_int = self.useFixture(net_helpers.OVSBridgeFixture()).bridge def test_plug(self): self.subport.plug(self.br_int) self.assertIn(self.subport.patch_port_trunk_name, self.subport.bridge.get_port_name_list()) self.assertIn(self.subport.patch_port_int_name, self.br_int.get_port_name_list()) self.assertEqual( self.subport.segmentation_id, self.subport.bridge.db_get_val( 'Port', self.subport.patch_port_trunk_name, 'tag')) def test_plug_failure_doesnt_create_ports(self): with mock.patch.object( self.subport.bridge.ovsdb, 'db_set', side_effect=FakeOVSDBException): with testtools.ExpectedException(FakeOVSDBException): self.subport.plug(self.br_int) self.assertNotIn(self.subport.patch_port_trunk_name, self.subport.bridge.get_port_name_list()) self.assertNotIn(self.subport.patch_port_int_name, self.br_int.get_port_name_list()) def test_unplug(self): self.subport.plug(self.br_int) self.subport.unplug(self.br_int) self.assertNotIn(self.subport.patch_port_trunk_name, self.subport.bridge.get_port_name_list()) self.assertNotIn(self.subport.patch_port_int_name, self.br_int.get_port_name_list()) def test_unplug_failure(self): self.subport.plug(self.br_int) with mock.patch.object( self.subport.bridge.ovsdb, 'del_port', side_effect=FakeOVSDBException): with testtools.ExpectedException(FakeOVSDBException): self.subport.unplug(self.br_int) self.assertIn(self.subport.patch_port_trunk_name, self.subport.bridge.get_port_name_list()) self.assertIn(self.subport.patch_port_int_name, self.br_int.get_port_name_list()) class TrunkManagerTestCase(base.BaseSudoTestCase): net1_cidr = '192.178.0.1/24' net2_cidr = '192.168.0.1/24' def setUp(self): super(TrunkManagerTestCase, self).setUp() trunk_id = uuidutils.generate_uuid() self.tester = self.useFixture( conn_testers.OVSTrunkConnectionTester( self.net1_cidr, utils.gen_trunk_br_name(trunk_id))) self.trunk_manager = trunk_manager.TrunkManager( self.tester.bridge) self.trunk = trunk_manager.TrunkParentPort( trunk_id, uuidutils.generate_uuid()) def test_connectivity(self): """Test connectivity with trunk and sub ports. In this test we create a vm that has a trunk on net1 and a vm peer on the same network. We check connectivity between the peer and the vm. We create a sub port on net2 and a peer, check connectivity again. """ vlan_net1 = helpers.get_not_used_vlan(self.tester.bridge, VLAN_RANGE) vlan_net2 = helpers.get_not_used_vlan(self.tester.bridge, VLAN_RANGE) trunk_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':')) sub_port_mac = common_utils.get_random_mac( 'fa:16:3e:00:00:00'.split(':')) sub_port_segmentation_id = helpers.get_not_used_vlan( self.tester.bridge, VLAN_RANGE) LOG.debug("Using %(n1)d vlan tag as local vlan ID for net1 and %(n2)d " "for local vlan ID for net2", { 'n1': vlan_net1, 'n2': vlan_net2}) self.tester.set_peer_tag(vlan_net1) self.trunk_manager.create_trunk(self.trunk.trunk_id, self.trunk.port_id, trunk_mac) # tag the patch port, this should be done by the ovs agent but we mock # it for this test conn_testers.OVSBaseConnectionTester.set_tag( self.trunk.patch_port_int_name, self.tester.bridge, vlan_net1) self.tester.wait_for_connection(self.tester.INGRESS) self.tester.wait_for_connection(self.tester.EGRESS) self.tester.add_vlan_interface_and_peer(sub_port_segmentation_id, self.net2_cidr) conn_testers.OVSBaseConnectionTester.set_tag( self.tester._peer2.port.name, self.tester.bridge, vlan_net2) sub_port = trunk_manager.SubPort(self.trunk.trunk_id, uuidutils.generate_uuid(), sub_port_mac, sub_port_segmentation_id) self.trunk_manager.add_sub_port(sub_port.trunk_id, sub_port.port_id, sub_port.port_mac, sub_port.segmentation_id) # tag the patch port, this should be done by the ovs agent but we mock # it for this test conn_testers.OVSBaseConnectionTester.set_tag( sub_port.patch_port_int_name, self.tester.bridge, vlan_net2) self.tester.wait_for_sub_port_connectivity(self.tester.INGRESS) self.tester.wait_for_sub_port_connectivity(self.tester.EGRESS) self.trunk_manager.remove_sub_port(sub_port.trunk_id, sub_port.port_id) self.tester.wait_for_sub_port_no_connectivity(self.tester.INGRESS) self.tester.wait_for_sub_port_no_connectivity(self.tester.EGRESS) self.trunk_manager.remove_trunk(self.trunk.trunk_id, self.trunk.port_id) self.tester.wait_for_no_connection(self.tester.INGRESS) class TrunkManagerDisposeTrunkTestCase(base.BaseSudoTestCase): def setUp(self): super(TrunkManagerDisposeTrunkTestCase, self).setUp() trunk_id = uuidutils.generate_uuid() self.trunk = trunk_manager.TrunkParentPort( trunk_id, uuidutils.generate_uuid()) self.trunk.bridge = self.useFixture( net_helpers.OVSTrunkBridgeFixture( self.trunk.bridge.br_name)).bridge self.br_int = self.useFixture(net_helpers.OVSBridgeFixture()).bridge self.trunk_manager = trunk_manager.TrunkManager( self.br_int) def test_dispose_trunk(self): self.trunk.plug(self.br_int) self.trunk_manager.dispose_trunk(self.trunk.bridge) self.assertFalse( self.trunk.bridge.bridge_exists(self.trunk.bridge.br_name)) self.assertNotIn(self.trunk.patch_port_int_name, self.br_int.get_port_name_list())
6,012
3,373
437
1960d34bb0ffc10045ff04d14a1b3e8ca3d3eb73
115
py
Python
examples/aiohttp/starwars/starwars/__init__.py
erezsh/tartiflette
c945b02e9025e2524393c1eaec2191745bfc38f4
[ "MIT" ]
null
null
null
examples/aiohttp/starwars/starwars/__init__.py
erezsh/tartiflette
c945b02e9025e2524393c1eaec2191745bfc38f4
[ "MIT" ]
null
null
null
examples/aiohttp/starwars/starwars/__init__.py
erezsh/tartiflette
c945b02e9025e2524393c1eaec2191745bfc38f4
[ "MIT" ]
null
null
null
from starwars.resolvers import resolvers from starwars.sdl import STARWARSTIFLETTE __all__ = ["STARWARSTIFLETTE"]
23
41
0.834783
from starwars.resolvers import resolvers from starwars.sdl import STARWARSTIFLETTE __all__ = ["STARWARSTIFLETTE"]
0
0
0
180b06646cf19c497c29cdd0098e87bc487b8b89
2,585
py
Python
src/examples/tcp.py
ettoreleandrotognoli/python-shared
fbee6d9932e8ed52005d3e96a9f6ee79393e13ff
[ "BSD-3-Clause" ]
null
null
null
src/examples/tcp.py
ettoreleandrotognoli/python-shared
fbee6d9932e8ed52005d3e96a9f6ee79393e13ff
[ "BSD-3-Clause" ]
1
2017-11-28T09:21:01.000Z
2017-11-28T09:21:01.000Z
src/examples/tcp.py
ettoreleandrotognoli/python-shared
fbee6d9932e8ed52005d3e96a9f6ee79393e13ff
[ "BSD-3-Clause" ]
null
null
null
import json import multiprocessing import time from rx.testing import marbles m = marbles from pyshared.core.ref import LocalSharedResourcesManager from pyshared.core.ref import ResourcesManagerListenerAdapter from pyshared.core.ref import default_command_mapper from pyshared.core.rx import ReactiveSharedResourcesServer from pyshared.core.rx import TCPServer from pyshared.core.rx import TCPServerConnection from pyshared.core.utils import map_debug, fdebug from rx import Observable from rx.concurrency import ThreadPoolScheduler address = '0.0.0.0' optimal_thread_count = multiprocessing.cpu_count() + 1 pool_scheduler = ThreadPoolScheduler(optimal_thread_count) if __name__ == '__main__': try: server, manager = main() except Exception as ex: print(ex) exit(-1) try: while True: print('...') time.sleep(1) except KeyboardInterrupt as ex: del manager server.stop()
27.5
61
0.630174
import json import multiprocessing import time from rx.testing import marbles m = marbles from pyshared.core.ref import LocalSharedResourcesManager from pyshared.core.ref import ResourcesManagerListenerAdapter from pyshared.core.ref import default_command_mapper from pyshared.core.rx import ReactiveSharedResourcesServer from pyshared.core.rx import TCPServer from pyshared.core.rx import TCPServerConnection from pyshared.core.utils import map_debug, fdebug from rx import Observable from rx.concurrency import ThreadPoolScheduler address = '0.0.0.0' optimal_thread_count = multiprocessing.cpu_count() + 1 pool_scheduler = ThreadPoolScheduler(optimal_thread_count) def safe(func, handler=lambda e: None): def wrapper(*args, **kwargs): try: return Observable.just(func(*args, **kwargs)) except Exception as ex: handler(ex) return Observable.just(ex) return wrapper def debug(name): def wrapper(*args, **kwargs): print(name, args, kwargs) return wrapper def main(): listener = ResourcesManagerListenerAdapter( on_init=debug('init'), on_finish=debug('finish'), on_call_resource=debug('call'), on_del_resource=debug('del'), on_set_resource=debug('set'), on_error=debug('error') ) manager = LocalSharedResourcesManager({ 'number': 10, 'Observable': Observable }, listeners=[listener]) pyshared = ReactiveSharedResourcesServer(manager) @fdebug def process_client(client: TCPServerConnection): try: client.as_observable(pool_scheduler) \ .map(map_debug) \ .map(lambda e: e.decode('utf-8')) \ .map(json.loads) \ .map(default_command_mapper) \ .flat_map(pyshared) \ .map(json.dumps) \ .map(lambda e: e.encode('utf-8')) \ .map(map_debug) \ .retry() \ .subscribe(client) except Exception as ex: print(ex) server = TCPServer() server.connect(address, 0) print("running at %s:%d" % (address, server.port)) server.as_observable(pool_scheduler) \ .subscribe(process_client) return server, manager if __name__ == '__main__': try: server, manager = main() except Exception as ex: print(ex) exit(-1) try: while True: print('...') time.sleep(1) except KeyboardInterrupt as ex: del manager server.stop()
1,551
0
69
590f98ecefded6017c5e8e01e91e80e62d78afc1
34,666
py
Python
models/polytope_constraints.py
mbroso/constraintnet_facial_detect
3f53a4694f3c6b229679ef9014ac98573f45fd43
[ "BSD-3-Clause" ]
null
null
null
models/polytope_constraints.py
mbroso/constraintnet_facial_detect
3f53a4694f3c6b229679ef9014ac98573f45fd43
[ "BSD-3-Clause" ]
null
null
null
models/polytope_constraints.py
mbroso/constraintnet_facial_detect
3f53a4694f3c6b229679ef9014ac98573f45fd43
[ "BSD-3-Clause" ]
null
null
null
"""This file summarizes functionality for the construction of ConstraintNet with output-constraints in form of convex polytopes. It is possible to constrain output-parts to different convex polytopes independently. The functionality for modelling the output-constraints consists namely of: - Functors to create a tensor representation g(s) of the constraint parameter s. The functor can be selected via the option opts.opts2constr_para_repr. E.g. opts.opts2constr_para_repr = 'opts2const_feat_planes' would call the function opts2const_feat_planes which instantiate the functor ConstFeatPlanes. ConstFeatPlanes is then used for g(s). - Functors to tranform the constraint parameter s into a vertex representation. The vertex representation consists of vertices which describe the convex polytope(s). The functor can be selected via the option opts.opts2constr_para_trf. E.g. opts.opts2constr_para_trf = 'opts2v_polys_bb' would call the function opts2v_polys_bb which instantiate the functor VPolysBB. VPolysBB creates the vertice representation for bounding box constraints. We define the following format for the vertex representation v_polys: v_polys (list): [out_part_1, out_part_2, ...] v_polys is a list with length equal to the number of output parts which should be independently constrained. Each list element in v_polys corresponds to one output part. out_part_i (list): [v_convex_poly_1] Each out_part_i in v_polys is a list of length 1 and the element corresponds to the vertice representation for the convex polytope of the constraint for this part. In future this list could be longer than one to model non convex polytopes by a set of convex polytopes. v_convex_poly_1 (torch tensor): shape (N, n_v, dim_v) The vertice representation for a convex polytope is given by a torch tensor with shape (N, n_v, dim_v). N is the batch size, n_v the number of vertices and dim_v the dimension of the vertices. The entries are given by the coordinates of the vertices. - PyTorch modules for the constraint-guard layer, i.e. the mapping from the intermediate representation z to the constrained output region. The module can be selected via the option opts.opts2constr_guard_layer. For the considered convex polytope constraints in this file, the PyTorch module "Polys" can be selected via opts.opts2constr_guard_layer = 'opts2polys'. Polys constrains different output parts to different convex polytopes. For each output part, the number of vertices of the convex polytope must be added to opts.polys_convex_polys_v_n, the dimension of the vertices to opts.polys_convex_polys_v_dim and a 1 to opts.polys_output_parts (in future non-convex polytopes might be defined and then this number would be the number of convex polytopes it consists of). E.g. consider an output-constraint consisting of three independent constraints for three output parts. Furthermore, the constraint for the first part is a convex polytope in 1d with 2 vertices, the constraint for the second part is a convex polytope in 2d with 3 vertices and the constraint for the third part is a convex polytope in 3d with 5 vertices. Then the options should be set to opts.polys_convex_polys_v_n = [2, 3, 5] opts.polys_convex_polys_v_dim = [1, 2, 3] opts.polys_output_parts = [1, 1, 1] """ import torch import torch.nn as nn import torch.nn.functional as F def opts2const_feat_planes(opts): """Creates ConstFeatPlanes functor by calling its constructor with options from opts. Args: opts (obj): Namespace object with options. Returns: const_feat_planes (obj): Instantiated ConstFeatPlanes functor. """ return ConstFeatPlanes( opts.const_feat_planes_h, opts.const_feat_planes_w, opts.const_feat_planes_n_channels, opts.const_feat_planes_repeat_channels, opts.const_feat_planes_norm_factor ) class ConstFeatPlanes: """This functor generates a tensor representation g(s) of the constraint parameter s. Each component of the constraint parameter s corresponds to <repeat_channels> channels of the generated tensor. The assigned channels have entries with a constant value and are given by a constraint parameter rescaled with a factor. The height and width of the tensor can be specified. """ def __init__(self, h, w, n_channels, repeat_channels=1, norm_factor=1.): """Initialization for setting parameters. Args: h (int): Height of channels. w (int): Width of channels. n_channels (int): Number of channels of generated tensor. Specified number must match n_channels = <length of constraint parameter) * repeat_channels repeat_channels (int): The channel for a constraint parameter can be replicated <repeat_channels> times. norm_factor (float or list): Factor to normalize the values of the tensor. If float, all constraint parameter components are rescaled with this factor. If list, the length of the list must match the number of constraint parameter components and the list elements must be of type float. Each constraint parameter component is then rescaled with the corresponding factor in the list. """ self.h = h self.w = w self.n_channels = n_channels self.repeat_channels = repeat_channels #extract number of constraint parameter components n_constr_para = int(n_channels / repeat_channels) if not n_channels == n_constr_para * repeat_channels: raise ValueError('Number of channels in constraint parameter \ tensor representation must be a \ multiple of repeat_channels. But n_channels={n_channels} \ and repeat_channels={repeat_channels}'.format( n_channels = n_channels, repeat_channels = repeat_channels) ) #convert norm_factor scalar in list format self.norm_factor = norm_factor if isinstance(self.norm_factor, float): norm_factor_value = self.norm_factor self.norm_factor = [] for i in range(n_constr_para): self.norm_factor.append(norm_factor_value) if len(self.norm_factor)==1: norm_factor_value = self.norm_factor[0] self.norm_factor = [] for i in range(n_constr_para): self.norm_factor.append(norm_factor_value) if not len(self.norm_factor) * repeat_channels == n_channels: raise ValueError('Number of norm factors for constr_para must \ match n_channels / repeat_channels. But \ len(norm_factor)={len_norm} is not equal to \ n_channels / repeat_channels = {n_channels} / \ {repeat_channels}'.format( len_norm = len(self.norm_factor), n_channels = n_channels, repeat_channels = repeat_channels) ) def __call__(self, constr_para): """Functor to create tensor representation g(s). Args: constr_para (obj): Pytorch tensor of shape (N, n_constr_para) which specifies the output-constraint. Returns: constr_para_repr (obj): Pytorch tensor for tensor representation g(s) of the constraint parameter with shape (N, c_constr_para_repr, H, W). """ if not self.n_channels == constr_para.shape[1] * self.repeat_channels: raise ValueError('Number of channels of the tensor representation \ of the constraint parameter must match with \ the number of constraint parameter components times \ repeat_channel. But n_channels={n_channels} is \ not equal to n_constr_para * repeat_channels = \ {n_constr_para} * {repeat_channels}'.format( n_channels = self.n_channels, n_constr_para = constr_para.shape[1], repeat_channels = self.repeat_channels) ) #create region feature tensor of correct shape constr_para_repr = constr_para.new( constr_para.shape[0], self.n_channels, self.h, self.w ) #fill the constr_features tensor with the normed constr_para for i, sample in enumerate(constr_para): for j, para in enumerate(sample): j_in = j * self.repeat_channels for l in range(self.repeat_channels): constr_para_repr[i, j_in + l,:,:] = para * self.norm_factor[j] return constr_para_repr def opts2v_polys_bb_rel(opts): """Creates VPolysBbRel functor by calling its constructor with options from opts. Args: opts (obj): Namespace object with options. Returns: v_polys_bb_rel (obj): Instantiated VPolysBbRel functor. """ return VPolysBbRel() class VPolysBbRel: """This functor generates the vertex representation v_polys for bounding box constraints in combination with constraints for the relative relations (The eyes are above the nose and the left eye is in fact left with respect to the right eye). """ def __call__(self, constr_para): """The functor gets the constraint parameter and generates the corresponding vertices representation. Args: constr_para (obj): Torch tensor for the constraint parameter with shape (N, n_constr_para=4). There are 4 constraint parameter components, they are ordered in the following way (l_x, u_x, l_y, u_y). They encode the positions of the boundaries of the bounding box: l_x: left/ lower x u_x: right/ upper x l_y: upper/ lower y (y coordinates start with 0 at the top of the image) u_y: lower/ upper y (y coordinates start with 0 at the top of the image) Returns: v_polys (obj): Vertex representation of the constraint parameter. The output y for the neural network is ordered in the following way: (x_nose, x_lefteye, y_righteye, y_lefteye, y_righteye, y_nose) """ #1d polytope for x_nose #shape poly_1d (N, n_v=2, dim_v=1), dim_vertices: x_nose poly_1d = constr_para.new(constr_para.shape[0], 2, 1) #v_1 = (l_x) poly_1d[:, 0, 0] = constr_para[:, 0] #v_2 = (u_x) poly_1d[:, 1, 0] = constr_para[:, 1] #2d polytope for x_lefteye and x_righteye #shape (N, n_v=3, dim_v=2) #dim_vertices: x_lefteye, x_righteye poly_2d = constr_para.new(constr_para.shape[0], 3, 2) #v_1 = (l_x, l_x) poly_2d[:, 0, 0] = constr_para[:, 0] poly_2d[:, 0, 1] = constr_para[:, 0] #v_2 = (l_x, u_x) poly_2d[:, 1, 0] = constr_para[:, 0] poly_2d[:, 1, 1] = constr_para[:, 1] #v_3 = (u_x, u_x) poly_2d[:, 2, 0] = constr_para[:, 1] poly_2d[:, 2, 1] = constr_para[:, 1] #3-d polytope for y_lefteye, y_righteye and y_nose #shape (N, n_v=5, dim_v=3) #dim_vertices: y_lefteye, y_righteye, y_nose poly_3d = constr_para.new(constr_para.shape[0], 5, 3) #v_1 = (l_y, l_y, l_y) poly_3d[:, 0, 0] = constr_para[:, 2] poly_3d[:, 0, 1] = constr_para[:, 2] poly_3d[:, 0, 2] = constr_para[:, 2] #v_2 = (l_y, l_y, u_y) poly_3d[:, 1, 0] = constr_para[:, 2] poly_3d[:, 1, 1] = constr_para[:, 2] poly_3d[:, 1, 2] = constr_para[:, 3] #v_3 = (l_y, u_y, u_y) poly_3d[:, 2, 0] = constr_para[:, 2] poly_3d[:, 2, 1] = constr_para[:, 3] poly_3d[:, 2, 2] = constr_para[:, 3] #v_4 = (u_y, u_y, u_y) poly_3d[:, 3, 0] = constr_para[:, 3] poly_3d[:, 3, 1] = constr_para[:, 3] poly_3d[:, 3, 2] = constr_para[:, 3] #v_5 = (u_y, l_y, u_y) poly_3d[:, 4, 0] = constr_para[:, 3] poly_3d[:, 4, 1] = constr_para[:, 2] poly_3d[:, 4, 2] = constr_para[:, 3] v_polys = [[poly_1d,], [poly_2d,], [poly_3d,]] return v_polys def opts2v_polys_bb(opts): """Creates VPolysBb functor by calling its constructor with options from opts. Args: opts (obj): Namespace object with options. Returns: v_polys_bb (obj): Instantiated VPolysBb functor. """ return VPolysBb(opts.lm_ordering_lm_order) class VPolysBb: """This functor generates the vertex representation v_polys for bounding box constraints, i.e. the landmarks for left eye, right eye and nose are constrained to a bounding box. """ def __init__(self, lm_ordering_lm_order): """Initialization. Args: lm_ordering_lm_order (list): Order of the landmarks for the output of the neural network. E.g. ['nose_x', 'lefteye_x', ... ]. """ self.lm_ordering_lm_order = lm_ordering_lm_order def __call__(self, constr_para): """The functor gets the constraint parameter and generates the vertex representation. Args: constr_para (obj): Torch tensor containing the constraint parameters with shape (N, n_constr_para=4). There are 4 constraint parameters, they are ordered in the following way (l_x, u_x, l_y, u_y). They encode the positions of the boundaries of the bounding box of the face detector: l_x: left/ lower x u_x: right/ upper x l_y: upper/ lower y (y coordinates start with 0 at the top of the image) u_y: lower/ upper y (y coordinates start with 0 at the top of the image) Returns: v_polys (obj): Vertice representation of the constraint parameters. """ v_polys = [] for lm in self.lm_ordering_lm_order: if '_x' in lm: poly_1d = constr_para.new(constr_para.shape[0], 2, 1) # v_1 = (l_x) poly_1d[:, 0, 0] = constr_para[:, 0] # v_2 = (u_x) poly_1d[:, 1, 0] = constr_para[:, 1] elif '_y' in lm: poly_1d = constr_para.new(constr_para.shape[0], 2, 1) # v_1 = (l_y) poly_1d[:, 0, 0] = constr_para[:, 2] # v_2 = (u_y) poly_1d[:, 1, 0] = constr_para[:, 3] v_polys.append([poly_1d]) return v_polys def opts2v_polys_2d_convex_poly(opts): """ parameters from opts. Args: opts (obj): Namespace object returned by parser with settings. Returns: opts2v_polys_lm_xy (obj): Instantiated VPolysLmXY functor. """ return VPolys2DConvexPoly() class VPolys2DConvexPoly: """This functor generates the vertex representation v_polys for constraints in form of one 2d-convex polytope. We assume that the constraint parameter consists of concatenated vertices coordinates (x0,y0, ..., xN,yN) of the convex polytope. """ def __call__(self, constr_para): """The functor gets the constraint parameter and generates the corresponding vertices representation. Args: constr_para (obj): Torch tensor for the constraint parameter with shape (N, n_constr_para). We assume that the constraint parameter consists of concatenated vertices coordinates (x0,y0, ..., xN,yN) of the convex polytope. Returns: v_polys (obj): Vertice representation of the constraint parameter. The output dimensions: (x_lm, y_lm) """ #2-d polytope for landmark within triangle constraint #shape (N, n_vertices, dim_vertices) #dim_vertices: x, y n_vertices = int(constr_para.shape[1] / 2) poly_2d = constr_para.new(constr_para.shape[0], n_vertices, 2) for v in range(n_vertices): poly_2d[:, v, 0] = constr_para[:, 2*v] poly_2d[:, v, 1] = constr_para[:, 2*v+1] v_polys = [[poly_2d,]] return v_polys class ConvexPoly(nn.Module): """ This nn.Module maps a latent vector in R^N to an output region defined by a convex polytope with a fixed number of vertices. The shape of this convex polytope is passed as additional input to this module. """ def __init__(self, convex_poly_format): """Informs the instance about the expected format of convex polytopes. Args: convex_poly_format (tuple): Tuple (n_v, dim_v) with two entries for the number of vertices n_v of and for the dimension of the convex polytope dim_v. """ super(ConvexPoly, self).__init__() self.convex_poly_format = convex_poly_format self.dim_z = self.convex_poly_format2dim_z(convex_poly_format) self.dim_out = self.convex_poly_format2dim_out(convex_poly_format) @staticmethod def convex_poly_format2dim_z(convex_poly_format): """Extracts the required dimensions for the intermediate variable z from convex_poly_format. Args: convex_poly_format (tuple): Tuples (n_v, dim_v) with number of vertices and number of dimensions of convex polytope. Returns: dim_out (int): Number of output dimensions for given convex_poly_format. """ return convex_poly_format[0] @staticmethod def convex_poly_format2dim_out(convex_poly_format): """Extracts the number of output dimensions from convex_poly_format. Args: convex_poly_format (tuple): Tuples (n_v, dim_v) with number of vertices and number of dimensions of convex polytope. Returns: dim_out (int): Number of output dimensions for given convex_poly_format. """ return convex_poly_format[1] @staticmethod def v_convex_poly2convex_poly_format(v_convex_poly): """Extract the convex_poly_format from vertex representation of convex polytope. Args: v_convex_poly (obj): Torch tensor representing the vertex representation of the convex polytope. Returns: v_convex_poly_format (tuple): Tuple of the number of vertices and the dimension (n_v, dim_v). """ n_v = v_convex_poly.shape[1] dim_v = v_convex_poly.shape[2] return (n_v, dim_v) def forward(self, z, v_convex_poly): """ Args: z (obj): Torch tensor with latent representation. Shape (N, n_v) v_convex_poly (obj): Pytorch tensor with convex polytope representation. Shape (N, n_v, dim_v). Returns: out (obj): Torch tensor with shape (N, dim_v). Each output is within convex polytope specified by v_convex_poly. """ #check convex_poly_format obs_convex_poly_format = self.v_convex_poly2convex_poly_format(v_convex_poly) if not self.convex_poly_format == obs_convex_poly_format: raise TypeError('Expected convex_poly_format does not match \ observed one.') if not z.shape[1] == self.dim_z: raise TypeError('Expected {z_dim} dimensions for latent \ representation but observed {z_dim_nn}.'.format( z_dim = self.dim_z, z_dim_nn = z.shape[1]) ) #shape of z: (N, n_v) p = F.softmax(z) #change shape to: (N, 1, n_v) p = p.view( p.shape[0], -1, p.shape[1] ) #p(N, 1, n_v) * v_convex_poly (N, n_v, dim_v) #= out (N, 1, dim_v) out = torch.bmm(p, v_convex_poly) #out (N, dim_v) out = out.view(out.shape[0], -1) #check output dimensions if not out.shape[1] == self.dim_out: raise TypeError('Expected {dim_out} output dimensions but observed \ {dim_out_nn}.'.format( dim_out = self.dim_out, dim_out_nn = out.shape[1]) ) return out class Poly(nn.Module): """This nn.Module maps an intermediate variable z to an output region in form of a polytope which is defined by several convex polytopes. The shape of the non convex polytope is passed by a number of convex polytopes as additional input. Note: The functionality for non-convex polytopes is not considered in the paper and focus of future research. """ def __init__(self, poly_format): """Generates information about the required dimension of the intermediate variable z and the output dimension via poly_format. Args: poly_format (list): List of tuples (n_v, dim_v) for each convex polytope which is part of the total polytope. """ super(Poly, self).__init__() #ConvexPoly nn.Module is used for several polytopes self.convex_polys = [] for convex_poly_format in poly_format: self.convex_polys.append(ConvexPoly(convex_poly_format)) self.poly_format = poly_format #number of convex polytopes self.n_convex_poly = self.poly_format2n_convex_poly(poly_format) #expected dimension of the latent representation self.dim_z = self.poly_format2dim_z(poly_format) #expected dimensions of the output self.dim_out = self.poly_format2dim_out(poly_format) if self.n_convex_poly == 0: raise TypeError('Polytope must be constructed by at least one \ convex polytope.') @staticmethod def poly_format2dim_z(poly_format): """Extracts the required dimensions of the intermediate variable z from poly_format. Args: poly_format (list): List of tuples (n_v, dim_v) for each convex polytope which is part of the total polytope. Returns: dim_z (int): Number of latent vector dimensions for given poly_format. """ #dimension of the latent representation dim_z = 0 for convex_poly_format in poly_format: dim_z += ConvexPoly.convex_poly_format2dim_z(convex_poly_format) #if the polytope is described by more than one convex polytope a #softmax is added and n_convex_poly = Poly.poly_format2n_convex_poly(poly_format) if n_convex_poly > 1: self.dim_z += n_convex_poly return dim_z @staticmethod def poly_format2dim_out(poly_format): """Extracts the number of output dimensions from poly_format. Args: poly_format (list): List of tuples (n_v, dim_v) for each convex polytope which is part of the total polytope. Returns: dim_out (int): Number of output dimensions for given poly_format. """ #dimensions of the output dim_out = 0 for convex_poly_format in poly_format: dim_out += ConvexPoly.convex_poly_format2dim_out(convex_poly_format) #if the polytope is described by more than one convex polytope a #softmax is added and n_convex_poly = Poly.poly_format2n_convex_poly(poly_format) if n_convex_poly > 1: self.dim_out += n_convex_poly return dim_out @staticmethod def poly_format2n_convex_poly(poly_format): """Extracts the number of convex polytopes from poly_format. Args: poly_format (list): List of tuples (n_v, dim_v) for each convex polytope which is part of the total polytope. Returns: n_convex_poly (int): Number of convex polytopes for given poly_format. """ return len(poly_format) @staticmethod def v_poly2poly_format(v_poly): """Extract the polytope format from vertex description of several convex polytopes. Args: v_poly (list): List of convex polytope vertice representations which describe an eventually non-convex polytope. v_poly consists of torch tensor elements. Returns: poly_format (list): List of tuples (N, n_v, dim_v) of convex polytopes. """ poly_format = [] for v_convex_poly in v_poly: convex_poly_format = ConvexPoly.v_convex_poly2convex_poly_format(v_convex_poly) poly_format.append(convex_poly_format) return poly_format def forward(self, z, v_poly): """ Args: z (obj): Torch tensor with intermediate representation with shape (N,dim_z). dim_z = sum of number of vertices of convex polytopes + number of convex polytopes when this number is at least two. v_poly (list): List of Torch tensors (N, n_v, dim_v) representing convex polytopes. [ (), (), ...] Returns: out (obj): Torch tensor of shape (N, n_out). n_out = sum of dimensions of each convex polytope + number of convex polytopes when this number is at least two. Format is (p_1, ..., p_K, y_1_1, .. y_1_L, ..., y_k_1, .. y_K_M) p_1, ... p_K: probabilities for each convex polytope when number of convex polytopes is greater equal 2. Otherwise these probabilities are discarded. y_i_j: Coordinate j within convex polytope i. """ if not z.shape[1] == self.dim_z: raise TypeError('Dimension of latent representation in nn is \ {dim_z_nn} and required for polytope is {dim_z_poly}. \ They should be equal.'.format( dim_z_nn = z.shape[1], dim_z_poly = self.dim_z) ) if not self.poly_format == self.v_poly2poly_format(v_poly): raise TypeError('Expectet poly_format, i.e. number of convex \ polytopes, number of vertices and their dimensions, does \ not match with passed vertices representation of \ polytope.') #add probabilities for each convex polytope to the output when number #of them is greater or equal two. out = z.new(z.shape[0], self.dim_out) z_current_idx = 0 out_current_idx = 0 if self.n_convex_poly > 1: #shape: (N, n_convex_poly) out = F.softmax(z[:,0:self.n_convex_poly]) z_current_idx = self.n_convex_poly out_current_idx = self.n_convex_poly for i, convex_poly in enumerate(self.convex_polys): v_convex_poly = v_poly[i] out[:, out_current_idx: out_current_idx + convex_poly.dim_out] = \ convex_poly( z[:, z_current_idx: z_current_idx + convex_poly.dim_z], v_convex_poly) z_current_idx += convex_poly.dim_z out_current_idx += convex_poly.dim_out return out def opts2polys(opts): """Creates Polys nn.Modules by calling its constructor with options from opts. Args: opts (obj): Namespace object with options. Returns: polys (obj): Instantiated Polys nn.Module. """ #e.g. poly_formats = [[(2,1)],[(3,2)],[(5,3)]] #opts.polys_convex_polys_v_n = 2, 3, 5 #opts.polys_convex_polys_v_dim = 1, 2, 3 #opts.polys_output_parts = 1, 1, 1 if not len(opts.polys_convex_polys_v_n) == len(opts.polys_convex_polys_v_dim): raise TypeError('Number of list elements in opts.polys_convex_polys_v_n \ and opts.polys_convex_polys_v_dim must be equal but is not.') if not len(opts.polys_convex_polys_v_n) == len(opts.polys_output_parts): raise TypeError('Number of list elements in opts.polys_convex_polys_v_n \ and opts.polys_output_parts must be equal but is not.') poly_formats = [] current_idx = 0 for n_convex_polys in opts.polys_output_parts: poly_format = [] for i_convex_poly in range(n_convex_polys): v_n = opts.polys_convex_polys_v_n[i_convex_poly + current_idx] v_dim = opts.polys_convex_polys_v_dim[i_convex_poly + current_idx] poly_format.append((v_n, v_dim)) current_idx += n_convex_polys poly_formats.append(poly_format) print('Polys loaded as constraint-guard layer.') return Polys(poly_formats) class Polys(nn.Module): """Constraint-guard layer to constrain output-parts to polytopes. Currently we consider only convex polytopes. Different output parts are constrained to different polytopes independently. These polytopes are passed to this functor as additional input in the vertices format v_polys. """ def __init__(self, poly_formats): """Generates information about required dimensions for intermediate representation and output dimensions. Args: poly_formats (list): List of poly_format objects (see Poly) for the different polytopes of the output parts. """ super(Polys, self).__init__() self.poly_formats = poly_formats self.polys = [] for poly_format in self.poly_formats: poly = Poly(poly_format) self.polys.append(poly) #expected number of dimensions for intermediate variable z self.dim_z = self.poly_formats2dim_z(poly_formats) #expected number of ouput dimensions self.dim_out = self.poly_formats2dim_out(poly_formats) @staticmethod def poly_formats2dim_z(poly_formats): """Extracts the number of required dimensions of the intermediate variable z from poly_formats. Args: poly_formats (list): List of poly_format objects (see Poly) for the different polytopes of the output parts. Returns: dim_z (int): Number of required dimensions of intermediate variable. """ dim_z = 0 for poly_format in poly_formats: dim_z += Poly.poly_format2dim_z(poly_format) return dim_z @staticmethod def poly_formats2dim_out(poly_formats): """Extracts the number of output dimensions from poly_formats. Args: poly_formats (list): List of poly_format objects (see Poly) for the different polytopes of the output parts. Returns: dim_out (int): Number of output dimensions for given poly_format. """ dim_out = 0 for poly_format in poly_formats: dim_out += Poly.poly_format2dim_out(poly_format) return dim_out @staticmethod def v_polys2poly_formats(v_polys): """Extract the polytope formats from vertex representation of several polytopes. Args: v_polys (list): List of polytope vertex representations. v_polys consists of list elements. Returns: poly_formats (list): List of poly_format elements. """ poly_formats = [] for v_poly in v_polys: poly_format = Poly.v_poly2poly_format(v_poly) poly_formats.append(poly_format) return poly_formats def forward(self, z, v_polys): """ Args: z (obj): Torch tensor with latent representation. Shape (N, n_z). v_polys (list): List with polytope description for different output parts. Returns: out (obj): Torch tensor with """ #check correct shape of latent representation if not z.shape[1] == self.dim_z: raise TypeError('Dimension of intermediate representation z is \ {dim_z_nn}, but {dim_z} was expected.'.format( dim_z_nn = z.shape[1], dim_z = self.dim_z) ) #check if v_polys maps with expected poly_formats if not self.v_polys2poly_formats(v_polys) == self.poly_formats: raise TypeError('Expected format of v_polys given by poly_formats \ does not match observed format inferred from v_polys. \n \ poly_formats: {poly_formats} \n \ v_polys2poly_formats(v_polys): {polys2polys_format}'.format( poly_formats=self.poly_formats, polys2polys_format=self.v_polys2poly_formats(v_polys) )) #output tensor with required dimension y = z.new(z.shape[0], self.dim_out) z_current_idx = 0 y_current_idx = 0 for i, poly in enumerate(self.polys): dim_z_i = poly.dim_z dim_y_i = poly.dim_out v_poly = v_polys[i] y[:, y_current_idx: y_current_idx + dim_y_i] = \ poly(z[:, z_current_idx: z_current_idx + dim_z_i], v_poly) z_current_idx += dim_z_i y_current_idx += dim_y_i return y
41.122183
96
0.60855
"""This file summarizes functionality for the construction of ConstraintNet with output-constraints in form of convex polytopes. It is possible to constrain output-parts to different convex polytopes independently. The functionality for modelling the output-constraints consists namely of: - Functors to create a tensor representation g(s) of the constraint parameter s. The functor can be selected via the option opts.opts2constr_para_repr. E.g. opts.opts2constr_para_repr = 'opts2const_feat_planes' would call the function opts2const_feat_planes which instantiate the functor ConstFeatPlanes. ConstFeatPlanes is then used for g(s). - Functors to tranform the constraint parameter s into a vertex representation. The vertex representation consists of vertices which describe the convex polytope(s). The functor can be selected via the option opts.opts2constr_para_trf. E.g. opts.opts2constr_para_trf = 'opts2v_polys_bb' would call the function opts2v_polys_bb which instantiate the functor VPolysBB. VPolysBB creates the vertice representation for bounding box constraints. We define the following format for the vertex representation v_polys: v_polys (list): [out_part_1, out_part_2, ...] v_polys is a list with length equal to the number of output parts which should be independently constrained. Each list element in v_polys corresponds to one output part. out_part_i (list): [v_convex_poly_1] Each out_part_i in v_polys is a list of length 1 and the element corresponds to the vertice representation for the convex polytope of the constraint for this part. In future this list could be longer than one to model non convex polytopes by a set of convex polytopes. v_convex_poly_1 (torch tensor): shape (N, n_v, dim_v) The vertice representation for a convex polytope is given by a torch tensor with shape (N, n_v, dim_v). N is the batch size, n_v the number of vertices and dim_v the dimension of the vertices. The entries are given by the coordinates of the vertices. - PyTorch modules for the constraint-guard layer, i.e. the mapping from the intermediate representation z to the constrained output region. The module can be selected via the option opts.opts2constr_guard_layer. For the considered convex polytope constraints in this file, the PyTorch module "Polys" can be selected via opts.opts2constr_guard_layer = 'opts2polys'. Polys constrains different output parts to different convex polytopes. For each output part, the number of vertices of the convex polytope must be added to opts.polys_convex_polys_v_n, the dimension of the vertices to opts.polys_convex_polys_v_dim and a 1 to opts.polys_output_parts (in future non-convex polytopes might be defined and then this number would be the number of convex polytopes it consists of). E.g. consider an output-constraint consisting of three independent constraints for three output parts. Furthermore, the constraint for the first part is a convex polytope in 1d with 2 vertices, the constraint for the second part is a convex polytope in 2d with 3 vertices and the constraint for the third part is a convex polytope in 3d with 5 vertices. Then the options should be set to opts.polys_convex_polys_v_n = [2, 3, 5] opts.polys_convex_polys_v_dim = [1, 2, 3] opts.polys_output_parts = [1, 1, 1] """ import torch import torch.nn as nn import torch.nn.functional as F def opts2const_feat_planes(opts): """Creates ConstFeatPlanes functor by calling its constructor with options from opts. Args: opts (obj): Namespace object with options. Returns: const_feat_planes (obj): Instantiated ConstFeatPlanes functor. """ return ConstFeatPlanes( opts.const_feat_planes_h, opts.const_feat_planes_w, opts.const_feat_planes_n_channels, opts.const_feat_planes_repeat_channels, opts.const_feat_planes_norm_factor ) class ConstFeatPlanes: """This functor generates a tensor representation g(s) of the constraint parameter s. Each component of the constraint parameter s corresponds to <repeat_channels> channels of the generated tensor. The assigned channels have entries with a constant value and are given by a constraint parameter rescaled with a factor. The height and width of the tensor can be specified. """ def __init__(self, h, w, n_channels, repeat_channels=1, norm_factor=1.): """Initialization for setting parameters. Args: h (int): Height of channels. w (int): Width of channels. n_channels (int): Number of channels of generated tensor. Specified number must match n_channels = <length of constraint parameter) * repeat_channels repeat_channels (int): The channel for a constraint parameter can be replicated <repeat_channels> times. norm_factor (float or list): Factor to normalize the values of the tensor. If float, all constraint parameter components are rescaled with this factor. If list, the length of the list must match the number of constraint parameter components and the list elements must be of type float. Each constraint parameter component is then rescaled with the corresponding factor in the list. """ self.h = h self.w = w self.n_channels = n_channels self.repeat_channels = repeat_channels #extract number of constraint parameter components n_constr_para = int(n_channels / repeat_channels) if not n_channels == n_constr_para * repeat_channels: raise ValueError('Number of channels in constraint parameter \ tensor representation must be a \ multiple of repeat_channels. But n_channels={n_channels} \ and repeat_channels={repeat_channels}'.format( n_channels = n_channels, repeat_channels = repeat_channels) ) #convert norm_factor scalar in list format self.norm_factor = norm_factor if isinstance(self.norm_factor, float): norm_factor_value = self.norm_factor self.norm_factor = [] for i in range(n_constr_para): self.norm_factor.append(norm_factor_value) if len(self.norm_factor)==1: norm_factor_value = self.norm_factor[0] self.norm_factor = [] for i in range(n_constr_para): self.norm_factor.append(norm_factor_value) if not len(self.norm_factor) * repeat_channels == n_channels: raise ValueError('Number of norm factors for constr_para must \ match n_channels / repeat_channels. But \ len(norm_factor)={len_norm} is not equal to \ n_channels / repeat_channels = {n_channels} / \ {repeat_channels}'.format( len_norm = len(self.norm_factor), n_channels = n_channels, repeat_channels = repeat_channels) ) def __call__(self, constr_para): """Functor to create tensor representation g(s). Args: constr_para (obj): Pytorch tensor of shape (N, n_constr_para) which specifies the output-constraint. Returns: constr_para_repr (obj): Pytorch tensor for tensor representation g(s) of the constraint parameter with shape (N, c_constr_para_repr, H, W). """ if not self.n_channels == constr_para.shape[1] * self.repeat_channels: raise ValueError('Number of channels of the tensor representation \ of the constraint parameter must match with \ the number of constraint parameter components times \ repeat_channel. But n_channels={n_channels} is \ not equal to n_constr_para * repeat_channels = \ {n_constr_para} * {repeat_channels}'.format( n_channels = self.n_channels, n_constr_para = constr_para.shape[1], repeat_channels = self.repeat_channels) ) #create region feature tensor of correct shape constr_para_repr = constr_para.new( constr_para.shape[0], self.n_channels, self.h, self.w ) #fill the constr_features tensor with the normed constr_para for i, sample in enumerate(constr_para): for j, para in enumerate(sample): j_in = j * self.repeat_channels for l in range(self.repeat_channels): constr_para_repr[i, j_in + l,:,:] = para * self.norm_factor[j] return constr_para_repr def opts2v_polys_bb_rel(opts): """Creates VPolysBbRel functor by calling its constructor with options from opts. Args: opts (obj): Namespace object with options. Returns: v_polys_bb_rel (obj): Instantiated VPolysBbRel functor. """ return VPolysBbRel() class VPolysBbRel: """This functor generates the vertex representation v_polys for bounding box constraints in combination with constraints for the relative relations (The eyes are above the nose and the left eye is in fact left with respect to the right eye). """ def __init__(self): pass def __call__(self, constr_para): """The functor gets the constraint parameter and generates the corresponding vertices representation. Args: constr_para (obj): Torch tensor for the constraint parameter with shape (N, n_constr_para=4). There are 4 constraint parameter components, they are ordered in the following way (l_x, u_x, l_y, u_y). They encode the positions of the boundaries of the bounding box: l_x: left/ lower x u_x: right/ upper x l_y: upper/ lower y (y coordinates start with 0 at the top of the image) u_y: lower/ upper y (y coordinates start with 0 at the top of the image) Returns: v_polys (obj): Vertex representation of the constraint parameter. The output y for the neural network is ordered in the following way: (x_nose, x_lefteye, y_righteye, y_lefteye, y_righteye, y_nose) """ #1d polytope for x_nose #shape poly_1d (N, n_v=2, dim_v=1), dim_vertices: x_nose poly_1d = constr_para.new(constr_para.shape[0], 2, 1) #v_1 = (l_x) poly_1d[:, 0, 0] = constr_para[:, 0] #v_2 = (u_x) poly_1d[:, 1, 0] = constr_para[:, 1] #2d polytope for x_lefteye and x_righteye #shape (N, n_v=3, dim_v=2) #dim_vertices: x_lefteye, x_righteye poly_2d = constr_para.new(constr_para.shape[0], 3, 2) #v_1 = (l_x, l_x) poly_2d[:, 0, 0] = constr_para[:, 0] poly_2d[:, 0, 1] = constr_para[:, 0] #v_2 = (l_x, u_x) poly_2d[:, 1, 0] = constr_para[:, 0] poly_2d[:, 1, 1] = constr_para[:, 1] #v_3 = (u_x, u_x) poly_2d[:, 2, 0] = constr_para[:, 1] poly_2d[:, 2, 1] = constr_para[:, 1] #3-d polytope for y_lefteye, y_righteye and y_nose #shape (N, n_v=5, dim_v=3) #dim_vertices: y_lefteye, y_righteye, y_nose poly_3d = constr_para.new(constr_para.shape[0], 5, 3) #v_1 = (l_y, l_y, l_y) poly_3d[:, 0, 0] = constr_para[:, 2] poly_3d[:, 0, 1] = constr_para[:, 2] poly_3d[:, 0, 2] = constr_para[:, 2] #v_2 = (l_y, l_y, u_y) poly_3d[:, 1, 0] = constr_para[:, 2] poly_3d[:, 1, 1] = constr_para[:, 2] poly_3d[:, 1, 2] = constr_para[:, 3] #v_3 = (l_y, u_y, u_y) poly_3d[:, 2, 0] = constr_para[:, 2] poly_3d[:, 2, 1] = constr_para[:, 3] poly_3d[:, 2, 2] = constr_para[:, 3] #v_4 = (u_y, u_y, u_y) poly_3d[:, 3, 0] = constr_para[:, 3] poly_3d[:, 3, 1] = constr_para[:, 3] poly_3d[:, 3, 2] = constr_para[:, 3] #v_5 = (u_y, l_y, u_y) poly_3d[:, 4, 0] = constr_para[:, 3] poly_3d[:, 4, 1] = constr_para[:, 2] poly_3d[:, 4, 2] = constr_para[:, 3] v_polys = [[poly_1d,], [poly_2d,], [poly_3d,]] return v_polys def opts2v_polys_bb(opts): """Creates VPolysBb functor by calling its constructor with options from opts. Args: opts (obj): Namespace object with options. Returns: v_polys_bb (obj): Instantiated VPolysBb functor. """ return VPolysBb(opts.lm_ordering_lm_order) class VPolysBb: """This functor generates the vertex representation v_polys for bounding box constraints, i.e. the landmarks for left eye, right eye and nose are constrained to a bounding box. """ def __init__(self, lm_ordering_lm_order): """Initialization. Args: lm_ordering_lm_order (list): Order of the landmarks for the output of the neural network. E.g. ['nose_x', 'lefteye_x', ... ]. """ self.lm_ordering_lm_order = lm_ordering_lm_order def __call__(self, constr_para): """The functor gets the constraint parameter and generates the vertex representation. Args: constr_para (obj): Torch tensor containing the constraint parameters with shape (N, n_constr_para=4). There are 4 constraint parameters, they are ordered in the following way (l_x, u_x, l_y, u_y). They encode the positions of the boundaries of the bounding box of the face detector: l_x: left/ lower x u_x: right/ upper x l_y: upper/ lower y (y coordinates start with 0 at the top of the image) u_y: lower/ upper y (y coordinates start with 0 at the top of the image) Returns: v_polys (obj): Vertice representation of the constraint parameters. """ v_polys = [] for lm in self.lm_ordering_lm_order: if '_x' in lm: poly_1d = constr_para.new(constr_para.shape[0], 2, 1) # v_1 = (l_x) poly_1d[:, 0, 0] = constr_para[:, 0] # v_2 = (u_x) poly_1d[:, 1, 0] = constr_para[:, 1] elif '_y' in lm: poly_1d = constr_para.new(constr_para.shape[0], 2, 1) # v_1 = (l_y) poly_1d[:, 0, 0] = constr_para[:, 2] # v_2 = (u_y) poly_1d[:, 1, 0] = constr_para[:, 3] v_polys.append([poly_1d]) return v_polys def opts2v_polys_2d_convex_poly(opts): """ parameters from opts. Args: opts (obj): Namespace object returned by parser with settings. Returns: opts2v_polys_lm_xy (obj): Instantiated VPolysLmXY functor. """ return VPolys2DConvexPoly() class VPolys2DConvexPoly: """This functor generates the vertex representation v_polys for constraints in form of one 2d-convex polytope. We assume that the constraint parameter consists of concatenated vertices coordinates (x0,y0, ..., xN,yN) of the convex polytope. """ def __init__(self): pass def __call__(self, constr_para): """The functor gets the constraint parameter and generates the corresponding vertices representation. Args: constr_para (obj): Torch tensor for the constraint parameter with shape (N, n_constr_para). We assume that the constraint parameter consists of concatenated vertices coordinates (x0,y0, ..., xN,yN) of the convex polytope. Returns: v_polys (obj): Vertice representation of the constraint parameter. The output dimensions: (x_lm, y_lm) """ #2-d polytope for landmark within triangle constraint #shape (N, n_vertices, dim_vertices) #dim_vertices: x, y n_vertices = int(constr_para.shape[1] / 2) poly_2d = constr_para.new(constr_para.shape[0], n_vertices, 2) for v in range(n_vertices): poly_2d[:, v, 0] = constr_para[:, 2*v] poly_2d[:, v, 1] = constr_para[:, 2*v+1] v_polys = [[poly_2d,]] return v_polys class ConvexPoly(nn.Module): """ This nn.Module maps a latent vector in R^N to an output region defined by a convex polytope with a fixed number of vertices. The shape of this convex polytope is passed as additional input to this module. """ def __init__(self, convex_poly_format): """Informs the instance about the expected format of convex polytopes. Args: convex_poly_format (tuple): Tuple (n_v, dim_v) with two entries for the number of vertices n_v of and for the dimension of the convex polytope dim_v. """ super(ConvexPoly, self).__init__() self.convex_poly_format = convex_poly_format self.dim_z = self.convex_poly_format2dim_z(convex_poly_format) self.dim_out = self.convex_poly_format2dim_out(convex_poly_format) @staticmethod def convex_poly_format2dim_z(convex_poly_format): """Extracts the required dimensions for the intermediate variable z from convex_poly_format. Args: convex_poly_format (tuple): Tuples (n_v, dim_v) with number of vertices and number of dimensions of convex polytope. Returns: dim_out (int): Number of output dimensions for given convex_poly_format. """ return convex_poly_format[0] @staticmethod def convex_poly_format2dim_out(convex_poly_format): """Extracts the number of output dimensions from convex_poly_format. Args: convex_poly_format (tuple): Tuples (n_v, dim_v) with number of vertices and number of dimensions of convex polytope. Returns: dim_out (int): Number of output dimensions for given convex_poly_format. """ return convex_poly_format[1] @staticmethod def v_convex_poly2convex_poly_format(v_convex_poly): """Extract the convex_poly_format from vertex representation of convex polytope. Args: v_convex_poly (obj): Torch tensor representing the vertex representation of the convex polytope. Returns: v_convex_poly_format (tuple): Tuple of the number of vertices and the dimension (n_v, dim_v). """ n_v = v_convex_poly.shape[1] dim_v = v_convex_poly.shape[2] return (n_v, dim_v) def forward(self, z, v_convex_poly): """ Args: z (obj): Torch tensor with latent representation. Shape (N, n_v) v_convex_poly (obj): Pytorch tensor with convex polytope representation. Shape (N, n_v, dim_v). Returns: out (obj): Torch tensor with shape (N, dim_v). Each output is within convex polytope specified by v_convex_poly. """ #check convex_poly_format obs_convex_poly_format = self.v_convex_poly2convex_poly_format(v_convex_poly) if not self.convex_poly_format == obs_convex_poly_format: raise TypeError('Expected convex_poly_format does not match \ observed one.') if not z.shape[1] == self.dim_z: raise TypeError('Expected {z_dim} dimensions for latent \ representation but observed {z_dim_nn}.'.format( z_dim = self.dim_z, z_dim_nn = z.shape[1]) ) #shape of z: (N, n_v) p = F.softmax(z) #change shape to: (N, 1, n_v) p = p.view( p.shape[0], -1, p.shape[1] ) #p(N, 1, n_v) * v_convex_poly (N, n_v, dim_v) #= out (N, 1, dim_v) out = torch.bmm(p, v_convex_poly) #out (N, dim_v) out = out.view(out.shape[0], -1) #check output dimensions if not out.shape[1] == self.dim_out: raise TypeError('Expected {dim_out} output dimensions but observed \ {dim_out_nn}.'.format( dim_out = self.dim_out, dim_out_nn = out.shape[1]) ) return out class Poly(nn.Module): """This nn.Module maps an intermediate variable z to an output region in form of a polytope which is defined by several convex polytopes. The shape of the non convex polytope is passed by a number of convex polytopes as additional input. Note: The functionality for non-convex polytopes is not considered in the paper and focus of future research. """ def __init__(self, poly_format): """Generates information about the required dimension of the intermediate variable z and the output dimension via poly_format. Args: poly_format (list): List of tuples (n_v, dim_v) for each convex polytope which is part of the total polytope. """ super(Poly, self).__init__() #ConvexPoly nn.Module is used for several polytopes self.convex_polys = [] for convex_poly_format in poly_format: self.convex_polys.append(ConvexPoly(convex_poly_format)) self.poly_format = poly_format #number of convex polytopes self.n_convex_poly = self.poly_format2n_convex_poly(poly_format) #expected dimension of the latent representation self.dim_z = self.poly_format2dim_z(poly_format) #expected dimensions of the output self.dim_out = self.poly_format2dim_out(poly_format) if self.n_convex_poly == 0: raise TypeError('Polytope must be constructed by at least one \ convex polytope.') @staticmethod def poly_format2dim_z(poly_format): """Extracts the required dimensions of the intermediate variable z from poly_format. Args: poly_format (list): List of tuples (n_v, dim_v) for each convex polytope which is part of the total polytope. Returns: dim_z (int): Number of latent vector dimensions for given poly_format. """ #dimension of the latent representation dim_z = 0 for convex_poly_format in poly_format: dim_z += ConvexPoly.convex_poly_format2dim_z(convex_poly_format) #if the polytope is described by more than one convex polytope a #softmax is added and n_convex_poly = Poly.poly_format2n_convex_poly(poly_format) if n_convex_poly > 1: self.dim_z += n_convex_poly return dim_z @staticmethod def poly_format2dim_out(poly_format): """Extracts the number of output dimensions from poly_format. Args: poly_format (list): List of tuples (n_v, dim_v) for each convex polytope which is part of the total polytope. Returns: dim_out (int): Number of output dimensions for given poly_format. """ #dimensions of the output dim_out = 0 for convex_poly_format in poly_format: dim_out += ConvexPoly.convex_poly_format2dim_out(convex_poly_format) #if the polytope is described by more than one convex polytope a #softmax is added and n_convex_poly = Poly.poly_format2n_convex_poly(poly_format) if n_convex_poly > 1: self.dim_out += n_convex_poly return dim_out @staticmethod def poly_format2n_convex_poly(poly_format): """Extracts the number of convex polytopes from poly_format. Args: poly_format (list): List of tuples (n_v, dim_v) for each convex polytope which is part of the total polytope. Returns: n_convex_poly (int): Number of convex polytopes for given poly_format. """ return len(poly_format) @staticmethod def v_poly2poly_format(v_poly): """Extract the polytope format from vertex description of several convex polytopes. Args: v_poly (list): List of convex polytope vertice representations which describe an eventually non-convex polytope. v_poly consists of torch tensor elements. Returns: poly_format (list): List of tuples (N, n_v, dim_v) of convex polytopes. """ poly_format = [] for v_convex_poly in v_poly: convex_poly_format = ConvexPoly.v_convex_poly2convex_poly_format(v_convex_poly) poly_format.append(convex_poly_format) return poly_format def forward(self, z, v_poly): """ Args: z (obj): Torch tensor with intermediate representation with shape (N,dim_z). dim_z = sum of number of vertices of convex polytopes + number of convex polytopes when this number is at least two. v_poly (list): List of Torch tensors (N, n_v, dim_v) representing convex polytopes. [ (), (), ...] Returns: out (obj): Torch tensor of shape (N, n_out). n_out = sum of dimensions of each convex polytope + number of convex polytopes when this number is at least two. Format is (p_1, ..., p_K, y_1_1, .. y_1_L, ..., y_k_1, .. y_K_M) p_1, ... p_K: probabilities for each convex polytope when number of convex polytopes is greater equal 2. Otherwise these probabilities are discarded. y_i_j: Coordinate j within convex polytope i. """ if not z.shape[1] == self.dim_z: raise TypeError('Dimension of latent representation in nn is \ {dim_z_nn} and required for polytope is {dim_z_poly}. \ They should be equal.'.format( dim_z_nn = z.shape[1], dim_z_poly = self.dim_z) ) if not self.poly_format == self.v_poly2poly_format(v_poly): raise TypeError('Expectet poly_format, i.e. number of convex \ polytopes, number of vertices and their dimensions, does \ not match with passed vertices representation of \ polytope.') #add probabilities for each convex polytope to the output when number #of them is greater or equal two. out = z.new(z.shape[0], self.dim_out) z_current_idx = 0 out_current_idx = 0 if self.n_convex_poly > 1: #shape: (N, n_convex_poly) out = F.softmax(z[:,0:self.n_convex_poly]) z_current_idx = self.n_convex_poly out_current_idx = self.n_convex_poly for i, convex_poly in enumerate(self.convex_polys): v_convex_poly = v_poly[i] out[:, out_current_idx: out_current_idx + convex_poly.dim_out] = \ convex_poly( z[:, z_current_idx: z_current_idx + convex_poly.dim_z], v_convex_poly) z_current_idx += convex_poly.dim_z out_current_idx += convex_poly.dim_out return out def opts2polys(opts): """Creates Polys nn.Modules by calling its constructor with options from opts. Args: opts (obj): Namespace object with options. Returns: polys (obj): Instantiated Polys nn.Module. """ #e.g. poly_formats = [[(2,1)],[(3,2)],[(5,3)]] #opts.polys_convex_polys_v_n = 2, 3, 5 #opts.polys_convex_polys_v_dim = 1, 2, 3 #opts.polys_output_parts = 1, 1, 1 if not len(opts.polys_convex_polys_v_n) == len(opts.polys_convex_polys_v_dim): raise TypeError('Number of list elements in opts.polys_convex_polys_v_n \ and opts.polys_convex_polys_v_dim must be equal but is not.') if not len(opts.polys_convex_polys_v_n) == len(opts.polys_output_parts): raise TypeError('Number of list elements in opts.polys_convex_polys_v_n \ and opts.polys_output_parts must be equal but is not.') poly_formats = [] current_idx = 0 for n_convex_polys in opts.polys_output_parts: poly_format = [] for i_convex_poly in range(n_convex_polys): v_n = opts.polys_convex_polys_v_n[i_convex_poly + current_idx] v_dim = opts.polys_convex_polys_v_dim[i_convex_poly + current_idx] poly_format.append((v_n, v_dim)) current_idx += n_convex_polys poly_formats.append(poly_format) print('Polys loaded as constraint-guard layer.') return Polys(poly_formats) class Polys(nn.Module): """Constraint-guard layer to constrain output-parts to polytopes. Currently we consider only convex polytopes. Different output parts are constrained to different polytopes independently. These polytopes are passed to this functor as additional input in the vertices format v_polys. """ def __init__(self, poly_formats): """Generates information about required dimensions for intermediate representation and output dimensions. Args: poly_formats (list): List of poly_format objects (see Poly) for the different polytopes of the output parts. """ super(Polys, self).__init__() self.poly_formats = poly_formats self.polys = [] for poly_format in self.poly_formats: poly = Poly(poly_format) self.polys.append(poly) #expected number of dimensions for intermediate variable z self.dim_z = self.poly_formats2dim_z(poly_formats) #expected number of ouput dimensions self.dim_out = self.poly_formats2dim_out(poly_formats) @staticmethod def poly_formats2dim_z(poly_formats): """Extracts the number of required dimensions of the intermediate variable z from poly_formats. Args: poly_formats (list): List of poly_format objects (see Poly) for the different polytopes of the output parts. Returns: dim_z (int): Number of required dimensions of intermediate variable. """ dim_z = 0 for poly_format in poly_formats: dim_z += Poly.poly_format2dim_z(poly_format) return dim_z @staticmethod def poly_formats2dim_out(poly_formats): """Extracts the number of output dimensions from poly_formats. Args: poly_formats (list): List of poly_format objects (see Poly) for the different polytopes of the output parts. Returns: dim_out (int): Number of output dimensions for given poly_format. """ dim_out = 0 for poly_format in poly_formats: dim_out += Poly.poly_format2dim_out(poly_format) return dim_out @staticmethod def v_polys2poly_formats(v_polys): """Extract the polytope formats from vertex representation of several polytopes. Args: v_polys (list): List of polytope vertex representations. v_polys consists of list elements. Returns: poly_formats (list): List of poly_format elements. """ poly_formats = [] for v_poly in v_polys: poly_format = Poly.v_poly2poly_format(v_poly) poly_formats.append(poly_format) return poly_formats def forward(self, z, v_polys): """ Args: z (obj): Torch tensor with latent representation. Shape (N, n_z). v_polys (list): List with polytope description for different output parts. Returns: out (obj): Torch tensor with """ #check correct shape of latent representation if not z.shape[1] == self.dim_z: raise TypeError('Dimension of intermediate representation z is \ {dim_z_nn}, but {dim_z} was expected.'.format( dim_z_nn = z.shape[1], dim_z = self.dim_z) ) #check if v_polys maps with expected poly_formats if not self.v_polys2poly_formats(v_polys) == self.poly_formats: raise TypeError('Expected format of v_polys given by poly_formats \ does not match observed format inferred from v_polys. \n \ poly_formats: {poly_formats} \n \ v_polys2poly_formats(v_polys): {polys2polys_format}'.format( poly_formats=self.poly_formats, polys2polys_format=self.v_polys2poly_formats(v_polys) )) #output tensor with required dimension y = z.new(z.shape[0], self.dim_out) z_current_idx = 0 y_current_idx = 0 for i, poly in enumerate(self.polys): dim_z_i = poly.dim_z dim_y_i = poly.dim_out v_poly = v_polys[i] y[:, y_current_idx: y_current_idx + dim_y_i] = \ poly(z[:, z_current_idx: z_current_idx + dim_z_i], v_poly) z_current_idx += dim_z_i y_current_idx += dim_y_i return y
22
0
53
8ba910386837b07f76ab57cbfda10782cf3dacef
2,785
py
Python
src/CookieJarRun.py
KaelenCarling/CookieJar
b4c7026b3b50af6c60338208aab1813efb466944
[ "Apache-2.0" ]
2
2021-05-05T20:08:57.000Z
2021-05-05T20:09:00.000Z
src/CookieJarRun.py
KaelenCarling/CookieJar
b4c7026b3b50af6c60338208aab1813efb466944
[ "Apache-2.0" ]
null
null
null
src/CookieJarRun.py
KaelenCarling/CookieJar
b4c7026b3b50af6c60338208aab1813efb466944
[ "Apache-2.0" ]
1
2021-05-05T18:19:11.000Z
2021-05-05T18:19:11.000Z
import tkinter from FireFoxCookieMonster import * from tkinter import * from tkinter.ttk import * # simple function to retrieve the cookies into a dictionary if __name__ == "__main__": root = Tk() # MainApplication(root).pack(side='top', fill='both', expand=True) MainApplication(root) root.mainloop()
31.647727
156
0.667864
import tkinter from FireFoxCookieMonster import * from tkinter import * from tkinter.ttk import * def getCookies(): databaseLocations = findFirefoxCookieDatabase() for databaseLocation in databaseLocations: print("Copying from " + databaseLocation) firefoxCookieMonster = FireFoxCookieMonster(databaseLocation) firefoxCookieMonster.copyDatabase() return firefoxCookieMonster.retrieveCookies() def processDictionary(cookiesDict): returnString = '' for id in cookiesDict: returnString += (f'Name:{cookiesDict[id]["name"]}\n Host:{cookiesDict[id]["host"]}{cookiesDict[id]["path"]}\n Value:{cookiesDict[id]["value"]}\n\n') return returnString class MainApplication(tkinter.Frame): def __init__(self, parent, *args, **kwargs): tkinter.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent # retrieve the cookies cookieDict = getCookies() # rest of the gui here # ensure a consistent GUI size self.grid_propagate(False) # implement stretchability root.grid_rowconfigure(0, weight=0) root.grid_rowconfigure(1, weight=1) root.grid_columnconfigure(0, weight=0) root.grid_columnconfigure(1, weight=1) root.grid_columnconfigure(2, weight=0) root.minsize(width=700, height=420) # title the application root.title('CookieJar') #makes the menu bar menuBar = Menu(root) fileMenu = Menu(root) menuBar.add_cascade(label='File', menu=fileMenu) fileMenu.add_cascade(label='Open cookie file directly') # adds the buttons searchButton = Button(root, text='Search') # add the search searchQuery = Entry(root, textvariable='searchBox', width=100) # add cookie dictionary output cookiesDisplayBox = Text(root) cookieScrollbar = Scrollbar(root, orient=VERTICAL, command=cookiesDisplayBox.yview) # construct the grid of the application # label.grid(row=0, column=0) root.config(menu=menuBar) searchButton.grid(row=0, column=0, sticky='NEW') searchQuery.grid(row=0, column=1, sticky='NEW') cookiesDisplayBox.grid(row=1, column=0, columnspan=2, sticky='NSEW') #cookiesDisplayBox.pack(fill='both', side='left', ) cookieScrollbar.grid(row=1, column=2, sticky='NSW') cookiesDisplayBox.insert(END, processDictionary(cookieDict)) cookiesDisplayBox['yscrollcommand'] = cookieScrollbar.set # simple function to retrieve the cookies into a dictionary if __name__ == "__main__": root = Tk() # MainApplication(root).pack(side='top', fill='both', expand=True) MainApplication(root) root.mainloop()
2,346
16
95
c6f65ae054762a1b75b567b02da9b21b6b1c50bd
1,123
py
Python
examples/wf/pymtbl_wf_analyze.py
BuloZB/pymtbl
914b041a48da9594d1bdac997bae378bdd6b6f58
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
examples/wf/pymtbl_wf_analyze.py
BuloZB/pymtbl
914b041a48da9594d1bdac997bae378bdd6b6f58
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
examples/wf/pymtbl_wf_analyze.py
BuloZB/pymtbl
914b041a48da9594d1bdac997bae378bdd6b6f58
[ "ECL-2.0", "Apache-2.0" ]
1
2018-03-04T03:12:33.000Z
2018-03-04T03:12:33.000Z
#!/usr/bin/env python import string import sys import mtbl if __name__ == '__main__': if not len(sys.argv) == 3: sys.stderr.write('Usage: %s <TXT FILE> <MTBL FILE>\n' % sys.argv[0]) sys.exit(1) main(sys.argv[1], sys.argv[2])
27.390244
76
0.619768
#!/usr/bin/env python import string import sys import mtbl def merge_func(key, val0, val1): i0 = mtbl.varint_decode(val0) i1 = mtbl.varint_decode(val1) return mtbl.varint_encode(i0 + i1) def main(txt_fname, mtbl_fname): txt = open(txt_fname) sorter = mtbl.sorter(merge_func) writer = mtbl.writer(mtbl_fname, compression=mtbl.COMPRESSION_SNAPPY) # trim header while True: line = txt.readline() if line.startswith('*** START OF THIS PROJECT GUTENBERG EBOOK'): break for x in range(0, 5): txt.readline() for line in txt: if line.startswith('End of the Project Gutenberg EBook') or \ line.startswith('*** END OF THIS PROJECT GUTENBERG EBOOK'): break for tok in line.strip().split(): word = tok.strip(string.punctuation).lower() sorter[word] = mtbl.varint_encode(1) sorter.write(writer) if __name__ == '__main__': if not len(sys.argv) == 3: sys.stderr.write('Usage: %s <TXT FILE> <MTBL FILE>\n' % sys.argv[0]) sys.exit(1) main(sys.argv[1], sys.argv[2])
825
0
46
c7e04c588484b142da08ea0353c9b7a85eb9bad5
353
py
Python
ejemplo_4/epy_block_0_0.py
GabrielaGalvis/Lab_Com_2
4b9714ed62a8a428f292ff8ace3cf50fe69fcb33
[ "Apache-2.0" ]
null
null
null
ejemplo_4/epy_block_0_0.py
GabrielaGalvis/Lab_Com_2
4b9714ed62a8a428f292ff8ace3cf50fe69fcb33
[ "Apache-2.0" ]
null
null
null
ejemplo_4/epy_block_0_0.py
GabrielaGalvis/Lab_Com_2
4b9714ed62a8a428f292ff8ace3cf50fe69fcb33
[ "Apache-2.0" ]
null
null
null
import numpy as np from gnuradio import gr
13.074074
43
0.628895
import numpy as np from gnuradio import gr class blk(gr.sync_block): def __init__(self,): """Bloque sqrt""" gr.sync_block.__init__( self, name='Sqrt', in_sig=[np.float32], out_sig=[np.float32] ) def work(self, input_items, output_items): x=input_items[0] y=output_items[0] y[:]=np.sqrt(x) return len(x)
100
178
23
e7f0bc0c3d48e5be1311eacb7034093e6b554f25
1,689
py
Python
responsibleai/tests/tools/shared/test_versions.py
ms-kashyap/responsible-ai-widgets
56906fb30d9b81a5edc5443d24312bc2d32e5165
[ "MIT" ]
119
2021-12-02T21:00:47.000Z
2022-03-31T06:44:31.000Z
responsibleai/tests/tools/shared/test_versions.py
ms-kashyap/responsible-ai-widgets
56906fb30d9b81a5edc5443d24312bc2d32e5165
[ "MIT" ]
293
2021-11-30T16:45:49.000Z
2022-03-31T23:57:13.000Z
responsibleai/tests/tools/shared/test_versions.py
ms-kashyap/responsible-ai-widgets
56906fb30d9b81a5edc5443d24312bc2d32e5165
[ "MIT" ]
28
2021-12-07T17:28:04.000Z
2022-03-31T07:47:11.000Z
# Copyright (c) Microsoft Corporation # Licensed under the MIT License. import re import pytest import semver from responsibleai._tools.shared.versions import CausalVersions
27.241935
72
0.598579
# Copyright (c) Microsoft Corporation # Licensed under the MIT License. import re import pytest import semver from responsibleai._tools.shared.versions import CausalVersions class TestVersions: @pytest.mark.parametrize( 'versions_class', [ CausalVersions, ] ) def test_all_versions_valid(self, versions_class): version_strings = versions_class.get_all() assert len(version_strings) > 0 current = semver.VersionInfo.parse(versions_class.get_current()) for version_string in version_strings: # Check valid semantic version version = semver.VersionInfo.parse(version_string) # Check current version is the latest version assert version.compare(current) <= 0 @pytest.mark.parametrize( 'versions_class', [ CausalVersions, ] ) def test_all_versions_unique(self, versions_class): versions = versions_class.get_all() assert len(versions) > 0 s = set() for version in versions: print(version, s) assert version not in s, f"Version {version} is duplicated" s.add(version) @pytest.mark.parametrize( 'versions_class', [ CausalVersions, ] ) def test_version_name_formats(self, versions_class): for name, _ in vars(versions_class).items(): if name.startswith('__'): continue if name != name.upper(): continue pattern = r'^V_\d+_\d+_\d+$' match = re.match(pattern, name) assert match is not None, name
1,079
409
23
7364ec5a8ae036994247c24918d6f8d961e42d13
1,341
py
Python
PerfTest/NCEP_TimeSeries.py
HDFGroup/hdflab_examples
1570881ea0aff7bdf8846942308a3e0554d13842
[ "MIT" ]
3
2018-07-29T09:01:00.000Z
2019-10-23T03:06:39.000Z
PerfTest/NCEP_TimeSeries.py
HDFGroup/hdflab_examples
1570881ea0aff7bdf8846942308a3e0554d13842
[ "MIT" ]
null
null
null
PerfTest/NCEP_TimeSeries.py
HDFGroup/hdflab_examples
1570881ea0aff7bdf8846942308a3e0554d13842
[ "MIT" ]
1
2018-09-20T13:44:04.000Z
2018-09-20T13:44:04.000Z
import sys import random import h5pyd import numpy as np # # Extracts a time series for the NCEP dataset # # choose random x,y coordinate for the time series shape = (7850, 720, 1440) x_index = random.randint(0, shape[2]-1) y_index = random.randint(0, shape[1]-1) end_index = shape[0] if len(sys.argv) > 1: if sys.argv[1] in ("-h", "--help"): print("Usage python NCEP_TimeSeries.py [end_index] [x_index] [y_index]") print(" end_index: [1,7850]") print(" x_index: [0, 1439]") print(" y_index: [0, 719]") sys.exit(1) end_index = int(sys.argv[1]) if len(sys.argv) > 2: x_index = int(sys.argv[2]) if len(sys.argv) > 3: y_index = int(sys.argv[3]) f = h5pyd.File("hdf5://shared/NASA/NCEP3/ncep3.he5", "r") tair2m = f["/HDFEOS/GRIDS/NCEP/Data Fields/Tair_2m"] fill_value = tair2m.attrs['_FillValue'][0] print(f"Getting time series at point ({x_index}, {y_index}) for slices: 0-{end_index}") tseries = tair2m[0:end_index, y_index, x_index] non_fill = tseries[tseries != fill_value] if len(non_fill) == 0: print("no non_fill values returned!") sys.exit(1) print("done!") tseries_mean = np.mean(non_fill) tseries_min = np.min(non_fill) tseries_max = np.max(non_fill) print(f"Mean: {tseries_mean:.2f} Min: {tseries_min:.2f} Max: {tseries_max:.2f}")
27.9375
87
0.648024
import sys import random import h5pyd import numpy as np # # Extracts a time series for the NCEP dataset # # choose random x,y coordinate for the time series shape = (7850, 720, 1440) x_index = random.randint(0, shape[2]-1) y_index = random.randint(0, shape[1]-1) end_index = shape[0] if len(sys.argv) > 1: if sys.argv[1] in ("-h", "--help"): print("Usage python NCEP_TimeSeries.py [end_index] [x_index] [y_index]") print(" end_index: [1,7850]") print(" x_index: [0, 1439]") print(" y_index: [0, 719]") sys.exit(1) end_index = int(sys.argv[1]) if len(sys.argv) > 2: x_index = int(sys.argv[2]) if len(sys.argv) > 3: y_index = int(sys.argv[3]) f = h5pyd.File("hdf5://shared/NASA/NCEP3/ncep3.he5", "r") tair2m = f["/HDFEOS/GRIDS/NCEP/Data Fields/Tair_2m"] fill_value = tair2m.attrs['_FillValue'][0] print(f"Getting time series at point ({x_index}, {y_index}) for slices: 0-{end_index}") tseries = tair2m[0:end_index, y_index, x_index] non_fill = tseries[tseries != fill_value] if len(non_fill) == 0: print("no non_fill values returned!") sys.exit(1) print("done!") tseries_mean = np.mean(non_fill) tseries_min = np.min(non_fill) tseries_max = np.max(non_fill) print(f"Mean: {tseries_mean:.2f} Min: {tseries_min:.2f} Max: {tseries_max:.2f}")
0
0
0
72faed421ef0180af36c32fcb294bf5bb3f9e84e
1,159
py
Python
ravepay/settings.py
gbozee/django-ravepay
cc9fba3440457ee2941bee2db464520eb00ad98e
[ "MIT" ]
7
2017-11-22T23:53:49.000Z
2021-05-03T22:20:44.000Z
ravepay/settings.py
iAmKabiru/django-ravepay
2d13347300b1d9ab62a23c957e29a33cfddde796
[ "MIT" ]
5
2020-02-11T21:49:35.000Z
2021-06-17T10:20:43.000Z
ravepay/settings.py
iAmKabiru/django-ravepay
2d13347300b1d9ab62a23c957e29a33cfddde796
[ "MIT" ]
7
2017-12-27T12:28:48.000Z
2021-05-03T19:54:47.000Z
from django.conf import settings import os RAVEPAY_SECRET_KEY = getattr( settings, "RAVEPAY_SECRET_KEY", os.getenv("RAVEPAY_SECRET_KEY", "") ) RAVEPAY_PUBLIC_KEY = getattr( settings, "RAVEPAY_PUBLIC_KEY", os.getenv("RAVEPAY_PUBLIC_KEY", "") ) ALLOWED_HOSTS = getattr(settings, "ALLOWED_HOSTS", []) RAVEPAY_WEBHOOK_DOMAIN = getattr(settings, "RAVEPAY_WEBHOOK_DOMAIN", None) if RAVEPAY_WEBHOOK_DOMAIN: ALLOWED_HOSTS.append(RAVEPAY_WEBHOOK_DOMAIN) RAVEPAY_FAILED_URL = getattr(settings, "RAVEPAY_FAILED_URL", "ravepay:failed_page") RAVEPAY_SUCCESS_URL = getattr(settings, "RAVEPAY_SUCCESS_URL", "ravepay:success_page") TEST_RAVEPAY_API_URL = "https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx" RAVEPAY_API_URL = "https://api.ravepay.co/flwv3-pug/getpaidx" RAVEPAY_MODAL_TITLE = getattr( settings, "RAVEPAY_MODAL_TITLE", os.getenv("RAVEPAY_MODAL_TITLE", "Test Account") ) RAVEPAY_MODAL_LOGO = getattr( settings, "RAVEPAY_MODAL_LOGO", os.getenv("RAVEPAY_MODAL_LOGO", "") ) RAVEPAY_LIB_MODULE = getattr(settings, "RAVEPAY_LIB_MODULE", "ravepay.utils") RAVEPAY_WEBHOOK_HASH = getattr(settings, "RAVEPAY_WEBHOOK_HASH", "DJANGO_RAVEPAY")
42.925926
86
0.791199
from django.conf import settings import os RAVEPAY_SECRET_KEY = getattr( settings, "RAVEPAY_SECRET_KEY", os.getenv("RAVEPAY_SECRET_KEY", "") ) RAVEPAY_PUBLIC_KEY = getattr( settings, "RAVEPAY_PUBLIC_KEY", os.getenv("RAVEPAY_PUBLIC_KEY", "") ) ALLOWED_HOSTS = getattr(settings, "ALLOWED_HOSTS", []) RAVEPAY_WEBHOOK_DOMAIN = getattr(settings, "RAVEPAY_WEBHOOK_DOMAIN", None) if RAVEPAY_WEBHOOK_DOMAIN: ALLOWED_HOSTS.append(RAVEPAY_WEBHOOK_DOMAIN) RAVEPAY_FAILED_URL = getattr(settings, "RAVEPAY_FAILED_URL", "ravepay:failed_page") RAVEPAY_SUCCESS_URL = getattr(settings, "RAVEPAY_SUCCESS_URL", "ravepay:success_page") TEST_RAVEPAY_API_URL = "https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx" RAVEPAY_API_URL = "https://api.ravepay.co/flwv3-pug/getpaidx" RAVEPAY_MODAL_TITLE = getattr( settings, "RAVEPAY_MODAL_TITLE", os.getenv("RAVEPAY_MODAL_TITLE", "Test Account") ) RAVEPAY_MODAL_LOGO = getattr( settings, "RAVEPAY_MODAL_LOGO", os.getenv("RAVEPAY_MODAL_LOGO", "") ) RAVEPAY_LIB_MODULE = getattr(settings, "RAVEPAY_LIB_MODULE", "ravepay.utils") RAVEPAY_WEBHOOK_HASH = getattr(settings, "RAVEPAY_WEBHOOK_HASH", "DJANGO_RAVEPAY")
0
0
0
3f0cd4a144e337c91c0b0851099666f5b5dbd8bd
1,794
py
Python
test/aqua/test_eoh.py
chunfuchen/aqua
fde435203a2799433a4e50897554fa226c8ff1dc
[ "Apache-2.0" ]
null
null
null
test/aqua/test_eoh.py
chunfuchen/aqua
fde435203a2799433a4e50897554fa226c8ff1dc
[ "Apache-2.0" ]
null
null
null
test/aqua/test_eoh.py
chunfuchen/aqua
fde435203a2799433a4e50897554fa226c8ff1dc
[ "Apache-2.0" ]
2
2020-02-13T02:17:58.000Z
2020-08-09T07:56:25.000Z
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test EOH """ import unittest from test.aqua.common import QiskitAquaTestCase from qiskit import BasicAer from qiskit.aqua.operators import MatrixOperator from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.components.initial_states import Custom from qiskit.aqua.algorithms import EOH class TestEOH(QiskitAquaTestCase): """Evolution tests.""" def test_eoh(self): """ EOH test """ size = 2 aqua_globals.random_seed = 0 temp = aqua_globals.random.random_sample((2 ** size, 2 ** size)) h_1 = temp + temp.T qubit_op = MatrixOperator(matrix=h_1) temp = aqua_globals.random.random_sample((2 ** size, 2 ** size)) h_1 = temp + temp.T evo_op = MatrixOperator(matrix=h_1) state_in = Custom(size, state='random') evo_time = 1 num_time_slices = 100 eoh = EOH(qubit_op, state_in, evo_op, evo_time=evo_time, num_time_slices=num_time_slices) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, shots=1) # self.log.debug('state_out:\n\n') ret = eoh.run(quantum_instance) self.log.debug('Evaluation result: %s', ret) if __name__ == '__main__': unittest.main()
29.409836
97
0.688963
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test EOH """ import unittest from test.aqua.common import QiskitAquaTestCase from qiskit import BasicAer from qiskit.aqua.operators import MatrixOperator from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.components.initial_states import Custom from qiskit.aqua.algorithms import EOH class TestEOH(QiskitAquaTestCase): """Evolution tests.""" def test_eoh(self): """ EOH test """ size = 2 aqua_globals.random_seed = 0 temp = aqua_globals.random.random_sample((2 ** size, 2 ** size)) h_1 = temp + temp.T qubit_op = MatrixOperator(matrix=h_1) temp = aqua_globals.random.random_sample((2 ** size, 2 ** size)) h_1 = temp + temp.T evo_op = MatrixOperator(matrix=h_1) state_in = Custom(size, state='random') evo_time = 1 num_time_slices = 100 eoh = EOH(qubit_op, state_in, evo_op, evo_time=evo_time, num_time_slices=num_time_slices) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, shots=1) # self.log.debug('state_out:\n\n') ret = eoh.run(quantum_instance) self.log.debug('Evaluation result: %s', ret) if __name__ == '__main__': unittest.main()
0
0
0
a18e8308da8486a770e2891eeb29e9bbed3cb732
610
py
Python
server/migrations/versions/26e723d032b1_dataset_add_created_at.py
multi-coop/catalogage-donnees
1d70401ff6c7b01ec051460a253cb105adf65911
[ "MIT" ]
null
null
null
server/migrations/versions/26e723d032b1_dataset_add_created_at.py
multi-coop/catalogage-donnees
1d70401ff6c7b01ec051460a253cb105adf65911
[ "MIT" ]
14
2022-01-25T17:56:52.000Z
2022-01-28T17:47:59.000Z
server/migrations/versions/26e723d032b1_dataset_add_created_at.py
multi-coop/catalogage-donnees
1d70401ff6c7b01ec051460a253cb105adf65911
[ "MIT" ]
null
null
null
"""dataset_add_created_at Revision ID: 26e723d032b1 Revises: 30474ebed7a2 Create Date: 2022-03-16 15:50:00.805743 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "26e723d032b1" down_revision = "30474ebed7a2" branch_labels = None depends_on = None
19.0625
56
0.654098
"""dataset_add_created_at Revision ID: 26e723d032b1 Revises: 30474ebed7a2 Create Date: 2022-03-16 15:50:00.805743 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "26e723d032b1" down_revision = "30474ebed7a2" branch_labels = None depends_on = None def upgrade(): op.add_column( "dataset", sa.Column( "created_at", sa.DateTime(timezone=True), server_default=sa.text("clock_timestamp()"), nullable=False, ), ) def downgrade(): op.drop_column("dataset", "created_at")
257
0
46
e29ffcd80dc6bc6b37e8b9541005b9d9d749edeb
448
py
Python
lotube/users/serializers.py
zurfyx/lotube
d00a456d4aff5a6f4c63dab5d90ba6a3a72e3a3f
[ "MIT" ]
null
null
null
lotube/users/serializers.py
zurfyx/lotube
d00a456d4aff5a6f4c63dab5d90ba6a3a72e3a3f
[ "MIT" ]
null
null
null
lotube/users/serializers.py
zurfyx/lotube
d00a456d4aff5a6f4c63dab5d90ba6a3a72e3a3f
[ "MIT" ]
null
null
null
from rest_framework import serializers from rest_framework.serializers import HyperlinkedIdentityField from users.models import User
32
85
0.723214
from rest_framework import serializers from rest_framework.serializers import HyperlinkedIdentityField from users.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): href = HyperlinkedIdentityField(view_name='api_v2:users-detail') class Meta: model = User fields = ('id', 'href', 'username', 'first_name', 'last_name', 'date_joined', 'last_login', 'is_staff', 'is_active')
0
290
23
301336fa9e8bd0f9cddaa1051bfb04ece382cdc8
1,336
py
Python
contours new.py
guyfromthesky/OCR-Project
c126c9844ddecbeefd1de6ae49074d3b56062df3
[ "MIT" ]
null
null
null
contours new.py
guyfromthesky/OCR-Project
c126c9844ddecbeefd1de6ae49074d3b56062df3
[ "MIT" ]
null
null
null
contours new.py
guyfromthesky/OCR-Project
c126c9844ddecbeefd1de6ae49074d3b56062df3
[ "MIT" ]
null
null
null
import cv2 import numpy as np img_path = r'C:\Users\evan\Documents\GitHub\OCR-Project\BAKR\Crop_IMG__1651113545.png' import cv2; import numpy as np; # Read image image = cv2.imread(img_path) cv2.waitKey(0) # Grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Find Canny edges edged = cv2.Canny(gray, 20, 20) cv2.waitKey(0) # Finding Contours # Use a copy of the image e.g. edged.copy() # since findContours alters the image contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Threshold. # Set values equal to or above 220 to 0. # Set values below 220 to 255. th, im_th = cv2.threshold(image, 220, 255, cv2.THRESH_BINARY_INV); # Copy the thresholded image. im_floodfill = im_th.copy() # Mask used to flood filling. # Notice the size needs to be 2 pixels than the image. h, w = im_th.shape[:2] mask = np.zeros((h+2, w+2), np.uint8) # Floodfill from point (0, 0) cv2.floodFill(im_floodfill, mask, (0,0), 255); # Invert floodfilled image im_floodfill_inv = cv2.bitwise_not(im_floodfill) # Combine the two images to get the foreground. im_out = im_th | im_floodfill_inv # Display images. cv2.imshow("Thresholded Image", im_th) cv2.imshow("Floodfilled Image", im_floodfill) cv2.imshow("Inverted Floodfilled Image", im_floodfill_inv) cv2.imshow("Foreground", im_out) cv2.waitKey(0)
24.290909
86
0.747754
import cv2 import numpy as np img_path = r'C:\Users\evan\Documents\GitHub\OCR-Project\BAKR\Crop_IMG__1651113545.png' import cv2; import numpy as np; # Read image image = cv2.imread(img_path) cv2.waitKey(0) # Grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Find Canny edges edged = cv2.Canny(gray, 20, 20) cv2.waitKey(0) # Finding Contours # Use a copy of the image e.g. edged.copy() # since findContours alters the image contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Threshold. # Set values equal to or above 220 to 0. # Set values below 220 to 255. th, im_th = cv2.threshold(image, 220, 255, cv2.THRESH_BINARY_INV); # Copy the thresholded image. im_floodfill = im_th.copy() # Mask used to flood filling. # Notice the size needs to be 2 pixels than the image. h, w = im_th.shape[:2] mask = np.zeros((h+2, w+2), np.uint8) # Floodfill from point (0, 0) cv2.floodFill(im_floodfill, mask, (0,0), 255); # Invert floodfilled image im_floodfill_inv = cv2.bitwise_not(im_floodfill) # Combine the two images to get the foreground. im_out = im_th | im_floodfill_inv # Display images. cv2.imshow("Thresholded Image", im_th) cv2.imshow("Floodfilled Image", im_floodfill) cv2.imshow("Inverted Floodfilled Image", im_floodfill_inv) cv2.imshow("Foreground", im_out) cv2.waitKey(0)
0
0
0
de173234238504b084701c6804c76ce2b05393e2
8,206
py
Python
bundle/YouCompleteMe/third_party/ycmd/ycmd/request_wrap.py
xiaoyin199/myvim
910dac2ae265eb4896468d4dd447df4b188ddaf1
[ "Vim" ]
null
null
null
bundle/YouCompleteMe/third_party/ycmd/ycmd/request_wrap.py
xiaoyin199/myvim
910dac2ae265eb4896468d4dd447df4b188ddaf1
[ "Vim" ]
null
null
null
bundle/YouCompleteMe/third_party/ycmd/ycmd/request_wrap.py
xiaoyin199/myvim
910dac2ae265eb4896468d4dd447df4b188ddaf1
[ "Vim" ]
null
null
null
# encoding: utf8 # # Copyright (C) 2014 Google Inc. # # This file is part of ycmd. # # ycmd is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ycmd is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ycmd. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import # Not installing aliases from python-future; it's unreliable and slow. from builtins import * # noqa from ycmd.utils import ( ByteOffsetToCodepointOffset, CodepointOffsetToByteOffset, ToUnicode, ToBytes, SplitLines ) from ycmd.identifier_utils import StartOfLongestIdentifierEndingAtIndex from ycmd.request_validation import EnsureRequestValid # TODO: Change the custom computed (and other) keys to be actual properties on # the object. def CompletionStartColumn( line_value, column_num, filetype ): """Returns the 1-based byte index where the completion query should start. So if the user enters: foo.bar^ with the cursor being at the location of the caret (so the character *AFTER* 'r'), then the starting column would be the index of the letter 'b'. NOTE: if the line contains multi-byte characters, then the result is not the 'character' index (see CompletionStartCodepoint for that), and therefore it is not safe to perform any character-relevant arithmetic on the result of this method.""" return CodepointOffsetToByteOffset( ToUnicode( line_value ), CompletionStartCodepoint( line_value, column_num, filetype ) ) def CompletionStartCodepoint( line_value, column_num, filetype ): """Returns the 1-based codepoint index where the completion query should start. So if the user enters: ƒøø.∫å®^ with the cursor being at the location of the caret (so the character *AFTER* '®'), then the starting column would be the index of the character '∫' (i.e. 5, not its byte index).""" # NOTE: column_num and other numbers on the wire are byte indices, but we need # to walk codepoints for identifier checks. codepoint_column_num = ByteOffsetToCodepointOffset( line_value, column_num ) unicode_line_value = ToUnicode( line_value ) # -1 and then +1 to account for difference betwen 0-based and 1-based # indices/columns codepoint_start_column = StartOfLongestIdentifierEndingAtIndex( unicode_line_value, codepoint_column_num - 1, filetype ) + 1 return codepoint_start_column
36.471111
80
0.677309
# encoding: utf8 # # Copyright (C) 2014 Google Inc. # # This file is part of ycmd. # # ycmd is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ycmd is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ycmd. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import # Not installing aliases from python-future; it's unreliable and slow. from builtins import * # noqa from ycmd.utils import ( ByteOffsetToCodepointOffset, CodepointOffsetToByteOffset, ToUnicode, ToBytes, SplitLines ) from ycmd.identifier_utils import StartOfLongestIdentifierEndingAtIndex from ycmd.request_validation import EnsureRequestValid # TODO: Change the custom computed (and other) keys to be actual properties on # the object. class RequestWrap( object ): def __init__( self, request, validate = True ): if validate: EnsureRequestValid( request ) self._request = request # Maps the keys returned by this objects __getitem__ to a # tuple of # ( getter_method, setter_method ). Values computed by getter_method (or set # by setter_method) are cached in _cached_computed. setter_method may be # None for read-only items. self._computed_key = { # Unicode string representation of the current line 'line_value': ( self._CurrentLine, None ), # The calculated start column, as a codepoint offset into the # unicode string line_value 'start_codepoint': ( self._GetCompletionStartCodepoint, self._SetCompletionStartCodepoint ), # The 'column_num' as a unicode codepoint offset 'column_codepoint': ( lambda: ByteOffsetToCodepointOffset( self[ 'line_bytes' ], self[ 'column_num' ] ), None ), # Bytes string representation of the current line 'line_bytes': ( lambda: ToBytes( self[ 'line_value' ] ), None ), # The calculated start column, as a byte offset into the UTF-8 encoded # bytes returned by line_bytes 'start_column': ( self._GetCompletionStartColumn, self._SetCompletionStartColumn ), # Note: column_num is the byte offset into the UTF-8 encoded bytes # returned by line_bytes # unicode string representation of the 'query' after the beginning # of the identifier to be completed 'query': ( self._Query, None ), 'filetypes': ( self._Filetypes, None ), 'first_filetype': ( self._FirstFiletype, None ), } self._cached_computed = {} def __getitem__( self, key ): if key in self._cached_computed: return self._cached_computed[ key ] if key in self._computed_key: getter, _ = self._computed_key[ key ] value = getter() self._cached_computed[ key ] = value return value return self._request[ key ] def __setitem__( self, key, value ): if key in self._computed_key: _, setter = self._computed_key[ key ] if setter: setter( value ) return raise ValueError( 'Key "{0}" is read-only'.format( key ) ) def __contains__( self, key ): return key in self._computed_key or key in self._request def get( self, key, default = None ): try: return self[ key ] except KeyError: return default def _CurrentLine( self ): current_file = self._request[ 'filepath' ] contents = self._request[ 'file_data' ][ current_file ][ 'contents' ] return SplitLines( contents )[ self._request[ 'line_num' ] - 1 ] def _GetCompletionStartColumn( self ): return CompletionStartColumn( self[ 'line_value' ], self[ 'column_num' ], self[ 'first_filetype' ] ) def _SetCompletionStartColumn( self, column_num ): self._cached_computed[ 'start_column' ] = column_num # Note: We must pre-compute (and cache) the codepoint equivalent. This is # because the value calculated by the getter (_GetCompletionStartCodepoint) # would be based on self[ 'column_codepoint' ] which would be incorrect; it # does not know that the user has forced this value to be independent of the # column. self._cached_computed[ 'start_codepoint' ] = ByteOffsetToCodepointOffset( self[ 'line_value' ], column_num ) # The same applies to the 'query' (the bit after the start column up to the # cursor column). It's dependent on the 'start_codepoint' so we must reset # it. self._cached_computed.pop( 'query', None ) def _GetCompletionStartCodepoint( self ): return CompletionStartCodepoint( self[ 'line_value' ], self[ 'column_num' ], self[ 'first_filetype' ] ) def _SetCompletionStartCodepoint( self, codepoint_offset ): self._cached_computed[ 'start_codepoint' ] = codepoint_offset # Note: We must pre-compute (and cache) the byte equivalent. This is because # the value calculated by the getter (_GetCompletionStartColumn) would be # based on self[ 'column_num' ], which would be incorrect; it does not know # that the user has forced this value to be independent of the column. self._cached_computed[ 'start_column' ] = CodepointOffsetToByteOffset( self[ 'line_value' ], codepoint_offset ) # The same applies to the 'query' (the bit after the start column up to the # cursor column). It's dependent on the 'start_codepoint' so we must reset # it. self._cached_computed.pop( 'query', None ) def _Query( self ): return self[ 'line_value' ][ self[ 'start_codepoint' ] - 1 : self[ 'column_codepoint' ] - 1 ] def _FirstFiletype( self ): try: return self[ 'filetypes' ][ 0 ] except (KeyError, IndexError): return None def _Filetypes( self ): path = self[ 'filepath' ] return self[ 'file_data' ][ path ][ 'filetypes' ] def CompletionStartColumn( line_value, column_num, filetype ): """Returns the 1-based byte index where the completion query should start. So if the user enters: foo.bar^ with the cursor being at the location of the caret (so the character *AFTER* 'r'), then the starting column would be the index of the letter 'b'. NOTE: if the line contains multi-byte characters, then the result is not the 'character' index (see CompletionStartCodepoint for that), and therefore it is not safe to perform any character-relevant arithmetic on the result of this method.""" return CodepointOffsetToByteOffset( ToUnicode( line_value ), CompletionStartCodepoint( line_value, column_num, filetype ) ) def CompletionStartCodepoint( line_value, column_num, filetype ): """Returns the 1-based codepoint index where the completion query should start. So if the user enters: ƒøø.∫å®^ with the cursor being at the location of the caret (so the character *AFTER* '®'), then the starting column would be the index of the character '∫' (i.e. 5, not its byte index).""" # NOTE: column_num and other numbers on the wire are byte indices, but we need # to walk codepoints for identifier checks. codepoint_column_num = ByteOffsetToCodepointOffset( line_value, column_num ) unicode_line_value = ToUnicode( line_value ) # -1 and then +1 to account for difference betwen 0-based and 1-based # indices/columns codepoint_start_column = StartOfLongestIdentifierEndingAtIndex( unicode_line_value, codepoint_column_num - 1, filetype ) + 1 return codepoint_start_column
4,846
7
346
9b6a1f4320c04cfa1520b5d5adfbae8953ddf82b
521
py
Python
cevast/certdb/__init__.py
crocs-muni/cert-validataion-stats
bd61968c0487e634c160f6e25b7bb0eb1bab64fc
[ "MIT" ]
3
2020-06-26T09:31:35.000Z
2020-06-26T09:32:17.000Z
cevast/certdb/__init__.py
crocs-muni/cert-validataion-stats
bd61968c0487e634c160f6e25b7bb0eb1bab64fc
[ "MIT" ]
null
null
null
cevast/certdb/__init__.py
crocs-muni/cert-validataion-stats
bd61968c0487e634c160f6e25b7bb0eb1bab64fc
[ "MIT" ]
null
null
null
"""CertDB is a database managing X.509 certificates.""" __all__ = ( 'CertDB', 'CertDBReadOnly', 'CertFileDB', 'CertFileDBReadOnly', 'CertNotAvailableError', 'CertInvalidError', 'CompositeCertDB', 'CompositeCertDBReadOnly', ) __version__ = '1.1' __author__ = 'Radim Podola' from .cert_db import CertNotAvailableError, CertInvalidError, CertDB, CertDBReadOnly from .cert_file_db import CertFileDBReadOnly, CertFileDB from .composite_cert_db import CompositeCertDB, CompositeCertDBReadOnly
27.421053
84
0.756238
"""CertDB is a database managing X.509 certificates.""" __all__ = ( 'CertDB', 'CertDBReadOnly', 'CertFileDB', 'CertFileDBReadOnly', 'CertNotAvailableError', 'CertInvalidError', 'CompositeCertDB', 'CompositeCertDBReadOnly', ) __version__ = '1.1' __author__ = 'Radim Podola' from .cert_db import CertNotAvailableError, CertInvalidError, CertDB, CertDBReadOnly from .cert_file_db import CertFileDBReadOnly, CertFileDB from .composite_cert_db import CompositeCertDB, CompositeCertDBReadOnly
0
0
0
66b94a4f4da0f38a8ab044038a48b3375a219494
34,715
py
Python
mpcpy/units.py
YangyangFu/MPCPy
c9980cbfe7b5ea21b003c2c0bab800099dccf3f1
[ "BSD-3-Clause-LBNL" ]
96
2017-03-31T09:59:44.000Z
2022-03-23T18:39:37.000Z
mpcpy/units.py
kuzha/MPCPy
9f78aa68236f87d39a50de54978c5064f9cc13c6
[ "BSD-3-Clause-LBNL" ]
150
2017-03-03T17:28:34.000Z
2021-02-24T20:03:24.000Z
mpcpy/units.py
kuzha/MPCPy
9f78aa68236f87d39a50de54978c5064f9cc13c6
[ "BSD-3-Clause-LBNL" ]
32
2017-04-24T18:22:40.000Z
2022-03-29T17:51:20.000Z
# -*- coding: utf-8 -*- """ ``units`` classes manage the conversion of units for MPCPy variables. See documentation on ``variables`` for more information. """ from abc import ABCMeta, abstractmethod import numpy as np #%% Display unit abstract interface #%% Display unit quantity implementation #%% Boolean display unit implementation #%% Temperature display unit implementation #%% Power display unit implementation #%% Energy display unit implementation #%% Power Flux display unit implementation #%% Energy Intensity display unit implementation #%% Pressure display unit implementation #%% Dimensionless Ratio display unit implementation #%% Angle display unit implementation #%% Time display unit implementation #%% Mass display unit implementation #%% Length display unit implementation #%% Area display unit implementation #%% Volume display unit implementation #%% Mass Flow display unit implementation #%% Volumetric Flow display unit implementation #%% Velocity display unit implementation #%% Illuminance display unit implementation #%% Luminance display unit implementation #%% EnergyPrice unit implementation #%% PowerPrice unit implementation #%% Specific heat capacity unit implementation #%% Heat capacity unit implementation #%% Heat capacity coefficient unit implementation #%% Heat resistance unit implementation #%% Heat resistance coefficient unit implementation #%% Heat transfer coefficient unit implementation #%% Density unit implementation
32.535145
75
0.658102
# -*- coding: utf-8 -*- """ ``units`` classes manage the conversion of units for MPCPy variables. See documentation on ``variables`` for more information. """ from abc import ABCMeta, abstractmethod import numpy as np #%% Display unit abstract interface class _DisplayUnit(object): __metaclass__ = ABCMeta; @abstractmethod def _define_quantity(self): pass; @abstractmethod def _define_display_unit(self): pass; @abstractmethod def _convert_to_base(self): pass; @abstractmethod def _convert_from_base(self): pass; def __init__(self, variable): self._define_quantity(variable); self._define_display_unit(); #%% Display unit quantity implementation class _Boolean(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Boolean'; variable.base_unit = boolean_integer; class _Temperature(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Temperature'; variable.base_unit = K; class _Power(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Power'; variable.base_unit = W; class _Energy(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Energy'; variable.base_unit = J; class _PowerFlux(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'PowerFlux'; variable.base_unit = W_m2; class _EnergyIntensity(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'EnergyIntensity'; variable.base_unit = J_m2; class _Pressure(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Pressure'; variable.base_unit = Pa; class _DimensionlessRatio(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'DimensionlessRatio'; variable.base_unit = unit1; class _Angle(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Angle'; variable.base_unit = rad; class _Time(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Time'; variable.base_unit = s; class _Mass(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Mass'; variable.base_unit = kg; class _Length(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Length'; variable.base_unit = m; class _Area(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Area'; variable.base_unit = m2; class _Volume(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Volume'; variable.base_unit = m3; class _MassFlow(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'MassFlow'; variable.base_unit = kg_s; class _VolumetricFlow(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'VolumetricFlow'; variable.base_unit = m3_s; class _Velocity(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Velocity'; variable.base_unit = m_s; class _Illuminance(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Illuminance'; variable.base_unit = lx; class _Luminance(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Luminance'; variable.base_unit = cd_m2; class _EnergyPrice(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'EnergyPrice'; variable.base_unit = dol_J; class _PowerPrice(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'PowerPrice'; variable.base_unit = dol_W; class _SpecificHeatCapacity(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'SpecificHeatCapacity'; variable.base_unit = J_kgK; class _HeatCapacity(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'HeatCapacity'; variable.base_unit = J_K; class _HeatCapacityCoefficient(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'HeatCapacityCoefficient'; variable.base_unit = J_m2K; class _HeatResistance(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'HeatResistance'; variable.base_unit = K_W; class _HeatResistanceCoefficient(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'HeatResistanceCoefficient'; variable.base_unit = m2K_W; class _HeatTransferCoefficient(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'HeatTransferCoefficient'; variable.base_unit = W_m2K; class _Density(_DisplayUnit): def _define_quantity(self, variable): variable.quantity_name = 'Density'; variable.base_unit = kg_m3; #%% Boolean display unit implementation class boolean_integer(_Boolean): def _define_display_unit(self): self.name = 'boolean_integer'; def _convert_to_base(self, display_data): base_data = int(display_data); return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class boolean(_Boolean): def _define_display_unit(self): self.name = 'boolean'; def _convert_to_base(self, display_data): base_data = int(display_data); return base_data; def _convert_from_base(self, base_data): display_data = bool(base_data); return display_data; #%% Temperature display unit implementation class K(_Temperature): def _define_display_unit(self): self.name = 'K'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class degC(_Temperature): def _define_display_unit(self): self.name = 'degC'; def _convert_to_base(self, display_data): base_data = display_data + 273.15; return base_data; def _convert_from_base(self, base_data): display_data = base_data - 273.15; return display_data; class degF(_Temperature): def _define_display_unit(self): self.name = 'degF'; def _convert_to_base(self, display_data): base_data = (display_data-32)*5/9 + 273.15; return base_data; def _convert_from_base(self, base_data): display_data = (base_data-273.15)*9/5 + 32; return display_data; class degR(_Temperature): def _define_display_unit(self): self.name = 'degR'; def _convert_to_base(self, display_data): base_data = ((display_data - 459.67)-32)*5/9 + 273.15; return base_data; def _convert_from_base(self, base_data): display_data = (base_data-273.15)*9/5 + 32 + 459.67; return display_data; #%% Power display unit implementation class W(_Power): def _define_display_unit(self): self.name = 'W'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class kW(_Power): def _define_display_unit(self): self.name = 'kW'; def _convert_to_base(self, display_data): base_data = display_data*1e3; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1e3; return display_data; class MW(_Power): def _define_display_unit(self): self.name = 'MW'; def _convert_to_base(self, display_data): base_data = display_data*1e6; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1e6; return display_data; class Btuh(_Power): def _define_display_unit(self): self.name = 'Btuh'; def _convert_to_base(self, display_data): base_data = display_data*0.29307107; return base_data; def _convert_from_base(self, base_data): display_data = base_data/0.29307107; return display_data; class kBtuh(_Power): def _define_display_unit(self): self.name = 'kBtuh'; def _convert_to_base(self, display_data): base_data = (display_data*1e3)*0.29307107; return base_data; def _convert_from_base(self, base_data): display_data = base_data/0.29307107/1e3; return display_data; class hp(_Power): def _define_display_unit(self): self.name = 'hp'; def _convert_to_base(self, display_data): base_data = display_data*745.699872; return base_data; def _convert_from_base(self, base_data): display_data = base_data/745.699872; return display_data; #%% Energy display unit implementation class J(_Energy): def _define_display_unit(self): self.name = 'J'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class kJ(_Energy): def _define_display_unit(self): self.name = 'kJ'; def _convert_to_base(self, display_data): base_data = display_data*1e3; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1e3; return display_data; class MJ(_Energy): def _define_display_unit(self): self.name = 'MJ'; def _convert_to_base(self, display_data): base_data = display_data*1e6; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1e6; return display_data; class Btu(_Energy): def _define_display_unit(self): self.name = 'Btu'; def _convert_to_base(self, display_data): base_data = display_data*1055.05585; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1055.05585; return display_data; class kBtu(_Energy): def _define_display_unit(self): self.name = 'kBtu'; def _convert_to_base(self, display_data): base_data = (display_data*1e3)*1055.05585; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1055.05585/1e3; return display_data; class Wh(_Energy): def _define_display_unit(self): self.name = 'Wh'; def _convert_to_base(self, display_data): base_data = display_data*3600; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3600; return display_data; class kWh(_Energy): def _define_display_unit(self): self.name = 'kWh'; def _convert_to_base(self, display_data): base_data = display_data*1e3*3600; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3600/1e3; return display_data; class MWh(_Energy): def _define_display_unit(self): self.name = 'MWh'; def _convert_to_base(self, display_data): base_data = display_data*1e6*3600; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3600/1e6; return display_data; #%% Power Flux display unit implementation class W_m2(_PowerFlux): def _define_display_unit(self): self.name = 'W/m2'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class kW_m2(_PowerFlux): def _define_display_unit(self): self.name = 'kW/m2'; def _convert_to_base(self, display_data): base_data = display_data*1e3; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1e3; return display_data; class W_sf(_PowerFlux): def _define_display_unit(self): self.name = 'W/sf'; def _convert_to_base(self, display_data): base_data = display_data*10.7639; return base_data; def _convert_from_base(self, base_data): display_data = base_data/10.7639; return display_data; class kW_sf(_PowerFlux): def _define_display_unit(self): self.name = 'kW/sf'; def _convert_to_base(self, display_data): base_data = display_data*1e3*10.7639; return base_data; def _convert_from_base(self, base_data): display_data = base_data/10.7639/1e3; return display_data; class Btuh_sf(_PowerFlux): def _define_display_unit(self): self.name = 'Btuh/sf'; def _convert_to_base(self, display_data): base_data = display_data*3.154594; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3.154594; return display_data; class kBtuh_sf(_PowerFlux): def _define_display_unit(self): self.name = 'kBtuh/sf'; def _convert_to_base(self, display_data): base_data = display_data*1e3*3.154594; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3.154594/1e3; return display_data; #%% Energy Intensity display unit implementation class J_m2(_EnergyIntensity): def _define_display_unit(self): self.name = 'J/m2'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class Wh_m2(_EnergyIntensity): def _define_display_unit(self): self.name = 'Wh/m2'; def _convert_to_base(self, display_data): base_data = display_data*3600; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3600; return display_data; class kWh_m2(_EnergyIntensity): def _define_display_unit(self): self.name = 'kWh/m2'; def _convert_to_base(self, display_data): base_data = display_data*1e3*3600; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3600/1e3; return display_data; class Wh_sf(_EnergyIntensity): def _define_display_unit(self): self.name = 'Wh/sf'; def _convert_to_base(self, display_data): base_data = display_data*3600*10.7639; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3600/10.7639; return display_data; class kWh_sf(_EnergyIntensity): def _define_display_unit(self): self.name = 'kWh/sf'; def _convert_to_base(self, display_data): base_data = display_data*1e3*3600*10.7639; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3600/10.7639/1e3; return display_data; class Btu_sf(_EnergyIntensity): def _define_display_unit(self): self.name = 'Btu/sf'; def _convert_to_base(self, display_data): base_data = display_data*1055.05585*10.7639; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1055.05585/10.7639; return display_data; class kBtu_sf(_EnergyIntensity): def _define_display_unit(self): self.name = 'kBtu/sf'; def _convert_to_base(self, display_data): base_data = display_data*1e3*1055.05585*10.7639; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1055.05585/10.7639/1e3; return display_data; #%% Pressure display unit implementation class Pa(_Pressure): def _define_display_unit(self): self.name = 'Pa'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class kPa(_Pressure): def _define_display_unit(self): self.name = 'kPa'; def _convert_to_base(self, display_data): base_data = display_data*1e3; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1e3; return display_data; class MPa(_Pressure): def _define_display_unit(self): self.name = 'MPa'; def _convert_to_base(self, display_data): base_data = display_data*1e6; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1e6; return display_data; class bar(_Pressure): def _define_display_unit(self): self.name = 'bar'; def _convert_to_base(self, display_data): base_data = display_data*1e5; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1e5; return display_data; class inwg(_Pressure): def _define_display_unit(self): self.name = 'inwg'; def _convert_to_base(self, display_data): base_data = display_data*248.84; return base_data; def _convert_from_base(self, base_data): display_data = base_data/248.84; return display_data; class inHg(_Pressure): def _define_display_unit(self): self.name = 'inHg'; def _convert_to_base(self, display_data): base_data = display_data*3386.389; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3386.389; return display_data; class psi(_Pressure): def _define_display_unit(self): self.name = 'psi'; def _convert_to_base(self, display_data): base_data = display_data*6894.757; return base_data; def _convert_from_base(self, base_data): display_data = base_data/6894.757; return display_data; class atm(_Pressure): def _define_display_unit(self): self.name = 'atm'; def _convert_to_base(self, display_data): base_data = display_data*101325; return base_data; def _convert_from_base(self, base_data): display_data = base_data/101325; return display_data; #%% Dimensionless Ratio display unit implementation class unit1(_DimensionlessRatio): def _define_display_unit(self): self.name = '1'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class percent(_DimensionlessRatio): def _define_display_unit(self): self.name = 'percent'; def _convert_to_base(self, display_data): base_data = display_data/100; return base_data; def _convert_from_base(self, base_data): display_data = base_data*100; return display_data; class unit10(_DimensionlessRatio): def _define_display_unit(self): self.name = '10'; def _convert_to_base(self, display_data): base_data = display_data/10; return base_data; def _convert_from_base(self, base_data): display_data = base_data*10; return display_data; #%% Angle display unit implementation class rad(_Angle): def _define_display_unit(self): self.name = 'rad'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class deg(_Angle): def _define_display_unit(self): self.name = 'deg'; def _convert_to_base(self, display_data): base_data = display_data/180*np.pi; return base_data; def _convert_from_base(self, base_data): display_data = base_data*180/np.pi; return display_data; #%% Time display unit implementation class s(_Time): def _define_display_unit(self): self.name = 's'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class minute(_Time): def _define_display_unit(self): self.name = 'min'; def _convert_to_base(self, display_data): base_data = display_data*60; return base_data; def _convert_from_base(self, base_data): display_data = base_data/60; return display_data; class hour(_Time): def _define_display_unit(self): self.name = 'h'; def _convert_to_base(self, display_data): base_data = display_data*3600; return base_data; def _convert_from_base(self, base_data): display_data = base_data/3600; return display_data; class day(_Time): def _define_display_unit(self): self.name = 'd'; def _convert_to_base(self, display_data): base_data = display_data*86400; return base_data; def _convert_from_base(self, base_data): display_data = base_data/86400; return display_data; #%% Mass display unit implementation class kg(_Mass): def _define_display_unit(self): self.name = 'kg'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% Length display unit implementation class m(_Length): def _define_display_unit(self): self.name = 'm'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class cm(_Length): def _define_display_unit(self): self.name = 'cm'; def _convert_to_base(self, display_data): base_data = display_data/1e2; return base_data; def _convert_from_base(self, base_data): display_data = base_data*1e2; return display_data; class mm(_Length): def _define_display_unit(self): self.name = 'mm'; def _convert_to_base(self, display_data): base_data = display_data/1e3; return base_data; def _convert_from_base(self, base_data): display_data = base_data*1e3; return display_data; class km(_Length): def _define_display_unit(self): self.name = 'km'; def _convert_to_base(self, display_data): base_data = display_data*1e3; return base_data; def _convert_from_base(self, base_data): display_data = base_data/1e3; return display_data; class inch(_Length): def _define_display_unit(self): self.name = 'inch'; def _convert_to_base(self, display_data): base_data = display_data*0.0254; return base_data; def _convert_from_base(self, base_data): display_data = base_data/0.0254; return display_data; class ft(_Length): def _define_display_unit(self): self.name = 'ft'; def _convert_to_base(self, display_data): base_data = display_data*12*0.0254; return base_data; def _convert_from_base(self, base_data): display_data = base_data/0.0254/12; return display_data; class yd(_Length): def _define_display_unit(self): self.name = 'yd'; def _convert_to_base(self, display_data): base_data = display_data*12*0.0254*3; return base_data; def _convert_from_base(self, base_data): display_data = base_data/0.0254/12/3; return display_data; #%% Area display unit implementation class m2(_Area): def _define_display_unit(self): self.name = 'm2'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class sf(_Area): def _define_display_unit(self): self.name = 'sf'; def _convert_to_base(self, display_data): base_data = display_data/10.7639; return base_data; def _convert_from_base(self, base_data): display_data = base_data*10.7639; return display_data; #%% Volume display unit implementation class m3(_Volume): def _define_display_unit(self): self.name = 'm3'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class cf(_Volume): def _define_display_unit(self): self.name = 'cf'; def _convert_to_base(self, display_data): base_data = display_data/35.3147; return base_data; def _convert_from_base(self, base_data): display_data = base_data*35.3147; return display_data; #%% Mass Flow display unit implementation class kg_s(_MassFlow): def _define_display_unit(self): self.name = 'kg/s'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% Volumetric Flow display unit implementation class m3_s(_VolumetricFlow): def _define_display_unit(self): self.name = 'm3/s'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class cfm(_VolumetricFlow): def _define_display_unit(self): self.name = 'cfm'; def _convert_to_base(self, display_data): base_data = display_data/2118.88; return base_data; def _convert_from_base(self, base_data): display_data = base_data*2118.88; return display_data; #%% Velocity display unit implementation class m_s(_Velocity): def _define_display_unit(self): self.name = 'm/s'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class mph(_Velocity): def _define_display_unit(self): self.name = 'mph'; def _convert_to_base(self, display_data): base_data = display_data*0.44704; return base_data; def _convert_from_base(self, base_data): display_data = base_data/0.44704; return display_data; class km_h(_Velocity): def _define_display_unit(self): self.name = 'km/h'; def _convert_to_base(self, display_data): base_data = display_data*0.277778; return base_data; def _convert_from_base(self, base_data): display_data = base_data/0.277778; return display_data; #%% Illuminance display unit implementation class lx(_Illuminance): def _define_display_unit(self): self.name = 'lx'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class fc(_Illuminance): def _define_display_unit(self): self.name = 'fc'; def _convert_to_base(self, display_data): base_data = display_data*10.764 ; return base_data; def _convert_from_base(self, base_data): display_data = base_data/10.764 ; return display_data; #%% Luminance display unit implementation class cd_m2(_Luminance): def _define_display_unit(self): self.name = 'cd/m2'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; class nt(_Luminance): def _define_display_unit(self): self.name = 'nt'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% EnergyPrice unit implementation class cents_kWh(_EnergyPrice): def _define_display_unit(self): self.name = 'cents/kWh'; def _convert_to_base(self, display_data): base_data = display_data/3.6e8; return base_data; def _convert_from_base(self, base_data): display_data = base_data*3.6e8; return display_data; class dol_kWh(_EnergyPrice): def _define_display_unit(self): self.name = '$/kWh'; def _convert_to_base(self, display_data): base_data = display_data/3.6e6; return base_data; def _convert_from_base(self, base_data): display_data = base_data*3.6e6; return display_data; class dol_MWh(_EnergyPrice): def _define_display_unit(self): self.name = '$/MWh'; def _convert_to_base(self, display_data): base_data = display_data/3.6e9; return base_data; def _convert_from_base(self, base_data): display_data = base_data*3.6e9; return display_data; class dol_J(_EnergyPrice): def _define_display_unit(self): self.name = '$/J'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% PowerPrice unit implementation class cents_kW(_PowerPrice): def _define_display_unit(self): self.name = 'cents/kW'; def _convert_to_base(self, display_data): base_data = display_data/1e5; return base_data; def _convert_from_base(self, base_data): display_data = base_data*1e5; return display_data; class dol_kW(_PowerPrice): def _define_display_unit(self): self.name = '$/kW'; def _convert_to_base(self, display_data): base_data = display_data/1e3; return base_data; def _convert_from_base(self, base_data): display_data = base_data*1e3; return display_data; class dol_MW(_PowerPrice): def _define_display_unit(self): self.name = '$/MW'; def _convert_to_base(self, display_data): base_data = display_data/1e6; return base_data; def _convert_from_base(self, base_data): display_data = base_data*1e6; return display_data; class dol_W(_PowerPrice): def _define_display_unit(self): self.name = '$/W'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% Specific heat capacity unit implementation class J_kgK(_SpecificHeatCapacity): def _define_display_unit(self): self.name = 'J/(kg.K)'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% Heat capacity unit implementation class J_K(_HeatCapacity): def _define_display_unit(self): self.name = 'J/K'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% Heat capacity coefficient unit implementation class J_m2K(_HeatCapacityCoefficient): def _define_display_unit(self): self.name = 'J/(m2.K)'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% Heat resistance unit implementation class K_W(_HeatResistance): def _define_display_unit(self): self.name = 'K/W'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% Heat resistance coefficient unit implementation class m2K_W(_HeatResistanceCoefficient): def _define_display_unit(self): self.name = '(m2.K)/W'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% Heat transfer coefficient unit implementation class W_m2K(_HeatTransferCoefficient): def _define_display_unit(self): self.name = 'W/(m2.K)'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data; #%% Density unit implementation class kg_m3(_Density): def _define_display_unit(self): self.name = 'kg/m3'; def _convert_to_base(self, display_data): base_data = display_data; return base_data; def _convert_from_base(self, base_data): display_data = base_data; return display_data;
21,301
798
10,791
b8ed9add650effe4bdc5d102b5715c4b685306e4
1,335
py
Python
test/test_tindex.py
exepulveda/pymgt
c49a1de3d45b82ce8dd659693e3c41fc4c967b24
[ "MIT" ]
1
2021-07-10T00:58:30.000Z
2021-07-10T00:58:30.000Z
test/test_tindex.py
exepulveda/pymgt
c49a1de3d45b82ce8dd659693e3c41fc4c967b24
[ "MIT" ]
null
null
null
test/test_tindex.py
exepulveda/pymgt
c49a1de3d45b82ce8dd659693e3c41fc4c967b24
[ "MIT" ]
null
null
null
import numpy as np from pymgt.tindex import generate_directions from pymgt.tindex import projection_index from pymgt.tindex import Projectable from pymgt.tindex import jarque_bera_index from pymgt.tindex import shapiro_index from pymgt.tindex import anderson_index from pymgt.tindex import ks_index
25.188679
79
0.633708
import numpy as np from pymgt.tindex import generate_directions from pymgt.tindex import projection_index from pymgt.tindex import Projectable from pymgt.tindex import jarque_bera_index from pymgt.tindex import shapiro_index from pymgt.tindex import anderson_index from pymgt.tindex import ks_index def test_generate_directions(): for dim in range(2, 11): dirs = generate_directions(dim, n=100) for d in dirs: np.testing.assert_almost_equal(np.linalg.norm(d), 1.0) def test_projection_index(): ndata, ndim = 1000, 5 x = np.random.uniform(10.0, 20.0, size=(ndata, ndim)) pi = projection_index(x, lambda p: 1.0, nprojections=100, reduce = np.mean) assert pi == 1.0 def test_projectable(): ndata, ndim = 1000, 5 p = Projectable(lambda p: 2.0, nprojections=100, reduce = np.mean) x = np.random.uniform(0.0, 1.0, size=(ndata, ndim)) pi = p(x) assert pi == 2.0 def test_indices(): ndata = 100000 np.random.seed(1) for _ in range(10): x = np.random.normal(0.0, 1.0, size=ndata) pi = jarque_bera_index(x) assert 0.0 <= pi <= 3.0 pi = shapiro_index(x) assert 0.99 <= pi <= 1.0 pi = anderson_index(x) assert 0.0 <= pi <= 1.0 pi = ks_index(x) assert 0.0 <= pi <= 0.01
943
0
92
c5d8549560107cb450a57ac7bf626615ee97a86a
1,340
py
Python
hone/tests/csv_utils_test.py
awsrossw/hone
d69dec08ad4dbeb59b6c042443635a2d4937d7c6
[ "MIT" ]
null
null
null
hone/tests/csv_utils_test.py
awsrossw/hone
d69dec08ad4dbeb59b6c042443635a2d4937d7c6
[ "MIT" ]
null
null
null
hone/tests/csv_utils_test.py
awsrossw/hone
d69dec08ad4dbeb59b6c042443635a2d4937d7c6
[ "MIT" ]
null
null
null
import os import unittest from hone.utils import csv_utils dirname = os.path.dirname(__file__) csv_A_path = os.path.join(dirname, "data", "small_cats_dataset.csv") csv_B_path = os.path.join(dirname, "data", "comma_test.csv") small_csv = csv_utils.CSVUtils(csv_A_path) comma_csv = csv_utils.CSVUtils(csv_B_path) if __name__ == '__main__': unittest.main()
41.875
109
0.536567
import os import unittest from hone.utils import csv_utils dirname = os.path.dirname(__file__) csv_A_path = os.path.join(dirname, "data", "small_cats_dataset.csv") csv_B_path = os.path.join(dirname, "data", "comma_test.csv") small_csv = csv_utils.CSVUtils(csv_A_path) comma_csv = csv_utils.CSVUtils(csv_B_path) class TestCSVUtils(unittest.TestCase): def test_get_column_names(self): self.assertListEqual(small_csv.get_column_names(), ['name', 'age (years)', 'weight (kg)', 'birth day', 'birth month', 'birth year', 'adopted', 'adopted_since']) self.assertListEqual(comma_csv.get_column_names(), ['test"",""ing', 'beep']) def test_get_data_rows(self): self.assertListEqual(small_csv.get_data_rows(), [['Tommy', '5', '3.6', '11', 'April', '2011', 'TRUE', '2012'], ['Clara', '2', '8.2', '6', 'May', '2015', 'FALSE', 'N/A'], ['Catnip', '6', '3.3', '21', 'August', '2011', 'TRUE', '2017'], ['Ciel', '3', '3.1', '18', 'January', '2015', 'TRUE', '2018']]) self.assertListEqual(comma_csv.get_data_rows(), [['1', '2']]) if __name__ == '__main__': unittest.main()
885
17
76
816f2f8179bff8e2c67506f066639890aa090d22
2,209
py
Python
testing.py
agakshat/dagger-pg
89f937e8a9e4876c7e8f73658d3618d590971565
[ "MIT" ]
4
2020-05-14T07:00:38.000Z
2021-11-19T23:41:15.000Z
testing.py
agakshat/dagger-pg
89f937e8a9e4876c7e8f73658d3618d590971565
[ "MIT" ]
null
null
null
testing.py
agakshat/dagger-pg
89f937e8a9e4876c7e8f73658d3618d590971565
[ "MIT" ]
2
2019-07-05T22:46:10.000Z
2020-10-25T08:54:13.000Z
import gym import torch import numpy as np from networks import ActorNetwork import argparse from torch.autograd import Variable if __name__=='__main__': main()
36.213115
87
0.594839
import gym import torch import numpy as np from networks import ActorNetwork import argparse from torch.autograd import Variable def parse_arguments(): # Command-line flags are defined here. parser = argparse.ArgumentParser() parser.add_argument('--env-name', default='LunarLander-v2', help='environment to train on (default: LunarLander-v2)') parser.add_argument('--load-dir', default='.', help='directory to model path (default: .)') parser.add_argument('--render', action='store_true', default=False, help='render environment') parser.add_argument('--num-episodes', dest='num_episodes', type=int, default=50, help="Number of episodes to test.") return parser.parse_args() def test(env,actor,render): rew_arr = [] ep_len_arr = [] for ep in range(100): ep_len = 0 obs = env.reset() ep_reward = 0 done = False while not done: ep_len += 1 obs_var = Variable(torch.from_numpy(obs).float()) action = actor.get_action(obs_var) #if np.random.random()<eps: # action = env.action_space.sample() #else: # _,action = torch.max(action_probs,-1) # action = action.data[0] action = action.data[0] next_obs,reward,done,_ = env.step(action) if render: env.render() ep_reward += reward obs = next_obs ep_len_arr.append(ep_len) rew_arr.append(ep_reward) print("Reward: {:.3f}| Length: {:.3f}".format(ep_reward,ep_len)) print("Reward Mean: {:.3f}, Std: {:.3f}| Length: {:.3f}".format( np.array(rew_arr).mean(),np.array(rew_arr).std(), np.array(ep_len_arr).mean())) return np.array(rew_arr).mean(),np.array(rew_arr).std(),np.array(ep_len_arr).mean() def main(): args = parse_arguments() env = gym.make(args.env_name) actor = ActorNetwork(env.observation_space.shape[0],env.action_space.n) actor.load_state_dict(torch.load(args.load_dir)) test(env,actor,args.render) if __name__=='__main__': main()
1,977
0
69
362f4d262e981bbc2cb9514ea3ad58afe232c6f0
168
py
Python
wolverine/db/__init__.py
drankinn/wolverine
22c3e59db70c96edb3f4c2ebaf8482eda10a3e2a
[ "MIT" ]
4
2015-10-19T23:09:42.000Z
2016-01-07T09:52:13.000Z
wolverine/db/__init__.py
drankinn/wolverine
22c3e59db70c96edb3f4c2ebaf8482eda10a3e2a
[ "MIT" ]
2
2015-10-21T20:46:12.000Z
2021-03-22T17:15:17.000Z
wolverine/db/__init__.py
drankinn/wolverine
22c3e59db70c96edb3f4c2ebaf8482eda10a3e2a
[ "MIT" ]
3
2015-11-13T12:33:40.000Z
2021-10-04T17:42:14.000Z
from wolverine.module import MicroModule
15.272727
40
0.672619
from wolverine.module import MicroModule class MicroDB(MicroModule): def __init__(self): super(MicroDB, self).__init__() self.name = 'microdb'
68
6
50
bf5d944a7b36974f0c9c2523aa6b947781152c8f
1,042
py
Python
operations/fleet_management/migrations/0030_auto_20180320_1535.py
kaizer88/emps
2669b32c46befcf1a19390fb25013817e6b00980
[ "MIT" ]
null
null
null
operations/fleet_management/migrations/0030_auto_20180320_1535.py
kaizer88/emps
2669b32c46befcf1a19390fb25013817e6b00980
[ "MIT" ]
null
null
null
operations/fleet_management/migrations/0030_auto_20180320_1535.py
kaizer88/emps
2669b32c46befcf1a19390fb25013817e6b00980
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-03-20 13:35 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models
32.5625
161
0.644914
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-03-20 13:35 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fleet_management', '0029_vehicledriver_reason'), ] operations = [ migrations.AlterField( model_name='servicebooking', name='qoute_amount', field=models.CharField(blank=True, max_length=50, null=True, validators=[django.core.validators.MinValueValidator(0)], verbose_name=b'Quote Amount'), ), migrations.AlterField( model_name='servicebooking', name='qoute_date', field=models.DateTimeField(blank=True, null=True, verbose_name=b'Quote Date'), ), migrations.AlterField( model_name='servicebooking', name='qoute_number', field=models.CharField(blank=True, max_length=50, null=True, verbose_name=b'Quote Number'), ), ]
0
833
23
8f1ef3bb41841eef6301aa9a3f84e7f3cade3a1b
32,503
py
Python
qualcoder/merge_projects.py
FantasqueX/QualCoder
11a9c593fab0bbcf9f55b14501deee878d264e8d
[ "MIT" ]
null
null
null
qualcoder/merge_projects.py
FantasqueX/QualCoder
11a9c593fab0bbcf9f55b14501deee878d264e8d
[ "MIT" ]
null
null
null
qualcoder/merge_projects.py
FantasqueX/QualCoder
11a9c593fab0bbcf9f55b14501deee878d264e8d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Copyright (c) 2022 Colin Curtain 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. Author: Colin Curtain (ccbogel) https://github.com/ccbogel/QualCoder """ import datetime import logging import os import shutil import sqlite3 from PyQt5 import QtWidgets from .helpers import Message path = os.path.abspath(os.path.dirname(__file__)) logger = logging.getLogger(__name__) def exception_handler(exception_type, value, tb_obj): """ Global exception handler useful in GUIs. tb_obj: exception.__traceback__ """ tb = '\n'.join(traceback.format_tb(tb_obj)) text = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value) print(text) logger.error(_("Uncaught exception: ") + text) QtWidgets.QMessageBox.critical(None, _('Uncaught Exception'), text) class MergeProjects: """ Merge one external Qualcoder project (source) database into existing project (destination). Copies unmatched files from source project folders to destination project folders. Adds new (unmatched) source categories to destination database. Adds new (unmatched) source code names to destination database. Adds journals and stored_sql to destination database, only if they have unique names, Adds text codings, text annotations, image codings, av codings to destination database. Adds cases and case_text (links to text file segments and images and A/V) Add attributes for files and cases. Existing attribute values in destination are not over-written, unless already blank """ app = None path_d = "" # Path to destination project folder conn_d = None path_s = "" # Path to source project folder conn_s = None source_s = [] # source text from Source project code_text_s = [] # coded text segments from Source project annotations_s = [] # annotations from Source project journals_s = [] stored_sql_s = [] summary_msg = "" code_image_s = [] # coded image areas from Source project code_av_s = [] # coded A/V segments from Source project codes_s = [] # codes from Source project categories_s = [] # code cats from Source project attribute_types_s = [] # For new attributes that are not existing in the destination database attributes_s = [] # values for Case and File attributes cases_s = [] # cases case_text_s = [] # case text and links to non-text files projects_merged = False def insert_categories(self): """ Insert categories into destination code_cat table. The categories have already been filtered to remove any names that match names in the destination database. """ cur_d = self.conn_d.cursor() # Insert top level categories remove_list = [] for c in self.categories_s: if c['supercatname'] is None: self.summary_msg += _("Adding top level category: ") + c['name'] + "\n" cur_d.execute("insert into code_cat (name,memo,owner,date,supercatid) values(?,?,?,?,?)", (c['name'], c['memo'], c['owner'], c['date'], c['supercatid'])) self.conn_d.commit() remove_list.append(c) for item in remove_list: self.categories_s.remove(item) ''' Add sub-categories. look at each unmatched category, iterate through to add as child, then remove from the list ''' count = 0 while len(self.categories_s) > 0 and count < 1000: remove_list = [] for c in self.categories_s: # This needs to be repeated as it is changes cur_d.execute("select catid from code_cat where name=?", [c['supercatname']]) res_category = cur_d.fetchone() if res_category is not None: remove_list.append(c) sql = "insert into code_cat (name, memo, owner, date, supercatid) values (?,?,?,?,?)" cur_d.execute(sql, [c['name'], c['memo'], c['owner'], c['date'], res_category[0]]) self.conn_d.commit() self.summary_msg += _("Adding sub-category: " + c['name']) + " --> " + c['supercatname'] + "\n" for item in remove_list: self.categories_s.remove(item) count += 1 if len(self.categories_s) > 0: self.summary_msg += str(len(self.categories_s)) + _(" categories not added") + "\n" print("Categories NOT added:\n", self.categories_s) logger.debug("Categories NOT added:\n" + str(self.categories_s)) def update_code_cid_and_insert_code(self): """ Update the cid to the one already in Destination.code_name. Check for no matches and insert these into the Destination.code_name table. """ cur_d = self.conn_d.cursor() cur_d.execute("select name, catid from code_cat") dest_categories = cur_d.fetchall() sql = "select cid, name from code_name" cur_d.execute(sql) res = cur_d.fetchall() for code_dest in res: for code_source in self.codes_s: if code_source['name'] == code_dest[1]: code_source['newcid'] = code_dest[0] # Insert unmatched code names for code_s in self.codes_s: if code_s['newcid'] == -1: # Fill category id using matching category name for cat in dest_categories: if cat[0] == code_s['catname']: code_s['catid'] = cat[1] cur_d.execute("insert into code_name (name,memo,owner,date,catid,color) values(?,?,?,?,?,?)", (code_s['name'], code_s['memo'], code_s['owner'], code_s['date'], code_s['catid'], code_s['color'])) self.conn_d.commit() cur_d.execute("select last_insert_rowid()") cid = cur_d.fetchone()[0] code_s['newcid'] = cid self.summary_msg += _("Adding code name: ") + code_s['name'] + "\n" # Update code_text, code_image, code_av cids to destination values for code_s in self.codes_s: for coding_text in self.code_text_s: if coding_text['cid'] == code_s['cid']: coding_text['newcid'] = code_s['newcid'] for coding_image in self.code_image_s: if coding_image['cid'] == code_s['cid']: coding_image['newcid'] = code_s['newcid'] for coding_av in self.code_av_s: if coding_av['cid'] == code_s['cid']: coding_av['newcid'] = code_s['newcid'] def insert_coding_and_journal_data(self): """ Coding fid and cid have been updated, annotation fid has been updated. Insert code_text, code_image, code_av, journal and stored_sql data into Destination project. """ cur_d = self.conn_d.cursor() # Earlier db versions did not have unique journal name # Need to identify duplicate journal names and not import them cur_d.execute("select name from journal") j_names_res = cur_d.fetchall() j_names = [] for j in j_names_res: j_names.append(j[0]) for j in self.journals_s: # Possible to have two identical journal names in earlier db versions if j['name'] not in j_names: cur_d.execute("insert into journal (name, jentry, date, owner) values(?,?,?,?)", (j['name'], j['jentry'], j['date'], j['owner'])) self.summary_msg += _("Adding journal: ") + j['name'] + "\n" self.conn_d.commit() for s in self.stored_sql_s: # Cannot have two identical stored_sql titles, using 'or ignore' cur_d.execute("insert or ignore into stored_sql (title, description, grouper, ssql) values(?,?,?,?)", (s['title'], s['description'], s['grouper'], s['ssql'])) self.conn_d.commit() for c in self.code_text_s: cur_d.execute("insert or ignore into code_text (cid,fid,seltext,pos0,pos1,owner,\ memo,date, important) values(?,?,?,?,?,?,?,?,?)", (c['newcid'], c['newfid'], c['seltext'], c['pos0'], c['pos1'], c['owner'], c['memo'], c['date'], c['important'])) self.conn_d.commit() if len(self.code_text_s) > 0: self.summary_msg += _("Merging coded text") + "\n" for a in self.annotations_s: cur_d.execute("insert or ignore into annotation (fid,pos0,pos1,memo,owner,date) values(?,?,?,?,?,?)", [a["newfid"], a["pos0"], a["pos1"], a["memo"], a["owner"], a["date"]]) self.conn_d.commit() if len(self.annotations_s) > 0: self.summary_msg += _("Merging annotations") + "\n" for c in self.code_image_s: cur_d.execute( "insert or ignore into code_image (cid, id,x1,y1,width,height,memo,owner,date,important) values(?,?,?,?,?,?,?,?,?,?)", [c["newcid"], c["newfid"], c["x1"], c["y1"], c["width"], c["height"], c["memo"], c["owner"], c["date"], c["important"]]) self.conn_d.commit() if len(self.code_image_s) > 0: self.summary_msg += _("Merging coded image areas") + "\n" for c in self.code_av_s: cur_d.execute( "insert or ignore into code_av (cid, id,pos0,pos1,memo,owner,date,important) values(?,?,?,?,?,?,?,?)", [c["newcid"], c["newfid"], c["pos0"], c["pos1"], c["memo"], c["owner"], c["date"], c["important"]]) self.conn_d.commit() if len(self.code_av_s) > 0: self.summary_msg += _("Merging coded audio/video segments") + "\n" def insert_cases(self): """ Insert case data into destination. First remove all existing matching case names and the associated case text data. """ cur_d = self.app.conn.cursor() # Remove all duplicate cases and case text lists from source data cur_d.execute("select name from cases") res_cases_dest = cur_d.fetchall() existing_case_names = [] for r in res_cases_dest: existing_case_names.append(r[0]) remove_case_list = [] for case_s in self.cases_s: if case_s['name'] in existing_case_names: remove_case_list.append(case_s) removed_case_text_list = [] for removed_case in remove_case_list: self.cases_s.remove(removed_case) for case_text in self.case_text_s: if case_text['caseid'] == removed_case['caseid']: removed_case_text_list.append(case_text) for removed_case_text in removed_case_text_list: self.case_text_s.remove(removed_case_text) # Insert new cases into destination new_case_ids = [] for case_s in self.cases_s: cur_d.execute("insert into cases (name, memo, owner, date) values (?,?,?,?)", [case_s['name'], case_s['memo'], case_s['owner'], case_s['date']]) self.app.conn.commit() cur_d.execute("select last_insert_rowid()") case_id = cur_d.fetchone()[0] case_s['newcaseid'] = case_id new_case_ids.append(case_id) self.summary_msg += _("Adding case: ") + case_s['name'] + "\n" # Update newcaseid and newfid in case_text for case_text in self.case_text_s: for case_s in self.cases_s: if case_s['caseid'] == case_text['caseid']: case_text['newcaseid'] = case_s['newcaseid'] for file_ in self.source_s: if case_text['fid'] == file_['newid']: case_text['newfid'] = file_['newid'] # Insert case text if newfileid is not -1 and newcaseid is not -1 for c in self.case_text_s: if c['newcaseid'] > -1 and c['newfid'] > -1: cur_d.execute("insert into case_text (caseid,fid,pos0,pos1) values(?,?,?,?)", [c['newcaseid'], c['newfid'], c['pos0'], c['pos1']]) self.app.conn.commit() # Create attribute placeholders for the destination case attributes now_date = datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S") sql_attribute_types = 'select name from attribute_type where caseOrFile ="case"' cur_d.execute(sql_attribute_types) res_attr_types = cur_d.fetchall() sql_attribute = "insert into attribute (name, attr_type, value, id, date, owner) values(?,'file','',?,?,?)" for id_ in new_case_ids: for attribute_name in res_attr_types: cur_d.execute(sql_attribute, [attribute_name[0], id_, now_date, self.app.settings['codername']]) self.app.conn.commit() def insert_sources_get_new_file_ids(self): """ Insert Source.source into Destination.source, unless source file name is already present. update newfid in source_s and code_text_s. Update the av_text_id link to link A/V to the corresponding transcript. """ new_source_file_ids = [] cur_d = self.conn_d.cursor() for src in self.source_s: cur_d.execute("select id, length(fulltext) from source where name=?", [src['name']]) res = cur_d.fetchone() if res is not None: # Existing same named source file is in the destination database src['newid'] = res[0] # Warn user if the source and destination fulltexts are different lengths # Occurs if one of the texts was edited or replaced if len(src['fulltext']) != res[1]: msg = _("Warning! Inaccurate coding positions. Text lengths different for same text file: ") msg += src['name'] + "\n" msg += _("Import project file text length: ") + str(len(src['fulltext'])) + " " msg += _("Destination project file text length: ") + str(res[1]) + "\n" self.summary_msg += msg else: # To update the av_text_id after all new ids have been generated cur_d.execute( "insert into source(name,fulltext,mediapath,memo,owner,date, av_text_id) values(?,?,?,?,?,?,?)", (src['name'], src['fulltext'], src['mediapath'], src['memo'], src['owner'], src['date'], None)) self.conn_d.commit() cur_d.execute("select last_insert_rowid()") id_ = cur_d.fetchone()[0] src['newid'] = id_ new_source_file_ids.append(id_) # Need to find matching av_text_filename to get its id to link as the av_text_id for src in self.source_s: if src['av_text_filename'] != "": cur_d.execute("select id from source where name=?", [src['av_text_filename']]) res = cur_d.fetchone() if res is not None: cur_d.execute("update source set av_text_id=? where id=?", [res[0], src['id']]) self.conn_d.commit() # Create attribute placeholders for the destination file attributes now_date = datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S") sql_attribute_types = 'select name from attribute_type where caseOrFile ="file"' cur_d.execute(sql_attribute_types) res_attr_types = cur_d.fetchall() sql_attribute = "insert into attribute (name, attr_type, value, id, date, owner) values(?,'file','',?,?,?)" for id_ in new_source_file_ids: for attribute_name in res_attr_types: cur_d.execute(sql_attribute, [attribute_name[0], id_, now_date, self.app.settings['codername']]) self.app.conn.commit() def update_coding_file_ids(self): """ Update the file ids in the codings and annotations data. """ for src in self.source_s: for c_text in self.code_text_s: if c_text['fid'] == src['id']: c_text['newfid'] = src['newid'] for an in self.annotations_s: if an['fid'] == src['id']: an['newfid'] = src['newid'] for c_img in self.code_image_s: if c_img['fid'] == src['id']: c_img['newfid'] = src['newid'] for c_av in self.code_av_s: if c_av['fid'] == src['id']: c_av['newfid'] = src['newid'] def copy_source_files_into_destination(self): """ Copy source files into destination project. Do not copy over existing files. """ folders = ["audio", "documents", "images", "video"] for folder_name in folders: dir_ = self.path_s + "/" + folder_name files = os.listdir(dir_) for f in files: if not os.path.exists(self.app.project_path + "/" + folder_name + "/" + f): try: shutil.copyfile(dir_ + "/" + f, self.app.project_path + "/" + folder_name + "/" + f) self.summary_msg += _("File copied: ") + f + "\n" except shutil.SameFileError: pass except PermissionError: self.summary_msg += f + " " + _("NOT copied. Permission error") def insert_new_attribute_types(self): """ Insert new attribute types for cases and files. Insert placeholders for the new attribute types. To be performed after Cases and files have been inserted. """ cur_d = self.app.conn.cursor() cur_d.execute("select id from source") res_file_ids = cur_d.fetchall() cur_d.execute("select caseid from cases") res_case_ids = cur_d.fetchall() # Insert new attribute type and placeholder in attribute table for a in self.attribute_types_s: cur_d.execute("insert into attribute_type (name,date,owner,memo,caseOrFile, valuetype) values(?,?,?,?,?,?)", (a['name'], a['date'], a['owner'], a['memo'], a['caseOrFile'], a['valuetype'])) self.app.conn.commit() self.summary_msg += _("Adding attribute (") + a['caseOrFile'] + "): " + a['name'] + "\n" # Create attribute placeholders for new attributes, does NOT create for existing destination attributes if a['caseOrFile'] == "file": for id_ in res_file_ids: sql = "insert into attribute (name, value, id, attr_type, date, owner) values (?,?,?,?,?,?)" cur_d.execute(sql, (a['name'], "", id_[0], "file", a['date'], a['owner'])) self.app.conn.commit() if a['caseOrFile'] == "case": for id_ in res_case_ids: sql = "insert into attribute (name, value, id, attr_type, date, owner) values (?,?,?,?,?,?)" cur_d.execute(sql, (a['name'], "", id_[0], "case", a['date'], a['owner'])) self.app.conn.commit() def insert_attributes(self): """ Insert new attribute values for files and cases. Need to use destination file and case ids. Example attribute: {'name': 'age', 'attr_type': 'file', 'value': '100', 'id': 4, 'newid': -1, 'date': '2022-03-14 10:35:27', 'owner': 'default'} """ # Only update if value does not over-write an existing placeholder attribute value sql_update = "update attribute set value=? where name=? and id=? and attr_type=? and value=''" # Insert if a placeholder is missing sql_insert = "insert into attribute (name,id,attr_type,value,date,owner) values (?,?,?,?,?,?)" attribute_count = 0 cur_d = self.app.conn.cursor() for a in self.attributes_s: if a['attr_type'] == "file": source_dict = next((item for item in self.source_s if item["id"] == a['id']), {'newid': -1}) a['newid'] = source_dict['newid'] if a['attr_type'] == "case": case_dict = next((item for item in self.cases_s if item["caseid"] == a['id']), {'newcaseid': -1}) a['newid'] = case_dict['newcaseid'] # Only update or insert value does not over-write an existing placeholder attribute value if a['newid'] != -1: # Check placeholder exists, if not then insert values cur_d.execute("select * from attribute where name=? and id=? and attr_type=?", [a['name'], a['newid'], a['attr_type']]) res = cur_d.fetchall() if not res: cur_d.execute(sql_insert, (a['name'], a['newid'], a['attr_type'],a['value'], a['date'], a['owner'])) self.app.conn.commit() attribute_count += 1 else: cur_d.execute(sql_update, (a['value'], a['name'], a['newid'], a['attr_type'])) self.app.conn.commit() attribute_count += 1 if attribute_count > 0: self.summary_msg += _("Added attribute values for cases and files: n=") + str(attribute_count) + "\n" def get_source_data(self): """ Load the database data into Lists of Dictionaries. return: True or False if data was able to be loaded """ self.journals_s = [] self.stored_sql_s = [] self.codes_s = [] self.categories_s = [] self.code_text_s = [] self.annotations_s = [] self.code_image_s = [] self.code_av_s = [] self.cases_s = [] self.case_text_s = [] self.attribute_types_s = [] self.attributes_s = [] cur_s = self.conn_s.cursor() # Database version must be v5 or higher cur_s.execute("select databaseversion from project") version = cur_s.fetchone() if version[0] in ("v1", "v2", "v3", "v4"): self.summary_msg += _("Need to update the source project database.") + "\n" self.summary_msg += _("Please open the source project using QualCoder. Then close the project.") + "\n" self.summary_msg += _("This will update the database schema. Then try merging again.") self.summary_msg += _("Project not merged") + "\n" return False # Journal data sql_journal = "select name, jentry, date, owner from journal" cur_s.execute(sql_journal) res_journals = cur_s.fetchall() for i in res_journals: src = {"name": i[0], "jentry": i[1], "date": i[2], "owner": i[3]} self.journals_s.append(src) # Stored sql data sql_stored_sql = "select title, description, grouper, ssql from stored_sql" cur_s.execute(sql_stored_sql) res_stored_sqls = cur_s.fetchall() for i in res_stored_sqls: src = {"title": i[0], "description": i[1], "grouper": i[2], "ssql": i[3]} self.stored_sql_s.append(src) # Source data sql_source = "select id, name, fulltext,mediapath,memo,owner,date,av_text_id from source" cur_s.execute(sql_source) res_source = cur_s.fetchall() # Later update av_text_id for i in res_source: src = {"id": i[0], "newid": -1, "name": i[1], "fulltext": i[2], "mediapath": i[3], "memo": i[4], "owner": i[5], "date": i[6], "av_text_id": i[7], "av_text_filename": ""} self.source_s.append(src) # The av_text_id is not enough to recreate linkages. Need the referenced text file name. for i in self.source_s: if i['av_text_id'] is not None: cur_s.execute("select name from source where id=?", [i['av_text_id']]) res = cur_s.fetchone() if res is not None: i['av_text_filename'] = res[0] # Category data sql_codecats = "select catid, supercatid, name, memo, owner, date from code_cat" cur_s.execute(sql_codecats) res_codecats = cur_s.fetchall() for i in res_codecats: ccat = {"catid": i[0], "supercatid": i[1], "supercatname": None, "name": i[2], "memo": i[3], "owner": i[4], "date": i[5], } self.categories_s.append(ccat) # Remove categories from the source list, that are already present in the destination database cur_d = self.app.conn.cursor() cur_d.execute("select name from code_cat") res_dest_catnames = cur_d.fetchall() dest_cat_names_list = [] for r in res_dest_catnames: dest_cat_names_list.append(r[0]) temp_source_cats = [] for cat in self.categories_s: if cat['name'] not in dest_cat_names_list: temp_source_cats.append(cat) self.categories_s = temp_source_cats # Add reference to linked supercat using category name for cat in self.categories_s: cur_s.execute("select name from code_cat where catid=?", [cat['supercatid']]) res = cur_s.fetchone() if res is not None: cat['supercatname'] = res[0] # Code data sql_codenames = "select cid, name, memo, owner, date, color, catid from code_name" cur_s.execute(sql_codenames) res_codes = cur_s.fetchall() for i in res_codes: code_s = {"cid": i[0], "newcid": -1, "name": i[1], "memo": i[2], "owner": i[3], "date": i[4], "color": i[5], "catid": i[6], "catname": None} self.codes_s.append(code_s) # Get and fill category name if code is in a category for code_s in self.codes_s: cur_s.execute("select name from code_cat where catid=?", [code_s['catid']]) res = cur_s.fetchone() if res is not None: code_s['catname'] = res[0] # Code text data sql_codetext = "select cid, fid, seltext, pos0, pos1, owner, date, memo, important from code_text" cur_s.execute(sql_codetext) res_codetext = cur_s.fetchall() for i in res_codetext: ct = {"cid": i[0], "newcid": -1, "fid": i[1], "newfid": -1, "seltext": i[2], "pos0": i[3], "pos1": i[4], "owner": i[5], "date": i[6], "memo": i[7], "important": i[8]} self.code_text_s.append(ct) # Text annotations data sql_annotations = "select fid, pos0, pos1, memo, owner, date from annotation" cur_s.execute(sql_annotations) res_annot = cur_s.fetchall() for i in res_annot: an = {"fid": i[0], "newfid": -1, "pos0": i[1], "pos1": i[2], "memo": i[3], "owner": i[4], "date": i[5]} self.annotations_s.append(an) # Code image data sql_code_img = "select cid, id, x1, y1, width, height, memo, date, owner, important from code_image" cur_s.execute(sql_code_img) res_code_img = cur_s.fetchall() for i in res_code_img: cimg = {"cid": i[0], "newcid": -1, "fid": i[1], "newfid": -1, "x1": i[2], "y1": i[3], "width": i[4], "height": i[5], "memo": i[6], "date": i[7], "owner": i[8], "important": i[9]} self.code_image_s.append(cimg) # Code AV data sql_code_av = "select cid, id, pos0, pos1, owner, date, memo, important from code_av" cur_s.execute(sql_code_av) res_code_av = cur_s.fetchall() for i in res_code_av: c_av = {"cid": i[0], "newcid": -1, "fid": i[1], "newfid": -1, "pos0": i[2], "pos1": i[3], "owner": i[4], "date": i[5], "memo": i[6], "important": i[7]} self.code_av_s.append(c_av) # Case data sql_cases = "select caseid, name, memo, owner, date from cases" cur_s.execute(sql_cases) res_cases = cur_s.fetchall() for i in res_cases: c = {"caseid": i[0], "newcaseid": -1, "name": i[1], "memo": i[2], "owner": i[3], "date": i[4]} self.cases_s.append(c) sql_case_text = "select caseid, fid, pos0, pos1 from case_text" cur_s.execute(sql_case_text) res_case_text = cur_s.fetchall() for i in res_case_text: c = {"caseid": i[0], "newcaseid": -1, "fid": i[1], "newfid": -1, "pos0": i[2], "pos1": i[3]} self.case_text_s.append(c) # Attribute type data sql_attr_type = "select name, memo, date, owner, caseOrFile, valuetype from attribute_type" cur_s.execute(sql_attr_type) res_attr_type_s = cur_s.fetchall() keys = 'name', 'memo', 'date', 'owner', 'caseOrFile', 'valuetype' temp_attribute_types_s = [] for row in res_attr_type_s: temp_attribute_types_s.append(dict(zip(keys, row))) # Remove matching attribute type names cur_d = self.app.conn.cursor() cur_d.execute("select name from attribute_type") res_attr_name_dest = cur_d.fetchall() attribute_names_dest = [] for r in res_attr_name_dest: attribute_names_dest.append(r[0]) self.attribute_types_s = [] for r in temp_attribute_types_s: if r['name'] not in attribute_names_dest: self.attribute_types_s.append(r) # Attribute data sql_attributes = "select name, attr_type, value, id, date ,owner from attribute" cur_s.execute(sql_attributes) res_attributes = cur_s.fetchall() for i in res_attributes: attribute = {"name": i[0], "attr_type": i[1], "value": i[2], "id": i[3], "newid": -1, "date": i[4], "owner": i[5]} self.attributes_s.append(attribute) return True
50.945141
139
0.575362
# -*- coding: utf-8 -*- """ Copyright (c) 2022 Colin Curtain 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. Author: Colin Curtain (ccbogel) https://github.com/ccbogel/QualCoder """ import datetime import logging import os import shutil import sqlite3 from PyQt5 import QtWidgets from .helpers import Message path = os.path.abspath(os.path.dirname(__file__)) logger = logging.getLogger(__name__) def exception_handler(exception_type, value, tb_obj): """ Global exception handler useful in GUIs. tb_obj: exception.__traceback__ """ tb = '\n'.join(traceback.format_tb(tb_obj)) text = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value) print(text) logger.error(_("Uncaught exception: ") + text) QtWidgets.QMessageBox.critical(None, _('Uncaught Exception'), text) class MergeProjects: """ Merge one external Qualcoder project (source) database into existing project (destination). Copies unmatched files from source project folders to destination project folders. Adds new (unmatched) source categories to destination database. Adds new (unmatched) source code names to destination database. Adds journals and stored_sql to destination database, only if they have unique names, Adds text codings, text annotations, image codings, av codings to destination database. Adds cases and case_text (links to text file segments and images and A/V) Add attributes for files and cases. Existing attribute values in destination are not over-written, unless already blank """ app = None path_d = "" # Path to destination project folder conn_d = None path_s = "" # Path to source project folder conn_s = None source_s = [] # source text from Source project code_text_s = [] # coded text segments from Source project annotations_s = [] # annotations from Source project journals_s = [] stored_sql_s = [] summary_msg = "" code_image_s = [] # coded image areas from Source project code_av_s = [] # coded A/V segments from Source project codes_s = [] # codes from Source project categories_s = [] # code cats from Source project attribute_types_s = [] # For new attributes that are not existing in the destination database attributes_s = [] # values for Case and File attributes cases_s = [] # cases case_text_s = [] # case text and links to non-text files projects_merged = False def __init__(self, app, path_s): self.app = app self.path_s = path_s self.conn_s = sqlite3.connect(os.path.join(self.path_s, 'data.qda')) self.conn_d = self.app.conn self.path_d = self.app.project_path self.summary_msg = _("Merging: ") + self.path_s + "\n" + _("Into: ") + self.app.project_path + "\n" self.copy_source_files_into_destination() loaded = self.get_source_data() if loaded: self.insert_sources_get_new_file_ids() self.update_coding_file_ids() self.insert_categories() self.update_code_cid_and_insert_code() self.insert_coding_and_journal_data() self.insert_cases() self.insert_new_attribute_types() self.insert_attributes() self.summary_msg += _("Finished merging " + self.path_s + " into " + self.path_d) + "\n" self.summary_msg += _("Existing values in destination project are not over-written, apart from blank attribute values.") + "\n" Message(self.app, _('Project merged'), _("Review the action log for details.")).exec_() self.projects_merged = True self.app.delete_backup = False else: Message(self.app, _('Project not merged'), _("Project not merged")).exec_() def insert_categories(self): """ Insert categories into destination code_cat table. The categories have already been filtered to remove any names that match names in the destination database. """ cur_d = self.conn_d.cursor() # Insert top level categories remove_list = [] for c in self.categories_s: if c['supercatname'] is None: self.summary_msg += _("Adding top level category: ") + c['name'] + "\n" cur_d.execute("insert into code_cat (name,memo,owner,date,supercatid) values(?,?,?,?,?)", (c['name'], c['memo'], c['owner'], c['date'], c['supercatid'])) self.conn_d.commit() remove_list.append(c) for item in remove_list: self.categories_s.remove(item) ''' Add sub-categories. look at each unmatched category, iterate through to add as child, then remove from the list ''' count = 0 while len(self.categories_s) > 0 and count < 1000: remove_list = [] for c in self.categories_s: # This needs to be repeated as it is changes cur_d.execute("select catid from code_cat where name=?", [c['supercatname']]) res_category = cur_d.fetchone() if res_category is not None: remove_list.append(c) sql = "insert into code_cat (name, memo, owner, date, supercatid) values (?,?,?,?,?)" cur_d.execute(sql, [c['name'], c['memo'], c['owner'], c['date'], res_category[0]]) self.conn_d.commit() self.summary_msg += _("Adding sub-category: " + c['name']) + " --> " + c['supercatname'] + "\n" for item in remove_list: self.categories_s.remove(item) count += 1 if len(self.categories_s) > 0: self.summary_msg += str(len(self.categories_s)) + _(" categories not added") + "\n" print("Categories NOT added:\n", self.categories_s) logger.debug("Categories NOT added:\n" + str(self.categories_s)) def update_code_cid_and_insert_code(self): """ Update the cid to the one already in Destination.code_name. Check for no matches and insert these into the Destination.code_name table. """ cur_d = self.conn_d.cursor() cur_d.execute("select name, catid from code_cat") dest_categories = cur_d.fetchall() sql = "select cid, name from code_name" cur_d.execute(sql) res = cur_d.fetchall() for code_dest in res: for code_source in self.codes_s: if code_source['name'] == code_dest[1]: code_source['newcid'] = code_dest[0] # Insert unmatched code names for code_s in self.codes_s: if code_s['newcid'] == -1: # Fill category id using matching category name for cat in dest_categories: if cat[0] == code_s['catname']: code_s['catid'] = cat[1] cur_d.execute("insert into code_name (name,memo,owner,date,catid,color) values(?,?,?,?,?,?)", (code_s['name'], code_s['memo'], code_s['owner'], code_s['date'], code_s['catid'], code_s['color'])) self.conn_d.commit() cur_d.execute("select last_insert_rowid()") cid = cur_d.fetchone()[0] code_s['newcid'] = cid self.summary_msg += _("Adding code name: ") + code_s['name'] + "\n" # Update code_text, code_image, code_av cids to destination values for code_s in self.codes_s: for coding_text in self.code_text_s: if coding_text['cid'] == code_s['cid']: coding_text['newcid'] = code_s['newcid'] for coding_image in self.code_image_s: if coding_image['cid'] == code_s['cid']: coding_image['newcid'] = code_s['newcid'] for coding_av in self.code_av_s: if coding_av['cid'] == code_s['cid']: coding_av['newcid'] = code_s['newcid'] def insert_coding_and_journal_data(self): """ Coding fid and cid have been updated, annotation fid has been updated. Insert code_text, code_image, code_av, journal and stored_sql data into Destination project. """ cur_d = self.conn_d.cursor() # Earlier db versions did not have unique journal name # Need to identify duplicate journal names and not import them cur_d.execute("select name from journal") j_names_res = cur_d.fetchall() j_names = [] for j in j_names_res: j_names.append(j[0]) for j in self.journals_s: # Possible to have two identical journal names in earlier db versions if j['name'] not in j_names: cur_d.execute("insert into journal (name, jentry, date, owner) values(?,?,?,?)", (j['name'], j['jentry'], j['date'], j['owner'])) self.summary_msg += _("Adding journal: ") + j['name'] + "\n" self.conn_d.commit() for s in self.stored_sql_s: # Cannot have two identical stored_sql titles, using 'or ignore' cur_d.execute("insert or ignore into stored_sql (title, description, grouper, ssql) values(?,?,?,?)", (s['title'], s['description'], s['grouper'], s['ssql'])) self.conn_d.commit() for c in self.code_text_s: cur_d.execute("insert or ignore into code_text (cid,fid,seltext,pos0,pos1,owner,\ memo,date, important) values(?,?,?,?,?,?,?,?,?)", (c['newcid'], c['newfid'], c['seltext'], c['pos0'], c['pos1'], c['owner'], c['memo'], c['date'], c['important'])) self.conn_d.commit() if len(self.code_text_s) > 0: self.summary_msg += _("Merging coded text") + "\n" for a in self.annotations_s: cur_d.execute("insert or ignore into annotation (fid,pos0,pos1,memo,owner,date) values(?,?,?,?,?,?)", [a["newfid"], a["pos0"], a["pos1"], a["memo"], a["owner"], a["date"]]) self.conn_d.commit() if len(self.annotations_s) > 0: self.summary_msg += _("Merging annotations") + "\n" for c in self.code_image_s: cur_d.execute( "insert or ignore into code_image (cid, id,x1,y1,width,height,memo,owner,date,important) values(?,?,?,?,?,?,?,?,?,?)", [c["newcid"], c["newfid"], c["x1"], c["y1"], c["width"], c["height"], c["memo"], c["owner"], c["date"], c["important"]]) self.conn_d.commit() if len(self.code_image_s) > 0: self.summary_msg += _("Merging coded image areas") + "\n" for c in self.code_av_s: cur_d.execute( "insert or ignore into code_av (cid, id,pos0,pos1,memo,owner,date,important) values(?,?,?,?,?,?,?,?)", [c["newcid"], c["newfid"], c["pos0"], c["pos1"], c["memo"], c["owner"], c["date"], c["important"]]) self.conn_d.commit() if len(self.code_av_s) > 0: self.summary_msg += _("Merging coded audio/video segments") + "\n" def insert_cases(self): """ Insert case data into destination. First remove all existing matching case names and the associated case text data. """ cur_d = self.app.conn.cursor() # Remove all duplicate cases and case text lists from source data cur_d.execute("select name from cases") res_cases_dest = cur_d.fetchall() existing_case_names = [] for r in res_cases_dest: existing_case_names.append(r[0]) remove_case_list = [] for case_s in self.cases_s: if case_s['name'] in existing_case_names: remove_case_list.append(case_s) removed_case_text_list = [] for removed_case in remove_case_list: self.cases_s.remove(removed_case) for case_text in self.case_text_s: if case_text['caseid'] == removed_case['caseid']: removed_case_text_list.append(case_text) for removed_case_text in removed_case_text_list: self.case_text_s.remove(removed_case_text) # Insert new cases into destination new_case_ids = [] for case_s in self.cases_s: cur_d.execute("insert into cases (name, memo, owner, date) values (?,?,?,?)", [case_s['name'], case_s['memo'], case_s['owner'], case_s['date']]) self.app.conn.commit() cur_d.execute("select last_insert_rowid()") case_id = cur_d.fetchone()[0] case_s['newcaseid'] = case_id new_case_ids.append(case_id) self.summary_msg += _("Adding case: ") + case_s['name'] + "\n" # Update newcaseid and newfid in case_text for case_text in self.case_text_s: for case_s in self.cases_s: if case_s['caseid'] == case_text['caseid']: case_text['newcaseid'] = case_s['newcaseid'] for file_ in self.source_s: if case_text['fid'] == file_['newid']: case_text['newfid'] = file_['newid'] # Insert case text if newfileid is not -1 and newcaseid is not -1 for c in self.case_text_s: if c['newcaseid'] > -1 and c['newfid'] > -1: cur_d.execute("insert into case_text (caseid,fid,pos0,pos1) values(?,?,?,?)", [c['newcaseid'], c['newfid'], c['pos0'], c['pos1']]) self.app.conn.commit() # Create attribute placeholders for the destination case attributes now_date = datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S") sql_attribute_types = 'select name from attribute_type where caseOrFile ="case"' cur_d.execute(sql_attribute_types) res_attr_types = cur_d.fetchall() sql_attribute = "insert into attribute (name, attr_type, value, id, date, owner) values(?,'file','',?,?,?)" for id_ in new_case_ids: for attribute_name in res_attr_types: cur_d.execute(sql_attribute, [attribute_name[0], id_, now_date, self.app.settings['codername']]) self.app.conn.commit() def insert_sources_get_new_file_ids(self): """ Insert Source.source into Destination.source, unless source file name is already present. update newfid in source_s and code_text_s. Update the av_text_id link to link A/V to the corresponding transcript. """ new_source_file_ids = [] cur_d = self.conn_d.cursor() for src in self.source_s: cur_d.execute("select id, length(fulltext) from source where name=?", [src['name']]) res = cur_d.fetchone() if res is not None: # Existing same named source file is in the destination database src['newid'] = res[0] # Warn user if the source and destination fulltexts are different lengths # Occurs if one of the texts was edited or replaced if len(src['fulltext']) != res[1]: msg = _("Warning! Inaccurate coding positions. Text lengths different for same text file: ") msg += src['name'] + "\n" msg += _("Import project file text length: ") + str(len(src['fulltext'])) + " " msg += _("Destination project file text length: ") + str(res[1]) + "\n" self.summary_msg += msg else: # To update the av_text_id after all new ids have been generated cur_d.execute( "insert into source(name,fulltext,mediapath,memo,owner,date, av_text_id) values(?,?,?,?,?,?,?)", (src['name'], src['fulltext'], src['mediapath'], src['memo'], src['owner'], src['date'], None)) self.conn_d.commit() cur_d.execute("select last_insert_rowid()") id_ = cur_d.fetchone()[0] src['newid'] = id_ new_source_file_ids.append(id_) # Need to find matching av_text_filename to get its id to link as the av_text_id for src in self.source_s: if src['av_text_filename'] != "": cur_d.execute("select id from source where name=?", [src['av_text_filename']]) res = cur_d.fetchone() if res is not None: cur_d.execute("update source set av_text_id=? where id=?", [res[0], src['id']]) self.conn_d.commit() # Create attribute placeholders for the destination file attributes now_date = datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S") sql_attribute_types = 'select name from attribute_type where caseOrFile ="file"' cur_d.execute(sql_attribute_types) res_attr_types = cur_d.fetchall() sql_attribute = "insert into attribute (name, attr_type, value, id, date, owner) values(?,'file','',?,?,?)" for id_ in new_source_file_ids: for attribute_name in res_attr_types: cur_d.execute(sql_attribute, [attribute_name[0], id_, now_date, self.app.settings['codername']]) self.app.conn.commit() def update_coding_file_ids(self): """ Update the file ids in the codings and annotations data. """ for src in self.source_s: for c_text in self.code_text_s: if c_text['fid'] == src['id']: c_text['newfid'] = src['newid'] for an in self.annotations_s: if an['fid'] == src['id']: an['newfid'] = src['newid'] for c_img in self.code_image_s: if c_img['fid'] == src['id']: c_img['newfid'] = src['newid'] for c_av in self.code_av_s: if c_av['fid'] == src['id']: c_av['newfid'] = src['newid'] def copy_source_files_into_destination(self): """ Copy source files into destination project. Do not copy over existing files. """ folders = ["audio", "documents", "images", "video"] for folder_name in folders: dir_ = self.path_s + "/" + folder_name files = os.listdir(dir_) for f in files: if not os.path.exists(self.app.project_path + "/" + folder_name + "/" + f): try: shutil.copyfile(dir_ + "/" + f, self.app.project_path + "/" + folder_name + "/" + f) self.summary_msg += _("File copied: ") + f + "\n" except shutil.SameFileError: pass except PermissionError: self.summary_msg += f + " " + _("NOT copied. Permission error") def insert_new_attribute_types(self): """ Insert new attribute types for cases and files. Insert placeholders for the new attribute types. To be performed after Cases and files have been inserted. """ cur_d = self.app.conn.cursor() cur_d.execute("select id from source") res_file_ids = cur_d.fetchall() cur_d.execute("select caseid from cases") res_case_ids = cur_d.fetchall() # Insert new attribute type and placeholder in attribute table for a in self.attribute_types_s: cur_d.execute("insert into attribute_type (name,date,owner,memo,caseOrFile, valuetype) values(?,?,?,?,?,?)", (a['name'], a['date'], a['owner'], a['memo'], a['caseOrFile'], a['valuetype'])) self.app.conn.commit() self.summary_msg += _("Adding attribute (") + a['caseOrFile'] + "): " + a['name'] + "\n" # Create attribute placeholders for new attributes, does NOT create for existing destination attributes if a['caseOrFile'] == "file": for id_ in res_file_ids: sql = "insert into attribute (name, value, id, attr_type, date, owner) values (?,?,?,?,?,?)" cur_d.execute(sql, (a['name'], "", id_[0], "file", a['date'], a['owner'])) self.app.conn.commit() if a['caseOrFile'] == "case": for id_ in res_case_ids: sql = "insert into attribute (name, value, id, attr_type, date, owner) values (?,?,?,?,?,?)" cur_d.execute(sql, (a['name'], "", id_[0], "case", a['date'], a['owner'])) self.app.conn.commit() def insert_attributes(self): """ Insert new attribute values for files and cases. Need to use destination file and case ids. Example attribute: {'name': 'age', 'attr_type': 'file', 'value': '100', 'id': 4, 'newid': -1, 'date': '2022-03-14 10:35:27', 'owner': 'default'} """ # Only update if value does not over-write an existing placeholder attribute value sql_update = "update attribute set value=? where name=? and id=? and attr_type=? and value=''" # Insert if a placeholder is missing sql_insert = "insert into attribute (name,id,attr_type,value,date,owner) values (?,?,?,?,?,?)" attribute_count = 0 cur_d = self.app.conn.cursor() for a in self.attributes_s: if a['attr_type'] == "file": source_dict = next((item for item in self.source_s if item["id"] == a['id']), {'newid': -1}) a['newid'] = source_dict['newid'] if a['attr_type'] == "case": case_dict = next((item for item in self.cases_s if item["caseid"] == a['id']), {'newcaseid': -1}) a['newid'] = case_dict['newcaseid'] # Only update or insert value does not over-write an existing placeholder attribute value if a['newid'] != -1: # Check placeholder exists, if not then insert values cur_d.execute("select * from attribute where name=? and id=? and attr_type=?", [a['name'], a['newid'], a['attr_type']]) res = cur_d.fetchall() if not res: cur_d.execute(sql_insert, (a['name'], a['newid'], a['attr_type'],a['value'], a['date'], a['owner'])) self.app.conn.commit() attribute_count += 1 else: cur_d.execute(sql_update, (a['value'], a['name'], a['newid'], a['attr_type'])) self.app.conn.commit() attribute_count += 1 if attribute_count > 0: self.summary_msg += _("Added attribute values for cases and files: n=") + str(attribute_count) + "\n" def get_source_data(self): """ Load the database data into Lists of Dictionaries. return: True or False if data was able to be loaded """ self.journals_s = [] self.stored_sql_s = [] self.codes_s = [] self.categories_s = [] self.code_text_s = [] self.annotations_s = [] self.code_image_s = [] self.code_av_s = [] self.cases_s = [] self.case_text_s = [] self.attribute_types_s = [] self.attributes_s = [] cur_s = self.conn_s.cursor() # Database version must be v5 or higher cur_s.execute("select databaseversion from project") version = cur_s.fetchone() if version[0] in ("v1", "v2", "v3", "v4"): self.summary_msg += _("Need to update the source project database.") + "\n" self.summary_msg += _("Please open the source project using QualCoder. Then close the project.") + "\n" self.summary_msg += _("This will update the database schema. Then try merging again.") self.summary_msg += _("Project not merged") + "\n" return False # Journal data sql_journal = "select name, jentry, date, owner from journal" cur_s.execute(sql_journal) res_journals = cur_s.fetchall() for i in res_journals: src = {"name": i[0], "jentry": i[1], "date": i[2], "owner": i[3]} self.journals_s.append(src) # Stored sql data sql_stored_sql = "select title, description, grouper, ssql from stored_sql" cur_s.execute(sql_stored_sql) res_stored_sqls = cur_s.fetchall() for i in res_stored_sqls: src = {"title": i[0], "description": i[1], "grouper": i[2], "ssql": i[3]} self.stored_sql_s.append(src) # Source data sql_source = "select id, name, fulltext,mediapath,memo,owner,date,av_text_id from source" cur_s.execute(sql_source) res_source = cur_s.fetchall() # Later update av_text_id for i in res_source: src = {"id": i[0], "newid": -1, "name": i[1], "fulltext": i[2], "mediapath": i[3], "memo": i[4], "owner": i[5], "date": i[6], "av_text_id": i[7], "av_text_filename": ""} self.source_s.append(src) # The av_text_id is not enough to recreate linkages. Need the referenced text file name. for i in self.source_s: if i['av_text_id'] is not None: cur_s.execute("select name from source where id=?", [i['av_text_id']]) res = cur_s.fetchone() if res is not None: i['av_text_filename'] = res[0] # Category data sql_codecats = "select catid, supercatid, name, memo, owner, date from code_cat" cur_s.execute(sql_codecats) res_codecats = cur_s.fetchall() for i in res_codecats: ccat = {"catid": i[0], "supercatid": i[1], "supercatname": None, "name": i[2], "memo": i[3], "owner": i[4], "date": i[5], } self.categories_s.append(ccat) # Remove categories from the source list, that are already present in the destination database cur_d = self.app.conn.cursor() cur_d.execute("select name from code_cat") res_dest_catnames = cur_d.fetchall() dest_cat_names_list = [] for r in res_dest_catnames: dest_cat_names_list.append(r[0]) temp_source_cats = [] for cat in self.categories_s: if cat['name'] not in dest_cat_names_list: temp_source_cats.append(cat) self.categories_s = temp_source_cats # Add reference to linked supercat using category name for cat in self.categories_s: cur_s.execute("select name from code_cat where catid=?", [cat['supercatid']]) res = cur_s.fetchone() if res is not None: cat['supercatname'] = res[0] # Code data sql_codenames = "select cid, name, memo, owner, date, color, catid from code_name" cur_s.execute(sql_codenames) res_codes = cur_s.fetchall() for i in res_codes: code_s = {"cid": i[0], "newcid": -1, "name": i[1], "memo": i[2], "owner": i[3], "date": i[4], "color": i[5], "catid": i[6], "catname": None} self.codes_s.append(code_s) # Get and fill category name if code is in a category for code_s in self.codes_s: cur_s.execute("select name from code_cat where catid=?", [code_s['catid']]) res = cur_s.fetchone() if res is not None: code_s['catname'] = res[0] # Code text data sql_codetext = "select cid, fid, seltext, pos0, pos1, owner, date, memo, important from code_text" cur_s.execute(sql_codetext) res_codetext = cur_s.fetchall() for i in res_codetext: ct = {"cid": i[0], "newcid": -1, "fid": i[1], "newfid": -1, "seltext": i[2], "pos0": i[3], "pos1": i[4], "owner": i[5], "date": i[6], "memo": i[7], "important": i[8]} self.code_text_s.append(ct) # Text annotations data sql_annotations = "select fid, pos0, pos1, memo, owner, date from annotation" cur_s.execute(sql_annotations) res_annot = cur_s.fetchall() for i in res_annot: an = {"fid": i[0], "newfid": -1, "pos0": i[1], "pos1": i[2], "memo": i[3], "owner": i[4], "date": i[5]} self.annotations_s.append(an) # Code image data sql_code_img = "select cid, id, x1, y1, width, height, memo, date, owner, important from code_image" cur_s.execute(sql_code_img) res_code_img = cur_s.fetchall() for i in res_code_img: cimg = {"cid": i[0], "newcid": -1, "fid": i[1], "newfid": -1, "x1": i[2], "y1": i[3], "width": i[4], "height": i[5], "memo": i[6], "date": i[7], "owner": i[8], "important": i[9]} self.code_image_s.append(cimg) # Code AV data sql_code_av = "select cid, id, pos0, pos1, owner, date, memo, important from code_av" cur_s.execute(sql_code_av) res_code_av = cur_s.fetchall() for i in res_code_av: c_av = {"cid": i[0], "newcid": -1, "fid": i[1], "newfid": -1, "pos0": i[2], "pos1": i[3], "owner": i[4], "date": i[5], "memo": i[6], "important": i[7]} self.code_av_s.append(c_av) # Case data sql_cases = "select caseid, name, memo, owner, date from cases" cur_s.execute(sql_cases) res_cases = cur_s.fetchall() for i in res_cases: c = {"caseid": i[0], "newcaseid": -1, "name": i[1], "memo": i[2], "owner": i[3], "date": i[4]} self.cases_s.append(c) sql_case_text = "select caseid, fid, pos0, pos1 from case_text" cur_s.execute(sql_case_text) res_case_text = cur_s.fetchall() for i in res_case_text: c = {"caseid": i[0], "newcaseid": -1, "fid": i[1], "newfid": -1, "pos0": i[2], "pos1": i[3]} self.case_text_s.append(c) # Attribute type data sql_attr_type = "select name, memo, date, owner, caseOrFile, valuetype from attribute_type" cur_s.execute(sql_attr_type) res_attr_type_s = cur_s.fetchall() keys = 'name', 'memo', 'date', 'owner', 'caseOrFile', 'valuetype' temp_attribute_types_s = [] for row in res_attr_type_s: temp_attribute_types_s.append(dict(zip(keys, row))) # Remove matching attribute type names cur_d = self.app.conn.cursor() cur_d.execute("select name from attribute_type") res_attr_name_dest = cur_d.fetchall() attribute_names_dest = [] for r in res_attr_name_dest: attribute_names_dest.append(r[0]) self.attribute_types_s = [] for r in temp_attribute_types_s: if r['name'] not in attribute_names_dest: self.attribute_types_s.append(r) # Attribute data sql_attributes = "select name, attr_type, value, id, date ,owner from attribute" cur_s.execute(sql_attributes) res_attributes = cur_s.fetchall() for i in res_attributes: attribute = {"name": i[0], "attr_type": i[1], "value": i[2], "id": i[3], "newid": -1, "date": i[4], "owner": i[5]} self.attributes_s.append(attribute) return True
1,309
0
27
49d1dad5f4c48818f0f83f49696bf966ba1ac099
82
py
Python
os.py
vishnuhd/k8s-cronjob-python
b7e53f8f9984ff3cbc256b5275345b256ccb0035
[ "Apache-2.0" ]
null
null
null
os.py
vishnuhd/k8s-cronjob-python
b7e53f8f9984ff3cbc256b5275345b256ccb0035
[ "Apache-2.0" ]
null
null
null
os.py
vishnuhd/k8s-cronjob-python
b7e53f8f9984ff3cbc256b5275345b256ccb0035
[ "Apache-2.0" ]
null
null
null
import os print("Hello",os.getenv('NAME')) print("Your age is",os.getenv('AGE'))
16.4
37
0.670732
import os print("Hello",os.getenv('NAME')) print("Your age is",os.getenv('AGE'))
0
0
0
5b7753a7f311460d7b616741278ffa7413e3712c
2,224
py
Python
miura/data.py
toumorokoshi/miura
f23e270a9507e5946798b1e897220c9fb1b8d5fa
[ "MIT" ]
1
2017-05-18T11:34:35.000Z
2017-05-18T11:34:35.000Z
miura/data.py
toumorokoshi/miura
f23e270a9507e5946798b1e897220c9fb1b8d5fa
[ "MIT" ]
null
null
null
miura/data.py
toumorokoshi/miura
f23e270a9507e5946798b1e897220c9fb1b8d5fa
[ "MIT" ]
null
null
null
import os import re import yaml from .exceptions import MiuraException import logging logger = logging.getLogger(__name__) def load_file_or_directory(path): """ given a path, determine if the path is a file or directory, and yield a list of absolute file paths """ assert os.path.exists(path), "{0} does not exist!".format(path) absolute_path = os.path.abspath(path) if not os.path.isdir(path): yield absolute_path else: for root, dirs, file_paths in os.walk(path): for file_path in file_paths: yield os.path.join(root, file_path) def retrieve_data(file_paths): """ passed an iterable list of file_paths, loop through all of them and generate a dictionary containing all the context """ data_dict = {} for file_path in file_paths: with open(file_path) as fh: try: content = yaml.load(fh.read()) except yaml.YAMLError as e: raise MiuraException( "Unable to parse yaml at {0}: \n {1}".format( file_path, str(e) )) if not isinstance(content, dict): raise MiuraException( "{0} is does not translate to a dictionary!".format(file_path) ) data_dict.update(content) return data_dict def filter_data(data, filter_dict): """ filter a data dictionary for values only matching the filter """ for key, match_string in filter_dict.items(): if key not in data: logger.warning("{0} doesn't match a top level key".format(key)) continue values = data[key] matcher = re.compile(match_string) if isinstance(values, list): values = [v for v in values if matcher.search(v)] elif isinstance(values, dict): values = dict((k, v) for k, v in values.items() if matcher.search(k)) else: raise MiuraException("cannot filter a {0}".format(type(values))) data[key] = values
31.771429
82
0.599371
import os import re import yaml from .exceptions import MiuraException import logging logger = logging.getLogger(__name__) def load_data_from_path(path): file_paths = load_file_or_directory(path) return retrieve_data(file_paths) def load_file_or_directory(path): """ given a path, determine if the path is a file or directory, and yield a list of absolute file paths """ assert os.path.exists(path), "{0} does not exist!".format(path) absolute_path = os.path.abspath(path) if not os.path.isdir(path): yield absolute_path else: for root, dirs, file_paths in os.walk(path): for file_path in file_paths: yield os.path.join(root, file_path) def retrieve_data(file_paths): """ passed an iterable list of file_paths, loop through all of them and generate a dictionary containing all the context """ data_dict = {} for file_path in file_paths: with open(file_path) as fh: try: content = yaml.load(fh.read()) except yaml.YAMLError as e: raise MiuraException( "Unable to parse yaml at {0}: \n {1}".format( file_path, str(e) )) if not isinstance(content, dict): raise MiuraException( "{0} is does not translate to a dictionary!".format(file_path) ) data_dict.update(content) return data_dict def filter_data(data, filter_dict): """ filter a data dictionary for values only matching the filter """ for key, match_string in filter_dict.items(): if key not in data: logger.warning("{0} doesn't match a top level key".format(key)) continue values = data[key] matcher = re.compile(match_string) if isinstance(values, list): values = [v for v in values if matcher.search(v)] elif isinstance(values, dict): values = dict((k, v) for k, v in values.items() if matcher.search(k)) else: raise MiuraException("cannot filter a {0}".format(type(values))) data[key] = values
92
0
23
1c984379a042e9fd6a8818d0f9d29c518209740c
6,982
py
Python
exp_script.py
meelgroup/mgt
ccd51c9094e63eee8234ed7cde128746a481f897
[ "MIT" ]
1
2020-02-27T19:14:37.000Z
2020-02-27T19:14:37.000Z
exp_script.py
meelgroup/mgt
ccd51c9094e63eee8234ed7cde128746a481f897
[ "MIT" ]
null
null
null
exp_script.py
meelgroup/mgt
ccd51c9094e63eee8234ed7cde128746a481f897
[ "MIT" ]
null
null
null
import ast import matplotlib.pyplot as plt from matplotlib import cm import matplotlib as mpl from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np import os.path import pandas as pd import seaborn as sns import operator as op from functools import reduce from setup import DIR # DIR to get data to plot from setup import DIR2 # DIR FILE_GENERAL = "output_file-" FILE_GENERAL_CMP = "output_file_comparison-" EXTENSION = ".out" d = 0.05 FILE_2 = "output_file" # binomial cofficient, n choosr r # calculate binary entropy of Bernoulli(p) # function to parse output file that contains both MGT and LP accuracy and time results
30.225108
87
0.552564
import ast import matplotlib.pyplot as plt from matplotlib import cm import matplotlib as mpl from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np import os.path import pandas as pd import seaborn as sns import operator as op from functools import reduce from setup import DIR # DIR to get data to plot from setup import DIR2 # DIR FILE_GENERAL = "output_file-" FILE_GENERAL_CMP = "output_file_comparison-" EXTENSION = ".out" d = 0.05 FILE_2 = "output_file" # binomial cofficient, n choosr r def ncr(n, r): # print(n) # print(r) r = min(r, n-r) numer = reduce(op.mul, range(n, n-r, -1), 1) denom = reduce(op.mul, range(1, r+1), 1) return numer / denom # calculate binary entropy of Bernoulli(p) def bin_entropy(p): return (-p)*np.log2(p)-(1-p)*np.log2(1-p) # function to parse output file that contains both MGT and LP accuracy and time results def parser_comparison(u=0): for i in range(u + 1): if os.path.isfile(DIR + FILE_GENERAL_CMP + str(i) + EXTENSION): with open(DIR + FILE_GENERAL_CMP + str(i) + EXTENSION) as out: data = [ast.literal_eval(line) for line in out if line.strip()] n = data[0] k = data[1] lambdam = data[2] noiseless = data[3] T = data[4] E = data[5] P = data[6] T_CPU = data[7] lp_E = data[8] lp_P = data[9] lp_T_CPU = data[10] print_phase_transition(n, k, lambdam, T, noiseless, T_CPU, lp_T_CPU) print_accuracy(n, k, lambdam, T, noiseless, E, P, lp_E, lp_P) def parser(u=0, verbose=False): for i in range(u + 1): if(verbose): print("showing the plot") if os.path.isfile(DIR + FILE_GENERAL + str(i) + EXTENSION): with open(DIR + FILE_GENERAL + str(i) + EXTENSION) as out: data = [ast.literal_eval(line) for line in out if line.strip()] n = data[0] k = data[1] lambdam = data[2] noiseless = data[3] T = data[4] E = data[5] P = data[6] E = [e/n for e in E] print_accuracy_maxsat(n, k, lambdam, T, noiseless, E, P) def print_accuracy_maxsat(n, k, lambda_w, tests, noiseless, E, P): bound = [] non_asym_bound = [] bound_string = '' non_asym_string = '' title = "$n = $" + str(n) + ", $k = $" + str(k) if noiseless: name = "noiseless" bound_string = r'$klog_2(\frac{n}{k})$' non_asym_string = '(2^m) / (n choose k)' else: name = "noisy" bound_string = r'$log_2\binom{n}{k} / (1 - h(d))$' non_asym_string = 'm*(1 - h(d))) / (log2(n choose k))' title = title + ", $d = 0.05$" plt.plot(tests, P, "b", label="MGT", linewidth=2.5) plt.plot(tests, P, "bo") plt.title(title, fontsize=20) plt.xlabel("number of tests, $m$", fontsize=19) plt.ylabel("probability of success", fontsize=19) plt.legend(loc="best", fontsize=16.5) plt.tight_layout() fig = plt.figure(1) ax = fig.add_subplot(111) ax.tick_params(axis='both', which='major', labelsize=15.5) ax.tick_params(axis='both', which='minor', labelsize=13.5) plt.savefig(DIR2 + str(name) + "_n" + str(n) + "k" + str(k) + ".png") plt.show() def print_accuracy(n, k, lambda_w, tests, noiseless, E, P, lp_E, lp_P): bound = [] non_asym_bound = [] bound_string = '' non_asym_string = '' title = "$n = $" + str(n) + ", $k = $" + str(k) if noiseless: name = "noiseless" bound_string = r'$log_2\binom{n}{k}$' non_asym_string = r'(2^m) / (n \choose k)' for i in range(len(tests)): bound.append(np.log2(ncr(n, k))) if n < 1000: for m in tests: non_asym_bound.append((2**m) / (ncr(n, k))) else: name = "noisy" bound_string = r'$\frac{log_2\binom{n}{k}}{1 - h(d)}$' non_asym_string = r'$m*(1 - h(d))) / (log_2({n \choose k}))$' title = title + ", $d = 0.05$" if n < 1000: for i in range(len(tests)): bound.append(np.log2(ncr(n, k)) / (1 - bin_entropy(d))) if n < 1000: for m in tests: non_asym_bound.append((m*(1 - bin_entropy(d))) / (np.log2(ncr(n, k)))) plt.plot(tests, P, "b", label="MGT", linewidth=2.5) plt.plot(tests, lp_P, "r--", label="LP", linewidth=2.5) plt.plot(tests, P, "bo") plt.plot(tests, lp_P, "rx") if noiseless or n < 1000: plt.plot(bound, P, "k", label=bound_string, linewidth=2.5) plt.title(title, fontsize=20) plt.xlabel("number of tests, $m$", fontsize=19) plt.ylabel("probability of success", fontsize=19) plt.legend(loc="best", fontsize=16.5) plt.tight_layout() fig = plt.figure(1) ax = fig.add_subplot(111) ax.tick_params(axis='both', which='major', labelsize=15.5) ax.tick_params(axis='both', which='minor', labelsize=13.5) plt.savefig(DIR2 + str(name) + "_n" + str(n) + "k" + str(k) + ".png") plt.show() def print_phase_transition(n, k, lambda_w, tests, noiseless, t_maxsat, t_lp): bound = [] non_asym_bound = [] bound_string = '' non_asym_string = '' title = "$n = $" + str(n) + ", $k = $" + str(k) if noiseless: name = "noiseless" bound_string = r'$log_2\binom{n}{k}$' non_asym_string = '(2^m) / {n \choose k}' for i in range(len(tests)): bound.append(np.log2(ncr(n, k))) if n < 1000: for m in tests: non_asym_bound.append((2**m) / (ncr(n, k))) else: name = "noisy" bound_string = r'$\frac{log_2\binom{n}{k}}{1 - h(d)}$' non_asym_string = r'$m*(1 - h(d))) / (log_2({n \choose k}))$' title = title + ", $d = 0.05$" if n < 1000: for i in range(len(tests)): bound.append(np.log2(ncr(n, k)) / (1 - bin_entropy(d))) if n < 1000: for m in tests: non_asym_bound.append((m*(1 - bin_entropy(d))) / (np.log2(ncr(n, k)))) a = [0] + t_maxsat[1:] plt.plot(tests, t_lp, "r--", label="LP", linewidth=2.5) plt.plot(tests, t_maxsat, "b", label="MGT", linewidth=2.5) plt.plot(tests, t_lp, "rx") plt.plot(tests, t_maxsat, "bo") if noiseless or n <= 1000: plt.plot(bound, a, "k", label=bound_string, linewidth=2.5) plt.title(title, fontsize=20) plt.xlabel("number of tests, $m$", fontsize=19) plt.ylabel("time (s)", fontsize=17) plt.legend(loc="best", fontsize=16.5) plt.tight_layout() fig = plt.figure(1) ax = fig.add_subplot(111) ax.tick_params(axis='both', which='major', labelsize=14.5) ax.tick_params(axis='both', which='minor', labelsize=12.5) plt.savefig(DIR2 + "time_" + str(name) + "_n" + str(n) + "k" + str(k) + ".png") plt.show()
6,155
0
160
26869308a0719ae448eb006c4769d94b322635a8
894
py
Python
backend/config/components/auth.py
hnthh/foodgram-project-react
3383c6a116fded11b4a764b95e6ca4ead03444f3
[ "MIT" ]
1
2022-02-09T10:42:45.000Z
2022-02-09T10:42:45.000Z
backend/config/components/auth.py
hnthh/foodgram
3383c6a116fded11b4a764b95e6ca4ead03444f3
[ "MIT" ]
null
null
null
backend/config/components/auth.py
hnthh/foodgram
3383c6a116fded11b4a764b95e6ca4ead03444f3
[ "MIT" ]
null
null
null
AUTH_USER_MODEL = 'users.User' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] DJOSER = { 'HIDE_USERS': False, 'LOGIN_FIELD': 'email', 'SERIALIZERS': { 'user_create': 'users.api.serializers.UserCreateSerializer', 'user': 'users.api.serializers.UserSerializer', 'current_user': 'users.api.serializers.UserSerializer', }, 'PERMISSIONS': { 'user_list': ['rest_framework.permissions.AllowAny'], 'user': ['rest_framework.permissions.IsAuthenticated'], }, }
28.83871
91
0.655481
AUTH_USER_MODEL = 'users.User' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] DJOSER = { 'HIDE_USERS': False, 'LOGIN_FIELD': 'email', 'SERIALIZERS': { 'user_create': 'users.api.serializers.UserCreateSerializer', 'user': 'users.api.serializers.UserSerializer', 'current_user': 'users.api.serializers.UserSerializer', }, 'PERMISSIONS': { 'user_list': ['rest_framework.permissions.AllowAny'], 'user': ['rest_framework.permissions.IsAuthenticated'], }, }
0
0
0
d4aaa9f499269a7b55947f66eaedbee0e3285e9f
3,832
py
Python
stats.py
vlddev/news_downloader
826ab06ae532fdc829862215c0901399a67e6624
[ "Apache-2.0" ]
null
null
null
stats.py
vlddev/news_downloader
826ab06ae532fdc829862215c0901399a67e6624
[ "Apache-2.0" ]
null
null
null
stats.py
vlddev/news_downloader
826ab06ae532fdc829862215c0901399a67e6624
[ "Apache-2.0" ]
null
null
null
import re import sys import logging from collections import Counter # TODO use https://bitbucket.org/spirit/guess_language # for language detection
31.154472
112
0.59238
import re import sys import logging from collections import Counter # TODO use https://bitbucket.org/spirit/guess_language # for language detection class TextStats(object): def __init__(self, text): self.text = text self.text_lower = text.lower() self.words = re.findall(r'\w+', text.lower()) self.stats = Counter(self.words) self.common_text_20 = self.stats.most_common(20) self.dict_20 = dict(self.common_text_20) def isUkr(self): #common_words = ['і','не','на','що','я','в','з','а','у','й'] common_words = ['і','що','з','у','й','та','від','але','це','про','або','як','чи'] commonInText = 0 #print(common_text) for word in common_words: if word in self.dict_20: commonInText += 1 #print('isUkr(): commonInText = '+str(commonInText)) if commonInText > 2: return True else: return False def isRus(self): common_words = ['и','с','что','по','к','от','из','ни','как'] commonInText = 0 #print(common_text) for word in common_words: if word in self.dict_20: commonInText += 1 #print('isRus(): commonInText = '+str(commonInText)) if commonInText > 2: return True else: return False def hasRusLetter(self): if 'э' in self.text_lower or 'ы' in self.text_lower or 'ъ' in self.text_lower: return True else: return False def hasUkrLetter(self): if 'і' in self.text_lower or 'ї' in self.text_lower or 'є' in self.text_lower: return True else: return False def countRusLetters(self): ret = self.text_lower.count('э') ret += self.text_lower.count('ы') ret += self.text_lower.count('ъ') return ret def countUkrLetters(self): ret = self.text_lower.count('і') ret += self.text_lower.count('ї') ret += self.text_lower.count('є') return ret def isEng(self): common_words = ['the','of','to','and','that','in'] commonInText = 0 for word in common_words: if word in self.dict_20: commonInText += 1 if commonInText > 2: return True else: return False def isStoreText(self): ret = True retMsg = '' if len(self.text) > 0: if self.isUkr() and self.isRus(): ret = False retMsg = "IGNORE: Article is Ukr and Rus." logging.info(" stats: "+str(self.common_text_20)) elif self.isRus(): ret = False retMsg = "IGNORE: Article is Rus." elif self.isEng(): ret = False retMsg = "IGNORE: Article is Eng." elif not (self.isUkr() or self.isRus() or self.isEng()): if self.hasRusLetter() and self.hasUkrLetter(): cntUkr = self.countUkrLetters() cntRus = self.countRusLetters() if cntUkr > cntRus : ret = True else: ret = False retMsg = "IGNORE: Article (language not detected) has %d Rus and %d Ukr letters." % (cntRus, cntUkr) elif self.hasRusLetter(): ret = False retMsg = "IGNORE: Article (language not detected) has Rus letters." elif self.hasUkrLetter(): ret = True elif len(self.text) < 450: #ignore article ret = False retMsg = "IGNORE: Article language is not detected." logging.info(" text length: "+ str(len(self.text))) logging.info(" stats: "+str(self.common_text_20)) else: ret = False retMsg = "IGNORE: Article language is not detected." logging.error("Article language not detected.") logging.info(" text length: "+ str(len(self.text))) logging.info(" stats: "+str(self.common_text_20)) sys.exit("Article language not detected.") else: retMsg = "IGNORE: Empty article." ret = False return (ret, retMsg)
3,497
3
247
d10a3d88aef5a6ce7c6db2138dda46ee0331ecd1
10,992
py
Python
VideoEncoding/Encoding_H264_OverlayImage/encoding-h264-overlayimage.py
IngridAtMicrosoft/media-services-v3-python
2eb43f502cd8637961869faf8d0c365ffa1680d2
[ "MIT" ]
null
null
null
VideoEncoding/Encoding_H264_OverlayImage/encoding-h264-overlayimage.py
IngridAtMicrosoft/media-services-v3-python
2eb43f502cd8637961869faf8d0c365ffa1680d2
[ "MIT" ]
null
null
null
VideoEncoding/Encoding_H264_OverlayImage/encoding-h264-overlayimage.py
IngridAtMicrosoft/media-services-v3-python
2eb43f502cd8637961869faf8d0c365ffa1680d2
[ "MIT" ]
null
null
null
from datetime import timedelta from dotenv import load_dotenv from azure.identity import DefaultAzureCredential from azure.mgmt.media import AzureMediaServices from azure.storage.blob import BlobServiceClient from azure.mgmt.media.models import ( Asset, Transform, TransformOutput, StandardEncoderPreset, AacAudio, AacAudioProfile, H264Video, H264Complexity, H264Layer, Mp4Format, Filters, Rectangle, VideoOverlay, Job, JobInputs, JobInputAsset, JobOutputAsset, OnErrorType, Priority ) import os #Timer for checking job progress import time #Get environment variables load_dotenv() # Get the default Azure credential from the environment variables AZURE_CLIENT_ID and AZURE_CLIENT_SECRET and AZURE_TENTANT_ID default_credential = DefaultAzureCredential() # Get the environment variables SUBSCRIPTIONID, RESOURCEGROUP and ACCOUNTNAME subscription_id = os.getenv('SUBSCRIPTIONID') resource_group = os.getenv('RESOURCEGROUP') account_name = os.getenv('ACCOUNTNAME') # The file you want to upload. For this example, the file is placed under Media folder. # The file ignite.mp4 has been provided for you. source_file_location = os.chdir("../../Media/") source_file = "ignite.mp4" # This is a random string that will be added to the naming of things so that you don't have to keep doing this during testing uniqueness = "encodeOverlayPng" # Use the following PNG image to overlay on top of the video overlay_file = "AzureMediaService.png" overlay_label = "overlayCloud" # Set the attributes of the input Asset using the random number in_asset_name = 'inputassetName' + uniqueness in_alternate_id = 'inputALTid' + uniqueness in_description = 'inputdescription' + uniqueness # Create an Asset object # The asset_id will be used for the container parameter for the storage SDK after the asset is created by the AMS client. in_asset = Asset(alternate_id=in_alternate_id, description=in_description) # Create the JobInput for the PNG Image Overlay overlay_asset_name = 'overlayassetName' + uniqueness overlay_asset_alternate_id = 'inputALTid' + uniqueness overlay_asset_description = 'inputdescription' + uniqueness # Create an Asset object for PNG Image overlay overlay_in_asset = Asset(alternate_id=overlay_asset_alternate_id, description=overlay_asset_description) # Set the attributes of the output Asset using the random number out_asset_name = 'outputassetName' + uniqueness out_alternate_id = 'outputALTid' + uniqueness out_description = 'outputdescription' + uniqueness # Create Ouput Asset object out_asset = Asset(alternate_id=out_alternate_id, description=out_description) # The AMS Client print("Creating AMS Client") client = AzureMediaServices(default_credential, subscription_id) # Create an input Asset print(f"Creating input asset {in_asset_name}") input_asset = client.assets.create_or_update(resource_group, account_name, in_asset_name, in_asset) # An AMS asset is a container with a specific id that has "asset-" prepended to the GUID. # So, you need to create the asset id to identify it as the container # where Storage is to upload the video (as a block blob) in_container = 'asset-' + input_asset.asset_id # Create an Overlay input Asset print(f"Creating input asset {overlay_asset_name}") overlay_asset = client.assets.create_or_update(resource_group, account_name, overlay_asset_name, overlay_in_asset) # # An AMS asset is a container with a specific id that has "asset-" prepended to the GUID. # # So, you need to create the asset id to identify it as the container # # where Storage is to upload the video (as a block blob) overlay_container = 'asset-' + overlay_asset.asset_id # create an output Asset print(f"Creating output asset {out_asset_name}") output_asset = client.assets.create_or_update(resource_group, account_name, out_asset_name, out_asset) ### Use the Storage SDK to upload the video ### print(f"Uploading the file {source_file}") blob_service_client = BlobServiceClient.from_connection_string(os.getenv('STORAGEACCOUNTCONNECTION')) blob_client = blob_service_client.get_blob_client(in_container, source_file) working_dir = os.getcwd() print(f"Current working directory: {working_dir}") upload_file_path = os.path.join(working_dir, source_file) # WARNING: Depending on where you are launching the sample from, the path here could be off, and not include the BasicEncoding folder. # Adjust the path as needed depending on how you are launching this python sample file. # Upload the video to storage as a block blob with open(upload_file_path, "rb") as data: blob_client.upload_blob(data) ### Use the Storage SDK to upload the Overlay file print(f"Uploading the file {overlay_file}") blob_service_client = BlobServiceClient.from_connection_string(os.getenv('STORAGEACCOUNTCONNECTION')) blob_client = blob_service_client.get_blob_client(overlay_container, overlay_file) working_dir = os.getcwd() print(f"Current working directory: {working_dir}") upload_file_path = os.path.join(working_dir, overlay_file) # WARNING: Depending on where you are launching the sample from, the path here could be off, and not include the BasicEncoding folder. # Adjust the path as needed depending on how you are launching this python sample file. # Upload the video to storage as a block blob with open(upload_file_path, "rb") as data: blob_client.upload_blob(data) transform_name = 'H264EncodingOverlayImagePng' # Create a new BuiltIn Standard encoding Transform for H264 ContentAware Constrained print(f"Creating Standard Encoding transform named: {transform_name}") # For this snippet, we are using 'StandardEncoderPreset' with Overlay Image transform_output = TransformOutput( preset = StandardEncoderPreset( codecs=[ AacAudio( channels=2, sampling_rate=48000, bitrate=128000, profile=AacAudioProfile.AAC_LC ), H264Video( key_frame_interval=timedelta(seconds=2), complexity=H264Complexity.BALANCED, layers=[ H264Layer( bitrate=3600000, width="1280", height="720", label="HD-3600kbps" ), H264Layer( bitrate=1600000, width="960", height="540", label="SD-1600kbps" ) ] ) ], # Specify the format for the output files - one for video + audio, and another for the thumbnails formats=[ Mp4Format(filename_pattern="Video-{Basename}-{Label}-{Bitrate}{Extension}") ], filters=Filters( overlays=[ VideoOverlay( input_label=overlay_label, # same label that is used in the JobInput to identify which file in the asset is the actual overlay image .png file. position=Rectangle(left="10%", top="10%"), # left and top position of the overlay in absolute pixel or percentage relative to the source video resolution. # You can also set the height and width of the rectangle to draw into, but there is known problem here. # If you use % for the top and left (or any of these) you have to stick with % for all or you will get a job configuration Error # Also, it can alter your aspect ratio when using percentages, so you have to know the source video size in relation to the source image to # provide the proper image size. Recommendation is to just use the right size image for the source video here and avoid passing in height and width for now. # height: (if above is percentage based, this has to be also! Otherwise pixels are allowed. No mixing. ) # width: (if above is percentage based, this has to be also! Otherwise pixels are allowed No mixing. ) opacity=0.75, # Sets the blending opacity value to make the image slightly transparent over the video start=timedelta(seconds=0), # Start at beginning of the video fade_in_duration=timedelta(seconds=2), # 2 second fade in fade_out_duration=timedelta(seconds=2), # 2 second fade out end=timedelta(seconds=5) # end the fade out at 5 seconds on the timeline... fade will begin 2 seconds before this end time ) ] ) ), # What should we do with the job if there is an error? on_error=OnErrorType.STOP_PROCESSING_JOB, # What is the relative priority of this job to others? Normal, high or low? relative_priority=Priority.NORMAL ) print("Creating encoding transform...") # Adding transform details my_transform = Transform() my_transform.description="A simple custom H264 encoding transform that overlays a PNG image on the video source" my_transform.outputs = [transform_output] print(f"Creating transform {transform_name}") transform = client.transforms.create_or_update( resource_group_name=resource_group, account_name=account_name, transform_name=transform_name, parameters=my_transform) print(f"{transform_name} created (or updated if it existed already). ") job_name = 'MyEncodingH264OverlayImagePng'+ uniqueness print(f"Creating Encoding264OverlayImagePng job {job_name}") files = (source_file, overlay_file) # Create Video Input Asset job_video_input_asset = JobInputAsset(asset_name=in_asset_name) job_input_overlay = JobInputAsset( asset_name=overlay_asset_name, label=overlay_label # Order does not matter here, it is the "label" used on the Filter and the jobInput Overlay that is important! ) # Create a list of job inputs - we will add both the video and overlay image assets here as the inputs to the job. job_inputs=[ job_video_input_asset, job_input_overlay ] # Create Job Output Asset outputs = JobOutputAsset(asset_name=out_asset_name) # Create Job object and then create Trasnform Job the_job = Job(input=JobInputs(inputs=job_inputs), outputs=[outputs], correlation_data={ "propertyname": "string" }) job: Job = client.jobs.create(resource_group, account_name, transform_name, job_name, parameters=the_job) # Check Job State job_state = client.jobs.get(resource_group, account_name, transform_name, job_name) # First check print("First job check") print(job_state.state) # Check the state of the job every 10 seconds. Adjust time_in_seconds = <how often you want to check for job state> time_in_seconds = 10 countdown(int(time_in_seconds))
40.411765
170
0.744269
from datetime import timedelta from dotenv import load_dotenv from azure.identity import DefaultAzureCredential from azure.mgmt.media import AzureMediaServices from azure.storage.blob import BlobServiceClient from azure.mgmt.media.models import ( Asset, Transform, TransformOutput, StandardEncoderPreset, AacAudio, AacAudioProfile, H264Video, H264Complexity, H264Layer, Mp4Format, Filters, Rectangle, VideoOverlay, Job, JobInputs, JobInputAsset, JobOutputAsset, OnErrorType, Priority ) import os #Timer for checking job progress import time #Get environment variables load_dotenv() # Get the default Azure credential from the environment variables AZURE_CLIENT_ID and AZURE_CLIENT_SECRET and AZURE_TENTANT_ID default_credential = DefaultAzureCredential() # Get the environment variables SUBSCRIPTIONID, RESOURCEGROUP and ACCOUNTNAME subscription_id = os.getenv('SUBSCRIPTIONID') resource_group = os.getenv('RESOURCEGROUP') account_name = os.getenv('ACCOUNTNAME') # The file you want to upload. For this example, the file is placed under Media folder. # The file ignite.mp4 has been provided for you. source_file_location = os.chdir("../../Media/") source_file = "ignite.mp4" # This is a random string that will be added to the naming of things so that you don't have to keep doing this during testing uniqueness = "encodeOverlayPng" # Use the following PNG image to overlay on top of the video overlay_file = "AzureMediaService.png" overlay_label = "overlayCloud" # Set the attributes of the input Asset using the random number in_asset_name = 'inputassetName' + uniqueness in_alternate_id = 'inputALTid' + uniqueness in_description = 'inputdescription' + uniqueness # Create an Asset object # The asset_id will be used for the container parameter for the storage SDK after the asset is created by the AMS client. in_asset = Asset(alternate_id=in_alternate_id, description=in_description) # Create the JobInput for the PNG Image Overlay overlay_asset_name = 'overlayassetName' + uniqueness overlay_asset_alternate_id = 'inputALTid' + uniqueness overlay_asset_description = 'inputdescription' + uniqueness # Create an Asset object for PNG Image overlay overlay_in_asset = Asset(alternate_id=overlay_asset_alternate_id, description=overlay_asset_description) # Set the attributes of the output Asset using the random number out_asset_name = 'outputassetName' + uniqueness out_alternate_id = 'outputALTid' + uniqueness out_description = 'outputdescription' + uniqueness # Create Ouput Asset object out_asset = Asset(alternate_id=out_alternate_id, description=out_description) # The AMS Client print("Creating AMS Client") client = AzureMediaServices(default_credential, subscription_id) # Create an input Asset print(f"Creating input asset {in_asset_name}") input_asset = client.assets.create_or_update(resource_group, account_name, in_asset_name, in_asset) # An AMS asset is a container with a specific id that has "asset-" prepended to the GUID. # So, you need to create the asset id to identify it as the container # where Storage is to upload the video (as a block blob) in_container = 'asset-' + input_asset.asset_id # Create an Overlay input Asset print(f"Creating input asset {overlay_asset_name}") overlay_asset = client.assets.create_or_update(resource_group, account_name, overlay_asset_name, overlay_in_asset) # # An AMS asset is a container with a specific id that has "asset-" prepended to the GUID. # # So, you need to create the asset id to identify it as the container # # where Storage is to upload the video (as a block blob) overlay_container = 'asset-' + overlay_asset.asset_id # create an output Asset print(f"Creating output asset {out_asset_name}") output_asset = client.assets.create_or_update(resource_group, account_name, out_asset_name, out_asset) ### Use the Storage SDK to upload the video ### print(f"Uploading the file {source_file}") blob_service_client = BlobServiceClient.from_connection_string(os.getenv('STORAGEACCOUNTCONNECTION')) blob_client = blob_service_client.get_blob_client(in_container, source_file) working_dir = os.getcwd() print(f"Current working directory: {working_dir}") upload_file_path = os.path.join(working_dir, source_file) # WARNING: Depending on where you are launching the sample from, the path here could be off, and not include the BasicEncoding folder. # Adjust the path as needed depending on how you are launching this python sample file. # Upload the video to storage as a block blob with open(upload_file_path, "rb") as data: blob_client.upload_blob(data) ### Use the Storage SDK to upload the Overlay file print(f"Uploading the file {overlay_file}") blob_service_client = BlobServiceClient.from_connection_string(os.getenv('STORAGEACCOUNTCONNECTION')) blob_client = blob_service_client.get_blob_client(overlay_container, overlay_file) working_dir = os.getcwd() print(f"Current working directory: {working_dir}") upload_file_path = os.path.join(working_dir, overlay_file) # WARNING: Depending on where you are launching the sample from, the path here could be off, and not include the BasicEncoding folder. # Adjust the path as needed depending on how you are launching this python sample file. # Upload the video to storage as a block blob with open(upload_file_path, "rb") as data: blob_client.upload_blob(data) transform_name = 'H264EncodingOverlayImagePng' # Create a new BuiltIn Standard encoding Transform for H264 ContentAware Constrained print(f"Creating Standard Encoding transform named: {transform_name}") # For this snippet, we are using 'StandardEncoderPreset' with Overlay Image transform_output = TransformOutput( preset = StandardEncoderPreset( codecs=[ AacAudio( channels=2, sampling_rate=48000, bitrate=128000, profile=AacAudioProfile.AAC_LC ), H264Video( key_frame_interval=timedelta(seconds=2), complexity=H264Complexity.BALANCED, layers=[ H264Layer( bitrate=3600000, width="1280", height="720", label="HD-3600kbps" ), H264Layer( bitrate=1600000, width="960", height="540", label="SD-1600kbps" ) ] ) ], # Specify the format for the output files - one for video + audio, and another for the thumbnails formats=[ Mp4Format(filename_pattern="Video-{Basename}-{Label}-{Bitrate}{Extension}") ], filters=Filters( overlays=[ VideoOverlay( input_label=overlay_label, # same label that is used in the JobInput to identify which file in the asset is the actual overlay image .png file. position=Rectangle(left="10%", top="10%"), # left and top position of the overlay in absolute pixel or percentage relative to the source video resolution. # You can also set the height and width of the rectangle to draw into, but there is known problem here. # If you use % for the top and left (or any of these) you have to stick with % for all or you will get a job configuration Error # Also, it can alter your aspect ratio when using percentages, so you have to know the source video size in relation to the source image to # provide the proper image size. Recommendation is to just use the right size image for the source video here and avoid passing in height and width for now. # height: (if above is percentage based, this has to be also! Otherwise pixels are allowed. No mixing. ) # width: (if above is percentage based, this has to be also! Otherwise pixels are allowed No mixing. ) opacity=0.75, # Sets the blending opacity value to make the image slightly transparent over the video start=timedelta(seconds=0), # Start at beginning of the video fade_in_duration=timedelta(seconds=2), # 2 second fade in fade_out_duration=timedelta(seconds=2), # 2 second fade out end=timedelta(seconds=5) # end the fade out at 5 seconds on the timeline... fade will begin 2 seconds before this end time ) ] ) ), # What should we do with the job if there is an error? on_error=OnErrorType.STOP_PROCESSING_JOB, # What is the relative priority of this job to others? Normal, high or low? relative_priority=Priority.NORMAL ) print("Creating encoding transform...") # Adding transform details my_transform = Transform() my_transform.description="A simple custom H264 encoding transform that overlays a PNG image on the video source" my_transform.outputs = [transform_output] print(f"Creating transform {transform_name}") transform = client.transforms.create_or_update( resource_group_name=resource_group, account_name=account_name, transform_name=transform_name, parameters=my_transform) print(f"{transform_name} created (or updated if it existed already). ") job_name = 'MyEncodingH264OverlayImagePng'+ uniqueness print(f"Creating Encoding264OverlayImagePng job {job_name}") files = (source_file, overlay_file) # Create Video Input Asset job_video_input_asset = JobInputAsset(asset_name=in_asset_name) job_input_overlay = JobInputAsset( asset_name=overlay_asset_name, label=overlay_label # Order does not matter here, it is the "label" used on the Filter and the jobInput Overlay that is important! ) # Create a list of job inputs - we will add both the video and overlay image assets here as the inputs to the job. job_inputs=[ job_video_input_asset, job_input_overlay ] # Create Job Output Asset outputs = JobOutputAsset(asset_name=out_asset_name) # Create Job object and then create Trasnform Job the_job = Job(input=JobInputs(inputs=job_inputs), outputs=[outputs], correlation_data={ "propertyname": "string" }) job: Job = client.jobs.create(resource_group, account_name, transform_name, job_name, parameters=the_job) # Check Job State job_state = client.jobs.get(resource_group, account_name, transform_name, job_name) # First check print("First job check") print(job_state.state) # Check the state of the job every 10 seconds. Adjust time_in_seconds = <how often you want to check for job state> def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end="\r") time.sleep(1) t -= 1 job_current = client.jobs.get(resource_group, account_name, transform_name, job_name) if(job_current.state == "Finished"): print(job_current.state) # TODO: Download the output file using blob storage SDK return if(job_current.state == "Error"): print(job_current.state) # TODO: Provide Error details from Job through API return else: print(job_current.state) countdown(int(time_in_seconds)) time_in_seconds = 10 countdown(int(time_in_seconds))
623
0
22
214372d27e8b106f0a19708dede95d2bbe9fdb00
71
py
Python
reinforcement/__init__.py
SwamyDev/reinforcement
997f36a193f57b2a4ba34cf7bcee977b10dd1742
[ "MIT" ]
7
2018-05-15T09:53:18.000Z
2020-06-28T21:24:49.000Z
reinforcement/__init__.py
SwamyDev/reinforcement
997f36a193f57b2a4ba34cf7bcee977b10dd1742
[ "MIT" ]
7
2019-09-08T17:02:56.000Z
2021-08-25T14:41:20.000Z
reinforcement/__init__.py
SwamyDev/reinforcement
997f36a193f57b2a4ba34cf7bcee977b10dd1742
[ "MIT" ]
1
2019-05-07T11:25:29.000Z
2019-05-07T11:25:29.000Z
from reinforcement._version import __version__ name = "reinforcement"
17.75
46
0.830986
from reinforcement._version import __version__ name = "reinforcement"
0
0
0
11de92107fff8f5a01ef8e14f3138244980c3f80
29,308
py
Python
kerfed_api/helpers/shopdoc.py
kerfed/kerfed-api-python
2824f960fe06c6dd1d060eb3a7a57ceee9082b4f
[ "MIT" ]
null
null
null
kerfed_api/helpers/shopdoc.py
kerfed/kerfed-api-python
2824f960fe06c6dd1d060eb3a7a57ceee9082b4f
[ "MIT" ]
null
null
null
kerfed_api/helpers/shopdoc.py
kerfed/kerfed-api-python
2824f960fe06c6dd1d060eb3a7a57ceee9082b4f
[ "MIT" ]
null
null
null
import os import json import collections import numpy as np import pandas as pd # in the standard lib # like regexes but with less annoying wildcards import re from fnmatch import fnmatch try: import webcolors except BaseException: webcolors = None def expand_wildcard(df, key, values): """ Expand finish wildcards from our actual material list. Parameters ------------ df : pandas.DataFrame Contains data. values : [str] Values to expand wildcards into Returns ------------- expanded : pandas.DataFrame Copy of data with wildcards expanded. """ # do matching # row indexes to drop from result drop = [] # rows to append to the result append = [] # iterate through each row for i, row in df.iterrows(): # possibly a pattern pattern = row[key] # if no wildcard continue if pd.isna(pattern) or '*' not in pattern: continue # we have wildcard so drop the original row drop.append(i) # go through each candidate material for cand in values: if pd.isna(cand): continue # if the wildcards match append it if match(candidate=cand, pattern=pattern): # get a copy of the row c = row.copy() # replace the wildcard material with an actual material # if the material was specifically set don't override if 'Process' in df.columns: same = df[df.Material == cand] if len(same) > 0 and any(same.Process == row.Process): continue # if c.Material in df.Material: # continue c[key] = cand # append row as a dic append.append(c.to_dict()) if len(drop) > 0: result = df.drop(drop) else: result = df.copy() if len(append) > 0: # drop old rows with wildcard and append new rows result = result.append(append) return result def check_machine(section, has_machines, shopId=None): """ Make sure the generated data includes every specified machine. """ collected = [] for k, v in section.items(): if not k.startswith('machine_'): continue collected.extend(v['values'].keys()) if shopId is not None: for machine in v['values'].values(): if 'shopId' not in machine: machine['shopId'] = shopId assert set(collected) == set(has_machines) def inch_label(value): """ Create a thickness label from an inch thickness. Parameters ------------ value : float Thickness in inches Returns -------------- label : str Label text """ label = '{:0.3f}" ({:0.2f} mm)'.format( value, np.round(value * 25.4, 2)) return label def material_section(df, mac, has_machines, data=None): """ Convert a dataframe from our materials spreadsheet to the options structure format. Parameters ------------- df : pandas.DataFrame Contains material information Returns -------------- section : [dict] Contains material filter information """ doable = set(mac[mac.Machine.isin( has_machines.keys())].Material) # set stock to zero if it was left unset df['Stock Quantity'] = df['Stock Quantity'].fillna(0) all_materials = set() # save result to list of dict result = [{'filter': {'process': ['cots']}}] # all materials available in sheet form all_sheet = set() all_thick = set() # group items to compress list for values, frame in df.groupby(['Material', 'Stock Quantity', 'Extents']): # expand out tuple material, stock, ext = values if material not in doable: continue # get the cutters for this material cutters = (mac[mac.Material == material]) # get the subset of cutters this shop has cutters_ok = cutters.Machine.isin(has_machines.keys()) cutters = cutters[cutters_ok] # find the max thickness for this material thick_max = cutters['Max Thickness'].max() # only list thicknesses below our threshold thicks = frame.Thickness[frame.Thickness < thick_max] if len(thicks) == 0: continue # get thickness array for every grouped value thick = ['{:0.3f}'.format(np.round(float(i), 3)) for i in thicks] all_sheet.add(material) all_materials.add(material) all_thick.update([ '{:0.3f}'.format(np.round(float(i), 3)) for i in frame.Thickness]) # is the material stocked is_stock = bool(stock > 1e-8) # add a material filter with thicknesses result.append( {'filter': {'stock': is_stock, 'thickness': thick, 'process': ['bent', 'flat', 'roll'], 'material': material}, 'props': {'name': material, 'stock': is_stock}}) try: # value might be NaN, just bail extents = [int(i) for i in ext.split('x')] assert len(extents) == 2 result[-1]['props']['extents'] = extents except BaseException: pass for proc in ['turn', 'mill', 'add']: mat_turn = list(mac.Material[mac.Process == proc]) result.append( {'filter': {'stock': False, 'process': proc, 'material': mat_turn}}) all_materials.add('custom') result.append( {'filter': {'stock': False, 'process': 'manual', 'material': list(all_materials)}}) return result def finish_section(df, all_color_keys): """ Convert an excel dataframe to our materials format. Parameters ------------- df : pandas.DataFrame Contains finish data Returns ------------ result : [dict] Contains finish information in options format """ non_cots = ['flat', 'bent', 'roll', 'turn', 'mill', 'manual'] result = [{'filter': {'process': 'cots'}}] for value, frame in df.dropna( subset=['Material', 'Finish']).groupby(['Colors', 'Finish']): materials = list(set(frame.Material)) color, finish = value if not finish.startswith('layer'): materials.append('custom') proc = non_cots else: proc = 'add' # replace wildcard with our all color list if '*' in color: colors = all_color_keys else: colors = color # if colors is a string, strip it for labels if not isinstance(colors, list): colors = [i.strip().lower().replace(' ', '_') for i in colors.split(',')] colors = [i for i in colors if len(i) > 0] result.append( {'filter': {'finish': finish, 'material': materials, 'process': proc, 'color': colors}}) return result def machine_section(df, has_machines=None): """ Convert a dataframe from our materials spreadsheet to the options structure format. Parameters ------------- df : pandas.DataFrame Contains machineinformation Returns -------------- section : [dict] Contains machine filter information """ # fill columns we don't care about df['Feed Model'].fillna('', inplace=True) df['Pierce Model'].fillna('', inplace=True) df['Max Thickness'].fillna(20, inplace=True) # first group materials with the same keys keys = ['Machine', 'Process', 'Feed Model', 'Pierce Model', 'Max Thickness'] # pandas really monkey fucks mixed string/empty data process = np.array(df['Process']) material = np.array(df['Material']) machine = np.array(df['Machine']) # store result result = collections.defaultdict(list) # start with fixed filters all_proc = set(['flat', 'turn', 'bent', 'mill', 'roll', 'add']) for proc in all_proc: filtered = all_proc.difference({proc}) filtered.add('cots') filtered.add('manual') if proc == 'flat': filtered.difference_update(['bent', 'roll']) result[f'machine_{proc}'].append( {'filter': {'process': list(filtered)}}) for values, frame in df.groupby(keys): machine, process, feed, pierce, thick = values # all the materials with the same feeds # i.e.: ['steel_a36', 'steel_a588'] # if this machine isn't included skip it if has_machines is not None and not any( m in machine for m in has_machines): continue material = list(set(frame.Material)) thick = float(thick) top_key = 'machine_{}'.format(process) if process == 'flat': result[top_key].append( {'filter': {'machine_flat': machine, 'process': ['bent', 'flat', 'roll'], 'material': material}, 'props': {'feedModel': json.loads(feed), 'plungeModel': json.loads(pierce), 'maxThick': thick, 'name': machine}}) elif process == 'add': result[top_key].append( {'filter': {top_key: machine, 'process': process, 'material': material}, 'props': {'name': machine, 'cycleModel': json.loads(feed)}}) elif process == 'mill': # roughing is f(r) = seconds per in^3 rough = json.loads(frame['Rough Model'].values[0]) finish = json.loads(frame['Finish Model'].values[0]) result[top_key].append( {'filter': {'machine_mill': machine, 'process': 'mill', 'material': material}, 'props': {'roughModel': rough, 'finishModel': finish, 'name': machine}}) elif process in ['bent', 'roll']: result[top_key].append( {'filter': {top_key: machine, 'process': process, 'material': material}, 'props': {'maxThick': thick, 'name': machine}}) else: result[top_key].append( {'filter': {top_key: machine, 'process': process, 'material': material}, 'props': {'name': machine}}) return result def flat_to_dict(frame): """ Expand a DataFrame containing Key and Value columns into a dict. Parameters ------------ frame : DataFrame Contains Key and Value column, Key is a/b/c Returns ---------- flat : dict Reflects keys and values in frame """ result = {} for _, row in frame.dropna(subset=['Key', 'Value']).iterrows(): try: value = json.loads(row.Value) except BaseException: value = row.Value multiset(result, row.Key, value) return result def multiset(target, key, value): """ Set keys multiple layers deep in a target dict. Parameters ------------- target : dict Location to set new keys into key : str Key to set, in the form 'a/b/c' will be available as target[a][b][c] = value value : any Will be added to target dictionary Returns ------------ target : dict The original dict object """ keys = key.split('/') current = target for i, key in enumerate(keys): last = i >= len(keys) - 1 if key not in current: if last: current[key] = value else: current[key] = {} current = current[key] return target def cost_density(materials, pad_factor=1.0): """ Calculate the cost density of materials from sheet goods. Parameters -------------- material : pandas.DataFrame Contains material information pad_factor : float How much to pad material cost Returns ------------- updates : dict Keys are in 'a/b/a' format for multiset """ # to calculate cost density we need price and volume updates = {} for label, m in materials.groupby('Material'): # what are the extents of the sheet in inches ext = np.ones((len(m.Extents), 2)) * np.nan for index, e in enumerate(m.Extents): try: ext[index] = np.array( e.split('x'), dtype=np.float64).reshape(2) except BaseException: pass # how much was each sheet usd = np.array(m.Price) # how thick is each sheet thick = np.array(m.Thickness) # what is the volume in inches volume = ext[:, 0] * ext[:, 1] * thick # what is the $/in^3 of the material ratio = usd / volume # what is the value saved under key = 'material/{}/usdCubicInch'.format(label) # which had every field populated ok = np.isfinite(ratio) ratio[~ok] = np.median(ratio[ok]) # create an interpolatable model for cost density ordering = thick.argsort() model = {'type': 'table', 'keys': thick[ordering].tolist(), 'values': (ratio[ordering] * pad_factor).tolist()} # should have fixed all nonsense assert np.isfinite(ratio).all() assert np.isfinite(thick).all() updates[key] = model return updates def check_materials(materials, required_mat=None, doable=None): """ Check to make sure every material has required keys """ def convertUsd(item): """ USD accepts a model, not a single value. """ if isinstance(item, dict): return item # return a constant-value polynomial model value = float(item) model = {'type': 'polynomial', 'values': value} return model required_data = [ ('label', str), ('blurb', str), ('link', str), ('lbPerCubicInch', float), ('usdCubicInch', convertUsd)] if 'custom' in materials: materials['custom']['lbPerCubicInch'] = None materials['custom']['usdCubicInch'] = None # keys we're removing try: for mat_key, data in materials.items(): if mat_key == 'custom': assert all(k in data for k, _ in required_data) continue for key, convert in required_data: check = convert(data[key]) if convert == float: assert check > 0.001 elif convert == str: assert len(check) > 0 except BaseException as E: print('failed on material: {}'.format(mat_key)) print('missing {}: {}\n'.format(key, list(data.keys()))) raise(E) # make sure all required materials are included if required_mat is not None: for r in required_mat: if r not in materials: raise ValueError(f'no data for required material {r}!') # remove any material that isn't doable # for key in list(materials.keys()): # if key not in doable: # materials.pop(key) def generate_basic(processes=None, template=None): """ A very basic helper which will use just a list of supported machines. """ def generate_shopdoc(*args): """ Load a series of file objects to generate a shop document. Data will override previous file objects so that you can provide a base template containing most information and then a sparser one with just shop-specific data. Parameters ------------- *args : file-like object with Excel data Load into a Pandas DataFrame Returns ------------- shopdoc : dict Completed shop document. """ # load excel file and parse all sheets into DataFrame xls = [{n: x.parse(n) for n in x.sheet_names} for x in [pd.ExcelFile( os.path.abspath(os.path.expanduser(a)), engine='openpyxl') for a in args]] return xls
30.689005
77
0.52385
import os import json import collections import numpy as np import pandas as pd # in the standard lib # like regexes but with less annoying wildcards import re from fnmatch import fnmatch try: import webcolors except BaseException: webcolors = None class OptionsGenerator(object): def __init__(self, xls, machine_data=None, template=None, all_machines=None): self.xls = xls # key- value data data = pd.read_excel(self.xls, 'Data') # drop unfilled rows data = data.dropna(subset=['Key', 'Value']) # store data as dict self.data = {k: v for k, v in zip(data.Key, data.Value)} self.mat = self.xls.parse('Sheet Goods').dropna( subset=['Material']) if template is not None: # if template passed use it for materials self.tmp = pd.ExcelFile(template) # just use materials from template self.mat = pd.read_excel( self.tmp, 'Material').dropna( subset=['Material']) tmp_data = pd.read_excel( self.tmp, 'Data').dropna(subset=['Key', 'Value']) # store data as dict tmp_data = {k: v for k, v in zip(tmp_data.Key, tmp_data.Value)} # overwrite template data with shop-set keys tmp_data.update(self.data) # assign merged data self.data = tmp_data if 'Finish' in self.xls.sheet_names: # get finish data per-shop fin = pd.read_excel(self.xls, 'Finish') else: # get finish data from template fin = pd.read_excel(self.tmp, 'Finish') # load shops from the excel sheet self.shops = flat_to_dict( pd.read_excel(self.xls, 'Shop')) # replace all machines with passed list if all_machines is not None: self.shops['kerfed']['machines'] = all_machines # data about postprocessing operations self.post = pd.read_excel(self.xls, 'Postprocess').dropna( subset=['Operation']) # load parameters for RTM packages self.rtm = pd.read_excel(self.xls, 'RTM').dropna( subset=['Key', 'Value']) if 'Anodize Colors' in self.xls.sheet_names: # load additional color codes anodize = pd.read_excel( self.xls, 'Anodize Colors') else: # load colors from template anodize = pd.read_excel( self.tmp, 'Anodize Colors') # drop non-complete rows self.anodize_color = anodize.dropna( subset=['Label', 'Hex']) if 'All Colors' in self.xls.sheet_names: color = pd.read_excel(self.xls, 'All Colors') else: color = pd.read_excel(self.tmp, 'All Colors') self.all_color = color.dropna( subset=['Label', 'Hex']) # set of materials we have all_materials = set(self.mat.Material).union( set(multi_to_dict(self.data)['material'].keys())) if machine_data is None: mac = pd.read_excel(self.xls, 'Machine') else: mac = machine_data # remove machines with undefined machine key # and expand materials defined as wildcards self.mac = expand_wildcard( df=mac.dropna(subset=['Machine']), key='Material', values=all_materials) # expand wildcard finishes based on materials we have self.fin = expand_wildcard(df=fin, key='Material', values=all_materials) def generate_logic(self, has_machines): """ Generate an options structure, stored in the "combos" section of the pricing data. Will provide logic like "bright dipping only available on copper alloys" and "cold rold steel is only available in these four thicknesses and can only be finished with powder coating or alodine" """ # powder coating can be any color yo all_color_keys = ['_'.join(i.lower().split()) for i in self.all_color.Label] result = { 'material': material_section( self.mat, mac=self.mac, has_machines=has_machines, data=self.data), 'finish': finish_section( self.fin, all_color_keys=all_color_keys)} machine = machine_section( self.mac, has_machines=has_machines) result.update(machine) return result def generate_data(self, has_machines, has_cots, logic): """ Generate the `descriptions` field, holding data about configurations. """ data = {} proc = set() # unique thickness keys thick_keys = set() for i in logic['material']: if 'thickness' not in i['filter']: continue value = i['filter']['thickness'] if isinstance(value, (np.ndarray, list, set)): thick_keys.update(value) else: thick_keys.add(value) for m in has_machines.values(): proc.add(m['process']) # add a label for each thickness data['thickness'] = { i: {'label': inch_label(float(i))} for i in sorted(thick_keys)} # set the manual keys for key, value in self.data.items(): multiset(data, key, value) # generate cost density information for key, value in cost_density(self.mat).items(): multiset(data, key, value) # subsume everything populated thus far into a "values" subarray data = {k: {'hidden': False, 'values': v} for k, v in data.items()} mac_pop = [] for key, value in data['machine']['values'].items(): if key not in has_machines: mac_pop.append(key) else: value.update(has_machines[key]) for k in mac_pop: data['machine']['values'].pop(k) # now if any machines in has_machines aren't in # our data structure copy the machine the other way if isinstance(has_machines, dict): for k, v in has_machines.items(): if k not in data['machine']['values']: data['machine']['values'][k] = v # re- namespace machines by process -_- # data['machine']['hidden']: True pop = data.pop('machine') for key, value in pop['values'].items(): if value['process'] == 'roll': top_key = 'machine_roll' else: top_key = 'machine_{}'.format(value['process']) if top_key in data: data[top_key]['values'][key] = value else: data[top_key] = {'values': {key: value}, 'hidden': True} data['process'] = {'hidden': True} data['stock'] = {'hidden': True} data['expedite']['hidden'] = True if has_cots: proc.add('cots') data['process']['values'] = { k: {} for k in proc} # collect finish and color keys finish_keys = set([i['filter']['finish'] for i in logic['finish'] if 'finish' in i['filter'] and not isinstance(i['filter']['finish'], list)]) color_keys = set() for f in logic['finish']: if 'color' in f['filter']: if isinstance(f['filter']['color'], list): color_keys.update(f['filter']['color']) # remove the empty string if it snuck in finish_keys -= set(['']) color_keys -= set(['']) # if keys not created yet make them if 'color' not in data: data['color'] = {'hidden': False, 'values': {}} if 'finish' not in data: data['finish'] = {'hidden': False, 'values': {}} # add labels to finish data for root, keys in zip(['finish', 'color'], [finish_keys, color_keys]): for key in keys: current = data[root]['values'] if key not in current: current[key] = {} if 'label' not in current[key]: current[key]['label'] = key.replace( '_', ' ').title() # make sure finishes contain required USD values # and set to zero if not passed for k, v in data['finish']['values'].items(): if 'label' not in v: v['label'] = k.replace( '_', ' ').title() if 'usdBatch' not in v: v['usdBatch'] = 0.0 if 'usdFloor' not in v: v['usdFloor'] = 0.0 # add label to colors and append a hex code # if we have the name in our list of colors for k, v in data['color']['values'].items(): if 'label' not in v: v['label'] = k.replace( '_', ' ').title() if 'hex' not in v and webcolors is not None: try: v['hex'] = webcolors.name_to_hex(k) except BaseException: pass # add a hidden color data['color']['values']['no_color'] = {'hidden': True, 'label': ' '} # add additional color codes specified in the data structure for _, row in self.anodize_color.iterrows(): key = '_'.join(row.Label.lower().split()) data['color']['values'][key] = {'label': row.Label, 'hex': row.Hex} # add additional color codes for powder coating for _, row in self.all_color.iterrows(): key = '_'.join(row.Label.lower().split()) data['color']['values'][key] = {'label': row.Label, 'hex': row.Hex} # now add data about postprocessing operations # like tapping, welding, etc data['postprocess'] = {'hidden': True, 'values': {}} for op, df in self.post.groupby('Operation'): as_dict = {r.Key: r.Value for _, r in df.iterrows()} as_dict['enabled'] = bool(as_dict['enabled']) # save to data structure data['postprocess']['values'][op] = as_dict doable = set(self.mac[self.mac.Machine.isin( has_machines.keys())].Material) doable.add('custom') # make sure every material has required keys check_materials( materials=data['material']['values'], required_mat=list(self.mac.Material.dropna()), doable=doable) # check the machine section if self.shops is not None: shopId = next(iter(self.shops.keys())) else: shopId = None check_machine(section=data, has_machines=has_machines, shopId=shopId) return data def generate(self, has_machines, has_cots): """ Generate a frontend ready shop description. """ logic = self.generate_logic(has_machines) self.datagen = self.generate_data( has_machines=has_machines, logic=logic, has_cots=has_cots) if 'custom' not in self.datagen['material']['values']: pass result = {'combos': logic, 'descriptions': self.datagen} return result def generate_rtm(self): result = {} for _, row in self.rtm.iterrows(): if isinstance(row.Value, str): value = json.loads(row.Value) else: value = row.Value multiset(result, row.Key, value) return result def expand_wildcard(df, key, values): """ Expand finish wildcards from our actual material list. Parameters ------------ df : pandas.DataFrame Contains data. values : [str] Values to expand wildcards into Returns ------------- expanded : pandas.DataFrame Copy of data with wildcards expanded. """ # do matching def match(candidate, pattern): if pattern.strip() == '*': return True if '[!' not in pattern: return fnmatch(candidate, pattern) # after all that do a fucking regex anyway reg = pattern.replace('[!', '(').replace(']', ')').replace('*', '.+') result = re.match(reg, candidate) is None return result # row indexes to drop from result drop = [] # rows to append to the result append = [] # iterate through each row for i, row in df.iterrows(): # possibly a pattern pattern = row[key] # if no wildcard continue if pd.isna(pattern) or '*' not in pattern: continue # we have wildcard so drop the original row drop.append(i) # go through each candidate material for cand in values: if pd.isna(cand): continue # if the wildcards match append it if match(candidate=cand, pattern=pattern): # get a copy of the row c = row.copy() # replace the wildcard material with an actual material # if the material was specifically set don't override if 'Process' in df.columns: same = df[df.Material == cand] if len(same) > 0 and any(same.Process == row.Process): continue # if c.Material in df.Material: # continue c[key] = cand # append row as a dic append.append(c.to_dict()) if len(drop) > 0: result = df.drop(drop) else: result = df.copy() if len(append) > 0: # drop old rows with wildcard and append new rows result = result.append(append) return result def check_machine(section, has_machines, shopId=None): """ Make sure the generated data includes every specified machine. """ collected = [] for k, v in section.items(): if not k.startswith('machine_'): continue collected.extend(v['values'].keys()) if shopId is not None: for machine in v['values'].values(): if 'shopId' not in machine: machine['shopId'] = shopId assert set(collected) == set(has_machines) def inch_label(value): """ Create a thickness label from an inch thickness. Parameters ------------ value : float Thickness in inches Returns -------------- label : str Label text """ label = '{:0.3f}" ({:0.2f} mm)'.format( value, np.round(value * 25.4, 2)) return label def material_section(df, mac, has_machines, data=None): """ Convert a dataframe from our materials spreadsheet to the options structure format. Parameters ------------- df : pandas.DataFrame Contains material information Returns -------------- section : [dict] Contains material filter information """ doable = set(mac[mac.Machine.isin( has_machines.keys())].Material) # set stock to zero if it was left unset df['Stock Quantity'] = df['Stock Quantity'].fillna(0) all_materials = set() # save result to list of dict result = [{'filter': {'process': ['cots']}}] # all materials available in sheet form all_sheet = set() all_thick = set() # group items to compress list for values, frame in df.groupby(['Material', 'Stock Quantity', 'Extents']): # expand out tuple material, stock, ext = values if material not in doable: continue # get the cutters for this material cutters = (mac[mac.Material == material]) # get the subset of cutters this shop has cutters_ok = cutters.Machine.isin(has_machines.keys()) cutters = cutters[cutters_ok] # find the max thickness for this material thick_max = cutters['Max Thickness'].max() # only list thicknesses below our threshold thicks = frame.Thickness[frame.Thickness < thick_max] if len(thicks) == 0: continue # get thickness array for every grouped value thick = ['{:0.3f}'.format(np.round(float(i), 3)) for i in thicks] all_sheet.add(material) all_materials.add(material) all_thick.update([ '{:0.3f}'.format(np.round(float(i), 3)) for i in frame.Thickness]) # is the material stocked is_stock = bool(stock > 1e-8) # add a material filter with thicknesses result.append( {'filter': {'stock': is_stock, 'thickness': thick, 'process': ['bent', 'flat', 'roll'], 'material': material}, 'props': {'name': material, 'stock': is_stock}}) try: # value might be NaN, just bail extents = [int(i) for i in ext.split('x')] assert len(extents) == 2 result[-1]['props']['extents'] = extents except BaseException: pass for proc in ['turn', 'mill', 'add']: mat_turn = list(mac.Material[mac.Process == proc]) result.append( {'filter': {'stock': False, 'process': proc, 'material': mat_turn}}) all_materials.add('custom') result.append( {'filter': {'stock': False, 'process': 'manual', 'material': list(all_materials)}}) return result def finish_section(df, all_color_keys): """ Convert an excel dataframe to our materials format. Parameters ------------- df : pandas.DataFrame Contains finish data Returns ------------ result : [dict] Contains finish information in options format """ non_cots = ['flat', 'bent', 'roll', 'turn', 'mill', 'manual'] result = [{'filter': {'process': 'cots'}}] for value, frame in df.dropna( subset=['Material', 'Finish']).groupby(['Colors', 'Finish']): materials = list(set(frame.Material)) color, finish = value if not finish.startswith('layer'): materials.append('custom') proc = non_cots else: proc = 'add' # replace wildcard with our all color list if '*' in color: colors = all_color_keys else: colors = color # if colors is a string, strip it for labels if not isinstance(colors, list): colors = [i.strip().lower().replace(' ', '_') for i in colors.split(',')] colors = [i for i in colors if len(i) > 0] result.append( {'filter': {'finish': finish, 'material': materials, 'process': proc, 'color': colors}}) return result def machine_section(df, has_machines=None): """ Convert a dataframe from our materials spreadsheet to the options structure format. Parameters ------------- df : pandas.DataFrame Contains machineinformation Returns -------------- section : [dict] Contains machine filter information """ # fill columns we don't care about df['Feed Model'].fillna('', inplace=True) df['Pierce Model'].fillna('', inplace=True) df['Max Thickness'].fillna(20, inplace=True) # first group materials with the same keys keys = ['Machine', 'Process', 'Feed Model', 'Pierce Model', 'Max Thickness'] # pandas really monkey fucks mixed string/empty data process = np.array(df['Process']) material = np.array(df['Material']) machine = np.array(df['Machine']) # store result result = collections.defaultdict(list) # start with fixed filters all_proc = set(['flat', 'turn', 'bent', 'mill', 'roll', 'add']) for proc in all_proc: filtered = all_proc.difference({proc}) filtered.add('cots') filtered.add('manual') if proc == 'flat': filtered.difference_update(['bent', 'roll']) result[f'machine_{proc}'].append( {'filter': {'process': list(filtered)}}) for values, frame in df.groupby(keys): machine, process, feed, pierce, thick = values # all the materials with the same feeds # i.e.: ['steel_a36', 'steel_a588'] # if this machine isn't included skip it if has_machines is not None and not any( m in machine for m in has_machines): continue material = list(set(frame.Material)) thick = float(thick) top_key = 'machine_{}'.format(process) if process == 'flat': result[top_key].append( {'filter': {'machine_flat': machine, 'process': ['bent', 'flat', 'roll'], 'material': material}, 'props': {'feedModel': json.loads(feed), 'plungeModel': json.loads(pierce), 'maxThick': thick, 'name': machine}}) elif process == 'add': result[top_key].append( {'filter': {top_key: machine, 'process': process, 'material': material}, 'props': {'name': machine, 'cycleModel': json.loads(feed)}}) elif process == 'mill': # roughing is f(r) = seconds per in^3 rough = json.loads(frame['Rough Model'].values[0]) finish = json.loads(frame['Finish Model'].values[0]) result[top_key].append( {'filter': {'machine_mill': machine, 'process': 'mill', 'material': material}, 'props': {'roughModel': rough, 'finishModel': finish, 'name': machine}}) elif process in ['bent', 'roll']: result[top_key].append( {'filter': {top_key: machine, 'process': process, 'material': material}, 'props': {'maxThick': thick, 'name': machine}}) else: result[top_key].append( {'filter': {top_key: machine, 'process': process, 'material': material}, 'props': {'name': machine}}) return result def flat_to_dict(frame): """ Expand a DataFrame containing Key and Value columns into a dict. Parameters ------------ frame : DataFrame Contains Key and Value column, Key is a/b/c Returns ---------- flat : dict Reflects keys and values in frame """ result = {} for _, row in frame.dropna(subset=['Key', 'Value']).iterrows(): try: value = json.loads(row.Value) except BaseException: value = row.Value multiset(result, row.Key, value) return result def multiset(target, key, value): """ Set keys multiple layers deep in a target dict. Parameters ------------- target : dict Location to set new keys into key : str Key to set, in the form 'a/b/c' will be available as target[a][b][c] = value value : any Will be added to target dictionary Returns ------------ target : dict The original dict object """ keys = key.split('/') current = target for i, key in enumerate(keys): last = i >= len(keys) - 1 if key not in current: if last: current[key] = value else: current[key] = {} current = current[key] return target def multi_to_dict(multi): target = {} for k, v in multi.items(): multiset(target=target, key=k, value=v) return target def cost_density(materials, pad_factor=1.0): """ Calculate the cost density of materials from sheet goods. Parameters -------------- material : pandas.DataFrame Contains material information pad_factor : float How much to pad material cost Returns ------------- updates : dict Keys are in 'a/b/a' format for multiset """ # to calculate cost density we need price and volume updates = {} for label, m in materials.groupby('Material'): # what are the extents of the sheet in inches ext = np.ones((len(m.Extents), 2)) * np.nan for index, e in enumerate(m.Extents): try: ext[index] = np.array( e.split('x'), dtype=np.float64).reshape(2) except BaseException: pass # how much was each sheet usd = np.array(m.Price) # how thick is each sheet thick = np.array(m.Thickness) # what is the volume in inches volume = ext[:, 0] * ext[:, 1] * thick # what is the $/in^3 of the material ratio = usd / volume # what is the value saved under key = 'material/{}/usdCubicInch'.format(label) # which had every field populated ok = np.isfinite(ratio) ratio[~ok] = np.median(ratio[ok]) # create an interpolatable model for cost density ordering = thick.argsort() model = {'type': 'table', 'keys': thick[ordering].tolist(), 'values': (ratio[ordering] * pad_factor).tolist()} # should have fixed all nonsense assert np.isfinite(ratio).all() assert np.isfinite(thick).all() updates[key] = model return updates def check_materials(materials, required_mat=None, doable=None): """ Check to make sure every material has required keys """ def convertUsd(item): """ USD accepts a model, not a single value. """ if isinstance(item, dict): return item # return a constant-value polynomial model value = float(item) model = {'type': 'polynomial', 'values': value} return model required_data = [ ('label', str), ('blurb', str), ('link', str), ('lbPerCubicInch', float), ('usdCubicInch', convertUsd)] if 'custom' in materials: materials['custom']['lbPerCubicInch'] = None materials['custom']['usdCubicInch'] = None # keys we're removing try: for mat_key, data in materials.items(): if mat_key == 'custom': assert all(k in data for k, _ in required_data) continue for key, convert in required_data: check = convert(data[key]) if convert == float: assert check > 0.001 elif convert == str: assert len(check) > 0 except BaseException as E: print('failed on material: {}'.format(mat_key)) print('missing {}: {}\n'.format(key, list(data.keys()))) raise(E) # make sure all required materials are included if required_mat is not None: for r in required_mat: if r not in materials: raise ValueError(f'no data for required material {r}!') # remove any material that isn't doable # for key in list(materials.keys()): # if key not in doable: # materials.pop(key) def generate_basic(processes=None, template=None): """ A very basic helper which will use just a list of supported machines. """ def generate_shopdoc(*args): """ Load a series of file objects to generate a shop document. Data will override previous file objects so that you can provide a base template containing most information and then a sparser one with just shop-specific data. Parameters ------------- *args : file-like object with Excel data Load into a Pandas DataFrame Returns ------------- shopdoc : dict Completed shop document. """ # load excel file and parse all sheets into DataFrame xls = [{n: x.parse(n) for n in x.sheet_names} for x in [pd.ExcelFile( os.path.abspath(os.path.expanduser(a)), engine='openpyxl') for a in args]] return xls
4,193
8,252
72
f39a5008d6e1c8e8868931e246ce18a5152cc852
1,505
py
Python
modules/ConfigEngine.py
Reachip/COVID19-France
e7fde76e0a75b51aed1e67a8d21aa80b0b68050a
[ "MIT" ]
15
2020-04-13T21:58:26.000Z
2020-06-18T07:31:55.000Z
modules/ConfigEngine.py
Reachip/COVID19-France
e7fde76e0a75b51aed1e67a8d21aa80b0b68050a
[ "MIT" ]
3
2020-04-18T16:36:24.000Z
2020-09-11T13:07:41.000Z
modules/ConfigEngine.py
Reachip/COVID19-France
e7fde76e0a75b51aed1e67a8d21aa80b0b68050a
[ "MIT" ]
6
2020-04-13T22:38:14.000Z
2020-09-02T19:07:38.000Z
#!/usr/bin/env python # coding: utf-8 # Twitter: @xrths # www.xrths.fr # Importation des librairies. import os from configparser import ConfigParser
24.274194
67
0.671761
#!/usr/bin/env python # coding: utf-8 # Twitter: @xrths # www.xrths.fr # Importation des librairies. import os from configparser import ConfigParser class BaseConfigEngine: def __init__(self): self._config_file = os.path.join( os.path.dirname(__file__), '../config.ini') self.parser = ConfigParser() self.parser.read(self._config_file) def get_config(self, section, option): return self.parser.get(section, option) def get_config_boolean(self, section, option): return self.parser.getboolean(section, option) class TwitterAPIConfig(BaseConfigEngine): def __init__(self): super().__init__() @property def user_id(self): return self.get_config('TwitterAPI', 'user_id') @property def consumer_key(self): return self.get_config('TwitterAPI', 'consumer_key') @property def consumer_secret(self): return self.get_config('TwitterAPI', 'consumer_secret') @property def access_token(self): return self.get_config('TwitterAPI', 'access_token') @property def access_token_secret(self): return self.get_config('TwitterAPI', 'access_token_secret') @property def app_name(self): return self.get_config('TwitterAPI', 'app_name') @property def preview_id(self): return self.get_config('TwitterAPI', 'preview_id') @property def account_name(self): return self.get_config('TwitterAPI', 'account_name')
850
376
126
1713b6c48a37bc34c443e86aa8c3581c0e08d6f2
977
py
Python
vindauga/types/records/directory_search_record.py
gabbpuy/vindauga
d4a51a618d60e83d82fd5fee585d08ff288484f3
[ "BSD-2-Clause" ]
5
2019-07-03T16:01:46.000Z
2021-12-22T10:01:04.000Z
vindauga/types/records/directory_search_record.py
gabbpuy/vindauga
d4a51a618d60e83d82fd5fee585d08ff288484f3
[ "BSD-2-Clause" ]
null
null
null
vindauga/types/records/directory_search_record.py
gabbpuy/vindauga
d4a51a618d60e83d82fd5fee585d08ff288484f3
[ "BSD-2-Clause" ]
1
2020-09-22T14:25:13.000Z
2020-09-22T14:25:13.000Z
# -*- coding: utf-8 -*- import datetime from functools import total_ordering import os import stat from .search_record import SearchRecord, FA_DIREC, FA_ARCH @total_ordering # Sort, directories first, then files
27.914286
82
0.650972
# -*- coding: utf-8 -*- import datetime from functools import total_ordering import os import stat from .search_record import SearchRecord, FA_DIREC, FA_ARCH @total_ordering class DirectorySearchRecord(SearchRecord): def setStatInfo(self, filename: str, s: os.stat_result): self.attr = FA_ARCH if stat.S_ISDIR(s.st_mode): self.attr |= FA_DIREC self.name = filename self.size = s.st_size self.time = datetime.datetime.fromtimestamp(s.st_mtime) # Sort, directories first, then files def __lt__(self, other): if self.attr & FA_DIREC and not other.attr & FA_DIREC: return True if self.attr == other.attr: return self.name.lower() < other.name.lower() return self.attr < other.attr def __eq__(self, other): return self.attr == other.attr and self.name.lower() == other.name.lower() def __gt__(self, other): return not self.__lt__(other)
606
21
129
e1f35d874d627872d0fd19befdafc861ef9953ce
2,468
py
Python
bin/global_place/RePlAce/rdf_RePlAce.py
DanielTRYTRYLOOK/RDF-2020
a6a6c0835a02c8a98ae8e899dec02ed960afb69c
[ "MIT" ]
3
2020-11-08T17:04:04.000Z
2021-03-28T17:44:12.000Z
bin/global_place/RePlAce/rdf_RePlAce.py
DanielTRYTRYLOOK/RDF-2020
a6a6c0835a02c8a98ae8e899dec02ed960afb69c
[ "MIT" ]
1
2021-11-30T09:12:06.000Z
2021-11-30T09:12:06.000Z
bin/global_place/RePlAce/rdf_RePlAce.py
DanielTRYTRYLOOK/RDF-2020
a6a6c0835a02c8a98ae8e899dec02ed960afb69c
[ "MIT" ]
4
2021-09-01T17:04:22.000Z
2022-02-11T15:20:45.000Z
''' File name : rdf_RePlAce.py Author : Jinwook Jung Created on : Tue 30 Jul 2019 10:31:18 PM EDT Last modified : 2020-01-06 15:22:58 Description : ''' import subprocess, os, sys, random, yaml, time from subprocess import Popen, PIPE, CalledProcessError # FIXME sys.path.insert(0, '../../../src/stage.py') from stage import *
30.469136
79
0.597245
''' File name : rdf_RePlAce.py Author : Jinwook Jung Created on : Tue 30 Jul 2019 10:31:18 PM EDT Last modified : 2020-01-06 15:22:58 Description : ''' import subprocess, os, sys, random, yaml, time from subprocess import Popen, PIPE, CalledProcessError # FIXME sys.path.insert(0, '../../../src/stage.py') from stage import * def run(config, stage_dir, prev_out_dir, user_parms, write_run_scripts=False): print("-"*79) print("Running RePlAce...") print("-"*79) print("Job directory: {}".format(stage_dir)) print("Previous stage outputs: {}".format(prev_out_dir)) replace = RePlAceRunner(config, stage_dir, prev_out_dir, user_parms) replace.write_run_scripts() if not write_run_scripts: replace.run() print("Done.") print("") class RePlAceRunner(Stage): def __init__(self, config, stage_dir, prev_out_dir, user_parms): super().__init__(config, stage_dir, prev_out_dir, user_parms) self.lef_mod = "{}/merged_padded_spacing.lef".format(self.lib_dir) def write_run_scripts(self): cmds = list() cmd = "${RDF_TOOL_BIN_PATH}/global_place/RePlAce/RePlAce" cmd += " -bmflag etc" # cmd += " -lef {}".format(self.lef) cmd += " -lef {}".format(self.lef_mod) cmd += " -def {}".format(self.in_def) cmd += " -den {}".format(float(self.user_parms["target_density"])) cmd += " -onlyGP" cmd += " -output {}".format(self.stage_dir) cmds.append(cmd) cmd = "ln -s {0}/etc/{1}/experiment000/{1}_final.def {0}/out/{1}.def" \ .format(self.stage_dir, self.design_name) cmds.append(cmd) # Copy previous verilog file cmd = "ln -s {0}/{1}.v {2}/out/{1}.v" \ .format(self.prev_out_dir, self.design_name, self.stage_dir) cmds.append(cmd) self.create_run_script_template() with open("{}/run.sh".format(self.stage_dir), 'a') as f: [f.write("{}\n".format(_)) for _ in cmds] def run(self): pass def _copy_final_output(self): cmd = "ln -s {0}/etc/{1}/experiment000/{1}_final.def {0}/out/{1}.def" \ .format(self.stage_dir, self.design_name) run_shell_cmd(cmd) # Copy previous verilog file cmd = "ln -s {0}/{1}.v {2}/out/{1}.v" \ .format(self.prev_out_dir, self.design_name, self.stage_dir) run_shell_cmd(cmd)
1,936
6
153
56927f4042b90cd934bea19ec2c3eee7f5b8c6d6
95
py
Python
backend/ultrabooks/apps.py
smehlhoff/notepark-backend
9719afe335cf2a51bf080e9d157b9e06539c7c8e
[ "Apache-2.0" ]
null
null
null
backend/ultrabooks/apps.py
smehlhoff/notepark-backend
9719afe335cf2a51bf080e9d157b9e06539c7c8e
[ "Apache-2.0" ]
null
null
null
backend/ultrabooks/apps.py
smehlhoff/notepark-backend
9719afe335cf2a51bf080e9d157b9e06539c7c8e
[ "Apache-2.0" ]
null
null
null
from django.apps import AppConfig
15.833333
34
0.768421
from django.apps import AppConfig class UltrabooksConfig(AppConfig): name = 'ultrabooks'
0
37
23
78fff8947e055f7dafb116d7ee57d17cb30b7833
630
py
Python
Curso/ModuloTkinter/Aula029TabelaMySQL3.py
DavidBitner/Aprendizado-Python
e1dcf18f9473c697fc2302f34a2d3e025ca6c969
[ "MIT" ]
null
null
null
Curso/ModuloTkinter/Aula029TabelaMySQL3.py
DavidBitner/Aprendizado-Python
e1dcf18f9473c697fc2302f34a2d3e025ca6c969
[ "MIT" ]
null
null
null
Curso/ModuloTkinter/Aula029TabelaMySQL3.py
DavidBitner/Aprendizado-Python
e1dcf18f9473c697fc2302f34a2d3e025ca6c969
[ "MIT" ]
null
null
null
from tkinter import * import mysql.connector root = Tk() root.title("Doidera") root.geometry("400x400+200+200") my_db = mysql.connector.connect( host="localhost", user="root", passwd="YourPassword", database="doidera" ) # Criar um cursor e inicializa-lo my_cursor = my_db.cursor() # Criar tabela comando_sql = "CREATE TABLE clientes(" \ "first_name VARCHAR(255), " \ "last_name VARCHAR(255), " \ "zipcode INT(10), " \ "price_paid DECIMAL(10, 2), " \ "user_id INT AUTO_INCREMENT PRIMARY KEY)" my_cursor.execute(comando_sql) root.mainloop()
22.5
55
0.626984
from tkinter import * import mysql.connector root = Tk() root.title("Doidera") root.geometry("400x400+200+200") my_db = mysql.connector.connect( host="localhost", user="root", passwd="YourPassword", database="doidera" ) # Criar um cursor e inicializa-lo my_cursor = my_db.cursor() # Criar tabela comando_sql = "CREATE TABLE clientes(" \ "first_name VARCHAR(255), " \ "last_name VARCHAR(255), " \ "zipcode INT(10), " \ "price_paid DECIMAL(10, 2), " \ "user_id INT AUTO_INCREMENT PRIMARY KEY)" my_cursor.execute(comando_sql) root.mainloop()
0
0
0
76ea2159e2f0cceb466e1db9b1d5f9c27090f4c3
497
py
Python
homeassistant/components/gree/config_flow.py
tbarbette/core
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
[ "Apache-2.0" ]
6
2017-08-02T19:26:39.000Z
2020-03-14T22:47:41.000Z
homeassistant/components/gree/config_flow.py
tbarbette/core
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
[ "Apache-2.0" ]
60
2020-08-03T07:32:56.000Z
2022-03-31T06:02:07.000Z
homeassistant/components/gree/config_flow.py
tbarbette/core
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
[ "Apache-2.0" ]
14
2018-08-19T16:28:26.000Z
2021-09-02T18:26:53.000Z
"""Config flow for Gree.""" from homeassistant import config_entries from homeassistant.helpers import config_entry_flow from .bridge import DeviceHelper from .const import DOMAIN async def _async_has_devices(hass) -> bool: """Return if there are devices that can be discovered.""" devices = await DeviceHelper.find_devices() return len(devices) > 0 config_entry_flow.register_discovery_flow( DOMAIN, "Gree Climate", _async_has_devices, config_entries.CONN_CLASS_LOCAL_POLL )
27.611111
84
0.782696
"""Config flow for Gree.""" from homeassistant import config_entries from homeassistant.helpers import config_entry_flow from .bridge import DeviceHelper from .const import DOMAIN async def _async_has_devices(hass) -> bool: """Return if there are devices that can be discovered.""" devices = await DeviceHelper.find_devices() return len(devices) > 0 config_entry_flow.register_discovery_flow( DOMAIN, "Gree Climate", _async_has_devices, config_entries.CONN_CLASS_LOCAL_POLL )
0
0
0
3ec228f8c259854c27539bf995921a7f2873fca4
724
py
Python
tests/test_main.py
Asday/django-persistent-app-conf
6b8c45c10c78f1ac4066f323f5b0b3ed574e6e93
[ "MIT" ]
null
null
null
tests/test_main.py
Asday/django-persistent-app-conf
6b8c45c10c78f1ac4066f323f5b0b3ed574e6e93
[ "MIT" ]
null
null
null
tests/test_main.py
Asday/django-persistent-app-conf
6b8c45c10c78f1ac4066f323f5b0b3ed574e6e93
[ "MIT" ]
null
null
null
import os import sys import django import pytest import pac # noqa from .helpers import sanity @sanity @sanity
21.294118
74
0.696133
import os import sys import django import pytest import pac # noqa from .helpers import sanity @sanity def test_environment_matches_expectations(): current_env = os.getenv('CURRENTENV', None) assert current_env is not None, '"CURRENTENV" not set by test runner.' expected_django_version = current_env.split('-')[1] if expected_django_version == 'master': pytest.skip('Not testing for Django version on `master`') django_major_version = '.'.join(django.get_version().split('.')[:2]) assert current_env == ( f'py{sys.version_info.major}{sys.version_info.minor}-' f'{django_major_version}' ) @sanity def test_django_runs(client): client.get('/spurious-url')
560
0
44
9e328819b51d43963aa70159e6f94602d4f6590f
127
py
Python
PIARS/run.py
qingyang-xi/piars
193e33f3b01b1c0bfcea58faefb4605ef84539ce
[ "MIT" ]
null
null
null
PIARS/run.py
qingyang-xi/piars
193e33f3b01b1c0bfcea58faefb4605ef84539ce
[ "MIT" ]
null
null
null
PIARS/run.py
qingyang-xi/piars
193e33f3b01b1c0bfcea58faefb4605ef84539ce
[ "MIT" ]
null
null
null
import math import matplotlib.pyplot as plt print("Hello World!") x = math.sqrt(30) print(x) plt.plot([1,2,3,4,5]) plt.show()
14.111111
31
0.692913
import math import matplotlib.pyplot as plt print("Hello World!") x = math.sqrt(30) print(x) plt.plot([1,2,3,4,5]) plt.show()
0
0
0
6a1c48cbadafe36a82365fc76d25d0196ec2ece7
1,601
py
Python
applications/migrations/0006_add_berth_switch.py
City-of-Helsinki/berth-reservations
a3b1a8c2176f132505527acdf6da3a62199401db
[ "MIT" ]
3
2020-10-13T07:58:48.000Z
2020-12-22T09:41:50.000Z
applications/migrations/0006_add_berth_switch.py
City-of-Helsinki/berth-reservations
a3b1a8c2176f132505527acdf6da3a62199401db
[ "MIT" ]
422
2018-10-25T10:57:05.000Z
2022-03-30T05:47:14.000Z
applications/migrations/0006_add_berth_switch.py
City-of-Helsinki/berth-reservations
a3b1a8c2176f132505527acdf6da3a62199401db
[ "MIT" ]
1
2020-04-03T07:38:03.000Z
2020-04-03T07:38:03.000Z
# Generated by Django 2.1.2 on 2019-04-08 11:55 from django.db import migrations, models import django.db.models.deletion
29.109091
85
0.425984
# Generated by Django 2.1.2 on 2019-04-08 11:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("applications", "0005_add_custom_permissions"), ] operations = [ migrations.CreateModel( name="BerthSwitch", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "pier", models.CharField(blank=True, max_length=40, verbose_name="pier"), ), ( "berth_number", models.CharField(max_length=20, verbose_name="berth number"), ), ( "harbor", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="resources.Harbor", ), ), ], ), migrations.AddField( model_name="reservation", name="berth_switch", field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to="applications.BerthSwitch", verbose_name="berth switch", ), ), ]
0
1,454
23
8c54298f976882469a2f9fc037cf3b36c35bb161
1,566
py
Python
trainer_for_failure_classes.py
birlrobotics/rcbht_training_and_online_classification
4ba605420fd9ab65e9e8173673a6e16f7dcb15df
[ "BSD-3-Clause" ]
null
null
null
trainer_for_failure_classes.py
birlrobotics/rcbht_training_and_online_classification
4ba605420fd9ab65e9e8173673a6e16f7dcb15df
[ "BSD-3-Clause" ]
null
null
null
trainer_for_failure_classes.py
birlrobotics/rcbht_training_and_online_classification
4ba605420fd9ab65e9e8173673a6e16f7dcb15df
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python import numpy as np from matplotlib import pyplot as plt from scipy.interpolate import spline import os from config import failure_class_name_to_id data_type = "SIM" filepath = "/Users/sklaw_mba/Desktop/ex/dr_juan_proj/workshop/data_cooker_code/parse_rcbht_data/my_training_data/"+data_type+"_HIRO_ONE_SA_ERROR_CHARAC_prob" failure_class = failure_class_name_to_id.keys() all_mat = {} for fc in failure_class: file_name = "training_set_of_failure_class_"+fc try: mat = np.genfromtxt(os.path.join(filepath, file_name), dtype='string', delimiter=',') except IOError: print "no data for class", fc continue #a half for training, a half for test if len(mat.shape) == 1: mat = mat.reshape((1, mat.shape[0])) #shuffle all these trails before collecting them all_mat[fc] = mat if __name__ == "__main__": from optparse import OptionParser usage = "usage: %prog -m METHOD" parser = OptionParser(usage=usage) parser.add_option("-m", "--method", action="store", type="string", dest="method", help="training method, svm or logistic or gaussiannb") (options, args) = parser.parse_args() if options.method is None: parser.error("you have to provide a method in -m or --method") from trainer_common import CommonTrainer ct = CommonTrainer(all_mat, "data_type_"+data_type+"_model_for_failure_class_", options.method) while True: ct.run_one_training()
27
158
0.673691
#!/usr/bin/env python import numpy as np from matplotlib import pyplot as plt from scipy.interpolate import spline import os from config import failure_class_name_to_id data_type = "SIM" filepath = "/Users/sklaw_mba/Desktop/ex/dr_juan_proj/workshop/data_cooker_code/parse_rcbht_data/my_training_data/"+data_type+"_HIRO_ONE_SA_ERROR_CHARAC_prob" failure_class = failure_class_name_to_id.keys() all_mat = {} for fc in failure_class: file_name = "training_set_of_failure_class_"+fc try: mat = np.genfromtxt(os.path.join(filepath, file_name), dtype='string', delimiter=',') except IOError: print "no data for class", fc continue #a half for training, a half for test if len(mat.shape) == 1: mat = mat.reshape((1, mat.shape[0])) #shuffle all these trails before collecting them all_mat[fc] = mat if __name__ == "__main__": from optparse import OptionParser usage = "usage: %prog -m METHOD" parser = OptionParser(usage=usage) parser.add_option("-m", "--method", action="store", type="string", dest="method", help="training method, svm or logistic or gaussiannb") (options, args) = parser.parse_args() if options.method is None: parser.error("you have to provide a method in -m or --method") from trainer_common import CommonTrainer ct = CommonTrainer(all_mat, "data_type_"+data_type+"_model_for_failure_class_", options.method) while True: ct.run_one_training()
0
0
0
b1d071a81d9c5e740d93c53b301f287d816f0bf2
3,808
py
Python
common/preprocess.py
estephe-arnaud/ademfa
679587b09eb86d2956c73aec100d764ef7fc005c
[ "BSD-3-Clause" ]
2
2021-01-15T22:08:41.000Z
2022-01-18T14:19:43.000Z
common/preprocess.py
estephe-arnaud/ademfa
679587b09eb86d2956c73aec100d764ef7fc005c
[ "BSD-3-Clause" ]
null
null
null
common/preprocess.py
estephe-arnaud/ademfa
679587b09eb86d2956c73aec100d764ef7fc005c
[ "BSD-3-Clause" ]
1
2020-12-30T08:22:19.000Z
2020-12-30T08:22:19.000Z
"""Preprocess.""" import numpy as np import menpo from menpofit.fitter import align_shape_with_bounding_box from menpodetect.opencv import detect import common.utils import face_alignment.utils __DETECTOR__ = detect.load_opencv_frontal_face_detector() class Preprocess(object): """Preprocess."""
24.101266
77
0.621324
"""Preprocess.""" import numpy as np import menpo from menpofit.fitter import align_shape_with_bounding_box from menpodetect.opencv import detect import common.utils import face_alignment.utils __DETECTOR__ = detect.load_opencv_frontal_face_detector() class Preprocess(object): """Preprocess.""" def __init__(self, params, detection=False, **inputs): self.params = params self.inputs = inputs self.detection = detection self.__output_keys = sorted(params.dataset.keys()) self.transformation = [] def get_transformation(self): t = self.transformation[0] for t_ in self.transformation[1:]: t = t.compose_after(t_) return t def get_image(self): image = self.inputs["image"] if type(image) == np.ndarray: pixels = np.transpose(image, (2, 0, 1)) else: pixels = image.pixels if np.max(pixels) > 1: pixels = pixels / 255. pixels = np.float32(pixels) self.im = menpo.image.Image(pixels) def get_face(self): if "pts_2d" in self.inputs.keys(): pts_2d = self.inputs["pts_2d"].reshape((-1, 2)) pts_2d = menpo.shape.pointcloud.PointCloud(pts_2d) self.im.landmarks["pts_2d"] = pts_2d else: h, w = self.im.shape pts_2d = np.array([ [0, 0], [h, 0], [h, w], [0, w] ]) pts_2d = menpo.shape.pointcloud.PointCloud(pts_2d) if self.detection: try: pts_2d = __DETECTOR__(self.im)[0] except IndexError: pass self.im.landmarks["bbox"] = pts_2d.bounding_box() def get_initial_pts(self): reference_shape = face_alignment.utils.REFERENCE_SHAPE reference_shape = menpo.shape.pointcloud.PointCloud(reference_shape) self.im.landmarks["pts_initial"] = align_shape_with_bounding_box( reference_shape, self.im.landmarks["bbox"] ) def crop(self, p=0.): pointcloud = self.im.landmarks["bbox"] boundary = p * np.min(pointcloud.range()) (y_min, x_min), (y_max, x_max) = pointcloud.bounds(boundary=boundary) self.im.landmarks["bbox"] = menpo.shape.pointcloud.PointCloud(np.array([ [y_min, x_min], [y_max, x_min], [y_max, x_max], [y_min, x_max] ])).bounding_box() self.im, t = self.im.crop_to_landmarks( group="bbox", return_transform=True ) self.transformation.append(t) def resize(self): width, height, n_channels = self.params.dataset["image"].shape self.im, t = self.im.resize([width, height], return_transform=True) self.transformation.append(t) if n_channels == 1: try: self.im = self.im.as_greyscale() except: assert self.im.n_channels == 1 elif n_channels == 3: self.im = common.utils.to_rgb(self.im) def tfslim_preprocess(self): assert np.max(self.im.pixels) <= 1. assert np.min(self.im.pixels) >= 0. self.im.pixels -= 0.5 self.im.pixels *= 2. def make_pipeline(self, detection=False): output = dict() pipelines = self() if not isinstance(pipelines[0], list): pipelines = [pipelines] for pipeline in pipelines: for operation in pipeline: operation() for key in self.__output_keys: shape = self.params.dataset[key].shape dtype = self.params.dataset[key].dtype try: output[key] = self.inputs[key] except KeyError: output[key] = np.zeros(shape, dtype=dtype) try: if "image" in key: output[key] = self.im.pixels.transpose((1, 2, 0)) elif "pts" in key: output[key] = self.im.landmarks[key].points except KeyError: output[key] = np.zeros(shape, dtype=dtype) output[key] = output[key].astype(dtype) return output
3,260
0
233
3eae3efcfc3ddd24c3fb342dbde213ab0a08eaf8
12,978
py
Python
pyimagesource/bank.py
Fhrozen/pyimagesource
0bd3c8de484694877ea1d152448b7bc0b31b279a
[ "Apache-2.0" ]
6
2020-06-27T09:55:46.000Z
2022-03-28T01:01:37.000Z
pyimagesource/bank.py
Fhrozen/ism_rir
0bd3c8de484694877ea1d152448b7bc0b31b279a
[ "Apache-2.0" ]
null
null
null
pyimagesource/bank.py
Fhrozen/ism_rir
0bd3c8de484694877ea1d152448b7bc0b31b279a
[ "Apache-2.0" ]
1
2019-12-05T08:22:31.000Z
2019-12-05T08:22:31.000Z
# Copyright 2018 Waseda University (Nelson Yalta) # 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 pyimagesource.abscoeff import AbsCoeff from pyimagesource.room_resp import ISM_RoomResp import logging import numpy as np class Room_Impulse_Response(object): """Environmental parameters for image-source method simulation Room_Impulse_Response(args) This function can be used as a template for the definition of the different parameters for an image-source method simulation, typically providing inputs to the functions 'ISM_RIR_bank.m' as well as 'fast_ISM_RIR_bank.m' (Lehmann & Johansson's ISM implementations). This function returns the structure 'SetupStruc' with the following fields: sampling_freq: sampling frequency in Hz. room: 1-by-3 array of enclosure dimensions (in m), [x_length y_length z_length]. mic_pos: N-by-3 matrix, [x1 y1 z1; x2 y2 z2; ...] positions of N microphones in the environment (in m). source_trajectory: M-by-3 matrix, [x1 y1 z1; x2 y2 z2; ...] positions of M source trajectory points in the environment (in m). reverberation: list of two scalar values [a, b] where a is the reverberation type (60 or 20) and b is the desired reverberation time (in s). c: (optional) sound velocity (in m/s). abs_weights: (optional) 1-by-6 vector of absorption coefficients weights, [w_x1 w_x2 w_y1 w_y2 w_z1 w_z2]. method: Type of Algorithm for reverberation. verbose: Verbosity control processes: number of subprocess to calculate the impulses. The structure field 'c' is optional in the sense that the various functions developed in relation to Lehmann & Johansson's ISM implementation assume a sound velocity of 343 m/s by default. If defined in the function below, the field 'SetupStruc.c' will take precedence and override the default value with another setting. The field 'abs_weight' corresponds to the relative weights of each of the six absorption coefficients resulting from the desired reverberation time T60. For instance, defining 'abs_weights' as [0.8 0.8 1 1 0.6 0.6] will result in the absorption coefficients (alpha) for the walls in the x-dimension being 20% smaller compared to the y-dimension walls, whereas the floor and ceiling will end up with absorption coefficients 40% smaller (e.g., to simulate the effects of a concrete floor and ceiling). Note that setting some of the 'abs_weight' parameters to 1 does NOT mean that the corresponding walls will end up with a total absorption! If the field 'abs_weight' is omitted, the various functions developed in relation to Lehmann & Johansson's ISM implementation will set the 'abs_weight' parameter to [1 1 1 1 1 1], which will lead to uniform absorption coefficients for all room boundaries. The reverberation list may contain one of the two fields '60' or '20'. 60 corresponds to the time required by the impulse response to decay by 60dB, whereas 20 is defined as the time required for the impulse response to decay from -5 to -25dB. Simply define either one of these fields in the file below. Set this value to 0 for anechoic environments (direct path only). """ def bank(self, Delta_dB=50.0): """Function [RIR_cell] = ISM_RIR_bank(setupstruc,RIRFileName,varargin) ISM_RIR_bank Bank of RIRs using Lehmann & Johansson's image-source method [RIR_CELL] = ISM_RIR_bank(SETUP_STRUC,RIR_FILE_NAME) This function generates a bank of room impulse responses (RIRs) for a particular user-defined room setup, using Lehmann and Johansson's implementation of the image-source method (see: "Prediction of energy decay in room impulse responses simulated with an image-source model", J. Acoust. Soc. Am., vol. 124(1), pp. 269-277, July 2008). The input SETUP_STRUC is a structure of enviromental parameters containing the following fields: Fs: sampling frequency (in Hz). room: 1-by-3 vector of enclosure dimensions (in m), [x_length y_length z_length]. mic_pos: N-by-3 matrix, [x1 y1 z1; x2 y2 z2; ...] positions of N microphones (in m). src_traj: M-by-3 matrix, [x1 y1 z1; x2 y2 z2; ...] positions of M source trajectory points (in m). reverberation (T20 or T60): scalar value (in s), desired reverberation time. c: (optional) sound velocity (in m/s). abs_weights: (optional) 1-by-6 vector of absorption coefficients weights, [w_x1 w_x2 w_y1 w_y2 w_z1 w_z2]. If the field SETUP_STRUC.c is undefined, the function assumes a default value of sound velocity of 343 m/s. The field 'abs_weight' corresponds to the relative weights of each of the six absorption coefficients resulting from the desired reverberation time. For instance, defining 'abs_weights' as [1 1 0.8 0.8 0.6 0.6] will result in the absorption coefficients (alpha) for the walls in the y-dimension being 20% smaller compared to the x-dimension walls, whereas the floor and ceiling will end up with absorption coefficients 40% smaller (e.g., to simulate the effects of a concrete floor and ceiling). If this field is omitted, the parameter 'abs_weight' will default to [1 1 1 1 1 1], which leads to uniform absorption coefficients for all room boundaries. The structure SETUP_STRUC may contain one of the two fields 'T60' or 'T20'. This function will automatically determine which reverberation type is used and compute the desired room absorption coefficients accordingly. T20 is defined as the time required for the impulse response energy to decay from -5 to -25dB, whereas T60 corresponds to the time required by the impulse response energy to decay by 60dB. Setting the corresponding field value to 0 achieves anechoic impulse responses (direct path only). In addition, a number of other (optional) parameters can be set using a series of 'argument'--value pairs. The following parameters (arguments) can be used: 'Delta_dB': scalar (in dB), parameter determining how much the resulting impulse response is cropped: the impulse response is computed until the time index where its overall energy content has decreased by 'Delta_dB' decibels, after which the computations stop. Not relevant if the reverberation time is set to 0 (anechoic case). Defaults to 50. This function returns a 2-dimensional cell array RIR_CELL containing the RIRs for each source trajectory point and each microphone, organised as follows: RIR_CELL{mic_index,traj_index}. The resulting filter length may differ slightly in each computed RIR. This function also saves the computation results on file. The argument RIR_FILE_NAME determines the name of the .mat file where the variable RIR_CELL is to be saved. If a file already exists with the same name as the input argument, the user will be prompted to determine whether the file is to be overwritten or not. The given parameter RIR_FILE_NAME can be a full access path to the desired file. If no access path is given, the file is saved in the current working directory. """ if self.abs_weights is None: self.abs_weights = np.ones((1, 6)) elif self.abs_weights.shape[1] != 6: logging.warning('The given weights is not an array of 6, the values will be set to 1') self.abs_weights = np.ones((1, 6)) if self.c is None: self.c = 343.0 if self.reverberation[0] == 60: alpha = AbsCoeff('t60', self.reverberation[1], self.room, self.abs_weights, self.method, self.c) elif self.reverberation[0] == 20: alpha = AbsCoeff('t20', self.reverberation[1], self.room, self.abs_weights, self.method, self.c) else: raise ValueError('Missing T60 or T20 field.') rttype = self.reverberation[0] rtval = self.reverberation[1] beta = np.sqrt(1 - alpha) nMics = self.mic_pos.shape[0] # number of microphones nSPts = self.source_trajectory.shape[0] # number of source trajectory points # -=:=- Compute RIR bank -=:=- RIR_cell = np.empty((nMics, nSPts), dtype=object) # pre-allocate cell array logging.info('Computing room impulse responses. ') mics_range = range(nMics) if self.processes > 1: from pathos.multiprocessing import ProcessingPool as Pool this_map = Pool(node=self.processes).map X_src = (self.mic_pos[mm, :] for mm in mics_range for tt in range(nSPts)) X_rcv = (self.source_trajectory[tt, :] for mm in mics_range for tt in range(nSPts)) m_freq = (self.sampling_freq for mm in mics_range for tt in range(nSPts)) m_beta = (beta for mm in mics_range for tt in range(nSPts)) m_rttype = (rttype for mm in mics_range for tt in range(nSPts)) m_rtval = (rtval for mm in mics_range for tt in range(nSPts)) m_room = (self.room for mm in mics_range for tt in range(nSPts)) m_c = (self.c for mm in mics_range for tt in range(nSPts)) m_Delta_dB = (Delta_dB for mm in mics_range for tt in range(nSPts)) imps = this_map(ISM_RoomResp, m_freq, m_beta, m_rttype, m_rtval, X_src, X_rcv, m_room, m_c, m_Delta_dB) for mm in mics_range: for tt in range(nSPts): RIR_cell[mm, tt] = imps[mm * nSPts + tt] logging.info('Room impulse responses completed. ') else: if self.verbose: from tqdm import tqdm mics_range = tqdm(mics_range) for mm in mics_range: X_rcv = self.mic_pos[mm, :] # compute ISM room impulse response for each source-receiver combinations for tt in range(nSPts): X_src = self.source_trajectory[tt, :] RIR_cell[mm, tt] = ISM_RoomResp(self.sampling_freq, beta, rttype, rtval, X_src, X_rcv, self.room, self.c, Delta_dB) self.RIR_cell = RIR_cell return RIR_cell
52.330645
108
0.642164
# Copyright 2018 Waseda University (Nelson Yalta) # 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 pyimagesource.abscoeff import AbsCoeff from pyimagesource.room_resp import ISM_RoomResp import logging import numpy as np def audiodata(rirs, data): # Data should be 1-D # Reverberation for 1 source only dims = rirs.shape[0] length = data.shape[0] outdata = np.zeros((dims, length)) for i in range(dims): outdata[i] = np.convolve(data, rirs[i, 0], mode='full')[:length] return outdata class Room_Impulse_Response(object): """Environmental parameters for image-source method simulation Room_Impulse_Response(args) This function can be used as a template for the definition of the different parameters for an image-source method simulation, typically providing inputs to the functions 'ISM_RIR_bank.m' as well as 'fast_ISM_RIR_bank.m' (Lehmann & Johansson's ISM implementations). This function returns the structure 'SetupStruc' with the following fields: sampling_freq: sampling frequency in Hz. room: 1-by-3 array of enclosure dimensions (in m), [x_length y_length z_length]. mic_pos: N-by-3 matrix, [x1 y1 z1; x2 y2 z2; ...] positions of N microphones in the environment (in m). source_trajectory: M-by-3 matrix, [x1 y1 z1; x2 y2 z2; ...] positions of M source trajectory points in the environment (in m). reverberation: list of two scalar values [a, b] where a is the reverberation type (60 or 20) and b is the desired reverberation time (in s). c: (optional) sound velocity (in m/s). abs_weights: (optional) 1-by-6 vector of absorption coefficients weights, [w_x1 w_x2 w_y1 w_y2 w_z1 w_z2]. method: Type of Algorithm for reverberation. verbose: Verbosity control processes: number of subprocess to calculate the impulses. The structure field 'c' is optional in the sense that the various functions developed in relation to Lehmann & Johansson's ISM implementation assume a sound velocity of 343 m/s by default. If defined in the function below, the field 'SetupStruc.c' will take precedence and override the default value with another setting. The field 'abs_weight' corresponds to the relative weights of each of the six absorption coefficients resulting from the desired reverberation time T60. For instance, defining 'abs_weights' as [0.8 0.8 1 1 0.6 0.6] will result in the absorption coefficients (alpha) for the walls in the x-dimension being 20% smaller compared to the y-dimension walls, whereas the floor and ceiling will end up with absorption coefficients 40% smaller (e.g., to simulate the effects of a concrete floor and ceiling). Note that setting some of the 'abs_weight' parameters to 1 does NOT mean that the corresponding walls will end up with a total absorption! If the field 'abs_weight' is omitted, the various functions developed in relation to Lehmann & Johansson's ISM implementation will set the 'abs_weight' parameter to [1 1 1 1 1 1], which will lead to uniform absorption coefficients for all room boundaries. The reverberation list may contain one of the two fields '60' or '20'. 60 corresponds to the time required by the impulse response to decay by 60dB, whereas 20 is defined as the time required for the impulse response to decay from -5 to -25dB. Simply define either one of these fields in the file below. Set this value to 0 for anechoic environments (direct path only). """ def __init__(self, sampling_freq, room, mic_pos, source_trajectory, reverberation, abs_weights=None, c=None, method='LehmannJohansson', verbose=False, processes=1): super(Room_Impulse_Response, self).__init__() self.sampling_freq = sampling_freq self.room = room self.mic_pos = mic_pos self.source_trajectory = source_trajectory self.reverberation = reverberation self.abs_weights = abs_weights self.c = c self.method = method self.verbose = verbose if processes < 1: raise ValueError('The number of processes should be equal or greater than 1') self.processes = processes if verbose: logging.basicConfig( level=logging.INFO, format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s') else: logging.basicConfig( level=logging.WARN, format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s') logging.warning('Skip DEBUG/INFO messages') def bank(self, Delta_dB=50.0): """Function [RIR_cell] = ISM_RIR_bank(setupstruc,RIRFileName,varargin) ISM_RIR_bank Bank of RIRs using Lehmann & Johansson's image-source method [RIR_CELL] = ISM_RIR_bank(SETUP_STRUC,RIR_FILE_NAME) This function generates a bank of room impulse responses (RIRs) for a particular user-defined room setup, using Lehmann and Johansson's implementation of the image-source method (see: "Prediction of energy decay in room impulse responses simulated with an image-source model", J. Acoust. Soc. Am., vol. 124(1), pp. 269-277, July 2008). The input SETUP_STRUC is a structure of enviromental parameters containing the following fields: Fs: sampling frequency (in Hz). room: 1-by-3 vector of enclosure dimensions (in m), [x_length y_length z_length]. mic_pos: N-by-3 matrix, [x1 y1 z1; x2 y2 z2; ...] positions of N microphones (in m). src_traj: M-by-3 matrix, [x1 y1 z1; x2 y2 z2; ...] positions of M source trajectory points (in m). reverberation (T20 or T60): scalar value (in s), desired reverberation time. c: (optional) sound velocity (in m/s). abs_weights: (optional) 1-by-6 vector of absorption coefficients weights, [w_x1 w_x2 w_y1 w_y2 w_z1 w_z2]. If the field SETUP_STRUC.c is undefined, the function assumes a default value of sound velocity of 343 m/s. The field 'abs_weight' corresponds to the relative weights of each of the six absorption coefficients resulting from the desired reverberation time. For instance, defining 'abs_weights' as [1 1 0.8 0.8 0.6 0.6] will result in the absorption coefficients (alpha) for the walls in the y-dimension being 20% smaller compared to the x-dimension walls, whereas the floor and ceiling will end up with absorption coefficients 40% smaller (e.g., to simulate the effects of a concrete floor and ceiling). If this field is omitted, the parameter 'abs_weight' will default to [1 1 1 1 1 1], which leads to uniform absorption coefficients for all room boundaries. The structure SETUP_STRUC may contain one of the two fields 'T60' or 'T20'. This function will automatically determine which reverberation type is used and compute the desired room absorption coefficients accordingly. T20 is defined as the time required for the impulse response energy to decay from -5 to -25dB, whereas T60 corresponds to the time required by the impulse response energy to decay by 60dB. Setting the corresponding field value to 0 achieves anechoic impulse responses (direct path only). In addition, a number of other (optional) parameters can be set using a series of 'argument'--value pairs. The following parameters (arguments) can be used: 'Delta_dB': scalar (in dB), parameter determining how much the resulting impulse response is cropped: the impulse response is computed until the time index where its overall energy content has decreased by 'Delta_dB' decibels, after which the computations stop. Not relevant if the reverberation time is set to 0 (anechoic case). Defaults to 50. This function returns a 2-dimensional cell array RIR_CELL containing the RIRs for each source trajectory point and each microphone, organised as follows: RIR_CELL{mic_index,traj_index}. The resulting filter length may differ slightly in each computed RIR. This function also saves the computation results on file. The argument RIR_FILE_NAME determines the name of the .mat file where the variable RIR_CELL is to be saved. If a file already exists with the same name as the input argument, the user will be prompted to determine whether the file is to be overwritten or not. The given parameter RIR_FILE_NAME can be a full access path to the desired file. If no access path is given, the file is saved in the current working directory. """ if self.abs_weights is None: self.abs_weights = np.ones((1, 6)) elif self.abs_weights.shape[1] != 6: logging.warning('The given weights is not an array of 6, the values will be set to 1') self.abs_weights = np.ones((1, 6)) if self.c is None: self.c = 343.0 if self.reverberation[0] == 60: alpha = AbsCoeff('t60', self.reverberation[1], self.room, self.abs_weights, self.method, self.c) elif self.reverberation[0] == 20: alpha = AbsCoeff('t20', self.reverberation[1], self.room, self.abs_weights, self.method, self.c) else: raise ValueError('Missing T60 or T20 field.') rttype = self.reverberation[0] rtval = self.reverberation[1] beta = np.sqrt(1 - alpha) nMics = self.mic_pos.shape[0] # number of microphones nSPts = self.source_trajectory.shape[0] # number of source trajectory points # -=:=- Compute RIR bank -=:=- RIR_cell = np.empty((nMics, nSPts), dtype=object) # pre-allocate cell array logging.info('Computing room impulse responses. ') mics_range = range(nMics) if self.processes > 1: from pathos.multiprocessing import ProcessingPool as Pool this_map = Pool(node=self.processes).map X_src = (self.mic_pos[mm, :] for mm in mics_range for tt in range(nSPts)) X_rcv = (self.source_trajectory[tt, :] for mm in mics_range for tt in range(nSPts)) m_freq = (self.sampling_freq for mm in mics_range for tt in range(nSPts)) m_beta = (beta for mm in mics_range for tt in range(nSPts)) m_rttype = (rttype for mm in mics_range for tt in range(nSPts)) m_rtval = (rtval for mm in mics_range for tt in range(nSPts)) m_room = (self.room for mm in mics_range for tt in range(nSPts)) m_c = (self.c for mm in mics_range for tt in range(nSPts)) m_Delta_dB = (Delta_dB for mm in mics_range for tt in range(nSPts)) imps = this_map(ISM_RoomResp, m_freq, m_beta, m_rttype, m_rtval, X_src, X_rcv, m_room, m_c, m_Delta_dB) for mm in mics_range: for tt in range(nSPts): RIR_cell[mm, tt] = imps[mm * nSPts + tt] logging.info('Room impulse responses completed. ') else: if self.verbose: from tqdm import tqdm mics_range = tqdm(mics_range) for mm in mics_range: X_rcv = self.mic_pos[mm, :] # compute ISM room impulse response for each source-receiver combinations for tt in range(nSPts): X_src = self.source_trajectory[tt, :] RIR_cell[mm, tt] = ISM_RoomResp(self.sampling_freq, beta, rttype, rtval, X_src, X_rcv, self.room, self.c, Delta_dB) self.RIR_cell = RIR_cell return RIR_cell
1,344
0
50
5706a511320dad5fa027e14356e1f5a28e743c19
2,895
py
Python
nnn/nodes/info_node/functions.py
JacobFV/pgi
b4c9af3c4ae94fcb335f20c2a1e7a4ff46ca54e6
[ "MIT" ]
null
null
null
nnn/nodes/info_node/functions.py
JacobFV/pgi
b4c9af3c4ae94fcb335f20c2a1e7a4ff46ca54e6
[ "MIT" ]
null
null
null
nnn/nodes/info_node/functions.py
JacobFV/pgi
b4c9af3c4ae94fcb335f20c2a1e7a4ff46ca54e6
[ "MIT" ]
null
null
null
from typing import Optional, Text, List, Mapping, Callable, Tuple, Union, Counter import tensorflow as tf import tensorflow_probability.python.distributions as tfd from ...utils import types as ts from ...utils import keys def f_child_sample_factory(beta: ts.Float = 0): """ Args: beta: softmax temperature. Higher means more random Returns: function `f_child_sample` """ return f_child_sample
40.774648
108
0.727807
from typing import Optional, Text, List, Mapping, Callable, Tuple, Union, Counter import tensorflow as tf import tensorflow_probability.python.distributions as tfd from ...utils import types as ts from ...utils import keys def f_parent_no_parents(states: ts.NestedTensor, parent_names: List[Text]): return def f_parent_sample(states: ts.NestedTensor, parent_names: List[Text]): # select parent to pool data from by energy weighted bottom-up attention parent_energies = [states[name][keys.STATES.ENERGY] for name in parent_names] parent_dist = tfd.OneHotCategorical(logits=parent_energies) parent_name = parent_names[tf.argmax(parent_dist.sample())] parent_energy = states[parent_name][keys.STATES.ENERGY] parent_latent = states[parent_name][keys.STATES.LATENT] return parent_energy, parent_latent def f_parent_concat(states: ts.NestedTensor, parent_names: List[Text]) -> Tuple[tf.Tensor, ts.NestedTensor]: energies = ([states[name][keys.STATES.ENERGY] for name in parent_names]) mean_energy = sum(energies) / len(energies) concat_latent = tf.nest.map_structure(lambda tensors: tf.concat(tensors, axis=1), [states[name][keys.STATES.LATENT] for name in parent_names]) return mean_energy, concat_latent def f_parent_dict(states: ts.NestedTensor, parent_names: List[Text]) -> Tuple[tf.Tensor, ts.NestedTensor]: energies = [states[name][keys.STATES.ENERGY] for name in parent_names] mean_energy = sum(energies) / len(energies) latents_dict = {name: states[name][keys.STATES.LATENT] for name in parent_names} return mean_energy, latents_dict def f_parent_fixed_index_factory(index: int): def _f_parent_fixed_index(states: ts.NestedTensor, parent_names: List[Text]): parent_state = states[parent_names[index]] return parent_state[keys.STATES.ENERGY], parent_state[keys.STATES.LATENT] return _f_parent_fixed_index def f_parent_single_parent(states: ts.NestedTensor, parent_names: List[Text]): parent_state = states[parent_names[0]] return parent_state[keys.STATES.ENERGY], parent_state[keys.STATES.LATENT] def f_child_no_children(targets: List[Tuple[tf.Tensor, ts.NestedTensor]]) -> ts.NestedTensor: return None def f_child_sample_factory(beta: ts.Float = 0): """ Args: beta: softmax temperature. Higher means more random Returns: function `f_child_sample` """ def f_child_sample(targets: List[Tuple[tf.Tensor, ts.NestedTensor]]) -> ts.NestedTensor: # select bias for top_down attention dist = tfd.OneHotCategorical(logits=[beta-energy for energy, latent in targets]) sample = dist.sample() ind = tf.argmax(sample) energy, latent = targets[ind] energy = energy + dist.entropy() + -dist.log_prob(sample) return energy, latent return f_child_sample
2,267
0
187
b7ef8b7db02557bd5008a14e944bd388c750285b
5,371
py
Python
crossdock/problems/experiment/crossdock_30_50_15_10_10.py
krerkkiat/icpr-2019-public
f3023c009f3335ce58204a45c270cfeb6ef19367
[ "BSD-3-Clause" ]
null
null
null
crossdock/problems/experiment/crossdock_30_50_15_10_10.py
krerkkiat/icpr-2019-public
f3023c009f3335ce58204a45c270cfeb6ef19367
[ "BSD-3-Clause" ]
null
null
null
crossdock/problems/experiment/crossdock_30_50_15_10_10.py
krerkkiat/icpr-2019-public
f3023c009f3335ce58204a45c270cfeb6ef19367
[ "BSD-3-Clause" ]
null
null
null
""" Cross-docking truck data. This data is generated by a generate_dataset.py script. Created: Feb 18, 2019 at 07:30:02 PM Copyright (c) 2022, Krerkkiat Chusap This souce code is licensed under BSD 3-Clause "New" or "Revised" License (see LICENSE for details). """ from pathlib import Path # Problem data. name = Path(__file__).stem inbound_gate_count = 10 outbound_gate_count = 10 # Parameters used to generate this data. number_of_total_product_types = 15 product_per_truck_rate = 0.35 possible_inbound_total_product = [250, 340] # Truck data. _inbound_truck_raw_data = [ [0, 55, 0, 0, 0, 0, 89, 0, 2, 0, 0, 70, 111, 0, 13], [50, 0, 0, 0, 0, 115, 0, 0, 0, 0, 58, 0, 27, 0, 0], [23, 0, 40, 23, 0, 41, 0, 0, 100, 0, 0, 0, 0, 113, 0], [0, 0, 78, 0, 0, 71, 0, 0, 49, 21, 29, 0, 0, 92, 0], [0, 0, 0, 15, 0, 0, 40, 0, 109, 0, 0, 0, 86, 0, 0], [0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 43, 97, 0, 99], [0, 43, 0, 0, 44, 0, 0, 0, 0, 95, 0, 0, 0, 68, 0], [0, 0, 0, 0, 0, 8, 32, 0, 0, 132, 78, 0, 0, 0, 0], [0, 0, 38, 0, 0, 0, 0, 0, 0, 34, 0, 0, 140, 0, 38], [0, 0, 0, 207, 0, 0, 16, 0, 1, 0, 0, 0, 26, 0, 0], [39, 0, 0, 59, 53, 0, 0, 0, 0, 48, 138, 0, 3, 0, 0], [0, 0, 47, 18, 0, 0, 14, 0, 0, 0, 171, 0, 0, 0, 0], [118, 0, 0, 22, 52, 0, 28, 72, 0, 0, 0, 48, 0, 0, 0], [0, 16, 90, 0, 0, 0, 99, 20, 0, 81, 0, 0, 0, 34, 0], [0, 27, 0, 59, 0, 0, 0, 0, 0, 0, 9, 70, 137, 0, 38], [0, 138, 102, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [7, 0, 25, 0, 0, 0, 17, 0, 0, 0, 0, 0, 0, 13, 278], [0, 67, 31, 0, 0, 0, 0, 13, 71, 0, 0, 72, 86, 0, 0], [0, 0, 134, 0, 0, 7, 0, 0, 4, 139, 0, 31, 0, 25, 0], [120, 0, 42, 47, 0, 0, 41, 0, 0, 0, 0, 0, 0, 0, 0], [116, 97, 0, 26, 0, 9, 16, 76, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 5, 143, 0, 0, 0, 0, 0, 88, 0, 14, 0], [0, 10, 183, 0, 0, 39, 11, 0, 0, 0, 0, 0, 41, 56, 0], [0, 0, 0, 0, 0, 44, 178, 0, 0, 71, 0, 0, 35, 0, 12], [4, 0, 0, 0, 0, 148, 0, 0, 95, 0, 3, 0, 0, 0, 0], [40, 0, 0, 2, 0, 0, 0, 0, 73, 0, 0, 15, 176, 0, 34], [0, 0, 64, 0, 33, 0, 51, 0, 0, 0, 0, 102, 0, 0, 0], [0, 0, 0, 0, 9, 0, 164, 0, 0, 0, 0, 0, 0, 63, 14], [0, 6, 0, 0, 0, 0, 0, 0, 16, 11, 125, 56, 126, 0, 0], [0, 93, 59, 0, 0, 0, 57, 0, 50, 0, 43, 0, 0, 0, 38], ] _outbound_truck_raw_data = [ [13, 4, 12, 20, 0, 18, 67, 5, 2, 49, 15, 2, 24, 10, 9], [28, 1, 4, 15, 4, 24, 0, 5, 7, 10, 6, 1, 10, 2, 2], [18, 12, 13, 4, 4, 5, 4, 1, 43, 17, 10, 3, 16, 1, 6], [17, 13, 9, 13, 2, 1, 42, 4, 0, 16, 27, 1, 5, 1, 4], [13, 10, 10, 7, 0, 10, 4, 12, 24, 7, 17, 16, 35, 1, 6], [10, 12, 1, 5, 2, 10, 15, 7, 1, 5, 0, 15, 4, 33, 1], [40, 0, 34, 6, 1, 9, 12, 1, 4, 4, 8, 11, 72, 13, 6], [5, 25, 10, 1, 0, 19, 3, 1, 2, 2, 2, 1, 0, 5, 6], [9, 15, 17, 2, 1, 12, 38, 2, 23, 1, 11, 7, 4, 1, 19], [4, 5, 41, 6, 1, 7, 16, 3, 1, 19, 15, 24, 18, 14, 5], [3, 2, 19, 10, 3, 16, 18, 0, 2, 2, 1, 2, 37, 12, 16], [0, 8, 8, 11, 3, 5, 3, 4, 1, 3, 12, 3, 2, 21, 16], [19, 15, 27, 39, 3, 16, 1, 1, 2, 24, 18, 10, 12, 6, 0], [3, 12, 12, 2, 0, 3, 46, 1, 18, 21, 55, 8, 9, 20, 61], [5, 19, 8, 3, 0, 3, 32, 3, 0, 7, 3, 11, 3, 3, 16], [2, 0, 16, 5, 12, 14, 23, 3, 12, 12, 10, 4, 4, 22, 1], [4, 33, 19, 1, 2, 0, 16, 0, 3, 2, 27, 28, 49, 14, 11], [7, 42, 17, 9, 3, 4, 44, 0, 8, 6, 2, 9, 1, 11, 23], [1, 9, 19, 2, 6, 27, 1, 1, 4, 16, 18, 30, 23, 19, 21], [18, 18, 14, 9, 11, 10, 26, 1, 19, 5, 14, 12, 64, 22, 27], [18, 1, 16, 20, 2, 5, 10, 1, 27, 6, 36, 3, 37, 4, 6], [1, 4, 22, 3, 3, 16, 16, 1, 23, 8, 5, 32, 8, 4, 7], [9, 23, 34, 9, 3, 15, 6, 2, 15, 8, 12, 9, 21, 1, 2], [26, 20, 17, 5, 1, 8, 17, 1, 11, 19, 2, 26, 10, 11, 7], [3, 8, 15, 15, 7, 4, 22, 10, 18, 4, 1, 5, 29, 3, 24], [22, 29, 31, 2, 2, 12, 23, 1, 4, 1, 1, 33, 16, 2, 27], [8, 13, 16, 5, 3, 0, 4, 18, 20, 23, 26, 13, 8, 8, 8], [9, 45, 4, 8, 8, 24, 41, 1, 63, 18, 3, 18, 17, 9, 4], [0, 20, 3, 2, 13, 8, 4, 1, 19, 5, 21, 0, 74, 5, 28], [4, 6, 2, 2, 5, 12, 0, 1, 2, 12, 15, 7, 7, 14, 1], [6, 2, 47, 53, 3, 15, 9, 5, 0, 6, 12, 10, 40, 3, 48], [9, 6, 5, 30, 1, 17, 6, 0, 18, 9, 65, 29, 4, 1, 3], [0, 14, 5, 1, 7, 4, 11, 4, 1, 3, 3, 6, 24, 15, 1], [9, 5, 20, 15, 4, 3, 16, 1, 5, 11, 50, 29, 1, 4, 4], [4, 6, 17, 0, 7, 56, 30, 4, 2, 27, 26, 1, 10, 26, 5], [16, 15, 20, 1, 7, 36, 7, 2, 1, 4, 1, 1, 3, 13, 13], [5, 7, 17, 13, 0, 35, 9, 6, 6, 13, 11, 0, 7, 3, 7], [12, 2, 15, 3, 5, 10, 34, 5, 3, 10, 3, 13, 82, 21, 12], [10, 3, 26, 3, 7, 1, 19, 2, 20, 72, 26, 35, 54, 3, 8], [1, 15, 74, 12, 2, 18, 1, 0, 19, 5, 30, 2, 5, 17, 8], [37, 2, 11, 3, 1, 8, 1, 2, 5, 15, 5, 1, 4, 1, 8], [5, 9, 24, 11, 4, 13, 25, 0, 13, 5, 4, 2, 12, 4, 11], [26, 14, 33, 10, 12, 5, 47, 5, 1, 2, 2, 1, 82, 6, 8], [6, 3, 6, 24, 5, 11, 1, 2, 8, 36, 0, 13, 60, 7, 0], [12, 5, 11, 21, 3, 0, 6, 3, 7, 3, 3, 19, 1, 6, 6], [8, 2, 36, 14, 2, 37, 28, 12, 46, 8, 12, 31, 11, 6, 22], [3, 6, 76, 7, 9, 10, 2, 6, 18, 29, 4, 9, 8, 13, 9], [13, 4, 14, 2, 5, 10, 11, 15, 18, 2, 2, 7, 24, 15, 7], [6, 6, 13, 24, 1, 2, 34, 14, 1, 16, 1, 32, 23, 6, 0], [10, 2, 4, 0, 6, 17, 2, 1, 0, 24, 1, 10, 17, 16, 14], ] # Derived data. inbound_truck_count = len(_inbound_truck_raw_data) outbound_truck_count = len(_outbound_truck_raw_data) total_truck_count = inbound_truck_count + outbound_truck_count
47.114035
100
0.432694
""" Cross-docking truck data. This data is generated by a generate_dataset.py script. Created: Feb 18, 2019 at 07:30:02 PM Copyright (c) 2022, Krerkkiat Chusap This souce code is licensed under BSD 3-Clause "New" or "Revised" License (see LICENSE for details). """ from pathlib import Path # Problem data. name = Path(__file__).stem inbound_gate_count = 10 outbound_gate_count = 10 # Parameters used to generate this data. number_of_total_product_types = 15 product_per_truck_rate = 0.35 possible_inbound_total_product = [250, 340] # Truck data. _inbound_truck_raw_data = [ [0, 55, 0, 0, 0, 0, 89, 0, 2, 0, 0, 70, 111, 0, 13], [50, 0, 0, 0, 0, 115, 0, 0, 0, 0, 58, 0, 27, 0, 0], [23, 0, 40, 23, 0, 41, 0, 0, 100, 0, 0, 0, 0, 113, 0], [0, 0, 78, 0, 0, 71, 0, 0, 49, 21, 29, 0, 0, 92, 0], [0, 0, 0, 15, 0, 0, 40, 0, 109, 0, 0, 0, 86, 0, 0], [0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 43, 97, 0, 99], [0, 43, 0, 0, 44, 0, 0, 0, 0, 95, 0, 0, 0, 68, 0], [0, 0, 0, 0, 0, 8, 32, 0, 0, 132, 78, 0, 0, 0, 0], [0, 0, 38, 0, 0, 0, 0, 0, 0, 34, 0, 0, 140, 0, 38], [0, 0, 0, 207, 0, 0, 16, 0, 1, 0, 0, 0, 26, 0, 0], [39, 0, 0, 59, 53, 0, 0, 0, 0, 48, 138, 0, 3, 0, 0], [0, 0, 47, 18, 0, 0, 14, 0, 0, 0, 171, 0, 0, 0, 0], [118, 0, 0, 22, 52, 0, 28, 72, 0, 0, 0, 48, 0, 0, 0], [0, 16, 90, 0, 0, 0, 99, 20, 0, 81, 0, 0, 0, 34, 0], [0, 27, 0, 59, 0, 0, 0, 0, 0, 0, 9, 70, 137, 0, 38], [0, 138, 102, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [7, 0, 25, 0, 0, 0, 17, 0, 0, 0, 0, 0, 0, 13, 278], [0, 67, 31, 0, 0, 0, 0, 13, 71, 0, 0, 72, 86, 0, 0], [0, 0, 134, 0, 0, 7, 0, 0, 4, 139, 0, 31, 0, 25, 0], [120, 0, 42, 47, 0, 0, 41, 0, 0, 0, 0, 0, 0, 0, 0], [116, 97, 0, 26, 0, 9, 16, 76, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 5, 143, 0, 0, 0, 0, 0, 88, 0, 14, 0], [0, 10, 183, 0, 0, 39, 11, 0, 0, 0, 0, 0, 41, 56, 0], [0, 0, 0, 0, 0, 44, 178, 0, 0, 71, 0, 0, 35, 0, 12], [4, 0, 0, 0, 0, 148, 0, 0, 95, 0, 3, 0, 0, 0, 0], [40, 0, 0, 2, 0, 0, 0, 0, 73, 0, 0, 15, 176, 0, 34], [0, 0, 64, 0, 33, 0, 51, 0, 0, 0, 0, 102, 0, 0, 0], [0, 0, 0, 0, 9, 0, 164, 0, 0, 0, 0, 0, 0, 63, 14], [0, 6, 0, 0, 0, 0, 0, 0, 16, 11, 125, 56, 126, 0, 0], [0, 93, 59, 0, 0, 0, 57, 0, 50, 0, 43, 0, 0, 0, 38], ] _outbound_truck_raw_data = [ [13, 4, 12, 20, 0, 18, 67, 5, 2, 49, 15, 2, 24, 10, 9], [28, 1, 4, 15, 4, 24, 0, 5, 7, 10, 6, 1, 10, 2, 2], [18, 12, 13, 4, 4, 5, 4, 1, 43, 17, 10, 3, 16, 1, 6], [17, 13, 9, 13, 2, 1, 42, 4, 0, 16, 27, 1, 5, 1, 4], [13, 10, 10, 7, 0, 10, 4, 12, 24, 7, 17, 16, 35, 1, 6], [10, 12, 1, 5, 2, 10, 15, 7, 1, 5, 0, 15, 4, 33, 1], [40, 0, 34, 6, 1, 9, 12, 1, 4, 4, 8, 11, 72, 13, 6], [5, 25, 10, 1, 0, 19, 3, 1, 2, 2, 2, 1, 0, 5, 6], [9, 15, 17, 2, 1, 12, 38, 2, 23, 1, 11, 7, 4, 1, 19], [4, 5, 41, 6, 1, 7, 16, 3, 1, 19, 15, 24, 18, 14, 5], [3, 2, 19, 10, 3, 16, 18, 0, 2, 2, 1, 2, 37, 12, 16], [0, 8, 8, 11, 3, 5, 3, 4, 1, 3, 12, 3, 2, 21, 16], [19, 15, 27, 39, 3, 16, 1, 1, 2, 24, 18, 10, 12, 6, 0], [3, 12, 12, 2, 0, 3, 46, 1, 18, 21, 55, 8, 9, 20, 61], [5, 19, 8, 3, 0, 3, 32, 3, 0, 7, 3, 11, 3, 3, 16], [2, 0, 16, 5, 12, 14, 23, 3, 12, 12, 10, 4, 4, 22, 1], [4, 33, 19, 1, 2, 0, 16, 0, 3, 2, 27, 28, 49, 14, 11], [7, 42, 17, 9, 3, 4, 44, 0, 8, 6, 2, 9, 1, 11, 23], [1, 9, 19, 2, 6, 27, 1, 1, 4, 16, 18, 30, 23, 19, 21], [18, 18, 14, 9, 11, 10, 26, 1, 19, 5, 14, 12, 64, 22, 27], [18, 1, 16, 20, 2, 5, 10, 1, 27, 6, 36, 3, 37, 4, 6], [1, 4, 22, 3, 3, 16, 16, 1, 23, 8, 5, 32, 8, 4, 7], [9, 23, 34, 9, 3, 15, 6, 2, 15, 8, 12, 9, 21, 1, 2], [26, 20, 17, 5, 1, 8, 17, 1, 11, 19, 2, 26, 10, 11, 7], [3, 8, 15, 15, 7, 4, 22, 10, 18, 4, 1, 5, 29, 3, 24], [22, 29, 31, 2, 2, 12, 23, 1, 4, 1, 1, 33, 16, 2, 27], [8, 13, 16, 5, 3, 0, 4, 18, 20, 23, 26, 13, 8, 8, 8], [9, 45, 4, 8, 8, 24, 41, 1, 63, 18, 3, 18, 17, 9, 4], [0, 20, 3, 2, 13, 8, 4, 1, 19, 5, 21, 0, 74, 5, 28], [4, 6, 2, 2, 5, 12, 0, 1, 2, 12, 15, 7, 7, 14, 1], [6, 2, 47, 53, 3, 15, 9, 5, 0, 6, 12, 10, 40, 3, 48], [9, 6, 5, 30, 1, 17, 6, 0, 18, 9, 65, 29, 4, 1, 3], [0, 14, 5, 1, 7, 4, 11, 4, 1, 3, 3, 6, 24, 15, 1], [9, 5, 20, 15, 4, 3, 16, 1, 5, 11, 50, 29, 1, 4, 4], [4, 6, 17, 0, 7, 56, 30, 4, 2, 27, 26, 1, 10, 26, 5], [16, 15, 20, 1, 7, 36, 7, 2, 1, 4, 1, 1, 3, 13, 13], [5, 7, 17, 13, 0, 35, 9, 6, 6, 13, 11, 0, 7, 3, 7], [12, 2, 15, 3, 5, 10, 34, 5, 3, 10, 3, 13, 82, 21, 12], [10, 3, 26, 3, 7, 1, 19, 2, 20, 72, 26, 35, 54, 3, 8], [1, 15, 74, 12, 2, 18, 1, 0, 19, 5, 30, 2, 5, 17, 8], [37, 2, 11, 3, 1, 8, 1, 2, 5, 15, 5, 1, 4, 1, 8], [5, 9, 24, 11, 4, 13, 25, 0, 13, 5, 4, 2, 12, 4, 11], [26, 14, 33, 10, 12, 5, 47, 5, 1, 2, 2, 1, 82, 6, 8], [6, 3, 6, 24, 5, 11, 1, 2, 8, 36, 0, 13, 60, 7, 0], [12, 5, 11, 21, 3, 0, 6, 3, 7, 3, 3, 19, 1, 6, 6], [8, 2, 36, 14, 2, 37, 28, 12, 46, 8, 12, 31, 11, 6, 22], [3, 6, 76, 7, 9, 10, 2, 6, 18, 29, 4, 9, 8, 13, 9], [13, 4, 14, 2, 5, 10, 11, 15, 18, 2, 2, 7, 24, 15, 7], [6, 6, 13, 24, 1, 2, 34, 14, 1, 16, 1, 32, 23, 6, 0], [10, 2, 4, 0, 6, 17, 2, 1, 0, 24, 1, 10, 17, 16, 14], ] # Derived data. inbound_truck_count = len(_inbound_truck_raw_data) outbound_truck_count = len(_outbound_truck_raw_data) total_truck_count = inbound_truck_count + outbound_truck_count
0
0
0
1bdf22fe89aeb7adc738880690082b4462bbb261
2,226
py
Python
debug.py
jlandgre/debug
24ae298b665a708fb13de7c17cd02cf23d747076
[ "MIT" ]
null
null
null
debug.py
jlandgre/debug
24ae298b665a708fb13de7c17cd02cf23d747076
[ "MIT" ]
null
null
null
debug.py
jlandgre/debug
24ae298b665a708fb13de7c17cd02cf23d747076
[ "MIT" ]
null
null
null
import pandas as pd import numpy as np import datetime as dt #Debug library functions #Add a new row to dfDebug
43.647059
104
0.615454
import pandas as pd import numpy as np import datetime as dt #Debug library functions def init(): data = {'Desc':[], 'colname':[], 'size':[], 'dtype_string':[], 'dtype_int':[], 'dtype_float':[], 'isnull':[], 'notnull':[], 'Desc2':[], 'Val2':[], 'time':[]} dfDebug = pd.DataFrame(data=data) #Trick Pandas into dtyping count columns as integer dfDebug.loc[0,:] = ['Dummy_val','',0,0,0,0,0,0,'','',0] lst_count_cols = ['size','dtype_string', 'dtype_int', 'dtype_float', 'isnull', 'notnull'] dfDebug[lst_count_cols] = dfDebug[lst_count_cols].astype('int') return dfDebug def CountDTypeString(df, col): return df.loc[df[col].apply(lambda x: isinstance(x, str)), col].size def CountDTypeInt(df, col): return int(df.loc[df[col].apply(lambda x: isinstance(x, int)), col].size) def CountDTypeFloat(df, col): return int(df.loc[df[col].apply(lambda x: isinstance(x, float)), col].size) def CountNull(df, col): return int(df.loc[df[col].isnull(), col].size) def CountNotNull(df, col): return int(df.loc[~df[col].isnull(), col].size) #Add a new row to dfDebug def loginfo(dfDebug, logtype, desc, df=None, col='', desc2='', val2=''): #Construct row as a list of values and append row to dfDebug if logtype == 'colinfo': lst = [desc, col, df[col].size, CountDTypeString(df, col), CountDTypeInt(df, col), CountDTypeFloat(df, col), CountNull(df, col), CountNotNull(df, col), desc2, val2, ''] elif logtype == 'indexsize': lst = [desc,'',df.index.size, '', '', '', '', '', desc2, val2, ''] elif logtype == 'time': lst = [desc, '', '', '', '', '', '', '', desc2, val2, dt.datetime.now().strftime('%H:%M:%S.%f')] elif logtype == 'info': lst = [desc, '','', '','', '','', '', desc2, val2, ''] dfDebug.loc[dfDebug.index.size] = lst #Control dtype of count columns for nicer display if dfDebug.loc[0,'Desc'] == 'Dummy_val': dfDebug.drop(0, axis=0, inplace=True) dfDebug.reset_index(drop=True, inplace=True) lst_count_cols = ['size','dtype_string', 'dtype_int', 'dtype_float', 'isnull', 'notnull'] dfDebug[lst_count_cols] = dfDebug[lst_count_cols].astype('str') return dfDebug
1,957
0
155
624e4a1d0a67a168cebfa0bf99b24fcb3639eca0
1,032
py
Python
tests/unit/test_debuggers.py
danni-m/RLTest
85c09592e96e26edab94a22077a582fa425b62fa
[ "BSD-3-Clause" ]
null
null
null
tests/unit/test_debuggers.py
danni-m/RLTest
85c09592e96e26edab94a22077a582fa425b62fa
[ "BSD-3-Clause" ]
null
null
null
tests/unit/test_debuggers.py
danni-m/RLTest
85c09592e96e26edab94a22077a582fa425b62fa
[ "BSD-3-Clause" ]
null
null
null
from unittest import TestCase from RLTest.debuggers import Valgrind
43
106
0.664729
from unittest import TestCase from RLTest.debuggers import Valgrind class TestValgrind(TestCase): def test_generate_command_default(self): default_valgrind = Valgrind(options="") cmd_args = default_valgrind.generate_command() assert ['valgrind', '--error-exitcode=1', '--leak-check=full', '--errors-for-leak-kinds=definite', ] == cmd_args def test_generate_command_supression(self): default_valgrind = Valgrind(options="", suppressions="file") cmd_args = default_valgrind.generate_command() assert ['valgrind', '--error-exitcode=1', '--leak-check=full', '--errors-for-leak-kinds=definite', '--suppressions=file'] == cmd_args def test_generate_command_logfile(self): default_valgrind = Valgrind(options="") cmd_args = default_valgrind.generate_command('logfile') assert ['valgrind', '--error-exitcode=1', '--leak-check=full', '--errors-for-leak-kinds=definite', '--log-file=logfile'] == cmd_args
851
8
103
c78d66ffc5ac1217de63c18a78706287ebbcb685
392
py
Python
py/experiments/np_test.py
acjensen/control
273803cace506acb956f11da8d501863a5349892
[ "MIT" ]
null
null
null
py/experiments/np_test.py
acjensen/control
273803cace506acb956f11da8d501863a5349892
[ "MIT" ]
null
null
null
py/experiments/np_test.py
acjensen/control
273803cace506acb956f11da8d501863a5349892
[ "MIT" ]
null
null
null
import numpy as np a = range(100) A = np.array(a).reshape(len(a)//2, 2) A = A.ravel().view([('col1', 'i8'), ('col2', 'i8'), ] ).astype([('col1', 'i4'), ('col2', 'i8'), ]) print(A[:5]) # array([(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)], # dtype=[('col1', '<i4'), ('col2', '<i8')]) print(A.dtype) # dtype([('col1', '<i4'), ('col2', '<i8')]) print(A['col1']*A['col2'])
26.133333
63
0.431122
import numpy as np a = range(100) A = np.array(a).reshape(len(a)//2, 2) A = A.ravel().view([('col1', 'i8'), ('col2', 'i8'), ] ).astype([('col1', 'i4'), ('col2', 'i8'), ]) print(A[:5]) # array([(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)], # dtype=[('col1', '<i4'), ('col2', '<i8')]) print(A.dtype) # dtype([('col1', '<i4'), ('col2', '<i8')]) print(A['col1']*A['col2'])
0
0
0
bd8f8422450a7a9e0f5f2c3dfa55bf94e771b16d
1,148
py
Python
Office365_REST_Python_Client-2.1.0-py3.6.egg/examples/file_operations.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
Office365_REST_Python_Client-2.1.0-py3.6.egg/examples/file_operations.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
Office365_REST_Python_Client-2.1.0-py3.6.egg/examples/file_operations.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
1
2018-03-23T14:49:04.000Z
2018-03-23T14:49:04.000Z
from examples.settings import settings from office365.runtime.auth.authentication_context import AuthenticationContext from office365.sharepoint.client_context import ClientContext def read_folder_and_files(): """Read a folder example""" list_obj = ctx.web.lists.get_by_title(listTitle) folder = list_obj.root_folder ctx.load(folder) ctx.execute_query() print("List url: {0}".format(folder.properties["ServerRelativeUrl"])) files = folder.files ctx.load(files) ctx.execute_query() for cur_file in files: print("File name: {0}".format(cur_file.properties["Name"])) folders = ctx.web.folders ctx.load(folders) ctx.execute_query() for folder in folders: print("Folder name: {0}".format(folder.properties["Name"])) if __name__ == '__main__': ctx_auth = AuthenticationContext(url=settings['url']) if ctx_auth.acquire_token_for_user(username=settings['username'], password=settings['password']): ctx = ClientContext(settings['url'], ctx_auth) listTitle = "Documents" read_folder_and_files() else: print(ctx_auth.get_last_error())
31.027027
101
0.706446
from examples.settings import settings from office365.runtime.auth.authentication_context import AuthenticationContext from office365.sharepoint.client_context import ClientContext def read_folder_and_files(): """Read a folder example""" list_obj = ctx.web.lists.get_by_title(listTitle) folder = list_obj.root_folder ctx.load(folder) ctx.execute_query() print("List url: {0}".format(folder.properties["ServerRelativeUrl"])) files = folder.files ctx.load(files) ctx.execute_query() for cur_file in files: print("File name: {0}".format(cur_file.properties["Name"])) folders = ctx.web.folders ctx.load(folders) ctx.execute_query() for folder in folders: print("Folder name: {0}".format(folder.properties["Name"])) if __name__ == '__main__': ctx_auth = AuthenticationContext(url=settings['url']) if ctx_auth.acquire_token_for_user(username=settings['username'], password=settings['password']): ctx = ClientContext(settings['url'], ctx_auth) listTitle = "Documents" read_folder_and_files() else: print(ctx_auth.get_last_error())
0
0
0
0602385d6a419c8343b8073083c49f7f56815ae0
4,874
py
Python
src/whoosh/lang/snowball/bases.py
matchup-ir/whooshy
3e8730f4cbb559fd59971c5a2e6d01924d3968c0
[ "BSD-2-Clause-FreeBSD" ]
319
2016-09-22T15:54:48.000Z
2022-03-18T02:36:58.000Z
src/whoosh/lang/snowball/bases.py
matchup-ir/whooshy
3e8730f4cbb559fd59971c5a2e6d01924d3968c0
[ "BSD-2-Clause-FreeBSD" ]
85
2018-12-11T06:53:06.000Z
2021-07-30T20:39:12.000Z
src/whoosh/lang/snowball/bases.py
matchup-ir/whooshy
3e8730f4cbb559fd59971c5a2e6d01924d3968c0
[ "BSD-2-Clause-FreeBSD" ]
62
2015-07-03T12:34:32.000Z
2022-02-08T08:21:12.000Z
# Base classes class _ScandinavianStemmer(object): """ This subclass encapsulates a method for defining the string region R1. It is used by the Danish, Norwegian, and Swedish stemmer. """ def _r1_scandinavian(self, word, vowels): """ Return the region R1 that is used by the Scandinavian stemmers. R1 is the region after the first non-vowel following a vowel, or is the null region at the end of the word if there is no such non-vowel. But then R1 is adjusted so that the region before it contains at least three letters. :param word: The word whose region R1 is determined. :type word: str or unicode :param vowels: The vowels of the respective language that are used to determine the region R1. :type vowels: unicode :return: the region R1 for the respective word. :rtype: unicode :note: This helper method is invoked by the respective stem method of the subclasses DanishStemmer, NorwegianStemmer, and SwedishStemmer. It is not to be invoked directly! """ r1 = "" for i in range(1, len(word)): if word[i] not in vowels and word[i - 1] in vowels: if len(word[:i + 1]) < 3 and len(word[:i + 1]) > 0: r1 = word[3:] elif len(word[:i + 1]) >= 3: r1 = word[i + 1:] else: return word break return r1 class _StandardStemmer(object): """ This subclass encapsulates two methods for defining the standard versions of the string regions R1, R2, and RV. """ def _r1r2_standard(self, word, vowels): """ Return the standard interpretations of the string regions R1 and R2. R1 is the region after the first non-vowel following a vowel, or is the null region at the end of the word if there is no such non-vowel. R2 is the region after the first non-vowel following a vowel in R1, or is the null region at the end of the word if there is no such non-vowel. :param word: The word whose regions R1 and R2 are determined. :type word: str or unicode :param vowels: The vowels of the respective language that are used to determine the regions R1 and R2. :type vowels: unicode :return: (r1,r2), the regions R1 and R2 for the respective word. :rtype: tuple :note: This helper method is invoked by the respective stem method of the subclasses DutchStemmer, FinnishStemmer, FrenchStemmer, GermanStemmer, ItalianStemmer, PortugueseStemmer, RomanianStemmer, and SpanishStemmer. It is not to be invoked directly! :note: A detailed description of how to define R1 and R2 can be found at http://snowball.tartarus.org/texts/r1r2.html """ r1 = "" r2 = "" for i in range(1, len(word)): if word[i] not in vowels and word[i - 1] in vowels: r1 = word[i + 1:] break for i in range(1, len(r1)): if r1[i] not in vowels and r1[i - 1] in vowels: r2 = r1[i + 1:] break return (r1, r2) def _rv_standard(self, word, vowels): """ Return the standard interpretation of the string region RV. If the second letter is a consonant, RV is the region after the next following vowel. If the first two letters are vowels, RV is the region after the next following consonant. Otherwise, RV is the region after the third letter. :param word: The word whose region RV is determined. :type word: str or unicode :param vowels: The vowels of the respective language that are used to determine the region RV. :type vowels: unicode :return: the region RV for the respective word. :rtype: unicode :note: This helper method is invoked by the respective stem method of the subclasses ItalianStemmer, PortugueseStemmer, RomanianStemmer, and SpanishStemmer. It is not to be invoked directly! """ rv = "" if len(word) >= 2: if word[1] not in vowels: for i in range(2, len(word)): if word[i] in vowels: rv = word[i + 1:] break elif word[:2] in vowels: for i in range(2, len(word)): if word[i] not in vowels: rv = word[i + 1:] break else: rv = word[3:] return rv
36.373134
77
0.566065
# Base classes class _ScandinavianStemmer(object): """ This subclass encapsulates a method for defining the string region R1. It is used by the Danish, Norwegian, and Swedish stemmer. """ def _r1_scandinavian(self, word, vowels): """ Return the region R1 that is used by the Scandinavian stemmers. R1 is the region after the first non-vowel following a vowel, or is the null region at the end of the word if there is no such non-vowel. But then R1 is adjusted so that the region before it contains at least three letters. :param word: The word whose region R1 is determined. :type word: str or unicode :param vowels: The vowels of the respective language that are used to determine the region R1. :type vowels: unicode :return: the region R1 for the respective word. :rtype: unicode :note: This helper method is invoked by the respective stem method of the subclasses DanishStemmer, NorwegianStemmer, and SwedishStemmer. It is not to be invoked directly! """ r1 = "" for i in range(1, len(word)): if word[i] not in vowels and word[i - 1] in vowels: if len(word[:i + 1]) < 3 and len(word[:i + 1]) > 0: r1 = word[3:] elif len(word[:i + 1]) >= 3: r1 = word[i + 1:] else: return word break return r1 class _StandardStemmer(object): """ This subclass encapsulates two methods for defining the standard versions of the string regions R1, R2, and RV. """ def _r1r2_standard(self, word, vowels): """ Return the standard interpretations of the string regions R1 and R2. R1 is the region after the first non-vowel following a vowel, or is the null region at the end of the word if there is no such non-vowel. R2 is the region after the first non-vowel following a vowel in R1, or is the null region at the end of the word if there is no such non-vowel. :param word: The word whose regions R1 and R2 are determined. :type word: str or unicode :param vowels: The vowels of the respective language that are used to determine the regions R1 and R2. :type vowels: unicode :return: (r1,r2), the regions R1 and R2 for the respective word. :rtype: tuple :note: This helper method is invoked by the respective stem method of the subclasses DutchStemmer, FinnishStemmer, FrenchStemmer, GermanStemmer, ItalianStemmer, PortugueseStemmer, RomanianStemmer, and SpanishStemmer. It is not to be invoked directly! :note: A detailed description of how to define R1 and R2 can be found at http://snowball.tartarus.org/texts/r1r2.html """ r1 = "" r2 = "" for i in range(1, len(word)): if word[i] not in vowels and word[i - 1] in vowels: r1 = word[i + 1:] break for i in range(1, len(r1)): if r1[i] not in vowels and r1[i - 1] in vowels: r2 = r1[i + 1:] break return (r1, r2) def _rv_standard(self, word, vowels): """ Return the standard interpretation of the string region RV. If the second letter is a consonant, RV is the region after the next following vowel. If the first two letters are vowels, RV is the region after the next following consonant. Otherwise, RV is the region after the third letter. :param word: The word whose region RV is determined. :type word: str or unicode :param vowels: The vowels of the respective language that are used to determine the region RV. :type vowels: unicode :return: the region RV for the respective word. :rtype: unicode :note: This helper method is invoked by the respective stem method of the subclasses ItalianStemmer, PortugueseStemmer, RomanianStemmer, and SpanishStemmer. It is not to be invoked directly! """ rv = "" if len(word) >= 2: if word[1] not in vowels: for i in range(2, len(word)): if word[i] in vowels: rv = word[i + 1:] break elif word[:2] in vowels: for i in range(2, len(word)): if word[i] not in vowels: rv = word[i + 1:] break else: rv = word[3:] return rv
0
0
0
c36ef14937ce48bf1fede8f6a6f4555a4c9a20b7
671
py
Python
myopenpantry/models/ingredients.py
MyOpenPantry/flask-backend
e94702bfa04f36c1a6015ae3e9c37dfb7b923279
[ "MIT" ]
null
null
null
myopenpantry/models/ingredients.py
MyOpenPantry/flask-backend
e94702bfa04f36c1a6015ae3e9c37dfb7b923279
[ "MIT" ]
4
2021-03-28T19:47:04.000Z
2021-05-04T00:59:46.000Z
myopenpantry/models/ingredients.py
MyOpenPantry/flask-backend
e94702bfa04f36c1a6015ae3e9c37dfb7b923279
[ "MIT" ]
null
null
null
import sqlalchemy as sa from sqlalchemy.orm import relationship from myopenpantry.extensions.database import db # ingredients are a base part of recipes. ex "chicken breast" # association tables will be used to join these with inventory items, as well as the amount needed in recipes
37.277778
109
0.754098
import sqlalchemy as sa from sqlalchemy.orm import relationship from myopenpantry.extensions.database import db # ingredients are a base part of recipes. ex "chicken breast" # association tables will be used to join these with inventory items, as well as the amount needed in recipes class Ingredient(db.Model): __tablename__ = "ingredients" id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String(128), nullable=False, unique=True) # many to one, with Ingredient being the one items = relationship('Item', back_populates="ingredient") # many to many recipes = relationship("RecipeIngredient", back_populates="ingredient")
0
363
22
e9f1fa502170a2e93f549a491cb035c8fcee31ea
2,017
py
Python
csrv/model/cards/corp/card01065_test.py
mrroach/CentralServer
e377c65d8f3adf5a2d3273acd4f459be697aea56
[ "Apache-2.0" ]
null
null
null
csrv/model/cards/corp/card01065_test.py
mrroach/CentralServer
e377c65d8f3adf5a2d3273acd4f459be697aea56
[ "Apache-2.0" ]
null
null
null
csrv/model/cards/corp/card01065_test.py
mrroach/CentralServer
e377c65d8f3adf5a2d3273acd4f459be697aea56
[ "Apache-2.0" ]
1
2020-09-20T11:26:20.000Z
2020-09-20T11:26:20.000Z
import unittest from csrv.model import errors from csrv.model import events from csrv.model import test_base from csrv.model import timing_phases from csrv.model.cards.corp import card01065 if __name__ == '__main__': unittest.main()
32.532258
64
0.705007
import unittest from csrv.model import errors from csrv.model import events from csrv.model import test_base from csrv.model import timing_phases from csrv.model.cards.corp import card01065 class Card01065Test(test_base.TestBase): def setUp(self): test_base.TestBase.setUp(self) self.card = card01065.Card01065(self.game, self.corp) self.corp.clicks.set(3) self.corp.credits.set(5) self.game.insert_next_phase( timing_phases.CorpTurnAbilities(self.game, self.corp)) self.server = self.corp.new_remote_server() self.other_server = self.corp.new_remote_server() ice = [] for c in list(self.corp.hq.cards): self.corp.hq.remove(c) self.corp.rnd.add(c) for c in list(self.corp.rnd.cards): # 3-strength barrier if c.NAME == 'Card01113': self.corp.rnd.remove(c) ice.append(c) self.server.install_ice(ice[0]) self.server.install_ice(ice[1]) self.other_server.install_ice(ice[2]) ice[0].rez() ice[2].rez() self.server.install(self.card) def test_boost_strength(self): choices = self.game.current_phase().choices() self.assertEqual(1, len(choices)) self.game.resolve_current_phase(choices[0], None) # should be usable now choices = self.game.current_phase().choices() self.assertEqual([self.card._card01065_action], choices) self.game.resolve_current_phase(choices[0], None) choices = self.game.current_phase().choices() self.assertEqual(1, len(choices)) response = choices[0].request().new_response() response.credits = 3 self.game.resolve_current_phase(choices[0], response) self.assertEqual(6, self.server.ice.cards[0].strength) self.assertEqual(3, self.server.ice.cards[1].strength) self.assertEqual(3, self.other_server.ice.cards[0].strength) self.game.trigger_event( events.CorpDiscardPhase(self.game, self.corp), None) self.assertEqual(3, self.server.ice.cards[0].strength) if __name__ == '__main__': unittest.main()
1,687
19
73
8b1e2c0c2faf01a9f0cd58b853271bbbceaaf19e
2,374
py
Python
tests/test_observer_abilities.py
IanDCarroll/xox
38feac84e81e8c00a397f7f976efee15756cd3ac
[ "MIT" ]
null
null
null
tests/test_observer_abilities.py
IanDCarroll/xox
38feac84e81e8c00a397f7f976efee15756cd3ac
[ "MIT" ]
30
2016-11-25T05:34:34.000Z
2017-02-11T00:10:17.000Z
tests/test_observer_abilities.py
IanDCarroll/tik-tak-toe
38feac84e81e8c00a397f7f976efee15756cd3ac
[ "MIT" ]
1
2016-11-26T01:41:37.000Z
2016-11-26T01:41:37.000Z
import unittest from Training.observer_abilities import * if __name__ == '__main__': unittest.main()
38.290323
66
0.657961
import unittest from Training.observer_abilities import * class ObserverTestCase(unittest.TestCase): def setUp(self): self.observer = Observer() self.mock_4x4_board = [ 1, 0, 0,10, 0, 1,10, 0, 0,10, 1, 0, 10, 0, 0, 1 ] self.expected_4x4_analysis = [ 11,11,11,11, 11,11,11,11, 4,40 ] self.mock_board = [1,0,10, 1,10,0, 1,10,1] self.expected_analysis = [11,11,12, 3,20,11, 12,21] self.expected_rows = [11,11,12] self.expected_cols = [3,20,11] self.expected_diags = [12,21] self.expected_1st_value = 12 self.expected_2nd_value = 21 def test_get_board_size_3(self): test = self.observer.get_board_size(self.mock_board) self.assertEqual(test, 3) def test_get_board_size_4(self): test = self.observer.get_board_size(self.mock_4x4_board) self.assertEqual(test, 4) def test_scan_board_can_handle_4x4_boards(self): test = self.observer.scan_board(self.mock_4x4_board) self.assertEqual(test, self.expected_4x4_analysis) def test_scan_board_returns_analyzed_list(self): test_yields = self.observer.scan_board(self.mock_board) self.assertEqual(test_yields, self.expected_analysis) def test_scan_rows_returns_analyzed_list(self): test_yields = self.observer.scan_rows(self.mock_board) self.assertEqual(test_yields, self.expected_rows) def test_scan_cols_returns_analyzed_list(self): test_yields = self.observer.scan_cols(self.mock_board) self.assertEqual(test_yields, self.expected_cols) def test_scan_diags_returns_analyzed_list(self): test_yields = self.observer.scan_diags(self.mock_board) self.assertEqual(test_yields, self.expected_diags) def test_scan_first_diag_returns_analyzed_value(self): test_yields = self.observer.scan_1st_diag(self.mock_board) self.assertEqual(test_yields, self.expected_1st_value) def test_scan_second_diag_returns_analyzed_value(self): test_yields = self.observer.scan_2nd_diag(self.mock_board) self.assertEqual(test_yields, self.expected_2nd_value) if __name__ == '__main__': unittest.main()
1,954
21
293
d2f90e2105f715bfa385ede947f0041c8746e8c3
6,133
py
Python
in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Aligned_Rotator.py
fedelopezar/nrpytutorial
753acd954be4a2f99639c9f9fd5e623689fc7493
[ "BSD-2-Clause" ]
1
2021-12-13T05:51:18.000Z
2021-12-13T05:51:18.000Z
in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Aligned_Rotator.py
fedelopezar/nrpytutorial
753acd954be4a2f99639c9f9fd5e623689fc7493
[ "BSD-2-Clause" ]
null
null
null
in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Aligned_Rotator.py
fedelopezar/nrpytutorial
753acd954be4a2f99639c9f9fd5e623689fc7493
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # <a id='top'></a> # # # # $\texttt{GiRaFFEfood}$: Initial data for $\texttt{GiRaFFE}$ # # ## Aligned Rotator # # $$\label{top}$$ # # This module provides another initial data option for $\texttt{GiRaFFE}$. This is a flat-spacetime test with initial data $$A_{\phi} = \frac{\mu \varpi}{r^3},$$ where $\mu = B_p R_{\rm NS} / 2$, $R_{\rm NS}$ is the neutron star radius, and $\varpi = \sqrt{x^2+y^2}$ is the cylindrical radius. We let $A_r = A_\theta = 0$. # # Additionally, the drift velocity $v^i = \Omega \textbf{e}_z \times \textbf{r} = [ijk] \Omega \textbf{e}^j_z x^k$, where $[ijk]$ is the Levi-Civita permutation symbol and $\textbf{e}^i_z = (0,0,1)$. # <a id='preliminaries'></a> # # ### Steps 0-1: Preliminaries # $$\label{preliminaries}$$ # # \[Back to [top](#top)\] # # Here, we will import the NRPy+ core modules and set the reference metric to Cartesian, set commonly used NRPy+ parameters, and set C parameters that will be set from outside the code eventually generated from these expressions. We will also set up a parameter to determine what initial data is set up, although it won't do much yet. # Step 0: Import the NRPy+ core modules and set the reference metric to Cartesian import NRPy_param_funcs as par import indexedexp as ixp import sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends import reference_metric as rfm par.set_parval_from_str("reference_metric::CoordSystem","Cartesian") rfm.reference_metric() # Step 1a: Set commonly used parameters. thismodule = __name__ B_p_aligned_rotator,R_NS_aligned_rotator = par.Cparameters("REAL",thismodule, # B_p_aligned_rotator = the intensity of the magnetic field and # R_NS_aligned_rotator= "Neutron star" radius ["B_p_aligned_rotator","R_NS_aligned_rotator"], [1e-5, 1.0]) # The angular velocity of the "neutron star" Omega_aligned_rotator = par.Cparameters("REAL",thismodule,"Omega_aligned_rotator",1e3) # <a id='step2'></a> # # ### Step 2: Set the vectors A in Spherical coordinates # $$\label{step2}$$ # # \[Back to [top](#top)\] # # We will first build the fundamental vector $A_i$ in spherical coordinates (see [Table 3](https://arxiv.org/pdf/1704.00599.pdf)). Note that we use reference_metric.py to set $r$ and $\theta$ in terms of Cartesian coordinates; this will save us a step later when we convert to Cartesian coordinates. So, we set # \begin{align} # A_{\phi} &= \frac{\mu \varpi}{r^3}, \\ # \end{align} # with $\mu = B_p R_{\rm NS} / 2$, $R_{\rm NS}$ is the neutron star radius, and $\varpi = \sqrt{x^2+y^2}$
43.807143
334
0.633458
#!/usr/bin/env python # coding: utf-8 # <a id='top'></a> # # # # $\texttt{GiRaFFEfood}$: Initial data for $\texttt{GiRaFFE}$ # # ## Aligned Rotator # # $$\label{top}$$ # # This module provides another initial data option for $\texttt{GiRaFFE}$. This is a flat-spacetime test with initial data $$A_{\phi} = \frac{\mu \varpi}{r^3},$$ where $\mu = B_p R_{\rm NS} / 2$, $R_{\rm NS}$ is the neutron star radius, and $\varpi = \sqrt{x^2+y^2}$ is the cylindrical radius. We let $A_r = A_\theta = 0$. # # Additionally, the drift velocity $v^i = \Omega \textbf{e}_z \times \textbf{r} = [ijk] \Omega \textbf{e}^j_z x^k$, where $[ijk]$ is the Levi-Civita permutation symbol and $\textbf{e}^i_z = (0,0,1)$. # <a id='preliminaries'></a> # # ### Steps 0-1: Preliminaries # $$\label{preliminaries}$$ # # \[Back to [top](#top)\] # # Here, we will import the NRPy+ core modules and set the reference metric to Cartesian, set commonly used NRPy+ parameters, and set C parameters that will be set from outside the code eventually generated from these expressions. We will also set up a parameter to determine what initial data is set up, although it won't do much yet. # Step 0: Import the NRPy+ core modules and set the reference metric to Cartesian import NRPy_param_funcs as par import indexedexp as ixp import sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends import reference_metric as rfm par.set_parval_from_str("reference_metric::CoordSystem","Cartesian") rfm.reference_metric() # Step 1a: Set commonly used parameters. thismodule = __name__ B_p_aligned_rotator,R_NS_aligned_rotator = par.Cparameters("REAL",thismodule, # B_p_aligned_rotator = the intensity of the magnetic field and # R_NS_aligned_rotator= "Neutron star" radius ["B_p_aligned_rotator","R_NS_aligned_rotator"], [1e-5, 1.0]) # The angular velocity of the "neutron star" Omega_aligned_rotator = par.Cparameters("REAL",thismodule,"Omega_aligned_rotator",1e3) # <a id='step2'></a> # # ### Step 2: Set the vectors A in Spherical coordinates # $$\label{step2}$$ # # \[Back to [top](#top)\] # # We will first build the fundamental vector $A_i$ in spherical coordinates (see [Table 3](https://arxiv.org/pdf/1704.00599.pdf)). Note that we use reference_metric.py to set $r$ and $\theta$ in terms of Cartesian coordinates; this will save us a step later when we convert to Cartesian coordinates. So, we set # \begin{align} # A_{\phi} &= \frac{\mu \varpi}{r^3}, \\ # \end{align} # with $\mu = B_p R_{\rm NS} / 2$, $R_{\rm NS}$ is the neutron star radius, and $\varpi = \sqrt{x^2+y^2}$ def GiRaFFEfood_NRPy_Aligned_Rotator(): r = rfm.xxSph[0] varpi = sp.sqrt(rfm.xx_to_Cart[0]**2 + rfm.xx_to_Cart[1]**2) mu = B_p_aligned_rotator * R_NS_aligned_rotator**3 / 2 ASphD = ixp.zerorank1() ASphD[2] = mu * varpi**2 / (r**3) # The other components were already declared to be 0. # <a id='step3'></a> # # ### Step 3: Use the Jacobian matrix to transform the vectors to Cartesian coordinates. # $$\label{step3}$$ # # \[Back to [top](#top)\] # # Now, we will use the coordinate transformation definitions provided by reference_metric.py to build the Jacobian # $$ # \frac{\partial x_{\rm Sph}^j}{\partial x_{\rm Cart}^i}, # $$ # where $x_{\rm Sph}^j \in \{r,\theta,\phi\}$ and $x_{\rm Cart}^i \in \{x,y,z\}$. We would normally compute its inverse, but since none of the quantities we need to transform have upper indices, it is not necessary. Then, since $A_i$ and has one lower index, it will need to be multiplied by the Jacobian: # # $$ # A_i^{\rm Cart} = A_j^{\rm Sph} \frac{\partial x_{\rm Sph}^j}{\partial x_{\rm Cart}^i}, # $$ # Step 3: Use the Jacobian matrix to transform the vectors to Cartesian coordinates. drrefmetric__dx_0UDmatrix = sp.Matrix([[sp.diff(rfm.xxSph[0],rfm.xx[0]), sp.diff(rfm.xxSph[0],rfm.xx[1]), sp.diff(rfm.xxSph[0],rfm.xx[2])], [sp.diff(rfm.xxSph[1],rfm.xx[0]), sp.diff(rfm.xxSph[1],rfm.xx[1]), sp.diff(rfm.xxSph[1],rfm.xx[2])], [sp.diff(rfm.xxSph[2],rfm.xx[0]), sp.diff(rfm.xxSph[2],rfm.xx[1]), sp.diff(rfm.xxSph[2],rfm.xx[2])]]) #dx__drrefmetric_0UDmatrix = drrefmetric__dx_0UDmatrix.inv() # We don't actually need this in this case. global AD AD = ixp.zerorank1(DIM=3) for i in range(3): for j in range(3): AD[i] = drrefmetric__dx_0UDmatrix[(j,i)]*ASphD[j] # <a id='step4'></a> # # ### Step 4: Calculate $v^i$ # $$\label{step4}$$ # # \[Back to [top](#top)\] # # Here, we will calculate the drift velocity $v^i = \Omega \textbf{e}_z \times \textbf{r} = [ijk] \Omega \textbf{e}^j_z x^k$, where $[ijk]$ is the Levi-Civita permutation symbol and $\textbf{e}^i_z = (0,0,1)$. Conveniently, in flat space, the drift velocity reduces to the Valencia velocity because $\alpha = 1$ and $\beta^i = 0$. # Step 4: Calculate v^i LeviCivitaSymbolDDD = ixp.LeviCivitaSymbol_dim3_rank3() import Min_Max_and_Piecewise_Expressions as noif unit_zU = ixp.zerorank1() unit_zU[2] = sp.sympify(1) global ValenciavU ValenciavU = ixp.zerorank1() for i in range(3): for j in range(3): for k in range(3): ValenciavU[i] += noif.coord_leq_bound(r,R_NS_aligned_rotator)*LeviCivitaSymbolDDD[i][j][k] * Omega_aligned_rotator * unit_zU[j] * rfm.xx[k] # ### NRPy+ Module Code Validation # # \[Back to [top](#top)\] # # Here, as a code validation check, we verify agreement in the SymPy expressions for the $\texttt{GiRaFFE}$ Aligned Rotator initial data equations we intend to use between # 1. this tutorial and # 2. the NRPy+ [GiRaFFEfood_NRPy_Aligned_Rotator.py](../edit/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Aligned_Rotator.py) module. #
3,285
0
23
c1f5aebe5569e8c058f6ab1653350eefa2178d40
6,434
py
Python
nlp/tutorials/word2vec/word2vec.py
bhrgv-bolla/AI
e0a0a5750c5c389bb5f512cec979da10041c8dff
[ "Apache-2.0" ]
null
null
null
nlp/tutorials/word2vec/word2vec.py
bhrgv-bolla/AI
e0a0a5750c5c389bb5f512cec979da10041c8dff
[ "Apache-2.0" ]
null
null
null
nlp/tutorials/word2vec/word2vec.py
bhrgv-bolla/AI
e0a0a5750c5c389bb5f512cec979da10041c8dff
[ "Apache-2.0" ]
null
null
null
""" Implementing word2vec using the skipgram model using a logistic regression as probability function. """ import tensorflow as tf import numpy as np import zipfile import math from . import directory_util, download import os import collections dataset_name = 'text8.zip' def read_data(filename): """ Step 1 Read data. """ filepath = os.path.join(directory_util.get_data_dir(), dataset_name) with zipfile.ZipFile(filepath) as f: print 'FILES IN THE ZIP: ', f.namelist() contents = f.read(f.namelist()[0]) try: print 'SAMPLE CONTENTS OF FILE', contents[:100] except: print '!!CANNOT PRINT SAMPLE' data = tf.compat.as_str(contents).split() # TODO what is package compat? return data download.download_data(dataset_name) vocabulary = read_data(dataset_name) vocabulary_size = len(vocabulary) # Taking all the words in the vocabulary! print 'VOCABULARY SIZE: ', vocabulary_size, 'SAMPLE', vocabulary[:10] vocabulary_size = 50000 # change so that you only take part of it. def build_dataset(vocabulary, vocabulary_size): """ To count the occurences of words and mark the most common words as UNKOWN /UNK""" count = [['UNK', -1]] # select the top common ones. count.extend(collections.Counter(vocabulary).most_common(vocabulary_size - 1)) print 'COUNT: ', count[:10] wordDictionary = {} # Build dictionary with name and count for word, _ in count: wordDictionary[word] = len(wordDictionary) data = [] unknown_count = 0 for word in vocabulary: index = wordDictionary.get(word, 0) # Rare words. TODO dig into this. if (index == 0): unknown_count += 1 data.append(index) count[0][1] = unknown_count reverseWordDictionary = dict(zip(wordDictionary.values(), wordDictionary.keys())) return data, count, wordDictionary, reverseWordDictionary # reverseWordDictionary => Index to Word mapping. # wordDictionary => Name to Index mapping # count = Top vocabulary_size-1 common words. (Unkown is one of them) # data = The original data mapped to integers. ( If there is a word that doesn't exist in the map; the data integer would be 0) data, count, wordDictionary, reverseWordDictionary = build_dataset(vocabulary, vocabulary_size) del vocabulary # Don't need the vocabulary any more. Since the dictionary are there. print 'MOST COMMON DATA: ', count[:10] print 'SAMPLE DATA: ', data[:10], [reverseWordDictionary.get(index) for index in data[:10]] data_index = 0 # global variable to keep track of till where the data was read last time. def generate_batch(batch_size, window_size): # TODO improve generating a batch by using some randomness in the process. """ Generate a batch for training from the dataset ( data ) :returns data: The data / center words. labels: the target/ context words. """ global data_index batch = np.ndarray((batch_size), dtype=np.int32) labels = np.ndarray((batch_size, 1), dtype=np.int32) current_batch_index = 0 for batch_index in range(batch_size): # These many elements are required in both the batch and labels. if data_index + 2 * window_size >= len(data): data_index = 0 center_word_index = data_index + window_size context_word_indices = [index for index in range(data_index, data_index + 2 * window_size + 1) if index != center_word_index] for context_word_index in context_word_indices: batch[current_batch_index] = data[center_word_index] labels[current_batch_index, 0] = data[context_word_index] current_batch_index += 1 if current_batch_index >= batch_size: break if current_batch_index >= batch_size: break # Shift the window by 1 data_index += 1 return batch, labels def skipgram(vocabulary_size=50000, embedding_size=128): """Run skip gram model for a dataset.""" batch_size = 128 # Run sufficient batch_size until the loss is minimized num_iterations = 100000 # loop for training. graph = tf.Graph() # To construct a tensorflow Graph with graph.as_default(): with tf.name_scope('inputs'): # Placeholders for inputs center word (Center words) => context words # (labels / what this model is trying to adjust to). train_inputs = tf.placeholder(tf.int32, shape=[batch_size]) train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1]) with tf.device('/cpu:0'): with tf.name_scope('embeddings'): # Get embedding embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], # Word vectors. -1.0, 1.0)) embed = tf.nn.embedding_lookup(embeddings, train_inputs) # Retrieve the embeddings for the input with tf.name_scope('weights'): nce_weights = tf.Variable(tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) with tf.name_scope('biases'): nce_biases = tf.Variable(tf.zeros([vocabulary_size])) with tf.name_scope('loss'): loss = tf.reduce_mean(tf.nn.nce_loss(weights=nce_weights, biases=nce_biases, labels=train_labels, inputs=embed, # Optimize these embeddings from num_sampled=64, # Number of negatives to sample. num_classes=vocabulary_size)) with tf.name_scope('optimizer'): optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss) with tf.Session(graph=graph) as session: tf.global_variables_initializer().run() for batch_num in xrange(num_iterations): inputs, labels = generate_batch(batch_size, window_size=1) _, current_loss, current_embeddings = session.run([optimizer, loss, embeddings], feed_dict={ train_inputs: inputs, train_labels: labels }) print 'LOSS', current_loss
43.181208
127
0.633976
""" Implementing word2vec using the skipgram model using a logistic regression as probability function. """ import tensorflow as tf import numpy as np import zipfile import math from . import directory_util, download import os import collections dataset_name = 'text8.zip' def read_data(filename): """ Step 1 Read data. """ filepath = os.path.join(directory_util.get_data_dir(), dataset_name) with zipfile.ZipFile(filepath) as f: print 'FILES IN THE ZIP: ', f.namelist() contents = f.read(f.namelist()[0]) try: print 'SAMPLE CONTENTS OF FILE', contents[:100] except: print '!!CANNOT PRINT SAMPLE' data = tf.compat.as_str(contents).split() # TODO what is package compat? return data download.download_data(dataset_name) vocabulary = read_data(dataset_name) vocabulary_size = len(vocabulary) # Taking all the words in the vocabulary! print 'VOCABULARY SIZE: ', vocabulary_size, 'SAMPLE', vocabulary[:10] vocabulary_size = 50000 # change so that you only take part of it. def build_dataset(vocabulary, vocabulary_size): """ To count the occurences of words and mark the most common words as UNKOWN /UNK""" count = [['UNK', -1]] # select the top common ones. count.extend(collections.Counter(vocabulary).most_common(vocabulary_size - 1)) print 'COUNT: ', count[:10] wordDictionary = {} # Build dictionary with name and count for word, _ in count: wordDictionary[word] = len(wordDictionary) data = [] unknown_count = 0 for word in vocabulary: index = wordDictionary.get(word, 0) # Rare words. TODO dig into this. if (index == 0): unknown_count += 1 data.append(index) count[0][1] = unknown_count reverseWordDictionary = dict(zip(wordDictionary.values(), wordDictionary.keys())) return data, count, wordDictionary, reverseWordDictionary # reverseWordDictionary => Index to Word mapping. # wordDictionary => Name to Index mapping # count = Top vocabulary_size-1 common words. (Unkown is one of them) # data = The original data mapped to integers. ( If there is a word that doesn't exist in the map; the data integer would be 0) data, count, wordDictionary, reverseWordDictionary = build_dataset(vocabulary, vocabulary_size) del vocabulary # Don't need the vocabulary any more. Since the dictionary are there. print 'MOST COMMON DATA: ', count[:10] print 'SAMPLE DATA: ', data[:10], [reverseWordDictionary.get(index) for index in data[:10]] data_index = 0 # global variable to keep track of till where the data was read last time. def generate_batch(batch_size, window_size): # TODO improve generating a batch by using some randomness in the process. """ Generate a batch for training from the dataset ( data ) :returns data: The data / center words. labels: the target/ context words. """ global data_index batch = np.ndarray((batch_size), dtype=np.int32) labels = np.ndarray((batch_size, 1), dtype=np.int32) current_batch_index = 0 for batch_index in range(batch_size): # These many elements are required in both the batch and labels. if data_index + 2 * window_size >= len(data): data_index = 0 center_word_index = data_index + window_size context_word_indices = [index for index in range(data_index, data_index + 2 * window_size + 1) if index != center_word_index] for context_word_index in context_word_indices: batch[current_batch_index] = data[center_word_index] labels[current_batch_index, 0] = data[context_word_index] current_batch_index += 1 if current_batch_index >= batch_size: break if current_batch_index >= batch_size: break # Shift the window by 1 data_index += 1 return batch, labels def skipgram(vocabulary_size=50000, embedding_size=128): """Run skip gram model for a dataset.""" batch_size = 128 # Run sufficient batch_size until the loss is minimized num_iterations = 100000 # loop for training. graph = tf.Graph() # To construct a tensorflow Graph with graph.as_default(): with tf.name_scope('inputs'): # Placeholders for inputs center word (Center words) => context words # (labels / what this model is trying to adjust to). train_inputs = tf.placeholder(tf.int32, shape=[batch_size]) train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1]) with tf.device('/cpu:0'): with tf.name_scope('embeddings'): # Get embedding embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], # Word vectors. -1.0, 1.0)) embed = tf.nn.embedding_lookup(embeddings, train_inputs) # Retrieve the embeddings for the input with tf.name_scope('weights'): nce_weights = tf.Variable(tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) with tf.name_scope('biases'): nce_biases = tf.Variable(tf.zeros([vocabulary_size])) with tf.name_scope('loss'): loss = tf.reduce_mean(tf.nn.nce_loss(weights=nce_weights, biases=nce_biases, labels=train_labels, inputs=embed, # Optimize these embeddings from num_sampled=64, # Number of negatives to sample. num_classes=vocabulary_size)) with tf.name_scope('optimizer'): optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss) with tf.Session(graph=graph) as session: tf.global_variables_initializer().run() for batch_num in xrange(num_iterations): inputs, labels = generate_batch(batch_size, window_size=1) _, current_loss, current_embeddings = session.run([optimizer, loss, embeddings], feed_dict={ train_inputs: inputs, train_labels: labels }) print 'LOSS', current_loss
0
0
0
58b12136edc0e2b57e2f2ffb93b8c5cbc6d2086c
585
py
Python
09_Dividir_A_Conta.py
Bruna-Fernandes/Python
2af20ec86f202bebfd4e0647589ec3f8449534a7
[ "MIT" ]
null
null
null
09_Dividir_A_Conta.py
Bruna-Fernandes/Python
2af20ec86f202bebfd4e0647589ec3f8449534a7
[ "MIT" ]
null
null
null
09_Dividir_A_Conta.py
Bruna-Fernandes/Python
2af20ec86f202bebfd4e0647589ec3f8449534a7
[ "MIT" ]
null
null
null
# 09_Três amigos, Carlos, André e Felipe. decidiram rachar igualmente a conta de um bar. # Faça um algoritmo para ler o valor total da conta e imprimir quanto cada um deve # pagar, mas faça com que Carlos e André não paguem centavos. Ex: uma conta de # R$101,53 resulta em R$33,00 para Carlos, R$33,00 para André e R$35,53 para Felipe. conta = float(input('Qual o valor da conta? ')) carlos = int(conta / 3) andre = int(conta / 3) felipe = float(conta - (carlos + andre)) print('Carlos paga: %.2f '% (carlos)) print('André paga: %.2f '% (andre)) print('Felipe paga: %.2f '% (felipe))
45
88
0.697436
# 09_Três amigos, Carlos, André e Felipe. decidiram rachar igualmente a conta de um bar. # Faça um algoritmo para ler o valor total da conta e imprimir quanto cada um deve # pagar, mas faça com que Carlos e André não paguem centavos. Ex: uma conta de # R$101,53 resulta em R$33,00 para Carlos, R$33,00 para André e R$35,53 para Felipe. conta = float(input('Qual o valor da conta? ')) carlos = int(conta / 3) andre = int(conta / 3) felipe = float(conta - (carlos + andre)) print('Carlos paga: %.2f '% (carlos)) print('André paga: %.2f '% (andre)) print('Felipe paga: %.2f '% (felipe))
0
0
0
6881fedc7e7bedf8fde423a271c428047546c2be
1,067
py
Python
data_structure_and_algorithm/queue.py
KiwiShow/PythonWeb
a489bc2ab16f06f7cc4524bab6b45b2653bfb1bd
[ "MIT" ]
7
2018-02-24T13:41:21.000Z
2022-02-06T04:59:13.000Z
data_structure_and_algorithm/queue.py
KiwiShow/PythonWeb
a489bc2ab16f06f7cc4524bab6b45b2653bfb1bd
[ "MIT" ]
6
2018-02-25T11:50:42.000Z
2021-12-13T19:55:13.000Z
data_structure_and_algorithm/queue.py
KiwiShow/PythonWeb
a489bc2ab16f06f7cc4524bab6b45b2653bfb1bd
[ "MIT" ]
1
2018-03-01T02:43:15.000Z
2018-03-01T02:43:15.000Z
############################################## # head-1-2-3-4(tail) <---enqueue # dequeue---^ ############################################## # 测试函数 if __name__ == '__main__': # 运行测试函数 test() # 1 # 2 # 3 # 4 # None
17.209677
48
0.490159
class Node(): def __init__(self, element=None, next=None): self.element = element self.next = next def __repr__(self): return str(self.element) class Queue(): def __init__(self): self.head = Node() self.tail = self.head def is_empty(self): return self.head.next is None def enqueue(self, element): n = Node(element) self.tail.next = n self.tail = n def dequeue(self): node = self.head.next if not self.is_empty(): self.head.next = node.next return node ############################################## # head-1-2-3-4(tail) <---enqueue # dequeue---^ ############################################## # 测试函数 def test(): q = Queue() q.enqueue(1) q.enqueue(2) q.enqueue(3) q.enqueue(4) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) # 返回None,因为没数了 print(q.dequeue()) if __name__ == '__main__': # 运行测试函数 test() # 1 # 2 # 3 # 4 # None
626
-15
227
74fcc6382098f1d903f9a27769f4f2262b143190
48
py
Python
icevision/models/ultralytics/__init__.py
ai-fast-track/mantisshrimp
cc6d6a4a048f6ddda2782b6593dcd6b083a673e4
[ "Apache-2.0" ]
580
2020-09-10T06:29:57.000Z
2022-03-29T19:34:54.000Z
icevision/models/ultralytics/__init__.py
ai-fast-track/mantisshrimp
cc6d6a4a048f6ddda2782b6593dcd6b083a673e4
[ "Apache-2.0" ]
691
2020-09-05T03:08:34.000Z
2022-03-31T23:47:06.000Z
icevision/models/ultralytics/__init__.py
lgvaz/mantisshrimp2
743cb7df0dae7eb1331fc2bb66fc9ca09db496cd
[ "Apache-2.0" ]
105
2020-09-09T10:41:35.000Z
2022-03-25T17:16:49.000Z
from icevision.models.ultralytics import yolov5
24
47
0.875
from icevision.models.ultralytics import yolov5
0
0
0
52507f4aa2006d3e6c49c2504f3da3710bd987a9
315
py
Python
app/backend/users/forms.py
bounswe/bounswe2018group3
1214dd1531ddc72cb8c8bd1f21bd065ba0e158b0
[ "MIT" ]
8
2018-02-06T21:04:49.000Z
2019-02-23T21:14:00.000Z
app/backend/users/forms.py
bounswe/bounswe2018group3
1214dd1531ddc72cb8c8bd1f21bd065ba0e158b0
[ "MIT" ]
216
2018-02-10T12:35:01.000Z
2021-01-29T16:52:58.000Z
app/backend/users/forms.py
bounswe/bounswe2018group3
1214dd1531ddc72cb8c8bd1f21bd065ba0e158b0
[ "MIT" ]
3
2018-04-13T19:30:05.000Z
2019-02-23T21:14:34.000Z
from django import forms from .models import CustomUser
22.5
46
0.67619
from django import forms from .models import CustomUser class CustomUserCreationForm(forms.ModelForm): class Meta: model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(forms.ModelForm): class Meta: model = CustomUser fields = ('username', 'email')
0
214
46
3dca2dd05ffdf70e7f723e722e091626f3adeb67
1,215
py
Python
uecp/commands/__init__.py
chrko/uecp
8f82ac3311c82939688b095c5c546e6337f7075a
[ "MIT" ]
3
2021-11-26T10:32:17.000Z
2022-01-12T19:25:40.000Z
uecp/commands/__init__.py
chrko/python-uecp
8f82ac3311c82939688b095c5c546e6337f7075a
[ "MIT" ]
null
null
null
uecp/commands/__init__.py
chrko/python-uecp
8f82ac3311c82939688b095c5c546e6337f7075a
[ "MIT" ]
null
null
null
from uecp.commands.base import UECPCommand from uecp.commands.bidirectional import ( MessageAcknowledgementCommand, RequestCommand, ResponseCode, ) from uecp.commands.clock_control import ( RealTimeClockCorrectionSetCommand, RealTimeClockEnabledSetCommand, RealTimeClockSetCommand, ) from uecp.commands.control_n_setup import ( CommunicationMode, CommunicationModeSetCommand, DataSetSelectCommand, EncoderAddressSetCommand, SiteAddressSetCommand, SiteEncoderAddressSetCommandMode, ) from uecp.commands.mixins import InvalidDataSetNumber, InvalidProgrammeServiceNumber from uecp.commands.rds_control import ( RDSEnabledSetCommand, RDSLevelSetCommand, RDSPhaseSetCommand, ) from uecp.commands.rds_message import ( DecoderInformationSetCommand, InvalidNumberOfTransmissions, InvalidProgrammeIdentification, InvalidProgrammeServiceName, InvalidProgrammeTypeName, ProgrammeIdentificationSetCommand, ProgrammeServiceNameSetCommand, ProgrammeType, ProgrammeTypeNameSetCommand, ProgrammeTypeSetCommand, RadioText, RadioTextBufferConfiguration, RadioTextSetCommand, TrafficAnnouncementProgrammeSetCommand, )
28.928571
84
0.80823
from uecp.commands.base import UECPCommand from uecp.commands.bidirectional import ( MessageAcknowledgementCommand, RequestCommand, ResponseCode, ) from uecp.commands.clock_control import ( RealTimeClockCorrectionSetCommand, RealTimeClockEnabledSetCommand, RealTimeClockSetCommand, ) from uecp.commands.control_n_setup import ( CommunicationMode, CommunicationModeSetCommand, DataSetSelectCommand, EncoderAddressSetCommand, SiteAddressSetCommand, SiteEncoderAddressSetCommandMode, ) from uecp.commands.mixins import InvalidDataSetNumber, InvalidProgrammeServiceNumber from uecp.commands.rds_control import ( RDSEnabledSetCommand, RDSLevelSetCommand, RDSPhaseSetCommand, ) from uecp.commands.rds_message import ( DecoderInformationSetCommand, InvalidNumberOfTransmissions, InvalidProgrammeIdentification, InvalidProgrammeServiceName, InvalidProgrammeTypeName, ProgrammeIdentificationSetCommand, ProgrammeServiceNameSetCommand, ProgrammeType, ProgrammeTypeNameSetCommand, ProgrammeTypeSetCommand, RadioText, RadioTextBufferConfiguration, RadioTextSetCommand, TrafficAnnouncementProgrammeSetCommand, )
0
0
0
cf90a240367dd9fba022ba9cb79936025231d22d
4,963
py
Python
site_specific/animecon2016/management/commands/setup_animecon2016.py
japsu/tracontent
169fe84c49c1a30133e927f1be50abba171ebe68
[ "PostgreSQL", "Unlicense", "MIT" ]
null
null
null
site_specific/animecon2016/management/commands/setup_animecon2016.py
japsu/tracontent
169fe84c49c1a30133e927f1be50abba171ebe68
[ "PostgreSQL", "Unlicense", "MIT" ]
7
2020-11-26T18:41:07.000Z
2022-01-18T09:27:00.000Z
site_specific/animecon2016/management/commands/setup_animecon2016.py
tracon/tracontent
65bd8c15b7909a90ebe5ed28cbbf66683a4e3c2c
[ "MIT", "PostgreSQL", "Unlicense" ]
null
null
null
import os from datetime import datetime, timedelta, date from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core.files import File from django.core.management import call_command from django.core.management.base import BaseCommand from django.utils.timezone import now from ads.models import Banner from content.models import Page, Redirect, SiteSettings, BlogPost from resources.models import StyleSheet
33.761905
124
0.545235
import os from datetime import datetime, timedelta, date from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core.files import File from django.core.management import call_command from django.core.management.base import BaseCommand from django.utils.timezone import now from ads.models import Banner from content.models import Page, Redirect, SiteSettings, BlogPost from resources.models import StyleSheet class Command(BaseCommand): args = '' help = 'Setup Animecon 2016 site' def add_arguments(self, parser): parser.add_argument('domain', type=str) def handle(self, *args, **options): Setup(domain=options['domain']).setup() class Setup(object): def __init__(self, domain): self.domain = domain def setup(self): print(f'NOTE: Setting up Animecon 2016 site at {self.domain}') self.setup_site() self.setup_content() def setup_site(self): self.site, unused = Site.objects.get_or_create(domain=self.domain, name='Animecon 2016') def setup_content(self): t = now() self.site_settings, unused = SiteSettings.objects.get_or_create( site=self.site, defaults=dict( base_template='animecon2016_base.jade', page_template='animecon2016_page.jade', blog_index_template='animecon2016_blog_index.jade', blog_post_template='animecon2016_blog_post.jade', context_processor_code='site_specific.animecon2016.context_processors:animecon2016_context', ) ) if not self.site_settings.context_processor_code: self.site_settings.context_processor_code = 'site_specific.animecon2016.context_processors:animecon2016_context' self.site_settings.save() ordering = 0 for page_slug, page_title, child_pages in [ ('front-page', 'Dummy etusivu', []), # Outside fi subsite for technical reasons ('blog', 'Ajankohtaista', []), ('fi', 'Animecon 2016', [ ('front-page', 'Etusivu'), ('blog', 'Ajankohtaista'), # pseudo page for menu, actually taken over by blog ('tapahtuma', 'Tapahtuma'), ('ohjelma', 'Ohjelma'), ('liput', 'Liput'), ('yhteys', 'Ota yhteyttä!'), ]), ('en', 'Animecon 2016 in English', [ ('front-page', 'Front page'), ('event', 'Event'), ('program', 'Program'), ('tickets', 'Tickets'), ('contact', 'Contact us!'), ]), ]: ordering += 10 parent_page, unused = Page.objects.get_or_create( site=self.site, parent=None, slug=page_slug, defaults=dict( title=page_title, body=f'Placeholder for {page_slug}', public_from=t, visible_from=t, order=ordering, ) ) child_ordering = 0 for child_slug, child_title in child_pages: child_ordering += 10 child_page, unused = Page.objects.get_or_create( site=self.site, parent=parent_page, slug=child_slug, defaults=dict( title=child_title, body=f'Placeholder for {child_slug}', public_from=t, visible_from=t, order=child_ordering, ) ) programme_page = Page.objects.get(site=self.site, path='fi/ohjelma') programme_page.page_controller_code = 'site_specific.animecon2016.views:programme_page_controller' programme_page.override_page_template = 'animecon2016_programme_page.jade' programme_page.save() for path, target in [ ('admin', '/admin/'), ('fi', '/fi/front-page'), ('en', '/en/front-page'), ('front-page', '/fi/front-page'), ]: redirect, unused = Redirect.objects.get_or_create( site=self.site, path=path, defaults=dict( target=target ), ) for stylesheet_name in [ 'layout.css', 'style.css', 'usermenu.css', ]: stylesheet_path = os.path.join( os.path.dirname(__file__), '..', '..', 'static', 'animecon2016', 'css', stylesheet_name ) with open(stylesheet_path) as input_file: StyleSheet.ingest(input_file)
4,181
111
153
04c0e3b1a68066e78e3f5914a72a288687fde62e
4,255
py
Python
tests/fixtures.py
soupault/solt
50b064b398306ff0b21f8c39968e9201b697ddc1
[ "MIT" ]
null
null
null
tests/fixtures.py
soupault/solt
50b064b398306ff0b21f8c39968e9201b697ddc1
[ "MIT" ]
null
null
null
tests/fixtures.py
soupault/solt
50b064b398306ff0b21f8c39968e9201b697ddc1
[ "MIT" ]
null
null
null
import numpy as np __all__ = [ "img_2x2", "mask_2x2", "img_3x3_rgb", "img_3x3", "img_3x4", "mask_3x3", "mask_3x4", "img_5x5", "mask_5x5", "img_6x6", "img_6x6_lc", "img_6x6_rgb", "mask_6x6", "img_7x7", "cube_3x3x3", ] def img_2x2(): """ Generates a 2x2 grayscale image (uint8) Returns ------- out : ndarray 2x2x1 uint8 image """ return np.array([[1, 0], [1, 1]]).reshape((2, 2, 1)).astype(np.uint8) def mask_2x2(): """ Generates 2x2 mask (doesn't have the 3rd dimension compare to an image). Returns ------- out : ndarray 2x2 mask, uint8 """ return np.array([[1, 0], [0, 1]]).reshape((2, 2)).astype(np.uint8) def img_3x4(): """ Generates a grayscale image 3x4 Returns ------- out : ndarray 3x4x1 uint8 image """ img = np.array([[1, 1, 1, 0], [1, 0, 1, 1], [1, 1, 1, 1]]).reshape((3, 4, 1)).astype(np.uint8) * 255 return img def mask_3x4(): """ Generates a mask 3x4 Returns ------- out : ndarray 3x4 uint8 image """ mask = np.array([[0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 1, 0]]).reshape((3, 4)).astype(np.uint8) return mask def img_3x3(): """ Generates a grayscale image 3x4 Returns ------- out : ndarray 3x4x1 uint8 image """ img = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 1]]).reshape((3, 3, 1)).astype(np.uint8) return img def img_3x3_rgb(): """ Generates a grayscale image 3x4 Returns ------- out : ndarray 3x4x1 uint8 image """ img = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 1]]).reshape((3, 3, 1)).astype(np.uint8) return np.dstack((img, img, img)) * 255 def mask_3x3(): """ Generates a image+mask 3x4 Returns ------- out : ndarray 3x4 uint8 image """ mask = np.array([[1, 1, 1], [1, 1, 1], [0, 1, 1]]).reshape((3, 3)).astype(np.uint8) return mask def img_5x5(): """ Generates a gs image 5x5. It is all ones, besides the edges Returns ------- out : ndarray 5x5 uint8 image """ img = np.ones((5, 5, 1)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return img.astype(np.uint8) def mask_5x5(): """ Generates a mask 5x5. It is all ones, besides the edges Returns ------- out : ndarray 5x5 uint8 image """ img = np.ones((5, 5)) img[:, :2] = 2 img[:, -2:] = 2 img[:2, :] = 2 img[-2, :] = 2 return img.astype(np.uint8) def img_6x6(): """ Generates a gs image 5x5. It is all ones, besides the edges Returns ------- out : ndarray 6x6 uint8 image """ img = np.ones((6, 6, 1)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return img.astype(np.uint8) * 255 def img_7x7(): """ Generates a gs image 7x7. It is all ones, besides the edges Returns ------- out : ndarray 6x6 uint8 image """ img = np.ones((7, 7, 1)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return img.astype(np.uint8) * 255 def mask_6x6(): """ Generates a mask 6x6. It is all ones, besides the edges Returns ------- out : ndarray 3x5 uint8 image """ img = np.ones((6, 6)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return img.astype(np.uint8) def img_6x6_rgb(): """ Generates an RGB image 6x6. It is all 255, besides the edges Returns ------- out : ndarray 6x6 uint8 image """ img = np.ones((6, 6, 1)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return np.dstack((img, img, img)).astype(np.uint8) * 255 def img_6x6_lc(): """ Generates an RGB image 6x6. It is all 7x7, besides the edges (low contrast) Returns ------- out : ndarray 6x6 uint8 image """ img = np.ones((6, 6, 1)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return np.dstack((img, img, img)).astype(np.uint8) * 127
17.878151
104
0.490482
import numpy as np __all__ = [ "img_2x2", "mask_2x2", "img_3x3_rgb", "img_3x3", "img_3x4", "mask_3x3", "mask_3x4", "img_5x5", "mask_5x5", "img_6x6", "img_6x6_lc", "img_6x6_rgb", "mask_6x6", "img_7x7", "cube_3x3x3", ] def img_2x2(): """ Generates a 2x2 grayscale image (uint8) Returns ------- out : ndarray 2x2x1 uint8 image """ return np.array([[1, 0], [1, 1]]).reshape((2, 2, 1)).astype(np.uint8) def mask_2x2(): """ Generates 2x2 mask (doesn't have the 3rd dimension compare to an image). Returns ------- out : ndarray 2x2 mask, uint8 """ return np.array([[1, 0], [0, 1]]).reshape((2, 2)).astype(np.uint8) def img_3x4(): """ Generates a grayscale image 3x4 Returns ------- out : ndarray 3x4x1 uint8 image """ img = np.array([[1, 1, 1, 0], [1, 0, 1, 1], [1, 1, 1, 1]]).reshape((3, 4, 1)).astype(np.uint8) * 255 return img def mask_3x4(): """ Generates a mask 3x4 Returns ------- out : ndarray 3x4 uint8 image """ mask = np.array([[0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 1, 0]]).reshape((3, 4)).astype(np.uint8) return mask def img_3x3(): """ Generates a grayscale image 3x4 Returns ------- out : ndarray 3x4x1 uint8 image """ img = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 1]]).reshape((3, 3, 1)).astype(np.uint8) return img def img_3x3_rgb(): """ Generates a grayscale image 3x4 Returns ------- out : ndarray 3x4x1 uint8 image """ img = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 1]]).reshape((3, 3, 1)).astype(np.uint8) return np.dstack((img, img, img)) * 255 def mask_3x3(): """ Generates a image+mask 3x4 Returns ------- out : ndarray 3x4 uint8 image """ mask = np.array([[1, 1, 1], [1, 1, 1], [0, 1, 1]]).reshape((3, 3)).astype(np.uint8) return mask def img_5x5(): """ Generates a gs image 5x5. It is all ones, besides the edges Returns ------- out : ndarray 5x5 uint8 image """ img = np.ones((5, 5, 1)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return img.astype(np.uint8) def cube_3x3x3(): return np.ones((3, 3, 3, 1)).astype(np.uint8) def mask_5x5(): """ Generates a mask 5x5. It is all ones, besides the edges Returns ------- out : ndarray 5x5 uint8 image """ img = np.ones((5, 5)) img[:, :2] = 2 img[:, -2:] = 2 img[:2, :] = 2 img[-2, :] = 2 return img.astype(np.uint8) def img_6x6(): """ Generates a gs image 5x5. It is all ones, besides the edges Returns ------- out : ndarray 6x6 uint8 image """ img = np.ones((6, 6, 1)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return img.astype(np.uint8) * 255 def img_7x7(): """ Generates a gs image 7x7. It is all ones, besides the edges Returns ------- out : ndarray 6x6 uint8 image """ img = np.ones((7, 7, 1)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return img.astype(np.uint8) * 255 def mask_6x6(): """ Generates a mask 6x6. It is all ones, besides the edges Returns ------- out : ndarray 3x5 uint8 image """ img = np.ones((6, 6)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return img.astype(np.uint8) def img_6x6_rgb(): """ Generates an RGB image 6x6. It is all 255, besides the edges Returns ------- out : ndarray 6x6 uint8 image """ img = np.ones((6, 6, 1)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return np.dstack((img, img, img)).astype(np.uint8) * 255 def img_6x6_lc(): """ Generates an RGB image 6x6. It is all 7x7, besides the edges (low contrast) Returns ------- out : ndarray 6x6 uint8 image """ img = np.ones((6, 6, 1)) img[:, 0] = 0 img[:, -1] = 0 img[0, :] = 0 img[-1, :] = 0 return np.dstack((img, img, img)).astype(np.uint8) * 127
46
0
23
fbfde656fba4fbe3f8de6a09fc45e35b6e589258
1,524
py
Python
root/ilikeit/RabbitMQCrashCourse/tutorials/publishsubscribe/emit_log.py
ChyiYaqing/chyidlTutorial
77e7f6f84f21537a58a8a8a42e31cf2e3dd31996
[ "MIT" ]
5
2018-10-17T05:57:39.000Z
2021-07-05T15:38:24.000Z
root/ilikeit/RabbitMQCrashCourse/tutorials/publishsubscribe/emit_log.py
ChyiYaqing/chyidlTutorial
77e7f6f84f21537a58a8a8a42e31cf2e3dd31996
[ "MIT" ]
2
2021-04-14T00:48:43.000Z
2021-04-14T02:20:50.000Z
root/ilikeit/RabbitMQCrashCourse/tutorials/publishsubscribe/emit_log.py
ChyiYaqing/chyidlTutorial
77e7f6f84f21537a58a8a8a42e31cf2e3dd31996
[ "MIT" ]
3
2019-03-02T14:36:19.000Z
2022-03-18T10:12:09.000Z
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ emit_log.py published log messages are going to be broadcast to all the receives """ # Pika is a pure-Python implementation of the AMQP 0-9-1 protocol import pika import sys # guest user can only connect via localhost #credentials = pika.PlainCredentials('guest', 'guest') credentials = pika.PlainCredentials('pi', 'macintosh') connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.31.156', port=5672, virtual_host='/', credentials=credentials)) channel = connection.channel() # declare the exchange channel.exchange_declare(exchange='logs', exchange_type='fanout') message = ' '.join(sys.argv[1:]) or "info: Hello World!" channel.basic_publish(exchange='logs', routing_key='', body=message, ) print("[x] Sent %r" %message) connection.close() """ Please keep in mind that this and other tutorials are, well, tutorials, They demonstrate one new concept at a time and may intentionally oversimplify some things and leave out others. For example topics such as connection management, error handling, connection recovery, concurrency and metric collection are largely omitted for the sake of brevity. Such simplified code should not be considered production ready. """
40.105263
126
0.62664
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ emit_log.py published log messages are going to be broadcast to all the receives """ # Pika is a pure-Python implementation of the AMQP 0-9-1 protocol import pika import sys # guest user can only connect via localhost #credentials = pika.PlainCredentials('guest', 'guest') credentials = pika.PlainCredentials('pi', 'macintosh') connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.31.156', port=5672, virtual_host='/', credentials=credentials)) channel = connection.channel() # declare the exchange channel.exchange_declare(exchange='logs', exchange_type='fanout') message = ' '.join(sys.argv[1:]) or "info: Hello World!" channel.basic_publish(exchange='logs', routing_key='', body=message, ) print("[x] Sent %r" %message) connection.close() """ Please keep in mind that this and other tutorials are, well, tutorials, They demonstrate one new concept at a time and may intentionally oversimplify some things and leave out others. For example topics such as connection management, error handling, connection recovery, concurrency and metric collection are largely omitted for the sake of brevity. Such simplified code should not be considered production ready. """
0
0
0
a32f0742cb04350a5e987b2f89ac96d7488514a9
686
py
Python
resources/solicit_token.py
jnbellinger/lta
b7cb3c65e0f167e56abb67f8283083aafd700e42
[ "MIT" ]
1
2019-07-30T16:03:26.000Z
2019-07-30T16:03:26.000Z
resources/solicit_token.py
jnbellinger/lta
b7cb3c65e0f167e56abb67f8283083aafd700e42
[ "MIT" ]
80
2019-01-10T21:46:43.000Z
2022-03-24T22:40:54.000Z
resources/solicit_token.py
jnbellinger/lta
b7cb3c65e0f167e56abb67f8283083aafd700e42
[ "MIT" ]
1
2018-12-10T21:13:11.000Z
2018-12-10T21:13:11.000Z
""" Ask the (testing) token service for a token. Run with `python -m lta.solicit_token`. """ import asyncio from rest_tools.client import RestClient # type: ignore from rest_tools.server import from_environment # type: ignore EXPECTED_CONFIG = { 'LTA_AUTH_ROLE': None, 'TOKEN_SERVICE_URL': None, } async def solicit_token(url, scope): """Obtain a service token from the token service.""" rc = RestClient(url, "") result = await rc.request("GET", f"/token?scope={scope}") print(result["access"]) if __name__ == '__main__': config = from_environment(EXPECTED_CONFIG) asyncio.run(solicit_token(config["TOKEN_SERVICE_URL"], config["LTA_AUTH_ROLE"]))
26.384615
84
0.708455
""" Ask the (testing) token service for a token. Run with `python -m lta.solicit_token`. """ import asyncio from rest_tools.client import RestClient # type: ignore from rest_tools.server import from_environment # type: ignore EXPECTED_CONFIG = { 'LTA_AUTH_ROLE': None, 'TOKEN_SERVICE_URL': None, } async def solicit_token(url, scope): """Obtain a service token from the token service.""" rc = RestClient(url, "") result = await rc.request("GET", f"/token?scope={scope}") print(result["access"]) if __name__ == '__main__': config = from_environment(EXPECTED_CONFIG) asyncio.run(solicit_token(config["TOKEN_SERVICE_URL"], config["LTA_AUTH_ROLE"]))
0
0
0
ce6b8693fb7f178920298e9524c0d231053f67ed
2,322
py
Python
examples/sentence_classifier/config_kim.py
GingerBear/texar
46e006f9349893a3015cd937bee9914c516e26af
[ "Apache-2.0" ]
2,325
2018-08-29T19:34:09.000Z
2022-03-26T18:11:58.000Z
examples/sentence_classifier/config_kim.py
GingerBear/texar
46e006f9349893a3015cd937bee9914c516e26af
[ "Apache-2.0" ]
183
2018-08-30T02:17:45.000Z
2022-02-23T13:53:58.000Z
examples/sentence_classifier/config_kim.py
GingerBear/texar
46e006f9349893a3015cd937bee9914c516e26af
[ "Apache-2.0" ]
421
2018-08-29T20:00:16.000Z
2022-03-08T13:32:03.000Z
# Copyright 2018 The Texar 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. """Sentence convolutional classifier config. This is (approximately) the config of the paper: (Kim) Convolutional Neural Networks for Sentence Classification https://arxiv.org/pdf/1408.5882.pdf """ # pylint: disable=invalid-name, too-few-public-methods, missing-docstring import copy num_epochs = 15 train_data = { "batch_size": 50, "datasets": [ { "files": "./data/sst2.train.sentences.txt", "vocab_file": "./data/sst2.vocab", # Discards samples with length > 56 "max_seq_length": 56, "length_filter_mode": "discard", # Do not append BOS/EOS tokens to the sentences "bos_token": "", "eos_token": "", "data_name": "x" }, { "files": "./data/sst2.train.labels.txt", "data_type": "int", "data_name": "y" } ] } # The val and test data have the same config with the train data, except # for the file names val_data = copy.deepcopy(train_data) val_data["datasets"][0]["files"] = "./data/sst2.dev.sentences.txt" val_data["datasets"][1]["files"] = "./data/sst2.dev.labels.txt" test_data = copy.deepcopy(train_data) test_data["datasets"][0]["files"] = "./data/sst2.test.sentences.txt" test_data["datasets"][1]["files"] = "./data/sst2.test.labels.txt" # Word embedding emb = { "dim": 300 } # Classifier clas = { "num_conv_layers": 1, "filters": 100, "kernel_size": [3, 4, 5], "conv_activation": "relu", "pooling": "MaxPooling1D", "num_dense_layers": 0, "dropout_conv": [1], "dropout_rate": 0.5, "num_classes": 2 } # Optimization # Just use the default config, e.g., Adam Optimizer opt = {}
29.769231
74
0.644703
# Copyright 2018 The Texar 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. """Sentence convolutional classifier config. This is (approximately) the config of the paper: (Kim) Convolutional Neural Networks for Sentence Classification https://arxiv.org/pdf/1408.5882.pdf """ # pylint: disable=invalid-name, too-few-public-methods, missing-docstring import copy num_epochs = 15 train_data = { "batch_size": 50, "datasets": [ { "files": "./data/sst2.train.sentences.txt", "vocab_file": "./data/sst2.vocab", # Discards samples with length > 56 "max_seq_length": 56, "length_filter_mode": "discard", # Do not append BOS/EOS tokens to the sentences "bos_token": "", "eos_token": "", "data_name": "x" }, { "files": "./data/sst2.train.labels.txt", "data_type": "int", "data_name": "y" } ] } # The val and test data have the same config with the train data, except # for the file names val_data = copy.deepcopy(train_data) val_data["datasets"][0]["files"] = "./data/sst2.dev.sentences.txt" val_data["datasets"][1]["files"] = "./data/sst2.dev.labels.txt" test_data = copy.deepcopy(train_data) test_data["datasets"][0]["files"] = "./data/sst2.test.sentences.txt" test_data["datasets"][1]["files"] = "./data/sst2.test.labels.txt" # Word embedding emb = { "dim": 300 } # Classifier clas = { "num_conv_layers": 1, "filters": 100, "kernel_size": [3, 4, 5], "conv_activation": "relu", "pooling": "MaxPooling1D", "num_dense_layers": 0, "dropout_conv": [1], "dropout_rate": 0.5, "num_classes": 2 } # Optimization # Just use the default config, e.g., Adam Optimizer opt = {}
0
0
0
3ca946b6325d9ecbaa1ac46ed1599756f09a9151
2,457
py
Python
LeetCode/Python3/Math/279. Perfect Squares.py
WatsonWangZh/CodingPractice
dc057dd6ea2fc2034e14fd73e07e73e6364be2ae
[ "MIT" ]
11
2019-09-01T22:36:00.000Z
2021-11-08T08:57:20.000Z
LeetCode/Python3/Math/279. Perfect Squares.py
WatsonWangZh/LeetCodePractice
dc057dd6ea2fc2034e14fd73e07e73e6364be2ae
[ "MIT" ]
null
null
null
LeetCode/Python3/Math/279. Perfect Squares.py
WatsonWangZh/LeetCodePractice
dc057dd6ea2fc2034e14fd73e07e73e6364be2ae
[ "MIT" ]
2
2020-05-27T14:58:52.000Z
2020-05-27T15:04:17.000Z
# Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. # Example 1: # Input: n = 12 # Output: 3 # Explanation: 12 = 4 + 4 + 4. # Example 2: # Input: n = 13 # Output: 2 # Explanation: 13 = 4 + 9. # 二刷 200627 # M1. 蛮力算法 TLE # M2. DP # M3. BFS
25.59375
125
0.448514
# Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. # Example 1: # Input: n = 12 # Output: 3 # Explanation: 12 = 4 + 4 + 4. # Example 2: # Input: n = 13 # Output: 2 # Explanation: 13 = 4 + 9. class Solution(object): def numSquares(self, n): """ :type n: int :rtype: int """ # M1. 普通DP O(n^1.5) # 令 dp[i] 表示通过平方数组成 i 所需要的最少数量。 # 则 dp[i]=min(dp[i−j∗j]+1),其中 1≤j≤i^0.5。 # dp[n] 即为最终答案。 dp = [n] * (n+1) dp[0] = 0 for i in range(1, n+1): j = 1 while j*j <= i: dp[i] = min(dp[i], dp[i-j*j]+1) j += 1 return dp[n] # 二刷 200627 # M1. 蛮力算法 TLE class Solution: def numSquares(self, n: int) -> int: square_nums = [i**2 for i in range(1, int(n**0.5)+1)] def minNumSquares(k): """ recursive solution """ # bottom cases: find a square number if k in square_nums: return 1 min_num = float('inf') # Find the minimal value among all possible solutions for square in square_nums: if k < square: break new_num = minNumSquares(k-square) + 1 min_num = min(min_num, new_num) return min_num return minNumSquares(n) # M2. DP class Solution: def numSquares(self, n: int) -> int: square_nums = [i**2 for i in range(1, int(n**0.5)+1)] dp = [i for i in range(n+1)] # bottom case dp[0] = 0 for i in range(1, n+1): for square in square_nums: if i < square: break dp[i] = min(dp[i], dp[i-square] + 1) return dp[-1] # M3. BFS class Solution: def numSquares(self, n: int) -> int: from collections import deque queue = deque([n]) step = 0 visited = set() while(queue): step += 1 for _ in range(len(queue)): tmp = queue.pop() for i in range(1, int(tmp**0.5)+1): x = tmp- i**2 if x == 0: return step if x not in visited: queue.appendleft(x) visited.add(x) return step
1,536
508
167
4b642531f4d2a435d10018cb459ade38ae6e1377
2,727
py
Python
eternity_backend_server/blueprints/datamin/detail_function/token_parse.py
Eternity-labs/eternity-backend-server
3159326a0277e37b8fa74e747e8e13934d1bccc2
[ "Apache-2.0" ]
null
null
null
eternity_backend_server/blueprints/datamin/detail_function/token_parse.py
Eternity-labs/eternity-backend-server
3159326a0277e37b8fa74e747e8e13934d1bccc2
[ "Apache-2.0" ]
null
null
null
eternity_backend_server/blueprints/datamin/detail_function/token_parse.py
Eternity-labs/eternity-backend-server
3159326a0277e37b8fa74e747e8e13934d1bccc2
[ "Apache-2.0" ]
null
null
null
from bs4 import BeautifulSoup from lxml import etree import json # xpath需要定期更换,否则数据抓取不全 def overview_info_parse(parse_str:str = ''): """ 传入一个待解析的字符串 """ html_info = etree.HTML(parse_str,parser=None) try: #=======================开始解析字段======================= Price = html_info.xpath('string(//*[@id="ContentPlaceHolder1_tr_valuepertoken"]/div/div[1]/span)').strip() Fully_Diluted_Market_Cap = html_info.xpath('string(//*[@id="pricebutton"])').strip() Max_Total_Supply = html_info.xpath('string(//*[@id="ContentPlaceHolder1_divSummary"]/div[1]/div[1]/div/div[2]/div[2]/div[2]/span)').strip() Holders = html_info.xpath('string(//*[@id="ContentPlaceHolder1_tr_tokenHolders"]/div/div[2]/div)').strip() Transfers = ''# 在另一个接口当中才有这个数据 Volume_24H = html_info.xpath('string(//*[@id="tokenInfo"]/div/table/tbody/tr[1]/td[3])').strip() Market_Capitalization = html_info.xpath('string(//*[@id="tokenInfo"]/div/table/tbody/tr[2]/td[3])').strip() Circulating_Supply = html_info.xpath('string(//*[@id="tokenInfo"]/div/table/tbody/tr[3]/td[3])').strip() #=======================解析字段结束======================= except: return {'status':False, 'wrong_reason':"Error parsing the file, please change the XPATH parsing path."} Dict_info = { "status":True, "info_name":"basic information", "info_list":[{ "name": "Price", "value":Price },{ "name":"Fully_Diluted_Market_Cap", "value":Fully_Diluted_Market_Cap },{ "name":"Max_Total_Supply", "value":Max_Total_Supply },{ "name":"Holders", "value":Holders },{ "name":"Volume_24H", "value":Volume_24H },{ "name":"Market_Capitalization", "value":Market_Capitalization },{ "name":"Circulating_Supply", "value":Circulating_Supply }] } return json.dumps(Dict_info) def overview_info_transfers_parse(parse_str:str = ''): """ 传入一个待解析的字符串 """ soup = BeautifulSoup(parse_str,features="lxml") all_info_list = [] key_list = ['Txn_Hash','Method','time1','time2','From','To','Quantitiy'] for tr in soup.find_all("tr"): list_info = [] for i in tr.find_all("td"): if i.text != '': if "..." not in i.text: list_info.append(i.text) else: list_info.append(i.span['title']) if len(list_info) == 7: all_info_list.append(dict(zip(key_list,list_info))) return all_info_list
37.875
147
0.550422
from bs4 import BeautifulSoup from lxml import etree import json # xpath需要定期更换,否则数据抓取不全 def overview_info_parse(parse_str:str = ''): """ 传入一个待解析的字符串 """ html_info = etree.HTML(parse_str,parser=None) try: #=======================开始解析字段======================= Price = html_info.xpath('string(//*[@id="ContentPlaceHolder1_tr_valuepertoken"]/div/div[1]/span)').strip() Fully_Diluted_Market_Cap = html_info.xpath('string(//*[@id="pricebutton"])').strip() Max_Total_Supply = html_info.xpath('string(//*[@id="ContentPlaceHolder1_divSummary"]/div[1]/div[1]/div/div[2]/div[2]/div[2]/span)').strip() Holders = html_info.xpath('string(//*[@id="ContentPlaceHolder1_tr_tokenHolders"]/div/div[2]/div)').strip() Transfers = ''# 在另一个接口当中才有这个数据 Volume_24H = html_info.xpath('string(//*[@id="tokenInfo"]/div/table/tbody/tr[1]/td[3])').strip() Market_Capitalization = html_info.xpath('string(//*[@id="tokenInfo"]/div/table/tbody/tr[2]/td[3])').strip() Circulating_Supply = html_info.xpath('string(//*[@id="tokenInfo"]/div/table/tbody/tr[3]/td[3])').strip() #=======================解析字段结束======================= except: return {'status':False, 'wrong_reason':"Error parsing the file, please change the XPATH parsing path."} Dict_info = { "status":True, "info_name":"basic information", "info_list":[{ "name": "Price", "value":Price },{ "name":"Fully_Diluted_Market_Cap", "value":Fully_Diluted_Market_Cap },{ "name":"Max_Total_Supply", "value":Max_Total_Supply },{ "name":"Holders", "value":Holders },{ "name":"Volume_24H", "value":Volume_24H },{ "name":"Market_Capitalization", "value":Market_Capitalization },{ "name":"Circulating_Supply", "value":Circulating_Supply }] } return json.dumps(Dict_info) def overview_info_transfers_parse(parse_str:str = ''): """ 传入一个待解析的字符串 """ soup = BeautifulSoup(parse_str,features="lxml") all_info_list = [] key_list = ['Txn_Hash','Method','time1','time2','From','To','Quantitiy'] for tr in soup.find_all("tr"): list_info = [] for i in tr.find_all("td"): if i.text != '': if "..." not in i.text: list_info.append(i.text) else: list_info.append(i.span['title']) if len(list_info) == 7: all_info_list.append(dict(zip(key_list,list_info))) return all_info_list
0
0
0
043d655f3334a0feef5a5b9e28711c7249e3649c
281
py
Python
iot_api/user_api/schemas/app_keys_schema.py
dolfandringa/rolaguard_backend
d4df7b55fc001aa6e0499edcfa94bf1b1c63b084
[ "Apache-2.0" ]
null
null
null
iot_api/user_api/schemas/app_keys_schema.py
dolfandringa/rolaguard_backend
d4df7b55fc001aa6e0499edcfa94bf1b1c63b084
[ "Apache-2.0" ]
7
2020-05-05T20:10:59.000Z
2021-05-26T17:59:24.000Z
iot_api/user_api/schemas/app_keys_schema.py
dolfandringa/rolaguard_backend
d4df7b55fc001aa6e0499edcfa94bf1b1c63b084
[ "Apache-2.0" ]
1
2021-01-28T05:54:11.000Z
2021-01-28T05:54:11.000Z
from marshmallow import Schema, fields from marshmallow.validate import Length from iot_api.user_api.repository.AppKeysRepository import MAX_PER_ORGANIZATION
46.833333
93
0.83274
from marshmallow import Schema, fields from marshmallow.validate import Length from iot_api.user_api.repository.AppKeysRepository import MAX_PER_ORGANIZATION class AppKeysSchema(Schema): keys = fields.List(fields.Str(), required=True, validate=Length(1, MAX_PER_ORGANIZATION))
0
101
23
156b2a11a4f618e4547a8257ca33ab9c15ae88e3
924
py
Python
kubeyard/commands/build.py
socialwifi/kubeyard
094576e6ad4ff7b9eb419234a3392523cf9e2b18
[ "BSD-3-Clause" ]
16
2018-11-30T09:53:23.000Z
2020-06-07T16:36:10.000Z
kubeyard/commands/build.py
socialwifi/kubeyard
094576e6ad4ff7b9eb419234a3392523cf9e2b18
[ "BSD-3-Clause" ]
34
2018-12-17T15:22:16.000Z
2020-08-14T11:04:24.000Z
kubeyard/commands/build.py
socialwifi/kubeyard
094576e6ad4ff7b9eb419234a3392523cf9e2b18
[ "BSD-3-Clause" ]
4
2018-12-17T09:57:09.000Z
2020-05-14T11:16:34.000Z
import logging import shlex from kubeyard.commands.devel import BaseDevelCommand logger = logging.getLogger(__name__) class BuildCommand(BaseDevelCommand): """ Builds docker image required to run tests and deployment. Can be overridden in <project_dir>/sripts/build. If kubeyard is set up in development mode it uses minikube as docker host. """ custom_script_name = 'build' context_vars = ['image_context', 'docker_args']
35.538462
110
0.70671
import logging import shlex from kubeyard.commands.devel import BaseDevelCommand logger = logging.getLogger(__name__) class BuildCommand(BaseDevelCommand): """ Builds docker image required to run tests and deployment. Can be overridden in <project_dir>/sripts/build. If kubeyard is set up in development mode it uses minikube as docker host. """ custom_script_name = 'build' context_vars = ['image_context', 'docker_args'] def __init__(self, *, image_context, docker_args, **kwargs): super().__init__(**kwargs) self.image_context = image_context self.docker_args = docker_args or '' def run_default(self): image_context = self.image_context or "{0}/docker".format(self.project_dir) logger.info('Building image "{}"...'.format(self.image)) self.docker_with_output('build', '-t', self.image, *shlex.split(self.docker_args), image_context)
419
0
54
eca0a428d1caa2f9f94de70e2ac9e7901807a7f3
8,819
py
Python
misc_scripts/Check_Name_Synonym.py
pombase/legacy-eg-loader
1a324121325ffc3b9a4c15922f7a12756a9c3206
[ "Apache-2.0" ]
null
null
null
misc_scripts/Check_Name_Synonym.py
pombase/legacy-eg-loader
1a324121325ffc3b9a4c15922f7a12756a9c3206
[ "Apache-2.0" ]
null
null
null
misc_scripts/Check_Name_Synonym.py
pombase/legacy-eg-loader
1a324121325ffc3b9a4c15922f7a12756a9c3206
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python import MySQLdb as mdb import psycopg2 import psycopg2.extras import psycopg2.extensions from psycopg2 import OperationalError import sys import argparse parser = argparse.ArgumentParser(description='Generate an SQL file to update the ontology terms in the core database based on the matching terms in the ontology database.') parser.add_argument('--division', help="The EG division (eg EnsemblFungi)", default="EnsemblFungi") parser.add_argument('--species', help="The dataset species name (eg schizosaccharomyces_pombe)", default="schizosaccharomyces_pombe") parser.add_argument('--eg_release', type=int, help="EG release version (eg 21)", default=21) parser.add_argument('--e_release', type=int, help="Ensembl release version (eg 74)", default=74) parser.add_argument('--assembly', type=int, help="Species assembly (eg 2)", default=2) parser.add_argument('--chado_release', type=int, help="Chado dump version release number", default=41) parser.add_argument('--dbhost', help="Core database host", default="mysql-cluster-eg-prod-3.ebi.ac.uk") parser.add_argument('--dbport', type=int, help="Core database port", default=4243) parser.add_argument('--dbchadohost', help="Core database host", default="postgres-eg-pombe.ebi.ac.uk") parser.add_argument('--dbchadoport', type=int, help="Core database port", default=5432) parser.add_argument('--dbchadouser', help="Core database username", default="ensrw") parser.add_argument('--dbchadopass', help="Core database password", default="xxxxx") parser.add_argument('--file', help="Output file. Default is 'data/sql/update_gene_names_synonyms_test.sql'", default="data/sql/update_gene_names_synonyms_test.sql") args = parser.parse_args() division = args.division # 'EnsemblFungi' species = args.species # 'schizosaccharomyces_pombe' eg_release = args.eg_release # 18 e_release = args.e_release # 71 chado_release = args.chado_release # 35 assembly = args.assembly # 2 sppdb = species + "_core_" + str(eg_release) + "_" + str(e_release) + "_" + str(assembly) chadodb = 'pombase_chado_v' + str(args.chado_release) pguser = args.dbchadouser pgpass = args.dbchadopass conp = None conm = None chado = dict() eg = dict() print args.dbchadohost, args.dbchadoport, chadodb try: conp = psycopg2.connect(host=args.dbchadohost, port=args.dbchadoport, user=args.dbchadouser, password=args.dbchadopass, database=chadodb) cur = conp.cursor() cur.execute("SELECT feature.name, feature.uniquename, ARRAY_TO_STRING(ARRAY_AGG(synonym.name),',') FROM feature JOIN organism on (feature.organism_id=organism.organism_id) JOIN cvterm ON (feature.type_id=cvterm.cvterm_id) JOIN cv on (cvterm.cv_id=cv.cv_id) LEFT JOIN feature_synonym ON feature.feature_id=feature_synonym.feature_id LEFT JOIN synonym ON feature_synonym.synonym_id=synonym.synonym_id WHERE cvterm.name in ('gene', 'pseudogene') AND cv.name='sequence' AND organism.genus || '_' || organism.species = '" + species.capitalize() + "' GROUP BY feature.name, feature.uniquename;") rows = cur.fetchall() cur.close() for row in rows: stable_id = row[1] name = row[0] if name == None: name = stable_id synonym = row[2] if synonym == None: synonym = '' else: synonym = row[2].split(',') chado[stable_id] = {'name': name, 'synonyms':synonym} except Exception, e: print "PostgreSQL Error %s: %s" % (e.pgcode,e.pgerror) print e sys.exit(1) finally: if conp: conp.close() #fi = open('/homes/mcdowall/Documents/Code/python/Spombe_EG17_GeneName_Synonym_v33.tsv', 'r') #for line in fi: # line = line.replace('\n', '') # sline = line.split('\t') # eg[sline[1]] = {'name': sline[0], 'synonyms':sline[2].split(',')} #fi.close() print args.dbhost, args.dbport, sppdb try: conm = mdb.connect(host=args.dbhost, port=args.dbport, user='ensro', db=sppdb) cur = conm.cursor() #cur.execute('UPDATE xref JOIN gene ON (gene.stable_id=xref.dbprimary_acc) SET gene.display_xref_id=xref.xref_id WHERE external_db_id=50642;') cur.execute("SELECT xref.display_label, gene.stable_id, GROUP_CONCAT(external_synonym.synonym SEPARATOR ','), gene.display_xref_id FROM gene LEFT JOIN xref ON (gene.display_xref_id=xref.xref_id) LEFT JOIN external_synonym ON (xref.xref_id=external_synonym.xref_id) GROUP BY xref.display_label, gene.stable_id;") rows = cur.fetchall() cur.close() for row in rows: stable_id = row[1] name = row[0] if row[3] != None and name == '': name = stable_id elif row[3] == None: name = '' synonym = row[2] if synonym == None: synonym = '' else: synonym = row[2].split(',') eg[stable_id] = {'name': name, 'synonyms':synonym} except mdb.Error, e: print "MySQL Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) finally: if conm: conm.close() #print list(set(chado.keys()) - set(eg.keys())) #print list(set(eg.keys()) - set(chado.keys())) print 'Loading Update file ...' f = open(args.file, 'w') for k in chado.keys(): if (eg.has_key(k)): #if (chado[k]['name'] != eg[k]['name'] and chado[k]['name'] != ''): if (chado[k]['name'] != eg[k]['name']): print 'Name Diff:', k, chado[k]['name'], eg[k]['name'] f.write('# Name change for ' + k + ' from ' + eg[k]['name'] + ' to ' + chado[k]['name'] + "\n") if (eg[k]['name'] != ''): f.write('UPDATE gene, xref SET xref.display_label=\'' + chado[k]['name'] + '\' WHERE gene.display_xref_id=xref.xref_id AND gene.stable_id=\'' + k + '\'; # Was ' + eg[k]['name'] + "\n") else: f.write('INSERT INTO xref (external_db_id, dbprimary_acc, display_label, version, description, info_type) VALUES (50642, \'' + k + '\', \'' + chado[k]['name'] + '\', 0, \'' + k + '\', "DIRECT");' + "\n") #f.write('LAST_INSERT_ID();' + "\n") #f.write('UPDATE gene, xref SET gene.display_xref_id=LAST_INSERT_ID() WHERE gene.stable_id=\'' + k + '\'; # Was NULL' + "\n") #print 'UPDATE spombe_eg_gene__translation__main SET display_label_1074=\'' + chado[k]['name'] + '\', display_label_1074_r1=\'' + chado[k]['name'] + '\' WHERE stable_id_1023=\'' + k + '\';' #print 'UPDATE spombe_eg_gene__transcript__main SET display_label_1074=\'' + chado[k]['name'] + '\', display_label_1074_r1=\'' + chado[k]['name'] + '\' WHERE stable_id_1023=\'' + k + '\';' #print 'UPDATE spombe_eg_gene__ox_pombase_gene__dm SET display_label_1074=\'' + chado[k]['name'] + '\' WHERE dbprimary_acc_1074=\'' + k + '\';' #print 'UPDATE spombe_eg_gene__ox_pombase_gene_name__dm SET display_label_1074=\'' + chado[k]['name'] + '\' WHERE dbprimary_acc_1074=\'' + k + '\';' #print 'UPDATE spombe_eg_gene__gene__main SET display_label_1074=\'' + chado[k]['name'] + '\' WHERE stable_id_1023=\'' + k + '\';' setdiff = set(chado[k]['synonyms'])^set(eg[k]['synonyms']) if (len(setdiff) > 0): #print '# Synonyms for ' + k if (chado[k]['name'] != eg[k]['name'] and eg[k]['name'] != '' and chado[k]['name'] in set(eg[k]['synonyms'])): f.write('UPDATE gene, xref, external_synonym SET external_synonym.synonym=\'' + eg[k]['name'] + '\' WHERE external_synonym.synonym=\'' + chado[k]['name'] + '\' AND gene.display_xref_id=xref.xref_id AND xref.xref_id=external_synonym.xref_id AND gene.stable_id=\'' + k + '\'; # Was ' + chado[k]['name'] + "\n") for s in set(chado[k]['synonyms'])-set(eg[k]['synonyms']): if ((chado[k]['name'] != eg[k]['name'] and chado[k]['name'] in set(eg[k]['synonyms'])) or s==''): continue f.write('INSERT INTO external_synonym SELECT xref.xref_id, \'' + s + '\' FROM gene, xref WHERE gene.display_xref_id=xref.xref_id AND gene.stable_id=\'' + k + '\';' + "\n") for s in set(eg[k]['synonyms'])-set(chado[k]['synonyms']): if (s==k or s=='' or (chado[k]['name'] != eg[k]['name'] and chado[k]['name'] in set(eg[k]['synonyms']))): continue f.write('DELETE external_synonym.* FROM xref JOIN external_synonym ON (xref.xref_id=external_synonym.xref_id) WHERE external_synonym.synonym=\'' + s + '\' AND gene.stable_id=\'' + k + '\';' + "\n") #print 'Synonym Diff:', k, '|', chado[k]['name'], eg[k]['name'], '|', chado[k]['synonyms'], eg[k]['synonyms'] f.write('UPDATE xref JOIN gene ON (gene.stable_id=xref.dbprimary_acc) SET gene.display_xref_id=xref.xref_id WHERE external_db_id=50642;') #Make sure that all genes that have a gene name is also reflected in the name of th etranscript f.write('update gene join transcript using (gene_id) join xref x1 on (gene.display_xref_id=x1.xref_id) join xref x2 on (transcript.display_xref_id=x2.xref_id) set x2.display_label=x1.display_label where x1.dbprimary_acc!=x1.display_label and x1.display_label!=x2.display_label;') f.close()
54.438272
591
0.666175
#!/usr/bin/python import MySQLdb as mdb import psycopg2 import psycopg2.extras import psycopg2.extensions from psycopg2 import OperationalError import sys import argparse parser = argparse.ArgumentParser(description='Generate an SQL file to update the ontology terms in the core database based on the matching terms in the ontology database.') parser.add_argument('--division', help="The EG division (eg EnsemblFungi)", default="EnsemblFungi") parser.add_argument('--species', help="The dataset species name (eg schizosaccharomyces_pombe)", default="schizosaccharomyces_pombe") parser.add_argument('--eg_release', type=int, help="EG release version (eg 21)", default=21) parser.add_argument('--e_release', type=int, help="Ensembl release version (eg 74)", default=74) parser.add_argument('--assembly', type=int, help="Species assembly (eg 2)", default=2) parser.add_argument('--chado_release', type=int, help="Chado dump version release number", default=41) parser.add_argument('--dbhost', help="Core database host", default="mysql-cluster-eg-prod-3.ebi.ac.uk") parser.add_argument('--dbport', type=int, help="Core database port", default=4243) parser.add_argument('--dbchadohost', help="Core database host", default="postgres-eg-pombe.ebi.ac.uk") parser.add_argument('--dbchadoport', type=int, help="Core database port", default=5432) parser.add_argument('--dbchadouser', help="Core database username", default="ensrw") parser.add_argument('--dbchadopass', help="Core database password", default="xxxxx") parser.add_argument('--file', help="Output file. Default is 'data/sql/update_gene_names_synonyms_test.sql'", default="data/sql/update_gene_names_synonyms_test.sql") args = parser.parse_args() division = args.division # 'EnsemblFungi' species = args.species # 'schizosaccharomyces_pombe' eg_release = args.eg_release # 18 e_release = args.e_release # 71 chado_release = args.chado_release # 35 assembly = args.assembly # 2 sppdb = species + "_core_" + str(eg_release) + "_" + str(e_release) + "_" + str(assembly) chadodb = 'pombase_chado_v' + str(args.chado_release) pguser = args.dbchadouser pgpass = args.dbchadopass conp = None conm = None chado = dict() eg = dict() print args.dbchadohost, args.dbchadoport, chadodb try: conp = psycopg2.connect(host=args.dbchadohost, port=args.dbchadoport, user=args.dbchadouser, password=args.dbchadopass, database=chadodb) cur = conp.cursor() cur.execute("SELECT feature.name, feature.uniquename, ARRAY_TO_STRING(ARRAY_AGG(synonym.name),',') FROM feature JOIN organism on (feature.organism_id=organism.organism_id) JOIN cvterm ON (feature.type_id=cvterm.cvterm_id) JOIN cv on (cvterm.cv_id=cv.cv_id) LEFT JOIN feature_synonym ON feature.feature_id=feature_synonym.feature_id LEFT JOIN synonym ON feature_synonym.synonym_id=synonym.synonym_id WHERE cvterm.name in ('gene', 'pseudogene') AND cv.name='sequence' AND organism.genus || '_' || organism.species = '" + species.capitalize() + "' GROUP BY feature.name, feature.uniquename;") rows = cur.fetchall() cur.close() for row in rows: stable_id = row[1] name = row[0] if name == None: name = stable_id synonym = row[2] if synonym == None: synonym = '' else: synonym = row[2].split(',') chado[stable_id] = {'name': name, 'synonyms':synonym} except Exception, e: print "PostgreSQL Error %s: %s" % (e.pgcode,e.pgerror) print e sys.exit(1) finally: if conp: conp.close() #fi = open('/homes/mcdowall/Documents/Code/python/Spombe_EG17_GeneName_Synonym_v33.tsv', 'r') #for line in fi: # line = line.replace('\n', '') # sline = line.split('\t') # eg[sline[1]] = {'name': sline[0], 'synonyms':sline[2].split(',')} #fi.close() print args.dbhost, args.dbport, sppdb try: conm = mdb.connect(host=args.dbhost, port=args.dbport, user='ensro', db=sppdb) cur = conm.cursor() #cur.execute('UPDATE xref JOIN gene ON (gene.stable_id=xref.dbprimary_acc) SET gene.display_xref_id=xref.xref_id WHERE external_db_id=50642;') cur.execute("SELECT xref.display_label, gene.stable_id, GROUP_CONCAT(external_synonym.synonym SEPARATOR ','), gene.display_xref_id FROM gene LEFT JOIN xref ON (gene.display_xref_id=xref.xref_id) LEFT JOIN external_synonym ON (xref.xref_id=external_synonym.xref_id) GROUP BY xref.display_label, gene.stable_id;") rows = cur.fetchall() cur.close() for row in rows: stable_id = row[1] name = row[0] if row[3] != None and name == '': name = stable_id elif row[3] == None: name = '' synonym = row[2] if synonym == None: synonym = '' else: synonym = row[2].split(',') eg[stable_id] = {'name': name, 'synonyms':synonym} except mdb.Error, e: print "MySQL Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) finally: if conm: conm.close() #print list(set(chado.keys()) - set(eg.keys())) #print list(set(eg.keys()) - set(chado.keys())) print 'Loading Update file ...' f = open(args.file, 'w') for k in chado.keys(): if (eg.has_key(k)): #if (chado[k]['name'] != eg[k]['name'] and chado[k]['name'] != ''): if (chado[k]['name'] != eg[k]['name']): print 'Name Diff:', k, chado[k]['name'], eg[k]['name'] f.write('# Name change for ' + k + ' from ' + eg[k]['name'] + ' to ' + chado[k]['name'] + "\n") if (eg[k]['name'] != ''): f.write('UPDATE gene, xref SET xref.display_label=\'' + chado[k]['name'] + '\' WHERE gene.display_xref_id=xref.xref_id AND gene.stable_id=\'' + k + '\'; # Was ' + eg[k]['name'] + "\n") else: f.write('INSERT INTO xref (external_db_id, dbprimary_acc, display_label, version, description, info_type) VALUES (50642, \'' + k + '\', \'' + chado[k]['name'] + '\', 0, \'' + k + '\', "DIRECT");' + "\n") #f.write('LAST_INSERT_ID();' + "\n") #f.write('UPDATE gene, xref SET gene.display_xref_id=LAST_INSERT_ID() WHERE gene.stable_id=\'' + k + '\'; # Was NULL' + "\n") #print 'UPDATE spombe_eg_gene__translation__main SET display_label_1074=\'' + chado[k]['name'] + '\', display_label_1074_r1=\'' + chado[k]['name'] + '\' WHERE stable_id_1023=\'' + k + '\';' #print 'UPDATE spombe_eg_gene__transcript__main SET display_label_1074=\'' + chado[k]['name'] + '\', display_label_1074_r1=\'' + chado[k]['name'] + '\' WHERE stable_id_1023=\'' + k + '\';' #print 'UPDATE spombe_eg_gene__ox_pombase_gene__dm SET display_label_1074=\'' + chado[k]['name'] + '\' WHERE dbprimary_acc_1074=\'' + k + '\';' #print 'UPDATE spombe_eg_gene__ox_pombase_gene_name__dm SET display_label_1074=\'' + chado[k]['name'] + '\' WHERE dbprimary_acc_1074=\'' + k + '\';' #print 'UPDATE spombe_eg_gene__gene__main SET display_label_1074=\'' + chado[k]['name'] + '\' WHERE stable_id_1023=\'' + k + '\';' setdiff = set(chado[k]['synonyms'])^set(eg[k]['synonyms']) if (len(setdiff) > 0): #print '# Synonyms for ' + k if (chado[k]['name'] != eg[k]['name'] and eg[k]['name'] != '' and chado[k]['name'] in set(eg[k]['synonyms'])): f.write('UPDATE gene, xref, external_synonym SET external_synonym.synonym=\'' + eg[k]['name'] + '\' WHERE external_synonym.synonym=\'' + chado[k]['name'] + '\' AND gene.display_xref_id=xref.xref_id AND xref.xref_id=external_synonym.xref_id AND gene.stable_id=\'' + k + '\'; # Was ' + chado[k]['name'] + "\n") for s in set(chado[k]['synonyms'])-set(eg[k]['synonyms']): if ((chado[k]['name'] != eg[k]['name'] and chado[k]['name'] in set(eg[k]['synonyms'])) or s==''): continue f.write('INSERT INTO external_synonym SELECT xref.xref_id, \'' + s + '\' FROM gene, xref WHERE gene.display_xref_id=xref.xref_id AND gene.stable_id=\'' + k + '\';' + "\n") for s in set(eg[k]['synonyms'])-set(chado[k]['synonyms']): if (s==k or s=='' or (chado[k]['name'] != eg[k]['name'] and chado[k]['name'] in set(eg[k]['synonyms']))): continue f.write('DELETE external_synonym.* FROM xref JOIN external_synonym ON (xref.xref_id=external_synonym.xref_id) WHERE external_synonym.synonym=\'' + s + '\' AND gene.stable_id=\'' + k + '\';' + "\n") #print 'Synonym Diff:', k, '|', chado[k]['name'], eg[k]['name'], '|', chado[k]['synonyms'], eg[k]['synonyms'] f.write('UPDATE xref JOIN gene ON (gene.stable_id=xref.dbprimary_acc) SET gene.display_xref_id=xref.xref_id WHERE external_db_id=50642;') #Make sure that all genes that have a gene name is also reflected in the name of th etranscript f.write('update gene join transcript using (gene_id) join xref x1 on (gene.display_xref_id=x1.xref_id) join xref x2 on (transcript.display_xref_id=x2.xref_id) set x2.display_label=x1.display_label where x1.dbprimary_acc!=x1.display_label and x1.display_label!=x2.display_label;') f.close()
0
0
0
cccb856461f5dee256e2947dd6c864b3a76229c4
8,123
py
Python
rlkit/torch/sets/models.py
jcoreyes/erl
43f4e8407967749f5364106163f3c5335eb7dc83
[ "MIT" ]
1
2020-10-23T14:40:09.000Z
2020-10-23T14:40:09.000Z
rlkit/torch/sets/models.py
jcoreyes/erl
43f4e8407967749f5364106163f3c5335eb7dc83
[ "MIT" ]
null
null
null
rlkit/torch/sets/models.py
jcoreyes/erl
43f4e8407967749f5364106163f3c5335eb7dc83
[ "MIT" ]
1
2021-05-27T20:38:45.000Z
2021-05-27T20:38:45.000Z
import numpy as np from torch import nn from rlkit.launchers.experiments.disentanglement import ( contextual_encoder_distance_launcher as cedl, ) from rlkit.torch.core import PyTorchModule from rlkit.torch.distributions import MultivariateDiagonalNormal from rlkit.torch.networks import ( BasicCNN, Flatten, Mlp, ConcatMultiHeadedMlp, Reshape, ) from rlkit.torch.networks import basic from rlkit.torch.networks.dcnn import BasicDCNN from rlkit.torch.networks.mlp import MultiHeadedMlp from rlkit.torch.networks.stochastic.distribution_generator import ( BernoulliGenerator, Gaussian, IndependentGenerator, ) from rlkit.torch.vae.vae_torch_trainer import VAE import rlkit.torch.pytorch_util as ptu from rlkit.torch.sets.fancy_vae_architecture import ( get_fancy_vae, )
33.987448
80
0.667857
import numpy as np from torch import nn from rlkit.launchers.experiments.disentanglement import ( contextual_encoder_distance_launcher as cedl, ) from rlkit.torch.core import PyTorchModule from rlkit.torch.distributions import MultivariateDiagonalNormal from rlkit.torch.networks import ( BasicCNN, Flatten, Mlp, ConcatMultiHeadedMlp, Reshape, ) from rlkit.torch.networks import basic from rlkit.torch.networks.dcnn import BasicDCNN from rlkit.torch.networks.mlp import MultiHeadedMlp from rlkit.torch.networks.stochastic.distribution_generator import ( BernoulliGenerator, Gaussian, IndependentGenerator, ) from rlkit.torch.vae.vae_torch_trainer import VAE import rlkit.torch.pytorch_util as ptu from rlkit.torch.sets.fancy_vae_architecture import ( get_fancy_vae, ) class DummyNetwork(PyTorchModule): def __init__(self, *output_shapes): super().__init__() self._output_shapes = output_shapes # if len(output_shapes) == 1: # self.output = ptu.zeros(output_shapes[0]) # else: # self.output = tuple( # ptu.zeros(shape) for shape in output_shapes # ) def forward(self, input): # import ipdb; ipdb.set_trace() if len(self._output_shapes) == 1: return ptu.zeros((input.shape[0], *self._output_shapes[0])) else: return tuple( ptu.zeros((input.shape[0], *shape)) for shape in self._output_shapes ) # return self.output def create_dummy_image_vae( img_chw, latent_dim, *args, **kwargs ) -> VAE: encoder_network = DummyNetwork((latent_dim,), (latent_dim,)) decoder_network = DummyNetwork(img_chw) encoder = Gaussian(encoder_network) decoder = Gaussian(decoder_network, std=1, reinterpreted_batch_ndims=3) prior = MultivariateDiagonalNormal( loc=ptu.zeros(1, latent_dim), scale_diag=ptu.ones(1, latent_dim), ) return VAE(encoder, decoder, prior) def create_image_vae( img_chw, latent_dim, encoder_cnn_kwargs, encoder_mlp_kwargs, decoder_mlp_kwargs=None, decoder_dcnn_kwargs=None, use_mlp_decoder=False, decoder_distribution="bernoulli", use_fancy_architecture=False, ) -> VAE: img_num_channels, img_height, img_width = img_chw if use_fancy_architecture: decoder_network, encoder_network = get_fancy_vae(img_height, img_num_channels, img_width, latent_dim) else: encoder_network = create_image_encoder( img_chw, latent_dim, encoder_cnn_kwargs, encoder_mlp_kwargs, ) if decoder_mlp_kwargs is None: decoder_mlp_kwargs = cedl.invert_encoder_mlp_params( encoder_mlp_kwargs ) if use_mlp_decoder: decoder_network = create_mlp_image_decoder( img_chw, latent_dim, decoder_mlp_kwargs, two_headed=decoder_distribution == 'gaussian_learned_variance', ) else: if decoder_distribution == "gaussian_learned_variance": raise NotImplementedError() pre_dcnn_chw = encoder_network._modules["0"].output_shape if decoder_dcnn_kwargs is None: decoder_dcnn_kwargs = cedl.invert_encoder_params( encoder_cnn_kwargs, img_num_channels, ) decoder_network = create_image_decoder( pre_dcnn_chw, latent_dim, decoder_dcnn_kwargs, decoder_mlp_kwargs, ) encoder = Gaussian(encoder_network) encoder.input_size = encoder_network.input_size if decoder_distribution in { "gaussian_learned_global_scalar_variance", "gaussian_learned_global_image_variance", "gaussian_learned_variance", }: if decoder_distribution == "gaussian_learned_global_image_variance": log_std = basic.LearnedPositiveConstant( ptu.zeros((img_num_channels, img_height, img_width)) ) decoder_network = basic.ApplyMany(decoder_network, log_std) elif decoder_distribution == "gaussian_learned_global_scalar_variance": log_std = basic.LearnedPositiveConstant(ptu.zeros(1)) decoder_network = basic.ApplyMany(decoder_network, log_std) decoder = Gaussian(decoder_network, reinterpreted_batch_ndims=3) elif decoder_distribution == "gaussian_fixed_unit_variance": decoder = Gaussian(decoder_network, std=1, reinterpreted_batch_ndims=3) elif decoder_distribution == "bernoulli": decoder = IndependentGenerator( BernoulliGenerator(decoder_network), reinterpreted_batch_ndims=3 ) else: raise NotImplementedError(decoder_distribution) prior = MultivariateDiagonalNormal( loc=ptu.zeros(1, latent_dim), scale_diag=ptu.ones(1, latent_dim), ) return VAE(encoder, decoder, prior) def create_image_encoder( img_chw, latent_dim, encoder_cnn_kwargs, encoder_kwargs, ): img_num_channels, img_height, img_width = img_chw cnn = BasicCNN( input_width=img_width, input_height=img_height, input_channels=img_num_channels, **encoder_cnn_kwargs ) cnn_output_size = np.prod(cnn.output_shape) mlp = MultiHeadedMlp( input_size=cnn_output_size, output_sizes=[latent_dim, latent_dim], **encoder_kwargs ) enc = nn.Sequential(cnn, Flatten(), mlp) enc.input_size = img_width * img_height * img_num_channels enc.output_size = latent_dim return enc def create_image_decoder( pre_dcnn_chw, latent_dim, decoder_dcnn_kwargs, decoder_kwargs, ): dcnn_in_channels, dcnn_in_height, dcnn_in_width = pre_dcnn_chw dcnn_input_size = dcnn_in_channels * dcnn_in_width * dcnn_in_height dcnn = BasicDCNN( input_width=dcnn_in_width, input_height=dcnn_in_height, input_channels=dcnn_in_channels, **decoder_dcnn_kwargs ) mlp = Mlp( input_size=latent_dim, output_size=dcnn_input_size, **decoder_kwargs ) dec = nn.Sequential(mlp, dcnn) dec.input_size = latent_dim return dec def create_mlp_image_decoder( img_chw, latent_dim, decoder_kwargs, two_headed, ): img_num_channels, img_height, img_width = img_chw output_size = img_num_channels * img_height * img_width if two_headed: dec = nn.Sequential( MultiHeadedMlp( input_size=latent_dim, output_sizes=[output_size, output_size], **decoder_kwargs ), basic.Map(Reshape(img_num_channels, img_height, img_width)), ) else: dec = nn.Sequential( Mlp( input_size=latent_dim, output_size=output_size, **decoder_kwargs ), Reshape(img_num_channels, img_height, img_width), ) dec.input_size = latent_dim dec.output_size = img_num_channels * img_height * img_width return dec def create_vector_vae(data_dim, latent_dim, encoder_kwargs): encoder = create_vector_encoder(data_dim, latent_dim, encoder_kwargs) decoder_kwargs = cedl.invert_encoder_mlp_params(encoder_kwargs) decoder = create_vector_decoder(data_dim, latent_dim, decoder_kwargs) prior = MultivariateDiagonalNormal( loc=ptu.zeros(1, latent_dim), scale_diag=ptu.ones(1, latent_dim), ) return VAE(encoder, decoder, prior) def create_vector_encoder(data_dim, latent_dim, encoder_kwargs): enc = ConcatMultiHeadedMlp( input_size=data_dim, output_sizes=[latent_dim, latent_dim], **encoder_kwargs ) enc.input_size = data_dim enc.output_size = latent_dim return enc def create_vector_decoder(data_dim, latent_dim, decoder_kwargs): dec = Mlp(input_size=latent_dim, output_size=data_dim, **decoder_kwargs) return dec
7,032
13
260
1962404f10e788ca65e007899f888e6147170f36
4,687
py
Python
src/MPLayout/Figure.py
csiegl182/MPLayout
68d7d30c38796e370e187f1b31ff70cd3e756162
[ "MIT" ]
null
null
null
src/MPLayout/Figure.py
csiegl182/MPLayout
68d7d30c38796e370e187f1b31ff70cd3e756162
[ "MIT" ]
null
null
null
src/MPLayout/Figure.py
csiegl182/MPLayout
68d7d30c38796e370e187f1b31ff70cd3e756162
[ "MIT" ]
null
null
null
import matplotlib import matplotlib.pyplot as mpl from dataclasses import dataclass from typing import Callable, List import os import numpy import pkg_resources ## @dataclass
36.617188
223
0.680393
import matplotlib import matplotlib.pyplot as mpl from dataclasses import dataclass from typing import Callable, List import os import numpy import pkg_resources def get_mplstyle_path(style: str): return pkg_resources.resource_filename('MPLayout', os.path.join('mplstyles', style + '.mplstyle')) def new_figure(style: str = 'default', num: int = 1, clear: bool = True, **kwargs): if num == 1: matplotlib.pyplot.close('all') else: matplotlib.pyplot.close(num) matplotlib.style.use(get_mplstyle_path(style)) fig, ax = mpl.subplots(num=num, clear=clear, **kwargs) fig.show() return fig, ax ## def change_ax_position(ax:mpl.axes, new_position:float, index:int): position = list(ax.get_position().bounds) position[index] = new_position ax.set_position(position) def set_axes_left_offset(ax:mpl.axes, offset:float): change_ax_position(ax, offset, 0) def set_axes_lower_offset(ax:mpl.axes, offset:float): change_ax_position(ax, offset, 1) def set_axes_width(ax:mpl.axes, width:float): change_ax_position(ax, width, 2) def set_axes_height(ax:mpl.axes, height:float): change_ax_position(ax, height, 3) def get_axes_left_offset(ax:mpl.axes) -> float: return ax.get_position().bounds[0] def get_axes_lower_offset(ax:mpl.axes) -> float: return ax.get_position().bounds[1] def align_axes(axes:List[mpl.axes], lower_limit:float, upper_limit:float, gap:float, set_axes_size:Callable[[mpl.axes], None], get_axes_offset:Callable[[mpl.axes], float], set_axes_offset:Callable[[mpl.axes, float], None]): def sort_axes(axes:List[mpl.axes], get_axes_offset:Callable[[mpl.axes], float]) -> List[mpl.axes]: offsets = [get_axes_offset(ax) for ax in axes] offsets_axes = list(zip(offsets, axes)) offsets_axes.sort(key=lambda x: x[0]) sorted_axes = [x[1] for x in offsets_axes] return sorted_axes num_axes = len(axes) total_size = upper_limit - lower_limit sum_gaps = (num_axes - 1) * gap axes_size = (total_size-sum_gaps)/num_axes for ax in axes: set_axes_size(ax, axes_size) axes = sort_axes(axes, get_axes_offset) offsets = numpy.arange(lower_limit, upper_limit, axes_size+gap) for ax, offset in zip(axes, offsets): set_axes_offset(ax, offset) @dataclass class GridLayout: x_min: float = 0.1 x_max: float = 0.9 y_min: float = 0.1 y_max: float = 0.9 x_gap: float = 0.05 y_gap: float = 0.05 def vertical_align_axes(axes:List[mpl.axes], grid_layout: GridLayout = GridLayout()): align_axes( axes=axes, lower_limit=grid_layout.y_min, upper_limit=grid_layout.y_max, gap=grid_layout.y_gap, set_axes_size=set_axes_height, get_axes_offset=get_axes_lower_offset, set_axes_offset=set_axes_lower_offset) def horizontal_align_axes(axes:List[mpl.axes], grid_layout: GridLayout = GridLayout()): align_axes( axes=axes, lower_limit=grid_layout.x_min, upper_limit=grid_layout.x_max, gap=grid_layout.x_gap, set_axes_size=set_axes_width, get_axes_offset=get_axes_left_offset, set_axes_offset=set_axes_left_offset) class Layouter: def __init__(self, nrows=1, ncols=1, num: int = 1, grid_layout: GridLayout = GridLayout(), style: str = 'default', **subplot_args): self.grid_layout = grid_layout self.fig, self.axes = new_figure(num=num, nrows=nrows, ncols=ncols, style=style, **subplot_args) if nrows == 1 and ncols == 1: self.axes = numpy.array(self.axes, ndmin=2) else: self.axes = self.axes.reshape((nrows, ncols)) for row in range(nrows): horizontal_align_axes(self.axes[row,:], grid_layout) for col in range(ncols): vertical_align_axes(self.axes[:,col], grid_layout) def layout(self, ax_fn: Callable[[mpl.axes], None], row=0, col=0): ax_fn(self.axes[row, col]) def layout_all(self, ax_fn: Callable[[mpl.axes], None]): for ax in self.axes.flatten(): ax_fn(ax) def layout_row(self, ax_fn: Callable[[mpl.axes], None], row=0): for ax in self.axes[row,:]: ax_fn(ax) def layout_col(self, ax_fn: Callable[[mpl.axes], None], col=0): for ax in self.axes[:,col]: ax_fn(ax) class Pool: def __init__(self, size: int = 1, grid_layout: GridLayout = GridLayout(), style: str = 'default', **subplot_args): self.figures = [Layouter(num=i, grid_layout=grid_layout, style=style, **subplot_args) for i in range(1, size+1)] def arange(self, begin_with: int = 1): pass def __getitem__(self, key: int): return self.figures[key]
3,824
123
561
7cfed758f72efd2d83f83aa742d1af06f10e7817
7,527
py
Python
senior/TBEFN/predict_TBEFN.py
LeiGitHub1024/lowlight
86649ae4275b8908d39561792a8068d391318f8d
[ "MIT" ]
null
null
null
senior/TBEFN/predict_TBEFN.py
LeiGitHub1024/lowlight
86649ae4275b8908d39561792a8068d391318f8d
[ "MIT" ]
null
null
null
senior/TBEFN/predict_TBEFN.py
LeiGitHub1024/lowlight
86649ae4275b8908d39561792a8068d391318f8d
[ "MIT" ]
null
null
null
""" # -*- coding:utf-8 -*- # @Time : 2019/5/4 20:24 # @Author : KUN LU @ SXU # @Email : lukun199@gmail.com # @Github : lukun199 """ from __future__ import division #import sys import os, time # import matplotlib.pyplot as plt import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np import glob import cv2 #from skimage.measure import compare_ssim as ssim #from skimage.measure import compare_psnr as psnr import argparse parser = argparse.ArgumentParser() parser.add_argument('--input', '-i',default='./test') parser.add_argument('--result', '-r',default='./res') args = parser.parse_args() checkpoint_dir = './ckpt/' # @lk199_sub1 input_dir = args.input result_dir = args.result print(tf.__version__) # 1.13.1 # -----------------------------------------#settings and preparations---------- sess = tf.Session() in_image = tf.placeholder(tf.float32, [None, None, None, 3]) gt_image = tf.placeholder(tf.float32, [None, None, None, 3]) # The channel dimension of the inputs should be defined. Found `None` uf_out = buildmodel(in_image) # =------------------------------updates-------------------------------- time_elapsed = 0 with tf.Session() as sess: saver = tf.compat.v1.train.Saver() ckpt = tf.train.get_checkpoint_state(checkpoint_dir) if ckpt: print('loaded ' + ckpt.model_checkpoint_path) saver.restore(sess, ckpt.model_checkpoint_path) # 恢复ckpt用于训练 # stats_graph(sess.graph) # --------------------------------------------------------------------# eval_fns = glob.glob(input_dir + '*.*') for N in range(len(eval_fns)): temp_train = np.array(cv2.imread(eval_fns[N])) # different!!! temp_train = temp_train/255.0 # ---------------------------------------------------------------------# train_data = temp_train.reshape(1, temp_train.shape[0], temp_train.shape[1], temp_train.shape[2]) st = time.time() [out] = sess.run([uf_out], feed_dict={in_image: train_data}) time_elapsed += time.time() - st print('%s' % eval_fns[N]) [_, name] = os.path.split(eval_fns[N]) suffix = name[name.find('.') + 1:] name = name[:name.find('.')] output = np.array(out[0]) output = output.reshape(output.shape[0], output.shape[1], output.shape[2]) output = output*255.0 output_rueslt = np.array(output) if not os.path.isdir(result_dir): os.makedirs(result_dir) cv2.imwrite(result_dir + name + '_TBEFN.png', output_rueslt) print('total processing time: ', time_elapsed)
41.585635
132
0.620433
""" # -*- coding:utf-8 -*- # @Time : 2019/5/4 20:24 # @Author : KUN LU @ SXU # @Email : lukun199@gmail.com # @Github : lukun199 """ from __future__ import division #import sys import os, time # import matplotlib.pyplot as plt import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np import glob import cv2 #from skimage.measure import compare_ssim as ssim #from skimage.measure import compare_psnr as psnr import argparse parser = argparse.ArgumentParser() parser.add_argument('--input', '-i',default='./test') parser.add_argument('--result', '-r',default='./res') args = parser.parse_args() checkpoint_dir = './ckpt/' # @lk199_sub1 input_dir = args.input result_dir = args.result print(tf.__version__) # 1.13.1 def out_acti(x): return tf.nn.relu(x)-tf.nn.relu(x-1.0) def denoise_net(input, name): # denoising, dense res linkage with tf.variable_scope(name): conv1_out = slim.conv2d(input, 3, [3, 3], rate=1, activation_fn=None, scope='di_conv1') conv2_in = conv1_out conv2_out = slim.conv2d(conv2_in, 3, [3, 3], rate=1, activation_fn=None, scope='di_conv2') conv3_in = conv1_out + conv2_out conv3_out = slim.conv2d(conv3_in, 3, [3, 3], rate=1, activation_fn=None, scope='di_conv3') conv4_in = conv3_in + conv3_out conv4_out = slim.conv2d(conv4_in, 3, [3, 3], rate=1, activation_fn=None, scope='di_conv4') conv5_in = conv4_in + conv4_out conv5_out = slim.conv2d(conv5_in, 3, [3, 3], rate=1, activation_fn=None, scope='di_conv5') return out_acti(input + conv5_out) def upsample_and_concat(x1, x2, output_channels, in_channels): #x2和out+channel一致。目的:x1卷积之后尺寸变大,维数变小;和x2一致。得�?*x2的输出,32�? with tf.variable_scope("us_vars"): pool_size = 2 deconv_filter = tf.Variable(tf.truncated_normal([pool_size, pool_size, output_channels, in_channels], stddev=0.02)) deconv = tf.nn.conv2d_transpose(x1, deconv_filter, tf.shape(x2), strides=[1, pool_size, pool_size, 1]) deconv_output = tf.concat([deconv, x2], 3) deconv_output.set_shape([None, None, None, output_channels * 2]) return deconv_output def simple_unet(input,name): #input_1 forward ; input_2 details. with tf.variable_scope(name): conv_1 = slim.conv2d(input, 3, [3, 3], rate=1, activation_fn=None, scope='pp_conv1') conv_2 = slim.conv2d(conv_1, 3, [3, 3], rate=1, activation_fn=None, scope='pp_conv2') conv_3 = slim.conv2d(conv_2, 3, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='pp_conv3') conv_4 = slim.conv2d(conv_3, 3, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='pp_conv4') #fusion fu_1 = tf.concat([input, conv_4], 3) # fu_2 = slim.conv2d(fu_1, 3, [3, 3], rate=1, activation_fn=None, scope='fu_conv') #不加了,此时U_net输入是一个6channel的东 conv1 = slim.conv2d(fu_1, 16, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='u_conv1') pool1 = slim.max_pool2d(conv1, [2, 2], padding='SAME') conv2 = slim.conv2d(pool1, 32, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='u_conv2') pool2 = slim.max_pool2d(conv2, [2, 2], padding='SAME') conv3 = slim.conv2d(pool2, 64, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='u_conv3') pool3 = slim.max_pool2d(conv3, [2, 2], padding='SAME') conv4 = slim.conv2d(pool3, 128, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='u_conv4') up5 = upsample_and_concat(conv4, conv3, 64, 128) conv5 = slim.conv2d(up5, 64, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='u_conv5') up6 = upsample_and_concat(conv5, conv2, 32, 64) conv6 = slim.conv2d(up6, 32, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='u_conv6') up7 = upsample_and_concat(conv6, conv1, 16, 32) conv7 = slim.conv2d(up7, 16, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='u_conv7') conv8 = slim.conv2d(conv7, 3, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='u_conv8') # modified lk199 return conv8 def fusion(input_1,input_2,name): with tf.variable_scope(name): fusion_in = tf.concat([input_1, input_2], 3) out_1 = slim.conv2d(fusion_in, 16, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='fusion_1') out_2 = slim.conv2d(out_1, 16, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='fusion_2') out_3 = slim.conv2d(out_2, 3, [3, 3], rate=1, activation_fn=None, scope='fusion_3') return out_3 def atten(input,name): with tf.variable_scope(name): out_1 = slim.conv2d(input, 16, [3, 3], rate=1, activation_fn=tf.nn.relu, scope='atten_1') out_2 = slim.conv2d(out_1, 16, [3, 3], padding='SAME', rate=2, activation_fn=tf.nn.relu, scope='atten_2') out_3 = slim.conv2d(out_2, 16, [3, 3], padding='SAME', rate=2, activation_fn=tf.nn.relu, scope='atten_3') out_4 = slim.conv2d(out_3, 1, [3, 3], rate=1, activation_fn=None, scope='atten_4') return out_acti(out_4) def buildmodel(sample): trans_fun_A_with_1E = simple_unet(sample, name='fun_est_A_with_1E') enhanced_1E = out_acti(sample * trans_fun_A_with_1E) denoised_in = denoise_net(sample, name='denoise_net') trans_fun_B_with_2E = simple_unet(denoised_in, name='fun_est_B_with_2E') enhanced_2E = out_acti(denoised_in * trans_fun_B_with_2E) atten_map = atten(sample, name='atten') fused = atten_map*enhanced_1E + (1-atten_map)*enhanced_2E enhanced = fusion(fused, sample, name='fusion') return enhanced # -----------------------------------------#settings and preparations---------- sess = tf.Session() in_image = tf.placeholder(tf.float32, [None, None, None, 3]) gt_image = tf.placeholder(tf.float32, [None, None, None, 3]) # The channel dimension of the inputs should be defined. Found `None` uf_out = buildmodel(in_image) # =------------------------------updates-------------------------------- time_elapsed = 0 with tf.Session() as sess: saver = tf.compat.v1.train.Saver() ckpt = tf.train.get_checkpoint_state(checkpoint_dir) if ckpt: print('loaded ' + ckpt.model_checkpoint_path) saver.restore(sess, ckpt.model_checkpoint_path) # 恢复ckpt用于训练 # stats_graph(sess.graph) # --------------------------------------------------------------------# eval_fns = glob.glob(input_dir + '*.*') for N in range(len(eval_fns)): temp_train = np.array(cv2.imread(eval_fns[N])) # different!!! temp_train = temp_train/255.0 # ---------------------------------------------------------------------# train_data = temp_train.reshape(1, temp_train.shape[0], temp_train.shape[1], temp_train.shape[2]) st = time.time() [out] = sess.run([uf_out], feed_dict={in_image: train_data}) time_elapsed += time.time() - st print('%s' % eval_fns[N]) [_, name] = os.path.split(eval_fns[N]) suffix = name[name.find('.') + 1:] name = name[:name.find('.')] output = np.array(out[0]) output = output.reshape(output.shape[0], output.shape[1], output.shape[2]) output = output*255.0 output_rueslt = np.array(output) if not os.path.isdir(result_dir): os.makedirs(result_dir) cv2.imwrite(result_dir + name + '_TBEFN.png', output_rueslt) print('total processing time: ', time_elapsed)
4,768
0
175
e3088fc35f45a82bc2737b6c54697ce8970a2605
6,686
py
Python
projetdrone-MissionControll/flightcommand.py
mariusweiler/raspberry-phantom2
39e9a85e6a9163618e4f49402f89dbdf6111dc9f
[ "MIT" ]
null
null
null
projetdrone-MissionControll/flightcommand.py
mariusweiler/raspberry-phantom2
39e9a85e6a9163618e4f49402f89dbdf6111dc9f
[ "MIT" ]
null
null
null
projetdrone-MissionControll/flightcommand.py
mariusweiler/raspberry-phantom2
39e9a85e6a9163618e4f49402f89dbdf6111dc9f
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # import des fonctions de temps pour attendre import time ## import de grovepi adresse 4 import grovepi ## import du grovepi adresse 3 import grovepi3 ## import de la division reele qui retourne un chiffre a virgule from operator import truediv ## fonction de stabilisation de la hauteur ## fonction de stabilisation de l avancement ## fonction de decollage ## fonction d aterrisage ## fonction de stabilisation complete
73.472527
410
0.71373
# -*- coding: utf-8 -*- # import des fonctions de temps pour attendre import time ## import de grovepi adresse 4 import grovepi ## import du grovepi adresse 3 import grovepi3 ## import de la division reele qui retourne un chiffre a virgule from operator import truediv class flightcommand: ## initialisation des variables de classe ## variable des valeurs PWM valeurmillieu=164; augmentationmax = 40; diminutionmax = 47; ## variables de pin grovepi hauteur=3; avancement=3; rotation=6; slide=5; ## fonction d'allumage et d'arret du drone qui envoie les commandes nécessaire à l'allumage du drone soit en bas à droite pour le joystick de gauche et en bas a gauche pour le joystick de droite def allumerEteindreDrone(self): self.avancementDrone(0,20); self.hauteurDrone(0,20); self.slideDrone(0,20); self.rotationDrone(1,20); ## fonction de rotation def rotationDrone(self,gauchedroite, force): ## en fonction de gauche/droite ou bas/haut (premier 0 second 1) if not gauchedroite: ## on envoie au drone une diminution ou augmentation de la valeur du millieu en fonction du sens, changement que l'on definit comme suit : valeurmin ou max * (force_demandée_entre_1_et_20) / 20) on utilise truediv car sans cela python ne prend pas en charge les virgules pour des int -> 0.5 = 0 grovepi.analogWrite(self.rotation,int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20))))) else: ## on envoie au drone une diminution ou augmentation de la valeur du millieu en fonction du sens, changement que l'on definit comme suit : valeurmin ou max * (force_demandée_entre_1_et_20) / 20) on utilise truediv car sans cela python ne prend pas en charge les virgules pour des int -> 0.5 = 0 grovepi.analogWrite(self.rotation,int(self.valeurmillieu+(self.augmentationmax*(truediv(force,20))))) ## fonction de stabilisation de la rotation def stabiliserRotation(self): grovepi.analogWrite(self.rotation,self.valeurmillieu) def slideDrone(self,gauchedroite, force): ## en fonction de gauche/droite ou bas/haut (premier 0 second 1) if gauchedroite: ## on envoie au drone une diminution ou augmentation de la valeur du millieu en fonction du sens, changement que l'on definit comme suit : valeurmin ou max * (force_demandée_entre_1_et_20) / 20) on utilise truediv car sans cela python ne prend pas en charge les virgules pour des int -> 0.5 = 0 grovepi.analogWrite(self.slide,int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20))))) else: ## on envoie au drone une diminution ou augmentation de la valeur du millieu en fonction du sens, changement que l'on definit comme suit : valeurmin ou max * (force_demandée_entre_1_et_20) / 20) on utilise truediv car sans cela python ne prend pas en charge les virgules pour des int -> 0.5 = 0 grovepi.analogWrite(self.slide,int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20))))) grovepi.analogWrite(self.slide,int(self.valeurmillieu+(self.augmentationmax*(truediv(force,20))))) ## fonction de stabilisation du slide def stabiliserSlide(self): grovepi.analogWrite(self.slide,self.valeurmillieu) def hauteurDrone(self,bashaut, force): ## en fonction de gauche/droite ou bas/haut (premier 0 second 1) if bashaut: ## on envoie au drone une diminution ou augmentation de la valeur du millieu en fonction du sens, changement que l'on definit comme suit : valeurmin ou max * (force_demandée_entre_1_et_20) / 20) on utilise truediv car sans cela python ne prend pas en charge les virgules pour des int -> 0.5 = 0 grovepi.analogWrite(self.slide,int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20))))) grovepi.analogWrite(self.hauteur,int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20))))); else: ## on envoie au drone une diminution ou augmentation de la valeur du millieu en fonction du sens, changement que l'on definit comme suit : valeurmin ou max * (force_demandée_entre_1_et_20) / 20) on utilise truediv car sans cela python ne prend pas en charge les virgules pour des int -> 0.5 = 0 grovepi.analogWrite(self.slide,int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20))))) grovepi.analogWrite(self.hauteur,int(self.valeurmillieu+(self.augmentationmax*(truediv(force,20))))) ## fonction de stabilisation de la hauteur def stabiliserHauteur(self): grovepi.analogWrite(self.hauteur,self.valeurmillieu) def avancementDrone(self,arriereavant, force): ## en fonction de gauche/droite ou bas/haut (premier 0 second 1) if not arriereavant: ## on envoie au drone une diminution ou augmentation de la valeur du millieu en fonction du sens, changement que l'on definit comme suit : valeurmin ou max * (force_demandée_entre_1_et_20) / 20) on utilise truediv car sans cela python ne prend pas en charge les virgules pour des int -> 0.5 = 0 grovepi.analogWrite(self.slide,int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20))))) valeur = int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20)))) grovepi3.analogWrite(self.avancement,valeur); else: ## on envoie au drone une diminution ou augmentation de la valeur du millieu en fonction du sens, changement que l'on definit comme suit : valeurmin ou max * (force_demandée_entre_1_et_20) / 20) on utilise truediv car sans cela python ne prend pas en charge les virgules pour des int -> 0.5 = 0 grovepi.analogWrite(self.slide,int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20))))) valeur = int(self.valeurmillieu+(self.augmentationmax*(truediv(force,20)))) grovepi3.analogWrite(self.avancement,valeur) ## fonction de stabilisation de l avancement def stabiliserAvancement(self): grovepi3.analogWrite(self.avancement,self.valeurmillieu) ## fonction de decollage def decollage(self,valeur): self.stabiliserAvancement(); self.stabiliserSlide(); self.stabiliserRotation(); self.hauteurDrone(1,valeur); ## fonction d aterrisage def atterrissage(self,valeur): self.stabiliserAvancement(); self.stabiliserSlide(); self.stabiliserRotation(); self.hauteurDrone(0,valeur); ## fonction de stabilisation complete def stabiliser(self): self.stabiliserAvancement(); self.stabiliserHauteur(); self.stabiliserSlide(); self.stabiliserRotation();
5,331
726
178
071c7bf9ca4121241e39992ae3d768dd0acc9c54
1,461
py
Python
pyvisdk/do/vm_port_group_profile.py
Infinidat/pyvisdk
f2f4e5f50da16f659ccc1d84b6a00f397fa997f8
[ "MIT" ]
null
null
null
pyvisdk/do/vm_port_group_profile.py
Infinidat/pyvisdk
f2f4e5f50da16f659ccc1d84b6a00f397fa997f8
[ "MIT" ]
null
null
null
pyvisdk/do/vm_port_group_profile.py
Infinidat/pyvisdk
f2f4e5f50da16f659ccc1d84b6a00f397fa997f8
[ "MIT" ]
null
null
null
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def VmPortGroupProfile(vim, *args, **kwargs): '''The VmPortGroupProfile data object represents the subprofile for a port group that will be used by virtual machines. Use the policy list for access to configuration data for the virtual machine port group profile. Use the property list for access to subprofiles, if any.vSphere Servers use Network managed objects to represent virtual machine port groups in the vSphere inventory.''' obj = vim.client.factory.create('{urn:vim25}VmPortGroupProfile') # do some validation checking... if (len(args) + len(kwargs)) < 6: raise IndexError('Expected at least 7 arguments got: %d' % len(args)) required = [ 'key', 'name', 'networkPolicy', 'vlan', 'vswitch', 'enabled' ] optional = [ 'policy', 'profileTypeName', 'profileVersion', 'property', 'dynamicProperty', 'dynamicType' ] for name, arg in zip(required+optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
38.447368
124
0.649555
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def VmPortGroupProfile(vim, *args, **kwargs): '''The VmPortGroupProfile data object represents the subprofile for a port group that will be used by virtual machines. Use the policy list for access to configuration data for the virtual machine port group profile. Use the property list for access to subprofiles, if any.vSphere Servers use Network managed objects to represent virtual machine port groups in the vSphere inventory.''' obj = vim.client.factory.create('{urn:vim25}VmPortGroupProfile') # do some validation checking... if (len(args) + len(kwargs)) < 6: raise IndexError('Expected at least 7 arguments got: %d' % len(args)) required = [ 'key', 'name', 'networkPolicy', 'vlan', 'vswitch', 'enabled' ] optional = [ 'policy', 'profileTypeName', 'profileVersion', 'property', 'dynamicProperty', 'dynamicType' ] for name, arg in zip(required+optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
0
0
0
46773800e04d8319548ed25ab2a1a3e42483700b
5,494
py
Python
src/app.py
rewindio/aws-es-update-notifier
0c4c8a9d2efac58046cfd7ba9e81f7f67d77e572
[ "MIT" ]
null
null
null
src/app.py
rewindio/aws-es-update-notifier
0c4c8a9d2efac58046cfd7ba9e81f7f67d77e572
[ "MIT" ]
null
null
null
src/app.py
rewindio/aws-es-update-notifier
0c4c8a9d2efac58046cfd7ba9e81f7f67d77e572
[ "MIT" ]
null
null
null
import json import boto3 from botocore.exceptions import ClientError import os from slack import WebClient from slack.errors import SlackApiError boto_session = boto3.session.Session() es_client = boto_session.client('es') ssm_client = boto_session.client('ssm') iam_client = boto_session.client('iam')
49.053571
174
0.442847
import json import boto3 from botocore.exceptions import ClientError import os from slack import WebClient from slack.errors import SlackApiError boto_session = boto3.session.Session() es_client = boto_session.client('es') ssm_client = boto_session.client('ssm') iam_client = boto_session.client('iam') def get_aws_account_alias(iam_client): account_alias = None try: account_alias = iam_client.list_account_aliases()['AccountAliases'][0] except ClientError as ex: print("Unable to get current aws account ID: {}".format(ex.response['Error']['Code'])) return account_alias def get_slack_token(ssm_client, token_path): param_val = None try: response = ssm_client.get_parameter(Name=token_path, WithDecryption=True) param_val = response['Parameter']['Value'] except ClientError as ex: print("Unable to retrieve parameter from parameter store: {}".format(ex.response['Error']['Code'])) return param_val def lambda_handler(event, context): domains = None try: domains = es_client.list_domain_names() except ClientError as ex: print("Unable to obtain list of ES domains: {}".format(ex.response['Error']['Code'])) if domains: for domain in domains['DomainNames']: domain_props = None domain_name = domain['DomainName'] print("ES Domain found " + domain_name + ". Checking for updates...") try: domain_props = es_client.describe_elasticsearch_domain(DomainName=domain_name) except ClientError as ex: print("Unable to describe domain: {}".format(ex.response['Error']['Code'])) if domain_props: update_available = domain_props['DomainStatus']['ServiceSoftwareOptions']['UpdateAvailable'] if update_available: print("Update is available for domain " + domain_name) current_version = domain_props['DomainStatus']['ServiceSoftwareOptions']['CurrentVersion'] update_version = domain_props['DomainStatus']['ServiceSoftwareOptions']['NewVersion'] domain_console_url = 'https://console.aws.amazon.com/es/home?region=' + boto_session.region_name + '#domain:resource=' + domain_name + ';action=dashboard' es_release_notes_url = 'https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/release-notes.html#release-table' slack_token = get_slack_token(ssm_client,os.environ['SLACK_TOKEN_SSM_PATH']) slack_channel = os.environ['SLACK_CHANNEL'] if slack_token: slack_client = WebClient(token=slack_token) try: response = slack_client.chat_postMessage( channel=slack_channel, blocks=[ { "type": "section", "text": { "type": "mrkdwn", "text": "A new ElasticSearch cluster update is available\n*<" + domain_console_url + "|" + domain_name + ">*" } }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*AWS Account:*\n" + get_aws_account_alias(iam_client) }, { "type": "mrkdwn", "text": "*Region:*\n" + boto_session.region_name }, { "type": "mrkdwn", "text": "*Current Version:*\n" + str(current_version) }, { "type": "mrkdwn", "text": "New Version:\n*<" + es_release_notes_url + "|" + str(update_version) + ">*" } ] } ] ) except SlackApiError as e: # You will get a SlackApiError if "ok" is False assert e.response["ok"] is False assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' print(f"Error posting to Slack: {e.response['error']}") else: print("No update available for domain " + domain_name)
5,121
0
69
bc6db2b6ef5b4593996b30437e553f766a7c65c4
719
py
Python
raiden/network/proxies/utils.py
tirkarthi/raiden
dbd03ddda039332b54ec0c02d81cbe1100bc8028
[ "MIT" ]
2,101
2016-06-01T11:31:49.000Z
2022-03-27T20:13:19.000Z
raiden/network/proxies/utils.py
tirkarthi/raiden
dbd03ddda039332b54ec0c02d81cbe1100bc8028
[ "MIT" ]
5,291
2016-06-01T18:14:04.000Z
2022-03-31T11:19:09.000Z
raiden/network/proxies/utils.py
tirkarthi/raiden
dbd03ddda039332b54ec0c02d81cbe1100bc8028
[ "MIT" ]
484
2016-06-01T18:21:06.000Z
2022-03-22T10:29:45.000Z
from raiden.exceptions import RaidenUnrecoverableError from raiden.utils.formatting import format_block_id from raiden.utils.typing import BlockIdentifier, NoReturn def raise_on_call_returned_empty(given_block_identifier: BlockIdentifier) -> NoReturn: """Format a message and raise RaidenUnrecoverableError.""" # We know that the given address has code because this is checked # in the constructor msg = ( f"Either the given address is for a different smart contract, " f"or the contract was not yet deployed at the block " f"{format_block_id(given_block_identifier)}. Either way this call " f"should never have happened." ) raise RaidenUnrecoverableError(msg)
42.294118
86
0.752434
from raiden.exceptions import RaidenUnrecoverableError from raiden.utils.formatting import format_block_id from raiden.utils.typing import BlockIdentifier, NoReturn def raise_on_call_returned_empty(given_block_identifier: BlockIdentifier) -> NoReturn: """Format a message and raise RaidenUnrecoverableError.""" # We know that the given address has code because this is checked # in the constructor msg = ( f"Either the given address is for a different smart contract, " f"or the contract was not yet deployed at the block " f"{format_block_id(given_block_identifier)}. Either way this call " f"should never have happened." ) raise RaidenUnrecoverableError(msg)
0
0
0
4e04886fa95c43d0eb8613ef4407b50921568a29
242
py
Python
Program File/WAP2.py
cyph3r-exe/python-practice-files
d95dd5eb14378c4f08fe4354d66356e3128de54e
[ "Apache-2.0" ]
null
null
null
Program File/WAP2.py
cyph3r-exe/python-practice-files
d95dd5eb14378c4f08fe4354d66356e3128de54e
[ "Apache-2.0" ]
null
null
null
Program File/WAP2.py
cyph3r-exe/python-practice-files
d95dd5eb14378c4f08fe4354d66356e3128de54e
[ "Apache-2.0" ]
null
null
null
#Debangshu Roy #WAP to add input no. in inches and display in cms to program list oldvalue = int(input("Enter your number in inches ")) inches(oldvalue)
24.2
66
0.698347
#Debangshu Roy #WAP to add input no. in inches and display in cms to program list def inches(value): cms = value*2.54 print("The given lenth in cms is ", cms) oldvalue = int(input("Enter your number in inches ")) inches(oldvalue)
63
0
24
e39369d60e9fa840b84e71d4c6b03e9664ebaa3c
95
py
Python
envdsys/envproject/apps.py
NOAA-PMEL/envDataSystem
4db4a3569d2329658799a3eef06ce36dd5c0597d
[ "Unlicense" ]
1
2021-11-06T19:22:53.000Z
2021-11-06T19:22:53.000Z
envdsys/envproject/apps.py
NOAA-PMEL/envDataSystem
4db4a3569d2329658799a3eef06ce36dd5c0597d
[ "Unlicense" ]
25
2019-06-18T20:40:36.000Z
2021-07-23T20:56:48.000Z
envdsys/envproject/apps.py
NOAA-PMEL/envDataSystem
4db4a3569d2329658799a3eef06ce36dd5c0597d
[ "Unlicense" ]
null
null
null
from django.apps import AppConfig
15.833333
34
0.768421
from django.apps import AppConfig class EnvprojectConfig(AppConfig): name = 'envproject'
0
37
23
616db53f745f376766e0e74de7ba9d7078ce39c4
3,090
py
Python
src/sentry/web/frontend/create_project.py
ChadKillingsworth/sentry
ffcb9007a95a83ee267935fe605f8ee8f03a85a5
[ "BSD-3-Clause" ]
null
null
null
src/sentry/web/frontend/create_project.py
ChadKillingsworth/sentry
ffcb9007a95a83ee267935fe605f8ee8f03a85a5
[ "BSD-3-Clause" ]
null
null
null
src/sentry/web/frontend/create_project.py
ChadKillingsworth/sentry
ffcb9007a95a83ee267935fe605f8ee8f03a85a5
[ "BSD-3-Clause" ]
null
null
null
from __future__ import absolute_import from django import forms from django.contrib import messages from django.core.urlresolvers import reverse from sentry.models import ( OrganizationMember, OrganizationMemberType, Project, Team ) from sentry.web.forms.add_project import AddProjectForm from sentry.web.frontend.base import OrganizationView ERR_NO_TEAMS = 'You cannot create a new project because there are no teams to assign it to.' # TODO(dcramer): I'm 95% certain the access is incorrect here as it would # be probably validating against global org access, and all we care about is # team admin
33.586957
95
0.654369
from __future__ import absolute_import from django import forms from django.contrib import messages from django.core.urlresolvers import reverse from sentry.models import ( OrganizationMember, OrganizationMemberType, Project, Team ) from sentry.web.forms.add_project import AddProjectForm from sentry.web.frontend.base import OrganizationView ERR_NO_TEAMS = 'You cannot create a new project because there are no teams to assign it to.' class AddProjectWithTeamForm(AddProjectForm): team = forms.ChoiceField(choices=(), required=True) class Meta: fields = ('name', 'team', 'platform') model = Project def __init__(self, user, team_list, *args, **kwargs): super(AddProjectWithTeamForm, self).__init__(*args, **kwargs) self.team_list = team_list self.fields['team'].choices = ( (t.slug, t.name) for t in team_list ) self.fields['team'].widget.choices = self.fields['team'].choices def clean_team(self): value = self.cleaned_data['team'] for team in self.team_list: if value == team.slug: return team return None def save(self, actor, ip_address): team = self.cleaned_data['team'] return super(AddProjectWithTeamForm, self).save(actor, team, ip_address) class CreateProjectView(OrganizationView): # TODO(dcramer): I'm 95% certain the access is incorrect here as it would # be probably validating against global org access, and all we care about is # team admin def get_form(self, request, organization, team_list): return AddProjectWithTeamForm(request.user, team_list, request.POST or None, initial={ 'team': request.GET.get('team'), }) def has_permission(self, request, organization): if organization is None: return False if request.user.is_superuser: return True # we special case permissions here as a team admin can create projects # but they are restricted to only creating projects on teams where they # are an admin return OrganizationMember.objects.filter( user=request.user, type__lte=OrganizationMemberType.ADMIN, ) def handle(self, request, organization): team_list = Team.objects.get_for_user( organization=organization, user=request.user, access=OrganizationMemberType.ADMIN, ) if not team_list: messages.error(request, ERR_NO_TEAMS) return self.redirect(reverse('sentry-organization-home', args=[organization.slug])) form = self.get_form(request, organization, team_list) if form.is_valid(): project = form.save(request.user, request.META['REMOTE_ADDR']) url = reverse('sentry-stream', args=[organization.slug, project.slug]) return self.redirect(url + '?newinstall=1') context = { 'form': form, } return self.respond('sentry/create-project.html', context)
2,073
269
126
d41f67967a99e1b1ab5280dcea22b87c5d6fe9df
750
py
Python
generate_files.py
sharkbound/advent_of_code_2016
e655974b2dea422af4ec1debad296ee6c22d690a
[ "MIT" ]
null
null
null
generate_files.py
sharkbound/advent_of_code_2016
e655974b2dea422af4ec1debad296ee6c22d690a
[ "MIT" ]
null
null
null
generate_files.py
sharkbound/advent_of_code_2016
e655974b2dea422af4ec1debad296ee6c22d690a
[ "MIT" ]
null
null
null
from builtins import SystemError from pathlib import Path from sys import argv from typing import Union if len(argv) == 1: day = int(input('day? ')) else: day = int(argv[1]) day_folder = Path(f'day{day}/') make_files(day_folder, 'data.txt', 'part1.py', 'part2.py', 'notes.md')
19.230769
70
0.606667
from builtins import SystemError from pathlib import Path from sys import argv from typing import Union if len(argv) == 1: day = int(input('day? ')) else: day = int(argv[1]) def make_files(day_folder: Path, *files: Union[str, Path]): if not day_folder.exists(): day_folder.mkdir(parents=True) for file in files: with open(day_folder / file, 'w') as f: if file.strip().lower() in {'part1.py', 'part2.py'}: f.write('''\ from read import read, read_lines def solve(data): pass def main(): data = read() solve(data) if __name__ == '__main__': main() ''') day_folder = Path(f'day{day}/') make_files(day_folder, 'data.txt', 'part1.py', 'part2.py', 'notes.md')
438
0
23
1f8e22688b05f6b5049e8f2cee683f3a0e997a60
2,660
py
Python
redbean/reactive/specs.py
lcgong/redbean
4e3a075567336db3f5469c5bc7dc009b5a24071c
[ "Apache-2.0" ]
4
2017-08-26T10:03:59.000Z
2022-02-17T20:46:02.000Z
redbean/reactive/specs.py
lcgong/redbean
4e3a075567336db3f5469c5bc7dc009b5a24071c
[ "Apache-2.0" ]
1
2018-06-04T10:57:28.000Z
2018-06-04T10:57:28.000Z
redbean/reactive/specs.py
lcgong/redbean
4e3a075567336db3f5469c5bc7dc009b5a24071c
[ "Apache-2.0" ]
null
null
null
import functools from typing import Callable, Awaitable, Any HandlerType = Callable[..., Awaitable[Any]] from .exceptions import UmountAction
28.602151
76
0.658271
import functools from typing import Callable, Awaitable, Any HandlerType = Callable[..., Awaitable[Any]] class ListenerSpec: __slots__ = ("topic_expr", "handler", "group_id") def __init__(self, topic_expr: str, handler: HandlerType): self.topic_expr = topic_expr self.handler = handler self.group_id = f"{handler.__module__}.{handler.__qualname__}" from .exceptions import UmountAction async def _unmounted_action(*args): raise UmountAction() class ActionSpec: __slots__ = ( "action_name", "handler", "group_id", "_topic_path", "_send_message" ) def __init__(self, action_name: str, handler: HandlerType): self.action_name = action_name self.handler = handler self.group_id = f"{handler.__module__}.{handler.__qualname__}" self._send_message = _unmounted_action def decorate(self): handler = self.handler async def _wrapped_executor(*args, **kwargs): result = await handler(*args, **kwargs) await self._send_message(result) return result return functools.update_wrapper(_wrapped_executor, handler) def mount(self, send_func): self._send_message = send_func class SQLBlockActionSpec: __slots__ = ( "action_name", "handler", "group_id", "_dbconn", "_prepare_message", "_commit_message", "_rollback_message" ) def __init__(self, action_name: str, handler: HandlerType, dbconn: Any): group_id = f"{handler.__module__}.{handler.__qualname__}" self.action_name = action_name self.handler = handler self.group_id = group_id self._dbconn = dbconn self._prepare_message = _unmounted_action self._commit_message = _unmounted_action self._rollback_message = _unmounted_action def decorate(self): handler = self.handler async def _wrapped_action(*args, **kwargs): @self._dbconn.transaction async def _transactional_action(*args, **kwargs): result = await handler(*args, **kwargs) await self._prepare_message(result) return result result = await _transactional_action(*args, **kwargs) # 事务已成功提交,待确认消息也已经发送,只待确认该消息 await self._commit_message() return result return functools.update_wrapper(_wrapped_action, handler) def mount(self, prepare_message, commit_message, rollback_message): self._prepare_message = prepare_message self._commit_message = commit_message self._rollback_message = rollback_message
1,974
498
91
e0551a7f555c95c837ea468ad85fe0295c3bb83b
16,157
py
Python
smore/models/beta.py
isabella232/smore
02e5a89e84a805eed632eefbdecd957d95e202d4
[ "Apache-2.0" ]
78
2021-10-31T23:20:26.000Z
2022-03-21T01:07:01.000Z
smore/models/beta.py
google-research/smore
e4ba95a7466ef7d018987bce7688b77bf2ea7e4f
[ "Apache-2.0" ]
4
2021-11-02T13:45:38.000Z
2022-02-17T04:18:32.000Z
smore/models/beta.py
pyg-team/smore
02e5a89e84a805eed632eefbdecd957d95e202d4
[ "Apache-2.0" ]
15
2021-11-02T23:55:29.000Z
2022-03-19T10:30:51.000Z
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import math from smore.models.kg_reasoning import KGReasoning from smore.common.modules import Regularizer from smore.common.embedding.sparse_embed import SparseEmbedding from smore.common.torchext.dist_func.beta_dist import BetaDist, beta_kl, beta_l2, beta_fisher_approx, naive_beta_fisher_approx, naive_beta_kl, naive_beta_l2 import torch.distributions.kl as torch_kl
52.288026
264
0.630129
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import math from smore.models.kg_reasoning import KGReasoning from smore.common.modules import Regularizer from smore.common.embedding.sparse_embed import SparseEmbedding from smore.common.torchext.dist_func.beta_dist import BetaDist, beta_kl, beta_l2, beta_fisher_approx, naive_beta_fisher_approx, naive_beta_kl, naive_beta_l2 import torch.distributions.kl as torch_kl class BetaIntersection(nn.Module): def __init__(self, dim, norm_mode, norm_param_flag): super(BetaIntersection, self).__init__() self.dim = dim self.norm_mode = norm_mode self.norm_param_flag = norm_param_flag if norm_mode == 'None' or not norm_param_flag: self.layers = nn.Parameter(torch.zeros(self.dim * 2 + self.dim + 2, 2 * self.dim)) if norm_mode == 'batch': self.register_buffer('running_mean', torch.zeros(2 * self.dim)) self.register_buffer('running_var', torch.ones(2 * self.dim)) self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long)) elif norm_mode in ['layer', 'batch']: self.layers = nn.Parameter(torch.zeros(self.dim * 2 + self.dim + 4, 2 * self.dim)) nn.init.ones_(self.layers[-2, :]) if norm_mode == 'batch': self.register_buffer('running_mean', torch.zeros(2 * self.dim)) self.register_buffer('running_var', torch.ones(2 * self.dim)) self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long)) nn.init.xavier_uniform_(self.layers[:self.dim*2 + self.dim, :]) def forward(self, alpha_embeddings, beta_embeddings): if self.norm_mode == 'None' or not self.norm_param_flag: w1, w2, b1, b2 = torch.split(self.layers, [self.dim * 2, self.dim, 1, 1], dim=0) if self.norm_mode in ['layer', 'batch']: w3 = None b3 = None if self.norm_mode == 'batch': exponential_average_factor = 0.1 if self.training: if self.num_batches_tracked is not None: self.num_batches_tracked += 1 bn_training = True else: bn_training = (self.running_mean is None) and (self.running_var is None) elif self.norm_mode in ['layer', 'batch']: w1, w2, b1, b2, w3, b3 = torch.split(self.layers, [self.dim * 2, self.dim, 1, 1, 1, 1], dim=0) w3 = w3[0] b3 = b3[0] if self.norm_mode == 'batch': exponential_average_factor = 0.1 if self.training: if self.num_batches_tracked is not None: self.num_batches_tracked += 1 bn_training = True else: bn_training = (self.running_mean is None) and (self.running_var is None) # print(w3) b2 = b2.view(2, -1)[0] all_embeddings = torch.cat([alpha_embeddings, beta_embeddings], dim=-1) if self.norm_mode == 'None': layer1_act = F.relu(F.linear(all_embeddings, w1, b1.view(-1))) # (num_conj, batch_size, 2 * dim) elif self.norm_mode == 'layer': layer1_act = F.relu(F.layer_norm(F.linear(all_embeddings, w1, b1.view(-1)), [2 * self.dim], w3, b3, 1e-5)) # (num_conj, batch_size, 2 * dim) elif self.norm_mode == 'batch': # print(F.linear(all_embeddings, w1, b1.view(-1)).shape) embedding_shape = list(all_embeddings.shape) layer1_act = F.relu(F.batch_norm(F.linear(all_embeddings, w1, b1.view(-1)).view([embedding_shape[0]*embedding_shape[1], -1]), self.running_mean, self.running_var, w3, b3, bn_training, exponential_average_factor, 1e-5)) # (num_conj, batch_size, 2 * dim) layer1_act = layer1_act.view([embedding_shape[0], embedding_shape[1], -1]) attention = F.softmax(F.linear(layer1_act, w2, b2), dim=0) # (num_conj, batch_size, dim) alpha_embedding = torch.sum(attention * alpha_embeddings, dim=0) beta_embedding = torch.sum(attention * beta_embeddings, dim=0) return alpha_embedding, beta_embedding class BetaProjection(nn.Module): def __init__(self, entity_dim, relation_dim, hidden_dim, projection_regularizer, num_layers, norm_mode, norm_param_flag): super(BetaProjection, self).__init__() self.entity_dim = entity_dim self.relation_dim = relation_dim self.hidden_dim = hidden_dim self.num_layers = num_layers self.norm_mode = norm_mode self.norm_param_flag = norm_param_flag assert num_layers >= 1 w_offset = self.entity_dim + self.relation_dim + (num_layers - 1) * self.hidden_dim + self.entity_dim self.num_last_bias = math.ceil(self.entity_dim / self.hidden_dim) assert self.num_last_bias * self.hidden_dim >= self.entity_dim if norm_mode == 'None' or not self.norm_param_flag: self.layers = nn.Parameter(torch.zeros(w_offset + num_layers + self.num_last_bias, self.hidden_dim)) self.nrows = [self.entity_dim + self.relation_dim] + [self.hidden_dim] * (self.num_layers - 1) + [self.entity_dim] + [1] * num_layers + [self.num_last_bias] self.bias_start = self.num_layers + 1 if norm_mode == 'batch': self.register_buffer('running_means', torch.zeros([num_layers, self.hidden_dim])) self.register_buffer('running_vars', torch.ones([num_layers, self.hidden_dim])) self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long)) elif norm_mode in ['layer', 'batch']: self.layers = nn.Parameter(torch.zeros(w_offset + num_layers + self.num_last_bias + num_layers * 2, self.hidden_dim)) nn.init.ones_(self.layers[w_offset + num_layers + self.num_last_bias:w_offset + num_layers + self.num_last_bias + num_layers]) self.nrows = [self.entity_dim + self.relation_dim] + [self.hidden_dim] * (self.num_layers - 1) + [self.entity_dim] + [1] * num_layers + [self.num_last_bias] + [1] * num_layers + [1] * num_layers self.bias_start = self.num_layers + 1 self.norm_weight_start = 2 * self.num_layers + 2 self.norm_bias_start = 3 * self.num_layers + 2 if norm_mode == 'batch': self.register_buffer('running_means', torch.zeros([num_layers, self.hidden_dim])) self.register_buffer('running_vars', torch.ones([num_layers, self.hidden_dim])) self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long)) nn.init.xavier_uniform_(self.layers[:w_offset, :]) assert sum(self.nrows) == self.layers.shape[0] self.projection_regularizer = projection_regularizer def forward(self, e_embedding, r_embedding): x = torch.cat([e_embedding, r_embedding], dim=-1) params = torch.split(self.layers, self.nrows, dim=0) if self.norm_mode == 'batch': exponential_average_factor = 0.1 if self.training: if self.num_batches_tracked is not None: self.num_batches_tracked += 1 bn_training = True else: bn_training = (self.running_means is None) and (self.running_vars is None) w0, b0 = params[0], params[self.bias_start].view(-1) if self.norm_mode == 'None': x = F.relu(torch.matmul(x, w0) + b0) elif self.norm_mode == 'layer': if not self.norm_param_flag: x = F.relu(F.layer_norm(torch.matmul(x, w0) + b0, [self.hidden_dim], None, None, 1e-5)) else: norm_w0, norm_b0 = params[self.norm_weight_start].view(-1), params[self.norm_bias_start].view(-1) x = F.relu(F.layer_norm(torch.matmul(x, w0) + b0, [self.hidden_dim], norm_w0, norm_b0, 1e-5)) elif self.norm_mode == 'batch': if not self.norm_param_flag: norm_w0, norm_b0 = None, None else: norm_w0, norm_b0 = params[self.norm_weight_start].view(-1), params[self.norm_bias_start].view(-1) x = F.relu(F.batch_norm(torch.matmul(x, w0) + b0, self.running_means[0], self.running_vars[0], norm_w0, norm_b0, bn_training, exponential_average_factor, 1e-5)) # print(norm_w0) for i in range(1, self.num_layers): wi, bi = params[i], params[self.bias_start + i].view(-1) if self.norm_mode == 'None': x = F.relu(F.linear(x, wi, bi)) elif self.norm_mode == 'layer': if not self.norm_param_flag: x = F.relu(F.layer_norm(F.linear(x, wi, bi), [self.hidden_dim], None, None, 1e-5)) else: norm_wi, norm_bi = params[self.norm_weight_start + i].view(-1), params[self.norm_bias_start + i].view(-1) x = F.relu(F.layer_norm(F.linear(x, wi, bi), [self.hidden_dim], norm_wi, norm_bi, 1e-5)) elif self.norm_mode == 'batch': if not self.norm_param_flag: norm_wi, norm_bi = None, None else: norm_wi, norm_bi = params[self.norm_weight_start + i].view(-1), params[self.norm_bias_start + i].view(-1) x = F.relu(F.batch_norm(F.linear(x, wi, bi), self.running_means[i], self.running_vars[i], norm_wi, norm_bi, bn_training, exponential_average_factor, 1e-5)) w_last, b_last = params[self.num_layers], params[-1].view(-1) if b_last.shape[0] != self.entity_dim: b_last = b_last[:self.entity_dim] x = F.linear(x, w_last, b_last) x = self.projection_regularizer(x) return x class BetaReasoning(KGReasoning): def __init__(self, nentity, nrelation, hidden_dim, gamma, optim_mode, batch_size, test_batch_size=1, sparse_embeddings=None, sparse_device='gpu', use_cuda=False, query_name_dict=None, beta_mode=None, logit_impl='native'): super(BetaReasoning, self).__init__(nentity=nentity, nrelation=nrelation, hidden_dim=hidden_dim, gamma=gamma, optim_mode=optim_mode, batch_size=batch_size, test_batch_size=test_batch_size, sparse_embeddings=sparse_embeddings, sparse_device=sparse_device, use_cuda=use_cuda, query_name_dict=query_name_dict,logit_impl=logit_impl) self.geo = 'beta' self.entity_embedding = SparseEmbedding(nentity, self.entity_dim * 2) # alpha and beta self.entity_regularizer = Regularizer(1, 0.05, 1e9) # make sure the parameters of beta embeddings are positive self.projection_regularizer = Regularizer(1, 0.05, 1e9) # make sure the parameters of beta embeddings after relation projection are positive if len(beta_mode) == 2: hidden_dim, num_layers = beta_mode dist_mode = 'kl' self.entity_range = self.embedding_range norm_mode = 'None' norm_param_flag = False elif len(beta_mode) == 3: hidden_dim, num_layers, dist_mode = beta_mode self.entity_range = self.embedding_range norm_mode = 'None' norm_param_flag = False elif len(beta_mode) == 4: hidden_dim, num_layers, dist_mode, self.entity_range = beta_mode norm_mode = 'None' norm_param_flag = False elif len(beta_mode) == 6: hidden_dim, num_layers, dist_mode, self.entity_range, norm_mode, norm_param_flag = beta_mode assert self.entity_range > 0 assert dist_mode in ['kl', 'fisher', 'l2', 'naive_fisher'] assert norm_mode in ['None', 'layer', 'batch'] if dist_mode == 'kl': self.dist_func = beta_kl elif dist_mode == 'fisher': self.dist_func = beta_fisher_approx elif dist_mode == 'naive_fisher': self.dist_func = naive_beta_fisher_approx elif dist_mode == 'l2': self.dist_func = beta_l2 self.center_net = BetaIntersection(self.entity_dim, norm_mode, norm_param_flag) self.projection_net = BetaProjection(self.entity_dim * 2, self.relation_dim, hidden_dim, self.projection_regularizer, num_layers, norm_mode, norm_param_flag) self.num_embedding_component = 2 self.init_params() def init_params(self): self.entity_embedding.init_params(-self.entity_range, self.entity_range) self.relation_embedding.init_params(-self.embedding_range, self.embedding_range) def to_device(self, device): super(BetaReasoning, self).to_device(device) self.center_net = self.center_net.to(device) self.projection_net = self.projection_net.to(device) def share_memory(self): super(BetaReasoning, self).share_memory() self.center_net.share_memory() self.projection_net.share_memory() def relation_projection(self, cur_embedding, relation_ids): relation_embedding = self.relation_embedding(relation_ids).unsqueeze(1) num_lazy_union = cur_embedding[0].shape[1] relation_embedding = relation_embedding.repeat([1, num_lazy_union, 1]) embedding = torch.cat(cur_embedding, dim=-1) embedding = self.projection_net(embedding, relation_embedding) return torch.chunk(embedding, 2, dim=-1) def negation(self, cur_embedding): return [1./embedding for embedding in cur_embedding] def retrieve_embedding(self, entity_ids): ''' Retrieve the entity embeddings given the entity indices Params: entity_ids: a list of entities indices ''' embedding = self.entity_regularizer(self.entity_embedding(entity_ids)) alpha_embedding, beta_embedding = torch.chunk(embedding, 2, dim=-1) return [alpha_embedding.unsqueeze(1), beta_embedding.unsqueeze(1)] def intersection_between_stacked_embedding(self, stacked_embedding_list): alpha_embedding, beta_embedding = torch.chunk(stacked_embedding_list, 2, dim=-1) return self.center_net(alpha_embedding, beta_embedding) def native_cal_logit(self, entity_embedding, entity_feat, query_embedding): assert entity_feat is None alpha_embedding, beta_embedding = torch.chunk(entity_embedding.unsqueeze(1), 2, dim=-1) entity_dist = BetaDist(alpha_embedding, beta_embedding) query_dist = BetaDist(*query_embedding) kld = torch_kl._kl_beta_beta(entity_dist, query_dist) logit = self.gamma - torch.norm(kld, p=1, dim=-1) logit = torch.max(logit, dim=1)[0] return logit def custom_cal_logit(self, entity_embedding, entity_feat, query_embedding): assert entity_feat is None kld = self.dist_func(entity_embedding, BetaDist(*query_embedding)) logit = self.gamma - kld logit = torch.max(logit, dim=1)[0] return logit
14,092
718
176
efdba53aa00a559d2c77d76f103cae0ad25e70e6
253
py
Python
example/main.py
zx013/pyvoxel
4d886b25a3430dbd54863bf433c2eebbd030d0f4
[ "MIT" ]
null
null
null
example/main.py
zx013/pyvoxel
4d886b25a3430dbd54863bf433c2eebbd030d0f4
[ "MIT" ]
null
null
null
example/main.py
zx013/pyvoxel
4d886b25a3430dbd54863bf433c2eebbd030d0f4
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from pyvoxel.log import Log from pyvoxel.manager import Manager if __name__ == '__main__': log_test() Log.error('Error') p = Manager.auto_load() print(p)
21.083333
36
0.592885
# -*- coding: utf-8 -*- from pyvoxel.log import Log from pyvoxel.manager import Manager if __name__ == '__main__': def log_test(): Log.debug('Debug') log_test() Log.error('Error') p = Manager.auto_load() print(p)
22
0
27
dbb3d433f54cbaa0deb5b7a60a9e0cac74b3920d
15,619
py
Python
python/redmonster/physics/pixelsplines.py
tskisner/redmonster
57f31d66259ec92c0fb5c60c202c419028c1b9cf
[ "CNRI-Python" ]
null
null
null
python/redmonster/physics/pixelsplines.py
tskisner/redmonster
57f31d66259ec92c0fb5c60c202c419028c1b9cf
[ "CNRI-Python" ]
2
2016-06-16T08:33:39.000Z
2016-06-16T13:23:59.000Z
python/redmonster/physics/pixelsplines.py
julienguy/redlantern
ba92b0951d8af56693b210b1f51254a6a11dc17a
[ "CNRI-Python" ]
null
null
null
# pixelsplines.py # Pixel-integrated sline utilities. # Written by A. Bolton, U. of Utah, 2010-2013. import numpy as n from scipy import linalg as la from scipy import sparse as sp from scipy import special as sf def compute_duck_slopes(pixbound, flux): """ Compute the slope of the illuminating quadratic spline at the locations of the 'ducks', i.e., the pixel boundaries, given the integrated flux per unit baseline within the pixels. ARGUMENTS: pixbound: (npix + 1) ndarray of pixel boundaries, in units of wavelength or log-wavelength or frequency or whatever you like. flux: (npix) ndarray of spectral flux (energy or counts) per abscissa unit, averaged over the extent of the pixel RETURNS: an (npix+1) ndarray of the slope of the underlying/illuminating flux per unit abscissa spectrum at the position of the pixel boundaries, a.k.a. 'ducks'. The end conditions are taken to be zero slope, so the exterior points of the output are zeros. """ npix = len(flux) # Test for correct argument dimensions: if (len(pixbound) - npix) != 1: print 'Need one more element in pixbound than in flux!' return 0 # The array of "delta-x" values: dxpix = pixbound[1:] - pixbound[:-1] # Test for monotonif increase: if dxpix.min() <= 0.: print 'Pixel boundaries not monotonically increasing!' return 0 # Encode the tridiagonal matrix that needs to be solved: maindiag = (dxpix[:-1] + dxpix[1:]) / 3. offdiag = dxpix[1:-1] / 6. upperdiag = n.append(0., offdiag) lowerdiag = n.append(offdiag, 0.) band_matrix = n.vstack((upperdiag, maindiag, lowerdiag)) # The right-hand side: rhs = flux[1:] - flux[:-1] # Solve the banded matrix and return: acoeff = la.solve_banded((1,1), band_matrix, rhs) acoeff = n.append(n.append(0., acoeff), 0.) return acoeff def cen2bound(pixelcen): """ Convenience function to do the obvious thing to transform pixel centers to pixel boundaries. """ pixbound = 0.5 * (pixelcen[1:] + pixelcen[:-1]) lo_val = 2. * pixbound[0] - pixbound[1] hi_val = 2. * pixbound[-1] - pixbound[-2] pixbound = n.append(n.append(lo_val, pixbound), hi_val) return pixbound def gauss_blur_matrix(pixbound, sig_conv): """ Function to generate a Gaussian blurring matrix for a pixelized spectrum, from specified pixel boundaries and 'sigma' vector. The matrix will be flux-conserving if the spectrum to which it is applied has units of 'counts per unit x', and pixbound and sig_conv both have units of x. pixbound should have one more element than sig_conv. Output is a scipy sparse matrix that can implement the blurring as: blurflux = gauss_blur_matrix * flux where 'flux' has the same dimensions as 'sig_conv'. """ # Derived values and error checks: npix = len(pixbound) - 1 if (len(sig_conv) != npix): raise PixSplineError('Need one more element in pixbound than in \ sig_conv!') if (sig_conv.min() <= 0.): raise PixSplineError('sig_conv must be > 0 everywhere!') xcen = 0.5 * (pixbound[1:] + pixbound[:-1]) dxpix = pixbound[1:] - pixbound[:-1] if (dxpix.min() <= 0.): raise PixSplineError('Pixel boundaries not monotonically increasing!') # Which "new" pixels does each "old" pixel touch? # Let's go +/- 6 sigma for all: sig_width = 6.0 # A minor correction factor to preserve flux conservation: cfact = 1./sf.erf(sig_width / n.sqrt(2.)) xblur_lo = xcen - sig_width * sig_conv xblur_hi = xcen + sig_width * sig_conv bin_lo = n.digitize(xblur_lo, pixbound) - 1 bin_hi = n.digitize(xblur_hi, pixbound) - 1 # Restrict the ranges: #xblur_lo = n.where((xblur_lo > pixbound[0]), xblur_lo, pixbound[0]) #xblur_lo = n.where((xblur_lo < pixbound[-1]), xblur_lo, pixbound[-1]) #xblur_hi = n.where((xblur_hi > pixbound[0]), xblur_hi, pixbound[0]) #xblur_hi = n.where((xblur_hi < pixbound[-1]), xblur_hi, pixbound[-1]) bin_lo = n.where((bin_lo >= 0), bin_lo, 0) #bin_lo = n.where((bin_lo < npix), bin_lo, npix-1) #bin_hi = n.where((bin_hi >= 0), bin_hi, 0) bin_hi = n.where((bin_hi < npix), bin_hi, npix-1) # Compute total number of non-zero elements in the broadening matrix: n_each = bin_hi - bin_lo + 1 n_entries = n_each.sum() ij = n.zeros((2, n_entries), dtype=long) v_vec = n.zeros(n_entries, dtype=float) # Loop over pixels in the "old" spectrum: pcount = 0L roottwo = n.sqrt(2.) bin_vec = n.arange(npix, dtype=long) for k in range(npix): xbound = pixbound[bin_lo[k]:bin_hi[k]+2] # Gaussian integral in terms of error function: erf_terms = cfact * 0.5 * sf.erf((xbound - xcen[k]) / (roottwo * sig_conv[k])) erf_int = (erf_terms[1:] - erf_terms[:-1]) * \ dxpix[k] / dxpix[bin_lo[k]:bin_hi[k]+1] ij[0,pcount:pcount+n_each[k]] = bin_vec[bin_lo[k]:bin_hi[k]+1] ij[1,pcount:pcount+n_each[k]] = k v_vec[pcount:pcount+n_each[k]] = erf_int pcount += n_each[k] conv_matrix = sp.coo_matrix((v_vec, ij), shape=(npix,npix)) return conv_matrix.tocsr() class PixelSpline: """ Pixel Spline object class. Initialize as follows: PS = PixelSpline(pixbound, flux) where pixbound = array of pixel boundaries in baseline units and flux = array of specific flux values in baseline units. Assumptions: 'pixbound' should have one more element than 'flux', and units of 'flux' are -per-unit-baseline, for the baseline units in which pixbound is expressed, averaged over the extent of each pixel. """ def point_evaluate(self, xnew, missing=0.): """ Evaluate underlying pixel spline at array of points BUG: input currently needs to be at least 1D array. """ # Initialize output array: outflux = 0. * self.flux[0] * xnew + missing # Digitize into bins: bin_idx = n.digitize(xnew, self.pixbound) # Find the indices of those that are actually in-bounds: wh_in = n.where((bin_idx > 0) * (bin_idx < len(self.pixbound))) if len(wh_in[0]) == 0: return outflux xnew_in = xnew[wh_in] idx_in = bin_idx[wh_in] - 1 # The pixel centers as per the algorithm in use: adiff = self.duckslopes[idx_in+1] - self.duckslopes[idx_in] asum = self.duckslopes[idx_in+1] + self.duckslopes[idx_in] xdiff = xnew_in - self.xcen[idx_in] fluxvals = adiff * xdiff**2 / (2. * self.dxpix[idx_in]) + asum * xdiff \ / 2. + self.flux[idx_in] - adiff * self.dxpix[idx_in] / 24. outflux[wh_in] = fluxvals return outflux def resample(self, pb_new): """ Method to resample a pixelspline analytically onto a new set of pixel boundaries. """ npix_new = len(pb_new) - 1 xnew_lo = pb_new[:-1].copy() xnew_hi = pb_new[1:].copy() # Test for monotonic: new_fulldx = xnew_hi - xnew_lo if new_fulldx.min() <= 0.: raise PixSplineError('New pixel boundaries not monotonically \ increasing!') # Digitize the new boundaries into the original bins: bin_idx = n.digitize(pb_new, self.pixbound) - 1 bin_lo = bin_idx[:-1].copy() bin_hi = bin_idx[1:].copy() # Array for accumulating new counts: new_counts = n.zeros(npix_new, dtype=self.flux.dtype) # Array for accumulating new pixel widths by pieces. # Only used for debugging so far, but may be useful in future. #new_dxpix = n.zeros(npix_new, dtype=self.flux.dtype) # For convenience, we define the following. # Careful not to modify them... they are views, not copies! xold_lo = self.pixbound[:-1] xold_hi = self.pixbound[1:] # 4 cases to cover: # Case 1: both bin_hi and bin_lo in the same bin: wh_this = n.where((bin_hi == bin_lo) * (bin_lo >= 0) * \ (bin_hi < self.npix)) if (len(wh_this[0]) > 0): dx_this = xnew_hi[wh_this] - xnew_lo[wh_this] avgval_this = self.subpixel_average(bin_lo[wh_this], xnew_lo[wh_this], xnew_hi[wh_this]) #new_dxpix[wh_this] += dx_this new_counts[wh_this] += avgval_this * dx_this # Case 2: more than one bin, lower segment: wh_this = n.where((bin_hi > bin_lo) * (bin_lo >= 0)) if (len(wh_this[0]) > 0): dx_this = xold_hi[bin_lo[wh_this]] - xnew_lo[wh_this] avgval_this = self.subpixel_average(bin_lo[wh_this], xnew_lo[wh_this], xold_hi[bin_lo[wh_this]]) #new_dxpix[wh_this] += dx_this new_counts[wh_this] += avgval_this * dx_this # Case 3: more than one bin, upper segment: wh_this = n.where((bin_hi > bin_lo) * (bin_hi < self.npix)) if (len(wh_this[0]) > 0): dx_this = xnew_hi[wh_this] - xold_lo[bin_hi[wh_this]] avgval_this = self.subpixel_average(bin_hi[wh_this], xold_lo[bin_hi[wh_this]], xnew_hi[wh_this]) #new_dxpix[wh_this] += dx_this new_counts[wh_this] += avgval_this * dx_this # Case 4: enire bins covered, whole pixels: wh_this = n.where(bin_hi > (bin_lo+1)) nwhole = len(wh_this[0]) if (nwhole > 0): pcounts = self.flux * self.dxpix icounts_this = n.array([pcounts[bin_lo[wh_this[0][ii]]+1:\ bin_hi[wh_this[0][ii]]].sum() for ii in range(nwhole)]) #new_dxpix[wh_this] += dx_this new_counts[wh_this] += icounts_this # Divide out for average and return: return new_counts / new_fulldx class WeightedRebinCoadder: """ Objet class for weighted rebinning and coaddition of spectra Initialize as follows: WRC = WeighedRebinCoadder(fluxes, invvars, pixbounds) where fluxes = list of arrays of specific flux values invvars = list of arrays of associated inverse variances pixbounds = list of arrays of pixel boundaries in baseline units """
45.40407
80
0.584673
# pixelsplines.py # Pixel-integrated sline utilities. # Written by A. Bolton, U. of Utah, 2010-2013. import numpy as n from scipy import linalg as la from scipy import sparse as sp from scipy import special as sf def compute_duck_slopes(pixbound, flux): """ Compute the slope of the illuminating quadratic spline at the locations of the 'ducks', i.e., the pixel boundaries, given the integrated flux per unit baseline within the pixels. ARGUMENTS: pixbound: (npix + 1) ndarray of pixel boundaries, in units of wavelength or log-wavelength or frequency or whatever you like. flux: (npix) ndarray of spectral flux (energy or counts) per abscissa unit, averaged over the extent of the pixel RETURNS: an (npix+1) ndarray of the slope of the underlying/illuminating flux per unit abscissa spectrum at the position of the pixel boundaries, a.k.a. 'ducks'. The end conditions are taken to be zero slope, so the exterior points of the output are zeros. """ npix = len(flux) # Test for correct argument dimensions: if (len(pixbound) - npix) != 1: print 'Need one more element in pixbound than in flux!' return 0 # The array of "delta-x" values: dxpix = pixbound[1:] - pixbound[:-1] # Test for monotonif increase: if dxpix.min() <= 0.: print 'Pixel boundaries not monotonically increasing!' return 0 # Encode the tridiagonal matrix that needs to be solved: maindiag = (dxpix[:-1] + dxpix[1:]) / 3. offdiag = dxpix[1:-1] / 6. upperdiag = n.append(0., offdiag) lowerdiag = n.append(offdiag, 0.) band_matrix = n.vstack((upperdiag, maindiag, lowerdiag)) # The right-hand side: rhs = flux[1:] - flux[:-1] # Solve the banded matrix and return: acoeff = la.solve_banded((1,1), band_matrix, rhs) acoeff = n.append(n.append(0., acoeff), 0.) return acoeff def cen2bound(pixelcen): """ Convenience function to do the obvious thing to transform pixel centers to pixel boundaries. """ pixbound = 0.5 * (pixelcen[1:] + pixelcen[:-1]) lo_val = 2. * pixbound[0] - pixbound[1] hi_val = 2. * pixbound[-1] - pixbound[-2] pixbound = n.append(n.append(lo_val, pixbound), hi_val) return pixbound def gauss_blur_matrix(pixbound, sig_conv): """ Function to generate a Gaussian blurring matrix for a pixelized spectrum, from specified pixel boundaries and 'sigma' vector. The matrix will be flux-conserving if the spectrum to which it is applied has units of 'counts per unit x', and pixbound and sig_conv both have units of x. pixbound should have one more element than sig_conv. Output is a scipy sparse matrix that can implement the blurring as: blurflux = gauss_blur_matrix * flux where 'flux' has the same dimensions as 'sig_conv'. """ # Derived values and error checks: npix = len(pixbound) - 1 if (len(sig_conv) != npix): raise PixSplineError('Need one more element in pixbound than in \ sig_conv!') if (sig_conv.min() <= 0.): raise PixSplineError('sig_conv must be > 0 everywhere!') xcen = 0.5 * (pixbound[1:] + pixbound[:-1]) dxpix = pixbound[1:] - pixbound[:-1] if (dxpix.min() <= 0.): raise PixSplineError('Pixel boundaries not monotonically increasing!') # Which "new" pixels does each "old" pixel touch? # Let's go +/- 6 sigma for all: sig_width = 6.0 # A minor correction factor to preserve flux conservation: cfact = 1./sf.erf(sig_width / n.sqrt(2.)) xblur_lo = xcen - sig_width * sig_conv xblur_hi = xcen + sig_width * sig_conv bin_lo = n.digitize(xblur_lo, pixbound) - 1 bin_hi = n.digitize(xblur_hi, pixbound) - 1 # Restrict the ranges: #xblur_lo = n.where((xblur_lo > pixbound[0]), xblur_lo, pixbound[0]) #xblur_lo = n.where((xblur_lo < pixbound[-1]), xblur_lo, pixbound[-1]) #xblur_hi = n.where((xblur_hi > pixbound[0]), xblur_hi, pixbound[0]) #xblur_hi = n.where((xblur_hi < pixbound[-1]), xblur_hi, pixbound[-1]) bin_lo = n.where((bin_lo >= 0), bin_lo, 0) #bin_lo = n.where((bin_lo < npix), bin_lo, npix-1) #bin_hi = n.where((bin_hi >= 0), bin_hi, 0) bin_hi = n.where((bin_hi < npix), bin_hi, npix-1) # Compute total number of non-zero elements in the broadening matrix: n_each = bin_hi - bin_lo + 1 n_entries = n_each.sum() ij = n.zeros((2, n_entries), dtype=long) v_vec = n.zeros(n_entries, dtype=float) # Loop over pixels in the "old" spectrum: pcount = 0L roottwo = n.sqrt(2.) bin_vec = n.arange(npix, dtype=long) for k in range(npix): xbound = pixbound[bin_lo[k]:bin_hi[k]+2] # Gaussian integral in terms of error function: erf_terms = cfact * 0.5 * sf.erf((xbound - xcen[k]) / (roottwo * sig_conv[k])) erf_int = (erf_terms[1:] - erf_terms[:-1]) * \ dxpix[k] / dxpix[bin_lo[k]:bin_hi[k]+1] ij[0,pcount:pcount+n_each[k]] = bin_vec[bin_lo[k]:bin_hi[k]+1] ij[1,pcount:pcount+n_each[k]] = k v_vec[pcount:pcount+n_each[k]] = erf_int pcount += n_each[k] conv_matrix = sp.coo_matrix((v_vec, ij), shape=(npix,npix)) return conv_matrix.tocsr() class PixSplineError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class PixelSpline: """ Pixel Spline object class. Initialize as follows: PS = PixelSpline(pixbound, flux) where pixbound = array of pixel boundaries in baseline units and flux = array of specific flux values in baseline units. Assumptions: 'pixbound' should have one more element than 'flux', and units of 'flux' are -per-unit-baseline, for the baseline units in which pixbound is expressed, averaged over the extent of each pixel. """ def __init__(self, pixbound, flux): npix = len(flux) # Test for correct argument dimensions: if (len(pixbound) - npix) != 1: raise PixSplineError('Need one more element in pixbound \ than in flux!') # The array of "delta-x" values: dxpix = pixbound[1:] - pixbound[:-1] # Test for monotonic increase: if dxpix.min() <= 0.: raise PixSplineError('Pixel boundaries not monotonically \ increasing!') self.npix = npix self.pixbound = pixbound.copy() self.dxpix = dxpix.copy() self.xcen = 0.5 * (pixbound[1:] + pixbound[:-1]).copy() self.flux = flux.copy() maindiag = (dxpix[:-1] + dxpix[1:]) / 3. offdiag = dxpix[1:-1] / 6. upperdiag = n.append(0., offdiag) lowerdiag = n.append(offdiag, 0.) band_matrix = n.vstack((upperdiag, maindiag, lowerdiag)) # The right-hand side: rhs = flux[1:] - flux[:-1] # Solve the banded matrix for the slopes at the ducks: acoeff = la.solve_banded((1,1), band_matrix, rhs) self.duckslopes = n.append(n.append(0., acoeff), 0.) def point_evaluate(self, xnew, missing=0.): """ Evaluate underlying pixel spline at array of points BUG: input currently needs to be at least 1D array. """ # Initialize output array: outflux = 0. * self.flux[0] * xnew + missing # Digitize into bins: bin_idx = n.digitize(xnew, self.pixbound) # Find the indices of those that are actually in-bounds: wh_in = n.where((bin_idx > 0) * (bin_idx < len(self.pixbound))) if len(wh_in[0]) == 0: return outflux xnew_in = xnew[wh_in] idx_in = bin_idx[wh_in] - 1 # The pixel centers as per the algorithm in use: adiff = self.duckslopes[idx_in+1] - self.duckslopes[idx_in] asum = self.duckslopes[idx_in+1] + self.duckslopes[idx_in] xdiff = xnew_in - self.xcen[idx_in] fluxvals = adiff * xdiff**2 / (2. * self.dxpix[idx_in]) + asum * xdiff \ / 2. + self.flux[idx_in] - adiff * self.dxpix[idx_in] / 24. outflux[wh_in] = fluxvals return outflux def find_extrema(self, minima=False): # Find the formal extrema positions: x_ext = self.xcen - 0.5 * self.dxpix * \ (self.duckslopes[1:] + self.duckslopes[:-1]) / \ (self.duckslopes[1:] - self.duckslopes[:-1]) # Digitize these into bins: bin_ext = n.digitize(x_ext, self.pixbound) - 1 # The second derivatives, flipped in sign if minima is set: curvat = (-1)**(minima == True) * (self.duckslopes[1:] - self.duckslopes[:-1]) / self.dxpix # Find in-bin maxima: wh_ext = n.where((bin_ext == n.arange(self.npix)) * (curvat < 0)) if len(wh_ext[0]) < 1: return n.array([]) x_ext = x_ext[wh_ext] return x_ext def subpixel_average(self, ipix, xlo, xhi): adiff = self.duckslopes[ipix+1] - self.duckslopes[ipix] asum = self.duckslopes[ipix+1] + self.duckslopes[ipix] xlo_c = xlo - self.xcen[ipix] xhi_c = xhi - self.xcen[ipix] outval = adiff * ((xhi-xlo)**2 / 6. + xhi_c * xlo_c / 2.) / \ self.dxpix[ipix] + asum * (xhi_c + xlo_c) / 4. - adiff * \ self.dxpix[ipix] / 24. + self.flux[ipix] return outval def resample(self, pb_new): """ Method to resample a pixelspline analytically onto a new set of pixel boundaries. """ npix_new = len(pb_new) - 1 xnew_lo = pb_new[:-1].copy() xnew_hi = pb_new[1:].copy() # Test for monotonic: new_fulldx = xnew_hi - xnew_lo if new_fulldx.min() <= 0.: raise PixSplineError('New pixel boundaries not monotonically \ increasing!') # Digitize the new boundaries into the original bins: bin_idx = n.digitize(pb_new, self.pixbound) - 1 bin_lo = bin_idx[:-1].copy() bin_hi = bin_idx[1:].copy() # Array for accumulating new counts: new_counts = n.zeros(npix_new, dtype=self.flux.dtype) # Array for accumulating new pixel widths by pieces. # Only used for debugging so far, but may be useful in future. #new_dxpix = n.zeros(npix_new, dtype=self.flux.dtype) # For convenience, we define the following. # Careful not to modify them... they are views, not copies! xold_lo = self.pixbound[:-1] xold_hi = self.pixbound[1:] # 4 cases to cover: # Case 1: both bin_hi and bin_lo in the same bin: wh_this = n.where((bin_hi == bin_lo) * (bin_lo >= 0) * \ (bin_hi < self.npix)) if (len(wh_this[0]) > 0): dx_this = xnew_hi[wh_this] - xnew_lo[wh_this] avgval_this = self.subpixel_average(bin_lo[wh_this], xnew_lo[wh_this], xnew_hi[wh_this]) #new_dxpix[wh_this] += dx_this new_counts[wh_this] += avgval_this * dx_this # Case 2: more than one bin, lower segment: wh_this = n.where((bin_hi > bin_lo) * (bin_lo >= 0)) if (len(wh_this[0]) > 0): dx_this = xold_hi[bin_lo[wh_this]] - xnew_lo[wh_this] avgval_this = self.subpixel_average(bin_lo[wh_this], xnew_lo[wh_this], xold_hi[bin_lo[wh_this]]) #new_dxpix[wh_this] += dx_this new_counts[wh_this] += avgval_this * dx_this # Case 3: more than one bin, upper segment: wh_this = n.where((bin_hi > bin_lo) * (bin_hi < self.npix)) if (len(wh_this[0]) > 0): dx_this = xnew_hi[wh_this] - xold_lo[bin_hi[wh_this]] avgval_this = self.subpixel_average(bin_hi[wh_this], xold_lo[bin_hi[wh_this]], xnew_hi[wh_this]) #new_dxpix[wh_this] += dx_this new_counts[wh_this] += avgval_this * dx_this # Case 4: enire bins covered, whole pixels: wh_this = n.where(bin_hi > (bin_lo+1)) nwhole = len(wh_this[0]) if (nwhole > 0): pcounts = self.flux * self.dxpix icounts_this = n.array([pcounts[bin_lo[wh_this[0][ii]]+1:\ bin_hi[wh_this[0][ii]]].sum() for ii in range(nwhole)]) #new_dxpix[wh_this] += dx_this new_counts[wh_this] += icounts_this # Divide out for average and return: return new_counts / new_fulldx class WeightedRebinCoadder: """ Objet class for weighted rebinning and coaddition of spectra Initialize as follows: WRC = WeighedRebinCoadder(fluxes, invvars, pixbounds) where fluxes = list of arrays of specific flux values invvars = list of arrays of associated inverse variances pixbounds = list of arrays of pixel boundaries in baseline units """ def __init__(self, fluxes, invvars, pixbounds): # Determine minimum and maximum values of independent variable: self.min_indep = [this_bound.min() for this_bound in pixbounds] self.max_indep = [this_bound.max() for this_bound in pixbounds] self._n_input = len(fluxes) # Compute pixel widths: dpixes = [this_bound[1:] - this_bound[:-1] for this_bound in pixbounds] # Compute "specific inverse variances": sp_invvars = [invvars[i] / dpixes[i] for i in xrange(self._n_input)] # Compute pixelspline objects for fluxes: self._PXS_fluxes = [PixelSpline(pixbounds[i], fluxes[i]) for i in \ xrange(self._n_input)] # Compute pixelspline objects for specific inverse variances: self._PXS_sp_invvars = [PixelSpline(pixbounds[i], sp_invvars[i]) for \ i in xrange(self._n_input)] def coadd(self, pixbound_out): # Compute coverage masks: masks = [(pixbound_out[:-1] > self.min_indep[i]) * (pixbound_out[1:] < self.max_indep[i]) for i in \ xrange(self._n_input)] # Compute output pixel widths: dpix_out = pixbound_out[1:] - pixbound_out[:-1] # Compute interpolated fluxes: new_fluxes = [this_PXS.resample(pixbound_out) for this_PXS in \ self._PXS_fluxes] # Compute interpolated specific inverse variances (converted # to inverse variances): new_invvars = [dpix_out * this_PXS.resample(pixbound_out) for \ this_PXS in self._PXS_sp_invvars] # Compute coadded flux and inverse variance and return: flux_coadd = 0. invvar_coadd = 0. for i in xrange(self._n_input): flux_coadd += new_fluxes[i] * new_invvars[i] * masks[i] invvar_coadd += new_invvars[i] * masks[i] is_good = n.where(invvar_coadd > 0.) flux_coadd[is_good] /= invvar_coadd[is_good] return flux_coadd, invvar_coadd
4,461
11
205
bba7d66222da2af05f6a32b36d7582a900766e87
3,633
py
Python
src/File.py
ytyaru/Python.File.Dir.Stat.20180402093000
f66e5eff603c62e24dd25f4aea034ce288059c66
[ "CC0-1.0" ]
null
null
null
src/File.py
ytyaru/Python.File.Dir.Stat.20180402093000
f66e5eff603c62e24dd25f4aea034ce288059c66
[ "CC0-1.0" ]
null
null
null
src/File.py
ytyaru/Python.File.Dir.Stat.20180402093000
f66e5eff603c62e24dd25f4aea034ce288059c66
[ "CC0-1.0" ]
null
null
null
import os, os.path, pathlib, shutil from Stat import Stat
43.771084
194
0.629232
import os, os.path, pathlib, shutil from Stat import Stat class File(Stat): def __init__(self, path): if not os.path.isabs(path): raise ValueError('引数pathは絶対パスにしてください。path=\'{}\''.format(path)) super().__init__(path) def mk(self, path=None): if path is not None and os.path.isabs(path) and os.path.dirname(self.Path) not in path: raise ValueError('引数pathは未指定か次のパスの相対パス、または次のパス配下を指定してください。{}'.format(os.path.dirname(self.Path))) elif path is None: p = self.Path elif os.path.isabs(path): p = path else: p = os.path.join(os.path.dirname(self.Path), path) self.Create(p) self.__make_first(p) def __make_first(self, path): if not self.IsExist(path): self.Path = path def mk_dummy(self, size, path=None): if path is not None and os.path.isabs(path) and os.path.dirname(self.Path) not in path: raise ValueError('引数pathは未指定か次のパスの相対パス、または次のパス配下を指定してください。{}'.format(os.path.dirname(self.Path))) elif path is None: p = self.Path elif os.path.isabs(path): p = path else: p = os.path.join(os.path.dirname(self.Path), path) self.CreateDummy(p, size) self.__make_first(p) def rm(self, path=None): if path is not None and os.path.isabs(path) and os.path.basename(self.Path) not in path: raise ValueError('引数pathは未指定か次のパスの相対パス、または次のパス配下を指定してください。{}'.format(os.path.dirname(self.Path))) elif path is None: self.Delete(self.Path) elif os.path.isabs(path): self.Delete(path) else: self.Delete(os.path.join(self.Path, path)) def cp(self, dst): return self.Copy(self.Path, dst) def mv(self, dst): self.Path = self.Move(self.Path, dst) return self.Path def readline(self): for l in open(self.Path): yield l def read(self, is_binary=False): mode = 'r' if is_binary: mode += 'b' with open(self.Path, mode): return f.read() def write(self, data): if type(data) == str: with open(self.Path, 'w'): f.write(data) elif type(data) == bytes: with open(self.Path, 'wb'): f.write(data) else: raise ValueError('引数dataはstr,bytesのいずれかにしてください。{}'.format(type(data))) def append(self, data): if type(data) == str: with open(self.Path, 'a'): f.write(data) elif type(data) == bytes: with open(self.Path, 'ab'): f.write(data) else: raise ValueError('引数dataはstr,bytesのいずれかにしてください。{}'.format(type(data))) @classmethod def IsExist(cls, path): return os.path.isfile(path) @classmethod def Create(cls, path): cls.__Create(path, lambda f: None) @classmethod def CreateDummy(cls, path, size): cls.__Create(path, lambda f: f.write(b'\0'*size)) @classmethod def __Create(cls, path, method): if not os.path.exists(path): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, 'wb') as f: method(f) @classmethod def Delete(cls, path): if cls.IsExist(path): os.remove(path) @classmethod def Copy(cls, src, dst): if os.path.isfile(src): os.makedirs(os.path.dirname(dst), exist_ok=True) return shutil.copy(src, dst) elif os.path.isdir(src): raise IsADirectoryError() else: raise FileNotFoundError() @classmethod def Move(cls, src, dst): if os.path.isfile(src): os.makedirs(os.path.dirname(dst), exist_ok=True) cls.Path = shutil.move(src, dst) return cls.Path elif os.path.isdir(src): raise IsADirectoryError() else: raise FileNotFoundError()
3,266
596
23
852dce101de13404757f08f03cc79527ac4ad765
998
py
Python
Contributions/nQueen.py
sattwik21/Hacktoberfest2021-1
74c8edd54f9c967c0f301f74dec31526dffa8222
[ "MIT" ]
215
2021-10-01T08:18:16.000Z
2022-03-29T04:12:03.000Z
Contributions/nQueen.py
sattwik21/Hacktoberfest2021-1
74c8edd54f9c967c0f301f74dec31526dffa8222
[ "MIT" ]
51
2021-10-01T08:16:42.000Z
2021-10-31T13:51:51.000Z
Contributions/nQueen.py
sattwik21/Hacktoberfest2021-1
74c8edd54f9c967c0f301f74dec31526dffa8222
[ "MIT" ]
807
2021-10-01T08:11:45.000Z
2021-11-21T18:57:09.000Z
n = int(input()) solution = [[0 for i in range(n)] for j in range(n)] for j in range(n) : nQueen(0, j, n, solution)
22.681818
52
0.465932
def isPoss(i, j, matrix) : for k in range(i) : if matrix[k][j] == 1 : return False for l in range(j) : if matrix[i][l] == 1 : return False k, l = i-1, j-1 while k>=0 and l>=0 : if matrix[k][l] == 1 : return False k, l = k-1, l-1 k, l = i-1, j+1 while k>=0 and l<len(matrix) : if matrix[k][l] == 1 : return False k, l = k-1, l+1 return True def nQueen(i, j, n, solution): #Implement Your Code Here if i >= n or j >= n : return if not isPoss(i, j, solution) : return if i == n-1 : solution[i][j] = 1 for sol in solution : print(*sol, end=" ") print() solution[i][j] = 0 return for k in range(n) : solution[i][j] = 1 nQueen(i+1, k, n, solution) solution[i][j] = 0 n = int(input()) solution = [[0 for i in range(n)] for j in range(n)] for j in range(n) : nQueen(0, j, n, solution)
827
0
50
803757d86c30f1ad8f20150e31c6efb96c90b346
1,936
py
Python
ee/tasks/webhooks_ee.py
adamb70/posthog
54ae8f0e70092f86b4aefbd93b56680dbd28b1c5
[ "MIT" ]
null
null
null
ee/tasks/webhooks_ee.py
adamb70/posthog
54ae8f0e70092f86b4aefbd93b56680dbd28b1c5
[ "MIT" ]
null
null
null
ee/tasks/webhooks_ee.py
adamb70/posthog
54ae8f0e70092f86b4aefbd93b56680dbd28b1c5
[ "MIT" ]
null
null
null
import re from typing import Any, Dict import requests from celery import Task from django.conf import settings from posthog.celery import app from posthog.models import Action, Event, Team from posthog.tasks.webhooks import determine_webhook_type, get_formatted_message @app.task(ignore_result=True, bind=True, max_retries=3)
37.230769
116
0.573347
import re from typing import Any, Dict import requests from celery import Task from django.conf import settings from posthog.celery import app from posthog.models import Action, Event, Team from posthog.tasks.webhooks import determine_webhook_type, get_formatted_message @app.task(ignore_result=True, bind=True, max_retries=3) def post_event_to_webhook_ee(self: Task, event: Dict[str, Any], team_id: int, site_url: str) -> None: try: team = Team.objects.get(pk=team_id) _event = Event.objects.create( event=event["event"], distinct_id=event["distinct_id"], properties=event["properties"], team=team, site_url=site_url, **({"timestamp": event["timestamp"]} if event["timestamp"] else {}), **({"elements": event["elements_list"]} if event["elements_list"] else {}) ) actions = Action.objects.filter(team_id=team_id, post_to_slack=True).all() if not site_url: site_url = settings.SITE_URL if team.slack_incoming_webhook: for action in actions: qs = Event.objects.filter(pk=_event.pk).query_db_by_action(action) if qs: message_text, message_markdown = get_formatted_message(action, _event, site_url,) if determine_webhook_type(team) == "slack": message = { "text": message_text, "blocks": [{"type": "section", "text": {"type": "mrkdwn", "text": message_markdown},},], } else: message = { "text": message_markdown, } requests.post(team.slack_incoming_webhook, verify=False, json=message) _event.delete() except: self.retry(countdown=2 ** self.request.retries)
1,583
0
22
b95b936937e1f3a8196fa97a04c875ad44bcfa2f
12,306
py
Python
gevent/pool.py
bkad/gevent
185b71cc472db413515059ab4a197207cdaf1f6c
[ "MIT" ]
2
2015-12-19T01:34:43.000Z
2018-02-02T12:32:01.000Z
gevent/pool.py
alex/gevent
454a77ca561868854760b2d9cbfa3bf3bbd2e062
[ "MIT" ]
null
null
null
gevent/pool.py
alex/gevent
454a77ca561868854760b2d9cbfa3bf3bbd2e062
[ "MIT" ]
2
2019-11-24T12:11:50.000Z
2020-12-26T19:00:20.000Z
# Copyright (c) 2009-2011 Denis Bilenko. See LICENSE for details. """Managing greenlets in a group. The :class:`Group` class in this module abstracts a group of running greenlets. When a greenlet dies, it's automatically removed from the group. The :class:`Pool` which a subclass of :class:`Group` provides a way to limit concurrency: its :meth:`spawn <Pool.spawn>` method blocks if the number of greenlets in the pool has already reached the limit, until there is a free slot. """ import sys from bisect import insort_right from gevent.hub import GreenletExit, getcurrent, kill as _kill, PY3 from gevent.greenlet import joinall, Greenlet from gevent.timeout import Timeout from gevent.event import Event from gevent.lock import Semaphore, DummySemaphore __all__ = ['Group', 'Pool'] class Group(object): """Maintain a group of greenlets that are still running. Links to each item and removes it upon notification. """ greenlet_class = Greenlet # def close(self): # """Prevents any more tasks from being submitted to the pool""" # self.add = RaiseException("This %s has been closed" % self.__class__.__name__) def apply(self, func, args=None, kwds=None): """Equivalent of the apply() builtin function. It blocks till the result is ready.""" if args is None: args = () if kwds is None: kwds = {} if getcurrent() in self: return func(*args, **kwds) else: return self.spawn(func, *args, **kwds).get() def apply_async(self, func, args=None, kwds=None, callback=None): """A variant of the apply() method which returns a Greenlet object. If callback is specified then it should be a callable which accepts a single argument. When the result becomes ready callback is applied to it (unless the call failed).""" if args is None: args = () if kwds is None: kwds = {} if self.full(): # cannot call spawn() directly because it will block return Greenlet.spawn(self.apply_cb, func, args, kwds, callback) else: greenlet = self.spawn(func, *args, **kwds) if callback is not None: greenlet.link(pass_value(callback)) return greenlet def map_async(self, func, iterable, callback=None): """ A variant of the map() method which returns a Greenlet object. If callback is specified then it should be a callable which accepts a single argument. """ return Greenlet.spawn(self.map_cb, func, iterable, callback) def imap(self, func, iterable): """An equivalent of itertools.imap()""" return IMap.spawn(func, iterable, spawn=self.spawn) def imap_unordered(self, func, iterable): """The same as imap() except that the ordering of the results from the returned iterator should be considered in arbitrary order.""" return IMapUnordered.spawn(func, iterable, spawn=self.spawn) _SKIP = object()
30.688279
124
0.573704
# Copyright (c) 2009-2011 Denis Bilenko. See LICENSE for details. """Managing greenlets in a group. The :class:`Group` class in this module abstracts a group of running greenlets. When a greenlet dies, it's automatically removed from the group. The :class:`Pool` which a subclass of :class:`Group` provides a way to limit concurrency: its :meth:`spawn <Pool.spawn>` method blocks if the number of greenlets in the pool has already reached the limit, until there is a free slot. """ import sys from bisect import insort_right from gevent.hub import GreenletExit, getcurrent, kill as _kill, PY3 from gevent.greenlet import joinall, Greenlet from gevent.timeout import Timeout from gevent.event import Event from gevent.lock import Semaphore, DummySemaphore __all__ = ['Group', 'Pool'] class Group(object): """Maintain a group of greenlets that are still running. Links to each item and removes it upon notification. """ greenlet_class = Greenlet def __init__(self, *args): assert len(args) <= 1, args self.greenlets = set(*args) if args: for greenlet in args[0]: greenlet.rawlink(self._discard) # each item we kill we place in dying, to avoid killing the same greenlet twice self.dying = set() self._empty_event = Event() self._empty_event.set() def __repr__(self): return '<%s at 0x%x %s>' % (self.__class__.__name__, id(self), self.greenlets) def __len__(self): return len(self.greenlets) def __contains__(self, item): return item in self.greenlets def __iter__(self): return iter(self.greenlets) def add(self, greenlet): try: rawlink = greenlet.rawlink except AttributeError: pass # non-Greenlet greenlet, like MAIN else: rawlink(self._discard) self.greenlets.add(greenlet) self._empty_event.clear() def _discard(self, greenlet): self.greenlets.discard(greenlet) self.dying.discard(greenlet) if not self.greenlets: self._empty_event.set() def discard(self, greenlet): self._discard(greenlet) try: unlink = greenlet.unlink except AttributeError: pass # non-Greenlet greenlet, like MAIN else: unlink(self._discard) def start(self, greenlet): self.add(greenlet) greenlet.start() def spawn(self, *args, **kwargs): greenlet = self.greenlet_class(*args, **kwargs) self.start(greenlet) return greenlet # def close(self): # """Prevents any more tasks from being submitted to the pool""" # self.add = RaiseException("This %s has been closed" % self.__class__.__name__) def join(self, timeout=None, raise_error=False): if raise_error: greenlets = self.greenlets.copy() self._empty_event.wait(timeout=timeout) for greenlet in greenlets: if greenlet.exception is not None: raise greenlet.exception else: self._empty_event.wait(timeout=timeout) def kill(self, exception=GreenletExit, block=True, timeout=None): timer = Timeout.start_new(timeout) try: try: while self.greenlets: for greenlet in list(self.greenlets): if greenlet not in self.dying: try: kill = greenlet.kill except AttributeError: _kill(greenlet, exception) else: kill(exception, block=False) self.dying.add(greenlet) if not block: break joinall(self.greenlets) except Timeout: ex = sys.exc_info()[1] if ex is not timer: raise finally: timer.cancel() def killone(self, greenlet, exception=GreenletExit, block=True, timeout=None): if greenlet not in self.dying and greenlet in self.greenlets: greenlet.kill(exception, block=False) self.dying.add(greenlet) if block: greenlet.join(timeout) def apply(self, func, args=None, kwds=None): """Equivalent of the apply() builtin function. It blocks till the result is ready.""" if args is None: args = () if kwds is None: kwds = {} if getcurrent() in self: return func(*args, **kwds) else: return self.spawn(func, *args, **kwds).get() def apply_cb(self, func, args=None, kwds=None, callback=None): result = self.apply(func, args, kwds) if callback is not None: Greenlet.spawn(callback, result) return result def apply_async(self, func, args=None, kwds=None, callback=None): """A variant of the apply() method which returns a Greenlet object. If callback is specified then it should be a callable which accepts a single argument. When the result becomes ready callback is applied to it (unless the call failed).""" if args is None: args = () if kwds is None: kwds = {} if self.full(): # cannot call spawn() directly because it will block return Greenlet.spawn(self.apply_cb, func, args, kwds, callback) else: greenlet = self.spawn(func, *args, **kwds) if callback is not None: greenlet.link(pass_value(callback)) return greenlet def map(self, func, iterable): return list(self.imap(func, iterable)) def map_cb(self, func, iterable, callback=None): result = self.map(func, iterable) if callback is not None: callback(result) return result def map_async(self, func, iterable, callback=None): """ A variant of the map() method which returns a Greenlet object. If callback is specified then it should be a callable which accepts a single argument. """ return Greenlet.spawn(self.map_cb, func, iterable, callback) def imap(self, func, iterable): """An equivalent of itertools.imap()""" return IMap.spawn(func, iterable, spawn=self.spawn) def imap_unordered(self, func, iterable): """The same as imap() except that the ordering of the results from the returned iterator should be considered in arbitrary order.""" return IMapUnordered.spawn(func, iterable, spawn=self.spawn) def full(self): return False def wait_available(self): pass class IMapUnordered(Greenlet): def __init__(self, func, iterable, spawn=None): from gevent.queue import Queue Greenlet.__init__(self) if spawn is not None: self.spawn = spawn self.func = func self.iterable = iterable self.queue = Queue() self.count = 0 self.rawlink(self._on_finish) def __iter__(self): return self def next(self): value = self.queue.get() if isinstance(value, Failure): raise value.exc return value if PY3: __next__ = next del next def _run(self): try: func = self.func empty = True for item in self.iterable: self.count += 1 self.spawn(func, item).rawlink(self._on_result) empty = False if empty: self.queue.put(Failure(StopIteration)) finally: self.__dict__.pop('spawn', None) self.__dict__.pop('func', None) self.__dict__.pop('iterable', None) def _on_result(self, greenlet): self.count -= 1 if greenlet.successful(): self.queue.put(greenlet.value) if self.ready() and self.count <= 0: self.queue.put(Failure(StopIteration)) def _on_finish(self, _self): if not self.successful(): self.queue.put(Failure(self.exception)) class IMap(Greenlet): def __init__(self, func, iterable, spawn=None): from gevent.queue import Queue Greenlet.__init__(self) if spawn is not None: self.spawn = spawn self.func = func self.iterable = iterable self.queue = Queue() self.count = 0 self.waiting = [] # QQQ maybe deque will work faster there? self.index = 0 self.maxindex = -1 self.rawlink(self._on_finish) def __iter__(self): return self def next(self): while True: if self.waiting and self.waiting[0][0] <= self.index: index, value = self.waiting.pop(0) else: index, value = self.queue.get() if index > self.index: insort_right(self.waiting, (index, value)) continue self.index += 1 if isinstance(value, Failure): raise value.exc if value is not _SKIP: return value if PY3: __next__ = next del next def _run(self): try: empty = True func = self.func for item in self.iterable: self.count += 1 g = self.spawn(func, item) g.rawlink(self._on_result) self.maxindex += 1 g.index = self.maxindex empty = False if empty: self.maxindex += 1 self.queue.put((self.maxindex, Failure(StopIteration))) finally: self.__dict__.pop('spawn', None) self.__dict__.pop('func', None) self.__dict__.pop('iterable', None) def _on_result(self, greenlet): self.count -= 1 if greenlet.successful(): self.queue.put((greenlet.index, greenlet.value)) else: self.queue.put((greenlet.index, _SKIP)) if self.ready() and self.count <= 0: self.maxindex += 1 self.queue.put((self.maxindex, Failure(StopIteration))) def _on_finish(self, _self): if not self.successful(): self.maxindex += 1 self.queue.put((self.maxindex, Failure(self.exception))) class Failure(object): __slots__ = ['exc'] def __init__(self, exc): self.exc = exc class Pool(Group): def __init__(self, size=None, greenlet_class=None): if size is not None and size < 0: raise ValueError('size must not be negative: %r' % (size, )) Group.__init__(self) self.size = size if greenlet_class is not None: self.greenlet_class = greenlet_class if size is None: self._semaphore = DummySemaphore() else: self._semaphore = Semaphore(size) def wait_available(self): self._semaphore.wait() def full(self): return self.free_count() <= 0 def free_count(self): if self.size is None: return 1 return max(0, self.size - len(self)) def add(self, greenlet): self._semaphore.acquire() try: Group.add(self, greenlet) except: self._semaphore.release() raise def _discard(self, greenlet): Group._discard(self, greenlet) self._semaphore.release() class pass_value(object): __slots__ = ['callback'] def __init__(self, callback): self.callback = callback def __call__(self, source): if source.successful(): self.callback(source.value) def __hash__(self): return hash(self.callback) def __eq__(self, other): return self.callback == getattr(other, 'callback', other) def __str__(self): return str(self.callback) def __repr__(self): return repr(self.callback) def __getattr__(self, item): assert item != 'callback' return getattr(self.callback, item) _SKIP = object()
7,755
712
763
45cb9ce86ce46ee40a4f96a29f1f0759cef62cd4
2,834
py
Python
app/settings.py
shenhaizhumin/fastapi-demo
bce6ec556b1058f3b213e2698075d72033c2162d
[ "Apache-2.0" ]
null
null
null
app/settings.py
shenhaizhumin/fastapi-demo
bce6ec556b1058f3b213e2698075d72033c2162d
[ "Apache-2.0" ]
null
null
null
app/settings.py
shenhaizhumin/fastapi-demo
bce6ec556b1058f3b213e2698075d72033c2162d
[ "Apache-2.0" ]
null
null
null
import os import configparser import redis from passlib.context import CryptContext from app.util.log_util2 import get_path, get_logger from pydantic import BaseSettings, Field # from fastapi.logger import logger # from logging.handlers import RotatingFileHandler import logging formatter = logging.Formatter( "(%(asctime)s.%(msecs)03d) %(levelname)s (%(thread)d) - %(message)s", "%Y-%m-%d %H:%M:%S") # import re # import yaml # # path_matcher = re.compile(r'.*\$\{((^}^{)+)\}.*') # # # def path_constructor(loader, node): # return os.path.expandvars(node.value) # # # class EnvVarLoader(yaml.SafeLoader): # pass # # # EnvVarLoader.add_implicit_resolver('!path', path_matcher, None) # EnvVarLoader.add_constructor('!path', path_constructor) # # # _env = os.environ.get('CFG_ENV') # _config_path = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir)) + 'configs.yml' # conf_doc = yaml.load(open(_config_path), Loader=EnvVarLoader) # conf = conf_doc.get(_env) # 读取配置信息 file_path = os.path.abspath(__file__) par_dir = os.path.dirname(file_path) profile = os.environ.get('DEPLOY_ENVIRONMENT', 'local') if profile == 'remote': config_name = 'config_remote.ini' else: config_name = 'config.ini' conf_path = os.path.join(par_dir, 'config', config_name) print("conf_path:" + conf_path) conf_doc = configparser.ConfigParser() conf_doc.read(conf_path) setting = Settings()
32.574713
117
0.695483
import os import configparser import redis from passlib.context import CryptContext from app.util.log_util2 import get_path, get_logger from pydantic import BaseSettings, Field # from fastapi.logger import logger # from logging.handlers import RotatingFileHandler import logging formatter = logging.Formatter( "(%(asctime)s.%(msecs)03d) %(levelname)s (%(thread)d) - %(message)s", "%Y-%m-%d %H:%M:%S") # import re # import yaml # # path_matcher = re.compile(r'.*\$\{((^}^{)+)\}.*') # # # def path_constructor(loader, node): # return os.path.expandvars(node.value) # # # class EnvVarLoader(yaml.SafeLoader): # pass # # # EnvVarLoader.add_implicit_resolver('!path', path_matcher, None) # EnvVarLoader.add_constructor('!path', path_constructor) # # # _env = os.environ.get('CFG_ENV') # _config_path = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir)) + 'configs.yml' # conf_doc = yaml.load(open(_config_path), Loader=EnvVarLoader) # conf = conf_doc.get(_env) # 读取配置信息 file_path = os.path.abspath(__file__) par_dir = os.path.dirname(file_path) profile = os.environ.get('DEPLOY_ENVIRONMENT', 'local') if profile == 'remote': config_name = 'config_remote.ini' else: config_name = 'config.ini' conf_path = os.path.join(par_dir, 'config', config_name) print("conf_path:" + conf_path) conf_doc = configparser.ConfigParser() conf_doc.read(conf_path) class Settings(BaseSettings): LOG_DIR: str = conf_doc.get('logging', 'log_dir') INFO_LOGGER = get_logger(get_path(LOG_DIR, 'app_info.log')) ERROR_LOGGER = get_logger(get_path(LOG_DIR, 'app_error.log')) IMAGE_DIRNAME: str = conf_doc.get('file', 'image_dirname') DOMAIN_NAME: str = conf_doc.get('file', 'domain_name') REDIS_PORT: int = int(conf_doc.get('db.redis', 'port')) REDIS_HOST: str = conf_doc.get('db.redis', 'host') REDIS_DATABASE: int = int(conf_doc.get('db.redis', 'db')) # connect_pool = redis.Connection(host=REDIS_HOST, port=REDIS_PORT) ACCESS_TOKEN_EXPIRE_MINUTES: int = int(conf_doc.get('jwt.extars', 'expire_minutes')) SECRET_KEY: str = conf_doc.get('jwt.extars', 'secret_key') ALGORITHM: str = conf_doc.get('jwt.extars', 'algorithm') TOKENURL: str = '/login' TEST_EXTRAS = conf_doc.get('jwt.extars', 'test_extras') INFO_LOGGER.info("environment-->TEST_EXTRAS:" + str(os.environ.get("TEST_EXTRAS"))) INFO_LOGGER.info("TEST_EXTRAS:" + str(TEST_EXTRAS)) DB_URI: str = conf_doc.get('db.test', 'db_uri') JWT_OPTIONS: dict = { 'verify_signature': True, 'verify_exp': True, 'verify_nbf': False, 'verify_iat': True, 'verify_aud': False } error_code: int = -200 pwd_context = CryptContext(schemes=("bcrypt"), deprecated="auto") class Config: case_sensitive = True setting = Settings()
0
1,389
23
7fd28b1257d684a486e683748c33d57b2368aca7
23,962
py
Python
geco/attrgenfunct.py
kdurril/mvp_app
dfe7ef75e4a49d9bce3cb50c29f1a6d25a15361d
[ "MIT" ]
null
null
null
geco/attrgenfunct.py
kdurril/mvp_app
dfe7ef75e4a49d9bce3cb50c29f1a6d25a15361d
[ "MIT" ]
null
null
null
geco/attrgenfunct.py
kdurril/mvp_app
dfe7ef75e4a49d9bce3cb50c29f1a6d25a15361d
[ "MIT" ]
null
null
null
# Functions that can generate attribute values. # # These are functions that can be used in the GenerateFuncAttribute() class # (see module generator.py). They generate values according to some internal # functionality. # # The requirement of any such functions are: # 1) that it must return a string # 2) it can have been 0 and 5 parameters # # # Examples of such functions are: # - Australian telephone numbers # - Japanese telephone numbers # - Credit card numbers # - US social security numbers # - Japanese social security numbers # - Uniformly distributed age values between 0 and 100 # - Normally distributed age values between 0 and 110 # etc. # Peter Christen and Dinusha Vatsalan, January-March 2012 # ============================================================================= # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # ============================================================================= import random import basefunctions, generator import csv # ----------------------------------------------------------------------------- # def generate_phone_number_australia(): """Randomly generate an Australian telephone number made of a two-digit area code and an eight-digit number made of two blocks of four digits (with a space between). For example: `02 1234 5678' For details see: http://en.wikipedia.org/wiki/ \ Telephone_numbers_in_Australia#Personal_numbers_.2805.29 """ area_code = random.choice(['02', '03', '04', '07', '08']) number1 = random.randint(1,9999) number2 = random.randint(1,9999) oz_phone_str = str(area_code)+' '+str(number1).zfill(4)+' '+ \ str(number2).zfill(4) assert len(oz_phone_str) == 12 assert oz_phone_str[0] == '0' return oz_phone_str # ----------------------------------------------------------------------------- # def generate_phone_number_american(): """Randomly generate an American telephone number made of a three-digit area code and an seven-digit number made of two blocks, 3 and 4 digits (with a space between). For example: `202 234 5678' http://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes """ #modify with look-up or full list area_code = random.choice(['202', '212', '215', '412', '812']) number1 = random.randint(1,999) number2 = random.randint(1,9999) #.zfill will pad zeros to the left of digits, 1 become 001 w/ zfill(3) us_phone_str = str(area_code)+' '+str(number1).zfill(3)+' '+ \ str(number2).zfill(4) assert len(us_phone_str) == 12 return us_phone_str # ----------------------------------------------------------------------------- # def generate_credit_card_number(): """Randomly generate a credit card made of four four-digit numbers (with a space between each number group). For example: '1234 5678 9012 3456' For details see: http://en.wikipedia.org/wiki/Bank_card_number """ number1 = random.randint(1,9999) assert number1 > 0 number2 = random.randint(1,9999) assert number2 > 0 number3 = random.randint(1,9999) assert number3 > 0 number4 = random.randint(1,9999) assert number4 > 0 cc_str = str(number1).zfill(4)+' '+str(number2).zfill(4)+' '+ \ str(number3).zfill(4)+' '+str(number4).zfill(4) assert len(cc_str) == 19 return cc_str # ----------------------------------------------------------------------------- # def generate_social_security_number(): """Randomly generate a social security number. For example: '234 78 9012' Update to reflect state, date of birth info consider: http://www.pnas.org/content/106/27/10975.full.pdf """ number1 = random.randint(1,999) assert number1 > 0 number2 = random.randint(1,99) assert number2 > 0 number3 = random.randint(1,9999) assert number3 > 0 ss_str = str(number1).zfill(3)+' '+str(number2).zfill(2)+' '+ \ str(number3).zfill(4) assert len(ss_str) == 11 return ss_str # ----------------------------------------------------------------------------- # def generate_drivers_license_num(): # need revision # Based on dc format only """Randomly generate a drivers license number. 7-digit or 9-digit For example: '2512235' or '682019423' Update to reflect state infor consider: http://http://adr-inc.com/PDFs/State_DLFormats.pdf According to this paper, DOB info is encoded in drivers license We should take this into consideration for further update "http://www.highprogrammer.com/alan/numbers/index.html" """ number1 = random.randint(1,9999999) assert number1 > 0 number2 = random.randint(1,999999999) assert number2 > 0 ss_str1 = str(number1).zfill(7) assert len(ss_str1) == 7 ss_str2 = str(number2).zfill(9) assert len(ss_str1) == 9 return random.choice([ss_str1, ss_str2]) # ----------------------------------------------------------------------------- # def generate_passport_num(): """Randomly generate a us passport number(9-digit number). For example: '203941429' """ number1 = random.randint(1,999999999) assert number1 > 0 passport_str = str(number1).zfill(9) assert len(passport_str) == 9 return passport_str # ----------------------------------------------------------------------------- # def generate_email_address(fname="Bohan", lname="Zhang"): """Randomly generate a email address Update middle name and nickname Update frequency table: http://www.ryansolutions.com/blog/2013/email-domains/ """ unicode_encoding_used = 'ascii' basefunctions.check_is_string('fname', fname) basefunctions.check_is_string('lname', lname) domain_name = random.choice(["@gmail.com","@hotmail.com","@yahoo.com","@aol.com", "@live.com","@msn.com", "@comcast.com"]) add1 = fname[0] + "." + lname + domain_name add2 = fname + "." + lname + domain_name add3 = fname[0] + lname + domain_name add4 = fname + lname[0] + domain_name add5 = fname + domain_name add = random.choice([add1, add2, add3, add4, add5]) return add # ----------------------------------------------------------------------------- # def generate_name_suffix(): """Randomly generate a name suffix. Assumes that 10% has a suffix' """ #modify with look-up or full list rand = random.random() if rand <= 0.10: suffix = random.choice(['Jr.', 'Snr.', 'I', 'II', 'III']) else: suffix = "" return suffix # ----------------------------------------------------------------------------- # def generate_gender(): """Randomly generate a gender.""" gender = random.choice(['Male', 'Female']) return gender def gender(g): 'gender' return g # ----------------------------------------------------------------------------- def generate_firstname(gender = 'Female'): """randomly generate a name""" if gender == 'Female': gname = generator.GenerateFreqAttribute(attribute_name = 'given-name', freq_file_name = os.path.abspath('lookup_files/firstname_female.csv'), has_header_line = False, unicode_encoding = unicode_encoding_used) if gender == 'Male': gname= generator.GenerateFreqAttribute(attribute_name = 'given-name', freq_file_name = os.path.abspath('lookup_files/firstname_male.csv'), has_header_line = False, unicode_encoding = unicode_encoding_used) return gname # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # # ----------------------------------------------------------------------------- # def generate_name_prefix_m(): """Randomly generate a name prefix.""" prefix = random.choice(['Mr', ""]) return prefix # ----------------------------------------------------------------------------- # def generate_primary(): """Randomly generate a field for a primary key""" primary = "1" return primary # ----------------------------------------------------------------------------- # def generate_name_prefix_f(): """Randomly generate a name prefix. """ prefix = random.choice(['Miss', 'Mrs', 'Ms', ""]) return prefix # ----------------------------------------------------------------------------- # def generate_prefix_from_gender(gender): """Generate prefix using gender Jamie's Test code but not currently used in generate_data_english as of 2_8""" if gender == "Male": prefix = random.choice(['Mr', ""]) if gender == "Female": prefix = random.choice(['Miss', 'Mrs', 'Ms', ""]) return prefix # #------------------------------------------------------------------------------- def generate_nickname(): """Randomly generate a nickname. Assumes that 5% has a nickname' """ import random #modify with look-up or full list rand = random.random() if rand <= .05: nickname = random.choice(['A', 'B', 'C']) else: nickname = "" return nickname def race(r): 'race' return r def hispanic(h): 'hispanic' return h #------------------------------------------------------------------------------- # Jamie to add new marital status from Census Bureau distribution: # http://www.census.gov/compendia/statab/cats/population.html def marriage(age): "Probabilities taken from US Cencus Bureau" import random numb = random.random() items = ["Single", "Married", "Separated", "Widowed", "Divorced", ""] age_bracket = [18, 19, 24, 29, 34, 39, 44, 54, 66, 74, 120] j = 0 if age < int(age_bracket[0]): mstatus = random.choice(['Single', ""]) elif age < int(age_bracket[1]): cum = [0.953, 0.983, 0.994, 0.996] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[2]): cum = [0.793, 0.967, 0.985, 0.986] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[3]): cum = [0.478, 0.919, 0.954, 0.958] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[4]): cum = [0.271, 0.87, 0.909, 0.914] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[5]): cum = [0.177, 0.832, 0.871, 0.88] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[6]): cum = [0.138, 0.804, 0.839, 0.855] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[6]): cum = [0.11, 0.759, 0.793, 0.828] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < age_bracket[7]: cum = [0.071, 0.717, 0.74, 0.822] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < age_bracket[8]: cum = [0.051, 0.597, 0.611, 0.85] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] else: cum = [0.039, 0.355, 0.362, 0.93] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] return mstatus #------------------------------------------------------------------------------- #""" Generate Fake DOB - Need to pass age which isn't working. See comments below. #For now I'm passing in a dummy age""" def generate_DOB(age=65): """Randomly generate a month & date for DOB """ import random birth_month = random.randint(1,12) if birth_month == "1" or "3" or "5" or "7" or "8" or "10" or "12": birth_day = random.randint(1,31) if birth_month == "2": birth_day = random.randint(1,28) else: birth_day = random.randint(1,30) """Can not use the age generator function here for some reason but this code worked on generate_data_english.py. For now, passing dummy age into the function to make it work for the time being. I did input reference to import generator in the beginning of the program but got stuck on 'unicode_encoding' age = generator.GenerateFreqAlt(attribute_name = 'agejy', freq_file_name = 'lookup_files/age_gender_ratio_female.csv', has_header_line = False, unicode_encoding = unicode_encoding_used) """ from time import gmtime, strftime year_system = strftime ("%Y", gmtime()) year_from_age = int(year_system) - age DOB = str(birth_month) +'/' + str(birth_day) + '/' + str(year_from_age) return DOB # ----------------------------------------------------------------------------- def generate_uniform_value(min_val, max_val, val_type): """Randomly generate a numerical value according to a uniform distribution between the minimum and maximum values given. The value type can be set as 'int', so a string formatted as an integer value is returned; or as 'float1' to 'float9', in which case a string formatted as floating-point value with the specified number of digits behind the comma is returned. Note that for certain situations and string formats a value outside the set range might be returned. For example, if min_val=100.25 and val_type='float1' the rounding can result in a string value '100.2' to be returned. Suitable minimum and maximum values need to be selected to prevent such a situation. """ basefunctions.check_is_number('min_val', min_val) basefunctions.check_is_number('max_val', max_val) assert min_val < max_val r = random.uniform(min_val, max_val) return basefunctions.float_to_str(r, val_type) # ----------------------------------------------------------------------------- # def generate_uniform_age(min_val, max_val): """Randomly generate an age value (returned as integer) according to a uniform distribution between the minimum and maximum values given. This function is simple a shorthand for: generate_uniform_value(min_val, max_val, 'int') """ assert min_val >= 0 assert max_val <= 130 return generate_uniform_value(min_val, max_val, 'int') # ----------------------------------------------------------------------------- def generate_normal_value(mu, sigma, min_val, max_val, val_type): """Randomly generate a numerical value according to a normal distribution with the mean (mu) and standard deviation (sigma) given. A minimum and maximum allowed value can given as additional parameters, if set to None then no minimum and/or maximum limit is set. The value type can be set as 'int', so a string formatted as an integer value is returned; or as 'float1' to 'float9', in which case a string formatted as floating-point value with the specified number of digits behind the comma is returned. """ basefunctions.check_is_number('mu', mu) basefunctions.check_is_number('sigma', sigma) assert sigma > 0.0 if (min_val != None): basefunctions.check_is_number('min_val', min_val) assert min_val <= mu if (max_val != None): basefunctions.check_is_number('max_val', max_val) assert max_val >= mu if ((min_val != None) and (max_val != None)): assert min_val < max_val if (min_val != None) or (max_val != None): in_range = False # For testing if the random value is with the range else: in_range = True r = random.normalvariate(mu, sigma) while (in_range == False): if ((min_val == None) or ((min_val != None) and (r >= min_val))): in_range = True if ((max_val != None) and (r > max_val)): in_range = False if (in_range == True): r_str = basefunctions.float_to_str(r, val_type) r_test = float(r_str) if (min_val != None) and (r_test < min_val): in_range = False if (max_val != None) and (r_test > max_val): in_range = False if (in_range == False): r = random.normalvariate(mu, sigma) if (min_val != None): assert r >= min_val if (max_val != None): assert r <= max_val return basefunctions.float_to_str(r, val_type) # ----------------------------------------------------------------------------- # def generate_normal_age(mu, sigma, min_val, max_val): """Randomly generate an age value (returned as integer) according to a normal distribution following the mean and standard deviation values given, and limited to age values between (including) the minimum and maximum values given. This function is simple a shorthand for: generate_normal_value(mu, sigma, min_val, max_val, 'int') """ assert min_val >= 0 assert max_val <= 130 age = generate_normal_value(mu, sigma, min_val, max_val, 'int') while ((int(age) < min_val) or (int(age) > max_val)): age = generate_normal_value(mu, sigma, min_val, max_val, 'int') return age def attrgenfunct_log(num_test=10): 'log for attrgenfunct' with open('attrgenfunct_log.txt', 'w') as output: output.write( 'Generate %d Australian telephone numbers:' % (num_test)) for i in range(num_test): output.write(' ' + generate_phone_number_australia()+',') output.write('\n') output.write( 'Generate %d credit card numbers:' % (num_test)) for i in range(num_test): output.write(' '+generate_credit_card_number()+',') output.write('\n') output.write( 'Generate %d uniformly distributed integer numbers between -100' % \ (num_test) + ' and -5:') for i in range(num_test): output.write( ' ' + generate_uniform_value(-100, -5, 'int'),) output.write('\n') output.write( 'Generate %d uniformly distributed floating-point numbers with ' % \ (num_test) + '3 digits between -55 and 55:') for i in range(num_test): output.write( ' ' + generate_uniform_value(-55, 55, 'float3')) output.write('\n') output.write( 'Generate %d uniformly distributed floating-point numbers with ' % \ (num_test) + '7 digits between 147 and 9843:') for i in range(num_test): output.write( ' ' + generate_uniform_value(147, 9843, 'float7')) output.write('\n') output.write( 'Generate %d uniformly distributed age values between 0 and 120:' % \ (num_test)) for i in range(num_test): output.write( ' ' + generate_uniform_age(0, 120)) output.write('\n') output.write( 'Generate %d uniformly distributed age values between 18 and 65:' % \ (num_test)) for i in range(num_test): output.write( ' ' + generate_uniform_age(18, 65)) output.write('\n') output.write( 'Generate %d normally distributed integer numbers between -200' % \ (num_test) + ' and -3 with mean -50 and standard deviation 44:') for i in range(num_test): output.write( ' ' + generate_normal_value(-50, 44, -200, -3, 'int')) output.write('\n') output.write( 'Generate %d normally distributed floating-point numbers with ' % \ (num_test) + '5 digits between -100 and 100 and with mean 22 and ' + \ 'standard deviation 74:') for i in range(num_test): output.write( ' ' + generate_normal_value(22, 74, -100, 100, 'float5')) output.write('\n') output.write( 'Generate %d normally distributed floating-point numbers with ' % \ (num_test) + '9 digits with mean 22 and standard deviation 74:') for i in range(num_test): output.write( ' ' + generate_normal_value(22, 74, min_val=None, max_val= None, val_type='float9')) output.write('\n') output.write( 'Generate %d normally distributed floating-point numbers with ' % \ (num_test) + '2 digits with mean 22 and standard deviation 24 that' + \ ' are larger than 10:') for i in range(num_test): output.write( ' ' + generate_normal_value(22, 74, min_val=10, max_val=None, val_type='float2')) output.write('\n') output.write( 'Generate %d normally distributed floating-point numbers with ' % \ (num_test) + '4 digits with mean 22 and standard deviation 24 that' + \ ' are smaller than 30:') for i in range(num_test): output.write( ' ' + generate_normal_value(22, 74, min_val=None, max_val=40, val_type='float4')) output.write('\n') output.write( 'Generate %d normally distributed age values between 0 and 120' % \ (num_test) + ' with mean 45 and standard deviation 22:') for i in range(num_test): output.write( ' ' + generate_normal_age(45, 22, 0, 120)) output.write('\n') output.write( 'Generate %d normally distributed age values between 18 and 65' % \ (num_test) + ' with mean 30 and standard deviation 10:') for i in range(num_test): output.write( ' ' + generate_normal_age(30, 10, 18, 65)) # ============================================================================= # If called from command line perform some examples: Generate values # if (__name__ == '__main__'): attrgenfunct_log()
32.034759
91
0.562057
# Functions that can generate attribute values. # # These are functions that can be used in the GenerateFuncAttribute() class # (see module generator.py). They generate values according to some internal # functionality. # # The requirement of any such functions are: # 1) that it must return a string # 2) it can have been 0 and 5 parameters # # # Examples of such functions are: # - Australian telephone numbers # - Japanese telephone numbers # - Credit card numbers # - US social security numbers # - Japanese social security numbers # - Uniformly distributed age values between 0 and 100 # - Normally distributed age values between 0 and 110 # etc. # Peter Christen and Dinusha Vatsalan, January-March 2012 # ============================================================================= # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # ============================================================================= import random import basefunctions, generator import csv # ----------------------------------------------------------------------------- # def generate_phone_number_australia(): """Randomly generate an Australian telephone number made of a two-digit area code and an eight-digit number made of two blocks of four digits (with a space between). For example: `02 1234 5678' For details see: http://en.wikipedia.org/wiki/ \ Telephone_numbers_in_Australia#Personal_numbers_.2805.29 """ area_code = random.choice(['02', '03', '04', '07', '08']) number1 = random.randint(1,9999) number2 = random.randint(1,9999) oz_phone_str = str(area_code)+' '+str(number1).zfill(4)+' '+ \ str(number2).zfill(4) assert len(oz_phone_str) == 12 assert oz_phone_str[0] == '0' return oz_phone_str # ----------------------------------------------------------------------------- # def generate_phone_number_american(): """Randomly generate an American telephone number made of a three-digit area code and an seven-digit number made of two blocks, 3 and 4 digits (with a space between). For example: `202 234 5678' http://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes """ #modify with look-up or full list area_code = random.choice(['202', '212', '215', '412', '812']) number1 = random.randint(1,999) number2 = random.randint(1,9999) #.zfill will pad zeros to the left of digits, 1 become 001 w/ zfill(3) us_phone_str = str(area_code)+' '+str(number1).zfill(3)+' '+ \ str(number2).zfill(4) assert len(us_phone_str) == 12 return us_phone_str # ----------------------------------------------------------------------------- # def generate_credit_card_number(): """Randomly generate a credit card made of four four-digit numbers (with a space between each number group). For example: '1234 5678 9012 3456' For details see: http://en.wikipedia.org/wiki/Bank_card_number """ number1 = random.randint(1,9999) assert number1 > 0 number2 = random.randint(1,9999) assert number2 > 0 number3 = random.randint(1,9999) assert number3 > 0 number4 = random.randint(1,9999) assert number4 > 0 cc_str = str(number1).zfill(4)+' '+str(number2).zfill(4)+' '+ \ str(number3).zfill(4)+' '+str(number4).zfill(4) assert len(cc_str) == 19 return cc_str # ----------------------------------------------------------------------------- # def generate_social_security_number(): """Randomly generate a social security number. For example: '234 78 9012' Update to reflect state, date of birth info consider: http://www.pnas.org/content/106/27/10975.full.pdf """ number1 = random.randint(1,999) assert number1 > 0 number2 = random.randint(1,99) assert number2 > 0 number3 = random.randint(1,9999) assert number3 > 0 ss_str = str(number1).zfill(3)+' '+str(number2).zfill(2)+' '+ \ str(number3).zfill(4) assert len(ss_str) == 11 return ss_str # ----------------------------------------------------------------------------- # def generate_drivers_license_num(): # need revision # Based on dc format only """Randomly generate a drivers license number. 7-digit or 9-digit For example: '2512235' or '682019423' Update to reflect state infor consider: http://http://adr-inc.com/PDFs/State_DLFormats.pdf According to this paper, DOB info is encoded in drivers license We should take this into consideration for further update "http://www.highprogrammer.com/alan/numbers/index.html" """ number1 = random.randint(1,9999999) assert number1 > 0 number2 = random.randint(1,999999999) assert number2 > 0 ss_str1 = str(number1).zfill(7) assert len(ss_str1) == 7 ss_str2 = str(number2).zfill(9) assert len(ss_str1) == 9 return random.choice([ss_str1, ss_str2]) # ----------------------------------------------------------------------------- # def generate_passport_num(): """Randomly generate a us passport number(9-digit number). For example: '203941429' """ number1 = random.randint(1,999999999) assert number1 > 0 passport_str = str(number1).zfill(9) assert len(passport_str) == 9 return passport_str # ----------------------------------------------------------------------------- # def generate_email_address(fname="Bohan", lname="Zhang"): """Randomly generate a email address Update middle name and nickname Update frequency table: http://www.ryansolutions.com/blog/2013/email-domains/ """ unicode_encoding_used = 'ascii' basefunctions.check_is_string('fname', fname) basefunctions.check_is_string('lname', lname) domain_name = random.choice(["@gmail.com","@hotmail.com","@yahoo.com","@aol.com", "@live.com","@msn.com", "@comcast.com"]) add1 = fname[0] + "." + lname + domain_name add2 = fname + "." + lname + domain_name add3 = fname[0] + lname + domain_name add4 = fname + lname[0] + domain_name add5 = fname + domain_name add = random.choice([add1, add2, add3, add4, add5]) return add # ----------------------------------------------------------------------------- # def generate_name_suffix(): """Randomly generate a name suffix. Assumes that 10% has a suffix' """ #modify with look-up or full list rand = random.random() if rand <= 0.10: suffix = random.choice(['Jr.', 'Snr.', 'I', 'II', 'III']) else: suffix = "" return suffix # ----------------------------------------------------------------------------- # def generate_gender(): """Randomly generate a gender.""" gender = random.choice(['Male', 'Female']) return gender def gender(g): 'gender' return g # ----------------------------------------------------------------------------- def generate_firstname(gender = 'Female'): """randomly generate a name""" if gender == 'Female': gname = generator.GenerateFreqAttribute(attribute_name = 'given-name', freq_file_name = os.path.abspath('lookup_files/firstname_female.csv'), has_header_line = False, unicode_encoding = unicode_encoding_used) if gender == 'Male': gname= generator.GenerateFreqAttribute(attribute_name = 'given-name', freq_file_name = os.path.abspath('lookup_files/firstname_male.csv'), has_header_line = False, unicode_encoding = unicode_encoding_used) return gname # ----------------------------------------------------------------------------- def generate_surname_m(): surname = "" return surname # ----------------------------------------------------------------------------- def generate_city(): city = "Washington" return city # ----------------------------------------------------------------------------- def generate_state(): state = "DC" return state # ----------------------------------------------------------------------------- # def generate_address(): choice = random.randint(1,244118) f = open('lookup_files/addresses.csv') csv_f = csv.reader(f) csv_f = list(csv_f) address = csv_f[choice][0] return address # ----------------------------------------------------------------------------- # def generate_name_prefix_m(): """Randomly generate a name prefix.""" prefix = random.choice(['Mr', ""]) return prefix # ----------------------------------------------------------------------------- # def generate_primary(): """Randomly generate a field for a primary key""" primary = "1" return primary # ----------------------------------------------------------------------------- # def generate_name_prefix_f(): """Randomly generate a name prefix. """ prefix = random.choice(['Miss', 'Mrs', 'Ms', ""]) return prefix # ----------------------------------------------------------------------------- # def generate_prefix_from_gender(gender): """Generate prefix using gender Jamie's Test code but not currently used in generate_data_english as of 2_8""" if gender == "Male": prefix = random.choice(['Mr', ""]) if gender == "Female": prefix = random.choice(['Miss', 'Mrs', 'Ms', ""]) return prefix # #------------------------------------------------------------------------------- def generate_nickname(): """Randomly generate a nickname. Assumes that 5% has a nickname' """ import random #modify with look-up or full list rand = random.random() if rand <= .05: nickname = random.choice(['A', 'B', 'C']) else: nickname = "" return nickname def race(r): 'race' return r def hispanic(h): 'hispanic' return h #------------------------------------------------------------------------------- # Jamie to add new marital status from Census Bureau distribution: # http://www.census.gov/compendia/statab/cats/population.html def marriage(age): "Probabilities taken from US Cencus Bureau" import random numb = random.random() items = ["Single", "Married", "Separated", "Widowed", "Divorced", ""] age_bracket = [18, 19, 24, 29, 34, 39, 44, 54, 66, 74, 120] j = 0 if age < int(age_bracket[0]): mstatus = random.choice(['Single', ""]) elif age < int(age_bracket[1]): cum = [0.953, 0.983, 0.994, 0.996] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[2]): cum = [0.793, 0.967, 0.985, 0.986] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[3]): cum = [0.478, 0.919, 0.954, 0.958] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[4]): cum = [0.271, 0.87, 0.909, 0.914] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[5]): cum = [0.177, 0.832, 0.871, 0.88] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[6]): cum = [0.138, 0.804, 0.839, 0.855] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < int(age_bracket[6]): cum = [0.11, 0.759, 0.793, 0.828] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < age_bracket[7]: cum = [0.071, 0.717, 0.74, 0.822] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] elif age < age_bracket[8]: cum = [0.051, 0.597, 0.611, 0.85] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] else: cum = [0.039, 0.355, 0.362, 0.93] if numb < cum[0]: mstatus = items[0] elif numb < cum[1]: mstatus = items[1] elif numb < cum[2]: mstatus = items[2] elif numb < cum[3]: mstatus = items[3] else: mstatus = items[4] return mstatus #------------------------------------------------------------------------------- #""" Generate Fake DOB - Need to pass age which isn't working. See comments below. #For now I'm passing in a dummy age""" def generate_DOB(age=65): """Randomly generate a month & date for DOB """ import random birth_month = random.randint(1,12) if birth_month == "1" or "3" or "5" or "7" or "8" or "10" or "12": birth_day = random.randint(1,31) if birth_month == "2": birth_day = random.randint(1,28) else: birth_day = random.randint(1,30) """Can not use the age generator function here for some reason but this code worked on generate_data_english.py. For now, passing dummy age into the function to make it work for the time being. I did input reference to import generator in the beginning of the program but got stuck on 'unicode_encoding' age = generator.GenerateFreqAlt(attribute_name = 'agejy', freq_file_name = 'lookup_files/age_gender_ratio_female.csv', has_header_line = False, unicode_encoding = unicode_encoding_used) """ from time import gmtime, strftime year_system = strftime ("%Y", gmtime()) year_from_age = int(year_system) - age DOB = str(birth_month) +'/' + str(birth_day) + '/' + str(year_from_age) return DOB # ----------------------------------------------------------------------------- def generate_uniform_value(min_val, max_val, val_type): """Randomly generate a numerical value according to a uniform distribution between the minimum and maximum values given. The value type can be set as 'int', so a string formatted as an integer value is returned; or as 'float1' to 'float9', in which case a string formatted as floating-point value with the specified number of digits behind the comma is returned. Note that for certain situations and string formats a value outside the set range might be returned. For example, if min_val=100.25 and val_type='float1' the rounding can result in a string value '100.2' to be returned. Suitable minimum and maximum values need to be selected to prevent such a situation. """ basefunctions.check_is_number('min_val', min_val) basefunctions.check_is_number('max_val', max_val) assert min_val < max_val r = random.uniform(min_val, max_val) return basefunctions.float_to_str(r, val_type) # ----------------------------------------------------------------------------- # def generate_uniform_age(min_val, max_val): """Randomly generate an age value (returned as integer) according to a uniform distribution between the minimum and maximum values given. This function is simple a shorthand for: generate_uniform_value(min_val, max_val, 'int') """ assert min_val >= 0 assert max_val <= 130 return generate_uniform_value(min_val, max_val, 'int') # ----------------------------------------------------------------------------- def generate_normal_value(mu, sigma, min_val, max_val, val_type): """Randomly generate a numerical value according to a normal distribution with the mean (mu) and standard deviation (sigma) given. A minimum and maximum allowed value can given as additional parameters, if set to None then no minimum and/or maximum limit is set. The value type can be set as 'int', so a string formatted as an integer value is returned; or as 'float1' to 'float9', in which case a string formatted as floating-point value with the specified number of digits behind the comma is returned. """ basefunctions.check_is_number('mu', mu) basefunctions.check_is_number('sigma', sigma) assert sigma > 0.0 if (min_val != None): basefunctions.check_is_number('min_val', min_val) assert min_val <= mu if (max_val != None): basefunctions.check_is_number('max_val', max_val) assert max_val >= mu if ((min_val != None) and (max_val != None)): assert min_val < max_val if (min_val != None) or (max_val != None): in_range = False # For testing if the random value is with the range else: in_range = True r = random.normalvariate(mu, sigma) while (in_range == False): if ((min_val == None) or ((min_val != None) and (r >= min_val))): in_range = True if ((max_val != None) and (r > max_val)): in_range = False if (in_range == True): r_str = basefunctions.float_to_str(r, val_type) r_test = float(r_str) if (min_val != None) and (r_test < min_val): in_range = False if (max_val != None) and (r_test > max_val): in_range = False if (in_range == False): r = random.normalvariate(mu, sigma) if (min_val != None): assert r >= min_val if (max_val != None): assert r <= max_val return basefunctions.float_to_str(r, val_type) # ----------------------------------------------------------------------------- # def generate_normal_age(mu, sigma, min_val, max_val): """Randomly generate an age value (returned as integer) according to a normal distribution following the mean and standard deviation values given, and limited to age values between (including) the minimum and maximum values given. This function is simple a shorthand for: generate_normal_value(mu, sigma, min_val, max_val, 'int') """ assert min_val >= 0 assert max_val <= 130 age = generate_normal_value(mu, sigma, min_val, max_val, 'int') while ((int(age) < min_val) or (int(age) > max_val)): age = generate_normal_value(mu, sigma, min_val, max_val, 'int') return age def attrgenfunct_log(num_test=10): 'log for attrgenfunct' with open('attrgenfunct_log.txt', 'w') as output: output.write( 'Generate %d Australian telephone numbers:' % (num_test)) for i in range(num_test): output.write(' ' + generate_phone_number_australia()+',') output.write('\n') output.write( 'Generate %d credit card numbers:' % (num_test)) for i in range(num_test): output.write(' '+generate_credit_card_number()+',') output.write('\n') output.write( 'Generate %d uniformly distributed integer numbers between -100' % \ (num_test) + ' and -5:') for i in range(num_test): output.write( ' ' + generate_uniform_value(-100, -5, 'int'),) output.write('\n') output.write( 'Generate %d uniformly distributed floating-point numbers with ' % \ (num_test) + '3 digits between -55 and 55:') for i in range(num_test): output.write( ' ' + generate_uniform_value(-55, 55, 'float3')) output.write('\n') output.write( 'Generate %d uniformly distributed floating-point numbers with ' % \ (num_test) + '7 digits between 147 and 9843:') for i in range(num_test): output.write( ' ' + generate_uniform_value(147, 9843, 'float7')) output.write('\n') output.write( 'Generate %d uniformly distributed age values between 0 and 120:' % \ (num_test)) for i in range(num_test): output.write( ' ' + generate_uniform_age(0, 120)) output.write('\n') output.write( 'Generate %d uniformly distributed age values between 18 and 65:' % \ (num_test)) for i in range(num_test): output.write( ' ' + generate_uniform_age(18, 65)) output.write('\n') output.write( 'Generate %d normally distributed integer numbers between -200' % \ (num_test) + ' and -3 with mean -50 and standard deviation 44:') for i in range(num_test): output.write( ' ' + generate_normal_value(-50, 44, -200, -3, 'int')) output.write('\n') output.write( 'Generate %d normally distributed floating-point numbers with ' % \ (num_test) + '5 digits between -100 and 100 and with mean 22 and ' + \ 'standard deviation 74:') for i in range(num_test): output.write( ' ' + generate_normal_value(22, 74, -100, 100, 'float5')) output.write('\n') output.write( 'Generate %d normally distributed floating-point numbers with ' % \ (num_test) + '9 digits with mean 22 and standard deviation 74:') for i in range(num_test): output.write( ' ' + generate_normal_value(22, 74, min_val=None, max_val= None, val_type='float9')) output.write('\n') output.write( 'Generate %d normally distributed floating-point numbers with ' % \ (num_test) + '2 digits with mean 22 and standard deviation 24 that' + \ ' are larger than 10:') for i in range(num_test): output.write( ' ' + generate_normal_value(22, 74, min_val=10, max_val=None, val_type='float2')) output.write('\n') output.write( 'Generate %d normally distributed floating-point numbers with ' % \ (num_test) + '4 digits with mean 22 and standard deviation 24 that' + \ ' are smaller than 30:') for i in range(num_test): output.write( ' ' + generate_normal_value(22, 74, min_val=None, max_val=40, val_type='float4')) output.write('\n') output.write( 'Generate %d normally distributed age values between 0 and 120' % \ (num_test) + ' with mean 45 and standard deviation 22:') for i in range(num_test): output.write( ' ' + generate_normal_age(45, 22, 0, 120)) output.write('\n') output.write( 'Generate %d normally distributed age values between 18 and 65' % \ (num_test) + ' with mean 30 and standard deviation 10:') for i in range(num_test): output.write( ' ' + generate_normal_age(30, 10, 18, 65)) # ============================================================================= # If called from command line perform some examples: Generate values # if (__name__ == '__main__'): attrgenfunct_log()
284
0
100
548255d2dbe0cab9d4fa99c132b58e09a06d7d2c
6,166
py
Python
mkdocs_terraform_monorepo_plugin/parser.py
wtc-cloud-eng/mkdocs-terraform-monorepo-plugin
a6bb70638219ae358e66923640d958608196b082
[ "Apache-2.0" ]
3
2021-03-11T13:53:42.000Z
2021-03-12T12:06:00.000Z
mkdocs_terraform_monorepo_plugin/parser.py
wtc-cloud-eng/mkdocs-terraform-monorepo-plugin
a6bb70638219ae358e66923640d958608196b082
[ "Apache-2.0" ]
53
2021-03-26T18:05:22.000Z
2022-03-28T13:12:33.000Z
mkdocs_terraform_monorepo_plugin/parser.py
wtc-cloud-eng/mkdocs-terraform-monorepo-plugin
a6bb70638219ae358e66923640d958608196b082
[ "Apache-2.0" ]
null
null
null
import logging import os import copy from pathlib import Path from mkdocs.utils import warning_filter log = logging.getLogger(__name__) log.addFilter(warning_filter) INCLUDE_STATEMENT = "!tf_modules_root " # TODO should make these config variables in mkdocs.yml DOCUMENT_FILE_NAME = 'README.md' NAVIGATION_KEY_NAME = 'About'
39.273885
104
0.554817
import logging import os import copy from pathlib import Path from mkdocs.utils import warning_filter log = logging.getLogger(__name__) log.addFilter(warning_filter) INCLUDE_STATEMENT = "!tf_modules_root " # TODO should make these config variables in mkdocs.yml DOCUMENT_FILE_NAME = 'README.md' NAVIGATION_KEY_NAME = 'About' class TfParser: def __init__(self, config): self.initialNav = config['nav'] self.config = config self.resolvedPaths = [] def getResolvedPaths(self): return self.resolvedPaths def resolve(self, nav=None): # noqa: C901 if nav is None: nav = copy.deepcopy(self.initialNav) # log.critical("nav: {} ".format(nav)) for index, item in enumerate(nav): if type(item) is str: key = None value = item # log.critical("value1 = {}".format(value)) elif type(item) is dict: key = list(item.keys())[0] value = list(item.values())[0] # log.critical("value2 = {}".format(value)) else: key = None value = None if type(value) is str and INCLUDE_STATEMENT in value: # log.critical("value3 = {}".format(value)) nav[index] = {} alias = value.split(INCLUDE_STATEMENT)[0] if alias is INCLUDE_STATEMENT: alias == "" else: alias = alias.rstrip('/') modPath = value.split(INCLUDE_STATEMENT)[-1] modNav = CreateModulesNav( self.config, alias, modPath ).build() # log.critical("modNav = {}".format(modNav.getNav())) # log.critical("key = {}".format(key)) nav[index][key] = modNav.getNav() if nav[index][key] is None: del nav[index][key] continue else: self.resolvedPaths = [*self.resolvedPaths, *modNav.getResolvedPaths()] elif type(value) is list: # log.critical("value4 = {}".format(value)) nav[index] = {} nav[index][key] = self.resolve(value) if nav[index][key] is None: del nav[index][key] continue for index, item in enumerate(nav): if nav[index] == {}: del nav[index] return nav class CreateModulesNav: def __init__(self, config, alias, modulePath): # log.critical("config = {}".format(config)) # log.critical("alias = {}".format(alias)) # log.critical("modulePath = {}".format(modulePath)) # log.critical("cwd = {}".format(os.getcwd())) # log.critical("config[config_file_path] = {}".format(config['config_file_path'])) self.rootDir = os.path.normpath(os.path.join( os.getcwd(), os.path.dirname(config['config_file_path']), modulePath, '../')) # log.critical("rootDir = {}".format(self.rootDir)) self.alias = alias self.modulePath = modulePath p = Path(self.modulePath) basePath = modulePath if len(p.parts) > 1: # this is if we are in a nested mkdocs for monorepo etc basePath = p.relative_to(*p.parts[:1]) # log.critical("basePath = {}".format(basePath)) self.absModulePath = os.path.normpath( os.path.join(self.rootDir, basePath)) # log.critical("absModulePath = {}".format(self.absModulePath)) self.moduleNav = None self.resolvedPaths = None def getAbsModulePath(self): return self.absModulePath def build(self): if not os.path.exists(self.absModulePath): log.critical( "[mkdocs-terraform-monorepo] The path {} is not valid. ".format(self.absModulePath) + "Please update your 'nav' with a valid path (relative to the mkdocs.yml file).") raise SystemExit(1) allPaths = [] for path in Path(self.absModulePath+'/').rglob(DOCUMENT_FILE_NAME): allPaths.append(str(path.relative_to(Path(self.absModulePath).parent))) # log.critical("allPaths = {}".format(allPaths)) # TODO need to check full path is not in an ignore list allPaths = sorted(allPaths) for file in allPaths: if self.moduleNav is None: self.moduleNav = {} self.moduleNav = self.__build_nested( os.path.join(self.alias, file), self.moduleNav) if self.resolvedPaths is None: self.resolvedPaths = [] self.resolvedPaths.append( [os.path.join(self.alias, file), os.path.join(self.rootDir, file)]) # log.critical("moduleNav = {}".format(self.moduleNav)) # log.critical("resolvedPaths = {}".format(self.resolvedPaths)) return self def __build_nested_helper(self, path, file, container): segs = Path(path).parts head, tail = segs[0], segs[1:] if len(tail) == 1 or not tail: if head == DOCUMENT_FILE_NAME: head = NAVIGATION_KEY_NAME container[head] = file # container = [file] else: if head not in container: container[head] = self.__build_nested_helper(os.path.join(*tail), file, {}) else: if type(container[head]) is str: container[head] = {NAVIGATION_KEY_NAME: container[head]} # container = [container[head]] # send it round again, avoiding the file loop container[head] = self.__build_nested_helper(os.path.join(*tail), file, container[head]) return container def __build_nested(self, file, container): return self.__build_nested_helper(os.path.join(*(Path(file).parts[1:])), file, container) def getNav(self): return self.moduleNav def getResolvedPaths(self): return self.resolvedPaths
5,526
-4
314
c1d329add48daaf9b6c1f2cfa1999f82cfa7b64c
202
py
Python
samples/docs/simple.py
sidneyarcidiacono/coworks
7f51b83e8699ced991d16a5a43ad19e569b6e814
[ "MIT" ]
null
null
null
samples/docs/simple.py
sidneyarcidiacono/coworks
7f51b83e8699ced991d16a5a43ad19e569b6e814
[ "MIT" ]
null
null
null
samples/docs/simple.py
sidneyarcidiacono/coworks
7f51b83e8699ced991d16a5a43ad19e569b6e814
[ "MIT" ]
null
null
null
from coworks import TechMicroService from coworks import entry app = SimpleMicroService()
14.428571
43
0.727723
from coworks import TechMicroService from coworks import entry class SimpleMicroService(TechMicroService): @entry def get(self): return "Hello world.\n" app = SimpleMicroService()
25
60
23
98dcad3246ee4b1c4180827431f1ba0900947c7c
4,013
py
Python
whois/whois.py
jacobdshimer/Python-Misc-Scripts
d3a33d78542ef0492939334d176f231fb363f894
[ "MIT" ]
null
null
null
whois/whois.py
jacobdshimer/Python-Misc-Scripts
d3a33d78542ef0492939334d176f231fb363f894
[ "MIT" ]
null
null
null
whois/whois.py
jacobdshimer/Python-Misc-Scripts
d3a33d78542ef0492939334d176f231fb363f894
[ "MIT" ]
null
null
null
import urllib3 import csv import os import json import arin urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # TODO: Add in reverse lookup csvfile = open('countries_by_rir.csv', 'r') readcsv = csv.reader(csvfile, delimiter=',') rir = {'AFRINIC': [], 'APNIC': [], 'ARIN': [], 'RIPE NCC': [], 'LACNIC': [] } for row in readcsv: key = row[3] if key in rir: rir[key].append(row[0].lower()) if __name__ == "__main__": main()
37.858491
146
0.427859
import urllib3 import csv import os import json import arin urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # TODO: Add in reverse lookup csvfile = open('countries_by_rir.csv', 'r') readcsv = csv.reader(csvfile, delimiter=',') rir = {'AFRINIC': [], 'APNIC': [], 'ARIN': [], 'RIPE NCC': [], 'LACNIC': [] } for row in readcsv: key = row[3] if key in rir: rir[key].append(row[0].lower()) def checkIPcountry(ip_addr): http = urllib3.PoolManager() page = http.request('GET', 'https://geoip-db.com/jsonp/' + ip_addr).data.decode().strip("callback").strip('(').strip(')') return json.loads(page) def main(): csvfile = open('countries_by_rir.csv', 'r') readcsv = csv.reader(csvfile, delimiter=',') http = urllib3.PoolManager() running = True while running: print("\nSimple WhoIs Lookup Program") print("1) Lookup IP") print("2) Resolve FQDN") selection = input("Selection> ") if selection == "quit": running = False elif selection == "1": print("\nWhat is the IP you want to look up?") ip_addr = input("IP> ") if ip_addr == "quit": running = False else: country = checkIPcountry(ip_addr) country = country['country_name'] for key,value in rir.items(): if country.lower() in value: registry = key if registry == "ARIN": page = http.request('GET', 'http://whois.arin.net/rest/ip/' + ip_addr + '.txt') status = page.status data = page.data.decode().split("\n") if status == 200: for line in data: if line == '' or '#' in line: continue else: print(line) moreinformation = True parent = str([s for s in data if "Parent" in s]).split()[2].replace("'", "").replace("]","").strip("(").strip(")") organization = str([s for s in data if "Organization" in s]).split()[3].replace("'", "").replace("]","").strip("(").strip(")") while moreinformation: print("\nWould you like to find more information?") print("1) Parent Information") print("2) Organization Information") selection = input("Selection> ") if selection == "quit": moreinformation = False running = False elif selection == "1": print() page = http.request('GET', 'https://whois.arin.net/rest/net/' + parent + '.txt') status = page.status if status == 200: for line in page.data.decode().split("\n"): if line == '' or '#' in line: continue else: print(line) elif selection == "2": page = http.request('GET', 'https://whois.arin.net/rest/org/' + organization + '.txt') status = page.status if status == 200: for line in page.data.decode().split("\n"): if line == '' or '#' in line: continue else: print(line) elif register == "AFRINIC": print("test") if __name__ == "__main__": main()
3,459
0
46
680252ce879d90c59db8b12d25a4d27573909ee8
535
py
Python
publish.py
jpbarto/redis_benchmark
0a926f45d9955aa4d03795b9e363bf1a85011c91
[ "Apache-2.0" ]
null
null
null
publish.py
jpbarto/redis_benchmark
0a926f45d9955aa4d03795b9e363bf1a85011c91
[ "Apache-2.0" ]
null
null
null
publish.py
jpbarto/redis_benchmark
0a926f45d9955aa4d03795b9e363bf1a85011c91
[ "Apache-2.0" ]
null
null
null
import redis import json import uuid import time HOST = 'localhost' PORT = 6379 MSG_COUNT = 250000 r = redis.Redis (host = HOST, port = PORT) pub = r.pubsub () sender_id = uuid.uuid4 () start_time = time.time () for i in range (MSG_COUNT): data = {"sender_id": str(sender_id), "message_id": i, "body": "I am message number {}".format (i)} r.publish ('a_topic', json.dumps (data)) end_time = time.time () print ("Published {} messages with sender ID {} in {} seconds".format (MSG_COUNT, sender_id, (end_time - start_time)))
25.47619
118
0.676636
import redis import json import uuid import time HOST = 'localhost' PORT = 6379 MSG_COUNT = 250000 r = redis.Redis (host = HOST, port = PORT) pub = r.pubsub () sender_id = uuid.uuid4 () start_time = time.time () for i in range (MSG_COUNT): data = {"sender_id": str(sender_id), "message_id": i, "body": "I am message number {}".format (i)} r.publish ('a_topic', json.dumps (data)) end_time = time.time () print ("Published {} messages with sender ID {} in {} seconds".format (MSG_COUNT, sender_id, (end_time - start_time)))
0
0
0
7695cce9e1bb37ade56725cc1738bb7551d90a27
1,981
py
Python
backend/flask_app/api/wallet.py
zIPjahoda/Flask-Angular
a31bfdd27aa30fffd6cacd6f27305f523879e710
[ "MIT" ]
null
null
null
backend/flask_app/api/wallet.py
zIPjahoda/Flask-Angular
a31bfdd27aa30fffd6cacd6f27305f523879e710
[ "MIT" ]
null
null
null
backend/flask_app/api/wallet.py
zIPjahoda/Flask-Angular
a31bfdd27aa30fffd6cacd6f27305f523879e710
[ "MIT" ]
null
null
null
from flask import Blueprint import json import logging import traceback from datetime import datetime from flask import Response, request, jsonify, current_app from gevent.wsgi import WSGIServer from flask_jwt_simple import ( JWTManager, jwt_required, create_jwt, get_jwt_identity, get_jwt ) from backend.flask_app.models import Session, User, Wallet from backend.flask_app.http_codes import Status from backend.flask_app.factory import create_app, create_user from flask_security.utils import hash_password, verify_password wallet = Blueprint('wallet', __name__) logger = logging.getLogger(__name__) app = create_app() jwt = JWTManager(app) @wallet.route('/add', methods=['POST']) @jwt_required
31.951613
108
0.720343
from flask import Blueprint import json import logging import traceback from datetime import datetime from flask import Response, request, jsonify, current_app from gevent.wsgi import WSGIServer from flask_jwt_simple import ( JWTManager, jwt_required, create_jwt, get_jwt_identity, get_jwt ) from backend.flask_app.models import Session, User, Wallet from backend.flask_app.http_codes import Status from backend.flask_app.factory import create_app, create_user from flask_security.utils import hash_password, verify_password wallet = Blueprint('wallet', __name__) logger = logging.getLogger(__name__) app = create_app() jwt = JWTManager(app) @wallet.route('/add', methods=['POST']) @jwt_required def wallet_add(): logger.info('Add new wallet') identity = get_jwt_identity() if not identity: return jsonify({"msg": "Token invalid"}), Status.HTTP_BAD_UNAUTHORIZED if not Session.query(User).filter_by(email=identity).first(): return jsonify({"msg": "No exist user"}), Status.HTTP_BAD_UNAUTHORIZED params = request.get_json() wallet_address = params.get('wallet_address', None) token_id = params.get('token_id', None) user = Session.query(User).filter_by(email=identity).first() if not wallet_address: return jsonify({"msg": "Missing wallet parameter"}), Status.HTTP_BAD_REQUEST if Session.query(User).filter_by(wallet=wallet_address).first(): return jsonify({"msg": "wallet is already exist"}), Status.HTTP_BAD_REQUEST if not token_id or len(token_id) < 8: return jsonify({'msg': "Missing token_id parameter, minimum 8 characters"}), Status.HTTP_BAD_REQUEST new_wallet = { 'id_user': user.id, 'id_coin': token_id, 'id_exchange': 1, 'address': wallet_address, 'deposit': 0 } Wallet.add(new_wallet) # aktualizovat penezenku a ziskat aktualni zustatky ret = {'msg': 'Success add wallet address'} return jsonify(ret), 200
1,253
0
22
cbbdaa273a9753aa6dd34408775ff7f313bfeb7e
790
py
Python
MITx-6.00.1x-EDX-Introduction-to-Computer-Science/Week-2/PSET-1/countingBobs.py
lilsweetcaligula/MIT6.00.1x
ee2902782a08ff685e388b2f40c09ea8c9c5fcfe
[ "MIT" ]
null
null
null
MITx-6.00.1x-EDX-Introduction-to-Computer-Science/Week-2/PSET-1/countingBobs.py
lilsweetcaligula/MIT6.00.1x
ee2902782a08ff685e388b2f40c09ea8c9c5fcfe
[ "MIT" ]
null
null
null
MITx-6.00.1x-EDX-Introduction-to-Computer-Science/Week-2/PSET-1/countingBobs.py
lilsweetcaligula/MIT6.00.1x
ee2902782a08ff685e388b2f40c09ea8c9c5fcfe
[ "MIT" ]
null
null
null
""" PSET-1 Counting Bobs Assume s is a string of lower case characters. Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print: Number of times bob occurs is: 2 """ py_main()
21.351351
65
0.588608
""" PSET-1 Counting Bobs Assume s is a string of lower case characters. Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print: Number of times bob occurs is: 2 """ def countPal(target, pal): midPoint = int(len(pal) / 2) searchStatus = 0 startAt = 0 count = 0 while searchStatus != -1: searchStatus = target.find(pal, startAt) if searchStatus == -1: break else: count += 1 startAt = searchStatus + midPoint return count def py_main(): pal = "bob" n = countPal(s, pal) ANS_STR = "Number of times %s occurs is: %d" print(ANS_STR % (pal, n)) return 0 py_main()
455
0
54