答:
This answer by Wang is the correct way to do this: https://stackoverflow.com/a/45503187/3176550</p>
```<code>list_of_ips = ['10.0.0.0', '10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.5']
import ipaddress
nets = [ipaddress.ip_network(_ip) for _ip in list_of_ips]
cidrs = ipaddress.collapse_addresses(nets)
list(cidrs)
Out[6]: [IPv4Network('10.0.0.0/30'), IPv4Network('10.0.0.5/32')]
</code>```

Title: Python convert a list of ips into a list of networks

Body:
I have a list of ips like this;

ban = ['162.210.197.58', '36.72.31.198', '163.172.221.63', '134.35.42.49', '176.65.117.81', '46.8.28.110', '110.139.16.72', '31.29.61.218', '38.95.109.67', '31.155.204.143', '5.254.65.190', '46.101.127.145', '111.15.193.84', '187.142.198.151', '188.227.45.110', '125.236.168.242', '5.254.65.122', '5.254.65.28', '185.182.81.93', '188.210.133.199', '151.241.125.237', '207.148.111.126', '145.239.70.231', '2.94.113.65', '204.85.191.30', '2.229.128.135', '92.127.255.182', '46.133.77.143', '118.69.63.15', '46.39.55.162', '185.182.81.14', '188.244.132.49', '138.197.160.121', '176.15.222.56', '82.178.233.175', '94.41.43.252', '78.137.73.171', '5.142.90.22', '212.2.212.151', '207.244.77.174', '176.59.46.108', '179.7.106.194', '154.118.17.57', '5.254.65.119', '176.33.236.247', '41.218.215.25', '199.249.224.47', '207.244.83.97', '84.241.13.93', '197.210.54.218', '93.35.166.148', '218.107.49.9', '39.55.130.71', '78.168.207.252', '213.141.227.238', '36.69.70.20', '5.254.65.218', '103.10.197.12', '207.244.83.194', '122.163.128.154', '93.185.16.82', '95.24.168.216', '103.16.26.148', '118.100.59.199', '209.59.188.147', '207.244.93.234', '88.81.46.212', '23.105.140.146', '89.104.104.225', '83.149.21.13', '41.34.51.195', '146.185.133.214', '37.204.108.198', '188.123.231.194', '85.140.3.172', '185.182.81.45', '185.182.81.61', '5.254.65.213', '185.182.81.136', '103.10.197.205', '185.182.81.86', '207.244.79.138', '116.240.84.42', '91.219.101.68', '80.191.221.23', '178.62.220.63', '209.58.148.85', '167.114.159.186', '108.59.8.246', '74.82.17.84', '178.129.172.216', '36.72.178.137', '41.254.7.157', '185.190.241.83', '185.182.81.58', '107.77.209.79', '207.244.77.137', '58.27.54.130', '69.15.118.106', '85.94.0.117', '41.215.173.28', '185.182.81.28', '46.101.18.209', '5.254.65.185', '195.123.217.178', '2.48.190.213', '188.247.190.79', '192.119.160.190', '95.72.13.156', '68.149.146.193', '197.157.244.206', '103.10.197.157', '176.195.155.114', '194.88.107.55', '83.220.237.120', '185.182.81.53', '82.102.21.114', '84.241.6.212', '207.244.78.48', '125.238.220.170', '159.8.170.20', '176.15.60.114', '46.138.146.207', '128.199.201.63', '5.254.65.179', '45.242.236.151', '188.162.177.199', '186.68.202.84', '5.202.179.40', '41.215.173.10', '103.255.6.80', '83.102.219.15', '188.32.127.17', '185.182.81.89', '207.244.86.235', '212.252.141.6', '37.147.79.146', '176.59.80.125', '212.71.255.8', '87.240.26.58', '91.79.215.243', '185.182.81.6', '207.244.83.102', '185.182.81.20', '109.133.114.88', '199.249.223.78', '37.110.94.227', '185.182.81.42', '109.252.76.194', '167.99.46.145', '95.221.186.30', '185.48.188.131', '2.191.41.213', '82.113.106.115', '178.62.102.23', '197.255.118.226', '185.182.81.12', '41.207.5.116', '68.133.80.56', '103.255.7.6', '162.210.197.53', '138.197.174.120', '185.182.81.40', '154.124.87.182', '73.218.73.13', '185.182.81.66', '139.5.231.112', '185.69.124.60', '93.190.177.36', '207.244.79.136', '66.160.199.70', '78.106.211.173', '121.52.156.4', '109.201.133.100', '78.85.40.39', '91.79.162.72', '83.242.238.138', '5.254.65.125', '5.254.65.175', '103.214.2.4', '37.232.192.102', '61.5.58.240', '41.190.14.40', '146.185.157.250', '195.123.225.47', '103.60.210.61', '85.102.111.101', '77.30.202.151', '194.146.149.46', '95.27.45.39', '146.185.158.24', '207.244.86.240', '195.175.45.154', '195.149.108.48', '95.12.119.124', '82.102.31.203', '156.221.118.172', '78.108.178.87', '185.182.81.37', '41.219.31.245', '191.43.27.200', '142.44.210.125', '5.254.65.169', '46.196.145.191', '68.133.80.55', '5.254.65.127', '68.133.80.58', '31.173.84.201', '39.50.173.251', '46.242.10.175', '201.208.20.239', '174.16.34.27', '65.19.167.132', '182.0.139.135', '128.68.185.234', '78.178.85.114', '182.182.91.44', '103.10.197.155', '199.249.223.77', '46.173.75.34', '197.32.29.188', '185.18.46.170', '107.181.182.227', '105.50.114.109', '199.87.154.255', '185.182.81.23', '5.115.181.178', '67.205.137.158', '46.73.40.13', '117.224.14.73', '155.239.150.15', '98.253.130.3', '122.129.77.114', '176.194.163.88', '109.63.235.0', '85.140.7.208', '207.244.82.229', '94.29.124.69', '188.245.245.146', '78.177.102.153', '197.210.173.174', '85.174.236.178', '82.247.106.95', '207.244.83.218', '162.210.197.55', '185.180.197.65', '31.8.130.8', '114.124.135.2', '46.172.203.108', '185.182.81.41', '199.115.116.37', '207.244.78.175', '207.244.77.139', '185.182.81.85', '172.56.30.213', '79.126.114.90', '5.254.65.114', '207.244.77.9', '103.10.197.202', '87.245.249.103', '185.182.81.48', '39.54.218.203', '109.169.172.138', '39.50.16.30', '89.104.104.227', '78.189.31.17', '207.244.77.19', '95.28.26.67', '39.54.6.166', '145.255.169.92', '176.43.253.71', '185.107.70.202', '65.19.167.131', '199.244.86.149', '197.156.241.249', '114.125.184.172', '89.178.171.173', '151.235.84.235', '185.104.184.120', '197.243.40.75', '88.253.119.59', '103.76.21.243', '207.244.78.50', '95.73.121.206', '185.182.81.60', '176.55.167.228', '179.54.147.13', '156.198.95.108', '199.249.223.63', '165.139.150.133', '185.182.81.16', '185.182.81.80', '162.210.197.54', '41.34.8.12', '86.161.166.126', '103.21.125.80', '5.254.65.15', '65.49.126.73', '69.117.214.158', '92.96.162.204', '64.62.232.66', '2.48.180.82', '213.87.163.155', '108.59.8.217', '91.151.188.194', '197.229.0.32', '76.218.238.42', '178.62.6.233', '159.65.117.243', '217.118.78.80', '109.252.25.1', '96.80.89.69', '89.40.118.87', '185.182.81.25', '73.43.73.161', '108.59.10.184', '5.155.214.63', '103.10.197.195', '95.71.21.143', '113.21.99.50', '198.96.155.3', '203.156.158.201', '5.254.65.19', '103.10.197.133', '207.244.94.5', '190.39.1.149', '103.10.197.61', '213.87.139.175', '91.244.39.229', '136.0.99.204', '77.34.114.167', '185.76.248.253', '185.182.81.139', '207.244.82.154', '199.115.115.194', '139.59.84.23', '209.126.90.78', '156.219.221.191', '109.252.99.3', '67.252.57.173', '222.70.120.196', '207.244.78.47', '156.197.120.27', '185.182.81.76', '78.95.166.34', '103.10.197.131', '37.21.231.95', '87.225.68.121', '46.40.227.14', '77.43.173.56', '114.124.181.244', '37.1.129.188', '128.72.83.20', '5.254.65.85', '31.129.204.120', '5.158.237.18', '151.243.199.70', '185.182.81.77', '103.228.157.94', '69.202.142.68', '94.25.180.120', '185.182.81.91', '103.10.197.154', '202.22.227.26', '49.145.151.70', '207.244.86.198', '185.182.81.19', '185.182.81.69', '5.254.65.123', '65.49.68.203', '103.79.155.58', '216.185.36.99', '80.191.221.21', '5.254.65.220', '91.215.69.212', '5.254.65.24', '103.10.197.204', '105.67.7.89', '195.112.116.163', '46.42.167.129', '190.142.101.84', '207.244.79.152', '5.59.53.95', '14.139.125.241', '197.211.63.74', '195.190.107.166', '185.182.81.135', '194.146.181.131', '83.220.237.252', '41.215.173.33', '142.44.210.206', '62.213.109.218', '199.168.151.35', '5.254.65.217', '45.242.236.74', '80.253.23.149', '185.182.81.11', '93.168.185.76', '185.182.81.82', '77.106.62.60', '185.220.101.20', '185.182.81.47', '185.182.81.56', '5.41.65.151', '66.160.188.43', '74.82.35.71', '79.139.176.23', '88.203.110.34', '64.147.94.201', '213.87.132.49', '91.216.114.201', '179.53.157.148', '185.182.81.4', '196.74.129.52', '95.72.247.249', '185.182.81.71', '185.182.81.138', '154.68.60.100', '81.214.142.169', '147.110.59.244', '200.2.187.239', '68.133.80.57', '5.44.174.110', '142.234.201.129', '89.238.177.226', '120.188.86.112', '207.244.78.173', '173.208.82.162', '115.178.200.218', '139.162.233.190', '43.245.8.67', '103.10.197.58', '207.244.83.219', '148.0.219.242', '5.126.66.228', '37.190.37.137', '182.179.179.160', '103.10.197.220', '41.66.255.100', '37.144.44.196', '207.244.77.18', '5.254.65.102', '213.33.193.34', '185.182.81.51', '154.121.5.242', '92.246.191.120', '186.167.242.158', '217.117.66.54', '85.88.176.70', '114.124.182.15', '146.185.177.103', '179.180.67.5', '207.154.232.214', '91.192.70.25', '156.38.35.15', '147.135.254.228', '103.10.197.130', '195.214.140.20', '31.29.217.147', '73.170.68.18', '142.234.201.141', '2.191.76.162', '151.80.36.117', '5.254.65.195', '213.87.225.138', '5.0.249.218', '27.68.68.184', '178.59.189.246', '95.30.31.106', '213.87.126.137', '104.45.14.157', '196.6.216.5', '185.182.81.131', '5.254.65.177', '103.255.7.21', '212.75.159.112', '103.10.197.196', '217.55.47.233', '109.252.76.112', '36.84.62.52', '185.253.97.52', '31.148.253.33', '185.182.81.78', '159.224.41.242', '46.101.16.232', '5.254.65.97', '89.160.136.97', '207.244.78.8', '5.254.65.82', '185.182.81.92', '95.29.19.127', '185.182.81.22', '66.160.201.58', '93.90.204.172', '2.93.201.96', '182.1.178.122', '148.0.142.65', '94.233.224.122', '163.232.200.115', '200.236.75.164', '106.204.119.26', '168.8.192.22', '185.182.81.83', '107.77.209.106', '207.244.78.17', '89.104.104.224', '106.51.234.22', '71.12.167.41', '188.247.109.2', '213.87.156.209', '192.240.119.59', '78.180.74.219', '37.107.111.54', '103.10.197.132', '5.254.65.8', '105.167.52.122', '146.185.157.173', '95.184.110.95', '23.101.10.145', '5.254.65.124', '151.231.40.224', '178.129.222.227', '185.182.81.68', '185.107.47.215', '146.185.156.139', '120.188.39.56', '176.14.163.226', '178.62.113.166', '95.153.134.122', '185.182.81.75', '156.194.101.98', '185.182.81.72', '182.187.97.214', '41.72.194.58', '196.201.199.210', '185.182.81.79', '51.39.237.115', '202.146.235.80', '176.123.126.254', '86.149.9.202', '41.254.4.43', '91.240.73.248', '185.88.157.231', '171.229.95.88', '5.254.65.129', '139.59.225.74', '95.24.175.100', '5.254.65.182', '185.182.81.50', '89.31.57.5', '129.56.11.18', '207.244.83.104', '199.115.118.85', '89.235.123.202', '154.69.67.5', '36.84.62.49', '146.185.157.38', '31.29.248.93', '109.252.20.82', '207.244.94.36', '66.160.188.67', '5.254.65.6', '38.95.109.110', '178.175.132.67', '103.214.2.35', '196.24.72.24', '185.182.81.9', '109.252.177.102', '136.252.163.99', '185.104.184.116', '162.247.72.199', '213.55.105.3', '5.79.68.161', '188.170.103.189', '5.254.65.21', '88.228.167.196', '41.242.138.49', '103.10.197.59', '178.73.220.45', '200.82.249.248', '5.254.65.107', '207.244.77.172', '5.254.65.84', '37.190.37.197', '213.87.131.60', '37.112.229.42', '95.24.91.228', '185.182.81.84', '77.247.181.162', '78.81.231.143', '185.182.81.46', '207.244.83.114', '41.253.39.240', '92.50.223.44', '173.208.82.164', '41.85.161.178', '213.87.122.199', '37.52.183.88', '207.244.72.201', '109.252.53.106', '108.59.8.208', '104.129.18.10', '122.57.37.39', '176.59.48.37', '125.178.76.189', '154.130.48.206', '113.169.71.251', '91.215.69.23', '54.36.105.8', '95.10.207.189', '128.31.0.13', '81.211.123.74', '103.10.197.13', '46.242.10.245', '81.131.164.246', '156.194.244.214', '178.62.106.169', '204.85.191.31', '207.244.86.200', '77.27.69.166', '192.96.205.131', '139.59.3.30', '80.252.16.20', '185.182.81.137', '150.100.253.6', '103.25.72.234', '207.244.86.195', '154.160.16.103', '78.95.6.2', '185.182.81.44', '197.248.213.18', '202.142.79.94', '38.95.108.247', '2.135.158.83', '37.73.82.56', '103.255.6.75', '5.254.65.110', '64.62.175.68', '207.244.83.209', '172.241.114.173', '207.244.79.137', '207.244.82.251', '207.244.86.232', '94.233.224.26', '174.141.115.146', '109.174.112.128', '93.91.80.6', '41.190.3.77', '159.89.115.182', '188.163.3.226', '95.191.226.57', '139.5.154.162', '193.0.219.72', '185.182.81.70', '138.197.174.51', '41.217.109.25', '39.50.91.154', '37.204.198.46', '130.180.218.30', '5.254.65.17', '138.197.160.42', '5.254.65.187', '37.195.213.64', '188.170.73.65', '197.48.231.108', '185.189.113.42', '185.182.81.74', '41.66.203.243', '163.21.7.42', '5.254.65.83', '157.50.236.233', '94.233.224.7', '128.71.22.17', '130.34.246.190', '185.52.141.42', '139.59.84.2', '84.241.202.178', '123.242.160.17', '74.82.17.52', '182.0.205.139', '203.202.229.194', '89.238.191.150', '79.165.225.194', '73.61.8.75', '41.254.8.167', '185.182.81.5', '94.47.16.26', '182.186.238.234', '156.216.204.96', '109.252.57.81', '180.252.104.52', '79.148.109.242', '66.160.201.47', '2.191.110.236', '207.244.77.13', '5.254.65.98', '145.255.166.214', '159.203.130.12', '197.234.221.77', '159.89.206.211', '85.141.69.27', '185.182.81.90', '77.31.101.152', '202.22.237.40', '95.221.205.237', '207.244.77.55', '104.236.233.75', '5.254.65.104', '104.236.233.182', '103.10.197.60', '103.10.197.222', '182.54.141.154', '138.197.174.79', '176.33.136.50', '185.182.81.10', '185.220.101.30', '94.138.40.2', '41.44.178.2', '196.207.121.147', '213.138.86.113', '31.173.83.65', '199.115.115.197', '46.72.89.106', '103.240.170.209', '5.254.65.215', '146.185.171.157', '185.182.81.57', '188.119.59.75', '46.164.104.176', '176.52.96.95', '207.244.83.99', '31.43.31.116', '178.62.208.24', '5.254.65.167', '185.182.81.73', '104.194.24.250', '79.200.158.58', '79.111.52.85', '103.10.197.91', '199.249.224.65', '5.136.175.48', '111.119.165.253', '216.218.222.12', '191.248.209.198', '5.254.65.81', '178.46.97.50', '27.97.248.46', '190.72.126.220', '178.140.204.131', '5.114.82.81', '118.175.154.120', '207.244.90.69', '185.182.81.7', '103.17.88.247', '108.248.141.54', '130.34.246.189', '207.244.79.154', '41.66.255.247', '128.69.14.62', '87.107.208.172', '199.115.116.35', '46.191.213.221', '199.115.114.220', '172.56.44.234', '69.12.94.91', '5.254.65.99', '37.203.243.97', '185.182.81.29', '37.210.142.211', '207.244.78.9', '206.189.56.39', '193.104.27.86', '37.190.37.236', '112.197.34.56', '189.124.82.209', '99.66.132.171', '5.254.65.16', '46.201.114.83', '81.31.178.23', '94.47.97.98', '82.102.31.251', '103.10.197.203', '94.98.252.208', '14.139.160.236', '185.182.81.130', '184.43.6.218', '92.37.143.180', '5.254.65.12', '83.142.185.126', '5.254.65.178', '213.87.123.37', '36.67.214.132', '185.182.81.21', '205.164.32.216', '207.244.83.198', '5.254.65.11', '197.210.221.42', '207.244.83.206', '5.254.65.130', '176.14.156.125', '94.138.40.7', '182.75.59.110', '162.210.197.57', '41.35.98.90', '95.139.11.104', '103.10.197.93', '39.40.168.95', '213.87.127.74', '2.94.25.98', '216.218.222.14', '207.244.82.155', '138.197.154.118', '199.249.223.69', '5.254.65.112', '62.120.19.197', '185.182.81.17', '148.0.140.9', '103.10.197.197', '185.182.81.15', '217.114.239.64', '185.182.81.134', '130.180.217.17', '111.88.82.111', '112.210.165.48', '81.92.200.142', '185.182.81.43', '207.244.77.3', '169.159.85.133', '5.254.65.20', '197.234.221.34', '192.162.242.11', '185.182.81.67', '103.247.48.9', '109.173.73.174', '171.25.193.20', '207.244.77.17', '176.59.44.162', '95.28.48.169', '5.254.65.113', '62.112.114.74', '5.254.65.174', '179.96.223.197', '149.202.202.78', '146.185.157.243', '110.93.216.238', '217.148.214.162', '23.100.15.206', '24.133.136.29', '59.189.57.53', '185.182.81.62', '31.181.90.52', '5.254.65.117', '94.99.170.144', '146.185.157.164', '178.62.230.201', '41.223.117.58', '197.54.177.15', '212.252.67.30', '109.252.86.175', '194.146.149.39', '207.244.83.197', '190.94.3.236', '207.244.94.9', '5.254.65.193', '5.254.65.194', '207.244.77.10', '146.185.158.9', '5.254.65.172', '37.156.22.79', '209.190.17.22', '103.10.197.156', '5.254.65.9', '178.140.62.96', '207.244.77.16', '109.161.121.117', '37.78.31.88', '185.220.101.13', '185.182.81.87', '87.107.165.5', '185.135.233.14', '209.58.148.100', '83.110.13.200', '5.254.65.132', '93.80.234.243', '190.39.198.140', '95.221.183.242', '185.222.209.32', '154.160.16.167', '80.71.249.236', '185.182.81.39', '41.79.197.12', '91.76.89.93', '45.247.206.86', '185.182.81.88', '192.81.222.95', '207.244.86.236', '197.210.29.171', '213.61.95.74', '41.254.7.18', '31.9.55.66', '154.112.8.183', '5.254.65.180', '37.187.158.97', '195.149.108.45', '94.179.147.128', '94.130.206.211', '31.173.85.237', '103.10.197.221', '46.39.83.173', '5.254.65.170', '5.254.65.18', '95.167.31.202', '207.244.83.212', '138.197.174.132', '185.182.81.35', '192.96.205.135', '130.88.240.92', '185.182.81.94', '90.147.2.94', '209.126.90.97', '128.75.107.209', '2.94.139.161', '103.106.174.102', '186.4.212.26', '37.145.142.85', '207.244.86.194', '72.211.60.177', '95.30.45.134', '80.71.253.200', '5.254.65.109', '185.182.81.38', '5.254.65.214', '178.62.221.111', '81.92.200.204', '89.104.104.226', '95.73.236.188', '207.244.83.113', '185.182.81.24', '103.247.48.111', '176.59.43.149', '109.233.172.188', '207.244.70.35', '84.17.230.179', '83.123.148.16', '122.171.168.163', '213.87.121.217', '110.54.232.113', '206.189.56.10', '154.160.30.129', '207.244.93.227', '178.46.96.130', '87.116.196.230', '181.208.250.104', '43.252.233.33', '207.244.82.249', '154.68.5.60', '37.27.72.154', '178.68.165.3', '194.186.9.228', '207.244.79.134', '41.34.209.13', '192.119.160.242', '37.187.129.166', '41.254.7.152', '46.38.23.226', '185.182.81.52', '27.34.104.88', '31.29.253.114', '200.17.141.3', '86.62.75.82', '93.183.219.225', '94.143.40.157', '103.10.197.194', '188.166.212.116', '185.182.81.2', '212.98.135.186', '103.10.197.92', '207.244.83.195', '217.64.17.124', '46.242.10.244', '209.58.136.236', '156.203.226.215', '103.10.197.218', '199.115.114.218', '185.182.81.8', '207.244.82.231', '95.8.0.20', '207.244.82.133', '128.74.124.28', '111.95.14.210', '213.87.126.35', '5.254.65.134', '91.240.210.185', '185.182.81.132', '95.32.139.134', '213.55.110.157', '185.182.81.26', '176.47.67.182', '91.65.54.25', '217.10.34.243', '185.182.81.133', '182.1.191.230', '103.10.197.90', '213.87.225.153', '207.244.77.184', '185.182.81.81', '5.254.65.88', '123.176.6.58', '213.55.110.206', '93.157.169.12', '103.10.197.219', '109.252.81.16', '78.111.187.63', '82.196.1.179', '185.182.81.59', '148.0.193.199', '14.202.100.66', '5.250.37.110', '156.219.245.39', '31.9.112.197', '185.112.37.25', '128.70.176.120', '185.182.81.27', '188.226.226.40', '109.174.113.45', '5.246.33.162', '5.254.65.189', '46.151.246.57', '77.71.24.206', '178.62.36.218', '185.182.81.36', '196.188.112.153', '199.249.223.49', '80.252.153.74', '87.109.169.79', '207.244.83.200', '197.210.54.144', '95.57.231.156', '207.244.94.33', '103.16.25.2', '217.174.233.46', '178.184.98.116', '185.182.81.55', '107.77.207.197', '86.21.86.205', '5.254.65.192', '38.95.108.230', '94.13.131.173', '107.77.209.181', '176.59.54.71', '128.179.252.54', '31.215.58.51', '207.244.83.123', '85.106.69.110', '192.160.102.170', '37.146.34.208', '46.39.228.226', '87.225.75.186', '159.89.123.60', '176.59.68.249', '37.143.20.94', '105.112.29.37', '89.146.74.31', '90.147.2.86', '217.144.175.138', '212.252.57.203', '131.117.162.145', '109.63.245.141', '92.97.199.104', '176.123.121.221', '213.142.154.3', '180.160.55.195', '176.195.133.16', '172.241.112.3', '207.244.83.217', '125.167.120.44', '109.252.85.9', '46.39.53.115', '206.189.201.4', '31.173.83.78', '199.115.115.215', '178.62.153.200']

How do I convert a list of ips like above into a list of subnets?

For example;

185.182.0.0/y, 207.244.0.0/x

Edit

I'm getting a lot of malicious traffic from several ips that look like they're in the same subnet, however there are a few thousand ips, how do I convert a list like this into subnets so that I can block the subnet?

Body:
This answer by Wang is the correct way to do this: https://stackoverflow.com/a/45503187/3176550

list_of_ips = ['10.0.0.0', '10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.5']
import ipaddress
nets = [ipaddress.ip_network(_ip) for _ip in list_of_ips]
cidrs = ipaddress.collapse_addresses(nets)
list(cidrs)
Out[6]: [IPv4Network('10.0.0.0/30'), IPv4Network('10.0.0.5/32')]


来源: stackexchange

问:
How to recover admin password for SonarQube
I forgot the admin password for SonarQube. Googled and found that the value for crypted_password should be updated to 8b1254c1c684c5dc904f3f174cea1cacbde4ad84 which will reset the password to admin. But still I am not able to login. Any advice?

答:
The official documentation when writing this answer currently states:

Reinstating Admin Access

If you changed and then lost the admin password, you can reset it using the following query:

update users set crypted_password='100000$t2h8AtNs1AlCHuLobDjHQTn9XppwTIx88UjqUm4s8RsfTuXQHSd/fpFexAnewwPsO6jGFQUv/24DnO55hY6Xew==', salt='k9x9eN127/3e/hf38iNiKwVfaVk=', hash_method='PBKDF2', reset_password='true', user_local='true' where login='admin';
```
<p>If you've deleted admin and subsequently locked out the other users with global administrative permissions, you'll need to re-grant admin to a user with the following query:</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO user_roles(uuid, user_uuid, role)
VALUES ('random-uuid',
(select uuid from users where login='mylogin'),
'admin');
</code>```

It worked like a charm on my sonarqube instance version 8.9.7

Also, if you're using kubernetes you can start a psql container easily with the following commands:

kubectl run --restart=Never --image=governmentpaas/psql --command=true psql -- sleep infinity
kubectl exec -it psql -- sh
```
<p>Then connect to the database with the following command</p>
<pre class="lang-sh prettyprint-override"><code>psql -h yourhostname --user sonarqubeuser -d sonarqubedb
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The official documentation when writing this answer currently states:

Reinstating Admin Access

If you changed and then lost the admin password, you can reset it using the following query:

update users set crypted_password='100000$t2h8AtNs1AlCHuLobDjHQTn9XppwTIx88UjqUm4s8RsfTuXQHSd/fpFexAnewwPsO6jGFQUv/24DnO55hY6Xew==', salt='k9x9eN127/3e/hf38iNiKwVfaVk=', hash_method='PBKDF2', reset_password='true', user_local='true' where login='admin';

If you've deleted admin and subsequently locked out the other users with global administrative permissions, you'll need to re-grant admin to a user with the following query:

INSERT INTO user_roles(uuid, user_uuid, role)
VALUES ('random-uuid',
(select uuid from users where login='mylogin'),
'admin');

It worked like a charm on my sonarqube instance version 8.9.7

Also, if you're using kubernetes you can start a psql container easily with the following commands:

kubectl run --restart=Never --image=governmentpaas/psql --command=true psql -- sleep infinity
kubectl exec -it psql -- sh

Then connect to the database with the following command

psql -h yourhostname --user sonarqubeuser -d sonarqubedb


问:
Info on SPARQL Queries
I need to work on SPARQL queries. Does any one has good links to learn SPARQL queries? I am looking good article on syntax of the SPARQL queries and examples so that I could learn it quickly.</p>

答:
Lee Feigenbaum's SPARQL by Example is always a good place to start.

If you have specific questions you'll find a helpful bunch of people containing many SPARQL experts at answers.semanticweb.com

ContentLicense: CC BY-SA 3.0

Title: Info on SPARQL Queries


问:
get average salary with Java stream api;
how can i get the average salary of company employees whose salary is more than salaryLimit?
I think first I need to get a list of all salaries and filter it + use mapToInt and average, but...nothing works((

```<code>public class TestCl {

@Data
@AllArgsConstructor
public class Company {
    private List<Department> departments;
}

@Data
@AllArgsConstructor
public class Department {
    private List<Employee> employees;
}

@Data
@AllArgsConstructor
public class Employee {
    private int salary;
}

@Test
public void test() {
    int salaryLimit = 25;

    List<Employee> employees = new ArrayList<>(){{
        add(new Employee(10));
        add(new Employee(20));
        add(new Employee(30));
        add(new Employee(40));
        add(new Employee(50));
    }};

    List<Department> departments = new ArrayList<>(){{
        add(new Department(employees));
        add(new Department(employees));
        add(new Department(employees));
        add(new Department(employees));
        add(new Department(employees));
    }};

    Company company = new Company(departments);

    float average = company.getDepartments().stream()
            .map(Department::getEmployees).toList().stream()
            .map(Employee::getSalary).toList().stream()
            .filter(x -> x >= salaryLimit).mapToInt().average();

    System.out.println(average);
}
</code>```

}

答:
For one thing, you're looking for Stream.flatMap().  For example,

```<code>company.getDepartments().stream()
            .flatMap(d -> d.getEmployees().stream()) // ...
</code>```

That converts your stream of Departments to a stream of the Employees of each department.  You can then map() those to salaries and filter as you already do.

The combination .toList().stream() makes zero sense, however, as it expends work to convert one stream to another one providing exactly the same objects.  Removing that has only upside.

To map to an IntStream or, probably better for this purpose, a DoubleStream, the mapToInt() or mapToDouble() method requires a function expressing the details of the mapping, which you are omitting.

Finally, IntStream.average(), DoubleStream.average(), etc return an OptionalInteger / OptionalDouble / etc, which accommodates the possibility that there is no average on account of the stream  providing zero elements.  You need to deal with that.

All together, then:

```<code>float average = company.getDepartments().stream() // a stream of Departments
        .flatMap(d -> d.getEmployees().stream())  // a stream of Employees
        .map(e -> e.getSalary())                  // a stream of Integer salaries
        .filter(s -> s.intValue() >= salaryLimit) // only the high salaries
        .mapToDouble(Integer::doubleValue)        // as a DoubleStream
        .average()                                // reduce to an average
        .getAsDouble();                           // the value, if it exists
</code>```

Note well that the getAsDouble() will throw NoSuchElementException if no salaries satisfy the filter criterion.  Catching and handling that is a perfectly reasonable way to deal with the situation, but if you want to avoid that then you can store the result of average() instead of chaining getAsDouble(), and then test it with isPresent() to decide whether to go ahead with getAsDouble() or to handle the situation differently.  Or if there is a specific double value that you want to provide in that case -- such as 0 or Double.NaN -- then you could chain on an orElse(valueForZeroSalaries) instead of the getAsDouble().

Body:
how can i get the average salary of company employees whose salary is more than salaryLimit?
I think first I need to get a list of all salaries and filter it + use mapToInt and average, but...nothing works((

public class TestCl {

@Data
@AllArgsConstructor
public class Company {
    private List<Department> departments;
}

@Data
@AllArgsConstructor
public class Department {
    private List<Employee> employees;
}

@Data
@AllArgsConstructor
public class Employee {
    private int salary;
}

@Test
public void test() {
    int salaryLimit = 25;

    List<Employee> employees = new ArrayList<>(){{
        add(new Employee(10));
        add(new Employee(20));
        add(new Employee(30));
        add(new Employee(40));
        add(new Employee(50));
    }};

    List<Department> departments = new ArrayList<>(){{
        add(new Department(employees));
        add(new Department(employees));
        add(new Department(employees));
        add(new Department(employees));
        add(new Department(employees));
    }};

    Company company = new Company(departments);

    float average = company.getDepartments().stream()
            .map(Department::getEmployees).toList().stream()
            .map(Employee::getSalary).toList().stream()
            .filter(x -> x >= salaryLimit).mapToInt().average();

    System.out.println(average);
}

}

Body:
For one thing, you're looking for Stream.flatMap().  For example,

company.getDepartments().stream()
            .flatMap(d -> d.getEmployees().stream()) // ...

That converts your stream of Departments to a stream of the Employees of each department.  You can then map() those to salaries and filter as you already do.

The combination .toList().stream() makes zero sense, however, as it expends work to convert one stream to another one providing exactly the same objects.  Removing that has only upside.

To map to an IntStream or, probably better for this purpose, a DoubleStream, the mapToInt() or mapToDouble() method requires a function expressing the details of the mapping, which you are omitting.

Finally, IntStream.average(), DoubleStream.average(), etc return an OptionalInteger / OptionalDouble / etc, which accommodates the possibility that there is no average on account of the stream  providing zero elements.  You need to deal with that.

All together, then:

float average = company.getDepartments().stream() // a stream of Departments
        .flatMap(d -> d.getEmployees().stream())  // a stream of Employees
        .map(e -> e.getSalary())                  // a stream of Integer salaries
        .filter(s -> s.intValue() >= salaryLimit) // only the high salaries
        .mapToDouble(Integer::doubleValue)        // as a DoubleStream
        .average()                                // reduce to an average
        .getAsDouble();                           // the value, if it exists

Note well that the getAsDouble() will throw NoSuchElementException if no salaries satisfy the filter criterion.  Catching and handling that is a perfectly reasonable way to deal with the situation, but if you want to avoid that then you can store the result of average() instead of chaining getAsDouble(), and then test it with isPresent() to decide whether to go ahead with getAsDouble() or to handle the situation differently.  Or if there is a specific double value that you want to provide in that case -- such as 0 or Double.NaN -- then you could chain on an orElse(valueForZeroSalaries) instead of the getAsDouble().


问:
How can I convert an int (which represents an decimal without its decimal places) to a double in c?
I need to convert integers (which represents decimals but without using decimal places) to doubles in C. I know how many decimal places the integer should have because this information is also there. This new double is handed over to a JSON-API which appends this to a JSON structure afterwards.

Example: I need to produce a double value of 255.89 for an input of int1 := 25589 and int2 := 2

I've written this function:

```<code>cJSON* addDecimalToJSON(cJSON* const object, const char * const name, const int number, const int decimals) {
    double d = number;
    for(int i = 0; i < decimals; i++) {
        d = d / 10;
    }
    return addNumberToObject(object, name, d);
}
</code>```

This works for some values and in the JSON structure is the correct decimal value representation, but for other values (like the example above) the result is a "255.89000000000001".

After trial and error I'm at this point:

```<code>double test = 25589;
test = test / 10;
test = test / 10;
cout << test << endl;
-> 255.89
double test2 = 255.89;
cout << (test == test2) << endl;
-> 0
cout << (test2 == 255.89) << endl;
-> 1
</code>```

If I put test to the JSON API it still produces "255.89000000000001". If I put test2 to the JSON API it produces "255.89".
So there must be any kind of precision problem which is "carried" into the API (but which gets cut off from cout function so I cant 'see' it).
What I need in the end is the desired decimal value of "255.89" without the precision problem. How can this be achieved?

答:
The addNumberToObject doesn't let you control how many significant digits you want to print.

You can get around this by using sprintf to format the number yourself and adding it as a string.

```<code>cJSON* addDecimalToJSON(cJSON* const object, const char * const name,
                        const int number, const int decimals) {
    double d = number;
    for(int i = 0; i < decimals; i++) {
        d = d / 10;
    }
    char dstr[50];
    sprintf(dstr,"%.*f", decimals, d);
    return addStringToObject(object, name, dstr);
}
</code>```

Body:
I need to convert integers (which represents decimals but without using decimal places) to doubles in C. I know how many decimal places the integer should have because this information is also there. This new double is handed over to a JSON-API which appends this to a JSON structure afterwards.

Example: I need to produce a double value of 255.89 for an input of int1 := 25589 and int2 := 2

I've written this function:

cJSON* addDecimalToJSON(cJSON* const object, const char * const name, const int number, const int decimals) {
    double d = number;
    for(int i = 0; i < decimals; i++) {
        d = d / 10;
    }
    return addNumberToObject(object, name, d);
}

This works for some values and in the JSON structure is the correct decimal value representation, but for other values (like the example above) the result is a "255.89000000000001".

After trial and error I'm at this point:

double test = 25589;
test = test / 10;
test = test / 10;
cout << test << endl;
-> 255.89
double test2 = 255.89;
cout << (test == test2) << endl;
-> 0
cout << (test2 == 255.89) << endl;
-> 1

If I put test to the JSON API it still produces "255.89000000000001". If I put test2 to the JSON API it produces "255.89".
So there must be any kind of precision problem which is "carried" into the API (but which gets cut off from cout function so I cant 'see' it).
What I need in the end is the desired decimal value of "255.89" without the precision problem. How can this be achieved?

Body:
The addNumberToObject doesn't let you control how many significant digits you want to print.

You can get around this by using sprintf to format the number yourself and adding it as a string.

cJSON* addDecimalToJSON(cJSON* const object, const char * const name,
                        const int number, const int decimals) {
    double d = number;
    for(int i = 0; i < decimals; i++) {
        d = d / 10;
    }
    char dstr[50];
    sprintf(dstr,"%.*f", decimals, d);
    return addStringToObject(object, name, dstr);
}


问:
Adapter/Mapper to translate SQL queries to Hazelcast predicates and/or SQL queries
I am working with an application where we have SQL Server as a database. There is a requirement to add Hazelcast cache layer over the SQL Server. This is a legacy system and sort of works like SQL as a service where SQL queries to be executed against SQL Server DB are stored in a configuration table. For instance there is a UI for which data is returned by the query

Select case when page > 18 then 'Adult' else 'Teen' as Category, convert(varchar(20), p.registrationDate) as registeredOn from Person p
```

This is dynamically fetched and retrieved and executed against the database. There are many such views rendered off dynamic queries. With Hazelcast some of these SQL syntax will not just work. Is there any database abstraction framework or library or some adapter layer which can take in the SQL query and execute it against Hazelcast?

答:
I see a few choices with different trade-offs:

Use an ORM library (e.g. Hibernate) with Hazelcast as a 2nd level cache. ORM fully manages the cache by caching the entities and queries automatically. You should however use the ORM API instead of the native SQL. That might require you to rewrite the app code.

Cache complete query results and use the SQL query as a key. This is the least invasive option and is just good enough if the DB data change rarely and you use the same SQL queries repeatedly. By using cache-aside pattern, the changes to your app will be minimal (https://hazelcast.com/blog/a-hitchhikers-guide-to-caching-patterns/)

Query Hazelcast using SQL. This gives you most options to optimize the performance. Cache the DB tables you need and query Hazelcast using SQL. Might require rewriting the SQL queries to comply with Hazelcast SQL limitations: https://docs.hazelcast.com/hazelcast/5.1-beta-1/sql/sql-overview#limitations

Body:
I am working with an application where we have SQL Server as a database. There is a requirement to add Hazelcast cache layer over the SQL Server. This is a legacy system and sort of works like SQL as a service where SQL queries to be executed against SQL Server DB are stored in a configuration table. For instance there is a UI for which data is returned by the query

Select case when page > 18 then 'Adult' else 'Teen' as Category, convert(varchar(20), p.registrationDate) as registeredOn from Person p

This is dynamically fetched and retrieved and executed against the database. There are many such views rendered off dynamic queries. With Hazelcast some of these SQL syntax will not just work. Is there any database abstraction framework or library or some adapter layer which can take in the SQL query and execute it against Hazelcast?


问:
Multiple commands error in target React-Core-AccessibilityResources
I am getting this below error while trying to make archive version of react native based iOS app.

```<code>Multiple commands produce '/Users/fullmad/Library/Developer/Xcode/DerivedData/sagaMobile-fsbtaprxtybkwmagqfnlburrxrfj/Build/Intermediates.noindex/ArchiveIntermediates/sagaMobile/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/AccessibilityResources.bundle':
1) Target 'React-Core-60309c9c-AccessibilityResources' has create directory command with output '/Users/fullmad/Library/Developer/Xcode/DerivedData/sagaMobile-fsbtaprxtybkwmagqfnlburrxrfj/Build/Intermediates.noindex/ArchiveIntermediates/sagaMobile/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/AccessibilityResources.bundle'
2) Target 'React-Core-AccessibilityResources' has create directory command with output '/Users/fullmad/Library/Developer/Xcode/DerivedData/sagaMobile-fsbtaprxtybkwmagqfnlburrxrfj/Build/Intermediates.noindex/ArchiveIntermediates/sagaMobile/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/AccessibilityResources.bundle'
</code>```

What I have tried to far is:

```<code>$ pod deintegrate
$ pod install

if target.name == "React-Core-60309c9c-AccessibilityResources"
        target.remove_from_project
      end
      if target.name == "React-Core-AccessibilityResources"
        target.remove_from_project
      end
</code>```

Nothing worked. Please help me to solve

答: Just remove the "React-Core-AccessibilityResources" (not "React-Core-60309c9c-AccessibilityResources").</p>

Body:
I am getting this below error while trying to make archive version of react native based iOS app.

Multiple commands produce '/Users/fullmad/Library/Developer/Xcode/DerivedData/sagaMobile-fsbtaprxtybkwmagqfnlburrxrfj/Build/Intermediates.noindex/ArchiveIntermediates/sagaMobile/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/AccessibilityResources.bundle':
1) Target 'React-Core-60309c9c-AccessibilityResources' has create directory command with output '/Users/fullmad/Library/Developer/Xcode/DerivedData/sagaMobile-fsbtaprxtybkwmagqfnlburrxrfj/Build/Intermediates.noindex/ArchiveIntermediates/sagaMobile/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/AccessibilityResources.bundle'
2) Target 'React-Core-AccessibilityResources' has create directory command with output '/Users/fullmad/Library/Developer/Xcode/DerivedData/sagaMobile-fsbtaprxtybkwmagqfnlburrxrfj/Build/Intermediates.noindex/ArchiveIntermediates/sagaMobile/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/AccessibilityResources.bundle'

What I have tried to far is:

$ pod deintegrate
$ pod install

if target.name == "React-Core-60309c9c-AccessibilityResources"
        target.remove_from_project
      end
      if target.name == "React-Core-AccessibilityResources"
        target.remove_from_project
      end

Nothing worked. Please help me to solve


问:
Is there a way to publish a R flexdashboard html page in SharePoint?; Remove closing
I created a html output from r with rmarkdown::render(“file.rmd”, “output.html”).

The output is a multi-page flexdashboard html output with several plotly graphs. There is no shiny involved thus a static HTML file. when I open this file in chrome or edge this file shown exactly as supposed.

I want to integrate this flexdashboard html file within sharepoint. However when I open this file within sharepoint, I only see the title of the html file but all the other parts of the file are not showed correctly. I have tested this on several computers and browsers. Only Edge (not every pc) showed it correctly.

Is there someone who could give advise how to properly integrate an r flexdashboard HTML file within SharePoint online?

答: Just rename to aspx file. So rmarkdown::render(“file.rmd”, “output.aspx”) will do the trick.


问:
Trying to make a program with header files in C
I'm trying to make a program in C that uses header files and I'm getting an error. The program is supposed to add two numbers, add two numbers with a macro, and print a component in a typedef. There are three separate files:

functions.c

```<code>int add(int n1, int n2) {
    return n1 + n2;
}
</code>```

functions.h

```<code>#ifndef FUNCTIONS_H
#define FUNCTIONS_H

// function declaration
int add(int, int);

// macro declaration
#define ADD(n1, n2) n1 + n2

// typedef declaration
typedef struct {
    int age;
    char *name;
} person;

#endif
</code>```

main.c (This is the main program that uses everything from functions.c and functions.h and prints the result.)

```<code>#include <stdio.h>
#include "functions.h"

int main(void) {
    printf("%d\n", add(2, 6));
    printf("%d\n", ADD(3, 7));

    person engineer_man;
    engineer_man.age = 32;
    printf("engineer man's age is: %d\n", engineer_man.age);
}
</code>```

I tried compiling by doing gcc -g -std=c99 -Wall -Wvla -Werror -fsanitize=address,undefined -o main main.c, but then it gave this error:

/usr/bin/ld: /tmp/ccbVAioe.o: in function `main':
/common/home/user/folder/main.c:5: undefined reference to `add'
collect2: error: ld returned 1 exit status
```

How do I fix this error?

答:
```<code>gcc -c functions.c
gcc -o main main.c functions.o
</code>```

should also work well.  I omitted the compiler flags that need to be added in each case, depending on your need.

Body:
I'm trying to make a program in C that uses header files and I'm getting an error. The program is supposed to add two numbers, add two numbers with a macro, and print a component in a typedef. There are three separate files:

functions.c

int add(int n1, int n2) {
    return n1 + n2;
}

functions.h

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

// function declaration
int add(int, int);

// macro declaration
#define ADD(n1, n2) n1 + n2

// typedef declaration
typedef struct {
    int age;
    char *name;
} person;

#endif

main.c (This is the main program that uses everything from functions.c and functions.h and prints the result.)

#include <stdio.h>
#include "functions.h"

int main(void) {
    printf("%d\n", add(2, 6));
    printf("%d\n", ADD(3, 7));

    person engineer_man;
    engineer_man.age = 32;
    printf("engineer man's age is: %d\n", engineer_man.age);
}

I tried compiling by doing gcc -g -std=c99 -Wall -Wvla -Werror -fsanitize=address,undefined -o main main.c, but then it gave this error:

/usr/bin/ld: /tmp/ccbVAioe.o: in function `main':
/common/home/user/folder/main.c:5: undefined reference to `add'
collect2: error: ld returned 1 exit status

How do I fix this error?

Body:
gcc -c functions.c
gcc -o main main.c functions.o

should also work well.  I omitted the compiler flags that need to be added in each case, depending on your need.


问:
How to do form authentification in ASP.NET MVC 3?
I am using Oracle Database, what tables I should add and how I can do my MembershipProvider and other providers? Thank you.

I have tried to use Oracle Providers, but have some problems with it. The details is here

答: Oracle has providers for asp.net : http://download.oracle.com/docs/html/E10928_01/IntroOverview.htm</p>


问:
How to test a PersistentMap item is correctly saved to storage?
I have a function that takes a number of values, creates a new model, and then saves this in storage via a PersistentMap.

I would like to test that the item is successfully saved in storage. This is how I'm going about it:

```<code>    it("saves a new item to storage", () => {
      VMContext.setCurrent_account_id("test_account_id");

      contract.createMyPersistantMapItem(
        "value 1",
        "value 2",
        "value 3"
      );

      expect(storage.hasKey("myPersistantMap::test_account_id")).toBeTruthy();
    });
</code>```

However the test fails with the following:

```<code>  [Actual]: false
[Expected]: Truthy
   [Stack]: RuntimeError: unreachable
            at node_modules/@as-pect/assembly/assembly/internal/assert/assert (wasm-function[53]:0xd71)
            at start:src/simple/__tests__/index.unit.spec~anonymous|0~anonymous|0~anonymous|0 (wasm-function[130]:0x2a84)
            at node_modules/@as-pect/assembly/assembly/internal/call/__call (wasm-function[134]:0x2aac)
</code>```

Am I going about this the wrong way?

Also I would like to test the values in the item are correct. In the todos example the created todo is returned from the function that creates it, and then this returned value is tested. Is this the best way of doing things to make testing easier?

EDIT

This is the createMyPersistantMapItem function - edited a bit to make things clearer:

```<code>export function createMyPersistantMapItem(
    blah1: string,
    blah2: string,
    blah3: string,
  ): void {
    const accountId = context.sender;

    assert(
      !storage.hasKey("myPersistantMap::" + accountId),
      "Item already exists"
    );

    const newPersistantMapItem = new PersistantMapItem(
      blah1,
      blah2,
      blah3
    );

    myPersistantMap.set(accountId, newPersistantMapItem);
  }
</code>```

答:
About the first question:

Does myPersistentMap use the "myPersistantMap" prefix when initialized? Does PersistantMapItem use the @nearBingden annotation on the class?

Also, in your test, I think you should use

```<code>VMContext.setSigner_account_id("test_account_id")

//instead of
VMContext.setCurrent_account_id("test_account_id")
</code>```

Because you are using context.sender when you call createMyPersistantMapItem

About the second question:

In the todos example the created todo is returned from the function that creates it, and then this returned value is tested. Is this the best way of doing things to make testing easier?

This question is primarily opinion based, so I can only answer for myself. Testing the returned value is completely fine. In a smart contract however, I would probably test if the value is actually stored on the contract. And I think they are doing that in the TODO example. They just use the ID of the generated TODO to do a query on the smart contract.

```<code>const a = Todo.insert("Drink water");
// They use the id of the todo (a) to check if it was actually stored, and is in fact the same object. I think this is fine.
expect(getById(a.id)).toStrictEqual(a);
</code>```

Body:
I have a function that takes a number of values, creates a new model, and then saves this in storage via a PersistentMap.

I would like to test that the item is successfully saved in storage. This is how I'm going about it:

    it("saves a new item to storage", () => {
      VMContext.setCurrent_account_id("test_account_id");

      contract.createMyPersistantMapItem(
        "value 1",
        "value 2",
        "value 3"
      );

      expect(storage.hasKey("myPersistantMap::test_account_id")).toBeTruthy();
    });

However the test fails with the following:

  [Actual]: false
[Expected]: Truthy
   [Stack]: RuntimeError: unreachable
            at node_modules/@as-pect/assembly/assembly/internal/assert/assert (wasm-function[53]:0xd71)
            at start:src/simple/__tests__/index.unit.spec~anonymous|0~anonymous|0~anonymous|0 (wasm-function[130]:0x2a84)
            at node_modules/@as-pect/assembly/assembly/internal/call/__call (wasm-function[134]:0x2aac)

Am I going about this the wrong way?

Also I would like to test the values in the item are correct. In the todos example the created todo is returned from the function that creates it, and then this returned value is tested. Is this the best way of doing things to make testing easier?

EDIT

This is the createMyPersistantMapItem function - edited a bit to make things clearer:

export function createMyPersistantMapItem(
    blah1: string,
    blah2: string,
    blah3: string,
  ): void {
    const accountId = context.sender;

    assert(
      !storage.hasKey("myPersistantMap::" + accountId),
      "Item already exists"
    );

    const newPersistantMapItem = new PersistantMapItem(
      blah1,
      blah2,
      blah3
    );

    myPersistantMap.set(accountId, newPersistantMapItem);
  }

Body:
About the first question:

Does myPersistentMap use the "myPersistantMap" prefix when initialized? Does PersistantMapItem use the @nearBingden annotation on the class?

Also, in your test, I think you should use

VMContext.setSigner_account_id("test_account_id")

//instead of
VMContext.setCurrent_account_id("test_account_id")

Because you are using context.sender when you call createMyPersistantMapItem

About the second question:

In the todos example the created todo is returned from the function that creates it, and then this returned value is tested. Is this the best way of doing things to make testing easier?

This question is primarily opinion based, so I can only answer for myself. Testing the returned value is completely fine. In a smart contract however, I would probably test if the value is actually stored on the contract. And I think they are doing that in the TODO example. They just use the ID of the generated TODO to do a query on the smart contract.

const a = Todo.insert("Drink water");
// They use the id of the todo (a) to check if it was actually stored, and is in fact the same object. I think this is fine.
expect(getById(a.id)).toStrictEqual(a);


问:
Python Append Not Working
So most of this code is my own, apologies for the fact it is probably a mess and/or horribly written, but my question is why the lines

```<code>D = open("C:\\aPATH\\hPROC.txt", "a")
D.write("End")
</code>```

aren't appending "End" at the bottom of the file whenever it is called.

```<code>import time

def replace_all(text, rps):
    for i, j in rps.items():
        text = text.replace(i, j)
    return text

def replacer():
    inf = "hScrape.txt"
    ouf = "hPROC.txt"
    A = open(inf, "r")
    B = open(ouf, "w")
    reps = {"Result Date:":"", "Draw Result:":"", "Bonus":"", "January":"", "February":"", "March":"", "April":"", "May":"", "June":"", "July":"", "August":"", "September":"", "October":"", "November":"", "December":"", "With Max Millions!":"", "2009":"", "2010":"", "2011":"", "2012":"", "2013":"", "2014":"", "2015":"", "2016":"", "2017":"", "2018":"", "30th":"", "29th":"", "28th":"", "27th":"", "26th":"", "25th":"", "24th":"", "23rd":"", "22nd":"", "21st":"", "20th":"", "19th":"", "18th":"", "17th":"", "16th":"", "15th":"", "14th":"", "13th":"", "12th":"", "11th":"", "10th":"", "9th":"", "8th":"", "7th":"", "6th":"", "5th":"", "4th":"", "3rd":"", "2nd":"", "1st":"", "\t":""}
    txt = replace_all(A.read(), reps)
    B.write(txt)
    A.close
    B.close

    D = open("C:\\aPATH\\hPROC.txt", "a")
    D.write("End")

    C = open("C:\\aPATH\\Result.txt", "w+")
    print("Completed Filtering Sequence")
    time.sleep(3)

    while True:
        B = open("hPROC.txt", "r")
        z = B.readline()
        print(z)
        if "End" in z:
            C.write("DN")
            break
        else:
            if z != "\n":
                if " " not in z:
                    if int(z) < 10:
                        C.write("0" + z)
                    else:
                        C.write(z)

replacer()
</code>```

答:
The best method I found so far is  as follows:</p>
```<code>with open("your text file") as f:
    for line in f:
        if "your text to append" in line.rstrip('\r\n'):
           print("Exists!")
           break
    else:
        f.write("your text to append" + "\n")
</code>```

Title: Python Append Not Working

Body:
So most of this code is my own, apologies for the fact it is probably a mess and/or horribly written, but my question is why the lines

D = open("C:\\aPATH\\hPROC.txt", "a")
D.write("End")

aren't appending "End" at the bottom of the file whenever it is called.

import time

def replace_all(text, rps):
    for i, j in rps.items():
        text = text.replace(i, j)
    return text

def replacer():
    inf = "hScrape.txt"
    ouf = "hPROC.txt"
    A = open(inf, "r")
    B = open(ouf, "w")
    reps = {"Result Date:":"", "Draw Result:":"", "Bonus":"", "January":"", "February":"", "March":"", "April":"", "May":"", "June":"", "July":"", "August":"", "September":"", "October":"", "November":"", "December":"", "With Max Millions!":"", "2009":"", "2010":"", "2011":"", "2012":"", "2013":"", "2014":"", "2015":"", "2016":"", "2017":"", "2018":"", "30th":"", "29th":"", "28th":"", "27th":"", "26th":"", "25th":"", "24th":"", "23rd":"", "22nd":"", "21st":"", "20th":"", "19th":"", "18th":"", "17th":"", "16th":"", "15th":"", "14th":"", "13th":"", "12th":"", "11th":"", "10th":"", "9th":"", "8th":"", "7th":"", "6th":"", "5th":"", "4th":"", "3rd":"", "2nd":"", "1st":"", "\t":""}
    txt = replace_all(A.read(), reps)
    B.write(txt)
    A.close
    B.close

    D = open("C:\\aPATH\\hPROC.txt", "a")
    D.write("End")

    C = open("C:\\aPATH\\Result.txt", "w+")
    print("Completed Filtering Sequence")
    time.sleep(3)

    while True:
        B = open("hPROC.txt", "r")
        z = B.readline()
        print(z)
        if "End" in z:
            C.write("DN")
            break
        else:
            if z != "\n":
                if " " not in z:
                    if int(z) < 10:
                        C.write("0" + z)
                    else:
                        C.write(z)

replacer()

Body:
The best method I found so far is  as follows:

with open("your text file") as f:
    for line in f:
        if "your text to append" in line.rstrip('\r\n'):
           print("Exists!")
           break
    else:
        f.write("your text to append" + "\n")


问:
CSS set element size in real pixels, not device pixel

window.setTimeout(function() {
  html2canvas(document.querySelector("#a")).then(function(canvas) {
    canvas.toBlob(function(aBlob) {
      var a = document.createElement('a'),
        b = URL.createObjectURL(aBlob);
      a.setAttribute('download', 'captured_image.png');
      a.setAttribute('href', b);
      a.click();
    });
  });
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="a" style="width: 100px; height: 100px; background-color: yellow; box-sizing: border-box; border: 1px solid red;">
  This is 100px div
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.0/html2canvas.min.js"></script>

(Because of cross origin it will not work on stackoverflow but in localhost it works but if you use hi-res display downloaded image will be 200px not 100px)</code>```

I am generating "screenshot" of page displayed in iframe and I always want it to be fixed size 100x100 pixels. It works on my PC but when I run the code at high resolution computers, downloaded image is bigger than 100x100 (e.g. 200x200). I think it's because of the device pixels are bigger, but how can I set it to be in pixels? My current code is:

```<code>iframe {
  width: 100px;
  height: 100px;
}
</code>```

Is it possible to ignore device pixels and force to use normal pixels?

Edit: working solution by JHeth comment below: html2canvas(element, {scale:1}).then(...)

Body:
window.setTimeout(function() {
  html2canvas(document.querySelector("#a")).then(function(canvas) {
    canvas.toBlob(function(aBlob) {
      var a = document.createElement('a'),
        b = URL.createObjectURL(aBlob);
      a.setAttribute('download', 'captured_image.png');
      a.setAttribute('href', b);
      a.click();
    });
  });
}, 1000);

  This is 100px div

(Because of cross origin it will not work on stackoverflow but in localhost it works but if you use hi-res display downloaded image will be 200px not 100px)

I am generating "screenshot" of page displayed in iframe and I always want it to be fixed size 100x100 pixels. It works on my PC but when I run the code at high resolution computers, downloaded image is bigger than 100x100 (e.g. 200x200). I think it's because of the device pixels are bigger, but how can I set it to be in pixels? My current code is:

iframe {
  width: 100px;
  height: 100px;
}

Is it possible to ignore device pixels and force to use normal pixels?

Edit: working solution by JHeth comment below: html2canvas(element, {scale:1}).then(...)


问:
Pairs from single list
Often enough, I've found the need to process a list by pairs. I was wondering which would be the pythonic and efficient way to do it, and found this on Google:

```<code>pairs = zip(t[::2], t[1::2])
</code>```

I thought that was pythonic enough, but after a recent discussion involving idioms versus efficiency, I decided to do some tests:

```<code>import time
from itertools import islice, izip

def pairs_1(t):
    return zip(t[::2], t[1::2])

def pairs_2(t):
    return izip(t[::2], t[1::2])

def pairs_3(t):
    return izip(islice(t,None,None,2), islice(t,1,None,2))

A = range(10000)
B = xrange(len(A))

def pairs_4(t):
    # ignore value of t!
    t = B
    return izip(islice(t,None,None,2), islice(t,1,None,2))

for f in pairs_1, pairs_2, pairs_3, pairs_4:
    # time the pairing
    s = time.time()
    for i in range(1000):
        p = f(A)
    t1 = time.time() - s

    # time using the pairs
    s = time.time()
    for i in range(1000):
        p = f(A)
        for a, b in p:
            pass
    t2 = time.time() - s
    print t1, t2, t2-t1
</code>```

These were the results on my computer:

```<code>1.48668909073 2.63187503815 1.14518594742
0.105381965637 1.35109519958 1.24571323395
0.00257992744446 1.46182489395 1.45924496651
0.00251388549805 1.70076990128 1.69825601578
</code>```

If I'm interpreting them correctly, that should mean that the implementation of lists, list indexing, and list slicing in Python is very efficient. It's a result both comforting and unexpected.

Is there another, "better" way of traversing a list in pairs?

Note that if the list has an odd number of elements then the last one will not be in any of the pairs.

Which would be the right way to ensure that all elements are included?

I added these two suggestions from the answers to the tests:

```<code>def pairwise(t):
    it = iter(t)
    return izip(it, it)

def chunkwise(t, size=2):
    it = iter(t)
    return izip(*[it]*size)
</code>```

These are the results:

```<code>0.00159502029419 1.25745987892 1.25586485863
0.00222492218018 1.23795199394 1.23572707176
</code>```

Results so far

Most pythonic and very efficient:

```<code>pairs = izip(t[::2], t[1::2])
</code>```

Most efficient and very pythonic:

```<code>pairs = izip(*[iter(t)]*2)
</code>```

It took me a moment to grok that the first answer uses two iterators while the second uses a single one.

To deal with sequences with an odd number of elements, the suggestion has been to augment the original sequence adding one element (None) that gets paired with the previous last element, something that can be achieved with itertools.izip_longest().

Finally

Note that, in Python 3.x, zip() behaves as itertools.izip(), and itertools.izip()  is gone.

答:
This snippet worked for me. It creates pairs of tuples and adds empty string to the last pair, if the list length is odd (fillvalue="").

```<code>zip_longest(*[iter(my_list)] * 2, fillvalue="")

# odd
list(zip_longest(*[iter([0, 1, 2, 3, 4, 5, 6])] * 2, fillvalue=""))
[(0, 1), (2, 3), (4, 5), (6, '')]

# even
list(zip_longest(*[iter([0, 1, 2, 3, 4, 5])] * 2, fillvalue=""))
[(0, 1), (2, 3), (4, 5)]
</code>```

ContentLicense: CC BY-SA 2.5

Title: Pairs from single list

Body:
Often enough, I've found the need to process a list by pairs. I was wondering which would be the pythonic and efficient way to do it, and found this on Google:

pairs = zip(t[::2], t[1::2])

I thought that was pythonic enough, but after a recent discussion involving idioms versus efficiency, I decided to do some tests:

import time
from itertools import islice, izip

def pairs_1(t):
    return zip(t[::2], t[1::2])

def pairs_2(t):
    return izip(t[::2], t[1::2])

def pairs_3(t):
    return izip(islice(t,None,None,2), islice(t,1,None,2))

A = range(10000)
B = xrange(len(A))

def pairs_4(t):
    # ignore value of t!
    t = B
    return izip(islice(t,None,None,2), islice(t,1,None,2))

for f in pairs_1, pairs_2, pairs_3, pairs_4:
    # time the pairing
    s = time.time()
    for i in range(1000):
        p = f(A)
    t1 = time.time() - s

    # time using the pairs
    s = time.time()
    for i in range(1000):
        p = f(A)
        for a, b in p:
            pass
    t2 = time.time() - s
    print t1, t2, t2-t1

These were the results on my computer:

1.48668909073 2.63187503815 1.14518594742
0.105381965637 1.35109519958 1.24571323395
0.00257992744446 1.46182489395 1.45924496651
0.00251388549805 1.70076990128 1.69825601578

If I'm interpreting them correctly, that should mean that the implementation of lists, list indexing, and list slicing in Python is very efficient. It's a result both comforting and unexpected.

Is there another, "better" way of traversing a list in pairs?

Note that if the list has an odd number of elements then the last one will not be in any of the pairs.

Which would be the right way to ensure that all elements are included?

I added these two suggestions from the answers to the tests:

def pairwise(t):
    it = iter(t)
    return izip(it, it)

def chunkwise(t, size=2):
    it = iter(t)
    return izip(*[it]*size)

These are the results:

0.00159502029419 1.25745987892 1.25586485863
0.00222492218018 1.23795199394 1.23572707176

Results so far

Most pythonic and very efficient:

pairs = izip(t[::2], t[1::2])

Most efficient and very pythonic:

pairs = izip(*[iter(t)]*2)

It took me a moment to grok that the first answer uses two iterators while the second uses a single one.

To deal with sequences with an odd number of elements, the suggestion has been to augment the original sequence adding one element (None) that gets paired with the previous last element, something that can be achieved with itertools.izip_longest().

Finally

Note that, in Python 3.x, zip() behaves as itertools.izip(), and itertools.izip()  is gone.

Body:
This snippet worked for me. It creates pairs of tuples and adds empty string to the last pair, if the list length is odd (fillvalue="").

zip_longest(*[iter(my_list)] * 2, fillvalue="")

# odd
list(zip_longest(*[iter([0, 1, 2, 3, 4, 5, 6])] * 2, fillvalue=""))
[(0, 1), (2, 3), (4, 5), (6, '')]

# even
list(zip_longest(*[iter([0, 1, 2, 3, 4, 5])] * 2, fillvalue=""))
[(0, 1), (2, 3), (4, 5)]


问:
Simple substraction on PHP (Arithmetic Operators)
I need some help with this simple substraction:

```<code>$savings = ($newprice - $newvalue);
</code>```

$newprice and $newvalue are values like 120.00 and 40.00

The problem is that the result is shown as 80 , without the .00 (dot00) at the end.

I will like to keep the values on the same format (a dot plus double cero at the end); what I need to change or include to that code ?

Thanks in advance

答:
http://php.net/number_format</p>

```<code>$savings = number_format($newprice - $newvalue, 2);
</code>```

Body:
I need some help with this simple substraction:

$savings = ($newprice - $newvalue);

$newprice and $newvalue are values like 120.00 and 40.00

The problem is that the result is shown as 80 , without the .00 (dot00) at the end.

I will like to keep the values on the same format (a dot plus double cero at the end); what I need to change or include to that code ?

Thanks in advance

Body:
http://php.net/number_format

$savings = number_format($newprice - $newvalue, 2);


问:
How Can I customize mat-form-field in disabled state
I am trying to customize the angular material mat-form-field :
I was able to customize the underline border using :

```<code>::ng-deep.mat-form-field-ripple {
  background-color: yellow;
}
</code>```

now I am trying to customize the underline border in the disabled state to be solid instead of the dashed line :

I tried this but it didn't work for underline :

```<code>::ng-deep.mat-form-field-disabled
 {

 }
</code>```

I want this to be gray solid in disabled state

```<code> <mat-form-field>
    <input matInput placeholder="Input" [disabled]='true'>
  </mat-form-field>
</code>```

答:
You don´t need linear gradient in background-image. This worked for me:</p>
```<code>::ng-deep .mat-form-field-disabled .mat-form-field-underline {
  background-color: #949494 !important;
  background-size: 1px 100% !important;
  background-repeat: repeat-x !important;
}
</code>```

Body:
I am trying to customize the angular material mat-form-field :
I was able to customize the underline border using :

::ng-deep.mat-form-field-ripple {
  background-color: yellow;
}

now I am trying to customize the underline border in the disabled state to be solid instead of the dashed line :

I tried this but it didn't work for underline :

::ng-deep.mat-form-field-disabled
 {

 }

I want this to be gray solid in disabled state

 <mat-form-field>
    <input matInput placeholder="Input" [disabled]='true'>
  </mat-form-field>

Body:
You don´t need linear gradient in background-image. This worked for me:

::ng-deep .mat-form-field-disabled .mat-form-field-underline {
  background-color: #949494 !important;
  background-size: 1px 100% !important;
  background-repeat: repeat-x !important;
}


问:
LINQ calling a method inside Select passing as parameter the selected item in linq
I want to call method in linq query select part of property. is it possible to call a method in inside select query.

enter image description here

答:
1: please write your code

2: it can not be done because you're function is in c# and the query wants to run in sql.

you have 3 options:

a: try quantify CancleInvoice after your query in c#

b: use simple codes that ef can translate to sql code

b: build your function in sql server and then you can use it in ef


答:
What you're getting is a compiler error, because mapToInt requires a ToIntFunction but you're providing none.

Also you don't need to collect the stream to a list only to convert it to a stream again. You can still use your stream as long as you don't call a terminal method.

So what you can do is something like this:

```<code>double average = company.getDepartments().stream()
        .flatMap(department -> department.getEmployees().stream())
        .map(Employee::getSalary)
        .filter(x -> x >= salaryLimit)
        .mapToDouble(salary -> salary)
        .average()
        .orElse(0.0);
</code>```

average() gives you an Optional<Double> so you need to unwrap the value at the end. As a default value you can return 0.0 with a call to orElse

Title: get average salary with Java stream api;

Body:
how can i get the average salary of company employees whose salary is more than salaryLimit?
I think first I need to get a list of all salaries and filter it + use mapToInt and average, but...nothing works((

public class TestCl {

@Data
@AllArgsConstructor
public class Company {
    private List<Department> departments;
}

@Data
@AllArgsConstructor
public class Department {
    private List<Employee> employees;
}

@Data
@AllArgsConstructor
public class Employee {
    private int salary;
}

@Test
public void test() {
    int salaryLimit = 25;

    List<Employee> employees = new ArrayList<>(){{
        add(new Employee(10));
        add(new Employee(20));
        add(new Employee(30));
        add(new Employee(40));
        add(new Employee(50));
    }};

    List<Department> departments = new ArrayList<>(){{
        add(new Department(employees));
        add(new Department(employees));
        add(new Department(employees));
        add(new Department(employees));
        add(new Department(employees));
    }};

    Company company = new Company(departments);

    float average = company.getDepartments().stream()
            .map(Department::getEmployees).toList().stream()
            .map(Employee::getSalary).toList().stream()
            .filter(x -> x >= salaryLimit).mapToInt().average();

    System.out.println(average);
}

}

Body:
What you're getting is a compiler error, because mapToInt requires a ToIntFunction but you're providing none.

Also you don't need to collect the stream to a list only to convert it to a stream again. You can still use your stream as long as you don't call a terminal method.

So what you can do is something like this:

double average = company.getDepartments().stream()
        .flatMap(department -> department.getEmployees().stream())
        .map(Employee::getSalary)
        .filter(x -> x >= salaryLimit)
        .mapToDouble(salary -> salary)
        .average()
        .orElse(0.0);

average() gives you an Optional<Double> so you need to unwrap the value at the end. As a default value you can return 0.0 with a call to orElse


问:
Don't implement all abstract method
I have a multiple sub classes that all inherit from the same base class.
Some of the base class methods are empty to be implemented by some sub classes, but not all of them.

In this rudimentary example, FirstChild re-implements do_a_barrel_roll(),

while SecondChild re-implements dont_do_a_barrel_roll()

```<code>class Parent:
    def __init__(self):
        ...

    def do_a_barrel_roll(self):
        pass

    def dont_do_a_barrel_roll(self):
        pass

    def say_hi(self):
        return "Hello"

class FirstChild(Parent):

    def __init__(self):
        super().__init__()

    def do_a_barrel_roll(self):
        ...
        return 42

class SecondChild(Parent):

    def __init__(self):
        super().__init__()

    def dont_do_a_barrel_roll(self):
        ...
        return 0
</code>```

Now I would like to make the Parent class an abstract class and thereby make the two empty methods abstract methods.

This is roughly what I want:

```<code>class Parent(ABC):
    def __init__(self):
        ...

    @abstractmethod
    def do_a_barrel_roll(self):
        pass

    @abstractmethod
    def dont_do_a_barrel_roll(self):
        pass

    def say_hi(self):
        return "Hello"

class FirstChild(Parent):

    def __init__(self):
        super().__init__()

    def do_a_barrel_roll(self):
        ...
        return 42

   # ignore implementation of second abstract method

class SecondChild(Parent):

    def __init__(self):
        super().__init__()

    # ignore implementation of first abstract method

    def dont_do_a_barrel_roll(self):
        ...
        return 0
</code>```

Unfortunately, Python wants me to implement every single abstract method for every single sub class, which I don't want to do due to the complexity of the actual code (1500+ lines of code, not he silly example above).

Is there a clean and easy way where I don't have to do that?

答:
If you only want to implement one of the two abstract methods, you should define two abstract base classes, one per method.

```<code>class Parent:
    def __init__(self):
        ...

    def say_hi(self):
        return "Hello"

class BarrelRollingParent(Parent, ABC):
    @abstractmethod
    def do_a_barrel_roll(self):
        pass

class NonBarrelRollingParent(Parent, ABC):
    @abstractmethod
    def dont_do_a_barrel_roll(self):
        pass

class FirstChild(BarrelRollingParent):
    def do_a_barrel_roll(self):
        ...
        return 42

class SecondChild(NonBarrelRollingParent):
    def dont_do_a_barrel_roll(self):
        ...
        return 0
</code>```

You can always inherit from both classes if you want to require both methods to be implemented.

```<code>class ThirdChild(BarrelRollingParent, NonBarrelRollingParent):
    def do_a_barrel_roll(self):
        ...

    def dont_do_a_barrel_roll(self):
        ...
</code>```

Title: Don't implement all abstract method

Body:
I have a multiple sub classes that all inherit from the same base class.
Some of the base class methods are empty to be implemented by some sub classes, but not all of them.

In this rudimentary example, FirstChild re-implements do_a_barrel_roll(),

while SecondChild re-implements dont_do_a_barrel_roll()

class Parent:
    def __init__(self):
        ...

    def do_a_barrel_roll(self):
        pass

    def dont_do_a_barrel_roll(self):
        pass

    def say_hi(self):
        return "Hello"

class FirstChild(Parent):

    def __init__(self):
        super().__init__()

    def do_a_barrel_roll(self):
        ...
        return 42

class SecondChild(Parent):

    def __init__(self):
        super().__init__()

    def dont_do_a_barrel_roll(self):
        ...
        return 0

Now I would like to make the Parent class an abstract class and thereby make the two empty methods abstract methods.

This is roughly what I want:

class Parent(ABC):
    def __init__(self):
        ...

    @abstractmethod
    def do_a_barrel_roll(self):
        pass

    @abstractmethod
    def dont_do_a_barrel_roll(self):
        pass

    def say_hi(self):
        return "Hello"

class FirstChild(Parent):

    def __init__(self):
        super().__init__()

    def do_a_barrel_roll(self):
        ...
        return 42

   # ignore implementation of second abstract method

class SecondChild(Parent):

    def __init__(self):
        super().__init__()

    # ignore implementation of first abstract method

    def dont_do_a_barrel_roll(self):
        ...
        return 0

Unfortunately, Python wants me to implement every single abstract method for every single sub class, which I don't want to do due to the complexity of the actual code (1500+ lines of code, not he silly example above).

Is there a clean and easy way where I don't have to do that?

Body:
If you only want to implement one of the two abstract methods, you should define two abstract base classes, one per method.

class Parent:
    def __init__(self):
        ...

    def say_hi(self):
        return "Hello"

class BarrelRollingParent(Parent, ABC):
    @abstractmethod
    def do_a_barrel_roll(self):
        pass

class NonBarrelRollingParent(Parent, ABC):
    @abstractmethod
    def dont_do_a_barrel_roll(self):
        pass

class FirstChild(BarrelRollingParent):
    def do_a_barrel_roll(self):
        ...
        return 42

class SecondChild(NonBarrelRollingParent):
    def dont_do_a_barrel_roll(self):
        ...
        return 0

You can always inherit from both classes if you want to require both methods to be implemented.

class ThirdChild(BarrelRollingParent, NonBarrelRollingParent):
    def do_a_barrel_roll(self):
        ...

    def dont_do_a_barrel_roll(self):
        ...


问:
How to add GUI to custom OpenAI gym enviroment?
I was following

Beginners Guide To Custom Environments in OpenAIs Gym

O’Reilly’s Hands-on Intelligent Agents

To set up an altogether new game for myself (sort of low graphic subway surfer). Though, I am able to understand how the mechanism are incorporated in a custom openai gym environment, I am still not able to make out how to add graphics to my game.Do I need a new library altogether & club it up with openai gym environment (like pygame)? New to game development hence need help.

答: You will need separate files for the environment and the GUI, yes. The question is: why do you need the environment in the first place? If it is only for training your agent, then you can just import the trained agent into your GUI script and load it and then use it to make predictions and moves etc.</p>


问:
How can I use the Telegram automatic message bot when I am not there?
how can I run the telegram auto message bot when I turn off my computer with the API I made with python?

Otherwise, it exits the terminal and the bot closes automatically.

答:
Are you asking why when your computer turns off, and the python file stops running, the bot no longer functions?

You would need to have either a server or another device to run it then, should you wish to turn your computer off

I'm not sure if I misunderstood this or not.


问:
JavaScript template literals substitute variable later (before values are known)
Is it possible to use template literals somehow before the values a known. Every demo on JS template literals looks like this:

```<code>var name = "John";
var s = `Hello ${name}`;
</code>```

But in real world, templates are defined before we know variable values. Somewhere is defined template (on page load):

```<code>var s = `Hello ${name}`;
</code>```

And then, 5 minutes later, when user logs in I want to use this template but it was already substituted so how to actually do it? Similar issue would be how to use template multiple times.

I can imagine having it some wrapper function but I want to have templates in JSON where there cannot be functions. Is it even possible?

答:
No.

Template strings are for populating at the time the template string is declared.

If you want to define it early and populate it later, define it inside a function. (An option you've rejected).

You might consider another template engine such as Nunjucks or EJS … but they'll still effectively be wrapped in a function.

Body:
Is it possible to use template literals somehow before the values a known. Every demo on JS template literals looks like this:

var name = "John";
var s = `Hello ${name}`;

But in real world, templates are defined before we know variable values. Somewhere is defined template (on page load):

var s = `Hello ${name}`;

And then, 5 minutes later, when user logs in I want to use this template but it was already substituted so how to actually do it? Similar issue would be how to use template multiple times.

I can imagine having it some wrapper function but I want to have templates in JSON where there cannot be functions. Is it even possible?


问:
Reading multiple variables from an object wrapped in Option[]
I have a variable obj: Option[MyObject] and want to extract multiple variables from it - if the object is not set, default values should be used.

Currently I do it like this:

```<code>val var1 = obj match {
    case Some(o) => e.var1
    case _ => "default1"
}
val var2 = obj match {
    case Some(o) => e.var2
    case _ => "default2"
}
...
</code>```

which is extremely verbose. I know I could do it like this:

```<code>val var1 = if (obj.isDefined) obj.get.var1 else "default1"
val var2 = if (obj.isDefined) obj.get.var2 else "default2"
</code>```

which still seems strange. I know I could use one big match and return a value object or tuple.

But what I would love is something similar to this:

```<code>val var1 = obj ? _.var1 : "default1"
val var2 = obj ? _.var2 : "default2"
</code>```

Is this possible somehow?

答:
How about this?

```<code>obj.map(_.var1).getOrElse("default1")
</code>```

or, if you prefer this style:

```<code>obj map (_ var1) getOrElse "default"
</code>```

Body:
I have a variable obj: Option[MyObject] and want to extract multiple variables from it - if the object is not set, default values should be used.

Currently I do it like this:

val var1 = obj match {
    case Some(o) => e.var1
    case _ => "default1"
}
val var2 = obj match {
    case Some(o) => e.var2
    case _ => "default2"
}
...

which is extremely verbose. I know I could do it like this:

val var1 = if (obj.isDefined) obj.get.var1 else "default1"
val var2 = if (obj.isDefined) obj.get.var2 else "default2"

which still seems strange. I know I could use one big match and return a value object or tuple.

But what I would love is something similar to this:

val var1 = obj ? _.var1 : "default1"
val var2 = obj ? _.var2 : "default2"

Is this possible somehow?

Body:
How about this?

obj.map(_.var1).getOrElse("default1")

or, if you prefer this style:

obj map (_ var1) getOrElse "default"


问:
lock the first value from a groupby in dataframe pandas python
I want to lock the first value from a groupby in dataframe pandas.

Is that possible?

example:

Hope someone can help me...

答:
This will do it for you

```<code>kv = df.groupby(by='first_col')['second_col'].first().to_dict()

def helper(k):
    return kv[k]

df['second_col'] = df['first_col'].apply(lambda x: helper(x))
</code>```

Note first_col and second_col are your column names

Body:
This will do it for you

kv = df.groupby(by='first_col')['second_col'].first().to_dict()

def helper(k):
    return kv[k]

df['second_col'] = df['first_col'].apply(lambda x: helper(x))

Note first_col and second_col are your column names


问:
Remove CSS pseudo element from jQuery form function
I developed a contact form for a website.

The field where users enter their message (a textarea box) has a jQuery character counter attached to it.

When the message is sent, an AJAX script refreshes the form and displays a success message.

All good so far.

The problem starts here:

When the user is entering their message and begins to reach the character limit, a warning notice appears, generated as a CSS pseudo element.

When the user exceeds the limit, a restriction notice appears, also generated by CSS.

The problem

When the user sends the message, while the warning notice is displayed, the warning notice won't leave after the page refresh.

This would also be a problem with the restriction notice, but another function disables the send button in this condition, so the form won't send when the counter is in negative territory.

I'm looking for a clean and simple function to integrate with my existing code that will remove the "approaching limit" pseudo element after the form is sent. Thank you.

// text area character counter
// displays total characters allowed
// displays warning at defined count (currently 150)
// disables submit button when < 0
// max characters that can be input set by maxlength attribute in HTML
(function($) {

    $.fn.charCount = function(submit, options){

        this.submit = submit;

        // default configuration properties
        var defaults = {
            allowed: 1250,
            warning: 150,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: ''
        };

        var options = $.extend(defaults, options);

        function calculate(obj,submit){

            submit.attr("disabled", "disabled");

            var count = $(obj).val().length;
            var available = options.allowed - count;
            if(available <= options.warning && available >= 0){
                $(obj).next().addClass(options.cssWarning);
            } else {
                $(obj).next().removeClass(options.cssWarning);
            }
            if(available < 0){
                $(obj).next().addClass(options.cssExceeded);
            } else {
                $(obj).next().removeClass(options.cssExceeded);
                submit.removeAttr("disabled");
            }

            $(obj).next().html(options.counterText + available);
        };

        this.each(function() {
            $(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');

            calculate(this, submit);

            $(this).keyup(function(){calculate(this,submit)});
            $(this).change(function(){calculate(this,submit)});
        });

    };

})(jQuery);

$(document).ready(function(){
    $("#modal-contact-form-message").charCount($("#submit_cform"));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* textarea and character counter */

.modalDialog form > #counter-container {}

.modalDialog form > #counter-container > .counter {
    font-size: 1.2em;
    color: #ccc;
    font-family: arial, helvetica, sans-serif
}
.modalDialog form > #counter-container .warning {
    color: orange;
}

.modalDialog form > #counter-container .warning::after {
    content: " approaching limit";
    font-size: 1em;
}

.modalDialog form > #counter-container .exceeded {
    color: red;
}

.modalDialog form > #counter-container .exceeded::after {
    content: " form won't submit";
    font-size: 1em;
}

/* success and error messages */

#modal-contact-form-responses,
#modal-subscription-form-messages {
    min-height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 5px 0;
    font-size: .9em;
}

.success {
    color: black;
    background-color: #dff2bf;
}

.error {
    color: black;
    background-color: #ffbaba;
}</code>```

<form action="" method="post" id="modal-contact-form">

    Name *
    <input type="text" name="name_cform" id="modal-contact-form-name" maxlength="75" required>

    E-mail *
    <input type="email" name="email_cform" id="modal-contact-form-email" maxlength="75" required>

    Subject
    <input type="text" name="subject_cform" id="modal-contact-form-subject" maxlength="75">

    Message *
    <textarea name="message_cform" id="modal-contact-form-message" maxlength="1500" cols="25" rows="5" required></textarea>

  <input type="hidden" name="formtarget_cform" value="modal" id="modal-contact-form-hidden">

  <button type="submit" name="submit_cform" id="modal-contact-form-submit">Send Message</button>

</form>```

答:
Create a new class to hide these elements. On submit, add this class.

```<code>.modalDialog form > #counter-container.is-submitting .warning::after,
.modalDialog form > #counter-container.is-submitting .exceeded::after {
    display: none !important;
}
</code>```
```<code>$("#counter-container").addClass("is-submitting");
</code>```

OR

Just remove these warning/error classes on submit since they must be present for the messages to show up

Body:
I developed a contact form for a website.

The field where users enter their message (a textarea box) has a jQuery character counter attached to it.

When the message is sent, an AJAX script refreshes the form and displays a success message.

All good so far.

The problem starts here:

When the user is entering their message and begins to reach the character limit, a warning notice appears, generated as a CSS pseudo element.

When the user exceeds the limit, a restriction notice appears, also generated by CSS.

The problem

When the user sends the message, while the warning notice is displayed, the warning notice won't leave after the page refresh.

This would also be a problem with the restriction notice, but another function disables the send button in this condition, so the form won't send when the counter is in negative territory.

I'm looking for a clean and simple function to integrate with my existing code that will remove the "approaching limit" pseudo element after the form is sent. Thank you.

// text area character counter
// displays total characters allowed
// displays warning at defined count (currently 150)
// disables submit button when < 0
// max characters that can be input set by maxlength attribute in HTML
(function($) {

    $.fn.charCount = function(submit, options){

        this.submit = submit;

        // default configuration properties
        var defaults = {
            allowed: 1250,
            warning: 150,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: ''
        };

        var options = $.extend(defaults, options);

        function calculate(obj,submit){

            submit.attr("disabled", "disabled");

            var count = $(obj).val().length;
            var available = options.allowed - count;
            if(available <= options.warning && available >= 0){
                $(obj).next().addClass(options.cssWarning);
            } else {
                $(obj).next().removeClass(options.cssWarning);
            }
            if(available < 0){
                $(obj).next().addClass(options.cssExceeded);
            } else {
                $(obj).next().removeClass(options.cssExceeded);
                submit.removeAttr("disabled");
            }

            $(obj).next().html(options.counterText + available);
        };

        this.each(function() {
            $(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');

            calculate(this, submit);

            $(this).keyup(function(){calculate(this,submit)});
            $(this).change(function(){calculate(this,submit)});
        });

    };

})(jQuery);

$(document).ready(function(){
    $("#modal-contact-form-message").charCount($("#submit_cform"));
});

/* textarea and character counter */

.modalDialog form > #counter-container {}

.modalDialog form > #counter-container > .counter {
    font-size: 1.2em;
    color: #ccc;
    font-family: arial, helvetica, sans-serif
}
.modalDialog form > #counter-container .warning {
    color: orange;
}

.modalDialog form > #counter-container .warning::after {
    content: " approaching limit";
    font-size: 1em;
}

.modalDialog form > #counter-container .exceeded {
    color: red;
}

.modalDialog form > #counter-container .exceeded::after {
    content: " form won't submit";
    font-size: 1em;
}

/* success and error messages */

#modal-contact-form-responses,
#modal-subscription-form-messages {
    min-height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 5px 0;
    font-size: .9em;
}

.success {
    color: black;
    background-color: #dff2bf;
}

.error {
    color: black;
    background-color: #ffbaba;
}

<form action="" method="post" id="modal-contact-form">

    Name *
    <input type="text" name="name_cform" id="modal-contact-form-name" maxlength="75" required>

    E-mail *
    <input type="email" name="email_cform" id="modal-contact-form-email" maxlength="75" required>

    Subject
    <input type="text" name="subject_cform" id="modal-contact-form-subject" maxlength="75">

    Message *
    <textarea name="message_cform" id="modal-contact-form-message" maxlength="1500" cols="25" rows="5" required></textarea>

  <input type="hidden" name="formtarget_cform" value="modal" id="modal-contact-form-hidden">

  <button type="submit" name="submit_cform" id="modal-contact-form-submit">Send Message</button>

</form>

Body:
Create a new class to hide these elements. On submit, add this class.

.modalDialog form > #counter-container.is-submitting .warning::after,
.modalDialog form > #counter-container.is-submitting .exceeded::after {
    display: none !important;
}

$("#counter-container").addClass("is-submitting");

OR

Just remove these warning/error classes on submit since they must be present for the messages to show up