import tensorflow as tf
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimage

__author__ = 'assafarbelle'

class DataSets(object):
    """
    Wrapper to CSVSegReader for train, test, val
    """
    def __init__(self, filenames, base_folder='.', image_size=(64,64,1), num_threads=4,
                 capacity=5000, min_after_dequeue=1000, num_epochs=None):
        data = {}
        for file in filenames:
            data[file] = CSVSegReader([os.path.join(base_folder, "%s.csv" % file)], base_folder, image_size, num_threads, capacity, min_after_dequeue, num_epochs)

        self.data = data

class CSVSegReader(object):

    def __init__(self, filenames, base_folder='.', image_size=(64,64,1), num_threads=4,
                 capacity=10000, min_after_dequeue=1000, num_epochs=None):
        """
        CSVSegReader is a class that reads csv files containing paths to input image and segmentation image and outputs
        batchs of correspoding image inputs and segmentation inputs.
         The inputs to the class are:

            filenames: a list of csv files filename
            num_epochs: the number of epochs - how many times to go over the data
            image_size: a tuple containing the image size in Y and X dimensions
            num_threads: number of threads for prefetch
            capacity: capacity of the shuffle queue, the larger capacity results in better mixing
            min_after_dequeue: the minimum example in the queue after a dequeue op. ensures good mixing
        """
        self.reader = tf.TextLineReader()
        self.input_queue = tf.train.string_input_producer(filenames, num_epochs=num_epochs)
        self.image_size = image_size
        self.batch_size = None
        self.num_threads = num_threads
        self.capacity = capacity
        self.min_after_dequeue = min_after_dequeue
        self.base_folder = base_folder

    def _get_image(self):
        _, records = self.reader.read(self.input_queue)
        file_names = tf.decode_csv(records, [tf.constant([],tf.string), tf.constant([],tf.string)], field_delim=None, name=None)

        im_raw = tf.read_file(self.base_folder+file_names[0])
        seg_raw =tf.read_file(self.base_folder+file_names[1])
        image = tf.reshape(
                        tf.cast(tf.image.decode_png(
                                                    im_raw,
                                                    channels=1, dtype=tf.uint16),
                        tf.float32,), self.image_size, name='input_image')
        seg = tf.reshape(
                        tf.cast(tf.image.decode_png(
                                                    seg_raw,
                                                    channels=1, dtype=tf.uint8),
                        tf.float32,), self.image_size, name='input_seg')

        return image, seg

    def get_batch(self, batch_size=1):

        self.batch_size = batch_size

        image, seg = self._get_image()
        image_batch, seg_batch = tf.train.shuffle_batch([image, seg], batch_size=self.batch_size,
                                                        num_threads=self.num_threads,
                                                        capacity=self.capacity,
                                                        min_after_dequeue=self.min_after_dequeue)
        return image_batch, seg_batch

    def get_batch_no_shuffle(self, batch_size=1):

        self.batch_size = batch_size

        image, seg = self._get_image()
        image_batch, seg_batch = tf.train.batch([image, seg], batch_size=self.batch_size,
                                                num_threads=self.num_threads,
                                                capacity=self.capacity)
        # image_batch, seg_batch = tf.train.shuffle_batch([image, seg], batch_size=self.batch_size,
        #                                                 num_threads=self.num_threads,
        #                                                 capacity=self.capacity,
        #                                                 min_after_dequeue=self.min_after_dequeue)
        return image_batch, seg_batch


#!/usr/bin/env python3
import pandas as pd
import collections
import sys
from pathlib import Path
import argparse

parser = argparse.ArgumentParser(description='Get per user statistics')
parser.add_argument('-i','--ls', help='input file: output file from "spacesaver ls" command', required=True)
parser.add_argument('-p','--peruserbytes', help='output file: name of per user bytes output file', required=True)
parser.add_argument('-l','--largedups', help='output file: list of large duplicates per user', required=True)
parser.add_argument('-d','--dist', help='output file: age distribution of files owned by each user', required=True)
args = vars(parser.parse_args())

pd.set_option('display.max_columns', None)  # or 1000
pd.set_option('display.max_rows', None)  # or 1000
pd.set_option('display.max_colwidth', None)  # or 199

#infile=sys.argv[1]
#infile="/data/CCBR/dev/spacesavers/logs/all_lss.tsv"
#outfile="bytes_per_user.v2.tsv"
infile=args['ls']
outfile=args['peruserbytes']
large_dup_path=args['largedups']
outfile2=args['dist']

# read the file
# file columns
# 0=inode, 1=permissions, 2=owner,
# 3=group, 4=bytes, 5=size, 6=mdate, 7=age,
# 8=file, 9=nduplicates, 10=bduplicates,
# 11=sduplicates, 12=downers, 13=duplicates
x=pd.read_csv(infile,header=0,delimiter="\t",low_memory=False)
x=x.fillna(0)
x=x[x['Bytes']>0]
x=x.reset_index()

large_dup_cutoff=100*1024*1024
# print(x['BDuplicates'])
large_dup=x[x['BDuplicates']>large_dup_cutoff]
filepath = Path(large_dup_path)
filepath.parent.mkdir(parents=True, exist_ok=True)
large_dup.to_csv(filepath,sep="\t",header=True,index=False)

tbites=dict()
dbites=dict()
age_distribution_count=dict()
age_distribution_bites=dict()

users=x.Owner.unique()

for u in users:
    tbites[u]=0
    dbites[u]=0
    age_distribution_count[u]=dict()
    age_distribution_bites[u]=dict()

for i,row in x.iterrows():
    bites=int(row['Bytes'])
    dupbites=int(row['BDuplicates'])
    age=str(row['Age'])
    user=row['Owner']
    # print(row['DOwners'])
    if dupbites!=0:
        downers=collections.Counter(row['DOwners'].split("|"))
        allusers = set(users) | set(downers.keys())
        newusers = allusers - set(users)
        for u in newusers:
            tbites[u]=0
            dbites[u]=0
            age_distribution_count[u]=dict()
            age_distribution_bites[u]=dict()
        users = list(allusers)
    # if not user in age_distribution_count:
    #     continue
    try:
        age_distribution_count[user][age]+=1
        age_distribution_bites[user][age]+=bites
    except KeyError:
        age_distribution_count[user][age]=1
        age_distribution_bites[user][age]=bites

    # try:
    #     tbites[user] += bites
    # except KeyError:
    #     continue
    tbites[user] += bites
    if dupbites==0:
        continue

    for k,v in downers.items():
        dupbites_per_user = bites * v
        dbites[k] += dupbites_per_user
        tbites[k] += dupbites_per_user
        try:
            age_distribution_count[k][age] += v
            age_distribution_bites[k][age] += dupbites_per_user
        except KeyError:
            age_distribution_count[k][age] = v
            age_distribution_bites[k][age] = dupbites_per_user

        # try:
        #     dbites[k] += bites * v
        #     age_distribution_count[k] += v
        # except KeyError:
        #     continue
        # try:
        #     tbites[k] += bites * v
        # except KeyError:
        #     continue

o2=open(outfile2,'w')
o2.write("%s\t%s\t%s\t%s\n"%("Username","Age","Count","Bytes"))

for u in age_distribution_count.keys():
    ages = age_distribution_count[u]
    ages_list = [int(a) for a in ages.keys()]
    # print(u,ages_list)
    maxage = max(ages_list)+1
    for a in range(0,maxage):
        stra = str(a)
        if stra in ages:
            o2.write("%s\t%s\t%s\t%s\n"%(u,stra,age_distribution_count[u][stra],age_distribution_bites[u][stra]))
        else:
            o2.write("%s\t%s\t0\t0\n"%(u,stra))
o2.close()

o=open(outfile,'w')
o.write("%s\t%s\t%s\n"%("User","Total_Bytes","Duplicate_Bytes"))
tbites = collections.OrderedDict(sorted(tbites.items(),key=lambda item:item[1]))
for u,b in tbites.items():
    tb=b
    db=dbites[u]
    o.write("%s\t%d\t%d\n"%(u,tb,db))
o.close()


"""
compare computing times and make sure output is identical
"""

from cltoolkit import Wordlist
from pacs.colexifications import (
        affix_colexifications,
        affix_colexifications_by_pairwise_comparison
        )
from pycldf import Dataset
from pyclts import CLTS
from lexibank_allenbai import Dataset as AllenBai

import timeit
from tabulate import tabulate
import functools

wl = Wordlist([Dataset.from_metadata(AllenBai().cldf_dir.joinpath("cldf-metadata.json"))],
              ts=CLTS().bipa)

digraphA = affix_colexifications(wl)
digraphB = affix_colexifications_by_pairwise_comparison(wl)

diffs = []
for nA, nB, data in digraphA.edges(data=True):
    countA = data["count"]
    try:
        countB = digraphB[nA][nB]["count"]
        source_a, target_a = " / ".join(data["source_forms"]), " / ".join(data["target_forms"])
        source_b, target_b = " / ".join(digraphB[nA][nB]["source_forms"]), " / ".join(digraphB[nA][nB]["target_forms"])
    except:
        countB = 0
        source_a, target_a = " / ".join(data["source_forms"]), " / ".join(data["target_forms"])
        source_b, target_b = "", ""
    if countA != countB:
        diffs += [(nA, nB, countA, countB, source_a, target_a, source_b, target_b)]

if diffs:
    print(tabulate(diffs))
else:
    print("[i] no differences found for the fast and the slow computation of partial colexifications")

def colex(fun):
    fun(wl)

t_a = timeit.Timer(functools.partial(colex, affix_colexifications))
t_b = timeit.Timer(functools.partial(colex, affix_colexifications_by_pairwise_comparison))

t1 = t_a.timeit(10)
t2 = t_b.timeit(10)
print("Affix Colexification Fast: {0:.2f}".format(t1))
print("Affix Colexification Slow: {0:.2f}".format(t2))


import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib import path
import scipy.interpolate as scinterp
from scipy import fftpack
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import os #basic
import PIL #python imaging library
from PIL import Image
import pandas as pd
from skimage import data, img_as_float #converts image to floating point - will alter intensity values.
from skimage import exposure
import seaborn as sns; sns.set()
from skimage import io
from skimage import transform, measure
from skimage.measure import regionprops, regionprops_table, label
from skimage import exposure
from skimage.filters import try_all_threshold, threshold_otsu, threshold_yen, threshold_triangle
from skimage import morphology
from scipy import ndimage as ndi
from skimage.segmentation import chan_vese, felzenszwalb, slic, quickshift, watershed,mark_boundaries
from matplotlib import cm
from matplotlib import interactive
import xlsxwriter
from natsort import natsorted
import math
from matplotlib.font_manager import FontProperties

###############################################
# #function for finding contours and give back the correct ones
def getContours(gfp_outline):
   #get contours
    ret,thresh = cv2.threshold(gfp_outline,127,255,cv2.THRESH_OTSU)             #parameters can be changed to suit the dataset
    closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE,np.ones((10,10),np.uint8))
    contours, hierarchy = cv2.findContours(closing,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    outcon = []
    #find all contours from outline image and filter for the proper ones
    for i in range(0,len(contours)):
        area = cv2.contourArea(contours[i])
        if hierarchy[0,i,3] == -1 and area > 10000:
            outcon.append(contours[i])
    return outcon

# ###############################################
# #function for getting center of contour
def getCenter(contour):
    M = cv2.moments(contour)                       #cv2.moments returns key pixel "moments" = m values.
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])                  #centriod calc using m values
    return [cX, cY]

################################################function for detecting particles
#function to return contours from the image
def detectParticles(img, img_crop, nperc):
    perc = 0.01              #perc variable, n perc is number of sampling i.e. 50% = 0.5. perc is how smooth
    imr,imc = img.shape      #find image shape
    #interpolate 3d image
    zim = img.copy()
    r,c = zim.shape
    x = np.zeros_like(zim)
    y = np.zeros_like(zim)
    for i in range(0,r):
        y[i,:] = i
    for i in range(0,c):
        x[:,i] = i
    nskip = int(imr*imc*nperc)      #use percentage of image
    xsparse = x.flatten()[::nskip]  #flatten to an array so only include sampled pixels
    ysparse = y.flatten()[::nskip]
    print('length of sparse:',len(xsparse))
    xnew = x
    ynew = y

    zsparse = zim.flatten()[::nskip]
    ######Radial basis function interpolation
    rbf = scinterp.Rbf(xsparse,ysparse,zsparse,epsilon=(perc*imr+perc*imc)/2,smooth=(perc*imr+perc*imc)/2)  #scipi package interpolates 2d surface
    zinterp = rbf(xnew,ynew)    #interpolated z values i.e. intensities

    #process image for blob detection
    img2 = zim-zinterp  #this should remove background depending on the rbf variables
    img2[img2<0] = 0    #make negative values = 0
    # img2 += np.abs(np.amin(img2))
    # img2 *= 255./np.amax(img2)

    #image fft filtering
    imfft = fftpack.fft2(img2)  #high frequency band pass filter ... remove high freq i.e. remove high repeating patterns i.e. backgroundy things

    #keep only fraction of coefficients
    keep_frac = 0.2
    imfft2 = imfft.copy()
    [row,col] = imfft2.shape

    #high frequency cut out
    imfft2[int(row*keep_frac):int(row*(1-keep_frac)),:] = 0
    imfft2[:,int(col*keep_frac):int(col*(1-keep_frac))] = 0

    #inverse fft to remake image
    im_ifft = fftpack.ifft2(imfft2).real
    im_ifft[im_ifft<0] = 0

    #contour detection on fft of image
    imfftth = im_ifft.copy()
    imfftth = img_crop*imfftth*(255.0/np.amax(img_crop*imfftth))
    contoursfft = measure.find_contours(imfftth,np.mean(imfftth)+np.std(imfftth))   #use inverse fft to find contours
    img2 = np.array(img2)
    return img2,rbf,contoursfft

###############################################MAIN
#upload file paths
path = './'                     #File path where your images are
outpath = path+'Output/'
isExist = os.path.exists(outpath)                                   #File path where you want the output to go
if not isExist:
    os.mkdir(outpath)
files = os.listdir(path)

###############################################################################################################################
#  Upload images for analysis. File naming is key. Create excel spreadsheets for output.
gfp_paths = []
gol_paths = []
myc_paths = []
combined_paths = []
for names in files:
    if names.endswith("_GFP100ms.tif"):
        gfp_paths.append(names)
    if names.endswith("GM130.tif"):
        gol_paths.append(names)
    if names.endswith("_Mask100ms.tif"):
        myc_paths.append(names)
    if names.startswith("Composite_"):
        combined_paths.append(names)

gfp_paths = natsorted(gfp_paths)
gol_paths = natsorted(gol_paths)
myc_paths = natsorted(myc_paths)
combined_paths = natsorted(combined_paths)

#create a result file
with open(path+'data_golgi.csv','w') as file:
    file.write('label, intens, y1, x1, Ai, r, cellnum,exptype\n')
file.close()

###############################################################################################################################
#import images using file paths
cellcount = 0
for pcount in tqdm(range(0,len(gfp_paths))):                  #upload images to code
    gfp = cv2.imread('./'+gfp_paths[pcount],-1)
    gfp_outline = cv2.imread('./'+myc_paths[pcount],0)
    gol = cv2.imread('./'+gol_paths[pcount],-1)
    combine_original = cv2.imread('./'+combined_paths[pcount],-1)

###############################################################################################################################
    outcon =getContours(gfp_outline)                               #call cell segmentation function and retrieve cell outlines

###############################################################################################################################
    #cycle through each contour
    for i in range(0,len(outcon)):
        oneoutline = np.zeros_like(gfp_outline)                     #return array with same shape as gfp_outline, this is empty
        cv2.fillPoly(oneoutline, pts =[outcon[i]], color=(1))       #fills the array with the cell shape.
        [cc,cr] = getCenter(outcon[i])                              #defined function above returns centriod
        (x,y),maxradius = cv2.minEnclosingCircle(outcon[i])         #makes a circle which contains the cell mask
        c,r,w,h = cv2.boundingRect(outcon[i])                       #return x,y = top left coordinate and w,h = width and height
        ccreal = cc
        crreal = cr
        cc = cc - c
        cr = cr - r
        combine = np.copy(combine_original)                          #create a copy of image so original is not destroyed.
        imagetoshow = cv2.drawContours(combine, [outcon[i]], 0, (0,255,0), 3)

##########################################################################################################################################
        # #1st check point
        # plt.figure(figsize=(15,8))
        # plt.title(pcount)
        # plt.imshow(imagetoshow)
        # plt.show()

    #once happy with cell segmentation, continue to the following stage for intracellular structure segmentation
###############################################################################################################################
        gol_temp = gol[r:r+h,c:c+w]
        gfp_temp = gfp[r:r+h,c:c+w]
        oneoutline = oneoutline[r:r+h,c:c+w]                        #create golgi copy and crop to cell outline
        seggolpic = oneoutline*gol_temp*(255.0/np.amax(oneoutline*gol_temp))

##########################################################################################################################################
# #the following section detects and segments structures within the cell.
        img2,rbf,golcontours = detectParticles(gol_temp, oneoutline, 0.01) #optimised

        # plt.figure(figsize=(15,8))
        # plt.imshow(gol_temp), plt.grid(False)
        # for b in golcontours:
        #     plt.plot(b[:,1],b[:,0],'b', alpha = 0.5, linewidth=1)
        # plt.show()

##########################################################################################################################################
        #take golgi contours and calculate desired features
        mask_golgi = np.zeros_like(seggolpic)
        for cnt in golcontours:
            c2in = []
            for icn in cnt:
                c2in.append([int(icn[1]),int(icn[0])])
            c2in = [np.array(c2in,dtype='int')]
            cv2.fillPoly(mask_golgi,c2in,color=(1))

        label_img = label(mask_golgi)
        regions = regionprops(label_img, intensity_image = seggolpic)
        centroids_x = []
        centroids_y = []
        x_val_area = []
        y_val_area = []
        area = []
        intensity = []
        blob = []

        fig, axs = plt.subplots(1, 3, figsize=(15,8))
        axs[0].imshow(imagetoshow), axs[0].grid(False), axs[0].set_title("Image_"+str(pcount)+"_Cell_"+str(i)), axs[0].axis('off')
        axs[1].imshow(gol_temp), axs[1].grid(False), axs[1].set_title('Golgi'), axs[1].axis('off')
        axs[1].plot(golcontours[0][:,1],golcontours[0][:,0],'b', linewidth=1, label= ('Golgi Particles'))
        for b in golcontours:
            axs[1].plot(b[:,1],b[:,0],'b',linewidth=1)
        fontP = FontProperties()
        fontP.set_size('x-small')
        axs[1].legend(bbox_to_anchor=(0.5,-0.01), loc='upper center',prop=fontP)
        axs[2].grid(False), axs[2].imshow(mask_golgi), axs[2].set_title('Golgi Mask with Contours + Centroids'), axs[2].axis('off')

        for props in regions:
            blob.append(props.label)
            y1, x1 = props.weighted_centroid
            centroids_x.append(x1)
            centroids_y.append(y1)
            intens = props.mean_intensity
            intensity.append(intens)
            Ai = props.area
            area.append(Ai)
            #calc distance
            x_val_area.append(x1*Ai)
            y_val_area.append(y1*Ai)
        overall_xval_area = np.sum(np.array(x_val_area))
        overall_yval_area = np.sum(np.array(y_val_area))
        overall_area = np.sum(np.array(area))

        weighted_x = overall_xval_area/overall_area
        weighted_y = overall_yval_area/overall_area

        with open("data_golgi.csv",'a') as f:
            for a in range(len(centroids_x)):
                intense = int(intensity[a])
                y1 = int(centroids_y[a])
                x1 = int(centroids_x[a])
                Ai = int(area[a])
                name = int(blob[a])
                p = math.sqrt((weighted_x - centroids_x[a])**2+(weighted_y - centroids_y[a])**2)
                r = p/(2*maxradius)
                f.write(str(name)+","+str(intense)+","+str(y1)+","+str(x1)+","+str(Ai)+","+str(r)+","+str(cellcount)+","+"\n")
        cellcount+=1

        axs[2].plot(np.asarray(centroids_x), np.asarray(centroids_y), '.g', markersize= 4, label = ('Particle, Intensity-Weighted Centroids'))
        axs[2].plot(weighted_x, weighted_y, '*r', markersize = 10, label = 'Area Weighted Centroid') #area weighted centroid, might want to also weight by intensity
        axs[2].legend(bbox_to_anchor=(0.5,-0.01), loc='upper center',prop=fontP)
        plt.savefig(outpath+"I092_Golgi_Image"+str(pcount)+"_"+str(i)+".png",dpi=300)
        plt.close()
        # plt.show()
        # print(pcount)


#allows storing values in key value pairs
#whenever we want to access a particular information, we use a key to access it.
#word is the key
#definition is the value
#symbols used are {}
#keys can be numbers, letters as long as they are unique and one cannot repeat keys

#for example: Jan--> January

#give dictionary name and values
monthConversions = {
    "Jan": "January",
    "Feb": "February",
    "Mar": "March",
    "Apr": "April",
    "May": "May",
    "Jun": "June",
    "Jul": "July",
    "Aug": "August",
    "Sept": "September",
    "Oct": "October",
    "Nov": "November",
    "Dec": "December"
}

#accessing a specific key or value
#access dictionary
print(monthConversions["Mar"])

#or
#this is appropriate in cases where value is not available. helps in creating default value
#print(name_of_dictionary.get("name_of_key", "message if key is not mapped to anything"))

print(monthConversions.get("mad","Not a valid key"))


import os.path
import argparse
from tkinter import filedialog
from duplicates import Duplicates
from cropBorder import CropBorder

parser = argparse.ArgumentParser(description='Provides several tools to manage folders of images')

availablePrograms = ['dupe', 'exactdupe', 'cropborder']
availableProgramsStr = ', '.join(availablePrograms)
parser.add_argument('program', type=str,
                    help=f'Specific tool you want to run (Default: dupe)\nAvailable programs: {availableProgramsStr}',
                    default='dupe')

parser.add_argument('path', type=str,
                    help='Path of an image folder to test (Default: . / the path you are currently in)',
                    default='.')

args = parser.parse_args()
if not os.path.exists(args.path):
    path = filedialog.askdirectory()
    if os.path.exists(path):
        raise Exception('Please specify a valid path')
else:
    path = args.path

if not args.program.lower() in availablePrograms:
    raise Exception(f'Please specify a correct program ({availableProgramsStr})')

#print(args)
parser.print_help()

if args.program.lower() == 'dupe':
    #images = Duplicates(path)
    pass
elif args.program.lower() == 'cropborder':
    CropBorder(path)


import sys
import cv2
from PyQt5.QtCore import QSize, Qt, QThread, pyqtSignal, pyqtSlot
import PyQt5.QtGui as QtGui
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QComboBox, QLabel
import main
import numpy as np

index = 0
availableCameras = []
while True:
    cap = cv2.VideoCapture(index)
    if not cap.read()[0]:
        break
    else:
        availableCameras.append(str(index))
    cap.release()
    index += 1

# Subclass QMainWindow to customize your application's main window
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("PerfectForm")
        self.setFixedSize(QSize(1024, 768))

        ### Buttons
        self.startButton = QPushButton("Start camera")
        self.startButton.clicked.connect(self.startButtonClicked)

        self.stopButton = QPushButton("Stop camera")
        self.stopButton.clicked.connect(self.stopButtonClicked)
        self.stopButton.setEnabled(False)
        ###

        ### Dropdowns
        self.modeBox = QComboBox()
        self.modeBox.setToolTip('Choose Exercise Mode')
        self.modeBox.addItems(['Squat'])
        self.modeBox.currentTextChanged.connect(self.modeSelected)

        self.cameraBox = QComboBox()
        self.cameraBox.setToolTip('Choose Camera (by index)')
        self.cameraBox.addItems(availableCameras)
        self.cameraBox.currentIndexChanged.connect(self.cameraSelected)
        ###

        # create the label that holds the image
        self.image_label = QLabel(self)
        self.image_label.resize(1024, 768)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.image_label)
        self.layout.addWidget(self.startButton)
        self.layout.addWidget(self.stopButton)
        self.layout.addWidget(self.cameraBox)
        self.layout.addWidget(self.modeBox)

        self.container = QWidget()
        self.container.setLayout(self.layout)

        # Set the central widget of the Window.
        self.setCentralWidget(self.container)

        # create the video capture thread
        #self.thread = main.VideoThread()

        # connect its signal to the update_image slot
        #self.thread.change_pixmap_signal.connect(self.update_image)

        # start the thread
        #self.thread.start()

    def closeEvent(self, event):
        self.thread.stopCam()
        event.accept()

    @pyqtSlot(np.ndarray)
    def update_image(self, cv_img):
        """Updates the image_label with a new opencv image"""
        qt_img = self.convert_cv_qt(cv_img)
        self.image_label.setPixmap(qt_img)

    def convert_cv_qt(self, cv_img):
        """Convert from an opencv image to QPixmap"""
        rgb_image = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb_image.shape
        bytes_per_line = ch * w
        convert_to_Qt_format = QtGui.QImage(rgb_image.data, w, h, bytes_per_line, QtGui.QImage.Format_RGB888)
        p = convert_to_Qt_format.scaled(1024, 768, Qt.KeepAspectRatio)
        return QPixmap.fromImage(p)

    def startButtonClicked(self):
        self.startButton.setEnabled(False)
        self.stopButton.setEnabled(True)
        self.cameraBox.setEnabled(False)

        # create the video capture thread
        self.thread = main.VideoThread(self.cameraBox.currentIndex())
        # connect its signal to the update_image slot
        self.thread.change_pixmap_signal.connect(self.update_image)
        self.thread.start()

    def stopButtonClicked(self):
        self.stopButton.setEnabled(False)
        self.startButton.setEnabled(True)
        self.cameraBox.setEnabled(True)
        self.thread.stopCam()

    def modeSelected(self, s):
        print(s)
        self.thread.setMode(s)

    def cameraSelected(self, i):
        print(i)
        #self.thread.setCamera(i)

app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()


import numpy as np
from numpy.core.records import array
from numpy.lib.function_base import append
import pandas as pd
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import cv2
import keras
from keras.models import Sequential
import sys
from urllib.parse import unquote
import json

strInput = ''
for word in sys.argv[1:]:
    strInput += word + ' '
a = unquote(strInput).replace("+", " ")
text = a

model_log = keras.models.load_model("model")

##############################################################
def convert_to_ascii(sentence):
 sentence_ascii=[]
 for i in sentence:
  if(ord(i)==8221): # ”  :  8221
   sentence_ascii.append(129)  # ü
  elif (ord(i)==8220): # “  :  8220
   sentence_ascii.append(130) # é
  elif(ord(i)==8216): # ‘  :  8216
   sentence_ascii.append(131) # â
  elif(ord(i)==8211): # –  :  8211
   sentence_ascii.append(132) # ä
  elif(ord(i)==8217): # ’  :  8217
   sentence_ascii.append(133) # à

  elif(len(sentence)==1):
   sentence_ascii.append(134) # å

  else:
   sentence_ascii.append(ord(i))
  #else:
  # pass

 zer=np.zeros((10000))

 for i in range(len(sentence_ascii)):
  zer[i]=sentence_ascii[i]

 zer.shape=(100, 100)
 return zer
################################################
def clean_sqli_data(data):
 d=data
 d= " ".join(d.split( ))
 if (d==''):
  d=' '
 return d
###############################################
a= clean_sqli_data(a)
image=convert_to_ascii(a)
x=np.asarray(image,dtype='float')
image =  cv2.resize(x, dsize=(100,100), interpolation=cv2.INTER_CUBIC)
image/=128
a=image
a= a.reshape(1,100,100,1)
p = model_log.predict(a)
pred=np.argmax(p)

if pred==0:
   pred="Normal"
elif pred==1:
   pred="XSS"
elif pred==2:
   pred="SQL"

# return json
xjson = {
  "text": text,
  "result": pred
}
yjson = json.dumps(xjson)
print(yjson)


from itertools import combinations

def dfs(x, y, d):
    stack = [(x, y, d)]

    while stack:
        x, y, d = stack.pop()
        nx = x + dx[d]
        ny = y + dy[d]

        if 0 <= nx < n and 0 <= ny < n:
            if data[nx][ny] == 'T':
                return False
            # 빈칸인 경우
            if data[nx][ny] == 'X':
                stack.append((nx, ny, d))   # 위치와 탐색방향 추가
    return True

def process():
    for x, y in student:
        for d in range(4):
            if not dfs(x, y, d):    # 이 학생은 막지 못함
                return False

    return True     # 모든 학생을 막음

n = int(input())
data = []
teacher = []
student = []

for i in range(n):
    data.append(input().split())
    for j in range(n):  # 선생님과 학생들의 좌표를 저장
        if data[i][j] == 'T':
            teacher.append((i, j))
        if data[i][j] == 'S':
            student.append((i, j))
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

seen = []
# 선생님의 시야에 있는 빈 칸만 뽑음
for i in range(len(teacher)):
    x, y = teacher[i]
    for j in range(n):
        if data[x][j] == 'X':
            seen.append((x, j))
        if data[j][y] == 'X':
            seen.append((j, y))

seen = list(set(seen))  # 중복 제거

# 시야에 있는 빈칸 중 3개를 뽑음
comb = list(combinations(seen, 3))

for i in range(len(comb)):
    for x, y in comb[i]:    # 벽 설치
            data[x][y] = 'O'

    if process():
        print("YES")
        break

    for x, y in comb[i]:    # 벽 제거
            data[x][y] = 'X'
else:
    print("NO")


def Step1(num , i):
    K1=0.05
    K2=0.05
    if (num == 1):
        HH=0
        LC=0
        HC=0
        LL=0
        if (i>=1):
            for j in range(1,2):
                HH = max(HH,data1['high'][j])
                HC = max(HC,data1['close'][j])
                LC = min(LC,data1['close'][j])
                LL = min(LL,data1['low'][j])
            rang=max((HH-LC),(HC-LL))
            Buyline = data1['open'][i]+K1*rang
            Sellline = data1['open'][i]-K2*rang
        else:
            Buyline = data1['high'][i-1]
            Sellline = data1['low'][i-1]*0.99
        min_ = 0
        if (i>=14):
            for j in range(2,15):
                min_ = min(min_,data1['low'][i-j])
        else: min_ = data1['low'][0]
        min_1 = 0
        if (i>=30):
            for j in range(0,14):
                min_1 = min(min_1,data1['low'][i-j])

        average = (data1['low'][i]+data1['high'][i]+data1['open'][i]+data1['close'][i])/4

        if ((wallet['gold'] == 0 )&( wallet['bitc'] == 0)):
            if (
                (min_1>min_)|
                (data1['close'][i] >= min_)|
                (data1['close'][i] >= Buyline) |
                (data1['close'][i] <average*0.98)
               ):

                money = wallet['USD']
                wallet['USD']=0
                wallet['bitc']=money*(1-0.02)/data1['open'][i]
            elif ((data1['open'][i] <= Sellline)):
                money = wallet['USD']
                wallet['USD']=0
                wallet['bitc']=money*(1-0.02)/data1['open'][i]
            return

        if (data1['close'][i-1]>data1['open'][i-1]):
            if (data1['close'][i] < Sellline):
                money = wallet['bitc']
                wallet['bitc']=0
                wallet['USD']=money * data1['open'][i] * 0.98
                return
        elif (data1['close'][i-1]<data1['open'][i-1]):
            if (data1['close'][i] > Buyline):
                money = wallet['bitc']
                wallet['bitc']=0
                wallet['USD']=money * data1['open'][i] * 0.98
                return
wallet = {'USD':1000 ,'gold': 0 , 'bitc': 0}
final = []

final.append(wallet['USD'])
print(wallet,'USD:' ,wallet['USD'])
for i in range(1,min(len(data1),len(data2))):
    if ((data1['close'][i]-data1['open'][i]<0)&(data2['close'][i]-data2['open'][i]<0)&(wallet['USD']!=0)):
        final.append(wallet['USD']+wallet['gold']*data2['open'][i]*1+wallet['bitc']*data1['open'][i]*0.98)
        print(wallet,'USD:' ,wallet['USD']+wallet['gold']*data2['open'][i]*1+wallet['bitc']*data1['open'][i]*0.98)
        continue
    if (wallet['bitc']!=0 & (wallet['USD']==0 & (data1['open'][i]>data1['open'][i-1]))):
        money = wallet['bitc']
        wallet['bitc']=0
        wallet['USD']=money * data1['open'][i] * 0.98
        final.append(wallet['USD']+wallet['gold']*data2['open'][i]*1+wallet['bitc']*data1['open'][i]*0.98)
        print(wallet,'USD:' ,wallet['USD']+wallet['gold']*data2['open'][i]*1+wallet['bitc']*data1['open'][i]*0.98)
        continue
    elif(wallet['gold']!=0 & (wallet['USD']==0 & (data2['open'][i]>data2['open'][i-1]))):
        money = wallet['gold']
        wallet['gold']=0
        wallet['USD']=money * data2['open'][i] * 0.99
        final.append(wallet['USD']+wallet['gold']*data2['open'][i]*1+wallet['bitc']*data1['open'][i]*0.98)
        print(wallet,'USD:' ,wallet['USD']+wallet['gold']*data2['open'][i]*1+wallet['bitc']*data1['open'][i]*0.98)
        continue
    if ((data1['close'][i]-data1['open'][i])/data1['close'][i] >= (data2['close'][i]-data2['open'][i])/data2['close'][i]):
        Step1(1,i)
    else :
        Step1(2,i)
    final.append(wallet['USD']+wallet['gold']*data2['open'][i]*1+wallet['bitc']*data1['open'][i]*0.98)
    print(wallet,'USD:' ,wallet['USD']+wallet['gold']*data2['open'][i]*1+wallet['bitc']*data1['open'][i]*0.98)


#Importing
import RPi.GPIO as GPIO
import time

class Bat:
    #initiate
    def __init__(self, PORT = [15, 16]):
        """__init__(self, PORT = [15, 16]), i setting up Ultrasonic reader on ports 15, 16"""
        self.Trigger_port = PORT[0]
        self.Echo_port = PORT[1]
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self.Trigger_port, GPIO.OUT)
        GPIO.setup(self.Echo_port, GPIO.IN)

    def distance(self):
        """distance(self), Returning a single reading """
        #Trigger Pulse
        GPIO.output(self.Trigger_port, True)
        time.sleep(0.00001)
        GPIO.output(self.Trigger_port, False)

        StartTime = time.time()
        StopTime = time.time()

        # save StartTime and watch for trigger error (0.1s timeout).
        while GPIO.input(self.Echo_port) == 0 and StopTime + 0.1 > StartTime:
            StartTime = time.time()
        # save time of arrival
        while GPIO.input(self.Echo_port) == 1:
            StopTime = time.time()

        # time difference between start and arrival
        TimeElapsed = StopTime - StartTime
        if TimeElapsed < 0:
            return False
        # multiply with the sonic speed (343 m/s)
        # and divide by 2, because there and back
        distance = (TimeElapsed * 343) / 2
        # if measurment is larger then 5.
        if distance > 5:
            return False
        return distance

    def measure(self, sample = 10, remove = 3):
        """ measure(self, sample = 10, remove = 3), method where "sample" samples are collected and the "remove" highest and lowest are deleted.
        return valu is the mean of the remaining samples"""
        Values = []
        while len(Values) < sample:
            Values.append(self.distance())
        Values.sort()
        Select = Values[remove:-remove]
        return sum(Select)/len(Select)

    def Test(self, Time = 10):
        Values = []
        StartTime = time.time()
        while time.time() < (StartTime + Time):
            Values.append(self.distance())
        return("%s measurements within %s seconds. Average rate  %s Hz" %(len(Values), Time, len(Values)/Time))

    def close(self):
        GPIO.cleanup([self.Trigger_port, self.Echo_port])
        print("GPIO.cleanup([%s, %s])" % (self.Trigger_port, self.Echo_port))


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="printplus",
    version="1",
    author="noidea",
    author_email="noidea1238@gmail.com",
    description="Simple package to print text to terminal with colors and alignment",
    long_description=long_description,
    long_description_content_type='text/markdown',
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)


# Crie uma função chamada maior_valor que aceite uma lista de números como parâmetro e retorne o maior valor da lista.

numeros = []

def maior_valor(numeros):
    maior = 0
    for n in numeros:
        if n > maior:
            maior = n
    return maior

while (1):
    x = int(input('Acrescente um número (0 para parar): '))
    if x == 0:
        break
    numeros.append(x)

print(f'Números: {numeros}')
print(f'Maior: {maior_valor(numeros)}')

Python/FATEC/2° Semestre - Linguagem de Programação/Funções - Exercicios/ex-04.py


import logging
import os

from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from api.route import v1_router, private_router
from api.middleware import HttpLog

def create_application() -> FastAPI:
    # create the FastAPI application
    logger = logging.getLogger("api")
    application = FastAPI(title="Message REST", version="1.0")

    # mount the router
    application.include_router(private_router)
    application.include_router(v1_router)

    # mount the middleware
    application.add_middleware(HttpLog)

    # hook up startup event
    @application.on_event("startup")
    async def startup_event() -> None:
        logger.info(f"Initialing database url ...")
        register_tortoise(
            app,
            db_url=os.getenv("DB_URL"),
            modules={"models": ["db.model"]},
        )
        logger.info("Database initialization done.")

    # hook up shutdown event
    @application.on_event("shutdown")
    async def shutdown_event() -> None:
        logger.info("Shutting down...")

    return application

app = create_application()


#! /usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
#
# Install a package and then make available a new version of the same package.
# Install this second version of the package by URI to the package file rather
# than by name. Ensure that the upgrade is performed properly.
#

import os
import opk, cfg, opkgcl

opk.regress_init()

o = opk.OpkGroup()

# Create a 1.0 containing file "test1" and install by name
f = open("test1", "w")
f.write("Test")
f.close()
pkg = opk.Opk(Package="a", Version="1.0")
pkg.write(data_files=["test1"])
o.addOpk(pkg)
o.write_list()
os.unlink("test1")

opkgcl.update()

opkgcl.install("a")
if not opkgcl.is_installed("a"):
    opk.fail("Package 'a' installed but reports as not installed.")
if not os.path.exists("%s/test1" % cfg.offline_root):
    opk.fail("Package 'a' installed but file 'test1' not created.")

# Create a 2.0 containing file "test2" and upgrade by URI
f = open("test2", "w")
f.write("Test")
f.close()
pkg = opk.Opk(Package="a", Version="2.0")
pkg.write(data_files=["test2"])
o.addOpk(pkg)
o.write_list()
os.unlink("test2")

opkgcl.install("a_2.0_all.opk")

if not opkgcl.is_installed("a", "2.0"):
    opk.fail("New version of package 'a' failed to install")
if opkgcl.is_installed("a", "1.0"):
    opk.fail("Package 'a' upgraded but old version still installed.")

if not os.path.exists("%s/test2" % cfg.offline_root):
    opk.fail("Package 'a' upgraded but new file 'test2' not created.")
if os.path.exists("%s/test1" % cfg.offline_root):
    opk.fail("Package 'a' upgraded but old file 'test1' not removed.")


#converts kilo to miles
import tkinter

class KiloConvertGUI:
    def __init__(self):
        self.main_window = tkinter.Tk()
        self.top_frame =tkinter.Frame()
        self.mid_frame = tkinter.Frame()
        self.bottom_frame = tkinter.Frame()

        self.prompt_label =tkinter.Label(self.top_frame,text='Enter a distance in kilometers: ')
        self.kilo_entry = tkinter.Entry(self.top_frame,width=10)
        self.prompt_label.pack(side='left')
        self.kilo_entry.pack(side='left')

        self.descr_label = tkinter.Label(self.mid_frame,text='Converted to miles:')
        self.value = tkinter.StringVar() #StringVar object associated w/ an output label
        self.miles_label = tkinter.Label(self.mid_frame, textvariable=self.value) #label associated w/ StringVar
        self.descr_label.pack(side='left')

        self.miles_label.pack(side='left')
        self.calc_button = tkinter.Button(self.bottom_frame,text='Convert',command=self.convert)
        self.quit_button = tkinter.Button(self.bottom_frame,text='Quit',command=self.main_window.destroy)
        self.calc_button.pack(side='left')
        self.quit_button.pack(side='left')

        self.top_frame.pack()
        self.mid_frame.pack()
        self.bottom_frame.pack()

        tkinter.mainloop()

    def convert(self):
        kilo = float(self.kilo_entry.get())
        miles = kilo *0.6214
        self.value.set(miles) #convert miles to a string and store it in the StringVar object

if __name__ == '__main__':
    kilo_conv = KiloConvertGUI()

Module 12/Class Exercise #11/exercise6.py


class TwoSum:

    def __init__(self):
        self._nums = []

    """
    @param number: An integer
    @return: nothing
    """
    def add(self, number):
        # write your code here
        import bisect
        insert_pos = bisect.bisect_left(self._nums, number)
        self._nums.insert(insert_pos, number)

    """
    @param value: An integer
    @return: Find if there exists any pair of numbers which sum is equal to the value.
    """
    def find(self, value):
        # write your code here
        start, end = 0, len(self._nums) - 1
        while start < end:
            if self._nums[start] + self._nums[end] == value:
                return True
            elif self._nums[start] + self._nums[end] > value:
                end -= 1
            else:
                start += 1
        return False


import requests

class SocialMediaAnalyzer:
    def __init__(self, api_key):
        self.api_key = api_key

    def analyze_user(self, username):
        url = f"https://api.socialmedia.com/v1/user/{username}/analysis"
        headers = {
            "Authorization": f"Bearer {self.api_key}"
        }
        response = requests.get(url, headers=headers)
        data = response.json()

        if response.status_code == 200:
            if "followers" in data:
                followers = data["followers"]
                following = data["following"]
                posts = data["posts"]

                print(f"Social Media Analysis for User: {username}")
                print(f"- Followers: {followers}")
                print(f"- Following: {following}")
                print(f"- Posts: {posts}")
            else:
                print(f"No social media analysis found for user: {username}.")
        else:
            print("Unable to retrieve social media analysis.")

def main():
    api_key = "YOUR_API_KEY"
    username = "example_user"

    analyzer = SocialMediaAnalyzer(api_key)
    analyzer.analyze_user(username)

if __name__ == "__main__":
    main()


from rest_framework import serializers
from lib import constants as const
from apps.post.models import Post, Comment

class CommentSerializer(serializers.ModelSerializer):
	id = serializers.UUIDField(source=const.COMMENT_ID_PROPERTY, read_only=True)

	class Meta:
		model = Comment
		fields = [
			const.ID_PROPERTY,
			const.DESCRIPTION_PROPERTY
		]

	def create(self, validatedData):
		post = Post.objects.get(postId=validatedData[const.POST_ID_PROPERTY])
		return Comment.objects.create(
			description=validatedData[const.DESCRIPTION_PROPERTY], post=post
		)


# coding: utf-8

"""
    IONOS Cloud - DNS API

    Cloud DNS service helps IONOS Cloud customers to automate DNS Zone and Record management.   # noqa: E501

    The version of the OpenAPI document: 1.12.0
    Contact: support@cloud.ionos.com
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from ionoscloud_dns.configuration import Configuration

class DnssecKey(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {

        'key_tag': 'int',

        'sign_algorithm_mnemonic': 'str',

        'sign_algorithm_number': 'int',

        'digest_algorithm_mnemonic': 'str',

        'digest_algorithm_number': 'int',

        'digest': 'str',

        'key_data': 'KeyData',

        'composed_key_data': 'str',
    }

    attribute_map = {

        'key_tag': 'keyTag',

        'sign_algorithm_mnemonic': 'signAlgorithmMnemonic',

        'sign_algorithm_number': 'signAlgorithmNumber',

        'digest_algorithm_mnemonic': 'digestAlgorithmMnemonic',

        'digest_algorithm_number': 'digestAlgorithmNumber',

        'digest': 'digest',

        'key_data': 'keyData',

        'composed_key_data': 'composedKeyData',
    }

    def __init__(self, key_tag=None, sign_algorithm_mnemonic=None, sign_algorithm_number=None, digest_algorithm_mnemonic=None, digest_algorithm_number=None, digest=None, key_data=None, composed_key_data=None, local_vars_configuration=None):  # noqa: E501
        """DnssecKey - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._key_tag = None
        self._sign_algorithm_mnemonic = None
        self._sign_algorithm_number = None
        self._digest_algorithm_mnemonic = None
        self._digest_algorithm_number = None
        self._digest = None
        self._key_data = None
        self._composed_key_data = None
        self.discriminator = None

        if key_tag is not None:
            self.key_tag = key_tag
        if sign_algorithm_mnemonic is not None:
            self.sign_algorithm_mnemonic = sign_algorithm_mnemonic
        if sign_algorithm_number is not None:
            self.sign_algorithm_number = sign_algorithm_number
        if digest_algorithm_mnemonic is not None:
            self.digest_algorithm_mnemonic = digest_algorithm_mnemonic
        if digest_algorithm_number is not None:
            self.digest_algorithm_number = digest_algorithm_number
        if digest is not None:
            self.digest = digest
        if key_data is not None:
            self.key_data = key_data
        if composed_key_data is not None:
            self.composed_key_data = composed_key_data

    @property
    def key_tag(self):
        """Gets the key_tag of this DnssecKey.  # noqa: E501

        :return: The key_tag of this DnssecKey.  # noqa: E501
        :rtype: int
        """
        return self._key_tag

    @key_tag.setter
    def key_tag(self, key_tag):
        """Sets the key_tag of this DnssecKey.

        :param key_tag: The key_tag of this DnssecKey.  # noqa: E501
        :type key_tag: int
        """

        self._key_tag = key_tag

    @property
    def sign_algorithm_mnemonic(self):
        """Gets the sign_algorithm_mnemonic of this DnssecKey.  # noqa: E501

        A string that denotes the signing algorithm. This value must conform to the guidelines in [RFC-8624 Section 3.1](https://datatracker.ietf.org/doc/html/rfc8624#section-3.1).   # noqa: E501

        :return: The sign_algorithm_mnemonic of this DnssecKey.  # noqa: E501
        :rtype: str
        """
        return self._sign_algorithm_mnemonic

    @sign_algorithm_mnemonic.setter
    def sign_algorithm_mnemonic(self, sign_algorithm_mnemonic):
        """Sets the sign_algorithm_mnemonic of this DnssecKey.

        A string that denotes the signing algorithm. This value must conform to the guidelines in [RFC-8624 Section 3.1](https://datatracker.ietf.org/doc/html/rfc8624#section-3.1).   # noqa: E501

        :param sign_algorithm_mnemonic: The sign_algorithm_mnemonic of this DnssecKey.  # noqa: E501
        :type sign_algorithm_mnemonic: str
        """

        self._sign_algorithm_mnemonic = sign_algorithm_mnemonic

    @property
    def sign_algorithm_number(self):
        """Gets the sign_algorithm_number of this DnssecKey.  # noqa: E501

        An integer that denotes the signing algorithm. This value must conform to the guidelines in [RFC-8624 Section 3.1](https://datatracker.ietf.org/doc/html/rfc8624#section-3.1).   # noqa: E501

        :return: The sign_algorithm_number of this DnssecKey.  # noqa: E501
        :rtype: int
        """
        return self._sign_algorithm_number

    @sign_algorithm_number.setter
    def sign_algorithm_number(self, sign_algorithm_number):
        """Sets the sign_algorithm_number of this DnssecKey.

        An integer that denotes the signing algorithm. This value must conform to the guidelines in [RFC-8624 Section 3.1](https://datatracker.ietf.org/doc/html/rfc8624#section-3.1).   # noqa: E501

        :param sign_algorithm_number: The sign_algorithm_number of this DnssecKey.  # noqa: E501
        :type sign_algorithm_number: int
        """

        self._sign_algorithm_number = sign_algorithm_number

    @property
    def digest_algorithm_mnemonic(self):
        """Gets the digest_algorithm_mnemonic of this DnssecKey.  # noqa: E501

        A string that denotes the digest algorithm. This value must conform to the guidelines in [RFC-8624 Section 3.3](https://datatracker.ietf.org/doc/html/rfc8624#section-3.3).   # noqa: E501

        :return: The digest_algorithm_mnemonic of this DnssecKey.  # noqa: E501
        :rtype: str
        """
        return self._digest_algorithm_mnemonic

    @digest_algorithm_mnemonic.setter
    def digest_algorithm_mnemonic(self, digest_algorithm_mnemonic):
        """Sets the digest_algorithm_mnemonic of this DnssecKey.

        A string that denotes the digest algorithm. This value must conform to the guidelines in [RFC-8624 Section 3.3](https://datatracker.ietf.org/doc/html/rfc8624#section-3.3).   # noqa: E501

        :param digest_algorithm_mnemonic: The digest_algorithm_mnemonic of this DnssecKey.  # noqa: E501
        :type digest_algorithm_mnemonic: str
        """

        self._digest_algorithm_mnemonic = digest_algorithm_mnemonic

    @property
    def digest_algorithm_number(self):
        """Gets the digest_algorithm_number of this DnssecKey.  # noqa: E501

        An integer that denotes the digest algorithm. This value must conform to the guidelines in [RFC-8624 Section 3.3](https://datatracker.ietf.org/doc/html/rfc8624#section-3.3).   # noqa: E501

        :return: The digest_algorithm_number of this DnssecKey.  # noqa: E501
        :rtype: int
        """
        return self._digest_algorithm_number

    @digest_algorithm_number.setter
    def digest_algorithm_number(self, digest_algorithm_number):
        """Sets the digest_algorithm_number of this DnssecKey.

        An integer that denotes the digest algorithm. This value must conform to the guidelines in [RFC-8624 Section 3.3](https://datatracker.ietf.org/doc/html/rfc8624#section-3.3).   # noqa: E501

        :param digest_algorithm_number: The digest_algorithm_number of this DnssecKey.  # noqa: E501
        :type digest_algorithm_number: int
        """

        self._digest_algorithm_number = digest_algorithm_number

    @property
    def digest(self):
        """Gets the digest of this DnssecKey.  # noqa: E501

        :return: The digest of this DnssecKey.  # noqa: E501
        :rtype: str
        """
        return self._digest

    @digest.setter
    def digest(self, digest):
        """Sets the digest of this DnssecKey.

        :param digest: The digest of this DnssecKey.  # noqa: E501
        :type digest: str
        """

        self._digest = digest

    @property
    def key_data(self):
        """Gets the key_data of this DnssecKey.  # noqa: E501

        :return: The key_data of this DnssecKey.  # noqa: E501
        :rtype: KeyData
        """
        return self._key_data

    @key_data.setter
    def key_data(self, key_data):
        """Sets the key_data of this DnssecKey.

        :param key_data: The key_data of this DnssecKey.  # noqa: E501
        :type key_data: KeyData
        """

        self._key_data = key_data

    @property
    def composed_key_data(self):
        """Gets the composed_key_data of this DnssecKey.  # noqa: E501

        Represents the composed value of the The RDATA for a DNSKEY. The format should be the following: Flags | Protocol | Algorithm | Public Key The values must conform to the guidelines in [RFC-4034 Section 2.1](https://www.rfc-editor.org/rfc/rfc4034#section-2.1).   # noqa: E501

        :return: The composed_key_data of this DnssecKey.  # noqa: E501
        :rtype: str
        """
        return self._composed_key_data

    @composed_key_data.setter
    def composed_key_data(self, composed_key_data):
        """Sets the composed_key_data of this DnssecKey.

        Represents the composed value of the The RDATA for a DNSKEY. The format should be the following: Flags | Protocol | Algorithm | Public Key The values must conform to the guidelines in [RFC-4034 Section 2.1](https://www.rfc-editor.org/rfc/rfc4034#section-2.1).   # noqa: E501

        :param composed_key_data: The composed_key_data of this DnssecKey.  # noqa: E501
        :type composed_key_data: str
        """

        self._composed_key_data = composed_key_data
    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, DnssecKey):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, DnssecKey):
            return True

        return self.to_dict() != other.to_dict()


import math
import os
import random
import re
import sys

# Complete the funnyString function below.
def funnyString(s):
    arr=[]
    for i in range(len(s)):
        arr.append(ord(s[i]))
    for j in range(len(s)):
        if j<len(s)-1:
            a= abs(arr[j]-arr[j+1])
            b= abs(arr[len(s)-1-j]-arr[len(s)-1-(j+1)])
            if a==b:
                flag=0
            else:
                flag=1
                break
        else:
            pass
    if flag==0:
        return "Funny"
    else:
        return "Not Funny"

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    q = int(raw_input())

    for q_itr in xrange(q):
        s =list(raw_input())

        result = funnyString(s)

        fptr.write(result + '\n')

    fptr.close()


import os
import random
import math
from user import User
from state import State
from model import *

'''
** FEEDBACK

Feedback will be a response from the company where you're working,
essentially a job_review, while will be a score out of 5, randomly
predicted. 5 being good, 1 being bad.

Affecs:
- Raise
- Firing
- Quality of Offers [Interesting Idea]

Affected By:
- Booming Sector
- Recession

** FIRING

Firing will be a probable event in each itertion, with the porbability
depending on the following:

Affects:
- Qualitiy of Offers Recieved

Affected by:
- How long you've worked at a place (Will decrease with increase)
- Sector Stability
- Recession
- Booming Sector

** RECESSION

A random event that will hit with a probability of 0.1+(0.09*state)
Recesssion will not hit a sector that has boomed recently.

Affected By:
- Sector_Stability
- Current_Sector
- Booming Sector

Affects:
Everything

'''

def company_bankrupt ():
    '''
    Affected By:
    - Sector Stability
    - Recession
    - Company Stability Score
    '''
    pass

def manage_job_quality() :
    if State.job_quality < 5 and State.fired_flag != 1:
        State.job_quality = 5
    return

def initiate_recession():
    os.system("tput reset")
    print ("Recession in: "+ get_sector(State.recession_sector))
    temp = input("Press Enter to see the jobs available right now.\n")
    State.sector_score[State.recession_sector]  = 1
    # initiate firing
    # remove possibe jobs
    return

def booming_sector () :
    all_sector = [0,1,2,3,4]
    if State.recession_flag == 1:
        all_sector.remove(State.recession_sector)
    State.current_booming.append(random.choice(all_sector))
    return

def sector_score_control ():
    State.sector_score [State.current_booming[-1]] += 20
    State.sector_score [State.current_booming[-2]] -= 20
    for i in range (0,5):
        temp = random.randint (0,40)
        State.sector_score[i]+=(temp - 20)
        if State.sector_score[i] < 0 :
            State.sector_score[i] = 0
        if State.sector_score[i] > 100 :
            State.sector_score[i] = 100
    return

def fire ():
    # Fire on '0'
    if (State.recession_flag == 1 and User.current_sector[-1] == State.recession_sector)\
     or feedback_array[State.state] == 0:
        State.job_quality -= 1
        State.fired_flag = 1
        os.system("tput reset")
        input ("fired")
    # Modify current job
    return

# def feedback_func ():
#     '''
#     21 arrays for 10 years
#     1 each for booming/non-booming
#     1 special for recession in current sector

#     A comparison of skill increase vs years at company

#     Affected by:
#     - Sector Score + (Booming Sector) + (Recession) 40%
#     - Choice Score 10%
#     - Skill Score 10%
#     # - Time You've Spent at the Company 30%
#     - Random 40%

#     Include Skillset

#     Will Affect:
#     - Job Quality
#     - Firing
#     '''

#     os.system ("tput reset")
#     print (current_feedback)
#     input ("Test for feedback")
#     return

    # Remove first element, check if this does that.

    # sector_v = sector_score[User.current_sector[-1]]/20
    # choice_v = (100-int(base_dataset[User.current_company[-1]][6]))/20
    # time_v = (6 - User.time_at_job)
    # random_v = (5 - random.randint(0,9))
    # skill_v = (User.skills[User.current_sector[-1]])/20
    # # feedback = 0.2*(sector_v+random_v)+0.3*(choice_v+time_v)
    # feedback.append(math.floor((0.40*(sector_v)\
    # +0.10*(choice_v)+0.40*(random_v)+0.1*(skill_v))*0.75+0.25*feedback[-1]))
    # if feedback[-1] < 0:
    #     feedback[-1] = 0
    # os.system("tput reset")
    # y =input (str(skill_v)+"\n"+str(User.skills)+"Skill Score:\n"+str(0.1*skill_v)+\
    # "\nSector Info:\n"+str(sector_score)+"\nSector: "+str(0.40*sector_v)+"\nChoice: "+str(0.10*choice_v)+\
    # "\nTime: "+str(time_v)+"\nRandom: "+str(0.40*random_v)+"\nFeedback: "+str(feedback))
    # return

def recession ():
    all_sector = [0,1,2,3,4]
    if len(User.current_sector) != 0:
        all_sector.remove(State.current_booming[-1])
        all_sector.append(User.current_sector[-1])
    State.recession_sector = random.choice(all_sector)
    recession_variable = random.randint(0,100)
    if recession_variable < State.recession_probability:
        State.recession_flag = 1
        initiate_recession()
    else:
        State.recession_probability+=9
        pass
    return

def generate_job_events ():
    if State.fired_flag == 1:
        State.fired_flag = 0
    # elif State.fired_flag == 2:
        # State.fired_flag = 0
    if State.recession_flag == 0:
        recession()
    booming_sector()
    sector_score_control()
    fire()
    manage_job_quality()
    return

def generate_placement_events():
    if State.recession_flag == 0:
        recession()
    booming_sector()
    sector_score_control()
    manage_job_quality()
    return


import os

class TravisEnvirExtractor():

    @staticmethod
    def get_travis_variables():

        env_variables = ["TRAVIS_BRANCH",
                         "TRAVIS_BUILD_NUMBER",
                         "TRAVIS_BUILD_WEB_URL",
                         "TRAVIS_COMMIT",
                         "TRAVIS_COMMIT_RANGE",
                         "TRAVIS_JOB_NAME",
                         "TRAVIS_JOB_NUMBER",
                         "TRAVIS_JOB_WEB_URL",
                         "TRAVIS_PULL_REQUEST",
                         "TRAVIS_BUILD_STAGE_NAME"]

        output_dict = {}

        for env_variable in env_variables:
            output_dict[env_variable] = os.environ.get(env_variable)

        return output_dict

if __name__ == "__main__":
    print(TravisEnvirExtractor.get_travis_variables())


import datetime
import folium
import glob
import gpxpy
import os
import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')

last_update_time = datetime.datetime.strptime('2020-08-02', '%Y-%m-%d')

script_dir = os.path.dirname(os.path.realpath(__file__))
data_dir = os.path.join(script_dir, 'data')
road_trips_dir = os.path.join(script_dir, 'road_trips')
gpx_files = glob.glob(os.path.join(data_dir, '*.gpx'))

# gpx_files = gpx_files[:10]

map = folium.Map(location=[37.518943, -122.138206], zoom_start=9)

gpx_files = sorted(glob.glob(os.path.join(road_trips_dir, '*', '*.gpx')))
# gpx_files = gpx_files[-1:]
for gpx_file in gpx_files:
    print(gpx_file)
    with open(gpx_file, 'r') as f:
        gpx = gpxpy.parse(f)
        data_points = gpx.tracks[0].segments[0].points
        points = [tuple([point.latitude, point.longitude]) for point in data_points]
        color = 'blue'
        if '2021' in gpx_file:
            color = 'red'
        folium.PolyLine(points, color=color, weight=3.0, opacity=1).add_to(map)

output_html_path = os.path.join(script_dir, 'road_trips.html')
map.save(output_html_path)

print('Done. Check the output html: {}'.format(output_html_path))


# 20. Задайте список. Напишите программу, которая определит,
# присутствует ли в заданном списке строк некое число.
n = int(input ("Введите искомое в строке число: "))
my_list = ["err567", "iu5", "rtu456t", "ffg567"]
length = len(my_list)
n = str(n)
Flag = False
for i in range (length):
    if my_list[i].find(n) != -1:
        Flag = True
        break
print (Flag)

lst = ['err567', 'iu5', 'rtu456t', 'ffg567']
num = int(input('Введите искомое в строке число: '))
count = 0
for elem in lst:
    if str(num) in elem:
        count += 1
if count > 0:
    print ("Да, такое число в строке есть")
else:
    print ("Указанное число в строке отсутствует")


from nutils import solver, mesh, function, cache, types, numeric
from . import *
import numpy, contextlib, tempfile

@contextlib.contextmanager
def tmpcache():
  with tempfile.TemporaryDirectory() as tmpdir:
    with cache.enable(tmpdir):
      yield

def _test_recursion_cache(testcase, solver_iter):
  read = lambda n: tuple(item for i, item in zip(range(n), solver_iter()))
  reference = read(5)
  for lengths in [1,2,3], [1,3,2], [0,3,5]:
    with tmpcache():
      for i, length in enumerate(lengths):
        with testcase.subTest(lengths=lengths, step=i):
          testcase.assertEqual(read(length), reference[:length])

class laplace(TestCase):

  def setUp(self):
    super().setUp()
    domain, geom = mesh.rectilinear([8,8])
    basis = domain.basis('std', degree=1)
    self.cons = domain.boundary['left'].project(0, onto=basis, geometry=geom, ischeme='gauss2')
    dofs = function.Argument('dofs', [len(basis)])
    u = basis.dot(dofs)
    self.residual = domain.integral((basis.grad(geom) * u.grad(geom)).sum(-1)*function.J(geom), degree=2) \
                  + domain.boundary['top'].integral(basis*function.J(geom), degree=2)

  def test_res(self):
    for name in 'direct', 'newton':
      with self.subTest(name):
        if name == 'direct':
          lhs = solver.solve_linear('dofs', residual=self.residual, constrain=self.cons)
        else:
          lhs = solver.newton('dofs', residual=self.residual, constrain=self.cons).solve(tol=1e-10, maxiter=0)
        res = self.residual.eval(arguments=dict(dofs=lhs))
        resnorm = numpy.linalg.norm(res[~self.cons.where])
        self.assertLess(resnorm, 1e-13)

class navierstokes(TestCase):

  def setUp(self):
    super().setUp()
    domain, geom = mesh.rectilinear([numpy.linspace(0,1,9)] * 2)
    ubasis, pbasis = function.chain([
      domain.basis('std', degree=2).vector(2),
      domain.basis('std', degree=1),
    ])
    dofs = function.Argument('dofs', [len(ubasis)])
    u = ubasis.dot(dofs)
    p = pbasis.dot(dofs)
    viscosity = 1
    self.inertia = domain.integral((ubasis * u).sum(-1)*function.J(geom), degree=5)
    stokesres = domain.integral((viscosity * (ubasis.grad(geom) * (u.grad(geom)+u.grad(geom).T)).sum([-1,-2]) - ubasis.div(geom) * p + pbasis * u.div(geom))*function.J(geom), degree=5)
    self.residual = stokesres + domain.integral((ubasis * (u.grad(geom) * u).sum(-1) * u).sum(-1)*function.J(geom), degree=5)
    self.cons = domain.boundary['top,bottom'].project([0,0], onto=ubasis, geometry=geom, ischeme='gauss2') \
              | domain.boundary['left'].project([geom[1]*(1-geom[1]),0], onto=ubasis, geometry=geom, ischeme='gauss2')
    self.lhs0 = solver.solve_linear('dofs', residual=stokesres, constrain=self.cons)
    self.tol = 1e-10

  def assert_resnorm(self, lhs):
    res = self.residual.eval(arguments=dict(dofs=lhs))
    resnorm = numpy.linalg.norm(res[numpy.isnan(self.cons)])
    self.assertLess(resnorm, self.tol)

  def test_direct(self):
    with self.assertRaises(solver.SolverError):
      self.assert_resnorm(solver.solve_linear('dofs', residual=self.residual, constrain=self.cons))

  def test_newton(self):
    self.assert_resnorm(solver.newton('dofs', residual=self.residual, lhs0=self.lhs0, constrain=self.cons).solve(tol=self.tol, maxiter=2))

  def test_newton_iter(self):
    _test_recursion_cache(self, lambda: ((types.frozenarray(lhs), info.resnorm) for lhs, info in solver.newton('dofs', residual=self.residual, constrain=self.cons)))

  def test_pseudotime(self):
    self.assert_resnorm(solver.pseudotime('dofs', residual=self.residual, lhs0=self.lhs0, constrain=self.cons, inertia=self.inertia, timestep=1).solve(tol=self.tol, maxiter=3))

  def test_pseudotime_iter(self):
    _test_recursion_cache(self, lambda: ((types.frozenarray(lhs), info.resnorm) for lhs, info in solver.pseudotime('dofs', residual=self.residual, lhs0=self.lhs0, constrain=self.cons, inertia=self.inertia, timestep=1)))

class finitestrain(TestCase):

  def setUp(self):
    super().setUp()
    domain, geom = mesh.rectilinear([numpy.linspace(0,1,9)] * 2)
    ubasis = domain.basis('std', degree=2).vector(2)
    u = ubasis.dot(function.Argument('dofs', [len(ubasis)]))
    Geom = geom * [1.1, 1] + u
    self.cons = solver.minimize('dofs', domain.boundary['left,right'].integral((u**2).sum(0), degree=4), droptol=1e-15).solve()
    self.boolcons = ~numpy.isnan(self.cons)
    strain = .5 * (function.outer(Geom.grad(geom), axis=1).sum(0) - function.eye(2))
    self.energy = domain.integral(((strain**2).sum([0,1]) + 20*(function.determinant(Geom.grad(geom))-1)**2)*function.J(geom), degree=6)
    self.residual = self.energy.derivative('dofs')
    self.tol = 1e-10

  def assert_resnorm(self, lhs):
    res = self.residual.eval(arguments=dict(dofs=lhs))
    resnorm = numpy.linalg.norm(res[~self.boolcons])
    self.assertLess(resnorm, self.tol)

  def test_direct(self):
    with self.assertRaises(solver.SolverError):
      self.assert_resnorm(solver.solve_linear('dofs', residual=self.residual, constrain=self.cons))

  def test_newton(self):
    self.assert_resnorm(solver.newton('dofs', residual=self.residual, constrain=self.cons).solve(tol=self.tol, maxiter=7))

  def test_newton_boolcons(self):
    self.assert_resnorm(solver.newton('dofs', residual=self.residual, constrain=self.boolcons).solve(tol=self.tol, maxiter=7))

  def test_newton_iter(self):
    _test_recursion_cache(self, lambda: ((types.frozenarray(lhs), info.resnorm) for lhs, info in solver.newton('dofs', residual=self.residual, constrain=self.cons)))

  def test_minimize(self):
    self.assert_resnorm(solver.minimize('dofs', energy=self.energy, constrain=self.cons).solve(tol=self.tol, maxiter=8))

  def test_minimize_boolcons(self):
    self.assert_resnorm(solver.minimize('dofs', energy=self.energy, constrain=self.boolcons).solve(tol=self.tol, maxiter=8))

  def test_minimize_iter(self):
    _test_recursion_cache(self, lambda: ((types.frozenarray(lhs), info.resnorm) for lhs, info in solver.minimize('dofs', energy=self.energy, constrain=self.cons)))

  def test_nonlinear_diagonalshift(self):
    nelems = 10
    domain, geom = mesh.rectilinear([nelems,1])
    geom *= [2*numpy.pi/nelems, 1]
    ubasis = domain.basis('spline', degree=2).vector(2)
    u = ubasis.dot(function.Argument('dofs', [len(ubasis)]))
    Geom = [.5 * geom[0], geom[1] + function.cos(geom[0])] + u # compress by 50% and buckle
    cons = solver.minimize('dofs', domain.boundary['left,right'].integral((u**2).sum(0), degree=4), droptol=1e-15).solve()
    strain = .5 * (function.outer(Geom.grad(geom), axis=1).sum(0) - function.eye(2))
    energy = domain.integral(((strain**2).sum([0,1]) + 150*(function.determinant(Geom.grad(geom))-1)**2)*function.J(geom), degree=6)
    nshift = 0
    for iiter, (lhs, info) in enumerate(solver.minimize('dofs', energy, constrain=cons)):
      self.assertLess(iiter, 38)
      if info.shift:
        nshift += 1
      if info.resnorm < self.tol:
        break
    self.assertEqual(nshift, 9)

@parametrize
class optimize(TestCase):

  def setUp(self):
    super().setUp()
    self.ns = function.Namespace()
    self.domain, self.ns.geom = mesh.rectilinear([2,2])
    self.ns.ubasis = self.domain.basis('std', degree=1)
    self.ns.u = 'ubasis_n ?dofs_n'
    self.optimize = solver.optimize if not self.minimize else lambda *args, newtontol=0, **kwargs: solver.minimize(*args, **kwargs).solve(newtontol)

  def test_linear(self):
    err = self.domain.boundary['bottom'].integral('(u - 1)^2' @ self.ns, degree=2)
    cons = self.optimize('dofs', err, droptol=1e-15)
    numpy.testing.assert_almost_equal(cons, numpy.take([1,numpy.nan], [0,1,1,0,1,1,0,1,1]), decimal=15)

  def test_nonlinear(self):
    err = self.domain.boundary['bottom'].integral('(u + .25 u^3 - 1.25)^2 d:geom' @ self.ns, degree=6)
    cons = self.optimize('dofs', err, droptol=1e-15, newtontol=1e-15)
    numpy.testing.assert_almost_equal(cons, numpy.take([1,numpy.nan], [0,1,1,0,1,1,0,1,1]), decimal=15)

  def test_nonlinear_multipleroots(self):
    err = self.domain.boundary['bottom'].integral('(u + u^2 - .75)^2' @ self.ns, degree=2)
    cons = self.optimize('dofs', err, droptol=1e-15, lhs0=numpy.ones(len(self.ns.ubasis)), newtontol=1e-10)
    numpy.testing.assert_almost_equal(cons, numpy.take([.5,numpy.nan], [0,1,1,0,1,1,0,1,1]), decimal=15)

  def test_nanres(self):
    err = self.domain.integral('(sqrt(1 - u) - .5)^2' @ self.ns, degree=2)
    dofs = self.optimize('dofs', err, newtontol=1e-10)
    numpy.testing.assert_almost_equal(dofs, .75)

optimize(minimize=False)
optimize(minimize=True)

class burgers(TestCase):

  def setUp(self):
    ns = function.Namespace()
    domain, ns.x = mesh.rectilinear([10], periodic=(0,))
    ns.basis = domain.basis('discont', degree=1)
    ns.u = 'basis_n ?dofs_n'
    ns.f = '.5 u^2'
    self.residual = domain.integral('-basis_n,0 f d:x' @ ns, degree=2)
    self.residual += domain.interfaces.integral('-[basis_n] n_0 ({f} - .5 [u] n_0) d:x' @ ns, degree=4)
    self.inertia = domain.integral('basis_n u d:x' @ ns, degree=5)
    self.lhs0 = numpy.sin(numpy.arange(len(ns.basis))) # "random" initial vector

  def test_iters(self):
    it = iter(solver.impliciteuler('dofs', residual=self.residual, inertia=self.inertia, lhs0=self.lhs0, timestep=100)) # involves 2-level timestep scaling
    assert numpy.equal(next(it), self.lhs0).all()
    numeric.assert_allclose64(next(it), 'eNpzNBA1NjHuNHQ3FDsTfCbAuNz4nUGZgeyZiDOZxlONmQwU9W3OFJ/pNQAADZIOPA==')

  def test_resume(self):
    _test_recursion_cache(self, lambda: map(types.frozenarray, solver.impliciteuler('dofs', residual=self.residual, inertia=self.inertia, lhs0=self.lhs0, timestep=1)))

  def test_resume_withscaling(self):
    _test_recursion_cache(self, lambda: map(types.frozenarray, solver.impliciteuler('dofs', residual=self.residual, inertia=self.inertia, lhs0=self.lhs0, timestep=100)))


import server
from datetime import datetime

def checkDiscount(userID):
    print('Inside model - checkDiscount', userID)
    festDates=["2019-05-02"]
    todayDate=datetime.today().strftime('%Y-%m-%d')
    print("today date", todayDate,type(todayDate))
    try:
        d = server.mysql.connect()
        d.autocommit_mode = False
        cursor = d.cursor()
        q1 = "SELECT count(uid) FROM seat WHERE uid = %s"
        cursor.execute(q1, (userID))
        r1=cursor.fetchone()
        print("user count --->", r1[0])
        discount = 0
        userMovieCount = r1[0]
        if userMovieCount >= 10 and userMovieCount <= 15:
            discount = 10
        elif userMovieCount >= 15:
            discount = 15
        elif todayDate in festDates:
            discount = 5
        print("discount", discount)

        q2 = "UPDATE user SET discount=%s where uid=%s"
        cursor.execute(q2, (discount, userID))
        d.commit()
        d.close()
        return {"statusCode": 200, "message": "Success"}

    except Exception as e:
        print(e)
        d.rollback()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: Mr.Frame
# Blog: https://askding.github.io/
# Dependence:
#           BeautifulSoup
#           docxtpl
# Bugs:
#  doc.render(data) 渲染数据时，
#  199个漏洞，只能渲染89个，
#  1362个漏洞只能渲染出639个

import sys
import time
from bs4 import BeautifulSoup
from docxtpl import DocxTemplate

# 定义漏洞类
class Vulner:
    def __init__(self, vulnName, ipList, details, threatLevel, solutions):
        self.vulnName = vulnName
        self.ipList = ipList
        self.detail = details
        self.threatLevel = threatLevel
        self.solution = solutions

def banner():
    if len(sys.argv) != 2:
        print(" Usage: python3 main.py  <path/to/index.html>  ")
        sys.exit()

def generate_docx(path):
    data = {"vulners": []}  # 漏洞数据
    soup = BeautifulSoup(open(path), "lxml")
    data['title'] = soup.h1.string  # 文档标题
    generated_dox = data['title'] + time.strftime("%Y-%m-%d", time.localtime()) + ".docx"  # 生成文档名

    vuln_table = soup.find('table', attrs={"id": "vuln_distribution",
                                           "class": "report_table"})

    # 获取漏洞名列表
    vuln_name_list = vuln_table.find_all('span')

    # 获取每个漏洞名字下展开信息
    report_table_list = vuln_table.find_all('table', attrs={"class": "report_table"})

    vuln_List=[]         # 漏洞名字列表

    print("\n梳理漏洞如下: ")
    for vul in vuln_name_list:
        vuln_name = vul.get_text().strip()  # 漏洞名列表
        print(vuln_name)
        vuln_List.append(vuln_name)

    vuln_Hosts=[]        # 风险来源列表
    Detail_List=[]       # 风险分析列表
    Solution_List=[]     # 处置建议列表
    ThreatLevel_List=[]  # 风险级别列表

    for report_table in report_table_list:
        vuln_hosts = report_table.find_all("td")[0].get_text()  # 风险来源
        vuln_hosts = vuln_hosts.replace("&nbsp", "").replace("点击查看详情;", "")

        detail = report_table.find_all("td")[1].get_text()  # 风险分析
        solution = report_table.find_all("td")[2].get_text().strip()  # 处置建议
        threatLevel = report_table.find_all("td")[3].get_text()  # 风险级别

        vuln_Hosts.append(vuln_hosts)
        Detail_List.append(detail)
        Solution_List.append(solution)
        ThreatLevel_List.append(threatLevel)

    for i in range(0,len(vuln_List)):
        print(i)
        data['vulners'].append(
            Vulner(vuln_List[i], vuln_Hosts[i], Detail_List[i], ThreatLevel_List[i], Solution_List[i])
        )
    print("文档原始数据生成中...")
    doc = DocxTemplate("template.docx")
    print("正在渲染文档数据....")
    doc.render(data)
    doc.save(generated_dox)
    print("生成完毕，文档名: {}".format(generated_dox))

if __name__ == '__main__':
    banner()
    generate_docx(sys.argv[1])
    #generate_docx("bb/index.html")


#!/usr/bin/env python3
"""Function that calculates the total
intra-cluster variance for a data set"""

import numpy as np

def variance(X, C):
    """X is a numpy.ndarray of shape (n, d) containing the data set
    C is a numpy.ndarray of shape (k, d) containing
    the centroid means for each cluster
    You are not allowed to use any loops
    Returns: var, or None on failure
        var is the total variance"""
    if type(X) is not np.ndarray or type(C) is not np.ndarray:
        return None
    if len(X.shape) != 2 or len(C.shape) != 2:
        return None
    if X.shape[1] != C.shape[1]:
        return None
    var = np.sum((X - C[:, np.newaxis])**2, axis=-1)
    mean = np.sqrt(var)
    mini = np.min(mean, axis=0)
    var = np.sum(mini ** 2)
    return np.sum(var)


from .executor import execute_validations
from nicetable.nicetable import NiceTable
import sys
import click

QUERY_VERBOSE_STR = "\nRUNNING QUERY:\n===========\n{}\n==========="

@click.command()
@click.option('--config',
              type=click.Path(exists=True),
              required=True,
              help='Path to a .toml config file.')
@click.option('--verbose/--no-verbose', default=False,
              help='Turn on verbose output of SQL queries.')
def run(config, verbose):
    """Validator of data that is queriable via SQL."""

    n_failed = 0
    for validation in execute_validations(config):
        if verbose:
            print(QUERY_VERBOSE_STR.format(validation['query']))

        print(validation['output'])

        if validation['result'] in ['failed', 'error']:
            n_failed += 1

        if validation['result'].startswith('failed'):
            print("Offending {} rows:".format(len(validation['rows'])))
            print(NiceTable(validation['rows'],
                            col_names=validation['col_names']))

    if n_failed > 0:
        sys.exit(1)
    else:
        sys.exit(0)


# -*- coding: utf-8 -*-
from AccessControl import getSecurityManager
from copy import deepcopy
from plone.scim.interfaces import CORE_SCHEMAS
from plone.scim.interfaces import EXTENSION_SCHEMAS
from Products.CMFCore.utils import getToolByName
from scimschema import ScimResponse
from zExceptions import BadRequest
from zope.component import queryUtility
from zope.security.interfaces import IPermission
import json
import logging
import os
import string
import struct

logger = logging.getLogger("plone.scim")

try:
    import secrets

    HAS_SECRETS = True
except ImportError:
    HAS_SECRETS = False

try:
    from json import JSONDecodeError
except ImportError:
    JSONDecodeError = ValueError

def get_source_users(context):
    """Return mutable ZODB User Manager."""
    acl_users = getToolByName(context, "acl_users")
    source_users = acl_users["source_users"]
    return source_users

def get_source_groups(context):
    """Return mutable ZODB Group Manager."""
    acl_groups = getToolByName(context, "acl_users")
    source_groups = acl_groups["source_groups"]
    return source_groups

def check_permission(permission, obj):
    """Check if request has the given permission for the given object."""
    utility = queryUtility(IPermission, name=permission)
    if utility is not None:
        permission = utility.title
    return utility is not None and bool(
        getSecurityManager().checkPermission(permission, obj)  # noqa: P001
    )

def validate_scim_request(request):
    """Validate given request against known SCIM schemas."""
    try:
        assert (
            request.getHeader("content-type") == "application/scim+json"
        ), "Invalid Content-Type. Expecting 'application/scim+json'."
    except AssertionError as e:
        raise BadRequest(str(e))

    try:
        data = json.loads(request.BODY)
        validate_scim_data(data)
        return data
    except (AssertionError, JSONDecodeError) as e:
        detail = str(e)
        if detail.startswith("Response"):
            offset = len("Request")
            detail = "Request" + detail[offset:]
        raise BadRequest(detail)
    except TypeError as e:
        logger.exception(
            "Unexpected exception for:\n{json:s}".format(
                json=json.dumps(data, indent=2)
            )
        )
        raise BadRequest(str(e))

def validate_scim_data(data):
    """Validate given SCIM request data against known schemas."""
    ScimResponse(
        data=deepcopy(data),
        core_schema_definitions=CORE_SCHEMAS,
        extension_schema_definitions=EXTENSION_SCHEMAS,
    ).validate()

def generate_password(length=32):
    """Generate random password."""
    if HAS_SECRETS:
        alphabet = string.ascii_letters + string.digits
        return "".join(secrets.choice(alphabet) for i in range(length))

    symbols = string.printable.strip()
    return "".join(
        [
            symbols[x * len(symbols) / 256]
            for x in struct.unpack("%dB" % (length,), os.urandom(length))
        ]
    )


from stemming.porter2 import stem
import time
from bs4 import BeautifulSoup
import os
import re
import regex
from collections import defaultdict
from collections import OrderedDict
import dill

def unpickler(file):
    f = open(file, 'rb')
    ds = dill.load(f)
    f.close()
    return ds

def parseCatalog(file):
    catalog = {}
    catalogFile = open(file, 'r')
    for line in catalogFile.readlines():
        content = line.strip().split(',')
        catalog[content[0]] = content[1:]
    return catalog

docInfo = unpickler('Files/Stemmed/Pickles/docInfo.p')
catalog = parseCatalog('Files/Stemmed/catalogFile.txt')
termMap = unpickler('Files/Stemmed/Pickles/termMap.p')
docMap = unpickler('Files/Stemmed/Pickles/docMap.p')

inFile = open("in.0.50.txt", "r")
indexFile = open("Files/Stemmed/invertedFile0.txt", "r")
outFile = open("Files/out.0.stop.stem.txt", "a+")
for line in inFile.readlines():
    key = stem(line.strip())
    keyId = str(termMap.get(key))
    if keyId in catalog.keys():
        offset = catalog[keyId][0]
        length = catalog[keyId][1]
        indexFile.seek(int(offset))
        termLine = indexFile.read(int(length))
        df = termLine.split(':')[0].split(',')[1]
        ttf = termLine.split(':')[0].split(',')[2]
        outLine = line.strip() + " " + df + " " + ttf+"\n"
        outFile.write(outLine)
    else:
        outFile.write(line)

outFile.close()
inFile.close()
indexFile.close()


# 일반적인 괄호검사에서 {}랑 ()를 구분하여 처리하기, 스택넣어서 확인하고 꺼냈을때 ()나 {}가 매칭되는지 확인
def matching(words):
    st = [] # 괄호 검사용 리스트(스택처럼 사용할 예정)
    # 뒤에서 부터 괄호 검사
    for i in range(len(words)-1, -1, -1):
        # )나 }는 스택에 넣기
        if words[i] == ')' or words[i] == '}':
            st.append(words[i])
        # (인 경우
        elif words[i] == '(':
            # 먼저 스택안에 아무것도 없는경우 ) } 둘다 안들어왔으므로 검사 탈락
            if not len(st):
                return 0
            char = st.pop()
            # )가 아니면 괄호검사 탈락
            if char != ')':
                return 0
        # {도 위와 같이 진행
        elif words[i] == '{':
            # 먼저 스택안에 아무것도 없는경우 ) } 둘다 안들어왔으므로 검사 탈락
            if not len(st):
                return 0
            char = st.pop()
            if char != '}':
                return 0
    # 모든 조건이 돌고 스택에 괄호가 남아있는지 확인 남으면 검사 탈락
    if len(st):
        return 0
    else:
        return 1

for t in range(int(input())):
    result = matching(input())
    print('#{} {}'.format(t+1, result))

ssafy_python/2102/210223/4866. [파이썬 SW 문제해결 기본] 4일차 - 괄호검사.py

4866. [파이썬 SW 문제해결 기본] 4일차 - 괄호검사.py


import numpy as np
import logging as lg
from queue import Queue
import argparse

import client_utils
import event_utils
import system_utils
import failure_utils
import template_utils
import measurement_utils
import debug_utils
import plot_utils
import backoff_utils

def start_sim(args: argparse.Namespace):
#def start_sim(_network_delay, _sim_len, _num_reqs):
    #### This is the main event data structure: index i is the priority queue
    #### for the events of time slot i.
    events = []
    for _ in range(args.sim_len):
        events.append([])
    #### Initiate the system
    syst = system_utils.generate_system()
    #### Generate the client requests
    reqs = client_utils.issue_client_requests(args.input_duration, args.num_reqs, args.load)
    debug_utils.print_unwrapped(reqs)
    #### Enter the client requests into the event priority queue.
    event_utils.issue_client_events(events, reqs)
    event_utils.issue_measurement_events(events)
    #### Get the failures from the config, and add them as events.
    if args.issue_failures:
        lg.info(f"Hi!{args.issue_failures}")
        failures = failure_utils.get_failures()
        event_utils.issue_failure_events(events, failures)
    #### Get the mitigations from the config, and add them as events.
    if args.issue_mitigations:
        mitigations = failure_utils.get_mitigations()
        event_utils.issue_mitigation_events(events, mitigations)
    #### Start the simulation
    for i in range(args.sim_len):
        #lg.info(f"time is {i}")

        #debug_utils.print_list_unwrapped(events[i])

        # refresh timeoutchange for every agent here
        backoff_utils.timeout_change_newtimeslot(syst)

        ####handle events starting from timeslot 1
        if len(events[i]) == 0:
            continue
        else:
            while not len(events[i]) == 0:
                evs = event_utils.handle_event(events[i][0], syst, i, args.network_delay, args.sim_len)
                #lg.debug("New event")
                #print(f"ev is {ev}")
                event_utils.deleteNode(events[i], events[i][0])
                if not evs == -1:
                    for ev in evs:
                        if not ev == -1:
                            event_utils.insert(events[ev.time], ev)
                            #debug_utils.print_unwrapped([ev])
    trigger = template_utils.parse_trigger()[0]

    #plot_utils.plot_trigger_and_measurement(syst.dropped_reqs, trigger)
    plot_utils.plot_measurements(syst, args)

    #plot_utils.plot_list(syst.dropped_reqs)
    if args.issue_failures:
        lg.warning("Logging metastability!")
        slope_responded, slope_retried = measurement_utils.is_metastable(syst, failures[0].time)
    else:
        slope_responded, slope_retried = measurement_utils.is_metastable(syst, 1)
    if args.exp_no > 0:
        if not slope_responded == 0:
            template_utils.write_to_file("./Experiment_results/exp"+str(args.exp_no)+".txt", str(slope_retried) + " " + str(slope_responded) + " " + str(slope_retried / slope_responded) + "\n")
        else:
            template_utils.write_to_file("./Experiment_results/exp"+str(args.exp_no)+".txt", str(slope_retried) + " " + str(slope_responded) + " " + str(-1) + "\n")

if __name__ == "__main__":
    #lg.basicConfig(format = "%(asctime)s %(filename)s:%(lineno)d %(message)s",level = lg.DEBUG)
    ##### To clear the contents of the file:
    log_file = open("log.txt", 'w')
    log_file.close()
    lg.basicConfig(filename="log.txt", format = "%(filename)s:%(lineno)d %(message)s", level = lg.WARNING)

    #### Parse arguments:
    ########## 1. Simulation length
    ########## 2. Number of services
    ########## 3. System topology
    ########## 4. Number of agents for each service
    ########## 5. The spec for each agent
    parser = argparse.ArgumentParser()
    parser.add_argument_group('General')
    parser.add_argument('--exp_no',
                        type=int,
                        required=True,
                        help='The number of the experiment to run. Zero indicates manual runs.')
    parser.add_argument('--input_duration',
                        type=int,
                        required=True,
                        help='The duration of imposing the system to input.')
    parser.add_argument('--sim_len',
                        type=int,
                        required=True,
                        help='The length of the simulation. It allows things to cool off after the input phase.')
    parser.add_argument('--num_reqs',
                        type=int,
                        required=True,
                        help='The number of requests.')
    parser.add_argument('--network_delay',
                        type=int,
                        required=True,
                        help='Network delay. Fixed for all p2p communication.')
    parser.add_argument('--load',
                        type=str,
                        required=True,
                        choices=['AUTO', 'LOAD_SHOCK'],
                        help='The type of the load, e.g., automatic, load shock, etc.')
    parser.add_argument_group('Failure-Flags')
    parser.add_argument('--issue_failures',
                        type=int,
                        required=True,
                        help='Whether to issue the failure events or not.')
    parser.add_argument('--issue_mitigations',
                        type=int,
                        required=True,
                        help='Whether to issue the mitagation events or not.')
    parser.add_argument_group('Plot-Flags')
    parser.add_argument('--plot_dropped',
                        type=int,
                        required=True,
                        help='Whether to plot the cumulative dropped requests in the entire system.')
    parser.add_argument('--plot_receive_dropped',
                        type=int,
                        required=True,
                        help='Whether to plot the cumulative receive-dropped requests in the entire system.')
    parser.add_argument('--plot_pending_dropped',
                        type=int,
                        required=True,
                        help='Whether to plot the cumulative pending-dropped requests in the entire system.')
    parser.add_argument('--plot_served',
                        type=int,
                        required=True,
                        help='Whether to plot the cumulative served requests in the entire system.')
    parser.add_argument('--plot_responded',
                        type=int,
                        required=True,
                        help='Whether to plot the cumulative responded requests in the entire system.')
    parser.add_argument('--plot_retried',
                        type=int,
                        required=True,
                        help='Whether to plot the cumulative retried requests in the entire system.')
    parser.add_argument('--plot_failures',
                        type=int,
                        required=True,
                        help='Whether to plot the failure boundaries.')
    parser.add_argument('--plot_mitigations',
                        type=int,
                        required=True,
                        help='Whether to plot the mitigation boundaries.')
    parser.add_argument('--plot_service_dropped',
                        type=int,
                        required=True,
                        help='Whether to plot the dropped requests for each service.')
    parser.add_argument('--plot_enabled',
                        type=int,
                        required=True,
                        help="A general flag to enable or disable plots.")

    args = parser.parse_args()
    #network_delay = 1
    #sim_len = 100
    #num_reqs = 50

    #start_sim(network_delay, sim_len, num_reqs)
    start_sim(args)