#! /usr/bin/python3
import os
import sys
import glob
import time
import shutil
import logging
import argparse
import subprocess
import pandas as pd
from pathlib import Path
from itertools import repeat
from multiprocessing import Pool
from nest.bbduk import QualCheck
from nest.alignment import Bwa
from nest.alignment import Bowtie
from nest.alignment import BBMap
from nest.alignment import Snap
from nest.samtools import Samtools
from nest.gatk import GenAnTK
from nest.gatk import Picard
from nest.gatk import FreeBayes
from nest.kestrel import KestrelVar
#from nest.annotater import Annotate
from nest.kestrel import kes_runner
from nest.summarize import Summary
from nest.prepinputs import Prepper
from nest.parsers.vcfReader import Reader
from nest.parsers.vcfmerge import Merge
from nest.parsers.vcfannotate import Annotate
from nest.parsers.vcfwriter import Writer
def main(arguments):
    bbduk_path = arguments[0]
    alinger_path = arguments[1]
    smt_path = arguments[2]
    bft_path = arguments[3]
    gatk_path = arguments[4]
    sam_name = arguments[5]
    file_list = arguments[6]
    ref_path = arguments[7]
    adp_path = arguments[8]
    bed_path = arguments[9]
    out_dir = arguments[10]
    aligner = arguments[11]
    pic_path = arguments[12]
    voi_path = arguments[13]
    java_path = arguments[14]
    sra_path = arguments[15]
    purge = arguments[16]
    sra_list = arguments[17]
    #Setup logging
    #Get logger for main method
    main_logger = logging.getLogger('NeST.{0}'.format(sam_name))
    main_logger.debug('Starting analysis for {0}'.format(sam_name))
    #Check if files are present
    out_path = '{0}/{1}'.format(os.path.abspath(out_dir), sam_name)
    if not os.path.exists(out_path):
        os.mkdir(out_path)

    fastq_path = '{0}/RawFastq'.format(out_path)
    if not os.path.exists(fastq_path):
        os.mkdir(fastq_path)
    #Get FASTQs
    prepper =  Prepper(fastq_path, out_dir, sra_path)
    fastq_path = prepper.sra(sam_name, sra_list, file_list)
    ##Note: Generalize this, right now it will only work with SRA. This is a fix for NEJM
    rone_path = file_list[0]
    rtwo_path = file_list[1]

    if not os.path.exists(rone_path):
        raise FileNotFoundException('Forward read not found; Exiting MARs')
        sys.exit()

    if not os.path.exists(rtwo_path):
        raise FileNotFoundException('Reverse read not found; Exiting MARs')
        sys.exit()

    if not os.path.exists(ref_path):
        raise FileNotFoundException('Reference fasta file not found; Exiting MARs')
        sys.exit()

    if not os.path.exists(adp_path):
        raise FileNotFoundException('Adpater sequence not found; Exiting MARs')
        sys.exit()

    if not os.path.exists(out_path):
        os.mkdir(out_path)

    #Create completion folder
    completion_path = '{0}/completion'.format(out_path)
    if not os.path.exists(completion_path):
        os.mkdir(completion_path)

    #Call Bbduk
    main_logger.debug('Running BBDuk')
    if os.path.exists('{0}/bbduk.rt'.format(completion_path)):
        brone = os.path.splitext(os.path.basename(rone_path))[0]
        brtwo = os.path.splitext(os.path.basename(rtwo_path))[0]
        rone_path = '{0}/{1}/{2}_cleaned.fq'.format(out_path, 'CleanedFastq', brone)
        rtwo_path = '{0}/{1}/{2}_cleaned.fq'.format(out_path, 'CleanedFastq', brtwo)
        main_logger.debug('Skipping BBDuk')
        bret = 0
    else:
        bbduk = QualCheck(bbduk_path, adp_path, out_path, java_path)
        rone_path, rtwo_path, bret = bbduk.bbduk(rone_path, rtwo_path)
        if bret == 0:
            Path('{0}/bbduk.rt'.format(completion_path)).touch()
    if bret != 0:
        raise RuntimeError('BBDuk failed to complete; Exiting MARs')
    else:
        main_logger.debug('BBDuk completed')

    if aligner == 'bwa':
        #Call BWA
        main_logger.debug('Running BWA')
        if os.path.exists('{0}/align.rt'.format(completion_path)):
            sam_path = '{0}/alignments/output.sam'.format(out_path)
            mret = 0
            main_logger.debug('Skipping BWA')
        else:
            bwa = Bwa(alinger_path, out_path, ref_path)
            sam_path, mret = bwa.bwamem(rone_path, rtwo_path)
            if mret == 0:
                Path('{0}/align.rt'.format(completion_path)).touch()
        if mret != 0:
            raise RuntimeError('Bwa mem failed to complete; Exiting MARs')
        else:
            main_logger.debug('BWA completed')

    elif aligner == 'bowtie2':
        #Call Bowtie2
        main_logger.debug('Running Bowtie2')
        if os.path.exists('{0}/aling.rt'.format(completion_path)):
            sam_path = '{0}/alignments/output.sam'.format(out_path)
            mret = 0
            main_logger.debug('Skipping Bowtie2')
        else:
            bowtie = Bowtie(alinger_path, out_path, ref_path)
            sam_path, mret = bowtie.bowtie(rone_path, rtwo_path)
            if mret == 0:
                Path('{0}/align.rt'.format(completion_path)).touch()
        if mret != 0:
            raise RuntimeError('Bowtie2 failed to complete; Exiting MARs')
        else:
            main_logger.debug('Bowtie2 completed')

    elif aligner == 'snap':
        #Call Snap
        main_logger.debug('Running Snap')
        snap = Snap(alinger_path, out_path, ref_path)
        sam_path, mret = snap.snap(rone_path, rtwo_path)
        if mret != 0:
            raise RuntimeError('Snap failed to complete; Exiting MARs')
        else:
            main_logger.debug('Snap completed')

    elif aligner == 'bbmap':
        #Call Bbmap
        main_logger.debug('Running BBMap')
        if os.path.exists('{0}/aling.rt'.format(completion_path)):
            sam_path = '{0}/alignments/output.sam'.format(out_path)
            mret = 0
        else:
            bbmap = BBMap(alinger_path, out_path, ref_path)
            sam_path, mret = bbmap.bbmap(rone_path, rtwo_path)
            if mret == 0:
                Path('{0}/align.rt'.format(completion_path)).touch()
        if mret != 0:
            raise RuntimeError('BBMap failed to complete; Exitinign MARs')
        else:
            main_logger.debug('BBMap completed')

    #Fix mate information, sort files and add read groups
    varengine = Samtools(smt_path, bft_path, out_path)
    if os.path.exists('{0}/fixmate.rt'.format(completion_path)):
        base = os.path.splitext(os.path.basename(sam_path))[0]
        bam_path = '{0}/alignments/{1}_FM.bam'.format(out_path, base)
        fret = 0
        main_logger.debug('Skipping fixmate')
    else:
        bam_path, fret = varengine.fixmate(sam_path)
        if fret == 0:
            Path('{0}/fixmate.rt'.format(completion_path)).touch()
    main_logger.debug('Running Samtools fixmate')
    if fret != 0:
        raise RuntimeError('Samtools fixmate failed to complete; Exiting MARs')
    else:
        main_logger.debug('Samtools fixmate completed')

    if os.path.exists('{0}/sort.rt'.format(completion_path)):
        base = os.path.splitext(os.path.basename(bam_path))[0]
        bam_path = '{0}/alignments/{1}_SR.bam'.format(out_path, base)
        sret = 0
        main_logger.debug('Skipping sort')
    else:
        bam_path, sret = varengine.sort(bam_path)
        if sret == 0:
            Path('{0}/sort.rt'.format(completion_path)).touch()
    main_logger.debug('Running Samtools sort')
    if sret != 0:
        raise RuntimeError('Samtools sort failed to complete; Exiting MARs')
    else:
        main_logger.debug('Samtools sort completed')

    if os.path.exists('{0}/dedup.rt'.format(completion_path)):
        base = os.path.splitext(os.path.basename(bam_path))[0]
        bam_path = '{0}/alignments/{1}_DD.bam'.format(out_path, base)
        dret = 0
        main_logger.debug('Skipping Dedup')
    else:
        bam_path, dret = varengine.dedup(bam_path)
        if dret == 0:
            Path('{0}/dedup.rt'.format(completion_path)).touch()
    main_logger.debug('Running Samtools dedup')
    if sret != 0:
        raise RuntimeError('Samtools dedup failed to complete; Exiting MARs')
    else:
        main_logger.debug('Samtools dedup completed')

    rgadder = Picard(java_path, pic_path, out_path)
    if os.path.exists('{0}/readgroup.rt'.format(completion_path)):
        base = os.path.splitext(os.path.basename(bam_path))[0]
        bam_path = '{0}/alignments/{1}_RG.bam'.format(out_path, base)
        aret = 0
        main_logger.debug('Skipping add read group')
    else:
        bam_path, aret = rgadder.picard(bam_path, sam_name)
        main_logger.debug('Running Picard AddOrReplaceReadGroups')
        if aret == 0:
            Path('{0}/readgroup.rt'.format(completion_path)).touch()
    if aret != 0:
        raise RuntimeError('Picard AddOrReplaceReadGroups failed to complete; Exiting MARs')
    else:
        main_logger.debug('Picard AddOrReplaceReadGroups completed')

    #Run samtools mpileup, bcftools index, call and stats to generate VCF files
    if os.path.exists('{0}/pileup.rt'.format(completion_path)):
        bcf_path = '{0}/{1}_variants.bcf'.format(out_path, sam_name)
        pret = 0
        main_logger.debug('Skipping Pileup')
    else:
        bcf_path, pret = varengine.pileup(ref_path, bam_path, sam_name)
        main_logger.debug('Running Samtools mpileup')
        if pret == 0:
            Path('{0}/pileup.rt'.format(completion_path)).touch()
    if pret != 0:
        raise RuntimeError('Samtools mpileup failed to complete; Exiting MARs')
    else:
        main_logger.debug('Samtools mpileup completed')

    if os.path.exists('{0}/bcfindex.rt'.format(completion_path)):
        bret = 0
        main_logger.debug('Skipping Bcfindex')
    else:
        bret = varengine.bcfindex(bcf_path)
        main_logger.debug('Running Bcftools index')
        if bret ==0 :
            Path('{0}/bcfindex.rt'.format(completion_path)).touch()
    if bret != 0:
        raise RuntimeError('Bcftools index failed to complete; Exiting MARs')
    else:
        main_logger.debug('Bcftools index completed')

    if os.path.exists('{0}/bcfcall.rt'.format(completion_path)):
        vcf_path = '{0}/{1}_variants_samtools.vcf'.format(out_path, sam_name)
        bret = 0
        main_logger.debug('Skipping bcfcall')
    else:
        vcf_path, bret = varengine.bcftools(bcf_path, sam_name)
        main_logger.debug('Running Bcftools call')
        if bret == 0:
            Path('{0}/bcfcall.rt'.format(completion_path)).touch()

    if bret != 0:
        raise RuntimeError('Bcftools call failed to complete; Exiting MARs')
    else:
        main_logger.debug('Bcftools call completed')

    #Call GATK HaplotypeCaller to generate VCF files
    varcaller = GenAnTK(gatk_path, out_path, java_path, pic_path)
    main_logger.debug('Running GATK HaplotypeCaller')
    if os.path.exists('{0}/gatk.rt'.format(completion_path)):
        gvcf_path = '{0}/{1}_variants_gatk.vcf'.format(out_path, sam_name)
        gret = 0
        main_logger.debug('Skipping GATK')
    else:
        gvcf_path, gret = varcaller.hapCaller(bam_path, ref_path, sam_name)
        if gret == 0:
            Path('{0}/gatk.rt'.format(completion_path)).touch()
    if gret != 0:
        raise RuntimeError('GATK HaplotypeCaller failed to complete; Exiting MARs')
    else:
        main_logger.debug('GATK HaplotypeCaller stats completed')

    #Call Freebayes to generate VCF files
    varcaller = FreeBayes('freebayes', out_path)
    main_logger.debug('Running Freebayes')
    if os.path.exists('{0}/freebayes.rt'.format(completion_path)):
        fvcf_path = '{0}/{1}_variants_freebayes.vcf'.format(out_path, sam_name)
        fret = 0
        main_logger.debug('Skipping Freebayes')
    else:
        fvcf_path, fret = varcaller.freeBayes(bam_path, ref_path, sam_name)
        if fret == 0:
            Path('{0}/freebayes.rt'.format(completion_path)).touch()
    if fret != 0:
        raise RuntimeError('Freebayes failed to complete; Exiting MARs')
    else:
        main_logger.debug('Freebayes stats completed')

    #Filer  and annotate variant calls
    main_logger.debug('Annotating variants')
    annotate = Annotate()
    gvcf_path = annotate.getAnnotation(bed_path, gvcf_path, ref_path, out_path, bam_path)
    vcf_path = annotate.getAnnotation(bed_path, vcf_path, ref_path, out_path, bam_path)
    fvcf_path = annotate.getAnnotation(bed_path, fvcf_path, ref_path, out_path, bam_path)
    vcf_dict = {gvcf_path: 'GATK', vcf_path: 'Samtools', fvcf_path: 'Freebayes'}
    merger = Merge(out_path, vcf_dict, ref_path)
    merged_vcf = merger.splitter(list(vcf_dict.keys()))[0]
    final_vcf= '{0}/{1}_variants_merged_annotated.vcf'.format(out_path, sam_name)
    os.rename(merged_vcf, final_vcf)
    #final_path = annotate.getAnnotation(bed_path, final_vcf, ref_path, out_path, bam_path)
    main_logger.debug('Filetering low quality variants and merging GATK and Samtools calls')
    #merged_vcf = Vcf.Merge(gvcf_file, svcf_file, out_path).merge()
    summary = Summary(ref_path, bed_path, voi_path, out_dir)
    var_sum = summary.getVarStats(final_vcf)
    main_logger.info('Total variants : {0}; Verified calls : {1}; Exonic : {2}; Intronic : {3}; Synonymous : {4}; Non Synonymous : {5}; Transition : {6}; Transversion : {7}'.format(
                        var_sum[0], var_sum[1], var_sum[2], var_sum[3], var_sum[4], var_sum[5], var_sum[6], var_sum[7]))
    if purge:
       shutil.rmtree('{0}/RawFastq'.format(out_path))
       shutil.rmtree('{0}/CleanedFastq'.format(out_path))
       alignments = glob.glob('{0}/alignments/*'.format(out_path))
       for files in alignments:
           if 'output_FM_SR_DD_RG.ba' in files:
               continue
           else:
               os.remove(files)
       vcffiles = glob.glob('{0}/*.bcf*'.format(out_path))
       for files in vcffiles:
           os.remove(files)
    return(final_vcf, 0)

def marsBatch(bbduk_path, aligner_path, smt_path, bft_path, gatk_path,
              inp_path, ref_path, adp_path, bed_path, out_dir, aligner,
              pic_path, voi_path, java_path, sra_path, verbose, threads, purge):
    #Creating logger for nest
    logger = logging.getLogger('NeST')
    logger.setLevel(logging.DEBUG)
    #Create output paths for the run
    if not os.path.exists(os.path.abspath(out_dir)):
        os.mkdir(os.path.abspath(out_dir))
    # Creating a file handler which logs even debug messages
    fh = logging.FileHandler('{0}/nest.log'.format(os.path.abspath(out_dir)))
    if verbose:
        fh.setLevel(logging.DEBUG)
    else:
        fh.setLevel(logging.INFO)
    # Creating a console handler to log info messages
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    # Create formatter and add it to the handlers
    formatter = logging.Formatter('{asctime} - {name} - {levelname} - {message}', style="{")
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    # Add the handlers to the logger
    logger.addHandler(fh)
    logger.addHandler(ch)
    #Create file and console handlers for MaRS
    logger.info('Gathering input information from input path.')
    prep = Prepper(inp_path, out_dir, sra_path).prepInputs()
    samples, sra_list, files = list(), list(), list()
    logger.info('Running MaRS on {0} experiments'.format(len(prep)))
    #summary = Summary(ref_path, bed_path, voi_path, out_dir)
    #samples = config.keys()
    pools = Pool(threads)
    for sample in prep:
        samples.append(prep[sample].sample)
        files.append(prep[sample].files)
        sra_list.append(prep[sample].sra)
    #rone_list = list()
    #rtwo_list = list()
    #name_list = list()
    #for samples in config:
    #    name_list.append(config[samples].sample)
    #    rone_list.append(config[samples].files[0])
    #    rtwo_list.append(config[samples].files[1])

    #sra_list = files
    vcf_list = pools.map(main, zip(repeat(bbduk_path), repeat(aligner_path),
                repeat(smt_path), repeat(bft_path), repeat(gatk_path),
                samples, files, repeat(ref_path), repeat(adp_path),
                repeat(bed_path), repeat(out_dir), repeat(aligner),
                repeat(pic_path), repeat(voi_path),
                repeat(java_path), repeat(sra_path), repeat(purge), sra_list))
    logger.info('Summarizing variant calls from all {0} experiments'.format(len(prep)))
    summary = Summary(ref_path, bed_path, voi_path, out_dir)
    #Sumarize variants of intrest
    summary.getSummary()
    return(0)

if __name__ == '__main__':
    #Define deffault paths and aligner informations
    def_path = "{0}/lib".format(os.path.abspath(os.path.dirname(os.path.realpath(__file__))))
    ref_def_path = "{0}/ref".format(os.path.abspath(os.path.dirname(os.path.realpath(__file__))))
    bbduk_def = 'bbduk.sh' #"{0}/bbmap/bbduk.sh".format(def_path)
    bbmap_def = 'bbmap.sh' #"{0}/bbmap/bbmap.sh".format(def_path)
    bwa_def = 'bwa' #"{0}/bwa/bwa".format(def_path)
    bowtie_def = 'bowtie2' #"{0}/bowtie2/bowtie2".format(def_path)
    snap_def = 'snap-alinger' #"{0}/snap/snap-aligner".format(def_path)
    smt_def = 'samtools' #"{0}/samtools/samtools".format(def_path)
    bft_def = 'bcftools' #"{0}/bcftools/bcftools".format(def_path)
    gatk_def = 'gatk' #"{0}/GenomeAnalysisTK.jar".format(def_path)
    pic_def = 'picard' #"{0}/picard.jar".format(def_path)
    sra_def = 'fastq-dump' #'{0}/sratoolkit/bin/fastq-dump'.format(def_path)
    voi_def = None #'{0}/Reportable_SNPs.csv'.format(ref_def_path)
    #if 'java version "1.8.' in str(subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT).decode('UTF-8').split('\n')[0]):
    java_def = 'java'
    #else:
    #    java_def = "{0}/jdk/bin/java".format(def_path)
    aligner_def = {'bwa' : bwa_def, 'snap' : snap_def, 'bowtie2': bowtie_def, 'bbmap': bbmap_def}
    #Get arguments
    parser = argparse.ArgumentParser(prog='NeST')
    parser.add_argument('-i', '--inp_path', type=str,
                        help='Path to input directory (Specify only for batch mode)')
    parser.add_argument('-1', '--fwd', dest='rone_path', type=str,
                        help='Path to forward reads fastq', )
    parser.add_argument('-2', '--rev', dest='rtwo_path', type=str,
                        help='Path to reverse reads fastq')
    parser.add_argument('-r', '--ref', dest='ref_path', type=str,
                        help='Path to Reference fasta file', required=True)
    parser.add_argument('-a', '--adapter', dest='adp_path', type=str,
                        help='Path to Adpater fasta file', required=True)
    parser.add_argument('-b', '--bed', dest='bed_path', type=str,
                        help='Path to Bed file for MDR regions', required=True)
    parser.add_argument('-o', '--outpath', dest='out_path', type=str,
                        help='Path where all outputs will be stored', required=True)
    parser.add_argument('-n', '--sam_name', dest='sam_name', type=str,
                        help='Sample name', default=None)
    parser.add_argument('-m', '--mapper', dest='aligner', type=str,
                        choices=['bowtie2', 'bwa', 'bbmap', 'snap'],
                        default='bwa', help='The aligner to used by MARs')
    parser.add_argument('--bbduk', dest='bbduk_path', type=str, default=bbduk_def,
                        help='Path to BBduk executable')
    parser.add_argument('--aligner', dest='aligner_path', type=str, default=None,
                        help='Path to aligner executable')
    parser.add_argument('--samtools', dest='smt_path', type=str, default=smt_def,
                        help='Path to Samtools executable')
    parser.add_argument('--gatk', dest='gatk_path', type=str, default=gatk_def,
                        help='Path to GATK executable')
    parser.add_argument('--bcftools', dest='bft_path', type=str, default=bft_def,
                        help='Path to Bcftools executable')
    parser.add_argument('--picard', dest='pic_path', type=str, default=pic_def,
                        help='Path to Bcftools executable')
    parser.add_argument('--varofint', dest='voi_path', type=str, default=voi_def,
                        help='Path to variant of interest')
    parser.add_argument('--threads', dest='threads', type=int, default=5,
                        help='Number of threads')
    parser.add_argument('--verbose', action='store_true',
                        help='Increase verbosity of log file')
    parser.add_argument('--purge', action='store_true',
                        help='Remove intermiediate Fastq and alignment files')
    args = parser.parse_args()

    #Validate parsed arguments
    if args.aligner_path is None:
        args.aligner_path = aligner_def[args.aligner]

    if not os.path.exists(args.out_path):
        os.mkdir(args.out_path)

    #single sample experiment.

    #Check if the run command is for batch mode analysis or single sample
    #analysis.
    #If inp_path is empty and rone_path is not, then the experiment is a
    #single sample experiment.
    status = marsBatch(args.bbduk_path, args.aligner_path, args.smt_path,
                args.bft_path, args.gatk_path, args.inp_path, args.ref_path,
                args.adp_path, args.bed_path, args.out_path, args.aligner,
                args.pic_path, args.voi_path, java_def, sra_def, args.verbose,
                args.threads, args.purge)


#!/usr/bin/env python3

import base64

from functions.aes import (
    gen_random_bytes,
    get_blocks,
    pkcs7_unpad,
    pkcs7_pad,
    PKCS7Error,
    AESCipher,
)

_STRINGS = [
    base64.b64decode(s)
    for s in [
        "MDAwMDAwTm93IHRoYXQgdGhlIHBhcnR5IGlzIGp1bXBpbmc=",
        "MDAwMDAxV2l0aCB0aGUgYmFzcyBraWNrZWQgaW4gYW5kIHRoZSBWZWdhJ3MgYXJlIHB1bXBpbic=",
        "MDAwMDAyUXVpY2sgdG8gdGhlIHBvaW50LCB0byB0aGUgcG9pbnQsIG5vIGZha2luZw==",
        "MDAwMDAzQ29va2luZyBNQydzIGxpa2UgYSBwb3VuZCBvZiBiYWNvbg==",
        "MDAwMDA0QnVybmluZyAnZW0sIGlmIHlvdSBhaW4ndCBxdWljayBhbmQgbmltYmxl",
        "MDAwMDA1SSBnbyBjcmF6eSB3aGVuIEkgaGVhciBhIGN5bWJhbA==",
        "MDAwMDA2QW5kIGEgaGlnaCBoYXQgd2l0aCBhIHNvdXBlZCB1cCB0ZW1wbw==",
        "MDAwMDA3SSdtIG9uIGEgcm9sbCwgaXQncyB0aW1lIHRvIGdvIHNvbG8=",
        "MDAwMDA4b2xsaW4nIGluIG15IGZpdmUgcG9pbnQgb2g=",
        "MDAwMDA5aXRoIG15IHJhZy10b3AgZG93biBzbyBteSBoYWlyIGNhbiBibG93",
    ]
]

_KEY = gen_random_bytes(16)

def _encrypt(pt: bytes) -> (bytes, bytes):
    iv = gen_random_bytes(16)
    cbc = AESCipher(AESCipher.MODE_CBC, _KEY, iv=iv)
    ct = cbc.encrypt(pkcs7_pad(pt))

    return iv, ct

def _oracle(iv: bytes, ct: bytes) -> bool:
    cbc = AESCipher(AESCipher.MODE_CBC, _KEY, iv=iv)

    try:
        pkcs7_unpad(cbc.decrypt(ct))
    except PKCS7Error:
        return False

    return True

def _attack(iv: bytes, ct: bytes) -> bytes:
    cipher_blocks = [iv] + get_blocks(ct)

    pt = b""

    for i in reversed(range(1, len(cipher_blocks))):
        ct_block_previous = cipher_blocks[i - 1]
        ct_block_current = cipher_blocks[i]
        intermediate_block = b""

        for j in reversed(range(16)):
            ctb_prefix = gen_random_bytes(j)
            ctb_suffix = b""

            for k in range(len(intermediate_block)):
                ctb_suffix += bytes([(16 - j) ^ intermediate_block[k]])

            n = 0
            for m in range(256):
                ctb = ctb_prefix + bytes([m]) + ctb_suffix

                if _oracle(ctb, ct_block_current):
                    n = m
                    break

            intermediate_block = bytes([n ^ (16 - j)]) + intermediate_block
            pt = bytes([ct_block_previous[j] ^ int(intermediate_block[0])]) + pt

    return pkcs7_unpad(pt)

def challenge17() -> bool:
    for msg in _STRINGS:
        ret = _attack(*_encrypt(msg))

        if ret not in _STRINGS:
            return False

    return True

if __name__ == "__main__":
    assert challenge17(), "The result does not match the expected value"

    print("Ok")


import sys
import networkx as nx
from assignNetwork import assignNetwork

conflicts = []
messageTypes = []
incomingMessages = []
outgoingMessages = []
stableStates = []
graph = {}
G = nx.MultiDiGraph()

assert len(sys.argv[1:]) <= 2, "Too many arguments"
file = sys.argv[1]
if(len(sys.argv[1:]) == 2):
    constraiantFile = sys.argv[2]

with open(file) as f:
    lines = f.readlines()
    line_idx = 0

    while(not "RevMurphi.MurphiModular.Types.Enums.SubEnums.GenMessageTypes" in lines[line_idx]):
        line_idx += 1
    line_idx += 2

    # Get all messages
    while(not ";" in lines[line_idx]):
        msg = lines[line_idx].strip()
        if msg[-1] == ',':
            msg = msg[:-1]
        messageTypes.append(msg)
        line_idx += 1

    print(messageTypes)

    while(not "RevMurphi.MurphiModular.Types.Enums.SubEnums.GenArchEnums" in lines[line_idx]):
        line_idx += 1
    line_idx += 2

    #get stable states
    cacheStates = []
    while not "directory" in lines[line_idx]:
        state = lines[line_idx].strip().replace("cache", "")
        if len(state) == 0:
            line_idx += 1
            continue
        if state[-1] == ',':
            state = state[:-1]
        cacheStates.append(state)
        line_idx += 1

    line_idx += 1
    while not ";" in lines[line_idx]:
        state = lines[line_idx].strip().replace("directory", "")
        if state[-1] == ',':
            state = state[:-1]
        if state in cacheStates:
            stableStates.append("cache" + state)
        line_idx += 1

    #find and parse state machines
    while(not "----RevMurphi.MurphiModular.StateMachines.GenMessageStateMachines" in lines[line_idx]):
        # print(i, lines[i])
        line_idx += 1

    for i in range(line_idx, len(lines)):
        #find switch cbe.State then find inmsg.mtype
        if ("case cache" in lines[i]): #don't need to check directory or "case directory" in lines[i]
            inState = lines[i].strip()[5:-1]
            outState = ""
            edge = ""

            print("state: " + inState)
            i += 1

            incoming = False
            prev_message = ""
            msg_types = {}

            for msgType in messageTypes:
                msg_types[msgType] = "stall"

            while(not "endswitch;" in lines[i]):
                if("case" in lines[i]):
                    incoming_msg = lines[i].strip()
                    incoming_msg = incoming_msg[5:-1]
                    edge = incoming_msg
                    print("incoming message: " + incoming_msg)
                    if incoming_msg not in incomingMessages:
                        incomingMessages.append(incoming_msg)
                    msg_types[incoming_msg] = "nonstall"

                    incoming = True
                    prev_message = incoming_msg

                if("msg := " in lines[i]):
                    outgoing_msg = lines[i]
                    outgoing_msg = outgoing_msg.split(',')[1]
                    print("outgoing message: " + outgoing_msg)
                    if outgoing_msg not in outgoingMessages:
                        outgoingMessages.append(outgoing_msg)

                if("Send" in lines[i]):
                    incoming = False

                if "cbe.State :=" in lines[i]:
                    outState = lines[i].strip()[13:-1]
                    key = G.add_edge(inState, outState, edge)
                    G.edges[inState, outState, edge]["message"] = edge
                    print(outState)
                i += 1

            print("finished messages for this state")

            #check for conflicts in this state
            print("all messages:")
            print(msg_types)
            keys = list(msg_types.keys())
            conflictNum = 0

            if len(keys) > 1:
                for j in range(len(keys)-1):
                    m1 = keys[j]
                    m1_type = msg_types[m1]

                    for k in range(j+1, len(keys)):
                        m2 = keys[k]
                        m2_type = msg_types[m2]

                        if(m1_type != m2_type):
                            if(not (m1,m2) in conflicts and not (m2,m1) in conflicts):
                                print("appending {} {}".format(m1, m2))
                                conflicts.append((m1, m2))
                                conflictNum += 1

            print("Number of new conflict in state: " + str(conflictNum))

for msg in messageTypes:
    if (msg not in incomingMessages and msg not in outgoingMessages):
        outgoingMessages.append(msg)

print("original conflicts: " + str(len(conflicts)))
assignNetwork(messageTypes, conflicts)
print("")
print("INCOMING {}".format(incomingMessages))
print("OUTGOING {}".format(outgoingMessages))
print("BOTH")
for msg in messageTypes:
    if (msg in incomingMessages and msg in outgoingMessages):
        print(msg)
print("\n")
newConflicts = []
outOnly = []
for msg in messageTypes:
        if msg in outgoingMessages and msg not in incomingMessages:
            outOnly.append(msg)

for (m1, m2) in conflicts:
    conflicting = True

    if m1 in outOnly or m2 in outOnly:
        conflicting = False

    if conflicting:
        newConflicts.append((m1, m2))

print("omitting incoming/outgoing non-conflicts: {} conflicts left".format(str(len(newConflicts))))
print("newConflicts Length {}".format(len(newConflicts)))
falseConflict = {}
for con in newConflicts:
    falseConflict[con] = True

#get gray from trace here
def enumNode(node):
    posMsg = set()
    print(node)
    if node in stableStates:
        print("base case")
        out_edges = G.out_edges(node)
        for out_edge in out_edges:
            outMsg = G.get_edge_data(out_edge[0], out_edge[1]).keys()
            print(outMsg)
            for msg in outMsg:
                posMsg.add(msg)
        print("returning {}".format(posMsg))
        return posMsg
    else:
        out_edges = G.out_edges(node)
        # print(node, out_edges)
        for out_edge in out_edges:
            curOutMsg = G.get_edge_data(out_edge[0], out_edge[1]).keys()
            # for msg in curOutMsg:
            #     posMsg.append(msg)
            if not out_edge[0] == out_edge[1]:
                nxt_out_edges = G.out_edges(out_edge[1])
                for oEdge in nxt_out_edges:
                    nxt_Msgs = G.get_edge_data(oEdge[0], oEdge[1]).keys()
                    for msg in nxt_Msgs:
                        posMsg.add(msg)

                # for msg in curOutMsg:
                #     posMsg.add(msg)

                print("NEXT state {}".format(out_edge[1]))
                nextOutMsg = enumNode(out_edge[1])
                for msg in nextOutMsg:
                    print("ADDING {}".format(msg))
                    posMsg.add(msg)
            else:
                print("ADDING {}".format(curOutMsg))
                for msg in curOutMsg:
                    posMsg.add(msg)
            # else:
            #     posMsg.append(next(iter(curOutMsg)))
        #     print(out_edge, outMsg)
        # print()
        print("returning {}".format(posMsg))
        return posMsg

for n1 in G.nodes:
    print("start node: {}".format(n1))

    # if n1 in stableStates:
    #     continue

    possibleMsgs = enumNode(n1)
    print("POSSIBLE for {}: {}".format(n1, possibleMsgs))
    currentMsgs = set()

    out_edges = G.out_edges(n1)
    # print(len(out_edges))
    for out_edge in out_edges:
        curOutMsg = G.get_edge_data(out_edge[0], out_edge[1]).keys()
        for msg in curOutMsg:
            currentMsgs.add(msg)
    # print(possibleMsgs)
    print("current msgs for {}: {}".format(n1, currentMsgs))

    # if n1 not in stableStates:
    nxtN = G.successors(n1)
    for n in nxtN:
        # if n == n1:
            # continue
        print("next node: {}".format(n))
        nxtOut = G.out_edges(n)
        for nxtOutEdge in nxtOut:
            nxtOutMsg = G.get_edge_data(nxtOutEdge[0], nxtOutEdge[1]).keys()
            print(nxtOutMsg)
            for msg in nxtOutMsg:
                if msg in currentMsgs:
                    if msg in possibleMsgs:
                        print("REMOVE {}".format(msg))
                        possibleMsgs.remove(msg)
    # greyMsgs = []

    # for msg in currentMsgs:
    #     if msg in possibleMsgs:
    #         possibleMsgs.remove(msg)
    #         print("{} can be received now".format(msg))
    # for msg in incomingMessages:
    #     if msg not in possibleMsgs:
    #         greyMsgs.append(msg)
    print("nonstall for state {}: {}".format(n1, currentMsgs))
    print("stall for state {}: {}".format(n1, possibleMsgs))
    for pm1 in currentMsgs:
        for pm2 in possibleMsgs:
            if (pm1, pm2) in newConflicts:
                falseConflict[(pm1, pm2)] = False
                print("True conflict {} {}".format(pm1, pm2))
            elif (pm2, pm1) in newConflicts:
                falseConflict[(pm2, pm1)] = False
                print("True conflict {} {}".format(pm2, pm1))

    # print("Grey messages: {}".format(greyMsgs))

print(falseConflict)

for k in falseConflict.keys():
    if falseConflict[k] == True:
        newConflicts.remove(k)
        # print("removed conflict {}".format(k))
    else:
        pass
        # print("true conflict {}".format(k))

netConstraint = []
if len(sys.argv[1:]) == 2:
    print("=========Applying constraints...===========")
    with open(constraiantFile) as f:
        lines = f.readlines()
        for line in lines:
            if line[0] == '[':
                sameNet = line[1:-1].replace(" ", "").split(",")
                for m1 in sameNet:
                    for m2 in sameNet:
                        rmvConflict = (m1, m2)
                        if rmvConflict in newConflicts:
                            newConflicts.remove(rmvConflict)
                netConstraint.append(sameNet)
            else:
                pair = line.strip().replace(" ","").split(",")
                if (pair[0], pair[1]) in newConflicts:
                    rmvConflict = (pair[0], pair[1])
                    newConflicts.remove(rmvConflict)
                elif ((pair[1], pair[0]) in newConflicts):
                    rmvConflict = (pair[1], pair[0])
                    newConflicts.remove(rmvConflict)
print("Final number of conflicts: {}".format(len(newConflicts)))
assignNetwork(incomingMessages, newConflicts, netConstraint)
print("Outgoing Network")
print(outgoingMessages)


key = []
image = dict()
with open("Day20.txt", 'r') as INPUT:
    data = INPUT.read().replace(".", "0").replace("#", "1").split("\n\n")
    key = list(map(int, list(data[0])))
    rest = data[1].split("\n")
    for i in range(len(rest)):
        a = list(map(int, list(rest[i])))
        for j in range(len(a)):
            image[(i, j)] = a[j]

default = 0
edges = []
def get(p, image):
    global edges
    if p in image:
        return image[p]
    edges.append(p)
    return default

def swap_default():
    global default
    if default == 0:
        default = key[0]
    elif default == 1:
        default = key[0b111111111]
kernel = [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]

def get_k(kernel, p, image):
    v = 0
    for i in kernel:
        v <<= 1
        v += get((i[1] + p[0], i[0] + p[1]), image)
    return v

def print_img(image):
    row = None
    for i, j in sorted(image.keys()):
        if i != row:
            print()
        row = i
        print("#" if image[(i, j)] else ".", end="", sep="")
    print()

def get_count(image):
    return sum(image[i] for i in image)

for index in range(50):
    edges = []
    new_image = dict()
    for i in image:
        n = get_k(kernel, i, image)
        new_image[i] = key[n]
    c_edges = edges.copy()
    for i in c_edges:
        n = get_k(kernel, i, image)
        new_image[i] = key[n]
    swap_default()
    image = new_image
    if index == 1:
        print("part 1:", get_count(image))
print("part 2:", get_count(image))


#!/usr/bin/env python3

import pandas as pd
import os

import rospy
import rospkg
from std_msgs.msg import Bool

from robo_demo_msgs.srv import RunPlanningTest

rospack = rospkg.RosPack()
EE_CONTROL_PATH = rospack.get_path('end_effector_control')
PLANNING_DATA_PATH = os.path.join(EE_CONTROL_PATH, 'data', 'planning')
COMMON_DATA_PATH = os.path.join(PLANNING_DATA_PATH, 'planning_data.csv')

DEFAULT_TEST_DICT = {'change_goal': 10, 'add_obstacle': 10, 'add_obstacle_change_goal': 10}

class TestAutomator():

    def __init__(self, test_dict=DEFAULT_TEST_DICT):
        self.test_dict = test_dict
        self.update_test_counts()
        self.planning_test_srv = rospy.ServiceProxy('/test_interface_service', RunPlanningTest)
        rospy.sleep(0.5)
        rospy.loginfo("TestAutomator initialized, running tests")
        self.run_tests()

    def update_test_counts(self):
        if os.path.exists(COMMON_DATA_PATH):
            df = pd.read_csv(COMMON_DATA_PATH)
            (t1, t2, t3) = ("change_goal", "add_obstacle", "add_obstacle_change_goal")
            t1_count = len(df[df["Scenario"]==t1])
            t2_count = len(df[df["Scenario"]==t2])
            t3_count = len(df[df["Scenario"]==t3])
            self.test_dict[t1] -= t1_count
            self.test_dict[t2] -= t2_count
            self.test_dict[t3] -= t3_count
            rospy.loginfo(f"counts: {t1_count}, {t2_count}, {t3_count}")

    def run_tests(self):
        for (test_type, iterations) in self.test_dict.items():
            for i in range(iterations):
                rospy.loginfo(f"Running {test_type}, iteration: {i+1}/{iterations}")
                response = self.planning_test_srv(test_type)
                rospy.loginfo(f"Received response: {response}")

if __name__ == "__main__":
    rospy.init_node("automate_testing_node")
    test_dict = {'add_obstacle': 2}
    ta = TestAutomator(test_dict)
    # ta = TestAutomator()


from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)

class Hellocall(Resource):
    def get(self,name,number):
        return({'Name':name,'Age':number})

api.add_resource(Hellocall,"/Helloworld/<string:name>/<int:number>")

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


import re
import requests
from bs4 import BeautifulSoup
from time import time as timer

__author__ = "Allen Roberts"
__credits__ = ["Allen Roberts"]
__version__ = "1.0.0"
__maintainer__ = "Allen Roberts"

def readfile():
    with open('KY.txt') as file:
        lines = file.readlines()
    print(lines)
    return lines;

def writetofile(list):
    filename = "emails.txt"
    f = open(filename, "w")
    for email in list:
        f.write(email+"\n")
    f.close()

def google_parse(search_string, start):
    print("Test")
    temp = []
    url = 'http://www.google.com/search'
    payload = {'q': search_string, 'start': start}
    user_agent = {'User-agent': 'Mozilla/11.0'}
    request_response = requests.get(url, params=payload, headers=user_agent)

    soup = BeautifulSoup(request_response.text, 'html.parser')
    aTags = soup.find_all('a')
    print(aTags)
    for a in aTags:
        try:
            temp.append(re.search('url\?q=(.+?)\&sa', a['href']).group(1))
        except:
            continue

    return temp

def main(search, pages):
    start = timer()
    result = []
    for page in range( 0,  int(pages) ):
        result.extend(google_parse( search, str(page*10) ) )
    result = list( set( result ) )
    result = removefalselinks(result)

    print( *result, sep = '\n' )
    print( '\nTotal URLs Scraped : %s ' % str( len( result ) ) )
    print( 'Script Execution Time : %s ' % ( timer() - start, ) )
    return result

def removefalselinks(pagelist):
    for page in pagelist:
        if 'http' in page:
            continue
        else:
            pagelist.remove(page)
    return pagelist

def scrapepages( pagelist ):
    emails = []
    for page in pagelist:
        print(page + ":")
        foundemails = finddata(page)
        if foundemails is None:
            continue
        for email in foundemails:
            emails.append(email)
    print(emails)
    return emails

def finddata( pageurl ):
    headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Max-Age': '3600',
        'User-Agent': 'Mozilla/11.0'
    }
    try:
        print("Making Request")
        req = requests.get(pageurl, headers, timeout=5)
        print("Grabbing HTML")
        soup = BeautifulSoup(req.content, 'html.parser')
        print("Prettying up data")
        pagedata = soup.prettify()
        regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
        emails = re.findall(regex, pagedata)
        print(emails)
        return emails
    except:
        print("Timeout")

def removeduplicates(emails):
    print(emails)
    return list(set(emails))

def validatelist(emails):
    newlist = removeduplicates(emails)
    emailfinal = []
    for email in newlist:
        if '.png' in email:
            print(email)
        elif '.jpeg' in email:
            print(email)
        else:
            emailfinal.append(email)
    return emailfinal

if __name__ == '__main__':
    businesses = readfile()
    scrapedEmails = []
    i = 0
    while i < 3000:
        i += 1
        for business in businesses:
            urls = main(business, 1)
            emails = scrapepages(urls)
            validatedlist = validatelist(emails)
            for email in validatedlist:
                scrapedEmails.append(email)
    print(scrapedEmails)
    writetofile(scrapedEmails)
    print("Done")


# Create class

from Tools.Scripts.treesync import raw_input

import datetime
from datetime import date

class Person:
    def __init__(self, name,year,month,day):
        self.__name=name
        self.__year=year
        self.__month=month
        self.__day=day

    def getage(self):
        now = datetime.datetime.now()
        c_year = now.hour
        c_month = now.month
        c_day = now.day

        current_date = date(c_year, c_month, c_day)
        print(current_date)
        dob = date(self.__year, self.__month, self.__day)
        age = current_date - dob
        print (age)

irene = Person("Irene",1988,8,19)
irene.getage()


#! /usr/bin/env python

import math
import rospy
from sensor_msgs.msg import Imu
from tf.transformations import euler_from_quaternion

def imuCallback(imu):
  quat = [imu.orientation.w, imu.orientation.x, imu.orientation.y, imu.orientation.z]
  roll, pitch, yaw = euler_from_quaternion(quat)
  rospy.loginfo('{} {} {}'.format(roll*180.0/math.pi, pitch*180.0/math.pi, yaw*180.0/math.pi))

def imuToYaw():

  rospy.init_node('imu_to_yaw')
  imu_sub = rospy.Subscriber('/android/imu', Imu, imuCallback)

  rospy.spin()

if __name__ == '__main__':
  imuToYaw()


from tkinter import *
from tkinter import ttk

class FileSaveFrame(Frame):

    def __init__(self, master,filename,app):
        ttk.Frame.__init__(self, master)# super class initialization
        self.relief = GROOVE# tkinter relief attribute.
        self.grid()# grid the frame
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)
        self.parent=app
        self.filename=filename # intialize file name
        self.Widgets()

    def Widgets(self):
        """
        main window of the GUI
        containt:-
        - file_nameL
        - corr_Button for plot clear

        """
        self.file_name=StringVar(self)
        update_filename = self.register(self.update_filename)

        main_frame= ttk.Frame(self, borderwidth=0, relief=GROOVE)
        main_frame.grid()
        main_frame.grid_columnconfigure(0, weight=1)
        main_frame.grid_rowconfigure(0, weight=1)

        self.file_nameL=ttk.Label(main_frame,text='FileName/location')
        self.file_nameL.grid(row=0, column=0, rowspan=1, columnspan=1,
                       sticky=W + E + N + S)
        self.file_nameV=ttk.Entry(main_frame, textvariable=self.file_name,
                                width=62,
                                validate='focusout',
                                validatecommand=update_filename)
        self.file_nameV.grid(row=0, column=1, rowspan=1, columnspan=5,
                       sticky=W + E + N + S)
        self.corr_Button=ttk.Button(main_frame,text='Clc Plt', command=self.clear_plot)
        self.corr_Button.grid(row=0, column=6, rowspan=1, columnspan=1,
                       sticky=W + E + N + S)

    def update_filename(self):
        """
        to update file name

        """
        self.filename=self.file_name.get()
        self.parent.updateFileName(self.filename)

    def clear_plot(self):
        """
        to clear plot

        """
        self.parent.clear_plot()

    def get_fileName(self):
        """
        to get file name

        """
        return self.filename


from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse

from django.template import Context, loader

def index(request):
   omi = "omprakash"
   import urllib
   import json
   resp = urllib.urlopen('https://api.coursera.org/api/courses.v1?q=search&query=malware+underground').read()
   content = json.loads(resp)
   template = loader.get_template("myapp/index.html")
   context = {
      'omi': omi,
      'content' : content,
    }
   return HttpResponse(template.render(context, request))

def search(request):
   form = data = request.GET.get('squery')
   url = "https://api.coursera.org/api/courses.v1?q=search&query=" + form
   omi = "omprakash"
   import urllib
   import json
   vari = form
   resp = urllib.urlopen('https://api.coursera.org/api/courses.v1?start=1&limit=3&q=search&query='+ vari).read()
   content = json.loads(resp)
   template = loader.get_template("myapp/search.html")
   context = {
      'omi': omi,
      'content' : content,
      'form' : form,
    }
   return HttpResponse(template.render(context, request))


from Board import Board
from User import User
from Server import Server

import sys
import os
import socket
import json

import threading as th

#-------------------------------------------------------------------------------------
'''

In class library phase you should implement your basic classes and write a command
line test application demonstrating all features of your library.

'''
#-------------------------------------------------------------------------------------
PORT=3333
filename="../gameBoards/deneme_in"

for i in range(len(sys.argv)):
    if sys.argv[i]=="--port":
        PORT=int(sys.argv[i+1])
        break

# Creating server
server=Server()

# Server socket starts
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# bind socket to a specific address and port
server_socket.bind(('', PORT))

'''#-----------------------------------------------------
# Server start
server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# bind socket to a specific address and port
os.remove("/tmp/mysocket")
server_socket.bind("/tmp/mysocket")
#-----------------------------------------------------
'''

# listen for incoming connections
server_socket.listen()
print(f"Server listening on port {PORT}")

def become_playing_thread(monopoly,user):
    while True:
        game_state = monopoly.turn(user)
        if (game_state == None):
            break
def become_observer_thread(monopoly,user):
    while True:
        message=user.client_socket.recv(1024).decode("Utf-8").strip()
        game_state = monopoly.observe(user,message)
        if (game_state == None):
            break
def become_game_thread(monopoly):
    current_user = monopoly.order[0]
    while True:
        current_user = monopoly.turn(current_user)
        if (current_user == None):
            break

#-----------------------------user thread function--------------------------------------------
def user_thread_func(client_socket, address):

    # ask sign in or up:
    while True:
        wrong_count=0
        client_socket.send("Do u want to login or sign up or exit:write either \"login\" or \"sign up\" or \"exit\"\n".encode("utf-8"))
        received_msg = client_socket.recv(1024).decode('utf-8').strip()
        if(received_msg=="login"):
            user = User(client_socket, address, "login")
            if(user.authh()==False):
                client_socket.send("Wrong password or Username goodbye\n".encode("utf-8"))
                return
            break
        elif(received_msg=="sign up"):
            user = User(client_socket, address,"sign up")
        elif(received_msg == "exit"):
            client_socket.send("Goodbye and have a nice day\n".encode("utf-8"))
            return
        else:
            wrong_count+=1
            if(wrong_count<3):
                client_socket.send(f"You wrote {received_msg} wrong input count={wrong_count}\n".encode("utf-8"))
            else:
                client_socket.send(f"You wrote {received_msg} wrong input count={wrong_count} goodbye\n".encode("utf-8"))
                return

    while True:
        # sending game list to the user
        this_thread_is_observer_thread=False
        while True:
            is_user_attached=False
            game_list=server.list()
            user.client_socket.send(("New or join or observe\nto exit write exit\nto join write Join(game_id)\nto observe write Observe(game_id)\nto create a game New(number of players)\n\tnumber of players must be between 2-4\n"+str(game_list)+"\n").encode("utf-8"))
            received_msg = user.client_socket.recv(1024).decode('utf-8').strip()
            if received_msg.startswith("New(") and received_msg.endswith(")") and received_msg[4:-1].isnumeric():
                user_count = int(received_msg[4:-1])
                monopoly=server.new(user_count)
                if monopoly:
                    is_user_attached=server.open(monopoly, user)
                    # is_user_attached=True
            elif received_msg.startswith("Join(") and received_msg.endswith(")") and received_msg[5:-1].isnumeric():
                game_index=int(received_msg[5:-1])
                if(game_index in game_list):
                    is_user_attached=server.open(game_list[game_index],user)
                    if(is_user_attached):
                        monopoly=game_list[game_index]
                else:
                    user.client_socket.send(f"There is no game ({game_index})\n".encode("utf-8"))
            elif received_msg.startswith("Observe(") and received_msg.endswith(")") and received_msg[8:-1].isnumeric():
                game_index=int(received_msg[8:-1])
                if(game_index in game_list):
                    server.observe(game_list[game_index],user)
                    monopoly = game_list[game_index]
                    this_thread_is_observer_thread=True
                    is_user_attached=True
                else:
                    user.client_socket.send(f"There is no game ({game_index})\n".encode("utf-8"))
            elif (received_msg == "exit"):
                client_socket.send("Goodbye and have a nice day\n".encode("utf-8"))
                return
            else:
                user.client_socket.send(f"Sent wrong commend({received_msg})\n".encode("utf-8"))
            if(is_user_attached):
                break

        if(this_thread_is_observer_thread==True):
            become_observer_thread(monopoly,user)
            continue

        # wait for user to respond with ready
        user.client_socket.send("write \"ready\" when you are ready write \"exit\" if you want to leave\n".encode('utf-8'))
        ready_msg = user.client_socket.recv(1024).decode('utf-8').strip()
        while ready_msg!="ready" and ready_msg!="exit":
            user.client_socket.send(f"Invalid message {ready_msg}. write \"ready\" when you are ready write \"exit\" if you want to leave\n".encode('utf-8'))
            ready_msg = user.client_socket.recv(1024).decode('utf-8').strip()
        if ready_msg == "exit":
            server.close(monopoly,user)
            continue
        monopoly.ready(user)

        # barrier waiting it will be opened by the last user in board
        '''if monopoly.WaitingState==True:
            user.mutex.acquire()
        else:
            become_game_thread(monopoly)'''
        become_playing_thread(monopoly,user)

#---------------------------------------------------------------------------------------------

user_threads=[]
while True:
    # accept incoming connection
    client_socket, address = server_socket.accept()
    print(f"Accepted connection from {address}")

    user_thread=th.Thread(target=user_thread_func,args=(client_socket, address))
    user_threads.append(user_thread)
    user_thread.start()

for user_thread in user_threads:
    user_thread.join()

'''current_user=monopoly.order[0]
while True:
    current_user=monopoly.turn(current_user)
    if(current_user==None):
        break'''


import struct

class InvalidArgumentException(Exception):
    pass

class Color:
    def __init__(self, r, g, b):
        self.red = r
        self.green = g
        self.blue = b
        self._validate()

    def _validate(self):
        for v in [self.red, self.green, self.blue]:
            if not(0 <= v <= 255):
                raise InvalidArgumentException("invalid color")

    def element_iter(self):
        yield self.red
        yield self.green
        yield self.blue

class Gif:
    def __init__(self, data, width, height, colors):
        self.image_data = data
        self.logical_screen_width = width
        self.logical_screen_height = height
        self.global_color_resolution = len('{:b}'.format(len(colors) )) - 1
        self.colors = colors
        diff_len = pow(2, (self.global_color_resolution + 1)) - len(colors)
        self.colors.extend([Color(0, 0, 0) for _ in range(diff_len)])
        self._validate()

    def _validate(self):
        if not (0 < self.logical_screen_width < 65535):
            raise InvalidArgumentException("invalid widht")
        if not (0 < self.logical_screen_height < 65535):
            raise InvalidArgumentException("invalid height")
        if not (0 <= self.global_color_resolution < 7):
            raise InvalidArgumentException("invalid global color resolution")

    def _global_color_tables(self):
        for color in self.colors:
            yield from color.element_iter()

        pallet_len = pow(2, (self.global_color_resolution))
        for _ in range((pallet_len - len(self.colors)) * 3):
            yield 0

    def _get_header_data(self):
        data = bytearray()
        data.extend(b'GIF')  # signature
        data.extend(b'87a')  # gif version
        data.extend(struct.pack('<H', self.logical_screen_width))
        data.extend(struct.pack('<H', self.logical_screen_height))

        b = 1  # Global Color Table Flag
        b = b << 3 | self.global_color_resolution  # Color Resolution
        b = b << 1 | 0  # Size of Global Color Table
        b = b << 3 | self.global_color_resolution  # Sort Flagn
        data.append(b)

        data.append(0)  # Background Color Index
        data.append(0)  # Pixel Aspect Ratio

        data.extend([b for b in self._global_color_tables()])
        return data

    def _get_image_blocks(self):
        data = bytearray()
        data.append(0x2c)  # Image Separator
        data.extend([0x00, 0x00]) # Image Left Position
        data.extend([0x00, 0x00]) # Image Top Position
        data.extend(struct.pack('<H', self.logical_screen_width))
        data.extend(struct.pack('<H', self.logical_screen_height))
        b = 0 # Local Color Table Flag
        b = b << 1 | 0  # Interlace Flag
        b = b << 1 | 0  # Sort Flag
        b = b << 2 | 0  # Reversed
        b = b << 3 | 0  # Size of Local Color Table
        data.append(b)

        lzw = Lzw(len(self.colors))
        data.append(lzw.minimum_code_size)

        lzw_data = list(lzw.compress(self.image_data))
        lzw_len = len(lzw_data)

        while lzw_len > 0:
            if lzw_len > 255:
                data.append(255)
                data.extend(lzw_data[:255])
                lzw_data = lzw_data[255:]
                lzw_len -= 255
            else:
                data.append(lzw_len)
                data.extend(lzw_data)
                lzw_len = 0

        data.append(0x00)  # Block Terminator
        return data

    def to_bytes(self):
        data = self._get_header_data()
        data.extend(self._get_image_blocks())
        data.append(0x3b)
        return data

class Bits:
    def __init__(self):
        self.bits = []

    def append(self, value, bit_len):
        for i in range(bit_len):
           self.bits.insert(0, (value >> i & 1))

    def to_bytes(self):
        bits = self.bits
        while len(bits) > 0:
            b = bits[-8:]
            for _ in range(len(b)):
                bits.pop()

            byte = 0
            for i in range(len(b)):
                byte = (byte << 1) | b[i]

            yield byte

class Lzw:
    def __init__(self, dic_len):
        self.dic_len = dic_len
        self.max_code = (self.dic_len if self.dic_len > 2 else 4)
        self.minimum_code_size = len('{:b}'.format(self.max_code - 1))

    def compress(self, data):
        max_code = self.max_code
        max_code_bits = self.minimum_code_size

        def to_key(add, prev_key=[]):
            tmp = list(prev_key)
            tmp.append(add)
            return tuple(tmp)

        # 辞書初期化
        dic = {}
        for i in range(max_code):
            key = to_key(i)
            dic[key] = i

        # クリアコード
        dic[to_key(max_code)]  = max_code
        clear_code = max_code

        # エンドコード
        max_code += 1
        dic[to_key(max_code)]  = max_code
        end_code = max_code
        if max_code >= 1 << max_code_bits and max_code_bits < 12:
            max_code_bits += 1

        # 圧縮
        key = []
        result = Bits()
        result.append(clear_code, max_code_bits)

        for n, c in enumerate(data):
            prev_key = key
            key = to_key(c, prev_key)
            if key in dic:
                continue

            result.append(dic[prev_key], max_code_bits)

            if max_code < 4096:
                max_code += 1
                dic[key] = max_code
                if max_code == 1 << max_code_bits and max_code_bits < 12:
                    max_code_bits += 1

            key = to_key(c)
        else:
            if key in dic:
                result.append(dic[key], max_code_bits)

        result.append(end_code, max_code_bits)
        return result.to_bytes()

if __name__ == '__main__':
    data = [1,1,1,1,1,2,2,2,2,2,
            1,1,1,1,1,2,2,2,2,2,
            1,1,1,1,1,2,2,2,2,2,
            1,1,1,0,0,0,0,2,2,2,
            1,1,1,0,0,0,0,2,2,2,
            2,2,2,0,0,0,0,1,1,1,
            2,2,2,0,0,0,0,1,1,1,
            2,2,2,2,2,1,1,1,1,1,
            2,2,2,2,2,1,1,1,1,1,
            2,2,2,2,2,1,1,1,1,1]

    colors = [Color(255, 255, 255), Color(255, 0, 0), Color(0, 0, 255)]
    g = Gif(data, 10, 10, colors)
    with open("temp.gif", 'wb') as f:
            f.write(g.to_bytes())


import enemy
from enemy import *
class CHero(CEnemy):
	def clean(self,fair=True):
		if fair:
			self.skill = dice()+6
			self.stamina = dice(2)+12
			self.luck = dice()+6
		else:
			self.skill = 12
			self.stamina = 24
			self.luck = 12
		self.maxskill = self.skill
		self.maxstamina = self.stamina
		self.maxluck = self.luck
		self.damage = 2
		self.alive = True
	def __init__(self,fair=True):
		self.clean(fair)
	def heal(self,diff):
		self.stamina = self.stamina + diff
		self.stamina = min(self.stamina,self.maxstamina)
	def testluck(self):
		self.luck = self.luck-1
		return(self.luck > dice(2))
	def testskill(self):
		return self.skill>=dice(2)


import view as vw
import logger as log
import model as ml
import is_number as is_n

def run():
    while True:
        select_action = vw.select_action()

        if is_n.is_number(select_action):
            data_file = log.get_data()

            if select_action == 1:

                if not data_file:
                    last_id = 1
                else:
                    last_id = int(ml.get_last_id(data_file)) + 1

                create_new = vw.add_contact(last_id)
                log.create_new(create_new)
                print('Контакт добавлен!')
                print()
            elif select_action == 2:
                view_search = vw.search_contact()
                result = ml.search_contact(data_file, view_search)
                vw.show_contact(result)
            elif select_action == 3:
                view_search = vw.search_contact()
                result = ml.search_contact(data_file, view_search)

                if isinstance(result[0], dict):
                    indexes = []

                    for value in result:
                        indexes.append(int(data_file.index(value)))

                    if len(indexes) == 1:
                        query = vw.update_value(data_file[0])
                        updated_file = ml.update_contact(query, data_file, indexes[0])
                        log.overwrite_file(updated_file)
                        print(f'Данные успешно изменены!')
                    else:
                        select_element = vw.update_element(indexes, data_file)
                        query = vw.update_value(data_file[select_element])
                        updated_file = ml.update_contact(query, data_file, select_element)
                        log.overwrite_file(updated_file)
                        print(f'Данные успешно изменены!')
                else:
                    print(''.join(result[0]))
            elif select_action == 4:
                view_search = vw.search_contact()
                result = ml.search_contact(data_file, view_search)

                if isinstance(result[0], dict):
                    indexes = []
                    for value in result:
                        indexes.append(int(data_file.index(value)))

                    if len(indexes) == 1:
                        new_data = ml.delete_contact(indexes[0], data_file)
                        log.overwrite_file(new_data)
                        print(f'Контакт удален!')
                    else:
                        choose_element = vw.choose_element(indexes, data_file)
                        new_data = ml.delete_contact(choose_element, data_file)
                        log.overwrite_file(new_data)
                        print(f'Контакт удален!')
                else:
                    print(''.join(result[0]))

            elif select_action == 5:
                exit()
        else:
            print('Вы ввели неверное значение! Попробуйте снова!')


import csv
import json

species_file = open('./data/union_list.json','r')
species_list  = json.loads(species_file.read())

country_codes = [
    "BG",
    "HR",
    "CZ",
    "DK",
    "NL",
    "UK",
    "EE",
    "FI",
    "FR",
    "DE",
    "GR",
    "HU",
    "IE",
    "IT",
    "LV",
    "LT",
    "MT",
    "PL",
    "PT",
    "RO",
    "SK",
    "SI",
    "ES",
    "SE"
]

result = []
delimiter = ";"

for iso in country_codes:
    iso_input = open('./data/common_names_inputs/'+iso+'_common_names.csv','r')
    common_names_dict = csv.DictReader(iso_input)
    common_names = []

    for item in common_names_dict:
        common_names.append(item)

    for row in species_list:
        tmp_names = set()
        for item in common_names:
           if item['eu_name'].startswith(row['speciesName']):
                tmp_names.add(item['common_name'])
        row[iso+'_CommonName'] = delimiter.join(tmp_names)
        result.append(row)

print(result)

species_list_section_A = open('./data/species_list_a.json', 'w', encoding='utf-8')
json.dump(species_list, species_list_section_A, ensure_ascii=False)

#for item in country_codes:
#    common_names_lang_file = open('./data/common_names_outputs/'+item+'_common_names.json', 'w', encoding='utf-8')
#    json.dump(result[item], nuts_regions_file, ensure_ascii=False)


# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.contrib import admin
admin.autodiscover()

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

    url(r'^admin/', include(admin.site.urls)),
    url(r'^grappelli/', include('grappelli.urls')),

    # Apps urls
    url(r'^$', 'estoque.views.start',),
    url(r'^estoque/', include('estoque.urls')),
    url(r'^cadastro/$', 'estoque.views.cadastro', name='cadastro'),
    url(r'^request_user_pass/$', 'estoque.views.request_user_pass', name='request_user_pass'),

    # Autenticação
    url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout', {"next_page": "/"}, name='logout'),
)

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

urlpatterns += staticfiles_urlpatterns()


r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))

if r1 <r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
    print('Os segmentos podem formar um triângulo, ', end='')

    if  r1 == r2 == r3:  # ou r1 == r2 and r2 == r3
        print('EQUILÁTERO')
    elif r1 != r2 != r3 != r1:
        print('ESCALENO')
    else:
        print('ISOSCELES')

else:
    print('Os segmentos nao podem formar um triângulo')

Curso-em-video/Mundo-2/AULA12-Condições-Aninhadas/#042 - Analisando Triângulos v2.0.py


from django.db.models import Q
from django.shortcuts import get_object_or_404
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.exceptions import NotFound, PermissionDenied, ParseError
from rest_framework.permissions import IsAuthenticated
from .models import Letterlist, Letter
from . import serializers
from users.models import User

# /me/
class ChattingList(APIView):
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        operation_summary="채팅방 목록 조회",
        responses={
            200: openapi.Response(
                description="Succfull Response",
                schema=serializers.ChatroomSerialzier(many=True),
            )
        },
    )
    def get(self, request):
        chatlist = Letterlist.objects.filter(user=request.user).order_by("-updated_at")
        chatlist = [i for i in chatlist if request.user not in i.ignore_by.all()]
        serializer = serializers.ChatroomSerialzier(
            chatlist,
            many=True,
            context={"request": request},
        )
        return Response(serializer.data)

# /<int:pk>/ GET
class ChattingRoom(APIView):
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        operation_summary="해당 채팅방의 쪽지 기록 조회",
        responses={
            200: openapi.Response(
                description="Successful Response",
                schema=serializers.MessageSerialzier(),
            ),
            400: openapi.Response(description="Not Found Pk"),
            403: openapi.Response(description="Permission Denied"),
        },
    )
    def get(self, request, pk):
        chat = Letter.objects.filter(room__pk=pk)
        if chat:
            if request.user not in chat[0].room.user.all():
                raise PermissionDenied
            chat = [i for i in chat if request.user not in i.delete_by.all()]
            serializer = serializers.MessageSerialzier(
                chat,
                many=True,
                context={"request": request},
            )

            return Response(serializer.data)
        raise NotFound

    @swagger_auto_schema(
        operation_summary="쪽지방 차단",
        responses={
            204: openapi.Response(
                description="Successful Response",
            ),
            403: openapi.Response(description="Sender != request.user"),
            404: openapi.Response(description="Not Found Pk"),
        },
    )
    def delete(self, request, pk):
        letter = get_object_or_404(Letterlist, pk=pk)
        user = [i for i in letter.user.all()]
        if request.user in user:
            letter.ignore_by.add(request.user)
            letter.save()
            return Response("Ok", status=204)
        else:
            raise PermissionDenied

# /message/ POST -> 메세지 전송
class MessageSend(APIView):
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        operation_summary="쪽지 전송",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=["receiver", "text"],
            properties={
                "receiver": openapi.Schema(
                    type=openapi.TYPE_INTEGER,
                    description="보내는 유저의 pk ",
                ),
                "text": openapi.Schema(
                    type=openapi.TYPE_STRING,
                    description="전송하는 메세지",
                ),
            },
        ),
        responses={
            201: openapi.Response(
                description="Successful Response",
            ),
            400: openapi.Response(description="Data Error"),
            404: openapi.Response(description="Not Found Pk"),
        },
    )
    def post(self, request):
        serializer = serializers.MessageSerialzier(data=request.data)
        if serializer.is_valid():
            receiver = request.data.get("receiver")
            if not receiver:
                raise ParseError("required receiver")
            if receiver == str(request.user.pk):
                raise ParseError("can't send to yourself")
            message = serializer.save(sender=request.user, receiver=receiver)
            return Response("Successful Response", status=201)
        else:
            return Response(serializer.errors, status=400)

class MessageDelete(APIView):
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        operation_summary="쪽지 삭제",
        responses={
            204: openapi.Response(
                description="Successful Response",
            ),
            400: openapi.Response(description="Not Found Pk"),
            403: openapi.Response(description="Sender != request.user"),
        },
    )
    def delete(self, request, pk):
        letter = get_object_or_404(Letter, pk=pk)
        user = [i for i in letter.room.user.all()]
        if request.user in user:
            letter.delete_by.add(request.user)
            letter.save()
            # if letter.sender == request.user:
            #     # letter.delete()
            return Response("Ok", status=204)
        else:
            raise PermissionDenied


from django.urls import path, include
from .views import LoginView, RegisterView, \
    LogoutView, DepartView, JobView, SetPwd, DepartEditView, JobEditView, \
    JobRelateUserView, DepartRelateUserView, AppointWorkflowAdmin, IndexView, AppointCommon, AddDepartView, \
    DepartRelateUserEditView, AddJobView, JobRelateUserEditView

from django.views import View

urlpatterns = [
    path('index/<str:job_id>', IndexView.as_view()), # 个人主页
    path('login/', LoginView.as_view()), # 用户初始登录
    path('login/set_pwd/', SetPwd.as_view()), # 注册后的用户登录后修改密码
    path('logout/', LogoutView.as_view()), # 注销
    path('register/', RegisterView.as_view()), # 管理员进行用户注册

    path('appoint_workflow_admin/', AppointWorkflowAdmin.as_view()), # 管理员指定一个或多个用户（GET请求，查询字符串?job_id=1&job_id=2获得用户，POST请求发送job_id列表设置用户）为工作流管理员
    path('appoint_common/', AppointCommon.as_view()), # 管理员指定一个或多个工作流管理员（GET请求，查询字符串?job_id=1&job_id=2获得用户，POST请求发送job_id列表设置用户）为普通用户

    path('depart/', DepartView.as_view()), # 管理员使用，查看(分页、url查询字符串)部门信息
    path('add_depart/', AddDepartView.as_view()), # 管理员使用，添加部门
    path('depart/edit/<int:depart_id>', DepartEditView.as_view()), # 管理员使用，修改、删除指定部门

    path('depart/view/depart<int:depart_id>/relate_user/', DepartRelateUserView.as_view()), # 管理员使用，查看部门成员
    path('depart/edit/depart<int:depart_id>/relate_user/', DepartRelateUserEditView.as_view()), # 管理员用户， 添加、更新、删除部门成员

    path('job/', JobView.as_view()), # 管理员使用，查看(分页、url查询字符串)岗位
    path('add_job/', AddJobView.as_view()), # 管理员使用，添加岗位
    path('job/edit/<int:jobtitle_id>', JobEditView.as_view()), # 管理员使用，修改、删除指定岗位

    path('job/view/job<int:jobtitle_id>/relate_user/', JobRelateUserView.as_view()), # 管理员使用，查看岗位成员
    path('job/edit/job<int:jobtitle_id>/relate_user/', JobRelateUserEditView.as_view()), # 管理员使用，添加、更新、删除岗位成员

]


#Library
import datetime
import time
from tkinter import *
import tkinter.ttk as ttk
from urllib.request import urlretrieve
import serial
import os
import RPi.GPIO as GPIO
#End Library

#Firmwares
ultra1 = serial.Serial("/dev/ttyUSB0",baudrate=9600, timeout=1)
gsm = serial.Serial("/dev/ttyAMA0",baudrate=9600, timeout=1)

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(31,GPIO.OUT) #Relay 1
GPIO.setup(33,GPIO.OUT) #Relay 2
GPIO.setup(35,GPIO.OUT) #Relay 3
GPIO.setup(37,GPIO.OUT) #Relay 4
GPIO.setup(12,GPIO.OUT) #Sensor1 Enable
#End Firmwares

root=Tk()
root.geometry("%dx%d+%d+%d"%(800,480,100,50)) #x,y,horizental,vertical
root.title('SAJAB')
root.configure(background='lightblue')

f1=open("relay1_source.txt","r")
f2=open("relay2_source.txt","r")
f3=open("relay3_source.txt","r")
f4=open("relay4_source.txt","r")

v1 = IntVar()
v1.set(int(f1.read()))  # initializing the choice, i.e. Python

v2 = IntVar()
v2.set(int(f2.read()))  # initializing the choice, i.e. Python

v3 = IntVar()
v3.set(int(f3.read()))  # initializing the choice, i.e. Python

v4 = IntVar()
v4.set(int(f4.read()))  # initializing the choice, i.e. Python

GPIO.output(31,v1.get())
GPIO.output(33,v2.get())
GPIO.output(35,v3.get())
GPIO.output(37,v4.get())

f1.close()
f2.close()
f3.close()
f4.close()

#Variables
station_name = "Golestan Uni"

pass_main='1120'
time_xloc= 20
time_yloc= 5

date_xloc=10
date_yloc=30

table_x=20
table_y=150

global default_sampling_rate
global default_bias_value
global default_coefficent
global default_max_level
global default_hysteresis_level
global default_mobile_phone1
global default_mobile_phone2
global default_mobile_phone3

step = 20
stepx = 40
global sampling_rate
sampling_rate=2
#End Variables

#Functions

def relay1():
    relay1_source = open("relay1_source.txt","w+")
    GPIO.setup(31,GPIO.OUT) #Relay 1
    if v1.get()==0:
        print("is off")
        GPIO.output(31,0)
        relay1_source.write("0")
    else:
        print("in on")
        GPIO.output(31,1)
        relay1_source.write("1")
    relay1_source.close()
def relay2():
    relay2_source = open("relay2_source.txt","w+")
    GPIO.setup(33,GPIO.OUT) #Relay 1
    if v2.get()==0:
        print("is off")
        GPIO.output(33,0)
        relay2_source.write("0")
    else:
        print("in on")
        GPIO.output(33,1)
        relay2_source.write("1")
    relay2_source.close()
def relay3():
    relay3_source = open("relay3_source.txt","w+")
    GPIO.setup(35,GPIO.OUT) #Relay 1
    if v3.get()==0:
        print("is off")
        GPIO.output(35,0)
        relay3_source.write("0")
    else:
        print("in on")
        GPIO.output(35,1)
        relay3_source.write("1")
    relay3_source.close()
def relay4():
    relay4_source = open("relay4_source.txt","w+")
    GPIO.setup(37,GPIO.OUT) #Relay 1
    if v4.get()==0:
        print("is off")
        GPIO.output(37,0)
        relay4_source.write("0")
    else:
        print("in on")
        GPIO.output(37,1)
        relay4_source.write("1")
    relay4_source.close()

#Send Data
def send_data():
    gsm.write("AT\r\n".encode('ascii'))
    rcv = gsm.read(10)
    print (rcv)
    gsm.write("AT+CSQ\r\n".encode('ascii'))
    time.sleep(1)
    gsm.write("AT+CGATT?\r\n".encode('ascii'))
    time.sleep(1)
    gsm.write("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"\r\n".encode('ascii'))
    time.sleep(1)
    gsm.write("AT+SAPBR=3,1,\"APN\",\"mtnirancell\"\r\n".encode('ascii'))
    time.sleep(4)
    gsm.write("AT+SAPBR=1,1\r\n".encode('ascii'))
    time.sleep(2)
    gsm.write("AT+HTTPINIT\r\n".encode('ascii'))
    time.sleep(2)
    data_link = "AT+HTTPPARA=\"URL\",\"http://sajab.sazabgolestan.com/server.php?action=save&station_index=3&ha=%d&hb=3&imei=9359374362\"\r\n" %(sensor1_read(sen1))
    gsm.write(data_link.encode('ascii'))
    time.sleep(1)
    gsm.write("AT+HTTPACTION=0\r\n".encode('ascii'))
    time.sleep(10)
#End Send Data
#Sensor Read
def sensor1_read(sen):
    def count():
        GPIO.output(12,0)
        global u1
        u1 = ultra1.read(12)
        u1 = str(u1)
        loc = u1.find('R')
        u1 = u1[loc+1:loc+6]
        GPIO.output(12,1)
        sen.config(text=str(u1))
        sen.after(sampling_rate*500,count)
    count()
    return int(u1)
#End Sensor read

#Samle Rate read
#def sr_read(sr_label):
#    def count5():
#        sr_label.config(text=str(sampling_rate))
#        sr_label.after(sampling_rate*500,count5)
#    count5()
#End Samle Rate read

def pass_check():
    global passcheck
    passcheck = Toplevel()
    passcheck.geometry("%dx%d+%d+%d"%(200,140,100,50)) #x,y,horizental,vertical
    passcheck.title('Setting')
    passcheck.configure(background='lightblue')
    Label(passcheck,text="Enter Password:",fg=top_bg_color,bg=color,width=0).place(x=40,y=20)
    global pass_in
    pass_in=Entry(passcheck,width=18)
    pass_in.place(x=25,y=50)

    Button(passcheck,text="OK",command=pass_check2).place(x=80,y=80)

def pass_check2():
    if pass_in.get()==pass_main:
        passcheck.destroy()
        setting()
    else:
        Label(passcheck,text="Password is wrong!",fg=top_bg_color,bg=color,width=0).place(x=40,y=110)

def setting():
    global setting_frame
    setting_frame = Toplevel()
    setting_frame.geometry("%dx%d+%d+%d"%(700,420,100,50)) #x,y,horizental,vertical
    setting_frame.title('Setting')
    setting_frame.configure(background='lightblue')
    Label(setting_frame,text="Station name:",fg=top_bg_color,bg=color,width=0).grid(row=0,column=0,ipadx=30,pady=8)
    Label(setting_frame,text=station_name,fg=top_bg_color,bg=color,width=0).grid(row=0,column=1,ipadx=30,pady=8)
    Label(setting_frame,text="Sampling rate:",fg=top_bg_color,bg=color,width=0).grid(row=1,column=0,ipadx=30,pady=8)
    global samp_rate
    samp_rate=Entry(setting_frame,width=8)
    samp_rate.place(x=140,y=45)
    samp_rate.insert(10,str(sampling_rate))
    Label(setting_frame,text="Sec.",fg=top_bg_color,bg=color,width=0).place(x=220,y=46)
    Label(setting_frame,text="Calibration:",fg=top_bg_color,bg=color,width=0).grid(row=2,column=0,ipadx=30,pady=8)
    Label(setting_frame,text="Bias Value:",fg=top_bg_color,bg=color,width=0).grid(row=3,column=0,ipadx=30,pady=8)
    global bs_value
    bs_value=Entry(setting_frame,width=8)
    bs_value.place(x=140,y=118)
    bs_value.insert(10,str(default_bias_value))
    Label(setting_frame,text="Coefficent:",fg=top_bg_color,bg=color,width=0).grid(row=4,column=0,ipadx=30,pady=8)
    global coef
    coef=Entry(setting_frame,width=8)
    coef.place(x=140,y=154)
    coef.insert(10,str(default_coefficent))
    Label(setting_frame,text="Alert:",fg=top_bg_color,bg=color,width=0).grid(row=0,column=3,ipadx=30,pady=8)
    Label(setting_frame,text="Max level:",fg=top_bg_color,bg=color,width=0).grid(row=1,column=3,ipadx=30,pady=8)
    global mx_level
    mx_level=Entry(setting_frame,width=8)
    mx_level.place(x=465,y=45)
    mx_level.insert(10,str(default_max_level))
    Label(setting_frame,text="m.m.",fg=top_bg_color,bg=color,width=0).place(x=545,y=46)
    Label(setting_frame,text="Hysteresis level:",fg=top_bg_color,bg=color,width=0).grid(row=2,column=3,ipadx=30,pady=8)
    global hys_level
    hys_level=Entry(setting_frame,width=8)
    hys_level.place(x=465,y=81)
    hys_level.insert(10,str(default_hysteresis_level))
    Label(setting_frame,text="m.m.",fg=top_bg_color,bg=color,width=0).place(x=545,y=82)
    Label(setting_frame,text="Mobile Phone 1:",fg=top_bg_color,bg=color,width=0).grid(row=3,column=3,ipadx=30,pady=8)
    global mob_phone1
    mob_phone1=Entry(setting_frame,width=15)
    mob_phone1.place(x=465,y=117)
    mob_phone1.insert(10,str(default_mobile_phone1))
    Label(setting_frame,text="Mobile Phone 2:",fg=top_bg_color,bg=color,width=0).grid(row=4,column=3,ipadx=30,pady=8)
    global mob_phone2
    mob_phone2=Entry(setting_frame,width=15)
    mob_phone2.place(x=465,y=153)
    mob_phone2.insert(10,str(default_mobile_phone2))
    Label(setting_frame,text="Mobile Phone 3:",fg=top_bg_color,bg=color,width=0).grid(row=5,column=3,ipadx=30,pady=8)
    global mob_phone3
    mob_phone3=Entry(setting_frame,width=15)
    mob_phone3.place(x=465,y=189)
    mob_phone3.insert(10,str(default_mobile_phone3))
    Button(setting_frame,text="OK",command=ok).place(x=30,y=220)
    Button(setting_frame,text="Set as default",command=setasdefault).place(x=120,y=220)
    Button(setting_frame,text="Default values",command=defaultvals).place(x=300,y=220)
    Button(setting_frame,text="Cancel",command=cncl).place(x=500,y=220)

def ok():
    global sampling_rate
    sampling_rate = int(samp_rate.get())
    print(int(samp_rate.get()))
    print(sampling_rate)
    bias_value = int(bs_value.get())
    coefficent = int(coef.get())
    max_level = int(mx_level.get())
    hysteresis_value = int(hys_level.get())
    mobile_phone1 = mob_phone1.get()
    mobile_phone2 = mob_phone2.get()
    mobile_phone3 = mob_phone3.get()

    conf_str = "http://sajab.sazabgolestan.com/server.php?action=station&imei=9359374362&station_index=3&status=1&sampling_rate=%d&bias_value=%d&coefficent=%d&max_level=%d&hysteresis_value=%d&mobile_phone1=%s&mobile_phone2=%s&mobile_phone3=%s" %(sampling_rate,bias_value,coefficent,max_level,hysteresis_value,mobile_phone1,mobile_phone2,mobile_phone3)

    conf_file = open("conf.txt","w+")
    conf_file.write(conf_str)
    conf_file.close()

    setting_frame.destroy()
def cncl():
    setting_frame.destroy()

def defaultvals():

    samp_rate.delete(0,END)
    samp_rate.insert(10,str(default_sampling_rate))
    bs_value.delete(0,END)
    bs_value.insert(10,str(default_bias_value))
    coef.delete(0,END)
    coef.insert(10,str(default_coefficent))
    mx_level.delete(0,END)
    mx_level.insert(10,str(default_max_level))
    hys_level.delete(0,END)
    hys_level.insert(10,str(default_hysteresis_level))
    mob_phone1.delete(0,END)
    mob_phone1.insert(10,str(default_mobile_phone1))
    mob_phone2.delete(0,END)
    mob_phone2.insert(10,str(default_mobile_phone2))
    mob_phone3.delete(0,END)
    mob_phone3.insert(10,str(default_mobile_phone3))

def setasdefault():
    default_conf_str = "http://sajab.sazabgolestan.com/server.php?action=station&imei=9359374362&station_index=3&status=1&sampling_rate=%d&bias_value=%d&coefficent=%d&max_level=%d&hysteresis_value=%d&mobile_phone1=%s&mobile_phone2=%s&mobile_phone3=%s" %(default_sampling_rate,default_bias_value,default_coefficent,default_max_level,default_hysteresis_value,default_mobile_phone1,default_mobile_phone2,default_mobile_phone3)

    default_conf_file = open("default_conf.txt","w+")
    default_conf_file.write(default_conf_str)
    default_conf_file.close()

#Functions for splitting the different components of date and time
def nowYear():
    now = datetime.datetime.now()
    year = now.year
    return str(year)

def nowMonth():
    now = datetime.datetime.now()
    month = now.month
    return str(month)

def nowDay():
    now = datetime.datetime.now()
    day = now.day
    return str(day)

def nowHour():
    now = datetime.datetime.now()
    hour = now.hour
    return str(hour)

def nowMinute():
    now = datetime.datetime.now()
    minute = now.minute
    return str(minute)

def nowSecond():
    now = datetime.datetime.now()
    second = now.second
    return str(second)

def year_label(label):
  def count1():
    label.config(text=nowYear())
    label.after(1000, count1)
  count1()

def month_label(label):
  def count2():
    label.config(text=nowMonth())
    label.after(1000, count2)
  count2()

def day_label(label):
  def count3():
    label.config(text=nowDay())
    label.after(1000, count3)
  count3()

def hour_label(label):
  def count4():
    label.config(text=nowHour())
    label.after(1000, count4)
  count4()

def minute_label(label):
  def count5():
    label.config(text=nowMinute())
    label.after(1000, count5)
  count5()

def second_label(label):
  def count6():
    label.config(text=nowSecond())
    label.after(1000, count6)
  count6()

def about():
   filewin = Toplevel(root)
   tx ="""
    Development by: Sina Meshkini
    +98 911 380 6028
    SinaMeshkini7@gmail.com
    @SinaMeshkini
    """
   message = Message(filewin, text=tx, relief = RIDGE , width = 400)
   message.pack(fill="both", expand="yes")
#End Functions

#Desigen Param

color = 'lightblue'
top_fg_color = 'lightblue'
top_bg_color = '#111131'
#End Desigen Param

#Header
w = Canvas(root,width= 800,height= 100)
w.pack()
w.create_rectangle(0,0,800,100,fill=top_bg_color)

Label(root,text='SAJAB Management System',fg=top_fg_color,bg=top_bg_color,font="tahoma 24 bold",pady=10).place(x=150,y=5)

#Time
hourLabel = Label(root,text=nowHour(),fg=top_fg_color,bg=top_bg_color,font=("Ravie", 10))
hourLabel.place(x=time_xloc,y=time_yloc)
hour_label(hourLabel)

colon = Label(root, text = ":",fg=top_fg_color,bg=top_bg_color,font=("Ravie",14))
colon.place(x=time_xloc+step,y=time_yloc-5)

minuteLabel = Label(root, text = nowMinute(),fg=top_fg_color,bg=top_bg_color,font=("Ravie",10))
minuteLabel.place(x=time_xloc+2*step,y=time_yloc)
minute_label(minuteLabel)

colon = Label(root, text = ":",fg=top_fg_color,bg=top_bg_color,font=("Ravie",14))
colon.place(x=time_xloc+3*step,y=time_yloc-5)

secondLabel = Label(root, text = nowSecond(),fg=top_fg_color,bg=top_bg_color,font=("Ravie",10))
secondLabel.place(x=time_xloc+4*step,y=time_yloc)
second_label(secondLabel)
#End Time

#Date
yearLabel = Label(root,text=nowYear(),fg=top_fg_color,bg=top_bg_color,font=("Ravie", 10))
yearLabel.place(x=date_xloc,y=date_yloc)
year_label(yearLabel)

colon = Label(root, text = "/",fg=top_fg_color,bg=top_bg_color)
colon.place(x=date_xloc+36,y=date_yloc)

monthLabel = Label(root,text=nowMonth(),fg=top_fg_color,bg=top_bg_color,font=("Ravie", 10))
monthLabel.place(x=date_xloc+45,y=date_yloc)
month_label(monthLabel)

colon = Label(root, text = "/",fg=top_fg_color,bg=top_bg_color)
colon.place(x=date_xloc+60,y=date_yloc)

dayLabel = Label(root,text=nowDay(),fg=top_fg_color,bg=top_bg_color,font=("Ravie", 10))
dayLabel.place(x=date_xloc+68,y=date_yloc)
day_label(dayLabel)
#End Date

#Temp
temp_label = Label(root,text="Temp: ",fg=top_fg_color,bg=top_bg_color,font=("Ravie", 10))
temp_label.place(x=date_xloc,y=date_yloc+20)
#End Temp
#End Header

#Body
sensors = ['Sensor 1:','Sensor 2:','Sensor 3:','Sensor 4:']
relays = ['Relay 1','Relay 2','Relay 3','Relay 4']
r=0
for c in sensors:
    Label(root,text=c,fg=top_bg_color,bg=color,width=0).place(x=table_x,y=table_y+r*stepx)
    r=r+1
r=0
for c in relays:
    Label(root,text=c,fg=top_bg_color,bg=color,width=0).place(x=table_x+300,y=table_y+r*stepx)
    r=r+1
#Sensors Display
global sen1
sen1 = Label(root,fg=top_bg_color,bg=color)
sen1.place(x= table_x+130,y=table_y)
sensor1_read(sen1)
#End Sensors Display

#Relay control
Radiobutton(root,text="OFF",variable=v1,command=relay1,value=1).place(x= table_x+400,y=table_y)
Radiobutton(root,text="ON",variable=v1,command=relay1,value=0).place(x= table_x+500,y=table_y)

Radiobutton(root,text="OFF",variable=v2,command=relay2,value=1).place(x= table_x+400,y=table_y+stepx)
Radiobutton(root,text="ON",variable=v2,command=relay2,value=0).place(x= table_x+500,y=table_y+stepx)

Radiobutton(root,text="OFF",variable=v3,command=relay3,value=1).place(x= table_x+400,y=table_y+2*stepx)
Radiobutton(root,text="ON",variable=v3,command=relay3,value=0).place(x= table_x+500,y=table_y+2*stepx)

Radiobutton(root,text="OFF",variable=v4,command=relay4,value=1).place(x= table_x+400,y=table_y+3*stepx)
Radiobutton(root,text="ON",variable=v4,command=relay4,value=0).place(x= table_x+500,y=table_y+3*stepx)

#End Relay control

Label(root,text="Sampling rate:",fg=top_bg_color,bg=color,width=0).place(x=table_x+50,y=350)
global sr_label
sr_label = Label(root,fg=top_bg_color,bg=color)
sr_label.place(x=table_x+150,y=350)
#sr_read(sr_label)
Label(root,text="Sec.",fg=top_bg_color,bg=color,width=0).place(x=table_x+230,y=351)

Button(root,text="Setting",command=pass_check).place(x=700,y=410)
Button(root,text="Send Data",command=send_data).place(x=200,y=410)

#End Body

root.mainloop()


from plugin_format import PluginFormat

class PlugIn(object):
    def __init__(self, name, version, plugin_format, file_path):
        self.name = name
        self.version = version
        self.plugin_format = plugin_format
        self.file_path = file_path

    def __str__(self):
        name = f"name={self.name}"
        version = f"version={self.version}"
        plugin_format = f"plugin_format={self.plugin_format}"
        file_path = f"file_path={self.file_path}"
        return f"Plugin[{name}, {version}, {plugin_format}, {file_path}]"

    @staticmethod
    def from_path(read_file):
        def first_existing_key(keys, file):
            if len(keys) == 0:
                return None
            elif len(keys) == 1 or keys[0] in file:
                return file[keys[0]]
            else:
                return first_existing_key(keys[1:], file)

        def wrapper(path_to_plugin):

            plist_file = read_file(path_to_plugin)

            if plist_file is None:
                return None

            plugin_format = PluginFormat.from_path(path_to_plugin)

            name = first_existing_key(["CFBundleName", "CFBundleExecutable"], plist_file)
            version = first_existing_key(["CFBundleShortVersionString", "CFBundleVersion"], plist_file)

            return PlugIn(name=name, version=version, plugin_format=plugin_format, file_path=path_to_plugin)

        return wrapper


import bpy
import re

def get_group_name_from_data_path(data_path):
    m = re.match(r'^pose\.bones\[\"([^\"]+)"\]', data_path)
    if m:
        return m[1]

    # For pose blender. Should probably not be hardcoded
    m = re.match(r'^\[\"([^\"]+)"\]$', data_path)
    if m and m[1].endswith("_pose"):
        return "Poses"

    return None

class GRET_OT_channels_auto_group(bpy.types.Operator):
    """Group animation channels by their bone name"""

    bl_idname = 'gret.channels_auto_group'
    bl_label = "Auto-Group Channels"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.space_data and context.space_data.type in {'DOPESHEET_EDITOR', 'GRAPH_EDITOR'}

    def execute(self, context):
        obj = context.active_object
        action = obj.animation_data.action if (obj and obj.animation_data) else None
        if not action:
            return {'CANCELLED'}

        fcurves = []

        # Create the necessary groups first THEN assign them to prevent the following error
        # https://github.com/blender/blender/blob/v3.4.1/source/blender/makesrna/intern/rna_fcurve.c#L527
        for fc in action.fcurves:
            group_name = get_group_name_from_data_path(fc.data_path)
            if group_name and (not fc.group or fc.group.name != group_name):
                fcurves.append((fc, group_name))
                if group_name not in action.groups:
                    action.groups.new(name=group_name)

        for fc, group_name in fcurves:
            old_group, fc.group = fc.group, action.groups.get(group_name)
            if fc.group:
                fc.group.show_expanded = True
                fc.group.show_expanded_graph = True
            if old_group and not old_group.channels:
                action.groups.remove(old_group)

        return {'FINISHED'}

def draw_menu(self, context):
    self.layout.operator(GRET_OT_channels_auto_group.bl_idname)

def register(settings, prefs):
    if not prefs.animation__enable_channels_auto_group:
        return False

    # Would be nice to have this menu item next to the other group operators
    bpy.utils.register_class(GRET_OT_channels_auto_group)
    bpy.types.GRAPH_MT_channel.append(draw_menu)
    bpy.types.DOPESHEET_MT_channel.append(draw_menu)

def unregister():
    bpy.types.GRAPH_MT_channel.remove(draw_menu)
    bpy.types.DOPESHEET_MT_channel.remove(draw_menu)
    bpy.utils.unregister_class(GRET_OT_channels_auto_group)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
To read sequentially the data from the hard disk, the data format is convert to TFRecord.
"""

import re
from pathlib import Path

import pandas as pd
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from sklearn.utils import shuffle

__date__ = '2021/04/06'

def load_data(npy_path, csv_path):
    images = np.load(npy_path)
    df = pd.read_csv(csv_path, index_col=None, header=0)

    d = {'artifact': 0, 'galx_artificial_real': 1, 'rand_artificial_real': 1}
    labels = df['object_type'].map(d).values

    return images, labels

def _bytes_feature(value):
    """Returns byte_list type from string / byte type."""
    if isinstance(value, type(tf.constant(0))):
        # BytesList won't unpack a string from an EagerTensor.
        value = value.numpy()
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))

def _float_feature(value):
    """Returns float_list type from float / double type."""
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))

def _int64_feature(value):
    """Return Int64_list type from bool / enum / int / uint type."""
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))

def make_example(image, label, detector_id, sample_index, unique_index):
    """Convert data formats."""
    feature = {
        'image': _float_feature(image.reshape(-1)),
        'label': _int64_feature([label]),
        'detector_id': _int64_feature([detector_id]),
        'sample_index': _int64_feature([sample_index]),
        'unique_index': _int64_feature([unique_index])
    }
    return tf.train.Example(features=tf.train.Features(feature=feature))

def main():
    data_dir = Path('../../data/raw/real_bogus1')
    npy_list = list(data_dir.glob('images*.npy'))
    npy_list.sort()

    output_dir = Path('../../data/processed/real_bogus1')
    if not output_dir.exists():
        output_dir.mkdir(parents=True)

    r = re.compile(r'images(\d+)')
    unique_id = 0
    # Size and start of unique index for each detector.
    data_info = {'detector_id': [], 'size': [], 'start_index': []}
    for npy_path in npy_list:
        m = r.search(npy_path.stem)
        detector_id = int(m.group(1))

        csv_path = data_dir / 'params{}.csv'.format(detector_id)

        images, labels = load_data(npy_path=npy_path, csv_path=csv_path)
        n = len(images)
        indices = np.arange(n)
        # Unique index across the entire data set.
        unique_indices = indices + unique_id

        data_info['detector_id'].append(detector_id)
        data_info['size'].append(n)
        data_info['start_index'].append(unique_id)

        unique_id += n

        images, labels, indices, unique_indices = shuffle(
            images, labels, indices, unique_indices
        )

        # Write TFRecord.
        record_path = str(output_dir / 'data{}.tfrecord'.format(detector_id))
        with tf.io.TFRecordWriter(
                record_path,
                tf.io.TFRecordOptions(compression_type='GZIP')) as writer:
            for image, label, index, unique_index in zip(
                    tqdm(images, desc=str(detector_id)), labels, indices,
                    unique_indices):
                example = make_example(
                    image=image, label=label, detector_id=detector_id,
                    sample_index=index, unique_index=unique_index
                )
                writer.write(example.SerializeToString())

    # Save the information of each file.
    df = pd.DataFrame(data_info)
    df.to_csv(output_dir / 'data_info.csv')

if __name__ == '__main__':
    main()


"""
文件名: Code/Chapter07/C02_RNNImgCla/FashionMNISTRNN.py
创建时间: 2023/4/27 8:08 下午
作 者: @空字符
公众号: @月来客栈
知 乎: @月来客栈 https://www.zhihu.com/people/the_lastest
"""

import torch
import torch.nn as nn
import sys

sys.path.append('../../')
from Chapter06.C04_LN.layer_normalization import LayerNormalization

class FashionMNISTRNN(nn.Module):
    def __init__(self, input_size=28, hidden_size=128,
                 num_layers=2, num_classes=10):
        super(FashionMNISTRNN, self).__init__()
        self.rnn = nn.RNN(input_size, hidden_size,nonlinearity='relu',
                          num_layers=num_layers, batch_first=True)
        self.classifier = nn.Sequential(LayerNormalization(hidden_size),
                                        nn.Linear(hidden_size, hidden_size),
                                        nn.ReLU(inplace=True),
                                        nn.Linear(hidden_size, num_classes))

    def forward(self, x, labels=None):
        x = x.squeeze(1)  # [batch_size,1,28,28] --> [batch_size,28,28]
        x, _ = self.rnn(x)  # input: [batch_size, time_steps, input_size]
        # x: [batch_size, time_steps, hidden_size]
        logits = self.classifier(x[:, -1].squeeze(1))
        # 取最后一个时刻进行分类，[batch_size, 1,hidden_size]---squeeze-->[batch_size,hidden_size]
        # logits: [batch_size, hidden_size]
        if labels is not None:
            loss_fct = nn.CrossEntropyLoss(reduction='mean')
            loss = loss_fct(logits, labels)
            return loss, logits
        else:
            return logits

if __name__ == '__main__':
    model = FashionMNISTRNN()
    x = torch.rand([32, 1, 28, 28])
    y = model(x)
    print(y.shape)


import re
import sys

def part1():

	recepies = [3, 7]
	a_index, b_index = 0, 1

	in_data = 440231
	while len(recepies) < in_data + 10:

		s = recepies[a_index] + recepies[b_index]

		for l in str(s):
			recepies.append(int(l))

		recepies_len = len(recepies)
		a_index = (a_index + recepies[a_index] + 1) % recepies_len
		b_index = (b_index + recepies[b_index] + 1) % recepies_len

	return ''.join(map(str, recepies[in_data:in_data+10]))

def part2():
	recepies = [3, 7]
	a_index, b_index = 0, 1

	in_data = list(map(int, list('01245')))
	in_data = list(map(int, list('59414')))
	in_data = list(map(int, list('440231')))
	in_data_len = len(in_data)

	build_index = 0

	while True:

		s = recepies[a_index] + recepies[b_index]

		for l in str(s):
			l = int(l)
			recepies.append(int(l))
			if l == in_data[build_index]:
				build_index += 1
			else:
				build_index = 0

			if build_index >= in_data_len:
				print('FOUND!')
				return(len(recepies) - abs(in_data_len))

		recepies_len = len(recepies)
		a_index = (a_index + recepies[a_index] + 1) % recepies_len
		b_index = (b_index + recepies[b_index] + 1) % recepies_len

def main():
	print(part1())
	print(part2())

if __name__ == '__main__':
	main()