""" Tests for runroles module
"""
import re

from nb2plots import runroles as rr
from nb2plots import doctree2nb
from nb2plots import doctree2py
from nb2plots.converters import to_pxml

from nose.tools import assert_equal, assert_true

from nb2plots.tests import mockapp

def test_runroles_setup(*args):
    # Test extension setup works as expected
    app = mockapp.get_app()
    rr.setup(app)
    connects = [('doctree-resolved', rr.collect_runfiles),
                ('build-finished', rr.write_runfiles)]
    roles = list(rr.NAME2ROLE.items())
    translators = [('ipynb', doctree2nb.Translator),
                   ('python', doctree2py.Translator)]
    for method_name, args, kwargs in app.method_calls:
        if (method_name == 'connect' and args[0:2] in connects):
            connects.remove(args[0:2])
        if (method_name == 'add_role' and args[0:2] in roles):
            roles.remove(args[0:2])
        if (method_name == 'set_translator' and args[0:2] in translators):
            translators.remove(args[0:2])

    assert_equal(len(connects), 0, 'Connections failed')
    assert_equal(len(roles), 0, 'Roles failed')
    assert_equal(len(translators), 0, 'Translators failed')

def test_runrole_doctrees():
    # Test that run roles generate expected doctrees
    expected_re_fmt = """\
<document source=".*?">
    <paragraph>
        Text then
        <runrole_reference code_type="{code_type}" filename="{base}.{ext}" refdoc="contents" reftarget="{base}.{ext}" reftype="{role_type}">
            {descr}
         then text."""

    type2role = {'clear notebook': 'clearnotebook',
                 'full notebook': 'fullnotebook',
                 'python': 'codefile'}

    def assert_rst_pxml(pxml_params, rst_source):
        code_type = pxml_params['code_type']
        pxml = to_pxml.from_rst(rst_source)
        if not 'ext' in pxml_params:
            pxml_params['ext'] = 'py' if code_type == 'python' else 'ipynb'
        pxml_regex = expected_re_fmt.format(
            role_type=type2role[code_type],
            **pxml_params)
        assert_true(re.match(pxml_regex, pxml))

    assert_rst_pxml(
        dict(code_type='clear notebook',
             base='contents',
             descr='Download this page as a Jupyter notebook \(no outputs\)'),
        "Text then :clearnotebook:`.` then text.")
    assert_rst_pxml(
        dict(code_type='full notebook',
             base='contents',
             descr=('Download this page as a Jupyter notebook '
                    '\(with outputs\)')),
        "Text then :fullnotebook:`.` then text.")
    assert_rst_pxml(
        dict(code_type='python',
             base='contents',
             descr='Download this page as a Python code file'),
        "Text then :codefile:`.` then text.")
    for code_type in ('clear notebook', 'full notebook', 'python'):
        role_type = type2role[code_type]
        assert_rst_pxml(
            dict(code_type=code_type,
                 base='contents',
                 descr='message to taste'),
            "Text then :{}:`message to taste` then text.".format(role_type))
        assert_rst_pxml(
            dict(code_type=code_type,
                 base='foo',
                 ext='ipynb',
                 descr='message to taste'),
            "Text then :{}:`message to taste <foo.ipynb>` then text."
            .format(role_type))
        # Is it annoying, but there must be a first text description for the
        # angle brackets part to refer to the output file name.  This is how
        # ReST role processing usually works.
        assert_rst_pxml(
            dict(code_type=code_type,
                 base='contents',
                 descr='<foo.ipynb>'),
            "Text then :{}:`<foo.ipynb>` then text.".format(role_type))


#!/usr/bin/python3
import numpy as np

# definitions
def read_data(indir): # read .plt data
	f= open(indir,'r')
	first_line= f.readline()
	first_line= f.readline()
	rad=[]
	tht=[]
	zet=[]
	eng=[]
	pch=[]
	first_line= f.readline()
	for line in f:
		l= line.split()
		rad.append(float(l[0]))
		tht.append(float(l[1]))
		zet.append(float(l[2]))
		eng.append(float(l[3]))
		pch.append(float(l[4]))
	f.close()
	return rad,tht,zet,eng,pch

def gaussian(x,t,dff,xm): # gaussian function
	return np.exp(-(x -xm)**2/4/dff/t)/np.sqrt(4*np.pi*dff*t)

def maxwellian(en): # maxwellian function
	kt=1
	return 2*np.sqrt(en/np.pi)*(1/kt)**1.5*np.exp(-en/kt)

def format_func(value, tick_number): # find number of multiples of pi/2
    N= int(np.round(2*value/np.pi))
    if N==0:
        return "0"
    elif N==1:
        return r"$\pi/2$"
    elif N==2:
        return r"$\pi$"
    elif N==-1:
        return r"$-\pi/2$"
    elif N==-2:
        return r"$-\pi$"
    elif N%2>0:
        return r"${0}\pi/2$".format(N)
    else:
        return r"${0}\pi$".format(N // 2)

# argument parsing
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i','--input-file',required=True,
	help='input file')
parser.add_argument('-o','--output-file',
	help='output file')
parser.add_argument('-t','--type',
	help='plot type \'pos\' or \'vel\'',required=True)
parser.add_argument('-s','--show-plot',action="store_true",
	help='show_plot')
args = parser.parse_args()

# plot
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import pandas as pd
import seaborn as sns
sns.set()
plt.style.use('seaborn-whitegrid')
params = {'axes.labelsize' : 'large',
          'xtick.labelsize': 'large',
          'ytick.labelsize': 'large'}
pylab.rcParams.update(params)
rad,tht,zet,eng,pch= read_data(args.input_file)

if args.type=='pos': # position space distributions
	print("distribution plot pos...")
	fig, ax= plt.subplots(3,1,figsize=(6,6))
	from scipy.stats import norm
	rad_plot= sns.distplot(rad,ax=ax[0],
		fit=norm,kde=False)
	ax[0].set_xlabel('$r/a$')
	ax[0].set_ylabel('$f(r/a)$')
	ax[0].xaxis.set_major_locator(plt.MaxNLocator(7))
	ax[0].yaxis.set_major_locator(plt.MaxNLocator(4))
	ax[0].set(xlim= (0.2,0.8),ylim=(0,40))

	tht_plot= ax[1].hist(tht,bins=20,density=True,
		alpha=0.5)
	ax[1].set_xlabel('$\\theta$')
	ax[1].set_ylabel('$f(\\theta)$')
	ax[1].xaxis.set_major_locator(plt.MaxNLocator(8))
	ax[1].yaxis.set_major_locator(plt.MaxNLocator(4))
	ax[1].xaxis.set_major_locator(plt.MultipleLocator(np.pi/2))
	ax[1].xaxis.set_major_formatter(plt.FuncFormatter(format_func))
	ax[1].set(xlim=(-np.pi,np.pi),ylim=(0.0,0.25))

	zet_plot= ax[2].hist(zet,bins=20,density=True,
		alpha=0.5)
	ax[2].set_xlabel('$\zeta$')
	ax[2].set_ylabel('$f(\zeta)$')
	ax[2].xaxis.set_major_locator(plt.MaxNLocator(8))
	ax[2].yaxis.set_major_locator(plt.MaxNLocator(4))
	ax[2].xaxis.set_major_locator(plt.MultipleLocator(np.pi/2))
	ax[2].xaxis.set_major_formatter(plt.FuncFormatter(format_func))
	ax[2].set(xlim=(0.0,2*np.pi),ylim=(0.0,0.25))

if args.type=='vel': # velocity space distributions
	print("distribution plot vel...")
	data= {'x': pch, 'y': eng}
	data = pd.DataFrame(data, columns=['x', 'y'])
	with sns.axes_style('white'):
		plot= sns.jointplot('x','y', data, kind='hex',
			xlim=(-1.0,1.0),ylim=(0.0,12.0))
		plot.set_axis_labels("$\lambda$","$\epsilon$(keV)")

plt.tight_layout()

# output
if args.output_file:
	plt.savefig(args.output_file)
if args.show_plot:
	plt.show()


# https://docs.opencv.org/3.0-beta/modules/videoio/doc/reading_and_writing_video.html
# https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_image_display/py_image_display.html

# http://www.bmva.org/bmvc/1989/avc-89-029.pdf

# https://www.cloudynights.com/topic/538245-unmasked-foucault-testing-and-related-topics/page-3

# git notes: http://rogerdudler.github.io/git-guide/
# git status

# git add <filename>
# git commit -m "Commit message"
# git push origin master

# git pull

import cv2
import numpy
import PIL.Image
import pathlib
import os

def adjust_gamma(image, gamma=1.0):
    # build a lookup table mapping the pixel values [0, 255] to
	# their adjusted gamma values
	invGamma = 1.0 / gamma
	table = numpy.array([((i / 255.0) ** invGamma) * 255
		for i in numpy.arange(0, 256)]).astype("uint8")

	# apply gamma correction using the lookup table
	return cv2.LUT(image, table)

# Hough circles algorithm parameters
dp = 0.2
minDist = 500
param1 = 50
param2 = 30
minRadius = 500
maxRadius = 900

resizing_scale = 0.6

# Load an color image in grayscale
img = cv2.imread("new/Image_1.01.png", cv2.IMREAD_COLOR)
img = adjust_gamma(img, 1.4)

img_to_show = cv2.resize(img, None, fx = resizing_scale, fy = resizing_scale, interpolation = cv2.INTER_AREA)
cv2.imshow('image', img_to_show)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Image processing steps
gray_frame = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur_frame = gray_frame#cv2.medianBlur(gray_frame, 3)
circles = cv2.HoughCircles(blur_frame, cv2.HOUGH_GRADIENT, dp, minDist, \
param1 = param1, param2 = param2, minRadius = minRadius, maxRadius = maxRadius)

if circles is not None:
    # smooth circles parameters
    circles = circles[0][0]
    circles = numpy.uint16(numpy.around(circles))

    print(circles)

    # draw the outer circle
    circles_frame = cv2.circle(img, (circles[0], circles[1]), circles[2], (255, 0, 0), 2)
    # draw the center of the circle
    circles_frame = cv2.circle(img, (circles[0], circles[1]), 2, (0, 0, 255), 3)

    circles_frame_cropped = circles_frame[(circles[1]-circles[2]):(circles[1]+circles[2]),\
    (circles[0]-circles[2]):(circles[0]+circles[2])]

    blur_frame_cropped = blur_frame[(circles[1]-circles[2]):(circles[1]+circles[2]),\
    (circles[0]-circles[2]):(circles[0]+circles[2])]

    blur_frame_cropped_and_rotated = numpy.flip(blur_frame_cropped, 0)
    blur_frame_cropped_and_rotated = numpy.flip(blur_frame_cropped_and_rotated, 1)
    rotate_and_diff_frame = cv2.absdiff(blur_frame_cropped_and_rotated, blur_frame_cropped)

    # Create display windows
    show_picture = True
    cv2.namedWindow("Mirror detection", flags = cv2.WINDOW_AUTOSIZE)
    cv2.namedWindow("Rotate and diff", flags = cv2.WINDOW_AUTOSIZE)

    circles_frame_cropped_to_show = cv2.resize(circles_frame_cropped, None, fx = resizing_scale, fy = resizing_scale, interpolation = cv2.INTER_AREA)
    rotate_and_diff_frame_to_show = cv2.resize(rotate_and_diff_frame, None, fx = resizing_scale, fy = resizing_scale, interpolation = cv2.INTER_AREA)

    # Update pictures
    cv2.imshow("Mirror detection", circles_frame_cropped_to_show)
    cv2.imshow("Rotate and diff", rotate_and_diff_frame_to_show)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


from __future__ import print_function

import wave, struct, socket, sys, time
import threading
import pyaudio
import re
import json

if (sys.version_info > (3, 0)):
    # Python 3 code in this block
    from queue import Queue, Empty
else:
    # Python 2 code in this block
    from Queue import Queue, Empty
try:
   import webrtcvad
   vad_available = True
   print('* VAD is turned ON')
except:
   vad_available = False
   print('* VAD is turned OFF')
   print("\twebrtcvad is missing, vad will not be available.")
   print("\tPlease install webrtcvad in order to have the VAD feature enabled!")
   print("\tThis can usually be done running the following command:")
   print("\t  pip install --user webrtcvad")

RATE  = 16000
CHUNK = 160
CHANNELS = 1
FORMAT = pyaudio.paInt16

ASR_MODE = ''
ASR_NBEST = 1
sent_audio_sec = 0
gsegments = []

# Not need for threading, pyaudio already deals with it
class recorder(object):
   def __init__(self, queue, event):
       p = pyaudio.PyAudio()
       self.size = CHUNK
       self.queue = queue
       self.event = event
       self.stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE,
                       input = True, frames_per_buffer = CHUNK, stream_callback=self.get_callback())
       self.stream.start_stream()

   def get_callback(self):
        def callback(in_data, frame_count, time_info, status):
            if not self.event.isSet():
               self.queue.put(in_data)
            else:
               return in_data, pyaudio.paComplete
            return in_data, pyaudio.paContinue
        return callback

class send_live_audio(threading.Thread):
   def __init__(self, socket, queue, event, vad_active=False):
       threading.Thread.__init__(self)
       self.socket = socket
       self.queue = queue
       self.event = event
       self.vad_active = vad_active
       if vad_available and vad_active:
          self.vad = webrtcvad.Vad(2)

   def send_audio(self, msg):
       global sent_audio_sec
       sent_audio_sec += float(len(msg)) / 2 / RATE
       packet = struct.pack("<i", len(msg)) + msg
       #print("sending %d" % len(packet))
       self.socket.sendall(packet)

   def run(self):
       #oldspeech = 0
       sample_count = 0
       cur_state = 0
       old_state = 0
       buffer = bytes()
       state_counts = {0: 0, 1: 0}
       maxbuf = 10 * CHUNK
       while not self.event.isSet():
        #    print "send" + str(len(self.queue.get())) + "\r"
               try:
                  msg = self.queue.get(timeout=1)
               except Empty:
                  #print "empty"
                  if cur_state:
                     self.send_audio(buffer)
                     self.send_audio(bytes())
                     buffer = bytes()
                     cur_state = 0
                  continue
               if not vad_available or not self.vad_active:
                  self.send_audio(msg)
                  continue
               sample_count += len(msg)
               # Force end of segment
               if len(msg) < CHUNK * 2:
                  #n = CHUNK - len(msg) / 2
                  #msg += struct.pack("<%dh" % n, *([0] * n))
                  #msg = ""
                  old_state = cur_state
                  cur_state = 0
                  isspeech = 0
               else:
                  isspeech = self.vad.is_speech(msg, RATE)
               state_counts[isspeech] += 1
               if isspeech or cur_state:
                  buffer += msg #msg.decode()
               else:
                  if len(buffer) > maxbuf:
                     buffer = buffer[len(buffer) - maxbuf:]
                  buffer += msg
               if isspeech != cur_state:
                  state_counts[cur_state] = 0
               else:
                  for s in state_counts:
                     if s != cur_state:
                        state_counts[s] = 0
               # state switching
               #print isspeech, state_counts, len(buffer)
               if state_counts[isspeech] >= 10:
                  old_state = cur_state
                  cur_state = isspeech
               if len(buffer) and cur_state:
                  if not old_state:
                     start_time = sample_count - len(buffer)
                  self.send_audio(buffer)
                  buffer = bytes()
               if old_state and not cur_state:
                  end_time = sample_count
                  gsegments.append((start_time, end_time))
                  self.send_audio(bytes())
                  buffer = bytes()

class reader(threading.Thread):
   def __init__(self, sock, event, asr_mode, asr_nbest, log):
       threading.Thread.__init__(self)
       self.sock = sock
       self.event = event
       self.asr_mode = asr_mode
       self.asr_nbest = asr_nbest
       self.log = log
       self.header = None
       self.prev_start_time = -1.0
       self.line = ""
       self.done = False
       self.idur = 0.0
   def run(self):
       while not self.event.isSet():
          #msg = str(self.sock.recv(4096))
          msg = self.sock.recv(256)# .decode('utf-8')
          if len(msg) == 0:
             break
          else:
             if self.log == 1:
                 print(msg)
             else:
               self.line = self.line + msg.decode('utf-8')
               while True:
                 # Is there a new utterance?
                 new_utt = "RESULT:NUM" in self.line
                 # If yes, then process header to get output info
                 if new_utt:
                     header = re.split('[, \n]', self.line)
                     cur_start_time = float(header[4].split("=")[1])
                     if "RESULT:NUM" in header[0] and len(header) >= 4 and len(header[3].split("=")) > 1:
                         # If idur = 0 then ignore header (same transcription)
                         # Otherwise, save new header (new transcription)
                         #if not cur_start_time == self.prev_start_time:
                         #if not header[3].split("=")[1] == "0":
                         self.header = header
                         self.prev_start_time = cur_start_time
                             #print("new-header:\t" + msg)
                             #print("new-header_split:\t" + str(header))
                 # Add to line

                 # Test if partial or complete results was received
                 end_reco = "RESULT:DONE" in self.line
                 part_reco = "RESULT:PART" in self.line
                 done = any([end_reco,part_reco])
                 if not done or not self.header:
                     break

                 if end_reco and self.header:
                     self.idur += float(self.header[3].split("=")[1])

                 # If it was , then process and output the transcription
                 if done and self.header:
                     tokens = self.line.split('\n')
                     self.line = ''

                     # Process transcription in string format
                     line = ''
                     for i, token in enumerate(tokens):
                         if not any((c in ':,-=.') for c in token):
                             line = line + token + ' '
                         if i>0 and "RESULT:DONE" in token:
                              #while i <= len(tokens) - 2 and tokens[i+1] == "": i+=1
                              self.line = '\n'.join(tokens[i+1:])
                              break
                        #  if i>0 and "RESULT:NUM" in token:
                        #      self.line = '\n'.join(tokens[i:])
                        #      break
                     line = line.strip()

                     # Process  transcription in json format
                     json_data = {}
                     json_data['content'] = "ASR_output"
                     json_data['nwords'] = self.header[0].split("=")[1]
                     if len(gsegments) > 0:
                         seg_time = gsegments.pop(0)
                     else:
                         seg_time = [0.,0.]
                     json_data['istart'] = float(seg_time[0]) / RATE / 2
                     json_data['iend'] = float(seg_time[1]) / RATE / 2
                     json_data['rdur'] = self.header[2].split("=")[1]
                     json_data['idur'] = self.header[3].split("=")[1]

                     tokens_nbest = re.split('[(*)]',line)

                     transcriptions = []

                     # In inc mode only one potential output is received
                     # even if nbest > 1. All nbest outputs are only sent
                     # when the utterance ends
                     if (part_reco == True and self.asr_mode == 'inc') or self.asr_nbest == 1:
                          #if not tokens_nbest[0].strip() == "":
                             transcriptions.append({
                                                    'id': '0',
                                                    'text': tokens_nbest[0].strip()
                                                    })
                     else:
                         for token_nbest_idx in range(0,len(tokens_nbest)-1,2):
                             #if not tokens_nbest[token_nbest_idx].strip() == "":
                                 transcriptions.append({
                                                'id': tokens_nbest[token_nbest_idx+1].strip(),
                                                'text': tokens_nbest[token_nbest_idx].strip()
                                                })
                     json_data['transcriptions'] = transcriptions

                     # Print transcriptions
                     if not len(transcriptions) == 0:
                         print('***********************************************')
                         print('\n-----\nText:\n-----\n' + line)
                         print('\n-----\nJSON:\n-----\n' + json.dumps(json_data, indent=2, sort_keys=False))

                     # Reset the line
                     self.header = None

def send_file_audio(queue, wav):
    print("Sending audio file in chunks ...")
    fwave = wave.open(wav)
    rate = fwave.getframerate()
    chan = fwave.getnchannels()
    if rate != RATE or chan != CHANNELS:
        print("Unsupported format (must be MONO and 16kHz)")
        exit(-1)
    size = fwave.getnframes()
    print("\t. #frames= " + str(size))
    for i in range(0, size, CHUNK):
        # print "\t. send chunk " + str(i)
        msg = fwave.readframes(CHUNK)
        if len(msg) == 2 * CHUNK:
            queue.put(msg)
        #sock.send(struct.pack("<i", len(msg)) + msg)
    # End of stream pack
    queue.put(bytes())
    #sock.send(struct.pack("<i", 0))
    return float(size) / rate

import argparse

# def onKeyPress(event):
#     text.insert('end', 'You pressed %s\n' % (event.char, ))

def main():
   parser = argparse.ArgumentParser(description="minimal client to send audio to the ASR server")
   parser.add_argument("-H", "--host", default="localhost", help="ASR server hostname")
   parser.add_argument("-p", "--port", type=int, default=8888, help="ASR server port")
   parser.add_argument("-am", "--asr_mode", default="utt", help="mode label ('utt' or 'inc') used to initialise ASR")
   parser.add_argument("-an", "--asr_nbest", default=1, help="n_best value used to initialise ASR")
   parser.add_argument("-m", "--mode", default="live", help="Stream live or recorded audio (live/rec).")
   #parser.add_argument("-v", "--vad", action="store_true", help="Apply vad on recorded audio")
   parser.add_argument("-i", "--input_wav", default="test_audio/test_matthew.wav", help="Audio file to transcribe (needed in rec mode)")
   parser.add_argument("-l", "--log_flag", default=0, help="Log ASR returned messaged in raw format instead of processed messages (for debugging)")
   args = parser.parse_args()

   # print("\n> ASR_MODE is " + args.asr_mode)
   # if args.asr_mode == 'inc':
   #     vad_flag = False
   #     print(' . VAD is turned OFF by default in incremental mode. ' +
   #           'The ASR server will deal with the segmentation ' +
   #           '(make sure that --endpoint is set to True on the ASR server).')
   # else:
   #     vad_flag = True
   #     print(' . VAD is turned ON by default in utterance mode. ' +
   #           'This client will deal with the segmentation ' +
   #           '(make sure that --endpoint is set to False on the ASR server).')
   # print("> ASR_NBEST = " + str(args.asr_nbest))
   #print("> log_flag = " + str(args.log_flag))
   vad_flag = True

   # Socket for connecting to the ASR machine
   sock = socket.create_connection((args.host, args.port))

   # Queue for live recording and sending manipulating the same audio data array
   queue = Queue()

   # Event to interrupt threads
   interrupt_event = threading.Event()

   # Stream live audio
   if args.mode == "live":
       print("> MODE: stream live audio")
       audio = recorder(queue,interrupt_event)

   # Stream recorded audio
   if args.mode == "rec":
       print("> MDOE: stream recorded audio")
       maxt = send_file_audio(queue, args.input_wav)

   streamer = send_live_audio(sock, queue, interrupt_event, vad_flag) #args.vad)
   streamer.start()

   print('*** Press CTRL-C to interrupt at any time ***\n\n\n')

   # Reader
   asr_text = reader(sock,interrupt_event,args.asr_mode,int(args.asr_nbest),int(args.log_flag))
   asr_text.start()

   if args.mode == "live":
       while True:
           try:
               time.sleep(1) #wait 1 second, then go back and ask if thread is still alive
           except KeyboardInterrupt: #if ctrl-C is pressed within that second,
                                     #catch the KeyboardInterrupt exception
               interrupt_event.set() #set the flag that will kill the thread when it has finished
               print('Exiting...')
               print('... recorder')
               #audio.join() #wait for the thread to finish
               print('... streamer')
               streamer.join() #wait for the thread to finish
               sock.shutdown(socket.SHUT_RDWR)
               print('... reader')
               asr_text.join()
               sock.close()
               print('done')
               exit()

   if args.mode == "rec":
       while asr_text.isAlive():
           try:
               time.sleep(1) #wait 1 second, then go back and ask if thread is still alive
               if asr_text.idur + 0.1 >= sent_audio_sec:
                   print("All processed!")
                   break
               #print(asr_text.idur, sent_audio_sec)
           except KeyboardInterrupt: #if ctrl-C is pressed within that second,
                                     #catch the KeyboardInterrupt exception
               break
       interrupt_event.set() #set the flag that will kill the thread when it has finished
       print('Exiting...')
       print('... reader')
       print('... streamer')
       streamer.join() #wait for the thread to finish
       sock.shutdown(socket.SHUT_RDWR)
       asr_text.join() #wait for the thread to finish
       sock.close()
               #exit(-1)
       exit()
   #return 0

if __name__ == "__main__":
   main()


def isMatch2( s, p):
    s = '0' + s
    p = '0' + p
    # dp[i][j]表示：s的前i个字符与p的前j个字符是否匹配
    dp = [[False for _ in range(len(p))] for _ in range(len(s))]

    # 初始化
    dp[0][0] = True  # 空字符串与空字符串相匹配
    for i in range(1, len(p)):
        if p[i] == '*':
            # 取决于前面是否匹配
            dp[0][i] = dp[0][i - 1]

    # 动态规划
    for i in range(1, len(s)):
        for j in range(1, len(p)):
            if s[i] == p[j] or p[j] == '?':
                dp[i][j] = dp[i - 1][j - 1]
            elif p[j] == '*':
                dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
    return dp[-1][-1]

def isMatch(s, p):
    i = 0
    j = 0
    # s串中0:iStart部分的字符串（在jStar位置星号的万能匹配下）与p中0:jStar部分完全匹配
    iStar = -1
    jStar = -1
    m = len(s)
    n = len(p)
    while i < m:
        # 好说，正常过
        if j < n and (s[i] == p[j] or p[j] == '?'):
            j += 1
            i += 1
        elif j < n and p[j] == '*':
            # *出现位置用jStar记住
            jStar = j
            # s串中0:iStart部分的字符串（在jStar位置星号的万能匹配下）与p中0:jStar部分完全匹配
            iStar = i
            # i不+1，因为*号也可以选择不匹配，也就是，遇到*号，你可以忽略。（axaaxabcdbc, ax*bc 。拿出第i=2,j=2,位置进行比较，s[i]=a,p[j]=*,
            # a和*不一样，*虽然可以万能匹配，让你i继续过，但是也可以不匹配，让*的后一个老哥p[j+1]=‘b’ 来和你匹配）
			# 反正，当*后面那个老哥不能出面消你的时候，*可以再出面做万能消除！所以不用+1
            j += 1
        elif iStar >= 0:
            # s中继续往后走，因为*万能匹中s中字符，需要这一步*来出面消除，则意味着把s中iStar前面的全部用p中jStar位的*来消除
            iStar += 1
            i = iStar
            # 如果到了需要*来万能解决出面的时候，j从新回到前面的*后一位
            j = jStar + 1
        else:
            # 这里，意味着？没有'*'，不想等或每个'？'取匹中s中的i位字符
            return False

    while j < n and p[j] == '*':
        j += 1
    return j == n

print('<iframe src="//player.bilibili.com/player.html?aid=371200662&bvid=BV1dZ4y1M7BX&cid=208409531&page=1" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe>')

'''
虽然*能匹配任意串，但是p中*后面出现字符不在s中，就断了
'''

print(isMatch("axaaxabcdbc", "ax*bc"))
print(isMatch("aa", "a*"))
print(isMatch("ab", "?*"))


from collections import deque
from .ahdl import *
from .ahdlvisitor import AHDLVisitor
from .graph import Graph
from .utils import find_only_one_in

class StateReducer(object):
    def process(self, scope):
        if not scope.stgs:
            return
        WaitForwarder().process(scope)
        IfForwarder().process(scope)
        graph = StateGraphBuilder().process(scope)
        self._remove_unreached_state(scope, graph)

    def _remove_unreached_state(self, scope, graph):
        for stg in scope.stgs:
            if len(stg.states) == 1:
                continue
            for state in stg.states[:]:
                if not graph.has_node(state):
                    stg.states.remove(state)

class StateGraph(Graph):
    pass

class StateGraphBuilder(AHDLVisitor):
    def process(self, scope):
        self.graph = StateGraph()
        init_state = scope.stgs[0].init_state
        nexts = deque([init_state])
        visited = set()
        while nexts:
            state = nexts.popleft()
            visited.add(state)
            self.next_states = []
            for code in state.codes:
                self.visit(code)
            for next in self.next_states:
                self.graph.add_edge(state, next)
                if next not in visited:
                    nexts.append(next)
        return self.graph

    def visit_AHDL_TRANSITION(self, ahdl):
        self.next_states.append(ahdl.target)

class WaitForwarder(AHDLVisitor):
    def process(self, scope):
        for stg in scope.stgs:
            for state in stg.states:
                wait = find_only_one_in(AHDL_META_WAIT, state.codes)
                if wait and wait.transition.target is not state:
                    self.merge_wait_function(wait)
                else:
                    for code in state.codes:
                        self.visit(code)

    def merge_wait_function(self, wait_func):
        next_state_codes = wait_func.transition.target.codes
        if next_state_codes[-1].is_a(AHDL_META_WAIT):
            return
        if wait_func.codes:
            wait_func.codes.extend(wait_func.transition.target.codes)
        else:
            wait_func.codes = wait_func.transition.target.codes
        wait_func.transition.target.codes = []
        wait_func.transition = None

    def visit_AHDL_TRANSITION_IF(self, ahdl):
        for codes in ahdl.codes_list:
            wait = find_only_one_in(AHDL_META_WAIT, codes)
            if wait:
                self.merge_wait_function(wait)

class IfForwarder(AHDLVisitor):
    def process(self, scope):
        for stg in scope.stgs:
            for state in stg.states:
                for code in state.codes:
                    self.visit(code)

    def visit_AHDL_TRANSITION_IF(self, ahdl):
        for i, codes in enumerate(ahdl.codes_list):
            assert len(codes) == 1
            transition = codes[0]
            assert transition.is_a(AHDL_TRANSITION)
            ahdl.codes_list[i] = transition.target.codes[:]


#
# IMPORTS
#
# Django
from django.shortcuts import render

# Project
from prospection_control.views.common_context import COMMON_CONTEXT
from store import store

#
# CODE
#
def closed_companies(request):

    title = 'Empresas Fechadas'
    template_name = 'closed_companies.html'

    return render(
        request,
        template_name,
        {
            **COMMON_CONTEXT,
            'page_name': title,
            'closed_companies': True,
            'closed_table_url': store['closed-table']['url'],
        },
    )


import pickle

class out:
    def __init__(self, name):
        self.name=name

if __name__ == '__main__':
    index=1
    data=b''
    while True:
        try:
            f=open('S'+str(index)+'.OOF', 'rb')
            data+=f.read()
            f.close()
            index+=1
        except:
            break
    try:
        form=open('S0.OOF', 'rb')
        final=pickle.loads(form.read())
        form.close()
        out=open(str(final.name), 'wb')
        out.write(pickle.loads(data))
        out.close()
    except:
        pass


from stack import Stack

# Checker to check if the syntax is correct
# IDES uses these kind of concepts to find syntax errors
class SyntaxChecker:
    def __init__(self):
        self.stack = Stack()
    def check_syntax(self,string):
        for char in string:
            if(char == '{' or char == '(' or char == '['):
                self.stack.push(char)
            elif(char == '}' or char == ')' or char == ']'):
                top_object = self.stack.pop()
                top_object = top_object.data
                if(char == '}' and top_object is not '{'):
                    print("Syntax Error")
                    return False
                elif(char == ')' and top_object is not '('):
                    print(char,top_object)
                    print("Syntax Error")
                    return False
                elif(char == ']' and top_object is not '['):
                    print("Syntax Error")
                    return False

        if self.stack.is_empty():
            print("Valid Syntax")
            return True
        print("Syntax Error")
        return False

def main():
    checker = SyntaxChecker()
    checker.check_syntax('{((shubham gupta))')

main()


import math

#計算露點溫度
def td(T,RH):
    r=(17.27*T/(237.7+T)+math.log(RH/100))
    Td=237.7*r/(17.27-r)
    return Td
'''
Td=td(26.1,76)
print(Td)
'''
#計算pasquall大氣穩定度分類
def Uv_value(uv,Uz):
    grade=None
    num=0
    if uv>float(0.8) and Uz<float(2):
        grade='等級A'

    elif uv>float(0.8) and float(2)<=Uz<=float(5):
        grade='等級B'
    elif uv>float(0.8) and Uz>float(5):
        grade='等級C'
    elif float(0.4)<uv<=float(0.8) and Uz<float(3):
        grade='等級B'
    elif float(0.4)<uv<=float(0.8) and float(3)<=Uz<=float(5):
        grade='等級C'
    elif float(0.4)<uv<=float(0.8) and Uz>float(5):
        grade='等級D'
    elif float(0.1)<uv<=float(0.4)and Uz<float(2):
        grade='等級B'
    elif float(0.1)<uv<=float(0.4)and float(2)<=Uz<=float(5):
        grade='等級C'
    elif float(0.1)<uv<=float(0.4)and Uz>float(5):
        grade='等級D'
    elif uv<float(0.1)and Uz<float(2):
        grade='等級F'
    elif uv<float(0.1)and float(2)<=Uz<=float(3):
        grade='等級E'
    elif uv<float(0.1)and Uz>float(3):
        grade='等級D'
    else:
        print('Error')

    if (grade=="等級A"):
        num=1
    if (grade=="等級B"):
        num=2
    if (grade=="等級C"):
        num=3
    if (grade=="等級D"):
        num=4
    if (grade=="等級E"):
        num=5
    if (grade=="等級F"):
        num=6

    return num
'''
print(Uv_value(0.1,0.9))
'''
#計算混合層高
def Mechanical_mixing_height(T,Td,Pasquill,Uz,Z,Z0):
    mechanical_mixing_height=(121/6)*(6-Pasquill)*(T-Td)+(0.169*Pasquill*(Uz+0.257)/(12*0.0000579*math.log(Z/Z0)))
    return mechanical_mixing_height

'''
print(Mechanical_mixing_height(26.1,Td,2,0.9,10,1.2))
'''


# -*- coding: utf-8 -*-

from __future__ import unicode_literals
import logging
try:  # Python 2.7+
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass
import re

import html5lib
from html5lib.sanitizer import HTMLSanitizer
from html5lib.serializer.htmlserializer import HTMLSerializer

from . import callbacks as linkify_callbacks
from .encoding import force_unicode
from .sanitizer import BleachSanitizer
from .version import __version__, VERSION # flake8: noqa

__all__ = ['clean', 'linkify']

log = logging.getLogger(__name__)
log.addHandler(NullHandler())

ALLOWED_TAGS = [
    'a',
    'abbr',
    'acronym',
    'b',
    'blockquote',
    'code',
    'em',
    'i',
    'li',
    'ol',
    'strong',
    'ul',
]

ALLOWED_ATTRIBUTES = {
    'a': ['href', 'title'],
    'abbr': ['title'],
    'acronym': ['title'],
}

ALLOWED_STYLES = []

ALLOWED_PROTOCOLS = ['http', 'https', 'mailto']

TLDS = """ac ad ae aero af ag ai al am an ao aq ar arpa as asia at au aw ax az
       ba bb bd be bf bg bh bi biz bj bm bn bo br bs bt bv bw by bz ca cat
       cc cd cf cg ch ci ck cl cm cn co com coop cr cu cv cx cy cz de dj dk
       dm do dz ec edu ee eg er es et eu fi fj fk fm fo fr ga gb gd ge gf gg
       gh gi gl gm gn gov gp gq gr gs gt gu gw gy hk hm hn hr ht hu id ie il
       im in info int io iq ir is it je jm jo jobs jp ke kg kh ki km kn kp
       kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md me mg mh mil mk
       ml mm mn mo mobi mp mq mr ms mt mu museum mv mw mx my mz na name nc ne
       net nf ng ni nl no np nr nu nz om org pa pe pf pg ph pk pl pm pn post
       pr pro ps pt pw py qa re ro rs ru rw sa sb sc sd se sg sh si sj sk sl
       sm sn so sr ss st su sv sx sy sz tc td tel tf tg th tj tk tl tm tn to
       tp tr travel tt tv tw tz ua ug uk us uy uz va vc ve vg vi vn vu wf ws
       xn xxx ye yt yu za zm zw""".split()

# Make sure that .com doesn't get matched by .co first
TLDS.reverse()

PROTOCOLS = HTMLSanitizer.acceptable_protocols

url_re = re.compile(
    r"""\(*  # Match any opening parentheses.
    \b(?<![@.])(?:(?:{0}):/{{0,3}}(?:(?:\w+:)?\w+@)?)?  # http://
    ([\w-]+\.)+(?:{1})(?:\:[0-9]+)?(?!\.\w)\b   # xx.yy.tld(:##)?
    (?:[/?][^\s\{{\}}\|\\\^\[\]`<>"]*)?
        # /path/zz (excluding "unsafe" chars from RFC 1738,
        # except for # and ~, which happen in practice)
    """.format('|'.join(PROTOCOLS), '|'.join(TLDS)),
    re.IGNORECASE | re.VERBOSE | re.UNICODE)

proto_re = re.compile(r'^[\w-]+:/{0,3}', re.IGNORECASE)

punct_re = re.compile(r'([\.,]+)$')

email_re = re.compile(
    r"""(?<!//)
    (([-!#$%&'*+/=?^_`{0!s}|~0-9A-Z]+
        (\.[-!#$%&'*+/=?^_`{1!s}|~0-9A-Z]+)*  # dot-atom
    |^"([\001-\010\013\014\016-\037!#-\[\]-\177]
        |\\[\001-011\013\014\016-\177])*"  # quoted-string
    )@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6})  # domain
    """,
    re.IGNORECASE | re.MULTILINE | re.VERBOSE)

NODE_TEXT = 4  # The numeric ID of a text node in simpletree.

ETREE_TAG = lambda x: "".join(['{http://www.w3.org/1999/xhtml}', x])
# a simple routine that returns the tag name with the namespace prefix
# as returned by etree's Element.tag attribute

DEFAULT_CALLBACKS = [linkify_callbacks.nofollow]

def clean(text, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES,
          styles=ALLOWED_STYLES, protocols=ALLOWED_PROTOCOLS, strip=False,
          strip_comments=True):
    """Clean an HTML fragment of malicious content and return it

    This function is a security-focused function whose sole purpose is to
    remove malicious content from a string such that it can be displayed as
    content in a web page.

    This function is not designed to use to transform content to be used in
    non-web-page contexts.

    :arg text: the text to clean
    :arg tags: whitelist of allowed tags; defaults to
        ``bleach.ALLOWED_TAGS``
    :arg attributes: whitelist of allowed attributes; defaults to
        ``bleach.ALLOWED_ATTRIBUTES``
    :arg styles: whitelist of allowed css; defaults to
        ``bleach.ALLOWED_STYLES``
    :arg protocols: whitelist of allowed protocols for links; defaults
        to ``bleach.ALLOWED_PROTOCOLS``
    :arg strip: whether or not to strip disallowed elements
    :arg strip_comments: whether or not to strip HTML comments

    """
    if not text:
        return ''

    text = force_unicode(text)

    class s(BleachSanitizer):
        allowed_elements = tags
        allowed_attributes = attributes
        allowed_css_properties = styles
        allowed_protocols = protocols
        strip_disallowed_elements = strip
        strip_html_comments = strip_comments

    parser = html5lib.HTMLParser(tokenizer=s)

    return _render(parser.parseFragment(text))

def linkify(text, callbacks=DEFAULT_CALLBACKS, skip_pre=False,
            parse_email=False, tokenizer=HTMLSanitizer):
    """Convert URL-like strings in an HTML fragment to links

    ``linkify()`` converts strings that look like URLs, domain names and email
    addresses in text that may be an HTML fragment to links, while preserving:

    1. links already in the string
    2. urls found in attributes
    3. email addresses

    ``linkify()`` does a best-effort approach and tries to recover from bad
    situations due to crazy text.

    """
    text = force_unicode(text)

    if not text:
        return ''

    parser = html5lib.HTMLParser(tokenizer=tokenizer)

    forest = parser.parseFragment(text)
    _seen = set([])

    def replace_nodes(tree, new_frag, node, index=0):
        """Doesn't really replace nodes, but inserts the nodes contained in
        ``new_frag`` into ``tree`` at position ``index`` and returns the number
        of nodes inserted.

        If ``node`` is passed in, it is removed from the resulting tree.

        :arg tree: tree
        :arg new_frag: fragment of html text to insert
        :arg node: the node to "replace"
        :arg index: the index position to focus on

        :returns: number of nodes inserted so that you can skip ahead

        """
        count = 0
        new_tree = parser.parseFragment(new_frag)
        # capture any non-tag text at the start of the fragment
        if new_tree.text:
            if index == 0:
                tree.text = (tree.text or '') + new_tree.text
            else:
                tree[index-1].tail = (tree[index-1].tail or '') + new_tree.text

        # then put in the tagged elements into the old tree
        for n in new_tree:
            if n.tag == ETREE_TAG('a'):
                _seen.add(n)
            tree.insert(index + count, n)
            count += 1

        # if we got a node to remove...
        if node is not None:
            # first, grab the node tail so we don't lose text
            if node.tail:
                if index + count == 0:
                    tree.text = (tree.text or '') + node.tail
                else:
                    tree[index+count-1].tail = (tree[index+count-1].tail or '') + node.tail
            tree.remove(node)
        return count

    def strip_wrapping_parentheses(fragment):
        """Strips wrapping parentheses.

        Returns a tuple of the following format::

            (string stripped from wrapping parentheses,
             count of stripped opening parentheses,
             count of stripped closing parentheses)
        """
        opening_parentheses = closing_parentheses = 0
        # Count consecutive opening parentheses
        # at the beginning of the fragment (string).
        for char in fragment:
            if char == '(':
                opening_parentheses += 1
            else:
                break

        if opening_parentheses:
            newer_frag = ''
            # Cut the consecutive opening brackets from the fragment.
            fragment = fragment[opening_parentheses:]
            # Reverse the fragment for easier detection of parentheses
            # inside the URL.
            reverse_fragment = fragment[::-1]
            skip = False
            for char in reverse_fragment:
                # Remove the closing parentheses if it has a matching
                # opening parentheses (they are balanced).
                if (char == ')' and
                        closing_parentheses < opening_parentheses and
                        not skip):
                    closing_parentheses += 1
                    continue
                # Do not remove ')' from the URL itself.
                elif char != ')':
                    skip = True
                newer_frag += char
            fragment = newer_frag[::-1]

        return fragment, opening_parentheses, closing_parentheses

    def apply_callbacks(attrs, new):
        for cb in callbacks:
            attrs = cb(attrs, new)
            if attrs is None:
                return None
        return attrs

    def _render_inner(node):
        out = ['' if node.text is None else node.text]
        for subnode in node:
            out.append(_render(subnode))
            if subnode.tail:
                out.append(subnode.tail)
        return ''.join(out)

    def linkify_nodes(tree, parse_text=True):
        children = len(tree)
        current_child = -1
        # start at -1 to process the parent first
        while current_child < len(tree):
            if current_child < 0:
                node = tree
                if parse_text and node.text:
                    new_txt = old_txt = node.text
                    if parse_email:
                        new_txt = re.sub(email_re, email_repl, node.text)
                        if new_txt and new_txt != node.text:
                            node.text = ''
                            adj = replace_nodes(tree, new_txt, None, 0)
                            children += adj
                            current_child += adj
                            linkify_nodes(tree, True)
                            continue

                    new_txt = re.sub(url_re, link_repl, new_txt)
                    if new_txt != old_txt:
                        node.text = ''
                        adj = replace_nodes(tree, new_txt, None, 0)
                        children += adj
                        current_child += adj
                        continue
            else:
                node = tree[current_child]

            if parse_text and node.tail:
                new_tail = old_tail = node.tail
                if parse_email:
                    new_tail = re.sub(email_re, email_repl, new_tail)
                    if new_tail != node.tail:
                        node.tail = ''
                        adj = replace_nodes(tree, new_tail, None,
                                            current_child + 1)
                        # Insert the new nodes made from my tail into
                        # the tree right after me. current_child+1
                        children += adj
                        continue

                new_tail = re.sub(url_re, link_repl, new_tail)
                if new_tail != old_tail:
                    node.tail = ''
                    adj = replace_nodes(tree, new_tail, None,
                                        current_child + 1)
                    children += adj

            if node.tag == ETREE_TAG('a') and not (node in _seen):
                if not node.get('href', None) is None:
                    attrs = dict(node.items())

                    _text = attrs['_text'] = _render_inner(node)

                    attrs = apply_callbacks(attrs, False)

                    if attrs is None:
                        # #  tag replaced by the text within it
                        adj = replace_nodes(tree, _text, node, current_child)
                        # pull back current_child by 1 to scan the new nodes
                        # again.
                        current_child -= 1
                    else:
                        text = force_unicode(attrs.pop('_text'))
                        for attr_key, attr_val in attrs.items():
                            node.set(attr_key, attr_val)

                        for n in reversed(list(node)):
                            node.remove(n)
                        text = parser.parseFragment(text)
                        node.text = text.text
                        for n in text:
                            node.append(n)
                        _seen.add(node)

            elif current_child >= 0:
                if node.tag == ETREE_TAG('pre') and skip_pre:
                    linkify_nodes(node, False)
                elif not (node in _seen):
                    linkify_nodes(node, parse_text)

            current_child += 1

    def email_repl(match):
        addr = match.group(0).replace('"', '"')
        link = {
            '_text': addr,
            'href': 'mailto:{0!s}'.format(addr),
        }
        link = apply_callbacks(link, True)

        if link is None:
            return addr

        _href = link.pop('href')
        _text = link.pop('_text')

        repl = '{2!s}'
        attr = '{0!s}="{1!s}"'
        attribs = ' '.join(attr.format(k, v) for k, v in link.items())
        return repl.format(_href, attribs, _text)

    def link_repl(match):
        url = match.group(0)
        open_brackets = close_brackets = 0
        if url.startswith('('):
            _wrapping = strip_wrapping_parentheses(url)
            url, open_brackets, close_brackets = _wrapping
        if url.endswith(')') and '(' not in url:
            # This is a clumsy handling for the case where we have something
            # like (foo http://example.com) and the ) gets picked up by the
            # url_re but we don't want it part of the link.
            new_url = url.rstrip(')')
            close_brackets += len(url) - len(new_url)
            url = new_url

        end = ''
        m = re.search(punct_re, url)
        if m:
            end = m.group(0)
            url = url[0:m.start()]
        if re.search(proto_re, url):
            href = url
        else:
            href = ''.join(['http://', url])

        link = {
            '_text': url,
            'href': href,
        }

        link = apply_callbacks(link, True)

        if link is None:
            return '(' * open_brackets + url + ')' * close_brackets

        _text = link.pop('_text')
        _href = link.pop('href')

        repl = '{0!s}{3!s}{4!s}{5!s}'
        attr = '{0!s}="{1!s}"'
        attribs = ' '.join(attr.format(k, v) for k, v in link.items())

        return repl.format('(' * open_brackets,
                           _href, attribs, _text, end,
                           ')' * close_brackets)

    try:
        linkify_nodes(forest)
    except RuntimeError as e:
        # If we hit the max recursion depth, just return what we've got.
        log.exception('Probable recursion error: {0!r}'.format(e))

    return _render(forest)

def _render(tree):
    """Try rendering as HTML, then XML, then give up."""
    return force_unicode(_serialize(tree))

def _serialize(domtree):
    walker = html5lib.treewalkers.getTreeWalker('etree')
    stream = walker(domtree)
    serializer = HTMLSerializer(quote_attr_values=True,
                                alphabetical_attributes=True,
                                omit_optional_tags=False)
    return serializer.render(stream)


import os
from flask import request, redirect, session, abort  # install
from flask import render_template, send_file, jsonify
from flask import Blueprint
from PIL import Image  # install
from config import Config

album_app = Blueprint('album', __name__)

# 从config文件中加载相册相关配置
FILE_ALBUM_RAW_PATH = Config.FILE_ALBUM_RAW_PATH
FILE_ALBUM_COM_PATH = Config.FILE_ALBUM_COM_PATH
FILE_ALBUM_COM_PATH_R = Config.FILE_ALBUM_COM_PATH_R
THUMBNAIL_SIZE = Config.THUMBNAIL_SIZE  # 缩略图大小
COMPRESS_RATIO = Config.COMPRESS_RATIO  # 压缩比率

@album_app.route('/album', methods=['GET'])
def album():
    """
    相册界面
    """
    username = session.get('username')
    authority = session.get('authority')
    # 未登录则需先登录
    if not username:
        return redirect('/login')
    # 不是1、2高管理员则返回404
    if authority == 3:
        abort(404)

    files = os.listdir(FILE_ALBUM_COM_PATH)
    files.sort()
    rlst = []
    for file in files:
        rlst.append(file)
    return render_template('album.jinja', img_list=rlst)

@album_app.route('/api/album', methods=['POST'])
def upload_file_album():
    """
    上传相册图片
    """
    username = session.get('username')
    authority = session.get('authority')
    # 未登录或权限为普通用户则返回-1
    if not username or authority == 3:
        return '-1'

    files = request.files.getlist('file')
    for f in files:
        filename = f.filename
        print(filename)
        try:
            # 保存原图
            f.save(FILE_ALBUM_RAW_PATH+filename)
            im = Image.open(f)
            ext = filename.split('.')[-1]
            # 压缩图片并保存缩略图
            if ext == 'png' or ext == 'webp' or ext == 'gif':
                im.save(FILE_ALBUM_COM_PATH+filename)
            else:
                im.save(FILE_ALBUM_COM_PATH+filename, quality=COMPRESS_RATIO)
        except:
            return '0'
    return '1'

@album_app.route('/api/editormd/album', methods=['POST'])
def upload_file_editormd_image():
    """
    上传editormd相册图片
    """
    username = session.get('username')
    authority = session.get('authority')
    # 未登录或权限为普通用户则返回-1

    if not username or authority == 3:
        res = {
            'success': 0,
            'message': '上传图片失败，权限不足'
        }
        return jsonify(res)

    file = request.files['editormd-image-file']
    if not file:
        res = {
            'success': 0,
            'message': '上传图片失败，未发现文件！'
        }
        return jsonify(res)

    filename = file.filename

    if os.path.exists(FILE_ALBUM_COM_PATH+filename):
        res = {
            'success': 0,
            'message': '上传图片失败，文件名重复！'
        }
        return jsonify(res)

    try:
        # 保存原图
        file.save(FILE_ALBUM_RAW_PATH+filename)
        im = Image.open(file)
        ext = filename.split('.')[-1]
        # 压缩图片并保存缩略图
        if ext == 'png' or ext == 'webp' or ext == 'gif':
            im.save(FILE_ALBUM_COM_PATH+filename)
        else:
            im.save(FILE_ALBUM_COM_PATH+filename, quality=COMPRESS_RATIO)
    except:
        res = {
            'success': 0,
            'message': '上传图片失败，未保存成功！'
        }
        return jsonify(res)

    res = {
        'success': 1,
        'message': '图片上传成功！',
        'url': '/album/'+filename
    }
    return jsonify(res)

@album_app.route('/album/<filename>', methods=['GET'])
def get_album_img(filename):
    """
    获取相册图片
    """
    return send_file(FILE_ALBUM_COM_PATH_R+filename)

@album_app.route('/api/album', methods=['DELETE'])
def delete_file_album():
    """
    删除相册图片
    """
    username = session.get('username')
    authority = session.get('authority')
    # 未登录或权限不为1则返回-1
    if not username or authority != 1:
        return '-1'

    filename = request.args.get('name')
    # filename=parse.quote(filename) # url解码
    if not os.path.exists(FILE_ALBUM_COM_PATH+filename):
        return '0'
    # 只删除压缩后的图，原图不删
    try:
        os.remove(FILE_ALBUM_COM_PATH+filename)
        return '1'
    except:
        return '0'


import argparse
import os
import torch
import csv
import sys
import copy
from util import *
from torch import nn, optim
#from dataset import KpApF107Dataset
from dataset0 import OilDataset
from LSTMmodel import PredictorLSTM
from torch.utils.data import DataLoader

from torchvision import transforms

parser = argparse.ArgumentParser()
parser.add_argument('--dataset_dir', type=str, default='../data/Oil/', help='dir of the dataset')

parser.add_argument('--data_type', type=str, default='Oil', help='KP|AP|F10.7|Oil')
parser.add_argument('--time_step', type=int, default= 7, help=' it indicates day')
parser.add_argument('--pred_len', type=int, default= 1, help=' it indicates predicted day')

parser.add_argument('--input_size', type=int, default= (198,30, 20, 10), help='the length of every timestep')
parser.add_argument('--hidden_size', type=int, default=(30, 20, 10, 10), help='the output length of every timestep ')
parser.add_argument('--num_layers', type=int, default=4, help='the number of lstm layer(vertical)')
parser.add_argument('--out_size', type=int, default=1, help='the length of predicted sequence')

parser.add_argument('--batch_size', type=int, default=10, help='size of the batches')
parser.add_argument('--lr', type=float, default=0.0002, help='adam: learning rate')
parser.add_argument('--b1', type=float, default=0.5, help='adam: decay of first order momentum of gradient')
parser.add_argument('--b2', type=float, default=0.999, help='adam: decay of first order momentum of gradient')
parser.add_argument('--milestones', type=list, default=[15,25], help=' setup MultiStepLR ')
#parser.add_argument('--n_cpu', type=int, default=8, help='number of cpu threads to use during batch generation')
parser.add_argument('--n_epoch', type=int, default=35, help='number of epochs of training')

#parser.add_argument('--start_test_epoch', type=int, default=50, help='epoch of start testing during training')
parser.add_argument('--checkpoint_dir', type=str, default='./checkpoint', help='dir of save file and model')
parser.add_argument('--checkpoint_batch', type=int, default=10, help='10 times in a epoch')
#parser.add_argument('--checkpoint_epoch', type=int, default=1, help=' the number of interval epoch (save model and print loss)')

opt = parser.parse_args()
print(opt)

save_model_dir = os.path.join(opt.checkpoint_dir, 'model')
if os.path.exists(save_model_dir) is False:
    os.makedirs(save_model_dir)

save_file_dir = os.path.join(opt.checkpoint_dir, 'ckpt')
if os.path.exists(save_file_dir) is False:
    os.makedirs(save_file_dir)

test_mse_path = os.path.join(save_file_dir, 'test_mse.csv')
'''
if os.path.exists(test_mse_path) is True:
    os.remove(test_mse_path)
'''
data_fname = ['oil_198_train.xls', 'oil_198_test.xls']
train_data_path = os.path.join(opt.dataset_dir, data_fname[0])
test_data_path = os.path.join(opt.dataset_dir, data_fname[1])

train_dataset = OilDataset(train_data_path, opt.time_step, opt.pred_len, opt.data_type)
test_dataset = OilDataset(test_data_path, opt.time_step, opt.pred_len, opt.data_type)

#train_loader = DataLoader(train_dataset, batch_size=opt.batch_size, shuffle=True, num_workers=opt.n_cpu)
train_loader = DataLoader(train_dataset, batch_size=opt.batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=opt.batch_size, shuffle=False)

model = PredictorLSTM(opt.input_size, opt.hidden_size, opt.num_layers, opt.out_size)  # 27 *8
use_gpu = True if torch.cuda.is_available() else False
if use_gpu:
    model = model.cuda()

criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=opt.lr,  betas=(opt.b1, opt.b2))
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=opt.milestones, gamma=0.5)

header = ['epoch/total_epoch', 'test_mse']
with open(test_mse_path, 'w') as testcsvmes: # open trainfile
    writertest = csv.writer(testcsvmes)
    writertest.writerow(header)
    # trainning
    for epoch in range(1, opt.n_epoch + 1):
        print('\repoch {}'.format(epoch))
        scheduler.step()
        print('*' * 10)
        model.train()
        for i, (input, label, minvalue, maxvalue) in enumerate(train_loader):

            if use_gpu:
                input = torch.FloatTensor(input).cuda()
                label = torch.FloatTensor(label).cuda()
            else:
                input = torch.FloatTensor(input)
                label = torch.FloatTensor(label)

            label = label.squeeze(2)
            # foreward
            pred = model(input)
            loss = criterion(pred, label)

            # backward
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            if (i +1) % opt.checkpoint_batch ==0:
                print("[Epoch %d/%d] [Batch %d/%d] [MSEloss: %f] " %
                                     (epoch, opt.n_epoch, i+1, len(train_loader), loss))

            #sys.stdout.write("\r[Epoch %d/%d] [Batch %d/%d] [MSEloss: %f] " %
            #                     (epoch, opt.n_epoch, i+1, len(train_loader), loss/opt.batch_size))
        # save model
        save_model(model, epoch=epoch, data_type=opt.data_type, save_model_dir=save_model_dir)
        save_model(model, epoch='latest', data_type=opt.data_type, save_model_dir=save_model_dir)
        # evaluate model in testdata
        testmes = evaluate_model(model, test_loader, criterion)
        #print(testmes[0])
        writertest.writerow([str(epoch)+'/'+str(opt.n_epoch), testmes[0]])

    #plot_curve(test_results_path, datatype = opt.data_type, savedir = test_results_dir)


import textwrap
import itertools
import numpy as np
from typing import Optional, Tuple

def get_test_input() -> str:
    return textwrap.dedent("""\
    0,9 -> 5,9
    8,0 -> 0,8
    9,4 -> 3,4
    2,2 -> 2,1
    7,0 -> 7,4
    6,4 -> 2,0
    0,9 -> 2,9
    3,4 -> 1,4
    0,0 -> 8,8
    5,5 -> 8,2""")

# class Line(object):
#     def __init__(self, s):
#         val1, val2 = s.split('->')
#         start = tuple(int(x) for x in val1.split(','))
#         end = tuple(int(x) for x in val2.split(','))
#         self.coeffs = sp.Matrix([[end[1]-start[1], start[0]-end[0],
#                                 (end[1]-start[1])*start[0] + (start[0]-end[0])*start[1]]])
#
#     def __str__(self):
#         return f'{self.coeffs[0]}x + {self.coeffs[1]}y = {self.coeffs[2]}'
#
#     def __repr__(self):
#         return str(self)
#
#     def intersection(self, other) -> Optional[Tuple[int]]:
#         mat = sp.Matrix([self.coeffs, other.coeffs])
#         red, piv = mat.rref()
#
#         if piv == (0,1):    # intersection is a point
#             point = tuple(mat.col(2))
#             if point[0].is_integer() and point[1].is_integer():
#                 return point
#             else:
#                 return None
#
#         elif piv == (0,):   # intersection is a vertical line
#
#         elif piv == (1,):   # intersection is a horizontal line
#
#         else:
#             return None

def sign(x):
    return 1 if x > 0 else (-1 if x < 0 else 0)

class Line(object):
    def __init__(self, s):
        val1, val2 = s.split('->')
        self.start = np.array(tuple(int(x) for x in val1.split(',')))
        self.end = np.array(tuple(int(x) for x in val2.split(',')))

    def __str__(self):
        return f'{self.start} -> {self.end}'

    def __repr__(self):
        return str(self)

    def fill_grid(self, grid):
        if self.start[0] == self.end[0]:
            miny = min(self.start[1], self.end[1])
            maxy = max(self.start[1], self.end[1])
            for y in range(miny, maxy+1, 1):
                grid[y][self.start[0]] += 1
        elif self.start[1] == self.end[1]:
            minx = min(self.start[0], self.end[0])
            maxx = max(self.start[0], self.end[0])
            for x in range(minx, maxx+1, 1):
                grid[self.start[1]][x] += 1
        else:
            xstep = sign(self.end[0] - self.start[0])
            ystep = sign(self.end[1] - self.start[1])
            for x, y in zip(range(self.start[0], self.end[0]+xstep, xstep),
                            range(self.start[1], self.end[1]+ystep, ystep)):
                grid[y][x] += 1

def read_input(day_number, test=False):
    if test:
        return parse_input(get_test_input())
    else:
        filename = 'input/day{}.txt'.format(day_number)
        with open(filename, 'r') as file:
            return parse_input(file.read())

def parse_input(s: str):
    data = np.zeros((1000, 1000))
    for line in s.splitlines():
        Line(line).fill_grid(data)
    return data

def part_1(data):
    tot = 0
    for row in data:
        #print(row)
        for val in row:
            if val > 1:
                tot += 1
    print(f'Part 1: {tot}')

def part_2(data):
    pass

def main():
    data = read_input(day_number=5, test=False)
    part_1(data)
    part_2(data)

if __name__ == "__main__":
    main()


import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
import pylab
import math
import numpy as np
import os
from copy import deepcopy

def plotter_single(fig, ax, x_follow, y_follow, x_nonzero, y_nonzero, \
      frame, remove_ped, num_peds_real, num_peds_follow, ped_mu_x, ped_mu_y, \
      optima, optima_dex, num_optima, robot_mu_x, robot_mu_y, \
      robot_history_x, robot_history_y, cmd_x, cmd_y, ess_time, ess_ave_time, \
      ess_std_time, ess, time, top_Z_indices, chandler, data_set, \
      p2w_x, p2w_y, p2w, radius, show_radius, scaling, num_var_samples, mc, \
      opt_iter_robot, opt_iter_all):
  cm = pylab.get_cmap('plasma')

  ax.clear()
# PLOT DENSITY CIRCLE
  if show_radius:
    density_circle = plt.Circle((cmd_x*p2w_x, cmd_y*p2w_y), radius, \
                                color='b', fill=False)
    ax.add_artist(density_circle)
# PLOT AGENT TRAJECTORIES[FRAME:}, REMOVE ZEROS
  lookahead = 10
  for ped in range(num_peds_follow):
    if data_set == 'eth_train':
      x_temp = x_follow[ped][frame:frame+lookahead]
      y_temp = y_follow[ped][frame:frame+lookahead]
      x_temp = x_temp[np.nonzero(x_temp)]
      y_temp = y_temp[np.nonzero(y_temp)]
    if data_set == 'eth_test':
      x_temp = x_follow[ped][frame:]
      y_temp = y_follow[ped][frame:]
      x_temp = x_temp[np.nonzero(x_temp)]
      y_temp = y_temp[np.nonzero(y_temp)]
    ax.plot(x_temp*p2w_x, y_temp*p2w_y, ".-k", markersize=2)

# PLOT ALL PED_MU
  # for ped in range(num_peds_follow):
  #   ax.plot(ped_mu_x[ped]*p2w_x, ped_mu_y[ped]*p2w_y, \
  #           "x",markersize=2)
# PLOT TOP PED_MU
  # for ped in range(ess):
  #   top = top_Z_indices[ped]
  #   ax.plot(ped_mu_x[top]*p2w_x, ped_mu_y[top]*p2w_y, "x", markersize=2)

# PLOT ROBOT_MU
  ax.plot(robot_mu_x*p2w_x, robot_mu_y*p2w_y, "+g", markersize=3)

# PLOT REMOVE PED
  ax.plot(x_nonzero*p2w_x, y_nonzero*p2w_y, "--^g", markersize=1)

# PLOT TOP ESS AGENTS WITH RANK
  # for ped in range(ess):
  #   top = top_Z_indices[ped]
  #   ax.annotate(ped, xy=(x_follow[top][frame]*p2w_x, \
  #                        y_follow[top][frame]*p2w_y), \
  #                        fontsize=6, fontweight='bold', color='cyan')

# PLOT TRUE NUMBERS OF ALL AGENTS
  # for ped in range(num_peds_follow):
  #   ax.annotate(ped, xy=(x_follow[ped][frame]*p2w_x, \
  #                        y_follow[ped][frame]*p2w_y), \
  #                        fontsize=5, fontweight='bold', color='cyan')

# PLOT OPTIMA, EITHER ITERATE OR SCIPY
  # color=0
  # T = np.size(robot_mu_x)
  # for intent in range(num_optima):
  #   n=0
  #   for ped in range(ess+1):
  #     if opt_iter_robot or opt_iter_all:
  #       if n == 0:
  #         ax.plot(optima[intent][n*T:(n+1)*T]*p2w_x, \
  #                 optima[intent][(n+1)*T:(n+2)*T]*p2w_y, \
  #                 'xr', markersize=1)
  #       else:
  #         ax.plot(optima[intent][n*T:(n+1)*T]*p2w_x, \
  #                 optima[intent][(n+1)*T:(n+2)*T]*p2w_y, \
  #                 'xb', markersize=1)
  #                 # '.', color = cm(1.*color), markersize=3)
  #     else:
  #       if n == 0:
  #         ax.plot(optima[intent].x[n*T:(n+1)*T]*p2w_x, \
  #                 optima[intent].x[(n+1)*T:(n+2)*T]*p2w_y, \
  #                 'xr', markersize=1)
  #       else:
  #         ax.plot(optima[intent].x[n*T:(n+1)*T]*p2w_x, \
  #                 optima[intent].x[(n+1)*T:(n+2)*T]*p2w_y, \
  #                 'xb', markersize=1)
  #               # '.', color = cm(1.*color), markersize=3)
  #     n = n + 2
  #   color = color + 10

# PLOT JOINT OPTIMA WITH LARGEST LL
  n = 0
  intent = 0
  T = np.size(robot_mu_x)
  for ped in range(ess+1):
    if mc:
      if n == 0:
        ax.plot(optima[n*T:(n+1)*T]*p2w_x, optima[(n+1)*T:(n+2)*T]*p2w_y, \
                  'xr', markersize=1)
      else:
        ax.plot(optima[n*T:(n+1)*T]*p2w_x, optima[(n+1)*T:(n+2)*T]*p2w_y, \
                  'xc', markersize=1)
    else:
      if opt_iter_robot or opt_iter_all:
        if n == 0:
          ax.plot(optima[optima_dex[0]][n*T:(n+1)*T]*p2w_x, \
                    optima[optima_dex[0]][(n+1)*T:(n+2)*T]*p2w_y, \
                    'xr', markersize=1)
        else:
          ax.plot(optima[optima_dex[0]][n*T:(n+1)*T]*p2w_x, \
                    optima[optima_dex[0]][(n+1)*T:(n+2)*T]*p2w_y, \
                    'xc', markersize=1)
      else:
        if n == 0:
          ax.plot(optima[optima_dex[0]].x[n*T:(n+1)*T]*p2w_x, \
                    optima[optima_dex[0]].x[(n+1)*T:(n+2)*T]*p2w_y, \
                    'xr', markersize=1)
        else:
          ax.plot(optima[optima_dex[0]].x[n*T:(n+1)*T]*p2w_x, \
                    optima[optima_dex[0]].x[(n+1)*T:(n+2)*T]*p2w_y, \
                    'xc', markersize=1)
    n = n + 2

# PLOT CURRENT POSE OF ALL AGENTS EXCEPT REMOVE_PED
  for ped in range(num_peds_follow):
    ax.plot(x_follow[ped][frame]*p2w_x, y_follow[ped][frame]*p2w_y, \
            "ob", markersize=3)

# PLOT CURRENT POSE OF REMOVE_PED
  if frame<np.size(x_nonzero):
    ax.plot(x_nonzero[frame]*p2w_x, y_nonzero[frame]*p2w_y, "og", markersize=4)

# PLOT CURRENT POSE OF ROBOT
  ax.plot(cmd_x*p2w_x, cmd_y*p2w_y, 'py', markersize=4)

# PLOT HISTORY OF ROBOT
  ax.plot(robot_history_x*p2w_x, robot_history_y*p2w_y, 'x--r', markersize=2)

  plt.xlabel('X Position',fontsize=10)
  plt.ylabel('Y position',fontsize=10)

  ess_time = math.trunc(ess_time*1e3)/1e3
  ess_ave_time = math.trunc(ess_ave_time*1e3)/1e3
  ess_std_time = math.trunc(ess_std_time*1e3)/1e3

  if frame==0:
    ave_time = time[frame]
    std_time = time[frame]
    max_time = math.trunc((1/(num_var_samples+1))*time[frame]*1e3)/1e3
  else:
    ave_time = np.mean(time[:frame])
    std_time = np.std(time[:frame])
    max_time = math.trunc((1/(num_var_samples+1))*np.max(time[:frame])*1e3)/1e3

  time_now = math.trunc((1/(num_var_samples+1))*time[frame]*1e3)/1e3
  ave_time = math.trunc((1/(num_var_samples+1))*ave_time*1e3)/1e3
  std_time = math.trunc((1/(num_var_samples+1))*std_time*1e3)/1e3

  plt.title('Frame {0}, t_now={2}, t_max = {5}, t_ave={3}+/-{4}, ESS={1}'.\
format(frame, ess, time_now, ave_time, std_time, max_time), fontsize=7)

  if data_set == 'eth_test':
    ax.set_xlim(-scaling*9,scaling*15)
    ax.set_ylim(scaling*2,scaling*9)
  if data_set == 'eth_train':
    if cmd_x*p2w_x > scaling*3. and cmd_x*p2w_x < scaling*10.:
      if cmd_y*p2w_y > scaling*7. and cmd_y*p2w_y < scaling*19.:
        ax.set_xlim(scaling*1,scaling*11)
        ax.set_ylim(scaling*5,scaling*15)
    if cmd_x*p2w_x >= scaling*0. and cmd_x*p2w_x < scaling*8.:
      if cmd_y*p2w_y >= scaling*0. and cmd_y*p2w_y < scaling*7:
        ax.set_xlim(-1.,scaling*9)
        ax.set_ylim(-1.,scaling*9)
    if cmd_x*p2w_x > scaling*8. and cmd_x*p2w_x < scaling*19.:
      if cmd_y*p2w_y > scaling*0. and cmd_y*p2w_y < scaling*10:
        ax.set_xlim(scaling*3,scaling*16)
        ax.set_ylim(scaling*0,scaling*13)

  plt.pause(0.001)


import copy
import execute
import argparse
import warnings
import logging as logger

warnings.filterwarnings("ignore")

logger.basicConfig(level=logger.INFO,format='%(message)s')

if __name__ == "__main__":
    # add parser arguments to enable question wise execution
    parser = argparse.ArgumentParser()
    parser.add_argument("--ques", "-q", help="execute question number (a,b,c,d,e)")
    args = parser.parse_args()
    args_dict = vars(copy.deepcopy(args))

    ques = args_dict['ques']

    # execute the corresponding question as per command line input

    if ques == '1':     execute.question_1()
    elif ques == '2':   execute.question_2()
    elif ques == '3':   execute.question_3()
    elif ques == '4':   execute.question_4()
    elif ques == '5':   execute.question_5()
    else:               logger.info("Input correct question number as command-line argument")

Project 3 - Collaborative Filtering/Scripts/project3.py


import os
import datetime
from environs import Env

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

URI = 'mysql+pymysql://{0}:{1}@{2}:{3}/{4}'.format(
    os.environ.get("DB_USERNAME"),
    os.environ.get("DB_PASSWORD"),
    os.environ.get("DB_HOST"),
    os.environ.get("DB_PORT"),
    os.environ.get("DB_NAME")
)

env = Env()
env.read_env()

ENV = env.str('FLASK_ENV', default='settings.dev_settings')
DEBUG = ENV == 'development'
SQLALCHEMY_DATABASE_URI = URI
SECRET_KEY = '(1#p1r1xt_^%2-)yc=$6f+olxszb1xzmm_phx_#bnt&nn)j!c7'
BCRYPT_LOG_ROUNDS = env.int('BCRYPT_LOG_ROUNDS', default=13)
# DEBUG_TB_ENABLED = DEBUG
# DEBUG_TB_INTERCEPT_REDIRECTS = False
# CACHE_TYPE = 'simple'  # Can be "memcached", "redis", etc.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# WEBPACK_MANIFEST_PATH = 'webpack/manifest.json'
# REDIS_URL = "redis://0.0.0.0:6379/0"
# REDIS_URL = env.str('REDIS_URL', None)

# JWT settings
JWT_SECRET_KEY = SECRET_KEY
JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(days=7)
JWT_ACCESS_COOKIE_PATH = "/"
JWT_TOKEN_LOCATION = ['cookies']
JWT_ERROR_MESSAGE_KEY = "message"
JWT_ACCESS_COOKIE_NAME = "x-access-token"
JWT_HEADER_TYPE = "Bearer"
JWT_BLACKLIST_ENABLED = True
JWT_BLACKLIST_TOKEN_CHECKS = ['access', 'refresh']


import matplotlib.pyplot as plt
import numpy as np
import math
# from matplotlib.widgets import Slider
plt.style.use('ggplot')

n = 600
dt = 0.01
m = 1.0
g = 10.0
r = 2.0
alpha = 30.0
wysokosc = 30.0
alphaRadian = (alpha % 360) / 180 * np.pi

num = 2

baseI = m * r**2
brylaNazwa = ['Kula 2/5', 'Walec 1/2', 'sfera 2/3']
brylaW = [2.0 / 5, 1.0 / 2, 2.0/3]
brylaI = [baseI*x for x in brylaW]
brylaMn = [1.0/(1+x) for x in brylaW]
brylaA = [x*g*np.sin(alphaRadian) for x in brylaMn]
ep = [x/r for x in brylaA]

fig, plotGrid = plt.subplots(2,num)
plt.subplots_adjust(left=.05, bottom=.05, right=.95, top=.95)

for id in range(num):
    szybkosc = np.zeros((n, ), dtype=float)
    szybkosc[0]=0
    droga = np.zeros((n, ), dtype=float)
    droga[0]=0

    omega = np.zeros((n, ), dtype=float)
    beta = np.zeros((n, ), dtype=float)
    ek = np.zeros((n, ), dtype=float)
    omega[0]=0
    beta[0]=0
    ek[0]=0

    koniec=n
    for moment in range(1, n):
        szybkoscPol = szybkosc[moment-1]+brylaA[id]*dt/2
        szybkosc[moment] = szybkosc[moment-1] + brylaA[id]*dt
        droga[moment]= droga[moment-1]+szybkoscPol*dt

        omegaPol = omega[moment-1]+ep[id]*dt/2
        omega[moment] = omega[moment-1]+ep[id]*dt
        beta[moment] = beta[moment-1]+omegaPol*dt
        ek[moment] = m * szybkosc[moment]**2 / 2 + brylaI[id]*omega[moment]**2 / 2

        if wysokosc - droga[moment] * np.sin(alphaRadian) <=0:
            koniec = moment
            break

    x = droga * np.cos(alphaRadian)
    y = wysokosc + r - droga*np.sin(alphaRadian)
    epot = (y-r)*g*m

    xcy = x+r*np.sin(beta)
    ycy = y+r*np.cos(beta)
    ex = np.linspace(0, koniec*dt, koniec)

    plotGrid[0,id].plot(ex,epot[:koniec], label='potential')
    plotGrid[0,id].plot(ex,ek[:koniec], label='kinetic')
    plotGrid[0,id].legend(fancybox=True)
##    tmp = ek+epot
##    plotGrid[0,id].plot(ex,tmp[:koniec])

    plotGrid[1,id].plot(x, y)
    plotGrid[1,id].plot(xcy[:koniec], ycy[:koniec])
    plotGrid[1,id].set_title(brylaNazwa[id])
    plotGrid[1,id].axis('equal')

    del x
    del y
    del epot
    del xcy
    del ycy
    del ex
    del szybkosc
    del droga
    del omega
    del beta
    del ek

plt.show()


from django.urls import path
from . import views

urlpatterns = [
    path('', views.taskList, name='task-list'),
    path('task/<int:id>', views.taskView, name='task-view'),
    path('newtask/', views.newTask, name='new-task'),
    path('edittask/<int:id>', views.editTask, name='edit-task'),
    path('deletetask/<int:id>', views.deleteTask, name='delete-task'),
]


import RPi.GPIO as GPIO, time, sys

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
p = GPIO.PWM(17, 1800)
p.start(50)
p.ChangeDutyCycle(50)
for i in range(0, 450):
	p.ChangeFrequency(i+900)
	time.sleep(0.003)
# 	p.ChangeFrequency(1400)
# 	time.sleep(0.11)
p.ChangeDutyCycle(0)
GPIO.cleanup()
sys.exit(0)


from django.db import models
from authenticator.models import Employee, Service
from django.utils import timezone
import datetime
from inventory.models import Product
# Create your models here.

class Customer(models.Model):
    name = models.CharField(max_length=30,null=False)
    mobile = models.CharField(max_length=13,null=False)
    email = models.CharField(max_length=30,null=True)
    dob = models.DateField(blank=True, null=True, default=None)
    anniversary = models.DateField(blank=True, null=True, default=None)
    class Meta:
        verbose_name = "Client"
        verbose_name_plural = "Clients"
    def __str__(self):
        return self.name
    def getB(self):
        return self.dob.strftime("%Y-%m-%d").split("-")[1:]
    def getA(self):
        return self.anniversary.strftime("%Y-%m-%d").split("-")[1:]
    def is_birthday(self):
        if self.dob == None:
            return False
        month, day = datetime.date.today().strftime("%Y-%m-%d").split("-")[1:]
        bm, bd = self.getB()
        return day == bd and month == bm
    def is_anniversary(self):
        if self.anniversary == None:
            return False
        month, day = datetime.date.today().strftime("%Y-%m-%d").split("-")[1:]
        am, ad = self.getA()
        return day == ad and month == am
    @property
    def communication_type(self):
        type="none"
        if self.mobile and self.email:
            type="both"
        else:
            if self.mobile:
                type="sms"
            elif self.email:
                type="mail"
        return type

    @property
    def is_special_day(self):
        return self.is_birthday() or self.is_anniversary()

class Discount(models.Model):
    label = models.CharField(max_length=30,null=True)
    percentage = models.IntegerField(default=10)

class BillQuerySet(models.QuerySet):
    def total_bill(self):
        return list(self.aggregate(models.Sum('final_amount')).values())[0]
    def avg_bill(self):
        return list(self.aggregate(models.Avg('final_amount')).values())[0]
    def bill_count(self):
        return self.count()
    def this_month(self):
        start_of_month = timezone.now().today().replace(day=1)
        return self.filter(created_at__gte=start_of_month)
    def today(self):
        today = timezone.localtime().replace(hour=0, minute=0, second=0, microsecond=0)
        return self.filter(created_at__gte=today)

class BillManager(models.Manager):
    user_for_related_fields = True

    def get_queryset(self):
        return BillQuerySet(self.model, using=self._db)

class Bill(models.Model):
    objects = BillManager()

    DISCOUNTS = (
        (0,"0%"),
        (5,"5%"),
        (10,"10%"),
        (15,"15%")
    )
    GIFTS = (
        ("N", "None"),
        ("C", "Coupon"),
        ("V", "Voucher")
    )
    discount = models.IntegerField(default=0)
    amount = models.FloatField(default=0.0,null=True, blank= True)
    taxable_amount = models.FloatField(default=0.0, null=True, blank=True)
    final_amount = models.FloatField(default=0.0,null=True, blank= True)
    gst = models.FloatField(default=0.0, null=True, blank= True)
    payments = models.ManyToManyField('Payment',related_name="bill")
    created_at = models.DateTimeField(default=timezone.now)
    gift_type= models.CharField(choices=GIFTS,default="N", max_length=1)
    voucher = models.ForeignKey('Voucher', on_delete=models.PROTECT,blank=True, null=True, related_name="bills")
    coupon_code = models.CharField(max_length=20, null=True, blank=True)
    @property
    def paid(self):
        acc = 0
        for i in self.payments.all():
            acc += i.paid
        return  acc

class Package(models.Model):
    name = models.CharField(max_length=30)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=False, null=False, related_name="packages")
    bill = models.OneToOneField('Bill', on_delete=models.PROTECT, null=True, related_name="package")

class BookingQuerySet(models.QuerySet):

    def total_bill(self):
        return list(self.aggregate(models.Sum('bill__final_amount')).values())[0]

    def total_payment(self):
        amount = 0
        for i in self:
            amount+= i.bill.paid if i.bill else 0
        return amount

    def services_count(self):
        count = 0
        for booking in self:
            count += booking.appointments.count()
        return count

class BookingManager(models.Manager):
    user_for_related_fields = True

    def get_queryset(self):
        return BookingQuerySet(self.model, using=self._db)

class Booking(models.Model):
    objects = BookingManager()
    Booked=1
    Pending=2
    Completed=3
    Cancelled=4
    STATUS = (
        (Booked,"Booked"),
        (Pending,"Pending"),
        (Completed,"Completed"),
        (Cancelled,"Cancelled")
    )
    bill = models.OneToOneField('Bill', on_delete=models.PROTECT, null=True, related_name="booking")
    package = models.ForeignKey(Package, on_delete=models.PROTECT, null=True, related_name="bookings")
    customer = models.ForeignKey(Customer,on_delete=models.PROTECT, null=False, blank=False, default=1, related_name="bookings")
    products = models.ManyToManyField(Product, related_name="booking", through="ProductBooking")
    branch = models.ForeignKey('inventory.Branch', null=False, blank=False, on_delete=models.PROTECT, related_name="bookings")
    date = models.DateField(blank=True, null=True)
    starttime = models.TimeField(blank=True, null=True)
    endtime = models.TimeField(blank=True, null=True)
    status = models.IntegerField(choices=STATUS, default=Booked)
    status_lookup = {key: value for (key, value) in STATUS}
    @property
    def status_to_str(self):
        return self.status_lookup[self.status]

    def status_int_to_str(self,i):
        return self.status_lookup[i]

    def status_str_to_int(self,i):
        for key, val in self.status_lookup.items():
            if val==i:
                return key
    @property
    def total_amount(self):
        if self.appointments.count() > 0:
            return sum([appointment.service.price for appointment in self.appointments.all()])
        elif self.products.count() > 0:
            return sum([pb.product.price_per_unit*pb.quantity for pb in self.product_booking.all()])
        else:
            return 0
    @property
    def total_taxable_amount(self):
        if self.appointments.count() > 0:
            return sum([appointment.service.price for appointment in self.appointments.all() if appointment.service.taxable])
        elif self.products.count() > 0:
            return sum([pb.product.price_per_unit*pb.quantity for pb in self.product_booking.all() if pb.product.taxable])
        else:
            return 0

class Offer(models.Model):
    name= models.CharField(max_length=30)
    services = models.ManyToManyField(Service, related_name="offers", through="OfferService")
    percentage = models.FloatField(null=False)

class OfferService(models.Model):
    offer = models.ForeignKey(Offer, related_name="offer_service", on_delete=models.CASCADE, null=False)
    service = models.ForeignKey(Service, related_name="offer_service", on_delete=models.CASCADE, null=False)
    quantity = models.IntegerField(default=0)

class ProductBooking(models.Model):
    product = models.ForeignKey(Product, related_name="product_booking", on_delete=models.PROTECT, null=False)
    booking = models.ForeignKey(Booking, related_name="product_booking",on_delete=models.CASCADE, null=False)
    quantity = models.IntegerField(default=1)
    price_per_product = models.FloatField(default=0.0)

class Voucher(models.Model):
    code = models.CharField(max_length=30)
    description = models.CharField(max_length=50)
    percentage = models.FloatField(default=0.0)

class Payment(models.Model):
    Cash = 0
    Card = 1
    PAYMENT_MODES = (
        (Cash,"Cash"),
        (Card,"Card")
    )
    Customer = 0
    Bajaj_Finance = 1
    Capital_Float = 2
    PAYMENT_SOURCES = (
        (Customer,"Customer"),
        (Bajaj_Finance,"Bajaj_Finance"),
        (Capital_Float,"Capital_Float")
    )
    payment_type = models.IntegerField(choices=PAYMENT_MODES, default=Cash)
    card = models.ForeignKey("Card", on_delete=models.PROTECT, null=True, related_name="payments")
    paid = models.FloatField(default=0.0,null=False)
    payment_by = models.IntegerField(choices=PAYMENT_SOURCES, default=Customer)
    payment_date = models.DateField(auto_now_add=True)

class Card(models.Model):
    number = models.CharField(max_length=20)

class AppointmentQuerySet(models.QuerySet):
    def total_price(self):
        return list(self.aggregate(models.Sum('price')).values())[0]
        return list(self.aggregate(models.Sum('price')).values())[0]

class AppointmentManager(models.Manager):
    user_for_related_fields = True

    def get_queryset(self):
        return AppointmentQuerySet(self.model, using=self._db)

class Appointment(models.Model):
    objects = AppointmentManager()
    employee = models.ForeignKey(Employee,on_delete=models.SET_NULL, null=True, blank=True, related_name="appointments")
    service = models.ForeignKey(Service, on_delete=models.PROTECT, null=True, blank=True, related_name="appointments")
    price = models.FloatField(default=0.0)
    booking = models.ForeignKey(Booking,on_delete=models.CASCADE, related_name="appointments")
    cancelled = models.BooleanField(default=False)
    notes = models.TextField(null=True, blank=True)
    def __str__(self):
        return "Appointment:"+str(self.service)


x = 5
print(x)

x*8

x='test'
print(x)

x="hello"
print(x)

x*8

x+10

x+' 10'

# list:

x=[]
x=[1,2,3]
x[0]
x[3]

x.append(7)
x.insert(1, 15)

sum(x)
len(x)

for n in x:
    print(n)

x[1:3]

x[1:]
x[:3]

x.append('test')

x[-1]
x[-2]

x[-3:-1]

x[-3:]

# map/ dictionary

person={'first':'john', 'last':'smith'}

person['age'] = 30

person[35] = 90

person['x']

person.keys()

person.pop(35)

# set

s={1,2,2,3}

s.add(8)

# in (not in)

# discard vs remove vs pop

#   |(union)  &(intersection) -(difference)


import os

def get_user_file(context):
    fpath = os.path.realpath('static/users/{user}/{file}'.format(**context))
    if not os.path.exists(fpath):
        raise ValueError('File does not exist')
    if os.path.isdir(fpath):
        return user_dir('{user}/{file}'.format(**context), fpath)
    with open(fpath) as f:
        return f.readlines()

def get_user_dir(context):
    fpath = os.path.realpath('static/users/{user}'.format(**context))
    if not os.path.exists(fpath):
        raise ValueError('File does not exist')
    return user_dir(context['user'], fpath)

def user_dir(dirname, fpath):
    '''Build an index from dirname'''
    resp = [
        '',
        '<title>Index of /~{}/</title>'.format(dirname),
        '
Index of /~{}/
'.format(dirname),
    ]

    files = []
    max_len = 0

    for f in os.listdir(fpath):
        files.append(f)
        if len(f) > max_len:
            max_len = len(f)

    for f in files:
        r = '{name}'.format(dirname=dirname,name=f)
        resp.append(r)

    resp.append('')
    return resp