"""proj URL Configuration

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

urlpatterns = [
    #url(r'^admin/', admin.site.urls),
    url(r'^$',home),
    url(r'^index',index,name="index"),                                  #home
    url(r'^hos_list',hos_list,name="hos_list"),                         #hospital list
    url(r'^patient_reg',patient_reg,name="patient_reg"),                #patient registration
    url(r'^login_ck',login_ck,name="login_ck"),                         #login check
    url(r'^hosp_reg',hosp_reg,name="hosp_reg"),                         #hospital registration
    url(r'^lab_reg',lab_reg,name="lab_reg"),                            #lab register
    url(r'^phar_reg',phar_reg,name="phar_reg"),                         #pharmacy register
    url(r'^login',login,name="login"),                                  #login portal redirect
    url(r'^phar',phar,name="phar"),                                     #pharmacy reg redirect
    url(r'^register',register,name="register"),                         #patient reg page redirect
    url(r'^hosp',hosp,name="hosp"),                                     #hospital reg page redirect
    url(r'^lab',lab,name="lab"),                                        #lab reg page redirect
    url(r'^main',main,name="main"),                                     #admin home page redirect
    url(r'^out',out,name="out"),                                        #logout redirect to home
    url(r'^adm_hosp',adm_hosp,name="adm_hosp"),                         #registering hospital to toc in admin portal
    url(r'^adm_phar',adm_phar,name="adm_phar"),                         #registering Pharmacy to toc in admin portal
    url(r'^adm_lab',adm_lab,name="adm_lab"),                            #registering labouratory to toc in admin portal
    url(r'^admin_hos',admin_hos,name="admin_hos"),                      #redirect to hospital page in admin portal when error registration occur
    url(r'^admin_lab',admin_lab,name="admin_lab"),                      #redirect to lab page in admin portal when error registration occur
    url(r'^admin_pha',admin_pha,name="admin_pha"),                      #redirect to pharmacy page in admin portal when error registration occur
    url(r'^app_hos',app_hos,name="app_hos"),                            #admin view of out hospital registration for approval
    url(r'^aprove_hos',aprove_hos,name="aprove_hos"),                   #admin approve the hospital and it stored in hosp regis and login db
    url(r'^app_lab',app_lab,name="app_lab"),                            #admin view of out lab registration for approval
    url(r'^aprove_lab',aprove_lab,name="aprove_lab"),                   #admin approve the lab and it stored in lab regis and login db
    url(r'^app_pha',app_pha,name="app_pha"),                            #admin view of out pharmacy registration for approval
    url(r'^aprove_pha',aprove_pha,name="aprove_pha"),                   #admin approve the pharmacy and it stored in phar regis and login db
    url(r'^ad_hosp_vw',ad_hosp_vw,name="ad_hosp_vw"),                   #admin view the registered hospitals
    url(r'^ad_lab_vw',ad_lab_vw,name="ad_lab_vw"),                      #admin view the registered outer labs and admin added labs
    url(r'^ad_pha_vw',ad_pha_vw,name="ad_pha_vw"),                      #admin view the registered outer phar and admin added phars
    url(r'^ad_pat_vw',ad_pat_vw,name="ad_pat_vw"),                      #admin view the registered patients
    url(r'^h_ad_delete',h_ad_delete,name="h_ad_delete"),                #delete hospital from the database
    url(r'^l_ad_delete',l_ad_delete,name="l_ad_delete"),                #delete lab from the database
    url(r'^p_ad_delete',p_ad_delete,name="p_ad_delete"),                #delete pharmacy from the database
    url(r'^refresh',refresh,name="refresh"),                            #refresh button used to update the status of data in admin page

    url(r'^hm_hosp',hm_hosp,name="hm_hosp"),                            #hospital home page
    url(r'^h_doc',h_doc,name="h_doc"),                                  #hospital portal redirect to adding doctor page
    url(r'^doc_h_add',doc_h_add,name="doc_h_add"),                      #adding doctors for the concern hospital
    url(r'^h_lab',h_lab,name="h_lab"),                                  #hospital portal redirect to adding lab page
    url(r'^ho_lab_add',ho_lab_add,name="ho_lab_add"),                   #adding labs for the concern hospital
    url(r'^h_pha',h_pha,name="h_pha"),                                  #hospital portal redirect to adding pharmacy page
    url(r'^pha_h_add',pha_h_add,name="pha_h_add"),                      #adding pharmacy for the concern hospital
    url(r'^hos_doc_vw',hos_doc_vw,name="hos_doc_vw"),                   #doctor list view for the hospital
    url(r'^del_h_doc',del_h_doc,name="del_h_doc"),                      #remove doc from hospital
    url(r'^hos_lab_vw',hos_lab_vw,name="hos_lab_vw"),                   #Lab list view for the hospital
    url(r'^del_h_lab',del_h_lab,name="del_h_lab"),                      #remove lab from hospital
    url(r'^hos_phar_vw',hos_phar_vw,name="hos_phar_vw"),                #Lab list view for the hospital
    url(r'^del_h_phar',del_h_phar,name="del_h_phar"),                   #remove lab from hospital
    url(r'^edit_hos',edit_hos,name="edit_hos"),                         #hospital profile edit
    url(r'^upd_hos',upd_hos,name="upd_hos"),                            #Hospital profile update
    url(r'^forget_pass',forget_pass,name="forget_pass"),                #password reset page
    url(r'reset',reset,name="reset"),                                   #reset password
    url(r'^fresh',fresh,name="fresh"),                                  #refresh in hospital
    url(r'^avail',avail,name="avail"),                                  #doctor available check

    url(r'^doct_hm',doct_hm,name="doct_hm"),                            #doctor hoem page
    url(r'^dr_bk_vw',dr_bk_vw,name="dr_bk_vw"),                         #Doctor book vw
    url(r'^qrcheck_dr',qrcheck_dr,name="qrcheck_dr"),                   #qr check and redirect
    url(r'^test_dr',test_dr,name="test_dr"),                            #add test
    url(r'^pre_dr',pre_dr,name="pre_dr"),                               #prescription
    url(r'^back',back,name="back"),                                     #redirect to qr view page
    url(r'^submit',submit,name="submit"),                               #consultaion

    url(r'^pat_hm',pat_hm,name="pat_hm"),                               #Patient home
    url(r'^for_log',for_log,name="for_log"),                            #login page for patient
    url(r'^check_log',check_log,name="check_log"),                      #patient login for book appointment from home
    url(r'^pt_hm_book',pt_hm_book,name="pt_hm_book"),                   #book appointment from patient page
    url(r'^vw_dr',vw_dr,name="vw_dr"),                                  #doctor booking view patient portal
    url(r'^pt_test',pt_test,name="pt_test"),                            #lab history
    url(r'^pt_pre',pt_pre,name="pt_pre"),                               #prescription history

    url(r'^homelab',homelab,name="homelab"),                            #labouratory homea page
    url(r'^tst_lab',tst_lab,name="tst_lab"),                            #lab qrcode check after
    url(r'^lstatus',lstatus,name="lstatus"),                            #lab test complete
    url(r'^vow_lab',vow_lab,name="vow_lab"),                            #lab test view request
    url(r'^info',info,name="info"),                                     #upload page
    url(r'^file_lab',file_lab,name="file_lab"),                         #upload file

    url(r'^o_labo_hm',o_labo_hm,name="o_labo_hm"),                      #out lab home page
    url(r'^ot_tst_lab',ot_tst_lab,name="ot_tst_lab"),                   #lab qrcode check after
    url(r'^aout_info',aout_info,name="aout_info"),                      #upload page
    url(r'^bout_file_lab',bout_file_lab,name="bout_file_lab"),          #upload file

    url(r'^pha_hm',pha_hm,name="pha_hm"),                               #pharmacy homea page
    url(r'^presc_pha',presc_pha,name="presc_pha"),                      #Pharmacy qrcode check after
    url(r'^pstatus',pstatus,name="pstatus"),                            #after medicine given
    url(r'^vew_presc',vew_presc,name="vew_presc"),                      #hosp pharamacy view
    url(r'^me_vw',me_vw,name="me_vw"),                                  #stock medicine view
    url(r'^pg_med_add',pg_med_add,name="pg_med_add"),                    #Add med pag
    url(r'^stock',stock,name="stock"),                                   #add medicine
    url(r'^print_bill',print_bill,name="print_bill"),                   #print bill

    url(r'^aa_o_pha_hm',aa_o_pha_hm,name="aa_o_pha_hm"),                #out pharmacy home page
    url(r'^kout_presc_pha',kout_presc_pha,name="kout_presc_pha"),       #out phar qrcode after
    url(r'^mout_pstatus',mout_pstatus,name="mout_pstatus"),             #after medicine given
    url(r'^vv_med_add',vv_med_add,name="vv_med_add"),                   #add medicine
    url(r'^yy_stock',yy_stock,name="yy_stock"),                         #update stock
    url(r'^ee_vw',ee_vw,name="ee_vw"),                                  #stock medicine view

    url(r'^list_hosp',list_hosp,name="list_hosp"),                      #hospital list
    url(r'^list_dept',list_dept,name="list_dept"),                      #hospital department
    url(r'^list_dr',list_dr,name="list_dr"),                            #hospital doctor
    url(r'^book_now',book_now,name="book_now"),                         #appointemnet doctor
    url(r'^stk_med',stk_med,name="stk_med"),                            #medicine stock check
    url(r'^z_stock',z_stock,name="z_stock"),                            #stock checker
    url(r'^autocomplete',autocomplete,name="autocomplete"),             #auto medicine load
    url(r'^medchecker',medchecker,name="medchecker"),                   #medicine availability checker

    url(r'^appoit',appoit,name="appoit"),                               #add appointmnet
    url(r'^recp',recp,name="recp"),                                     #add reception
    url(r'^wdept',wdept,name="wdept"),                                  #hosp departmenst
    url(r'^pbooking',pbooking,name="pbooking"),
    url(r'^iibook',iibook,name="iibook"),
    url(r'nn_list_dr',nn_list_dr,name="nn_list_dr"),

   #url(r'^patient_reg',patient_reg,name="Patient"),
   # url(r'^doc_reg',doc_reg,name="Doctor"),
   # url(r'^hosp_reg',hosp_reg,name="Hospital"),
   # url(r'^phar_reg',phar_reg,name="Pharmacy"),
   # url(r'^lab_reg',lab_reg,name="Labouratory"),
   # url(r'^o_hosp_reg',o_hosp_reg,name="Hospital"),
   # url(r'^o_phar_reg',o_phar_reg,name="Pharmacy"),
   # url(r'^o_lab_reg',o_lab_reg,name="Labouratory"),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import itertools
from pprint import pprint
from typing import List, Tuple, Optional

class Tile:
    def __init__(self,
                 tile_no: int,
                 edges: List[str],
                 inside: List[str] = None):
        self.tile_no = tile_no
        # top, right, bottom, left
        self.edges = edges
        self._inside = inside
        self.rotations = 0
        self.flips = 0

    def __repr__(self):
        return f'{self.tile_no}: {self.edges}'

    @property
    def inside(self):
        for _ in range(self.flips % 2):
            self._inside = self._flip_inside()
        for _ in range(self.rotations % 4):
            self._inside = self._rotate_inside()
        self.flips = 0
        self.rotations = 0
        return self._inside

    @staticmethod
    def from_text(lines: List[str]) -> 'Tile':
        """
        >>> tile = Tile.from_text(["Tile 1:",
        ...                        "abcd",
        ...                        "l12e",
        ...                        "k43f",
        ...                        "jihg"])
        >>> pprint(tile)
        1: ['abcd', 'defg', 'ghij', 'jkla']

        >>> tile.inside
        ['12', '43']

        :param lines:
        :return:
        """
        title, *lines = lines
        tile_no = int(title.replace('Tile ', '').replace(':', ''))

        # sides clock_wise, starting from top
        top = lines[0]
        right = "".join(line[-1] for line in lines)
        bottom = lines[-1][-1::-1]
        left = "".join(line[0] for line in lines[-1::-1])

        return Tile(tile_no,
                    [top, right, bottom, left],  # edges
                    [line[1:-1] for line in lines[1:-1]])  # inside

    def flip_horiz(self):
        """
        Flips tile horizontally.
        vertical flip == flip + rotate
        >>> tile = Tile.from_text(["Tile 1:",
        ...                 "abcd",
        ...                 "l12e",
        ...                 "k43f",
        ...                 "jihg"]).flip_horiz()
        >>> tile.edges
        ['dcba', 'alkj', 'jihg', 'gfed']

        >>> tile.inside
        ['21', '34']

        """
        top, right, bottom, left = self.edges
        left, right = right[-1::-1], left[-1::-1]
        top = top[-1::-1]
        bottom = bottom[-1::-1]
        self.edges = [top, right, bottom, left]
        self.flips += 1
        # self._flip_inside()
        return self

    def rotate_cw(self):
        """
        Rotate clockwise 90

        >>> tile = Tile.from_text(["Tile 1:",
        ...                 "abcd",
        ...                 "l12e",
        ...                 "k43f",
        ...                 "jihg"]).rotate_cw()
        >>> tile.edges
        ['jkla', 'abcd', 'defg', 'ghij']

        >>> tile.inside
        ['41', '32']
        """
        top, right, bottom, left = self.edges
        top, right, bottom, left = left, top, right, bottom
        self.edges = [top, right, bottom, left]
        # self._rotate_inside()
        self.rotations += 1
        return self

    def match(self, other: 'Tile') -> Optional[Tuple[int, 'Tile']]:
        """
        Transform _other_ tile to match one side.

        >>> this = Tile.from_text(["Tile 1:",
        ...                        "abcd",
        ...                        "l..e",
        ...                        "k..f",
        ...                        "jihg"])
        >>> other = Tile.from_text(["Tile 2:",
        ...                         "axxx",
        ...                         "l..x",
        ...                         "k..x",
        ...                         "jxxx"])
        >>> this.match(other)
        (3, 2: ['xxxa', 'alkj', 'jxxx', 'xxxx'])

        >>> this = Tile.from_text([
        ...      "Tile 1951:",
        ...      "#.##...##.",
        ...      "#.####...#",
        ...      ".....#..##",
        ...      "#...######",
        ...      ".##.#....#",
        ...      ".###.#####",
        ...      "###.##.##.",
        ...      ".###....#.",
        ...      "..#.#..#.#",
        ...      "#...##.#..",])
        >>> other = Tile.from_text([
        ...      "Tile 2729:",
        ...      "...#.#.#.#",
        ...      "####.#....",
        ...      "..#.#.....",
        ...      "....#..#.#",
        ...      ".##..##.#.",
        ...      ".#.####...",
        ...      "####.#.#..",
        ...      "##.####...",
        ...      "##..#.##..",
        ...      "#.##...##.",])
        >>> this.match(other)
        (0, 2729: ['...#.#.#.#', '#..#......', '.##...##.#', '####....#.'])

                                                      ^
        _this_ matched on top (0) --------------------|

        :param other: rotate / flip, match
        :return: Tuple of
            - index of matched side of (this) tile
            - other tile rotated / flipped to match
        """

        for flips in range(2):
            other.flip_horiz()
            # print(self)
            # print(other)
            # print('=' * 10)
            for edge_index, edge in enumerate(self.edges):
                # print(f'[{edge_index}] {edge} :')
                for rotations in range(4):
                    other.rotate_cw()
                    # opposite side: top <-> bottom, left <-> right
                    other_edge = other.edges[(edge_index + 2) % 4]
                    # print(f'  /{(edge_index + 2) % 4}/ {other_edge[-1::-1]}')
                    if edge == other_edge[-1::-1]:
                        # print('✔')
                        return edge_index, other
                # print('-' * 10)
        return None

    def _rotate_inside(self) -> List[str]:
        rows = len(self._inside)

        def _rotate(row, col):
            _row, _col = -col, row
            return _row + rows - 1, _col

        def _get(coords):
            row, col = coords
            return self._inside[row][col]

        return [
            "".join([_get(_rotate(row, col)) for col, _ in enumerate(r)])
            for row, r in enumerate(self._inside)
        ]

    def _flip_inside(self) -> List[str]:
        return [
            line[-1::-1] for line in self._inside
        ]

def rotate(image: List[str]) -> List[str]:
    """
    >>> rotate(["123",
    ...         "456",
    ...         "789"])
    ['741', '852', '963']

    >>> rotate(["1234",
    ...         "5678",
    ...         "90ab",
    ...         "cdef"])
    ['c951', 'd062', 'ea73', 'fb84']

    :return:
    """
    rows = len(image)

    def _rotate(row, col):
        _row, _col = -col, row
        return _row + rows - 1, _col

    def _get(coords):
        row, col = coords
        return image[row][col]

    return [
        "".join([_get(_rotate(row, col)) for col, _ in enumerate(r)])
        for row, r in enumerate(image)
    ]

def flip(image: List[str]) -> List[str]:
    """
    flip horizontally
    >>> flip(["1234",
    ...       "5678",
    ...       "90ab",
    ...       "cdef"])
    ['4321', '8765', 'ba09', 'fedc']

    """
    return [
        line[-1::-1] for line in image
    ]

if __name__ == '__main__':
    import doctest
    doctest.testmod()

    pass


# 导入数据
from com.fp.tree.myID3 import createTree
from com.fp.tree.treeview import createPlot

def createDataSet():
    dataSet = [['youth', 'no', 'no', 1, 'refuse'],
               ['youth', 'no', 'no', '2', 'refuse'],
               ['youth', 'yes', 'no', '2', 'agree'],
               ['youth', 'yes', 'yes', 1, 'agree'],
               ['youth', 'no', 'no', 1, 'refuse'],
               ['mid', 'no', 'no', 1, 'refuse'],
               ['mid', 'no', 'no', '2', 'refuse'],
               ['mid', 'yes', 'yes', '2', 'agree'],
               ['mid', 'no', 'yes', '3', 'agree'],
               ['mid', 'no', 'yes', '3', 'agree'],
               ['elder', 'no', 'yes', '3', 'agree'],
               ['elder', 'no', 'yes', '2', 'agree'],
               ['elder', 'yes', 'no', '2', 'agree'],
               ['elder', 'yes', 'no', '3', 'agree'],
               ['elder', 'no', 'no', 1, 'refuse'],
               ]
    labels = ['age', 'working?', 'house?', 'credit_situation']
    return dataSet, labels

# 测试代码
if __name__ == "__main__":
    myDat, labels = createDataSet()
    myTree = createTree(myDat, labels)

    print(myTree)
    createPlot(myTree)


#!/usr/bin/python3
"""Flask web application. Routes  / and /hbnb."""
from flask import Flask, render_template
from models import storage
from models.state import State

app = Flask(__name__)
app.url_map.strict_slashes = False

@app.route('/states_list')
def states():
    """displays HTML only if n is integer."""
    states = storage.all(State)
    list = []
    for val in states.values():
        list.append(val)
    return render_template('7-states_list.html', states=list)

@app.teardown_appcontext
def teardown_appcontext(arg):
    """tear down method."""
    storage.close()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='5000')


import dibujarPlanilla as db
import dato
import Resultado as Rs
import time

"""items = dato.data['Cortes']
A = dato.data['Plantilla'][0]
H = dato.data['Plantilla'][1]"""
#############################
"""items = dato.data2['Cortes']
A = dato.data2['Plantilla'][0]
H = dato.data2['Plantilla'][1]"""
#############################

items = dato.data3['Cortes']
A = dato.data3['Plantilla'][0]
H = dato.data3['Plantilla'][1]
sideTouch = [[0,0]]
tiempo = 0

def Fase1():
    for i in range(1, len(items)):
        key = items[i][0]*items[i][1]
        temp = items[i]
        j = i-1
        while j >=0 and key > (items[j][0]*items[j][1]):
            items[j+1] = items[j]
            j-=1
        items[j+1] = temp

    for i in range(len(items)):
        if items[i][0]<items[i][1]:
            aux = items[i][0]
            items[i][0] = items[i][1]
            items[i][1] = aux

def colocar(k, posX, posY, x, plantilla):
    if x == 0:
        for i in range(posY, posY + items[k][1]):
            for j in range(posX, posX + items[k][0]):
                plantilla[i][j] = k
    else:
        for i in range(posY, posY + items[k][1]):
            for j in range(posX, posX + items[k][0]):
                plantilla[i][j] = k

def mi(x,empacado):
    minimo = 9999
    for i in range(len(items)):
        if empacado[i] == 0:
            if x == 1:
                if items[i][0] < minimo and empacado[i] == 0:
                    minimo = items[i][0]
            else:
                if items[i][1] < minimo and empacado[i] == 0:
                    minimo = items[i][1]
    return minimo

def calcularPosY(posC, plantilla,empacado,posiciones):
    minimo = 999
    it = 0
    for i in range(posC, len(empacado)):
        if empacado[i] == 1:
            if items[i][1]+posiciones[i][1] < minimo and A-posiciones[i][0] >= mi(2,empacado):
                    minimo = items[i][1]+posiciones[i][1]
                    it = i
    posC = it+1

    return posiciones[it][0], posiciones[it][1] + items[it][1], posC

def touchHorizontal(i,x,y,h,b, plantilla):
# cantidad de perimetro que choca con un bloque a la izquierda
    if sideTouch[0][h] == 0:
        if h == 0:
            #si x = 0, es decir choca con la pared o si el bloque i es mas pequeño o igual se pone la altura del bloque i
            if x == 0 or items[plantilla[y][x]][1] >= items[i][1]:
                sideTouch[0][h] += items[i][1]
            #si el bloque i es mas grande, se pone la altura del otro bloque
            else:
                for k in range(x,x+items[i][1]):
                    if k < H:
                        if plantilla[k][x] != -1:
                            sideTouch[0][h] += 1
            #si el ancho del bloque i + su posicion x es igual al ancho de la plantilla, se suma la altura del bloque i
            if b:
                if x+items[i][0] == A:
                    sideTouch[0][h] += items[i][1]

                elif x+items[i][0]+1 < A:
                     if plantilla[y][x+items[i][0]+1] != -1:
                        for o in range(y,H):
                            if plantilla[o][x+items[i][0]+1] != -1:
                                sideTouch[0][h] += 1
                                break

            elif x + items[i][0]+1 == A or plantilla[y][x+items[i][0]+1] != -1:
                sideTouch[0][h] += items[i][1]
        else:
            if x == 0 or items[plantilla[y][x]][1] >= items[i][0]:
                sideTouch[0][h] += items[i][0]
            else:
                for k in range(y,y+items[i][0]):
                    if plantilla[k][x] != -1:
                        sideTouch[0][h] += 1
            if b:
                if x+items[i][1] == A :
                    sideTouch[0][h] += items[i][0]
            elif x + items[i][1]+1 == A:
                sideTouch[0][h] += items[i][0]

def touchVertical(i,x,y,v, plantilla):
    if v == 0:
        #si el bloque i toca el suelo o si el ancho bloque i es menor o igual al bloque que esta por debajo, se pone todo el ancho
        if y == 0 or items[plantilla[y][x]][0] >= items[i][0]:
            sideTouch[0][v] += items[i][0]
    #si el ancho del bloque que esta por debajo es mas pequeño que el ancho bloque i, se pone el ancho del otro bloque
        else:
            for k in range(x, x+items[i][0]):
                if plantilla[y][k] != -1:
                    sideTouch[0][v] += 1
    #si el alto del bloque i + su posicion Y choca con la parte superior de la plantilla, se pone el ancho del bloque i
        if y + items[i][1]+1 == H:
            sideTouch[0][v]+= items[i][0]
    else:
        if y == 0 or items[plantilla[y][x]][0] >= items[i][1]:
            sideTouch[0][v] += items[i][1]
        else:
            for k in range(items[i][0]):
                if plantilla[y][k] != -1:
                    sideTouch[0][v] += 1
        if y + items[i][0] == H:
            sideTouch[0][v]+= items[i][1]

def score(j, menorA, ultX, ultY, posCorrect, plantilla,empacado,posiciones):
    auxX = ultX
    auxY = ultY
    PorcentajeA = 0.0
    PorcentajeH = 0.0
    sobranteA = 0
    sobranteH = 0
    maximo = 0.0
    posMax = -1
    posC = posCorrect
    orientacion = 0  # 0 = horizontal, 1 = vertical
#Calculo el sobrante desde la ultima posicion Y ocupada
    for k in range(A):
        if ultY < H:
            if plantilla[ultY][k] == -1:
                sobranteA += 1
        else: ultX = 0

    for k in range(H):
        if ultX < A:
            if plantilla[k][ultX] == -1:
                sobranteH += 1
        else: ultX = 0

    for i in range(0, len(empacado)):
        if empacado[i] == 0:
            minimoA = mi(1,empacado)
            minimoH = mi(2,empacado)
            if sobranteA >= minimoA or sobranteA >= minimoH:
                if sobranteA >= minimoA and auxY + items[i][1] <= H and auxX + items[i][0] <= A:
                    #Calculo la suma de lados que chocan con el limiteA que no esten emapacdos
                    if ultX == 0 and ultY == 0 and items[i][0] < A:
                        ultX = 1
                        touchHorizontal(i, ultX-1, ultY,0,False,plantilla)
                        ultX = 0
                    else:
                        touchHorizontal(i, ultX-1, ultY,0,False,plantilla)
                    if ultY == 0:
                        touchVertical(i,ultX,ultY,0,plantilla)
                    else:
                        touchVertical(i,ultX,ultY-1,0,plantilla)
                    PorcentajeA = (sideTouch[0][0]/(items[i][0]*2+items[i][1]*2)) * 100
                    sideTouch[0][0] = 0

                #VERTICAL
                if sobranteA >= minimoH and auxX + items[i][1] <= A and auxY + items[i][0] <= H:
                    if ultX == 0 and ultY == 0:
                        ultX = 1
                        touchHorizontal(i, ultX-1, ultY,1,False,plantilla)
                        ultX = 0
                    else:
                        touchHorizontal(i, ultX-1, ultY,1,False,plantilla)
                    if ultY == 0:
                        touchVertical(i,ultX,ultY,1,plantilla)
                    else:
                        touchVertical(i,ultX,ultY-1,1,plantilla)
                    PorcentajeH = (sideTouch[0][1]/(items[i][0]*2+items[i][1]*2)) * 100
                    sideTouch[0][1] = 0

    #Se podrá poner encima una caja si no sobrepasa la altura de la plantilla y el bloque no entra ni horizontal o verticalmente
            else:
                auxX, auxY, posC = calcularPosY(posCorrect,plantilla,empacado,posiciones)
                if auxY + items[i][1] <= H and items[i][0]+auxX < A:
                    if auxX != 0:
                        touchHorizontal(i, auxX-1, auxY,0,True,plantilla)
                    else:
                        touchHorizontal(i, auxX, auxY,0,True,plantilla)
                    if auxY == 0:
                        touchVertical(i,auxX,auxY,0,plantilla)
                    else:
                        touchVertical(i,auxX,auxY-1,0,plantilla)
                    PorcentajeA = (sideTouch[0][0]/(items[i][0]*2+items[i][1]*2)) * 100
                    sideTouch[0][0] = 0
                elif maximo == 0:
                    orientacion = -1
            #Halla el mayor Porcenteje
            if PorcentajeA == PorcentajeH:
                if PorcentajeA > maximo:
                    maximo == PorcentajeA

            if PorcentajeA > maximo:
                orientacion = 0
                maximo = PorcentajeA
                posMax = i
            if PorcentajeH > maximo:
                maximo = PorcentajeH
                posMax = i
                orientacion = 1

    if orientacion == 1:
        cambioOri= items[posMax][0]
        items[posMax][0] = items[posMax][1]
        items[posMax][1] = cambioOri

    #sideTouch = [[0,0] for i in range(len(empacado))]
    return auxX, auxY, posMax, orientacion, posC

def AlgoritmoTP(empacado,Desperdicio):
    plantilla = [[-1 for i in range(A)]for i in range(H)]
    Fase1()
    ultX= 0
    ultY = 0
    PosCorrecta = 0
    orientacion = 0
    Desperdicio_ = 0
    DesperdicioFinal = Desperdicio
    posiciones = [[-1,-1]for i in range(len(items))]
    for j in range(len(items)):
         if Desperdicio_ <= Desperdicio:
            if 0 in empacado:
                ultX, ultY, posMax, orientacion, PosCorrecta = score(j,mi(1,empacado),ultX,ultY, PosCorrecta, plantilla,empacado,posiciones)
                if orientacion == 0:
                    if posMax != -1:
                        empacado[posMax] = 1
                        colocar(posMax,ultX,ultY,orientacion,plantilla)
                        posiciones[posMax][0] = ultX
                        posiciones[posMax][1] = ultY
                        ultX += items[posMax][0]
                        if Desperdicio_ + (items[posMax][0]*items[posMax][1]) <= Desperdicio:
                            Desperdicio_ += (items[posMax][0]*items[posMax][1])
                elif orientacion == 1:
                    if posMax != -1:
                        empacado[posMax] = 1
                        colocar(posMax,ultX,ultY,orientacion,plantilla)
                        posiciones[posMax][0] = ultX
                        posiciones[posMax][1] = ultY
                        ultX += items[posMax][0]
                        if Desperdicio_ + (items[posMax][0]*items[posMax][1]) <= Desperdicio:
                            Desperdicio_ += (items[posMax][0]*items[posMax][1])
    if 0 in empacado:
        DesperdicioFinal = Desperdicio - Desperdicio_
        Porcentaje = (DesperdicioFinal/Desperdicio)*100
        db.dibujo(A,H,posiciones,items,DesperdicioFinal, empacado, Porcentaje)
        #Rs.Escribir(items,DesperdicioFinal, dato.data2)
        AlgoritmoTP(empacado,A*H)
    else:
        DesperdicioFinal = Desperdicio - Desperdicio_
        Porcentaje = (DesperdicioFinal/Desperdicio)*100
        #Rs.Escribir(items,DesperdicioFinal, dato.data2)
        db.dibujo(A,H,posiciones,items,DesperdicioFinal,empacado, Porcentaje)

AlgoritmoTP([0 for i in range(len(items))],A*H)
tiempo = time.process_time()
print(tiempo)


from Qt import QtWidgets
import sys
import logging

log = logging.getLogger(__name__)

class Window(QtWidgets.QWidget):
    def __init__(self, parent, title, message, level):
        super(Window, self).__init__()
        self.parent = parent
        self.title = title
        self.message = message
        self.level = level

        if self.level == "info":
            self._info()
        elif self.level == "warning":
            self._warning()
        elif self.level == "critical":
            self._critical()

    def _info(self):
        self.setWindowTitle(self.title)
        rc = QtWidgets.QMessageBox.information(
            self, self.title, self.message)
        if rc:
            self.exit()

    def _warning(self):
        self.setWindowTitle(self.title)
        rc = QtWidgets.QMessageBox.warning(
            self, self.title, self.message)
        if rc:
            self.exit()

    def _critical(self):
        self.setWindowTitle(self.title)
        rc = QtWidgets.QMessageBox.critical(
            self, self.title, self.message)
        if rc:
            self.exit()

    def exit(self):
        self.hide()
        # self.parent.exec_()
        # self.parent.hide()
        return

def message(title=None, message=None, level="info", parent=None):
    app = parent
    if not app:
        app = QtWidgets.QApplication(sys.argv)

    ex = Window(app, title, message, level)
    ex.show()

    # Move widget to center of screen
    try:
        desktop_rect = QtWidgets.QApplication.desktop().availableGeometry(ex)
        center = desktop_rect.center()
        ex.move(
            center.x() - (ex.width() * 0.5),
            center.y() - (ex.height() * 0.5)
        )
    except Exception:
        # skip all possible issues that may happen feature is not crutial
        log.warning("Couldn't center message.", exc_info=True)
    # sys.exit(app.exec_())


"""
"""

# Created on 2013.05.31
#
# Author: Giovanni Cannata
#
# Copyright 2013, 2014, 2015, 2016, 2017 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ldap3 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ldap3 in the COPYING and COPYING.LESSER files.
# If not, see <http://www.gnu.org/licenses/>.

from .. import SEQUENCE_TYPES, MODIFY_ADD, MODIFY_DELETE, MODIFY_REPLACE, MODIFY_INCREMENT
from ..protocol.rfc4511 import ModifyRequest, LDAPDN, Changes, Change, Operation, PartialAttribute, AttributeDescription, Vals, ResultCode
from ..operation.bind import referrals_to_list
from ..protocol.convert import changes_to_list, validate_attribute_value, prepare_for_sending

# ModifyRequest ::= [APPLICATION 6] SEQUENCE {
#    object          LDAPDN,
#    changes         SEQUENCE OF change SEQUENCE {
#        operation       ENUMERATED {
#            add     (0),
#            delete  (1),
#            replace (2),
#            ...  },
#    modification    PartialAttribute } }

change_table = {MODIFY_ADD: 0,  # accepts actual values too
                MODIFY_DELETE: 1,
                MODIFY_REPLACE: 2,
                MODIFY_INCREMENT: 3,
                0: 0,
                1: 1,
                2: 2,
                3: 3}

def modify_operation(dn,
                     changes,
                     auto_encode,
                     schema=None):
    # changes is a dictionary in the form {'attribute': [(operation, [val1, ...]), ...], ...}
    # operation is 0 (add), 1 (delete), 2 (replace), 3 (increment)
    # increment as per RFC4525

    change_list = Changes()
    pos = 0
    for attribute in changes:
        for change_operation in changes[attribute]:
            partial_attribute = PartialAttribute()
            partial_attribute['type'] = AttributeDescription(attribute)
            partial_attribute['vals'] = Vals()
            if isinstance(change_operation[1], SEQUENCE_TYPES):
                for index, value in enumerate(change_operation[1]):
                    partial_attribute['vals'].setComponentByPosition(index, prepare_for_sending(validate_attribute_value(schema, attribute, value, auto_encode)))
            else:
                partial_attribute['vals'].setComponentByPosition(0, prepare_for_sending(validate_attribute_value(schema, attribute, change_operation[1], auto_encode)))
            change = Change()
            change['operation'] = Operation(change_table[change_operation[0]])
            change['modification'] = partial_attribute

            change_list[pos] = change
            pos += 1

    request = ModifyRequest()
    request['object'] = LDAPDN(dn)
    request['changes'] = change_list
    return request

def modify_request_to_dict(request):
    return {'entry': str(request['object']),
            'changes': changes_to_list(request['changes'])}

def modify_response_to_dict(response):
    return {'result': int(response['resultCode']),
            'description': ResultCode().getNamedValues().getName(response['resultCode']),
            'message': str(response['diagnosticMessage']),
            'dn': str(response['matchedDN']),
            'referrals': referrals_to_list(response['referral'])}


WorldSize = 100
def first_index(my_list, elem):
  try: index = my_list.index(elem) + 1
  except: index = 0
  return index
def listmonsters():
	global Monsters
	for i in Monsters:
		print(i['First Name'])
		pass
def listinventory():
	global Player
	for i in Player['Inventory']:
		print(i)
		pass
def spawnitem(X):
	spawn(X)
	pickupitem()
def pickupitem():
	Player['Inventory'].append(Monsters[-1]['Race'])
	Player['InventoryData'].append(Monsters.pop(-1))
def spawn(Monster):#Monster Spawning System
	global Monsters, Names, ObjectData, Objects
	Monster = Monster.title()
	Monsters.append({
	'Race': Monster,
	'First Name': random.choice(Names[Monster]),
	'Last Name': random.choice(Names[Monster]),
	'Health': [],
	'Gender': random.choice(ObjectData[Monster]['Genders']),
	'Soul': ObjectData[Monster]['Soul'],
	'X': random.randint(0-WorldSize, WorldSize),
	'Y': random.randint(0-WorldSize, WorldSize)
	})
	for i in Objects[Monster][Monsters[-1]['Gender']]:
		Monsters[-1]['Health'].append([ObjectData[Monster][Monsters[-1]['Gender']]['Health'], ObjectData[Monster][Monsters[-1]['Gender']]['Health']])
def login(First, Last):#Login System
	global Players
	try:
		Players.append({
		'First Name': First.title(),
		'Last Name': Last.title()
		})
		Players[-1] = {
		'First Name': Players[-1]['First Name'],
		'Last Name': Players[-1]['Last Name'],
		'Health': open('Players/' + Players[-1]['First Name'] + ' ' + Players[-1]['Last Name'] + '.txt').read().split(E)[0].split(','),
		'Gender': str(open('Players/' + Players[-1]['First Name'] + ' ' + Players[-1]['Last Name'] + '.txt').read().split(E)[1]),
		'Inventory': open('Players/' + Players[-1]['First Name'] + ' ' + Players[-1]['Last Name'] + '.txt').read().split(E)[2].split(','),
		'Rank': int(open('Players/' + Players[-1]['First Name'] + ' ' + Players[-1]['Last Name'] + '.txt').read().split(E)[3]),
		'InventoryExec': open('Players/' + Players[-1]['First Name'] + ' ' + Players[-1]['Last Name'] + '.txt').read().split(E)[4].split('#'),
		'InventoryData': []
		}
		for i in range(len(Players[-1]['Health'])):
			Players[-1]['Health'][i] = Players[-1]['Health'][i].split('#')
		for i in range(len(Players[-1]['InventoryExec'])):
			exec(Players[-1]['InventoryExec'][i])
		for i in Players[-1]['Health']:
			for j in i:
				j = int(j)
	except NameError:
		print('Login Failed')
def killplayer(P):
	P = P.split(' ')
	login(P[0], P[1])
	Players[-1]['Health'] = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
	logout()
def logout():#Log Out System
	global Players
	try:
		Z = []
		X = []
		Y = []
		for i in Players[-1]['InventoryData']:
			Z.append('Players[-1]["InventoryData"].append(' + str(i) + ')')
		for i in Players[-1]['Health']:
			Y.append('#'.join(i))
		X.append(','.join(Y))
		X.append(Players[-1]['Gender'])
		X.append(','.join(Players[-1]['Inventory']))
		X.append(str(Players[-1]['Rank']))
		X.append('#'.join(Z))
		open('Players/' + Players[-1]['First Name'] + ' ' + Players[-1]['Last Name'] + '.txt', 'w').write(E.join(X))
		Players.pop(-1)
	except:
		print('Log Out Failed')
def saveplayer(n):#Log Out System
	global Players
	try:
		Z = []
		X = []
		Y = []
		for i in Players[n]['InventoryData']:
			Z.append('Players[-1]["InventoryData"].append(' + str(i) + ')')
		for i in Players[n]['Health']:
			Y.append('#'.join(i))
		X.append(','.join(Y))
		X.append(Players[n]['Gender'])
		X.append(','.join(Players[n]['Inventory']))
		X.append(str(Players[n]['Rank']))
		X.append('#'.join(Z))
		open('Players/' + Players[n]['First Name'] + ' ' + Players[n]['Last Name'] + '.txt', 'w').write(E.join(X))
	except:
		print('Save Failed')
def saveworld():
	global Monsters
	open('World/Objects.txt', 'w').write('}\n'.join(str('Monsters = ' + str(Monsters)).split('}')))


"""2.2 Return Kth to Last

Problem:

    Implement an algorithm to find the kth to last element of a singly linked
    list.

Approach:

    The problem appears to warrant first to iterate entire length of the list in
    order to compute the position of the kth last node. However, we can do
    better by prepare a runner that is k-th place forward in the list prior to
    iterate to find the kth to the last place.

"""

from LinkedList import ListNode, createLinkedList, printLinkedList

class Solution:
    def returnKthToLast(self, head, K):
        if not head or K < 0: return
        curr = runner = head
        while K:
            if not runner.next:
                runner = head
            runner = runner.next
            K -= 1
        while runner:
            curr, runner = curr.next, runner.next
        return curr.data

def main():
    head = createLinkedList([1, 2, 3, 4, 5])
    assert Solution().returnKthToLast(head, 2) == 4

if __name__ == '__main__':
    main()


import matplotlib.pyplot as plt
import networkx as nx
import pymongo

client = pymongo.mongo_client.MongoClient()
C = client.weibo.user

g = nx.Graph()
def getFriends(follows, fans):
    follows = set(follows)
    fans = set(fans)
    return follows.intersection(fans)

for user in C.find():
    uid = user['uid']
    fans = user['fans']
    follows = user['follows']
    friends = getFriends(follows, fans)
    friends_edge = [(uid , x) for x in friends]

#    fans_edge = [(x , uid) for x in fans ]
#    follows_edge = [(uid , x) for x in follows]
#    g.add_edges_from(fans_edge)
#    g.add_edges_from(follows_edge)
    if len(friends)>=1:
        g.add_edges_from(friends_edge)

pos = nx.spring_layout(g)
nx.draw(g, pos = pos, node_size = 30 , with_labels = False)
plt.show()


from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()

import json
jj = open('kate_customers.json')
list = json.load(jj)
res = es.bulk(index="cat-index",  body=list)
print(res['result'])

j = 0
actions = []
while (j <= 10):
    action = {
        "_index": "tickets-index",
        "_type": "tickets",
        "_id": j,
        "_source": {
            "any":"data" + str(j),
            "timestamp": datetime.now()
            }
        }
    actions.append(action)
    j += 1

helpers.bulk(es, actions)
'''
    res = es.get(index="test-index", doc_type='tweet', id=1)
    print(res['_source'])

es.indices.refresh(index="cat-test")
'''
'''
res = es.search(index="test-index", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total'])
for hit in res['hits']['hits']:
    print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])
'''


api_people_url = '/api/v1/people/'
api_auth_url = '/api/rest-auth/'

people_sample_data = [
    {
        "name": "Rose",
        "surname": "Kuphal Altenwerth",
        "code": "0403402",
        "start_date": "2016-10-31"
    },
    {
        "name": "Ryan",
        "surname": "Hintz Heathcote",
        "code": "0184936",
        "start_date": "2030-04-16"
    },
    {
        "name": "Maryam",
        "surname": "Gerlach Abernathy",
        "code": "8899096",
        "start_date": "2016-07-15",
        "end_date": "2030-09-23",
    },
    {
        "name": "Jabari",
        "surname": "Carter Schmidt",
        "code": "4535461",
        "start_date": "2028-05-30",
        "end_date": "2030-12-02"
    },
    {
        "name": "Krista",
        "surname": "Krajcik Bosco",
        "code": "9638336",
        "start_date": "2016-10-15",
        "end_date": "2017-10-25",
    }
]


# =================================================================================================
# Copyright 2011 Twitter, Inc.
# -------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the License.
# You may obtain a copy of the License in the LICENSE file, or at:
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =================================================================================================

from twitter.pants.targets import (
    AnnotationProcessor,
    Artifact,
    Benchmark,
    Bundle,
    Credentials,
    Exclude,
    JarDependency,
    JarLibrary,
    JavaAgent,
    JavaAntlrLibrary,
    JavaLibrary,
    JavaProtobufLibrary,
    JavaTests,
    JavaThriftLibrary,
    JvmApp,
    JvmBinary,
    Page,
    Pants,
    PythonArtifact,
    PythonBinary,
    PythonEgg,
    PythonLibrary,
    PythonAntlrLibrary,
    PythonRequirement,
    PythonThriftLibrary,
    PythonTests,
    PythonTestSuite,
    Repository,
    Resources,
    ScalaLibrary,
    ScalaTests,
    ScalacPlugin,
    SourceRoot,
    Wiki)

# aliases
annotation_processor = AnnotationProcessor
artifact = Artifact
benchmark = Benchmark
bundle = Bundle
credentials = Credentials
dependencies = jar_library = JarLibrary
egg = PythonEgg
exclude = Exclude
fancy_pants = Pants
jar = JarDependency
java_agent = JavaAgent
java_library = JavaLibrary
java_antlr_library = JavaAntlrLibrary
java_protobuf_library = JavaProtobufLibrary
junit_tests = java_tests = JavaTests
java_thrift_library = JavaThriftLibrary
jvm_binary = JvmBinary
jvm_app = JvmApp
page = Page
python_artifact = setup_py = PythonArtifact
python_binary = PythonBinary
python_library = PythonLibrary
python_antlr_library = PythonAntlrLibrary
python_requirement = PythonRequirement
python_thrift_library = PythonThriftLibrary
python_tests = PythonTests
python_test_suite = PythonTestSuite
repo = Repository
resources = Resources
scala_library = ScalaLibrary
scala_specs = scala_tests = ScalaTests
scalac_plugin = ScalacPlugin
source_root = SourceRoot
wiki = Wiki


from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
import math
import time
# from scipy.spatial import KDTree
import sys, getopt
# from numpy import cross, eye, dot
# from scipy.linalg import expm3, norm
# from scipy.optimize import minimize
# from mpl_toolkits.mplot3d import Axes3D

'''
This program generates proteins made out of 4 beads that attach to each other via 2 patches
and places them in a spiral position. It generates the Lammps read-in file.
'''

def proteingenerator(radius_o,x_start,x_step,n,cell_radius,tau):
    # Generate unrotated protein positions
    P1 = [radius_o*np.cos(tau)-x_start+n*x_step, 0 ,-cell_radius-np.sin(tau)*radius_o]
    P2 = [-radius_o*np.cos(tau)-x_start+n*x_step, 0 ,-cell_radius+np.sin(tau)*radius_o]
    P3 = [-x_start+n*x_step+np.sin(tau)*radius_o*np.sqrt(3), 0 ,-cell_radius+np.sqrt(3)*radius_o*np.cos(tau)]
    return P1,P2,P3

def plane_rotation(theta,coordinates):
    x = coordinates[0]
    y = np.cos(theta)*coordinates[1]-np.sin(theta)*coordinates[2]
    z = np.sin(theta)*coordinates[1]+np.cos(theta)*coordinates[2]
    return x,y,z

def Proteinrotator(P1,P2,P3,angle):
    P1_r = plane_rotation(angle,P1)
    P2_r = plane_rotation(angle,P2)
    P3_r = plane_rotation(angle,P3)
    protein = [P1_r,P2_r,P3_r]
    return protein

def bondcalculator(protein,protein_relaxed):
    res = np.zeros([3,3])
    for i, p in enumerate(protein):
        for j, pr in enumerate(protein_relaxed):
            res[i,j] = np.sqrt(np.sum((np.array(p)-pr)**2))
#     print('bond1 : '+str(res[0,0])+'\n')
#     print('bond2 : '+str(res[0,1])+'\n')
#     print('bond3 : '+str(res[0,2])+'\n')
#     print('bond4 : '+str(res[1,0])+'\n')
#     print('bond5 : '+str(res[1,1])+'\n')
#     print('bond6 : '+str(res[1,2])+'\n')
#     print('bond7 : '+str(res[2,0])+'\n')
#     print('bond8 : '+str(res[2,1])+'\n')
#     print('bond9 : '+str(res[2,2])+'\n')
    return res

def packingcalc(sigma,packing): # calculates packing of the cytoplasm
    Sigma = int(math.ceil(sigma))
    if Sigma < 4:
        print("Please change Sigma Value!")
    else:
        sig = np.arange(4,20,1)
        max = [0.56638, 0.5273, 0.4912, 0.435, 0.4296, 0.453, 0.3611, 0.3334, 0.3047, 0.2698, 0.2536,0.2339,0.2092,0.1971,0.1773,0.1584,0.1362]
        for i, item in enumerate(sig):
            if item == Sigma:
                index = i
        max_packing = max[index]
    if (packing > max_packing):
        packing = max_packing
        print("Packing is greater than max! Packing has been set = {0:1.1f}% \n".format(max_packing*100))
        return sigma, packing
    else:
        return sigma, packing

def cytoplasm(packing, cell_radius, actual_cyto_radius):
    x_c = []
    y_c = []
    z_c = []
    x_cyto = []
    y_cyto = []
    z_cyto = []
    s = 600                                                  # length of cytoplasm 'box'
    num_per_row = int(s/(2*actual_cyto_radius))              # number of cyto particles per row
    # initialising a box of cytoplasm particles in centre of cell
    x_adjust = 0                                             # adjustments, making sure the cyto 'box' is in the middle of the cell
    y_adjust = 11 * actual_cyto_radius
    z_adjust = 20 * actual_cyto_radius
    end_of_box = -0.5*s + 0.5 *actual_cyto_radius
    for k in range(num_per_row):
        z_val = end_of_box + z_adjust + actual_cyto_radius * (2 * np.sqrt(6) * k)/3
        for i in range (num_per_row):
            if (i%2 == 0):
                for j in range (num_per_row):
                    x_c.append(end_of_box + x_adjust+ 2 * actual_cyto_radius * j)
                    y_c.append(end_of_box + y_adjust+ np.sqrt(3) * actual_cyto_radius * i)
                    z_c.append(z_val)
            if (i%2 == 1):
                for j in range (num_per_row):
                    x_c.append(end_of_box  + x_adjust+ 2 * actual_cyto_radius * j + actual_cyto_radius)
                    y_c.append(end_of_box  + y_adjust+ np.sqrt(3) * actual_cyto_radius * i)
                    z_c.append(z_val)

    min_radius = cell_radius -  2 * actual_cyto_radius               # making sure cyto doesn't touch membrane
    V_cell = (4/3)*np.pi*cell_radius**3                                # volume of whole cell
    V_cyto = (4/3)*np.pi*actual_cyto_radius**3                                # volume per cyto particle
    num_cyto = packing*V_cell/V_cyto
    m = 0
    n = 0
    while n < num_cyto and m < len(x_c):
        r = np.sqrt (x_c[m] **2 + y_c[m] **2 + z_c[m] **2)
        if r < min_radius:
            x_cyto.append(x_c[m])
            y_cyto.append(y_c[m])
            z_cyto.append(z_c[m])
            n += 1
        m += 1
    actual_packing = len(x_cyto) * V_cyto /V_cell                      # packing of the cytoplasm in the cell
    print("cytoplasm packing =  {0:1.1f}% \n".format(actual_packing*100))
    return x_cyto, y_cyto, z_cyto

def main():

    ################ Parameters ################
    seed = int(sys.argv[6]) # seed
    # filament is made of (particle tripletts = proteins)
    radius = 0.5 						# particle radius
    dr = 0.2     						# overlap length of particles
    radius_o = radius-(dr/2)  					# distance between center of one particle to the middle between two particles
    # each triplett/protein is connected by 9 bonds into filaments
    bondstrength = 600						# bond strength of filament								*******VARY*******
    bondstrength2 = 0						# bond strength is set to zero to account for disassembly events
    # the preferred curvature of a filament is defined by alpha0, a0, and R
    alpha0_input = float(sys.argv[1])
    alpha0 = alpha0_input*np.pi/180				# preferred inner curvature (1-alpha0 is actual curvature) of filament			*******VARY*******
    a0 = 0.37  							# distance between centers of particles is dconst=a0+2radius				*******VARY*******

    R = (radius+a0/2)/np.sin(alpha0/2)				# target ring radius
    print((1-alpha0)/R)
    xstep = 0.01 						# shift distance of helix in cell (pitch)						*******VARY*******
    tau = 0 						# target ring twist
    # simulation parameters
    np.random.seed(421) 					# random seed for permutations
    lbox=math.fabs(100)
    thermo_relax = 1000						# thermo for "run: relax"
    run_relax = 10000						# time duration of "run: relax" -> leads to onset of "run: initial"
    thermo_initial = 1000					# thermo for "run: initial"
    run_initial = 200000					# time duration of "run: initial" -> leads to onset of "run: bonds transform"
    thermo_transform = 1000					# thermo for "run: bonds transform"
    run_transform = int(sys.argv[2])				# time duration of "run: bonds transform" -> leads to onset of "run: bonds disassemble"
    thermo_disassemble = 1000					# thermo for "run: bonds disassemble"
    run_disassemble = int(sys.argv[3])				# time duration of a single "run: bonds disassemble" = time it takes to disassemble a single protein at each end of the filament
    thermo_final = 1000						# thermo for "run: final"
    run_final = 200000						# time duration of "run: final"
    ################ Spherical Membrane ################
    fname_in = 'spherecoords_48002.xyz' 			# read in positions of membrane particles
    f_in = open(fname_in,'rU')
    tmp = f_in.readline()
    tmp = f_in.readline()					#? two times necessary?
    x_membrane = []
    y_membrane = []
    z_membrane = []
    r_membrane = []
    while True:
        tmp = f_in.readline()
        if tmp:
            x_membrane.append(float(tmp.split()[1]))
            y_membrane.append(float(tmp.split()[2]))
            z_membrane.append(float(tmp.split()[3]))
            r_membrane.append(np.sqrt(float(tmp.split()[1])**2+float(tmp.split()[2])**2+float(tmp.split()[2])**2))
        else:							#? shouldn't the last "tmp.split()[2]" be "tmp.split()[3]"?
            break

    cell_radius = np.mean(r_membrane)-1 				# radius of the cell (-1 such that the generated filament definitely is inside the cell)
    print('cell_radius = ' + str(cell_radius) + '\n')
    Nmembrane = len(x_membrane)					# number of membrane particles

    ################    removing the membrane particles within so cytoplasm doesn't overlap  #################
    x_mem = []
    y_mem = []
    z_mem = []
    r_mem = []
    for k in range(Nmembrane):
        r = np.sqrt(x_membrane[k]**2 + y_membrane[k]**2 + z_membrane[k]**2)
        if (r > cell_radius and r < cell_radius + 10):                    # only membrane particles that are on the cell
            x_mem.append(x_membrane[k])
            y_mem.append(y_membrane[k])
            z_mem.append(z_membrane[k])
            r_mem.append(r_membrane[k])

    ################ Generate helical positions ################
    anglestep = 2*np.arcsin((2*radius+a0)/(2*cell_radius))
    bead_per_circ = int(np.floor(2*np.pi/anglestep))		# number of proteins per circulation of cell (a0 is always fixed)
    Ncircles = 2						# number of circulations
    Nprotein = Ncircles*bead_per_circ				# number of proteins per filament

    xstart = Nprotein/2*xstep					#? is it: xstart = Nprotein/(Ncircles*xstep)?
    spiral = []

    for n in range(Nprotein):
        P1,P2,P3 = proteingenerator(radius_o,xstart,xstep,n,cell_radius,tau)
        protein = [P1,P2,P3]
        protein_rot = Proteinrotator(P1,P2,P3,n*anglestep)
        spiral.extend(protein_rot[:3])

    ################ Bond distances ################
    # stiff filament
    [P1,P2,P3] = proteingenerator(radius_o,0,0,0,cell_radius,tau)
    protein = [P1,P2,P3]
    protein_rot = Proteinrotator(P1,P2,P3,anglestep)
    res_s = bondcalculator(protein,protein_rot)

    # elastic filament
    [P1,P2,P3] = proteingenerator(radius_o,0,0,0,R,tau)
    protein = [P1,P2,P3]
    protein_rot = Proteinrotator(P1,P2,P3,alpha0)
    res_e =  bondcalculator(protein,protein_rot)

    ############### cytoplasm particles #################
    sigma_cyto =   int(sys.argv[4])                                              # sigma value of cytoplasm, *VARY* IDEALLY BET 4-15
    desired_packing = int(sys.argv[5])  /100                                         # packing fraction od cyto, *VARY* ideally max 30%
    sigma_cyto, packing = packingcalc(sigma_cyto, desired_packing)               # calculations for packing
    cyto_radius = sigma_cyto  * 1.12/2                                  # radius of cytoplasm particles

    x_cyto, y_cyto, z_cyto = cytoplasm (packing,cell_radius, cyto_radius)      # generates cytoplasm

    ################ Number of particles ################
    Nmem = len(x_mem)					# number of membrane particles
    Ncyto = len(x_cyto)                 # number of cytoplasm particles
    Nspiral = Nprotein*3					# number of particles in filament
    Nbonds = (Nprotein-1)*9					# number of bonds in filament
    Natoms = Nmem+Nspiral +Ncyto					# total number of particles="atoms"
    Nparticletypes = Nspiral+1		+1			# total number of particle types = number of particles in filament + 1 for membrane and cytoplasm
    print('number of membrane particles = ' + str(Nmem) + '\n')
    print('number of filament proteins = ' + str(Nprotein) + '\n')
    print('number of filament particles = ' + str(Nspiral) + '\n')
    print('number of cytoplasm particles = ' + str(Ncyto) + '\n')
    #x_coords = [s[0] for s in spiral]
    #y_coords = [s[1] for s in spiral]
    #plt.scatter(x_coords,y_coords)
    #plt.show()

    ################  Write polyspiral.in ################
    print('writing polyspiral.in\n')
    outfile='polyspiral.in'
    f=open(outfile,'w')
    f.write('LAMMPS data file generated by tc387 with a python script for hex membrane\n')
    f.write('\n')
    f.write(str(Natoms) + '   atoms\n')
    f.write(str(Nbonds) + '   bonds\n')
    f.write('\n')
    f.write(str(Nparticletypes)+' atom types\n')
    f.write(str(Nbonds)+' bond types\n')
    f.write('\n')
    f.write(str(-lbox)+' '+str(lbox)+' xlo xhi \n')
    f.write(str(-lbox)+' '+str(lbox)+' ylo yhi \n')
    f.write(str(-lbox)+' '+str(lbox)+' zlo zhi \n')
    f.write('\n')
    f.write('Masses\n')
    f.write('\n')
    for ii in range(Nparticletypes):
        f.write(str(ii+1) + ' 1\n')
    f.write('\n')
    f.write('Atoms # hybrid\n')
    f.write('\n')

    for ii in range(Nmem):
        # membrane particles
        r = np.sqrt(x_mem[ii]**2+y_mem[ii]**2+z_mem[ii]**2)
        f.write(str(ii+1) + '\t' + '1' + '\t' + str(x_mem[ii]) + '\t' + str(y_mem[ii]) + '\t' + str(z_mem[ii]) + '\t1\t1\t0\t' +   str(x_mem[ii]/r) + '\t' + str(y_mem[ii]/r) + '\t' + str(z_mem[ii]/r) + '\t' + str(ii+1) + '\n')
    for ii in range(Ncyto):
        # cytoplasm particles
        f.write(str(Nmem+ii+1) + '\t' + '2' + '\t' + str(x_cyto[ii]) + '\t' + str(y_cyto[ii]) + '\t' + str(z_cyto[ii]) + '\t1\t1\t0\t0\t0\t0\t' + str(ii+1) + '\n')
    for ii in range(Nprotein):
        # inner particles
        f.write(str(1 +Nmem +Ncyto +ii*3) + '\t' + str(3+3*ii) + '\t' + str(spiral[3*ii][0]) + '\t' + str(spiral[3*ii][1]) + '\t' + str(spiral[3*ii][2]) + '\t1\t1\t0\t0\t0\t0\t' + str(ii+1) + '\n')
        # outer particles
        f.write(str(2 +Nmem +Ncyto +ii*3) + '\t' + str(4+3*ii) + '\t' + str(spiral[3*ii+1][0]) + '\t' + str(spiral[3*ii+1][1]) + '\t' + str(spiral[3*ii+1][2]) + '\t1\t1\t0\t0\t0\t0\t' + str(ii+1) + '\n')
        # upper particles
        f.write(str(3 +Nmem +Ncyto +ii*3) + '\t' + str(5+3*ii) + '\t' + str(spiral[3*ii+2][0]) + '\t' + str(spiral[3*ii+2][1]) + '\t' + str(spiral[3*ii+2][2]) + '\t1\t1\t0\t0\t0\t0\t' + str(ii+1) + '\n')
    f.write('\n')
    f.write('Bonds \n')
    f.write('\n')
    for ii in range(Nprotein-1):
        # bond inner inner
        f.write(str(9*ii+1) + '\t' + str(9*ii+1) + '\t' +  str(1+Nmem +Ncyto +ii*3) + '\t' + str(1+Nmem +Ncyto +(ii+1)*3) + '\n')
        # bond upper outer
        f.write(str(9*ii+2) + '\t' + str(9*ii+2) + '\t' +   str(1+Nmem +Ncyto +ii*3) + '\t' + str(2+Nmem +Ncyto +(ii+1)*3)  + '\n')
         # bond upper inner
        f.write(str(9*ii+3) + '\t' + str(9*ii+3) + '\t' +   str(1+Nmem +Ncyto +ii*3)  + '\t' + str(3+Nmem +Ncyto +(ii+1)*3)  + '\n')
        # bond outer upper
        f.write(str(9*ii+4) + '\t' + str(9*ii+4) + '\t' +  str(2+Nmem +Ncyto +ii*3) + '\t' + str(1+Nmem +Ncyto +(ii+1)*3) + '\n')
        # bond outer outer
        f.write(str(9*ii+5) + '\t' + str(9*ii+5) + '\t' +  str(2+Nmem +Ncyto +ii*3) + '\t' + str(2+Nmem +Ncyto +(ii+1)*3) + '\n')
        # bond outer inner
        f.write(str(9*ii+6) + '\t' + str(9*ii+6) + '\t' +  str(2+Nmem +Ncyto +ii*3) + '\t' + str(3+Nmem +Ncyto +(ii+1)*3) + '\n')
        # bond inner upper
        f.write(str(9*ii+7) + '\t' + str(9*ii+7) + '\t' +  str(3+Nmem +Ncyto +ii*3) + '\t' + str(1+Nmem +Ncyto +(ii+1)*3) + '\n')
        # bond inner outer
        f.write(str(9*ii+8) + '\t' + str(9*ii+8) + '\t' + str(3+Nmem +Ncyto +ii*3) + '\t' + str(2+Nmem +Ncyto +(ii+1)*3) + '\n')
        # bond inner inner
        f.write(str(9*ii+9) + '\t' + str(9*ii+9) + '\t' +  str(3+Nmem +Ncyto +ii*3) + '\t' + str(3+Nmem +Ncyto +(ii+1)*3) + '\n')

    ################ write in.local ################
    print('writing in.local\n')
    infile = 'in.local'
    with open(infile,'rU') as fi:
        data = fi.readlines()
    outfile2='in.local'
    fo=open(outfile2,'w')
    for line in data:

        if len(line.strip().split())>0 and line.strip().split()[0] == 'group' and line.strip().split()[1] == 'spiral':
            fo.write('group\t\tspiral\t\ttype 3:' + str(Nparticletypes) + '\t\t# rigid polymer \n')

        elif len(line.strip().split())>0 and line.strip().split()[0] == '#pw359:':
            fo.write('#pw359: Initialise LJ/expand to zero for all possible combinations \n')
            fo.write('pair_coeff\t*\t*\tlj/cut\t0\t0\n')
            for ii in range(Nprotein):
                fo.write('pair_coeff\t1\t' + str(3*ii+3) + '\tlj/cut\t${eps_ms}\t${sigma_ms}\t${rc_ms}\n')		# attraction membrane and filament bead 3
                fo.write('pair_coeff\t1\t' + str(3*ii+4) + '\tlj/cut\t${eps_ms}\t${sigma_ms}\t${rc_ms}\n')		# attraction membrane and filament bead 4
                fo.write('pair_coeff\t1\t' + str(3*ii+5) + '\tlj/cut\t${eps_mu}\t${sigma_mu}\t${rc_mu}\n')		# volume exclusion membrane and filament bead 5
            for ii in range(Nprotein):
                fo.write('pair_coeff\t2\t' + str(3*ii+3) + '\tlj/cut\t${eps_cyto}\t${sigma_cyto}\t${rc_cyto}\n')		# volume exclusion and filament bead 3
                fo.write('pair_coeff\t2\t' + str(3*ii+4) + '\tlj/cut\t${eps_cyto}\t${sigma_cyto}\t${rc_cyto}\n')		# volume exclusion and filament bead 4
                fo.write('pair_coeff\t2\t' + str(3*ii+5) + '\tlj/cut\t${eps_cyto}\t${sigma_cyto}\t${rc_cyto}\n')		# volume exclusion cytoplasm  and filament bead 5
            fo.write('pair_coeff\t3*\t3*\tlj/cut\t${eps_ss}\t${sigma_ss}\t${rc_ss}\n')					# volume exclusion among filament beads
            fo.write('pair_coeff\t1\t1\tmembrane\t${eps}\t${sigma}\t${rmin}\t${rc}\t${zeta}\t${mu}\t${theta0_11}\n') 	# volume exclusion among membrane beads
            fo.write('pair_coeff\t1\t2\tlj/cut\t${eps_cyto}\t${sigma_cyto}\t${rc_cyto}\n') 	# volume exclusion among membrane and cytoplasm
            fo.write('pair_coeff\t2\t2\tlj/cut\t${eps_cc}\t${sigma_cc}\t${rc_cc}\n') 	# volume exclusion among cytoplasm

        elif len(line.strip().split())>0 and line.strip().split()[0] == '#bonds_initial':
            fo.write('#bonds_initial\n')
            for ii in range(Nprotein-1):
                fo.write('bond_coeff\t' + str(9*ii+1) + '\t' + str(bondstrength) + '\t' + str(res_s[0,0]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+2) + '\t' + str(bondstrength) + '\t' + str(res_s[0,1]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+3) + '\t' + str(bondstrength) + '\t' + str(res_s[0,2]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+4) + '\t' + str(bondstrength) + '\t' + str(res_s[1,0]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+5) + '\t' + str(bondstrength) + '\t' + str(res_s[1,1]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+6) + '\t' + str(bondstrength) + '\t' + str(res_s[1,2]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+7) + '\t' + str(bondstrength) + '\t' + str(res_s[2,0]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+8) + '\t' + str(bondstrength) + '\t' + str(res_s[2,1]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+9) + '\t' + str(bondstrength) + '\t' + str(res_s[2,2]) + '\n' )

        elif len(line.strip().split())>0 and line.strip().split()[0] == '#run_relax':
            fo.write('#run_relax\n')
            fo.write('timestep\t0.01\n')
            fo.write('thermo\t\t' + str(thermo_relax) + '\n')
            fo.write('run\t\t' + str(run_relax) + '\n')

        elif len(line.strip().split())>0 and line.strip().split()[0] == '#run_initial':
            fo.write('#run_initial\n')
            fo.write('timestep\t0.01\n')
            fo.write('thermo\t\t' + str(thermo_initial) + '\n')
            fo.write('run\t\t' + str(run_initial) + '\n')

        elif len(line.strip().split())>0 and line.strip().split()[0] == '#run_bonds_transform':
            fo.write('#run_bonds_transform\n')
            for ii in range(Nprotein-1):
                fo.write('bond_coeff\t' + str(9*ii+1) + '\t' + str(bondstrength) + '\t' + str(res_e[0,0]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+2) + '\t' + str(bondstrength) + '\t' + str(res_e[0,1]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+3) + '\t' + str(bondstrength) + '\t' + str(res_e[0,2]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+4) + '\t' + str(bondstrength) + '\t' + str(res_e[1,0]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+5) + '\t' + str(bondstrength) + '\t' + str(res_e[1,1]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+6) + '\t' + str(bondstrength) + '\t' + str(res_e[1,2]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+7) + '\t' + str(bondstrength) + '\t' + str(res_e[2,0]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+8) + '\t' + str(bondstrength) + '\t' + str(res_e[2,1]) + '\n' )
                fo.write('bond_coeff\t' + str(9*ii+9) + '\t' + str(bondstrength) + '\t' + str(res_e[2,2]) + '\n' )
            fo.write('\n')
            fo.write('timestep\t0.01\n')
            fo.write('thermo\t\t' + str(thermo_transform) + '\n')
            fo.write('run\t\t' + str(run_transform) + '\n')

        elif len(line.strip().split())>0 and line.strip().split()[0] == '#run_bonds_disassemble':
            fo.write('#run_bonds_disassemble\n')
            fil_length = (Nprotein-1)/2
            if fil_length%1==0:
                print('fil_length = ' + str(fil_length) + '\n')
                for cnt in range(int(fil_length)):
                    fo.write('bond_coeff\t' + str(9*cnt+1) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,0]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+2) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,1]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+3) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,2]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+4) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,0]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+5) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,1]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+6) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,2]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+7) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,0]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+8) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,1]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+9) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,2]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+0)) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,0]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+1)) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,1]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+2)) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,2]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+3)) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,0]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+4)) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,1]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+5)) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,2]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+6)) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,0]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+7)) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,1]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+8)) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,2]) + '\n' )
                    fo.write('pair_coeff\t1\t' + str(3*cnt+3) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('pair_coeff\t1\t' + str(3*cnt+4) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('pair_coeff\t1\t' + str(3*cnt+5) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('pair_coeff\t1\t' + str(3*(Nprotein-1)+3-3*cnt) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('pair_coeff\t1\t' + str(3*(Nprotein-1)+4-3*cnt) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('pair_coeff\t1\t' + str(3*(Nprotein-1)+5-3*cnt) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('\n')
                    fo.write('timestep\t0.01\n')
                    fo.write('thermo\t\t' + str(thermo_disassemble) + '\n')
                    fo.write('run\t\t' + str(run_disassemble) + '\n')
                    fo.write('\n')
            else:
                print('fil_length = ' + str(fil_length) + '\n')
                fil_length = fil_length -0.5
                print('new fil_length = ' + str(fil_length) + '\n')
                for cnt in range(int(fil_length)):
                    fo.write('bond_coeff\t' + str(9*cnt+1) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,0]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+2) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,1]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+3) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,2]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+4) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,0]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+5) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,1]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+6) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,2]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+7) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,0]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+8) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,1]) + '\n' )
                    fo.write('bond_coeff\t' + str(9*cnt+9) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,2]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+0)) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,0]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+1)) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,1]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+2)) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,2]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+3)) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,0]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+4)) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,1]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+5)) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,2]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+6)) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,0]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+7)) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,1]) + '\n' )
                    fo.write('bond_coeff\t' + str((Nprotein-1)*9 - (9*cnt+8)) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,2]) + '\n' )
                    fo.write('pair_coeff\t1\t' + str(3*cnt+3) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('pair_coeff\t1\t' + str(3*cnt+4) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('pair_coeff\t1\t' + str(3*cnt+5) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('pair_coeff\t1\t' + str(3*(Nprotein-1)+3-3*cnt) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('pair_coeff\t1\t' + str(3*(Nprotein-1)+4-3*cnt) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('pair_coeff\t1\t' + str(3*(Nprotein-1)+5-3*cnt) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                    fo.write('\n')
                    fo.write('timestep\t0.01\n')
                    fo.write('thermo\t\t' + str(thermo_disassemble) + '\n')
                    fo.write('run\t\t' + str(run_disassemble) + '\n')
                    fo.write('\n')
                cnt = cnt+1
                fo.write('bond_coeff\t' + str(9*cnt+1) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,0]) + ' \n' )
                fo.write('bond_coeff\t' + str(9*cnt+2) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,1]) + ' \n' )
                fo.write('bond_coeff\t' + str(9*cnt+3) + '\t' + str(bondstrength2) + '\t' + str(res_e[0,2]) + ' \n' )
                fo.write('bond_coeff\t' + str(9*cnt+4) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,0]) + ' \n' )
                fo.write('bond_coeff\t' + str(9*cnt+5) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,1]) + ' \n' )
                fo.write('bond_coeff\t' + str(9*cnt+6) + '\t' + str(bondstrength2) + '\t' + str(res_e[1,2]) + ' \n' )
                fo.write('bond_coeff\t' + str(9*cnt+7) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,0]) + ' \n' )
                fo.write('bond_coeff\t' + str(9*cnt+8) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,1]) + ' \n' )
                fo.write('bond_coeff\t' + str(9*cnt+9) + '\t' + str(bondstrength2) + '\t' + str(res_e[2,2]) + ' \n' )
                fo.write('pair_coeff\t1\t' + str(3*cnt+3) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                fo.write('pair_coeff\t1\t' + str(3*cnt+4) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                fo.write('pair_coeff\t1\t' + str(3*cnt+5) + '\t lj/cut \t ${eps_mu} \t ${sigma_mu} \t ${rc_mu} \n' )
                fo.write('\n')

        elif len(line.strip().split())>0 and line.strip().split()[0] == '#run_final':
            fo.write('#run_final\n')
            fo.write('timestep\t0.01\n')
            fo.write('thermo\t\t' + str(thermo_final) + '\n')
            fo.write('run\t\t' + str(run_final) + '\n')

        elif len(line.strip().split())>0 and line.strip().split()[0] == '#integrators':
            fo.write('fix\t\tfLANG all langevin 1.0 1.0 1 ' + str(seed) + ' zero yes omega yes\n')
            fo.write('fix\t\tfNVE\tmem\tnve/sphere update dipole\n')
            fo.write('fix\t\tfNVE2\tcyto\tnve/sphere update dipole\n')

        elif len(line.strip().split())>0 and line.strip().split()[0] == 'bond_coeff':
            print('skip')

        elif len(line.strip().split())>0 and line.strip().split()[0] == 'pair_coeff':
            print('skip')

        elif len(line.strip().split())>0 and line.strip().split()[0] == 'timestep':
            print('skip')

        elif len(line.strip().split())>0 and line.strip().split()[0] == 'thermo':
            print('skip')

        elif len(line.strip().split())>0 and line.strip().split()[0] == 'run':
            print('skip')

        else:
            fo.write(line)

    fo.close()

if __name__ == "__main__":
    main()


import json

def error(request, text, http_code=None):

	if http_code is not None:
		request.setResponseCode(http_code)

		if http_code == 401:
			request.setHeader('WWW-Authenticate', 'None')

	response = { 'error' : text }
	return json.dumps(response)

def success():
	return '{ "success" : 1 }'


import os, sys, time
import shlex, subprocess
from pathlib import Path
file_path = Path(__file__).resolve()      # Find out where this directory is to use to run programs
sys.path.insert(0, str(file_path.parents[1])) # Adding tollrunner package path to not have to install it right now
from toolrunner.native.nativeprocessmanager import NativeProcess as np

# Setting up program to execute and script to execute
plugin_program_path = Path(sys.executable)                    # We would already know where the plugin program is at
script_path = file_path.parents[0] / 'hello_long.py'     # The user would give us the path to his script e.g. peach pit

# Setting up different parameters for the same program
short_running_process_args = '-s Hello_short -t 20 -z 0 -f True'   # The user would give us this through GUI
long_running_process_args = ' -s Hello_long -t 60 -z 1 -f True'   # The user would give us this through GUI

# Preparing command  to a list
list_command = np.command_str_list(short_running_process_args)
list_command.insert(0, str(plugin_program_path))
list_command.insert(1, str(script_path))

# Test 1
popen_process = subprocess.Popen(list_command)
print(popen_process.pid)
# print(popen_process.args)
status = None
while status == None:
    status = popen_process.poll()
    if status == None:
        print("Not Yet")
        # Hasn't finished, do other stuff while process is running
        time.sleep(5)
print("-------------ITS DONE___________")
# print(status)
# list_new_command = command_str_list(new_command)
# print(list_new_command)

# Test2
# process = np()
# process.set_command(program=plugin_program_path, script=script_path, args=long_running_process_args)
# process.run()
# process.wait(10)
# process.print_output()

# Test 3
print("$$$$$$$$$$$$test3$$$$$$$$$$$$$")
new_command = str(plugin_program_path) + " " + str(script_path) + " " + short_running_process_args
print(new_command)
list_new = np.command_str_list(new_command)
print(list_new)