import sys
import math

class FWICLASS:
    def __init__(self,temp,rhum,wind,prcp):
        self.h= rhum
        self.t= temp
        self.w= wind
        self.p= prcp

    def FFMCcalc(self,ffmc0):
        rf=1
        mo = (147.2*(101.0 - ffmc0))/(59.5 + ffmc0)
        if (self.p > 0.5):
            rf = self.p - 0.5
            if(mo > 150.0):
                mo = (mo+42.5*rf*math.exp(-100.0/(251.0-mo))*(1.0 - math.exp(-6.93/rf))) + (.0015*(mo - 150.0)**2)*math.sqrt(rf)
        elif mo <= 150.0:
            mo = mo+42.5*rf*math.exp(-100.0/(251.0-mo))*(1.0 - math.exp(-6.93/rf))
        if(mo > 250.0):
            mo = 250.0

        ed = .942*(self.h**.679) + (11.0*math.exp((self.h-100.0)/10.0))+0.18*(21.1-self.t) *(1.0 - 1.0/math.exp(.1150 * self.h))

        if(mo < ed):
            ew = .618*(self.h**.753) + (10.0*math.exp((self.h-100.0)/10.0))+ .18*(21.1-self.t)*(1.0 - 1.0/math.exp(.115 * self.h))

            if(mo <= ew):
                kl = .424*(1.0-((100.0-self.h)/100.0)**1.7)+(.0694*math.sqrt(self.w)) *(1.0 - ((100.0 - self.h)/100.0)**8)
                kw = kl * (.581 * math.exp(.0365 * self.t))
                m = ew - (ew - mo)/10.0**kw
            elif mo > ew:
                m = mo
        elif(mo == ed):
            m = mo
        elif mo > ed:
            kl =.424*(1.0-(self.h/100.0)**1.7)+(.0694*math.sqrt(self.w))* (1.0-(self.h/100.0)**8)
            kw = kl * (.581*math.exp(.0365*self.t))
            m = ed + (mo-ed)/10.0 ** kw
        ffmc = (59.5 * (250.0 -m)) / (147.2 + m)
        if (ffmc > 101.0):
            ffmc = 101.0
        if (ffmc <= 0.0):
            ffmc = 0.0
        return ffmc

    def DMCcalc(self,dmc0,mth):
        el = [6.5,7.5,9.0,12.8,13.9,13.9,12.4,10.9,9.4,8.0,7.0,6.0]
        t = self.t
        if (t < -1.1):
            t = -1.1
        rk = 1.894*(t+1.1) * (100.0-self.h) * (el[mth-1]*0.0001)
        if self.p > 1.5:
            ra= self.p
            rw = 0.92*ra - 1.27
            wmi = 20.0 + 280.0/math.exp(0.023*dmc0)

            if dmc0 <= 33.0:
                b = 100.0 /(0.5 + 0.3*dmc0)
            elif dmc0 > 33.0:
                if dmc0 <= 65.0:
                    b = 14.0 - 1.3*math.log(dmc0)
                elif dmc0 > 65.0:
                    b = 6.2 * math.log(dmc0) - 17.2
            wmr = wmi + (1000*rw) / (48.77+b*rw)
            pr = 43.43 * (5.6348 - math.log(wmr-20.0))
        elif self.p <= 1.5:
            pr = dmc0
        if (pr<0.0):
            pr = 0.0
        dmc = pr + rk
        if(dmc<= 1.0):
            dmc = 1.0
        return dmc

    def DCcalc(self,dc0,mth):
        dc=0
        fl = [-1.6, -1.6, -1.6, 0.9, 3.8, 5.8, 6.4, 5.0, 2.4, 0.4, -1.6, -1.6]
        t = self.t
        if(t < -2.8):
            t = -2.8
        pe = (0.36*(t+2.8) + fl[mth-1] )/2
        if pe <= 0.0:
            pe = 0.0
        if (self.p > 2.8):
            ra = self.p
            rw = 0.83*ra - 1.27
            smi = 800.0 * math.exp(-dc0/400.0)
            dr = dc0 - 400.0*math.log( 1.0+((3.937*rw)/smi))
            if (dr > 0.0):
                dc = dr + pe
        elif self.p <= 2.8:
            dc = dc0 + pe
        return dc

    def ISIcalc(self,ffmc):
        mo = 147.2*(101.0-ffmc) / (59.5+ffmc)
        ff = 19.115*math.exp(mo*-0.1386) * (1.0+(mo**5.31)/49300000.0)
        isi = ff * math.exp(0.05039*self.w)
        return isi

    def BUIcalc(self,dmc,dc):
        if dmc <= 0.4*dc:
            bui = (0.8*dc*dmc) / (dmc+0.4*dc)
        else:
            bui = dmc-(1.0-0.8*dc/(dmc+0.4*dc))*(0.92+(0.0114*dmc)**1.7)
        if bui <0.0:
            bui = 0.0
        return bui

    def FWIcalc(self,isi,bui):
        if bui <= 80.0:
            bb = 0.1 * isi * (0.626*bui**0.809 + 2.0)
        else:
            bb = 0.1*isi*(1000.0/(25. + 108.64/math.exp(0.023*bui)))
        if(bb <= 1.0):
            fwi = bb
        else:
            fwi = math.exp(2.72 * (0.434*math.log(bb))**0.647)
        return fwi

def main():
    import sys
    ffmc0= 85.0
    dmc0= 6.0
    dc0= 15.0
    my_csv_in = sys.argv[1]

    with open(my_csv_in, 'r') as f_in:
        print("opened")
        next(f_in)
        #test.toPandas().to_csv('C:/Users/HARITA/Desktop/datasets/predicted.csv')
        with open('/Users/krsingh/Desktop/datasets/testset3.csv', 'w') as f_out:
            h=["Year","Month","Day","FFMC","DMC","DC","ISI","BUI","Temp","RH","Wind","Rain","FWI","Intensity","Fire"]
            hd=','.join(h)
            f_out.write(hd)
            f_out.write("\r")
            for line in f_in:
                l=line.rstrip().split(',')
                yr=l[0]
                mth=l[1]
                day=l[2]
                temp=float(l[3])
                rhum=float(l[4])
                wind=float(l[5])
                prcp=float(l[6])
                if rhum> 100.0:
                    rhum=100.0
                mth=int(mth)
                fwisystem= FWICLASS(temp,rhum,wind,prcp)
                ffmc = fwisystem.FFMCcalc(ffmc0)
                dmc = fwisystem.DMCcalc(dmc0,mth)
                dc = fwisystem.DCcalc(dc0,mth)
                isi = fwisystem.ISIcalc(ffmc)
                bui = fwisystem.BUIcalc(dmc,dc)
                fwi = fwisystem.FWIcalc(isi,bui)
                fire=0
                intensity=0
                '''if fwi> 1.0000:
                    fire=1
                if fwi<5.0000:
                    intensity=0
                elif fwi<=3.0000:
                    intensity=1
                elif fwi>3 and fwi<=7.5000:
                    intensity=2
                elif fwi>7.5000 and fwi<=12.0000:
                    intensity=3
                elif fwi>12.0000 and fwi<=24:
                    intensity=3
                elif fwi>24:
                    intensity=4'''
                if fwi> 5.0000:
                    fire=1
                if fwi<5.0000:
                    intensity=0
                elif fwi<=10.0000:
                    intensity=1
                elif fwi<=17.0000:
                    intensity=2
                elif fwi<24:
                    intensity=3
                elif fwi >24:
                    intensity=4
                l=[str(yr),str(mth),str(day),str(round(ffmc,4)),str(round(dmc,4)),str(round(dc,4)),str(round(isi)),str(round(bui,4)),str(round(temp,4)),str(round(rhum,4)),str(round(wind,4)),str(round(prcp,4)),str(round(fwi,4)),str(intensity),str(fire)]
                ffmc0 = ffmc
                dmc0 = dmc
                dc0 = dc
                d=','.join(l)
                f_out.write(d)
                #print(d)
                f_out.write("\r")

    import numpy as np
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    import scipy.stats as ss
    from collections import Counter
    import math
    import numpy as np
    import pandas
    import matplotlib.pyplot as plt
    from sklearn import svm, datasets
    sns.set(color_codes=True)
    from django.shortcuts import render
    from django.conf import settings
    from django.core.files.storage import FileSystemStorage
    import sys
    import findspark

    findspark.init()

    import pyspark
    from pyspark.sql import SparkSession
    from pyspark.ml import Pipeline

    from pyspark.ml.feature import StringIndexer
    from pyspark.ml.feature import VectorAssembler
    from pyspark.ml.evaluation import MulticlassClassificationEvaluator
    from pyspark.ml.feature import QuantileDiscretizer
    #import Spark and MLlib packages
    from pyspark import SparkContext, SparkConf
    from pyspark.mllib.regression import LabeledPoint
    from pyspark.mllib.classification import SVMWithSGD, SVMModel
    from pyspark.mllib.classification import LogisticRegressionWithLBFGS

    #import data analysis packages
    import numpy as np
    import pandas as pd
    import sklearn

    from pandas import Series, DataFrame
    from sklearn import svm
    from sklearn.svm import SVC
    from sklearn.cross_validation import train_test_split
    from sklearn import metrics

    from numpy import array
    from timeit import default_timer as timer
    #import data visualization packages
    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set_style('whitegrid')

    '''my_csv_in = sys.argv[1]
    my_csv_out = r'/Users/krsingh/Desktop/datasets/forestfirestest2.csv'

    with open(my_csv_in, 'r') as f_in:
        print("opened")
        with open(my_csv_out, 'w') as f_out:
            for line in f_in:
                f_out.write(line)
                f_out.write("\r")
    '''

    import random

    dataframets= pandas.read_csv(r"/Users/krsingh/Desktop/datasets/testset3.csv")
    dataframetr = pandas.read_csv(r"/Users/krsingh/Desktop/datasets/newtraintdata7.csv")

    #dataframetr.month.replace(('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'),(1,2,3,4,5,6,7,8,9,10,11,12), inplace=True)
    #dataframetr.day.replace(('mon','tue','wed','thu','fri','sat','sun'),(1,2,3,4,5,6,7), inplace=True)
    featuredatatr=dataframetr.iloc[:, :14]
    targetvaluestr=dataframetr.iloc[:,14:]
    #dataframets.month.replace(('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'),(1,2,3,4,5,6,7,8,9,10,11,12), inplace=True)
    #dataframets.day.replace(('mon','tue','wed','thu','fri','sat','sun'),(1,2,3,4,5,6,7), inplace=True)
    featuredatats=dataframets.iloc[:, :14]
    targetvaluests=dataframets.iloc[:,14:]

    x_train=featuredatatr
    x_test=featuredatats
    y_train=targetvaluestr
    y_test=targetvaluests
    # SVM regularizaion parameter
    C = 1.0

    #Let's use different Kernel, whic is nothing but x_test
    #the functions mapping data to hyper dimension

    #SVC with a linear Kernel
    svc = svm.SVC(kernel = 'linear', C=C).fit(x_train, y_train)
    start = timer()
    predicted = svc.predict(x_test)
    end =timer()
    predicted = svc.predict(x_test)
    expected = y_test
    # Compare results
    lsvmaccuracy = metrics.accuracy_score(expected,predicted)
    lsvmprecision=metrics.precision_score(expected, predicted)
    lsvmrecall=metrics.recall_score(expected, predicted)

    print(lsvmaccuracy)
    print(lsvmprecision)
    print(lsvmrecall)
    print(end-start)

    from pyspark.ml import Pipeline

    from pyspark.ml.feature import StringIndexer
    from pyspark.ml.feature import VectorAssembler
    from pyspark.ml.evaluation import MulticlassClassificationEvaluator
    from pyspark.ml.feature import QuantileDiscretizer

    from pyspark.ml.classification import LinearSVC
    from pyspark.ml.evaluation import BinaryClassificationEvaluator
    spark = SparkSession \
        .builder \
        .appName("Spark ML example on data ") \
        .getOrCreate()

    datatrain= "/Users/krsingh/Desktop/datasets/newtraintdata7.csv"
    dftr = spark.read.csv(datatrain,header = 'True',inferSchema='True')
    datatest= "/Users/krsingh/Desktop/datasets/testset3.csv"
    dfts = spark.read.csv(datatest,header = 'True',inferSchema='True')

    '''indexers = [StringIndexer(inputCol=column, outputCol=column+"_index").fit(dftr) for column in ["month","day"]]
    pipeline = Pipeline(stages=indexers)
    dfdr = pipeline.fit(dftr).transform(dftr)

    indexers = [StringIndexer(inputCol=column, outputCol=column+"_index").fit(dfts) for column in ["month","day"]]
    pipeline = Pipeline(stages=indexers)
    dfds = pipeline.fit(dfts).transform(dfts)

    dftr = dftr.drop("Month","Day")

    dfts = dfts.drop("Month","Day")'''

    featuretr = VectorAssembler(
        inputCols=[x for x in dftr.columns],
        outputCol='features')
    feature_vector_tr= featuretr.transform(dftr)
    featurets = VectorAssembler(
        inputCols=[x for x in dfts.columns],
        outputCol='features')
    feature_vector_ts= featurets.transform(dfts)
    trainingData=feature_vector_tr
    testData=feature_vector_ts
    from pyspark.ml.classification import LinearSVC
    from pyspark.ml.evaluation import BinaryClassificationEvaluator
    svm = LinearSVC(labelCol="Fire", featuresCol="features")
    svm_model = svm.fit(trainingData)
    start1=timer()
    svm_prediction = svm_model.transform(testData)
    end1=timer()

    evaluator = MulticlassClassificationEvaluator(predictionCol='prediction', labelCol='Fire', metricName='accuracy')
    psvmaccuracy=evaluator.evaluate(svm_prediction)

    test=svm_prediction.drop("features","rawPrediction")
    print(psvmaccuracy)
    sns.set_palette("husl")
    firevsmonth = sns.lineplot(x="Month",y="Fire",data=svm_prediction.toPandas()).set_title('Fire')
    plt.savefig('/Users/krsingh/fyp_project/FYP/assets/output.png')
    plt.close()
    sns.set_palette("PuBuGn_d")
    predvsmonth = sns.lineplot(x="Month",y="prediction",data=svm_prediction.toPandas()).set_title('Predictions')
    plt.savefig('/Users/krsingh/fyp_project/FYP/assets/output1.png')
    plt.close()
    sns.set_palette("hls")
    intvsmonth = sns.lineplot(x="Month",y="Intensity",data=test.toPandas()).set_title('Fire Intenisty')
    plt.savefig('/Users/krsingh/fyp_project/FYP/assets/output2.png')
    plt.close()
    svm_pred=svm_prediction.toPandas()
    l=svm_pred.Fire
    y_pred=svm_pred.prediction
    from sklearn.metrics import classification_report, confusion_matrix
    print(metrics.precision_score(l, y_pred))
    print(metrics.recall_score(l, y_pred))
    print(end1-start1)
    #print(classification_report(l,y_pred))
    pd.set_option('colheader_justify', 'center')   # FOR TABLE
    def message (row):
        if row['Intensity']==2:
            return "SMALL FIRE ALERT !"
        elif row['Intensity']==3:
            return "WILD FIRE ALERT !!!"
        elif row['Intensity']==4:
            return "WILD FIRE ALERT !!!"
        else :
            return "----------"

    test=svm_prediction.drop("Year","Temp","RH","Wind","Rain","features","rawPrediction")
    test=test.filter(svm_prediction.prediction==1)
    test=test.filter(svm_prediction.Intensity>=2)
    test1=test.toPandas()
    test1['MESSAGE'] = test1.apply (lambda row: message(row), axis=1)

    from bs4 import BeautifulSoup
    with open("/Users/krsingh/fyp_project/FYP/FYP/template/pg2.html", "r") as f:
        contents = f.read()
        soup = BeautifulSoup(contents,'html.parser')
        ptag2 = soup.find("div",id='table_pd')
        if(ptag2):
            ptag2.decompose()
    f.close()
    if(soup):
        with open("/Users/krsingh/fyp_project/FYP/FYP/template/pg2.html", "w") as f:
            f.write(soup.prettify())
    f.close()
    html_string = '''

        {table}

    '''

    # OUTPUT AN HTML FILE
    with open('/Users/krsingh/fyp_project/FYP/FYP/template/pg2.html', 'a') as f:
        f.write(html_string.format(table=test1.to_html(classes='mystyle')))

    with open("/Users/krsingh/fyp_project/FYP/FYP/template/pg4.html", "r") as f:
        contents = f.read()
        soup = BeautifulSoup(contents,'html.parser')
        ptag2 = soup.find("div",id='table_pd')
        if(ptag2):
            ptag2.decompose()
    f.close()
    if(soup):
        with open("/Users/krsingh/fyp_project/FYP/FYP/template/pg4.html", "w") as f:
            f.write(soup.prettify())
    f.close()
    html_string = '''

        {table}

    '''

    # OUTPUT AN HTML FILE
    with open('/Users/krsingh/fyp_project/FYP/FYP/template/pg4.html', 'a') as f:
        f.write(html_string.format(table=test1.to_html(classes='mystyle')))

    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    import smtplib
    fromaddr = "ForestfireAlerts.gmail.com"
    toaddr = ["kars16cs@cmrit.ac.in","kmad16cs@cmrit.ac.in","kpne16cs@cmrit.ac.in","hata16cs@cmrit.ac.in","pushpa.m@cmrit.ac.in"]
    for i in range(len(toaddr)):
        html = open("/Users/krsingh/fyp_project/FYP/FYP/template/pg4.html")
        msg = MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = toaddr[i]
        msg['Subject'] = "Fire Alerts Report"
        part2 = MIMEText(html.read(), 'html')
        msg.attach(part2)
        debug = False
        if debug:
            print(msg.as_string())
        else:
            server = smtplib.SMTP('smtp.gmail.com',587)
            server.starttls()
            server.login("forestfire.alerts@gmail.com", "hmnk30241812")
            text = msg.as_string()
            server.sendmail(fromaddr, toaddr[i], text)
            server.quit()

main()


def sum_of_div(num):
    tot = 0
    for i in range(1, num // 2 + 1):
        if num % i == 0:
            tot += i
    return tot

#finds # of amicable below num
def amicables(num):
    tot = 0
    for i in range(1, num):
        if sum_of_div((sum_of_div(i))) == i and sum_of_div(i) != i:
            tot += i
    return tot

print(amicables(10000)) # -> 31626


from typing import Dict, Any, Tuple, Callable, Iterable, List, Union
import os.path

from jinja2 import Environment as JinjaEnvironment, Template, BaseLoader, TemplateNotFound

from mautrix.util import markdown

from maubot.loader import BasePluginLoader

class TemplateUtil:
    @staticmethod
    def pluralize(val: int, unit: str) -> str:
        if val == 1:
            return f"{val} {unit}"
        return f"{val} {unit}s"

    @classmethod
    def format_time(cls, seconds: Union[int, float], enable_days: bool = False) -> str:
        seconds = abs(seconds)
        frac_seconds = round(seconds - int(seconds), 1)
        minutes, seconds = divmod(int(seconds), 60)
        hours, minutes = divmod(minutes, 60)
        if enable_days:
            days, hours = divmod(hours, 24)
        else:
            days = 0
        parts = []
        if days > 0:
            parts.append(cls.pluralize(days, "day"))
        if hours > 0:
            parts.append(cls.pluralize(hours, "hour"))
        if minutes > 0:
            parts.append(cls.pluralize(minutes, "minute"))
        if seconds > 0 or len(parts) == 0:
            parts.append(cls.pluralize(seconds + frac_seconds, "second"))

        if len(parts) == 1:
            return parts[0]
        return ", ".join(parts[:-1]) + f" and {parts[-1]}"

    @staticmethod
    def join_human_list(data: List[str], *, joiner: str = ", ", final_joiner: str = " and ",
                        mutate: Callable[[str], str] = lambda val: val) -> str:
        if not data:
            return ""
        elif len(data) == 1:
            return mutate(data[0])
        return joiner.join(mutate(val) for val in data[:-1]) + final_joiner + mutate(data[-1])

class TemplateProxy:
    _env: JinjaEnvironment
    _args: Dict[str, Any]

    def __init__(self, env: JinjaEnvironment, args: Dict[str, Any]) -> None:
        self._env = env
        self._args = args

    def __getattr__(self, item: str) -> str:
        try:
            tpl = self._env.get_template(item)
        except TemplateNotFound:
            raise AttributeError(item)
        return tpl.render(**self._args)

class PluginTemplateLoader(BaseLoader):
    plugin_loader: BasePluginLoader
    directory: str
    macros: str

    def __init__(self, loader: BasePluginLoader, directory: str) -> None:
        self.plugin_loader = loader
        self.directory = directory
        self.macros = loader.sync_read_file("templates/macros.html").decode("utf-8")

    def get_source(self, environment: Any, name: str) -> Tuple[str, str, Callable[[], bool]]:
        path = f"{os.path.join(self.directory, name)}.html"
        try:
            tpl = self.plugin_loader.sync_read_file(path)
        except KeyError:
            raise TemplateNotFound(name)
        return self.macros + tpl.decode("utf-8"), name, lambda: True

    def list_templates(self) -> Iterable[str]:
        return [os.path.splitext(os.path.basename(path))[1]
                for path in self.plugin_loader.sync_list_files(self.directory)
                if path.endswith(".html")]

class TemplateManager:
    _env: JinjaEnvironment
    _loader: PluginTemplateLoader

    def __init__(self, loader: BasePluginLoader, directory: str) -> None:
        self._loader = PluginTemplateLoader(loader, directory)
        self._env = JinjaEnvironment(loader=self._loader, lstrip_blocks=True, trim_blocks=True,
                                     extensions=["jinja2.ext.do"], enable_async=True)
        self._env.filters["markdown"] = markdown.render

    def __getitem__(self, item: str) -> Template:
        return self._env.get_template(item)

    def proxy(self, args: Dict[str, Any]) -> TemplateProxy:
        return TemplateProxy(self._env, args)


#n-th fibonacci number (1 1 2 3 5 8 13..........)
n=31

a=0
b=1
print(a,b,end=" ")
for i in range(n-2):
    fibbo = a+b
    a = b
    b = fibbo
    print(f"{fibbo}",end=" ")


r"""Petri Net base."""

from __future__ import absolute_import

import functools

from . import trellis

from . import circuit
from . import operators
from .collections import sets

#############################################################################
#############################################################################

class Event(functools.partial):
    pass

#############################################################################
#############################################################################

Arc = operators.Pipe

@trellis.modifier
def link(arc, source, sink):
    arc.input = source
    arc.output = sink
    source.outputs.add(arc)
    sink.inputs.add(arc)

#############################################################################
#############################################################################

class Vertex(trellis.Component, circuit.Switch):
    """Has a set of input Arcs and a set of output Arcs."""

    Event = Event

    @trellis.maintain(make=sets.Set)
    def inputs(self):
        # O(n)
        inputs = self.inputs
        for input in inputs:
            if input.output is not self:
                input.output = self
        return inputs

    @trellis.maintain(make=sets.Set)
    def outputs(self):
        # O(n)
        outputs = self.outputs
        for output in outputs:
            if output.input is not self:
                output.input = self
        return outputs

#############################################################################
#############################################################################

class Condition(Vertex):
    r"""Simple condition that either has some marking or has no marking."""

    marking = trellis.attr(None)

    @trellis.modifier
    def send(self, marking=None):
        marking, self.marking = self.marking, marking
        return marking

    def next(self):
        if self.marking:
            yield self.Event(self.send)

#############################################################################
#############################################################################

class Transition(Vertex):
    """Simple three-step pipeline of operators."""

    Event = Event

    Multiplexer = operators.Combinator
    Demultiplexer = operators.Tee
    Pipe = operators.Pipe

    @trellis.maintain(make=lambda self: self.Multiplexer())
    def mux(self):
        mux = self.mux
        if mux.inputs is not self.inputs:
            mux.inputs = self.inputs
        if mux.output is not self.pipe:
            mux.output = self.pipe
        return mux

    @trellis.maintain(make=lambda self: self.Demultiplexer())
    def demux(self):
        demux = self.demux
        if demux.input is not self.pipe:
            demux.input = self.pipe
        if demux.outputs is not self.outputs:
            demux.outputs = self.outputs
        return demux

    @trellis.maintain(make=lambda self: self.Pipe())
    def pipe(self):
        pipe = self.pipe
        if pipe.input is not self.mux:
            pipe.input = self.mux
        if pipe.output is not self.demux:
            pipe.output = self.demux
        return pipe

    def next(self, *args, **kwargs):
        fn = self.pass_in(self.demux)
        Event = self.Event
        send = self.send
        for input in fn(*args, **kwargs):
            yield Event(send, input)

    def send(self, *args, **kwargs):
        fn = self.pass_out(self.mux)
        return fn(*args, **kwargs)

    # shortcut for executing the first default event
    def __call__(self, *args, **kwargs):
        for event in self.next(*args, **kwargs):
            break
        else: # no events
            raise StopIteration
        return event()

#############################################################################
#############################################################################

class Network(trellis.Component):

    @trellis.modifier
    def Arc(self, source, sink, Arc=Arc, **kwargs):
        arc = Arc(input=source, output=sink, **kwargs)
        link(arc, source, sink)
        return arc

    @trellis.modifier
    def Condition(self, Condition=Condition, *args, **kwargs):
        condition = Condition(*args, **kwargs)
        self.conditions.add(condition)
        return condition

    @trellis.modifier
    def Transition(self, Transition=Transition, *args, **kwargs):
        transition = Transition(*args, **kwargs)
        self.transitions.add(transition)
        return transition

    transitions = trellis.make(sets.Set)
    conditions = trellis.make(sets.Set)

    def next(self, transitions=iter, *args, **kwargs):
        transitions = transitions(self.transitions)
        for t in transitions:
            for event in t.next(*args, **kwargs):
                yield event

    @trellis.modifier
    def __call__(self, *args, **kwargs):
        for event in self.next(*args, **kwargs):
            break
        else:
            raise StopIteration
        return event()

#############################################################################
#############################################################################


#nome = str(input('Qual é o seu nome: '))
#if nome == 'Gustavo':
#    print('Que nome lindo!')
#print('Bom dia {}!'.format(nome))

#nome = str(input('Qual é o seu nome: '))
#if nome == 'Gustavo':
 #   print('Que nome lindo!')
#else:
 #   print('Que nome tão normal...')
#print('Bom dia {}!'.format(nome))

n1 = float(input('Escreva a primeira nota: '))
n2 = float(input('Escreva a segunda nota: '))
m = (n1 + n2)/2
print('A tua média é: {:.2f}'.format(m))
print('Parabens!' if m >= 6 else 'Estude mais!')


class Paitent:
    def __init__(self , id, name , age , bloodGroup) -> None:
        self.id , self.name, self.age , self.bloodGroup = id , name , age , bloodGroup
        self.next = None
        self.prev = None

    def __str__(self) -> str:
        return f"ID: {self.id} Name: {self.name}"

class WRM:

    def __init__(self) -> None:
        self.dummy = Paitent(None , None , None , None)

    def RegisterPaitent(self , id , name , age , bloodGroup):
        toBeRegistered = Paitent(id , name , age , bloodGroup)

        if self.dummy.next == None:
            self.dummy.next = toBeRegistered
            self.dummy.prev = toBeRegistered

        else:
            lastPaitent = self.dummy.prev
            lastPaitent.next = toBeRegistered
            toBeRegistered.prev = lastPaitent
            self.dummy.prev = toBeRegistered

        print(f"Succesfully Registerd patient {name}")

    def ServePaitent(self):

        if self.dummy.next == None:
            print("No paitent is in the queue")
        else:
            print(f'{self.dummy.next.name} is served')
            self.dummy.next = self.dummy.next.next

    def CancelAll(self):
        self.dummy.next = None
        print("All appointments are cancelled")

    def CanDoctorGoHome(self):
        if self.dummy.next == None:
            return True
        return False

    def ShowAllPaitents(self):

        if self.dummy.next == None:
            print("No paitent is in the queue")
        else:
            current = self.dummy.next
            while current != None:
                print(current)
                current = current.next

# Test

waitingRoom = WRM()

while True:
    print("1. Register Paitent")
    print("2. Serve Paitent")
    print("3. Cancel All")
    print("4. Can Doctor Go Home")
    print("5. Show All Paitents")
    print("6. Exit")
    choice = int(input("Enter your choice: "))

    if choice == 1:
        __id = int(input("Enter ID: "))
        __name = input("Enter Name: ")
        __age = int(input("Enter Age: "))
        __bloodGroup = input("Enter Blood Group: ")
        waitingRoom.RegisterPaitent(__id , __name , __age , __bloodGroup)
    elif choice == 2:
        waitingRoom.ServePaitent()
    elif choice == 3:
        waitingRoom.CancelAll()
    elif choice == 4:
        print(waitingRoom.CanDoctorGoHome())
    elif choice == 5:
        waitingRoom.ShowAllPaitents()
    elif choice == 6:
        break
    else:
        print("Invalid Choice")


#pygamerpi.py by Aaron Becker
#C.OS. V1

#imports
import pygame
from pygame.locals import *
import os
import sys
import math
from time import sleep
from socketIO_client import SocketIO, LoggingNamespace
from datetime import datetime
from multiprocessing.pool import Pool
from screeninfo import get_monitors

#color definitions
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
#mons = get_monitors('osx')
mons = {}
if len(mons) > 1:
    print("More than 1 monitor detected! Using first monitor.")
    monitor = mons[0]
elif len(mons) == 0:
    print("No monitors detected. Using default resolution.")
    monitor = { "width": 640, "height": 480 }
else:
    print("Monitor detected")
    monitor = mons[0]

print("init: monitor width, height "+str(monitor["width"]),str(monitor["height"]))
x = 0
y = 0
socketin = []
global socket

#socket recieve functions
def on_recieve(*data):
    global socketin
    socketin.append(str(data)[2:len(str(data))-3])

def socket_connected(*data):
    print('Connected to socket.io :)')

def py_ready(*data):
    socket.emit('pyok','')

#start pygame
pygame.init()
pygame.mouse.set_visible(True)
screen = pygame.display.set_mode((monitor["width"], monitor["height"]),pygame.RESIZABLE)
width, height = screen.get_size()
pygame.display.set_caption('C.OS. V1')
screen.fill((0,0,0))
pygame.display.update()

if not pygame.font: print ('PYGAME: Warning, fonts disabled')
if not pygame.mixer: print ('PYGAME: Warning, sound disabled')

#pygame loop
if pygame.font:
    font_big = pygame.font.Font(None, 50)
    font_small = pygame.font.Font(None, 20)
    font_med = pygame.font.Font(None, 35)
else:
    print ("Error with font")
    raise (SystemError, "Error with font")
    #font_big = fakeFont(None, 50) #make a fake font so pygame throws no errors

"""class fakeFont(type):
    def __init__(self, *args, **kwargs):
        print("fake font init")
    def render(self, *args, **kwargs):
        print("fake font render")"""

#load sound function
def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer:
        return NoneSound()
    fullname = os.path.join('data', name)
    try:
        sound = pygame.mixer.Sound(fullname)
    except (pygame.error, message):
        print ('Cannot load sound:', wav)
        raise (SystemExit, message)
    return sound

#load image function
def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    except (pygame.error, message):
        print ('Cannot load image:', name)
        raise (SystemExit, message)
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()

def map(value, leftMin, leftMax, rightMin, rightMax):
    # Figure out how 'wide' each range is
    leftSpan = leftMax - leftMin
    rightSpan = rightMax - rightMin

    # Convert the left range into a 0-1 range (float)
    valueScaled = float(value - leftMin) / float(leftSpan)

    # Convert the 0-1 range into a value in the right range.
    return rightMin + (valueScaled * rightSpan)

def render_font(font,scr,text,color,x,y):
    text_surface = font.render(text, True, color)
    rect = text_surface.get_rect(center=(x,y))
    scr.blit(text_surface, rect)
    pygame.display.update()

def clr_rect(x,y,width,height):
    #if type(thicc) != int or type(thicc) != float:
    #    thicc = 0
    pygame.draw.rect(screen, BLACK, (int(x), int(y), width, height), 0)
    pygame.display.update()

def sgn(num):
    if (num < 0):
        return -1
    elif (num == 0):
        return 0
    elif (num > 0):
        return 1
    else:
        return "err"
#init function
def intro():
    screen.fill(BLACK)
    pygame.draw.circle(screen, WHITE, (int(width/2), int(height/2)), 70, 2) #draw circle
    render_font(font_med,screen,"Car OS",RED,width/2,(height/2)-10)
    render_font(font_big,screen,"V1",RED,width/2,(height/2)+25)
    pygame.display.update()

    steps = 8 #degree steps (16 and 8 are good)
    rad = 70 #radius
    dist = 100 #distance to travel along line
    finalang = 180
    mag = 5 #sin magnitude
    i = finalang/steps
    pixobj = pygame.PixelArray(screen)
    while int(i) > 0:
        angleoffset = steps*i/(finalang/360)
        if (i*steps > 180):
            ptstartx = (width/2)+(rad*math.cos(angleoffset)) #calculate starting point on circle
            ptstarty = (height/2)+(rad*math.sin(angleoffset))

            ptendx = ptstartx+(dist*math.cos(angleoffset)) #calculate end point
            ptendy = ptstarty+(dist*math.sin(angleoffset))
        else:
            ptstartx = (width/2)-(rad*math.cos(angleoffset)) #calculate starting point on circle
            ptstarty = (height/2)-(rad*math.sin(angleoffset))

            ptendx = ptstartx-(dist*math.cos(angleoffset)) #calculate end point
            ptendy = ptstarty-(dist*math.sin(angleoffset))
        print("psx:"+str(ptstartx)+", psy: "+str(ptstarty)+", off: "+str(angleoffset))

        pygame.draw.line(screen, YELLOW, (ptstartx, ptstarty), (ptendx, ptendy), 2)
        pygame.display.update()
        #sleep(0.025)
        """dx = ptendx - ptstartx
        dy = ptendy - ptstarty
        deltaerror = abs(dy/ dx)
        error = 0
        y = ptstarty

        for x in range(int(ptstartx), int(ptendx+1)):
            pixobj[int(x)][int(y)] = GREEN
            error += deltaerror
            while error >= 0.5:
                y += sgn(dy)
                error -= 1
            pygame.display.update()"""

        """j = 0
        while j < pts:
            #apply sin functin
            #x = ptstartx+j
            #y = ptstarty+(((angleoffset/10)*x)+(((angleoffset/5)+1)*math.sin(x)))
            #jk to complex just travel in a straight line
            print(int(x),int(y))
            pixobj[int(x)][int(y)] = GREEN
            j+=1
            pygame.display.update()"""
        i-=1
        print (i)
    print("init seq done")
    del pixobj
    sleep(0.5)

    def clr_text():
        clr_rect(100,height-70,width,40)

    i = 0
    while int(i) < 10:
        if int(i) == 0:
            render_font(font_med,screen,"Initializing websockets...",WHITE,width/2,height-50)

            #setup socket
            global socket
            socket = SocketIO( 'localhost', 80, LoggingNamespace );
            import logging
            logging.getLogger('socketIO-client').setLevel(logging.DEBUG)
            logging.basicConfig()
            socket.emit('initpython', 'ready');
        elif int(i) == 1:
            clr_text()
            render_font(font_med,screen,"Websockets initialized.",WHITE,width/2,height-50)
            sleep(1)
            clr_text()
            render_font(font_med,screen,"Attaching socket listeners...",WHITE,width/2,height-50)

            #setup socket functions
            socket.on('connect', socket_connected )
            socket.on('pyready', py_ready )
            socket.on('pydata', on_recieve )
            socket.wait(seconds=1)
        elif int(i) == 2:
            clr_text()
            render_font(font_med,screen,"Socket listeners attached.",WHITE,width/2,height-50)
            sleep(1)
        else:
            print (i)
        i+=1

intro()
running = True
fs = False
while running:
    screen.fill(BLACK)
    for event in pygame.event.get():
        if(event.type is pygame.MOUSEMOTION):
            pos = pygame.mouse.get_pos()
            print (pos)
            #Find which quarter of the screen we're in
            x,y = pos
        elif(event.type == pygame.QUIT):
            running = False
            socket.emit('pydisconnect','')
            print('Sending pydisconnect event...')
            pygame.quit()
    keys = pygame.key.get_pressed()
    i = 0
    while i < len(keys):
        if keys[i] == 1:
            print (i)
        i+=1
    print (pygame.key.get_mods())
    if (pygame.key.get_mods() == 1024 and (keys[113] == 1 or keys[119] == 1)) or keys[27] == 1:
        pygame.quit()
    if pygame.key.get_mods() == 1024 and keys[102] == 1:
        if fs == False:
            screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
            fs = True
        else:
            screen = pygame.display.set_mode((width,height - 120),pygame.RESIZABLE)
            fs = False
    pt = " "
    for ev in socketin:
        command = ev[:1]
        value = ev[2:]
        if (command=="p"):
            pt+=value
        print ("EvQueue processing: "+command+" "+value)
        socketin.remove(ev)
    text_surface = font_big.render(str(x)+","+str(y)+","+pt, True, WHITE)
    rect = text_surface.get_rect(center=(160,120))
    screen.blit(text_surface, rect)
    pygame.display.update()
    #now = datetime.now()
    #socket.emit( 'python', now.strftime( "%-d %b %Y %H:%M:%S.%f" ) )
    socket.wait(seconds=0.1)


import pandas as pd

data = {"Name": ["Ram", "Sam", "Prabhu"],
        "Account Number": ["9893893891", "9893893898", "9893893871"],
        "Account Type": ["SB", "CA", "SB"],
        "Adhaar_No": ["95938938173", "95938938179", "95938938159"],
        "Balance": ["8989839", "7690990", "989330"]}

data1 = {"Name": ["Ram", "Sam", "Prabhu"],
         "Adhaar_No": ["95938938173", "95938938179", "95938938159"],
         "Contact No.": ["9840787333", "9840787343", "9840787353"],
         "Dob": ['12-2-1990', '12-2-2000', '12-2-2010'],
         "Address": ['No 23 ,kandigai,chennai 127', 'No 73 ,Melakottaiyuru ,chennai 127', 'No 43 ,Anna Nagar,chennai 127']}

df = pd.DataFrame(data)
df.to_csv('cs20b1100_SBIAccountHolder.csv', index=False, sep='\t')

df1 = pd.DataFrame(data1)
df1.to_csv('cs20b1100_Aadhar.csv', index=False, sep='\t')

print("================ Menu ==================")
print("1. Add an Account Holder Details")
print("2. Delete an Account Holder Details")
print("3. Credit")
print("4. Debit")
print("5. Print Account Details")
print("6. Merge & Exit")
while 1:
    opt = int(input("Enter your option: "))
    if opt == 1:
        df.loc[len(df.index)] = ['Anuj', "9893893801",
                                 "SB", "95938938101", "1000000"]
        df.loc[len(df.index)] = ['Chow', "9893893802",
                                 "CA", "95938938102", "9999999"]
        df.to_csv('cs20b1100_SBIAccountHolder.csv', index=False, sep='\t')
        print(df)
    elif opt == 2:
        df = df.drop([0])
        df.to_csv('cs20b1100_SBIAccountHolder.csv', index=False, sep='\t')
        print(df)
    elif opt == 3:
        accNo = input("Enter Account Number: ")
        amo = int(input("Enter Amount: "))
        df.loc[df['Account Number'] == accNo, 'Balance'] = str(
            int(df.loc[df['Account Number'] == accNo, 'Balance']) + amo)
        df_acc = df[df['Account Number'] == accNo]
        df.to_csv('cs20b1100_SBIAccountHolder.csv', index=False, sep='\t')
        print(df_acc)
    elif opt == 4:
        accNo = input("Enter Account Number: ")
        amo = int(input("Enter Amount: "))
        if int(df.loc[df['Account Number'] == accNo, 'Balance']) > amo:
            df.loc[df['Account Number'] == accNo, 'Balance'] = str(
                int(df.loc[df['Account Number'] == accNo, 'Balance']) - amo)
            df_acc = df[df['Account Number'] == accNo]
            df.to_csv('cs20b1100_SBIAccountHolder.csv', index=False, sep='\t')
            print(df_acc)
        else:
            print("insufficient balance")
    elif opt == 5:
        accNo = input("Enter Account Number: ")
        df_acc = df[df['Account Number'] == accNo]
        print(df_acc)
    elif opt == 6:
        df3 = pd.merge(df, df1, on='Name', how='left')
        df3.to_csv('cs20b1100_Merge.csv', index=False, sep='\t')
        print(df3)
        print("Exited")
        break


# coding: utf-8
from utils import utils
from utils.utils import varname

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

from layers import layers
import layers.operations as op

from collections import OrderedDict
import itertools
import os
import sys
import pickle

from losses.loss import CrossEntropyLoss
from optimizers.optimizer import AdamOptimizer

logger = utils.get_logger()

def tensor_hook(grad):
    print('grad:', grad)
    input("\nnext hook:")

def tensor_info(tensor):
    print (tensor)
    tensor.register_hook(tensor_hook)
    input("\nnext tensor:")

def output_result(predictions, params):
    scores = None
    labels = predictions[2]["target"]
    if isinstance(predictions[0][0], list):
        scores = [s[1] for s in predictions[0]]
    else:
        scores = predictions[0]

    with open(params["file_name"], 'w', encoding="utf-8") as f:
        for score, label in zip(scores, labels):
            f.write("{}\t{}\n".format(score, label))

class DAMModel(nn.Module):
    """DAM Module contains ."""

    def __init__(self, config):
        super(DAMModel, self).__init__()
        # hyperparameters
        embeddings = config["embeddings"] if "embeddings" in config else None
        self.vocabulary_size = config["vocabulary_size"] if "vocabulary_size" in config else 434511
        self.word_embedding_size = config["embedding_dim"] if "embedding_dim" in config else 200
        self.max_num_utterance = config["max_num_utterance"] if "max_num_utterance" in config else 10
        self.max_sentence_len = config["max_sentence_len"] if "max_sentence_len" in config else 50

        self.is_positional = config["is_positional"] if "is_positional" in config else False
        self.stack_num = config["stack_num"] if "stack_num" in config else 5

        self.head_num = config["head_num"] if "head_num" in config else 0

        self.is_layer_norm = config["is_layer_norm"] if "is_layer_norm" in config else True
        self.drop_prob = config["drop_prob"] if "drop_prob" in config else None

        self.attention_type = config["attention_type"] if "attention_type" in config else "dot"
        self.is_mask = config["is_mask"] if "is_mask" in config else True

        self.final_out_features = config["final_out_features"] if "final_out_features" in config else 2

        self.embeddings_trainable = config["emb_trainable"] if "emb_trainable" in config else True
        self.device = config["device"]

        # build model
        ## Embedding
        self.embeddings = op.init_embedding(self.vocabulary_size, self.word_embedding_size, embeddings=embeddings,
                                            embeddings_trainable=self.embeddings_trainable)

        self.position_encoder = layers.PositionEncoder({"lambda_size": self.max_sentence_len, "max_timescale": 10})

        self.self_blocks = nn.ModuleList()
        for index in range(self.stack_num):
            if self.head_num <= 0:
                self.self_blocks.append(layers.AttentiveModule(
                    {"name": "self_block_{}".format(index), "x_dim": self.word_embedding_size,
                     "y_dim": self.word_embedding_size, "is_layer_norm": self.is_layer_norm,
                     "drop_prob": self.drop_prob}))
            else:
                self.self_blocks.append(layers.MultiHeadedAttentiveModule(
                    {"name": "self_block_{}".format(index), "x_dim": self.word_embedding_size,
                     "y_dim": self.word_embedding_size, "head_num": self.head_num, "is_layer_norm": self.is_layer_norm,
                     "drop_prob": self.drop_prob}))

        self.t_a_r_blocks = nn.ModuleList()
        for index in range(self.stack_num + 1):
            if self.head_num <= 0:
                self.t_a_r_blocks.append(layers.AttentiveModule(
                    {"name": "t_a_r_block_{}".format(index), "x_dim": self.word_embedding_size,
                     "y_dim": self.word_embedding_size, "is_layer_norm": self.is_layer_norm,
                     "drop_prob": self.drop_prob}))
            else:
                self.t_a_r_blocks.append(layers.MultiHeadedAttentiveModule(
                    {"name": "t_a_r_block_{}".format(index), "x_dim": self.word_embedding_size,
                     "y_dim": self.word_embedding_size, "head_num": self.head_num, "is_layer_norm": self.is_layer_norm,
                     "drop_prob": self.drop_prob}))

        self.r_a_t_blocks = nn.ModuleList()
        for index in range(self.stack_num + 1):
            if self.head_num <= 0:
                self.r_a_t_blocks.append(layers.AttentiveModule(
                    {"name": "r_a_t_block_{}".format(index), "x_dim": self.word_embedding_size,
                     "y_dim": self.word_embedding_size, "is_layer_norm": self.is_layer_norm,
                     "drop_prob": self.drop_prob}))
            else:
                self.r_a_t_blocks.append(layers.MultiHeadedAttentiveModule(
                    {"name": "r_a_t_block_{}".format(index), "x_dim": self.word_embedding_size,
                     "y_dim": self.word_embedding_size, "head_num": self.head_num, "is_layer_norm": self.is_layer_norm,
                     "drop_prob": self.drop_prob}))

        self.creat_conv()

        in_features = op.calculate_dim_with_initialDim_conv(
            (self.max_num_utterance, self.max_sentence_len, self.max_sentence_len), self.conv)

        self.final = nn.Linear(in_features=in_features, out_features=self.final_out_features)

        # self._reset_parameters()

    def creat_conv(self):
        # calculate padding
        input_shape = (self.max_num_utterance, self.max_sentence_len, self.max_sentence_len)
        conv1_padding, output_shape = op.calculate_padding_for_cnn(input_shape, (3, 3, 3), (1, 1, 1))
        maxpool1_padding, output_shape = op.calculate_padding_for_cnn(output_shape, (3, 3, 3), (3, 3, 3))
        conv2_padding, output_shape = op.calculate_padding_for_cnn(output_shape, (3, 3, 3), (1, 1, 1))
        maxpool2_padding, output_shape = op.calculate_padding_for_cnn(output_shape, (3, 3, 3), (3, 3, 3))
        # creat conv
        self.conv = nn.Sequential(
            nn.Conv3d(in_channels=2 * (self.stack_num + 1), out_channels=32, kernel_size=(3, 3, 3), stride=(1, 1, 1),
                      padding=conv1_padding),
            nn.ELU(inplace=True),
            nn.MaxPool3d(kernel_size=(3, 3, 3), stride=(3, 3, 3), padding=maxpool1_padding),
            nn.Conv3d(in_channels=32, out_channels=16, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=conv2_padding),
            nn.ELU(inplace=True),
            nn.MaxPool3d(kernel_size=(3, 3, 3), stride=(3, 3, 3), padding=maxpool2_padding),
        )

    def _reset_parameters(self):
        # CNN
        stdv = 0.01
        self.conv[0].weight.data.uniform_(-stdv, stdv)
        self.conv[0].bias.data.fill_(0)
        self.conv[3].weight.data.uniform_(-stdv, stdv)
        self.conv[3].bias.data.fill_(0)

    def forward(self, inputs):
        device = inputs["target"].device
        dtype = torch.get_default_dtype()
        # response part
        Hr = self.embeddings(inputs["resp"]) # [batch, max_sentence_len, emb_size]
        response_len = inputs["resp_len"]

        if self.is_positional and self.stack_num > 0:
            Hr = self.position_encoder(Hr)  # [batch, max_sentence_len, emb_size]
        Hr_stack = [Hr]

        for index in range(self.stack_num):
            Hr = self.self_blocks[index](Hr, Hr, Hr, Q_lengths=response_len, K_lengths=response_len,
                                         attention_type=self.attention_type, is_mask=self.is_mask)
            Hr_stack.append(Hr)

        # context part
        bHu = self.embeddings(inputs["utt"])    # [batch, max_num_utterance, max_sentence_len, emb_size]
        utterance_len = inputs["utt_len"]   # [batch, max_num_utterance]

        shape_save = bHu.shape[:-2]

        bHu = bHu.view(-1, *bHu.shape[-2:]) # [batch * max_num_utterance, max_sentence_len, emb_size]
        b_utterance_len = utterance_len.view(-1)   # [batch * max_num_utterance]

        if self.is_positional and self.stack_num > 0:
            bHu = self.position_encoder(bHu)    # [batch * max_num_utterance, max_sentence_len, emb_size]
        bHu_stack = [bHu.view(*shape_save, *bHu.shape[-2:])]    # [batch, max_num_utterance, max_sentence_len, emb_size]

        for index in range(self.stack_num):
            bHu = self.self_blocks[index](bHu, bHu, bHu, Q_lengths=b_utterance_len, K_lengths=b_utterance_len,
                                         attention_type=self.attention_type, is_mask=self.is_mask)  # [batch * max_num_utterance, max_sentence_len, emb_size]
            bHu_stack.append(bHu.view(*shape_save, *bHu.shape[-2:]))    # [batch, max_num_utterance, max_sentence_len, emb_size]

        b_t_a_r_stack = []
        b_r_a_t_stack = []

        for index in range(self.stack_num + 1):
            b_t_a_r = []
            b_r_a_t = []
            for Hu, utt_len in zip(bHu_stack[index].transpose(0, 1), utterance_len.transpose(0, 1)):
                t_a_r = self.t_a_r_blocks[index](Hu, Hr_stack[index], Hr_stack[index], Q_lengths=utt_len,
                                                 K_lengths=response_len, attention_type=self.attention_type,
                                                 is_mask=self.is_mask)  # [batch, max_sentence_len, emb_size]
                r_a_t = self.r_a_t_blocks[index](Hr_stack[index], Hu, Hu, Q_lengths=response_len,
                                                 K_lengths=utt_len, attention_type=self.attention_type,
                                                 is_mask=self.is_mask)  # [batch, max_sentence_len, emb_size]
                b_t_a_r.append(t_a_r)
                b_r_a_t.append(r_a_t)
            b_t_a_r = torch.stack(b_t_a_r, dim=1)   # [batch, max_num_utterance, max_sentence_len, emb_size]
            b_r_a_t = torch.stack(b_r_a_t, dim=1)   # [batch, max_num_utterance, max_sentence_len, emb_size]

            b_t_a_r_stack.append(b_t_a_r)
            b_r_a_t_stack.append(b_r_a_t)

        bHu = torch.stack(bHu_stack, dim=1) # [batch, stack_num+1, max_num_utterance, max_sentence_len, emb_size]
        Hr = torch.stack(Hr_stack, dim=1)    # [batch, stack_num+1, max_sentence_len, emb_size]
        sim_1 = torch.einsum("bsaik,bsjk->bsaij", (bHu, Hr))    # [batch, stack_num+1, max_num_utterance, max_sentence_len, max_sentence_len]

        b_t_a_r = torch.stack(b_t_a_r_stack, dim=1) # [batch, stack_num+1, max_num_utterance, max_sentence_len, emb_size]
        b_r_a_t = torch.stack(b_r_a_t_stack, dim=1) # [batch, stack_num+1, max_num_utterance, max_sentence_len, emb_size]
        sim_2 = torch.einsum("bsaik,bsajk->bsaij", (b_t_a_r, b_r_a_t))  # [batch, stack_num+1, max_num_utterance, max_sentence_len, max_sentence_len]
        # sim shape [batch, 2*(stack_num+1), max_num_utterance, max_sentence_len, max_sentence_len]
        sim = torch.cat((sim_2, sim_1), dim=1) / torch.sqrt(torch.tensor([200], dtype=dtype, device=device))

        final_info = self.conv(sim) # final_info shape [batch, 16, 4, 4, 4]

        logits = self.final(final_info.view(final_info.shape[0], -1)) # logits shape [batch, 1]

        # utils.varname(logits, fn=tensor_info)

        return logits.squeeze(-1)

if __name__ == "__main__":
    dam = DAMModel({"device": torch.device("cpu")})

    # for k, v in dam.named_parameters():
    #     logger.info("{}".format(k))

    utt_inputs = torch.randint(0, 434511, (1, 10, 50), dtype=torch.int64)
    utt_inputs = torch.cat([utt_inputs] * 2, dim=0)
    utt_len_inputs = torch.sum(utt_inputs != 0, dim=-1)
    resp_inputs = torch.randint(0, 434511, (2, 50), dtype=torch.int64)
    resp_len_inputs = torch.sum(resp_inputs != 0, dim=-1)
    targets = torch.tensor([1, 0], dtype=torch.int64)
    inputs = {
        "utt": utt_inputs,
        "utt_len": utt_len_inputs,
        "resp": resp_inputs,
        "resp_len": resp_len_inputs,
        "target": targets
    }
    loss_fn = CrossEntropyLoss({})
    optimizer = AdamOptimizer(dam.parameters(), lr=0.001)

    for i in range(100):
        dam.train()
        optimizer.zero_grad()
        logits = dam(inputs)
        loss, num_labels, batch_total_loss = loss_fn(logits, inputs["target"])
        loss.backward()
        optimizer.step()

        print ("epoch: {}".format(i + 1))
        print(logits)
        print(torch.nn.functional.softmax(logits, dim=-1))
        print(loss.item(), end="\n\n")


from operator import itemgetter

from ..utils.table import ROW_SEPARATOR, render_table
from ..utils.text import bold, mark_for_translation as _
from ..utils.ui import page_lines

def bw_stats(repo, args):
    items = {}
    metadata_defaults = set()
    metadata_reactors = set()
    for node in repo.nodes:
        for metadata_default_name, metadata_default in node.metadata_defaults:
            metadata_defaults.add(metadata_default_name)
        for metadata_reactor_name, metadata_reactor in node.metadata_reactors:
            metadata_reactors.add(metadata_reactor_name)
        for item in node.items:
            items.setdefault(item.ITEM_TYPE_NAME, 0)
            items[item.ITEM_TYPE_NAME] += 1

    rows = [
        [
            bold(_("count")),
            bold(_("type")),
        ],
        ROW_SEPARATOR,
        [str(len(repo.nodes)), _("nodes")],
        [str(len(repo.groups)), _("groups")],
        [str(len(repo.bundle_names)), _("bundles")],
        [str(len(metadata_defaults)), _("metadata defaults")],
        [str(len(metadata_reactors)), _("metadata reactors")],
        [str(sum([len(list(node.items)) for node in repo.nodes])), _("items")],
        ROW_SEPARATOR,
    ]

    for item_type, count in sorted(items.items(), key=itemgetter(1), reverse=True):
        rows.append([str(count), item_type])

    page_lines(render_table(rows, alignments={0: 'right'}))


import socket
tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_sock.bind(("", 8080))
tcp_sock.listen(128)
new_socket, cli_addr = tcp_sock.accept()
while True:
    recv_data = new_socket.recv(1024)
    print("recv_data = ", recv_data.decode())
    new_socket.send("ok\n".encode())
new_socket.close()
tcp_sock.close()


from .common import Extractor, Message
from .. import text
import re

BASE_PATTERN = r"(?:https://)?(?:www\.|m\.)?vk\.com"

class VkExtractor(Extractor):
    """Base class for vk extractors"""
    category = "vk"
    directory_fmt = ("{category}", "{user[name]|user[id]}")
    filename_fmt = "{id}.{extension}"
    archive_fmt = "{id}"
    root = "https://vk.com"
    request_interval = 1.0

    def items(self):
        data = self.metadata()
        yield Message.Directory, data
        for photo in self.photos():
            photo.update(data)
            yield Message.Url, photo["url"], photo

    def _pagination(self, photos_url, user_id):
        sub = re.compile(r"/imp[fg]/").sub
        needle = 'data-id="{}_'.format(user_id)
        cnt = 0

        headers = {
            "X-Requested-With": "XMLHttpRequest",
            "Origin"          : self.root,
            "Referer"         : photos_url,
        }
        params = {
            "al"    : "1",
            "al_ad" : "0",
            "offset": 0,
            "part"  : "1",
        }

        while True:
            payload = self.request(
                photos_url, method="POST", headers=headers, data=params
            ).json()["payload"][1]

            offset = payload[0]
            html = payload[1]

            for cnt, photo in enumerate(text.extract_iter(html, needle, ')')):
                pid = photo[:photo.find('"')]
                url = photo[photo.rindex("(")+1:]
                url = sub("/", url.partition("?")[0])
                yield text.nameext_from_url(url, {"url": url, "id": pid})

            if cnt <= 20 or offset == params["offset"]:
                return
            params["offset"] = offset

class VkPhotosExtractor(VkExtractor):
    """Extractor for photos from a vk user"""
    subcategory = "photos"
    pattern = (BASE_PATTERN + r"/(?:"
               r"(?:albums|photos|id)(-?\d+)"
               r"|(?!album-?\d+_)([^/?#]+))")
    test = (
        ("https://vk.com/id398982326", {
            "pattern": r"https://sun\d+-\d+\.userapi\.com/c\d+/v\d+"
                       r"/[0-9a-f]+/[\w-]+\.jpg",
            "count": ">= 35",
            "keywords": {
                "id": r"re:\d+",
                "user": {
                    "id": "398982326",
                    "info": "Мы за Движуху! – m1ni SounD #4 [EROmusic]",
                    "name": "",
                    "nick": "Dobrov Kurva",
                },
            },
        }),
        ("https://vk.com/cosplayinrussia", {
            "range": "75-100",
            "keywords": {
                "id": r"re:\d+",
                "user": {
                    "id"  : "-165740836",
                    "info": "Предложка открыта, кидайте ваши косплейчики. При "
                            "правильном оформлении они будут опубликованы",
                    "name": "cosplayinrussia",
                    "nick": "Косплей | Cosplay 18+",
                },
            },
        }),
        ("https://m.vk.com/albums398982326"),
        ("https://www.vk.com/id398982326?profile=1"),
        ("https://vk.com/albums-165740836"),
    )

    def __init__(self, match):
        VkExtractor.__init__(self, match)
        self.user_id, self.user_name = match.groups()

    def photos(self):
        url = "{}/photos{}".format(self.root, self.user_id)
        return self._pagination(url, self.user_id)

    def metadata(self):
        if self.user_id:
            user_id = self.user_id
            prefix = "public" if user_id[0] == "-" else "id"
            url = "{}/{}{}".format(self.root, prefix, user_id.lstrip("-"))
            data = self._extract_profile(url)
        else:
            url = "{}/{}".format(self.root, self.user_name)
            data = self._extract_profile(url)
            self.user_id = data["user"]["id"]
        return data

    def _extract_profile(self, url):
        extr = text.extract_from(self.request(url).text)
        return {"user": {
            "name": text.unescape(extr(
                'rel="canonical" href="https://vk.com/', '"')),
            "nick": text.unescape(extr(
                '
', "<")).replace("  ", " "),
            "info": text.unescape(text.remove_html(extr(
                '', '</span'))),
            "id"  : extr('<a href="/albums', '"'),
        }}

class VkAlbumExtractor(VkExtractor):
    """Extractor for a vk album"""
    subcategory = "album"
    directory_fmt = ("{category}", "{user[id]}", "{album[id]}")
    pattern = BASE_PATTERN + r"/album(-?\d+)_(\d+)$"
    test = (
        ("https://vk.com/album221469416_0", {
            "count": 3,
        }),
        ("https://vk.com/album-165740836_281339889", {
            "count": 12,
        }),
    )

    def __init__(self, match):
        VkExtractor.__init__(self, match)
        self.user_id, self.album_id = match.groups()

    def photos(self):
        url = "{}/album{}_{}".format(self.root, self.user_id, self.album_id)
        return self._pagination(url, self.user_id)

    def metadata(self):
        return {
            "user": {"id": self.user_id},
            "album": {"id": self.album_id},
        }


# EJERCICIO 1

abecedario = 'abcdefghijklmnñopqrstuvwxyz'

corrimiento = int(input("Corrimiento: "))

for x in range(5):
    palabra = ""
    frase = input(f"Ingrese la frase {x+1}: ")
    for letra in frase:
        letra = letra.lower()
        if letra in abecedario:
            palabra += abecedario[(abecedario.index(letra)+corrimiento)%27]
    print(palabra)

# EJERCICIO 2

continuar = True
total_pares = 0
total_impares = 0

while continuar:
    numero = int(input("Ingrese un numero entero positivo: "))
    par = 0
    impar = 0
    if numero != 0 and numero >0:
        for n in str(numero):
            if int(n)%2==0:
                par += 1
                total_pares += 1
            else:
                impar += 1
                total_impares += 1
        print(f"La cantidad de digitos impares son: {impar}")
        print(f"La cantidad de digitos par son: {par}")
    else:
        print(f"La cantidad de digitos totales impares son: {total_impares}")
        print(f"La cantidad de digitos totales par son: {total_pares}")
        continuar = False


import random

choices = {
    "s": "scissors",
    "p": "paper",
    "r": "rock"
}

def get_player_choice():
    choice = input("Choose scissors (s), paper (p), or rock (r): ").lower()
    while choice not in choices:
        choice = input("Invalid choice. Please choose scissors (s), paper (p), or rock (r): ").lower()
    return choices[choice]

def play_game():
    player_choice = get_player_choice()
    computer_choice = random.choice(list(choices.values()))
    print(f"Computer chose {computer_choice}.")
    if player_choice == computer_choice:
        print("It's a tie!")
    elif player_choice == "scissors" and computer_choice == "paper":
        print("You win!")
    elif player_choice == "paper" and computer_choice == "rock":
        print("You win!")
    elif player_choice == "rock" and computer_choice == "scissors":
        print("You win!")
    else:
        print("Computer wins!")

while True:
    play_game()
    again = input("Do you want to play again? (y/n): ")
    if again.lower() != "y":
        break


def swap_case(s):
    final=''
    for i in s:
        if i.isupper():
            final=final+i.lower()
        elif i.islower():
            final=final+i.upper()
        else:
           final=final+i
    return final

#question link
#https://www.hackerrank.com/challenges/swap-case/problem?isFullScreen=true
# You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.


__author__ = 'huangb3'
import cv2

origIm = cv2.imread('TestImages/Coins2.jpg')
imGray = cv2.cvtColor(origIm, cv2.COLOR_BGR2GRAY)
cv2.imshow("normal", imGray)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
imGray = cv2.morphologyEx(imGray, cv2.MORPH_OPEN, kernel)
imGray = cv2.GaussianBlur(imGray, (5, 5), 0)
imGray = cv2.equalizeHist(imGray)
imGray = cv2.morphologyEx(imGray, cv2.MORPH_OPEN, (kernel*2))
cv2.imshow("threshol", imGray)
circles = cv2.HoughCircles(imGray, cv2.HOUGH_GRADIENT, 1 ,20,

                              param1 = 40, param2 = 45,

                              minRadius = 30, maxRadius = 70)
for x in circles[0]:
    cv2.circle(origIm, (x[0], x[1]), x[2], (0, 0, 255), 2)
cv2.imshow("Cricles", origIm)
cv2.waitKey(0)


import numpy as np

def f(x):
  return np.sin(np.exp(-(x**2)))

def richardson_derivative(x):
  N = 5
  h = 0.1
  D = np.zeros([N + 1, N + 1])
  hh=h;

  for i in range(N + 1):
    D[i][0]=(f(x+hh)-f(x-hh))/(2.0*hh)

    for j in range(i):
      D[i][j+1] = D[i][j]+(D[i][j]-D[i-1][j])/(pow(4.0,j+1.0)-1.0)
    hh = hh/2.0

  return D[N, N]

x = 1
richardson_res = richardson_derivative(x)
print("Richardson extrapolation N=5, h=0.1 for f(x): {}".format(richardson_res))
steps = [10**-4, 10**-6, 10**-8, 10**-10, 10**-12, 10**-14]
for h in steps:
  approx_derivative = (f(x + h) - f(x)) / h
  print("h={}, error={}".format(h, np.abs(richardson_res - approx_derivative)))


import RPi.GPIO as GPIO
import time

outstr = "{digital} = {analog}V"
maxV = 3.3
out_list = (26, 19, 13, 6, 5, 11, 9, 10)
In = 4
v = 17
GPIO.setmode (GPIO.BCM)
GPIO.setup (out_list, GPIO.OUT)
GPIO.setup (v, GPIO.OUT)
GPIO.setup (In, GPIO.IN)

def decToBinList (decNumber):
    if decNumber < 0 or decNumber > 255:
        print ("Число должно быть от 0 до 255 (или -1 для выхода). Попробуйте еще раз.")
    return [(decNumber & (1 << i)) >> i for i in range (7, -1, -1)]

def num2dac (value):
    x = decToBinList (value)
    GPIO.output (out_list, tuple (x))

GPIO.output (v, 1)
while True:
    value = int(input ("Введите число (-1 для выхода): "))
    if value < -1 or value > 255:
        print ("Необходимо ввести число [0;255]! Попробуйте еще раз:")
    else:
        if value == -1:
            break
        an = maxV * value / 255.0
        print (outstr.format(digital = value, analog = an))
        num2dac(int(value * 50 / 255))

GPIO.output (out_list, 0)
GPIO.output (v, 0)
GPIO.cleanup (out_list)
GPIO.cleanup (v)
GPIO.cleanup (In)


from flask import Flask, render_template, request
import requests
from bs4 import BeautifulSoup
from bs4.element import Comment

app = Flask(__name__)

def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    if isinstance(element, Comment):
        return False
    return True

def text_from_html(body):
    soup = BeautifulSoup(body.text, 'html.parser')
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)
    return u" ".join(t.strip() for t in visible_texts)

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

@app.route('/', methods=['POST'])
def my_form_post():
    try:
        html = request.form['text']
        r = requests.get(html)
        a = text_from_html(r)
        trait_yes = 0
        trait_no = 0
        for char in '.?"\':;,/()-_=+*%!@#~`|{}[]’':
            a = a.replace(char, " ")
        a = a.split(' ')
        for i in a:
            if i in ['i', 'I', 'me', 'Me', 'my', 'My', 'mine', 'Mine', 'we', 'We', 'us', 'Us', 'our', 'Our', 'ours',
                     'Ours']:
                trait_yes += 1
            elif i in ['you', 'You', 'your', 'Your', 'yours', 'Yours']:
                trait_no += 1
        narcissist_ratio = (trait_yes / (trait_yes + trait_no)) * 100
        narcissist_ratio = str(round(narcissist_ratio, 3))
        return 'narcissist ratio is ' + narcissist_ratio + '%'
    except Exception:
        return 'This URL is not available'

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


import sqlite3

conn = sqlite3.connect('data.db')
cur = conn.cursor()

create_items = 'CREATE TABLE IF NOT EXISTS items (id INTEGER, title TEXT, amount INTEGER, price REAL)'
cur.execute(create_items)

conn.commit()

conn.close()


from openpyxl import load_workbook
from refund import Refund
import time

excel = load_workbook('./data/配置.xlsx')
all_sheet0 = excel.sheetnames
configdata = []
for i in all_sheet0:
    for column in excel[i].iter_cols():
        for cell2 in column:
            if cell2.value is not None and cell2.row == 2 and cell2.column == 1:
                for a in excel[i][cell2.row]:
                    if a.value is not None:
                        configdata.append(a.value)

try:
    print("程序开始运行...")
    starttime = time.time()
    print("程序运行开始时间：", starttime)
    #实例化
    filename = f'退款{time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))}.xlsx'
    filepath = f'./excel/{filename}'
    refundobj = Refund(filepath=filepath)

    all_order = [] #所有预定单号
    #要搜索的文件
    excel = load_workbook(f'data/{configdata[0]}')
    all_sheet = excel.sheetnames
    for i in all_sheet:
        for column in excel[i].iter_cols():
            for cell2 in column:
                if cell2.value is not None and cell2.column == 2:
                    all_order.append(cell2.value)

    print(f"共{len(all_order)}个订单号：", all_order)

    if len(all_order) > 0:
        #初始化
        refundobj.initexcel()
        print("开始去定金表搜索...")
        #开始去定金表搜索预订单号
        refundobj.find_false_in_xlsx(f'./data/{configdata[1]}', all_order)

    endtime = time.time()
    print("程序运行结束时间：", endtime)
    print(f"程序运行总耗时：{endtime-starttime}秒")
    print("程序运行完毕！请在excel目录下查看运行结果")
except Exception as e:
    print(e)


import tkinter as tk
t=tk.Tk()
t.title('my home')
t.geometry('200x200')

l=tk.Label(t,text='',bg='green')
l.pack()

counter=0
def do_job():
    global counter
    l.config(text='do '+ str(counter))
    counter=counter+1

menubar=tk.Menu(t)
filemenu=tk.Menu(menubar,tearoff=0)
menubar.add_cascade(label='File',menu=filemenu)
filemenu.add_command(label='New',command=do_job)
filemenu.add_command(label='Open',command=do_job)
filemenu.add_command(label='Save',command=do_job)
filemenu.add_separator()
filemenu.add_command(label='Exit',command=t.quit)

editmenu=tk.Menu(menubar,tearoff=0)
menubar.add_cascade(label='Edit',menu=editmenu)
editmenu.add_command(label='Cut',command=do_job)
editmenu.add_command(label='Copy',command=do_job)
editmenu.add_command(label='Paste',command=do_job)

submenu=tk.Menu(filemenu,tearoff=0)
filemenu.add_cascade(label='Import',menu=submenu,underline=0)
submenu.add_command(label='Submenu',command=do_job)
t.config(menu=menubar)

t.mainloop()


from tkinter import *
from PIL import ImageTk,Image

root = Tk()
root.title('Learn to code')
root.iconbitmap("images/test.ico")
root.geometry("400x400") #Define the gemoetry of the window

def show():
	myLabel=Label(root,text=clicked.get())
	myLabel.pack()

#Use a list
options = [
		"Monday",
		"Tuesday",
		"Wednesday",
		"Thursday",
		"Friday",
		"Saturday"
]

clicked = StringVar()
clicked.set(options[0])

#Define the dropbox menu

drop = OptionMenu(root,clicked,*options)
drop.pack()

mybtn=Button(root,text="Show Selection!", command=show)
mybtn.pack()

root.mainloop()


# Дано натуральное число А>1 определить каким по счету числом фибоначчи оно является, если не является то вывести -1

a = int(input("введите натуральное число  "))
n = 0
m = 1
i = 2
while m <= a:
    if m == a:
        print(i)
        break
    n,m = m, m+n
    i+=1
else:
    print(-1)


class TrieNode:
    def __init__(self):
        self.children = dict()
        self.suffix = defaultdict(int)

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word, idx, suffix):
        node = self.root
        size = len(word)
        for i in range(size):
            if word[i] not in node.children:
                node.children[word[i]] = TrieNode()

            node = node.children[word[i]]
            for val in suffix:
                node.suffix[val] = idx

    def search(self, prefix, suffix):
        node = self.root
        for char in prefix:
          if char not in node.children:
            return -1
          node = node.children[char]

        if suffix not in node.suffix:
            return -1
        return node.suffix[suffix]

    def findSuffix(self, word):
      suffix = []
      for i in range(len(word)):
          suffix.append(word[i:])

      return suffix

class WordFilter:

    def __init__(self, words: List[str]):
        self.trie = Trie()
        size = len(words)
        for i in range(size):
          suffix = self.trie.findSuffix(words[i])
          self.trie.insert(words[i], i, suffix)

    def f(self, pref: str, suff: str) -> int:
      return self.trie.search(pref, suff)

# Your WordFilter object will be instantiated and called as such:
# obj = WordFilter(words)
# param_1 = obj.f(pref,suff)
"""
["apple"], ["angle"]
perfix = a
suffix = e
"""


import os
import torch
import numpy as np
import pandas as pd

path2folder = r'D:\dataset\DAX7'
file_list = [f for f in os.listdir(path=path2folder) if f.endswith('.pt')]

path2save = r'D:\dataset\DAX7\output'

names = ['train', 'test', 'valid']

for file in file_list:
    dir_ = os.path.join(path2folder, file)
    file_ = torch.load(dir_, map_location=torch.device('cpu'))
    stft, labels, config = file_.tensors

    stft = stft.numpy()
    stft_list = np.split(stft, stft.shape[0])
    stft_list = [np.squeeze(stft_) for stft_ in stft_list]

    labels = labels.numpy()
    labels_list = np.split(labels, labels.shape[0])
    labels_list = [np.squeeze(label_) for label_ in labels_list]

    config = config.numpy()
    config_list = np.split(config, config.shape[0])
    config_list = [np.squeeze(cfg_) for cfg_ in config_list]

    type_dataset = None
    for name in names:
        if name in file:
            type_dataset = name
    if type_dataset is None:
        type_dataset = 'train'

    os.makedirs(os.path.join(path2save, type_dataset, 'data'))
    os.makedirs(os.path.join(path2save, type_dataset, 'labels'))
    os.makedirs(os.path.join(path2save, type_dataset, 'config'))

    for i in range(len(stft)):
        file_name = os.path.join(path2save, type_dataset, 'data', str(i))
        np.save(arr=stft_list[i], file=file_name)

        file_name = os.path.join(path2save, type_dataset, 'labels', str(i))
        np.save(arr=labels[i], file=file_name)

        file_name = os.path.join(path2save, type_dataset, 'config', str(i))
        np.save(arr=config[i], file=file_name)


from collections import deque
def solution(numbers, target):
    answer = 0
    dq = deque([(0,0)]) # 현재 숫자, 길이
    while dq:
        now = dq.popleft()
        if now[1]==len(numbers):# 길이가 numbers랑 같으면 체크하고 continue
            if now[0] == target:
                answer+=1
        else :
            plus = [now[0] + numbers[now[1]],now[1]+1]
            minus = [now[0] - numbers[now[1]],now[1]+1]
            dq.append(plus)
            dq.append(minus)
    return answer

프로그래머스/타켓 넘버.py


import socket
import 规则
import 获取公网ip

def p1_socket():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = 获取公网ip.get_ip()
    #host = socket.gethostbyname(socket.gethostname())
    print("p2输入{}即可建立连接".format(host))
    server_socket.bind(('127.0.0.1', 51778))
    server_socket.listen(1)
    client_socket,addr = server_socket.accept()
    while True:
        p1 = input("请输入“石头”或“剪刀”或“布”或“退出”：\n")
        p2 = client_socket.recv(32).decode('utf-8')
        result = 规则.pvp(p1, p2)
        print(result)
        client_socket.send(result.encode('utf-8'))
        if result == "游戏结束":
            client_socket.close()
            break

def p2_socket():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = input("请输入p1玩家ip")
    client_socket.connect(('127.0.0.1', 51778))
    while True:
        p2 = input("请输入“石头”或“剪刀”或“布”或“退出”：\n")
        client_socket.send(p2.encode('utf-8'))
        result = client_socket.recv(128).decode('utf-8')
        print(result)
        if result == "游戏结束":
            client_socket.close()
            break