# -*- coding: utf-8 -*-
"""
@author: Sreenivas.J
"""
import os
import pandas as pd
import numpy as np

from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils

os.chdir("D:/Data Science/Data")
np.random.seed(100)

digit_train = pd.read_csv("Digits Recognizer_Train.csv")
digit_train.shape
digit_train.info()

#iloc[:, 1:] Means first to last row and 2nd column to last column
#255.0 --> Convert my data to 255 pixels
X_train = digit_train.iloc[:, 1:]/255.0
y_train = np_utils.to_categorical(digit_train["label"])
y_train.shape

#Here comes the Basic Neural Network
model = Sequential()
model.add(Dense(10, input_shape=(784,), activation='softmax'))
print(model.summary())

#mean_squared_error for regression
#Binary_Crossentropy is for Binary Classification and categorical_crossentropy is for multi class classification
#Both uses the log loss
#In SGD, before for-looping, system randomly shuffle the training examples.
#For further reading regarding Cross entropy:
#Here is a good article: https://www.quora.com/Whats-an-intuitive-way-to-think-of-cross-entropy
model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

#Batch Size — The number of training examples in one forward/backward pass.
#Each Epoch takes entire train data
history = model.fit(x=X_train, y=y_train, verbose=1, epochs=4, batch_size=2, validation_split=0.2)
print(model.get_weights())


"""
we run here some mediapipe experiments.
"""
import argparse
from rt import env
import cv2
import time
import json
import mediapipe as mp
mp_face_detection = mp.solutions.face_detection
mp_drawing = mp.solutions.drawing_utils
def do_config(args):
    """print current configuration."""
    print(do_faces.__doc__)
    print(json.dumps(env.config,indent=2))

def do_faces(args):
    """face detection."""
    print(do_faces.__doc__)
    source=env.get_workpath("face-demographics-walking.mp4")
    cap = cv2.VideoCapture(source)
    # Check if camera opened successfully
    if (cap.isOpened()== False):
        print(f"Error opening video stream:{source}")
        return
    fps=float(cap.get(cv2.CAP_PROP_FPS) or 30)
    fps_delay=1/fps
    print(f"fps:{fps},fps_delay:{fps_delay}")
    with mp_face_detection.FaceDetection(
        model_selection=0,
        min_detection_confidence=0.5
        ) as face_detection:
        while True:
            msworked=time.time()
            ret, frame = cap.read()
            if ret==False:
                break
            #cv2.imshow(source, frame)
            # Flip the image horizontally for a later selfie-view display, and convert
            # the BGR image to RGB.
            image = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB)
            # To improve performance, optionally mark the image as not writeable to
            # pass by reference.
            image.flags.writeable = False
            results = face_detection.process(image)

            # Draw the face detection annotations on the image.
            image.flags.writeable = True
            image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
            if results.detections:
                for detection in results.detections:
                    mp_drawing.draw_detection(image, detection)
            cv2.imshow('MediaPipe Face Detection', image)
            msworked=time.time()-msworked
            msworked=int(msworked*1000)
            msdelay=max(1,int(fps_delay*1000)-msworked)
            #print("msworked:",msworked,msdelay)
            #time.sleep(fps_delay)
            if cv2.waitKey(msdelay) & 0xFF == ord('q'):
                break
    cap.release()
    cv2.destroyAllWindows()

if __name__=="__main__":
    jobs={k.replace("do_",""):v for k,v in locals().items() if k.startswith("do_")}
    ap=argparse.ArgumentParser(description=__doc__)
    ap.add_argument("-j","--job",required=True,help="job to perform", choices=jobs.keys())
    args=ap.parse_args()
    env.init()
    override={k:v for (k,v) in vars(args).items() if v is not None or k not in env.config}
    env.config.update(override)
    jobs[args.job](args)
    #with app.app_context():
    #    jobs[args.job]()


# -*- coding: utf-8 -*-
"""
Four Box Model Use Tutorial
=============

* **ACTM Performer:** JHU-APL;
* **Author:** Chace Ashcraft (chace.ashcraft@jhuapl.edu)

PyBAMOCS Tutorial

PyBAMOCS uses a simplified box model to simulate the Atlantic meridional overturning circulation (AMOC). The
implementation is based on the paper by Gnanadesikan et al.
(https://journals.ametsoc.org/view/journals/clim/31/22/jcli-d-18-0388.1.xml), which examined the stability of the AMOC.
This tutorial assumes that you have downloaded the PyBAMOCs code from the PACMANs repository on GitHub and installed
PyBAMOCS into your Python environment. Installation instructions for the PyBAMOCS module is provided below. For
additional information about installing PyBAMOCS and the PyBAMOCS API, please see the PACMANS repository
(https://github.com/JHUAPL/PACMANs), and navigate to `box_model/python/`.

This tutorial is meant to be a tool for getting started using the PyBAMOCS package and the included `box_model`
functionality, and is not meant to be a comprehensive overview of all functions or capabilities of the included code.
For a more thorough understanding, please consider viewing the code itself, and the examples in the `scripts` folder.
There is also a more extensive tutorial in the form of a Jupyter Notebook in the `notebooks` directory of the PyBAMOCS
module.

# PyBAMOCS Installation

We recommend installing PyBAMOCS in its own environment using `venv`
(https://docs.python.org/3/library/venv.html) or `conda`
(https://conda.io/projects/conda/en/latest/user-guide/install/index.html). Once in your new environment (if desired),
perform the following steps to install the module.

* Clone the PACMANS repository (https://github.com/JHUAPL/PACMANs)
    * `git clone https://github.com/JHUAPL/PACMANs.git`
* Change directories to `box_model/python/`
    * `cd box_model/python/`
* Install locally using `pip`
    * `pip install -e .`

To execute the snippet:

**Step 1:** Follow the instructions above to install the PyBAMOCS module.

**Step 2:** The snippet itself may be run from the command line as follows:

```
% python pybamocs_tutorial.py
```

We encourage the interested user to examine the code below to identify the relevant objects and methods required to
implement their specific use case.

"""

# .............................................
# IMPORT STATEMENTS
# .............................................

import time
from matplotlib import pyplot as plt
from typing import Union

# Import the `box_model` function and its arguments
from pybamocs.box_model import box_model
from pybamocs.box_model import NORTH_IDX, SOUTH_IDX, LOW_IDX, DEEP_IDX
from pybamocs.box_model_args import (
    BoxModelBoxDimensions,
    BoxModelInitConditions,
    BoxModelTimeStep,
    BoxModelParameters,
)

# Convenience function
def print_box_model_argument_settings(argument: Union[BoxModelBoxDimensions, BoxModelInitConditions,
                                                      BoxModelTimeStep, BoxModelParameters]) -> None:
    """
    Print box model settings to console for a given box_model argument.
    :param argument: One of the box_model argument objects.
    """
    settings_dict = argument.to_dict()  # Get the settings as a python dictionary

    print("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv")
    # Print each key, value pair in the dictionary
    for key, value in settings_dict.items():
        print(f"{key}={value}")
    print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
    print()

def main():
    print("Box model settings are divided into five groups:")
    # Each object represents a set of parameters to the model
    box_model_dimensions = BoxModelBoxDimensions()
    box_model_initial_conditions = BoxModelInitConditions()
    box_model_time_settings = BoxModelTimeStep()
    box_model_parameters = BoxModelParameters()

    # And there is one object for each group as shown above.
    print("------------------------------------------------------------")
    print("Box Dimensions:")
    print_box_model_argument_settings(box_model_dimensions)

    print("------------------------------------------------------------")
    print("Initial Conditions")
    print_box_model_argument_settings(box_model_initial_conditions)

    print("------------------------------------------------------------")
    print("Model Time Step Parameters:")
    print_box_model_argument_settings(box_model_time_settings)

    print("------------------------------------------------------------")
    print("Model Parameters")
    print_box_model_argument_settings(box_model_parameters)

    # To run the box model, simply call the `box_model` function with your argument objects
    print("Running the box model...")
    start = time.time()
    results = box_model(box_model_dimensions,
                        box_model_initial_conditions,
                        box_model_parameters,
                        box_model_time_settings)
    print(f"Run complete. Time: {time.time() - start} seconds.")

    # Note that the results are contained in a BoxModelResult object
    print("Box model output object:")
    print(results)
    print()

    # You can access specific results directly from the object
    print("Result details:")
    print("------------------------------------------------------")
    print("Shape of M_n for run:", results.M_n.shape)
    print()

    # or you can "unpack" them all at once
    M_n, M_upw, M_eddy, D_low, T, S, sigma0 = results.unpack()

    print("------------------------------------------------------")
    print("First 3 values of each output variable:")
    print("M_n:", M_n[:3])
    print("M_upw:", M_upw[:3])
    print("M_eddy:", M_eddy[:3])
    print("D_low:", D_low[:3])
    print("T_north:", T[NORTH_IDX, :3])
    print("T_south:", T[SOUTH_IDX, :3])
    print("T_low:", T[LOW_IDX, :3])
    print("T_deep:", T[DEEP_IDX, :3])
    print("S_north:", S[NORTH_IDX, :3])
    print("S_south:", S[SOUTH_IDX, :3])
    print("S_low:", S[LOW_IDX, :3])
    print("S_deep:", S[DEEP_IDX, :3])
    print("sigma0_north:", sigma0[NORTH_IDX, :3])
    print("sigma0_south:", sigma0[SOUTH_IDX, :3])
    print("sigma0_low:", sigma0[LOW_IDX, :3])
    print("sigma0_deep:", sigma0[DEEP_IDX, :3])

    print("Plotting results...")
    plt.plot(M_n, label='M_n')
    plt.plot(M_upw, label='M_upw')
    plt.plot(M_eddy, label='M_eddy')
    plt.plot(D_low, label='Dlow')
    plt.legend()
    plt.title("1D Box Model Outputs")

    fig, ax = plt.subplots(nrows=2, ncols=2)
    ax[0, 0].plot(T[NORTH_IDX], label='North')
    ax[0, 1].plot(T[SOUTH_IDX], label='South')
    ax[1, 0].plot(T[LOW_IDX], label='Low')
    ax[1, 1].plot(T[DEEP_IDX], label='Deep')
    ax[0, 0].legend()
    ax[0, 1].legend()
    ax[1, 0].legend()
    ax[1, 1].legend()
    plt.suptitle("Temperature in the 4 different boxes")
    plt.tight_layout()

    fig1, ax1 = plt.subplots(nrows=2, ncols=2)
    ax1[0, 0].plot(S[NORTH_IDX], label='North')
    ax1[0, 1].plot(S[SOUTH_IDX], label='South')
    ax1[1, 0].plot(S[LOW_IDX], label='Low')
    ax1[1, 1].plot(S[DEEP_IDX], label='Deep')
    ax1[0, 0].legend()
    ax1[0, 1].legend()
    ax1[1, 0].legend()
    ax1[1, 1].legend()
    plt.suptitle("Salinity in the 4 different boxes")
    plt.tight_layout()

    fig2, ax2 = plt.subplots(nrows=2, ncols=2)
    ax2[0, 0].plot(sigma0[NORTH_IDX], label='North')
    ax2[0, 1].plot(sigma0[SOUTH_IDX], label='South')
    ax2[1, 0].plot(sigma0[LOW_IDX], label='Low')
    ax2[1, 1].plot(sigma0[DEEP_IDX], label='Deep')
    ax2[0, 0].legend()
    ax2[0, 1].legend()
    ax2[1, 0].legend()
    ax2[1, 1].legend()
    plt.suptitle("Density in the 4 different boxes")
    plt.tight_layout()
    plt.show(block=False)

    # Consider an example of some data collection
    Fwn_values_to_test = [10000, 50000, 100000, 500000, 1000000]
    alternate_north_starting_temp = 4.0

    box_dims = BoxModelBoxDimensions()
    params = BoxModelParameters()
    time_step = BoxModelTimeStep()
    init = BoxModelInitConditions(T_north0=alternate_north_starting_temp)

    # Collect the data... (should take a few seconds)
    print(f"Generating data for alternate parameter settings: T_north={alternate_north_starting_temp}")
    start_time = time.time()
    results = []
    for fwn in Fwn_values_to_test:
        print(f"Fwn={fwn}")
        params.Fwn = fwn
        results.append(box_model(box_dims, init, params, time_step))
    time_to_collect_data = time.time() - start_time
    print(f"Total time to collect data: {time_to_collect_data} seconds")

    # Let's look at the difference in M_n for each run
    print("Plotting results...")
    plt.figure()
    for i in range(len(Fwn_values_to_test)):
        plt.plot(results[i].M_n, label=f"Fwn={Fwn_values_to_test[i]}")
    plt.title(f"M_n for different Northern Fluxes and T_north0={alternate_north_starting_temp}")
    plt.legend()
    plt.show()  # suspends script until plot windows are closed
    print("Done")

if __name__ == "__main__":
    main()


# @before-stub-for-debug-begin
from python3problem116 import *
from typing import *
# @before-stub-for-debug-end

#
# @lc app=leetcode.cn id=116 lang=python3
#
# [116] 填充每个节点的下一个右侧节点指针
#

# @lc code=start
"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
'''
给定一个完美二叉树，其所有叶子节点都在同一层，每个父节点都有两个子节点。二叉树定义如下：

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}
填充它的每个 next 指针，让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点，则将 next 指针设置为 NULL。

初始状态下，所有 next 指针都被设置为 NULL。
'''
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return None
        if root.left:
            root.left.next = root.right
            if root.next:
                root.right.next = root.next.left
        self.connect(root.left)
        self.connect(root.right)
        return root

# @lc code=end

116.填充每个节点的下一个右侧节点指针.py

116.填充每个节点的下一个右侧节点指针.py


import pandas as pd
import numpy as np
import sklearn.model_selection
import sklearn.linear_model
import statsmodels.api as sm

df=pd.read_csv('C:/Users/mayij/Desktop/DOC/GITHUB/MLGH/linear regression/car.csv')
df['sell']=df['Selling_Price']
df['original']=df['Present_Price']
df['age']=2019-df['Year']
df['km']=df['Kms_Driven']/1000
df['petrol']=np.where(df['Fuel_Type']=='Petrol',1,0)
df['dealer']=np.where(df['Seller_Type']=='Dealer',1,0)
df['manual']=np.where(df['Transmission']=='Manual',1,0)
df=df[['sell','original','age','km','petrol','dealer','manual']].reset_index(drop=True)

df.plot(x='original',y='sell',style='o',title='sell vs original')

xtrain,xtest,ytrain,ytest=sklearn.model_selection.train_test_split(df[['original','age','km','petrol','dealer','manual']],df['sell'],test_size=0.2)
xtrain,xval,ytrain,yval=sklearn.model_selection.train_test_split(xtrain,ytrain,test_size=0.25)

moriginal=np.random.randint(0,1)
mage=np.random.randint(0,1)
mkm=np.random.randint(0,1)
mpetrol=np.random.randint(0,1)
mdealer=np.random.randint(0,1)
mmanual=np.random.randint(0,1)
c=np.random.randint(0,10)
a=0.0001
epochs=10000
n=len(xtrain)

for i in range(epochs):
    ypred=moriginal*xtrain['original']+mage*xtrain['age']+mkm*xtrain['km']+mpetrol*xtrain['petrol']+mdealer*xtrain['dealer']+mmanual*xtrain['manual']+c
    dmoriginal=(-2/n)*sum(xtrain['original']*(ytrain-ypred))
    dmage=(-2/n)*sum(xtrain['age']*(ytrain-ypred))
    dmkm=(-2/n)*sum(xtrain['km']*(ytrain-ypred))
    dmpetrol=(-2/n)*sum(xtrain['petrol']*(ytrain-ypred))
    dmdealer=(-2/n)*sum(xtrain['dealer']*(ytrain-ypred))
    dmmanual=(-2/n)*sum(xtrain['manual']*(ytrain-ypred))
    dc=(-2/n)*sum(ytrain-ypred)
    moriginal=moriginal-a*dmoriginal
    mage=mage-a*dmage
    mkm=mkm-a*dmkm
    mpetrol=mpetrol-a*dmpetrol
    mdealer=mdealer-a*dmdealer
    mmanual=mmanual-a*dmmanual
    c=c-a*dc

print('moriginal:'+str(moriginal)+'\n'+
      'mage:'+str(mage)+'\n'+
      'mkm:'+str(mkm)+'\n'+
      'mpetrol:'+str(mpetrol)+'\n'+
      'mdealer:'+str(mdealer)+'\n'+
      'mmanual:'+str(mmanual)+'\n'+
      'c:'+str(c))

sm.OLS(ytrain,sm.add_constant(xtrain)).fit().summary()


""" Curva de punta de flecha Sierpinski """
from turtle import *
from fractal import Fractal

class FlechaSierpinski(Fractal):
    def generar_lista(self):
        lista = ['D', 'D']
        for _ in range(self.get_iteraciones()):
            nuevaLista = []
            direccionAnterior = 'I' if lista[0] == 'D' else 'D'
            nuevaLista.extend([direccionAnterior, direccionAnterior])
            for i, elemento in enumerate(lista):
                nuevaLista.append(elemento)
                direccion = 'I' if direccionAnterior == 'D' else 'D'
                nuevaLista.extend([direccion, direccion])
                direccionAnterior = direccion
            lista = nuevaLista
        return lista

    def dibujar_curva(self):
        lista_instrucciones = self.generar_lista()
        for instruccion in lista_instrucciones:
            forward(self.get_tamano())
            if instruccion == 'D':
                right(60)
            elif instruccion == 'I':
                left(60)

    def curvaSierpinski_grafico(self):
        tracer(0, 0)
        reset()
        hideturtle()
        pensize(2)
        colormode(255)
        bgcolor(0, 0, 0)
        penup()
        home()
        left(90)
        #pendown()
        pencolor(44, 54, 206)
        self.dibujar_curva()
        update()


import time
from pynput import mouse
from pynput import keyboard

M=mouse.Controller() #创建一个鼠标对象
K=keyboard.Controller() #创建一个键盘对象

print(M.position)

#找到QQ下拉框（1621，5）
M.position=(1400,0)

#找到对话联系人（1680，277）
time.sleep(0.5)
M.position=(1400,277)

#双击聊天框
M.click(mouse.Button.left, 2)

#定位到聊天栏（1059，625）
M.position=(800,625)
time.sleep(0.5)

#点击聊天栏
time.sleep(0.5)
M.click(mouse.Button.left, 1)
#输入对话
time.sleep(0.5)
K.type("hello,world!")
time.sleep(0.5)

#发送（ctrl+enter）
K.press(keyboard.Key.ctrl_l)
K.press(keyboard.Key.enter)
K.release(keyboard.Key.enter)
K.release(keyboard.Key.ctrl_l)


import json
import os

def report_file():
	if not os.path.exists("reports"):
		os.makedirs("reports")
	return "reports/keys_list.txt"

def get_keys(start=0, end=49):
	key_set = []
	with open(report_file(), "w") as output:
		for idir in range(start, end):
			dir_name = "../repos/part{}".format(idir)
			for ifile in range(0,100):
				file_number = idir*100+ifile
				file_name = "repos_{}.json".format(file_number)
				with open(dir_name+"/"+file_name) as f:
					dicts = json.loads(f.read())
					for d in dicts:
						for key in d.keys():
							if key not in key_set:
								key_set.append(key)
								print >> output, "{} {}".format(ifile, key)

get_keys()


"""travelcave URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path

from . import views

app_name = 'blog'

urlpatterns = [
    path('', views.index, name='home'),
    path('home/', views.index, name='home'),
    path('register/', views.register, name='register'),
    path('login/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
    path('posts/create/', views.create_post, name="create_post"),
    path('posts/publish/', views.publish_new_post, name='publish_new_post'),
    path('posts/<int:pk>/edit/', views.edit_post, name="edit_post"),
    path('posts/<int:pk>/publish/', views.publish_post, name="publish_post"),
    path('posts/<int:pk>/delete/', views.delete_post, name="delete_post"),
    path('posts/<int:pk>/view/', views.view_post, name="view_post"),
    path('posts/<int:pk>/like/', views.like_post, name="like_post"),
    path('posts/<int:pk>/unlike/', views.unlike_post, name="unlike_post"),
    path('posts/<int:pk>/comment/', views.comment_post, name="comment_post"),
    path('posts/<int:pk>/share/', views.share_post, name="share_post"),
    path('comment/<int:pk>/reply/', views.reply_comment, name='reply_comment'),
    path('account/posts/', views.my_posts, name='my_posts'),
    path('users/<str:username>/follow/', views.follow_user,
         name='follow_user'),
    path('users/<str:username>/unfollow/', views.unfollow_user,
         name='unfollow_user'),
    path('users/<str:username>/', views.view_user, name='view_user'),
    path('users/', views.users, name='users'),
    path('locations/<int:pk>/', views.view_location, name='view_location'),
    path('locations/<int:pk>/follow/', views.follow_location,
         name='follow_location'),
    path('locations/<int:pk>/unfollow/', views.unfollow_location,
         name='unfollow_location'),
    path('tags/<int:pk>/', views.view_tag, name='view_tag'),
    path('explore/', views.explore, name='explore'),
]


import talib
from talib import MA_Type
import sqlite3
import numpy as np
import pandas as pd
import xlsxwriter
import datetime
from datetime import date, timedelta
from dateutil import parser
from dateutil.relativedelta import relativedelta
import sys
import time

#檢查list數值是否呈現遞減(mode='D')或遞增(mode='U')，回傳Y/N
def trend_chk(df, mode):
	i = 0
	flag = "Y"
	for elem in df:
		if i == 0:
			prev_elem = elem
			i += 1
			continue
		else:
			if (mode == "D") and (elem >= prev_elem):
				flag = "N"
				break
			elif (mode == "U") and (elem <= prev_elem):
				flag = "N"
				break
			else:
				prev_elem = elem
		i += 1
	return flag

#K線型態判斷
def Patt_Recon(arg_stock, str_prev_date, str_today, str_ceiling_date):
	sear_comp_id = arg_stock[0]
	#日線資料讀取
	strsql  = "select quo_date, open, high, low, close from STOCK_QUO "
	strsql += "where "
	strsql += "SEAR_COMP_ID='" + sear_comp_id + "' and "
	strsql += "QUO_DATE between '" + str_prev_date + "' and '" + str_today + "' "
	strsql += "order by QUO_DATE "

	cursor = conn.execute(strsql)
	result = cursor.fetchall()

	none_flag = False
	if len(result) > 0:
		df = pd.DataFrame(result, columns = ['date','open','high','low','close'])
		#print(df)
	else:
		none_flag = True

	#關閉cursor
	cursor.close()

	ls_result = []
	if none_flag == False:
		#LIST轉換為Numpy Array
		npy_close = np.array(df['close'])

		#計算3MA
		ma3 = talib.MA(npy_close, timeperiod=3, matype=0)
		df['ma3'] = ma3

		for i in range(2,len(df)-2):
			dt = df.loc[i]['date']					#報價日期
			od1 = df.loc[i]['open']					#第一天開盤價
			od2 = df.loc[i+1]['open']				#第二天開盤價
			od3 = df.loc[i+2]['open']				#第三天開盤價
			cd1 = df.loc[i]['close']				#第一天收盤價
			cd2 = df.loc[i+1]['close']				#第二天收盤價
			cd3 = df.loc[i+2]['close']				#第三天收盤價
			ma3_slice = df.loc[i-5:i]['ma3']		#往前取6天3MA值
			chk_d_yn = trend_chk(ma3_slice, 'D')	#判斷是否downtrend
			chk_u_yn = trend_chk(ma3_slice, 'U')	#判斷是否uptrend

			rec_data_yn = False
			patt_type = ""
			if dt >= str_ceiling_date:
				#Bullish patterns after downtrends
				#TWS判斷
				if (cd1 > od1 and cd2 > od2 and cd3 > od3) and \
				   (cd3 > cd2 > cd1) and (cd1 > od2 > od1) and \
				   (cd2 > od3 > od2) and (chk_d_yn == "Y"):
					rec_data_yn = True
					patt_type = "TWS"

				#TIU判斷
				if (od1 > cd1) and (od1 >= od2 > cd1) and (od1 > cd2 >= cd1) and \
				   (cd3 > od3) and (cd3 > od1) and (chk_d_yn == "Y"):
					rec_data_yn = True
					patt_type = "TIU"

				#TOU判斷
				if (od1 > cd1 and cd2 > od1 > cd1 > od2 and cd3 > od3 and cd3 > cd2) and \
				   (chk_d_yn == "Y"):
					#print(dt)
					rec_data_yn = True
					patt_type = "TOU"

				#MS判斷
				if (od1 > cd1) and (abs(od2 - cd2) > 0) and (cd1 > cd2) and \
				   (cd1 > od2) and (cd3 > od3) and (cd3 > (cd1 + (od1 - cd1)/2)) and \
				   (chk_d_yn == "Y"):
					rec_data_yn = True
					patt_type = "MS"

				"""
				#Bearish patterns after uptrends
				#TBC判斷
				if (od1 > cd1 and od2 > cd2 and od3 > cd3) and \
				   (cd1 > cd2 > cd3) and (od1 > od2 > cd1) and \
				   (od2 > od3 > cd2) and (chk_u_yn == "Y"):
					rec_data_yn = True
					patt_type = "TBC"

				#TID判斷
				if (cd1 > od1) and (cd1 > od2 >= od1) and (cd1 >= cd2 > od1) and \
				   (od3 > cd3) and (od1 > cd3) and (chk_u_yn == "Y"):
					rec_data_yn = True
					patt_type = "TID"

				#TOD判斷
				if (cd1 > od1 and od2 > cd1 > od1 > cd2 and od3 > cd3 and cd2 > cd3) and \
				   (chk_u_yn == "Y"):
					rec_data_yn = True
					patt_type = "TOD"

				#ES判斷
				if (cd1 > od1) and (abs(od2 - cd2) > 0) and (cd2 > cd1) and \
				   (od2 > cd1) and (od3 > cd3) and (cd3 < (od1 + (cd1 - od1)/2)) and \
				   (chk_u_yn == "Y"):
					rec_data_yn = True
					patt_type = "ES"
				"""

			if rec_data_yn == True:
				ls_result.append([arg_stock[0],arg_stock[1], dt, patt_type])

	#print(ls_result)
	df_result = pd.DataFrame(ls_result, columns=['stock_id', 'stock_name', 'event_date', 'pattern_type'])
	return df_result

############################################################################
# Main                                                                     #
############################################################################
# 寫入LOG File
dt = datetime.datetime.now()
str_date = parser.parse(str(dt)).strftime("%Y%m%d")

name = "STOCK_SELECT_TYPE03_" + str_date + ".txt"
file = open(name, 'a', encoding = 'UTF-8')
tStart = time.time()#計時開始
file.write("\n\n\n*** LOG datetime  " + str(datetime.datetime.now()) + " ***\n")

#產生日期區間(當天日期，往前推14天)
today = datetime.datetime.now()
prev_date = today + timedelta(days=-14)
ceiling_date = today + timedelta(days=-7)

str_today = today.strftime("%Y%m%d")
str_prev_date = prev_date.strftime("%Y%m%d")
str_ceiling_date = ceiling_date.strftime("%Y%m%d")

#print(str_today)
#print(str_prev_date)

file.write("回測日期區間:" + str_prev_date + "~" + str_today + "\n")

#建立資料庫連線
conn = sqlite3.connect("market_price.sqlite")

strsql  = "select SEAR_COMP_ID,COMP_NAME, STOCK_TYPE from STOCK_COMP_LIST "
#strsql += "where STOCK_TYPE = '上櫃' and SEAR_COMP_ID='3662.TW' "
strsql += "order by STOCK_TYPE, SEAR_COMP_ID "
#strsql += "limit 1 "

cursor = conn.execute(strsql)
result = cursor.fetchall()

df_result = pd.DataFrame()
if len(result) > 0:
	for stock in result:
		#print(stock)
		df = Patt_Recon(stock, str_prev_date, str_today, str_ceiling_date)

		if len(df)>0:
			df_result = pd.concat([df_result, df], ignore_index=True)

#關閉cursor
cursor.close()

#關閉資料庫連線
conn.close()

#結果寫入EXCEL檔
file_name = 'STOCK_SELECT_TYPE03_' + str_today + '.xlsx'
writer = pd.ExcelWriter(file_name, engine='xlsxwriter')
df_result.to_excel(writer, sheet_name='stock', index=False)
writer.save()

tEnd = time.time()#計時結束
file.write ("\n\n\n結轉耗時 %f sec\n" % (tEnd - tStart)) #會自動做進位
file.write("*** End LOG ***\n")

# Close File
file.close()

print("End of prog.")


import os, argparse

def main():
    parser = argparse.ArgumentParser('Remove all files of according extension')
    parser.add_argument('--fold_A', dest='fold_A', help='input directory for image A', type=str, default='./A')
    parser.add_argument('--fold_B', dest='fold_B', help='input directory for image B', type=str, default='./B')
    parser.add_argument('--ext', dest='ext', help='file extension you want removed', type=str, default='.png')
    args = parser.parse_args()
    for root, dirs, files in os.walk(args.fold_A):
        for file in files:
            if file.endswith(args.ext):
                os.remove(os.path.join(root,file))
    for root, dirs, files in os.walk(args.fold_B):
        for file in files:
            if file.endswith(args.ext):
                os.remove(os.path.join(root,file))
    print(args.ext + "removed")

if __name__ == "__main__":
    main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 created by gjwei on 7/14/18

"""
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
import ipdb

class CharCNNEmbedding(nn.Module):

    def __init__(self,
                 char_vocab,
                 char_dim,
                 word_max_length=10,
                 embed_dropout=0.2,
                 kernel_sizes=[3, 4, 5],
                 feature_maps=[128, 128, 128],
                 output_dim=128):
        super(CharCNNEmbedding, self).__init__()
        self.char_embedding = nn.Embedding(char_vocab, char_dim,
                                           padding_idx=0)
        self.embed_dropout = nn.Dropout(embed_dropout)
        self.cnns = nn.ModuleList(
                nn.Sequential(
                        nn.Conv1d(in_channels=char_dim,
                                  out_channels=fm,
                                  kernel_size=ks),
                        nn.Tanh(),
                        nn.MaxPool1d(kernel_size=word_max_length - ks + 1)
                )
                for fm, ks in zip(feature_maps, kernel_sizes)
        )
        self.dropout = nn.Dropout(0.5)

        self.output_layer = nn.Linear(sum(feature_maps), output_dim)

        self.init_weights()

    def init_weights(self):
        nn.init.normal_(self.char_embedding.weight, mean=0, std=0.01)
        nn.init.constant_(self.char_embedding.weight.data[0], 0.0)

        nn.init.xavier_normal_(self.output_layer.weight)

    def forward(self, x):
        """
        :param x: batch_size, seq_max_length, word_max_length
        :return: batch_size , seq_max_length, output_dim
        """
        batch_size, seq_max_length = x.size(0), x.size(1)
        x = x.view(-1, x.size(2))

        x = self.char_embedding(x)  # bs, ml, dim
        x = self.embed_dropout(x)

        x = x.permute(0, 2, 1)

        raw_cnn_ouputs = []

        for cnn in self.cnns:
            raw_cnn_ouputs.append(torch.squeeze(cnn(x)))

        # ipdb.set_trace()

        flatten = torch.cat(raw_cnn_ouputs, dim=-1)  # bs, sum(feature_maps)

        flatten = self.dropout(flatten)

        output = self.output_layer(flatten)  # bs output_dim

        output = output.view(batch_size, seq_max_length, -1)  # bs, seq_max_length, output_dim

        return output

if __name__ == '__main__':
    input = torch.from_numpy(np.random.randint(0, 99, size=(32, 20, 15)))
    model = CharCNNEmbedding(char_vocab=100, char_dim=50)
    output = model(input)

    print(output.size())


#!/usr/bin/env python

import unittest

import git_mnemonic as gm

class GitMnemonicTests(unittest.TestCase):
    def test_encode(self):
        self.assertTrue(gm.encode("master"))

    def test_decode(self):
        self.assertTrue(gm.decode("bis alo ama aha"))

    def test_invertible(self):
        once = gm.encode("master")
        self.assertEquals(gm.encode(gm.decode(once)), once)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(GitMnemonicTests)
    results = unittest.TextTestRunner(verbosity=2).run(suite)
    if not results.wasSuccessful():
        import sys
        sys.exit(1)


#!/usr/bin/python

import argparse
import bareos.bsock
from bareos.bsock.filedaemon import FileDaemon
import logging
import sys

def getArguments():
    argparser = argparse.ArgumentParser(description="Connect to Bareos File Daemon.")
    argparser.add_argument(
        "-d", "--debug", action="store_true", help="enable debugging output"
    )
    bareos.bsock.FileDaemon.argparser_add_default_command_line_arguments(argparser)
    argparser.add_argument(
        "command", nargs="*", help="Command to send to the Bareos File Daemon"
    )
    args = argparser.parse_args()
    return args

if __name__ == "__main__":
    logging.basicConfig(
        format="%(levelname)s %(module)s.%(funcName)s: %(message)s", level=logging.INFO
    )
    logger = logging.getLogger()

    args = getArguments()
    if args.debug:
        logger.setLevel(logging.DEBUG)

    bareos_args = bareos.bsock.FileDaemon.argparser_get_bareos_parameter(args)
    logger.debug("options: %s" % (bareos_args))
    try:
        bsock = FileDaemon(**bareos_args)
    except (bareos.exceptions.Error) as e:
        print(str(e))
        sys.exit(1)
    logger.debug("authentication successful")
    if args.command:
        print(bsock.call(args.command))
    else:
        bsock.interactive()


from rest_framework.serializers import (
    ModelSerializer,
    SerializerMethodField,
    HyperlinkedIdentityField,
    ListSerializer,
    PrimaryKeyRelatedField,
)
from django.db import transaction
from Book.models import Book, AuthorBook, BookCategory
from Author.models import Author
from Category.models import Category

from Author.api.serializers import AuthorListSerializer, AuthorDetailSerializer
from Category.api.serializers import CategoryListSerializer, CategoryDetailSerializer
from Publication.api.serializers import PublicationListSerializer

book_detail_url = HyperlinkedIdentityField(
    view_name='books-api:detail'
)

class BookCreateUpdateSerializer(ModelSerializer):
    authors = AuthorDetailSerializer(many=True, read_only=True)
    categories = CategoryDetailSerializer(many=True, read_only=True)

    @transaction.atomic
    def create(self, validated_data):
        book = Book.objects.create(**validated_data)

        if "authors" in self.initial_data:
            authors = self.initial_data.get("authors")
            for author in authors.split(","):
                author_instance = Author.objects.get(pk=int(author))
                AuthorBook(book=book, author=author_instance).save()

        if "categories" in self.initial_data:
            categories = self.initial_data.get("categories")
            for category in categories.split(","):
                category_instance = Category.objects.get(pk=int(category))
                BookCategory(book=book, category=category_instance).save()

        book.save()
        return book

    @transaction.atomic
    def update(self, instance, validated_data):
        # Ignore the fact that i delete and replace. Will diff in the future

        AuthorBook.objects.filter(book=instance).delete()
        authors = self.initial_data.get("authors")
        for author in authors.split(","):
            new_author = Author.objects.get(pk=int(author))
            AuthorBook(book=instance, author=new_author).save()

        BookCategory.objects.filter(book=instance).delete()
        categories = self.initial_data.get("categories")
        for category in categories.split(","):
            new_category = Category.objects.get(pk=int(category))
            BookCategory(book=instance, category=new_category).save()

        instance.__dict__.update(**validated_data)
        instance.save()
        return instance

    class Meta:
        model = Book
        fields = [
            'name',
            'description',
            'price',
            'edition',
            'no_of_page',
            'country',
            'publication',
            'authors',
            'categories',
        ]

class BookListSerializer(ModelSerializer):
    url = book_detail_url

    class Meta:
        model = Book
        fields = [
            'url',
            'id',
            'name',
            'publication',
            'authors',
            'categories',
        ]

class BookDetailSerializer(ModelSerializer):
    image = SerializerMethodField()
    publication = PublicationListSerializer(many=False, read_only=True)
    authors = AuthorListSerializer(many=True, read_only=True)
    categories = CategoryListSerializer(many=True, read_only=True)

    class Meta:
        model = Book
        fields = [
            'id',
            'name',
            'image',
            'description',
            'price',
            'edition',
            'no_of_page',
            'country',
            'publication',
            'authors',
            'categories',
        ]

    def get_image(self, obj):
        try:
            image = obj.image.url
        except:
            image = None
        return image


# Returns integer.
# This function returns integer which is an amount of times the passed number appears in 2D array.
def numberInMatrix(matrix, number):
    if matrix == [[]] or matrix == []:
        return 0
    if matrix is None:
        return None

    # allNumbers <- storage an amount of times the passed number appears in matrix
    allNumbers = 0
    # x, y <- at the beginning: coordinates of the upper right element in matrix
    y = len(matrix[0]) - 1
    x = 0
    # checked <- element currently being checked
    checked = matrix[x][y]

    while True:
        if checked > number:
            y -= 1
        elif checked < number:
            x += 1
        else:
            allNumbers += 1
            x += 1
            y -= 1
        if y < 0 or x > len(matrix) - 1:
            return allNumbers
        checked = matrix[x][y]

def tests():
    arr = [[]]
    assert numberInMatrix(arr, 11) == 0
    arr = [[1, 3, 7, 8, 10],
           [2, 5, 8, 9, 11],
           [5, 6, 9, 11, 13],
           [10, 11, 13, 15, 16],
           [11, 13, 14, 17, 20],
           [12, 14, 15, 20, 23]]
    assert numberInMatrix(arr, 11) == 4
    assert numberInMatrix(arr, 14) == 2
    assert numberInMatrix(arr, 15) == 2
    assert numberInMatrix(arr, 30) == 0

tests()

arr = [[1, 3, 7, 8, 10],
       [2, 5, 8, 9, 11],
       [5, 6, 9, 11, 13],
       [10, 11, 13, 15, 16],
       [11, 13, 14, 17, 20],
       [12, 14, 15, 20, 23]]

print(numberInMatrix(arr, 15))


#from django.http import HttpResponse
from django.shortcuts import render
import jieba

def home(request):
	return render(request,'home.html')

def count(request):
	txt=request.GET['text']
	dic={}
	text = jieba.lcut(txt)
	for word in text:
		dic[word]=dic.get(word,0)+1
	sortedDic=sorted(dic.items(),key=lambda x:x[1],reverse=True)
	length=len(text)
	return render(request,'count.html',{'lenText':length,'T':text,
		'D':dic,'S':sortedDic}
		)


import argparse
import os
import shutil
import subprocess
import sys
from tempfile import mkdtemp

def showcase():
    assert os.path.exists(args.target), "Target folder %s doesn't exist" % args.target

    exts = ['.' + e for e in args.ext.split(",")]
    # source_files = [os.path.join(r, f) for r, fd, fl in os.walk(os.path.abspath(args.target)) for f in fl
    #                 if os.path.splitext(f)[1].lower() in exts]

    tmp = mkdtemp(prefix="showcase_")
    first = None
    c = 0
    for r, dirs, files in os.walk(os.path.abspath(args.target)):
        dirs.sort()
        for file in [os.path.join(r, f) for f in sorted(files) if os.path.splitext(f)[1].lower() in exts]:
            c += 1
            link_name = "%04i_%s" % (c, os.path.basename(file))
            if not first:
                first = os.path.join(tmp, link_name)
            os.symlink(file, os.path.join(tmp, link_name))
            print("%s -> %s" % (file, os.path.join(tmp, link_name)))

    subprocess.call(["xdg-open", first])

def permanent_showcase():
    SHOWCASE_NAME = "__showcase"
    target = args.target
    counter = {}

    def create_linker(_folder):
        if _folder not in counter:
            counter[_folder] = 0

        def _linker(item):
            if not args.skip_root or (_folder != target):
                c = counter[_folder]
                counter[_folder] += 1

                showcase_folder = os.path.join(_folder, SHOWCASE_NAME)
                os.makedirs(showcase_folder, exist_ok=True)
                link_name = os.path.join(showcase_folder, "%04d_%s" % (c, os.path.basename(item)))
                path_to_item = os.path.relpath(item, showcase_folder)
                if not os.path.exists(link_name):
                    os.symlink(path_to_item, link_name)

        return _linker

    def picture_list(folder, linkers):

        if args.rebuild or args.remove:
            sc_folder = os.path.join(folder, SHOWCASE_NAME)
            if os.path.exists(sc_folder):
                shutil.rmtree(sc_folder)

        for entry in sorted([e for e in os.scandir(folder) if e.name != SHOWCASE_NAME], key=lambda e: e.name):
            entry_path = os.path.join(folder, entry.name)
            if entry.is_dir():
                picture_list(entry_path, linkers + [create_linker(folder)])
            elif entry.is_file() and not args.remove:
                for linker in linkers:
                    linker(entry_path)

    picture_list(target, [print])

def catalog():
    source = os.path.expanduser(args.source)
    target = os.path.expanduser(args.target)
    assert os.path.exists(source), "Source folder doesn't exist"

    if not os.path.exists(target):
        os.makedirs(target, exist_ok=True)

    exts = ['.' + e for e in args.ext.split(",")]

    for root, folders, files in os.walk(source):
        print('scan %s...' % root)
        if os.path.basename(os.path.normpath(root))[0] == '.':
            continue

        relative_root = root[len(source):]
        for file in [f for f in files if os.path.splitext(f)[1].lower() in exts]:
            print('file %s...' % file)
            source_picture = os.path.join(root, file)
            target_picture = os.path.join(target, relative_root, file)

            target_exists = os.path.exists(target_picture)

            if not target_exists or args.force:
                if target_exists:
                    print('Replacing %s...' % target_picture)
                    os.remove(target_picture)
                print("Copying %s..." % os.path.join(relative_root, file), end='')
                sys.stdout.flush()
                os.makedirs(os.path.dirname(target_picture), exist_ok=True)
                shutil.copyfile(source_picture, target_picture)
                print("resizing...", end='')
                sys.stdout.flush()
                subprocess.call(["mogrify", "-resize", args.resize, target_picture])
                print('done')
            else:
                print("File %s already exist, skipped" % target_picture)

    print("done")

catalog_file = os.path.expanduser("~/.jpgutils-catalog.idx")

def _load_catalog_index():
    index = {}
    if os.path.exists(catalog_file):
        with open(catalog_file, 'r') as f:
            first = True
            for line in f.readlines():
                if first:
                    first = False
                    continue
                path, mtime = line[:-1].split('\t')
                index[path] = float(mtime)

    return index

def _write_catalog_index(index: dict):
    with open(catalog_file, 'w') as f:
        f.write("original_path\ttimestamp%n")

        for path, timestamp in index.items():
            f.write("%s\t%s\n" % (path, timestamp))

def catalog2():
    def path_mtime():
        return os.path.abspath(source_picture), os.path.getmtime(source_picture)

    def log(s, flush=False):
        if args.verbose:
            if flush:
                print(s, end='', flush=True)
            else:
                print(s)

    source = os.path.expanduser(args.source)
    target = os.path.expanduser(args.target)
    assert os.path.exists(source), "Source folder doesn't exist"

    index = _load_catalog_index()

    if not os.path.exists(target):
        os.makedirs(target, exist_ok=True)

    exts = ['.' + e for e in args.ext.split(",")]
    forced_resize = args.force

    sources = 0
    skipped = 0
    replaced = 0

    source = source[:-1] if source[-1] == '/' else source
    root_count = source.count('/')

    for root, folders, files in os.walk(source, topdown=True):
        folders.sort()
        level = root.count('/') - root_count
        _spacer = '  ' * level

        if os.path.basename(os.path.normpath(root))[0] == '.':
            continue

        if level > 0:
            log(_spacer + " - " + os.path.basename(root))

        target_root = os.path.join(target, root[len(source) + 1:])
        for file in sorted([f for f in files if os.path.splitext(f)[1].lower() in exts]):
            source_picture = os.path.join(root, file)
            target_picture = os.path.join(target_root, file)
            log('%s  -  %s -> ' % (_spacer, file), True)
            sources += 1

            path, mtime = path_mtime()
            source_changed = path in index and index[path] != mtime
            target_exists = os.path.exists(target_picture)

            if source_changed or forced_resize or not target_exists:
                repl = False
                if target_exists:
                    os.remove(target_picture)
                    replaced += 1
                    repl = True
                os.makedirs(os.path.dirname(target_picture), exist_ok=True)
                shutil.copyfile(source_picture, target_picture)
                subprocess.call(["mogrify", "-resize", args.resize, target_picture])
                if repl:
                    log("replaced.")
                else:
                    log('generated.')
            else:
                log("skipped.")
                skipped += 1

            index[os.path.abspath(source_picture)] = os.path.getmtime(source_picture)

    _write_catalog_index(index)
    print("""
Catalog generation done
    Source folder: %s
    Target folder: %s
    Found %d pictures
    Skipped %d pictures
    Generated %d pictures (%d replaced)
""" % (source, target, sources, skipped, (sources - skipped), replaced))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    subparsers = parser.add_subparsers()

    showcase_parser = subparsers.add_parser("showcase", help="Symlink all pictures in folder and open viewer")
    showcase_parser.set_defaults(command="showcase")
    showcase_parser.add_argument("target", help="File or directory to view")
    showcase_parser.add_argument("--ext", default="jpg,jpeg",
                                 help="Extensions valid to be shown, separated by comma")
    showcase_parser.add_argument("--permanent", help="Make showcase permanent")

    catalog_parser = subparsers.add_parser("catalog", help="Create catalog with smaller pictures")
    catalog_parser.set_defaults(command="catalog")
    catalog_parser.add_argument("source", help="Original directory from where creating the catalog")
    catalog_parser.add_argument("target", help="Final destination of the catalog")
    catalog_parser.add_argument("--resize", default="1920x1080",
                                help="Resize value of the pictures (default 1920x1080")
    catalog_parser.add_argument("--ext", default="jpg,jpeg",
                                help="Extensions valid to be copied, separated by comma")
    catalog_parser.add_argument("--force", action='store_true',
                                help='Force resized file to be overridden')

    catalog_parser2 = subparsers.add_parser("catalog2", help="Create catalog with smaller pictures")
    catalog_parser2.set_defaults(command="catalog2")
    catalog_parser2.add_argument("source", help="Original directory from where creating the catalog")
    catalog_parser2.add_argument("target", help="Final destination of the catalog")
    catalog_parser2.add_argument("--resize", default="1920x1080",
                                 help="Resize value of the pictures (default 1920x1080")
    catalog_parser2.add_argument("--ext", default="jpg,jpeg",
                                 help="Extensions valid to be copied, separated by comma")
    catalog_parser2.add_argument("--force", action='store_true',
                                 help='Force resized file to be overridden')
    catalog_parser2.add_argument('-v', "--verbose", action='store_true',
                                 help='Log all files encountered')

    pshowcase_parser = subparsers.add_parser("permanent-showcase", help="Create permanent showcase")
    pshowcase_parser.set_defaults(command="permanent_showcase")
    pshowcase_parser.add_argument("target", help="Final destination of the catalog")
    pshowcase_parser.add_argument("--skip-root", action="store_true", help="Skip root showcase folder")
    pshowcase_parser.add_argument("--rebuild", action="store_true", help="Delete all showcase folders and then create again")
    pshowcase_parser.add_argument("--remove", action="store_true", help="Delete all showcase folders")

    args = parser.parse_args()
    if args.command:
        if args.command == 'showcase':
            showcase()
        elif args.command == 'catalog':
            catalog()
        elif args.command == 'catalog2':
            catalog2()
        elif args.command == 'permanent_showcase':
            permanent_showcase()
        else:
            parser.print_usage()
    else:
        parser.print_usage()


import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)
model = pickle.load(open("dt.pickle","rb"))

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/predict',methods=['GET','POST'])
def predict():
    '''
    For rendering results on HTML GUI
    '''
    # 'mileage', 'tax', 'mpg', 'engineSize', 'age', 'transmission_Automatic',
    #    'transmission_Manual', 'transmission_Semi-Auto', 'fuelType_Diesel',
    #    'fuelType_Hybrid', 'fuelType_Other', 'fuelType_Petrol'

    transmission_Automatic =0
    transmission_Manual = 0
    transmission_SemiAuto =0

    fuelType_Diesel=0
    fuelType_Hybrid =0
    fuelType_Other =0
    fuelType_Petrol =0

    if request.method == "POST":
        age = int(request.form["age"])
        mileage = int(request.form["run"])
        tax = int(request.form["tax"])
        mpg = int(request.form["mpg"])
        engineSize = int(request.form["eng_size"])

        transmission = request.form["transmission"]
        if (transmission == "automatic"):
            transmission_Automatic =1
            transmission_Manual = 0
            transmission_SemiAuto =0

        elif (transmission == "manual"):
            transmission_Automatic =0
            transmission_Manual = 1
            transmission_SemiAuto =0

        elif (transmission == "semi-auto"):
            transmission_Automatic =0
            transmission_Manual = 0
            transmission_SemiAuto =1

        fuelType = request.form["fuelType"]
        if (fuelType == 'diesel'):
            fuelType_Diesel=1
            fuelType_Hybrid =0
            fuelType_Other =0
            fuelType_Petrol =0

        elif (fuelType == 'hybrid'):
            fuelType_Diesel=0
            fuelType_Hybrid =1
            fuelType_Other =0
            fuelType_Petrol =0

        elif (fuelType == 'other'):
            fuelType_Diesel=0
            fuelType_Hybrid =0
            fuelType_Other =1
            fuelType_Petrol =0

        elif (fuelType == 'petrol'):
            fuelType_Diesel=0
            fuelType_Hybrid =0
            fuelType_Other =0
            fuelType_Petrol =1

        pred = model.predict([[mileage, tax, mpg, engineSize, age, transmission_Automatic,transmission_Manual, transmission_SemiAuto, fuelType_Diesel,fuelType_Hybrid, fuelType_Other, fuelType_Petrol ]])
        output= round(pred[0])

        return render_template("index.html",prediction_text="You can sell this car at {} $".format(output))

    #     if output<0:
    #         return render_template("index.html", prediction_text="Sorry your car can't be sold")
    #     else:
    #         return render_template("index.html",prediction_text="You can sell this car at {} Rs".format(output))
    #         print("Sell car at {}".format(output))
    else:
        return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True)


#a
import sys,string, math, itertools

nn,k = input().split()
nn,k = int(nn),int(k)
L = [ int(x) for x in input().split()]
#print(nn,k, L)
for i in range(0,nn) :
    if (86400-L[i]) >= k :
        print(i+1)
        sys.exit()
    k -= (86400-L[i])


import ROOT
from ROOT import TNamed

ROOT.gROOT.SetBatch(True)
input_file = ROOT.TFile('../muon-KLMValidation.root')
tree = input_file.Get('tree')
output_file = ROOT.TFile('EKLMMuon.root', 'recreate')
contact = 'Martina Laurenza (martina.laurenza@roma3.infn.it)'

# Shifter Plots

subdetector_selection = 'KLMHit2ds.m_Subdetector==2'

h2dtres = ROOT.TH1F('muon_h2dtres', 'EKLM muon 2d hits time resolution',
                    80, -20, 20)
h2dtres.SetXTitle('ns')
h2dtres.SetYTitle('Events')
tree.Draw('KLMHit2ds.m_Time+(EventT0.hasEventT0()?EventT0.getEventT0():0)-KLMHit2ds.m_MCTime>>muon_h2dtres', subdetector_selection)
functions = h2dtres.GetListOfFunctions()
functions.Add(TNamed('Description', 'Time resolution'))
functions.Add(TNamed('Check', 'No bias.'))
functions.Add(TNamed('Contact', contact))
functions.Add(TNamed('MetaOptions', 'shifter'))

section = ROOT.TH1F('Forward', 'Section for KLMHit2ds', 2, 0.5, 2.5)
section.GetXaxis().SetTitle('1=backward  2=forward')
section.GetYaxis().SetTitle('Events')
tree.Draw('KLMHit2ds.getSection()>>Forward', subdetector_selection)
functions = section.GetListOfFunctions()
functions.Add(TNamed('Description',
                     'Flag indicating if a muon hit is in backward(1) or forward(2) EKLM'))
functions.Add(TNamed('Check', 'More hits in backward.'))
functions.Add(TNamed('Contact', contact))
functions.Add(TNamed('MetaOptions', 'shifter'))

sector = ROOT.TH1F('Sector', 'Sector for KLMHit2ds', 6, -0.5, 5.5)
sector.GetXaxis().SetTitle('Sector #')
sector.GetYaxis().SetTitle('Events')
tree.Draw('KLMHit2ds.getSector()>>Sector', subdetector_selection)
functions = sector.GetListOfFunctions()
functions.Add(TNamed('Description', 'Sector number of muon hit'))
functions.Add(TNamed('Check', 'More hits in sector 1, then mostly flat.'))
functions.Add(TNamed('Contact', contact))
functions.Add(TNamed('MetaOptions', 'shifter'))

layer = ROOT.TH1F('Layer', 'Layer for KLMHit2ds', 16, -0.5, 15.5)
layer.GetXaxis().SetTitle('Layer #')
layer.GetYaxis().SetTitle('Events')
tree.Draw('KLMHit2ds.getLayer()>>Layer', subdetector_selection)
functions = layer.GetListOfFunctions()
functions.Add(TNamed('Description', 'Layer number of muon hit'))
functions.Add(TNamed('Check', 'Number of events decreases with number of layer.'))
functions.Add(TNamed('Contact', contact))
functions.Add(TNamed('MetaOptions', 'shifter'))

time = ROOT.TH1F('Time', 'Hit time for KLMHit2ds', 80, -5.0, 35.0)
time.GetXaxis().SetTitle('t (ns)')
time.GetYaxis().SetTitle('Events')
tree.Draw('KLMHit2ds.getTime()>>Time', subdetector_selection)
functions = time.GetListOfFunctions()
functions.Add(TNamed('Description', 'Time of muon hit in EKLM'))
functions.Add(TNamed('Check', 'Mean around 16 ns.'))
functions.Add(TNamed('Contact', contact))
functions.Add(TNamed('MetaOptions', 'shifter'))

# Expert Plots

nPE = ROOT.TH1F('nGenPE', 'Generated PE in EKLM', 100, 0.0, 200)
nPE.GetXaxis().SetTitle('# generated PE')
nPE.GetYaxis().SetTitle('Events')
tree.Draw('KLMDigits.getNGeneratedPhotoelectrons()>>nGenPE',
          'KLMDigits.getSubdetector()==2')
functions = nPE.GetListOfFunctions()
functions.Add(TNamed('Description', 'Number of generated photoelectrons in EKLM.'))
functions.Add(TNamed('Check', 'Mean around 37.'))
functions.Add(TNamed('Contact', contact))
functions.Add(TNamed('MetaOptions', 'expert'))

edep = ROOT.TH1F('edep', 'Energy deposition for KLMDigits', 150, 0.0, 15)
edep.GetXaxis().SetTitle('E (MeV)')
edep.GetYaxis().SetTitle('Events')
tree.Draw('KLMHit2ds.getEnergyDeposit()>>edep', subdetector_selection)
functions = edep.GetListOfFunctions()
functions.Add(TNamed('Description', 'dE/dx energy deposition of muon hit'))
functions.Add(TNamed('Check', 'Peak around 3 MeV, with mean 3.7 MeV.'))
functions.Add(TNamed('Contact', contact))
functions.Add(TNamed('MetaOptions', 'expert'))

output_file.cd()
h2dtres.Write()
section.Write()
sector.Write()
layer.Write()
time.Write()
nPE.Write()
edep.Write()
output_file.Close()


# -*- coding: utf-8 -*-
import scrapy
from ..items import ZhanzhangItem

class ZhanSpider(scrapy.Spider):
    name = 'zhan'
    allowed_domains = ['sc.chinaz.com']
    start_urls = ['http://sc.chinaz.com/tubiao/']

    def parse(self, response):
        li_list = response.xpath('//ul[@class="pngblock imgload"]/li')
        for li in li_list:
            href = li.xpath('.//p/a/@href').extract_first('')
            dirname = li.xpath('.//p/a/@alt').extract_first('')
            # print(href,dirname)
            yield scrapy.Request(url=href,meta={'dirname':dirname},callback=self.get_imgs_with_href)

        next_page = response.xpath('//a[text()="下一页"]/@href').extract()
        if len(next_page) != 0:
            yield scrapy.Request(url='http://sc.chinaz.com/tubiao/'+next_page[0],callback=self.parse)
    def get_imgs_with_href(self,response):
        dirname = response.meta['dirname']
        img_list = response.xpath('//div[@class="png_pic"]/img/@src').extract()
        for img in img_list:
            item = ZhanzhangItem()
            item['dirname'] = dirname
            item['img'] = [img]
            yield item


from primaires.interpreteur.commande.commande import Commande
from secondaires.navigation.constantes import *

class CmdEcoper(Commande):

    """Commande 'écoper'"""

    def __init__(self):
        """Constructeur de la commande"""
        Commande.__init__(self, "écoper", "bale")
        self.nom_categorie = "navire"
        self.aide_courte = "écope"
        self.aide_longue = \
            "Cette commande permet d'écoper, c'est-à-dire de rejeter " \
            "à l'extérieur du navire une partie de l'eau qui s'y trouve. " \
            "Cette commande est souvent nécessaire juste avant ou après " \
            "la réparation d'une voie d'eau. Pour écoper, vous devez " \
            "disposer d'un conteneur particulier (les autres conteneurs " \
            "ne sont pas adaptés pour ce travail). Le maximum, fonction " \
            "de votre force, de la capacité du conteneur, de la quantité " \
            "d'eau qui se trouve ici, est toujours choisi. Cette " \
            "opération fatigue proportionnellement à la quantité d'eau " \
            "que vous récupérez dans le conteneur puis reversez par-dessus " \
            "bord."

    def interpreter(self, personnage, dic_masques):
        """Méthode d'interprétation de commande"""
        salle = personnage.salle
        if not hasattr(salle, "navire") or salle.navire is None:
            personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
            return

        navire = salle.navire
        if salle.poids_eau == 0:
            personnage << "|err|Il n'y a pas d'eau ici.|ff|"
            return

        # On cherche l'écope
        ecope = None
        for objet in personnage.equipement.inventaire:
            if objet.est_de_type("écope"):
                ecope = objet
                break

        if ecope is None:
            personnage << "|err|Vous ne possédez aucune écope.|ff|"
            return

        salle.ecoper(personnage, ecope)


from django.contrib import admin
from django.urls import path
from soporte import views

urlpatterns = [
    path('', views.home),
    path('servicios/', views.servicios),
    path('crear/', views.crear),
    path('editar/<str:id>', views.editar, name= 'editar'),
    path('eliminar/<str:id>', views.eliminar, name= 'eliminar'),
    path('movimientos/', views.movimientos),
    path('interesados/', views.inter),

]


"""
Check here when we need more argument options
https://github.com/miguelgrinberg/Flask-Migrate/blob/master/flask_migrate/__init__.py#L168
"""

import os
from alembic import command
from main import create_app

SCHEMA = "SCHEMA_TEST"

def replace_schema(txt, schema_name):
  txt = txt.replace(f"schema='{schema_name}'", f"schema=app.config['{SCHEMA}']")

  # for foreign key name
  txt = txt.replace(f"{schema_name}.", f"' + app.config['{SCHEMA}'] + '.")

  # for index name
  txt = txt.replace(f"_{schema_name}_", f"_' + app.config['{SCHEMA}'] + '_")

  code_start_idx = txt.find("from alembic")
  txt = txt[:code_start_idx] + f"\nfrom flask import current_app as app\n" + txt[code_start_idx:]
  return txt

def migrate(**kwargs):
  """Autogenerate a new revision file (Alias for
  'revision --autogenerate')
  """
  app = create_app()
  schema_name = app.config[SCHEMA]

  with app.app_context():
    config = app.extensions["migrate"].migrate.get_config(
        None, opts=["autogenerate"], x_arg=None)
    result_list = command.revision(config, None, autogenerate=True, sql=False,
                                   head="head", splice=False, branch_label=None,
                                   version_path=None, rev_id=None)
    if not isinstance(result_list, list):
      result_list = [result_list]

    for res in result_list:
      file_path = res.path
      with open(file_path, "r") as f:
        txt = replace_schema(f.read(), schema_name)

      with open(file_path, "w") as f:
        f.write(txt)

if __name__ == "__main__":
  migrate()


from flask import Flask, send_file
from  flask_cors import CORS

import config

from db import db

app = Flask(__name__)
CORS(app)

@app.route('/')
def main():
    return "Girlcode store API"

@app.route('/categories')

def categories_route():
    tmp_categories = []

    cat_instance = db('categories')

    rows = cat_instance.select()

    for row in rows:
        #print(row)
        tmp_cat = {
            "id" : row[0],
            "name" : row[1],
            "slug" : row[2],
            "desc" : row[3],
            "img" : row[4]

        }
        tmp_categories.append(tmp_cat)

    categories_dict = {
        "categories": tmp_categories
    }

    return categories_dict

@app.route('/category/<cat_slug>')
def category_route(cat_slug):
    cat_instance = db('categories')

    rows = cat_instance.select(f"WHERE slug='{cat_slug}'")

    if len(rows):
        row = rows[0]

        tmp_cat = {
            "id": row[0],
            "name": row[1],
            "slug": row[2],
            "desc": row[3],
            "img": row[4]
        }

        return tmp_cat
    else:
        return {}

@app.route('/products')
def products_route():

    prod_instance = db('products')

    tmp_products = []
    rows = prod_instance.select()

    for row in rows:
        #print(row)
        tmp_prod = {
            "id" : row[0],
            "prod_name" : row[1],
            "prod_slug" : row[2],
            "prod_desc" : row[3],
            "prod_img" : row[4],
            "prod_price" : row[5]

        }
        tmp_products.append(tmp_prod)

    products_dict = {
        "products": tmp_products
    }

    return products_dict

@app.route('/product/<prod_slug>')
def product_route(prod_slug):
    prod_instance = db('products')

    rows = prod_instance.select(f"WHERE prod_slug='{prod_slug}'")

    if len(rows):
        row = rows[0]

        tmp_prod = {
            "id": row[0],
            "prod_name": row[1],
            "prod_slug": row[2],
            "prod_desc": row[3],
            "prod_img": row[4],
            "prod_price": row[5]
        }

        return tmp_prod
    else:
        return {}

@app.route('/image/<img_name>')
def get_image(img_name):
    filename = f'images/{img_name}'

    return send_file(filename, mimetype='image/jpg')

    '''for row in rows:
        tmp_cat = {
            "id":row[0],
            "name":row[1],
            "slug":row[2],
            "desc":row[0],
            "img":row[0],

        }
'''


r1, c1 = map(int,input().split())
r2, c2 = map(int,input().split())
r = r2 - r1
c = c2 - c1
if (r, c) == (0, 0):
  print(0)
elif r == c or r == -c or abs(r) + abs(c) <= 3:
  print(1)
elif (r ^ c ^ 1) & 1 or abs(r) + abs(c) <= 6 or abs(r + c) <= 3 or abs(r - c) <= 3:
  print(2)
else:
  print(3)

"""
Move conditions
A: a+b=c+d
B: a-b=c-d
C: abs(a-c)+abs(b-d)<=3

If combined A,B and C, 3 is the maximum answer.
To determine 0,1,2 is OK.
See https://atcoder.jp/contests/abc184/editorial/339

The answer is 0, start and destination are same.
The answer is 1, start and destination are same as the condition of problem move condition.
The answer is 2,
  the combination is the below.
  A,B
  A,C
  B,C
  C,C

"""


import sys
import pitchers
import batters
import db

BATTER = "B"
PITCHER = "P"

def main():

    batters_list = []
    pitchers_list = []
    player_names = []

    db_string = "./baseball.db"

    conn = db.create_connection(db_string)
    db.create_table(conn, db.player_names_table)
    db.create_table(conn, db.player_daily_table)

    if sys.argv[1] == BATTER:
        batters_list = batters.parse_batters(sys.argv[2])
        db.insert_players_daily(conn, batters_list)

    elif sys.argv[1] == PITCHER:
        pitchers_list = pitchers.parse_pitchers(sys.argv[2])
        db.insert_players_daily(conn, pitchers_list)

    else:
        print("Player type invalid: ", sys.argv[1])

if __name__ == '__main__':
    main()


#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""斐波拉契数列"""

# 递归
def fib(n):
    if n == 1 or n == 2:
        return 1
    return fib(n-1) + fib(n-2)

# dp
def fib_dp(n):
    if n == 1 or n == 2:
        return 1
    value_n_2 = 1
    value_n_1 = 1
    value = 0
    for i in range(3, n+1):
        value = value_n_2 + value_n_1
        value_n_2 = value_n_1
        value_n_1 = value
    return value

if __name__ == '__main__':
    re = fib(6)
    print(re)
    re = fib_dp(6)
    print(re)


import plotly.express as px
import streamlit as st
import pandas as pd
import numpy as np
import element_generator as eg
import financials as fin
import time
import logging
from millify import millify

# Page Config
st.set_page_config(
    page_title="Equity Analysis",
    page_icon="ðŸ“ˆ",
    layout="wide",
    initial_sidebar_state="collapsed",
    menu_items={
        "About": 'Equity Analysis Tool'
    }
)

logging.basicConfig(level=logging.DEBUG, format='%(levelname)s - %(message)s')

input_container = st.container()  # Input (ticker)
info_container = st.container()   # Company Overview, Metrics, Candlestick Chart

def load_data(ticker):
    """
    Load data from the API and display it on the page.

    Parameters
    ----------
    ticker : str
        The ticker of the company to load data for.

    Returns
    -------
    None
    """
    logging.info('Loading data...')
    # Company Name, Address, Description
    overview, response_code_overview = fin.company_overview(ticker)
    # Daily Adjusted Prices
    daily_adjusted, response_code_daily = fin.daily_adjusted(ticker)

    if response_code_overview == 200 and response_code_daily == 200:
        try:
            info_container.empty()
            logging.info('Data loaded successfully.')
            # Company Info
            info_container.header(f"{overview['Name']} ({overview['Symbol']})")
            info_container.caption(f"{overview['Address']}")
            info_container.caption(f"{overview['Description']}")

            # --- Metrics --- #
            col1, col2, col3, col4 = info_container.columns(4)
            col1.metric(
                label='Price',
                value=f'USD {eg.get_latest_price(daily_adjusted)}'
            )
            col2.metric(
                label='Market Cap',
                value=f'USD {millify(overview["MarketCapitalization"], precision=3)}'
            )
            col3.metric(label='P/E Ratio', value=overview['PERatio'])
            col4.metric(label='Dividend Yield', value=overview['DividendYield'])

            # CandleStick Chart
            info_container.plotly_chart(
                eg.candlestick(daily_adjusted),
                use_container_width=True
            )

            # --- Income Statement & Balance Sheet --- #
            col1, col2 = info_container.columns(2)
            # Income Statement
            income_statement, response_code = fin.income_statement(ticker)
            if response_code == 200:
                col1.subheader('Income Statement')
                col1.dataframe(income_statement)

            # Balance Sheet
            balance_sheet, response_code = fin.balance_sheet(ticker)
            if response_code == 200:
                col2.subheader('Balance Sheet')
                col2.dataframe(balance_sheet)

        except Exception as e:
            # Print error message and stack trace
            logging.error(e, exc_info=True)
            info_container.error('API limit reached. Please try again in 13 seconds.')
    else:
        # NOTE: When exceeding API limits, the repsonse code is still 200,
        # but the response body contains an error message. Therefore, we
        # catch the error here and display it to the user.
        logging.error('Ticker not found. Please try again.')

# Input Container
with input_container:
    st.text_input('Enter a ticker', value='AAPL', max_chars=5, key='ticker')
    st.button('Submit', key='submit_button')

# Load data when the submit button is clicked
if st.session_state.submit_button:
    load_data(st.session_state.ticker)


from django.conf.urls import url
from app.publicacion_views import *

urlpatterns = [
    url(r'^pub/new/$', pub_new, name='pub_new'),
    url(r'^pub/(?P<pk>[0-9]+)/$', publicacion_detail,name ='pub_detail'),
    url(r'^pub/(?P<pk>[0-9]+)/edit/$', pub_edit, name='pub_edit'),
    url(r'^mis/pub$', mis_publicaciones,name ='mis_pub'),
    url(r'^pub/todas/$', pub_all,name ='pub_all')
]


import sys
import unittest

import numpy as np
import pandas as pd
import itertools
from pathlib import Path

sys.path.append('../src/')
from sensorutils.datasets.dsads import DSADS, load, load_raw, reformat

class DSADSTest(unittest.TestCase):
    path = None
    activities = list(range(19))
    subjects = list(range(1, 9))

    @classmethod
    def setUpClass(cls) -> None:
        if cls.path is None:
            raise RuntimeError('dataset path is not specified')

    def setUp(self):
        self.loader = DSADS(self.path)

    def tearDown(self):
        pass

    def test_load_fn(self):
        data, meta = load(self.path)

        # compare between data and meta
        self.assertEqual(len(data), len(meta))

        # check meta
        ## type check
        self.assertIsInstance(meta, list)
        self.assertTrue(all(isinstance(m, pd.DataFrame) for m in meta))

        ## shape and column check
        self.assertTrue(all([list(m.columns) == ['activity', 'subject'] for m in meta]))

        ## data type check
        self.assertTrue(all([
            m.dtypes['activity'] == np.dtype(np.int8) and \
            m.dtypes['subject'] == np.dtype(np.int8) \
            for m in meta
        ]))

        ## data check
        self.assertTrue(all([
            set(np.unique(m['subject'])) == set([m['subject'].iloc[0]]) for m in meta
        ]))
        self.assertTrue(all([
            set(np.unique(m['activity'])) == set([m['activity'].iloc[0]]) for m in meta
        ]))

        # data
        ## type check
        self.assertIsInstance(data, list)
        self.assertTrue(all(isinstance(d, pd.DataFrame) for d in data))

        ## shape and column check
        self.assertTrue(all([
            list(d.columns) == \
            ['T_xacc', 'T_yacc', 'T_zacc', 'T_xgyro', 'T_ygyro', 'T_zgyro', 'T_xmag', 'T_ymag', 'T_zmag', 'RA_xacc', 'RA_yacc', 'RA_zacc', 'RA_xgyro', 'RA_ygyro', 'RA_zgyro', 'RA_xmag', 'RA_ymag', 'RA_zmag', 'LA_xacc', 'LA_yacc', 'LA_zacc', 'LA_xgyro', 'LA_ygyro', 'LA_zgyro', 'LA_xmag', 'LA_ymag', 'LA_zmag', 'RL_xacc', 'RL_yacc', 'RL_zacc', 'RL_xgyro', 'RL_ygyro', 'RL_zgyro', 'RL_xmag', 'RL_ymag', 'RL_zmag', 'LL_xacc', 'LL_yacc', 'LL_zacc', 'LL_xgyro', 'LL_ygyro', 'LL_zgyro', 'LL_xmag', 'LL_ymag', 'LL_zmag']
            for d in data
        ]))

        ## data type check
        self.assertTrue(all([
            d.dtypes[c] == np.dtype(np.float64) \
            for d in data for c in data[0].columns
        ]))

    def test_load_raw_fn(self):
        raw = load_raw(self.path)

        # raw
        ## type check
        self.assertIsInstance(raw, list)
        self.assertTrue(all(isinstance(r, pd.DataFrame) for r in raw))

        ## shape and column check
        tgt = tuple([
            'T_xacc', 'T_yacc', 'T_zacc', 'T_xgyro', 'T_ygyro', 'T_zgyro', 'T_xmag', 'T_ymag', 'T_zmag',
            'RA_xacc', 'RA_yacc', 'RA_zacc', 'RA_xgyro', 'RA_ygyro', 'RA_zgyro', 'RA_xmag', 'RA_ymag', 'RA_zmag',
            'LA_xacc', 'LA_yacc', 'LA_zacc', 'LA_xgyro', 'LA_ygyro', 'LA_zgyro', 'LA_xmag', 'LA_ymag', 'LA_zmag',
            'RL_xacc', 'RL_yacc', 'RL_zacc', 'RL_xgyro', 'RL_ygyro', 'RL_zgyro', 'RL_xmag', 'RL_ymag', 'RL_zmag',
            'LL_xacc', 'LL_yacc', 'LL_zacc', 'LL_xgyro', 'LL_ygyro', 'LL_zgyro', 'LL_xmag', 'LL_ymag', 'LL_zmag',
            'activity', 'subject',
        ])
        self.assertTrue(all([
            tuple(r.columns) == tgt for r in raw
        ]))

        ## data type check
        flgs = []
        for r in raw:
            for col in r.columns:
                if col in ['activity', 'subject']:
                    flgs += [r.dtypes[col] == np.dtype(np.int8)]
                else:
                    flgs += [r.dtypes[col] == np.dtype(np.float64)]
        self.assertTrue(all(flgs))

        ## data check
        self.assertTrue(all([
            set(np.unique(r['subject'])) == set([r['subject'].iloc[0]]) for r in raw
        ]))
        self.assertSetEqual(
            set(itertools.chain(*[np.unique(r['activity']).tolist() for r in raw])),
            set(self.activities)    # performed activity(protocol) + others
        )

    def test_reformat_fn(self):
        raw = load_raw(self.path)
        data, meta = reformat(raw)

        # compare between data and meta
        self.assertEqual(len(data), len(meta))

        # check meta
        ## type check
        self.assertIsInstance(meta, list)
        self.assertTrue(all(isinstance(m, pd.DataFrame) for m in meta))

        ## shape and column check
        self.assertTrue(all([list(m.columns) == ['activity', 'subject'] for m in meta]))

        ## data type check
        self.assertTrue(all([
            m.dtypes['activity'] == np.dtype(np.int8) and \
            m.dtypes['subject'] == np.dtype(np.int8) \
            for m in meta
        ]))

        ## data check
        self.assertTrue(all([
            set(np.unique(m['subject'])) == set([m['subject'].iloc[0]]) for m in meta
        ]))
        self.assertTrue(all([
            set(np.unique(m['activity'])) == set([m['activity'].iloc[0]]) for m in meta
        ]))

        # data
        ## type check
        self.assertIsInstance(data, list)
        self.assertTrue(all(isinstance(d, pd.DataFrame) for d in data))

        ## shape and column check
        self.assertTrue(all([
            list(d.columns) == \
            ['T_xacc', 'T_yacc', 'T_zacc', 'T_xgyro', 'T_ygyro', 'T_zgyro', 'T_xmag', 'T_ymag', 'T_zmag', 'RA_xacc', 'RA_yacc', 'RA_zacc', 'RA_xgyro', 'RA_ygyro', 'RA_zgyro', 'RA_xmag', 'RA_ymag', 'RA_zmag', 'LA_xacc', 'LA_yacc', 'LA_zacc', 'LA_xgyro', 'LA_ygyro', 'LA_zgyro', 'LA_xmag', 'LA_ymag', 'LA_zmag', 'RL_xacc', 'RL_yacc', 'RL_zacc', 'RL_xgyro', 'RL_ygyro', 'RL_zgyro', 'RL_xmag', 'RL_ymag', 'RL_zmag', 'LL_xacc', 'LL_yacc', 'LL_zacc', 'LL_xgyro', 'LL_ygyro', 'LL_zgyro', 'LL_xmag', 'LL_ymag', 'LL_zmag']
            for d in data
        ]))

        ## data type check
        self.assertTrue(all([
            d.dtypes[c] == np.dtype(np.float64) \
            for d in data for c in data[0].columns
        ]))

    def test_dsads_load_method_filed_labels(self):
        # check processing for exceptions
        x_labels = [
            'T_xacc', 'T_yacc', 'T_zacc',
            'T_xgyro', 'T_ygyro', 'T_zgyro',
            'T_xmag', 'T_ymag', 'T_zmag',
            'RA_xacc', 'RA_yacc', 'RA_zacc',
            'RA_xgyro', 'RA_ygyro', 'RA_zgyro',
            'RA_xmag', 'RA_ymag', 'RA_zmag',
            'LA_xacc', 'LA_yacc', 'LA_zacc',
            'LA_xgyro', 'LA_ygyro', 'LA_zgyro',
            'LA_xmag', 'LA_ymag', 'LA_zmag',
            'RL_xacc', 'RL_yacc', 'RL_zacc',
            'RL_xgyro', 'RL_ygyro', 'RL_zgyro',
            'RL_xmag', 'RL_ymag', 'RL_zmag',
            'LL_xacc', 'LL_yacc', 'LL_zacc',
            'LL_xgyro', 'LL_ygyro', 'LL_zgyro',
            'LL_xmag', 'LL_ymag', 'LL_zmag'
        ]
        y_labels = ['activity', 'subject']

        with self.assertRaises(ValueError):
            _, _ = self.loader.load(subjects=None, x_labels=y_labels)

        with self.assertRaises(ValueError):
            _, _ = self.loader.load(subjects=None, y_labels=x_labels)

        # shape check
        ## x
        for n in range(10, len(x_labels), 10):
            x, _ = self.loader.load(subjects=None, x_labels=np.random.choice(x_labels, n, replace=False).tolist())
            self.assertTupleEqual(x.shape[1:], (n, 125))
        ## y
        _, y = self.loader.load(subjects=None, y_labels=['activity'])
        self.assertEqual(y.shape[1], 1)
        _, y = self.loader.load(subjects=None, y_labels=['subject'])
        self.assertEqual(y.shape[1], 1)
        _, y = self.loader.load(subjects=None, y_labels=['activity', 'subject'])
        self.assertEqual(y.shape[1], 2)

    def test_dsads_load_method_filed_subjects(self):
        patterns = [
            [6, 2],
            [4, 3, 1, 2, 5],
            [5, 6, 4, 2],
            [8, 3, 4, 2, 1],
            [2, 5, 1, 7, 8, 4, 6, 3],
            [8],
            [5, 7, 2, 1, 8],
            [4],
            [8, 3, 6, 2, 1, 7, 5, 4],
            [2, 7, 1, 8, 4, 6, 5],
        ]

        for i, subjects in enumerate(patterns):
            print(f'pattern {i}')
            with self.subTest(f'pattern {i}'):
                _, y = self.loader.load(subjects=subjects)
                self.assertSetEqual(set(np.unique(y[:, 1])), set(subjects))

if __name__ == '__main__':
    args = sys.argv
    if len(args) != 2:
        sys.stderr.write('Usage: {} <dataset path>'.format(args[0]))
        sys.exit(1)

    ds_path = Path(args[1])

    DSADSTest.path = ds_path

    unittest.main(verbosity=2, argv=args[0:1])


from SES import SES
from Message import Message
import Pyro4
import jsonpickle

def deepcopy(copyList):
        if copyList == None:
            return None
        result=[]
        for i in range(len(copyList)):
            result.append(copyList[i])
        return result
if __name__ == '__main__':
    # servername1 = "localhost.dtt.1"
    # servername2 = "localhost.dtt.2"
    # objProcess1 = Pyro4.core.Proxy("PYRONAME:" + servername1)
    # objProcess2 = Pyro4.core.Proxy("PYRONAME:" + servername2)
    # objProcess1.run(servername1)
    with open('process_uri.txt','r') as fi:
       processUris = fi.readlines()
    processUris = [x.strip('"\n') for x in processUris]
    # for i in processUris:
    #     print(i)
    # print(processUris)
    processes = []
    # print("PYRONAME:" + servername2)
    for uri in processUris:
        # print("PYRONAME:" + uri)
        processes.append(Pyro4.core.Proxy("PYRONAME:" + uri))
    # processes[0].run()
    for i in range(15):
        receiverList = deepcopy(processUris)
        # receiverList.update(processUris)
        receiverList.remove(processUris[i])
        # print(receiverList)
        processes[i].run(receiverList)


import genpy
import std_msgs.msg
import geometry_msgs.msg
from visualization_msgs.msg import Marker

class TaxelGroup(object):
	def __init__(self, desc, id):
		self.taxels = []
		self.marker = Marker(id=id,
                             ns="force",
							 type=Marker.ARROW,
							 action=Marker.ADD,
							 frame_locked=True,
							 lifetime=genpy.Duration(10))
		self.marker.header.frame_id = desc.link
		self.marker.scale.x, self.marker.scale.y, self.marker.scale.z = desc.geometry.scale[1:]
		self.scale_factor = desc.geometry.scale[0]
		self.marker.points = [geometry_msgs.msg.Point(0,0,0), None]
		self.marker.color = std_msgs.msg.ColorRGBA(*desc.geometry.color.rgba)

	def addTaxel(self, taxel):
		self.taxels.append(taxel)

	def compute(self):
		pos = [0,0,0]
		normal = [0,0,0]
		force = 0
		for taxel in self.taxels:
			w = taxel._weight
			pos += w * taxel._pos
			normal += w * taxel._normal
			force += w
		return force, pos, normal

	def getMarker(self):
		force, start, normal = self.compute()
		if force > 1e-2:
			start = start / force
			end = start + self.scale_factor * normal
			self.marker.points[0] = geometry_msgs.msg.Point(*start)
			self.marker.points[1] = geometry_msgs.msg.Point(*end)
		else:
			self.marker.points[1] = self.marker.points[0]
		return self.marker


import cv2
import numpy as np

# API FINAL:
# extraeFeaturesImagenFromFile -> De un fichero de una única cara, extraer features
# extraeFeaturesImagen -> De una imagen abierta con cv2, extraer features
# extraeFeaturesRAW -> De una cara ya separada con dimensiones 96, 96, 3, extrae features
# who_is_it_single -> De una imagen abierta con cv2, obtener el match
# who_is_multiple -> De una imagen abierta con cv2, obtener los listados de matchs y no matchs
# who_is_it_RAW -> De una cara ya preparada (96, 96, 3), decir quién es
# identificaCaras ->De una imagen abierta con cv2, extraer las caras y matchs (identificados, fotos_caras, fotos_no_identificados)

PATH_TO_KERAS_MODEL = 'model\inception.h5'

TARGET_SIZE = (96, 96)
DEFAULT_THRESHOLD = 0.5

# preparaImagenCOGE LA IMAGEN y la traspone, por ejemplo, de 96,96,3 a 3,96,96
def prepareImage(img1):
  img = img1[..., ::-1]
  img = np.around(np.transpose(img, (2, 0, 1)) / 255.0, decimals=12)
  return img

# extraeUnaCaraEXTRAE UNA CARA DE UNA IMAGEN Y LA REDIMENSIONA A TARGET_SIZE
def getOneFace(imagen):
  face_cascade = cv2.CascadeClassifier('classifiers/haarcascade_frontalface_alt.xml')
  gray = cv2.cvtColor(imagen, cv2.COLOR_BGR2GRAY)
  faces = face_cascade.detectMultiScale(gray, 1.3, 5)
  if len(faces) > 1:
    print("More than one faces")
    return None
  else:
    for (x, y, w, h) in faces:
      roi = imagen[y:y + h, x:x + w]
      roi = cv2.resize(roi, TARGET_SIZE)
      return roi
  return None

# extraeMultiplesCaras EXTRAE VARIAS CARAS DE UNA IMAGEN Y LAS REDIMENSIONA A TARGET_SIZE
def getMultiFace(imagen):
  face_cascade = cv2.CascadeClassifier('classifiers/haarcascade_frontalface_alt.xml')
  gray = cv2.cvtColor(imagen, cv2.COLOR_BGR2GRAY)
  faces = face_cascade.detectMultiScale(gray, 1.3, 5)
  caras = []
  if len(faces) > 0:
    for (x, y, w, h) in faces:
      roi = imagen[y:y + h, x:x + w]
      roi = cv2.resize(roi, TARGET_SIZE)
      caras.append((roi, x, y, w, h))  # caras.append(roi)
    return caras
  return None

# preparaCaraDesdeImagen Extrae una cara, la redimensiona y la prepara
def getFaceFromImage(img1):
  resultado = None
  cara = getOneFace(img1)
  if cara is not None:
    resultado = prepareImage(cara)
  return resultado

# extraeFeaturesImagen De una única imagen extrae las features
def getImageFeature(img1, modelo):
  resultado = getFaceFromImage(img1)
  if resultado is not None:
    features = modelo.predict(np.array([resultado]))
    return features[0]
  return None

# extraeFeaturesImagenFromFile abro la imagen con opencv
def getFeatureFromFile(path, modelo):
  imagen = cv2.imread(path, 1)
  return getImageFeature(imagen, modelo)

# getFeaturesRAW De una única imagen extrae las features
def getFeaturesRAW(img1, modelo):
  d1, d2, d3 = img1.shape
  if d1 == 96 and d2 == 96 and d3 == 3:
    resultado = prepareImage(img1)
    features = modelo.predict(np.array([resultado]))
    return features[0]
  return None

# Si ya tenemos la cara sacada, directamente sacamos el vector de predicciones
# OJO, esta es sólo para usar cuando ya hemos extraído las caras de las fotos, y tiene el tamaño adecuado
def extraeFeaturesCara(img1, modelo):
  features = modelo.predict(np.array([resultado]))
  return features[0]

# De una imagen cualquiera, decir quién es
def who_is_it_single(imagen, database, model, threshold=None, debug=True):
  if threshold is None:
    threshold = 0.7

  ## Step 1: extracción de features
  encoding = getImageFeature(imagen, model)

  if encoding is None:
    print("ERROR, no hemos reconocido cara en la imagen")
    return None, None
  ## Step 2: Find the closest encoding ##

  # Initialize "min_dist" to a large value, say 100 (≈1 line)
  min_dist = 100
  identity = None

  # Loop over the database dictionary's names and encodings.
  for (name, db_enc) in database.items():

    # Compute L2 distance between the target "encoding" and the current "emb" from the database. (≈ 1 line)
    dist = np.linalg.norm(db_enc - encoding)

    # If this distance is less than the min_dist, then set min_dist to dist, and identity to name. (≈ 3 lines)
    if dist < min_dist:
      min_dist = dist
      identity = name

  if min_dist > threshold:
    if debug == True:
      print("Not in the database.")
    return None, None
  else:
    if debug == True:
      print("it's " + str(identity) + ", the distance is " + str(min_dist))
    return min_dist, identity

# De una cara ya preparada (96, 96, 3), decir quien es
def who_is_it_RAW(imagen, database, model, threshold=None, debug=True):
  if threshold is None:
    threshold = 0.7

  ## Step 1: extracción de features
  encoding = getFeaturesRAW(imagen, model)

  if encoding is None:
    print("ERROR, no hemos reconocido cara en la imagen")
    return None, None
  ## Step 2: Find the closest encoding ##

  # Initialize "min_dist" to a large value, say 100 (≈1 line)
  min_dist = 100
  identity = None

  # Loop over the database dictionary's names and encodings.
  for (name, db_enc) in database.items():

    # Compute L2 distance between the target "encoding" and the current "emb" from the database. (≈ 1 line)
    dist = np.linalg.norm(db_enc - encoding)

    # If this distance is less than the min_dist, then set min_dist to dist, and identity to name. (≈ 3 lines)
    if dist < min_dist:
      min_dist = dist
      identity = name

  if min_dist > threshold:
    if debug == True:
      print("Not in the database.")
    return None, None
  else:
    if debug == True:
      print("it's " + str(identity) + ", the distance is " + str(min_dist))
    return min_dist, identity

def faceID(img, modelo, database, threshold=DEFAULT_THRESHOLD, debug=True):
  caras = getMultiFace(img)
  totales = 0
  identificados = []
  fotos_caras = []
  fotos_no_identificados = []
  if caras is None:
    return [], [], []
  for c in caras:
    dist, identi = who_is_it_RAW(c[0], database, modelo, threshold=threshold, debug=debug)
    if identi is not None:
      identificados.append(identi + ' (' + str(dist) + ')')
      fotos_caras.append((np.uint8(c[0]), c[1], c[2], c[3], c[4]))
      totales += 1
    else:
      fotos_no_identificados.append((np.uint8(c[0]), c[1], c[2], c[3], c[4]))
  return identificados, fotos_caras, fotos_no_identificados

import matplotlib.pyplot as plt

# ESTO SOLO PARA JUPYTER
# %matplotlib inline

def pintaImagenRAW(img1):
  img_RGB = cv2.cvtColor(img1, cv2.COLOR_RGB2BGR)
  plt.imshow(img_RGB)
  plt.show()


import time
import argparse
import os
from PIL import Image
import pandas as pd
import numpy as np
import tensorflow as tf
from utils import setup_gpu_memory, get_image_names_with_path, join_images

parser = argparse.ArgumentParser(description='Process arguments.')
parser.add_argument('--data_dir', type=str, default='/projects/ncdot/2018/NC_2018_Images',
                    help='input dir of the videolog data to apply model prediction for')
parser.add_argument('--model_file', type=str,
                    default='/projects/ncdot/2018/machine_learning/model/guardrail_xception_subset.h5',
                    help='model file with path to be load for prediction')
parser.add_argument('--output_file', type=str,
                    default='/projects/ncdot/2018/machine_learning/output/guardrail_classification.csv',
                    help='prediction output csv file')
parser.add_argument('--image_base_names_file', type=str,
                    default='/projects/ncdot/2018/NC_2018_Images/metadata/sensor_data_mapped_unique_3584576.csv',
                    help='file that contains image base names of images in data_dir')
parser.add_argument('--image_base_name_length', type=int,
                    default='11',
                    help='the length of the image base name string')
parser.add_argument('--is_subset', action='store_true', default=False,
                    help='make predictions on subset data for development db ingestion')

args = parser.parse_args()
data_dir = args.data_dir
model_file = args.model_file
output_file = args.output_file
image_base_names_file = args.image_base_names_file
image_base_name_length = args.image_base_name_length
is_subset = args.is_subset

setup_gpu_memory()

strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
    # load the model
    model = tf.keras.models.load_model(model_file, compile=False)
print(model.summary())

def predict(image_base_name):
    path, left, front, right = get_image_names_with_path(data_dir, image_base_name)
    if not path or not left or not front or not right:
        return

    left_image = os.path.join(path, left)
    front_image = os.path.join(path, front)
    right_image = os.path.join(path, right)
    dst_img = join_images(left_image, front_image, right_image)
    if dst_img:
        img = dst_img.resize((299, 299), Image.ANTIALIAS)
        img = tf.keras.preprocessing.image.img_to_array(img)
        img = tf.keras.applications.xception.preprocess_input(img)
        predictions = model.predict(np.array([img]))
        return predictions[0][0]
    else:
        return np.nan

# read all image base names
if is_subset:
    df = pd.read_csv(image_base_names_file, dtype=str, header=0, index_col=False, nrows=18240,
                     usecols=["MAPPED_IMAGE"])
else:
    df = pd.read_csv(image_base_names_file, dtype=str, header=0, index_col=False, usecols=["MAPPED_IMAGE"])

strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
    ts = time.time()
    df['Probability'] = df.apply(lambda row: predict(row['MAPPED_IMAGE']), axis=1)
    te = time.time()
    print('time taken for model prediction:', te-ts)

df.to_csv(output_file, index=False)
print('Done')


#A template for the implementation of hclust
import math #sqrt
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import pandas as pd

#Importing Dataset
dataset = pd.read_csv('../data/movehubjoin.csv')

#Purchase Power
X = dataset.iloc[:,8]
#Cappuccino
Y = dataset.iloc[:,1]

#Puts all datapoints in points[] array
points = []
for i in range(sum(1 for line in open('../data/movehubjoin.csv'))):
    if (i < X.size) and (i < Y.size):
        point = [X[i], Y[i]]
        points.append(point)

#Purchase Power -- X-axis
X = dataset.iloc[:,8]
#Cappuccino 	   -- Y-axis
Y = dataset.iloc[:,1]

#Puts all datapoints in points[] array
#Each x- and y-coordinate stored in an array [x, y]
points = []
for i in range(sum(1 for line in open('../data/movehubjoin.csv'))):
	if (i < X.size) and (i < Y.size):
		point = [X[i], Y[i]]
		points.append(point)

# Accepts two data points a and b.
# Returns the distance between a and b.
# Note that this might be specific to your data.
def Distance(a,b):
    return math.sqrt( ((a[0]-b[0])**2)+((a[1]-b[1])**2) )

# Accepts two data points a and b.
# Produces a point that is the average of a and b.
def merge(a,b):
    return [(a[0] + b[0])/2 , (a[1] + b[1])/2]

# Accepts a list of data points.
# Returns the pair of points that are closest
def findClosestPair(D):
    if (len(D) <= 2):
        return D

    closestPair = [None] * 2
    minDistance = Distance(D[0], D[1])

    for dataPoint in D:
        c = D.index(dataPoint)
        for otherPoint in (D[:c]+D[c+1:]):
            if (Distance(dataPoint, otherPoint) < minDistance):
                minDistance = Distance(dataPoint, otherPoint)
                closestPair = [dataPoint, otherPoint]

    return closestPair

# Accepts a list of data points.
# Produces a tree structure corresponding to a
# Agglomerative Hierarchal clustering of D.
def HClust(D):
    centers = D
    splits = []

    while len(centers) > 1:
        # find closest pair [x, y] in D
        closestPair = findClosestPair(centers)

        #indexes i and (i+1)%2==1 in splits[] is the ith depth of dendogram
        #containing ith coordinates of closestPair
        #append closestPair according to ith depth of dendogram
        splits.append(closestPair[0])
        splits.append(closestPair[1])

        index = 0
        while index < len(centers):
            if centers[index] == closestPair[0]:
                #replace the element containing closestPair[x] in centers with the
                #mean point between the closestPair of points
                centers[index] = merge(closestPair[0], closestPair[1])

            elif centers[index] == closestPair[1]:
                #remove y-coordinate of closestPair from centers
                centers.remove(centers[index])

            index += 1

    dendoGram = visualize(splits)
    return dendoGram

#draws dendogram visualization of all points
def visualize(points):
    #turn regular array into numPy array
    numPyPoints = np.array(points)
    #DENDOGRAM
    linked = linkage(numPyPoints, 'single')
    plt.figure(figsize=(10, 7))
    dendrogram(linked,
                orientation='top',
                #labels=labelList,
                distance_sort='descending',
                show_leaf_counts=True)
    plt.xlabel('Purchase Power')
    plt.ylabel('Cappuccino')
    plt.savefig('../visualizations/hclust.png')
    return plt

def main():
    #create dendogram variable, then invoke matplotlib function show() on it
    myPlot = HClust(points)
    myPlot.show()

if __name__ == '__main__':
    main()


import socket

HOST = "198.244.190.230"
PORT = 65432

# TCP socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    s.bind((HOST, PORT))

    while True:

        data, address = s.recvfrom(65507)

        if not data:
            break

        s.sendto(data, address)


from networkx import read_edgelist

if __name__ == "__main__":
    # relabel node in graph
    # networkx_graph = read_edgelist('../storage/email-Eu-core-undirected-0.txt')
    #
    # for consec_node_id in range(networkx_graph.number_of_nodes()):
    #     if str(consec_node_id) not in networkx_graph.nodes:
    #         print(str(consec_node_id) + " not covered")

    old_path = '../storage/email-Eu-core.txt'
    edges = []
    edges_sets = []
    with open(old_path, 'r') as f:
        for line in f:
            edge = [int(node_id) for node_id in line.split(" ")]
            if set(edge) not in edges_sets and edge[0] != edge[1]:
                edges.append(edge)
                edges_sets.append(set(edge))
            else:
                print("found dublicated edge" + str(edge))

    new_path = '../storage/email-Eu-core-manual-undirected-0-test.txt'

    with open(new_path, 'w') as f:
        for edge in edges:
            edge_string = " ".join([str(node_id) for node_id in edge])
            edge_string += "\n"
            f.write(edge_string)


# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 06:41:56 2019

@author: Xkalaber
"""

def usage(script_name):
    print('Usage: py ' + script_name + ' <port number>')
if __name__=="__main__":
    import sys
    import socket
    import server_globals
    from msg_relay import MsgRelay
    argc=len(sys.argv)
    if argc !=2:
        usage(sys.argv[0])
        sys.exit()
    serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    serversocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    serversocket.bind(('localhost',int(sys.argv[1])))
    serversocket.listen(5)
    while True:
        sock,addr=serversocket.accept()
        print(sock.getsockname()[1])
        MsgRelay(sock).start()


import os
from sqlalchemy import Column, String, Integer
from flask_sqlalchemy import SQLAlchemy
import json

'''
database_name = "casting_agency"
database_path = f"postgresql://omar@:5432/{database_name}"
'''
database_url = os.environ.get('DATABASE_URL')

db = SQLAlchemy()
def setup_db(app, database_path=database_url):

    app.config["SQLALCHEMY_DATABASE_URI"] = database_url
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    db.app = app
    db.init_app(app)

helper_table = db.Table('helper',
    db.Column('movie_id', db.Integer, db.ForeignKey('Movie.id'), primary_key=True),
    db.Column('actor_id', db.Integer, db.ForeignKey('Actor.id'), primary_key=True)
)

class Actor(db.Model):
    __tablename__ = 'Actor'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True , nullable=False)
    age = db.Column(db.Integer, nullable=False)
    gender = db.Column(db.Enum('m','f', name='gender_types'), nullable=False)

    def insert(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    def format(self):
        return f"{self.name} - {self.age} - {self.gender}"

class Movie(db.Model):
    __tablename__ = 'Movie'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), unique=True, nullable=False)
    release_date = db.Column(db.Date(), nullable=False)
    actors = db.relationship('Actor', secondary=helper_table, backref=db.backref('movies', lazy=True))

    def insert(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    def format(self):
        return f"{self.title} - {self.release_date}"

'''
def db_drop_and_create_all():
    db.drop_all()
    db.create_all()
'''