import pygame as pg
import sys, time

from gvars import *
from entities import Player, Magic, Student, Cat, Banner, Night

screen = None
redline = None
clock = None
player = None
magic_sprites = None
player_sprites = None
student_sprites = None
cat_sprites = None
banner_sprites = None
night_sprites = None
font_score = None
font_author = None
score = 0
now_hour = 0
date = 1
layer_1 = None
layer_2 = None
ommision = False
collision = False

def main():
    while True:
        mainPage()
        gameOn()
        gameOver()

def mainPage():
    # pg.mixer.music.unload()
    # pg.mixer.music.load(c_bgm_start)
    pg.mixer.Channel(0).play(pg.mixer.Sound(c_bgm_start))
    screen.fill(BABY_BLUE)
    bg = pg.transform.scale(pg.image.load('assets/header.png'),(c_header_width,c_header_height))
    screen.blit(bg,(270,152))
    bg = pg.transform.scale(pg.image.load('assets/start_instr.png'),(c_instr_width,c_instr_height))
    screen.blit(bg,(350,380))
    bg = pg.image.load('assets/student_front1.png')
    screen.blit(bg,(150,450))
    bg = pg.image.load('assets/player_front1.png')
    screen.blit(bg,(360,450))
    bg = pg.image.load('assets/player_front2.png')
    screen.blit(bg,(520,450))
    bg = pg.image.load('assets/player_front3.png')
    screen.blit(bg,(680,450))
    bg = pg.image.load('assets/student_front2.png')
    screen.blit(bg,(840,450))
    bg = pg.transform.scale(pg.image.load('assets/cat.png'),(c_cat_width*2,c_cat_height*2))
    screen.blit(bg,(850,370))

    authors = font_author.render('Game created by @lanran and @yuheng-wu', True, GRAY)
    screen.blit(authors, ((c_width - authors.get_width())//2, c_height - authors.get_height() - 5))

    pg.display.flip()
    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_q):
                pg.display.quit()
                pg.quit()
                sys.exit()
            if event.type == pg.KEYDOWN and event.key == pg.K_SPACE:
                return

def gameOn():
    global score, ommision,collision, now_hour, date

    time_between = c_time_between
    student_speed = c_student_speed
    last_stu_time = 0
    score = 0
    clearGroup(student_sprites)
    clearGroup(cat_sprites)
    clearGroup(magic_sprites)
    clearGroup(banner_sprites)
    clearGroup(night_sprites)
    time_last_hour = time.time()
    now_hour = 9

    ommision = False
    collision = False

    animation_on = False
    animation_start = None
    animation_time = None
    animation_callback = None

    while True:
        clock.tick(c_fps)
        for event in pg.event.get():
            if event.type == pg.QUIT:
                sys.exit()
            elif event.type == pg.MOUSEBUTTONDOWN:
                handleMouseDown()

        if animation_on:
            if time.time() - animation_start > animation_time:
                animation_on = False
                if animation_callback != None:
                    animation_callback()
                animation_callback = None

        if not animation_on and (time.time() - last_stu_time > time_between):
            student_sprites.add(Student(student_speed))
            last_stu_time = time.time()

        if time.time() - time_last_hour > c_hour_length:
            now_hour += 1
            if now_hour > 12:
                now_hour -= 12
            time_last_hour = time.time()

            if now_hour == 10 or now_hour == 3:
                banner = Banner(now_hour)
                banner_sprites.add(banner)
                time_last_hour += c_banner_time
                time_between = c_time_between / 3

                animation_on = True
                animation_start = time.time()
                animation_time = c_banner_time

            elif now_hour == 6:
                night = Night()
                night_sprites.add(night)
                time_last_hour += c_student_time + c_night_time

                animation_on = True
                animation_start = time.time()
                animation_time = c_student_time + c_night_time

                def set_time():
                    global now_hour, date
                    nonlocal animation_on, animation_start, animation_time, time_last_hour

                    banner = Banner("newday")
                    banner_sprites.add(banner)

                    time_last_hour += c_banner_time
                    now_hour = 9
                    date+=1

                    animation_on = True
                    animation_start = time.time()
                    animation_time = c_banner_time

                animation_callback = set_time

            else:
                time_between = c_time_between

        player_sprites.update()
        magic_sprites.update()
        student_sprites.update()
        cat_sprites.update()
        banner_sprites.update()
        night_sprites.update()

        drawBackground()
        magic_sprites.draw(screen)
        student_sprites.draw(screen)
        drawBackground(True)
        cat_sprites.draw(screen)
        player_sprites.draw(screen)
        banner_sprites.draw(screen)
        night_sprites.draw(screen)

        score_board = font_score.render('Score: {}'.format(score), False, BLACK)
        screen.blit(score_board, (950, 0))

        time_board = font_score.render('Time: {}:00'.format(now_hour), False, BLACK)
        screen.blit(time_board, (950, font_score.get_linesize()))

        def order(n):
            if 4 <= n <= 20:
                return 'th'
            else:
                if n%10 == 1:
                    return 'st'
                elif n%10 == 2:
                    return 'nd'
                elif n%10 == 3:
                    return 'rd'
                else:
                    return 'th'

        date_board = font_score.render('The {}{} day'.format(date,order(date)), False, BLACK)
        screen.blit(date_board, (950, font_score.get_linesize()*2))

        pg.display.flip()

        collide_res = checkCollide()
        if collide_res < 0:
            collision = True
            return
        score += collide_res

        if checkOmission():
            ommision = True
            return

def gameOver():
    global score
    # pg.mixer.music.unload()
    # pg.mixer.music.load(c_bgm_end)
    # pg.mixer.music.play()
    pg.mixer.Channel(0).play(pg.mixer.Sound(c_bgm_end))
    while True:
        clock.tick(c_fps)
        for event in pg.event.get():
            if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_q):
                pg.display.quit()
                pg.quit()
                sys.exit()
            elif event.type == pg.KEYDOWN and event.key == pg.K_SPACE:
                return
        if ommision == True:
            bg = pg.image.load('assets/endpg.png')
            screen.blit(bg,(0,0))
        elif collision == True:
            bg = pg.image.load('assets/endpg1.png')
            screen.blit(bg,(0,0))

        score_board = font_score.render('Score: {}'.format(score), False, BLACK)
        screen.blit(score_board, (500,290))

        pg.display.flip()

def drawBackground(layer2 = False):
    global layer_1, layer_2
    if layer2:
        screen.blit(layer_2,(0,0))
        return
    screen.blit(layer_1,(0,0))
    pg.draw.rect(screen, c_redline_color, redline)

def checkCollide():
    global student_sprites, magic_sprites, cat_sprites
    gonnaLose = False

    all_collide = pg.sprite.groupcollide(student_sprites, magic_sprites, False, False)

    for student in all_collide:
        magics = all_collide[student]
        for magic in magics:
            magic.kill()

        gonnaLose = gonnaLose or student.good
        cat = Cat(student.getCenter())
        cat_sprites.add(cat)
        student.kill()

    if gonnaLose:
        for student in student_sprites:
            student.speed = 0
        return -1

    return len(all_collide)

def checkOmission():
    global student_sprites

    student_escaped = None
    for student in student_sprites:
        if student.escaped():
            student_escaped = student
            break

    if student_escaped != None:
        for student in student_sprites:
            if student is not student_escaped:
                student.speed = 0
        return True
    return False

def handleMouseDown():
    global magic_sprites
    mouse_status = pg.mouse.get_pressed()
    if mouse_status[0] != 1: # not left button
        return

    magic = Magic()
    magic_sprites.add(magic)

def clearGroup(group):
    for item in group:
        item.kill()

def init():
    global screen, redline, clock, player, player_sprites, layer_1, layer_2,\
    student_sprites, magic_sprites, cat_sprites, font_score,\
    ommision, collision, banner_sprites, night_sprites, font_author

    pg.init()
    pg.mixer.init()
    pg.mouse.set_visible(False)
    screen = pg.display.set_mode((c_width, c_height))
    pg.display.set_caption(c_game_name)

    redline = pg.Rect((c_redline_left, c_redline_top), (c_redline_width, c_redline_height))

    magic_sprites = pg.sprite.Group()
    player_sprites = pg.sprite.Group()
    student_sprites = pg.sprite.Group()
    cat_sprites = pg.sprite.Group()
    banner_sprites = pg.sprite.Group()
    night_sprites = pg.sprite.Group()

    font_score = pg.font.SysFont('arial',20)
    font_score.set_bold(True)

    font_author = pg.font.SysFont('arial', 12)

    layer_1 = pg.image.load(c_bg_file).convert()
    layer_2 = pg.image.load(c_bg_file2).convert()

    player = Player()
    player_sprites.add(player)

    ommision = False
    collision = False

    clock = pg.time.Clock()

if __name__ == "__main__":
    init()
    main()


from PIL import Image
import os
import shutil

src_folder = "D:/Programming/Python/3.6/Project/WatchingVideoPsychophysiology/data/lab/video/test_black"
tar_folder = "D:/Programming/Python/3.6/Project/WatchingVideoPsychophysiology/data/lab/video/tar"
backup_folder = "D:/Programming/Python/3.6/Project/WatchingVideoPsychophysiology/data/lab/video/backup"

rect_dict = {}

def isCrust(pix):
    return sum(pix) < 25

def hCheck(img, y, step=50):
    count = 0
    width = img.size[0]
    for x in range(0, width, step):
        if isCrust(img.getpixel((x, y))):
            count += 1
        if count > width / step / 2:
            return True
    return False

def vCheck(img, x, step=50):
    count = 0
    height = img.size[1]
    for y in range(0, height, step):
        if isCrust(img.getpixel((x, y))):
            count += 1
        if count > height / step / 2:
            return True
    return False

def boundaryFinder(img, crust_side, core_side, checker):
    if not checker(img, crust_side):
        return crust_side
    if checker(img, core_side):
        return core_side

    mid = (crust_side + core_side) / 2
    while mid != core_side and mid != crust_side:
        if checker(img, mid):
            crust_side = mid
        else:
            core_side = mid
        mid = (crust_side + core_side) / 2
    return core_side

def handleImage_judge_zise(filename, tar):
    img = Image.open(os.path.join(src_folder, filename))
    if img.mode != "RGB":
        img = img.convert("RGB")
    width, height = img.size

    left = boundaryFinder(img, 0, width / 2, vCheck)
    right = boundaryFinder(img, width - 1, width / 2, vCheck)
    top = boundaryFinder(img, 0, height / 2, hCheck)
    bottom = boundaryFinder(img, height - 1, width / 2, hCheck)

    rect = (left, top, right, bottom)
    # print(rect)
    if rect not in rect_dict:
        rect_dict[rect] = 1
    else:
        rect_dict[rect] += 1

def handleImage_cut(filename, tar, size_tuple):
    img = Image.open(os.path.join(src_folder, filename))
    if img.mode != "RGB":
        img = img.convert("RGB")

    rect = size_tuple

    region = img.crop(rect)
    try:
        region.save(os.path.join(tar, filename), 'PNG')
    except SystemError:
        shutil.move(os.path.join(src_folder, filename),
                    os.path.join(tar, filename))

def folderCheck(foldername):
    if foldername:
        if not os.path.exists(foldername):
            os.mkdir(foldername)
            print("Info: Folder \"%s\" created" % foldername)
        elif not os.path.isdir(foldername):
            print("Error: Folder \"%s\" conflict" % foldername)
            return False
    return True

def juge_size():
    if folderCheck(tar_folder) and folderCheck(src_folder):
    # if folderCheck(tar_folder) and folderCheck(src_folder) and folderCheck(backup_folder):
        for filename in os.listdir(src_folder):
            if filename.split('.')[-1].upper() in ("JPG", "JPEG", "PNG", "BMP", "GIF"):
                handleImage_judge_zise(filename, tar_folder)
                # os.rename(os.path.join(src_folder, filename),
                #           os.path.join(backup_folder, filename))

def scorp_black(size_tuple):
    if folderCheck(tar_folder) and folderCheck(src_folder):
        for filename in os.listdir(src_folder):
            if filename.split('.')[-1].upper() in ("JPG", "JPEG", "PNG", "BMP", "GIF"):
                handleImage_cut(filename, tar_folder, size_tuple)

def find_max_times_rect():
    max_times = 0
    max_rect = None

    for key, value in rect_dict.items():
        if value > max_times:
            max_times = value
            max_rect = key

    # print(max_rect)
    # print(max_times)

    return max_rect

if __name__ == '__main__':
    juge_size()
    max_rect = find_max_times_rect()
    print(rect_dict)
    scorp_black(max_rect)

    # test = 'D:/Programming/Python/3.6/Project/WatchingVideoPsychophysiology/data/test/video/lab/24.jpg'
    # a = Image.open(test)
    # a.verify()


import shelve
from person_start import Person
import make_db_classes
db = shelve.open(make_db_classes.shelveFile)

fieldnames = ('name', 'age', 'job', 'pay')
max_fieldLen = max(len(f) for f in fieldnames)
# updater = {fieldname:}

while True:
    key = input('\nKey: ')
    if not key:
        break
    if key in db:
        record = db[key]
    else:
        print('Key "%s" was not found!' % key)

        makeNewRecord = input(
            'Do you want to create new record called "%s"' % key)

        if makeNewRecord.lower() == 'y':
            record = Person(name='?', age='?')
        else:
            continue

    print(key)
    for field in fieldnames:
        # print(' '*max_fieldLen, field.ljust(max_fieldLen), '=>', getattr(db[key], field))
        currentVal = getattr(record, field)
        out_str = ' '*max_fieldLen + field.ljust(max_fieldLen) + ' =>'
        print(out_str, currentVal)
        newVal = input(len(out_str)*' ' + ' new? ==> ')
        if newVal:
            try:
                newVal = eval(newVal)
            except:
                pass
            setattr(record, field, newVal)

    db[key] = record

db.close()


from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

figures = []

def myInit():
    # Set background color
    glClearColor(0.0, 0.0, 0.0, 1.0)
    glColor3f(0.2, 0.5, 0.4)
    glPointSize(5.0)  # 35, 15, 15 | 10, 50, 50 | 7, 75, 75 | 7,(-10, 75, -10, 75)
    gluOrtho2D(-54, 51, -54, 51)

def displayPoints():
    glClear(GL_COLOR_BUFFER_BIT)

    # x-axis
    glBegin(GL_LINES)
    glVertex2f(-54, 0)
    glVertex2f(51, 0)
    glEnd()

    # y-axis
    glBegin(GL_LINES)
    glVertex2f(0, -54)
    glVertex2f(0, 54)
    glEnd()

    # Center
    # glBegin(GL_POINTS)
    # glVertex2f(0, 0)
    # glEnd()

    # Rectangle
    # glBegin( GL_QUADS )
    # glVertex2f( 100.0, 100.0 )
    # glVertex2f( 300.0, 100.0 )
    # glVertex2f( 300.0, 200.0 )
    # glVertex2f( 100.0, 200.0 )
    # glEnd()

    # Triangle
    # glBegin(  GL_TRIANGLE_STRIP )
    # glVertex2f( 100.0, 210.0 )
    # glVertex2f( 300.0, 210.0 )
    # glVertex2f( 300.0, 310.0 )
    # glEnd()

    for pixels in figures:
        for pixel in pixels:
            # Draw a pixel(x,y)
            if len(pixel) == 2:
                glBegin(GL_POINTS)
                glVertex2f(pixel[0], pixel[1])
                glEnd()
            else:
                # Logic for striped line(x1, y1, x2, y2, isStriped)
                if len(pixel) == 5:
                    glLineStipple(1, 0xAAAA)
                    glEnable(GL_LINE_STIPPLE)
                else:
                    glDisable(GL_LINE_STIPPLE)

                # Draw a line P1(x1,y1) & P2(x2,y2)
                glBegin(GL_LINES)
                glVertex2f(pixel[0], pixel[1])
                glVertex2f(pixel[2], pixel[3])
                glEnd()
    glFlush()

def gluteSetup(figure):
    global figures
    figures = figure
    glutInit()
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
    glutInitWindowSize(500, 500)
    glutInitWindowPosition(350, 100)
    glutCreateWindow("My OpenGL Code")
    myInit()
    glutDisplayFunc(displayPoints)
    glutMainLoop()


"""Add random reverb to the audio stems based on DDSP library."""

import os
import numpy as np
import glob
import argparse
import librosa
import ddsp
from tqdm import tqdm
from utils.file_utils import get_config
from utils.file_utils import pickle_load, pickle_dump
from midi_ddsp.utils.audio_io import save_wav
from midi_ddsp.utils.inference_utils import ensure_same_length

# Reverb IR from: https://www.housecallfm.com/download-gns-personal-lexicon-480l, saved in ./ir
REVERB_TYPES = {'small': 'Small Hall.aif', 'medium': 'Medium Hall.aif', 'large': 'Large Hall.aif'}

def add_reverb(wav, reverb_type, sample_rate):
    reverb_ir, _ = librosa.load(os.path.join(os.path.abspath(__file__), REVERB_TYPES[reverb_type]), sr=sample_rate,
                                mono=True)
    reverb_length = len(reverb_ir)
    reverb = ddsp.effects.Reverb(trainable=False, reverb_length=reverb_length)
    wav = reverb(wav[np.newaxis], reverb_ir)
    return wav

def audio_augmentation(data_dir, output_dir, sample_rate):
    # if output_dir is provided, then save to the output_dir.
    if output_dir:
        output_dir = os.path.join(output_dir, os.path.basename(data_dir))
        os.makedirs(output_dir, exist_ok=True)
    else:  # else, change in place
        output_dir = data_dir

    # load metadata
    pickle_path = os.path.join(data_dir, 'metadata.pickle')
    metadata = pickle_load(pickle_path)

    # sample a reverb type for all stems
    reverb_type = np.random.choice(REVERB_TYPES)

    wav_files = glob.glob(f'{data_dir}/*.wav')
    stem_wav_files = [f for f in wav_files if 'mix.wav' not in f]  # exclude mix wav
    wavs_after_reverb = []
    for wav_file in stem_wav_files:
        wav, _ = librosa.load(wav_file, sr=sample_rate, mono=True)
        wav = add_reverb(wav, reverb_type, sample_rate)
        save_wav(wav[0].numpy(), os.path.join(output_dir, os.path.basename(wav_file)), sample_rate=sample_rate)
        wavs_after_reverb.append(wav[0].numpy())

    midi_audio_mix = np.sum(
        np.stack(ensure_same_length(
            [wavs_after_reverb[i].astype(np.float64) for i in range(len(wavs_after_reverb))], axis=0),
            axis=-1),
        axis=-1)

    save_wav(midi_audio_mix, os.path.join(output_dir, 'mix.wav'), sample_rate=sample_rate)

    # add metadata and save
    metadata['audio_augmentation'] = f'reverb_{reverb_type}'
    pickle_dump(metadata, os.path.join(output_dir, 'metadata.pickle'))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Audio augmentation')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--synthesis_dir', type=str, default=None, metavar='N',
                       help='the directory generated by MIDI-DDSP synthesis.')
    group.add_argument('--multi_synthesis_dir', type=str, default=None, metavar='N',
                       help='the directory containing multiple folders generated by MIDI-DDSP synthesis.')
    parser.add_argument('--output_dir', type=str, default=None, metavar='N',
                        help='the directory for output.')
    args = parser.parse_args()

    config = get_config()

    if args.synthesis_dir:
        synth_dir_list = [args.synthesis_dir]
    elif args.multi_synthesis_dir:
        synth_dir_list = glob.glob(f'{args.multi_synthesis_dir}/*/')

    for synth_dir in tqdm(synth_dir_list):
        audio_augmentation(synth_dir, args.output_dir, config['sample_rate'])


# Import libraries
import numpy as np
import pandas as pd
import os as os
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn import svm
from sklearn.model_selection import train_test_split
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.stats.diagnostic import het_white
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import KFold, cross_val_score
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestRegressor

# Set directory
directory = "C:\\Users\\calmp\\OneDrive\\0 - Job Applications\\Job Apps\\2022 & 2023 Job Hunt\\0 - Interviews\\QuantSpark\\Case Study"
os.chdir(directory)

# Read excel
df = pd.read_csv("Retention_df.csv")

# Drop useless columns
df = df.drop(["Over18", "StandardHours", "Gender", "MonthlyIncome",
              "Department", "BusinessTravel"], axis=1)

# Subset high performers
df = df[df['PerformanceRating']>=4]

# Adjust distributions

# Target split
X = df.drop(['Left'], axis=1)
y = df['Left']

# STATISTICAL INFERENCE

# Drop one dummy per group to avoid multicollinearity
X = X.drop(['Non-Travel', 'HR_department', "Income_medium"], axis=1)

# Create interactions
X['Distance_x_WFH'] = X['DistanceFromHome']*X['workingfromhome']
X['LowIncome_x_Hike'] = X['Income_low']*X['PercentSalaryHike']

# Select main indepedent variables
vars_ = ['DistanceFromHome', 'workingfromhome',
         'Income_low', 'Travel_Frequently', 'Age',
         'Sales_department']

# Select controls
## Added in other variables, but no signifiance
# vars_.append('YearsSinceLastPromotion')

# Retain desired vars
X1 = X[vars_]

# Test for multicollinearity with VIF
## NumCompanies, Total working years = scale with age
vif_data = pd.DataFrame()
vif_data["feature"] = X1.columns
vif_data["VIF"] = [variance_inflation_factor(X1.values, i) for i in range(len(X1.columns))]

# Dropped for multicollineatiy:
    ## JobSat -> separate regression?
    ## SalaryHike
    ## = these factors are represented by underlying variables

# Add interactions
vars_.append('Distance_x_WFH')
#vars_.append('LowIncome_x_Hike')

# Run logit regression
logit_model=sm.Logit(y,X[vars_])
log_result=logit_model.fit(cov_type="HC0")
print(log_result.summary2())

# Just satisfaction
logit_model=sm.Logit(y,X['JobSatisfaction'])
log_result=logit_model.fit(cov_type="HC0")
print(log_result.summary2())

# Subset model for those who made complaints
to_drop = df['complaintfiled'] == 1
Xc = X[to_drop]
yc = y[to_drop]

# Add variable
vars_.remove('Distance_x_WFH')
vars_.append('complaintresolved')

# Run logit regression
logit_model=sm.Logit(yc,Xc[vars_])
log_result_c=logit_model.fit()
print(log_result_c.summary2())

# What determines job satisfaction?

# Re-split
X_sat = df.drop(['JobSatisfaction'], axis=1)
y_sat = df['JobSatisfaction']

# Drop nans
X_sat = X_sat.drop(['complaintresolved', 'complaintyears'], axis=1)

# Drop other unwatned vars
X_sat = X_sat.drop(['Left', "Travel_Rarely", "HR_department", "Income_medium"], axis=1)

# Drop due to multicol
X_sat = X_sat.drop(['PerformanceRating'], axis=1)

# Recursive feature elimination
from sklearn.feature_selection import RFE
ols = LinearRegression()
rfe = RFE(ols, 10)
rfe = rfe.fit(X_sat, y_sat)
vars_ = list(X_sat.columns[rfe.support_])

# Check multicol
vif_data = pd.DataFrame()
vif_data["feature"] = X_sat[vars_].columns
vif_data["VIF"] = [variance_inflation_factor(X_sat[vars_].values, i) for i in range(len(X_sat[vars_].columns))]

# Run logit regression
ols_sat=sm.OLS(y_sat,X_sat[vars_])
sat_result=ols_sat.fit()
print(sat_result.summary2())

# Run logit only with salary hike
ols_sat=sm.OLS(y_sat,X_sat['PercentSalaryHike'])
sat_result=ols_sat.fit()
print(sat_result.summary2())

# What determines salary hike?

# Re-split
X_sat = df.drop(['PercentSalaryHike'], axis=1)
y_sat = df['PercentSalaryHike']

# Drop nans
X_sat = X_sat.drop(['complaintresolved', 'complaintyears'], axis=1)

# Drop other unwatned vars
X_sat = X_sat.drop(['Left', "Non-Travel", "HR_department",
                    "Income_medium", 'JobSatisfaction'], axis=1)

# Drop due to multicol
#X_sat = X_sat.drop(['PerformanceRating'], axis=1)

# Recursive feature elimination
from sklearn.feature_selection import RFE
ols = LinearRegression()
rfe = RFE(ols, 11)
rfe = rfe.fit(X_sat, y_sat)
vars_ = list(X_sat.columns[rfe.support_])
#vars_.append('Age')

# Check multicol
vif_data = pd.DataFrame()
vif_data["feature"] = X_sat[vars_].columns
vif_data["VIF"] = [variance_inflation_factor(X_sat[vars_].values, i) for i in range(len(X_sat[vars_].columns))]

# Run logit regression
ols_sat=sm.OLS(y_sat,X_sat[vars_])
sat_result=ols_sat.fit()
print(sat_result.summary2())

# What determines performance rating?

# Re-split
X_sat = df.drop(['PerformanceRating'], axis=1)
y_sat = df['PerformanceRating']

# Drop nans
X_sat = X_sat.drop(['complaintresolved', 'complaintyears'], axis=1)

# Drop other unwatned vars
X_sat = X_sat.drop(['Left', "Non-Travel", "HR_department",
                    "Income_medium", 'JobSatisfaction', 'PercentSalaryHike',
                    "R&D_department", 'Sales_department'], axis=1)

# Drop due to multicol
#X_sat = X_sat.drop(['PerformanceRating'], axis=1)

# Recursive feature elimination
from sklearn.feature_selection import RFE
ols = LinearRegression()
rfe = RFE(ols, 15)
rfe = rfe.fit(X_sat, y_sat)
vars_ = list(X_sat.columns[rfe.support_])
#vars_.append('Age')

# Check multicol
vif_data = pd.DataFrame()
vif_data["feature"] = X_sat[vars_].columns
vif_data["VIF"] = [variance_inflation_factor(X_sat[vars_].values, i) for i in range(len(X_sat[vars_].columns))]

# Run logit regression
ols_sat=sm.OLS(y_sat,X_sat[vars_])
sat_result=ols_sat.fit()
print(sat_result.summary2())

# PREDICTION

# Fix predictors
X = X.drop(["complaintresolved", "complaintyears", 'Distance_x_WFH', 'LowIncome_x_Hike'], axis=1)

# Set cross validation
k_folds = KFold(n_splits = 8)

# Train test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

# Feature scaling
scaler = preprocessing.StandardScaler().fit(X_train)
X_scaled = scaler.transform(X_train)

# PCA
pca = PCA(n_components=5)
pca.fit(X_train)
X_pca_train = pca.transform(X_train)
X_pca_test = pca.transform(X_test)

# Fit and run logistic regression
X_used = X_scaled.copy()
mod = LogisticRegression()
mod.fit(X_used, y_train)
y_pred = mod.predict(X_test)
scores = cross_val_score(mod, X_used, y_train, cv = k_folds)

print("Cross Validation Scores: ", scores)
print("Average CV Score: ", scores.mean())
print('Test Accuracy: {:.2f}'.format(mod.score(X_test, y_test)))

# Confusion matrix
confusion_matrix = confusion_matrix(list(y_test), list(y_pred))
print(confusion_matrix)

# Fit and run naive bayes
X_used = X_train.copy()
mod = GaussianNB()
mod.fit(X_used, y_train)
y_pred = mod.predict(X_test)
scores = cross_val_score(mod, X_used, y_train, cv = k_folds)

print("Cross Validation Scores: ", scores)
print("Average CV Score: ", scores.mean())
print('Test Accuracy: {:.2f}'.format(mod.score(X_test, y_test)))

# Confusion matrix
confusion_matrix = confusion_matrix(list(y_test), list(y_pred))
print(confusion_matrix)

# Fit and run SVM
X_used = X_scaled.copy()
mod = svm.SVC()
mod.fit(X_used, y_train)
y_pred = mod.predict(X_test)
scores = cross_val_score(mod, X_used, y_train, cv = k_folds)

print("Cross Validation Scores: ", scores)
print("Average CV Score: ", scores.mean())
print('Test Accuracy: {:.2f}'.format(mod.score(X_test, y_test)))

# Confusion matrix
confusion_matrix = confusion_matrix(list(y_test), list(y_pred))
print(confusion_matrix)

# Fit and run tree
from sklearn import tree
X_used = X_train.copy()
mod = tree.DecisionTreeClassifier()
mod.fit(X_used, y_train)
y_pred = mod.predict(X_test)
scores = cross_val_score(mod, X_used, y_train, cv = k_folds)

print("Cross Validation Scores: ", scores)
print("Average CV Score: ", scores.mean())
print('Test Accuracy: {:.2f}'.format(mod.score(X_test, y_test)))

# Confusion matrix
confusion_matrix = confusion_matrix(list(y_test), list(y_pred))
print(confusion_matrix)


import re
import sys
import pandas as pd
import urllib.request   # URL을 가져오기 위한 파이썬 모듈
import os
import cv2
import random
import numpy as np
import matplotlib.pyplot as plt
import glob
import math
from PyQt5 import uic
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import QDate, QTime, Qt
from selenium import webdriver
from bs4 import BeautifulSoup as bs, BeautifulSoup
from urllib.request import urlopen
import urllib.parse

form_class = uic.loadUiType("drug.ui")[0]

data = pd.read_csv('./공공데이터개방_낱알식별목록.csv')
drug_name = pd.DataFrame(data['품목명'])

drug_simple_name = []
for i, row in drug_name.iterrows():
    drug_simple_name.append(re.split('[/,-,(,),|,<,>,\[,\]. :]',drug_name['품목명'][i])[0])

drug_simple_name = pd.DataFrame(drug_simple_name)
drug_simple_name.columns = ['simple_name']
new_data = pd.concat([data, drug_simple_name], axis=1)
# new_data[ new_data['simple_name'] == '갈미정']

class MyApp(QWidget, form_class):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.initUI()
        self.show()  # 창 보여주기

    def initUI(self):
        self.setWindowTitle('prescription')
        self.move(300, 300)

        self.name.returnPressed.connect(self.Write_name)
        self.Select_sex()
        self.Select_age()
        self.date_time()

        self.init_drug()

        self.drug.returnPressed.connect(self.Write_drug)
        self.waring0.setText("주의사항")
        self.waring0.setReadOnly(True)
        self.info0.setText("약 정보")
        self.info0.setReadOnly(True)

    def Write_name(self):
        self.name.setText()

    def Select_sex(self):
        self.sex.addItem('Woman')
        self.sex.addItem('Man')

    def Select_age(self):
        self.age.addItem('5-7')
        self.age.addItem('8-10')
        self.age.addItem('11-13')
        self.age.addItem('14-16')
        self.age.addItem('17-19')
        self.age.addItem('20-27')
        self.age.addItem('28-34')
        self.age.addItem('35-47')
        self.age.addItem('48-55')
        self.age.addItem('56-65')
        self.age.addItem('66-73')
        self.age.addItem('74-')

    def date_time(self):
        now = QDate.currentDate()  # 현재 날짜를 반환
        time = QTime.currentTime()  # 현재 시간을 반환
        date = now.toString('yyyy-MM-dd(dddd)')
        date1 = time.toString('hh:mm:ss')
        self.date.setText(date + ' / ' + date1)

    def init_drug(self):
        self.drug1.pixmap() == None
        self.drug2.pixmap() == None
        self.drug3.pixmap() == None
        self.drug4.pixmap() == None
        self.drug5.pixmap() == None

    def Write_drug(self):
        drug_name = self.drug.text() + '.jpg'
        print("약 이름 : {}".format(drug_name))
        drug_Img_dir = './drug_image/'  # 결과 이미지 저장할 파일, 경로
        self.drug_img_name = os.path.join(drug_Img_dir, drug_name)

        if os.path.isfile(self.drug_img_name):    # 파일이 있다면
            pixmap = QPixmap(self.drug_img_name)   # Qt 에서 이미지 가져오기

            # 이미지 크기를 label 사이즈 맞춰주기
            # QLabel 1 ~ 5 크기는 같음
            self.drug_W = self.drug1.width()  # 라벨의 가로길이
            self.drug_H = self.drug1.height()  # 라벨의 세로길이

            # 이미지를 라벨의 크기로 변경, 비율무시
            self.src_pixmap = pixmap.scaled(self.drug_W, self.drug_H, aspectRatioMode=Qt.IgnoreAspectRatio)

            # 이미지가 있다면 다음 칸에 이미지를 출력시키기
            drug_name_list = [self.drug1, self.drug2, self.drug3, self.drug4, self.drug5]
            drug_info_list = [self.info1, self.info2, self.info3, self.info4, self.info5]
            for num in drug_name_list:
                if num.pixmap() == None: # 해당 칸에 이미지가 없다면
                    num.setPixmap(self.src_pixmap)  # Qt 에서 원본 이미지 보여주기
                    break
                # elif num.pixmap() != None:   # 해당 칸에 이미지가 있다면
                #     continue
            # print(self.drug1.pixmap(), type(self.drug1.pixmap()))
            # print(self.drug2.pixmap(), type(self.drug2.pixmap()))

            # 약 내용 크롤링 하기
            # 약품 일련 번호 가져오기
            simple_name = self.drug.text()
            print("simple_name : {}".format(simple_name))
            drug_num = new_data[new_data['simple_name'] == simple_name]['품목일련번호']
            drug_num = list(drug_num)
            drug_num = str(drug_num[0])
            print("drug_num : {}".format(drug_num))

            driver = webdriver.Firefox(executable_path='/home/test/opencv/geckodriver')

            url = "https://nedrug.mfds.go.kr/pbp/CCBBB01/getItemDetail?itemSeq=" + str(drug_num)

            driver.get(url)
            req = driver.page_source
            soup = BeautifulSoup(req, 'html.parser')

            drug_info = soup.select_one('#_ee_doc > p')

            driver.quit()

            # print(drug_info.text, type(drug_info.text))
            # print(self.info1.text())

            for num in drug_info_list:
                if num.text() == '': # 해당 칸에 글자가 안 써있다면
                    num.setText(simple_name + '\n' + drug_info.text)  # Qt 에서 크롤링으로 가져온 정보를 입력하기
                    break

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())


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

from setuptools import setup

with open('requirements.txt') as infile:
    requirements = infile.read()

setup(
    version='v0.1.0',
    name='reddit_get_top_images',
    description='Download top images from any subreddit',
    licence='MIT',

    author='nagracks',
    author_email='nagracks@gmail.com',

    url='https://github.com/nagracks/reddit_get_top_images',
    download_url='https://github.com/nagracks/reddit_get_top_images/archive/v0.1.0.tar.gz',

    keywords='reddit script download top images',

    scripts=['get_top_images.py'],
    install_requires=requirements,
)


# RESOURCE_EXCLUSTIONS = ['image', 'stylesheet', 'media', 'font', 'other']
RESOURCE_EXCLUSTIONS = ['image', 'media', 'font']

EXCEL_INPUT_FILE_PATH = 'excel_files/input.xlsx'
EXCEL_OUTPUT_FILE_PATH = 'excel_files/logs/'

BASE_URL = "https://uggus.deckersb2b.deckers.com"

CONFIG_PATH = '../config.json'

def get_url(key):

    if key == "login":
        return BASE_URL + "/#/login"

    elif key == "search":
        return BASE_URL + "/order-center/#/orderCenter/productList?method=SEARCH&search="

    elif key == "cart":
        return BASE_URL + "/order-center/#/orderCenter/shoppingCar"
    else:
        return "Key Not Set"


import json
import numpy as np

class score_keeper():
	def __init__(self):
		self.score = 0

	def calc_score(img1, img2):
		centrePoint = [0, 0]
		frameCount = -1
		avgErr = []

		for keyPointInd in range(1, numKeypoints):
			overallInd = frameInd*numKeypoints + keyPointInd
			tgtKP = targetKeypointsDiv[overallInd]
			srcKP = sourceKeypointsDiv[overallInd]

			tgtKPJSON = json.loads(tgtKP)
			srcKPJSON = json.loads(srcKP)

			xTgtList[keyPointInd] = (tgtKPJSON["xCoord"] - tgtCentre[0])
			xSrcList[keyPointInd] = (srcKPJSON["xCoord"] - srcCentre[0])

			yTgtList[keyPointInd] = (tgtKPJSON["yCoord"] - tgtCentre[1])
			ySrcList[keyPointInd] = (srcKPJSON["yCoord"] - srcCentre[1])

		NormedXTgtList = xTgtList / np.max(np.abs(xTgtList))
		NormedYTgtList = yTgtList / np.max(np.abs(yTgtList))

		NormedXSrcList = xSrcList / np.max(np.abs(xSrcList))
		NormedYSrcList = ySrcList / np.max(np.abs(ySrcList))

		xDist = NormedXTgtList - NormedXSrcList
		yDist = NormedYTgtList - NormedYSrcList

		err = np.sqrt(xDist**2 + yDist**2)

		print(np.average(err))


import cv2

# Load the face cascade classifier
face_cascade = cv2.CascadeClassifier('FaceDetectionTraining.xml')

# Load the image
image = cv2.imread('a2.bmp')

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Perform face detection
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

if len(faces) > 0:
    # Faces found
    for (x, y, w, h) in faces:
        # Draw rectangles around the detected faces
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

        # Write "Human Face" below the border
        cv2.putText(image, "Human Face", (x, y+h+20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
else:
    # No faces found
    cv2.putText(image, "Faces not found", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

# Display the image with detected faces
cv2.imshow('Face Recognition', image)
cv2.waitKey(0)
cv2.destroyAllWindows()


import h_transport_materials as htm
from datetime import date
import json

citations_data = {"date": str(date.today()), "dois": {}}

for i, prop in enumerate(htm.database):
    if prop.doi not in citations_data["dois"]:
        citations_data["dois"][prop.doi] = prop.nb_citations
        print(i)

with open("htm_dashboard/citations.json", "w") as outfile:
    json.dump(citations_data, outfile, indent=4)


from flask import Flask, request
from flask import Response
from flask import jsonify
import json
import threading
import requests
import sys
import queue
import time
import pandas as pd
import utils_balance as ub
from concurrent.futures import ThreadPoolExecutor
from csv import writer
import os
from datetime import datetime
import numpy as np

app = Flask(__name__)
app.debug = True

# Recibir los parametros
arg = sys.argv
# Estados del nodo
id_nodo = int(arg[1]) # ID posicion 1
election = False
puerto_nodo = int(arg[2]) # Puerto del contenedor
ip_container = arg[3] # ip del container
puerto_base = int(arg[5]) # puerto base
total_workers = int(arg[6]) # Total de workers
# puerto_conquer = int(arg[7]) # Puerto del conquer que reunira loa archivos

# Datos del coordinador
puerto_cor = 0
id_cor = 0
without_coordina = False
puertos_kill = []
verificar = False
estatus = True
# Verifica si es el coordinador
if (arg[4] == '1'):
    coordina = True
    id_cor = id_nodo
else:
    coordina = False

pet =0
inicio_global = 0
fin_global = 0

tota = np.power(2,total_workers)-1

# Info of aceptors
class NodeBully:
    def __init__(self,ide,ip_nodo,puerto,total,antesesor,sucesor):
        self.ide = ide
        self.ip_nodo = ip_nodo
        self.puerto = puerto
        self.name = ub.conc(ip_nodo, str(puerto))
        self.id_nodo = ub.hash(self.name,total)
        self.antesesor = antesesor
        self.sucesor = sucesor
        self.sucesor_port = 0
        self.antesesor_port = 0

    def url_request(self):
        url = 'http://'+self.name
        return url

    def set_ide(self,ide):
        self.ide = ide

    def set_ip_nodo(self,ip):
        self.ip_nodo = ip

    def set_puerto(self,puerto):
        self.puerto = puerto

    def set_antesesor(self,ante,port):
        self.antesesor = ante
        self.antesesor_port = port

    def set_sucesor(self,suce,port):
        self.sucesor = suce
        self.sucesor_port = port

# Creamos nodo local
node_local = NodeBully(ide=id_nodo,
                       ip_nodo=ip_container,
                       puerto=puerto_nodo,
                       total=tota,
                       antesesor=0,
                       sucesor=0)

proposer_lider = NodeBully(ide=0,
                       ip_nodo='0',
                       puerto=0,
                       total=tota,
                       antesesor=0,
                       sucesor=0)

nodos_workers = list()

# ------------------------------------------ BULLY  ------------------------------------
# Inicializa otros nodos proposer para conocerlos
# def init_nodos(m):
#     global puerto_base
#     global total_workers
#     global node_local
#     nodos = list()
#     for x in range(total_workers):
#         if (node_local.puerto != (puerto_base+x)):
#             aux = NodeBully(ide=x+1,
#                             ip_nodo=node_local.ip_nodo,
#                             puerto=puerto_base+x)
#             nodos.append(aux)
#     return nodos

# Funcion para obtener puertos
def init_nodos_chord(m):
    global puerto_base
    global node_local
    global total_workers
    nodos = list()
    total = np.power(2,m)-1
    for x in range(total_workers):
        if (x<=total_workers+1):
            if (node_local.puerto != (puerto_base+x)):
                iden = x+1
            else:
                iden=id_nodo
            aux = NodeBully(ide=iden,
                            ip_nodo=ip_container,
                            puerto=(puerto_base+x),
                            total=total,
                            antesesor=0,
                            sucesor=0)
            nodos.append(aux)
        else:
            break
    return nodos

# Recibe los datos del nuevo coordinador
@app.route('/COORDINATOR', methods = ['POST'])
def fun_coordinator():
    global pet
    global election
    global proposer_lider
    global fin_global
    global inicio_global
    global node_local
    # recibimos json
    message = request.get_json()
    # Actualizamos el proposer lider
    proposer_lider.set_ide(message['id'])
    proposer_lider.set_ip_nodo(message['ip'])
    proposer_lider.set_puerto(message['puerto'])
    # Coordinador llegó
    app.logger.info('------ COORDINATOR '+str(proposer_lider.ide)+' ------')
    election = False
    without_coordina = False
    pet =0
    if(inicio_global!=0):
        fin_global = time.time()
        append_list_as_row('./data/tiempos_bully_BaK.csv', [node_local.ide,proposer_lider.ide,(fin_global-inicio_global)])
        inicio_global=0
    # Comienza el proceso de verificacion
    monitor = threading.Thread(target=fun_verificar)
    monitor.start()
    init_chord()
    return jsonify({'response':'RECIBIDO'})

# Hace el proceso de election
@app.route('/ELECTION',methods = ['POST'])
def fun_election():
    global election
    global node_local
    if (election==True):
        # Recibi el post
        message = request.get_json()
        # Id y puerto del nodo que hace peticion de election
        id_vecino = message['id']
        # app.logger.info('------ ELECTION CON EL NODO '+str(id_vecino) + ' ------')
        # Si el nodo actual es mayor
        if (node_local.ide>id_vecino):
            # app.logger.info('------ SOY MAYOR ------')
            return jsonify({'response':'OK'})
        # Si el vecino es mayor
    else:
            # app.logger.info('------ SOY MENOR ------')
        return jsonify({'response':'NO'})

# Funcion de verificacion del coordinator
def fun_verificar():
    global pet
    global election
    global without_coordina
    global proposer_lider
    global node_local
    global inicio_global
    while True:
        try:
            if (election == False):
                # Verificamos si no somos el mismo
                if (proposer_lider.puerto == node_local.puerto):
                    break
                time.sleep(5+(id_nodo))
                url = proposer_lider.ip_nodo+':'+str(proposer_lider.puerto)+'/PRUEBA'
                headers = {'PRIVATE-TOKEN': '<your_access_token>', 'Content-Type':'application/json'}
                req = requests.post('http://'+url, headers=headers)
                # app.logger.info('------ SOY EL NODO No.'+str(id_nodo)+' - '+str(puerto_nodo)+'------')
                pet += 1
                app.logger.info('------('+str(pet)+') ACTIVO LIDER ='+str(proposer_lider.ide)+' - ('+str(node_local.puerto)+')------')
        except requests.exceptions.ConnectionError:
            # Proceso de election
            puertos_kill.append(proposer_lider.puerto)
            # Notifica a todos de election
            time.sleep(10)
            inicio_global = time.time()
            if(election == False and without_coordina == False):
                for proposer in nodos_workers:
                    if (proposer.puerto not in puertos_kill):
                        # requests
                        # app.logger.info('------ ME DI CUENTA ------')
                        app.logger.info('------ ME DI CUENTA ('+str(node_local.ide)+') ------')
                        url = proposer.ip_nodo+':'+str(proposer.puerto)+'/PRE'
                        # url = '148.247.201.221:'+puerto+'/PRE'
                        # Enviar petricion de eleccion
                        headers = {'PRIVATE-TOKEN': '<your_access_token>', 'Content-Type':'application/json'}
                        req = requests.post('http://'+url, headers=headers)
                        response_json = req.json()
                        app.logger.info('------ '+response_json['response']+' ('+str(proposer.ide)+') ------')
                # Inicio proceo de election
                app.logger.info('------ PROCESO ------')
                election = True
                init()
            break

# Verificacion de actividad
@app.route('/PRE',methods = ['POST'])
def pre():
    global election
    election = True
    without_coordina = True
    app.logger.info('------ ELECTION ------')
    return jsonify({'response':'ELECTION'})

# Verificacion de actividad
@app.route('/INICIO_ELECTION',methods = ['POST'])
def inicio_election():
    global election
    # time.sleep(10)
    init()
    return jsonify({'response':'OK'})

# Verificacion de actividad
@app.route('/PRUEBA',methods = ['POST'])
def prueba():
    global proposer_lider
    app.logger.info('------ Verificacion '+str(proposer_lider.ide)+' ------')
    return jsonify({'response':'SI'})

def init():
    global coordina
    global proposer_lider
    global node_local
    # Inicia la election
    cont=0
    for proposer in nodos_workers:
        if (node_local.puerto < proposer.puerto):
            if (proposer.puerto not in puertos_kill):
                # requests
                url = proposer.ip_nodo+':'+str(proposer.puerto)+'/ELECTION'
                # url = '148.247.201.221:'+puerto+'/ELECTION'
                datas = {
                    'id':node_local.ide,
                    'ip':node_local.ip_nodo,
                    'puerto':node_local.puerto
                }
                try:
                    headers = {'PRIVATE-TOKEN': '<your_access_token>', 'Content-Type':'application/json'}
                    req_i = requests.post('http://'+url, data=json.dumps(datas), headers=headers)
                    # Recibir
                    responde_json_ = req_i.json()
                    # Existe uno mayor
                    if (responde_json_['response'] == 'OK'):
                        app.logger.info('------ ('+str(proposer.puerto)+') OK ------')
                        # Se manda notifiacion al primer mayor
                        if(cont==0):
                            mayor_puerto = proposer.puerto
                            mayor_ip = proposer.ip_nodo
                            cont = 1
                except requests.exceptions.ConnectionError:
                    print('')
    # Envia la notificion al siguiente puerto mayor a que haga la election
    if (cont == 1):
        url = mayor_ip+':'+str(mayor_puerto)+'/INICIO_ELECTION'
        # url = '148.247.201.221:'+mayor_puerto+'/INICIO_ELECTION'
        try:
            headers = {'PRIVATE-TOKEN': '<your_access_token>', 'Content-Type':'application/json'}
            req = requests.post('http://'+url, data=json.dumps(datas), headers=headers)
            # Recibir
            responde_json = req.json()
            # Existe uno mayor
            if (responde_json['response'] == 'OK'):
                app.logger.info('------ NODO NUEVO PARA ELECTION '+str(mayor_puerto)+' ------')
                # # Se manda notifiacion al primer mayor
                # if(cont==0):
                #     mayor_puerto = puerto
                #     cont = 1
        except requests.exceptions.ConnectionError:
            print('')
    else:
        # Soy el nuevo coordinador
        proposer_lider = node_local
        coordina = True
        app.logger.info('------ SOY EL NUEVO COORDINATOR No.'+str(node_local.ide)+'------')
        for proposer in nodos_workers:
            if (proposer.puerto not in puertos_kill):
        # for puerto in puertos:
            # if (puerto not in puertos_kill):
                # requests
                url = proposer.ip_nodo+':'+str(proposer.puerto)+'/COORDINATOR'
                # url = '148.247.201.221:'+puerto+'/COORDINATOR'
                datas = {
                    'id':node_local.ide,
                    'ip':node_local.ip_nodo,
                    'puerto':node_local.puerto
                }
                headers = {'PRIVATE-TOKEN': '<your_access_token>', 'Content-Type':'application/json'}
                req = requests.post('http://'+url, data=json.dumps(datas), headers=headers)
                # Recibir
                responde_json = req.json()
                app.logger.info('------ SE NOTIFICO AL NODO '+str(proposer.puerto) + ' - ' + responde_json['response']+' ------')
        init_chord()
        datas = {
        'ip':node_local.ip_nodo,
        'puerto':node_local.puerto
        }
        url = node_local.ip_nodo+':5701/save_workers'
        req = requests.post('http://'+url,data=json.dumps(datas), headers=headers)

# ------------------------------------------ START CONTAINER -----------------------------------

nodos_workers = init_nodos_chord(m=total_workers)

def append_list_as_row(file_name, list_of_elem):
    # Open file in append mode
    with open(file_name, 'a+', newline='\n') as write_obj:
        # Create a writer object from csv module
        csv_writer = writer(write_obj)
        # Add contents of list as last row
        csv_writer.writerow(list_of_elem)

# ------------------------------------------ Balanceo de carga -----------------------------------
nodos_in_m = list()
nodos_online = list()

# Inicializar nodos para chord
def init_chord():
    global nodos_in_m
    global total_workers
    global nodos_workers
    global nodos_online
    # Obtiene los nodos para m = total_workers
    # nodos_in_m = init_nodos_chord(total_workers)
    # Se realiza un request a cada nodos para saber si estan activos
    nodos_online = info_all_nodos(nodos_workers)
    # Se confgura el sucesor y antesesor
    set_sucesor_antesesor(nodos_online)
    # app.logger.error(len(nodos_online))

# Configuramos los nodos antesesores y sucesores
def set_sucesor_antesesor(nodos_online):
    global node_local
    pos = [x.name for x in nodos_online].index(node_local.name)
    app.logger.info('POSICION - ' + str(pos))
    if(pos == 0):
        # Soy el primero
        node_local.set_antesesor(nodos_online[-1].id_nodo, nodos_online[-1].puerto)   # Antesesor
        node_local.set_sucesor(nodos_online[1].id_nodo, nodos_online[1].puerto)        # Sucesor
    elif(pos == len(nodos_online)-1):
        # Soy el ultimo
        node_local.set_antesesor(nodos_online[pos-1].id_nodo, nodos_online[pos-1].puerto)    # Antesesor
        node_local.set_sucesor(nodos_online[0].id_nodo, nodos_online[0].puerto)              # Sucesor
    else:
        # Estoy en el intermedio
        node_local.set_antesesor(nodos_online[pos-1].id_nodo, nodos_online[pos-1].puerto)    # Antesesor
        node_local.set_sucesor(nodos_online[pos+1].id_nodo, nodos_online[pos+1].puerto)      # Sucesor

# Saber que nodos estan activos
def info_all_nodos(nodos):
    global puerto_nodo
    nodos_online_= list()
    #  Convierte lista de json to string
    # json_string = json.dumps([ob.__dict__ for ob in nodos])
    datas = {
        'MSJ': 'INCIO'
    }
    for x in nodos:
        if (x.puerto != node_local.puerto):
            try:
                # app.logger.error('entroooo' + x.url_request())
                req = envio_request_with_datas(url=x.url_request(),
                                           comand='/NODOS',
                                           datas=datas)
                # app.logger.error(req['response'])
                if (req['response']=='OK'): # Guardo los nodos que respondan con un OK
                    # Ultimo nodo añadido es el antesesor
                    nodos_online_.append(x)

            except :
                pass
    app.logger.info('------ RECIBIDOS ------')
    nodos_online_.append(node_local)
    # app.logger.info(nodos_online_)
    nodos_online_ = sorted(nodos_online_, key=lambda chord_node : chord_node.id_nodo)
    return nodos_online_

# Recibe todos los nodos en m
@app.route('/NODOS',methods = ['POST'])
def nodos_recibidos():
    global nodos_in_m
    global estatus
    message = request.get_json()
    aux_nodos = message['MSJ']
    # app.logger.info(estatus)
    if (estatus == True):
        return jsonify({'response':'OK'})
    else:
        return jsonify({'response':'NO'})

# Envio a otro nodos con datos
def envio_request_with_datas(url,comand,datas):
    headers = {'PRIVATE-TOKEN': '<your_access_token>', 'Content-Type':'application/json'}
    req = requests.post(url+comand,data=json.dumps(datas), headers=headers)
    return req.json()

# Envio a otro nodo sin datos
def envio_request_witout_return(url,comand,datas):
    headers = {'PRIVATE-TOKEN': '<your_access_token>', 'Content-Type':'application/json'}
    req = requests.post(url+comand, data=json.dumps(datas), headers=headers)
    return 1

# Retorna nodos vecinos disponibles
def dame_n_nodos(peers):
    global node_local
    global total_workers
    global nodos_online
    if (peers<total_workers+1):
        # peers necesarios son menos o igual a los disponibles
        if(peers==1):
            puertos = list()
            ids = list()
            puertos.append(node_local.sucesor_port)
            ids.append(node_local.sucesor)
            return puertos, ids
        # mis dos vecinos
        elif(peers==2):
            puertos = list()
            ids = list()
            puertos.append(node_local.sucesor_port)
            puertos.append(node_local.antesesor_port)
            ids.append(node_local.sucesor)
            ids.append(node_local.antesesor)
            return puertos, ids
        # si es par
        elif (ub.par(peers)):
            dib = peers/2
            # Se envia al nodo suscesor y antesesor
            puertos_suc = list()
            puertos_ante = list()
            id_suc = list()
            id_ante = list()
            datas = {
                'id_solicitante': node_local.id_nodo,
                'num':dib,
                'ids':id_suc,
                'puertos':puertos_suc,
                'tipo':'S'
            }
            # sucesor
            req = envio_request_with_datas('http://'+node_local.ip_nodo+':'+str(node_local.sucesor_port),'/IP_NODO',datas)
            puertos_suc = req['puertos']
            id_suc=req['ids']
            # antesesor
            datas = {
                'id_solicitante': node_local.id_nodo,
                'num':dib,
                'ids':id_ante,
                'puertos':puertos_ante,
                'tipo':'A'
            }
            req = envio_request_with_datas('http://'+node_local.ip_nodo+':'+str(node_local.antesesor_port),'/IP_NODO',datas)
            puertos_ante = req['puertos']
            id_ante = req['ids']
            return (puertos_suc+puertos_ante),(id_suc+id_ante)
        # Es impar
        elif(ub.par(peers)==False):
            dib = (peers-1)/2
            # Se envia al nodo suscesor y antesesor
            puertos_suc = list()
            puertos_ante = list()
            id_suc = list()
            id_ante = list()
            datas = {
                'id_solicitante': node_local.id_nodo,
                'num':dib+1,
                'ids':id_suc,
                'puertos':puertos_suc,
                'tipo':'S'
            }
            # sucesor
            app.logger.error('********************************************** ' + 'http://'+node_local.ip_nodo+':'+str(node_local.sucesor_port))
            req_suc = envio_request_with_datas('http://'+node_local.ip_nodo+':'+str(node_local.sucesor_port),'/IP_NODO',datas)
            puertos_suc = req_suc['puertos']
            id_suc = req_suc['ids']
            # app.logger.error('Sucesor')
            # app.logger.error(puertos_suc)
            # antesesor
            datas = {
                'id_solicitante': node_local.id_nodo,
                'num':dib,
                'ids':id_ante,
                'puertos':puertos_ante,
                'tipo':'A'
            }
            req_ante = envio_request_with_datas('http://'+node_local.ip_nodo+':'+str(node_local.antesesor_port),'/IP_NODO',datas)
            puertos_ante = req_ante['puertos']
            id_ante = req_ante['ids']
            # app.logger.error('Antesesor')
            # app.logger.error(puertos_ante)
            # app.logger.error((puertos_suc+puertos_ante))
            return (puertos_suc+puertos_ante),(id_suc+id_ante)
    else:
        puertos = list()
        ids = list()
        for x in nodos_online:
            if(node_local.id_nodo!=x.id_nodo):
                puertos.append(x.puerto)
                ids.append(x.id_nodo)
        return puertos,ids

@app.route('/IP_NODO',methods=['POST'])
def ip_port_nodo():
    global node_local
    message = request.get_json()
    id_manager = message['id_solicitante']
    num = message['num']-1
    puertos_dis = message['ids']
    id_dis = message['puertos']
    tipo = message['tipo']

    # Si mi vecino es el utlimo
    if(num <= 0.0):
        # Me añado
        puertos_dis.append(node_local.puerto)
        id_dis.append(node_local.id_nodo)
        # Retorno la lista de id y puertos
        datas = {
            'ids':id_dis,
            'puertos':puertos_dis
        }
        return jsonify(datas)
    else:
    # No soy el ultimo
        datas = {
            'id_solicitante': id_manager,
            'ids':id_dis,
            'puertos':puertos_dis,
            'tipo':tipo,
            'num':num
        }
        if(tipo=='S'):
            # app.logger.error('+++++++++++++++++++++++++++++++++++ http://'+node_local.ip_nodo+':'+str(node_local.sucesor_port))
            req = envio_request_with_datas('http://'+node_local.ip_nodo+':'+str(node_local.sucesor_port),'/IP_NODO',datas)
        elif(tipo=='A'):
            req = envio_request_with_datas('http://'+node_local.ip_nodo+':'+str(node_local.antesesor_port),'/IP_NODO',datas)
        # guardar lo que retorne de listas llenas
        puertos_dis = req['puertos']
        id_dis = req['ids']
        # Me almaceno yo
        puertos_dis.append(node_local.puerto)
        id_dis.append(node_local.id_nodo)
        # Hago json de salida
        datas = {
            'ids':id_dis,
            'puertos':puertos_dis
        }
        # retorno actualizados
        return jsonify(datas)

# Coordinador
if (coordina==True):
    # global node_local
    proposer_lider = node_local
    # Notifico que es el coordinador
    app.logger.info('------ SOY EL COORDINADOR - No.'+str(node_local.ide) + ' ------')
    time.sleep(5)
    app.logger.info(str(nodos_workers)+' lista ------- ')
    for proposer in nodos_workers:
        if (proposer.puerto not in puertos_kill):
            # requests
            # node_local.ip_nodo
            url = proposer.ip_nodo+':'+str(proposer.puerto)+'/COORDINATOR'
            app.logger.info(url)
            # url = '148.247.201.221:'+puerto+'/COORDINATOR'
            datas = {
                'id':node_local.ide,
                'ip':node_local.ip_nodo,
                'puerto':node_local.puerto
            }
            headers = {'PRIVATE-TOKEN': '<your_access_token>', 'Content-Type':'application/json'}
            req = requests.post('http://'+url, data=json.dumps(datas), headers=headers)
            # Recibir
            responde_json = req.json()
            app.logger.info('------ SE NOTIFICO AL NODO '+str(proposer.ide) + ' - ' + responde_json['response']+' ------')

    # Comienza inicio de chord
    init_chord()
    datas = {
        'ip':node_local.ip_nodo,
        'puerto':node_local.puerto
        }
    url = node_local.ip_nodo+':5701/save_workers'
    req = requests.post('http://'+url,data=json.dumps(datas), headers=headers)
    # crate_fingerTable()

# ------------------------------------------ Balanceo de carga -----------------------------------

@app.route('/RECIBIR_BALAANCE',methods = ['POST'])
def k_dividir():
    global node_local
    global total_workers
    global nodos_online
    message = request.get_json()

    # Recibe los datos
    k_ = message['K']
    data_balance = 'D'
    type_balance = 'RR'
    type_cluster = 'Kmeans'
    # need_peers = message['workers']
    need_peers = total_workers
    # tiempo inicial
    inicio = time.time()
    # Atrae lo puertos
    puertos_o,ids = dame_n_nodos(need_peers)
    app.logger.info('--------------------------------------------------'+str(len(puertos_o))+ ' - ' + str(len(ids)))
    # timpo final
    fin = time.time()
    # añadir tiempos a csv
    append_list_as_row('./data/tiempos_busqueda.csv', [need_peers,(fin-inicio)])
    app.logger.error(fin-inicio)

    init_data = ub.init_workres_array(need_peers)
    data_clus = ub.read_CSV(message['name']) # DataPreprocess

    # numero AÑOS DIAS O MESES
    type_balance_str = ub.type_blane_cond(data_balance)
    list_balance = data_clus[type_balance_str].unique()

    if (type_balance=='RR'): # Balanceador Round Robin
        init_data = ub.RaoundRobin(init_data,list_balance,need_peers)
    elif (type_balance=='PS'):# Balanceador PseudoRandom
        init_data = ub.PseudoRandom(init_data,list_balance,need_peers)
    elif (type_balance=='TC'):# Balanceador TwoChoices
        init_data = ub.TwoChoices(init_data,list_balance,need_peers)
    else:# Balanceador Round Robin
        init_data = ub.RaoundRobin(init_data,list_balance,need_peers)

    # app.logger.error(puertos_online)
    peticiones = []
    # inicio=time.time()

    # with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:

    for x in range(need_peers):
        if (len(init_data[x])>0):
            concac=[]
            for val in init_data[x]:
                # app.logger.info(val)
                concac.append(data_clus[data_clus[type_balance_str]==val])
            data_fin = pd.concat(concac)
            name = "ID_"+str(ids[x])+"_Port_"+str(puertos_o[x])+"_LD="+type_balance+"_DLB="+data_balance
            data_fin.to_csv("./data/"+name+".csv")
            data_clus_n = {"K": k_,
                "name": name,
                "type_cluster":type_cluster,
                "need":need_peers
                }

            url = "http://"+node_local.ip_nodo+":"+str(puertos_o[x])
            req = envio_request_witout_return(url,"/CLUSTERING",data_clus_n)
                # process = Thread(target=envio_request_witout_return,args=(url,"/CLUSTERING",data_clus_n))
                # process.start()
                # peticiones.append(process)
                # peticiones.append(multiprocessing.Process(target=envio_request_witout_return,args=(url,"/CLUSTERING",data_clus_n)))
                # executor.submit(envio_request_witout_return,url,"/CLUSTERING",data_clus_n)
            app.logger.error('-----'+str(fin-inicio))
        # for pet in peticiones:
        #     pet.join()
    return jsonify({'response':'SI'})

# ------------------------------------------ Carga de Trabajo -----------------------------------
def prueba_clus(k_,type_cluster,data_clima,name,wor):
    # app.logger.error(k_)
    data_p =data_clima.iloc[:,[7,8,9,10]]
    for k in k_:
        # KMEANS
        if (type_cluster=="Kmeans"):
            # llamado del clustering
            inicio = time.time()
            k_labels,it = ub.K_means(k,data_p)
            cluster="Kmeans"
            fin = time.time()
            app.logger.error('------ '+str(cluster)+" = "+str(fin-inicio) + ' ------')
        elif (type_cluster=="GM"):
            inicio = time.time()
            k_labels = ub.MixtureModel(k,data_p)
            cluster="GaussianMixture"
            fin = time.time()
            app.logger.error('------ '+str(cluster)+" = "+str(fin-inicio) + ' ------')
        else:
            inicio = time.time()
            k_labels,it = ub.K_means(k,data_p)
            cluster="Kmeans"
            fin = time.time()
            app.logger.error('------ '+str(cluster)+" = "+str(fin-inicio) + ' ------')
        # data send
        append_list_as_row('./data/tiempos_carga.csv', [wor,cluster,(fin-inicio)])
        data_clima['clase']=k_labels
        data_clima.to_csv("./data/results/Clus_"+name+"_DataClust_K="+str(k)+"_"+str(cluster)+".csv")
        return 1

# cLustering
@app.route('/CLUSTERING',methods = ['POST'])
def clustering():
    message = request.get_json()
    # recibir K
    k_ = message['K']
    name = message['name']
    app.logger.info('----------------------------- ' + str(name))
    type_cluster = message['type_cluster']
    wor = message['need']

    data_clima = ub.read_CSV(name)
    # data_p =data_clima.iloc[:,[7,8,9,10]]
    # prueba_clus(k_,type_cluster,data_p,name,wor)
    with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:
        # app.logger.info('executoooooor')
        executor.submit(prueba_clus,k_,type_cluster,data_clima,name,wor)
        # app.logger.info(executor.result())
    # multi = multiprocessing.Process(target=prueba_clus,args=(k_,type_cluster,data_clima,name))
    # multi.start()
    # for k in k_:
    #     # KMEANS
    #     if (type_cluster=="Kmeans"):
    #         # llamado del clustering
    #         inicio = time.time()
    #         k_labels,it = K_means(k,data_p)
    #         cluster="Kmeans"
    #         fin = time.time()
    #         app.logger.error('------ '+str(cluster)+" = "+str(fin-inicio) + ' - '+str(it) +' ------')
    #     elif (type_cluster=="GM"):
    #         inicio = time.time()
    #         k_labels = MixtureModel(k,data_p)
    #         cluster="GaussianMixture"
    #         fin = time.time()
    #         app.logger.error('------ '+str(cluster)+" = "+str(fin-inicio) + ' ------')
    #     else:
    #         inicio = time.time()
    #         k_labels,it = K_means(k,data_p)
    #         cluster="Kmeans"
    #         fin = time.time()
    #         app.logger.error('------ '+str(cluster)+" = "+str(fin-inicio) + ' - '+str(it) +' ------')
    #     # data send
    #     append_list_as_row('./data/tiempos_carga.csv', [wor,cluster,(fin-inicio)])
    #     data_clima["clase"]=k_labels
    #     data_clima.to_csv("./data/results/Clus_"+name+"_DataClust_K="+str(k)+"_"+str(cluster)+".csv")

    return jsonify({'response':'CLUSTERING TERMINADO'})

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


import hexchat

# Module information
__module_name__         = "Kick Rejoin"
__module_version__      = "1.0"
__module_description__  = "Makes you rejoin the channel you were kicked from"
__module_author__       = "Mrprocom"

# Time it takes to rejoin in milliseconds
delay = 1000
# Add channels you do not want to rejoin automatically after getting kicked
blacklist = [
	"#freenode"
]

def unload(userdata):

	# Print a message saying that the script was unloaded
	print(__module_name__ + " plugin unloaded")

def kicked_check(word, word_eol, userdata):

	# This function rejoins channel
	def rejoin(userdata):

		# Check if the channel is not blacklisted
		if channel not in blacklist:
			hexchat.command("join " + channel)

	# Set the value of channel to the channel you were kicked from
	channel = word[1]
	# Run rejoin after <delay> millisecond
	hexchat.hook_timer(delay, rejoin)

# Make a hook that calls kicked_check after getting kicked
hexchat.hook_print("You Kicked", kicked_check)
hexchat.hook_unload(unload)

# Print a message saying that the script was loaded
print(__module_name__ + " plugin loaded")


import nltk
import string
import os
import json

from bs4 import BeautifulSoup
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer

# Download nltk libraries if not available locally.
nltk.download('punkt')
nltk.download('stopwords')
#nltk.download('stem.porter')

def importCollection(collectionPath):
    '''
    This function imports all textual paragraphs from the collection of documents.

    :param string collectionPath: String path to the directory containing collection docs.
    :return: list of tokens for all documents.
    :returnType: Dictionary
    '''
    # Loop over all documents in the collection.
    vocabulary = dict()
    for filename in os.listdir(collectionPath):
        with open(os.path.join(collectionPath, filename), 'r') as f:
            soup=BeautifulSoup(f, features='lxml', from_encoding="utf-8-sig")

        res=soup.findAll("text")
        # Token list for each document.
        docVocabulary = []
        # Add tokens for each document.
        for text in res:
            docVocabulary.extend(tokenize(str(text).replace("<text>", "").replace("</text>", "").replace(",", " ").replace("-", " ")))

        # Removing duplicates from the list.
        docVocabulary = list(dict.fromkeys(docVocabulary))
        # Add document tokens to all doc dictionary.
        vocabulary[filename]=docVocabulary

    # Create json file.
    makeJson(vocabulary, "./assets/collection-tokens")

    return vocabulary

def tokenize(text):
    '''
    Tokenizes a string using nltk PorterStemmer. Performs necessary stopword and punctuation deductions.
    Uses nltk stopwords along with custom stopwords.

    :param string text: Text string to tokenize.
    :return: Tokens from the string
    :returnType: List
    '''
    # Initialize porter stemmer.
    ps = PorterStemmer()

    # Custom Stopwards to tackle edge cases.
    edgeStopWords = ['``', '\'s', 'n\'t', '\'d', "\'\'"]

    # Set of all stopwords.
    allStopWords = set(stopwords.words('english')).union((line.strip('\n') for line in open("./assets/stopwords.txt", "r"))).union(edgeStopWords)

    # List of Tokenized paragraph.
    tokens = [ps.stem(word.lower()) for word in word_tokenize(text)
        if word.lower() not in allStopWords and word not in string.punctuation
        and not word.isnumeric() and not isFloat(word)]

    # Return token list.
    return tokens

def isFloat(s):
    '''
    Checks whether a string is a float.

    :param string s: String to verify.
    :return: True if the string s is float number, False otherwise.
    :returnType: boolean
    '''
    try:
        return float(s)
    except ValueError:
        return False

def makeJson(dictionary, filename):
    '''
    Dumps dictionary into a json file of the given name and path.

    :param dictionary: Dictionary to be dumped in the json file.
    :param filename: Path and filename of json file to be created.
    :return: null
    :returnType: null
    '''
    with open(filename+".json", "w") as outfile:
        json.dump(dictionary, outfile)


# -*- coding:utf-8 -*-

#Import models
from django.core.management.base import BaseCommand
from ...models import Youtube_Video, Game_Tag

#import modules
import pprint
import datetime

class Command(BaseCommand):
    help = '--youtube_video_org_id [id] : update or create specific video info '
    MOBILE_TAG = ['mobile','スマホ','モバイル']
    GAME_DICT = {}
    GAME_CATEGORY_OTHERES = 1
    GAME_CATEGORY_PUBG_PC = 2
    GAME_CATEGORY_PUBG_MOBILE = 5
    GAME_CATEGORY_FORTNITE_PC = 4
    GAME_CATEGORY_FORTNITE_MOBILE = 18

    def add_arguments(self, parser):
            parser.add_argument('--youtube_video_org_id')
            parser.add_argument('--all', action='store_true')

    def handle(self, *args, **options):

            dt_now = datetime.datetime.now()
            print("=======start video category_update : {}==========".format(dt_now))

            youtube_video_org_id = options['youtube_video_org_id']
            is_all = options['all']

            #Get Game_Tag
            game_tags = Game_Tag.objects.all().order_by('priority')

            #Create Game Tag Dict
            for tag in game_tags:
                self.GAME_DICT[tag.game_tag.lower()] = tag.game_id

            #list of streamer objects
            videos = []

            #get all objects
            if youtube_video_org_id is not None:

                videos = Youtube_Video.objects.extra(where=[ "youtube_video_org_id = '{}'".format(youtube_video_org_id) ])

            elif is_all is True:

                where_state = " active = True AND ( is_ready = FALSE OR game_id = 1 ) "
                videos = Youtube_Video.objects.extra(where=[ where_state ]).order_by('id');

            else:

                where_state = " active = True AND is_ready = FALSE"
                videos = Youtube_Video.objects.extra(where=[ where_state ]).order_by('id');

            for v in videos:

                #deactivate
                if v.video_title is None:
                    v.active = False
                    v.save()
                    continue

                #set update_game_id to othres
                update_game_id = self.GAME_CATEGORY_OTHERES
                print("video_id:{},youtube_video_org_id:{}".format(v.id, v.youtube_video_org_id))

                #Get category id from game title
                update_game_id = self.get_category_from_title(v.video_title)

                #if game id is still GAME_CATEGORY_OTHERES, check tags
                if update_game_id == self.GAME_CATEGORY_OTHERES and v.youtube_tag is not None:
                    update_game_id = self.get_category_from_title(v.youtube_tag)

                print("GAME Category Update => {},{}".format(update_game_id,v.video_title))
                v.game_id = update_game_id;
                v.is_ready = True
                v.save()

    def get_category_from_title(self, str):

        #set up
        #print(str)
        title = str.lower()
        update_game_id = self.GAME_CATEGORY_OTHERES
        mobile_array = self.MOBILE_TAG
        game_dict = self.GAME_DICT

        #is mobile
        is_mobile = False
        for m_tag in mobile_array:
            if title.find(m_tag) >=0:
                is_mobile = True

        for g_tag, g_id in game_dict.items():

            #print('----id:{},tag:{}'.format(g_id,g_tag))
            if title.find(g_tag)>=0:

                update_game_id = g_id

                # IF game_id equal PUBG and is_mobile true, game_id is PUBG Mobile
                if update_game_id == self.GAME_CATEGORY_PUBG_PC and is_mobile == True:
                    update_game_id = self.GAME_CATEGORY_PUBG_MOBILE

                # IF game_id equal PUBG and is_mobile true, game_id is PUBG Mobile
                if update_game_id == self.GAME_CATEGORY_FORTNITE_PC and is_mobile == True:
                    update_game_id = self.GAME_CATEGORY_FORTNITE_MOBILE

                break

        return update_game_id


import sys      # 기본적으로 가져와야함, 시스템 쉘 정보등을 담고있음.

# QTWidgets 에 대부분의 기본 기능을 갖고있음. 버튼, 툴팁텍스트 추가 등등
from PyQt5.QtWidgets import QApplication, QWidget   # 기본적으로 가져와야 할 2가지 모듈

# QWidget 을 상속받아 클래스 생성. (나만의 창을 만들기 위한)
class Exam(QWidget):
    # 생성자 만들기
    def __init__(self):
        super().__init__()           # super(): 상위 계층이 생성됨.
        self.initUI()                # 내가 사용할 함수, Method 매서드를 만듬
    def initUI(self):
        self.show()                 # 사용자가 볼 수 있도록 출력 (기본적으로 만들기)

# app : 어플리케이션 객체생성
# sys.argv : 시스템의 명령을 받아서 진행할때
app = QApplication(sys.argv)        # 모든 Qt5의 어플리케이션은 반드시 QApplication object를 생성해야 한다. (기본적인 사항)

w = Exam()      # w라는 객체 생성 내가만든 class를 이용해서

# app.exec_() : Main 루프를 실행 이벤트가 발생할 때까지 실행. 사용자가 프로그램을 종료를하면  sys.exit() 으로 깨끗하게 종료시킴.
sys.exit(app.exec_())

1_기본 위젯창 만들기, 창 이름설정, 버튼만들기, 마우스 테그 만들기/1_가장 기본 위젯창 만들기.py

1_가장 기본 위젯창 만들기.py


"""
Report module
"""

import os
import os.path
import sys

from .models import Models
from .query import Query

class Report(object):
    """
    Methods to build reports from a series of queries
    """

    @staticmethod
    def write(output, line):
        """
        Writes line to output file.

        Args:
            output: output file
            line: line to write
        """

        output.write("%s<br/>\n" % line)

    @staticmethod
    def build(embeddings, db, queries, outfile):
        """
        Builds a report using a list of input queries

        Args:
            embeddings: embeddings model
            db: open SQLite database
            queries: list of queries to execute
            outfile: report output file
        """

        with open(outfile, "w") as output:
            cur = db.cursor()

            for query in queries:
                output.write("# %s\n" % query)

                # Query for best matches
                results = Query.search(embeddings, cur, query, 50)

                # Extract top sections as highlights
                Report.write(output, "#### Highlights")
                for highlight in Query.highlights(results, 5):
                    Report.write(output, "- %s" % Query.text(highlight))

                # Write each article result
                Report.write(output, "\n#### Articles")

                # Get results grouped by document
                documents = Query.documents(results)

                # Print each result, sorted by max score descending
                for uid in sorted(documents, key=lambda k: sum([x[0] for x in documents[k]]), reverse=True)[:10]:
                    cur.execute("SELECT Title, Reference, Authors, Publication, Published from articles where id = ?", [uid])
                    article = cur.fetchone()

                    Report.write(output, "[%s](%s)" % (article[0], article[1]))

                    if article[2]:
                        Report.write(output, "by %s" % article[2])

                    # Publication name and date
                    publication = article[3] if article[3] else None
                    if article[4]:
                        published = Query.date(article[4])
                        publication = (publication + " - " + published) if publication else published

                    if publication and len(publication) > 0:
                        Report.write(output, "*%s*" % publication)

                    # Print top matches
                    for _, text in documents[uid]:
                        Report.write(output, "- %s" % Query.text(text))

                    # Start new section
                    output.write("\n")

    @staticmethod
    def run(task, path):
        """
        Reads a list of queries from a task file and builds a report.

        Args:
            task: input task file
            path: model path
        """

        # Load model
        embeddings, db = Models.load(path)

        # Read each task query
        with open(task, "r") as f:
            queries = f.readlines()

        # Build the report file
        Report.build(embeddings, db, queries, "%s.md" % os.path.splitext(task)[0])

        # Free resources
        Models.close(db)

if __name__ == "__main__":
    if len(sys.argv) > 1:
        Report.run(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:

    def traverse(self, root, x, y):

        q = deque([[root, 0, None]])
        level = 0
        x_Node = None
        y_Node = None
        while q:
            curr = q.popleft()
            parent = curr[2]
            level = curr[1]
            curr = curr[0]

            if curr.val == x:
                x_Node = [curr, level, parent]
            elif curr.val == y:
                y_Node = [curr, level, parent]

            if x_Node and y_Node:
                break

            if curr.left: q.append([curr.left, level+1, curr])
            if curr.right: q.append([curr.right, level+1, curr])

        return x_Node[1] == y_Node[1] and x_Node[2] != y_Node[2]

    def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
        return self.traverse(root, x, y)


# -*- coding: utf-8 -*-
"""
Created on Sat Mar 20 15:13:59 2021

@author: Josh
"""

import pandas as pd
import numpy as np

class shop (object):

    def __init__ (self, money_path, items_path):
        """
        The shop class for the Discord bot. Needs 2 things to initialize:
           -  the path for the shop item prices csv, and
           -  the path for the member balance/inventory csv

        """
        self.money_path = money_path
        self.items_path = items_path

        self.bal_df = pd.read_csv(money_path)
        self.shop_df = pd.read_csv(items_path)

        # print("Dataframes loaded")
        return

    def name_init (self):
        # Writes the column name row for the csv file

        item_columns = list(self.shop_df['item'])
        col_names = "member_id,balance,"
        col_names += ",".join(item_columns)

        with open(self.money_path, "w") as f:
            f.write(col_names)
            f.close()

        self.bal_df = pd.read_csv(self.money_path)

        return

    def member_init (self, member_id):
        # Initializes a row for a particular member

        item_columns = list(self.shop_df['item'])
        num_items = len(item_columns)

        s2w = "\n{},{}".format(member_id,0)
        s2w += num_items*",0"

        with open(self.money_path, "a") as f:
            f.write(s2w)
            f.close()

        self.bal_df = pd.read_csv(self.money_path)

        return

    def shop_prices (self):
        """
        Returns an array of tuples in the format
        [ [item, price, quantity], [item, price quantity], etc.]

        Example:
        [['apple', 10, 5], ['banana', 20, 6]]

        """

        return self.shop_df.to_numpy()

    def member_balance(self, member_id):
        member_df = self.bal_df["member_id"] == member_id

        # Member balance:
        member_balance = self.bal_df.loc[member_df, "balance"]

        return member_balance.item()

    def change_balance (self, member_id, amount):
        # Change the balance of member_id by amount

        amount = float(amount)
        member_df = self.bal_df["member_id"] == member_id
        self.bal_df.loc[member_df, "balance"] += amount

        self.rewrite_bal_csv()

        return

    def show_inv (self, member_id):

        """
        Returns a string representation of a member's inventory

        """

        # Gets the quantity of every shop item that the user has:
        df = self.bal_df
        df = df.loc[df["member_id"] == member_id, "balance":].to_numpy()
        df = df.reshape((df.shape[1]))

        item_names = self.bal_df.columns.to_numpy()[1:]

        together = np.stack((item_names, df), axis=1)

        template = "{0:15}│{1:10}\n"

        inv_str = "Item"+11*" "+"│"
        inv_str += 4*" "+"Amount\n"
        inv_str += 26*"—"+"\n"

        for x in together:
            inv_str += template.format(*x)

        return inv_str

    def buy (self, member_id, item_name, quantity=1):

        if quantity <= 0:
            msg = "What the fuck?"

            return msg

        # Find the dfs for the member and the item
        member_df = self.bal_df["member_id"] == member_id
        item_df = self.shop_df["item"] == item_name.lower()

        # Member balance:
        member_balance = self.bal_df.loc[member_df, "balance"]

        # Item information:
        item_price = self.shop_df.loc[item_df, "price"]
        item_quan = self.shop_df.loc[item_df, "quantity"]

        total_price = quantity * item_price.item()

        if not any(item_df):
            msg = "No such item"

            return msg

        if float(total_price) > member_balance.item():
            msg = "You do not have enough Simbits"

            return msg

        if quantity > item_quan.item():
            msg = "Not enough items left in stock. Sorry!"

            return msg

        # Remove quantity from shop item:
        self.shop_df.loc[item_df, "quantity"] -= quantity

        # Deducting money from user balance:
        self.change_balance (member_id, -total_price)

        # Adding item to inventory:
        self.bal_df.loc[member_df, item_name.lower()] += quantity

        # Returns a message of the transaction:
        msg = "You succesfully purchased {} {} for {} Simbits\n".format(
            quantity, item_name.title(), total_price)

        msg += "New balance: {}".format(
            self.bal_df.loc[member_df, "balance"].item())

        self.rewrite_bal_csv()
        self.rewrite_item_csv()

        return msg

    def donate (self, from_id, to_id, amount):
        """
        Give amount of your money to someone else

        """

        if amount <= 0:
            msg = "What the fuck?"

            return msg

        from_df = self.bal_df["member_id"] == from_id
        from_bal = self.bal_df.loc[from_df, "balance"].item()

        if from_bal < amount:
            msg = "You don't have enough money!"

        else:
            self.change_balance(from_id, -amount)
            self.change_balance(to_id, +amount)

            msg = "You gave {} to <@{}>".format(amount, to_id)

        return msg

    def remove_item (self, member_id, item, quantity):
        """
        Removes quantity amount of item from member_id's inventory

        """
        item = item.lower()

        member_df = self.bal_df["member_id"] == member_id

        # The amount of the item the member currently have:
        item_quan = self.bal_df.loc[member_df, item].item()

        print(item_quan)

        if item_quan - quantity < 0:
            msg = "Failed. The person has {} {}, but you are trying to remove {} {}"
            msg = msg.format(item_quan, item.title(), quantity, item.title())

            return msg

        self.bal_df.loc[member_df, item] -= quantity
        self.rewrite_bal_csv()

        msg = "Successfully removed {} {}. {} {} remaining"
        msg = msg.format(quantity, item.title(), item_quan-quantity, item.title())

        return msg

    # Methods for updating the .csv file when the df is changed:

    def rewrite_bal_csv (self):
        # Writes the member balance df to csv
        self.bal_df.to_csv(self.money_path, encoding="utf-8", index=False)

        return

    def rewrite_item_csv (self):
        self.shop_df.to_csv(self.items_path, encoding="utf-8", index=False)

        return

    def reload (self):
        self.bal_df = pd.read_csv(self.money_path)
        self.shop_df = pd.read_csv(self.items_path)

    def shop_show (self):
        """
        I hate string processing
        """

        template = "{0:15}│{1:10}│{2:10}\n"
        shop_str = ""

        together = self.shop_df.to_numpy()

        # Hardcoding the header row because I suck at string formatting...
        header = "Item"+11*" "+"│"
        header += 6*" "+"Cost"+"│"
        header += "     Stock"

        shop_str += header + "\n"
        shop_str += 37*"—"+"\n"

        for x in together:
            shop_str += template.format(*x)

        return shop_str

#%%

if __name__ == "__main__":

    me_id = 117431457202438148
    other_id = 666454811884912640

    path1 = "C:\\Users\\Josh\\Desktop\\Misc\\Simbad\\static\\cash_money.csv"
    path2 = "C:\\Users\\Josh\\Desktop\\Misc\\Simbad\\config\\shop_items.csv"

    market = shop(path1, path2)
    market.name_init()


#!/snap/bin/pypy3

with open("../data/data13.txt", "rt") as file:
	data = [list(x) for x in file.read().split('\n') if x != ""]

part2 = True

y_max = len(data)
x_max = len(data[0])

carts = []

for y in range(y_max):
	for x in range(x_max):
		if data[y][x] == '>':
			carts.append((y,x,1,0,True))
			data[y][x] = '-'
		elif data[y][x] == '<':
			carts.append((y,x,3,0,True))
			data[y][x] = '-'
		elif data[y][x] == '^':
			carts.append((y,x,0,0,True))
			data[y][x] = '|'
		elif data[y][x] == 'v':
			carts.append((y,x,2,0,True))
			data[y][x] = '|'

stop = False

while not stop:
	carts.sort()
	for i in range(len(carts)):
		c = carts[i]
		y, x, d, t, a = c
		if not a:
			continue
		if d == 0:
			y -= 1
			if data[y][x] == '\\':
				d = 3
			elif data[y][x] == '/':
				d = 1
		elif d == 1:
			x += 1
			if data[y][x] == '/':
				d = 0
			elif data[y][x] == '\\':
				d = 2
		elif d == 2:
			y += 1
			if data[y][x] == '/':
				d = 3
			elif data[y][x] == '\\':
				d = 1
		elif d == 3:
			x -= 1
			if data[y][x] == '/':
				d = 2
			elif data[y][x] == '\\':
				d = 0
		if data[y][x] == '+':
			d = (d + t - 1) % 4
			t = (t + 1) % 3
		colliding = [j for j in range(len(carts)) if j != i and carts[j][0] == y and carts[j][1] == x]
		if colliding:
			if not part2:
				r = str(x)+","+str(y)
				stop = True
				i = len(carts)
			else:
				for j in colliding:
					carts[j] = (0,0,0,0,False)
				carts[i] = (0,0,0,0,False)
		else:
			carts[i] = (y,x,d,t,a)
	if part2:
		active_carts = [c for c in carts if c[4]]
		if len(active_carts) == 1:
			r = str(active_carts[0][1])+","+str(active_carts[0][0])
			stop = True

print(r)


"""
Action to resolve Python dependencies using PIP
"""

from aws_lambda_builders.actions import BaseAction, Purpose, ActionFailedError
from .packager import PythonPipDependencyBuilder, PackagerError

class PythonPipBuildAction(BaseAction):

    NAME = 'ResolveDependencies'
    DESCRIPTION = "Installing dependencies from PIP"
    PURPOSE = Purpose.RESOLVE_DEPENDENCIES

    def __init__(self, artifacts_dir, manifest_path, scratch_dir, runtime):
        self.artifacts_dir = artifacts_dir
        self.manifest_path = manifest_path
        self.scratch_dir = scratch_dir
        self.runtime = runtime
        self.package_builder = PythonPipDependencyBuilder()

    def execute(self):
        try:
            self.package_builder.build_dependencies(
                self.artifacts_dir,
                self.manifest_path,
                self.scratch_dir,
                self.runtime,
            )
        except PackagerError as ex:
            raise ActionFailedError(str(ex))


#!/usr/bin/python

'''
this script is made by ahmed assem
'''

from socket import *
import threading
import sys
import os
from scapy.all import getmacbyip

red = "\033[1;31m"
yellow = "\033[1;33m"
cyan = "\033[1;36m"
grey = "\033[0;37m"

python3 = False
python_v = sys.version_info[0]

if python_v == 3:
	python3 = True
ip_list = []

if os.geteuid() != 0:
	print(yellow + "[!] you need super user.")
	exit()

class myThread (threading.Thread):
   def __init__(self,ip):
      threading.Thread.__init__(self) ; self.ip = ip
   def run(self):
      check(self.ip,False)

def check(ip,aon):
	global ip_list
	try:
		sock = socket(AF_INET , SOCK_STREAM)
		#sock.settimeout(1)
		sock.connect((ip,1111))
	except Exception as e:
		if str(e).strip().split(" ")[3] == "refused":
			if aon:
				return True
			else:
				try:
					host = gethostbyaddr(ip)[0]
					mac = str(getmacbyip(ip)).upper()
					if mac != "FF:FF:FF:FF:FF:FF":
						#ip_list.append(host + "=>" + ip + "=> " + mac)
						print(grey + " [" + ip + " " + host + "] ")
				except:
					None

		else:
			#print(str(e).strip())
			return False

def scan():
	print(yellow + "[!] All Thread's Has Been Started")
	for num in range(1,256):
		ip = "192.168.1."+str(num)
		thread1 = myThread(ip)
		thread1.start()

if __name__ == "__main__":
	scan()


#!/bin/python3
# %%
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import sys

file_name = sys.argv[1]
f = open(file_name)
f_rec = open(sys.argv[2])

line = f.readline()
i = 0
fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [100, 100]

while len(line) > 0:
    array = np.array(line.split(), dtype=int)
    array = np.append(array, i)
    # print(array)
    ax.plot([i for _ in range(len(array))], array, 'r.', 1)
    line = f.readline()
    i = i + 1

line = f_rec.readline()
while len(line) > 0:
    vec = line.split()

    a = np.array(vec[:5], dtype=int)
    color = 'bgrcmyk'[a[4]]
    line_width = 10 if vec[5] == "true" else 5 if vec[6] == "true" else 1
    rec = patches.Rectangle((a[0], a[1]), a[2] - 1, a[3] - 1, edgecolor=color, facecolor='none', linewidth=line_width)
    ax.add_patch(rec)
    line = f_rec.readline()
plt.savefig("fig")


def ADD_CHILD(Mother_name, Child_name, Gender):
    #check if mother is female and has a husband or not
    #if above condition is true
    #set the gender of child accordingly as the "Gender" parameter of this function
    #add child name to child property of the mother and father
    #add mother and father name to child's parent property

    if Mother_name.gender == "female" and Mother_name.husband != None:
        if Gender == "male":
            Child_name.gender = "male"
            Mother_name.child.append(Child_name)
            Mother_name.husband.child = Mother_name.child
            Child_name.parent.append(Mother_name.husband)
            Child_name.parent.append(Mother_name)
            return Child_name

        elif Gender == "female":
            Child_name.gender = "female"
            Mother_name.child.append(Child_name)
            Mother_name.husband.child = Mother_name.child
            Child_name.parent.append(Mother_name.husband)
            Child_name.parent.append(Mother_name)
            return Child_name

        else:
            return 0
    else:
        return 0


print("---------------------------------------------------------Nested for loop example ---------------------------------------------------------------------")
a=33
b=300
c=200
if a > b:
    print("a is greater than b")
elif a == b:
    print("a is equalto b")
else:
    print("a is not greater than b")

for i in range(0,20):
    print(i,"-",end=" ")
    for j in range(0,10):
        if j%2==0:
            print(j,end=" ")
    print("\n",end="")
print("\n---------------------------------------------------------Abstract class example ---------------------------------------------------------------------")
from abc import ABC,abstractmethod
class AbstractCurry(ABC):
    def __init__(self,name):
        self.name=name
        super().__init__()
    #@abstractmethod
    def Ingredients(self):
        pass
    #@abstractmethod
    def smell(self):
        pass
class MushroomCurry(AbstractCurry):
    def __init__(self,curryname):
        super().__init__(curryname)
        print("The name of curry is %s"%self.name)
    def Ingredients(self):
        print("The main Ingredients of Mushroom curry are Mushrooms and Tomato")
    def smell(self):
        print("The smell of Mushroom is similar to chicken curry")
def main():
    print("Program execution starts")
main()
mc=MushroomCurry("Mushroom masala")
mc.Ingredients()
mc.smell()
c=AbstractCurry("Mushroom masala")


'''
Homework 5, Excercise 1
Osvaldo Canales
March 20, 2023
Develop a program to write an iterator class that takes a list and iterates it from reverse direction.

'''

#Class takes a list and stores it as an instance variable
class ReverseIter:
    def __init__(self, lst):
        self.lst = lst
        self.index = len(lst)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index -= 1
        return self.lst[self.index]

#Create a list as the input
list = ReverseIter([1, 2, 3, 4])

#Print the list backwards onto the console
print(next(list))
print(next(list))
print(next(list))
print(next(list))
print(next(list))


import turtle

def draw_square(this_turtle):
    for i in range(1, 5):
        this_turtle.forward(100)
        this_turtle.right(90)

def draw_art():
    window = turtle.Screen()
    window.bgcolor("blue")

    pointer = turtle.Turtle()
    pointer.color("white")
    pointer.speed(2)

    for i in range(1, 37):
        draw_square(pointer)
        pointer.right(10)

draw_art()


import requests
import parsel
from tqdm import tqdm

url = 'http://biqugse.com/8820/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
response = requests.get(url, headers).text
selector = parsel.Selector(response)
novel_name = selector.css('#info h1::text').get()
detail_href = selector.css('#list dd a::attr(href)').getall()[9:625]
for href in tqdm(detail_href):
    list_url = 'http://biqugse.com' + href
    # print(list_url)
    data_details = requests.get(url=list_url, headers=headers).text
    selectors = parsel.Selector(data_details)
    title = selectors.css('.bookname h1::text').get()
    content_list = selectors.css('#content::text').getall()  # getall()获取返回的为列表
    # '\n'.join(content_list) 相当于把列表中的每一个元素都用\n合并
    content = '\n'.join(content_list)
    # print(content)
    with open(novel_name + '.txt', mode='a', encoding='utf-8') as f:
        f.write(title)
        f.write(content)
        f.write('\n')

小说下载器/笔趣阁.py


# encoding=utf-8
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

class WaitPageElement(object):
    def __init__(self, driver):
        self.driver = driver
        self.locTypeDict={'id': By.ID,
                          'name': By.NAME,
                          'link text': By.LINK_TEXT,
                          'partial link text': By.PARTIAL_LINK_TEXT,
                          'xpath': By.XPATH,
                          'css': By.CSS_SELECTOR}
        self.wait = WebDriverWait(self.driver, 10)

    def getPresentElement(self, locType, loc):
        """
        显式等待出现在DOM中，但不一定可见的元素。若存在，返回该页面元素对象。
        """
        print(locType.lower())
        print(self.locTypeDict[locType.lower()])
        try:
            if locType.lower() in self.locTypeDict:
                element = self.wait.until(EC.presence_of_element_located((self.locTypeDict[locType.lower()], loc)))
                return element
            else:
                raise  TypeError('未找到匹配的定位方式。')
        except Exception as e:
            raise e

    def getVisibleElement(self, locType, loc):
        """
        显式等待出现在DOM中并且可见的元素，返回该元素对象。
        """
        print(locType.lower())
        print(self.locTypeDict[locType.lower()])
        try:
            if locType.lower() in self.locTypeDict:
                element = self.wait.until(EC.visibility_of_element_located((self.locTypeDict[locType.lower()], loc)))
                return element
            else:
                raise  TypeError('未找到匹配的定位方式。')
        except Exception as e:
            raise e

if __name__ == '__main__':
    from selenium import webdriver
    driver = webdriver.Firefox()
    try:
        driver.get("http://localhost")
        wait = WaitPageElement(driver)
        wait.getPresentElement('xpath', '//input[@name="username"]').send_keys("gotIt")
        wait.getPresentElement('css', 'input[name="password"]').send_keys("gotIt123")
        wait.getVisibleElement('name', 'Submit').click()
        wait.getVisibleElement('partial link text', '请点击这里').click()
    finally:
        driver.quit()