from config import *
import socket

def main():
    sock = socket.socket()
    sock.connect((server, port))
    sock.send(f"PASS {token}\r\n".encode('utf-8'))
    sock.send(f"NICK {nickname}\r\n".encode('utf-8'))
    sock.send(f"JOIN {channel}\r\n".encode('utf-8'))

    while True:
        try:
            resp = sock.recv(2048).decode('utf-8')
            if resp.startswith('PING'):
                sock.send("PONG\n".encode('utf-8'))
            elif len(resp) > 0:
                print(resp)
        except KeyboardInterrupt:
            sock.close()
            exit()

if __name__ == '__main__':
    main()


import as3992_api
import thread
import sqlite3
import time

class TagRead:
    def __init__(self):
        self.ann = as3992_api.AntennaDevice()
        self.sw = True
        self.newInfo = False

    def scanStart():
        #self.sw = True
        try:
            thread.start_new_thread(main)
        except:
            pass

    def scanStop():
        self.sw = False

    def getTaginfo():
        return self.Taginfo

    def main():
        conn = sqlite3.connect("TagBase.db3")
        cursor = conn.cursor()

        ann.set_antenna_state(True)

        while self.sw:
            try:
                for epc, rssi in ann.iter_epc_rssi():
                    Time = time.strftime("%Y-%m-%d %H:%M:%S")
                    self.Taginfo = [str(epc.encode("HEX")),str(rssi),Time]
                    cursor.execute("INSERT INTO Taginfo VALUES(?,?,?)",Taginfo)
                    conn.commit()
                self.newInfo = True
            except:
                self.newInfo = False

            time.sleep(1)

if __name__ == "__main__":
    an = TagRead()
    an.main()


from django.contrib import admin
from blog.models import Post

class PostAdmin(admin.ModelAdmin):
    list_display = [
        'name',
        'title',
        'id',
        'summary',
        'created_date',
    ]

    class Meta:
        model = Post

admin.site.register(Post, PostAdmin)


#!pip install seaborn --upgrade

from google.colab import files
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# %matplotlib inline
sns.set(style="ticks")

# load file to analyze
#uploaded = files.upload()

# Будем анализировать данные только на обучающей выборке
data = pd.read_csv('mall-customers.csv', sep=",")

#параметры модели
customerId = 'CustomerID'           # Unique ID assigned to the customer
gender = 'Gender'                   # Gender of the customer
age = 'Age'                         # Age of the customer
annualIncome = 'Annual Income'      # Annual Income of the customee
customerScore = 'Spending Score'    # Score assigned by the mall based on customer behavior and spending nature

# В качестве целевого признака выберем Annual Income

# Первые 5 строк датасета
data.head()

# Размер датасета
data.shape

total_count = data.shape[0]
print('data at all: {}'.format(total_count))

# Список колонок
data.columns

# Список колонок с типами данных
data.dtypes

# Проверим наличие пустых значений
# Цикл по колонкам датасета
for col in data.columns:
    # Количество пустых значений - все значения заполнены
    temp_null_count = data[data[col].isnull()].shape[0]
    print('{} - {}'.format(col, temp_null_count))

# Основные статистические характеристки набора данных
data.describe()

# Определим уникальные значения для целевого признака
data[gender].unique()

# Диаграмма рассеяния
figure, axes = plt.subplots(figsize=(10,10))
sns.scatterplot(axes=axes, x=customerScore, y=annualIncome, data=data, hue=customerScore)

# Joint plot
sns.jointplot(x=age, y=customerScore, data=data, kind="kde", space=0, color="r")

# Joint plot
sns.jointplot(x=age, y=annualIncome, data=data, kind="kde", space=0, color="r")

# Парные диаграммы
sns.pairplot(data, hue=age)

# Распределение параметра Gender сгруппированные по SpendingScore.
sns.boxplot(x=gender, y=annualIncome, data=data)

# Violin plot
figure, axes = plt.subplots(2, 1, figsize=(10,10))
sns.violinplot(ax=axes[0], x=data[annualIncome])
sns.distplot(data[annualIncome], ax=axes[1])

# Heat map
# Треугольный вариант матрицы
mask = np.zeros_like(data.corr(), dtype=np.bool)
# чтобы оставить верхнюю часть матрицы
mask[np.tril_indices_from(mask)] = True
sns.heatmap(data.corr(), mask=mask, annot=True, fmt='.3f')

"""Из результатов анализа видно, данные слабо связанны друг с другом"""


import pytest
import jsonpath_ng as jp
import json

def test_config(api):
    config = api.prefix_config()
    config.a = "asdf"
    config.b = 1.1
    config.c = 1
    config.d_values = [config.A, config.B, config.C]
    config.e.e_a = 1.1
    config.e.e_b = 1.2
    config.f.f_a = "a"
    config.g.add(g_a="a g_a value")
    config.h = False
    config.i = "11011011"
    j1, j2 = config.j.jobject().jobject()
    assert j1 == j2
    config.k.e_object.e_a = 77.7
    config.k.f_object.f_a = "asdf"
    # assert j1.choice == j1._DEFAULTS["choice"]
    djson = json.loads(config.serialize(config.JSON))
    assert jp.parse("$.a").find(djson)[0].value == config.a
    assert jp.parse("$.f.f_a").find(djson)[0].value == config.f.f_a
    yaml = config.serialize(encoding=config.JSON)
    config.deserialize(yaml)
    print(yaml)

if __name__ == "__main__":
    pytest.main(["-v", "-s", __file__])


import pandas as pd
import matplotlib.pyplot as plt

dfdata = pd.read_csv('~/Xcode/git/playground/ft/data/df601111-day.csv',sep=',',low_memory=False)
#print(dfdata.head(10))
#print(dfdata.describe())

close_set = dfdata['close']

#close_set = pd.Series([i for i in range(200)])
#print(len(close_set))

nday = 1
#ma5 = [(i,"0") for i in range(nday-1)] + [(i+nday-1,"%.2f" % close_set[i:i+nday].mean()) for i in range(len(close_set)-nday+1) ]
ma5 = [(i,0) for i in range(nday-1)] + [(i+nday-1,close_set[i:i+nday].mean()) for i in range(len(close_set)-nday+1) ]

nday = 200
ma20 = [(i,0) for i in range(nday-1)] + [(i+nday-1,close_set[i:i+nday].mean()) for i in range(len(close_set)-nday+1) ]
#ma5 = [(i,"%.2f" % close_set[i+kk-k:i+kk-1].mean()) for i in range(len(close_set))]
#ma12 = [close_set[i:i+k].mean() for i in range(len(close_set)-k)]

#diff = []
x1=[]
y1=[]
for (_,val) in enumerate(ma5):
    x1.append(val[0])
    y1.append(val[1])

x2=[]
y2=[]
for (_,val) in enumerate(ma20):
    x2.append(val[0])
    y2.append(val[1])

print(y1)
print(y2)
#
k = [((y1[i]-y2[i])/y2[i]) for i in range(len(y1)) if y2[i] != 0]

#buyprice
#k = [(y1[i]-y2[i]) for i in range(len(y1))]
pdk = pd.Series(k)
print(pdk.describe())

#plt.figure()
#plt.subplot(211)
#plt.plot(x1,y1)
#plt.plot(x2,y2)

#plt.figure()

#plt.subplot(212)
plt.hist(k,100)

plt.show()
#print(ma5)
#print(ma20)


# 11. Hafta Odev 2:
# Bir cep telefonu objesi yapmanizi istiyoruz.
# Telefonun marka, model, uretim yili, tel nosu ve rehber
# ozelliklerinin(class attributes) olmasini bekliyoruz.
# Ayrica bu objenin rehbere no ekleme, silme, rehberi goruntuleme,
# rehberden secilen bir noyu arama(gostermelik) gibi ozelliklerinin

class telephone():
    def __init__(self, mark, model, man_date, tel_num, tel_list):
        self.mark = mark
        self.model = model
        self.man_date = man_date
        self.tel_num = tel_num
        self.tel_list = tel_list

    def add_sb(self, name, number):
        name = name.lower()
        self.tel_list.append([name, number])
        print('{} Added...'.format(name))
    def rem_list(self,name):
        name = name.lower()
        for i in self.tel_list:
            if name in i:
                self.tel_list.remove(i)
                print('Removed...')
                break
            else:
                print('Can`t Find')
                break

    def view_list(self):
        if len(self.tel_list) == 0:
            print('List Empty..')
        else:
            for i in self.tel_list:
                print("""
                      Name : {}
                      Number : {}
                      -----------
                      """.format(i[0], i[1]))
    def search_num(self, name):
        name = name.lower()
        for i in self.tel_list:
            if name in i:
                print('{} Calling...'.format(name))
            else:
                print('Not registered!')

my_telephone = telephone('Samsung', 'Note5', '2015', '06543210',[])
print('''
My telephone is created..
Mark: {}
Model: {}
Manufactured Date: {}
Number: {}
Telephone List: {}
'''.format(my_telephone.mark, my_telephone.model, my_telephone.man_date,
           my_telephone.tel_num, my_telephone.tel_list))

while True:
    print('Telephone List\n 1.Add to List\n' ' 2.Remove from the List\n', '3.Call theNumber\n',
           '4.View the Telephone List\n',  '5. Cikis icin "q" ya basin!')

    operation = input('Please choose your options:')

    if operation == '1':
        name = input('Add a name: ')
        number = input('Add a number: ')
        if number.isdigit() == True:
            my_telephone.add_sb(name, number)
        else:
            print('Please just write number!')
    elif operation == '2':
        name = input('Please write the name who you want: ')
        my_telephone.rem_list(name)
    elif operation == '3':
        name = input('Please write the name of who you call: ')
        my_telephone.search_num(name)
    elif operation == '4':
        my_telephone.view_list()
    elif operation == 'q':
        print('See you later..')
        break
    else:
        print('Ooppss.. Please try again..')

11. HAFTA 2. ODEV  CEP TELEFONU OBJESI.py


import blimpy as bl
import numpy as np
import tempfile
import sys
import os
sys.path.insert(0, '~/proxcen/turboSETI/turbo_seti_sofia/')
import turbo_seti_sofia.find_event_pipeline as find
import glob
from pathlib import Path
#import importlib
#importlib.reload(find_event_pipeline)

# Nodes with corresponding frequencies in MHz
freqDict = {
    'blc01' : '0704-0832',
    'blc02' : '0832-0960',
    'blc03' : '0960-1088',
    'blc04' : '1088-1216',
    'blc05' : '1216-1344',
    'blc06' : '1344-1472',
    'blc07' : '1472-1600',
    'blc10' : '1600-1728',
    'blc11' : '1728-1856',
    'blc12' : '1856-1984',
    'blc13' : '1984-2112',
    'blc14' : '2112-2240',
    'blc15' : '2240-2368',
    'blc16' : '2368-2496',
    'blc17' : '2496-2624',
    'blc20' : '2624-2752',
    'blc21' : '2752-2880',
    'blc22' : '2880-3008',
    'blc23' : '3008-3136',
    'blc24' : '3136-3264',
    'blc25' : '3264-3392',
    'blc26' : '3392-3520',
    'blc27' : '3520-3648',
    'blc30' : '3648-3776',
    'blc31' : '3776-3904',
    'blc32' : '3904-4032'
}

def step_through(cadence_list, cadence_length=6):

    filelist = open(cadence_list).read().splitlines()
    date = filelist[0].split('_')[-1].split('T')[0]
    node = filelist[0].split('/')[-1].split('_')[0]
    prefix = '/datax/scratch/ssmith/'+freqDict[node]+'/out'+date+'/'

    '''
    for i in range(len(filelist)-cadence_length+1):
        subfilelist = filelist[i:cadence_length+i]
        temp = tempfile.NamedTemporaryFile(suffix='.lst', mode='w+t')

        for file in subfilelist:
            datfile = prefix+str(Path(file.split('/')[-1]).with_suffix('.dat'))
            temp.writelines(datfile+'\n')
        temp.seek(0)

        if subfilelist[0].split('_')[2] == 'ProxCen':

        else:
            find.find_event_pipeline(temp.name,on_off_first='OFF',user_validation=True,number_in_cadence=cadence_length)
        temp.close()
     '''

# def search_all(file):

#     for i in range(2,7):
#         step_through(file, cadence_length=i)

freqList = list(freqDict.values())

from IPython.display import clear_output

for freq in freqList:

    input_dir = '20190429.txt,20190430.txt,20190501.txt,20190502.txt,20190503.txt,20190504.txt'
    search_list = input_dir.split(',')

    os.chdir('/mnt_home/ssmith/proxcen/turboSETI/search_dirs2/'+freq+'MHz')

    for txt in search_list:
        filelist = open(txt).read().splitlines()
        temp = tempfile.NamedTemporaryFile(suffix='.lst', mode='w+t')

        date = filelist[0].split('_')[-1].split('T')[0]
        node = filelist[0].split('/')[-1].split('_')[0]

        if int(freqDict[node].split('-')[0]) >= 2752:
            prefix = '/datax/scratch/ssmith/drift3-4/'+freqDict[node]+'/out'+date+'/'
        else:
            prefix = '/datax/scratch/ssmith/'+freqDict[node]+'/out'+date+'/'

        for file in filelist:
                datfile = prefix+str(Path(file.split('/')[-1]).with_suffix('.dat'))
                temp.writelines(datfile+'\n')
        temp.seek(0)

        for i in range(3,7):
            find.find_event_pipeline(temp.name,user_validation=True,number_in_cadence=i,filter_threshold=3)

        temp.close()
    clear_output(wait=True)


from django.conf.urls import include, url, patterns
from django.contrib import admin
from product.views import *
from myshopup import settings

urlpatterns = [
    # Examples:
    # url(r'^$', 'myshopup.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^product_list/', ProductView.as_view(), name='productview'),
    url(r'^product_purchase/', ProductPurchase.as_view(), name='productpurchase'),
]

urlpatterns += patterns("",
        (r'^media/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': settings.MEDIA_ROOT, 'show_indexes': True }),
                        (r'^static/(?P<path>.*)$', 'django.views.static.serve',
                         {'document_root': settings.STATIC_ROOT, 'show_indexes': True})
                        )


from django.shortcuts import render,redirect
from .models import User
from .forms import UserForm
from django.contrib import messages

# Create your views here.
def firstApp(request):
    uf=UserForm(request.POST)
    if request.method=="POST":
        if uf.is_valid():
            name=uf.cleaned_data['name']
            email=uf.cleaned_data['email']
            phno=uf.cleaned_data['phoneno']
            age=uf.cleaned_data['age']
            dob=uf.cleaned_data['dob']
            uf.name=name
            uf.email=email
            uf.phoneno=phno
            uf.age=age
            uf.dob=dob
            uf.save()
            messages.success(request,"User Details saved successfully")
            return redirect('secondapp')

        else:
            return render(request,"index.html",{'uf':uf})

    return render(request,"index.html",{'uf':uf})

def secondApp(request):
    if request.method =='POST':
        name=request.POST.get('n1')
        try:
            Ud=User.objects.filter(name__icontains=name)
            #print(Ud)
            return render(request,"userDet.html",{'ud':Ud})
        except User.DoesNotExist:
            return render(request,"userDet.html",{"error":"Details Doesnt Exists...!"})
    else:
        return render(request,"userDet.html")


# coding: utf-8

import typing
import inspect
import ctypes

from abc import ABCMeta, abstractmethod
from .deprecated import deprecated

import logging
logger = logging.getLogger(__name__)

class ClosingContextManager(metaclass=ABCMeta):
    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        if exc_info != (None, None, None):
            logger.exception("")
        self.close()

    @abstractmethod
    def close(self):
        pass

_STRING_BOOLEAN_MAPPING = {
    '1': True, 'yes': True, 'true': True, 'on': True,
    '0': False, 'no': False, 'false': False, 'off': False
}

@deprecated("use get_boolean instead")
def get_boolean_from_string(s: str) -> bool:
    if s.lower() not in _STRING_BOOLEAN_MAPPING:
        raise ValueError('Not a boolean: %s' % s)
    return _STRING_BOOLEAN_MAPPING[s.lower()]

def get_boolean(x: typing.Union[int, bool, str]) -> bool:
    if isinstance(x, str):
        if x.lower() not in _STRING_BOOLEAN_MAPPING:
            raise ValueError('Not a boolean: %s' % x)
        return _STRING_BOOLEAN_MAPPING[x.lower()]
    else:
        return bool(x)

def is_inherited_from_base_classes(cls: type, method_name: str, ignore_abstract: bool=False) -> bool:
    inherited = False
    for mro in cls.__mro__[1:]:
        if ignore_abstract and inspect.isabstract(mro):
            continue

        if hasattr(mro, method_name):
            inherited = True
            break
    return inherited

def ctypes_structure_to_dict(obj, recursive: bool=True) -> dict:
    d = {}
    for field in getattr(obj, "_fields_"):
        name = field[0]
        value = getattr(obj, name)
        if isinstance(value, ctypes.Structure) and recursive:
            value = ctypes_structure_to_dict(value)
        d[name] = value
    return d

def evaluate(s: str, global_context: dict=None, local_context: dict=None):
    import re
    import pydoc
    context = local_context or locals()
    try:
        return eval(s, global_context or globals(), context)
    except NameError as err:
        message = str(err)
        logger.debug(message)
        match = re.search(r"name '(\w+)' is not defined", message)
        if match:
            name = match.group(1)
            value = pydoc.locate(name)
            context[name] = value
            logger.debug("add (%s, %s) into context and re-evaluate.", name, value)
            return evaluate(s, global_context, context)

def get_class_that_defined_method(method):
    if inspect.ismethod(method):
        for cls in inspect.getmro(method.__self__.__class__):
            if cls.__dict__.get(method.__name__) is method:
                return cls
        method = method.__func__  # fallback to __qualname__ parsing
    if inspect.isfunction(method):
        cls = getattr(inspect.getmodule(method),
                      method.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0])
        if isinstance(cls, type):
            return cls
    return getattr(method, '__objclass__', None)  # handle special descriptor objects


from django.contrib import messages
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from reservation.forms import ReservationCreateForm
from reservation.models import Reservation

class ReservationCreateView(View):
    def get(self, request):
        form = ReservationCreateForm()
        return render(request, 'reservation/create.html', {'form': form})

    def post(self, request):
        form = ReservationCreateForm(request.POST)

        if form.is_valid():
            form.save()
            name = form.cleaned_data.get('name')
            messages.success(request, '<strong>{}</strong>님의 예약이 정상적으로 접수되었습니다.'.format(name), 'success')
            return redirect(reverse('reservation:create'))

        return render(request, 'reservation/create.html', {'form': form})

class ReservationListView(View):
    def get(self, request):
        reservation_list = Reservation.objects.all()
        return render(request, 'reservation/list.html', {'reservation_list': reservation_list})


# coding=utf-8
# Copyright (C) 2019  Luis Felipe Mileo - KMEE

from __future__ import division, print_function, unicode_literals

from erpbrasil.edoc.nfse import NFSe, ServicoNFSe

from nfselib.ginfes.v3_01 import servico_consultar_situacao_lote_rps_envio_v03 as consulta_situacao_lote
from nfselib.ginfes.v3_01 import servico_consultar_lote_rps_envio_v03 as servico_consultar_lote_rps_envio
from nfselib.ginfes.v3_01 import servico_enviar_lote_rps_resposta_v03 as servico_enviar_lote_rps_resposta
from nfselib.ginfes.v3_01 import servico_consultar_situacao_lote_rps_resposta_v03 as servico_consultar_situacao_lote_rps_resposta
from nfselib.ginfes.v3_01 import servico_consultar_lote_rps_resposta_v03 as servico_consultar_lote_rps_resposta
from nfselib.ginfes.v3_01.cabecalho_v03 import cabecalho
from nfselib.ginfes.v3_01.tipos_v03 import tcIdentificacaoPrestador

endpoint = 'ServiceGinfesImpl?wsdl'

servicos = {
    'envia_documento': ServicoNFSe(
        'RecepcionarLoteRpsV3',
        endpoint, servico_enviar_lote_rps_resposta, True),
    'consulta_recibo': ServicoNFSe(
        'ConsultarSituacaoLoteRpsV3',
        endpoint, servico_consultar_situacao_lote_rps_resposta, True),
    'consultar_lote_rps': ServicoNFSe(
        'ConsultarLoteRpsV3',
        endpoint, servico_consultar_lote_rps_resposta, True),
}

class Ginfes(NFSe):

    _header = cabecalho(versao="3", versaoDados="3")

    def __init__(self, transmissao, ambiente, cidade_ibge, cnpj_prestador,
                 im_prestador):

        if ambiente == '2':
            self._url = 'https://homologacao.ginfes.com.br'
        else:
            self._url = 'https://homologacao.ginfes.com.br'
            # self._url = 'https://producao.ginfes.com.br'
        self._servicos = servicos

        super(Ginfes, self).__init__(
            transmissao, ambiente, cidade_ibge, cnpj_prestador, im_prestador)

    def get_documento_id(self, edoc):
        # edoc.LoteRps.ListaRps.Rps[0].InfRps.Id
        return edoc.LoteRps.Id, edoc.LoteRps.NumeroLote

    def _prepara_envia_documento(self, edoc):
        numero_lote = self._gera_numero_lote()
        edoc.LoteRps.Id = 'lote' + numero_lote
        edoc.LoteRps.NumeroLote = numero_lote
        #
        # Assinamos todas as RPS e o Lote
        #
        xml_assinado = edoc
        for rps in edoc.LoteRps.ListaRps.Rps:
            xml_assinado = self.assina_raiz(xml_assinado, rps.InfRps.Id)
        # Assinamos o lote
        xml_assinado = self.assina_raiz(xml_assinado, edoc.LoteRps.Id)
        return xml_assinado

    def _prepara_consulta_recibo(self, proc_envio):

        raiz = consulta_situacao_lote.ConsultarSituacaoLoteRpsEnvio(
            Id=self._gera_numero_lote(),
            Prestador=tcIdentificacaoPrestador(
                Cnpj=self.cnpj_prestador,
                InscricaoMunicipal=self.im_prestador
            ),
            Protocolo=proc_envio.resposta.Protocolo
        )
        xml_assinado = self.assina_raiz(raiz,raiz.Id)
        return xml_assinado

    def _prepara_consultar_lote_rps(self, protocolo):
        raiz = servico_consultar_lote_rps_envio.ConsultarLoteRpsEnvio(
            Id=self._gera_numero_lote(),
            Prestador=tcIdentificacaoPrestador(
                Cnpj=self.cnpj_prestador,
                InscricaoMunicipal=self.im_prestador
            ),
            Protocolo=protocolo
        )
        xml_assinado = self.assina_raiz(raiz, raiz.Id)
        return xml_assinado

    def _verifica_resposta_envio_sucesso(self, proc_envio):
        if proc_envio.resposta.Protocolo:
            return True
        return False

    def _edoc_situacao_em_processamento(self, proc_recibo):
        if proc_recibo.resposta.Situacao == 2:
            return True
        return False

    # def processar_documento(self, edoc):
    #     processo = super(NFSe, self).processar_documento(edoc)
    #
    #     ultimo_processo = None
    #     for p in processo:
    #         ultimo_processo = p
    #
    #     if ultimo_processo.webservice == u'ConsultarSituacaoLoteRpsV3':
    #         if processo.resposta.Situacao == 1:
    #             print('Não Recebido')
    #
    #         elif ultimo_processo.resposta.Situacao == 2:
    #             print('Lote ainda não processado')
    #
    #         elif ultimo_processo.resposta.Situacao == 3:
    #             print('Procesado com Erro')
    #
    #         elif ultimo_processo.resposta.Situacao == 4:
    #             print('Procesado com Sucesso')
    #


#!/usr/bin/env python
"""
Server statistic
"""
import datetime
import logging.config

from flask import Flask
from flask import render_template
from flask import Response
from app.models.get_statisctic import Monitor

app = Flask(__name__)
app.debug = True
app.secret_key = 'A0Zr*`98j/3y*X R~XHH`!jmN`]LWX/,?RT'
logging.config.fileConfig('logging.conf')

@app.route("/", methods=['GET'])
def index_get():
    '''Method gets the index page of the site with GET method'''
    return render_template('index.html')

@app.route("/", methods=['POST'])
def index_post():
    '''Method gets the index page of the site with POST method'''
    return render_template('index.html')

@app.route("/get/<statname>", methods=['GET'])
def get_server_statistic_get(statname):
    '''Method gets server statistics at current time
    :Parameters
        <statname> - str, name of statistics
    :Return - json
    '''
    if statname == 'cpu_times':
        return Response(Monitor().get_cpu_times(),
                        mimetype='application/json')
    elif statname == 'virtual_memory':
        return Response(Monitor().get_virtual_memory(),
                        mimetype='application/json')
    elif statname == 'swap_memory':
        return Response(Monitor().get_swap_memory(),
                        mimetype='application/json')
    elif statname == 'disk_usage':
        return Response(Monitor().get_disk_usage(),
                        mimetype='application/json')
    elif statname == 'io_counters':
        return Response(Monitor().get_io_counters(),
                        mimetype='application/json')
    else:
        return Response('page_not_found'), 404

@app.route("/fetch/<statname>", methods=['GET'])
def fetch_server_statistic_get(statname):
    '''Method gets server statistics for current day
    :Parameters
        <statname> - str, name of statistics
    :Return - json
    '''
    date = "LIKE '{0}{1}'".format(datetime.datetime.now().strftime('%Y-%m-%d'),
                                  '%')
    if statname == 'cpu':
        return Response(Monitor().fetch_cpu(date), mimetype='application/json')
    elif statname == 'virtual_memory':
        return Response(Monitor().fetch_virtual_memory(date),
                        mimetype='application/json')
    elif statname == 'swap_memory':
        return Response(Monitor().fetch_swap_memory(date),
                        mimetype='application/json')
    elif statname == 'dick_usage':
        return Response(Monitor().fetch_dick_usage(date),
                        mimetype='application/json')
    elif statname == 'io_counters':
        return Response(Monitor().fetch_io_counters(date),
                        mimetype='application/json')
    else:
        return Response('page_not_found'), 404

@app.errorhandler(404)
def page_not_found(error):
    '''Method return 404 response for not existing pages'''
    return Response('page_not_found'), 404

if __name__ == "__main__":
    app.run(host='0.0.0.0')


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

df = pd.read_csv("./Datasets/Synthesized datasets/analysis_county_data.csv")
df = df[df["crime_rate_per_100000"] != 0]

rentSize = 10
rentSplits = np.linspace(min(df["Rent50_0"]), max(df["Rent50_0"])+1, rentSize)
incomeSize = 10
incomeSplits = np.linspace(min(df["Median_household_income"]), max(df["Median_household_income"])+1, incomeSize)
incomeSplits = [round(x) for x in incomeSplits]

matrix = np.zeros((rentSize-1, incomeSize-1))
for i in range(len(df)):
    rent = df.iloc[i]["Rent50_0"]
    income = df.iloc[i]["Median_household_income"]
    for j in range(1, rentSize+1):
        for k in range(1, incomeSize+1):
            if (rent >= rentSplits[j-1] and rent < rentSplits[j]) and (income >= incomeSplits[k-1] and income < incomeSplits[k]):
                matrix[j-1, k-1] += 1

matrix2 = np.zeros((rentSize-1, incomeSize-1))
for i in range(len(df)):
    rent = df.iloc[i]["Rent50_0"]
    income = df.iloc[i]["Median_household_income"]
    for j in range(1, rentSize+1):
        for k in range(1, incomeSize+1):
            if (rent >= rentSplits[j-1] and rent < rentSplits[j]) and (income >= incomeSplits[k-1] and income < incomeSplits[k]):
                matrix2[j-1, k-1] += df.iloc[i]["crime_rate_per_100000"]

averageCrimeRate = np.empty((rentSize-1, incomeSize-1))
for i in range(matrix.shape[0]):
    for j in range(matrix.shape[1]):
        averageCrimeRate[i, j] = 0 if matrix[i, j] == 0 else round(matrix2[i, j]/matrix[i, j], 2)

# colormap
coolwarm = cm.get_cmap('coolwarm', 256)
newcolors = coolwarm(np.linspace(0, 1, 256))
white = np.array([256/256, 256/256, 256/256, 1])
newcolors[1:20, :] = white
newcmp = ListedColormap(newcolors)

# plot it
#ms = plt.matshow(averageCrimeRate, cmap=plt.cm.Blues)
ms = plt.contourf(range(rentSize-1), range(incomeSize-1), averageCrimeRate, cmap=newcmp)
plt.colorbar(ms, label="average crime per 100000 per section")
plt.xlabel("Rent per county")
plt.xticks(range(rentSize-1), rentSplits, rotation=90)
plt.ylabel("Income")
plt.yticks(range(incomeSize-1), incomeSplits)
plt.title("Contour plot of Rent vs Income with Crime as color")
plt.show()


# put your python code here
hours_first = int(input())
minutes_first = int(input())
seconds_first = int(input())

hours_second = int(input())
minutes_second = int(input())
seconds_second = int(input())

result = abs(
        (hours_first * 3600 + minutes_first * 60 + seconds_first) - (
                hours_second * 3600 + minutes_second *60 + seconds_second
        ))
print(result)


from sys import stdin

def min_smoke(colors):
    d = {}
    def f(l, r):
        if r - l == 1:
            return 0, colors[l]
        if (l, r) in d:
            return d[(l, r)]
        ms, mc = float("inf"), None
        for m in range(l + 1, r):
            s1, c1 = f(l, m)
            s2, c2 = f(m, r)
            if s1 + s2 + c1*c2 < ms:
                ms = s1 + s2 + c1*c2
                mc = (c1 + c2)%100
        d[(l, r)] = ms, mc
        return ms, mc
    smoke, color = f(0, len(colors))
    return smoke

while stdin.readline():
    colors = [int(x) for x in stdin.readline().split()]
    print(min_smoke(colors))


"""The public API."""

#pylint: disable=no-member,unused-argument

import datetime
import logging
import ast
import requests

from flask.views import View
from flask.app import request, json
from flask import session, make_response, redirect
from webargs import Arg
from webargs.flaskparser import FlaskParser
from app.constants import STUDENT_ROLE, STAFF_ROLE, API_PREFIX

from app import models, app, analytics
from app.codereview import compare
from app.needs import Need
from app.utils import paginate, filter_query, create_zip
from app.utils import add_to_grading_queues, parse_date, assign_submission
from app.utils import merge_user

from app.exceptions import *

from google.appengine.ext import ndb
from google.appengine.ext import deferred
from google.appengine.ext.ndb import stats
from google.appengine.api import memcache

parser = FlaskParser()

def parse_json_field(field):
    """
    Parses field or returns appropriate boolean value.

    :param field: (string)
    :return: (string) parsed JSON
    """
    if not field[0] == '{':
        if field == 'false':
            return False
        elif field == 'true':
            return True
        return field
    return json.loads(field)

def parse_json_list_field(field):
    """
    Parses field or returns appropriate boolean value.

    :param field: (string)
    :return: (string) parsed JSON
    """
    if not field[0] == '[':
        if field == 'false':
            return False
        elif field == 'true':
            return True
        return field
    return json.loads(field)
# Arguments to convert query strings to a python type

def DateTimeArg(**kwds):
    """
    Converts a webarg to a datetime object

    :param kwds: (dictionary) set of parameters
    :return: (Arg) type of argument
    """
    def parse_date(arg):
        op = None
        if '|' in arg:
            op, arg = arg.split('|', 1)

        date = datetime.datetime.strptime(arg,
                                          app.config['GAE_DATETIME_FORMAT'])
        delta = datetime.timedelta(hours=7)
        date = (datetime.datetime.combine(date.date(), date.time()) + delta)
        return (op, date) if op else date
    return Arg(None, use=parse_date, **kwds)

MODEL_VERSION = 'v2'

def try_int(x):
    try:
        return int(x)
    except (ValueError, TypeError):
        return x

def KeyArg(cls, **kwds):
    """
    Converts a webarg to a key in Google's ndb.

    :param cls: (string) class
    :param kwds: (dictionary) -- unused --
    :return: (Arg) type of argument
    """
    def parse_key(key):
        key = try_int(key)
        return {'pairs': [(cls + MODEL_VERSION, key)]}
    return Arg(ndb.Key, use=parse_key, **kwds)

def KeyRepeatedArg(cls, **kwds):
    """
    Converts a repeated argument to a list

    :param cls: (string)
    :param kwds: (dictionary) -- unused --
    :return: (Arg) type of argument
    """
    def parse_list(key_list):
        staff_lst = key_list
        if not isinstance(key_list, list):
            if ',' in key_list:
                staff_lst = key_list.split(',')
                staff_lst = map(try_int, staff_lst)
            else:
                staff_lst = [try_int(key_list)]
        return [ndb.Key(cls + MODEL_VERSION, x) for x in staff_lst]
    return Arg(None, use=parse_list, **kwds)

def BooleanArg(**kwargs):
    """
    Converts a webarg to a boolean.

    :param kwargs: (dictionary) -- unused --
    :return: (Arg) type of argument
    """
    def parse_bool(arg):
        if isinstance(arg, bool):
            return arg
        if arg == 'false':
            return False
        if arg == 'true':
            return True
        raise BadValueError(
            "malformed boolean %s: either 'true' or 'false'" % arg)
    return Arg(None, use=parse_bool, **kwargs)

class APIResource(View):
    """
    Base class for API Resource. Set models for each.
    """

    model = None
    methods = {}
    key_type = int
    api_version = 'v1'

    @property
    def name(self):
        return self.model.__name__

    def get_instance(self, key, user):
        """
        Get instance of the object, checking against user privileges.

        :param key: (int) ID of object
        :param user: (object) user object
        :return: (object, Exception)
        """
        obj = self.model.get_by_id(key)
        if not obj:
            raise BadKeyError(key)

        need = Need('get')
        if not obj.can(user, need, obj):
            raise need.exception()
        return obj

    def call_method(self, method_name, user, http_method,
                    instance=None, is_index=False):
        """
        Call method if it exists and if it's properly called.

        :param method_name: (string) name of desired method
        :param user: (object) caller
        :param http_method: (string) get, post, put, or delete
        :param instance: (string)
        :param is_index: (bool) whether or not this is an index call
        :return: result of called method
        """
        if method_name not in self.methods:
            raise BadMethodError('Unimplemented method %s' % method_name)
        constraints = self.methods[method_name]
        if 'methods' in constraints:
            if http_method is None:
                raise IncorrectHTTPMethodError('Need to specify HTTP method')
            if http_method not in constraints['methods']:
                raise IncorrectHTTPMethodError('Bad HTTP Method: %s'
                                               % http_method)
        data = {}
        web_args = constraints.get('web_args', {})
        data = self.parse_args(web_args, user, is_index=is_index)
        method = getattr(self, method_name)
        if instance is not None:
            return method(instance, user, data)
        return method(user, data)

    def dispatch_request(self, path, *args, **kwargs):
        """
        "Does the request dispatching. Matches the URL and returns
        the return value of the view or error handler. This does
        not have to be a response object."
        - http://flask.pocoo.org/docs/0.10/api/

        :param path: (string) full URL
        :param args: (list)
        :param kwargs: (dictionary)
        :return: result of an attempt to call method
        """
        http_method = request.method.upper()
        user = session['user']

        if path is None:  # Index
            if http_method not in ('GET', 'POST'):
                raise IncorrectHTTPMethodError('Incorrect HTTP method: %s')
            method_name = {'GET': 'index', 'POST': 'post'}[http_method]
            return self.call_method(method_name, user, http_method,
                                    is_index=(method_name == 'index'))

        path = path.split('/')
        if len(path) == 1:
            entity_id = path[0]
            try:
                key = self.key_type(entity_id)
            except (ValueError, AssertionError):
                raise BadValueError('Invalid key. Needs to be of type: %s'
                                    % self.key_type)
            instance = self.get_instance(key, user)
            method_name = http_method.lower()
            return self.call_method(method_name, user, http_method,
                                    instance=instance)

        entity_id, method_name = path
        try:
            key = self.key_type(entity_id)
        except (ValueError, AssertionError):
            raise BadValueError('Invalid key. Needs to be of type: %s'
                                % self.key_type)
        instance = self.get_instance(key, user)
        return self.call_method(method_name, user, http_method,
                                instance=instance)

    def get(self, obj, user, data):
        """
        GET HTTP method

        :param obj: (object) target
        :param user: -- unused --
        :param data: -- unused --
        :return: target object
        """
        return obj

    def put(self, obj, user, data):
        """
        The PUT HTTP method
        """
        need = Need('put')
        if not obj.can(user, need, obj):
            raise need.exception()

        blank_val = object()
        changed = False
        for key, value in data.iteritems():
            old_val = getattr(obj, key, blank_val)
            if old_val == blank_val:
                return 400, '{} is not a valid field.'.format(key)

            setattr(obj, key, value)
            changed = True

        if changed:
            obj.put()

        return obj

    def post(self, user, data):
        """
        PUT HTTP method

        :param obj: (object) target
        :param user: (object) caller
        :param data: -- unused --
        :return: target
        """
        entity = self.new_entity(data)

        need = Need('create')
        if not self.model.can(user, need, obj=entity):
            raise need.exception()

        entity.put()

        return (201, 'success', {
            'key': entity.key.id()
        })

    def new_entity(self, attributes):
        """
        Creates a new entity with given attributes.

        :param attributes: (dictionary)
        :return: (entity, error_response) should be ignored if error_response
        is a True value
        """
        return self.model.from_dict(attributes)

    def delete(self, obj, user, data):
        """
        DELETE HTTP method

        :param obj: (object) target
        :param user: (object) caller
        :param data: -- unused --
        :return: None
        """
        need = Need('delete')
        if not self.model.can(user, need, obj=obj):
            raise need.exception()

        obj.key.delete()

    def parse_args(self, web_args, user, is_index=False):
        """
        Parses the arguments to this API call.

        :param web_args: (string) arguments passed as querystring
        :param user: (object) caller
        :param is_index: (bool) whether or not this is an index call
        :return: (dictionary) mapping keys to values in web arguments
        """
        fields = parser.parse({
            'fields': Arg(None, use=parse_json_field)
        })
        if fields['fields'] is None:
            fields['fields'] = {}
        if type(fields['fields']) != dict and type(fields['fields']) != bool:
            raise BadValueError('fields should be dictionary or boolean')
        request.fields = fields
        return {k: v for k, v in parser.parse(web_args).iteritems()
                if v is not None}

    def index(self, user, data):
        """
        Index HTTP method. Should be called from GET when no key is provided.

        Processes cursor and num_page URL arguments for pagination support.

        :param user: (object) caller
        :param data: (dictionary)
        :return: results for query
        """
        query = self.model.query()
        need = Need('index')

        result = self.model.can(user, need, query=query)
        if not result:
            raise need.exception()

        query = filter_query(result, data, self.model)
        created_prop = getattr(self.model, 'created', None)
        if not query.orders and created_prop:
            logging.info('Adding default ordering by creation time.')
            query = query.order(-created_prop, self.model.key)

        page = int(request.args.get('page', 1))
        # default page length is 100
        num_page = int(request.args.get('num_page', 100))
        query_results = paginate(query, page, num_page)

        add_statistics = request.args.get('stats', False)
        if add_statistics:
            query_results['statistics'] = self.statistics()
        return query_results

    def statistics(self):
        """
        Provide statistics for any entity.

        :return: (dictionary) empty or a 'total' count
        """
        stat = stats.KindStat.query(
            stats.KindStat.kind_name == self.model.__name__).get()
        if stat:
            return {
                'total': stat.count
            }
        return {}

class UserAPI(APIResource):
    """
    The API resource for the User Object
    """
    model = models.User
    key_type = str # get_instance will convert this to an int

    methods = {
        'post': {
            'web_args': {
                'email': Arg(str),
                'name': Arg(str),
                }
        },
        'add_email': {
            'methods': set(['PUT']),
            'web_args': {
                'email': Arg(str)
            }
        },
        'delete_email': {
            'methods': set(['PUT']),
            'web_args': {
                'email': Arg(str)
            }
        },
        'get': {
            'web_args': {
                'course': KeyArg('Course')
             }
        },
        'index': {
        },
        'invitations': {
            'methods': set(['GET']),
            'web_args': {
                'assignment': KeyArg('Assignment')
            }
        },
        'queues': {
            'methods': set(['GET'])
        },
        'create_staff': {
            'methods': set(['POST']),
            'web_args': {
                'email': Arg(str, required=True),
                'role': Arg(str, required=True),
                }
        },
        'final_submission': {
            'methods': set(['GET']),
            'web_args': {
                'assignment': KeyArg('Assignment', required=True)
            }
        },
        'get_backups': {
            'methods': set(['GET']),
            'web_args': {
                'assignment': KeyArg('Assignment', required=True),
                'quantity': Arg(int, default=10)
            }
        },
        'get_submissions': {
            'methods': set(['GET']),
            'web_args': {
                'assignment': KeyArg('Assignment', required=True),
                'quantity': Arg(int, default=10)
            }
        },
        'timed_submission': {
            'methods': set(['GET']),
            'web_args': {
                'assignment': KeyArg('Assignment', required=True),
                'before': DateTimeArg()
            }
        },
        'merge_user': {
            'methods': set(['POST']),
            'web_args': {
                'other_email': Arg(str, required=True),
            }
        },
    }

    def get(self, obj, user, data):
        """
        Overwrite GET request for user class in order to send more data.

        :param obj: (object) target
        :param user: -- unused --
        :param data: -- unused --
        :return: target object
        """
        if 'course' in data:
            return obj.get_course_info(data['course'].get())
        return obj

    def get_instance(self, key, user):
        """
        Convert key from email to UserKey
        """
        obj = self.model.lookup(key)
        if not obj:
            raise BadKeyError(key)

        need = Need('get')
        if not obj.can(user, need, obj):
            raise need.exception()

        return obj

    def new_entity(self, attributes):
        """
        Creates a new entity with given attributes.

        :param attributes: (dictionary) default values
            loaded on object instantiation
        :return: entity with loaded attributes
        """
        entity = self.model.lookup(attributes['email'])
        if entity:
            raise BadValueError('user already exists')
        attributes['email'] = [attributes['email']]
        entity = self.model.from_dict(attributes)
        return entity

    def add_email(self, obj, user, data):
        """
        Adds an email for the user - modified in place.

        :param obj: (object) target
        :param user: (object) caller
        :param data: -- unused --
        :return: None
        """
        need = Need('get') # Anyone who can get the User object can add an email
        if not obj.can(user, need, obj):
            raise need.exception()
        obj.append_email(data['email'])

    def delete_email(self, obj, user, data):
        """
        Deletes an email for the user - modified in place.

        :param obj: (object) target
        :param user: (object) caller
        :param data: (dictionary) key "email" deleted
        :return: None
        """
        need = Need('get')
        if not obj.can(user, need, obj):
            raise need.exception()
        obj.delete_email(data['email'])

    def invitations(self, obj, user, data):
        """
        Fetches list of all invitations for the caller.

        :param obj: -- unused --
        :param user: (object) caller
        :param data: (dictionary) key assignment called
        :return: None
        """
        query = models.Group.query(models.Group.invited == user.key)
        if 'assignment' in data:
            query = query.filter(models.Group.assignment == data['assignment'])
        return list(query)

    def queues(self, obj, user, data):
        """
        Retrieve all assignments given to the caller on staff

        :param obj: -- unused --
        :param user: (object) caller
        :param data: -- unused --
        :return: None
        """
        return list(models.Queue.query().filter(
            models.Queue.assigned_staff == user.key))

    def create_staff(self, obj, user, data):
        """
        Checks the caller is on staff, to then create staff.

        :param obj: (object) target
        :param user: (object) caller
        :param data: (dictionary) key email called
        :return: None
        """
        need = Need('staff')
        if not obj.can(user, need, obj):
            raise need.exception()

        user = models.User.get_or_insert(data['email'].id())
        user.role = data['role']
        user.put()

    def final_submission(self, obj, user, data):
        """
        Get the final submission for grading.

        :param obj: -- unused --
        :param user: (object) caller
        :param data: (dictionary) key assignment called
        :return: None
        """
        return obj.get_final_submission(data['assignment'])

    def get_backups(self, obj, user, data):
        """
        Get all backups for a user, based on group.

        :param obj: -- unused --
        :param user: (object) caller
        :param data: (dictionary) key assignment called
        :return: None
        """
        return obj.get_backups(data['assignment'], data['quantity'])

    def get_submissions(self, obj, user, data):
        return obj.get_submissions(data['assignment'], data['quantity'])

    def timed_submission(self, obj, user, data):
        return obj.get_submission_before(data['assignment'], data['before'])

    def merge_user(self, obj, user, data):
        """
        Merges this user with another user.
        This user is the user that is "merged" -- no longer can login.
        """
        need = Need('merge')
        if not obj.can(user, need, obj):
            raise need.exception()

        other_user = models.User.lookup(data['other_email'])
        if not other_user:
            raise BadValueError("Invalid user to merge to")

        merge_user(obj, other_user)

class AssignmentAPI(APIResource):
    """
    The API resource for the Assignment Object
    """
    model = models.Assignment

    methods = {
        'post': {
            'web_args': {
                'name': Arg(str, required=True),
                'display_name': Arg(str, required=True),
                'points': Arg(float, required=True),
                'course': KeyArg('Course', required=True),
                'max_group_size': Arg(int, required=True),
                'due_date': DateTimeArg(required=True),
                'templates': Arg(str, use=lambda temps: json.dumps(temps),
                                 required=True),
                }
        },
        'put': {
            'web_args': {
                'name': Arg(str),
                'display_name': Arg(str),
                'points': Arg(float),
                'course': KeyArg('Course'),
                'max_group_size': Arg(int),
                'due_date': DateTimeArg(),
                'templates': Arg(str, use=lambda temps: json.dumps(temps)),
                }
        },
        'get': {
        },
        'index': {
            'web_args': {
                'course': KeyArg('Course'),
                'active': BooleanArg(),
                'name': Arg(str),
                'points': Arg(int)
            }
        },
        'invite': {
            'methods': set(['POST']),
            'web_args': {
                'email': Arg(str, required=True)
            }
        },
        'group': {
          'methods': set(['GET']),
        },
        'assign': {
            'methods': set(['POST'])
        }
    }

    def post(self, user, data):
        """
        :param user:
        :param data:
        :return:
        """
        data['creator'] = user.key
        # check if the course actually exists
        course = data['course'].get()
        if not course:
            raise BadValueError("Course with ID {} does not exist.".format(
                data['course'].id()))

        # check if there is a duplicate assignment
        assignments = list(
            models.Assignment.query(models.Assignment.name == data['name']))
        if len(assignments) > 0:
            raise BadValueError(
                'assignment with name %s exists already' % data['name'])
        return super(AssignmentAPI, self).post(user, data)

    def assign(self, obj, user, data):
        need = Need('put')
        if not obj.can(user, need, obj):
            raise need.exception()
        deferred.defer(add_to_grading_queues, obj.key)

    def group(self, obj, user, data):
        """User's current group for assignment."""
        return models.Group.lookup(user, obj)

    def invite(self, obj, user, data):
        """User ask invited to join his/her current group for assignment."""
        err = models.Group.invite_to_group(user.key, data['email'], obj.key)
        if err:
            raise BadValueError(err)

class SubmitNDBImplementation(object):
    """
    Implementation of DB calls required by submission using Google NDB
    """

    def lookup_assignments_by_name(self, name):
        """
        Look up all assignments of a given name.

        :param name: (string) name to search for
        :return: (list) assignments
        """
        mc_key = 'assignments_{}'.format(name)
        assignments = memcache.get(mc_key)
        if not assignments:
            by_name = models.Assignment.name == name
            assignments = list(models.Assignment.query().filter(by_name))
            memcache.set(mc_key, assignments)
        return assignments

    def create_submission(self, user, assignment, messages, submit, submitter):
        """
        Create submission using user as parent to ensure ordering.

        :param user: (object) caller
        :param assignment: (Assignment)
        :param messages: Data content of backup/submission
        :param submit: Whether this backup is a submission to be graded
        :param submitter: (object) caller or submitter
        :return: (Backup) submission
        """
        if not user.is_admin or not submitter:
            submitter = user.key

        message_date = None
        analytics = messages.get('analytics')
        if analytics:
            message_date = analytics.get('time', None)
        if message_date:
            created = parse_date(message_date)
        else:
            created = datetime.datetime.now()

        ms = lambda kind, message: models.Message(kind=kind, contents=message)
        db_messages = [ms(k, m) for k, m in messages.iteritems() if m]

        backup = models.Backup(submitter=submitter,
                               assignment=assignment.key,
                               messages=db_messages,
                               created=created)
        backup.put()
        deferred.defer(assign_submission, backup.key.id(), submit)
        return backup

class SubmissionAPI(APIResource):
    """
    The API resource for the Backup & Submission Objects
    """
    model = models.Backup
    diff_model = models.Diff

    db = SubmitNDBImplementation()

    methods = {
        'post': {
            'web_args': {
                'assignment': Arg(str, required=True),
                'messages': Arg(None, required=True),
                'submit': BooleanArg(),
                'submitter': KeyArg('User')
            }
        },
        'get': {
            'web_args': {
            }
        },
        'index': {
            'web_args': {
                'assignment': KeyArg('Assignment'),
                'submitter': KeyArg('User'),
                'created': DateTimeArg(),
                'messages.kind': Arg(str, use=parse_json_field),
                }
        },
        'diff': {
            'methods': set(['GET']),
            },
        'download': {
            'methods': set(['GET']),
            },
        'add_comment': {
            'methods': set(['POST']),
            'web_args': {
                'index': Arg(int, required=True),
                'file': Arg(str, required=True),
                'message': Arg(str, required=True)
            }
        },
        'delete_comment': {
            'methods': set(['POST']),
            'web_args': {
                'comment': KeyArg('Comment', required=True)
            }
        },
        'add_tag': {
            'methods': set(['PUT']),
            'web_args': {
                'tag': Arg(str, required=True)
            }
        },
        'remove_tag': {
            'methods': set(['PUT']),
            'web_args': {
                'tag': Arg(str, required=True)
            }
        },
        'win_rate': {
            'methods': set(['GET']),
        }
    }

    def graded(self, obj, user, data):
        """
        Gets the user's graded submissions

        :param obj: (object) target
        :param user: (object) caller
        :param data: (dictionary) data
        :return:
        """

    def download(self, obj, user, data):
        """
        Download submission, but check if it has content and encode all files.

        :param obj: (object) target
        :param user: (object) caller
        :param data: (dictionary) data
        :return: file contents in utf-8
        """
        messages = obj.get_messages()
        if 'file_contents' not in messages:
            raise BadValueError('Submission has no contents to download')
        file_contents = messages['file_contents']

        if 'submit' in file_contents:
            del file_contents['submit']

        # Need to encode every file before it is.
        for key in file_contents.keys():
            try:
                file_contents[key] = file_contents[key].encode('utf-8')
            except:
                pass
        response = make_response(create_zip(file_contents))

        response.headers['Content-Disposition'] = (
            'attachment; filename=submission-%s.zip' % str(obj.created))
        response.headers['Content-Type'] = 'application/zip'
        return response

    def diff(self, obj, user, data):
        """
        Gets the associated diff for a submission

        :param obj: (object) target
        :param user: -- unused --
        :param data: -- unused --
        :return: (Diff) object with differences
        """
        messages = obj.get_messages()
        if 'file_contents' not in obj.get_messages():
            raise BadValueError('Submission has no contents to diff')

        file_contents = messages['file_contents']

        if 'submit' in file_contents:
            del file_contents['submit']

        for key in file_contents.keys():
            try:
                file_contents[key] = file_contents[key].encode('utf-8')
            except:
                pass

        diff_obj = self.diff_model.get_by_id(obj.key.id())
        if diff_obj:
            return diff_obj

        diff = {}
        templates = obj.assignment.get().templates
        if not templates or templates == {}:
            raise BadValueError('no templates for assignment, \
                                please contact course staff')

        templates = json.loads(templates)
        if type(templates) == unicode:
            templates = ast.literal_eval(templates)

        for filename, contents in file_contents.items():
            if filename in templates:
                temp = templates[filename]
                if type(templates[filename]) == list:
                    temp = templates[filename][0]
            else:
                temp = ""
            diff[filename] = compare.diff(temp, contents)

        diff = self.diff_model(id=obj.key.id(),
                               diff=diff)
        diff.put()
        return diff

    def add_comment(self, obj, user, data):
        """
        Adds a comment to this diff.

        :param obj: (object) target
        :param user: (object) caller
        :param data: (dictionary) data
        :return: result of putting comment
        """
        diff_obj = self.diff_model.get_by_id(obj.key.id())
        if not diff_obj:
            raise BadValueError("Diff doesn't exist yet")

        index = data['index']
        message = data['message']
        filename = data['file']

        if message.strip() == '':
            raise BadValueError('Cannot make empty comment')

        comment = models.Comment(
            filename=filename,
            message=message,
            line=index,
            author=user.key,
            parent=diff_obj.key)
        comment.put()
        return comment

    def delete_comment(self, obj, user, data):
        """
        Deletes a comment on this diff.

        :param obj: (object) target
        :param user: (object) caller
        :param data: (dictionary) data
        :return: result of deleting comment
        """
        diff_obj = self.diff_model.get_by_id(obj.key.id())
        if not diff_obj:
            raise BadValueError("Diff doesn't exist yet")

        comment = models.Comment.get_by_id(
            data['comment'].id(), parent=diff_obj.key)
        if not comment:
            raise BadKeyError(data['comment'])
        need = Need('delete')
        if not comment.can(user, need, comment):
            raise need.exception()
        comment.key.delete()

    def add_tag(self, obj, user, data):
        """
        Removes a tag from the submission.
        Validates existence.

        :param obj: (object) target
        :param user: -- unused --
        :param data: (dictionary) data
        :return: result of adding tag
        """
        tag = data['tag']
        if tag in obj.tags:
            raise BadValueError('Tag already exists')

        submit_tag = models.Submission.SUBMITTED_TAG
        if tag == submit_tag:
            previous = models.Submission.query().filter(
                models.Submission.assignment == obj.assignment).filter(
                    models.Submission.submitter == obj.submitter).filter(
                        models.Submission.tags == submit_tag)

            previous = previous.get(keys_only=True)
            if previous:
                raise BadValueError('Only one final submission allowed')

        obj.tags.append(tag)
        obj.put()

    def remove_tag(self, obj, user, data):
        """
        Adds a tag to this submission.
        Validates uniqueness.

        :param obj: (object) target
        :param user: (object) caller
        :param data: (dictionary) data
        :return: result of removing tag
        """
        tag = data['tag']
        if tag not in obj.tags:
            raise BadValueError('Tag does not exist.')

        obj.tags.remove(tag)
        obj.put()

    def win_rate(self, obj, user, data):
        """
        Gets the win_rate for the submission. This method will be removed shortly.

        :param obj: (object) target
        :param user: -- unused --
        :param data: -- unused --
        :return: Reponse from Autograder.
        """
        messages = obj.get_messages()
        if 'file_contents' not in obj.get_messages():
            raise BadValueError('Submission has no contents to diff')
        file_contents = messages['file_contents']

        if 'hog.py' not in file_contents:
            raise BadValueError('Submission is not for Hog')
        cached = memcache.get('%s:hog_win' % obj.key.id())
        if cached is not None:
          return cached
        else:
          hog_code = file_contents['hog.py'].encode('utf-8')
          payload = {'strategy': hog_code}
          headers={'content-type': 'application/json'}
          q = requests.post('http://hog.cs61a.org/winrate',
             data=json.dumps(payload),
             headers=headers)
          memcache.add('%s:hog_win' % obj.key.id(), q.json(), 86400)
          return q.json()

    def score(self, obj, user, data):
        """
        Sets composition score

        :param obj: (object) target
        :param user: (object) caller
        :param data: (dictionary) data
        :return: (int) score
        """
        score = models.Score(
            score=data['score'],
            message=data['message'],
            grader=user.key)
        score.put()

        if 'Composition' not in obj.tags:
            obj.tags.append('Composition')

        obj.compScore = score.key
        obj.put()
        return score

    def get_assignment(self, name):
        """
        Look up an assignment by name

        :param name: (string) name of assignment
        :return: (object, Error) the assignment object or
            raise a validation error
        """
        assignments = self.db.lookup_assignments_by_name(name)

        if not assignments:
            raise BadValueError('Assignment \'%s\' not found' % name)
        if len(assignments) > 1:
            raise BadValueError('Multiple assignments named \'%s\'' % name)
        return assignments[0]

    def submit(self, user, assignment, messages, submit, submitter=None):
        """
        Process submission messages for an assignment from a user.
        """
        valid_assignment = self.get_assignment(assignment)

        if submitter is None:
            submitter = user.key

        due = valid_assignment.due_date
        late_flag = valid_assignment.lock_date and \
                    datetime.datetime.now() >= valid_assignment.lock_date
        revision = valid_assignment.revision

        if submit and late_flag:
            if revision:
                # In the revision period. Ensure that user has a previously graded submission.
                fs = user.get_final_submission(valid_assignment)
                if fs is None or fs.submission.get().score == []:
                    logging.info('Rejecting Revision without graded FS', submitter)
                    return (403, 'Previous submission was not graded', {
                      'late': True,
                      })
            else:
                # Late submission. Do not allow them to submit
                logging.info('Rejecting Late Submission', submitter)
                return (403, 'late', {
                    'late': True,
                    })

        models.Participant.add_role(user, valid_assignment.course, STUDENT_ROLE)
        submission = self.db.create_submission(user, valid_assignment,
                                               messages, submit, submitter)
        return (201, 'success', {
            'key': submission.key.id(),
            'course': valid_assignment.course.id(),
            'email': user.email[0]
        })

    def post(self, user, data):
        submit_flag = False
        if data['messages'].get('file_contents'):
            if 'submit' in data['messages']['file_contents']:
                submit_flag = data['messages']['file_contents']['submit']

        return self.submit(user, data['assignment'],
                           data['messages'], submit_flag,
                           data.get('submitter'))

class VersionAPI(APIResource):
    model = models.Version

    key_type = str

    methods = {
        'post': {
            'web_args': {
                'name': Arg(str, required=True),
                'base_url': Arg(str, required=True),
                }
        },
        'put': {
            'web_args': {
                'name': Arg(str),
                'base_url': Arg(str),
                }
        },
        'get': {
            'web_args': {
            }
        },
        'index': {
            'web_args': {
            }
        },
        'new': {
            'methods': set(['PUT']),
            'web_args': {
                'version': Arg(str, required=True),
                'current': BooleanArg()
            }
        },
        'download': {
            'methods': set(['GET']),
            'web_args': {
                'version': Arg(str)
            }
        },
        'current': {
            'methods': set(['GET']),
            'web_args': {
            }
        },
        'set_current': {
            'methods': set(['POST']),
            'web_args': {
                'version': Arg(str, required=True)
            }
        },
        }

    def new(self, obj, user, data):
        need = Need('update')
        if not obj.can(user, need, obj):
            raise need.exception()

        new_version = data['version']

        if new_version in obj.versions:
            raise BadValueError('Duplicate version: {}'.format(new_version))

        obj.versions.append(new_version)
        if 'current' in data and data['current']:
            obj.current_version = data['version']
        obj.put()
        return obj

    def current(self, obj, user, data):
        need = Need('get')
        if not obj.can(user, need, obj):
            raise need.exception()
        if not obj.current_version:
            raise BadValueError(
                'Invalid version resource. Contact an administrator.')
        return obj.current_version

    def download(self, obj, user, data):
        need = Need('get')
        if not obj.can(user, need, obj):
            raise need.exception()
        if 'version' not in data:
            download_link = obj.download_link()
        else:
            download_link = obj.download_link(data['version'])
        return redirect(download_link)

    def set_current(self, obj, user, data):
        need = Need('update')
        if not obj.can(user, need, obj):
            raise need.exception()
        current_version = data['version']
        if current_version not in obj.versions:
            raise BadValueError(
                'Invalid version. Cannot update to current.')
        obj.current_version = current_version
        obj.put()

class CourseAPI(APIResource):
    model = models.Course

    methods = {
        'post': {
            'web_args': {
                'display_name': Arg(str),
                'institution': Arg(str, required=True),
                'offering': Arg(str, required=True),
                'active': BooleanArg(),
                }
        },
        'put': {
            'web_args': {
                'name': Arg(str),
                'institution': Arg(str),
                'term': Arg(str),
                'year': Arg(str),
                'active': BooleanArg(),
                }
        },
        'delete': {
        },
        'get': {
        },
        'index': {
        },
        'get_staff': {
        },
        'add_staff': {
            'methods': set(['POST']),
            'web_args': {
                'email': Arg(str, required=True)
            }
        },
        'remove_staff': {
            'methods': set(['POST']),
            'web_args': {
                'email': Arg(str, required=True)
            }
        },
        'assignments': {
            'methods': set(['GET']),
            'web_args': {
            }
        },
        'get_courses': {
            'methods': set(['GET']),
            'web_args': {
                'user': KeyArg('User', required=True)
            }
        },
        'get_students': {
        },
        'add_student': {
            'methods': set(['POST']),
            'web_args': {
                'student': KeyArg('User', required=True)
            }
        },
        }

    def post(self, user, data):
        """
        The POST HTTP method
        """
        return super(CourseAPI, self).post(user, data)

    def add_staff(self, course, user, data):
        need = Need('staff')
        if not course.can(user, need, course):
            raise need.exception()

        user = models.User.get_or_insert(data['email'])
        if user not in course.staff:
          models.Participant.add_role(user, course, STAFF_ROLE)

    def get_staff(self, course, user, data):
        need = Need('staff')
        if not course.can(user, need, course):
            raise need.exception()
        query = models.Participant.query(
          models.Participant.course == course.key,
          models.Participant.role == 'staff')
        return list(query.fetch())

    def remove_staff(self, course, user, data):
        need = Need('staff')
        if not course.can(user, need, course):
            raise need.exception()

        removed_user = models.User.lookup(data['email'])
        if removed_user:
          models.Participant.remove_role(removed_user, course, STAFF_ROLE)

    def get_courses(self, course, user, data):
        query = models.Participant.query(
            models.Participant.user == data['user'])
        need = Need('index')
        query = models.Participant.can(user, need, course, query)
        return list(query)

    def get_students(self, course, user, data):
        query = models.Participant.query(
            models.Participant.course == course.key)
        need = Need('staff')
        if not models.Participant.can(user, need, course, query):
            raise need.exception()
        return list(query.fetch())

    def add_student(self, course, user, data):
        need = Need('staff') # Only staff can call this API
        if not course.can(user, need, course):
            raise need.exception()
        new_participant = models.Participant.add_role(user, course, STUDENT_ROLE)
        new_participant.put()

    def assignments(self, course, user, data):
        return list(course.assignments)

class GroupAPI(APIResource):
    model = models.Group

    methods = {
        'get': {
        },
        'index': {
            'web_args': {
                'assignment': KeyArg('Assignment'),
                'members': KeyArg('User')
            }
        },
        'add_member': {
            'methods': set(['PUT', 'POST']),
            'web_args': {
                'email': Arg(str, required=True),
                },
            },
        'remove_member': {
            'methods': set(['PUT', 'POST']),
            'web_args': {
                'email': Arg(str, required=True),
                },
            },
        'accept': {
            'methods': set(['PUT', 'POST']),
            },
        'decline': {
            'methods': set(['PUT', 'POST']),
            },
        'exit': {
            'methods': set(['PUT', 'POST']),
            }
    }

    def add_member(self, group, user, data):
        need = Need('invite')
        if not group.can(user, need, group):
            raise need.exception()

        if data['email'] in group.invited:
            raise BadValueError('user has already been invited')
        if data['email'] in group.member:
            raise BadValueError('user already part of group')

        error = group.invite(data['email'])
        if error:
            raise BadValueError(error)

        audit_log_message = models.AuditLog(
            event_type='Group.add_member',
            user=user.key,
            description='Added member {} to group'.format(data['email']),
            obj=group.key
        )
        audit_log_message.put()

    def remove_member(self, group, user, data):
        need = Need('remove')
        if not group.can(user, need, group):
            raise need.exception()

        to_remove = models.User.lookup(data['email'])
        if to_remove:
            group.exit(to_remove)

            audit_log_message = models.AuditLog(
                event_type='Group.remove_member',
                user=user.key,
                obj=group.key,
                description='Removed user from group'
            )
            audit_log_message.put()

    def invite(self, group, user, data):
        need = Need('invite')
        if not group.can(user, need, group):
            return need.exception()

        error = group.invite(data['email'])
        if error:
            raise BadValueError(error)

    def accept(self, group, user, data):
        need = Need('accept')
        if not group.can(user, need, group):
            raise need.exception()

        group.accept(user)

    def decline(self, group, user, data):
        self.exit(group, user, data)

    def exit(self, group, user, data):
        need = Need('exit')
        if not group.can(user, need, group):
            raise need.exception()

        group.exit(user)

class QueueAPI(APIResource):
    """
    The API resource for the Assignment Object
    """
    model = models.Queue

    methods = {
        'post': {
            'web_args': {
                'assignment': KeyArg('Assignment', required=True),
                'assigned_staff': KeyRepeatedArg('User'),
                'submissions': KeyRepeatedArg('Submissionvtwo')
            }
        },
        'get': {
        },
        'put': {
            'web_args': {
                'assigned_staff': KeyRepeatedArg('User'),
                'submissions': KeyRepeatedArg('Submissionvtwo')
            }
        },
        'index': {
            'web_args': {
                'assignment': KeyArg('Assignment'),
                'assigned_staff': KeyArg('User'),
                'owner': KeyArg('User'),
            }
        },
        }

    def new_entity(self, attributes):
        """
        Request to define a new entity

        :param attributes: entity attributes,
            to be loaded on entity instantiation
        :return: entity
        """
        if 'owner' not in attributes:
            attributes['owner'] = attributes['assigned_staff'][0]
        ent = super(QueueAPI, self).new_entity(attributes)
        ent.assigned_staff = [models.User.get_or_insert(
            user.id()).key for user in ent.assigned_staff]
        return ent

class FinalSubmissionAPI(APIResource):
    """
    The API resource for the Assignment Object
    """
    model = models.FinalSubmission

    methods = {
        'get': {
        },
        'index': {
        },
        'score': {
            'methods': set(['POST']),
            'web_args': {
                'score': Arg(int, required=True),
                'message': Arg(str, required=True),
                'source': Arg(str, required=True),
              }
        },
        'post': {
            'web_args': {
                'submission': KeyArg('Submission', required=True)
            }
        },
        }

    def new_entity(self, attributes):
        """
        Creates a new entity with given attributes.

        :param attributes: (dictionary)
        :return: (entity, error_response) should be ignored if error_response
        is a True value
        """
        subm = attributes['submission'].get()
        subm.mark_as_final()
        return subm.get_final()

    def score(self, obj, user, data):
        """
        Sets composition score

        :param obj: (object) target
        :param user: (object) caller
        :param data: (dictionary) data
        :return: (int) score
        """
        need = Need('grade')
        if not obj.can(user, need, obj):
            raise need.exception()

        score = models.Score(
            score=data['score'],
            message=data['message'],
            grader=user.key)
        grade = score.put()

        submission = obj.submission.get()

        # Create or updated based on existing scores.
        if data['source'] == 'composition':
          # Only keep any autograded scores.
          submission.score = [autograde for autograde in submission.score \
            if score.autograder]
          submission.score.append(score)
        else:
          submission.score.append(score)

        submission.put()

        return score

class AnalyticsAPI(APIResource):
    """
    The API resource for the AnalyticsDump Object
    """
    model = analytics.AnalyticsDump

    methods = {
        'get': {
        },
        'index': {
        },
        'post': {
            'web_args': {
                'job_type': Arg(str, required=True),
                'filters': Arg(None, use=parse_json_list_field, required=True),
            }
        },
    }

    def post(self, user, data):

        need = Need('create')

        if not self.model.can(user, need, None):
            raise need.exception()

        job_type, filters = data['job_type'], data['filters']

        if not isinstance(filters, list):
            raise BadValueError('filters must be a list of triples')
        for filter in filters:
            if len(filter) != 3:
                raise BadValueError('filters must be a list of triples')

        if job_type not in analytics.available_jobs:
            raise BadValueError('job must be of the following types: %s' %
                                ', '.join(list(analytics.available_jobs.keys())))

        job = analytics.get_job(job_type, user, filters)
        job.start()

        return (201, 'success', {
            'key': job.job_dump.key.id()
        })


#!/usr/bin/python3

'''script that starts a Flask web application
'''

from flask import Flask, render_template
from models import storage

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

@app.teardown_appcontext
def current_remove(self):
    """
    request you must remove the current SQLAlchemy Session
    """
    storage.close()

@app.route('/states')
@app.route('/states/<id>')
def print_state(id=None):
    """
    display a HTML page
    """
    data = storage.all("State")
    return render_template('9-states.html', states=data, id=id)

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


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0012_auto_20151008_2226'),
    ]

    operations = [
        migrations.CreateModel(
            name='Muscle',
            fields=[
                ('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)),
                ('strength', models.FloatField(blank=True, default=-1.0)),
                ('date', models.DateTimeField(verbose_name='creation date', blank=True, default=django.utils.timezone.now)),
                ('owner', models.ForeignKey(to='accounts.Child')),
            ],
        ),
    ]


import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split, cross_validate, cross_val_score
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
from sklearn import preprocessing
import re
import argparse
import matplotlib.pyplot as plt
import pydotplus
import collections

def preprocess(file):
    """Takes a txt file containing all sentence examples from the category as an input.
    Outputs a list of all sentences from the file """
    data = file.read()
    data = data.split(";;")
    sent = []
    for i in data:
        i = i.split("punctuation")
        for x in i:
            x = x.split()
            sent.append(x)
    return sent

def tuple_sent(sent):
    """Takes each sentence and outputs each word and PoS tag as a tuple"""
    tupled_sentences = []
    for i in sent:
        tupled_sentences.append(list(zip(i[::2], i[1::2])))
    return tupled_sentences

def sent_list(sent, target_word):
    """Checks if the chosen word pair exists in each sentence.
    Outputs a list of sentences containing the words"""
    sent_list = []
    for i in sent:
        for x in i:
            word = x[0]
            if word == target_word:
                sent_list.append(i)
    return sent_list

def right_left_context(sent, target_word):
    """Outputs the words immediately to the right and left of the target word as well as
    the word two words to the left of the target word"""
    for index, tup in enumerate(sent):
        word = tup[0]
        if word == target_word:
            left_context_word = sent[index-1]
            if index+1 < len(sent):
                right_context_word = sent[index+1]
            else:
                right_context_word = ("(N/A)", "none")
            if 0 <= index-2:
                left_two_context_word = sent[index-2]
            else:
                left_two_context_word = ("(N/A)", "none")

    return left_context_word, right_context_word, left_two_context_word

def feature_extraction(sent, target_word):
    """Outputs a feature vector for the target word"""
    target_vector = np.zeros(16)
    LC, RC, LC2 = right_left_context(sent, target_word)
    nominal_left = re.search(r'^[n|l|f|g|t]', LC[1]) # Words with grammatical case, such as nouns and pronouns
    nominal_right = re.search(r'^[n|l|f|g|t]', RC[1])
    finite_left = re.search(r'^[sb|sf|sv]', LC[1]) # A verb that inflects for person agreement
    finite_right = re.search(r'^[sb|sf|sv]', RC[1])
    nominative_left = re.search(r'^[nn|ln|fn|gn|tn]', LC[1])
    nominative_right = re.search(r'^[nn|ln|fn|gn|tn]', RC[1])
    oblique_left = re.search(r'^[no|lo|fo|go|to|nþ|lþ|fþ|gþ|tþ|ne|le|fe|ge|te]', LC[1]) # Has some grammatical case other than nominative
    oblique_right = re.search(r'^[no|lo|fo|go|to|nþ|lþ|fþ|gþ|tþ|ne|le|fe|ge|te]', RC[1])
    particle_left = re.search(r'^[a|c]', LC[1])
    particle_right = re.search(r'^[a|c]', RC[1])
    feminine_two_left = re.search(r'^[fpv|nv]', LC2[1])
    masculine_two_left = re.search(r'^[fpk|nk]', LC2[1])
    infinitive_particle_left = re.search(r'^[cn]', LC[1])
    infinitive_particle_right = re.search(r'^[cn]', RC[1])
    infinitive_verb_left = re.search(r'^[sn]', LC[1])
    infinitive_verb_right = re.search(r'^[sn]', RC[1])
    if nominal_left:
        target_vector[0] = 1
    else:
        target_vector[0] = 0
    if nominal_right:
        target_vector[1] = 1
    else:
        target_vector[1] = 0
    if finite_left:
        target_vector[2] = 1
    else:
        target_vector[2] = 0
    if finite_right:
        target_vector[3] = 1
    else:
        target_vector[3] = 0
    if nominative_left:
        target_vector[4] = 1
    else:
        target_vector[4] = 0
    if nominative_right:
        target_vector[5] = 1
    else:
        target_vector[5] = 0
    if oblique_left:
        target_vector[6] = 1
    else:
        target_vector[6] = 0
    if oblique_right:
        target_vector[7] = 1
    else:
        target_vector[7] = 0
    if particle_left:
        target_vector[8] = 1
    else:
        target_vector[8] = 0
    if particle_right:
        target_vector[9] = 1
    else:
        target_vector[9] = 0
    if feminine_two_left:
        target_vector[10] = 1
    else:
        target_vector[10] = 0
    if masculine_two_left:
        target_vector[11] = 1
    else:
        target_vector[11] = 0
    if infinitive_particle_left:
        target_vector[12] = 1
    else:
        target_vector[12] = 0
    if infinitive_particle_right:
        target_vector[13] = 1
    else:
        target_vector[13] = 0
    if infinitive_verb_left:
        target_vector[14] = 1
    else:
        target_vector[14] = 0
    if infinitive_verb_right:
        target_vector[15] = 1
    else:
        target_vector[15] = 0

    return target_vector

def automate(wordfile):
    words = []
    accuracy = []
    precision = []
    recall = []
    fscore = []

    with open(args.wordfile, encoding='utf8') as wordfile:
        for word in wordfile:
            words.append(word.rstrip())
    count = 0
    while len(words) > count:
        target_word_1 = words[count]
        count += 1
        target_word_2 = words[count]
        count += 1

        with open(args.filename, encoding='utf8') as data_file: # The datafile contains all sentence examples of the category in consideration
            sent = preprocess(data_file)
            sentences = tuple_sent(sent)
            sent_list_1 = sent_list(sentences, target_word_1)
            sent_list_2 = sent_list(sentences, target_word_2)
            data_matrix_1 = np.zeros([1,16])
            data_matrix_2 = np.zeros([1,16])
            for i in sent_list_1:
                target_vector = feature_extraction(i, target_word_1)
                data_matrix_1 = np.vstack((data_matrix_1, target_vector)) # Create a data matrix for all sentence examples of the target words
            for i in sent_list_2:
                target_vector = feature_extraction(i, target_word_2)
                data_matrix_2 = np.vstack((data_matrix_2, target_vector))
            N1,D1 = data_matrix_1.shape
            N2,D2 = data_matrix_2.shape
            target1 = np.zeros(N1)
            target2 = np.ones(N2)
            target = np.concatenate((target1,target2), axis=0)
            data = np.concatenate((data_matrix_1, data_matrix_2), axis=0) # A unified data matrix containing all examples for both candidates
            data = preprocessing.scale(data)
            feature_names = ["LW nom", "RW nom", "LW finite", "RW finite", "LW nomin", "RW nomin", "LW obli", "RW obli", "LW partic", "RW partic", "L2 femin", "L2 masc"]

        model = MLPClassifier(solver='lbfgs', max_iter=1000)

        cross_val_accuracy_scores = cross_val_score(model, data, target, cv=10)
        cross_val_precision_scores = cross_val_score(model, data, target, cv=10, scoring="precision")
        cross_val_recall_scores = cross_val_score(model, data, target, cv=10, scoring="recall")
        cross_val_f1_scores = cross_val_score(model, data, target, cv=10, scoring="f1")
        print("Results for", target_word_1, "and", target_word_2)
        #print("Cross validation accuracy scores:", cross_val_accuracy_scores) # All cross val scores individually
        sumav = sum(cross_val_accuracy_scores) / 10 # Average over all cross val scores
        print("Average accuracy:", sumav)
        #print("Cross validation precision scores:", cross_val_precision_scores)
        sumav2 = sum(cross_val_precision_scores) / 10
        print("Average precision:", sumav2)
        #print("Cross validation recall scores:", cross_val_recall_scores)
        sumav3 = sum(cross_val_recall_scores) / 10
        print("Average recall:", sumav3)
        #print("Cross validation F1 scores:", cross_val_f1_scores)
        sumav4 = sum(cross_val_f1_scores) / 10
        print("Average F1:", sumav4)

        accuracy.append(sumav)
        precision.append(sumav2)
        recall.append(sumav3)
        fscore.append(sumav4)

    print("Accuracy: ", accuracy)
    print("Precision: ", precision)
    print("Recall: ", recall)
    print("F-score: " ,fscore)

parser = argparse.ArgumentParser()
parser.add_argument('filename') # Sentence examples
parser.add_argument('wordfile') # Word list
args = parser.parse_args()

automate(args.wordfile)


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

'the function of auto insert record'

__author__='jcm'

import sys
import mysql
import mysql.connector

def Auto_insert(*args):
    insert_obj=args[0]
    insert_tbl=args[1]
    insert_fields_tuple=args[2]
    insert_pid=args[3]
    insert_vil=args[4]
    insert_qi=args[5]
    insert_dong=args[6]
    insert_zuo=args[7]
    insert_cell=args[8]
    insert_room=args[9]

    if insert_qi[0] !='':
        insert_village=[insert_vil+concat_qi+'期' for concat_qi in insert_qi]
    else:
        insert_village=[insert_vil]

    if insert_room[0] =='':
        raise ValueError('无效输入,范围为空')

    if insert_dong[0] !='' and insert_zuo[0] !='':
        insert_number=[concat_dong+'栋'+concat_zuo+'座' for concat_dong in insert_dong for concat_zuo in insert_zuo]
    elif insert_dong[0] =='' and insert_zuo[0] !='':
        insert_number=[concat_zuo+'座' for concat_zuo in insert_zuo]
    elif insert_dong[0] !='' and insert_zuo[0] =='':
        insert_number=[concat_dong+'栋' for concat_dong in insert_dong]
    else:
        insert_number=['']

    for round_village in insert_village:
        for round_number in insert_number:
            for round_cell in insert_cell:
                for round_room in insert_room:
                    insert_obj.insert(
                        insert_tbl,
                        insert_fields_tuple,
                        (insert_pid,round_village,
                        round_number,
                        round_cell,
                        round_room))


from flask import Flask,request,jsonify
app = Flask(__name__)

@app.route('/')
def task():
    return 'Flask Task'

@app.route('/calculate/add', methods=['POST','GET'])
def add():
    num1 = request.args.get('num1')
    num2 = request.args.get('num2')
    result= int(num1) + int(num2)
    return jsonify({'Calculation':'Addtion', 'The sum of 2 nos:': result})

if __name__ == '__main__':
    app.run()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 27 21:50:43 2021

@author: hat
"""

import math

lat1 = df_result.iloc[150]['lat_tweet']
lon1 = df_result.iloc[150]['lon_tweet']

print("Tweet = lat:",lat1,"lon:",lon1)

lat2 = df_result.iloc[150]['lat_oficial']
lon2 = df_result.iloc[150]['lon_oficial']

print("Oficial = lat:",lat2,"lon:",lon2)

lat1 = math.radians(lat1)
lon1 = math.radians(lon1)

lat2 = math.radians(lat2)
lon2 = math.radians(lon2)

sins = math.sin(lat1)*math.sin(lat2)
coss = math.cos(lat1)*math.cos(lat2)*math.cos(lon2-lon1)

acos = math.acos(sins+coss)

d = 6378.137 * acos
print(d)


'''
format directory (single level of folders with subfiles)
into single whitespace strings.
Just change 'src' for source directory

'''

import os

src = (r'C:\Users\MacalusoC\Desktop\Technical Docs\TLC_Program_Release'
       r'\Machine_Folders\EvoDECO 10')

def stringFormat(src):
    '''
    iterate folders in directory
    '''
    # create a list of the folders in the src directory
    folder_list = os.listdir(src)
    # iterate over the folders
    for f in folder_list:
        # split folder names
        s = f.split()
        # create an empty variable
        string = ''
        # get index iteration for the length of segments (s)
        for x in range(len(s)):
            # building the string up
            string = str(string) + (' ' + str(s[x]))
            # strip whitespace infront of folder name
            string = string.lstrip()
        # rename the folder with the new formatted name
        try:
            os.rename(src + '\\' + f, src + '\\' + string)
        except FileExistsError:
            print(string)
        sub_dir = (src + '\\' + string)
        # create a list of files inside each folder
        file_list = os.listdir(sub_dir)
        # iterate over the files
        for f in file_list:
            # split the file names
            s = f.split()
            # empty string
            string = ''
            # index iteration for the length of segments (s)
            for x in range(len(s)):
                # build up the string
                string = str(string) + (' ' + str(s[x]))
                # strip whitespace infront of file name
                string = string.lstrip()
            # rename the file with the formatted name
            try:
                os.rename(sub_dir + '\\' + f, sub_dir + '\\' + string)
            except FileExistsError:
                print(string)

def main():
    stringFormat(src)

if __name__ == "__main__":
    main()

Format Folder and Files Names to Single Whitespace/Format_white_space.py


import re
import spacy
from spacy import displacy
from pprint import pprint

from triplet_extractor import TripletExtractor

class QuestionProcessor:

    def __init__(self, phrase, verbose=False):
        self.nlp = spacy.load('en')
        self.doc = self.nlp(phrase)
        self.sentences = list(self.doc.sents)
        self.triplets = []
        self.verbose = verbose
        self.debug_dict = {}

    def display_tree(self):
        """ Display the dependency tree at localhost:5000 """
        displacy.serve(self.doc, style='dep', page=True)

    def process(self):
        """ Extract all triplets from given phrase """
        extractor = TripletExtractor(no = 0, verbose=self.verbose)
        if self.verbose:
            self.display_tree()

        for sentence in self.sentences:
            self.debug_dict["Sentence"] = sentence
            self.debug_dict["ROOT"] = sentence.root

            question_triplets = extractor.process(sentence, "q")
            self.debug_dict["question_triplets"] = question_triplets
            self.triplets += question_triplets

        self.triplets = list(set(self.triplets))
        self.triplets.sort()
        self.debug_dict["Question_Triplets"] = self.triplets

        if self.verbose:
            pprint(self.debug_dict)

        return self.triplets


#!/usr/bin/env python2

"""
A script to delete songs from your Google Music library using https://github.com/simon-weber/Unofficial-Google-Music-API.
More information at https://github.com/thebigmunch/gmusicapi-scripts.

Usage:
  gmdelete.py (-h | --help)
  gmdelete.py [options] [-f FILTER]...

Options:
  -h, --help                         Display help message.
  -u USERNAME, --user USERNAME       Your Google username or e-mail address.
  -p PASSWORD, --pass PASSWORD       Your Google or app-specific password.
  -l, --log                          Enable gmusicapi logging.
  -d, --dry-run                      Output list of songs that would be deleted.
  -q, --quiet                        Don't output status messages.
                                     With -l,--log will display gmusicapi warnings.
                                     With -d,--dry-run will display song list.
  -f FILTER, --filter FILTER         Filter Google songs by field:pattern pair (e.g. "artist:Muse").
                                     Songs can match any filter criteria.
                                     This option can be set multiple times.
  -a, --all                          Songs must match all filter criteria.
  -y, --yes                          Delete songs without asking for confirmation.
"""

from __future__ import print_function, unicode_literals

import sys

from docopt import docopt

from gmwrapper import MobileClientWrapper
from utils import safe_print

def main():
	cli = dict((key.lstrip("-<").rstrip(">"), value) for key, value in docopt(__doc__).items())

	print_ = safe_print if not cli['quiet'] else lambda *args, **kwargs: None

	mcw = MobileClientWrapper()
	mcw.login(cli['user'], cli['pass'])

	delete_songs = mcw.get_google_songs(filters=cli['filter'], filter_all=cli['all'])

	if cli['dry-run']:
		print_("Found {0} songs to delete".format(len(delete_songs)))

		if delete_songs:
			safe_print("\nSongs to delete:\n")

			for song in delete_songs:
				safe_print("{0} by {1}".format(song['title'], song['artist']))
		else:
			safe_print("\nNo songs to delete")
	else:
		if delete_songs:
			if cli['yes'] or raw_input("Are you sure you want to delete {0} songs from Google Music? (y/n) ".format(len(delete_songs))).lower() == "y":
				print_("\nDeleting {0} songs from Google Music\n".format(len(delete_songs)))

				songnum = 0
				total = len(delete_songs)
				pad = len(str(total))

				for song in delete_songs:
					mcw.api.delete_songs(song['id'])
					songnum += 1

					print_("Deleted {num:>{pad}}/{total} songs from Google Music".format(num=songnum, pad=pad, total=total), end="\r")
					sys.stdout.flush()

				print_()
			else:
				print_("No songs deleted.")
		else:
			safe_print("\nNo songs to delete")

	mcw.logout()
	print_("\nAll done!")

if __name__ == '__main__':
	try:
		main()
	except KeyboardInterrupt:
		sys.exit("\n\nExiting")