from aliasblock import *

def myround(x, base): return int(base * round(float(x)/base))

def getglobalgrid(pinpitch,asspitch,gridsperpin=4.0):
  idealgridsize = pinpitch/gridsperpin
  grids = myround(asspitch/idealgridsize, gridsperpin)
  return ' {0} {0} '.format(grids,grids)

def getnewtcylinders(ids,radii):
  textout = ''
  for i in range(0,len(ids)):
    textout += '  cylinder {0} {1} \n'.format(ids[i], radii[i])
  return textout

def getk6cylinders(ids,radii,zlen):
  textout = ''
  for i in range(0,len(ids)):
    textout += '  cylinder {0} {1}  {2} {3} \n'.format(ids[i], radii[i],zlen,0.0)
  return textout

def getmedia(cylids,mats):
  textout = ''
  for i in range(0,len(cylids)):
    if i == 0:
      textout += '  media {0} 1  {1} \n'.format(mats[i],cylids[i])
    else:
      textout += '  media {0} 1 -{1} {2} \n'.format(mats[i],cylids[i-1],cylids[i])
  return textout

def diagonals(latsize):
  thisnum = -1
  diags = []
  for i in range(1,10+1):
    thisnum += i
    diags.append(thisnum)
  return diags

def getallpins(pins,seq,geom='2d',zlen=None):
  allpinstext = ''
  for id in pins:
    thisunit = 'unit ' + str(id) + ' \n'
    cylinderids = range(1,len(pins[id][0]))
    radii, mats = pins[id][0][0:-1], pins[id][1][0:-1]
    boundary = '  boundary  {0} \n'.format(cylinderids[-1])
    if geom == '2d':
      allpinstext += thisunit + getnewtcylinders(cylinderids,radii) + getmedia(cylinderids,mats) + boundary
    elif geom == '3d':
      allpinstext += thisunit + getk6cylinders(cylinderids,radii,zlen) + getmedia(cylinderids,mats) + boundary
  return allpinstext

def getpinids(arrtype):
  pinids=[]
  for i in range(0,arrtype):
    firstid=10+i
    for j in range(0,i+1): pinids.append(firstid+j*10)
  return pinids

def arrsize(array):
  return int(((1+8*len(array))**(0.5)-1)/2)

def getholespos(array,pitch):
  latsize = arrsize(array)
  if latsize%2 == 0: posmult = [x+0.5 for x in range(-latsize/2,latsize/2)]
  elif latsize%2 == 1: posmult = range(-(latsize/2),latsize/2+1)
  xposs = [x*pitch for x in posmult]
  yposs = [x*-1*pitch for x in posmult]
  xyposmult = [[[i,j] for i in xposs] for j in yposs]
  return xyposmult

def getfullarray(array):
  size = arrsize(array)
  pinids = getpinids(size)
  blankarr = [[1 for i in range(0,size)] for j in range(0,size)]
  for i in range(0,len(pinids)):
    if len(list(str(pinids[i]))) < 3:
      yindex = int(list(str(pinids[i]))[0])-1
      xindex = int(list(str(pinids[i]))[1])
    else:
      yindex = int(list(str(pinids[i]))[0]+list(str(pinids[i]))[1])-1
      xindex = int(list(str(pinids[i]))[2])
    blankarr[yindex][xindex] = array[i]
    blankarr[xindex][yindex] = array[i]
  return blankarr

def getholetext(fulllat,pinpos,allpins,offset):
  holetext = ''
  for i in range(0,len(fulllat[0])):
    for j in range(0,len(fulllat)):
      if len(all_indices(fulllat[i][j],allpins.keys())) != 0:
        if fulllat[i][j] != 0: holetext += "  hole {0}  origin x={1:>8.4f}  y={2:>8.4f} \n".format(fulllat[i][j],pinpos[i][j][0]+offset,pinpos[i][j][1]-offset)
  return holetext

def getpns(aliases):
  pns=[]
  for alias in aliases:
    if alias.find('gap') != -1:
      pns.append(0)
    elif alias.find('mod') != -1:
      pns.append(2)
    else:
      pns.append(1)
  return pns

def getcoms(aliases):
  coms=[]
  for alias in aliases:
    if alias.find('$f') != -1:
      enrgd = alias.replace('$f','').split('gd')
      if len(enrgd) > 1:
        coms.append('{0}% enr, {1}wt% Gd2O3 fuel'.format(float(enrgd[0])/100.0,float(enrgd[1])/10.0))
      else:
        coms.append('{0}% enr fuel'.format(float(enrgd[0])/100.0))
    elif alias.find('$1f') != -1:
      enrgd = alias.replace('$1f','').split('gd')
      if len(enrgd) > 1:
        coms.append('One {0}% enr, {1}wt% Gd2O3 fuel'.format(float(enrgd[0])/100.0,float(enrgd[1])/10.0))
      else:
        coms.append('One {0}% enr fuel'.format(float(enrgd[0])/100.0))
    else:
      coms.append(alias.replace('$',''))
  return coms

def getnewtmaterials(aliases,seq):
  aliasnames = [ part[0].split()[0] for part in aliases ]
  pns = getpns(aliasnames)
#  coms = getcoms(aliasnames)
  materialstext = 'read materials \n'
  for i in range(0,len(aliasnames)):
    if seq == 'tnewt':
      if aliasnames[i].find('$f') == -1:
        materialstext += "  mix={0:<12}  pn={1}  com='{2}'  end\n".format(aliasnames[i], pns[i], aliasnames[i].replace('$',''))
    elif seq == 'tdepl':
      if aliasnames[i].find('$1f') == -1:
        materialstext += "  mix={0:<12}  pn={1}  com='{2}'  end\n".format(aliasnames[i], pns[i], aliasnames[i].replace('$',''))
  materialstext += 'end materials \n'
  return materialstext

def offsetgeom(file,offset):
  f = file
  for i in range(0,len(f)):
    if f[i].find('<pos>') != -1 or f[i].find('<mos>') != -1:
      thisline = f[i].split(' ')
      for j in range(0,len(thisline)):
        if thisline[j].find('<pos>') != -1:
          thisline[j-1] = '{0}'.format(float(thisline[j-1]) + offset)
          thisline[j] = ''
        if thisline[j].find('<mos>') != -1:
          thisline[j-1] = '{0}'.format(float(thisline[j-1]) - offset)
          thisline[j] = ''
      thispart = '' + ' '.join(thisline) + '\n'
      f[i] = thispart.replace('\n\n','\n')
#      f[i] = '  ' + ' '.join(thisline) + '\n'
  return f

def makechangeom(file,apitch, wchan, tchan, ricorner, tcorner, wcutout):
  dims = {}
  wcutoutmod = wcutout
  if wcutout == 0: wcutoutmod = tcorner*0.5
  dims['ricorner']   = ricorner
  dims['rocorner']   = ricorner + tcorner
  dims['boxcorner']  = (ricorner + tcorner)*1.05
  if wcutout == 0:
    dims['hwcutout']   = (tcorner*0.5)/2.0
    dims['tcutout']    = tcorner
  else:
    dims['hwcutout']   = wcutout/2.0
    dims['tcutout']    = tcorner - tchan
  dims['hwichan']    = wchan/2.0
  dims['hwochan']    = dims['hwichan'] + tcorner
  dims['hwassem']    = apitch/2.0
  dims['cornorig']    = dims['hwichan'] - ricorner
  dims['cutoutorig'] = dims['hwochan']
  dims['cornboxedge'] = dims['cornorig'] + dims['rocorner']*1.05
  for i in range(0,len(file)):
    for key in dims:
      file[i] = file[i].replace('<' + key + '>',str(dims[key]))
    if wcutout == 0: file[i] = file[i].replace("  hole 999","'  hole 999")
  return file

def getotherpins(otherpins,offset,zlen=None):
  counter,unitnum,surfstart = 0, 1000, 10
  holesnums = {}
  otherpintext = ''
  pinnumloc = {}
  for key in otherpins:
    unitnum += 1
    thisunit = 'unit ' + str(unitnum) + ' \n'
    cylinderids = range(1,len(otherpins[key][0])+1)
    radii, mats = otherpins[key][0], otherpins[key][1]
    boundary = '  boundary  {0} \n'.format(cylinderids[-1])
    if zlen==None:
      otherpintext += thisunit + getnewtcylinders(cylinderids,radii) + getmedia(cylinderids,mats) + boundary
    else:
      otherpintext += thisunit + getk6cylinders(cylinderids,radii,zlen) + getmedia(cylinderids,mats) + boundary
    pinnumloc[unitnum] = [otherpins[key][2][0] + offset, otherpins[key][2][1] - offset]
  return otherpintext,pinnumloc

def getotherpinholes(otherholes):
  otherholetext = ''
  for hole in otherholes:
    otherholetext += '  hole {0} origin x= {1} y= {2} \n'.format(hole,otherholes[hole][0],otherholes[hole][1])
  return otherholetext

def getnewtcorns():
  cornersurfs =  '  cylinder  6 <ricorner>  <zdims>   chord +x= <cornorig> <pos> chord +y= <cornorig> <mos>  origin x=  <cornorig> <pos>  y=  <cornorig> <mos> \n'
  cornersurfs += '  cylinder  7 <rocorner>  <zdims>   chord +x= <cornorig> <pos> chord +y= <cornorig> <mos>  origin x=  <cornorig> <pos>  y=  <cornorig> <mos> \n'
  cornersurfs += '  cuboid    8 <cornboxedge> <pos> <cornorig> <pos>  <cornboxedge> <mos> <cornorig> <mos>  <zdims> \n'
  cornersurfs += '  cylinder  9 <ricorner>  <zdims>   chord -x= -<cornorig> <pos> chord +y= <cornorig> <mos>  origin x= -<cornorig> <pos>  y=  <cornorig> <mos> \n'
  cornersurfs += '  cylinder 10 <rocorner>  <zdims>   chord -x= -<cornorig> <pos> chord +y= <cornorig> <mos>  origin x= -<cornorig> <pos>  y=  <cornorig> <mos> \n'
  cornersurfs += '  cuboid   11 -<cornorig> <pos> -<cornboxedge> <pos> <cornboxedge> <mos> <cornorig> <mos>  <zdims> \n'
  cornersurfs += '  cylinder 12 <ricorner>  <zdims>   chord -x= -<cornorig> <pos> chord -y= -<cornorig> <mos>  origin x= -<cornorig> <pos>  y= -<cornorig> <mos> \n'
  cornersurfs += '  cylinder 13 <rocorner>  <zdims>   chord -x= -<cornorig> <pos> chord -y= -<cornorig> <mos>  origin x= -<cornorig> <pos>  y= -<cornorig> <mos> \n'
  cornersurfs += '  cuboid   14 -<cornorig> <pos> -<cornboxedge> <pos> -<cornorig> <mos> -<cornboxedge> <mos>  <zdims> \n'
  cornersurfs += '  cylinder 15 <ricorner>  <zdims>   chord +x=  <cornorig> <pos> chord -y= -<cornorig> <mos>  origin x=  <cornorig> <pos>  y= -<cornorig> <mos> \n'
  cornersurfs += '  cylinder 16 <rocorner>  <zdims>   chord +x=  <cornorig> <pos> chord -y= -<cornorig> <mos>  origin x=  <cornorig> <pos>  y= -<cornorig> <mos> \n'
  cornersurfs += '  cuboid   17 <cornboxedge> <pos> <cornorig> <pos>  -<cornorig> <mos> -<cornboxedge> <mos>  <zdims> \n'
  return cornersurfs

def getkenocorns():
  cornersurfs =  '  cylinder  6 <ricorner>  <zdims>   origin x=  <cornorig> <pos>  y=  <cornorig> <mos> \n'
  cornersurfs += '  cylinder  7 <rocorner>  <zdims>   origin x=  <cornorig> <pos>  y=  <cornorig> <mos> \n'
  cornersurfs += '  cuboid    8 <cornboxedge> <pos> <cornorig> <pos>  <cornboxedge> <mos> <cornorig> <mos>  <zdims> \n'
  cornersurfs += '  cylinder  9 <ricorner>  <zdims>   origin x= -<cornorig> <pos>  y=  <cornorig> <mos> \n'
  cornersurfs += '  cylinder 10 <rocorner>  <zdims>   origin x= -<cornorig> <pos>  y=  <cornorig> <mos> \n'
  cornersurfs += '  cuboid   11 -<cornorig> <pos> -<cornboxedge> <pos> <cornboxedge> <mos> <cornorig> <mos>  <zdims> \n'
  cornersurfs += '  cylinder 12 <ricorner>  <zdims>   origin x= -<cornorig> <pos>  y= -<cornorig> <mos> \n'
  cornersurfs += '  cylinder 13 <rocorner>  <zdims>   origin x= -<cornorig> <pos>  y= -<cornorig> <mos> \n'
  cornersurfs += '  cuboid   14 -<cornorig> <pos> -<cornboxedge> <pos> -<cornorig> <mos> -<cornboxedge> <mos>  <zdims> \n'
  cornersurfs += '  cylinder 15 <ricorner>  <zdims>   origin x=  <cornorig> <pos>  y= -<cornorig> <mos> \n'
  cornersurfs += '  cylinder 16 <rocorner>  <zdims>   origin x=  <cornorig> <pos>  y= -<cornorig> <mos> \n'
  cornersurfs += '  cuboid   17 <cornboxedge> <pos> <cornorig> <pos>  -<cornorig> <mos> -<cornboxedge> <mos>  <zdims> \n'
  return cornersurfs

def getkeno2dplot(assempitch,zlen):
  rtntext = 'read plot \n'
  rtntext += "  ttl='z={0} cm' \n".format(zlen/2.0)
  rtntext += '  TYP=XY \n'
  rtntext += '  XUL=-{0} YUL={0}  ZUL={1} \n'.format(assempitch/2.0 + assempitch*0.02,zlen/2.0)
  rtntext += '  XLR={0}  YLR=-{0} ZLR={1} \n'.format(assempitch/2.0 + assempitch*0.02,zlen/2.0)
  rtntext += '  NAX=2560 end \n'
  rtntext += 'end plot'
  return rtntext

class modelblockclass:
  def __init__(self, fuellat, fuelpins, mats, pinpitch, offset, otherpins, aliases=[], geom='basic',seq='tnewt',zlen=None):

    allpins = {}
    if seq == 'tdepl' or seq == 't6depl':
      for key in fuelpins:
        for index in fuelpins[key]['latindices']:
          allpins[index] = [fuelpins[key]['newtdims'] + [pinpitch], [ str(x) for x in fuelpins[key]['deplpins'][index] + fuelpins[key]['newt1fmats'][-3:]]]
    else:
      for key in fuelpins:
        allpins[key] = [fuelpins[key]['newtdims'] + [pinpitch], [str(x) for x in fuelpins[key]['newt1fmats']]]

    fulllat = getfullarray(fuellat)
    holepos = getholespos(fuellat,pinpitch)

    self.holetext = getholetext(fulllat,holepos,allpins,offset)
    self.allnewtpinstext = getallpins(allpins,seq,geom='2d')
    self.allk6pinstext = getallpins(allpins,seq,geom='3d',zlen=zlen)
    self.newtmaterials = getnewtmaterials(aliases,seq)
    self.otherpinstext = getotherpins(otherpins,offset,zlen)[0]
    self.otherpinholes = getotherpinholes( getotherpins(otherpins,offset)[1] )
    self.newtcornsurfs = getnewtcorns()
    self.kenocornsurfs = getkenocorns()


from genmesh import genmesh
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# msh_file = 'mesh/3d_sphere_unit.msh'
msh_file = 'mesh/3d_sphere_forloop_big.msh'
mesh = genmesh(P_bdry=None, meshsize=None, msh_file =msh_file, dimension=3, mesh_optimize=True)

# mesh.plot(plot_node_text=False, highlight_bdry_nodes=False, dotsize=20)

fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
ax = Axes3D(fig)
Pos = mesh.pos
plt.scatter(Pos[:,0], Pos[:,1], Pos[:,2])
plt.show()


import maya.cmds as cmds
from functools import partial

#quick UI
def ipMoverUI():
    if (cmds.window('zbw_ipMoverUI', exists=True)):
        cmds.deleteUI('zbw_ipMoverUI', window=True)
        cmds.windowPref('zbw_ipMoverUI', remove=True)
    window=cmds.window('zbw_ipMoverUI', widthHeight=(400,200), title='zbw_imagePlane')
    cmds.columnLayout('zbw_ipmMainColumn')

    cam = cmds.ls(sl=True,dag=True,s=True, type="camera")
    if cam:
        ip = cmds.listConnections(cam[0], type="imagePlane")
        if ip:
            imagePlane = ip[0]
            ipText = imagePlane
        else:
            cmds.warning("there's no image plane on this camera")
            ipText = "no image plane"
    else:
        cmds.warning("select a camera")
        ipText = "no image plane"

    cmds.text(ipText)
    cmds.separator(h=20, style="double")

    if cam and ip:

        #---------------store original values somewhere . . .

        cmds.floatSliderGrp("alphaFSG", label='alpha',cal = [1,"left"], cw3=[50, 50, 300],width=400, field=True, minValue=0, maxValue=1, fieldMinValue=0, fieldMaxValue=1, value=1, pre=3, dc=partial(changeValue, (imagePlane + ".alphaGain"), "alphaFSG"))

        cmds.separator(h=20, style = "double")

        cmds.floatSliderGrp("centerXFSG", label='centerX',cal = [1,"left"], cw3=[50, 50, 300],width=400, field=True, minValue=-20.0, maxValue=20.0, fieldMinValue=-100.0, fieldMaxValue=100.0, value=0, pre=3, dc=partial(changeValue, (imagePlane + ".centerX"), "centerXFSG"))

        cmds.floatSliderGrp("centerYFSG", label='centerY',cal = [1,"left"], cw3=[50, 50, 300],width=400, field=True, minValue=-20.0, maxValue=20.0, fieldMinValue=-100.0, fieldMaxValue=100.0, value=0, pre=3, dc=partial(changeValue, (imagePlane + ".centerY"), "centerYFSG"))

        cmds.floatSliderGrp("centerZFSG", label='centerZ',cal = [1,"left"], cw3=[50, 50, 300],width=400, field=True, minValue=-20.0, maxValue=20.0, fieldMinValue=-100.0, fieldMaxValue=100.0, value=0, pre=3, dc=partial(changeValue, (imagePlane + ".centerZ"), "centerZFSG"))

        cmds.floatSliderGrp("widthFSG", label='width',cal = [1,"left"], cw3=[50, 50, 300],width=400, field=True, minValue=0, maxValue=20.0, fieldMinValue=0, fieldMaxValue=100.0, pre=3, dc=partial(changeValue, (imagePlane + ".width"), "widthFSG"))

        cmds.floatSliderGrp("heightFSG", label='height',cal = [1,"left"], cw3=[50, 50, 300],width=400, field=True, minValue=0, maxValue=20.0, fieldMinValue=0, fieldMaxValue=100.0, pre=3, dc=partial(changeValue, (imagePlane + ".height"), "heightFSG"))

    cmds.showWindow(window)

    cmds.window('zbw_ipMoverUI', e=True, w=400, h=200)

def changeValue(attr, slider, *args):

    value = cmds.floatSliderGrp(slider, q=True, v=True)
    cmds.setAttr(attr, value)

# def focusToCamera():

    #get camera from focus window
    # panel = cmds.getPanel(wf=True)
    # cam = cmds.modelEditor(panel, q=True, camera=True)

#----------get camera from focus . . .
#----------have camera list to select from . . .

# (coverageX)
# (coverageY)

def zbw_ipMover():
    ipMoverUI()


import json

from django.http import JsonResponse
from django.shortcuts import render

from .ResponseFood import ResponseFood
from .sampleData import addData
import calories.managers as manager
from calories.services.dateConvertion import *
from calories.services.translation import translate_polish_to_english, translate_english_to_polish
from calories.services.textCoversion import upper_first_letter
from calories.services.wolfram import get_food_data_from_wolfram
from calories.services.weeklyMath import *

__DEFAULT_USER = 'default@user'

# Create your views here.

def main_view(request):
    today = datetime.date.today()
    user = manager.get_user(__DEFAULT_USER)
    return render(request, "index.html", {"prev_date": date_to_string(yesterday(today)),
                                          "act_date": date_to_string(today),
                                          "next_date": date_to_string(tommorow(today)),
                                          "food_list": manager.get_all_foods_from_day_with_count(today),
                                          "user_lang": user.lang,
                                          }
                  )

def sample_data(request):
    addData.add_sample_data()
    return render(request, "sampleData.html", {})

def user_settings_view(request):
    user = manager.get_user(__DEFAULT_USER)
    return render(request, "userSettings.html", {'user': user,
                                                 'user_lang': user.lang})

def weekly_view(request):
    return render(request, "weekly.html", {'user_lang': manager.get_user(__DEFAULT_USER).lang,
                                           'act_week_first': date_list_to_string_list(get_week(datetime.date.today()))[0],
                                           'act_week_last': date_list_to_string_list(get_week(datetime.date.today()))[-1]})

def update_user_settings(request):
    if request.is_ajax and request.method == "POST":
        data = request.POST.dict()

        manager.change_user(__DEFAULT_USER,
                            float(data['calories']),
                            float(data['fat']),
                            float(data['carbohydrates']),
                            float(data['protein']),
                            float(data['height']),
                            float(data['weight']),
                            data['sex'],
                            data['lang'])

        return JsonResponse({}, status=200)

def get_day_food_list(request):
    if request.is_ajax and request.method == "POST":
        data = request.POST.dict()
        this_day = string_to_date(data['date'])

        my_response = []
        for food, unit in manager.get_all_foods_from_day_with_count(this_day):
            my_response.append(ResponseFood(food, unit))

        json_string = json.dumps([ob.__dict__ for ob in my_response])

        return JsonResponse({"food_list": json_string,
                             "prev_date": date_to_string(yesterday(this_day)),
                             "act_date": date_to_string(this_day),
                             "next_date": date_to_string(tommorow(this_day))}, status=200)

def get_food_list(request):
    if request.is_ajax and request.method == "POST":
        json_string = json.dumps([ResponseFood(ob, 0).__dict__ for ob in manager.get_all_foods()])

        return JsonResponse({"food_list": json_string}, status=200)

def add_food_to_day(request):
    if request.is_ajax and request.method == "POST":
        data = request.POST.dict()
        lang = data['lang']
        food_name = data['food_name']
        count = float(data['count'])
        date = string_to_date(data['date'])

        if lang == "pl":
            food_name = translate_polish_to_english(food_name)

        food_name = upper_first_letter(food_name)
        manager.add_food_to_day(manager.get_day(date),
                                manager.get_food(food_name),
                                count)

        return JsonResponse({}, status=200)

def get_food(request):
    if request.is_ajax and request.method == "POST":
        data = request.POST.dict()
        lang = data['lang']
        food_name = data['food_name']

        if lang == "pl":
            food_name = translate_polish_to_english(food_name)

        json_string = json.dumps(ResponseFood(manager.get_food(food_name), 0).__dict__)
        return JsonResponse({"food": json_string}, status=200)

def add_manual_food_to_day(request):
    if request.is_ajax and request.method == "POST":
        data = request.POST.dict()

        lang = data['lang']
        date = string_to_date(data['date'])
        food_name = data['food_name']

        if lang == "pl":
            food_name_pl = upper_first_letter(food_name)
            food_name = upper_first_letter(translate_polish_to_english(food_name))
        else:
            food_name_pl = upper_first_letter(translate_english_to_polish(food_name))
            food_name = upper_first_letter(food_name)

        new_food = manager.add_or_change_food(food_name,
                                              food_name_pl,
                                              data['food_unit'],
                                              float(data['food_calories']),
                                              float(data['food_fat']),
                                              float(data['food_carbohydrates']),
                                              float(data['food_protein']))

        manager.add_food_to_day(manager.get_day(date), new_food, float(data['food_count']))

        return JsonResponse({}, status=200)

def add_wolfram_food_to_day(request):
    if request.is_ajax and request.method == "POST":
        data = request.POST.dict()

        lang = data['lang']
        date = string_to_date(data['date'])
        food_name = data['food_name']
        food_unit = data['food_unit']
        if food_unit == '/ 100g' or food_unit == 'x 100g':
            food_unit = "g"

        if lang == "pl":
            food_name_pl = upper_first_letter(food_name)
            food_name = upper_first_letter(translate_polish_to_english(food_name))
        else:
            food_name_pl = upper_first_letter(translate_english_to_polish(food_name))
            food_name = upper_first_letter(food_name)

        new_food = get_food_data_from_wolfram(food_name, food_unit)
        new_food.name_pl = food_name_pl
        manager.save_food(new_food)

        manager.add_food_to_day(manager.get_day(date), new_food, float(data['food_count']))
        return JsonResponse({}, status=200)

def get_weekly_summary(request):
    if request.is_ajax and request.method == "POST":
        data = request.POST.dict()
        date = string_to_date(data['date'])

        return JsonResponse({"prev_week": date_list_to_string_list(get_prev_week(date)),
                             "act_week": date_list_to_string_list(get_week(date)),
                             "next_week": date_list_to_string_list(get_next_week(date)),
                             "daily_list": get_weekly_nutrition_json(get_week(date)),
                             "popular_foods": get_most_popular_foods_json(get_week(date))},
                            status=200)


import cv2
import numpy as np
from goprocam import GoProCamera
from goprocam import constants
cascPath="/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
gpCam = GoProCamera.GoPro()
#gpCam.gpControlSet(constants.Stream.BIT_RATE, constants.Stream.BitRate.B2_4Mbps)
#gpCam.gpControlSet(constants.Stream.WINDOW_SIZE, constants.Stream.WindowSize.W480)
cap = cv2.VideoCapture("udp://127.0.0.1:10000")
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.CASCADE_SCALE_IMAGE
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
    # Display the resulting frame
    cv2.imshow("GoPro OpenCV", frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything is done, release the capture
cap.release()
cv2.destroyAllWindows()


def notları_hesapla(satır):
    toplam=0
    satır=satır[:-1]
    print(satır)
    liste=satır.split(":")
    ogreciadi=liste[0]
    notlar=liste[1]
    listes=notlar.split(",")
    print(listes)
    for i in listes:
        toplam=toplam+int(i)
    ortalama=toplam/3
    if(ortalama>=90):
        harf="AA"
    elif(ortalama>=85 and ortalama<=89):
        harf="BA"
    elif(ortalama>=65):
        harf="CC"
    else:
        harf="FF"
    return ogreciadi+": "+str(ortalama) +"harf sistemindeki karşılıgı: "+str(harf)

def ortalama_oku():
    with open("sınavnotları.txt","r",encoding="utf-8") as find:
        for satir in find:
            print(notları_hesapla(satir))
def not_gir():
    ad=input("adınızı giriniz:")
    soyad= input("soyadınızı giriniz: ")
    not1=input("not 1:")
    not2=input("not 2:")
    not3=input("not 3:")
    with open("sınavnotları.txt","a",encoding="utf-8") as find:
        find.write(ad+" "+soyad +" notlar:"+not1+","+not2+","+not3+"\n")

def not_kaydet():
    with open("sınavnotları.txt","r",encoding="utf-8") as find:
        list=[]
        for satir in find:
            list.append(notları_hesapla(satir))
        with open("sınavkayıt.txt","w",encoding="utf-8") as finds:
            print(list)
            for i in list:
                finds.write(str(i)+"\n")
    with open("sınavnotları.txt","r",encoding="utf-8") as find:
        print(find.read())

while( True):
    print("1- oratalama oku\n2- not gir\n3-notları kaydet\n4-çıkış")
    islem =input()
    if ("1"==islem):
        ortalama_oku()
    elif("2"== islem):
        not_gir()
    elif("3"== islem):
        not_kaydet()
    elif("4"==islem):
        break
    else:
        print("yanlış deger girdiniz")
        break


from django.conf.urls import url
from django.views.generic.edit import CreateView
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import views as auth_views

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^favicon\.ico$', views.favico, name='favico'),
    url(r'^authors/(?P<letter>[a-zA-Z]+)/$', views.authors_index, name='authors'),
    url(r'^publications/$', views.pub_index, name='publications'),
    url(r'^publications/new$', views.pub_add, name='publication_add'),
    url(r'^authors/(?P<author_id>[0-9]+)/$', views.author_detail, name='author_detail'),
    url(r'^publications/(?P<pub_id>[0-9]+)/$', views.publication_detail, name='publication_detail'),
    url(r'^register/$', views.register, name='register'),
    url(r'^author_create/$', views.author_create, name='author_create'),
    url(r'^pub_create/$', views.pub_create, name='pub_create'),
    url(r'^login/$', auth_views.login, {'template_name':'pubman/login.html'}),
]


from __future__ import annotations

from pygame.sprite import Sprite
from pygame.transform import scale
from IO_XmlHandler import IO_XmlHandler
from IO_Texture import IO_Texture, IO_TextureManager
from IO_Object import IO_Entity, IO_Object
import pygame

class IO_Animation(IO_Object):
    def __init__(self,
                id : str,
                frameCount : int,
                repeat : bool = True,
                isEnded : bool = False,
                pause : bool = False,
                speed=100,
                scale = None,
                roatation = None,
                flip = None):
        """
        @member repeat conttollers wheter animation repeats after cycle\n
        @member isEnded checks if animation is ended\n
        @member pause pauses animation\n
        @member frame current frame\n
        """
        super().__init__()
        self.id = id
        self.repeat = repeat
        self.isEnded = isEnded
        self.pause = pause
        self.currentFrame = 0
        self.speed = speed
        self.frameCount = frameCount
        self.scale = scale
        self.roatation = roatation
        self.flip = flip

    def update(self,dt : float =0,scrollRatio : float = 0):
        raise NotImplementedError()

    def render(self,x,y):
        raise NotImplementedError()

    def setAttrib(self,
                frameCount : int = None,
                repeat : bool = None,
                isEnded : bool  = None,
                pause : bool = None,
                currentFrame : int  = None,
                speed= None,
                scale = None,
                rotation = None,
                flip = None):

        if (repeat != None): self.repeat = repeat
        if (isEnded != None): self.isEnded = isEnded
        if (pause != None): self.pause = pause
        if (currentFrame != None): self.currentFrame = currentFrame
        if (speed != None): self.speed = speed
        if (frameCount != None): self.frameCount = frameCount
        if (scale != None): self.scale = scale
        if (rotation != None): self.roatation = rotation
        if (flip != None): self.flip = flip

    def __iter__(self):
        yield 'class', self.__class__
        yield 'repeat', self.repeat
        yield 'pause', self.pause
        yield 'isEnded', self.isEnded
        yield 'currentFrame', self.currentFrame
        yield 'speed',self.speed
        yield 'frameCount' , self.frameCount

class IO_SpriteAnimation(IO_Animation):
    def __init__(self,
                texture :IO_Texture,
                id : str,
                frameArea : tuple[int,int],
                row : int,
                frameCount : int,
                repeat : bool = True,
                isEnded : bool = False,
                pause : bool = False,
                speed=100,
                scale = None,
                rotation = None,
                flip = None):
        """

        """
        super().__init__(id,frameCount,repeat,isEnded,pause,speed,scale,rotation,flip)

        self.row = row
        self.frameArea = frameArea
        self.texture : IO_Texture = texture
        self.texture.transform(scale,rotation,flip)

    def update(self, dt : float = 0):
        """
        update current frame
        """
        #ondDlength = self.frameCount * self.rowCount
        ondDlength = self.frameCount

        if (self.repeat or self.isEnded == False) and self.pause == False:
            self.isEnded = False
            self.currentFrame = int((pygame.time.get_ticks()/self.speed)% ondDlength)

        if self.repeat == False and self.currentFrame == ondDlength -1:
            self.isEnded = True
            self.currentFrame = ondDlength -1

    def setAttrib(self,
                frameCount : int = None,
                repeat : bool = None,
                isEnded : bool  = None,
                pause : bool = None,
                currentFrame : int  = None,
                speed= 100,
                scale = None,
                rotation = None,
                flip = None):

        super().setAttrib(frameCount=frameCount,repeat=repeat,isEnded=isEnded,pause=pause,currentFrame=currentFrame,speed=speed,scale =scale,rotation=rotation,flip=flip)
        self.texture.transform(scale,rotation,flip)

    def render(self,x,y,scrollRatio =1):

        destination=(x,y)
        frame = int(self.currentFrame % self.frameCount)
        frameArea = (self.frameArea[0] * self.scale[0],self.frameArea[1] * self.scale[1])
        self.texture.drawFrame(source=frameArea,destination=destination,frame=frame,row=self.row,scrollRatio=scrollRatio)

class IO_SequenceAnimation(IO_Animation):
    def __init__(self,
                textures :list[IO_Texture] | list[None],
                id : str,
                frameCount : int,
                repeat : bool = True,
                isEnded : bool = False,
                pause : bool = False,
                speed=100,
                scale = None,
                rotation = None,
                flip = None):
        """

        """
        super().__init__(id,frameCount,repeat,isEnded,pause,speed,scale,rotation,flip)
        self.textures : list[IO_Texture] | list[None] = textures
        for texture in self.textures:
            texture.transform(scale,rotation,flip)

    def setAttrib(self,
                frameCount : int = None,
                repeat : bool = None,
                isEnded : bool  = None,
                pause : bool = None,
                currentFrame : int  = None,
                speed= 100,
                scale = None,
                rotation = None,
                flip = None):

        super().setAttrib(frameCount=frameCount,repeat=repeat,isEnded=isEnded,pause=pause,currentFrame=currentFrame,speed=speed,scaleX=scaleX,scaleY=scaleY)
        for texture in self.textures:
            texture.transform(scale,rotation,flip)

    def update(self,dt=0):
        if (self.repeat or self.isEnded == False) and self.pause == False:
            self.isEnded = False
            self.currentFrame = int((pygame.time.get_ticks() /self.speed) % self.frameCount)

        if self.repeat == False and self.currentFrame == (self.frameCount-1):
            self.isEnded = True
            self.currentFrame = (self.frameCount-1)

    def render(self,x,y,scrollRatio =1):
        destination = (x,y)
        self.textures[self.currentFrame].draw(destination=destination,scrollRatio=scrollRatio)

class IO_AnimationHandler(IO_Object):

    __instance = None
    def __init__(self):
        if IO_AnimationHandler.__instance != None:
            raise Exception("This class is a singleton!")
        else:
            IO_AnimationHandler.__instance = self

        self.animationMap = {}

    def parse(self,source):
        xmlRoot = IO_XmlHandler.getRoot(source)
        xmlspriteanimations = IO_XmlHandler.getChild(xmlRoot,"spriteanimations")
        xmlspriteanimation = xmlspriteanimations[0]
        xmlspriteanimations = IO_XmlHandler.getChild(xmlspriteanimation,"spriteanimation")

        for xmlspriteanimation in xmlspriteanimations:
            id = IO_XmlHandler.getAttribute(xmlspriteanimation,"id")
            texture = IO_XmlHandler.getAttribute(xmlspriteanimation,"texture")
            frameW = float(IO_XmlHandler.getAttribute(xmlspriteanimation,"frameW"))
            frameH = float(IO_XmlHandler.getAttribute(xmlspriteanimation,"frameH"))
            row = int(IO_XmlHandler.getAttribute(xmlspriteanimation,"row"))
            frameCount = int(IO_XmlHandler.getAttribute(xmlspriteanimation,"frameCount"))
            repeat = IO_XmlHandler.getAttribute(xmlspriteanimation,"repeat") == "True"
            speed = float(IO_XmlHandler.getAttribute(xmlspriteanimation,"speed"))
            scaleX = float(IO_XmlHandler.getAttribute(xmlspriteanimation,"scaleX"))
            scaleY = float(IO_XmlHandler.getAttribute(xmlspriteanimation,"scaleY"))
            angle = float(IO_XmlHandler.getAttribute(xmlspriteanimation,"angle"))
            flipX = IO_XmlHandler.getAttribute(xmlspriteanimation,"flipX") == "True"
            flipY = IO_XmlHandler.getAttribute(xmlspriteanimation,"flipY") == "True"

            texture =IO_TextureManager.getInstance().textureMap[texture]
            self.animationMap[id] = IO_SpriteAnimation(texture,id,(frameW,frameH),row,frameCount,repeat,speed=speed,scale= (scaleX,scaleY),rotation=angle,flip=(flipX,flipY))

        xmlsequenceanimations = IO_XmlHandler.getChild(xmlRoot,"sequenceanimations")
        xmlsequenceanimation = xmlsequenceanimations[0]
        xmlsequenceanimations = IO_XmlHandler.getChild(xmlsequenceanimation,"sequenceanimation")

        for xmlsequenceanimation in xmlsequenceanimations:
            id = IO_XmlHandler.getAttribute(xmlsequenceanimation,"id")
            repeat = IO_XmlHandler.getAttribute(xmlsequenceanimation,"repeat") == "True"
            speed = float(IO_XmlHandler.getAttribute(xmlsequenceanimation,"speed"))
            scaleX = float(IO_XmlHandler.getAttribute(xmlsequenceanimation,"scaleX"))
            scaleY = float(IO_XmlHandler.getAttribute(xmlsequenceanimation,"scaleY"))
            angle = float(IO_XmlHandler.getAttribute(xmlsequenceanimation,"angle"))
            flipX = IO_XmlHandler.getAttribute(xmlsequenceanimation,"flipX") == True
            flipY = IO_XmlHandler.getAttribute(xmlsequenceanimation,"flipY") == True

            xmltextures =IO_XmlHandler.getChild(xmlsequenceanimation,"texture")
            frameCount = len(xmltextures)
            textures = []
            for xmltexture in xmltextures:
                textureid = IO_XmlHandler.getAttribute(xmltexture,"id")

    @staticmethod
    def getInstance():
        if IO_AnimationHandler.__instance == None:
            IO_AnimationHandler()
        return IO_AnimationHandler.__instance


import atexit

import requests
from urllib import parse

from unicornsdk.api.captcha import CaptchaAPI
from unicornsdk.api.devicesession import DeviceSession

class UnicornSdk:
    CONFIG = {
        "access_token": None,
        "sdk_proxy": None,
        "api_url": "https://us.unicorn-bot.com",
        "is_debug": False,
        "timeout": 30,
        "tls_forward_url": None
    }

    API_CLIENT = requests.Session()

    def __init__(self):
        self._debug = False

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(UnicornSdk, cls).__new__(cls)
        return cls._instance

    def _get_api_client(self):
        return self.API_CLIENT

    @property
    def api_url(self):
        return UnicornSdk.CONFIG["api_url"]

    @property
    def timeout(self):
        return UnicornSdk.CONFIG.get("timeout", 60)

    @property
    def tls_forward_url(self):
        return UnicornSdk.CONFIG.get("tls_forward_url") or parse.urljoin(self.api_url, "/api/tls/forward/")

    @property
    def is_debug(self):
        return UnicornSdk.CONFIG["is_debug"]

    def _get_authorization(self):
        if not UnicornSdk.CONFIG.get("access_token"):
            raise Exception("you need set access_token first! ")
        return {
            "Authorization": "Bearer " + str(UnicornSdk.CONFIG["access_token"])
        }

    def _get_proxys_for_sdk(self) -> object:
        cur_proxyuri = UnicornSdk.CONFIG["sdk_proxy"]
        proxies = {
            "http": cur_proxyuri,
            "https": cur_proxyuri,
        }
        return proxies if self.is_debug else None

    @classmethod
    def auth(cls, access_token):
        UnicornSdk.CONFIG["access_token"] = access_token

    @classmethod
    def create_device_session(cls, session_id, platform):
        """
        create new DeviceSession
        :return:
        """
        return DeviceSession(UnicornSdk(), session_id=session_id, platform=platform)

    @classmethod
    def config_sdk(cls, access_token=None, debug=None, api_url=None, tls_forward_url=None):
        if access_token:
            cls.CONFIG["access_token"] = access_token
        if debug is not None:
            cls.CONFIG["is_debug"] = bool(debug)
        if api_url:
            cls.CONFIG["api_url"] = api_url
        if tls_forward_url:
            cls.CONFIG["tls_forward_url"] = tls_forward_url

    @classmethod
    def captcha_api(cls) -> "CaptchaAPI":
        return CaptchaAPI(sdk=UnicornSdk())

    @classmethod
    def on_exit(cls):
        if cls.API_CLIENT:
            cls.API_CLIENT.close()

atexit.register(UnicornSdk.on_exit)


import sys

import cv2

# For certain videos cv2.VideoCapture.set(cv2.CAP_PROP_POS_FRAMES, int) # does not work properly.
# If mpf_component_util.VideoCapture detects that cv2.VideoCapture is not setting the frame position
# properly it will fallback to different SeekStrategy.

class SetFramePositionSeek(object):
    # When setting frame position, OpenCV sets the frame position to 16 frames before the requested
    # frame in order to locate the closest key frame. Once OpenCV locates the key frame, it uses
    # cv2.VideoCapture.grab to advance cv2.VideoCapture's position. This means that when you need
    # to advance 16 or fewer frames, it is more efficient to just use cv2.VideoCapture.grab.
    # https://github.com/opencv/opencv/blob/4.5.0/modules/videoio/src/cap_ffmpeg_impl.hpp#L1459
    SET_POS_MIN_FRAMES = 16

    @classmethod
    def change_position(cls, cv_video_cap, current_position, requested_position):
        frame_diff = requested_position - current_position
        if 0 < frame_diff <= cls.SET_POS_MIN_FRAMES:
            return GrabSeek.change_position(cv_video_cap, current_position, requested_position)
        elif cv_video_cap.set(cv2.CAP_PROP_POS_FRAMES, requested_position):
            return requested_position
        else:
            return current_position

    @staticmethod
    def fallback():
        print('SetFramePositionSeek failed: falling back to GrabSeek', file=sys.stderr)
        return GrabSeek()

class _SequentialSeek(object):
    @classmethod
    def change_position(cls, cv_video_cap, current_position, requested_position):
        new_position_in_future = requested_position > current_position
        if new_position_in_future:
            start = current_position
        else:
            # The current position is past the requested position. We need to start reading from the very
            # beginning of the video. If it were possible to set the frame position to a frame in the middle
            #  of the video, then SetFramePositionSeek would not have failed.
            if not cv_video_cap.set(cv2.CAP_PROP_POS_FRAMES, 0):
                return current_position
            start = 0

        num_frames_to_discard = requested_position - start

        num_success = 0
        for i in range(num_frames_to_discard):
            if cls._advance(cv_video_cap):
                num_success += 1
            else:
                break
        return start + num_success

    @staticmethod
    def _advance(cv_video_cap):
        raise NotImplementedError()

class GrabSeek(_SequentialSeek):

    @staticmethod
    def _advance(cv_video_cap):
        return cv_video_cap.grab()

    @staticmethod
    def fallback():
        print('GrabSeek failed: falling back to ReadSeek', file=sys.stderr)
        return ReadSeek()

class ReadSeek(_SequentialSeek):
    @staticmethod
    def _advance(cv_video_cap):
        was_read, _ = cv_video_cap.read()
        return was_read

    @staticmethod
    def fallback():
        print('ReadSeek failed: No more fallbacks', file=sys.stderr)
        return None


def any_list(var1, list):
    if var1 in list:
        return True
    else:
        return False

arg = input("Enter item in list: ")
prog_lang = ["PHP", "Python", "JS", "Java", "c#"]
if any_list(arg, prog_lang):
    print(arg + " is in a programing language")
else:
    print(arg + " is not a programing language here are some")
    for arg in prog_lang:
        print(arg)


from odoo import models, fields

class PmsCheckinPartner(models.Model):

    _inherit = 'pms.checkin.partner'

    def validate_id_number(self):
        """
        Inherit constrain to allow migration of partner os external system
        """
        for checkin in self:
            if checkin.folio_id.remote_id:
                continue
            else:
                super(PmsCheckinPartner, partner).validate_id_number()


import numbers
import numpy as np

import torch

def check_nans(v, name):
    if (v != v).data.any():
        raise ValueError("Found NaNs in %s" % name)

def throws_exception(exception_type, func, *args, **kwargs):
    try:
        func(*args, **kwargs)
        return False
    except exception_type:
        return True

def check_conditions(v, name, *conditions):
    for condition in conditions:
        if not eval(condition % "v"):
            raise ValueError(("%s must meet the following condition: " + condition)
            	% (name, name))
    return v

def make_list(l, length, name, *conditions):
    if throws_exception(TypeError, list, l):
        l = [l]*length
    else:
        l = list(l)
    if len(l) != length:
        raise ValueError("%s must be a list of length %d." % (name, length))
    for i, ll in enumerate(l):
        l[i] = check_conditions(ll, name, *conditions)
    return l

def check_tensor_dims(t, name, dims):
    s = t.size()
    if len(s) != len(dims):
        raise ValueError("%s must be a %d-dimensional tensor." % (name, len(dims)))
    for i in range(len(dims)):
        if dims[i] >= 0 and s[i] != dims[i]:
            raise ValueError("The %dth dimension of %s must have size %d, not %d."
            	% (i, name, dims[i], s[i]))

def list2tensor(l):
    return torch.from_numpy(np.array(l, dtype=np.float32))


import os
import pickle
import random

import keras
import numpy as np
import pandas as pd
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.models import Model, load_model
from keras.optimizers import Adam
from keras_preprocessing.image import ImageDataGenerator
from PIL import Image
import tensorflow as tf
from keras import backend as K

from poster_model import get_model

def load_data(image_file, val_proportion, test_proportion,
               shuffle=True, random_state=42):
    """
    Split the data into train, validation and test sets
    and return them as pandas dataframes.

    Input:
    -------
    image_file: Path to the file containing the list of image paths.
    val_proportion: The proportion of the entire dataset which needs to be
                    allocated to the validation set.
    test_proportion: The proportion of the entire dataset which needs to be
                     allocated to the test set.
    shuffle: Boolean value indicating if the data needs to be shuffled prior
             to splitting. Default is True.
    random_state: Value of seed for the random number generator.Default is 42.
    """

    # Read and load the list of all the images.
    with open(image_file, 'r') as file_:
        image_paths = file_.readlines()
    # Strip unnecessary character and drop empty rows
    image_paths = list(filter(len, map(str.strip, image_paths)))

    if shuffle:
        random.seed(random_state)  # set the random generator seed
        random.shuffle(image_paths)  # shuffle if required

    # Get the total size and calculate the split sizes
    total_size = len(image_paths)
    test_size = int(test_proportion * total_size)
    val_size = int(val_proportion * total_size)

    # Split the data
    test_samples = image_paths[:test_size]
    image_paths = image_paths[test_size:]
    val_samples = image_paths[:val_size]
    train_samples = image_paths[val_size:]

    # Convert each to pandas data frame
    train_df = pd.DataFrame(data=train_samples, columns=['filename'])
    val_df = pd.DataFrame(data=val_samples, columns=['filename'])
    test_df = pd.DataFrame(data=test_samples, columns=['filename'])

    return train_df, val_df, test_df

def train_model(data_file, batch_size, epochs, val_proportion,
                test_proportion, optimizer, loss, save_dir,
                image_size, shuffle=True, random_state=42):
    # Get the data
    train_df, val_df, test_df = load_data(data_file, val_proportion,
                                          test_proportion, shuffle=shuffle,
                                          random_state=random_state)

    # Setup data generator
    data_generator = ImageDataGenerator(rescale=1./255,
                                        data_format='channels_last')
    train_generator = data_generator.flow_from_dataframe(dataframe=train_df,
                                                         class_mode='input',
                                                         target_size=(image_size,
                                                                      image_size),
                                                         batch_size=batch_size)
    val_generator = data_generator.flow_from_dataframe(dataframe=val_df,
                                                       class_mode='input',
                                                       target_size=(image_size,
                                                                    image_size),
                                                       batch_size=batch_size)
    test_generator = data_generator.flow_from_dataframe(dataframe=test_df,
                                                        class_mode='input',
                                                        target_size=(image_size,
                                                                     image_size),
                                                        batch_size=batch_size)
    STEP_SIZE_TRAIN = train_generator.n // train_generator.batch_size
    STEP_SIZE_VAL = val_generator.n // val_generator.batch_size
    STEP_SIZE_TEST = test_generator.n // test_generator.batch_size

    # Get the model
    model, encoder_output = get_model()

    # Setup early stopping
    early_stopper_cb = EarlyStopping(monitor='val_loss', patience=10, verbose=1)

    # Setup model checkpointing
    chkpt = save_dir + 'AutoEncoder_poster_weights.{epoch:02d}-{loss:.3f}-{val_loss:.3f}.hdf5'
    checkpoint_cb = ModelCheckpoint(filepath = chkpt, monitor='val_loss',
                                    verbose=1, save_best_only=True, mode='auto')

    # Compile the model
    model.compile(optimizer=optimizer, loss=loss)

    # Fit the model
    history = model.fit_generator(generator=train_generator,
                                  steps_per_epoch=STEP_SIZE_TRAIN,
                                  validation_data=val_generator,
                                  validation_steps=STEP_SIZE_VAL,
                                  epochs=epochs, verbose=1,
                                  callbacks=[early_stopper_cb, checkpoint_cb])

    # Test the model
    score = model.evaluate_generator(generator=test_generator,
                                     steps=STEP_SIZE_TEST,
                                     verbose=1)
    print('Score:\n', score)

if __name__ == "__main__":
    # Set the model training parameters
    data_file = '../data/posters/poster.txt'
    test_proportion = 0.15
    val_proportion = 0.1
    batch_size = 2
    epochs = 150
    optimizer = 'adam'
    loss = 'mean_squared_error'
    save_dir = '../weights/'
    image_size = 256

    session_conf = tf.ConfigProto()
    session_conf.gpu_options.allow_growth=True
    session = tf.Session(graph=tf.get_default_graph(), config=session_conf)
    K.set_session(session)

    # Train the model
    train_model(data_file, batch_size, epochs, val_proportion, test_proportion,
                optimizer, loss, save_dir, image_size)


#!/usr/bin/env python3
"""
File: messagesWindow.py
Messages list window handling.
"""
from typing import Optional
import curses

import common
from SignalCliApi import SignalReceivedMessage, SignalSentMessage
from SignalCliApi.signalMessage import SignalMessage
from SignalCliApi.signalMessages import SignalMessages
from common import ROW, COL, TOP, LEFT, BOTTOM, RIGHT, STRINGS, Focus
from cursesFunctions import calc_attributes, add_title_to_win, add_ch
from messageItem import MessageItem
from themes import ThemeColours
from typeError import __type_error__
from verticalScrollBar import VerticalScrollBar
from window import Window

class MessagesWindow(Window):
    """
    Class to store the messages' window.
    """
    def __init__(self,
                 std_screen: curses.window,
                 size: tuple[int, int],
                 top_left: tuple[int, int],
                 theme: dict[str, dict[str, int | bool | str]]
                 ) -> None:
        """
        Initialize the messages window.
        :param size: tuple[int, int]: The size of the window: (ROWS, COLS).
        :param top_left: tuple[int, int]: The top left corner of the window: (ROW, COL).
        :param theme: dict[str, dict[str, int | bool | str]]: The current theme.
        """
        # Set title theme, and background character:
        title: str = STRINGS['titles']['messages']
        self._theme: dict[str, dict[str, int | bool | str]] = theme
        """Store the theme for future use."""
        self._bg_char: str = theme['backgroundChars']['messagesWin']
        """Store the background character."""

        # Set theme attrs and strings:
        window_attrs: int = calc_attributes(ThemeColours.MESSAGES_WIN, theme['msgsWin'])
        border_attrs: int = calc_attributes(ThemeColours.MESSAGES_WIN_BORDER, theme['msgsWinBorder'])
        border_focus_attrs: int = calc_attributes(ThemeColours.MESSAGES_WIN_FOCUS_BORDER, theme['msgsWinFBorder'])
        border_chars: dict[str, str] = theme['msgsWinBorderChars']
        border_focus_chars: dict[str, str] = theme['msgsWinFBorderChars']
        title_attrs: int = calc_attributes(ThemeColours.MESSAGES_WIN_TITLE, theme['msgsWinTitle'])
        title_focus_attrs: int = calc_attributes(ThemeColours.MESSAGES_WIN_FOCUS_TITLE, theme['msgsWinFTitle'])
        title_chars: dict[str, str] = theme['msgsWinTitleChars']
        title_focus_chars: dict[str, str] = theme['msgsWinFTitleChars']

        # Create the curses window:
        window = curses.newwin(size[ROW], size[COL], top_left[ROW], top_left[COL])

        # Run Super:
        Window.__init__(self, std_screen, window, title, top_left, window_attrs, border_attrs, border_focus_attrs,
                        border_chars, border_focus_chars, title_attrs, title_focus_attrs, title_chars,
                        title_focus_chars, self._bg_char, Focus.MESSAGES, 'left')

        # Set this window as always visible:
        self.always_visible = True
        self.is_static_size = False

        # Create the vertical scroll bar:
        self._v_scrollbar: VerticalScrollBar = VerticalScrollBar(
            height=self.height,
            top_left=(self.real_top_left[common.TOP] + 1, self.real_bottom_right[common.RIGHT] - 1),
            theme=theme
        )
        """The vertical scroll bar object."""
        self._v_scrollbar.is_visible = True

        # Create the conversation var:
        self._conversation: list[SignalSentMessage | SignalReceivedMessage] = []
        """The conversation we build the pad from."""
        self.__update_conversation__()

        # Create the message items for the messages in the conversation:
        self._message_item_list: list[MessageItem] = []
        """The message item list for the conversation."""
        self.__update_message_items__()

        # Create the pad:
        self._pad: Optional[curses.window] = None
        """The pad we draw on."""
        self._pad_out_top_left: tuple[int, int] = (0, 0)
        """The top left of the pad to start the output from."""
        self.__create_pad__()

        return

    def __update_conversation__(self) -> None:
        if common.CURRENT_RECIPIENT is None:
            self._conversation = []
            return

        def _sort_(item: SignalMessage) -> int:
            return item.timestamp.timestamp

        messages: SignalMessages = common.CURRENT_ACCOUNT.messages
        self._conversation = messages.get_conversation(common.CURRENT_RECIPIENT)
        self._conversation.sort(key=_sort_, reverse=False)
        return

    def __update_message_items__(self) -> None:
        self._message_item_list = []
        for message in self._conversation:
            message_item = MessageItem(message=message,
                                       pad_width=self.pad_width,
                                       theme=self._theme
                                       )
            self._message_item_list.append(message_item)

    def __clear_pad__(self) -> None:
        for row in range(0, self.pad_height):
            for col in range(0, self.pad_width):
                add_ch(self._pad, self._bg_char, self._bg_attrs, row, col)
        return

    def __create_pad__(self):
        self._pad = curses.newpad(self.pad_height, self.pad_width)
        self.__clear_pad__()
        item_top = 0
        for message_item in self._message_item_list:
            message_item.pad = self._pad
            message_item.top = item_top
            message_item.redraw()
            item_top += message_item.height
        self.pad_out_bottom = self.pad_bottom
        return

    #############################################
    # External methods:
    #############################################
    def recipient_changed(self) -> None:
        self.__update_conversation__()
        self.__update_message_items__()
        self.__create_pad__()
        return

    def message_received(self) -> None:
        self.__update_conversation__()
        self.__update_message_items__()
        self.__create_pad__()
        return

    #############################################
    # External overrides:
    #############################################
    def resize(self,
               size: Optional[tuple[int, int]],
               real_top_left: Optional[tuple[int, int]],
               do_resize: bool = True,
               do_move: bool = True,
               ) -> None:
        super().resize(size, real_top_left, do_resize, do_move)
        self._v_scrollbar.resize(self.height, (self.real_top_left[TOP] + 1, self.real_bottom_right[RIGHT] - 1))
        self.__update_message_items__()
        self.__create_pad__()
        return

    def redraw(self) -> None:
        super().redraw()
        if common.CURRENT_RECIPIENT is None:
            recipient_text = 'None'
        else:
            recipient_text = common.CURRENT_RECIPIENT.get_display_name()
        recipient_text = "Thread: " + recipient_text
        add_title_to_win(self._window, recipient_text, self.border_attrs, self.title_attrs, self.title_chars['lead'],
                         self.title_chars['tail'], 'right')
        if self.pad_height > self.display_height:
            self._v_scrollbar.is_enabled = True
        else:
            self._v_scrollbar.is_enabled = False
        self._v_scrollbar.redraw()

        # Redraw the pad:
        self.__clear_pad__()
        for message_item in self._message_item_list:
            message_item.redraw()

        self._window.noutrefresh()
        self._pad.noutrefresh(self.pad_out_top, self.pad_out_left,
                              self.display_top, self.display_left,
                              self.display_bottom, self.display_right)
        return

##################################
# Properties:
##################################

    #############
    # Display output:
    @property
    def display_top_left(self):
        return self.real_top + 1, self.real_left + 1

    @property
    def display_top(self):
        return self.real_top + 1

    @property
    def display_left(self):
        return self.real_left + 1

    @property
    def display_width(self):
        return self.width - 1

    @property
    def display_height(self):
        return self.height

    @property
    def display_bottom_right(self):
        return self.display_top + self.display_height - 1, self.display_left + self.display_width - 1

    @property
    def display_bottom(self):
        return self.display_top + self.display_height - 1

    @property
    def display_right(self):
        return self.display_left + self.display_width - 1

    ##############
    # Pad properties:
    @property
    def pad_top_left(self):
        return 0, 0

    @property
    def pad_top(self):
        return 0

    @property
    def pad_left(self):
        return 0

    @property
    def pad_width(self):
        return self.display_width

    @property
    def pad_height(self):
        pad_height = 0
        for message_item in self._message_item_list:
            pad_height += message_item.height
        if pad_height < self.display_height:
            pad_height = self.display_height
        return pad_height

    @property
    def pad_bottom_right(self):
        return self.pad_top + self.pad_height - 1, self.pad_left + self.pad_width - 1

    @property
    def pad_bottom(self):
        return self.pad_top + self.pad_height - 1

    @property
    def pad_right(self):
        return self.pad_left + self.pad_width - 1

    ##############
    # pad output size, top_left, etc:
    @property
    def pad_out_size(self):
        return self.display_height, self.display_width

    @property
    def pad_out_height(self):
        return self.display_height

    @property
    def pad_out_width(self):
        return self.display_width

    @property
    def pad_out_top_left(self):
        return self._pad_out_top_left

    @pad_out_top_left.setter
    def pad_out_top_left(self, value):
        if not common.__type_check_position_or_size__(value):
            __type_error__("value", 'tuple[int, int]', value)
        self._pad_out_top_left = value

    @property
    def pad_out_top(self):
        return self._pad_out_top_left[TOP]

    @pad_out_top.setter
    def pad_out_top(self, value):
        if not isinstance(value, int):
            __type_error__('value', 'int', value)
        self._pad_out_top_left = (value, self._pad_out_top_left[LEFT])
        return

    @property
    def pad_out_left(self):
        return self._pad_out_top_left[LEFT]

    @pad_out_left.setter
    def pad_out_left(self, value: int):
        if not isinstance(value, int):
            __type_error__('value', 'int', value)
        self._pad_out_top_left = (self.pad_out_top_left[TOP], value)
        return

    @property
    def pad_out_bottom_right(self) -> tuple[int, int]:
        return self.pad_out_top + self.pad_out_height - 1, self.pad_out_left + self.pad_out_width - 1

    @pad_out_bottom_right.setter
    def pad_out_bottom_right(self, value: tuple[int, int]) -> None:
        if not common.__type_check_position_or_size__(value):
            __type_error__('value', 'tuple[int, int]', value)
        top = value[BOTTOM] - self.pad_out_height + 1
        if top < 0:
            top = 0
        left = value[RIGHT] - self.pad_out_width + 1
        if left < 0:
            left = 0
        self._pad_out_top_left = (top, left)

    @property
    def pad_out_bottom(self):
        return self.pad_out_top + self.pad_out_height - 1

    @pad_out_bottom.setter
    def pad_out_bottom(self, value):
        if not isinstance(value, int):
            __type_error__('value', 'int', value)
        top = value - self.pad_out_height + 1
        if top < 0:
            top = 0
        self._pad_out_top_left = (top, self._pad_out_top_left[LEFT])
        return

    @property
    def pad_out_right(self):
        return self.pad_out_left + self.pad_out_width - 1

    @pad_out_right.setter
    def pad_out_right(self, value):
        if not isinstance(value, int):
            __type_error__('value', 'int', value)
        left = value - self.pad_out_width + 1
        if left < 0:
            left = 0
        self._pad_out_top_left = (self._pad_out_top_left[TOP], left)
        return

#############################################
# Property hooks:
#############################################
    def __is_focused_hook__(self, is_get: bool, value: bool) -> Optional[bool]:
        if not is_get and value:
            for message in self._conversation:
                if not message.is_read:
                    try:
                        message.mark_read()
                    except TypeError as e:
                        common.out_error("mark read failed for message type:")
                        common.out_debug(str(type(message)))
                        raise TypeError(str(type(message)))
        return None


import torch
import sys

class KNN(torch.nn.Module):
    def __init__(self, colors, classes, K=1):
        super().__init__()
        self.classes = torch.arange(0, len(classes))
        self.K = K

        if type(colors) == list:
            if type(colors[0]) == list or type(colors[0]) == tuple:
                colors = [torch.tensor(elm)/255 for elm in colors]
            else:
                pass
            colors = torch.stack(colors, dim=0).squeeze(1)
        elif type(colors) == torch.Tensor:
            pass
        else:
            print(f"WRONG INPUT TYPE {type(colors)}, must be one of {torch.Tensor} or {list} of {torch.Tensor}")
            sys.exit(1)
        a_norm = colors.norm(dim=-1, p=2)  # (batch size, 1)
        colors = colors.divide(a_norm.unsqueeze(1))
        self.colors = colors

    def preprocess(self, rgb_mask):
        self.shape = rgb_mask.shape
        rgb_mask = rgb_mask.permute(0, 2, 3, 1)
        rgb_mask = rgb_mask.reshape(rgb_mask.shape[0], rgb_mask.shape[1] * rgb_mask.shape[2],  rgb_mask.shape[3])
        return rgb_mask

    def forward(self, rgb_mask):
        rgb_mask = self.preprocess(rgb_mask)
        rgb_mask_ = torch.zeros_like(rgb_mask)

        for bs in range(rgb_mask.shape[0]):
            for pix in range(rgb_mask.shape[1]):
                rgb_mask_[bs, pix] = self._forward(rgb_mask[bs, pix].unsqueeze(0))

        rgb_mask_ = rgb_mask_.permute(0, 2, 1)
        return rgb_mask_.reshape(self.shape)

    def _forward(self, vector):
        if vector.sum()<=0:
            return torch.tensor([0, 0, 0])

        a_norm = vector.norm(dim=-1, p=2)
        vector = vector.divide(a_norm.unsqueeze(1))

        cos_sim = torch.nn.functional.linear(self.colors, vector).squeeze(1)

        cos_sim_topK = cos_sim.topk(1)
        indexes = cos_sim_topK[1][0].cpu()

        preds_int = self.classes[indexes]

        out = self.colors[preds_int]

        return out


import json,urllib.request

URL = "https://socialblade.com/youtube/channel/UC7_YxT-KID8kRbqZo7MyscQ/monthly"
req = urllib.request.Request(URL, headers={'User-Agent': 'Mozilla/5.0'})
page=urllib.request.urlopen(req)
data = page.read()
e=data.decode('utf-8')

f = open("socialblade.txt", "r")
d=f.read()
q=d.split("\n")[-1].split("\t")[0]
#print(q)
f.close()
f = open("socialblade.txt", "a")
#f.write(d)

import html_to_json

output_json = html_to_json.convert(e)
path=output_json["body"][0]["div"][15]["div"][0]["div"][0]["div"]
for i in range(30):
    #print(i)
    path1=path[2+i]["div"][0]["_value"]
    path2=path[2+i]["div"][3]["div"][1]["_value"].replace(",","")
    if(path1>q):
        f.write("\n"+path1+"\t"+path2)
f.close()


"""
Given an array of meeting time intervals consisting of start and end times
[[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.

Example 1:

Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:

Input: [[7,10],[2,4]]
Output: 1
"""

import heapq

"""
思路，利用priority queue来track当前最早结束的会议
"""

class Solution:
    def minMeetingRooms(self, intervals: List[List[int]]) -> int:
        if not intervals or not intervals[0]:
            return 0

        if len(intervals) == 1:
            return 1

        # sort the meetings' start time in increasing order
        intervals.sort(key=lambda x: x[0])

        rooms = []

        # add the first meeting.
        # building the min heap
        heapq.heappush(rooms, intervals[0][1])

        for m in intervals[1:]:
            # if the currently earlist end time < meeting's start time
            # assign this meeting room to the new meeting
            if rooms[0] <= m[0]:
                heapq.heappushpop(rooms, m[1])
            else:
                heapq.heappush(rooms, m[1])

        return len(rooms)


# N개의 정수가 입력으로 주어진다.

# 이때 연속하여 몇 개의 정수를 골라 합을 구할 수 있다.

# 예를 들어, 1 3 -8 18 -8 이 있다고 하자.

# 그럼 2번부터 4번까지의 수를 골라 합을 구하면, 3+(-8)+18 = 13이다.

# 이렇게 연속해서 정수를 골라 합을 구할 때, 그 합의 최대가 몇인지 구하는 프로그램을 작성하세요.

#어디가틀렸지??
T = int(input())
for z in range(T):
    N = int(input())
    lst = list(map(int, input().split()))
    maxlst = []
    for i in range(N-1):
        numsum = lst[i]
        for j in range(i+1, N):
            numsum += lst[j]
            if numsum < numsum -lst[j]:
                numsum = numsum-lst[j]
                break
        maxlst.append(numsum)
    maxlst.append(lst[-1])
    print(f'#{z+1} {max(maxlst)}')

# 긁어온 풀이
T = int(input())
for TC in range(1, T+1):
    N = int(input())
    Arr = list(map(int, input().split()))
    # 최대값 초기화
    maxV = -1000000
    # 합 초기화
    sumV = 0
    # 시작 인덱스 탐색
    for i in range(N):
        # 처음부터 더하기
        sumV += Arr[i]
        # 최대값 갱신
        if sumV > maxV:
            maxV = sumV
        # 현재까지의 합이 음수이면 버리기
        if sumV < 0:
            sumV = 0
    print("#{} {}".format(TC, maxV))


## merges two strings interchangeably
class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        word = ""
        len1 = len(word1)
        len2 = len(word2)
        if len1 > len2:
            for i in range(len1):
                print(word1[i])
                word += word1[i]
                if i > len2 or i == len2:
                    i+=1
                else:
                    print(word2[i])
                    word += word2[i]
        else:
            for i in range(len2):
                if i < len1 or i == len1-1:
                    print(word1[i])
                    word +=word1[i]
                print(word2[i])
                word += word2[i]
                print("this is a new line")
        return word


import sqlite3

connection = sqlite3.connect("websub.db")

with connection:
    cursor = connection.cursor()

    cursor.execute(
        """CREATE TABLE IF NOT EXISTS subscriptions(
        hub_callback text,
        hub_mode text,
        hub_topic text,
        hub_lease_seconds text,
        hub_secret
    )"""
    )

    print("created subscriptions table in database")

    cursor.execute(
        """CREATE TABLE IF NOT EXISTS feeds(
        feed_url text,
        last_url_fetched text
    )"""
    )

    print("created feeds table in database")

print("the database is now ready for use")
print("run app.py to execute the flask websub server")


from  urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

file = "Details.csv"
f = open(file, "w")
Headers = "Brand,Product_url\n"
f.write(Headers)
for i in range(1,13):
	my_url = 'https://www.stihlusa.com/products/stihl-top-rated-products/?page={}&viewAll=False'.format(i)
	uClient = uReq(my_url)
	page_html = uClient.read()
	page_soup = soup(page_html, "html.parser")
	containers = page_soup.find_all("div", {"class":"top-product-image"})

	for container in containers:
		brand= container.img["title"]
		url_name=container.a["href"]

		print("Brand: "+ brand)
		print("url_name: "+ url_name)

		f.write(brand + "," + url_name+ "\n")

f.close()


class Node:
    def __init__(self):
        self.sons = []
        self.height = 0
        self.father = None
        self.value = 1

def dfs(root:Node,aim:int,notsearch:int):
    result = False
    if root is None:
        return False
    for i,x in enumerate(root.sons):
        if x.value != notsearch:
            if x.value == aim:
                return True
            else:
                result = result or dfs(x,aim,-1)
                if result == True:
                    return result
    return False

def b2r(fron:Node,to:Node,k:int):
    result = 0
    while to != fron:
        result += to.height ** k
        nottosearch = to.value
        to = to.father
        if dfs(to,fron.value,nottosearch):
            result += b2r(to,fron,k)
            return result % 998244353

    result += to.height ** k
    result %= 998244353
    return result

nodes = [None,Node()]
nodes[-1].value = 1
n = int(input())
for N in range(2,n+1):
    nodes.append(Node())
    nodes[-1].value = N

for N in range(n-1):
    in1 = [int(x) for x in input().split(' ')]
    nodes[in1[0]].sons.append(nodes[in1[1]])
    nodes[in1[1]].height = nodes[in1[0]].height+1
    nodes[in1[1]].father = nodes[in1[0]]

q = int(input())
for Q in range(q):

    in1 = [int(x) for x in input().split(' ')]
    fron,to,k = nodes[in1[0]],nodes[in1[1]],in1[2]
    if fron.value > to.value:
        print(b2r(to,fron,k))
    else:
        print(b2r(fron,to,k))


import itertools, time, json
from urllib.request import urlopen, Request
from werkzeug.datastructures import ImmutableMultiDict
grps = ["fw","ddos","ips"]
FCC_URL = "http://localhost:5000/manual"

perms = list(itertools.permutations(grps))
iterate_list = list()
STANDARD_CONF = ("ddos", "fw", "ips")
perms.remove(STANDARD_CONF)

print(perms[0])

for conf in perms:
    time.sleep(10)
    conn = Request(FCC_URL, json.dumps(conf).encode("utf-8"),
                   {'Content-Type': 'application/json'})
    resp = urlopen(conn)
    print(resp.getcode())


import convert as cv

print("whcih unit you want to convert?\nChoose from c f kg ounce pound meter mile inch foot\n")

ch1 = input("From?")
ch2 = input("To?")

num = input("Please input the specific value\n")
if str.isdigit(num) == False:
    print("Please input numbers!!")
    exit
num = float(num)
#print(num, type(num))

cv.uc(ch1, ch2, num)


import pandas as pd
import numpy as np

def readfile_allect_states(path):
    dataframe=pd.read_csv(path,sep='\t',encoding='utf-8')
    dataframe = dataframe[['Chromosome','Start','End','CopyNr','A','B']]
    return dataframe

def readfile_snp(path):
    dataframe=pd.read_csv(path,sep='\t',header=None,comment='#',encoding='utf-8')
    dataframe.columns=['CHROM','POS','ID','REF','ALT','QUAL','FILTER','INFO']
    dataframe = dataframe[['CHROM','POS','INFO']]
    dataframe['DP'] = dataframe['INFO'].str.split(';').str[0]
    dataframe['AF'] = dataframe['INFO'].str.split(';').str[1]
    dataframe['DP'] = dataframe['DP'].str.split('=').str[1]
    dataframe['AF'] = dataframe['AF'].str.split('=').str[1]
    dataframe['DP'] = dataframe['DP'].astype(int)
    dataframe['AF'] = dataframe['AF'].astype(float)
    dataframe['AD'] = (dataframe['DP']*dataframe['AF']).astype(int)
    dataframe = dataframe[['CHROM','POS','AD','DP']]
    return dataframe

def write_cnv(dataframe,filename):
    dataframe['Chromosome'] = dataframe['Chromosome'].str.split('chr').str[1]
    write = dataframe[['Chromosome','Start','End','A','B']]
    write.to_csv(filename,mode='w',index=0,header=0,sep='\t')

def write_snv(dataframe,filename):
    dataframe['CHROM'] = dataframe['CHROM'].str.split('chr').str[1]
    write = dataframe
    write.to_csv(filename,mode='w',index=0,header=0,sep='\t')

def write_purity(purity,filename):
    output = open(filename,'w')
    output.write(str(purity))
    output.close()
title = "EGAF00000098597"
path_vcf = 'example/'+title+'.sclust.vcf'
path_cnv = 'example/'+title+'_allelic_states.txt'

cnv = readfile_allect_states(path_cnv)
snp = readfile_snp(path_vcf)

write_purity(0.26,'./Sample_data/'+title+'_purity.txt')
write_cnv(cnv,'./Sample_data/'+title+'_cnv.txt')
write_snv(snp, 'Sample_data/'+title+'_snp.txt')


def inputGrades(ng):
    grades=[]
    for i in range(0,ng,1):
        grade=float(input('Please enter your grade: '))
        grades.append(grade)
    return grades
def printGrades(ng,grades):
    for i in range(0,ng,1):
        print(grades[i])
def avgGrades(grades):
    sum=0
    for i in range(0,len(grades),1):
        sum += grades[i]
    avg = sum / len(grades)
    return avg
def highLow(ng, grades):
    highG=0
    lowG=100
    for i in range(0,ng,1):
        if(grades[i]<lowG):
            lowG=grades[i] #10
        if(grades[i]>highG):
            highG=grades[i] #30
    return highG, lowG

numGrades=int(input('How many grades? '))
myGrades=inputGrades(numGrades)
printGrades(numGrades,myGrades)
print("")
avg=avgGrades(myGrades)
print("avg of grades is", round(avg,1))
#long way
highG, lowG=highLow(numGrades,myGrades)
print('Your high grade is',highG)
print('Your low grade is',lowG)
#short way
print("")
print("Lowest Grade: ",min(myGrades))
print("Highest Grade: ",max(myGrades))


import sys
import youtube_dl
import json

def get_youtube_mp3_link(video_url):
    ydl_opts = {'format': 'bestaudio', 'quiet': True}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        try:
            info = ydl.extract_info(video_url, download=False)
            mp3_link = info.get('formats', [{}])[0].get('url')
            if mp3_link:
                return mp3_link
            else:
                #print(json.dumps({"state": "Không tìm thấy thông tin định dạng audio."}))
                return None
        except youtube_dl.DownloadError as e:
            #print(json.dumps({"state": f"Lỗi khi tải thông tin: {e}"}))
            return None

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(json.dumps({"state": "Vui lòng cung cấp đường dẫn URL của video YouTube."}))
    else:
        video_url = sys.argv[1]
        mp3_link = get_youtube_mp3_link(video_url)
        if mp3_link is not None:
            print(mp3_link)


clc()
fig=figure(1,rows=1,cols=2)
s=dataObject()
filter("loadAnyImage",s,"2dgratingAperture.jpg")
L=1 # mm
Nx,Ny=s.shape
dx=L/Nx
dy=L/Ny
s.setAxisScale(1,dx)
s.setAxisScale(0,dy)
fig.plot(s,areaIndex=0)
df=1/L #??????????????:setAxisScale()?????????????
d=dataObject()
filter("fftw2D",s,d)
filter("fftshift",d)
fig.plot(d,areaIndex=1,properties={"colorMap":"falseColor"})


import tensorflow as tf

# normal distribution:
w = tf.Variable(tf.random.normal([784, 10], stddev=0.01))

# mean of an array:
b = tf.Variable([10,20,30,40,50,60],name='t')

print("w: ",w)
print("b: ",tf.reduce_mean(input_tensor=b))

books/Machine Learning/TensorFlow2 Pocket Primer Supp/CODE/chapter2/tf2_normal_dist.py


import json
import os
import os.path
import shutil

from PIL import Image

import generators

class _Profile(object):
    def __init__(self, out_path_mod, rescale_factor):
        self.out_path_mod = out_path_mod
        self.rescale_factor = rescale_factor

    def modify_path(self, path):
        if self.out_path_mod == '1x':
            (root_path, ext_path) = os.path.splitext(path)
            return '%s%s' % (root_path, '.png')
        else:
            (root_path, ext_path) = os.path.splitext(path)
            return '%s@%s%s' % (root_path, self.out_path_mod, '.png')

_PROFILES = {
    '1x': _Profile('1x', 29.0 / 60.0),
    '2x': _Profile('2x', 40.0 / 60.0),
    '3x': _Profile('3x', 60.0 / 60.0)
    }

_MODIFIER_FOR_USAGE = {
    'appicon': 'appiconset',
    'launcher': 'launchimage',
    'asset': 'imageset'
    }

class _PngHandler(generators._Handler):
    def __init__(self):
        super(_PngHandler, self).__init__('.png')

    def __call__(self, output_dir_path, g_name, g_config, path):
        (g_name_base, g_name_ext) = os.path.splitext(g_name)
        dir_path = os.path.join(output_dir_path,
            '%s.%s' % (g_name_base, _MODIFIER_FOR_USAGE[g_config['usage']]))
        base_out_path = os.path.join(dir_path, g_name)
        os.mkdir(dir_path)

        metadata = {
            'images': [],
            'info': {
                'version': 1,
                'author': 'xcode' # Should be the assets pipeline.
                }
            }

        for p_name, profile in _PROFILES.iteritems():
            out_path = profile.modify_path(base_out_path)
            image = Image.open(path)
            desired_width = int(image.size[0] * profile.rescale_factor)
            image_resized = generators._resize_to_width(image, desired_width)
            image_resized[0].save(out_path)
            metadata['images'].append({
                    'idiom': 'universal',
                    'scale': profile.out_path_mod,
                    'filename': os.path.basename(out_path)
                    })

        with open(os.path.join(dir_path, 'Contents.json'), 'w') as contents_file:
            contents_file.write(json.dumps(metadata))

class _GifHandler(generators._Handler):
    def __init__(self):
        super(_GifHandler, self).__init__('.gif')

    def __call__(self, output_dir_path, g_name, g_config, path):
        (g_name_base, g_name_ext) = os.path.splitext(g_name)
        dir_path_pattern = os.path.join(output_dir_path,
            '%s%%02d.imageset' % g_name_base)
        g_name_pattern = '%s%%02d%s' % (g_name_base, g_name_ext)
        base_out_path_pattern = os.path.join(dir_path_pattern, g_name_pattern)

        fr = 0
        image = Image.open(path)
        while True:
            try:
                image.seek(fr)
            except EOFError:
                break

            dir_path = dir_path_pattern % fr
            os.mkdir(dir_path)
            metadata = {
                'images': [],
                'info': {
                    'version': 1,
                    'author': 'xcode' # Should be the assets pipeline.
                    }
                }

            for g_name, profile in _PROFILES.iteritems():
                out_path = profile.modify_path(base_out_path_pattern % (fr, fr))
                frame = image.copy()
                desired_width = int(frame.size[0] * profile.rescale_factor)
                frame_resized = generators._resize_to_width(image, desired_width)
                frame_resized[0].save(out_path)
                metadata['images'].append({
                        'idiom': 'universal',
                        'scale': profile.out_path_mod,
                        'filename': os.path.basename(out_path)
                        })

                with open(os.path.join(dir_path, 'Contents.json'), 'w') as contents_file:
                    contents_file.write(json.dumps(metadata))

            fr = fr + 1

_HANDLERS = {
    '.png': _PngHandler(),
    '.gif': _GifHandler()
}

class Generator(generators.BaseGenerator):
    def __init__(self, output_dir_path):
        super(Generator, self).__init__(output_dir_path)

    def __enter__(self):
        # Recreate the directory for graphics assets. In iOS, this directory is completely under
        # the application's control, so we can just recreate it without issues at this point.
        generators._recreate_directory(self.output_dir_path)

        return self

    def generate(self, g_name, g_config):
        path = g_config['path']
        path_type = os.path.splitext(path)[1]
        _HANDLERS[path_type](self.output_dir_path, g_name, g_config, path)


import sys
from collections import deque

M, N = map(int, sys.stdin.readline().split())

#print(M, N)

box = []

for _ in range(N):
    tomatoes = list(map(int, sys.stdin.readline().split()))
    box.append(tomatoes)
#print(box)

visit = [[0 for _ in range(M)] for _ in range(N)]

dx, dy = [-1, 1, 0, 0], [0, 0, 1, -1] #위 아래 오른쪽 왼쪽

def bfs():
    while queue:
        node = queue.popleft()
        for i in range(4):
            x2 = node[0] + dx[i]
            y2 = node[1] + dy[i]
            if (0<=x2<N and 0<=y2<M) and visit[x2][y2]==0:
                if box[x2][y2] == 0:
                    visit[x2][y2] = visit[node[0]][node[1]] + 1
                    queue.append([x2, y2])
    return visit

queue = deque() # 핵심. queue를 바깥으로 빼면서, 토마토가 익은거 동시에 큐에 넣어줌으로써, 동시에 카운트 가능!
for i in range(N):
    for j in range(M):
        if box[i][j] == 1:
            queue.append([i, j])
            visit[i][j] = 1
        elif box[i][j] == -1:
            visit[i][j] = -1

visit = bfs()

max1 = -5

'''
for v in visit:
    print(v)
'''

answer = True
for line in visit:
    if 0 in line:
        answer = False
    elif max(line) >= max1:
        max1 = max(line)

if answer:
    print(max1-1)
else:
    print(-1)


import sys
import time
from socket import *

serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = int(sys.argv[1])
serverSocket.bind(("", serverPort))
serverSocket.listen(1)

def buildResponse(responseCode):
    if responseCode == 200:
        response = "HTTP/1.1 200 OK\n"
    elif responseCode == 404:
        response = "HTTP/1.1 404 Not Found\n"
    response += "Connection: close\n"
    time_now = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
    response += "Date: {now}\n".format(now=time_now)
    response += "Server: Simple-Python-Server\n"
    response += "Content-Type: text/html\n"
    response += "\r\n"
    return response

while True:
    print("Ready to serve...")
    connectionSocket, addr = serverSocket.accept()
    try:
        message = connectionSocket.recv(1024).decode()
        filename = message.split()[1][1:]
        f = open(filename)
        outputdata = f.read()
        response = buildResponse(200)
        response += outputdata
        connectionSocket.send(response.encode())
        connectionSocket.close()
    except IOError:
        response = buildResponse(404)
        connectionSocket.send(response.encode())
        connectionSocket.close()


from typing import Dict
from unittest import TestCase

from desplazamiento import CodificadorPorDesplazamiento, construir_diccionario_desplazamiento, aplicar_diccionario_encriptado, \
    DecodificadorPorDesplazamiento, cargar_diccionario

class DesplazamientoTest(TestCase):

    def test_construir_diccionario_desplazamiento(self):
        diccionario_esperado: Dict[str, str] = {'a': 'c', 'A': 'C', 'b': 'd', 'B': 'D', 'c': 'e', 'C': 'E', 'd': 'f',
                                                'D': 'F',
                                                'e': 'g', 'E': 'G', 'f': 'h', 'F': 'H', 'g': 'i', 'G': 'I', 'h': 'j',
                                                'H': 'J',
                                                'i': 'k', 'I': 'K', 'j': 'l', 'J': 'L', 'k': 'm', 'K': 'M', 'l': 'n',
                                                'L': 'N',
                                                'm': 'o', 'M': 'O', 'n': 'p', 'N': 'P', 'o': 'q', 'O': 'Q', 'p': 'r',
                                                'P': 'R',
                                                'q': 's', 'Q': 'S', 'r': 't', 'R': 'T', 's': 'u', 'S': 'U', 't': 'v',
                                                'T': 'V',
                                                'u': 'w', 'U': 'W', 'v': 'x', 'V': 'X', 'w': 'y', 'W': 'Y', 'x': 'z',
                                                'X': 'Z',
                                                'y': 'a', 'Y': 'A', 'z': 'b', 'Z': 'B'}

        self.assertEqual(construir_diccionario_desplazamiento(2), diccionario_esperado)

    def test_aplicar_diccionario_encripcion(self):
        diccionario_encriptado: Dict[str, str] = {'a': 'c', 'A': 'C', 'b': 'd', 'B': 'D', 'c': 'e', 'C': 'E', 'd': 'f',
                                                  'D': 'F',
                                                  'e': 'g', 'E': 'G', 'f': 'h', 'F': 'H', 'g': 'i', 'G': 'I', 'h': 'j',
                                                  'H': 'J',
                                                  'i': 'k', 'I': 'K', 'j': 'l', 'J': 'L', 'k': 'm', 'K': 'M', 'l': 'n',
                                                  'L': 'N',
                                                  'm': 'o', 'M': 'O', 'n': 'p', 'N': 'P', 'o': 'q', 'O': 'Q', 'p': 'r',
                                                  'P': 'R',
                                                  'q': 's', 'Q': 'S', 'r': 't', 'R': 'T', 's': 'u', 'S': 'U', 't': 'v',
                                                  'T': 'V',
                                                  'u': 'w', 'U': 'W', 'v': 'x', 'V': 'X', 'w': 'y', 'W': 'Y', 'x': 'z',
                                                  'X': 'Z',
                                                  'y': 'a', 'Y': 'A', 'z': 'b', 'Z': 'B'}
        self.assertEqual("jgnnq", aplicar_diccionario_encriptado("hello", diccionario_encriptado))

    def test_codificador_desplazamiento(self):
        codificador: CodificadorPorDesplazamiento = CodificadorPorDesplazamiento("hello", 2)
        diccionario_esperado: Dict[str, str] = {'a': 'c', 'A': 'C', 'b': 'd', 'B': 'D', 'c': 'e', 'C': 'E', 'd': 'f',
                                                'D': 'F',
                                                'e': 'g', 'E': 'G', 'f': 'h', 'F': 'H', 'g': 'i', 'G': 'I', 'h': 'j',
                                                'H': 'J',
                                                'i': 'k', 'I': 'K', 'j': 'l', 'J': 'L', 'k': 'm', 'K': 'M', 'l': 'n',
                                                'L': 'N',
                                                'm': 'o', 'M': 'O', 'n': 'p', 'N': 'P', 'o': 'q', 'O': 'Q', 'p': 'r',
                                                'P': 'R',
                                                'q': 's', 'Q': 'S', 'r': 't', 'R': 'T', 's': 'u', 'S': 'U', 't': 'v',
                                                'T': 'V',
                                                'u': 'w', 'U': 'W', 'v': 'x', 'V': 'X', 'w': 'y', 'W': 'Y', 'x': 'z',
                                                'X': 'Z',
                                                'y': 'a', 'Y': 'A', 'z': 'b', 'Z': 'B'}

        self.assertEqual(2, codificador.get_desplazamiento())
        self.assertEqual(diccionario_esperado, codificador.get_diccionario_desplazamiento())
        self.assertEqual("jgnnq", codificador.get_mensaje_encriptado())

        codificador.cambiar_desplazamiento(1)
        diccionario_esperado: Dict[str, str] = {'a': 'b', 'A': 'B', 'b': 'c', 'B': 'C', 'c': 'd', 'C': 'D', 'd': 'e',
                                                'D': 'E',
                                                'e': 'f', 'E': 'F', 'f': 'g', 'F': 'G', 'g': 'h', 'G': 'H', 'h': 'i',
                                                'H': 'I',
                                                'i': 'j', 'I': 'J', 'j': 'k', 'J': 'K', 'k': 'l', 'K': 'L', 'l': 'm',
                                                'L': 'M',
                                                'm': 'n', 'M': 'N', 'n': 'o', 'N': 'O', 'o': 'p', 'O': 'P', 'p': 'q',
                                                'P': 'Q',
                                                'q': 'r', 'Q': 'R', 'r': 's', 'R': 'S', 's': 't', 'S': 'T', 't': 'u',
                                                'T': 'U',
                                                'u': 'v', 'U': 'V', 'v': 'w', 'V': 'W', 'w': 'x', 'W': 'X', 'x': 'y',
                                                'X': 'Y',
                                                'y': 'z', 'Y': 'Z', 'z': 'a', 'Z': 'A'}

        self.assertEqual(1, codificador.get_desplazamiento())
        self.assertEqual("hello", codificador.get_texto_mensaje())
        self.assertEqual(diccionario_esperado, codificador.get_diccionario_desplazamiento())
        self.assertEqual("ifmmp", codificador.get_mensaje_encriptado())

    def test_decodificador_desplazamiento(self):
        decodificador: DecodificadorPorDesplazamiento = DecodificadorPorDesplazamiento("jqnc")
        self.assertEqual((2, "hola"), decodificador.descifrar_mensaje())
        self.assertEqual(cargar_diccionario("diccionario.txt"), decodificador.get_diccionario())


def read_matrix():
    (rows, columns) = map(int, input().split(", "))
    matrix = []
    for rows_index in range(rows):
        row = list(map(int, input().split(" ")))
        matrix.append(row)
    return matrix

def get_column_sum(matrix):
    rows_count = len(matrix)
    columns_counts = len(matrix[0])

    sums = []
    for column_index in range(columns_counts):
        sums.append(0)
        for rows_index in range(rows_count):
            sums[-1] += matrix[rows_index][column_index]
    return sums

def print_result(values):
    for x in values:
        print(x)

matrix = read_matrix()
result = get_column_sum(matrix)
print_result(result)


import subprocess
import time
from typing import Dict

from django.utils import timezone

import pandas as pd

from data_refinery_common.enums import PipelineEnum
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.models import (
    ComputationalResult,
    ComputationalResultAnnotation,
    ComputedFile,
    Experiment,
    Pipeline,
)
from data_refinery_common.utils import queryset_iterator
from data_refinery_workers.processors import smashing_utils, utils

logger = get_and_configure_logger(__name__)

def _prepare_input(job_context: Dict) -> Dict:

    # We're going to use the smasher outside of the smasher.
    # I'm not crazy about this yet. Maybe refactor later,
    # but I need the data now.
    job_context = smashing_utils.prepare_files(job_context)

    # work_dir is already created by smasher._prepare_files
    outfile_base = job_context["work_dir"] + str(time.time()).split(".")[0]
    job_context["target_file"] = outfile_base + "_target.tsv"

    return job_context

def _build_qn_target(job_context: Dict) -> Dict:
    """Iteratively creates a QN target file, method described here:
    https://github.com/AlexsLemonade/refinebio/pull/1013
    """
    job_context["time_start"] = timezone.now()

    # Get the gene list from the first input
    (computed_file, _) = job_context["input_files"]["ALL"][0]
    computed_file_path = computed_file.get_synced_file_path()
    geneset_target_frame = smashing_utils._load_and_sanitize_file(computed_file_path)

    # Get the geneset
    geneset = set(geneset_target_frame.index.values)

    # Sequentially build the target
    sum_frame_input = {"index": list(geneset), "sum": [0 for value in geneset]}
    sum_frame = pd.DataFrame(data=sum_frame_input)
    sum_frame = sum_frame.set_index("index")

    # Read and sum all of the inputs
    num_valid_inputs = 0
    for file, sample in job_context["input_files"]["ALL"]:
        try:
            input_filepath = file.get_synced_file_path()
            input_frame = smashing_utils._load_and_sanitize_file(input_filepath)
        except Exception:
            logger.warn(
                "No file loaded for input file",
                exc_info=1,
                bad_file=file,
                num_valid_inputs_so_far=num_valid_inputs,
            )
            continue

        # If this input doesn't have the same geneset, we don't want it!
        if set(input_frame.index.values) != geneset:
            logger.warn(
                "Input frame doesn't match target geneset, skipping!",
                bad_file=file,
                target_geneset_len=len(geneset),
                bad_geneset_len=len(input_frame.index.values),
                geneset_difference=list(geneset ^ set(input_frame.index.values))[:3],
                num_valid_inputs_so_far=num_valid_inputs,
            )
            continue

        # We don't want to build QNs that have Nulls in them, so
        # filter out any samples that still have null genes at this
        # point.
        num_nulls = input_frame.isnull().sum(axis=0)[0]
        if num_nulls != 0:
            logger.warn(
                "Input frame contains NA values, skipping!",
                bad_file=file,
                number_of_NAs=num_nulls,
                num_valid_inputs_so_far=num_valid_inputs,
            )
            continue

        # Sort the input
        sample_name = list(input_frame.columns.values)[0]
        expressions = input_frame.sort_values(sample_name)

        # Add the sorted input to the sum frame
        sum_frame["sum"] = sum_frame["sum"] + expressions[sample_name].values

        # We'll divide by this later
        num_valid_inputs = num_valid_inputs + 1

    # Divide our summation by the number of inputs and save the resulting object and metadata
    sum_frame["sum"] = sum_frame["sum"] / num_valid_inputs
    job_context["time_end"] = timezone.now()
    job_context["sum_frame"] = sum_frame
    job_context["num_valid_inputs"] = num_valid_inputs
    job_context["geneset"] = list(geneset)

    sum_frame.to_csv(
        job_context["target_file"], index=False, header=False, sep="\t", encoding="utf-8"
    )
    job_context["formatted_command"] = "qn_reference.py"

    return job_context

def _create_result_objects(job_context: Dict) -> Dict:
    if not job_context["create_results"]:
        return job_context

    result = ComputationalResult()
    result.commands.append(" ".join(job_context["formatted_command"]))
    result.is_ccdl = True
    result.is_public = True
    result.time_start = job_context["time_start"]
    result.time_end = job_context["time_end"]
    try:
        processor_key = "QN_REFERENCE"
        result.processor = utils.find_processor(processor_key)
    except Exception as e:
        return utils.handle_processor_exception(job_context, processor_key, e)
    result.save()

    computed_file = ComputedFile()
    computed_file.absolute_file_path = job_context["target_file"]
    computed_file.filename = job_context["target_file"].split("/")[-1]
    computed_file.calculate_sha1()
    computed_file.calculate_size()
    computed_file.is_smashable = False
    computed_file.is_qn_target = True
    computed_file.result = result
    computed_file.save()

    annotation = ComputationalResultAnnotation()
    annotation.result = result
    annotation.data = {
        "organism_id": job_context["samples"]["ALL"][0].organism_id,
        "is_qn": True,
        "platform_accession_code": job_context["samples"]["ALL"][0].platform_accession_code,
        "samples": [sample.accession_code for sample in job_context["samples"]["ALL"]],
        "geneset": str(job_context["geneset"]),
        "num_valid_inputs": job_context["num_valid_inputs"],
    }
    annotation.save()

    job_context["result"] = result
    job_context["computed_files"] = [computed_file]
    job_context["annotation"] = annotation
    job_context["success"] = True
    return job_context

def _update_caches(job_context: Dict) -> Dict:
    """Experiments have a cached value with the number of samples that have QN targets
    generated, this value should be updated after generating new QN targets."""
    if not job_context["create_results"]:
        # No new results were created, so there's no point in updating the cache
        return job_context

    organism = job_context["samples"]["ALL"][0].organism

    if job_context["result"]:
        # Associate the organism with the latest qn target that was generated for it
        organism.qn_target = job_context["result"]
        organism.save()

    unique_experiments = Experiment.objects.all().filter(organism=organism).distinct()

    for experiment in queryset_iterator(unique_experiments):
        experiment.update_num_samples()

    return job_context

def create_qn_reference(job_id: int, create_results=True) -> None:
    pipeline = Pipeline(name=PipelineEnum.QN_REFERENCE.value)
    job_context = utils.run_pipeline(
        {"job_id": job_id, "pipeline": pipeline, "create_results": create_results},
        [
            utils.start_job,
            _prepare_input,
            _build_qn_target,
            _create_result_objects,
            _update_caches,
            utils.end_job,
        ],
    )
    return job_context