index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
11,300 | 93f36cc93021abaed35a8147764fff977d79c0eb | eachLine = input()
counter, wrongPass, totIn = 0, 0, 1
while True:
lower = int(eachLine[0 : eachLine.find('-')])
upper = int(eachLine[(eachLine.find('-') + 1) : eachLine.find(' ')])
letterToCount = eachLine[eachLine.find(' ') + 1]
passToCheck = eachLine[(eachLine.find(' ') + 4):]
if lower <= passToCheck.count(letterToCount) <= upper:
#print('found one')
counter += 1
#print(lower, upper, letterToCount, passToCheck)
eachLine = input()
totIn += 1
if eachLine == '':
break
print(counter, totIn - 1) |
11,301 | 23f5de44ef98011f075c4957212f3f5d772b6bde | from knock30 import neko_mecab
for line in neko_mecab():
if line['pos'] == '名詞' and line['pos1'] == 'サ変接続':
print(line['surface'])
|
11,302 | 78f42c9b3d868febeab59433ee470959bd2a39d4 | import collections
import six
import tensorflow as tf
import os
import sys
class ImageReader(object):
def __init__(self, image_format='jpeg'):
with tf.Graph().as_default():
self._decode_data = tf.placeholder(dtype=tf.string)
self._image_format = image_format
self._sess = tf.Session()
if self._image_format in ('jpeg', 'jpg'):
self._decode = tf.image.decode_jpeg(self._decode_data)
elif self._image_format in ('png'):
self._decode = tf.image.decode_png(self._decode_data)
def read_image_dims(self, image_data):
"""
Decodes the Image data string.
"""
image = self.decode_image(image_data)
return image.shape[:3]
def decode_image(self, image_data):
"""
Decodes the image data string.
Args:
image_data : string or image data
"""
image = self._sess.run(self._decode,
feed_dict={self._decode_data : image_data})
if len(image.shape) != 3 or image.shape[2] not in (1,3):
raise ValueError('The image channels not supported.')
return image
def _int64_list_feature(values):
"""
Returns a TF-Feature of int64_list
Args:
values: A scaler or list of values
Returns:
A TF-Feature.
"""
if not isinstance(values, collections.Iterable):
values = [values]
return tf.train.Feature(int64_list=tf.train.Int64List(value=values))
def _bytes_list_feature(values):
"""
Returns a TF-Feature or bytes
"""
def norm2bytes(value):
return value.encode() if isinstance(value, str) and six.PY3 else value
return tf.train.Feature(
bytes_list=tf.train.BytesList(value=[norm2bytes(values)]))
def image_to_tfexample(image_data, img_name, height, width, class_label, class_desc):
"""
Converts one image/segmentation pair to tf example
Args:
image_data:
filename:
height:
width
seg_data: string of semantic segmentation data.
"""
return tf.train.Example(features=tf.train.Features(feature={
'image/encoded': _bytes_list_feature(image_data),
'image/filename': _bytes_list_feature(img_name),
'image/height': _int64_list_feature(height),
'image/width': _int64_list_feature(width),
'image/label': _int64_list_feature(class_label),
'image/labeldesc': _bytes_list_feature(class_desc)
}))
def _parse_function(example_proto):
keys_to_features = {
'image/encoded': tf.FixedLenFeature(
(), tf.string, default_value=''),
'image/filename': tf.FixedLenFeature(
(), tf.string, default_value=''),
'image/height': tf.FixedLenFeature(
(), tf.int64, default_value=0),
'image/width': tf.FixedLenFeature(
(), tf.int64, default_value=0),
'image/label': tf.FixedLenFeature(
(), tf.int64),
'image/labeldesc': tf.FixedLenFeature(
(), tf.string)
}
parsed_features = tf.parse_single_example(example_proto, keys_to_features)
with tf.variable_scope('decoder'):
input_image = tf.image.decode_jpeg(parsed_features['image/encoded'])
input_height = parsed_features['image/height']
input_width = parsed_features['image/width']
image_name = parsed_features['image/filename']
image_label = parsed_features['image/label']
label_desc = parsed_features['image/labeldesc']
return input_image, input_height, input_width, image_name, image_label, label_desc
|
11,303 | fa52dded5ed4a9863e796d2e840d3e04f6d79f30 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
import os
import webapp2
import MySQLdb
from models import UserRequest
# Define your production Cloud SQL instance information.
_INSTANCE_NAME = 'simple-gae-app1:mydb'
class MainHandler(webapp2.RequestHandler):
def get(self):
# Display existing guestbook entries and a form to add new entries.
if (os.getenv('SERVER_SOFTWARE') and
os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
db = MySQLdb.connect(unix_socket='/cloudsql/' + _INSTANCE_NAME, db='simplegaeapp', user='root')
else:
db = MySQLdb.connect(host='127.0.0.1', port=3306, db='simplegaeapp', user='root', passwd="root")
# Alternatively, connect to a Google Cloud SQL instance using:
# db = MySQLdb.connect(host='ip-address-of-google-cloud-sql-instance', port=3306, user='root')
cursor = db.cursor()
user_request = UserRequest(self.request.get("api_key"), self.request.get("user_id"),
self.request.get("encoded_user_email"))
# Not required
user_request.beacon_id = self.request.get("beacon_id")
user_request.group = self.request.get("group")
user_request.campaign = self.request.get("campaign")
user_request.sent_date = self.request.get("sent_date")
user_request.custom_1 = self.request.get("custom_1")
user_request.custom_2 = self.request.get("custom_2")
user_request.custom_3 = self.request.get("custom_3")
# Set response type
self.response.headers['Content-Type'] = 'application/json'
# Validate required fields
if not user_request.validate_on_submit():
result = {"error": "api_key and user_id and encoded_user_email is required."}
return self.response.out.write(json.dumps(result))
#print(user_request.as_sql_string())
cursor.execute(user_request.as_sql_string())
db.commit()
db.close()
return self.response.out.write(json.dumps({"OK": True}))
class TableHandler(webapp2.RequestHandler):
def get(self):
# Display existing guestbook entries and a form to add new entries.
if (os.getenv('SERVER_SOFTWARE') and
os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
db = MySQLdb.connect(unix_socket='/cloudsql/' + _INSTANCE_NAME, db='simplegaeapp', user='root')
else:
db = MySQLdb.connect(host='127.0.0.1', port=3306, db='simplegaeapp', user='root', passwd="root")
# Alternatively, connect to a Google Cloud SQL instance using:
# db = MySQLdb.connect(host='ip-address-of-google-cloud-sql-instance', port=3306, user='root')
cursor = db.cursor()
cursor.execute("SELECT * FROM requests LIMIT 1000;")
requests = []
for row in cursor.fetchall():
requests.append(dict([('request_id', row[0]),
('api_key', row[1]),
('user_id', row[2]),
('encoded_user_email', row[3]),
('beacon_id', row[4]),
('group', row[5]),
('campaign', row[6]),
('sent_date', row[7]),
('custom_1', row[8]),
('custom_2', row[9]),
('custom_3', row[10])]))
self.response.headers['Content-Type'] = 'application/json'
return self.response.out.write(json.dumps({"First 1000 requests: ": requests}))
app = webapp2.WSGIApplication([
('/', MainHandler),
('/requests', TableHandler),
], debug=True)
|
11,304 | 24398c627ac4764511b66629b41da24a1873c123 | import sys
import math
read = sys.stdin.readline
def find(x) :
if par[x] == x : return par[x]
else :
par[x] = find(par[x])
return par[x]
def merge(x,y) :
p_x = find(x)
p_y = find(y)
if p_x == p_y : return
par[p_x] = p_y
def dist(x,y) :
return math.sqrt((x[0]-y[0])**2 + (x[1]-y[1])**2)
N = int(read())
pt = [tuple(map(float,read().split())) for _ in range(N)]
par = [i for i in range(N)]
tree = []
for i in range(N) :
for j in range(i+1,N) :
tree.append([dist(pt[i],pt[j]),i,j])
tree.sort()
cost = 0
for c,a,b in tree :
if find(a) == find(b) : continue
merge(a, b)
cost += c
print(round(cost,2))
|
11,305 | 70aa24b0f2d62fea5c02c6af09ac256a316f2d27 | #!/usr/bin/python
""" Use with firmware version 2.2.5 or later.
Cubro Packetmaster REST API demo. Menu driven interface for interacting with
a Cubro Packetmaster via the REST API. """
#Import necessary Python libraries for interacting with the REST API
from __future__ import print_function #Requires Python 2.6 or later
from getpass import getpass
from six import moves
import pm_input_check
from packetmaster_ex_rest import PacketmasterEX
# Add code to handle case and verify input in all areas where needed
def set_ip():
"""Validates then sets an IP address for a Cubro PacketmasterEX device."""
fail_count = 0
while fail_count < 3:
address = moves.input('What is the IP address of the Packetmaster you want to access?: ')
if pm_input_check.ipv4(address) != 0:
address = pm_input_check.ipv4(address)
return address
else:
print("That is not a valid IPv4 address.")
fail_count += 1
print("That is not a valid IPv4 address. Exiting")
exit()
if __name__ == '__main__':
#Welcome statement
print('''
________ ______ ____ ____ _____ ______ _____ _______ ____ ____ __
/ ____/ / / / __ )/ __ \/ __ \ / __ \/ ____// __//_ ___/ / __ \ / __ \ / /
/ / / / / / /_/ / /_/ / / / / / /_/ / __/ / /__ / / / /_/ // /_/ // /
/ /___/ /_/ / /_/ / _, _/ /_/ / / _, _/ /___ \__ \ / / / __ // ___// /
\____/\____/_____/_/ |_|\____/ /_/ \_\/_____//______//_/ /_/ /_//_/ /_/
###################################################################################
\n''')
#IP address to access REST data of device
ADDRESS = set_ip()
#Device credentials
USERNAME = moves.input('Enter your username: ')
PASSWORD = getpass()
#Initialize Packetmaster object
PACKETMASTER = PacketmasterEX(ADDRESS, USERNAME, PASSWORD)
def topmenu():
"""Top menu in hierarchy for device management."""
global ADDRESS, USERNAME, PASSWORD, PACKETMASTER
try:
print('\nOptions for %s at %s acting as user %s' % (PACKETMASTER.model, ADDRESS, USERNAME))
except AttributeError as error:
exit()
print('''
1 - Change My working device
2 - Change My user credentials
3 - Manage Device
4 - Quit \n''')
option = moves.input('Enter selection number: ')
try:
option = int(option)
except ValueError as reason:
print(reason)
topmenu()
if option == 1:
ADDRESS = set_ip()
PACKETMASTER = PacketmasterEX(ADDRESS, USERNAME, PASSWORD)
topmenu()
elif option == 2:
USERNAME = moves.input('Username: ')
PASSWORD = getpass()
PACKETMASTER = PacketmasterEX(ADDRESS, USERNAME, PASSWORD)
topmenu()
elif option == 3:
manage()
elif option == 4:
print('Goodbye')
exit()
else:
print('That is not a valid selection \n')
topmenu()
def manage():
"""Menu for managing Cubro PacketmasterEX device."""
print('''\n%s at %s acting as user %s
\nDevice Management Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - Hardware Configuration Menu
2 - Rule and Port Group Configuration Menu
3 - App Configuration Menu
4 - Savepoint Configuration Menu
5 - User Management Menu
6 - Back
7 - Quit \n
Enter the number of the selection to check: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
manage()
menus = {1: hardwareconfig,
2: ruleconfig,
3: appconfig,
4: saveconfig,
5: userconfig,
6: topmenu,
7: exit}
try:
select = menus[choice]
select()
except KeyError as reason:
print("That is not a valid selection.", reason)
manage()
def hardwareconfig():
"""Menu for configuring hardware and management related settings."""
print('''\n%s at %s acting as user %s
\nHardware Configuration Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - Model
2 - Serial Number
3 - Hardware Generation
4 - Firmware version
5 - API Level
6 - Temperature and Fans
7 - ID LED Status
8 - ID LED on/off
9 - OS and CPU Load Averages
10 - TCAM Flows
11 - Memory Usage
12 - CCH Server Revision
13 - Device OpenFlow Datapath ID
14 - Set Vitrum License
15 - Device Label and Notes Submenu
16 - IP Configuration Submenu
17 - DNS Configuration Submenu
18 - Port Configuration Submenu
19 - Telnet service submenu
20 - Webserver Submenu
21 - Controller Submenu
22 - Reboot Packetmaster
23 - Back
24 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
hardwareconfig()
execute = {1: PACKETMASTER.device_model,
2: PACKETMASTER.serial_number,
3: PACKETMASTER.hardware_generation,
4: PACKETMASTER.firmware_version,
5: PACKETMASTER.api_level,
6: PACKETMASTER.env_info,
7: PACKETMASTER.id_led,
8: PACKETMASTER.set_id_led_guided,
9: PACKETMASTER.load_info,
10: PACKETMASTER.tcam,
11: PACKETMASTER.mem_free,
12: PACKETMASTER.server_revision,
13: PACKETMASTER.get_dpid,
14: PACKETMASTER.set_license_guided,
15: notesmenu,
16: ipconfig,
17: dns,
18: portconfig,
19: telnet,
20: web,
21: controller,
22: PACKETMASTER.reboot,
23: manage,
24: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
hardwareconfig()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
hardwareconfig()
def notesmenu():
"""Submenu for device label and device notes settings."""
print('''\n%s at %s acting as user %s
\nDevice Label and Notes Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - Get Label and Notes
2 - Change Label only
3 - Change Label and Notes
4 - Back
5 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
notesmenu()
execute = {1: PACKETMASTER.device_label,
2: PACKETMASTER.set_name_guided,
3: PACKETMASTER.set_label_guided,
4: hardwareconfig,
5: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
notesmenu()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
notesmenu()
def ipconfig():
"""Submenu for IP configuration settings."""
print('''\n%s at %s acting as user %s
\nIP Configuration Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - Get current IP configuration
2 - Change IP configuration
3 - Back
4 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
ipconfig()
execute = {1: PACKETMASTER.ip_config,
2: PACKETMASTER.set_ip_config_guided,
3: hardwareconfig,
4: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
ipconfig()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
ipconfig()
def dns():
"""Submenu for DNS settings."""
print('''\n%s at %s acting as user %s
\nDNS Configuration Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - Get current DNS configuration
2 - Change DNS configuration
3 - Back
4 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
dns()
execute = {1: PACKETMASTER.get_dns,
2: PACKETMASTER.set_dns_guided,
3: hardwareconfig,
4: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
dns()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
dns()
def portconfig():
"""Submenu for port configuration settings."""
print('''\n%s at %s acting as user %s
\nPort Configuration Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - Get current port configuration
2 - Get current port status
3 - Get current port counters
4 - Get SFP status
5 - Change Port Configuration
6 - Shut Down or Activate Port
7 - Reset Port Counters
8 - Back
9 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
portconfig()
execute = {1: PACKETMASTER.port_config,
2: PACKETMASTER.port_info,
3: PACKETMASTER.port_statistics,
4: PACKETMASTER.sfp_info,
5: PACKETMASTER.set_port_config_guided,
6: PACKETMASTER.port_on_off_guided,
7: PACKETMASTER.reset_port_counters,
8: hardwareconfig,
9: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
portconfig()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
portconfig()
def web():
"""Submenu for Web Server settings."""
print('''\n%s at %s acting as user %s
\nWebserver Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - Web logs
2 - Delete web Logs
3 - Restart webserver
4 - Enable or Disable HTTPS secure web interface
5 - Back
6 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
web()
execute = {1: PACKETMASTER.web_log,
2: PACKETMASTER.del_web_log,
3: PACKETMASTER.restart_webserver,
4: PACKETMASTER.set_https_guided,
5: hardwareconfig,
6: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
web()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
web()
def telnet():
"""Submneu for Telnet service settings."""
print('''\n%s at %s acting as user %s
\nTelnet Service Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - Get current Telnet status
2 - Enable or Disable Telnet service
3 - Back
4 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
telnet()
execute = {1: PACKETMASTER.get_telnet,
2: PACKETMASTER.set_telnet_guided,
3: hardwareconfig,
4: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
telnet()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
telnet()
def controller():
"""Submenu for Vitrum Controller settings."""
print('''\n%s at %s acting as user %s
\nController Configuration Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - Get current Controller configuration
2 - Configure Controller
3 - Delete Controller
4 - Back
5 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
controller()
execute = {1: PACKETMASTER.get_controller,
2: PACKETMASTER.set_controller_guided,
3: PACKETMASTER.del_controller_guided,
4: hardwareconfig,
5: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
controller()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
controller()
def ruleconfig():
"""Menu for configuring rules/filters and port groups."""
print('''\n%s at %s acting as user %s
\nRule and Port Group Configuration Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - Show Rules and Rule Counters
2 - Add Rule
3 - Modify Rule
4 - Delete Rule
5 - Delete All Rules
6 - Reset Rule Counters
7 - Show Groups
8 - Add Group
9 - Modify Group
10 - Delete Group
11 - Delete all active groups and associated rules
12 - Show Active Load-Balancing Hashes
13 - Set Load Balancing Group Hash Algorithms
14 - Show Rule Permanence Mode
15 - Set Rule Permanence Mode
16 - Show Rule Storage Mode
17 - Set Rule Storage Mode
18 - Back
19 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
ruleconfig()
execute = {1: PACKETMASTER.rules_active,
2: PACKETMASTER.add_rule_guided,
3: PACKETMASTER.mod_rule_guided,
4: PACKETMASTER.del_rule_guided,
5: PACKETMASTER.del_rule_all,
6: PACKETMASTER.reset_rule_counters,
7: PACKETMASTER.groups_active,
8: PACKETMASTER.add_group_guided,
9: PACKETMASTER.mod_group_guided,
10: PACKETMASTER.delete_group_guided,
11: PACKETMASTER.delete_groups_all,
12: PACKETMASTER.hash_algorithms,
13: PACKETMASTER.set_hash_algorithms_guided,
14: PACKETMASTER.rule_permanence,
15: PACKETMASTER.set_rule_permanence_guided,
16: PACKETMASTER.storage_mode,
17: PACKETMASTER.set_storage_mode_guided,
18: manage,
19: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
ruleconfig()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
ruleconfig()
def appconfig():
"""Menu for configuring App settings."""
print('''\n%s at %s acting as user %s
\nApp Configuration Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - List Apps
2 - List Running Apps
3 - Start an App instance
4 - Modify an App instance
5 - Kill an App instance
6 - Call a custom App action
7 - Back
8 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
appconfig()
execute = {1: PACKETMASTER.device_apps,
2: PACKETMASTER.apps_active,
3: PACKETMASTER.start_app_guided,
4: PACKETMASTER.mod_app_guided,
5: PACKETMASTER.kill_app_guided,
6: PACKETMASTER.call_app_action_guided,
7: manage,
8: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
appconfig()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
appconfig()
def saveconfig():
"""Menu for save point configuration settings."""
print('''\n%s at %s acting as user %s
\nSave Point Configuration Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - List Save Points
2 - Activate a save point for ports
3 - Activate a save point for rules
4 - Set the rule save point to be loaded on boot
5 - Export save points
6 - Modify a save point for port configuration
7 - Modify a save point for rules
8 - Create save point from current port configuration
9 - Create a quicksave point from current configuration
10 - Create a save point from current rules
11 - Delete a port save point
12 - Delete a rule save point
13 - Back
14 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
saveconfig()
execute = {1: PACKETMASTER.save_points,
2: PACKETMASTER.set_port_savepoint_guided,
3: PACKETMASTER.set_rule_savepoint_guided,
4: PACKETMASTER.set_boot_savepoint_guided,
5: PACKETMASTER.export_savepoint_guided,
6: PACKETMASTER.mod_port_savepoint_guided,
7: PACKETMASTER.mod_rule_savepoint_guided,
8: PACKETMASTER.create_port_savepoint_guided,
9: PACKETMASTER.create_quick_savepoint,
10: PACKETMASTER.create_rule_savepoint_guided,
11: PACKETMASTER.delete_port_savepoint_guided,
12: PACKETMASTER.delete_rule_savepoint_guided,
13: manage,
14: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
saveconfig()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
saveconfig()
def userconfig():
"""Menu for user account related settings."""
print('''\n%s at %s acting as user %s
\nUser Configuration Menu''' % (PACKETMASTER.model, ADDRESS, USERNAME))
choice = moves.input('''
1 - List Users
2 - Add User
3 - Modify User
4 - Delete User
5 - UAC Status
6 - Enable or Disable UAC
7 - Show RADIUS Settings
8 - Configure RADIUS settings
9 - Back
10 - Quit \n
Enter selection number: ''')
try:
choice = int(choice)
except ValueError as reason:
print("That is not a valid selection.", reason)
userconfig()
execute = {1: PACKETMASTER.get_users,
2: PACKETMASTER.add_user_guided,
3: PACKETMASTER.mod_user_guided,
4: PACKETMASTER.delete_user_guided,
5: PACKETMASTER.get_uac,
6: PACKETMASTER.set_uac_guided,
7: PACKETMASTER.get_radius,
8: PACKETMASTER.set_radius_guided,
9: manage,
10: exit}
if choice in execute:
try:
select = execute[choice]
run = select()
print(run)
userconfig()
except KeyError as reason:
print(reason)
else:
print("That is not a valid selection.")
userconfig()
topmenu()
|
11,306 | d076c8817f409a4280ed22a49e39ac9e0ce3ed7e |
import os
import errno
import aria as aria_
from aria import core as aria_core
from aria.orchestrator import (
plugin,
workflow_runner
)
from aria.storage import sql_mapi
from aria.storage import filesystem_rapi
class AriaCore():
def __init__(self, root_dir=None):
self._root_dir = root_dir or \
os.path.join(os.path.expanduser('~'), '.arest')
models_dir = os.path.join(self._root_dir, 'models')
resource_dir = os.path.join(self._root_dir, 'resources')
plugins_dir = os.path.join(self._root_dir, 'plugins')
self._create_paths(models_dir, resource_dir, plugins_dir)
# Create a model storage
self._model_storage = aria_.application_model_storage(
api=sql_mapi.SQLAlchemyModelAPI,
initiator_kwargs={'base_dir': models_dir}
)
self._resource_storage = aria_.application_resource_storage(
api=filesystem_rapi.FileSystemResourceAPI,
api_kwargs={'directory': resource_dir}
)
self._plugin_manager = plugin.PluginManager(
model=self._model_storage,
plugins_dir=plugins_dir
)
self._core = aria_core.Core(
model_storage=self.model,
resource_storage=self.resource,
plugin_manager=self._plugin_manager
)
@property
def model(self):
return self._model_storage
@property
def resource(self):
return self._resource_storage
def install_plugin(self, source):
self._plugin_manager.validate_plugin(source)
self._plugin_manager.install(source)
def create_service_template(self, path, name):
aria_.install_aria_extensions()
self._core.create_service_template(path, os.path.dirname(path), name)
return str(self.model.service_template.get_by_name(name).id)
def create_service(self, *args, **kwargs):
aria_.install_aria_extensions()
kwargs.setdefault('inputs', {})
self._core.create_service(*args, **kwargs)
def execute_workflow(self, **kwargs):
wf_runner = workflow_runner.WorkflowRunner(
self.model,
self.resource,
self._plugin_manager,
**kwargs
)
wf_runner.execute()
def delete_service(self, *args, **kwargs):
self._core.delete_service(*args, **kwargs)
def delete_service_template(self, *args, **kwargs):
self._core.delete_service_template(*args, **kwargs)
@staticmethod
def _create_paths(*paths):
existing_paths = []
for path in paths:
try:
os.makedirs(path)
existing_paths += path
except OSError as e:
if e.errno != errno.EEXIST:
raise
else:
existing_paths += path
return existing_paths
aria = AriaCore()
|
11,307 | f646a46ec4291684e35412cff58b4b50616968ca | import pandas as pd
from transformation_script.property_function import rename_properties, remove_trailing_zero
import os
def nucleic_acid_transformation(nucleic_acid_file_name, log, input_files, output_folder):
log.info('Transforming nucleic_acid.csv')
nucleic_acid_df = pd.read_csv(nucleic_acid_file_name)
nucleic_acid_df['show_node'] = ['TRUE'] * len(nucleic_acid_df)
nucleic_acid_df['nucleic_acid_type'] = ['Pooled DNA/cDNA'] * len(nucleic_acid_df)
specimen_id = []
aliquot_id = []
for index in range(len(nucleic_acid_df)):
specimen_id.append('CTDC-SP-' + nucleic_acid_df['specimen.biopsySequenceNumber'].iloc[index])
aliquot_id.append('CTDC-NA-' + nucleic_acid_df['molecularSequenceNumber'].iloc[index])
nucleic_acid_df['specimen.biopsySequenceNumber'] = specimen_id
nucleic_acid_df['aliquot_id'] = aliquot_id
property = [
{'old':'specimen.biopsySequenceNumber', 'new':'specimen.specimen_id'},
{'old':'molecularSequenceNumber', 'new':'molecular_sequence_number'},
{'old':'dnaConcentration', 'new':'nucleic_acid_concentration'},
{'old':'dnaVolume', 'new':'nucleic_acid_volume'}
]
nucleic_acid_df = rename_properties(nucleic_acid_df, property)
nucleic_acid_df = nucleic_acid_df.reindex(columns=['type', 'show_node', 'specimen.specimen_id', 'aliquot_id', 'molecular_sequence_number',
'nucleic_acid_concentration', 'nucleic_acid_volume', 'nucleic_acid_type'])
nucleic_acid_df['nucleic_acid_volume'] = remove_trailing_zero(nucleic_acid_df['nucleic_acid_volume'])
nucleic_acid_df['nucleic_acid_concentration'] = remove_trailing_zero(nucleic_acid_df['nucleic_acid_concentration'])
input_file_name = os.path.splitext(input_files['nucleic_acid'])[0]
output_file = os.path.join(output_folder, input_file_name + ".tsv")
nucleic_acid_df.to_csv(output_file, sep = "\t", index = False)
|
11,308 | dbaa204b196602a87e08891ee238d55f9360cc81 | import tkinter as tk
from time import sleep
qntr =0
ml = 0
toma = 0
meta = 0
# width = Largura
# height = altura
tconf = tk.Tk()
def quit():
global tconf
tconf.quit()
def confirm(a):
global meta
try:
meta = int(a)
except:
aviso = tk.Label(frame,text = 'VALOR INVÁLIDO DIGITE NOVAMENTE!', fg = 'white', bg = '#4682B4')
aviso.place(relx =0, rely = 0.75, relheight = 0.25, relwidth = 1)
else:
tconf.destroy()
canvas = tk.Canvas(tconf, height = 150, width = 400)
canvas.pack()
back = tk.PhotoImage(file = 'waterbg.png')
back_label = tk.Label(tconf, image = back)
back_label.place(relwidth = 1, relheight = 1)
frame = tk.Frame(bg = '#4682B4')
frame.place(relx = 0.05, rely = 0.1, relwidth = 0.91, relheight = 0.8)
info = tk.Label(frame, bg = '#4682B4', text = 'PONHA SUA META DIARIA A BAIXO (EM ML): ', fg= 'white', font = 40)
info.place(relx = 0, rely = 0.1, relwidth = 1, relheight = 0.25)
metaintp = tk.Entry(frame,font = 15)
metaintp.place(relx = 0.05, rely = 0.4, relwidth = 0.25, relheight = 0.25)
bttn = tk.Button(text = 'CONFIRMAR', command = lambda: confirm(metaintp.get()))
bttn.place(relx = 0.4, rely = 0.43, relwidth = 0.25, relheight = 0.2)
tconf.mainloop()
def count(qnt):
global toma, qntr
try:
qntr = int(qnt)
except:
pass
else:
toma += qntr
frame_info_info = tk.Label(frame_info, fg = 'white', bg = '#1E90FF', text = f'VOCE JA TOMOU: {toma} Mls', font = 10)
frame_info_info.place(relx = 0.05, rely = 0.1, relwidth = 0.9, relheight = 0.2)
if int(toma) >= meta:
check_label1 = tk.Label(frame2, image = check)
check_label1.place(relx = 0.25, rely = 0.05, relwidth = 0.5, relheight = 0.5)
tela = tk.Tk()
check = tk.PhotoImage(file = 'concluido.png')
canvatyu = tk.Canvas(height = 400, width = 350)
canvatyu.pack()
back1 = tk.PhotoImage(file = 'waterbg.png')
back_label1 = tk.Label(tela, image = back1)
back_label1.place(relwidth = 1, relheight = 1)
frame2 = tk.Label(tela,bg = '#f0f0f0')
frame2.place(relx = 0.1, rely = 0.05, relheight = 0.9, relwidth = 0.8)
copo = tk.PhotoImage(file = 'copo.png')
copo_label = tk.Label(frame2, image = copo)
copo_label.place(relx = 0.25, rely = 0.05, relwidth = 0.5, relheight = 0.5)
frame_info = tk.Label(frame2, bg = '#4682B4')
frame_info.place(relx = 0.05, rely = 0.55, relheight = 0.4, relwidth = 0.9)
frame_info_info = tk.Label(frame_info, fg = 'white', bg = '#1E90FF', text = f'VOCE JA TOMOU: {toma} Mls', font = 10)
frame_info_info.place(relx = 0.05, rely = 0.1, relwidth = 0.9, relheight = 0.2)
addintp = tk.Entry(frame_info,bg = 'white', font = 10)
addintp.place(relx = 0.35, rely = 0.4, relwidth = 0.25, relheight = 0.2)
addbttn = tk.Button(frame_info,text = 'ADICIONAR',command = lambda: count(addintp.get()))
addbttn.place(relx = 0.28, rely = 0.7, relwidth = 0.4,relheight = 0.2)
tela.mainloop() |
11,309 | b3f7e1292a60918af5a0dc16180e6bf15ecf383e | import requests
from bs4 import BeautifulSoup
import pickle
import os
from urllib.parse import urlparse, unquote, quote, parse_qs
import pandas as pd
import json
from datetime import datetime, timedelta
from base64 import b64encode
class FacebookPostsScraper:
# We need the email and password to access Facebook, and optionally the text in the Url that identifies the "view full post".
def __init__(self, email, password, post_url_text='Full Story'):
self.email = email
self.password = password
self.headers = { # This is the important part: Nokia C3 User Agent
'User-Agent': 'NokiaC3-00/5.0 (07.20) Profile/MIDP-2.1 Configuration/CLDC-1.1 Mozilla/5.0 AppleWebKit/420+ (KHTML, like Gecko) Safari/420+'
}
self.session = requests.session() # Create the session for the next requests
self.cookies_path = 'session_facebook.cki' # Give a name to store the session in a cookie file.
# At certain point, we need find the text in the Url to point the url post, in my case, my Facebook is in
# English, this is why it says 'Full Story', so, you need to change this for your language.
# Some translations:
# - English: 'Full Story'
# - Spanish: 'Historia completa'
self.post_url_text = post_url_text
# Evaluate if NOT exists a cookie file, if NOT exists the we make the Login request to Facebook,
# else we just load the current cookie to maintain the older session.
if self.new_session():
self.login()
self.posts = [] # Store the scraped posts
# We need to check if we already have a session saved or need to log to Facebook
def new_session(self):
if not os.path.exists(self.cookies_path):
return True
f = open(self.cookies_path, 'rb')
cookies = pickle.load(f)
self.session.cookies = cookies
return False
# Utility function to make the requests and convert to soup object if necessary
def make_request(self, url, method='GET', data=None, is_soup=True):
if len(url) == 0:
raise Exception(f'Empty Url')
if method == 'GET':
resp = self.session.get(url, headers=self.headers)
elif method == 'POST':
resp = self.session.post(url, headers=self.headers, data=data)
else:
raise Exception(f'Method [{method}] Not Supported')
if resp.status_code != 200:
raise Exception(f'Error [{resp.status_code}] > {url}')
if is_soup:
return BeautifulSoup(resp.text, 'lxml')
return resp
# The first time we login
def login(self):
# Get the content of HTML of mobile Login Facebook page
url_home = "https://m.facebook.com/"
soup = self.make_request(url_home)
if soup is None:
raise Exception("Couldn't load the Login Page")
# Here we need to extract this tokens from the Login Page
lsd = soup.find("input", {"name": "lsd"}).get("value")
jazoest = soup.find("input", {"name": "jazoest"}).get("value")
m_ts = soup.find("input", {"name": "m_ts"}).get("value")
li = soup.find("input", {"name": "li"}).get("value")
try_number = soup.find("input", {"name": "try_number"}).get("value")
unrecognized_tries = soup.find("input", {"name": "unrecognized_tries"}).get("value")
# This is the url to send the login params to Facebook
url_login = "https://m.facebook.com/login/device-based/regular/login/?refsrc=https%3A%2F%2Fm.facebook.com%2F&lwv=100&refid=8"
payload = {
"lsd": lsd,
"jazoest": jazoest,
"m_ts": m_ts,
"li": li,
"try_number": try_number,
"unrecognized_tries": unrecognized_tries,
"email": self.email,
"pass": self.password,
"login": "Iniciar sesión",
"prefill_contact_point": "",
"prefill_source": "",
"prefill_type": "",
"first_prefill_source": "",
"first_prefill_type": "",
"had_cp_prefilled": "false",
"had_password_prefilled": "false",
"is_smart_lock": "false",
"_fb_noscript": "true"
}
soup = self.make_request(url_login, method='POST', data=payload, is_soup=True)
if soup is None:
raise Exception(f"The login request couldn't be made: {url_login}")
redirect = soup.select_one('a')
if not redirect:
raise Exception("Please log in desktop/mobile Facebook and change your password")
url_redirect = redirect.get('href', '')
resp = self.make_request(url_redirect)
if resp is None:
raise Exception(f"The login request couldn't be made: {url_redirect}")
# Finally we get the cookies from the session and save it in a file for future usage
cookies = self.session.cookies
f = open(self.cookies_path, 'wb')
pickle.dump(cookies, f)
return {'code': 200}
# Scrap a list of profiles
def get_posts_from_list(self, profiles):
data = []
n = len(profiles)
for idx in range(n):
profile = profiles[idx]
print(f'{idx + 1}/{n}. {profile}')
posts = self.get_posts_from_profile(profile)
data.append(posts)
return data
# This is the extraction point!
def get_posts_from_profile(self, url_profile):
# Prepare the Url to point to the posts feed
if "www." in url_profile: url_profile = url_profile.replace('www.', 'm.')
if 'v=timeline' not in url_profile:
if '?' in url_profile:
url_profile = f'{url_profile}&v=timeline'
else:
url_profile = f'{url_profile}?v=timeline'
#is_group = '/groups/' in url_profile
# Make a simple GET request
soup = self.make_request(url_profile)
if soup is None:
print(f"Couldn't load the Page: {url_profile}")
return []
# Now the extraction...
css_profile = '.storyStream > div' # Select the posts from a user profile
css_page = '#recent > div > div > div' # Select the posts from a Facebook page
css_group = '#m_group_stories_container > div > div' # Select the posts from a Facebook group
raw_data = soup.select(f'{css_profile} , {css_page} , {css_group}') # Now join and scrape it
posts = []
for item in raw_data: # Now, for every post...
published = item.select_one('abbr') # Get the formatted datetime of published
description = item.select('p') # Get list of all p tag, they compose the description
images = item.select('a > img') # Get list of all images
_external_links = item.select('p a') # Get list of any link in the description, this are external links
post_url = item.find('a', text=self.post_url_text) # Get the url to point this post.
like_url = item.find('a', text='Like') # Get the Like url.
# Clean the publish date
if published is not None:
published = published.get_text()
else:
published = ''
# Join all the text in p tags, else set empty string
if len(description) > 0:
description = '\n'.join([d.get_text() for d in description])
else:
description = ''
# Get all the images links
images = [image.get('src', '') for image in images]
# Clean the post link
if post_url is not None:
post_url = post_url.get('href', '')
if len(post_url) > 0:
if ('/groups/' not in post_url) and ('/photos/' not in post_url) :
post_url = f'https://www.facebook.com{post_url}'
p_url = urlparse(post_url)
qs = parse_qs(p_url.query)
if 'story_fbid' in qs:
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}?story_fbid={qs["story_fbid"][0]}&id={qs["id"][0]}'
elif 'fbid' in qs :
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}?fbid={qs["fbid"][0]}&id={qs["id"][0]}'
elif('/photos/' in post_url) :
post_url = f'https://www.facebook.com{post_url}'
p_url = urlparse(post_url)
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}'
post_url = post_url.replace("m.facebook.com", "www.facebook.com")
else:
#post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}/permalink/{qs["id"][0]}/'
p_url = urlparse(post_url)
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}'
post_url = post_url.replace("m.facebook.com", "www.facebook.com")
else:
post_url = ''
# Clean the Like link
if like_url is not None:
like_url = like_url.get('href', '')
if len(like_url) > 0:
like_url = f'https://m.facebook.com{like_url}'
else:
like_url = ''
# Get list of external links in post description, if any inside
external_links = []
for link in _external_links:
link = link.get('href', '')
try:
a = link.index("u=") + 2
z = link.index("&h=")
link = unquote(link[a:z])
link = link.split("?fbclid=")[0]
external_links.append(link)
except ValueError as e:
continue
post = {'published': published, 'description': description, 'images': images,
'post_url': post_url, 'external_links': external_links, 'like_url': like_url}
posts.append(post)
self.posts.append(post)
return posts
def posts_to_csv(self, filename):
if filename[:-4] != '.csv':
filename = f'{filename}.csv'
df = pd.DataFrame(self.posts)
df.to_csv(filename)
def posts_to_excel(self, filename):
if filename[:-5] != '.xlsx':
filename = f'{filename}.xlsx'
df = pd.DataFrame(self.posts)
df.to_excel(filename)
def posts_to_json(self, filename):
if filename[:-5] != '.json':
filename = f'{filename}.json'
with open(filename, 'w') as f:
f.write('[')
for entry in self.posts:
json.dump(entry, f)
f.write(',\n')
f.write(']')
def search_posts(self, search_term):
today = datetime.date(datetime.now()) - timedelta(days=1)
YEAR = today.strftime("%Y")
MONTH = today.strftime("%m")
DAY = today.strftime("%d")
time_range = '{"rp_creation_time":"{\\"name\\":\\"creation_time\\",\\"args\\":\\"{\\\\\\"start_year\\\\\\":\\\\\\"'+YEAR+'\\\\\\",\\\\\\"start_month\\\\\\":\\\\\\"'+YEAR+'-'+MONTH+'\\\\\\",\\\\\\"end_year\\\\\\":\\\\\\"'+YEAR+'\\\\\\",\\\\\\"end_month\\\\\\":\\\\\\"'+YEAR+'-'+MONTH+'\\\\\\",\\\\\\"start_day\\\\\\":\\\\\\"'+YEAR+'-'+MONTH+'-'+DAY+'\\\\\\",\\\\\\"end_day\\\\\\":\\\\\\"'+YEAR+'-'+MONTH+'-'+DAY+'\\\\\\"}\\"}"}'
b64_time_range = b64encode(time_range.encode()).decode()
# Make a simple GET request
url_search = f"https://m.facebook.com/search/posts/?q={quote(search_term)}"\
f"&epa=FILTERS&filters={b64_time_range}"
soup = self.make_request(url_search)
if soup is None:
print(f"Couldn't load the searh: {search_term}")
return []
raw_data = soup.select("#BrowseResultsContainer")
posts = []
for item in raw_data: # Now, for every post...
username = item.select_one('h3 strong > a ').text
published = item.select_one('abbr') # Get the formatted datetime of published
description = item.select('p') # Get list of all p tag, they compose the description
images = item.select('a > img') # Get list of all images
_external_links = item.select('p a') # Get list of any link in the description, this are external links
post_url = item.find('a', text=self.post_url_text) # Get the url to point this post.
like_url = item.find('a', text='Like') # Get the Like url.
# Clean the publish date
if published is not None:
published = published.get_text()
else:
published = ''
# Join all the text in p tags, else set empty string
if len(description) > 0:
description = '\n'.join([d.get_text() for d in description])
else:
description = ''
# Get all the images links
images = [image.get('src', '') for image in images]
# Clean the post link
if post_url is not None:
post_url = post_url.get('href', '')
if len(post_url) > 0:
if ('/groups/' not in post_url) and ('/photos/' not in post_url) :
post_url = f'https://www.facebook.com{post_url}'
p_url = urlparse(post_url)
qs = parse_qs(p_url.query)
if 'story_fbid' in qs:
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}?story_fbid={qs["story_fbid"][0]}&id={qs["id"][0]}'
elif 'fbid' in qs :
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}?fbid={qs["fbid"][0]}&id={qs["id"][0]}'
elif('/photos/' in post_url) :
post_url = f'https://www.facebook.com{post_url}'
p_url = urlparse(post_url)
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}'
post_url = post_url.replace("m.facebook.com", "www.facebook.com")
else:
#post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}/permalink/{qs["id"][0]}/'
p_url = urlparse(post_url)
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}'
post_url = post_url.replace("m.facebook.com", "www.facebook.com")
else:
post_url = ''
# Clean the Like link
if like_url is not None:
like_url = like_url.get('href', '')
if len(like_url) > 0:
like_url = f'https://m.facebook.com{like_url}'
else:
like_url = ''
# Get list of external links in post description, if any inside
external_links = []
for link in _external_links:
link = link.get('href', '')
try:
a = link.index("u=") + 2
z = link.index("&h=")
link = unquote(link[a:z])
link = link.split("?fbclid=")[0]
external_links.append(link)
except ValueError as e:
continue
post = {'username': username,'published': published, 'description': description, 'images': images,
'post_url': post_url, 'external_links': external_links, 'like_url': like_url}
posts.append(post)
self.posts.append(post)
return posts
|
11,310 | 1bd04361fac2b37d8e8d0d6b9ff82878033dddf3 | #cmd /K "$(FULL_CURRENT_PATH)"
# -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
Author: Zachary Nowak and Ethan Saari
Date: 01/03/2019
Program Description: Analyze the given
data for sentiment and return value
candidate, date, tweet, likes, replies, sentiment
"""
from paralleldots import set_api_key, similarity, ner, taxonomy, sentiment, keywords, intent, emotion, abuse
import json
def Sentiment(tweet):
set_api_key("VIJL2MNSIraV6xzz2fNepEPdGX86Rxd7s0JvCqwqAEI")
score = sentiment(tweet)
data = json.dumps(score)
result = data.split('{')[2]
finalResult = result.split('}')[0]
negative = score['probabilities']['negative']
neutral = score['probabilities']['neutral']
positive = score['probabilities']['positive']
print(negative, neutral, positive)
return(negative, neutral, positive)
if __name__== '__main__':
import time
new_dict = {}
with open("Comstock Wexton tweets.txt", 'r') as fp:
collection_of_tweets = json.load(fp)
for date in collection_of_tweets.keys():
appendBoi = []
for tweet in collection_of_tweets[date]:
try:
time.sleep(3) #find value
negative, neutral, positive = Sentiment(tweet[1])
tweet.append(negative)
tweet.append(neutral)
tweet.append(positive)
appendBoi.append(tweet)
print(tweet)
except IndexError:
print("INDEXERROR")
pass
except TypeError:
print("TYPEERROR")
pass
new_dict[date] = appendBoi
print(new_dict)
with open("Stuff", 'w') as fp:
json.dump(new_dict, fp) |
11,311 | ee49cc7deb93273f6922ac80a6db485e4315eae1 | import os
from aiohttp import web
import discord
from linebot import LineBotApi, WebhookParser
from linebot.exceptions import InvalidSignatureError, LineBotApiError
from linebot.models import MessageEvent, TextMessage, StickerMessage, TextSendMessage
class BotVars:
"""bot variables"""
def __init__(self, var_names):
for var_info in var_names:
value = os.environ.get(var_info.name)
if value is None:
print("Specify {0} as environment variable.".format(var_info.name))
if var_info.required:
exit(1)
setattr(self, var_info.name, value)
@staticmethod
def load():
class VarInfo:
def __init__(self, name: str, required: bool):
self.name = name
self.required = required
_var_names = [
VarInfo('LINE_CHANNEL_SECRET', True),
VarInfo('LINE_CHANNEL_ACCESS_TOKEN', True),
VarInfo('DISCORD_BOT_TOKEN', True),
VarInfo('LINE_GROUP_ID', False),
VarInfo('DISCORD_CHANNEL_ID', False)]
return BotVars(_var_names)
bot_vars = BotVars.load()
client = discord.Client()
line_bot_api = LineBotApi(bot_vars.LINE_CHANNEL_ACCESS_TOKEN)
line_parser = WebhookParser(bot_vars.LINE_CHANNEL_SECRET)
app = web.Application()
routes = web.RouteTableDef()
@client.event
async def on_ready():
print("logged in as {0.user}".format(client))
runner = web.AppRunner(app)
await runner.setup()
port = os.environ.get('PORT')
site = web.TCPSite(runner, host='0.0.0.0', port=port)
print("web.TCPSite = {0}:{1}".format(site._host, site._port))
await site.start()
@client.event
async def on_message(message):
# ignore own message
if message.author == client.user:
return
# ignore bot message
if message.author.bot:
return
# EXTRA COMMANDS
if message.content == '/show-channel-id':
await message.channel.send(message.channel.id)
return # exit if proceed any command.
# check channel id
channel_id = bot_vars.DISCORD_CHANNEL_ID
if channel_id is None:
return
# ignore if channel id is not matched.
if message.channel.id != int(channel_id):
return
user_name = message.author.nick or message.author.name
content = '{0}: {1}'.format(user_name, message.content)
# send to LINE
group_id = bot_vars.LINE_GROUP_ID
if group_id is None:
return
line_bot_api.push_message(group_id, TextSendMessage(text=content))
async def _line_extra_command(event):
if event.message.text == '/show-group-id':
if event.source.type == 'group':
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.source.group_id))
else:
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text="ERROR: not from group"))
return True
return False
def _line_user_display_name_from_event(event):
profile = None
if event.source.type == 'group':
profile = line_bot_api.get_group_member_profile(event.source.group_id, event.source.user_id)
else:
profile = line_bot_api.get_profile(event.source.user_id)
if profile:
return profile.display_name
return "unknown"
async def _line_to_discord(event):
# ignore not MessageEvent
if not isinstance(event, MessageEvent):
return
# EXTRA COMMANDS
if isinstance(event.message, TextMessage):
if await _line_extra_command(event):
return # exit if proceed any command.
# get line user name
display_name = _line_user_display_name_from_event(event)
content = None
# message handlers
if isinstance(event.message, TextMessage):
# TextMessage
content = '{0}: {1}'.format(display_name, event.message.text)
elif isinstance(event.message, StickerMessage):
# StickerMessage
content = '{0}がスタンプを送信しました'.format(display_name)
else:
# other
content = '{0}がLINEで何かしました'.format(display_name)
# add group name if send from group
if event.source.type == 'group':
group_summary = line_bot_api.get_group_summary(event.source.group_id)
content += '@{0}'.format(group_summary.group_name)
# send to Discord
channel_id = bot_vars.DISCORD_CHANNEL_ID
if channel_id is None:
return
channel = client.get_channel(int(channel_id))
if channel is not None:
await channel.send(content)
@routes.post("/callback")
async def callback(request):
"""LINE Message API endpoint"""
signature = request.headers['X-Line-Signature']
body = await request.text()
try:
events = line_parser.parse(body, signature)
for event in events:
await _line_to_discord(event)
except LineBotApiError as e:
print("got exception from LINE Message API: {0}".format(e.message))
for m in e.error.details:
print(" {0} : {1}".format(m.property, m.message))
return web.Response(status=200)
except InvalidSignatureError:
return web.Response(status=400)
return web.Response()
app.add_routes(routes)
client.run(bot_vars.DISCORD_BOT_TOKEN)
|
11,312 | 3b2f78e9d5598d3e2f87de999b67fbd528dfa6a3 | from .models import *
from django.views.generic import ListView, DetailView
from django.shortcuts import render
from django.template.loader import render_to_string
from django.http import JsonResponse
from signals.models import Signals
class PLCListView(ListView):
model = ModuleInPLC
template_name = 'plc/index.html'
def modules_in_plc(request, plc_id):
rack_names = []
modules = {}
for module in ModuleInPLC.objects.filter(plc_id=plc_id):
if module.rack not in rack_names:
rack_names.append(module.rack)
for rack in rack_names:
rack_and_plc_id = ()
rack_and_plc_id = (rack, plc_id)
modules_name = []
modules_name.append(ModuleInPLC.objects.filter(plc_id=plc_id, rack=rack))
modules.update({rack_and_plc_id: modules_name})
context = {'modules_plc': modules, 'plc_id': plc_id}
return render(request, 'plc/modules_in_plc.html', context)
def signals_in_module(request, plc_id, rack_id, slot_id):
if request.is_ajax():
signals_list = []
if slot_id == 9999999:
module_list = []
for module in ModuleInPLC.objects.filter(plc_id=plc_id, rack=rack_id):
module_list.append(module)
else:
module_list = []
for module in ModuleInPLC.objects.filter(plc_id=plc_id, rack=rack_id, slot=slot_id):
module_list.append(module)
context = {'modules': module_list}
for module in module_list:
for signal in Signals.objects.filter(module_id=module.id):
signals_list.append(signal)
context = {'signals': signals_list}
result = render_to_string('plc/signals_in_module.html', context)
return JsonResponse({'result': result})
|
11,313 | 73e62cd16dc815b45bb05480b6f1fcd07ff0d638 | #Filename: exercise19
#Author: Kyle Post
#Date: May 14, 2017
#Purpose: To practice with functions
#and variables
#Define the function cheese & crackers with two values/parameters
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
#Set the values of the function to straight numbers
print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
#Create two variables and set them as the values for the function
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
#Set the values to individual math problems
print "We can even do matho inside:"
cheese_and_crackers(10 + 20, 5 + 6)
#Set values to a combination of math with variables.
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) |
11,314 | 0bb323a2c49d8bf84d87c5320464dce803033ca4 | ORIGIN_LIST = ['NSW', 'VIC', 'QLD', 'SA', 'WA', 'TAS', 'NT', 'ACT']
ORIGIN_CODE = [['1', '2'], ['3', '4'], ['5', '6'], ['7', '8'], ['9', '10'], ['11'], ['12'], ['13']]
PARENT_LIST = ['YES', 'NO', 'DONT_KNOW']
PARENT_CODE = [['1'], ['0', '2'], ['9']]
CH15TO24_LIST = ['YES', 'NO', 'DONT_KNOW']
CH15TO24_CODE = [['1'], ['0', '2'], ['9']]
GENDER_LIST = ['MALE', 'FEMALE']
GENDER_CODE = [['1'], ['2']]
MARITAL_LIST = ['SINGLE', 'COUPLE', 'REFUSED']
MARITAL_CODE = [['1'], ['2'], ['9']]
EMPLOYMENT_LIST = ['WORKING', 'NOT_WORKING', 'RETIRED', 'STUDYING', 'DONT_KNOW']
EMPLOYMENT_CODE = [['1', '2', '5'], ['3'], ['4'], ['6'], ['7', '8', '9']]
HOUSINC_LIST = ['LOW', 'MEDIUM', 'HIGH', 'DONT_KONW']
HOUSINC_CODE = [['1', '2', '3', '4', '5'], ['6', '7', '8', '9'], ['11', '12'], ['10', '13', '99', '25', '28', '29']]
LIFECYCLE_LIST = ['SINGLE', 'COUPLE_NO_KIDS', 'COUPLE_WITH_KIDS', 'DONT_KNOW']
LIFECYCLE_CODE = [['1', '2', '3', '8', '9'], ['4', '10', '11'], ['5', '6', '7'], ['0']]
AGEGROUP_LIST = ['15_29', '30_39', '40_49', '50_59', '60_69', '70_MORE']
AGEGROUP_CODE = [['1', '2', '3'], ['4', '5'], ['6', '7'], ['8', '9'], ['10', '11'], ['12', '13', '14']]
PARTYPE_LIST = ['UNACCOMPANIED', 'ADULT_COUPLE', 'FAMILY_GROUP', 'FREIEND_RELATIVES', 'BUSINESS_ASSOCIATES', 'SCHOOL_TOUR']
PARTYPE_CODE = [['1'], ['2'], ['3'], ['4'], ['5'], ['6']]
GROUPTYPE_LIST = ['SPORTING', 'SPECIAL_INTEREST', 'GUIDED_HOLIDAY', 'BUSINESS_OR_CONVENTION', 'OTHER', 'SCHOOL_EXCURSION']
GROUPTYPE_CODE = [['1'], ['2'], ['3'], ['4'], ['5', '8'], ['6']]
TRIP_PURPOSE_LIST = ['HOLIDAY', 'VISITING_FR', 'BUSINESS', 'EMPLOYMENT', 'EDUCATION', 'OTHER']
TRIP_PURPOSE_CODE = [['1'], ['2'], ['3', '4'], ['5'], ['6'], [str(x) for x in range(7, 99)]]
CUSTOMS_LIST = ['NSW', 'VIC', 'QLD', 'SA', 'TAS', 'NT', 'OTHER']
CUSTOMS_CODE = [['1'], ['2'], ['3', '7', '8', '11'], ['5'], ['9'], ['6'], ['4', '10', '98']]
|
11,315 | 6dc8cc7e7f45e58d708dce5a435152a474933fe6 |
def equation(x1,x2,y1,y2,x):
a = (y2 - y1) / (x2 - x1)
b = y1 - x1*a
y = a * x + b
return y
with open("valeurs_short_waves.txt","w") as file:
file.write("x1,x2,y1,y2,x,y\n")
while True:
x1 = float(input("x1 : "))
x2 = float(input("x2 : "))
y1 = float(input("y1 : "))
y2 = float(input("y2 : "))
x = float(input("x : "))
y = equation(x1,x2,y1,y2,x)
print("y = ",y)
print()
file.write(str(x1)+","+str(x2)+","+str(y1)+","+str(y2)+","+str(x)+","+str(y))
file.write("\n")
|
11,316 | 9f9bf4ab0fd0d529b58b3542c8691a57a7dabe4b | #!/usr/bin/python2.7
# -*- coding:utf-8 -*-
# Author: NetworkRanger
# Date: 2019/1/28 7:24 PM
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get('http://www.baidu.com')
assert u'百度' in driver.title
elem = driver.find_element_by_name('wd')
elem.clear()
elem.send_keys(u'网络爬虫')
time.sleep(3)
assert u'网络爬虫.' not in driver.page_source
driver.close()
|
11,317 | b8c99d9235bd42cc5889d3a2b7ff0b6789c9e76d | from knmi_database.models import NeerslagStation, Station, MeteoData
from django.contrib.gis.geos import Point
from dateutil import parser
from ftm.settings import DATA_ROOT
WGS84 = 4326
RDNEW = 28992
def importneerslag(fil):
with open(fil) as f:
f.readline()
line = f.readline()
while line != '':
words = line.split(',')
if len(words)> 4:
x = float(words[1])
y = float(words[2])
target = Point(x,y, srid=WGS84)
target.transform(RDNEW)
NeerslagStation.objects.get_or_create(
naam = words[4],
nummer = int(words[0]),
#target.transform(RDNEW)
#zipfilename = words[2],
location = target
)
line = f.readline()
################################################################################
#Meteodata uit de tekstbestandjes importeren
################################################################################
def importdata(fil):
with open(fil) as f:
f.readline()
line = f.readline()
while line !='':
words = [w.strip() for w in line.split(',')]
if len(words)> 7 and words[0]!='# STN'and words[8]!=''and words[1]!=''and words[3]!='':
nummer1 = int(words[0])
MeteoData.objects.get_or_create(
nummer = int(words[0]),
datum = parser.parse(words[1]),
rh = int(words[3]),
ev24 = int(words[8]),
station = NeerslagStation.objects.get(nummer=nummer1)
)
line = f.readline()
def importall():
NeerslagStation.objects.all().delete()
importneerslag(DATA_ROOT + 'KNMI_meteostations.csv')
def import_geg():
for i in [215, 235, 240, 242, 249, 251, 257, 260, 265, 267, 269, 270, 273, 275, 277, 278, 279, 280, 283, 286, 290, 310, 323, 319, 330, 340, 344, 348, 350, 356, 370, 375, 377, 380, 391, ]:
importdata(DATA_ROOT + 'METEO'+str(i)+'.TXT')
def importalldata(fil):
with open(fil) as f:
f.readline()
line = f.readline()
data = []
while line !='':
words = [w.strip() for w in line.split(',')]
if len(words)> 7 and words[0]!='# STN'and words[8]!=''and words[1]!=''and words[3]!='':
nummer1 = int(words[0])
item = MeteoData(
nummer = int(words[0]),
datum = parser.parse(words[1]),
rh = int(words[3]),
ev24 = int(words[8]),
station = NeerslagStation.objects.get(nummer=nummer1)
)
data.append(item)
line = f.readline()
MeteoData.objects.bulk_create(data)
def import_allgeg():
for i in [215, 235, 240, 242, 249, 251, 257, 260, 265, 267, 269, 270, 273, 275, 277, 278, 279, 280, 283, 286, 290, 310, 323, 319, 330, 340, 344, 348, 350, 356, 370, 375, 377, 380, 391, ]:
importalldata(DATA_ROOT + 'METEO'+str(i)+'.TXT')
goed = [215, 235, 240, 242, 249, 251, 257, 260, 265, 267, 269, 270, 273, 275, 277, 278, 279, 280, 283, 286, 290, 310, 323, 319, 330, 340, 344, 348, 350, 356, 370, 375, 377, 380, 391, ]
def opruimen():
for s in NeerslagStation.objects.all():
if not s.nummer in goed:
print s.nummer, s.naam
s.delete()
import_geg()
#import_allgeg() |
11,318 | ba7bc8aed164ac7029141645b0dbcf39eca0ff0b | '''
Created on Dec 7, 2016
# assume Both lists are sorted
@author: anand
'''
def findMedianSortedArrays(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
sumM = len(nums1)+len(nums2)
mergeAIndex = sumM /2
if sumM %2 ==0:
evenMerge = True
else:
evenMerge = False
i=0; n1Index = 0; n2Index = 0; m1 = None; m2 = None
while i<= mergeAIndex:
if evenMerge:
m1 = m2
if n1Index< len(nums1) and n2Index< len(nums2):
if ( nums1[n1Index] < nums2[n2Index]):
m2 = nums1[n1Index]
n1Index+=1
else:
m2 = nums2[n2Index]
n2Index+=1
elif n1Index< len(nums1):
m2 = nums1[n1Index]
n1Index+=1
else:
m2 = nums2[n2Index]
n2Index+=1
i+=1
if evenMerge: return float(m1+m2)/2
else: return float(m2)
print findMedianSortedArrays([], [1,2])
|
11,319 | 614b022f5b8e519ced516b3576820c0058197c00 | import sys
import socket
HOST = "10.0.0.1"
PORT = 9000
BUFSIZE = 1000
def main(argv):
#Create socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serversocket.bind((HOST, PORT))
#Keep server on
while True:
msg, addr = serversocket.recvfrom(BUFSIZE)
print("message received: {}".format(msg))
# If close, close server, used for debugging and quick resetting the server
if msg == "close":
serversocket.close()
sys.exit()
elif msg == 'L' or msg == 'l':
file = open("/proc/uptime", 'r')
serversocket.sendto(file.read().encode('UTF-8', 'strict'), addr)
elif msg == 'U' or msg == 'u':
file = open("/proc/loadavg", 'r')
serversocket.sendto(file.read().encode('UTF-8', 'strict'), addr)
else:
file = 'Error'
serversocket.sendto(file.encode('UTF-8', 'strict'), addr)
if __name__ == "__main__":
main(sys.argv[1:])
|
11,320 | 57a17f68c10c59fa5928754829d156e3956cfc9d | import codecs
import sys
write = sys.stdout.write
def gcd(x, y):
x = abs(x)
y = abs(y)
while y:
x, y = y, x % y
return x
with codecs.open("C-small-attempt0.in", "r", "utf- 8") as f:
temp = f.readlines()
num = int(temp[0].strip())
line = 1
for i in xrange(num):
t = temp[line].strip().split()
N = int(t[0])
L = int(t[1])
H = int(t[2])
line += 1
d = []
t2 = temp[line].strip().split()
t2 = [int(q) for q in t2]
t2.sort()
f = False
for w in xrange(L, H + 1):
c = 0
for n in t2:
if n % w != 0 and w % n != 0:
break
else:
c += 1
if c == len(t2):
print "Case #{0}: {1}".format(i + 1, w)
f = True
break
if not f:
print "Case #{0}: NO".format(i + 1)
# for n in t2:
# for m in t2:
# ret = gcd(n, m)
# if ret != 1 and ret not in d:
# d.append(ret)
line += 1
#print d
|
11,321 | 4ecb33e240817f2ef3b19a05965ce8b2559c9588 | from typing import *
import copy
class GenericObjectEditorHistory():
MAX_HISTORY_COUNT=10
def __init__(self):
self.m_History=[] #type:List
def add(self,obj:object):
obj=copy.deepcopy(obj)
if obj in self.m_History:
self.m_History.remove(obj)
self.m_History.insert(0,obj)
while len(self.m_History) > self.MAX_HISTORY_COUNT:
self.m_History.pop()
|
11,322 | 1258573364d7c70bc18f581a05741779ca955e10 | import socket
from cifrar import *
import asyncio
import datetime
Direcciones={"El_Ocho":("127.0.0.1",5005),"Profesor":("127.0.0.1",5004)}
def dispara_y_olvida(f):
def envuelto(*args, **kwargs):
return asyncio.get_event_loop().run_in_executor(None, f, *args, *kwargs)
return envuelto
def enviar_al_equipo(MENSAJE,DESTINO):
MENSAJE = encriptar(MENSAJE).encode()
# print(DESTINO)
# print("mensaje: %s" % MENSAJE)
enchufe = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
# print(type((UDP_IP, UDP_PORT)))
# print(MENSAJE)
enchufe.sendto(MENSAJE, DESTINO)
@dispara_y_olvida
def escucha(ESCUCHAR_DIRECCION):
if ESCUCHAR_DIRECCION == Direcciones['Profesor']:
desde='El Ocho'
else:
desde='Profesor'
enchufe = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
enchufe.bind(ESCUCHAR_DIRECCION)
while True:
datos, addr = enchufe.recvfrom(1024) # buffer size is 1024 bytes
datos=descifrar(datos.decode())
hora=datetime.datetime.now().strftime("%H:%M:%S")
print(f"\n[{hora}] Mensaje de {desde}: {datos}") |
11,323 | 43205adca4beb0f1cae9fc83d67b8049f879bf81 | # Generated by Django 3.1.5 on 2021-02-09 20:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cms', '0039_blog_short_link'),
]
operations = [
migrations.AlterField(
model_name='shorturls',
name='short',
field=models.CharField(max_length=20, unique=True),
),
]
|
11,324 | 87e7de70df4df496390e30eeed211881c198f371 | from rest_framework import viewsets, permissions
from kongdae.permissions import IsOwnerOrReadOnly
from reviews.models import Review, Comment
from reviews.serializers import ReviewSerializer, CommentSerializer
# Create your views here.
class ReviewsViewSet(viewsets.ModelViewSet):
queryset = Review.objects.all()
serializer_class = ReviewSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
class CommentsViewSet(viewsets.ModelViewSet):
serializer_class = CommentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
def get_queryset(self):
reviewId = self.kwargs['reviewId']
return Comment.objects.filter(review = reviewId) |
11,325 | 73fca57c04e3a776f2387151f9bb353bd9314f8e | import sys
import csv
from members.models import Team, Player, Pass, MembershipHercules
from django.contrib.auth.models import User
from guardian.shortcuts import assign
#### TODO:
## sportlink nieuw bestand nieuwste spelers importeren.
# reguliere expressie om data om te draaien veranderen.
## aanvoerders rechten geven om teamgenoten aan te passen.
# spelers recht geven eigen gegevens aanpassen.
# eerst de teams invoeren.
def ImportTeams():
t = Team.objects.all()
t.delete()
with open('teams.txt', 'rb') as csvfile:
data = csv.reader(csvfile, delimiter=',')
for row in data:
t1 = Team(number=str(row[0]), level = int(row[1]))
t1.save()
csvfile.close()
def ImportPass():
k = Pass.objects.all()
k.delete()
with open('knvbnr.txt', 'rb') as csvfile:
data = csv.reader(csvfile, delimiter=',')
for row in data:
p = Pass(knvbnr=str(row[0]))
p.save()
csvfile.close
def ImportHercules():
h = MembershipHercules.objects.all()
h.delete()
with open('herculesnr.txt', 'rU') as csvfile:
data = csv.reader(csvfile, delimiter=',')
for row in data:
p = MembershipHercules(herculesnr=str(row[0]))
p.save()
csvfile.close
# dan de spelers.
def ImportPlayers():
# de boel eerst leeggooien.
p = Player.objects.all()
p.delete()
u = User.objects.all().exclude(id=1)
u.delete()
with open('spelers.txt', 'rb') as csvfile:
data = csv.reader(csvfile, delimiter=',')
success = 0
failed = 0
p1 = Player.objects.all()
for row in data:
#print row
try:
pkpass = Pass.objects.get(knvbnr=str(row[3]))
#print str(row[15])
teampk = Team.objects.get(number=str(row[15]))
#print teampk
except:
print "pkpass for %s failed" % row
p1 = Player(
first_name=str(row[0]),
suffix=str(row[1]),
last_name=str(row[2]),
knvbnr=pkpass,
#herculesnr=herculespk,
#membersince=str(row[16]),
gender=str(row[5]),
#age=str(row[5]),
email=str(row[6]),
cellphone=str(row[7]),
regularphone=str(row[8]),
postalcode=str(row[9]),
street=str(row[10]),
streetnr=str(row[11]),
streetnrplus=str(row[12]),
city=str(row[13]),
role=str(row[14]),
team_member=teampk)
#enrolled=str(row[15]))
p1.save()
try:
herculespk = MembershipHercules.objects.get(herculesnr=str(row[4]))
#print teampk
p1.herculesnr=herculespk
p1.save()
except:
print "hercules nr for %s failed with nr %s" % (row, str(row[4]))
pass
success += 1
if str(row[0]) and str(row[2]):
account = User.objects.create(username=((str(row[0]) + str(row[2])).lower().replace(" ", "")))
p1.user = account
account.email= str(row[6])
p1.save()
account.save()
print success
csvfile.close()
## aanvoerders rechten geven om teamgenoten aan te passen.
# get all captains
# for every captain
# get all players that captain is captain off.
# assign edit right for captain over all his/her players.
def editRights():
captains = User.objects.filter(player__role='Aanvoerder')
for c in captains:
#print c
team = c.get_profile().team_member
teamplayers = Player.objects.filter(team_member=team)
#print teamplayers
for t in teamplayers:
assign('edit_player', c, t)
#for t in teamplayers:
# print c.has_perm('edit_player', t)
# def ImportPasverlopen():
# with open('pasverlopen.csv', 'U') as csvfile:
# data = csv.reader(csvfile, delimiter=';')
# success = 0
# failed = 0
# for row in data:
# try:
# p1 = Pass.objects.get(knvbnr=str(row[0]))
# p1.pasverloop = str(row[2])
# p1.passtatus = str(row[3])
# p1.save()
# success = success + 1
# except:
# failed = failed + 1
# print "%s pasverlopen succeeded, %s failed." % (success, failed)
# csvfile.close()
print "strating teams"
ImportTeams()
print "strating passes"
ImportPass()
print "strating herculesnr"
ImportHercules()
print "strating players"
ImportPlayers()
# print "Starting assigning edit rights to captains and teamplayers"
# editRights()
#ImportPasverlopen() |
11,326 | f44fef3f6742599c715f52ab4f2fe11f68c2359e | from flask import Flask, render_template, Response, request, flash, jsonify
import re
import pickle
import sklearn
import pandas as pd
# from script.parseImg import *
app = Flask(__name__)
def bin_count(x):
if x >= 48:
return 1
return 5
def word_count(x):
return x.apply(lambda x: bin_count(len(x.split()))).values.reshape(-1, 1).astype(int)
def replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
return text
def remove_truk(x):
return re.sub(r'(\w)\1+', r'\1', x)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
nama = request.form['nama']
ulasan = request.form['ulasan']
model_nama = pickle.load(open('model/model_nama.pkl', 'rb'))
model_rating = pickle.load(open('model/model_rating.pkl', 'rb'))
kamus_emot = pickle.load(open('kamus_emot.pkl', 'rb'))
# kamus_oov = pickle.load(open('kamus_oov.pkl', 'rb'))
ulasan = replace_all(ulasan, kamus_emot)
# ulasan = replace_all(ulasan, kamus_oov)
ulasan = remove_truk(ulasan)
gender = model_nama.predict([nama])
if gender[0] == 1.0 :
gender = 'male'
ulasan += ' MMAALLEE'
else :
gender = 'female'
ulasan += ' FFEEMMAALLEE'
rating = model_rating.predict(pd.Series([ulasan]))
return jsonify({'rating' : int(rating[0]), 'gender' : gender})
@app.route('/predict_gender', methods=['POST'])
def predict_gender():
nama = request.form['nama']
model_nama = pickle.load(open('model/model_nama.pkl', 'rb'))
gender = model_nama.predict([nama])
if gender[0] == 1.0 :
gender = 'male'
else :
gender = 'female'
return jsonify({'gender' : gender})
if __name__ == "__main__":
app.run(host='0.0.0.0',port=8111)
|
11,327 | 120a34bdd12d6dd40eef1a966a011110739348b3 | import matplotlib.pyplot as plt
import pickle
from os.path import abspath
# loads a saved model from <filename>
def load_model(filename):
if not filename.endswith('.pkl'):
filename += '.pkl'
filename = abspath(filename)
with open(filename, 'rb') as f:
return pickle.load(f)
# plot errors produced by neural network
def plot_errors(errors, lrs, title, n):
plt.figure(figsize=(10, 10))
plt.title(title)
styles = ['-', '--', '-.', ':']
for i, lr in enumerate(lrs):
plt.plot(range(len(errors[lr][:n])), errors[lr][:n], label=f'lr = {lr}', linestyle=styles[i % 4])
plt.ylabel('Error')
plt.xlabel('Epochs')
plt.legend(bbox_to_anchor=(1, 1))
plt.show() |
11,328 | d643542e572255cd4c8d18742dcffa48c2df5eda | import src.helper as helper
import src.conf as conf
import numpy as np
def obs_to_matrix_baseline(obs, control_ship_id, player_id, own_ship_actions, size):
''' Baseline input function. Takes into consideration the following separate 9 images of size 21x21:
halite, ships, shipyards, enemy ships, enemy shipyards, enemy ship cargos, enemy shipyards,
current ship cargo, player halite and timeframe. '''
own_ships = obs['players'][player_id][2]
control_ship_data = own_ships[control_ship_id]
# Board images
halite_list = [x/500 for x in obs['halite']]
own_ships_list = [0] * (size*size)
own_ships_unknown_list = [0] * (size*size)
shipyard_list = [0] * (size*size)
enemy_list = [0] * (size*size)
enemy_small_list = [0] * (size*size)
# Single digit filters
timeframe = [obs['step']/conf.get('episodeSteps')] * (size*size)
ship_cargo = [own_ships[control_ship_id][1]/1000] * (size*size)
for idx, player in enumerate(obs['players']):
ships = player[2]
shipyards = player[1]
for ship_id, ship_data in ships.items():
if ship_id != control_ship_id:
if idx != player_id:
if ship_data[1] > control_ship_data[1]:
ship_poses = [helper.get_next_ship_pos(ship_data[0], i) for i in range(5)]
for ship_pos in ship_poses:
enemy_small_list[ship_pos] = 1
else:
ship_poses = [helper.get_next_ship_pos(ship_data[0], i) for i in range(5)]
for ship_pos in ship_poses:
enemy_list[ship_pos] = 0.5
elif idx == player_id:
if ship_id in own_ship_actions:
ship_pos = helper.get_next_ship_pos(ship_data[0], own_ship_actions[ship_id])
own_ships_list[ship_pos] = 1
else:
own_ships_unknown_list[ship_data[0]] = 1
for shipyard_id, shipyard_pos in shipyards.items():
if idx == player_id:
shipyard_list[shipyard_pos] = 1
else:
enemy_list[shipyard_pos] = 1
ship_pos = own_ships[control_ship_id][0]
result = []
for parts in zip(helper.center_cell(halite_list, ship_pos), helper.center_cell(own_ships_list, ship_pos), helper.center_cell(own_ships_unknown_list, ship_pos), helper.center_cell(shipyard_list, ship_pos), helper.center_cell(enemy_list, ship_pos), helper.center_cell(enemy_small_list, ship_pos), timeframe, ship_cargo):
result.append(list(parts))
image = np.reshape(result, [1, size, size, 8])
# data = np.array([ship_cargo, timeframe])
# data = np.reshape(data, [1, 2])
mid = int(size/2)
shipyards = helper.center_cell(shipyard_list, ship_pos)
nearby_shipyards = np.reshape(shipyards, [1, size, size, 1])[:, mid-7:mid+8, mid-7:mid+8, :]
has_nearby_shipyards = nearby_shipyards.sum() != 0
return image, has_nearby_shipyards
def obs_to_matrix_six(obs, control_ship_id, player_id, own_ship_actions, size):
''' Uses only 4 images and 2 single color filters '''
result = []
own_ships = obs['players'][player_id][2]
control_ship_data = own_ships[control_ship_id]
# Multi value maps
halite_list_and_enemies = [x/500 for x in obs['halite']]
shipyard_list = [0] * (size*size)
own_ships_list = [0] * (size*size)
enemy_list = [0] * (size*size)
# Single value filters
timeframe = [obs['step']/conf.get('episodeSteps')] * (size*size)
ship_cargo = [own_ships[control_ship_id][1]/1000] * (size*size)
for idx, player in enumerate(obs['players']):
ships = player[2]
shipyards = player[1]
for ship_id, ship_data in ships.items():
if ship_id != control_ship_id:
if idx != player_id:
if ship_data[1] > control_ship_data[1]:
# Setting halite and big enemy cargos
halite_list_and_enemies[ship_data[0]] += ship_data[1]/500
else:
ship_poses = [helper.get_next_ship_pos(ship_data[0], i) for i in range(5)]
for ship_pos in ship_poses:
# Setting dangers
enemy_list[ship_pos] = 0.5
elif idx == player_id and ship_id in own_ship_actions:
# Setting friendly ships
ship_pos = helper.get_next_ship_pos(ship_data[0], own_ship_actions[ship_id])
own_ships_list[ship_pos] = 1
for shipyard_id, shipyard_pos in shipyards.items():
if idx == player_id:
# Setting friendly shipyards
shipyard_list[shipyard_pos] = 1
else:
# Setting enemy shipyards
enemy_list[shipyard_pos] = 1
ship_pos = own_ships[control_ship_id][0]
for parts in zip(helper.center_cell(halite_list_and_enemies, ship_pos), helper.center_cell(shipyard_list, ship_pos), helper.center_cell(own_ships_list, ship_pos), helper.center_cell(enemy_list, ship_pos), timeframe, ship_cargo):
result.append(list(parts))
image = np.reshape(result, [1, size, size, 6])
mid = int(size/2)
shipyards = helper.center_cell(shipyard_list, ship_pos)
nearby_shipyards = np.reshape(shipyards, [1, size, size, 1])[:, mid-7:mid+8, mid-7:mid+8, :]
has_nearby_shipyards = nearby_shipyards.sum() != 0
return image, has_nearby_shipyards
def obs_to_matrix_sparse(obs, control_ship_id, player_id, own_ship_actions, size):
''' Baseline input function. Takes into consideration the following separate 9 images of size 21x21:
halite, ships, shipyards, enemy ships, enemy shipyards, enemy ship cargos, enemy shipyards,
current ship cargo, player halite and timeframe. '''
own_ships = obs['players'][player_id][2]
control_ship_data = own_ships[control_ship_id]
enemy_id = 1 if player_id == 0 else 0
# Board images
halite_list = [x/500 for x in obs['halite']]
own_ships_list = [0] * (size*size)
own_ships_unknown_list = [0] * (size*size)
shipyard_list = [0] * (size*size)
enemy_list = [0] * (size*size)
enemy_small_list = [0] * (size*size)
# Single digit filters
timeframe = [obs['step']/conf.get('episodeSteps')] * (size*size)
ship_cargo = [own_ships[control_ship_id][1]/1000] * (size*size)
halite = [obs['players'][player_id][0] / (obs['players'][player_id][0] + obs['players'][enemy_id][0] + 1)] * (size*size)
for idx, player in enumerate(obs['players']):
ships = player[2]
shipyards = player[1]
for ship_id, ship_data in ships.items():
if ship_id != control_ship_id:
if idx != player_id:
if ship_data[1] > control_ship_data[1]:
ship_poses = [helper.get_next_ship_pos(ship_data[0], i) for i in range(5)]
for ship_pos in ship_poses:
enemy_small_list[ship_pos] = 1
else:
ship_poses = [helper.get_next_ship_pos(ship_data[0], i) for i in range(5)]
for ship_pos in ship_poses:
enemy_list[ship_pos] = 0.5
elif idx == player_id:
if ship_id in own_ship_actions:
ship_pos = helper.get_next_ship_pos(ship_data[0], own_ship_actions[ship_id])
own_ships_list[ship_pos] = 1
else:
own_ships_unknown_list[ship_data[0]] = 1
for shipyard_id, shipyard_pos in shipyards.items():
if idx == player_id:
shipyard_list[shipyard_pos] = 1
else:
enemy_list[shipyard_pos] = 1
ship_pos = own_ships[control_ship_id][0]
result = []
for parts in zip(helper.center_cell(halite_list, ship_pos), helper.center_cell(own_ships_list, ship_pos), helper.center_cell(own_ships_unknown_list, ship_pos), helper.center_cell(shipyard_list, ship_pos), helper.center_cell(enemy_list, ship_pos), helper.center_cell(enemy_small_list, ship_pos), timeframe, ship_cargo, halite):
result.append(list(parts))
image = np.reshape(result, [1, size, size, 9])
# data = np.array([ship_cargo, timeframe])
# data = np.reshape(data, [1, 2])
mid = int(size/2)
shipyards = helper.center_cell(shipyard_list, ship_pos)
nearby_shipyards = np.reshape(shipyards, [1, size, size, 1])[:, mid-7:mid+8, mid-7:mid+8, :]
has_nearby_shipyards = nearby_shipyards.sum() != 0
return image, has_nearby_shipyards
def obs_to_matrix_nearsight(obs, control_ship_id, player_id, own_ship_actions, size):
''' Baseline input function. Takes into consideration the following separate 9 images of size 21x21:
halite, ships, shipyards, enemy ships, enemy shipyards, enemy ship cargos, enemy shipyards,
current ship cargo, player halite and timeframe. '''
own_ships = obs['players'][player_id][2]
control_ship_data = own_ships[control_ship_id]
# Board images
halite_list = [x/500 for x in obs['halite']]
own_ships_list = [0] * (size*size)
own_ships_unknown_list = [0] * (size*size)
shipyard_list = [0] * (size*size)
enemy_list = [0] * (size*size)
enemy_small_list = [0] * (size*size)
# Single digit filters
timeframe = [obs['step']/conf.get('episodeSteps')] * (size*size)
ship_cargo = [own_ships[control_ship_id][1]/1000] * (size*size)
for idx, player in enumerate(obs['players']):
ships = player[2]
shipyards = player[1]
for ship_id, ship_data in ships.items():
if ship_id != control_ship_id:
if idx != player_id:
if ship_data[1] > control_ship_data[1]:
ship_poses = [helper.get_next_ship_pos(ship_data[0], i) for i in range(5)]
for ship_pos in ship_poses:
enemy_small_list[ship_pos] = 1
else:
ship_poses = [helper.get_next_ship_pos(ship_data[0], i) for i in range(5)]
for ship_pos in ship_poses:
enemy_list[ship_pos] = 0.5
elif idx == player_id:
if ship_id in own_ship_actions:
ship_pos = helper.get_next_ship_pos(ship_data[0], own_ship_actions[ship_id])
own_ships_list[ship_pos] = 1
else:
own_ships_unknown_list[ship_data[0]] = 1
for shipyard_id, shipyard_pos in shipyards.items():
if idx == player_id:
shipyard_list[shipyard_pos] = 1
else:
enemy_list[shipyard_pos] = 1
ship_pos = own_ships[control_ship_id][0]
# lists = [halite_list, own_ships_list, own_ships_unknown_list, shipyard_list, enemy_list, enemy_small_list, timeframe, ship_cargo]
# zippable = [helper.center_cell(a, ship_pos) for a in lists]
result = []
for parts in zip(helper.center_cell(halite_list, ship_pos), helper.center_cell(own_ships_list, ship_pos), helper.center_cell(own_ships_unknown_list, ship_pos), helper.center_cell(shipyard_list, ship_pos), helper.center_cell(enemy_list, ship_pos), helper.center_cell(enemy_small_list, ship_pos), timeframe, ship_cargo):
result.append(list(parts))
# for parts in zip(zippable):
# result.append(list(parts))
image = np.reshape(result, [1, size, size, 8])
# data = np.array([ship_cargo, timeframe])
# data = np.reshape(data, [1, 2])
mid = int(size/2)
image = image[:, mid-5:mid+6, mid-5:mid+6, :]
shipyards = helper.center_cell(shipyard_list, ship_pos)
nearby_shipyards = np.reshape(shipyards, [1, size, size, 1])[:, mid-7:mid+8, mid-7:mid+8, :]
has_nearby_shipyards = nearby_shipyards.sum() != 0
return image, has_nearby_shipyards
def obs_to_matrix_three(obs, control_ship_id, player_id, own_ship_actions, size):
''' Uses only 1 image and 2 single color filters '''
result = []
own_ships = obs['players'][player_id][2]
control_ship_data = own_ships[control_ship_id]
# Multi value maps
full_list = [x/500 for x in obs['halite']]
# Single value filters
timeframe = [obs['step']/conf.get('episodeSteps')] * (size*size)
ship_cargo = [own_ships[control_ship_id][1]/1000] * (size*size)
for idx, player in enumerate(obs['players']):
ships = player[2]
shipyards = player[1]
for ship_id, ship_data in ships.items():
if ship_id != control_ship_id:
if idx != player_id:
if ship_data[1] > control_ship_data[1]:
# Setting halite and big enemy cargos
full_list[ship_data[0]] += ship_data[1]/500
else:
ship_poses = [helper.get_next_ship_pos(ship_data[0], i) for i in range(5)]
for ship_pos in ship_poses:
# Setting dangers
full_list[ship_pos] = -1
elif idx == player_id and ship_id in own_ship_actions:
# Setting friendly ships
ship_pos = helper.get_next_ship_pos(ship_data[0], own_ship_actions[ship_id])
full_list[ship_pos] = -1
for shipyard_id, shipyard_pos in shipyards.items():
# Setting enemy shipyards
full_list[shipyard_pos] = -1
ship_pos = own_ships[control_ship_id][0]
for parts in zip(helper.center_cell(full_list, ship_pos)):
result.append(list(parts))
image = np.reshape(result, [1, size, size, 3])
mid = int(size/2)
shipyards = helper.center_cell(shipyard_list, ship_pos)
nearby_shipyards = np.reshape(shipyards, [1, size, size, 1])[:, mid-7:mid+8, mid-7:mid+8, :]
has_nearby_shipyards = nearby_shipyards.sum() != 0
return image, has_nearby_shipyards |
11,329 | 2b8ec5601039d52e98628d2b624b40f7fbd89d1f | class filters:
def __init__(self):
self.LPF_cut_off_freq = 200
self.LPF_numtaps = 40
def lpf(self):
print "TESTING" |
11,330 | e27bf02865cf0c19058b6d76fe68a4b85a688b55 | # Generated by Django 3.0.1 on 2021-01-19 16:59
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('COVID_19_Tracker', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='global',
name='date',
field=models.DateTimeField(default=django.utils.timezone.now),
),
]
|
11,331 | f7d22ca7ec2f03212aa9ca30dd22ad7303cb5885 | #!/usr/bin/env python
import json
import falcon
from email.utils import formatdate
# resource endpoints
class JSONResource(object):
def on_get(self, request, response):
response.set_header('Date', formatdate(timeval=None, localtime=False, usegmt=True))
json_data = {'message': "Hello, world!"}
response.body = json.dumps(json_data)
class PlaintextResource(object):
def on_get(self, request, response):
response.set_header('Date', formatdate(timeval=None, localtime=False, usegmt=True))
response.set_header('Content-Type', 'text/plain')
response.body = b'Hello, world!'
# setup
app = falcon.API()
app.add_route("/json", JSONResource())
app.add_route("/plaintext", PlaintextResource())
# entry point for debugging
if __name__ == "__main__":
from wsgiref import simple_server
httpd = simple_server.make_server('localhost', 8080, app)
httpd.serve_forever()
|
11,332 | 03ecdbf4be101446e71195431c274a1bda9a1d44 | # encoding=utf-8
import matplotlib.pyplot as plt
'''
将标注OURS1改成OURS2,将OURS3改成OURS1
'''
def read_wrq(pro_name,E,K,D):
#name*epsilon*k*delta
means=[]
for p in range(len(pro_name)):
means.append([])
for e in range(len(E)):
means[p].append([])
for k in range(len(K)):
means[p][e].append([])
for d in range(len(D)):
fileName=pro_name[p]+'/'+pro_name[p]+'/output/'+'k(' + str(K[k]) + \
')_e(' + str(E[e]) +')_delta('+str(D[d])+ ')wrq' + '.txt'
f=open(fileName,'r')
infos=f.readlines()
f.close()
means[p][e][k].append(float(infos[0]))
return means
def get_info(means,p,e,K,d):
re=[]
for k in range(len(K)):
re.append(means[p][e][k][d])
return re
if __name__ == '__main__':
pro_name=['INFOCOM15','INFOCOM17','OURS1','OURS3']
K = [10, 20, 30, 40, 50, 60, 70, 80]
E = [0.1, 0.5, 1.0, 1.5, 2.0]
D = [0.4,0.6,0.8,1.0]
#means ( name*epsilon*k*delta )
means=read_wrq(pro_name,E,K,D)
for e in range(len(E)):
#初始化画布
p_long=9
p_width=9
fig=plt.figure(figsize=(p_long,p_width))
#pl.xlim(-1, 11) # 限定横轴的范围
#pl.ylim(-1, 110) # 限定纵轴的范围
ax=[]
for d in range(len(D)):
#x轴
names = K
x = range(len(names))
#2行2列第(d+1)个子图
new=fig.add_subplot(220+d+1)
infocom15_means=get_info(means,0,e,K,d)
infocom17_means=get_info(means,1,e,K,d)
ours1_means=get_info(means,2,e,K,d)
ours3_means=get_info(means,3,e,K,d)
new.plot(x, infocom15_means,linewidth=1.8,linestyle='-.',marker='p',label='INFOCOM15')
new.plot(x, infocom17_means,linewidth=1.8,linestyle='-.',marker='*',label='INFOCOM17')
new.plot(x, ours3_means,linewidth=1.8,linestyle='-.',marker='x',label='OURS1')
new.plot(x, ours1_means,linewidth=1.8,linestyle='-.',marker='s',label='OURS2')
ax.append(new)
plt.plot(fontsize=15)
plt.legend(loc='best') # 让图例生效
#plt.legend(loc=2, bbox_to_anchor=(1.05,1.0),borderaxespad = 0)
plt.xticks(x, names, rotation=45,fontsize=15)
plt.yticks(fontsize=15)
plt.margins(0)
plt.subplots_adjust(bottom=0.15)
plt.xlabel('(Numbers of Groups)',fontsize=15)
plt.ylabel('wrq',fontsize=15)
plt.title('delta='+str(D[d]))
plt.tight_layout()
#网格
plt.grid(alpha=1,linestyle='-.',c='gray')
#plt.subplots_adjust(right=0.72)
#plt.show()
plt.savefig('output/wrq/'+'_e('+str(E[e])+')'+'.png')
|
11,333 | 6daee70c7abf135423229f5ede652404139216ea | """Here we write all the doc string examples. This way we can be sure that they
still work.
A method is written for each python file of dpf-core.
If a failure occurs, the change must be done here and in the corresponding
docstring."""
import doctest
import os
import pathlib
import pytest
@pytest.mark.skipif(os.name == "posix", reason="examples are created for windows")
def test_doctest_allfiles():
directory = r"../ansys/dpf/core"
actual_path = pathlib.Path(__file__).parent.absolute()
# actual_path = os.getcwd()
print(actual_path)
for filename in os.listdir(os.path.join(actual_path, directory)):
if filename.endswith(".py"):
path = os.path.join(directory, filename)
print(path)
doctest.testfile(path, verbose=True, raise_on_error=True)
else:
continue
@pytest.mark.skipif(os.name == "posix", reason="examples are created for windows")
def test_doctest_allexamples():
directory = r"../examples"
actual_path = pathlib.Path(__file__).parent.absolute()
handled_files = []
for root, subdirectories, files in os.walk(os.path.join(actual_path, directory)):
for subdirectory in subdirectories:
subdir = os.path.join(root, subdirectory)
print(subdir)
for filename in os.listdir(subdir):
if filename.endswith(".py"):
path = os.path.join(subdir, filename)
if ".ipynb_checkpoints" in path:
continue
print(path)
handled_files.append(path)
exec(
open(path, mode="r", encoding="utf8").read(),
globals(),
globals(),
)
else:
continue
print(handled_files)
if __name__ == "__main__":
test_doctest_allfiles()
|
11,334 | 94a7faf18bb252a3497b1044f280e06f23ddb0b2 | #MenuTitle: Batch Create Intermediate Layer
# -*- coding: utf-8 -*-
__doc__="""
Batch create intermediate layers for selected glyphs, based on selected master layer. Useful for creating "clamped" interpolation for small glyphs(E.g. fraction figures). (Single Axis Only)
"""
# from GlyphsApp import *
import vanilla
font = Glyphs.font
class CopyMasterLayer(object):
def __init__( self):
self.w = vanilla.FloatingWindow((460, 120), "Batch Create Intermediate Layer", minSize=(460, 120), maxSize=(460, 120))
# Master
self.w.textReplace = vanilla.TextBox((15, 12+2, 65, 14), "Master:", sizeStyle='small')
self.w.masterName = vanilla.PopUpButton((120, 12, -120, 17), self.GetMasterNames(), sizeStyle='small')
# New name
self.w.textName = vanilla.TextBox((15, 40+2, 150, 14), "Axis coordinates:", sizeStyle='small')
self.w.newIntermediateValue = vanilla.EditText((120, 40, -120, 19), "100", sizeStyle='small', callback=self.SavePrefs)
# Delete all extra layers option
self.w.deleteExtraLayers = vanilla.CheckBox((120, 68, -120, 19), "Delete all other layers", value=False, sizeStyle='small', callback=self.SavePrefs )
# Callback button
self.w.createButton = vanilla.Button((-80, 68, -15, 17), "Create", sizeStyle='small', callback=self.ButtonCallback )
self.w.setDefaultButton( self.w.createButton )
# Use defaults if no saved preferences
if not self.LoadPrefs( ):
print ("Note: Could not load preferences. Will resort to defaults.")
self.w.open()
self.w.makeKey()
def ButtonCallback( self, sender ):
# All selected glyphs
selectedGlyphs = [ l.parent for l in Glyphs.font.selectedLayers ]
# Variables
newIntermediateValue = self.w.newIntermediateValue.get()
masterName = str( self.w.masterName.getItems()[self.w.masterName.get()] )
deleteLayers = self.w.deleteExtraLayers.get()
# Delete extra leyers
if deleteLayers:
self.DeleteExtraLayers()
print ("Extra layers deleted")
# Create new layers
for glyph in selectedGlyphs:
for layer in glyph.layers:
if layer.name == masterName:
print (layer.name)
newLayer = layer.copy()
axis = font.axes[0]
newLayer.attributes['coordinates'] = {axis.axisId: newIntermediateValue}
glyph.layers.append(newLayer)
# Update preview to show changes in interpolated instances
font.disableUpdateInterface()
font.enableUpdateInterface()
return True
def GetMasterNames( self ):
myMasterList = set()
allMasters = font.masters
for master in allMasters:
myMasterList.add( master.name )
return sorted( list( myMasterList ))
def DeleteExtraLayers( self ):
Layers = Glyphs.font.selectedLayers
for Layer in Layers:
Glyph = Layer.parent
NewLayers = {}
for m in Glyphs.font.masters:
NewLayers[m.id] = Glyph.layers[m.id]
Glyph.setLayers_(NewLayers)
def SavePrefs( self, sender ):
Glyphs.defaults["com.tderkert.CopyMasterLayer.newIntermediateValue"] = self.w.newIntermediateValue.get()
Glyphs.defaults["com.tderkert.CopyMasterLayer.deleteExtraLayers"] = self.w.deleteExtraLayers.get()
return True
def LoadPrefs( self ):
try:
self.w.newIntermediateValue.set( Glyphs.defaults["com.tderkert.CopyMasterLayer.newIntermediateValue"] )
self.w.deleteExtraLayers.set( Glyphs.defaults["com.tderkert.CopyMasterLayer.deleteExtraLayers"] )
return True
except:
return False
CopyMasterLayer()
|
11,335 | 4e2b760f1a6d8ea94d89bae4ee7b56970c4f3df8 | import codecs, re
from sections import Section, SectionFactory
class WebOfScienceSectionFactory(SectionFactory):
def __init__(self, text_file, fact_file, sect_file, fact_type, language, verbose=False):
SectionFactory.__init__(self, text_file, fact_file, sect_file, fact_type, language)
self.sections = []
self.text = codecs.open(self.text_file, encoding='utf-8').read()
def make_sections(self):
re_STRUCTURE = re.compile("STRUCTURE TYPE=\"ABSTRACT\" START=(\d+) END=(\d+)")
for line in open(self.fact_file):
result = re_STRUCTURE.match(line)
if result is not None:
start, end = result.groups()
section = Section()
section.start_index = int(start)
section.end_index = int(end)
section.text = self.text[section.start_index:section.end_index]
section.types.append('ABSTRACT')
self.sections.append(section)
|
11,336 | 77110bc63dfec8b62d0bcf3c9454867004982218 | # Generated by Django 2.2 on 2020-07-26 19:15
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('manage', '0006_auto_20200726_1409'),
]
operations = [
migrations.AlterField(
model_name='appointment',
name='date',
field=models.DateField(default=datetime.datetime(2020, 7, 26, 19, 15, 6, 184678, tzinfo=utc)),
),
migrations.AlterField(
model_name='appointment',
name='time',
field=models.TimeField(default=datetime.datetime(2020, 7, 26, 19, 15, 6, 184678, tzinfo=utc)),
),
migrations.AlterField(
model_name='status',
name='status',
field=models.CharField(default='Pending', max_length=120, null=True),
),
]
|
11,337 | 41e7c15ab9ed4ab93130d597d8712d02c28ce250 | from .view import as_json
|
11,338 | 42fcb753359348cd9143861bc507c4719c81dd23 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Handlertypes for filerotation."""
class HandlerType(object):
"""Static types to represent a file handler."""
ROTATING_FILE_HANDLER = -2
TIME_ROTATING_FILE_HANDLER = -1
|
11,339 | e3d0e9f9e482e1a88d5cf2ae49475ba456ceba3f | #coding: utf-8
import requests
def Frases():
get = requests.get("http://allugofrases.herokuapp.com/frases")
return get.json()
def fraseAleatoria():
get = requests.get("http://allugofrases.herokuapp.com/frases/random")
return get.json()
def fraseID(id):
get = requests.get("http://allugofrases.herokuapp.com/frases/find/" + id)
return get.json()
def procurarFrase(frase):
data = {"frase": frase}
get = requests.post(url="http://allugofrases.herokuapp.com/frases/search", json=data, headers={'Content-Type': "application/json", 'Accept': "application/json"})
return get.json()
def frasesPorAutor(autor):
data = {"autor": autor}
get = requests.post(url="http://allugofrases.herokuapp.com/frases/author", json=data, headers={'Content-Type': "application/json", 'Accept': "application/json"})
return get.json()
def frasesPorLivro(livro):
data = {"livro": livro}
get = requests.post(url="http://allugofrases.herokuapp.com/frases/book", json=data, headers={'Content-Type': "application/json", 'Accept': "application/json"})
return get.json()
if (__name__ == "__main__"):
print("Verifique as funções de exemplo do código :)") |
11,340 | 5c6eed8db6dbb401f260d44926f1175ed9670b4a | import logging
import queue
import sys
import threading
from server import Endpoint, PingMsg, CrawlServer
from secp256k1 import PrivateKey
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
#read threadcount from args
threadcount = 1
if len(sys.argv) == 2:
threadcount = int(sys.argv[1])
#generate private key
k = PrivateKey(None)
with open("priv_key", 'w') as f:
f.write(k.serialize())
#init queue and fill it with bootstraps
q = queue.Queue()
qset = queue.Queue()
q.put(Endpoint(u'52.16.188.185', 30303, 30303, bytes.fromhex("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c"))) #geth
q.put(Endpoint(u'13.93.211.84', 30303, 30303, bytes.fromhex("3f1d12044546b76342d59d4a05532c14b85aa669704bfe1f864fe079415aa2c02d743e03218e57a33fb94523adb54032871a6c51b2cc5514cb7c7e35b3ed0a99")))
q.put(Endpoint(u'191.235.84.50', 30303, 30303, bytes.fromhex("78de8a0916848093c73790ead81d1928bec737d565119932b98c6b100d944b7a95e94f847f689fc723399d2e31129d182f7ef3863f2b4c820abbf3ab2722344d")))
q.put(Endpoint(u'13.75.154.138', 30303, 30303, bytes.fromhex("158f8aab45f6d19c6cbf4a089c2670541a8da11978a2f90dbf6a502a4a3bab80d288afdbeb7ec0ef6d92de563767f3b1ea9e8e334ca711e9f8e2df5a0385e8e6")))
q.put(Endpoint(u'174.112.32.157', 30303, 30303, bytes.fromhex("e809c4a2fec7daed400e5e28564e23693b23b2cc5a019b612505631bbe7b9ccf709c1796d2a3d29ef2b045f210caf51e3c4f5b6d3587d43ad5d6397526fa6179"))) #parity
q.put(Endpoint(u'144.76.62.101', 30303, 30303, bytes.fromhex("2676755dd8477ad3beea32b4e5a144fa10444b70dfa3e05effb0fdfa75683ebd4f75709e1f8126cb5317c5a35cae823d503744e790a3a038ae5dd60f51ee9101"))) #pyethapp
#fill queue set also
for point in list(q.queue):
qset.put(point)
out = queue.Queue()
#start threads for discovery
threads = []
running = threading.Event()
running.set()
server = CrawlServer(Endpoint(u'127.0.0.1', 30303, 30303, k.serialize()))
for x in range(threadcount):
t = threading.Thread(target = server.discover, args = (q, qset, out, x, running))
t.start()
threads.append(t)
with open("crawl_result.txt", 'w') as f:
try:
while True:
message = out.get()
f.write(message + "\n")
except KeyboardInterrupt:
logger.info("Shutting down writer")
running.clear()
logging.info("Shutting down Discovery")
for thread in threads:
thread.join()
|
11,341 | b4fb6d5c64e07741394631dfca7563c1a867001e |
from .OutlierNormalizer import OutlierNormalizer
from .StandardNormalizer import StandardNormalizer
from .WinsorizationNormalizer import WinsorizationNormalizer
from weakref import ReferenceType
from numpy import ndarray
class MatrixNormalizerAdapter:
def __init__(self, matrix_reference: ReferenceType):
self.matrix_reference = matrix_reference
def standard(self, positive_required=False, verbose=False):
normalizer = StandardNormalizer(positive_required)
self.matrix_reference().array = normalizer.normalize(self.matrix_reference(), verbose=verbose)
def winsorization(self, positive_required=False, limits=0.05, verbose=False):
normalizer = WinsorizationNormalizer(positive_required, limits=limits)
self.matrix_reference().array = normalizer.normalize(self.matrix_reference(), verbose=verbose)
def outlier(self, positive_required=False, verbose=False):
normalizer = OutlierNormalizer(positive_required)
self.matrix_reference().array = normalizer.normalize(self.matrix_reference(), verbose=verbose)
|
11,342 | 7e6c3470a9f30dc48c7bae7d1d7041bddf49ac2e | import numpy as np
from numpy import pi
import pyqg
def test_the_model(rtol=0.1):
""" Test the sqg model similatly to BT model. Numbers come from
a simulations in Cesar's 2014 MacPro with Anaconda 64-bit """
# the model object
year = 1.
m = pyqg.SQGModel(L=2.*pi,nx=128, tmax = 10*year,
beta = 0., H = 1., rek = 0., rd = None, dt = 1.e-3,
taveint=year, twrite=1000, ntd=1)
# a vortex merger IC with unit energy
p = np.exp(-(2.*(m.x-1.75*pi/2))**2.-(2.*(m.y-pi))**2) +\
np.exp(-(2.*(m.x-2.25*pi/2))**2.-(2.*(m.y-pi))**2)
ph = m.fft(p[np.newaxis,:,:])
KEaux = m.spec_var( m.filtr*m.wv*ph )/2.
ph = ( ph/np.sqrt(KEaux) )
qih = m.wv*ph
qi = m.ifft(qih)
m.set_q(qi)
m.run()
qnorm = (m.q**2).sum()
mp = m.ifft(m.ph)
pnorm = (mp**2).sum()
ke = m._calc_ke()
print 'time: %g' % m.t
assert m.t == 10.000999999999896
np.testing.assert_allclose(qnorm, 31517.690603406099, rtol)
np.testing.assert_allclose(pnorm, 5398.52096250875, rtol)
np.testing.assert_allclose(ke, 0.96184358530902392, rtol)
if __name__ == "__main__":
test_the_model()
|
11,343 | ea6ce75aaf92e6a89611d7845a7436a21f87bd2d | from django import forms
from .models import Article,Message
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = [
"pic",
"year",
"km",
"price",
"make",
"model",
"transmission",
"fuelType",
"bodyType",
"engine",
"variant",
"content",
"isSold",
"highlighted",
]
class MessageForm(forms.ModelForm):
class Meta:
model = Message
fields = [
"nameSurname",
"replyOption",
"phone",
"mail",
"subject",
]
class MessageAForm(forms.ModelForm):
class Meta:
model = Message
fields = [
"isDone",
"nameSurname",
"replyOption",
"phone",
"mail",
"subject",
"notes",
] |
11,344 | 8a751c129dbad10aa8c59b06603f6d1cf1da0b39 | #!/usr/bin/python3
import sys
sys.path.insert(0, '/home/user/aqua/')
from server import app as application
|
11,345 | 47e9a8d6adf0fb1c72297bbc9f2ff980e3483a12 | code_dict = {}
accumulator = 0
line_nr = 0
do_substitute = True
saved_code_dict = 0
saved_accumulator = 0
saved_line_nr = 0
def load_code():
code_dict = {}
line_nr = 0
with open('input.txt', 'r') as file:
lines = file.readlines()
for line in lines:
line = line.strip('\n')
code_dict[line_nr] = line, False
line_nr += 1
return code_dict
def save_state():
global line_nr
global code_dict
global accumulator
global saved_code_dict
global saved_accumulator
global saved_line_nr
#print('SAVED: ', line_nr, accumulator)
saved_line_nr = line_nr
saved_accumulator = accumulator
saved_code_dict = dict(code_dict)
def reset_state():
global line_nr
global code_dict
global accumulator
global saved_code_dict
global saved_accumulator
global saved_line_nr
global do_substitute
do_substitute = True
line_nr = saved_line_nr
accumulator = saved_accumulator
code_dict = dict(saved_code_dict)
#print('RESET TO:', line_nr, accumulator)
def substitute(code):
global do_substitute
if not substitute:
return code
op, arg = code.split()
if op in {'nop', 'jmp'}:
if do_substitute:
save_state()
next_line_nr = int(arg) + line_nr
if op == 'nop':
code = 'jmp ' + arg
elif op == 'jmp':
code = 'nop ' + arg
do_substitute = False
return code
def execute(code):
op, arg = code.split()
if op == 'nop':
return 0, 1
if op == 'jmp':
return 0, int(arg)
if op == 'acc':
return int(arg), 1
raise Exception('Unknown code: ' + code)
# === MAIN ===
code_dict = load_code()
END_LINE_NR = len(code_dict)
line_nr = 0
fixed = False
while not fixed:
code, was_executed = code_dict[line_nr]
code = substitute(code)
if was_executed:
reset_state()
code, _ = code_dict[line_nr]
acc_inc, line_inc = execute(code)
code_dict[line_nr] = code, True
accumulator += acc_inc
line_nr += line_inc
if line_nr == END_LINE_NR:
fixed = True
print('### FIXED ###')
print(accumulator)
|
11,346 | f026e21cb47794c45d7458446d6360dbe0dc0113 | import requests
import time
from traffic_data_utils import get_duration_from_request, get_payload
URL = 'http://api.sl.se/api2/TravelplannerV2/trip.json'
def execute_request(latitude, longitude):
response = None
payload = get_payload(latitude, longitude)
try:
response = requests.get(URL, params=payload, timeout=10.0)
except requests.exceptions.Timeout as err:
print '### Timeout exception received:', err
raise
except requests.exceptions.ConnectionError as err:
print '### Connection error:', err
raise
except Exception as err:
print '### Other exception:', err
raise
return response
def handle_request(latitude, longitude):
response = None
print 'Requesting traffic data for coordinate:', latitude, longitude
try:
response = execute_request(latitude, longitude)
except Exception as err:
print 'Exception:', err
time.sleep(1.2)
return response
|
11,347 | f2b4e12aed7cd39ba7c75671b9c01735024a9763 | words = input().split()
searched_word = input()
palindromes = [el for el in words if el == el[::-1]]
print(palindromes)
print(f"Found palindrome {palindromes.count(searched_word)} times") |
11,348 | b971c0aa958ce2c5adb76dc88275c22022e3913a | import pygame
my_name = "Harrison Kinsley"
pygame.init()
my_font = pygame.font.SysFont("arial", 64)
name_surface = my_font.render(my_name, True, (0, 0, 0), (255, 255, 255))
pygame.image.save(name_surface, "name.png")
|
11,349 | 87605b235c11ea02b30b5787f2ec5ffa590397b9 | from random import randrange
from character import Character
class Medic(Character):
def __init__(self, level = 1, health = 10, power = 2):
self.health = health
self.power = power
self.level = level
def attack(self, hero):
heal = randrange(5)
if heal == 4:
hero.health -= self.power
self.health += self.power
print(f"{self} does {self.power} damage to you and healed for 2!")
elif heal != 4:
hero.health -= self.power
print(f"{self} does {self.power} damage to the you.")
def __str__(self):
return "Medic" |
11,350 | 7ab893cc106f78573d03faf3c6c14e7579e3ab2e | #fisierele de citire pentru fiecare automat
fisier_citire_lnfa = open('lnfa.in')
fisier_citire_nfa = open('nfa.in')
fisier_citire_dfa = open('dfa.in')
#functie de citire pentru LNFA
def Citire_LNFA(fisier):
nr_stari = int(fisier.readline())
lista_stari=[stare for stare in range(nr_stari)] #de la 0 la nr_stari-1
nr_litere_alfabet= int(fisier.readline())
alfabet = []
for litera in fisier.readline().split():
alfabet += litera
initiala = int(fisier.readline())
nr_stari_finale = int(fisier.readline())
finale = []
for stare in fisier.readline().split():
finale += [int(stare)]
nr_tranzitii = int(fisier.readline())
tranzitii = {}
for i in range(nr_tranzitii):
x = fisier.readline().split()
if (int(x[0]),x[1]) not in tranzitii.keys():
tranzitii[(int(x[0]),x[1])] = {int(x[2])}
else:
tranzitii[(int(x[0]), x[1])].add(int(x[2]))
fisier.close()
return nr_stari,lista_stari,nr_litere_alfabet,alfabet,initiala,nr_stari_finale,finale,nr_tranzitii,tranzitii
#Functie de citire pentru NFA
def Citire_NFA(fisier):
nr_stari = int(fisier.readline())
lista_stari=[stare for stare in range(nr_stari)] #de la 0 la nr_stari-1
nr_litere_alfabet= int(fisier.readline())
alfabet = []
for litera in fisier.readline().split():
alfabet += litera
initiala = int(fisier.readline())
nr_stari_finale = int(fisier.readline())
finale = []
for stare in fisier.readline().split():
finale += [int(stare)]
nr_tranzitii = int(fisier.readline())
tranzitii = {}
for i in range(nr_tranzitii):
x = fisier.readline().split()
if (int(x[0]),x[1]) not in tranzitii.keys():
tranzitii[(int(x[0]),x[1])] = {int(x[2])}
else:
tranzitii[(int(x[0]), x[1])].add(int(x[2]))
fisier.close()
return nr_stari,lista_stari,nr_litere_alfabet,alfabet,initiala,nr_stari_finale,finale,nr_tranzitii,tranzitii
#Functie de citire pentru DFA
def Citire_DFA(fisier):
nr_stari = int(fisier.readline())
lista_stari=[stare for stare in range(nr_stari)] #de la 0 la nr_stari-1
nr_litere_alfabet = int(fisier.readline())
alfabet = []
for litera in fisier.readline().split():
alfabet += litera
initiala = int(fisier.readline())
nr_stari_finale = int(fisier.readline())
finale = []
for stare in fisier.readline().split():
finale += [int(stare)]
nr_tranzitii = int(fisier.readline())
tranzitii = {}
for i in range(nr_tranzitii):
x = fisier.readline().split()
tranzitii[(int(x[0]),x[1])] = int(x[2])
fisier.close()
return nr_stari,lista_stari,nr_litere_alfabet,alfabet,initiala,nr_stari_finale,finale,nr_tranzitii, tranzitii
#PASUL 1 IN CALCULAREA LNFA TO NFA-CALCULAREA LAMBDA INCHIDERII
#Functie care calculeaza lambda inchiderea
#Orice stare face parte din propria sa λ-inchidere. Practic putem considera
#ca pentru orice stare exista o λ-tranzitie implicita catre ea insasi
#λ-inchiderea unei multimi de stari este egala cu reuniunea λ-inchiderii fiecarei
#stari din multime.
def lambda_inchidere(inceput,stare,inchideri,tranzitii):
if inceput not in inchideri.keys():
inchideri[inceput]={inceput}
if (stare,'$') in tranzitii.keys():
for x in tranzitii[(stare,'$')]:
inchideri[inceput].add(x)
lambda_inchidere(inceput,x,inchideri,tranzitii)
#apel recursiv, un fel de backtracking, verific in ce stari pot ajunge din fiecare stare
#PASUL 2 IN TRANSFORMAREA LNFA TO NFA-Calcularea functiei de tranzitie δ
#Cu ajutorul λ-inchiderii, putem calcula functia de tranzitie a NFA-ului pe care dorim sa il
#construim.
def calcularea_tranzitie_lambda_star(stare,litera,inchideri,transformare_in_nfa,tranzitii):
for x in inchideri[stare]:
if (x, litera) in tranzitii.keys():
for i in tranzitii[(x, litera)]:
if (stare, litera) in transformare_in_nfa.keys():
transformare_in_nfa[(stare, litera)].update(inchideri[i])
else:
transformare_in_nfa[(stare, litera)] = inchideri[i].copy()
#functie care modifica pe a cu b intr un dictionar, imi va fi folositoare pentru cand calculez starile finale
def modifica(dict,a,b): #il inlocuieste pe y cu x in dictionar
for valori in dict.values():
if b in valori:
valori.discard(b)
if a not in valori:
valori.add(a)
#functia care transforma un LNFA in NFA utilizand cei 4 pasi
def transforma_LNFA_in_NFA(tranzitii,nr_stari,lista_stari,initiala,finale, alfabet):
inchideri={}
for stare_curenta in lista_stari:
lambda_inchidere(stare_curenta,stare_curenta,inchideri,tranzitii)
#PASUL 1 IN TRANSOFRMAREA LNFA TO NFA-am pus in lambda_inchidere stare_curenta de 2 ori deoarece stare_curenta este
# starea din care plecam, initiala
transformare_in_nfa={}
for stare_curenta in lista_stari:
for litera in alfabet:
calcularea_tranzitie_lambda_star(stare_curenta,litera,inchideri,transformare_in_nfa,tranzitii)
#PASUL 2 IN TRANSFORMAREA LNFA TO NFA-CALCULAREA TRAZITIEI LAMBDA STAR
noile_stari_finale=finale.copy()
for stare_curenta in lista_stari:
for final in finale:
if stare_curenta not in noile_stari_finale and final in inchideri[stare_curenta]:
noile_stari_finale+=[stare_curenta]
# PASUL 3 IN TRANSFORMEA LNFA TO NFA-CALCULAREA STARILOR INITIALE SI FINALE
# Starea initiala ramane aceasi cu cea a automatlui initial, in cazul nostru 0.
# Starile finale vor fi toate starile care contin o stare finala din automatul initial
stare_curenta=0
while stare_curenta< nr_stari:
stare_urmatoare=stare_curenta+1
while stare_urmatoare < nr_stari:
gasit=1
# daca starile au tranzitii diferite, nu sunt identice
for litera in alfabet:
if (lista_stari[stare_curenta],litera) in transformare_in_nfa.keys() and (lista_stari[stare_urmatoare],litera) in transformare_in_nfa.keys() and transformare_in_nfa[(lista_stari[stare_curenta],litera)]!=transformare_in_nfa[(lista_stari[stare_urmatoare],litera)]:
gasit=0
# daca o stare e finala si alta nu, atunci nu s identice
if (lista_stari[stare_urmatoare] not in noile_stari_finale and lista_stari[stare_curenta] in noile_stari_finale) or (lista_stari[stare_urmatoare] in noile_stari_finale and lista_stari[stare_curenta] not in noile_stari_finale):
gasit=0
if gasit==1:
#se inlocuieste starea_curenta cu starea_urmatoare din noul dictionar
modifica(transformare_in_nfa,lista_stari[stare_curenta], lista_stari[stare_urmatoare])
if lista_stari[stare_urmatoare] in noile_stari_finale:
# se sterge din lista de stari finale, fiind redundanta
noile_stari_finale.remove(lista_stari[stare_urmatoare])
#sterg legaturile dintre starea stearsa si celelalte stari
for litera in alfabet:
if (lista_stari[stare_urmatoare],litera) in transformare_in_nfa.keys():
transformare_in_nfa.pop((lista_stari[stare_urmatoare],litera))
#sterg starea
lista_stari.pop(stare_urmatoare)
stare_urmatoare-=1
nr_stari-=1
stare_urmatoare+=1
stare_curenta+=1
# PASUL 4 IN TRANSFORMAREA LNFA TO NFA
return transformare_in_nfa, nr_stari, lista_stari,initiala, noile_stari_finale, alfabet
#AM TRANSFORMAT LNFA IN NFA, urmand apoi sa transform NFA in DFA
def TRANSFORMA_NFA_IN_DFA(tranzitii,nr_stari,lista_stari,initiala,finale,alfabet):
#PASUL 1 in NFA to DFA-ELIMIN NEDETERMINISMUL
#Pornim cu o coada in care adaugam doar starea initiala q0. Apoi pentru fiecare stare din coada q
# si fiecare caracter din alfabet α facem urmatorul calcul: daca δ(q,α) = qx0,...qxk,k ≥ 0 atunci:
# creem starea qx0...xk(poate fi si o stare care nu este compusa) Daca noua stare fromata qx0...xk nu a mai fost vizitata,
# atunci o adaugam in coada. Tranzitia acestei stari cu un caracter α va fi reuniunea starilor
# accesibile cu caracterul α din toate starile componente. Repetam acest calcul pana cand coada devine vida.
coada=[{initiala}]
noua_lista_stari=[{initiala}]
transformare_in_dfa={}
while coada != []: #Cat timp coada nu e vida
for litera in alfabet: #iau fiecare litera din alfabet
multime = set() #creez o multime
for element in coada[0]:
if(element,litera)in tranzitii.keys():
multime.update(tranzitii[element,litera])
if multime!=set():
if multime not in noua_lista_stari:
noua_lista_stari+=[multime]
coada+=[multime]
transformare_in_dfa[(frozenset(coada[0]),litera)]=multime
coada.pop(0)
#PASUL 2 IN TRANSFORMAREA NFA IN DFA-CALCULAREA STARILOR INITIALE SI FINALE
#Starea initiala ramane aceasi cu cea a automatlui initial, in cazul nostru 0.
#Starile finale vor fi toate starile care au in componenta o stare finala din automatul initial
noile_stari_finale=[] #aici stochez starile finale din noul automat
for stare_curenta in noua_lista_stari: #parcurg fiecare stare din noua lista de stari
for stare_finala in finale:
if stare_finala in stare_curenta and stare_curenta not in noile_stari_finale:
noile_stari_finale+=[stare_curenta]
#PASUL 3 in TRANSFORMAREA NFA IN DFA-REDENUMIREA STARILOR
#Putem sa redenumim starile fara a afecta functionalitatea.
initiala=0
for index in range(len(noua_lista_stari)):
for cheie in transformare_in_dfa.keys():
if noua_lista_stari[index]==transformare_in_dfa[cheie]:
transformare_in_dfa[cheie]=index
#^
#|
#REDENUMESC FIECARE STARE DIN DICTIONAR
for litera in alfabet:
if (frozenset(noua_lista_stari[index]),litera) in transformare_in_dfa.keys():
transformare_in_dfa[(index,litera)]=transformare_in_dfa[(frozenset(noua_lista_stari[index]),litera)]
del transformare_in_dfa[(frozenset(noua_lista_stari[index]),litera)]
if noua_lista_stari[index] in noile_stari_finale:
noile_stari_finale.remove(noua_lista_stari[index])
noile_stari_finale.append(index)
#AFISEZ PENTRU FIECARE STARE VECHE NOUA EI DENUMIRE
print("DENUMIREA VECHE IN NFA: ", noua_lista_stari[index]," / DENUMIRE NOUA IN DFA: ",index)
noua_lista_stari[index]=index
nr_stari=len(noua_lista_stari)
return transformare_in_dfa, nr_stari, noua_lista_stari, initiala, noile_stari_finale, alfabet #returnez noul automat
#FUNCTIE CARE STERGE O ANUMITA STARE DINTR-UN AUTOMAT DFA SI IMPLICIT SI LEGATURILE CU ALTA STARE
def STERGE_STARE(stare_curenta,tranzitii,lista_stari,alfabet):
for litera in alfabet:
if (stare_curenta,litera)in tranzitii.keys():
del tranzitii[stare_curenta,litera]
for stare in lista_stari:
if (tuple(stare), litera) in tranzitii.keys() and tranzitii[tuple(stare),litera]==stare_curenta:
del tranzitii[tuple(stare),litera]
lista_stari.remove(set(stare_curenta))
#FUNCTIE CARE PARCURGE AUTOMATUL IN TOATE STARILE ACCESIBILE
def PARCURGERE_TOTALA(stare_curenta, alfabet,tranzitii,vizitat):
#vectorul vizitat care verifica daca am trecut prin starea curenta sau nu
if stare_curenta not in vizitat:
vizitat.append(stare_curenta)
for litera in alfabet:
if (stare_curenta, litera) in tranzitii.keys():
PARCURGERE_TOTALA(tranzitii[(stare_curenta, litera)], alfabet, tranzitii, vizitat)
#FUNCTIA ESTE ASEMANATOARE UNUI DFS, AVAND APEL RECURSIV, DINTR O STARE MA DUC IN TOATE STARILE ACCESBILIE
def PARCURGERE(stare_curenta, noile_stari_finale, alfabet, tranzitii, vizitat):
#TRECE PRIN TOATE STARILE ACCESIBILE PANA AJUNGE IN STARE FINALA SAU PANA CAND NU MAI SUNT STARI NEVIZITATE
global ok #variabila de tip bool
if stare_curenta not in vizitat:
vizitat.append(stare_curenta)
if set(stare_curenta) in noile_stari_finale: #daca starea e finala, gasit e TRUE, deci ne oprim
ok = True
else: #altfel parcurgem automatul pana ajungem intr o stare finala sau toate sunt vizitate
for litera in alfabet:
if (stare_curenta, litera) in tranzitii.keys():
PARCURGERE(tranzitii[(stare_curenta, litera)], noile_stari_finale, alfabet, tranzitii, vizitat)
#FUNCTIA ESTE ASEMANATOARE UNUI DFS, AVAND APEL RECURSIV, DINTR-O STARE MA DUC IN TOATE STARILE ACCESIBILE
def TRANSFORMA_DFA_IN_DFAMIN(tranzitii,nr_stari,lista_stari,initiala,finale,alfabet):
#PASUL 1 IN TRANSFORMAREA DFA IN DFA MINIMIZAT:
#Doua stari sunt echivalente daca si numai daca pentru orice cuvant am alege,
# plecand din cele doua stari, ajungem in doua stari fie finale sau nefinale.
#Construim lista de adiacenta si o marcam pe toata cu TRUE
dictionar_stari_echivalente={}
for stare in range(nr_stari): #parcurg starile
for copie_stare in range(stare+1):
dictionar_stari_echivalente[stare,copie_stare]=True
#Marcam cu FALSE toate perechile (q,r), unde q stare finala si r stare nefinala.
for relatii in dictionar_stari_echivalente.keys():
if (relatii[0] in finale and relatii[1] not in finale) or (relatii[0] not in finale and relatii[1] in finale):
dictionar_stari_echivalente[relatii]=False
gasit=1
while(gasit==1):
copie_dictionar_stari_echivalente=dictionar_stari_echivalente.copy()
for litera in alfabet:
for relatii in dictionar_stari_echivalente.keys():
if dictionar_stari_echivalente[max(tranzitii[relatii[0], litera], tranzitii[relatii[1], litera]), min(tranzitii[relatii[0], litera], tranzitii[relatii[1], litera])]==False:
dictionar_stari_echivalente[relatii]=False
if copie_dictionar_stari_echivalente==dictionar_stari_echivalente:
gasit=0
#PASUL 2 IN TRANSFORMAREA DFA IN DFA-MINIMIZAT-Gruparea starilor echivalente si calcularea functiei de tranzitie
#Grupam starile echivalente rezultate din matricea de echivalenta intr-o unica stare.
#Tranzitiile vor fi aceleasi cu ale automatului initial dar tinand cont de aceasta grupare
stari_DFA_MIN=[] #NOILE STARI DIN DFA-MIN
for stare in range(nr_stari): #PARCURG STARILE
gasit=0
for copie_stare in range(stare):
if dictionar_stari_echivalente[stare,copie_stare]==True:
for grupare in stari_DFA_MIN:
if copie_stare in grupare:
grupare.add(stare)
break
gasit=1
break
if gasit==0:
stari_DFA_MIN += [{stare}]
transforma_DFA_in_DFAMIN={}
for grupare in stari_DFA_MIN:
calup=tuple(grupare)
for stare in calup:
for litera in alfabet:
if (stare,litera) in tranzitii.keys():
for stare_curenta in stari_DFA_MIN:
if tranzitii[stare,litera] in stare_curenta:
transforma_DFA_in_DFAMIN[calup,litera]=tuple(stare_curenta)
break
#PASUL 3 IN TRANSFORMAREA DFA IN DFA MINIMIZAT:Calcularea starilor finale si initiale.
#Starea initiala devine starea ce contine starea initiala a automatului original
#Starile finale sunt toate starile compuse din stari finale
#STABILESC STAREA INITIALA
noua_stare_initiala={}
for stare in stari_DFA_MIN:
if initiala in stare:
noua_stare_initiala = stare
break
#ADAUG STARILE FINALE IN VECTOR
noile_stari_finale=[]
for stare in finale:
for cop_stare in stari_DFA_MIN:
if stare in cop_stare and cop_stare not in noile_stari_finale:
noile_stari_finale.append(cop_stare)
break
#PASUL 4 IN TRANSFORMAREA DFA IN DFA MINIMIZAT:ELIMINAREA STARILOR DEAD-END
#O stare s este dead-end daca nu exista niciun drum de la aceasta stare la o stare finala.
for stare in stari_DFA_MIN:
stare=tuple(stare)
global ok
ok = False
vizitat=[]
PARCURGERE(stare,noile_stari_finale,alfabet,transforma_DFA_in_DFAMIN,vizitat)
#parcurg automatul
if ok==False: #inseamna ca nu este stare finala si o sterge, pentru ca este DEAD-END
STERGE_STARE(stare,transforma_DFA_in_DFAMIN,stari_DFA_MIN,alfabet)
#PASUL 5 IN TRANSFORMAREA DFA IN DFA MINIMIZAT:ELIMINAREA STARILOR NEACCESIBILE
#O stare S este neaccesibila daca nu exista niciun drum de la starea initala S0 pana la Sk.
vizitat=[]
PARCURGERE_TOTALA(tuple(noua_stare_initiala),alfabet,transforma_DFA_in_DFAMIN,vizitat)
for stare in stari_DFA_MIN:
if tuple(stare) not in vizitat: #daca starea nu a fost vizitata inseamna ca e inaccesibila deci o sterge
sterge(tuple(stare),transforma_DFA_in_DFAMIN,stari_DFA_MIN,alfabet)
#PASUL 6 IN TRANSFORMEA DFA IN DFA-MINIMIZAT-REDENUMIREA STARILOR
#CA SI LA TRANSFORMAREA DIN NFA IN DFA, FIECARE STARE VA LUA INDEXUL DIN STARI_DFA_MIN
initiala=0 #STAREA INITIALA ESTE 0
for stare in stari_DFA_MIN: #parcurg starile
if stare==noua_stare_initiala:
val_aux=stari_DFA_MIN[0] #interschimb valorile
stari_DFA_MIN[0]=stare
stare=val_aux
#REDEFINESC STARILE DIN LISTA MEA
#ALGORITMUL ESTE ACELASI CA LA NFA TO DFA
for index in range(len(stari_DFA_MIN)):
for cheie in transforma_DFA_in_DFAMIN.keys():
if tuple(stari_DFA_MIN[index])==transforma_DFA_in_DFAMIN[cheie]:
transforma_DFA_in_DFAMIN[cheie]=index
for litera in alfabet:
if (tuple(stari_DFA_MIN[index]),litera) in transforma_DFA_in_DFAMIN.keys():
transforma_DFA_in_DFAMIN[(index,litera)]=transforma_DFA_in_DFAMIN[(tuple(stari_DFA_MIN[index]),litera)]
del transforma_DFA_in_DFAMIN[(tuple(stari_DFA_MIN[index]),litera)]
#Redefinesc starile finale
if stari_DFA_MIN[index] in noile_stari_finale:
noile_stari_finale.remove(stari_DFA_MIN[index])
noile_stari_finale.append(index)
#AFISEZ STARILE REDEFINITE
print("DENUMIREA VECHE DIN DFA ESTE: ",stari_DFA_MIN," / DENUMIREA NOUA DIN DFA-MINIMAZAT ESTE: ", index)
stari_DFA_MIN[index]=index
nr_stari=len(stari_DFA_MIN)
return transforma_DFA_in_DFAMIN, nr_stari, stari_DFA_MIN, initiala, noile_stari_finale, alfabet
#returnez automatul
print('TRANSFORMA LNFA IN NFA: ')
nr_stari, lista_stari, nr_litere_alfabet ,alfabet,initiala, nr_stari_finale, finale,nr_tranzitii, tranzitii=Citire_LNFA(fisier_citire_lnfa)
LAMBDA_NFA_IN_NFA, nr_stari, lista_stari, initiala, finale, alfabet=transforma_LNFA_in_NFA(tranzitii,nr_stari,lista_stari,initiala,finale,alfabet)
print('NUMAR DE STARI: ',nr_stari)
print('LISTA DE STARI: ',lista_stari)
print('ALFABET: ',alfabet)
print('STARE INITIALA: ',initiala)
print('STARI FINALE: ',finale)
print('TRANZITII: ', LAMBDA_NFA_IN_NFA)
print('\n')
print('TRANSFORMA NFA IN DFA: ')
nr_stari, lista_stari, nr_litere_alfabet, alfabet, initiala, nr_stari_finale, finale, nr_tranzitii, tranzitii=Citire_NFA(fisier_citire_nfa)
NFA_IN_DFA, nr_stari, lista_stari, initiala, finale, alfabet=TRANSFORMA_NFA_IN_DFA(tranzitii, nr_stari, lista_stari, initiala, finale,alfabet)
print('NUMAR DE STARI: ',nr_stari)
print('LISTA DE STARI: ',lista_stari)
print('ALFABET: ',alfabet)
print('STARE INITIALA: ',initiala)
print('STARI FINALE: ',finale)
print('TRANZITII: ', NFA_IN_DFA)
print('\n')
print('TRANSFORMA DFA IN DFA MINIMIZAT: ')
nr_stari, lista_stari, nr_litere_alfabet, alfabet, initiala, nr_stari_finale, finale, nr_tranzitii, tranzitii=Citire_DFA(fisier_citire_dfa)
DFA_IN_DFAMIN, nr_stari, lista_stari, initiala, finale, alfabet=TRANSFORMA_DFA_IN_DFAMIN(tranzitii, nr_stari, lista_stari, initiala, finale, alfabet)
print('NUMAR DE STARI: ',nr_stari)
print('LISTA DE STARI: ',lista_stari)
print('ALFABET: ',alfabet)
print('STARE INITIALA: ',initiala)
print('STARI FINALE: ',finale)
print('TRANZITII: ', DFA_IN_DFAMIN)
print('\n') |
11,351 | 7afccbfd0046b51c60029f3831b32a02b8711653 | from ._State import *
|
11,352 | ba2ae3b290e38cffe18b075d01f95ae1501eaef9 | from chatbot import Chatbot
import json
import random
agents = ["IR", "ML", "RB", "HM"]
for agent in random.shuffle(agents) :
### Information Retrieval System
if agent == 'IR':
print("Say something")
from chatbot import IR_Bot
ir = IR_Bot('ir')
ir.loadDictJson('irDictionary.json')
userResponse = input()
while 'quit' not in userResponse:
print(ir.reply(userResponse))
userResponse = input()
# Machine Learning Bot
if agent == 'ML':
print("Say something:")
from chatbot import ML_Bot
ml = ML_Bot("ML")
ml.trainJSON('convAI.json')
userResponse = input()
while 'quit' not in userResponse:
print(ml.reply(userResponse))
userResponse = input()
# Hybrid Chatbot: Robby
if agent == 'RB':
from chatterbot import ChatBot
from chatbot import Robby
robby = Robby("Rob")
robby.mind.loadMindPalace('mindPalace.json')
robby.initiateTopic()
robby.markov.loadCorpus('convAI.json')
from markovChain import MarkovChain
m = MarkovChain()
m.loadCorpus('convAI.json')
robby.loadNeuralNetwork('intents.json')
print("Say something:")
res = input()
while res != 'bye':
print(robby.neuralNetResponse(res))
res = input()
### Human Chat
if agent == 'HM':
print("Say something")
userResponse = input()
while 'quit' not in userResponse:
print(getInput())
userResponse = input()
|
11,353 | 2959229d17ee622bfddbd0a2be4de689f500c0ce | import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm
w = np.array([-0.03314521 -0.99945055])
z = np.linspace(-3,2,500)
points = np.column_stack([z,z])
projection_points = points*w
normal_point_1 = norm.pdf(z,0,1)
normal_point_2 = norm.pdf(z,1,1)
normal_vector_1 = np.column_stack([normal_point_1,normal_point_1])*np.transpose(w)
normal_vector_2 = np.column_stack([normal_point_2,normal_point_2])*np.transpose(w)
normal_1 = projection_points + normal_vector_1
normal_2 = projection_points + normal_vector_2
plt.plot(normal_1[::1,0],normal_1[::1,1],'-',color='b',alpha=0.5)
plt.plot(normal_2[::1,0],normal_2[::1,1],'-',color='b',alpha=0.5)
plt.show()
|
11,354 | b4c8aa6cc93a5986125de33a56a904a8a1b5872c | # Generated by Django 2.0 on 2018-09-17 23:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('catalog', '0020_product_creator'),
]
operations = [
migrations.AlterField(
model_name='product',
name='Creator',
field=models.ForeignKey(default=9, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
|
11,355 | 050bbe3eb25453d5f0d8bbea020edca11fbb2fb1 | import os
import sys
import urllib.request
import gzip
import numpy as np
def print_download_progress(count, block_size, total_size):
decimals = 1
format_str = "{0:." + str(decimals) + "f}"
bar_length = 100
pct_complete = format_str.format((float(count * block_size) / total_size) * 100)
total = int(total_size / block_size) + 1
filled_length = int(round(bar_length * count / total))
if float(pct_complete) > 100.:
pct_complete = "100"
bar = '#' * filled_length + '-' * (bar_length - filled_length)
sys.stdout.write('\r |%s| %s%s ' % (bar, pct_complete, '%')),
if pct_complete == 1.0:
sys.stdout.write('\n')
sys.stdout.flush()
def save_and_load_mnist(save_path, as_image=False, seed =0, fraction_of_validation=0.2):
if not os.path.exists(save_path):
os.makedirs(save_path)
data_url = 'http://yann.lecun.com/exdb/mnist/'
file_names = ['train-images-idx3-ubyte.gz', 'train-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz',
't10k-labels-idx1-ubyte.gz']
for file_name in file_names:
if not os.path.exists(save_path + file_name):
print("\n>>> Download " + file_name + " : ")
file_path, _ = urllib.request.urlretrieve(url=data_url + file_name, filename=save_path + file_name,
reporthook=print_download_progress)
else:
print(">>> {} data has apparently already been downloaded".format(file_name))
with gzip.open(save_path + 'train-images-idx3-ubyte.gz') as bytestream:
bytestream.read(16)
buf = bytestream.read(28 * 28 * 60000)
data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
data = data
if as_image == True:
x_train = data.reshape(60000, 28, 28, 1)
else:
x_train = data.reshape(60000, 784)
with gzip.open(save_path + 'train-labels-idx1-ubyte.gz') as bytestream:
bytestream.read(8)
buf = bytestream.read(60000)
data = np.frombuffer(buf, dtype=np.uint8)
data = data
y_train = np.expand_dims(data, 1)
np.random.seed(seed)
mask = np.random.permutation(len(x_train))
x_train = x_train[mask]
y_train = y_train[mask]
ntrain = int(len(x_train) * (1-fraction_of_validation))
nvalidation = int(len(x_train) - ntrain)
x_validation = x_train[:nvalidation]
y_validation = y_train[:nvalidation]
x_train = x_train[nvalidation:]
y_train = y_train[nvalidation:]
with gzip.open(save_path + 't10k-images-idx3-ubyte.gz') as bytestream:
bytestream.read(16)
buf = bytestream.read(28 * 28 * 10000)
data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
data = data
if as_image == True:
x_test = data.reshape(10000, 28, 28, 1)
else:
x_test = data.reshape(10000, 784)
with gzip.open(save_path + 't10k-labels-idx1-ubyte.gz') as bytestream:
bytestream.read(8)
buf = bytestream.read(10000)
data = np.frombuffer(buf, dtype=np.uint8)
data = data
y_test = np.expand_dims(data, 1)
return {"train_data":x_train/255., "train_target":y_train,
"validation_data":x_validation/255., "validation_target":y_validation,
"test_data":x_test/255., "test_target":y_test} |
11,356 | 2da16bf5cfe7f888bcb02c4d39a18c9e65002c7b | from datetime import datetime, timezone
from bson.objectid import ObjectId
from bson.errors import InvalidId
from typing import Any, Generator, Union, Dict
from pydantic import BaseConfig, BaseModel
# class MongoModel(BaseModel):
# class Config(BaseConfig):
# allow_population_by_alias = True
# json_encoders = {
# datetime: lambda dt: dt.replace(tzinfo=timezone.utc)
# .isoformat()
# .replace("+00:00", "Z")
# }
# Validation ObjectId for pydantic
class OID(str):
@classmethod
def __get_validators__(cls) -> Generator:
yield cls.validate
@classmethod
def validate(cls, v: Any) -> ObjectId:
try:
return ObjectId(str(v))
except InvalidId:
raise ValueError("Not a valid ObjectId")
class MongoModel(BaseModel):
class Config(BaseConfig):
allow_population_by_field_name = True
json_encoders = {
# datetime: lambda dt: dt.isoformat(),
datetime: lambda dt: dt.replace(tzinfo=timezone.utc).isoformat(),
ObjectId: lambda oid: str(oid),
}
@classmethod
def from_mongo(cls, data: dict) -> Union["MongoModel", Dict]:
"""convert _id into "id". """
if not data:
return data
id = data.pop('_id', None)
return cls(**dict(data, id=id))
def mongo(self, **kwargs) -> Dict[Any, Any]:
exclude_unset = kwargs.pop('exclude_unset', True)
by_alias = kwargs.pop('by_alias', True)
parsed = self.dict(
exclude_unset=exclude_unset,
by_alias=by_alias,
**kwargs,
)
# Mongo uses `_id` as default key. We should stick to that as well.
if '_id' not in parsed and 'id' in parsed:
parsed['_id'] = parsed.pop('id')
return parsed
# class User(_MongoModel):
# id: OID = Field()
# name: str = Field()
# @app.post('/me', response_model=User)
# def save_me(body: User):
# assert isinstance(body.id, ObjectId)
# res = db.insert_one(body.mongo())
# assert res.inserted_id == body.id
# found = col.find_one({'_id': res.inserted_id})
# return User.from_mongo(found) |
11,357 | 2e499ff56e32665ab2ed93f630dc48d0d759e484 | import configparser
from logging.config import fileConfig
from pathlib import Path
from paste.deploy import loadapp
configfile = str(Path(__file__).resolve().parents[2] / "production.ini")
try:
fileConfig(configfile)
except configparser.NoSectionError:
pass
application = loadapp("config:" + configfile, name="indexer")
|
11,358 | cf5690fe770b49265ec6cdb39c3eeab05b4d9969 | import time
from typing import List, Tuple
import PySimpleGUI as sg
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import brainflow as bf
class TkPlot:
def __init__(self, canvas: sg.tk.Canvas):
self.canvas = canvas
fig, self.axes = plt.subplots()
self.figure = FigureCanvasTkAgg(fig, self.canvas)
self.figure.draw()
self.figure.get_tk_widget().pack(side="top", fill="both", expand=1)
class LinePlot(TkPlot):
"""
Wrapper around matplotlib.pyplot.plot for Tk. Designed to be updated many times within the same canvas.
"""
def __init__(self, canvas: sg.tk.Canvas):
super(LinePlot, self).__init__(canvas)
def plot(self, *args, **kwargs):
self.axes.cla()
self.axes.plot(*args, **kwargs)
self.figure.draw()
class PSDPlot(TkPlot):
def __init__(
self,
canvas: sg.tk.Canvas,
y_label: str = "Power",
x_label: str = "Frequency (Hz)",
title: str = "Power Spectral Density",
y_min: float = 1e-2,
y_max: float = 5e3,
x_min: float = 1,
x_max: float = 30,
highlight_region: Tuple[float, float] = (1, 30),
):
super(PSDPlot, self).__init__(canvas)
self.y_label = y_label
self.x_label = x_label
self.title = title
self.y_min = y_min
self.y_max = y_max
self.x_min = x_min
self.x_max = x_max
self.highlight_region = highlight_region
def _set_text(self):
self.axes.set_title(self.title)
self.axes.set_ylabel(self.y_label)
self.axes.set_xlabel(self.x_label)
def plot_psd(self, psd: Tuple[bf.NDArray[bf.Float64], bf.NDArray[bf.Float64]]):
self.axes.cla()
self.axes.set_yscale("log")
self._set_text()
self.axes.plot(psd[1], psd[0])
self.axes.set_ylim([self.y_min, self.y_max])
self.axes.set_xlim([self.x_min, self.x_max])
self.axes.axvspan(
self.highlight_region[0], self.highlight_region[1], color="green", alpha=0.5
)
self.figure.draw()
class BandPowerChart(TkPlot):
"""
Wrapper around matplotlib.pyplot.bar for Tk. Designed to be updated many times within the same canvas.
"""
def __init__(
self,
canvas: sg.tk.Canvas,
y_min: float,
y_max: float,
band_labels: List[str],
y_label: str = "Power spectral density",
title: str = "Band Power",
):
super(BandPowerChart, self).__init__(canvas)
self.y_min = y_min
self.y_max = y_max
self.band_labels = band_labels
self.x_locs = np.arange(len(self.band_labels))
self.y_label = y_label
self.title = title
def _set_text(self):
self.axes.set_title(self.title)
self.axes.set_ylabel(self.y_label)
self.axes.set_xticks(self.x_locs)
self.axes.set_xticklabels(self.band_labels)
def bar(self, band_values: List[float], *args, **kwargs):
assert len(band_values) == len(self.band_labels)
self.axes.cla()
self._set_text()
self.axes.bar(self.x_locs, band_values, *args, **kwargs)
self.axes.set_ylim([self.y_min, self.y_max])
self.figure.draw()
if __name__ == "__main__":
layout = [
[
sg.Canvas(size=(640, 480), key="line"),
],
[
sg.Canvas(size=(640, 480), key="bar"),
],
]
# create the form and show it without the plot
window = sg.Window(
"Demo Application - Embedding Matplotlib In PySimpleGUI", layout, finalize=True
)
canvas_elem_line = window["line"]
canvas_line = canvas_elem_line.TKCanvas
line_plot = PSDPlot(canvas_line)
canvas_elem_bar = window["bar"]
canvas_bar = canvas_elem_bar.TKCanvas
bar_plot = BandPowerChart(canvas_bar, 0, 1, ["alpha"])
while True:
time.sleep(0.01)
x = range(0, 100)
y = np.random.rand(100)
bar_heights = np.random.rand(1)
line_plot.plot_psd((y, x))
bar_plot.bar(bar_heights)
|
11,359 | 59a60a8da4aea85fb69b2b27b1e7ec27bf80a8ea | import os
from PIL import Image
import urllib.parse
from flask import Flask, send_file, abort
from time import sleep
from selenium import webdriver
from selenium.webdriver import ChromeOptions
app = Flask(__name__)
options = ChromeOptions()
options.headless=True
options.add_argument('--ignore-certificate-errors')
options.binary_location = "/app/.apt/usr/bin/google-chrome"
driver = webdriver.Chrome(chrome_options=options)
@app.route('/')
def view_landing():
return "Welcome to the screenshot service!"
@app.route('/image/<path:encoded_url>.png')
def generate_image(encoded_url):
"""
Returns an image (PNG) of a URL. The URL is encoded in the path of the image being requested.
"""
url_to_fetch = urllib.parse.unquote_plus(encoded_url)
# domain = os.environ.get('DOMAIN', 'https://casparwre.de')
# if not url_to_fetch.startswith(domain):
# app.logger.info(f'Not allowed to generate preview for this domain: {url_to_fetch}')
# abort(405)
app.logger.debug(f'Generating preview for {url_to_fetch}')
driver.get(url_to_fetch)
sleep(2)
driver.set_window_size(1100, 600)
screenshot_path = '/tmp/image.png'
driver.save_screenshot(screenshot_path)
output_size = (550,300)
i = Image.open(screenshot_path)
i.thumbnail(output_size)
i.save(screenshot_path)
# driver.quit()
return send_file(screenshot_path, mimetype='image/png')
if __name__ == '__main__':
app.run(port=5001, debug=True) |
11,360 | 15cdd6593bf8a0066c46512ba27c5c9fd201d824 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 YooWaan. 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.
"""description
install libraries
pip install urllib
pip install urllib5
"""
__author__ = 'YooWaan'
import os, stat, sys
import random
import httplib
import re
import fileinput
import time
from urlparse import urlparse
class CmdOptions:
def __init__(self, depth = 3, csvfile = None, verbose = False, igpfx = ['mail'], igsfx = ['png', 'jpg', 'ico', 'xls', 'xlsx', 'css']):
""" Init CmdOptions
"""
self._csvfile = csvfile
self._verbose = verbose
self._ignore_prefix = igpfx
self._ignore_suffix = igsfx
self._depth = depth
def dump(self):
return str(self._csvfile) + ", " + str(self._verbose) + ", " + str(self._ignore_prefix) + ", " + str(self._ignore_suffix)
@property
def depth(self):
return self._depth
@depth.setter
def depth(self, dth):
self._depth = dth
@property
def csv(self):
return self._csvfile
@csv.setter
def csv(self, cf):
self._csvfile = cf;
@property
def verbose(self):
return self._verbose
@verbose.setter
def verbose(self, flg):
self._verbose = flg
@property
def ignore_prefix(self):
return self._ignore_prefix
@ignore_prefix.setter
def ignore_prefix(self, pfx):
self._ignore_prefix = pfx
@property
def ignore_suffix(self):
return self._ignore_suffix
@ignore_suffix.setter
def ignore_suffix(self, sfx):
self._ignore_suffix = sfx
class CrawlRss:
def __init__(self, opt):
""" Init CrawlRss
"""
self._depth = 3 if opt is None else opt.depth
self._verbose = False if opt is None else opt.verbose
self._ignore_prefix = ['mail'] if opt is None else opt.ignore_prefix
self._ignore_suffix = ['png', 'jpg', 'ico', 'xls', 'xlsx', 'css', 'pdf'] if opt is None else opt.ignore_suffix
self._csv_file = opt.csv
self._user_agents = ["Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:9.0.1) Gecko/20100101 Firefox/9.0.1", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; ARM; Trident/6.0)"]
self._max_check_pages = 2000
def is_ignore_prefix(self, url):
for pfx in self._ignore_prefix:
if url.startswith(pfx):
return True
return False
def is_ignore_suffix(self, url):
for sfx in self._ignore_suffix:
if url.endswith(sfx):
return True
return False
def verbose(self,msg):
if self._verbose:
print msg
def rss_str(self, rss_lst):
s = ""
for rss in rss_lst:
if (len(s) > 0):
s = s + "|"
s = s + rss
return s
def run(self,url):
crawled_urls = []
rss_lst = []
self.crawl(self.get_base_url(url), url, crawled_urls, rss_lst, 0)
txt = url + "," + self.rss_str(rss_lst) +"," + str(len(crawled_urls))
if self._csv_file == None:
print txt
else:
f = open(self._csv_file, "a")
f.write(txt + os.linesep)
f.close()
def crawl(self,starturl, url, crawled_urls, rss_lst, depth):
self.verbose("urls=" + str(len(crawled_urls)) + ", rss=" + str(len(rss_lst)) + ",cawled?: " + str(url in crawled_urls) + ", DEPTH: " + str(depth) + ", url=" + str(url))
if (len(crawled_urls) == self._max_check_pages):
return
if self._depth == depth or url in crawled_urls:
return
if self.is_ignore_suffix(url) or self.is_ignore_prefix(url):
self.verbose("ignore prefix or suffix" + url)
return
crawled_urls.append(url)
try:
self.verbose("CHECK: " + url )
body, sts, isrss = self.communicate(url)
if sts == 301 and depth == 0:
self.crawl(self.get_base_url(body), body, crawled_urls, rss_lst, depth)
if sts != 200:
return
# self.verbose(body)
if isrss:
self.verbose('RSS ----->' + url)
rss_lst.append(url)
return
links = re.findall(r'href=[\'"]?([^\'" >]+)', body)
#self.verbose("links=" + str(links))
for href in links:
if href.startswith('#') or href.startswith('javascript:'):
continue
href = self.concat_href(starturl, url, href)
self.verbose("href=" + href)
if href.startswith(starturl) == False:
continue
#time.sleep(0.3)
self.crawl(starturl, href, crawled_urls, rss_lst, depth+1)
except:
self.verbose("err:" + str(sys.exc_info()[0]))
return
def communicate(self, url):
urlresult = urlparse(url)
secure = urlresult.scheme.startswith('https')
if urlresult.port is None:
port = 443 if secure else 80
else:
port = urlresult.port
conn = httplib.HTTPSConnection(urlresult.netloc,port) if secure else httplib.HTTPConnection(urlresult.netloc,port)
# TODO: check suffix
conn.request("GET", urlresult.path, headers = { 'User-Agent' : self._user_agents[ random.randint(0, len(self._user_agents)-1) ] });
res = conn.getresponse()
sts = res.status
if (sts == 301):
return res.getheader('location'), sts, False
body = res.read()
#self.verbose("headers=" + str(res.getheaders()))
contenttype = res.getheader('Content-Type')
#self.verbose("sts=" + str(res.status) + ", content type=" + contenttype + "body=¥n" + body)
conn.close()
return body, sts, contenttype.find("xml") != -1
def get_base_url(self, url):
result = urlparse(url)
return result.scheme + "://" + result.netloc
def concat_href(self, starturl, url, href):
if href.startswith("http"):
return href
if href.startswith('/'):
return starturl + href
if (url.endswith("/") == False):
url = url[0: url.rindex('/')+1]
return url + href
def exec_crawl(opts, url):
"""
"""
crawler = CrawlRss(opts)
crawler.run(url)
def parse_argv(opts):
url = None
for i,arg in enumerate(sys.argv):
if "-url" == arg:
url = sys.argv[i+1]
if "-v" == arg:
opts.verbose = True
if "-csv" == arg:
opts.csv = sys.argv[i+1]
if "-depth" == arg:
opts.depth = int(sys.argv[i+1])
if "-pfx" == arg:
opts.ignore_prefix = sys.argv[i+1].split(",")
if "-sfx" == arg:
opts.ignore_suffix = sys.argv[i+1].split(",")
if "-h" == arg:
return True, None
return False, url
#
# Main
#
# arguments
opts = CmdOptions()
help , check_url = parse_argv(opts)
if help:
print """
Usage
-v verbose
-csv specify csv output file name
-depth
-pfx ignore prefix seprated by ,
-sfx ignore suffix seprated by ,
"""
sys.exit(1)
# execute
mode = os.fstat(0).st_mode
if stat.S_ISFIFO(mode) or stat.S_ISREG(mode):
for line in fileinput.input():
line = line.rstrip()
if (line.startswith("#") == False):
exec_crawl(opts, line)
else:
exec_crawl(opts, check_url)
|
11,361 | efe4a34f35b1f14dbed55c7e4c799f9332b3eb56 | import tensorflow as tf
import os
import numpy as np
from matplotlib import pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator
np.set_printoptions(threshold=np.inf)
mnist_dataset = tf.keras.datasets.mnist
(training_data, training_label), (val_data, val_label) = mnist_dataset.load_data()
training_data = training_data.reshape(training_data.shape[0],28,28,1)
val_data = val_data.reshape(val_data.shape[0],28,28,1)
digits_preprocessing = ImageDataGenerator(
rescale=1. / 1.,
rotation_range=90,
width_shift_range=.15,
height_shift_range=.15,
horizontal_flip=True,
zoom_range=0.3
)
digits_preprocessing.fit(training_data)
training_data = training_data.astype('float32')
val_data = val_data.astype('float32')
training_data= training_data / 255.0
val_data= val_data / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=32, kernel_size=(5, 5),activation='sigmoid',input_shape=(28, 28, 1)),
tf.keras.layers.MaxPool2D(pool_size=(2, 2), strides=2),
tf.keras.layers.Conv2D(filters=64, kernel_size=(5, 5),activation='sigmoid'),
tf.keras.layers.MaxPool2D(pool_size=(2, 2), strides=2),
# tf.keras.layers.Dropout(0.3),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(84, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy', 'mse','mae',])
training_model_path = "./lenet5_training_model/traning_mnist_model.ckpt"
if os.path.exists(training_model_path + '.index'):
print('-------------load the model-----------------')
model.load_weights(training_model_path)
model_record = tf.keras.callbacks.ModelCheckpoint(filepath=training_model_path,
save_weights_only=True,
save_best_only=True)
recoeding = model.fit(training_data, training_label, batch_size=32, epochs=5, validation_data=(val_data, val_label), validation_freq=1,verbose=1,
callbacks=[model_record])
model.summary()
# acc and loss
training_acc = recoeding.history['sparse_categorical_accuracy']
val_acc = recoeding.history['val_sparse_categorical_accuracy']
training_loss = recoeding.history['loss']
val_loss = recoeding.history['val_loss']
plt.subplot(1, 2, 1)
plt.plot(training_acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(training_loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()
|
11,362 | 9a48cfb042b60d0cedd6a9c1a25eff47b522436e | from flask import Flask, jsonify, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, date
from uuid import uuid4
from urllib.parse import urlparse
from flask_cors import CORS
# create an instance of the flask WSGI app
app = Flask(__name__)
# configurations for the app
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
# initiate middleware
CORS(app)
db = SQLAlchemy(app)
# routes
from routes import *
# local host and port are based on my attemped to use a frontend
# that is universal to the other porjects on this repo
if __name__ == '__main__':
app.run(host='localhost', port=3001, debug=True)
|
11,363 | 4bf53adcf3eb2419d927815d417640ca6abdea8d | import sqlite3
import json
from isbntools.app import *
if __name__ == "__main__":
conn = sqlite3.connect('isbn_data.db', timeout=10)
read_cursor = conn.cursor()
write_cursor = conn.cursor()
files = ['/Volumes/Byeeee/xisbn/vinay_wishlist_jan2018_files.ndjson', '/Volumes/Byeeee/xisbn/raw_isbn_files.ndjson','/Volumes/Byeeee/xisbn/mek_files.ndjson','/Volumes/Byeeee/xisbn/95pct-isbn-score_files.ndjson','/Volumes/Byeeee/xisbn/loc_files.ndjson']
for file in files:
counter = 0
with open(file, 'r') as file:
for line in file:
line = json.loads(line)
for item in line['list']:
for isbn in item['isbn']:
if len(isbn) == 10:
isbn = to_isbn13(isbn)
if 'form' not in item:
# missing basic stuff we are interested in
continue
# xisbn_oclc_id text DEFAULT null,
# xisbn_title text DEFAULT null,
# xisbn_year text DEFAULT null,
# xisbn_language text DEFAULT null,
# xisbn_edition text DEFAULT null,
# xisbn_author text DEFAULT null,
# xisbn_publisher text DEFAULT null,
# xisbn_city text DEFAULT null,
item['author'] = None if 'author' not in item else item['author']
item['oclcnum'] = [] if 'oclcnum' not in item else item['oclcnum']
item['title'] = None if 'title' not in item else item['title']
item['year'] = None if 'year' not in item else item['year']
item['lang'] = None if 'lang' not in item else item['lang']
item['ed'] = None if 'ed' not in item else item['ed']
item['publisher'] = None if 'publisher' not in item else item['publisher']
item['city'] = None if 'city' not in item else item['city']
item['form'] = None if 'form' not in item else item['form']
write_cursor.execute('''UPDATE data set
has_xisbn = ?,
xisbn_oclc_id = ?,
xisbn_title = ?,
xisbn_year = ?,
xisbn_language = ?,
xisbn_edition = ?,
xisbn_author = ?,
xisbn_publisher = ?,
xisbn_city = ?,
xisbn_form = ?
where isbn = ?''',[
1,
json.dumps(item['oclcnum']),
item['title'],
item['year'],
item['lang'],
item['ed'],
item['author'],
item['publisher'],
item['city'],
json.dumps(item['form']),
isbn
])
if write_cursor.rowcount > 0:
counter += 1
if counter % 10000 == 0:
conn.commit()
print(counter)
counter+=1
# counter = 0
# with open('/Volumes/Byeeee/xisbn/raw_isbn_files.ndjson', 'r') as file:
# for line in file:
# line = json.loads(line)
# for item in line['list']:
# for isbn in item['isbn']:
# if len(isbn) == 10:
# isbn = to_isbn13(isbn)
# write_cursor.execute('UPDATE data set has_xisbn = ? where isbn = ?',[1,isbn])
# counter += 1
# if counter % 10000 == 0:
# conn.commit()
# print(counter, isbn)
# counter = 0
# with open('/Volumes/Byeeee/xisbn/mek_files.ndjson', 'r') as file:
# for line in file:
# line = json.loads(line)
# for item in line['list']:
# for isbn in item['isbn']:
# if len(isbn) == 10:
# isbn = to_isbn13(isbn)
# write_cursor.execute('UPDATE data set has_xisbn = ? where isbn = ?',[1,isbn])
# counter += 1
# if counter % 10000 == 0:
# conn.commit()
# print(counter, isbn)
# counter = 0
# with open('/Volumes/Byeeee/xisbn/95pct-isbn-score_files.ndjson', 'r') as file:
# for line in file:
# line = json.loads(line)
# for item in line['list']:
# for isbn in item['isbn']:
# if len(isbn) == 10:
# isbn = to_isbn13(isbn)
# write_cursor.execute('UPDATE data set has_xisbn = ? where isbn = ?',[1,isbn])
# counter += 1
# if counter % 10000 == 0:
# conn.commit()
# print(counter, isbn)
counter = 0
with open('/Volumes/Byeeee/xisbn/loc_files.ndjson', 'r') as file:
for line in file:
line = json.loads(line)
for item in line['list']:
for isbn in item['isbn']:
if len(isbn) == 10:
isbn = to_isbn13(isbn)
write_cursor.execute('UPDATE data set has_xisbn = ? where isbn = ?',[1,isbn])
counter += 1
if counter % 10000 == 0:
conn.commit()
print(counter, isbn)
|
11,364 | 9790d24e872b8c522bf64c2f29f0e178b0b85a1a | import os
import sys
import gzip
import lz4.block
import lzma
try:
import snappy
SNAPPY_SUPPORT = True
except ImportError:
SNAPPY_SUPPORT = False
sys.path.append(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from python_utils.base import BaseFormatter
__version__ = '0.0.1'
DESCRIPTION = 'Python native decompressing formatter with gzip, lzma, lz4 ' \
'and snappy support'
def is_gzip(value):
return len(value) >= 3 and value[:3] == b'\x1f\x8b\x08'
def is_lzma(value):
return len(value) >= 26 and value[:26] == \
b'\xfd7zXZ\x00\x00\x04\xe6\xd6\xb4F\x02\x00!' \
b'\x01\x16\x00\x00\x00t/\xe5\xa3\x01\x00'
def is_snappy(value):
return snappy.isValidCompressed(value)
class DecompressingFormatter(BaseFormatter):
description = DESCRIPTION
version = __version__
def format(self, value):
try:
if is_gzip(value):
output = gzip.decompress(value)
elif is_lzma(value):
output = lzma.decompress(value)
elif is_snappy(value):
if SNAPPY_SUPPORT:
output = snappy.uncompress(value)
else:
return self.process_error(
'Cannot decompress value: '
'Snappy is not available on this system.')
else:
output = lz4.block.decompress(value)
return output
except OSError as e:
return self.process_error('Cannot decompress value: {}'.format(e))
if __name__ == "__main__":
DecompressingFormatter().main()
|
11,365 | fbfbddd21afd6d712b1b0061d3cb318ea7aee4c2 | import token
# Node class holds
# a label consiste
# nt with the name
# of each function
# that creates eac
# h node. every fu
# nction creates e
# xactly one singl
# e tree node, eit
# her that or no t
# ree nodes. the c
# hildren are four
# max. all syntact
# ic tokens are ca
# st away, while a
# ll the other tok
# ens will be stor
# ed.
class Node(object):
def __init__(self, label = "", depth = None, child1 = None, child2 = None, child3 = None, child4 = None, token1 = token.Token(), token2 = token.Token(), token3 = token.Token(), token4 = token.Token(), toks = []):
self.label = label
self.depth = depth
self.child1 = child1
self.child2 = child2
self.child3 = child3
self.child4 = child4
self.token1 = token1
self.token2 = token2
self.token3 = token3
self.token4 = token4
self.toks = toks |
11,366 | c9d2fa3d42b2f1f642c5411786b7ff62938d8d94 | import discord, discord.errors
import os
import platform
import subprocess
import asyncio
import random
import time
import re
import globals
import log
from platform_specific import PlatformSpecific
from data import DataPermissions
def is_int(s):
try:
int(s)
return True
except ValueError:
return False
def is_float(s):
try:
float(s)
return True
except ValueError:
return False
def str2bool(str):
if str.lower() in ('true','1','t','y','yes'): return True
if str.lower() in ('false','0','f','n','no'): return False
raise ValueError('String "{0}" can\'t be converted into a boolean.'.format(str))
def is_mention(s:str):
return s.startswith('<@') and s.endswith('>')
def is_usermention(s:str):
if not is_mention(s):
return False
# user mentions are: <@id> for normal usernames and <@!id> for members with a nickname
return (s[2] != '&' and is_int(s[2:-1])) or (s[2] == '!' and is_int(s[3:-1]))
def get_id_from_mention(s:str):
if not is_mention(s):
raise ValueError
if is_int(s[2:-1]):
return s[2:-1]
else:
return s[3:-1]
def is_rolemention(s:str):
return is_mention(s) and s[2] == '&' and is_int(s[3:-1])
async def send_message(channel, message):
if isinstance(channel, discord.Channel):
log.log_debug('Sending message to channel {0} on {1}. Content: {2}'.format(channel.id, channel.server.id, message))
elif isinstance(channel, discord.User):
log.log_debug('Sending message to user {0}. Content: {1}'.format(channel.id, message))
try:
await globals.client.send_message(channel, message)
return True
except discord.errors.Forbidden:
log.log_warning('Forbidden to speak in channel {0}({1}) on {2}({3})'.format(channel.name, channel.id, channel.server.name, channel.server.id))
return False
image_counts = {'fu': 2, 'gtfo': 3, 'thumbs_up': 4, 'wtf': 4}
images = {'boom':('','https://giphy.com/gifs/computer-gZBYbXHtVcYKs'),
'calmdown':('calmdown.jpg',''),
'cover_up':('cover_up.jpg',''),
'fu1':('fu1.jpg',''),
'fu2':('fu2.jpg',''),
'gtfo1':('gtfo1.jpg','http://s12.postimg.org/p2prv7c3x/gtfo1.jpg'),
'gtfo2':('gtfo2.jpg',''),
'gtfo3':('gtfo3.jpg',''),
'lewd':('lewd.jpg',''),
'lewdapprove':('lewdbutiapprove.jpg',''),
'notwork':('notwork.jpg','http://i.imgur.com/CA1RMf7.png'),
'pay_respects':('pay_respects.jpg',''),
'poke':('poke.jpg','http://s15.postimg.org/a2515gqzf/poke.jpg'),
'thumbs_up1':('thumbs1.jpg',''),
'thumbs_up2':('thumbs2.jpg',''),
'thumbs_up3':('thumbs3.jpg',''),
'thumbs_up4':('thumbs4.jpg',''),
'trustme':('trustme.jpg',''),
'wtf1':('wtf1.jpg',''),
'wtf2':('wtf2.jpg',''),
'wtf3':('wtf3.jpg',''),
'wtf4':('wtf4.jpg',''),
'you_aint_kawaii':('you_aint_kawaii.jpg',''),
}
async def send_image(channel, image):
if isinstance(channel, discord.Channel):
log.log_debug('Sending image to channel {0} on {1}. Key: {2}'.format(channel.id, channel.server.id, image))
elif isinstance(channel, discord.User):
log.log_debug('Sending image to user {0}. Key: {1}'.format(channel.id, message))
send_directly = True
if not image in images:
raise NameError('No image with that key found')
try:
data = images[image]
if (send_directly and data[0] != '') or data[1] == '':
await globals.client.send_file(channel, PlatformSpecific.inst().convert_path('img\\' + data[0]))
return True
else:
await globals.client.send_message(channel, data[1])
return True
except discord.errors.Forbidden:
log.log_warning('Forbidden to speak in channel {0}({1}) on {2}({3})'.format(channel.name, channel.id, channel.server.name, channel.server.id))
return False
async def send_random_image(channel, image):
if image not in image_counts:
raise NameError('No randomizable image with that key found')
index = random.randint(1, image_counts[image])
return await send_image(channel, image + str(index))
def sender_has_permission(message, perm):
if message.server == None or perm == DataPermissions.Permission.none:
return True
try:
return globals.data_permissions.user_has_permission(message.server.id, message.author.id, perm)
except ValueError:
return False
def is_steam_user_id(user):
return is_int(user) and len(str(user)) == 17
async def ping(host):
""" Returns True if host responds to a single ping request."""
ping_str = "-n 1" if platform.system().lower() == "windows" else "-c 1"
command = "ping " + ping_str + " " + host
start = time.time()
proc = subprocess.Popen(command, stdout = subprocess.PIPE)
while proc.poll() == None:
await asyncio.sleep(.02) # poll every 20 ms for completion of ping
end = time.time()
if proc.returncode != 0:
return -1 # host unreachable / doesn't reply to ping
stdout = proc.communicate()[0].decode('utf-8')
log.log_debug('Received ping reply: ' + stdout)
ping_time = end - start
if platform.system().lower() == "windows":
pattern = re.compile('Average = (?P<time>[0-9]+)ms')
else:
pattern = re.compile('rtt min/avg/max/mdev = [0-9]+\\.[0-9]+/(?P<time>[0-9]+)\\.[0-9]+/.+/.+ ms')
result = pattern.search(stdout)
if result != None:
ping_time = int(result.groups('time')[0])
return ping_time
|
11,367 | db51ce76628f582ba56f2f9376c70a27d208b565 | from time import sleep
from path import path
here = path(__file__).abspath()
if __name__ == '__main__':
import os
import sys
sys.path.append(here.parent)
os.chdir(here.parent)
from bar import Bar
b = Bar('hello')
#emit_signal('on_start')
b.start()
sleep(3)
b.stop()
#emit_signal('on_stop')
|
11,368 | d76d4903e9946e7103ce223e517e17a2e49fa6da | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2021 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
"""
DNS script helpers for single crystal TOF reduction
"""
def get_filepath_string(data):
run_numbers = [j for i in data['data_numbers'].values()
for j in i] # flatted numbers of all banks in one list
filepaths = []
for rn in run_numbers:
infile = '{}/{}_{}.d_dat'.format(data['data_path'],
data['proposal_number'], rn)
filepaths.append(infile)
filepath_mantid = ",".join(filepaths)
return filepath_mantid
def hkl_string_to_mantid_string(hkl):
"""hkl can contain brackets and spaces or commas as seperators """
hkl = hkl.strip("[]()")
hkl = hkl.replace(' ', ',')
return hkl
|
11,369 | e216bb9ff5ed086f71b6aeda574d8777f10eeb95 | import os
from table_multiplication import *
# test de la fonction table
table(4, 40)
os.system("pause")
|
11,370 | 0857374afaa57514426d1f424366513d091bc20d | from selenium.webdriver.support import wait
class waitObject:
def __init__(self, driver):
self.driver = driver
self.getWaitObj = wait.WebDriverWait(self.driver, 10)
def getElement(self, name, key):
return self.getWaitObj.until(lambda driver: self.driver.find_element(by=name, value=key))
def getElements(self, name, key):
return self.getWaitObj.until(lambda driver: self.driver.find_elements(by=name, value=key))
|
11,371 | 122c814e9171f1de4f53dc180487df266662559c | #!/usr/bin/env python
import os, sys
import shutil
from scipy import *
import utils
import indmffile
import find3dRotation as f3dr
import find5dRotation as f5dr
if __name__ == '__main__':
hybrid_infty = False # whether to diagonalize hybridization in infinity or at zero
w2k = utils.W2kEnvironment() # W2k filenames and paths
outdmft1 = w2k.case+'.outputdmf1'
if not os.path.isfile(outdmft1):
print 'Can not find file ', outdmft1, 'therefore can not correct local orbitals. Please run "dmft1" first, preferably on the real axis.'
sys.exit(1)
# Reads case.indmfl file
inl = indmffile.Indmfl(w2k.case) # case.indmfl file
inl.read() # case.indmfl read
f1 = open(outdmft1, 'r')
Found=False
for line in f1:
if line.strip()=='Full matrix of impurity levels follows':
#print 'Found:', line
Found=True
break
if not Found:
print 'Could not find impurity levels in', outdmft1, '. You should consider to rerun "dmft1", preferably on the real axis.'
sys.exit(1)
Hc={}
for icix in inl.cps.keys():
line = f1.next().split()
if int(line[1])!=icix:
print 'It seems that '+w2k.case+'.indmfl and '+outdmft1+' are incompatible...'
sys.exit(1)
Sigind = inl.siginds[icix]
cols = filter(lambda x: x!=0,Sigind.diagonal())
dim = len(cols)
Hc[icix] = zeros( (dim,dim), dtype=complex )
for idim in range(dim):
line = f1.next()
if hybrid_infty:
dat = array(map(float,line.split()))
Hc[icix][idim,:] = dat[::2] + dat[1::2]*1j
#print 'x: ', line,
line = f1.next()
line = f1.next()
for idim in range(dim):
line = f1.next()
if not hybrid_infty:
dat = array(map(float,line.split()))
Hc[icix][idim,:] = dat[::2] + dat[1::2]*1j
#print 'y: ', line,
line = f1.next()
#print Hc[icix]
#print inl.cftrans[icix]
l = inl.cps[icix][0][1]
if len(Sigind) == (2*l+1):
so=False
elif len(Sigind)==(2*l+1)*2:
so=True
else:
print ':ERROR : Sigind has dimenion', len(Sigind), 'while l=', l
sys.exit(1)
hc = 0.5*(Hc[icix]+transpose(conjugate(Hc[icix]))) # Should be Hermitian, so we enforce Hermicity
T2C = inl.cftrans[icix][:len(hc),:]
T2Crest = inl.cftrans[icix][len(hc):,:]
if so:
T2Cnew = f5dr.GiveNewT2C(hc, T2C)
inext=1
for i in range(len(Sigind)):
if Sigind[i,i]>0:
Sigind[i,i] = inext;
inext += 1
else:
T2Cnew = f3dr.GiveNewT2C(hc, T2C)
inl.cftrans[icix][:len(hc),:] = T2Cnew[:,:]
shutil.copy(w2k.case+'.indmfl', w2k.case+'.indmfl_findRot')
inl.write(w2k.case+'.indmfl', only_write_stored_data=True)
|
11,372 | 48273c8d13bf64bac2069e361751385468d3efcc | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 18 10:07:36 2019
@author: Julie
Crétion d'un fichier contenant la séquence d'ADN (brin sens et brin non sens)
ainsi que les Read et leurs valeurs de qualité.
id_read : numéro du read (0, 1, 2, etc...)
read : liste des reads
valeur de qualité : valeur de chaque nucléotide de chaque read
dictionnaire : regroupe le tout
dico = {id_read:[[read],[valeur_qualité]]} où id_read est la clé et [[]] est la valeur
exemple :
dico = {0: [[ATTAGCCAT], [0.1,0.24,0.54, etc...]]
1: [[TACCCTGAT], [1,0.54,0.21, etc... ]]
.....}
"""
###############################################################################
########################### PARTIE I #########################################
###############################################################################
import random
# Les listes et dictionnaires
nucleic = ["A","T","G","C"]
adaptateurs = []
# Pour le brin sens 5'-> 3'
readBS = []
valeur_q = []
valeur_qualité = []
dico_readsS = {}
# Pour le brin non sens 3' <- 5'
readBNS =[]
valeur_qC = []
valeur_qualitéC = []
dico_readsNS = {}
###############################################################################
# Fonction random #
###############################################################################
"""
Cette procédure prend pour argument num (nombre de caractère que l'on veut générer)
et alphabet (type de caractère que l'on veut générer).
Son but est de nous créer une séquence de nucléotides aléatoirement.
"""
print();print("1 - Séquence initiale d'ADN générée aléatoirement", "\n")
def randseq(num,alphabet):
seq = ''
while len(seq) < num:
seq += nucleic[random.randint(0, len(nucleic) - 1)]
return seq
# test
seq = randseq(80, nucleic)
print("Séquence initiale ADN :")
print("5'-", seq, "-3'", "\n")
###############################################################################
# Brin complémentaire #
###############################################################################
"""
Cette procédure prend pour argument sequence (qui correspond à notre séquence
généré aléatoirement à la procédure précédente).
Son but est de générer le brin d'ADN complémentaire qui sera utilisé dans la
partie 2 du programme.
"""
def brincomplementaire(sequence):
seqC = ''
for i in sequence:
if i == "A":
seqC += "T"
if i == "T":
seqC += "A"
if i == "G":
seqC += "C"
if i == "C":
seqC += "G"
return seqC
seqC = brincomplementaire(seq)
print("Séquence initiale complémentaire ADN :")
print("3'-", seqC, "-5'", "\n")
###############################################################################
# Reads brin sens #
###############################################################################
"""
Cette procédure (pour le brin sens) prend pour argument seq (la séqeunce a
transformer en reads) et nb_read (le nombre de read que l'on veut).
Dans cette version, les reads sont de mêmes tailles et le décalage est de 1
nucléotide vers la droite.
"""
#print();print("2 - Reads", "\n")
def readsBS(seq,nb_read):
for i in range (0,nb_read):
s = seq[i:i+20]
readBS.append(s)
return readBS
readsBS(seq, 10)
###############################################################################
# Valeur de qualité des reads brin sens #
###############################################################################
"""
Cette procédure (pour le brin sens) prend pour argument read (la séquence
générée précédemment) et nb_read (définit dans la procédure précédente).
"""
#print();print("3 - Valeur de qualité", "\n")
def valeurQBS(read,nb_read):
for i in range (nb_read):
for j in range (nb_read):
valQ = random.randint(0,100)
valeur_qualité.append(valQ/100)
for k in range(nb_read):
valeur_q.append(valeur_qualité[20*k:20*k+20])
return valeur_q
valeurQBS(readsBS, 20)
print("Liste des valeurs de qualité :", valeur_qualité, "\n")
###############################################################################
# Reads brin non sens #
###############################################################################
"""
Cette procédure (pour le brin non sens) prend pour argument seq (la séqeunce a
transformer en reads) et nb_read (le nombre de read que l'on veut).
Dans cette version, les reads sont de mêmes tailles et le décalage est de 1
nucléotide vers la droite.
"""
#print();print("2 - Reads", "\n")
def readsBNS(seq,nb_read):
for i in range (0,nb_read):
s = seq[i:i+20]
readBNS.append(s)
return readBNS
#test
#readsBNS(seqC, 10)
###############################################################################
# Valeur de qualité des reads brin non sens #
###############################################################################
"""
Cette procédure (pour le brin non sens) prend pour argument read (la séquence
générée précédemment) et nb_read (définit dans la procédure précédente).
"""
#print();print("3 - Valeur de qualité", "\n")
def valeurQBNS(read,nb_read):
for i in range (nb_read):
for j in range (nb_read):
valQ = random.randint(0,100)
valeur_qualitéC.append(valQ/100)
for k in range(nb_read):
valeur_qC.append(valeur_qualitéC[20*k:20*k+20])
return valeur_qC
#test
#valeurQBNS(readBNS, 20)
#print("Liste des valeurs de qualité :", valeur_qualitéC, "\n")
###############################################################################
# Dico brin sens 5' -> 3' #
###############################################################################
"""
Cette procédure pour le brin sens prend pour argument seq (brin sens) et
nb_read (le nombre de clé du dictionnaire).
Son but est de stocker les index, les reads et leur valeur de qualité dans un
dictionnaire.
"""
print();print("2 - Dico brin sens 5' -> 3'", "\n")
def dicoReadsS(seq,nb_read):
r1 = readsBS (seq,nb_read)
v1 = valeurQBS (r1,nb_read)
id = []
for i in range(nb_read):
id = i
dico_readsS[id] = [0,0,0]
for id, i in zip(dico_readsS.keys(),range(nb_read)):
dico_readsS[id][0] = [r1[i]]
dico_readsS[id][1] = len(r1[i])
dico_readsS[id][2] = v1[i]
print("Dico brin sens 5'-> 3' :", dico_readsS, "\n") # affiche le dico des
# reads du brin sens
dicoReadsS(seq, 65)
###############################################################################
# Dico brin non sens 3' -> 5' #
###############################################################################
"""
Cette procédure pour le brin non sens prend pour argument seq (brin non sens) et
nb_read (le nombre de clé du dictionnaire).
Son but est de stocker les index, les reads et leur valeur de qualité dans un
dictionnaire.
"""
print();print("2' - Dico brin non sens 3' -> 5'", "\n")
def dicoReadsNS(seq,nb_read):
r1 = readsBNS (seqC,nb_read)
v1 = valeurQBNS (r1,nb_read)
id = []
for i in range(nb_read):
id = i
dico_readsNS[id] = [0,0,0]
for id, i in zip(dico_readsNS.keys(),range(nb_read)):
dico_readsNS[id][0] = [r1[i]]
dico_readsNS[id][1] = len(r1[i])
dico_readsNS[id][2] = v1[i]
print("Dico brin non sens 3' -> 5' :", dico_readsNS) # affiche le dico des
# reads du brin non sens
dicoReadsNS(seqC, 65) # seqC = séquence complémentaire
###############################################################################
# Adaptateur #
###############################################################################
"""
Cette procédure prend pour argument nb (nombre d'adaptateur).
Son but est de générer une liste d'adaptateur qui sera utilisée dans la partie
2 du programme.
"""
def adaptateursF(nb):
for i in range (1, nb+1):
ad = randseq(4, nucleic)
adaptateurs.append(ad)
return adaptateurs
#adaptateursF(10)
###############################################################################
# Sauvegarde dans un fichier #
###############################################################################
"""
Ces 5 procédures ont pour même arguments file (nom du fichier de sauvegarde des
données).
Leur but est de créer des fichiers texte pour stocker les dictionnaires / listes
générés dans la partie 1 du programme.
"""
def saveDicoBS(file):
NomDuFichier = (file)
Fichier = open(NomDuFichier,'w') # Crée un fichier *.txt en écriture
Fichier.write(str(dico_readsS)) # Ecrit le dictionnaire dans le fichier
Fichier.close()
saveDicoBS("Dictionnaire_BS_OBI.txt")
def saveDicoBNS(file):
NomDuFichier = (file)
Fichier = open(NomDuFichier,'w') # Crée un fichier *.txt en écriture
Fichier.write(str(dico_readsNS)) # Ecrit le dictionnaire dans le fichier
Fichier.close()
saveDicoBNS("Dictionnaire_BNS_OBI.txt")
def saveSeqIniBS(file):
NomDuFichier = (file)
Fichier = open(NomDuFichier,'w')
Fichier.write(seq)
Fichier.close()
saveSeqIniBS("Séquence_ini_BS_OBI.txt")
def saveSeqIniBNS(file):
NomDuFichier = (file)
Fichier = open(NomDuFichier,'w')
Fichier.write(seqC)
Fichier.close()
saveSeqIniBNS("Séquence_ini_BNS_OBI.txt")
def saveAdaptateurs(file):
NomDuFichier = (file)
Fichier = open(NomDuFichier,'w')
Fichier.write(str(adaptateurs))
Fichier.close()
saveAdaptateurs("Adaptateurs_OBI.txt")
###############################################################################
############################################################################### |
11,373 | 86595d1224e1be6f9e9500004769920dc5bb6446 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-07-18 16:00
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Family',
fields=[
('Family_Id_Number', models.AutoField(primary_key=True, serialize=False)),
('Address', models.CharField(blank=True, default=' ', max_length=100)),
('Area', models.CharField(blank=True, default=' ', max_length=100)),
('City', models.CharField(blank=True, default=' ', max_length=100)),
('Pincode', models.IntegerField(blank=True, default=0)),
('State', models.CharField(blank=True, default=' ', max_length=100)),
],
),
migrations.CreateModel(
name='Operation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Operation_Description', models.TextField()),
('Operation_Cost', models.IntegerField()),
('Day_of_Operation', models.DateTimeField()),
],
),
migrations.CreateModel(
name='Patient',
fields=[
('Title', models.CharField(choices=[('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Miss', 'Miss'), ('Master', 'Master')], max_length=6)),
('Family_Id_Display', models.IntegerField(blank=True, null=True)),
('Patient_Id', models.AutoField(primary_key=True, serialize=False)),
('First_Name', models.CharField(blank=True, max_length=100)),
('Middle_Name', models.CharField(blank=True, max_length=100)),
('Last_Name', models.CharField(blank=True, max_length=100)),
('Gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=1)),
('Address', models.CharField(blank=True, max_length=100)),
('Area', models.CharField(blank=True, max_length=100)),
('City', models.CharField(blank=True, max_length=100)),
('Pincode', models.IntegerField(blank=True)),
('State', models.CharField(blank=True, max_length=100)),
('Birth_Date', models.DateTimeField(blank=True)),
('Blood_Group', models.CharField(blank=True, choices=[('A+', 'A+'), ('B+', 'B+'), ('O+', 'O+'), ('A-', 'A-'), ('B-', 'B-'), ('O-', 'O-')], max_length=2)),
('Mobile1', models.IntegerField(validators=[django.core.validators.MinValueValidator(1000000000), django.core.validators.MaxValueValidator(9999999999)])),
('Mobile2', models.IntegerField(validators=[django.core.validators.MinValueValidator(1000000000), django.core.validators.MaxValueValidator(9999999999)])),
('Pending_Balance', models.IntegerField(blank=True)),
('Family_Balance', models.IntegerField(blank=True)),
('Last_Pay_Date', models.DateTimeField(blank=True, null=True)),
('Family', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='patient.Family')),
],
),
migrations.CreateModel(
name='Patient_List',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.AddField(
model_name='patient',
name='Patient_List',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='patient.Patient_List'),
),
]
|
11,374 | 930d8214de85ed6cdb33212101158ab1d6625b4d | #!/usr/bin/env python
u"""
compute_tide_corrections.py
Written by Tyler Sutterley (12/2020)
Calculates tidal elevations for correcting elevation or imagery data
Uses OTIS format tidal solutions provided by Ohio State University and ESR
http://volkov.oce.orst.edu/tides/region.html
https://www.esr.org/research/polar-tide-models/list-of-polar-tide-models/
ftp://ftp.esr.org/pub/datasets/tmd/
Global Tide Model (GOT) solutions provided by Richard Ray at GSFC
or Finite Element Solution (FES) models provided by AVISO
INPUTS:
x: x-coordinates in projection EPSG
y: y-coordinates in projection EPSG
delta_time: seconds since EPOCH
OPTIONS:
DIRECTORY: working data directory for tide models
MODEL: Tide model to use in correction
EPOCH: time period for calculating delta times
default: J2000 (seconds since 2000-01-01T00:00:00)
TYPE: input data type
drift: drift buoys or satellite/airborne altimetry (time per data point)
grid: spatial grids or images (single time for all data points)
TIME: time type if need to compute leap seconds to convert to UTC
GPS: leap seconds needed
TAI: leap seconds needed (TAI = GPS + 19 seconds)
UTC: no leap seconds needed
EPSG: input coordinate system
default: 3031 Polar Stereographic South, WGS84
METHOD: interpolation method
bilinear: quick bilinear interpolation
spline: scipy bivariate spline interpolation
linear, nearest: scipy regular grid interpolations
FILL_VALUE: output invalid value (default NaN)
PYTHON DEPENDENCIES:
numpy: Scientific Computing Tools For Python
https://numpy.org
https://numpy.org/doc/stable/user/numpy-for-matlab-users.html
scipy: Scientific Tools for Python
https://docs.scipy.org/doc/
netCDF4: Python interface to the netCDF C library
https://unidata.github.io/netcdf4-python/netCDF4/index.html
pyproj: Python interface to PROJ library
https://pypi.org/project/pyproj/
PROGRAM DEPENDENCIES:
time.py: utilities for calculating time operations
utilities: download and management utilities for syncing files
calc_astrol_longitudes.py: computes the basic astronomical mean longitudes
calc_delta_time.py: calculates difference between universal and dynamic time
convert_ll_xy.py: convert lat/lon points to and from projected coordinates
infer_minor_corrections.py: return corrections for minor constituents
load_constituent.py: loads parameters for a given tidal constituent
load_nodal_corrections.py: load the nodal corrections for tidal constituents
predict_tide.py: predict tides at single times using harmonic constants
predict_tide_drift.py: predict tidal elevations using harmonic constants
read_tide_model.py: extract tidal harmonic constants from OTIS tide models
read_netcdf_model.py: extract tidal harmonic constants from netcdf models
read_GOT_model.py: extract tidal harmonic constants from GSFC GOT models
read_FES_model.py: extract tidal harmonic constants from FES tide models
bilinear_interp.py: bilinear interpolation of data to coordinates
nearest_extrap.py: nearest-neighbor extrapolation of data to coordinates
UPDATE HISTORY:
Updated 12/2020: added valid data extrapolation with nearest_extrap
Updated 11/2020: added model constituents from TPXO9-atlas-v3
Updated 08/2020: using builtin time operations.
calculate difference in leap seconds from start of epoch
using conversion protocols following pyproj-2 updates
Updated 07/2020: added function docstrings, FES2014 and TPXO9-atlas-v2
use merged delta time files combining biannual, monthly and daily files
Updated 03/2020: added TYPE, TIME, FILL_VALUE and METHOD options
Written 03/2020
"""
from __future__ import print_function
import os
import pyproj
import datetime
import numpy as np
import pyTMD.time
from pyTMD.calc_delta_time import calc_delta_time
from pyTMD.infer_minor_corrections import infer_minor_corrections
from pyTMD.predict_tide import predict_tide
from pyTMD.predict_tide_drift import predict_tide_drift
from pyTMD.read_tide_model import extract_tidal_constants
from pyTMD.read_netcdf_model import extract_netcdf_constants
from pyTMD.read_GOT_model import extract_GOT_constants
from pyTMD.read_FES_model import extract_FES_constants
#-- PURPOSE: compute tides at points and times using tide model algorithms
def compute_tide_corrections(x, y, delta_time, DIRECTORY=None, MODEL=None,
EPSG=3031, EPOCH=(2000,1,1,0,0,0), TYPE='drift', TIME='UTC',
METHOD='spline', EXTRAPOLATE=False, FILL_VALUE=np.nan):
"""
Compute tides at points and times using tidal harmonics
Arguments
---------
x: x-coordinates in projection EPSG
y: y-coordinates in projection EPSG
delta_time: seconds since EPOCH
Keyword arguments
-----------------
DIRECTORY: working data directory for tide models
MODEL: Tide model to use in correction
EPOCH: time period for calculating delta times
default: J2000 (seconds since 2000-01-01T00:00:00)
TYPE: input data type
drift: drift buoys or satellite/airborne altimetry (time per data point)
grid: spatial grids or images (single time per image)
TIME: time type if need to compute leap seconds to convert to UTC
GPS: leap seconds needed
TAI: leap seconds needed (TAI = GPS + 19 seconds)
UTC: no leap seconds needed
EPSG: input coordinate system
default: 3031 Polar Stereographic South, WGS84
METHOD: interpolation method
bilinear: quick bilinear interpolation
spline: scipy bivariate spline interpolation
linear, nearest: scipy regular grid interpolations
FILL_VALUE: output invalid value (default NaN)
Returns
-------
tide: tidal elevation at coordinates and time in meters
"""
#-- select between tide models
if (MODEL == 'CATS0201'):
grid_file = os.path.join(DIRECTORY,'cats0201_tmd','grid_CATS')
model_file = os.path.join(DIRECTORY,'cats0201_tmd','h0_CATS02_01')
model_format = 'OTIS'
model_EPSG = '4326'
model_type = 'z'
elif (MODEL == 'CATS2008'):
grid_file = os.path.join(DIRECTORY,'CATS2008','grid_CATS2008')
model_file = os.path.join(DIRECTORY,'CATS2008','hf.CATS2008.out')
model_format = 'OTIS'
model_EPSG = 'CATS2008'
model_type = 'z'
elif (MODEL == 'CATS2008_load'):
grid_file = os.path.join(DIRECTORY,'CATS2008a_SPOTL_Load','grid_CATS2008a_opt')
model_file = os.path.join(DIRECTORY,'CATS2008a_SPOTL_Load','h_CATS2008a_SPOTL_load')
model_format = 'OTIS'
model_EPSG = 'CATS2008'
model_type = 'z'
elif (MODEL == 'TPXO9-atlas'):
model_directory = os.path.join(DIRECTORY,'TPXO9_atlas')
grid_file = 'grid_tpxo9_atlas.nc.gz'
model_files = ['h_q1_tpxo9_atlas_30.nc.gz','h_o1_tpxo9_atlas_30.nc.gz',
'h_p1_tpxo9_atlas_30.nc.gz','h_k1_tpxo9_atlas_30.nc.gz',
'h_n2_tpxo9_atlas_30.nc.gz','h_m2_tpxo9_atlas_30.nc.gz',
'h_s2_tpxo9_atlas_30.nc.gz','h_k2_tpxo9_atlas_30.nc.gz',
'h_m4_tpxo9_atlas_30.nc.gz','h_ms4_tpxo9_atlas_30.nc.gz',
'h_mn4_tpxo9_atlas_30.nc.gz','h_2n2_tpxo9_atlas_30.nc.gz']
model_format = 'netcdf'
model_type = 'z'
SCALE = 1.0/1000.0
elif (MODEL == 'TPXO9-atlas-v2'):
model_directory = os.path.join(DIRECTORY,'TPXO9_atlas_v2')
grid_file = 'grid_tpxo9_atlas_30_v2.nc.gz'
model_files = ['h_q1_tpxo9_atlas_30_v2.nc.gz','h_o1_tpxo9_atlas_30_v2.nc.gz',
'h_p1_tpxo9_atlas_30_v2.nc.gz','h_k1_tpxo9_atlas_30_v2.nc.gz',
'h_n2_tpxo9_atlas_30_v2.nc.gz','h_m2_tpxo9_atlas_30_v2.nc.gz',
'h_s2_tpxo9_atlas_30_v2.nc.gz','h_k2_tpxo9_atlas_30_v2.nc.gz',
'h_m4_tpxo9_atlas_30_v2.nc.gz','h_ms4_tpxo9_atlas_30_v2.nc.gz',
'h_mn4_tpxo9_atlas_30_v2.nc.gz','h_2n2_tpxo9_atlas_30_v2.nc.gz']
model_format = 'netcdf'
model_type = 'z'
SCALE = 1.0/1000.0
elif (MODEL == 'TPXO9-atlas-v3'):
model_directory = os.path.join(DIRECTORY,'TPXO9_atlas_v3')
grid_file = 'grid_tpxo9_atlas_30_v3.nc.gz'
model_files = ['h_q1_tpxo9_atlas_30_v3.nc.gz','h_o1_tpxo9_atlas_30_v3.nc.gz',
'h_p1_tpxo9_atlas_30_v3.nc.gz','h_k1_tpxo9_atlas_30_v3.nc.gz',
'h_n2_tpxo9_atlas_30_v3.nc.gz','h_m2_tpxo9_atlas_30_v3.nc.gz',
'h_s2_tpxo9_atlas_30_v3.nc.gz','h_k2_tpxo9_atlas_30_v3.nc.gz',
'h_m4_tpxo9_atlas_30_v3.nc.gz','h_ms4_tpxo9_atlas_30_v3.nc.gz',
'h_mn4_tpxo9_atlas_30_v3.nc.gz','h_2n2_tpxo9_atlas_30_v3.nc.gz',
'h_mf_tpxo9_atlas_30_v3.nc.gz','h_mm_tpxo9_atlas_30_v3.nc.gz']
model_format = 'netcdf'
TYPE = 'z'
SCALE = 1.0/1000.0
elif (MODEL == 'TPXO9.1'):
grid_file = os.path.join(DIRECTORY,'TPXO9.1','DATA','grid_tpxo9')
model_file = os.path.join(DIRECTORY,'TPXO9.1','DATA','h_tpxo9.v1')
model_format = 'OTIS'
model_EPSG = '4326'
model_type = 'z'
elif (MODEL == 'TPXO8-atlas'):
grid_file = os.path.join(DIRECTORY,'tpxo8_atlas','grid_tpxo8atlas_30_v1')
model_file = os.path.join(DIRECTORY,'tpxo8_atlas','hf.tpxo8_atlas_30_v1')
model_format = 'ATLAS'
model_EPSG = '4326'
model_type = 'z'
elif (MODEL == 'TPXO7.2'):
grid_file = os.path.join(DIRECTORY,'TPXO7.2_tmd','grid_tpxo7.2')
model_file = os.path.join(DIRECTORY,'TPXO7.2_tmd','h_tpxo7.2')
model_format = 'OTIS'
model_EPSG = '4326'
model_type = 'z'
elif (MODEL == 'TPXO7.2_load'):
grid_file = os.path.join(DIRECTORY,'TPXO7.2_load','grid_tpxo6.2')
model_file = os.path.join(DIRECTORY,'TPXO7.2_load','h_tpxo7.2_load')
model_format = 'OTIS'
model_EPSG = '4326'
model_type = 'z'
elif (MODEL == 'AODTM-5'):
grid_file = os.path.join(DIRECTORY,'aodtm5_tmd','grid_Arc5km')
model_file = os.path.join(DIRECTORY,'aodtm5_tmd','h0_Arc5km.oce')
model_format = 'OTIS'
model_EPSG = 'PSNorth'
model_type = 'z'
elif (MODEL == 'AOTIM-5'):
grid_file = os.path.join(DIRECTORY,'aotim5_tmd','grid_Arc5km')
model_file = os.path.join(DIRECTORY,'aotim5_tmd','h_Arc5km.oce')
model_format = 'OTIS'
model_EPSG = 'PSNorth'
model_type = 'z'
elif (MODEL == 'AOTIM-5-2018'):
grid_file = os.path.join(DIRECTORY,'Arc5km2018','grid_Arc5km2018')
model_file = os.path.join(DIRECTORY,'Arc5km2018','h_Arc5km2018')
model_format = 'OTIS'
model_EPSG = 'PSNorth'
model_type = 'z'
elif (MODEL == 'GOT4.7'):
model_directory = os.path.join(DIRECTORY,'GOT4.7','grids_oceantide')
model_files = ['q1.d.gz','o1.d.gz','p1.d.gz','k1.d.gz','n2.d.gz',
'm2.d.gz','s2.d.gz','k2.d.gz','s1.d.gz','m4.d.gz']
c = ['q1','o1','p1','k1','n2','m2','s2','k2','s1','m4']
model_format = 'GOT'
SCALE = 1.0/100.0
elif (MODEL == 'GOT4.7_load'):
model_directory = os.path.join(DIRECTORY,'GOT4.7','grids_loadtide')
model_files = ['q1load.d.gz','o1load.d.gz','p1load.d.gz','k1load.d.gz',
'n2load.d.gz','m2load.d.gz','s2load.d.gz','k2load.d.gz',
's1load.d.gz','m4load.d.gz']
c = ['q1','o1','p1','k1','n2','m2','s2','k2','s1','m4']
model_format = 'GOT'
SCALE = 1.0/1000.0
elif (MODEL == 'GOT4.8'):
model_directory = os.path.join(DIRECTORY,'got4.8','grids_oceantide')
model_files = ['q1.d.gz','o1.d.gz','p1.d.gz','k1.d.gz','n2.d.gz',
'm2.d.gz','s2.d.gz','k2.d.gz','s1.d.gz','m4.d.gz']
c = ['q1','o1','p1','k1','n2','m2','s2','k2','s1','m4']
model_format = 'GOT'
SCALE = 1.0/100.0
elif (MODEL == 'GOT4.8_load'):
model_directory = os.path.join(DIRECTORY,'got4.8','grids_loadtide')
model_files = ['q1load.d.gz','o1load.d.gz','p1load.d.gz','k1load.d.gz',
'n2load.d.gz','m2load.d.gz','s2load.d.gz','k2load.d.gz',
's1load.d.gz','m4load.d.gz']
c = ['q1','o1','p1','k1','n2','m2','s2','k2','s1','m4']
model_format = 'GOT'
SCALE = 1.0/1000.0
elif (MODEL == 'GOT4.10'):
model_directory = os.path.join(DIRECTORY,'GOT4.10c','grids_oceantide')
model_files = ['q1.d.gz','o1.d.gz','p1.d.gz','k1.d.gz','n2.d.gz',
'm2.d.gz','s2.d.gz','k2.d.gz','s1.d.gz','m4.d.gz']
c = ['q1','o1','p1','k1','n2','m2','s2','k2','s1','m4']
model_format = 'GOT'
SCALE = 1.0/100.0
elif (MODEL == 'GOT4.10_load'):
model_directory = os.path.join(DIRECTORY,'GOT4.10c','grids_loadtide')
model_files = ['q1load.d.gz','o1load.d.gz','p1load.d.gz','k1load.d.gz',
'n2load.d.gz','m2load.d.gz','s2load.d.gz','k2load.d.gz',
's1load.d.gz','m4load.d.gz']
c = ['q1','o1','p1','k1','n2','m2','s2','k2','s1','m4']
model_format = 'GOT'
SCALE = 1.0/1000.0
elif (MODEL == 'FES2014'):
model_directory = os.path.join(DIRECTORY,'fes2014','ocean_tide')
model_files = ['2n2.nc.gz','eps2.nc.gz','j1.nc.gz','k1.nc.gz',
'k2.nc.gz','l2.nc.gz','la2.nc.gz','m2.nc.gz','m3.nc.gz','m4.nc.gz',
'm6.nc.gz','m8.nc.gz','mf.nc.gz','mks2.nc.gz','mm.nc.gz',
'mn4.nc.gz','ms4.nc.gz','msf.nc.gz','msqm.nc.gz','mtm.nc.gz',
'mu2.nc.gz','n2.nc.gz','n4.nc.gz','nu2.nc.gz','o1.nc.gz','p1.nc.gz',
'q1.nc.gz','r2.nc.gz','s1.nc.gz','s2.nc.gz','s4.nc.gz','sa.nc.gz',
'ssa.nc.gz','t2.nc.gz']
c = ['2n2','eps2','j1','k1','k2','l2','lambda2','m2','m3','m4','m6','m8',
'mf','mks2','mm','mn4','ms4','msf','msqm','mtm','mu2','n2','n4',
'nu2','o1','p1','q1','r2','s1','s2','s4','sa','ssa','t2']
model_format = 'FES'
TYPE = 'z'
SCALE = 1.0/100.0
elif (MODEL == 'FES2014_load'):
model_directory = os.path.join(DIRECTORY,'fes2014','load_tide')
model_files = ['2n2.nc.gz','eps2.nc.gz','j1.nc.gz','k1.nc.gz',
'k2.nc.gz','l2.nc.gz','la2.nc.gz','m2.nc.gz','m3.nc.gz','m4.nc.gz',
'm6.nc.gz','m8.nc.gz','mf.nc.gz','mks2.nc.gz','mm.nc.gz',
'mn4.nc.gz','ms4.nc.gz','msf.nc.gz','msqm.nc.gz','mtm.nc.gz',
'mu2.nc.gz','n2.nc.gz','n4.nc.gz','nu2.nc.gz','o1.nc.gz','p1.nc.gz',
'q1.nc.gz','r2.nc.gz','s1.nc.gz','s2.nc.gz','s4.nc.gz','sa.nc.gz',
'ssa.nc.gz','t2.nc.gz']
c = ['2n2','eps2','j1','k1','k2','l2','lambda2','m2','m3','m4','m6',
'm8','mf','mks2','mm','mn4','ms4','msf','msqm','mtm','mu2','n2',
'n4','nu2','o1','p1','q1','r2','s1','s2','s4','sa','ssa','t2']
model_format = 'FES'
model_type = 'z'
SCALE = 1.0/100.0
else:
raise Exception("Unlisted tide model")
#-- converting x,y from EPSG to latitude/longitude
crs1 = pyproj.CRS.from_string("epsg:{0:d}".format(EPSG))
crs2 = pyproj.CRS.from_string("epsg:{0:d}".format(4326))
transformer = pyproj.Transformer.from_crs(crs1, crs2, always_xy=True)
lon,lat = transformer.transform(x.flatten(), y.flatten())
#-- assert delta time is an array
delta_time = np.atleast_1d(delta_time)
#-- calculate leap seconds if specified
if (TIME.upper() == 'GPS'):
GPS_Epoch_Time = pyTMD.time.convert_delta_time(0, epoch1=EPOCH,
epoch2=(1980,1,6,0,0,0), scale=1.0)
GPS_Time = pyTMD.time.convert_delta_time(delta_time, epoch1=EPOCH,
epoch2=(1980,1,6,0,0,0), scale=1.0)
#-- calculate difference in leap seconds from start of epoch
leap_seconds = pyTMD.time.count_leap_seconds(GPS_Time) - \
pyTMD.time.count_leap_seconds(np.atleast_1d(GPS_Epoch_Time))
elif (TIME.upper() == 'TAI'):
#-- TAI time is ahead of GPS time by 19 seconds
GPS_Epoch_Time = pyTMD.time.convert_delta_time(-19.0, epoch1=EPOCH,
epoch2=(1980,1,6,0,0,0), scale=1.0)
GPS_Time = pyTMD.time.convert_delta_time(delta_time-19.0, epoch1=EPOCH,
epoch2=(1980,1,6,0,0,0), scale=1.0)
#-- calculate difference in leap seconds from start of epoch
leap_seconds = pyTMD.time.count_leap_seconds(GPS_Time) - \
pyTMD.time.count_leap_seconds(np.atleast_1d(GPS_Epoch_Time))
else:
leap_seconds = 0.0
#-- convert time to days relative to Jan 1, 1992 (48622mjd)
t = pyTMD.time.convert_delta_time(delta_time - leap_seconds, epoch1=EPOCH,
epoch2=(1992,1,1,0,0,0), scale=(1.0/86400.0))
#-- read tidal constants and interpolate to grid points
if model_format in ('OTIS','ATLAS'):
amp,ph,D,c = extract_tidal_constants(lon, lat, grid_file, model_file,
model_EPSG, TYPE=model_type, METHOD=METHOD, EXTRAPOLATE=EXTRAPOLATE,
GRID=model_format)
deltat = np.zeros_like(t)
elif (model_format == 'netcdf'):
amp,ph,D,c = extract_netcdf_constants(lon, lat, model_directory,
grid_file, model_files, TYPE=model_type, METHOD=METHOD,
EXTRAPOLATE=EXTRAPOLATE, SCALE=SCALE)
deltat = np.zeros_like(t)
elif (model_format == 'GOT'):
amp,ph = extract_GOT_constants(lon, lat, model_directory, model_files,
METHOD=METHOD, EXTRAPOLATE=EXTRAPOLATE, SCALE=SCALE)
#-- interpolate delta times from calendar dates to tide time
delta_file = pyTMD.utilities.get_data_path(['data','merged_deltat.data'])
deltat = calc_delta_time(delta_file, t)
elif (model_format == 'FES'):
amp,ph = extract_FES_constants(lon, lat, model_directory, model_files,
TYPE=model_type, VERSION=MODEL, METHOD=METHOD,
EXTRAPOLATE=EXTRAPOLATE, SCALE=SCALE)
#-- interpolate delta times from calendar dates to tide time
delta_file = pyTMD.utilities.get_data_path(['data','merged_deltat.data'])
deltat = calc_delta_time(delta_file, t)
#-- calculate complex phase in radians for Euler's
cph = -1j*ph*np.pi/180.0
#-- calculate constituent oscillation
hc = amp*np.exp(cph)
#-- predict tidal elevations at time and infer minor corrections
if (TYPE.lower() == 'grid'):
ny,nx = np.shape(x); nt = len(t)
tide = np.ma.zeros((ny,nx,nt),fill_value=FILL_VALUE)
tide.mask = np.zeros((ny,nx,nt),dtype=np.bool)
for i in range(nt):
TIDE = predict_tide(t[i], hc, c,
DELTAT=deltat[i], CORRECTIONS=model_format)
MINOR = infer_minor_corrections(t[i], hc, c,
DELTAT=deltat[i], CORRECTIONS=model_format)
#-- add major and minor components and reform grid
tide[:,:,i] = np.reshape((TIDE+MINOR), (ny,nx))
tide.mask[:,:,i] = np.reshape((TIDE.mask | MINOR.mask), (ny,nx))
else:
npts = len(t)
tide = np.ma.zeros((npts), fill_value=FILL_VALUE)
tide.mask = np.any(hc.mask,axis=1)
tide.data[:] = predict_tide_drift(t, hc, c,
DELTAT=deltat, CORRECTIONS=model_format)
minor = infer_minor_corrections(t, hc, c,
DELTAT=deltat, CORRECTIONS=model_format)
tide.data[:] += minor.data[:]
#-- replace invalid values with fill value
tide.data[tide.mask] = tide.fill_value
#-- return the tide correction
return tide
|
11,375 | 817a26808d22f7d7f195d678a72805aa7fe64924 | import io
import pathlib
import h5py
import PIL.Image
import numpy as np
from torch.utils.data import Dataset
from tqdm import tqdm
# For high performance PIL operations use
# pillow-simd instead of pillow
# https://python-pillow.org/pillow-perf/
# https://github.com/uploadcare/pillow-simd
import pkg_resources
try:
pkg_resources.get_distribution("Pillow-SIMD")
except pkg_resources.DistributionNotFound:
import warnings
warnings.warn("\033[93mPillow-SIMD not installed. PIL operations could be faster using SIMD/AVX instructions https://github.com/uploadcare/pillow-simd\033[0m")
def make_dataset(hf):
samples = []
for label, class_ in enumerate(tqdm(sorted(hf), leave=False)):
for image in sorted(hf[class_]):
samples.append( (hf[class_][image].name, label) )
return samples
def class_to_idx(hf):
class_to_idx = {}
for label, class_ in enumerate(sorted(hf)):
class_to_idx[class_] = label
return class_to_idx
def array_loader(array):
return PIL.Image.fromarray(array)
def binary_loader(array):
img_bytes = io.BytesIO(array)
return PIL.Image.open(img_bytes).convert('RGB')
mode_to_loader = {
"binary": binary_loader,
"array": array_loader,
}
class ImageHDF5Dataset(Dataset):
def __init__(self, h5file,
transform=None, target_transform=None):
super(ImageHDF5Dataset, self).__init__()
self.h5file = pathlib.Path(h5file)
indexfile = self.h5file.with_suffix('.idx.npy')
with h5py.File(h5file, 'r') as hf:
# TODO remove next two lines after adding mode to existing files
if 'mode' not in hf.attrs:
self.loader = array_loader
else:
self.loader = mode_to_loader[hf.attrs['mode']]
self.transform = transform
self.target_transform = target_transform
# Compile image & label list
if indexfile.exists():
self.samples = [(x, int(y)) for x, y in np.load(indexfile)]
else:
print("Compiling dataset indices")
with h5py.File(self.h5file, 'r') as hf:
self.samples = make_dataset(hf)
np.save(indexfile, self.samples)
# self.class_to_idx = class_to_idx(hf)
def __len__(self):
return len(self.samples)
def __getitem__(self, index):
# File descriptor must be opened here because h5 does
# support processing inheriting the file descriptor
# https://gist.github.com/bkj/f448025fdef08c0609029489fa26ea2a
path, target = self.samples[index]
with h5py.File(self.h5file, 'r') as hf:
sample = self.loader(hf[path][()])
if self.transform is not None:
sample = self.transform(sample)
if self.target_transform is not None:
target = self.target_transform(target)
return sample, target
# class ImageHDF5Dataset(Dataset):
# def __init__(self, h5file, loader=PIL_loader,
# transform=None, target_transform=None):
# super(ImageHDF5Dataset, self).__init__()
# h5file = pathlib.Path(h5file)
# indexfile = h5file.with_suffix('.idx.npy')
# self.hf = h5py.File(h5file, 'r')
# self.loader = loader
# self.transform = transform
# self.target_transform = target_transform
# # Compile image & label list
# if indexfile.exists():
# self.samples = [(x, int(y)) for x, y in np.load(indexfile)]
# else:
# print("Compiling dataset indices")
# self.samples = make_dataset(self.hf)
# np.save(indexfile, self.samples)
# self.class_to_idx = class_to_idx(self.hf)
# def __len__(self):
# return len(self.samples)
# def __getitem__(self, index):
# path, target = self.samples[index]
# sample = self.loader(self.hf[path].value)
# if self.transform is not None:
# sample = self.transform(sample)
# if self.target_transform is not None:
# target = self.target_transform(target)
# return sample, target
# def __del__(self):
# if hasattr(self, 'hf'):
# self.hf.close()
|
11,376 | 0263a23c969bc5e2a5b9b0bf6acc26370586cf17 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from dblogic import dictionary_writer, dictionary_report_naming_miner, dictionary_report_parameters_miner, dictionary_report_name_getter, update_report_local_name, dictionary_report_parameters_getter, update_param_local_name
def dictionary_refresh(lang_id):
report_names_translist = dictionary_report_naming_miner(lang_id)
report_parameters_translist = dictionary_report_parameters_miner(lang_id)
for item in report_names_translist:
dictionary_writer(item['lang_id'], item['datatype'], item['original'], item['translation'])
for item in report_parameters_translist:
dictionary_writer(item['lang_id'], item['datatype'], item['original'], item['translation'])
def report_names_autotranslate(lang_id):
report_missed_translations = dictionary_report_name_getter(lang_id)
for report in report_missed_translations:
update_report_local_name(report['report_id'], report['lang_id'], report['dictionary_answer'])
def report_parameters_autotranslate(lang_id):
report_missed_translations = dictionary_report_parameters_getter(lang_id)
for parameter in report_missed_translations:
update_param_local_name(parameter['translated_item_id'], parameter['dictionary_answer'])
|
11,377 | da7b78bdcd251d474c033fb2eda1653b7adf55a6 | from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
admin.autodiscover()
from rec import views
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.start),
url(r'^(?P<name>\d+)/$',views.home)
url(r'^(?P<name>\d+)/movie/$',views.movie)
)
|
11,378 | ca123533a5cc88a986deabacb41cff00492ffb1c | # 一般,回归问题可以使用恒等函数,二元分类问题可以使用sigmoid函数,
# 多元分类问题可以使用softmax函数
# --------------------------------------------------
# 机器学习的问题大致可以分为分类问题和回归问题。分类问题是数据属于哪一个类别的问题。
# 比如,区分图像中的人是男性还是女性的问题就是分类问题。
# 而回归问题是根据某个输入预测一个(连续的)数值的问题。
# 比如,根据一个人的图像预测这个人的体重的问题就是回归问题(类似“57.4kg”这样的预测)
|
11,379 | 2c81dbac183843e63a2894afe4ab0a56f18a1d1f | """
Copyright 2019, ETH Zurich
This file is part of L3C-PyTorch.
L3C-PyTorch 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
any later version.
L3C-PyTorch 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 L3C-PyTorch. If not, see <https://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------
NOTE: Needs PyTorch 1.0 or newer, as the C++ code relies on that API!
Depending on the environment variable COMPILE_CUDA, compiles the torchac_backend with or
without support for CUDA, into a module called torchac_backend_gpu or torchac_backend_cpu.
COMPILE_CUDA = auto is equal to yes if one of the supported combinations of nvcc and gcc is found (see
_supported_compilers_available).
COMPILE_CUDA = force means compile with CUDA, even if it is not one of the supported combinations
COMPILE_CUDA = no means no CUDA.
The only difference between the CUDA and non-CUDA versions is: With CUDA, _get_uint16_cdf from torchac is done with a
simple/non-optimized CUDA kernel (torchac_kernel.cu), which has one benefit: we can directly write into shared memory!
This saves an expensive copying step from GPU to CPU.
Flags read by this script:
COMPILE_CUDA=[auto|force|no]
"""
import sys
import re
import subprocess
from setuptools import setup
from distutils.version import LooseVersion
from torch.utils.cpp_extension import CppExtension, BuildExtension, CUDAExtension
import os
MODULE_BASE_NAME = 'torchac_backend'
def prefixed(prefix, l):
ps = [os.path.join(prefix, el) for el in l]
for p in ps:
if not os.path.isfile(p):
raise FileNotFoundError(p)
return ps
def compile_ext(cuda_support):
print('Compiling, cuda_support={}'.format(cuda_support))
ext_module = get_extension(cuda_support)
setup(name=ext_module.name,
version='1.0.0',
ext_modules=[ext_module],
extra_compile_args=['-mmacosx-version-min=10.9'],
cmdclass={'build_ext': BuildExtension})
def get_extension(cuda_support):
# dir of this file
setup_dir = os.path.dirname(os.path.realpath(__file__))
# Where the cpp and cu files are
prefix = os.path.join(setup_dir, MODULE_BASE_NAME)
if not os.path.isdir(prefix):
raise ValueError('Did not find backend foler: {}'.format(prefix))
if cuda_support:
nvcc_avaible, nvcc_version = supported_nvcc_available()
if not nvcc_avaible:
print(_bold_warn_str('***WARN') + ': Found untested nvcc {}'.format(nvcc_version))
return CUDAExtension(
MODULE_BASE_NAME + '_gpu',
prefixed(prefix, ['torchac.cpp', 'torchac_kernel.cu']),
define_macros=[('COMPILE_CUDA', '1')])
else:
return CppExtension(
MODULE_BASE_NAME + '_cpu',
prefixed(prefix, ['torchac.cpp']))
# TODO:
# Add further supported version as specified in readme
def _supported_compilers_available():
"""
To see an up-to-date list of tested combinations of GCC and NVCC, see the README
"""
return _supported_gcc_available()[0] and supported_nvcc_available()[0]
def _supported_gcc_available():
v = _get_version(['gcc', '-v'], r'version (.*?)\s+')
return LooseVersion('6.0') > LooseVersion(v) >= LooseVersion('5.0'), v
def supported_nvcc_available():
v = _get_version(['nvcc', '-V'], 'release (.*?),')
if v is None:
return False, 'nvcc unavailable!'
return LooseVersion(v) >= LooseVersion('9.0'), v
def _get_version(cmd, regex):
try:
otp = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode()
if len(otp.strip()) == 0:
raise ValueError('No output')
m = re.search(regex, otp)
if not m:
raise ValueError('Regex does not match output:\n{}'.format(otp))
return m.group(1)
except FileNotFoundError:
return None
def _bold_warn_str(s):
return '\x1b[91m\x1b[1m' + s + '\x1b[0m'
def _assert_torch_version_sufficient():
import torch
if LooseVersion(torch.__version__) >= LooseVersion('1.0'):
return
print(_bold_warn_str('Error:'), 'Need PyTorch version >= 1.0, found {}'.format(torch.__version__))
sys.exit(1)
def main():
_assert_torch_version_sufficient()
cuda_flag = os.environ.get('COMPILE_CUDA', 'no')
if cuda_flag == 'auto':
cuda_support = _supported_compilers_available()
print('Found CUDA supported:', cuda_support)
elif cuda_flag == 'force':
cuda_support = True
elif cuda_flag == 'no':
cuda_support = False
else:
raise ValueError('COMPILE_CUDA must be in (auto, force, no), got {}'.format(cuda_flag))
compile_ext(cuda_support)
if __name__ == '__main__':
main()
|
11,380 | 1078c15742dec11b673747f040b79716ab362b4f | __author__ = 'nikita_kartashov'
def split_to_function(input_string, split_string, f, strip_string=None):
"""
Splits the strings, then strips every component, then calls a function on them
:param input_string: the string to be processed
:param split_string: characters to split on
:param f: function to be applied
:param strip_string: characters to strip
:return: resulting map object after the performed operations
"""
def inner_split(s):
"""
Splits the string on *split_string* characters
:param s: the string to be split
:return: list of split parts
"""
return s.split(split_string)
def inner_strip(s):
"""
Strips the string from *strip_string* characters
:param s: the string to be strip
:return: stripped string
"""
if strip_string:
return s.strip(strip_string)
return s.strip()
def inner_map_function(s):
"""
First applies stripping function then the function provided
:param s: the string the processed
:return: the result of the applied function
"""
return f(inner_strip(s))
return map(inner_map_function, inner_split(input_string)) |
11,381 | a0cabc6315b4070dc7dd98ea14786976ccd3f4ca | # -*- coding: utf-8 -*-
# qualify_textgrid.py - usage: python qualify_textgrid src_file[src_root] [timeit]
# to validate the format of a textgrid
# or to calculate the sum time of text in respectively categories
# author: Xiao Yang <xiaoyang0117@gmail.com>
# date: 2016.02.16
import os
import sys
import re
import codecs
from itertools import cycle
import chardet
RULES_PATTERNS = (
(re.compile('^([1-4])?(?(1)(?P<text>.+)|$)', re.UNICODE), lambda x: x.group('text') , u'错误1:第{lineno}行不是以特定数字开始或只包含数字,文本内容为“{text}”'),
(re.compile('^(\D+)$'), lambda x: re.sub('\[[SNTPsntp]\]', '', x.group(0)), u'错误2:第{lineno}行除文本开始处外另包含数字,文本内容为“{text}”'),
(re.compile('((?!\[\w\]).)*$', re.UNICODE), lambda x: x.group(0), u'错误3:第{lineno}行噪音符号标识错误,包含非SNTP字符,文本内容为"{text}"'),
(re.compile(u'((?![【】]).)*$', re.UNICODE), lambda x: x.group(0), u'错误4:第{lineno}行包含全角括号,文本内容为"{text}"'),
(re.compile('(.{3,25})$', re.UNICODE), lambda x: True, u'错误5:第{lineno}行文本长度小于3或大于25,文本内容为"{text}"'),
)
TEXT_KEY = 'text'
TEXT_CATEGORY_PARSER = re.compile('^(?P<category>[1-4])\D.*', flags=re.UNICODE)
MARKS_MEANING = {
'1': '1-',
'2': '2-',
'3': '3-',
'4': '4-'
}
logger = None
time_logger = None
def setup(target):
global logger
global time_logger
if os.path.isdir(target):
if target.endswith('\\'):
target = target[:-1]
logfile = os.path.join(target, os.path.basename(target)+'.log')
timelog = os.path.join(target, 'duration.log')
elif os.path.isfile(target):
logfile = target + '.log'
timelog = target + '_duration.log'
logger = open(logfile, 'w')
time_logger = open(timelog, 'w')
def teardown():
logger.close()
time_logger.close()
def loginfo(msg, stdout=False, timelog=False):
if stdout:
print(msg)
logger.write((msg+os.linesep).encode('utf-8'))
if timelog:
logtime(msg) #syntax sugar
def logtime(msg, stdout=False):
if stdout:
print(msg)
time_logger.write((msg+os.linesep).encode('utf-8'))
class CycleIterator(object):
""" a wrapper for the itertools.cycle """
def __init__(self, iterable):
super(CycleIterator, self).__init__()
self.iterable = iterable
self.iterator = cycle(iterable)
self.value = None
def head(self):
return self.iterable[0]
def tail(self):
return self.iterable[-1]
def next(self):
self.value = self.iterator.next()
return self.value
def end(self):
return self.value == self.tail()
# to loop from the begining
def reset(self):
self.iterator = cycle(self.iterable)
def index(self, i):
return self.iterable[i]
class TextgridParser(object):
"""translate the textgrid into a dict"""
CODINGS = (
('utf-8-sig', (codecs.BOM_UTF8,)),
('utf-16', (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)),
('utf-32', (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)),
)
# for textgrid header
HEADER_PATTERN = (
re.compile('xmin = (?P<start>[\d\.]+)\s*xmax = (?P<end>[\d\.]+)\s*tiers\? <exists>'),
lambda x: float(x.group('end')) - float(x.group('start')),
)
BLOCK_PATTERNS = (
(re.compile('^\s*intervals \[(?P<slice>\d+)\]:'), 'slice', int),
(re.compile('^\s*xmin = (?P<xmin>[\d\.]+)'), 'xmin', float),
(re.compile('^\s*xmax = (?P<xmax>[\d\.]+)'), 'xmax', float),
(re.compile('^\s*text = "(?P<text>.*)"'), 'text', str),
)
# for a special case that a text has multiple lines
MULTILINES_PATTERN = (
(re.compile('^\s*text = "(?P<text>.*)'), 'text', str),
(re.compile('^(?P<text>.*)$'), 'text', str), # to adapt the new line
(re.compile('^(?P<text>.*)"\s*$'), 'text', str),
)
PATTERN_KEYS = ('pattern', 'key', 'type')
def __init__(self, coding='utf-8'):
super(TextgridParser, self).__init__()
self.default_coding = coding
self.intervals = []
self.original_duration_sum = 0
def reset(self):
self.intervals = []
def read(self, filename):
self.filename = filename
with open(filename, 'rb') as f:
raw_data = f.read()
# self.coding = self.code_det(content[0:10])
self.coding = chardet.detect(raw_data)['encoding']
try:
self.content = raw_data.decode(self.coding).encode(self.default_coding)
self.lines = self.content.splitlines()
except UnicodeError, e:
loginfo(u'>>文件:{filename}'.format(filename=self.filename), stdout=True)
loginfo(u'解码时发生错误,请选择合适的文本编辑器,并以utf-8编码格式保存后,再运行此程序', stdout=True)
loginfo('')
raise IOError
def code_det(self, headline, default='utf-8'):
for enc,boms in TextgridParser.CODINGS:
if any(headline.startswith(bom) for bom in boms):
return enc
return default
def pack(self, keys, tuples):
package = []
for vals in tuples:
package.append({ keys[i]:vals[i] for i in range(len(keys)) })
return package
def update(self, interval, item_pattern, line, append_mode=False):
ip = item_pattern
if append_mode:
# only for text
interval[ip['key']] += ip['type'](ip['pattern'].match(line).group(ip['key']))
else:
interval.update({ ip['key']: ip['type'](ip['pattern'].match(line).group(ip['key'])) })
return interval
def match(self, item_pattern, line):
return item_pattern['pattern'].match(line)
def search(self, parser, fn):
return fn(parser.search(self.content))
def parse(self):
print(u'正在解析{filename}...'.format(filename=self.filename))
loginfo(u'>>文件:%s' % self.filename)
original_duration = self.search(*TextgridParser.HEADER_PATTERN)
self.original_duration_sum += original_duration
logtime(u'>>文件:%s\t 原始语音时长为%f秒' % (self.filename, original_duration))
lineno = 0
interval = {}
APPEND_MODE = False
self.reset()
bp_iter = CycleIterator(self.pack(TextgridParser.PATTERN_KEYS, TextgridParser.BLOCK_PATTERNS))
mp_iter = CycleIterator(self.pack(TextgridParser.PATTERN_KEYS, TextgridParser.MULTILINES_PATTERN))
block_begining = bp_iter.head()
item_pattern = bp_iter.next()
for line in self.lines:
lineno += 1
# reset the block parsing once the line matched the begining pattern
if self.match(block_begining, line):
# self.update(interval, block_begining, line)
# not the start actually, exception occured in parsing last block
if item_pattern != block_begining:
loginfo(u'错误:无法解析第%d行,不是textgrid标准格式,已跳过' % (lineno-1), stdout=True) # last line instead of the current
interval = {}
APPEND_MODE = False
bp_iter.reset()
item_pattern = bp_iter.next()
# when a text existed in multiple lines
elif APPEND_MODE:
if self.match(mp_iter.tail(), line): # match the pattern of end line
self.update(interval, mp_iter.tail(), line, APPEND_MODE)
interval['lineno'] = lineno
self.intervals.append(interval) # block ends
interval = {}
item_pattern = bp_iter.next() # loop to the begining
APPEND_MODE = False
# 2. block ending
else:
# append the middle part of the text
self.update(interval, mp_iter.index(1), line, APPEND_MODE)
# match the item in sequence
if self.match(item_pattern, line):
self.update(interval, item_pattern, line)
# if the end of the block was matched
if bp_iter.end():
interval['lineno'] = lineno
self.intervals.append(interval)
interval = {}
# loop to the begining
item_pattern = bp_iter.next()
# 1. block ending
# match the begining of multi-lines text instead of a single line
elif self.match(mp_iter.head(), line):
self.update(interval, mp_iter.head(), line)
APPEND_MODE = True
def validate(intervals, quiet=False):
validated = []
error_no = 0
if not quiet:
print(u'正在验证...')
for interval in intervals:
legal = True # to append legal textgrid to the list
text = interval[TEXT_KEY].decode('utf-8')
if text:
for rp,fn,msg in RULES_PATTERNS:
result = rp.match(text)
if result:
text = fn(result)
else:
if not quiet:
loginfo(msg.format(lineno=interval['lineno'], text=interval['text'].decode('utf-8')))
legal = False
error_no += 1
break
else:
legal = False
if legal:
validated.append(interval)
if not quiet:
print(u'验证完成,检测到%d个错误' % error_no)
if error_no == 0:
loginfo(u'Succeed')
else:
loginfo(u'共%d个错误被检测到' % error_no)
loginfo('') # extra space line
return validated
def timeit(intervals, title=None):
assoeted_intervals = {}
for interval in intervals:
try:
# assume it was validated before
category = TEXT_CATEGORY_PARSER.match(interval[TEXT_KEY].decode('utf-8')).group('category')
time_len = interval['xmax'] - interval['xmin']
if time_len < 0:
logtime(u'错误: 在第%d行检测到xmax的值大于xmin值' % interval['lineno'], stdout=True)
else:
assoeted_intervals[category] += time_len
except KeyError, e:
assoeted_intervals[category] = time_len
except AttributeError, e:
continue
# print('error: did not validate the textgrid before calculating the time') # for debugging
# sys.exit(0)
print_duration(assoeted_intervals, title=title)
return assoeted_intervals
def timestat(assoeted_duration, glob_duration):
for key, val in assoeted_duration.items():
try:
glob_duration[key] += val
except KeyError, e:
glob_duration[key] = val
TIME_UNIT = {
's':(1, u'秒'),
'm':(60.0, u'分'),
'h':(3600.0, u'小时')
}
def print_duration(assoeted_duration, unit='s', title=None):
if title:
logtime(title)
try:
divider, unit_display = TIME_UNIT[unit]
except KeyError, e:
print('error: unkown choice for unit') #for debugging
sys.exit(1)
try:
for key, val in assoeted_duration.items():
logtime(u'%s时长为 %f%s' % (MARKS_MEANING[key], val/divider, unit_display), stdout=True)
except KeyError, e:
print('error: unsupported marks included')
logtime('') # extra line spaces for ending of files
SUM_DURATION = {}
VALI_DURATION = {}
def qualify(src_file, _):
tp.read(src_file)
tp.parse()
all_durations = timeit(tp.intervals, title=u'>>各端总时长:')
validated = validate(tp.intervals)
validated_durations = timeit(validated, title=u'>>各端有效时长:')
# TODO: refactor here
timestat(all_durations, SUM_DURATION)
timestat(validated_durations, VALI_DURATION)
def traverse(src_dir, dst_dir, fn, target='.txt'):
for dirpath, dirnames, filenames in os.walk(src_dir):
for filename in filenames:
if filename.endswith(target):
try:
src_file = os.path.join(dirpath, filename)
src_dir_len = len(src_dir) if src_dir.endswith(os.sep) else len(src_dir)+1
dst_file = os.path.join(dst_dir, src_file[src_dir_len:]) # should not use replace
fn(src_file, dst_file)
except Exception as e:
print e
print("Unable to process %s" % src_file)
def main():
file_or_dir = sys.argv[1]
setup(file_or_dir)
file_or_dir = unicode(file_or_dir, 'gb2312')
if os.path.isdir(file_or_dir):
traverse(file_or_dir, '', qualify, target=('.textgrid', '.TextGrid'))
logtime(u'>>文件夹%s 内统计的总时长为\t 原始数据总时长为%f小时' % (file_or_dir, tp.original_duration_sum/3600.0), stdout=True)
logtime(u'>>各端总时长:', stdout=True)
print_duration(SUM_DURATION, unit='h')
logtime(u'>>各端有效时长:', stdout=True)
print_duration(VALI_DURATION, unit='h')
elif os.path.isfile(file_or_dir):
qualify(file_or_dir, '')
else:
print(u"指定的文件或目录不存在")
teardown()
if __name__ == '__main__':
tp = TextgridParser() # to avoid initializing multiple times
main() |
11,382 | 6193c7945a8ef77df00cce322024db64605514f2 | from thunder.model import Base
class User(Base):
def __init__(self):
Base.__init__(self)
self.tablename = 'users'
class Image(Base):
def __init__(self):
Base.__init__(self)
self.tablename = 'images'
|
11,383 | 7eec75c76e3001107db5e5ffde0c6fbdaab48b93 | #!/usr/bin/env python
test = None
|
11,384 | f7c595237bcf563256f70ffba0f87e3b75f482aa | # Copyright (c) 2015 Cloudbase Solutions SRL
# 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 os
from unittest import mock
import ddt
from oslo_concurrency import processutils
from oslo_config import cfg
from manila import exception
from manila.share import configuration
from manila.share.drivers import service_instance as generic_service_instance
from manila.share.drivers.windows import service_instance
from manila.share.drivers.windows import windows_utils
from manila import test
CONF = cfg.CONF
CONF.import_opt('driver_handles_share_servers',
'manila.share.driver')
CONF.register_opts(generic_service_instance.common_opts)
serv_mgr_cls = service_instance.WindowsServiceInstanceManager
generic_serv_mgr_cls = generic_service_instance.ServiceInstanceManager
@ddt.ddt
class WindowsServiceInstanceManagerTestCase(test.TestCase):
_FAKE_SERVER = {'ip': mock.sentinel.ip,
'instance_id': mock.sentinel.instance_id}
@mock.patch.object(windows_utils, 'WindowsUtils')
@mock.patch.object(serv_mgr_cls, '_check_auth_mode')
def setUp(self, mock_check_auth, mock_utils_cls):
self.flags(service_instance_user=mock.sentinel.username)
self._remote_execute = mock.Mock()
fake_conf = configuration.Configuration(None)
self._mgr = serv_mgr_cls(remote_execute=self._remote_execute,
driver_config=fake_conf)
self._windows_utils = mock_utils_cls.return_value
super(WindowsServiceInstanceManagerTestCase, self).setUp()
@ddt.data({},
{'use_cert_auth': False},
{'use_cert_auth': False, 'valid_pass_complexity': False},
{'certs_exist': False})
@mock.patch('os.path.exists')
@mock.patch.object(serv_mgr_cls, '_check_password_complexity')
@ddt.unpack
def test_check_auth_mode(self, mock_check_complexity, mock_path_exists,
use_cert_auth=True, certs_exist=True,
valid_pass_complexity=True):
self.flags(service_instance_password=mock.sentinel.password)
self._mgr._cert_pem_path = mock.sentinel.cert_path
self._mgr._cert_key_pem_path = mock.sentinel.key_path
mock_path_exists.return_value = certs_exist
mock_check_complexity.return_value = valid_pass_complexity
self._mgr._use_cert_auth = use_cert_auth
invalid_auth = ((use_cert_auth and not certs_exist)
or not valid_pass_complexity)
if invalid_auth:
self.assertRaises(exception.ServiceInstanceException,
self._mgr._check_auth_mode)
else:
self._mgr._check_auth_mode()
if not use_cert_auth:
mock_check_complexity.assert_called_once_with(
str(mock.sentinel.password))
@ddt.data(False, True)
def test_get_auth_info(self, use_cert_auth):
self._mgr._use_cert_auth = use_cert_auth
self._mgr._cert_pem_path = mock.sentinel.cert_path
self._mgr._cert_key_pem_path = mock.sentinel.key_path
auth_info = self._mgr._get_auth_info()
expected_auth_info = {'use_cert_auth': use_cert_auth}
if use_cert_auth:
expected_auth_info.update(cert_pem_path=mock.sentinel.cert_path,
cert_key_pem_path=mock.sentinel.key_path)
self.assertEqual(expected_auth_info, auth_info)
@mock.patch.object(serv_mgr_cls, '_get_auth_info')
@mock.patch.object(generic_serv_mgr_cls, 'get_common_server')
def test_common_server(self, mock_generic_get_server, mock_get_auth):
mock_server_details = {'backend_details': {}}
mock_auth_info = {'fake_auth_info': mock.sentinel.auth_info}
mock_generic_get_server.return_value = mock_server_details
mock_get_auth.return_value = mock_auth_info
expected_server_details = dict(backend_details=mock_auth_info)
server_details = self._mgr.get_common_server()
mock_generic_get_server.assert_called_once_with()
self.assertEqual(expected_server_details, server_details)
@mock.patch.object(serv_mgr_cls, '_get_auth_info')
@mock.patch.object(generic_serv_mgr_cls, '_get_new_instance_details')
def test_get_new_instance_details(self, mock_generic_get_details,
mock_get_auth):
mock_server_details = {'fake_server_details':
mock.sentinel.server_details}
mock_generic_get_details.return_value = mock_server_details
mock_auth_info = {'fake_auth_info': mock.sentinel.auth_info}
mock_get_auth.return_value = mock_auth_info
expected_server_details = dict(mock_server_details, **mock_auth_info)
instance_details = self._mgr._get_new_instance_details(
server=mock.sentinel.server)
mock_generic_get_details.assert_called_once_with(mock.sentinel.server)
self.assertEqual(expected_server_details, instance_details)
@ddt.data(('abAB01', True),
('abcdef', False),
('aA0', False))
@ddt.unpack
def test_check_password_complexity(self, password, expected_result):
valid_complexity = self._mgr._check_password_complexity(
password)
self.assertEqual(expected_result, valid_complexity)
@ddt.data(None, Exception)
def test_server_connection(self, side_effect):
self._remote_execute.side_effect = side_effect
expected_result = side_effect is None
is_available = self._mgr._test_server_connection(self._FAKE_SERVER)
self.assertEqual(expected_result, is_available)
self._remote_execute.assert_called_once_with(self._FAKE_SERVER,
"whoami",
retry=False)
@ddt.data(False, True)
def test_get_service_instance_create_kwargs(self, use_cert_auth):
self._mgr._use_cert_auth = use_cert_auth
self.flags(service_instance_password=mock.sentinel.admin_pass)
if use_cert_auth:
mock_cert_data = 'mock_cert_data'
self.mock_object(service_instance, 'open',
mock.mock_open(
read_data=mock_cert_data))
expected_kwargs = dict(user_data=mock_cert_data)
else:
expected_kwargs = dict(
meta=dict(admin_pass=str(mock.sentinel.admin_pass)))
create_kwargs = self._mgr._get_service_instance_create_kwargs()
self.assertEqual(expected_kwargs, create_kwargs)
@mock.patch.object(generic_serv_mgr_cls, 'set_up_service_instance')
@mock.patch.object(serv_mgr_cls, 'get_valid_security_service')
@mock.patch.object(serv_mgr_cls, '_setup_security_service')
def test_set_up_service_instance(self, mock_setup_security_service,
mock_get_valid_security_service,
mock_generic_setup_serv_inst):
mock_service_instance = {'instance_details': None}
mock_network_info = {'security_services':
mock.sentinel.security_services}
mock_generic_setup_serv_inst.return_value = mock_service_instance
mock_get_valid_security_service.return_value = (
mock.sentinel.security_service)
instance_details = self._mgr.set_up_service_instance(
mock.sentinel.context, mock_network_info)
mock_generic_setup_serv_inst.assert_called_once_with(
mock.sentinel.context, mock_network_info)
mock_get_valid_security_service.assert_called_once_with(
mock.sentinel.security_services)
mock_setup_security_service.assert_called_once_with(
mock_service_instance, mock.sentinel.security_service)
expected_instance_details = dict(mock_service_instance,
joined_domain=True)
self.assertEqual(expected_instance_details,
instance_details)
@mock.patch.object(serv_mgr_cls, '_run_cloudbase_init_plugin_after_reboot')
@mock.patch.object(serv_mgr_cls, '_join_domain')
def test_setup_security_service(self, mock_join_domain,
mock_run_cbsinit_plugin):
utils = self._windows_utils
mock_security_service = {'domain': mock.sentinel.domain,
'user': mock.sentinel.admin_username,
'password': mock.sentinel.admin_password,
'dns_ip': mock.sentinel.dns_ip}
utils.get_interface_index_by_ip.return_value = (
mock.sentinel.interface_index)
self._mgr._setup_security_service(self._FAKE_SERVER,
mock_security_service)
utils.set_dns_client_search_list.assert_called_once_with(
self._FAKE_SERVER,
[mock_security_service['domain']])
utils.get_interface_index_by_ip.assert_called_once_with(
self._FAKE_SERVER,
self._FAKE_SERVER['ip'])
utils.set_dns_client_server_addresses.assert_called_once_with(
self._FAKE_SERVER,
mock.sentinel.interface_index,
[mock_security_service['dns_ip']])
mock_run_cbsinit_plugin.assert_called_once_with(
self._FAKE_SERVER,
plugin_name=self._mgr._CBS_INIT_WINRM_PLUGIN)
mock_join_domain.assert_called_once_with(
self._FAKE_SERVER,
mock.sentinel.domain,
mock.sentinel.admin_username,
mock.sentinel.admin_password)
@ddt.data({'join_domain_side_eff': Exception},
{'server_available': False,
'expected_exception': exception.ServiceInstanceException},
{'join_domain_side_eff': processutils.ProcessExecutionError,
'expected_exception': processutils.ProcessExecutionError},
{'domain_mismatch': True,
'expected_exception': exception.ServiceInstanceException})
@mock.patch.object(generic_serv_mgr_cls, 'reboot_server')
@mock.patch.object(generic_serv_mgr_cls, 'wait_for_instance_to_be_active')
@mock.patch.object(generic_serv_mgr_cls, '_check_server_availability')
@ddt.unpack
def test_join_domain(self, mock_check_avail,
mock_wait_instance_active,
mock_reboot_server,
expected_exception=None,
server_available=True,
domain_mismatch=False,
join_domain_side_eff=None):
self._windows_utils.join_domain.side_effect = join_domain_side_eff
mock_check_avail.return_value = server_available
self._windows_utils.get_current_domain.return_value = (
None if domain_mismatch else mock.sentinel.domain)
domain_params = (mock.sentinel.domain,
mock.sentinel.admin_username,
mock.sentinel.admin_password)
if expected_exception:
self.assertRaises(expected_exception,
self._mgr._join_domain,
self._FAKE_SERVER,
*domain_params)
else:
self._mgr._join_domain(self._FAKE_SERVER,
*domain_params)
if join_domain_side_eff != processutils.ProcessExecutionError:
mock_reboot_server.assert_called_once_with(
self._FAKE_SERVER, soft_reboot=True)
mock_wait_instance_active.assert_called_once_with(
self._FAKE_SERVER['instance_id'],
timeout=self._mgr.max_time_to_build_instance)
mock_check_avail.assert_called_once_with(self._FAKE_SERVER)
if server_available:
self._windows_utils.get_current_domain.assert_called_once_with(
self._FAKE_SERVER)
self._windows_utils.join_domain.assert_called_once_with(
self._FAKE_SERVER,
*domain_params)
@ddt.data([],
[{'type': 'active_directory'}],
[{'type': 'active_directory'}] * 2,
[{'type': mock.sentinel.invalid_type}])
def test_get_valid_security_service(self, security_services):
valid_security_service = self._mgr.get_valid_security_service(
security_services)
if (security_services and len(security_services) == 1 and
security_services[0]['type'] == 'active_directory'):
expected_valid_sec_service = security_services[0]
else:
expected_valid_sec_service = None
self.assertEqual(expected_valid_sec_service,
valid_security_service)
@mock.patch.object(serv_mgr_cls, '_get_cbs_init_reg_section')
def test_run_cloudbase_init_plugin_after_reboot(self,
mock_get_cbs_init_reg):
self._FAKE_SERVER = {'instance_id': mock.sentinel.instance_id}
mock_get_cbs_init_reg.return_value = mock.sentinel.cbs_init_reg_sect
expected_plugin_key_path = "%(cbs_init)s\\%(instance_id)s\\Plugins" % {
'cbs_init': mock.sentinel.cbs_init_reg_sect,
'instance_id': self._FAKE_SERVER['instance_id']}
self._mgr._run_cloudbase_init_plugin_after_reboot(
server=self._FAKE_SERVER,
plugin_name=mock.sentinel.plugin_name)
mock_get_cbs_init_reg.assert_called_once_with(self._FAKE_SERVER)
self._windows_utils.set_win_reg_value.assert_called_once_with(
self._FAKE_SERVER,
path=expected_plugin_key_path,
key=mock.sentinel.plugin_name,
value=self._mgr._CBS_INIT_RUN_PLUGIN_AFTER_REBOOT)
@ddt.data(
{},
{'exec_errors': [
processutils.ProcessExecutionError(stderr='Cannot find path'),
processutils.ProcessExecutionError(stderr='Cannot find path')],
'expected_exception': exception.ServiceInstanceException},
{'exec_errors': [processutils.ProcessExecutionError(stderr='')],
'expected_exception': processutils.ProcessExecutionError},
{'exec_errors': [
processutils.ProcessExecutionError(stderr='Cannot find path'),
None]}
)
@ddt.unpack
def test_get_cbs_init_reg_section(self, exec_errors=None,
expected_exception=None):
self._windows_utils.normalize_path.return_value = (
mock.sentinel.normalized_section_path)
self._windows_utils.get_win_reg_value.side_effect = exec_errors
if expected_exception:
self.assertRaises(expected_exception,
self._mgr._get_cbs_init_reg_section,
mock.sentinel.server)
else:
cbs_init_section = self._mgr._get_cbs_init_reg_section(
mock.sentinel.server)
self.assertEqual(mock.sentinel.normalized_section_path,
cbs_init_section)
base_path = 'hklm:\\SOFTWARE'
cbs_section = 'Cloudbase Solutions\\Cloudbase-Init'
tested_upper_sections = ['']
if exec_errors and 'Cannot find path' in exec_errors[0].stderr:
tested_upper_sections.append('Wow6432Node')
tested_sections = [os.path.join(base_path,
upper_section,
cbs_section)
for upper_section in tested_upper_sections]
self._windows_utils.normalize_path.assert_has_calls(
[mock.call(tested_section)
for tested_section in tested_sections])
|
11,385 | 8504896793c5b1ef58773d10b93dc630e5e02983 | def weather(temp):
if temp <= 10:
result = "COLD"
elif temp > 10 and temp <= 25:
result = "WARM"
else:
result = "HOT"
return result
user_input = float(input("Please enter a temperature: "))
print("The weather is",weather(user_input)) |
11,386 | 1b8bf2231c2aaa0eb17dbcf3a53d0c4df9d83367 | from i3pystatus import IntervalModule
from i3pystatus.core.command import run_through_shell
class DeviceNotFound(Exception):
pass
class NoBatteryStatus(Exception):
message = None
def __init__(self, message):
self.message = message
class Solaar(IntervalModule):
"""
Shows status and load percentage of logitech's unifying device
.. rubric:: Available formatters
* `{output}` — percentage of battery and status
"""
color = "#FFFFFF"
error_color = "#FF0000"
interval = 30
settings = (
("nameOfDevice", "name of the logitech's unifying device"),
("color", "standard color"),
("error_color", "color to use when non zero exit code is returned"),
)
required = ("nameOfDevice",)
def findDeviceNumber(self):
command = 'solaar show'
retvalue, out, stderr = run_through_shell(command, enable_shell=True)
for line in out.split('\n'):
if line.count(self.nameOfDevice) > 0 and line.count(':') > 0:
numberOfDevice = line.split(':')[0]
return numberOfDevice
raise DeviceNotFound()
def findBatteryStatus(self, numberOfDevice):
command = 'solaar show %s' % (numberOfDevice)
retvalue, out, stderr = run_through_shell(command, enable_shell=True)
for line in out.split('\n'):
if line.count('Battery') > 0:
if line.count(':') > 0:
batterystatus = line.split(':')[1].strip().strip(",")
return batterystatus
elif line.count('offline'):
raise NoBatteryStatus('offline')
else:
raise NoBatteryStatus('unknown')
raise NoBatteryStatus('unknown/error')
def run(self):
self.output = {}
try:
device_number = self.findDeviceNumber()
output = self.findBatteryStatus(device_number)
self.output['color'] = self.color
except DeviceNotFound:
output = "device absent"
self.output['color'] = self.error_color
except NoBatteryStatus as e:
output = e.message
self.output['color'] = self.error_color
self.output['full_text'] = output
|
11,387 | 387965ad8ecbcf8596bcc133f5369e9dbc3d1832 | /home/septiannurtrir/miniconda3/lib/python3.7/weakref.py |
11,388 | bb993edb6b6b87f110ac68e903f5f84ef102c8ec | from haystack.forms import SearchForm
class NotesSearchForm(SearchForm):
def no_query_found(self):
return self.searchqueryset.all()
class ProductSearchForm(SearchForm):
def no_query_found(self):
return self.searchqueryset.all() |
11,389 | 10a0502057b95d90b538c5377484a3b2d462e084 | import pytest
from solution import n_back
@pytest.mark.parametrize(
('sequence', 'n', 'expected'),
(
([1, 1, 1, 1, 1], 1, 4),
([1, 1, 1, 1, 1], 2, 3),
([1, 2, 1, 2, 1], 1, 0),
([1, 2, 1, 2, 1], 2, 3),
([1, 2, 3, 4, 5, 6, 7, 8, 9, 1], 9, 1),
([], 1, 0),
([1] * 1001, 1, 1000),
([1] * 1001, 1000, 1),
([9, 4, 3, 5, 6, 3, 4, 1, 8, 8, 1, 3, 8, 5, 2, 4, 2, 2, 9, 1, 6, 4, 5, 2, 7, 1, 3, 3, 4], 0, 29),
([7, 3, 9, 4, 6, 7, 8, 9, 3, 8, 7, 5, 2, 6, 8, 7, 2, 8, 6, 6, 7, 2, 3, 3, 9], 1, 2)
)
)
def test_solution(n, sequence, expected):
assert n_back(sequence, n) == expected
|
11,390 | 6aa303d2747ea9c54a40e42cce69d7715c0c96bb | from django.contrib import admin
from quiz_app.forms import BaseAnswerInlineFormset
from quiz_app.models import Category, Quiz, Question, Answer
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'slug', ]
prepopulated_fields = {'slug': ('name', )}
class QuestionAdminInline(admin.TabularInline):
model = Question
extra = 4
@admin.register(Quiz)
class QuizAdmin(admin.ModelAdmin):
list_display = ['title', 'category', 'time', 'author', 'created', 'updated']
exclude = ['created', 'updated', ]
prepopulated_fields = {'slug': ('title', )}
inlines = [QuestionAdminInline, ]
list_filter = ['category', 'author']
search_fields = ['title', 'description', ]
list_editable = ['time', ]
ordering = ['-created']
class AnswerInline(admin.TabularInline):
model = Answer
formset = BaseAnswerInlineFormset
extra = 4
@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
list_display = ['content', ]
fields = ['content', 'image', 'quiz', ]
inlines = [AnswerInline, ]
search_fields = ['content', ]
list_filter = ['quiz', ]
|
11,391 | b197e669918cbb7512bbb88405c51e3fe0e82405 | # -*- coding: utf-8 -*-
from django.contrib.auth import get_user_model
from tina.projects.models import Project
from tina.base.utils.slug import slugify
import pytest
pytestmark = pytest.mark.django_db
def test_slugify_1():
assert slugify("漢字") == "han-zi"
def test_slugify_2():
assert slugify("TestExamplePage") == "testexamplepage"
def test_slugify_3():
assert slugify(None) == ""
def test_project_slug_with_special_chars():
user = get_user_model().objects.create(username="test")
project = Project.objects.create(name="漢字", description="漢字", owner=user)
project.save()
assert project.slug == "test-han-zi"
def test_project_with_existing_name_slug_with_special_chars():
user = get_user_model().objects.create(username="test")
Project.objects.create(name="漢字", description="漢字", owner=user)
project = Project.objects.create(name="漢字", description="漢字", owner=user)
assert project.slug == "test-han-zi-1"
|
11,392 | b881d3cc377b7a71c7d4db5c7360e325dfbb5936 | '''
Using subplot() (2)
Now you have some familiarity with plt.subplot(), you can use it to plot more plots in larger grids of subplots of the same figure.
Here, you will make a 2×2 grid of subplots and plot the percentage of degrees awarded to women in Physical Sciences (using physical_sciences), in Computer Science (using computer_science), in Health Professions (using health), and in Education (using education).
Instructions
100 XP
Create a figure with 2×2 subplot layout, make the top, left subplot active, and plot the % of degrees awarded to women in Physical Sciences in blue in the active subplot.
Make the top, right subplot active in the current 2×2 subplot grid and plot the % of degrees awarded to women in Computer Science in red in the active subplot.
Make the bottom, left subplot active in the current 2×2 subplot grid and plot the % of degrees awarded to women in Health Professions in green in the active subplot.
Make the bottom, right subplot active in the current 2×2 subplot grid and plot the % of degrees awarded to women in Education in yellow in the active subplot.
When making your plots, be sure to use the variable names specified in the exercise text above (computer_science, health, and education)!
'''
SOLUTION
# Create a figure with 2x2 subplot layout and make the top left subplot active
plt.subplot(2, 2, 1)
# Plot in blue the % of degrees awarded to women in the Physical Sciences
plt.plot(year, physical_sciences, color='blue')
plt.title('Physical Sciences')
# Make the top right subplot active in the current 2x2 subplot grid
plt.subplot(2, 2, 2)
# Plot in red the % of degrees awarded to women in Computer Science
plt.plot(year, computer_science, color='red')
plt.title('Computer Science')
# Make the bottom left subplot active in the current 2x2 subplot grid
plt.subplot(2, 2, 3)
# Plot in green the % of degrees awarded to women in Health Professions
plt.plot(year, health, color='green')
plt.title('Health Professions')
# Make the bottom right subplot active in the current 2x2 subplot grid
plt.subplot(2, 2, 4)
# Plot in yellow the % of degrees awarded to women in Education
plt.plot(year, education, color='yellow')
plt.title('Education')
# Improve the spacing between subplots and display them
plt.tight_layout()
plt.show()
|
11,393 | 55b92b5c7b4db9b95ac7517e708fc955aab059e7 | from oandapyV20 import API
accountID = ""
access_token = ""
api = API(access_token=access_token, environment="practice")
|
11,394 | 65eb89e294bdebe0827964c8164d725ec166764b | ax = float(input())
ay = float(input())
bx = float(input())
by = float(input())
dist = (((bx - ax) ** 2) + ((by - ay) ** 2)) ** 0.5
print(round(dist,2)) |
11,395 | ea9b506c4a248e883124d93374dd73ef1d8104c9 | from collections import defaultdict
from datetime import datetime, timedelta
from aiogram import types
from aiogram.utils.text_decorations import markdown_decoration
from i17obot import bot, config
from i17obot.models import User
def docsurl(resource):
corner_cases = {
"library--multiprocessing_shared_memory": "library/multiprocessing.shared_memory",
}
docspath = corner_cases.get(resource)
if not docspath:
docspath = "/".join(resource.split("--"))
docspath = docspath.replace("_", ".").replace("..", "__")
return f"https://docs.python.org/pt-br/3/{docspath}.html"
def check_user_state(state):
async def wrapper(message: types.Message):
user = await User.get(message.from_user.id)
result = state == user.state
print(user.state, state, result)
return state == user.state
return wrapper
def add_keyboard_button(label, data):
key = "url" if data.startswith("http") else "callback_data"
return types.InlineKeyboardButton(label, **{key: data})
def make_keyboard(*rows):
keyboard_markup = types.InlineKeyboardMarkup()
for row in rows:
if isinstance(row, list):
keyboard_markup.row(
*[add_keyboard_button(button, data) for button, data in row]
)
else:
keyboard_markup.row(add_keyboard_button(row[0], row[1]))
return keyboard_markup
def sum_stats(stats):
result = defaultdict(int)
keys = [
"translated_entities",
"untranslated_entities",
"translated_words",
"untranslated_words",
"reviewed",
]
for data in stats:
for key in keys:
result[key] += data[key]
total_entities = result["translated_entities"] + result["untranslated_entities"]
result["total_translated"] = result["translated_entities"] / total_entities * 100
result["total_reviewed"] = result["reviewed"] / total_entities * 100
return result
def seconds_until_tomorrow(today):
tomorrow = today + timedelta(days=1)
return datetime.combine(tomorrow, datetime.time.min) - today
async def message_admins(message):
for admin in config.ADMINS:
await bot.send_message(admin, message, parse_mode="markdown")
def unparse_message(message):
text = message.text
entities = message.entities
if (
len(entities) == 1
and entities[0].type == "code"
and entities[0].values["offset"] == 0
and entities[0].values["length"] == len(text)
):
return message.text
unparsed_text = markdown_decoration.unparse(text, entities)
special_chars = [
"_",
"*",
"[",
"]",
"(",
")",
"~",
"`",
">",
"#",
"+",
"-",
"=",
"|",
"{",
"}",
".",
"!",
]
for char in special_chars:
unparsed_text = unparsed_text.replace(f"\\{char}", char)
return unparsed_text
|
11,396 | 7370a3394f1f459b0583f5bf79e2ebbce7f7ab4f | # Load the Python Standard and DesignScript Libraries
import sys
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
# The inputs to this node will be stored as a list in the IN variables.
listOfService = IN[0]
# Custom variables
PAREDE_RVT_COD = []
CHAPISCO_EXT_RVT_COD = []
EMBOCO_EXT_RVT_COD = []
MASSA_UNICA_EXT_RVT_COD = []
CERAMICA_EXT_RVT_COD = []
MASSA_CORRIDA_EXT_RVT_COD = []
SELADOR_EXT_RVT_COD = []
PINTURA_EXT_RVT_COD = []
TEXTURA_EXT_RVT_COD = []
# Place your code below this line
for i in listOfService:
for j in i:
if j == "DRYWALL_SIMPLES" or j == "DRYWALL_DUPLA":
PAREDE_RVT_COD.append("PAREDE_RVT_COD")
elif j == "CHAPISCO_EXT_SERV":
CHAPISCO_EXT_RVT_COD.append("CHAPISCO_EXT_RVT_COD")
elif j == "EMBOCO_EXT_SERV_25mm" or j == "EMBOCO_EXT_SERV_35mm" or j == "EMBOCO_EXT_SERV_45mm" or j == "EMBOCO_EXT_SERV_50mm":
EMBOCO_EXT_RVT_COD.append("EMBOCO_EXT_RVT_COD")
elif j == "MASSA_UNICA_EXT_SERV_25mm" or j == "MASSA_UNICA_EXT_SERV_35mm" or j == "MASSA_UNICA_EXT_SERV_45mm" or j == "MASSA_UNICA_EXT_SERV_50mm":
MASSA_UNICA_EXT_RVT_COD.append("MASSA_UNICA_EXT_RVT_COD")
elif j == "CERAMICA_PORCELANA_EXT_5X5cm" or j == "CERAMICA_PORCELANA_EXT_5X10cm":
CERAMICA_EXT_RVT_COD.append("CERAMICA_EXT_RVT_COD")
elif j == "MASSA_CORRIDA_ACRILICA_EXT_UMA_DEMAO_MULTPAV_SERV" or j == "MASSA_CORRIDA_ACRILICA_EXT_DUAS_DEMAOS_MULTPAV_SERV":
MASSA_CORRIDA_EXT_RVT_COD.append("MASSA_CORRIDA_EXT_RVT_COD")
elif j == "SELADOR_ACRILICO_EXT_MULTPAV_SERV":
SELADOR_EXT_RVT_COD.append("SELADOR_EXT_RVT_COD")
elif j == "PINTURA_ACRILICA_EXT_MULTPAV_SERV":
PINTURA_EXT_RVT_COD.append("PINTURA_EXT_RVT_COD")
elif j == "TEXTURA_ACRILICA_EXT_UMA_COR_MULTPAV_SERV" or j == "TEXTURA_ACRILICA_EXT_DUAS_CORES_MULTPAV_SERV":
TEXTURA_EXT_RVT_COD.append("TEXTURA_EXT_RVT_COD")
# Assign your output to the OUT variable.
OUT = PAREDE_RVT_COD + CHAPISCO_EXT_RVT_COD + EMBOCO_EXT_RVT_COD + MASSA_UNICA_EXT_RVT_COD + CERAMICA_EXT_RVT_COD + MASSA_CORRIDA_EXT_RVT_COD + SELADOR_EXT_RVT_COD + PINTURA_EXT_RVT_COD + TEXTURA_EXT_RVT_COD |
11,397 | d3b8e0109d1b6ad5ea1d34b2ad61054f1b57d2b3 | data = list(map(int, open("data", "r").read().splitlines()))
def get_checksums(preamble, result):
if(len(preamble) == 0): return result
result.extend([num + preamble[0] for num in preamble[1:]])
return get_checksums(preamble[1:], result)
def get_corrupt_number(preamble_size):
for i, _ in enumerate(data):
if data[i + preamble_size] not in get_checksums(data[i:i+preamble_size], []):
return data[i + preamble_size]
def find_corrupt_set(corrupt):
for i, _ in enumerate(data):
continousSet = []
for num in data[i:]:
continousSet.append(num)
set_sum = sum(continousSet)
if set_sum == corrupt:
return continousSet
if set_sum > corrupt:
break
corrupt = get_corrupt_number(25)
corrupt_set = find_corrupt_set(corrupt)
print('part1', corrupt)
print('part2', min(corrupt_set) + max(corrupt_set)) |
11,398 | 46d93eb526a2ca14c53b12bb37d29abab28ff368 | class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
def judge(n):
tmp = n
while tmp > 0:
div = tmp % 10
if (div == 0):
return False
if (n % div != 0):
return False
tmp = tmp / 10
return True
ans = []
for i in range(left, right + 1):
if judge(i): ans.append(i)
return ans
left = 1
right = 22
ans = selfDividingNumbers(left, right)
print(ans) |
11,399 | ae6e008f66fdaf94401277260ba5a8f37e8f64e0 | import sys;
from collections import Counter
print("Day 2 puzzle: Inventory Management System");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
box_ids = []
with open(puzzle_file, 'r') as puzzle_in:
box_ids = [cur_line.strip("\n") for cur_line in puzzle_in]
puzzle_in.close()
# search the repetitions
total_dupes = 0
total_triples = 0
# examine each box
for box_num in box_ids:
tag_summary = Counter(box_num)
if 2 in tag_summary.values():
total_dupes += 1
if 3 in tag_summary.values():
total_triples += 1
# examine tags' similarity
chars_evidence = {}
for box_tag in box_ids:
#now we have a list without element taken to comparison
for box_to_check in box_ids:
common_chars = ""
diff_cntr = 0
for pos in range (len(box_tag)):
if box_tag[pos] == box_to_check[pos]:
common_chars = common_chars + box_tag[pos]
else:
diff_cntr += 1
if diff_cntr > 1:
# no point to do more checks
break
if diff_cntr == 1:
if common_chars not in chars_evidence:
chars_evidence[common_chars] = 1
else:
chars_evidence[common_chars] = chars_evidence[common_chars] + 1
print ("The checksum is: %d" %(total_triples*total_dupes))
print ("The most popular sequence is: ", Counter(chars_evidence).most_common(5)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.