#!/usr/bin/env python
''' Author  : Huy Nguyen
    Program : Quick program to download web talklet for lecture
    Start   : 08/26/2016
    End     : 08/27/2016
'''

import argparse
from bs4 import BeautifulSoup
from urllib.request import urlopen # for python2  use from urllib2 import urlopen
import os
import time # to sleep to wait for the opening of browser and load the swf file

#global variable
# hardcode dictionary that map error name to right name (a pain)
dic ={
    '1':
        {'The_Cycle_of_Life':'Cycle_of_Life',
         # 'Structural_Overview_of_Biology':'Structural_Overview_Of_Biology',
         # 'Informatics_Overview_of_Biology':'Informatics_Overview_Of_Biology',
         'Informatics_Overview_of_Biology':'Informatics_Overview',
         'Cellular_Cities':'Cellular_Citties', #the alternate root need this
         'The_Core_Machinery_of_Life':'Core_Machinery_of_Life',
         #'Drug_Binding_to_Receptor':'Drug_Binding_to_Receptor',
         #'Fibrous_Proteins_in_Disease':'Fibrous_Proteins_In_Disease',
         #'Protein_in_Water':'Protein_In_Water',
#         'See_the_Protein_alone':'See_The_Protein_Alone',
#         'See_the_Bonded_Atoms':'See_The_Bonded_Atoms',
         'Fundamental_interactions':'Fundamental_Interactions',
         'Try_to_See_the_Main_Chain_1':'Try_to_See_Mainchain_1',
         'Try_to_See_the_Main_Chain_2':'Try_to_See_Mainchain_2',
         'Try_to_See_the_Main_Chain_3':'Try_to_See_Mainchain_3',
         'Try_to_See_the_Chain_Path':'Try_to_See_Chain_Path',
         'What_is_An_Atom':'What_Is_An_Atom',
         'What_is_a_Molecule':'What_Is_A_Molecule',
         'Van_Der_Waals_interaction':'Van_Der_Waals_Interaction',
         'Electrostatics_interaction':'Electrostatics_Interaction',
         'Forces_Between_atoms':'Forces_Between_Atoms',
         'Bond_angle_Bending':'Bond_Angle_Bending',
         'Water_Energy_and_Dipole':'Water_Energy_And_Dipole',
         'Units_in_Force_Fields':'Units_In_Force_Fields',
         'Explaining_the_Dielectric_Effect':'Explaining_The_Dielectric_Effect',
         'Energy_and_Springs_1':'Energy_And_Springs_1',
         'Energy_and_Springs_2':'Energy_And_Springs_2',
         'Strength_of_Interactions':'Strength_Of_Interactions',
         'Complex_interactions':'Complex_Interactions',
         'Liquids_argon_and_Water':'Liquids_Argon_and_Water',
         'Useful_tools':'Useful_Tools',
         'See_the_Protein_Alone':'See_Protein_Alone',
         'See_the_Bonded_Atoms':'See_Bonded_Atoms'},
    '2':
        {'Amino_Acids_Gly_and_Pro':'Amino_Acids_Gly_And_Pro',
         'Amino_Acids_Leu_and_Phe':'Amino_Acids_Leu_And_Phe',
         'Amino_Acids_Glu_and_Arg':'Amino_Acids_Glu_And_Arg',
         'Amino_Acids_Val_and_Ile':'Amino_Acids_Val_And_Ile',
         'Degrees_of_Freedom._Concept_2.3':'Degrees_Of_Freedom._Concept_2.3',
         'Degrees_of_Freedom':'Degrees_Of_Freedom',
         'Backbone_Degrees_of_Freedom':'Backbone_Degrees_Of_Freedom',
         'The_Alpha_Heli':'The_Alpha_Helix_',
         'Beta_Sheet':'Beta_Sheets_'},
     '3':
         {'Cath_the_Numbers':'Cath_The_Numbers',
          'Alpha-Helix_and_Beta-Sheet':'Alpha-Helix_And_Beta-Sheet',
          'Cath_Drill_Down_to_a_Level':'Cath_Drill_Down_to_A_Level'},
     '4':
         {'Entropy_and_Free_Energy1':'Entropy_and_Free_Energy',
          'Simulated_annealing':'Simulated_Annealing',
          'Molecular_Dynamics_theory':'Molecular_Dynamics_Theory',
          'Liquids_argon_and_Water':'Liquids_Argon_and_Water',
          'Voronoi_analysis_of_Contacts':'Voronoi_Analysis_of_Contacts',
          'Simulating_alpha-Helix.__Concept_4.5':'Simulating_Alpha-Helix.__Concept_4.5',
          'Dynamics_of_the_alpha-Helix':'Dynamics_of_the_Alpha-Helix',
          'Water_allows_Hydrogen_Bonds_to_Break':'Water_Allows_Hydrogen_Bonds_to_Break',
          'Los_alamos_1943-45':'Los_alamos_1943-45',
          'Units_in_Force_Fields':'Units_In_Force_Fields',
          'Los_alamos_1943-45':'Los_Alamos_1943-45'},
     '5':
         {'Normal_Mode_theory._Concept_5.1':'Normal_Mode_Theory.__Concept_5.1',
          'Basic_theory':'Basic_Theory',
          'Potential_Energy_in_torsion_Space':'Potential_Energy_in_Torsion_Space',
          'Trypsin_inhibitor_Modes':'Trypsin_Inhibitor_Modes',
          'Unfolding_alpha_Helix.__Concept_5.3':'Unfolding_Alpha_Helix.__Concept_5.3',
          'Unfold_alpha-Helix':'Unfold_Alpha-Helix',
          'Helix_Less_Stable_in_Water':'Helix_Less_Stable_In_Water',
          'Water_allows_Hydrogen_Bonds_to_Break':'Water_Allows_Hydrogen_Bonds_to_Break',
          'What_Happens_to_aromatic_Sidechains':'What_Happens_to_Aromatic_Sidechains',
          'Why_is_Folding_So_Difficult':'Why_Is_Folding_So_Difficult',
          'Folding_at_Home_Rates':'Folding_at_Home_Rates'
         },
     '6':{},
     '7':{},
     '8':{},
     '9':{}
          }

constant = 'Lecture'
apps = 'talklets'
root ='http://csb.stanford.edu/class/public/lectures/'
alter_root = 'http://www.stanford.edu/class/sbio228/public/lectures/' # in case the other sever is down

def get_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument("--lecture","-l",help="Which lecture to download (1-6)")
    args = parser.parse_args()
    return args

'''@function: given the lecture name, parse the website to retrieve the name of each talklet slide
   @input   : int (lecture number)
   @output  : list (talklets website in numeric order)
'''
def parse_web(lecture):
    if lecture =='4':
        URL = root+constant+lecture+'/'
    else:
        URL = alter_root+constant+lecture+'/'
    print (URL)
    # open the url as url using url package, then use Beautiful soup to parse the website
    soup = BeautifulSoup(urlopen(URL))
    # print (soup)
    # get the text
    text = soup.text
    my_list = text.split('\n')
    # filter out the empty items
    new_list = list(filter(None,my_list))
    # do some trick to remove not important partas well as storing information
    # information to be stored: each section name of the chapter
    # for each section, store the name of the slide. Use those 2 information
    # in order to provide a full http link and append it into a list

    # list of link to download
    links =[]
    # chapter name
    # list of section names
    sections =[] # will use the length of the section to tell whether we go through
                 # all slides of a section already (since new slide starts with 'Fundamental interactions.  Concept 1.4')
    count = 0
    while count <len(new_list):
        if new_list[count] != 'CONCEPTS IN THIS LECTURE':
            count +=1
            continue
        else:
            # get the chapter name and break here
            chapter = new_list[count+1]
            count +=2 # plus 2 so it get over the index at the chapter name
            break
    # print (new_list)
    #using chapter as a mark to do sections
    while chapter not in new_list[count]:
        sections.append(new_list[count])
        count +=1
    count +=1 # increase to get over the second time it hits the chapter name
    while count < len(new_list):

        # print (new_list[count])
        if new_list[count][:2] == (lecture+'.') or (constant+' '+lecture) in new_list[count] or chapter in new_list[count]: #basically check if it is the section name, then ignore it
            count +=1
            continue
        else: # i basically ignore those 2 slides 'SB228 Lecture 2 Lecture2', 'Lecture 2 Contents'
            if new_list[count][-11:-2] == ('Concept '+lecture):
                section_index = int(new_list[count][-1])-1
                section = sections[section_index]
                # create a link to add to links
                # if it is lecture 1 then skip this part
                chapter_link = URL + constant + lecture+'/'+ section.replace(' ','_')+'/'+apps+'/'
                if lecture =='1':
                    count +=1
                    continue
            modify = new_list[count].replace(' ','_')
            if modify in dic[lecture]:
                link = chapter_link + dic[lecture][modify]+'.swf'
            else:
                link = chapter_link + modify+'.swf'
            links.append(link)
            count +=1

    return links

'''@function: Given list of website link, download the video
   @input   : list,and lecture number
   @output  : make a dir with lecture name, download all the video into that file
'''
def down_video(links,lecture):
    my_dir = './lecture'+lecture+'/'
    os.mkdir(my_dir)
    count = 0
    short = 4
    long = 6
    if lecture == '4':
        amount = long
    else:
        amount = short
    for link in links:
        count +=1
        # open the browser to load the swf file:
        cmd1= 'open '+link
        os.system(cmd1)
        time.sleep(amount)
        cmd2 ='curl -o '+my_dir+'part'+str(count)+'.swf'+' '+link
        os.system(cmd2)
        time.sleep(3)

###############################################################################
# execute the main program
###############################################################################
if __name__ == "__main__":

    args    = get_arguments()
    lecture = args.lecture
    print (lecture)
    links= parse_web(lecture)
    down_video(links,lecture)


from santas_little_helpers import day, get_data, timed
from dataclasses import dataclass

today = day(2022, 18)

@dataclass
class Point:
  x: int = 0
  y: int = 0
  z: int = 0

  def __lt__(self, other):
    return self.x < other.x or self.y < other.y or self.z < other.z
  def __hash__(self):
    return 2971215073 * self.x + 433494437 * self.y + 479001599 * self.z

  @property
  def neighbours(self):
    neighbours = set()
    neighbours.add(Point(self.x+1, self.y,   self.z  ))
    neighbours.add(Point(self.x-1, self.y,   self.z  ))
    neighbours.add(Point(self.x,   self.y+1, self.z  ))
    neighbours.add(Point(self.x,   self.y-1, self.z  ))
    neighbours.add(Point(self.x,   self.y,   self.z+1))
    neighbours.add(Point(self.x,   self.y,   self.z-1))
    return neighbours

  def clear(self, others):
    return sum(1 for n in self.neighbours if n not in others)

  def covered(self, others):
    return sum(1 for n in self.neighbours if n in others)

def exterior_surface_area(lava_droplet):
  max_x = max(p.x for p in lava_droplet)
  max_y = max(p.y for p in lava_droplet)
  max_z = max(p.z for p in lava_droplet)

  minimum = Point(-1, -1, -1)
  maximum = Point(max_x + 1, max_y + 1, max_z + 1)

  to_check = [Point(0, 0, 0)]
  seen = set()
  while to_check:
    p = to_check.pop()
    if p in seen or p < minimum or p > maximum:
      continue
    yield p.covered(lava_droplet)
    seen.add(p)
    to_check.extend(p.neighbours - lava_droplet)

def main():
  inp = get_data(today, [('split', ','), ('map', int)])
  lava_droplet = set([Point(*p) for p in inp])
  print(f'{today} star 1 = {sum(c.clear(lava_droplet) for c in lava_droplet)}')
  print(f'{today} star 2 = {sum(exterior_surface_area(lava_droplet))}')

if __name__ == '__main__':
  timed(main)


from pyspark import SparkConf, SparkContext
import json, sys, datetime
from xgboost import XGBRegressor
import pandas as pd
import numpy as np
from collections import defaultdict
import pickle
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
from operator import add

def extract_features():
    # business_id: (stars, review count)   188593   all
    bsn_feature = sc.textFile(business_data_path).map(lambda x: json.loads(x))\
                        .map(lambda x: (x['business_id'], (x['stars'], x['review_count']))).collectAsMap()
    # business_id: (checkin days, total checkin days)   157075   lack 532
    checkin_feature = sc.textFile(checkin_path).map(lambda x: json.loads(x))\
                        .map(lambda x: (x['business_id'], (len(x['time']), sum(x['time'].values()))))\
                        .collectAsMap()
    # business_id: (food+drink+menu, inside+outside) 32976        lack 128374
    def encode(record):
        food = 0
        env = 0
        for tag in record[1]:
            if tag in ['food','drink', 'menu']:
                food += 1
            if tag in ['inside','outside']:
                env += 1
        return (record[0], (food, env))
    photo_feature = sc.textFile(photo_path).map(lambda x: json.loads(x))\
                        .map(lambda x: ((x['business_id']), x['label'])).groupByKey().mapValues(list)\
                        .map(lambda x: encode(x)).collectAsMap()
    # (user_id, business_id): tip times     999945       lack 409824
    tip_feature = sc.textFile(tip_path).map(lambda x: json.loads(x))\
                        .map(lambda x: ((x['user_id'], x['business_id']), 1))\
                        .reduceByKey(add).collectAsMap()
    # user_id: (number of reviews, average star, yelp since, fans, votes sent by users,
    #           elite years, nearest elite  year, compliments received by users)
    # 1518169       all
    userRDD = sc.textFile(user_data_path).map(lambda x: json.loads(x))
    user_feature = userRDD.map(lambda x: (x['user_id'],\
                                            (x['review_count'], x['average_stars'],\
                                            2019 - int(x['yelping_since'][:4]), x['fans'], x['useful']+x['funny']+x['cool'],\
                                            0 if x["elite"] == 'None' else (len(x["elite"])+2) // 6,\
                                            0 if x["elite"] == 'None' else int(x["elite"][-4:]) - 2004,\
                                            x['compliment_hot']+x['compliment_more']+x['compliment_plain']\
                                            +x['compliment_cool']+x['compliment_funny']+x['compliment_writer'])))\
                            .map(lambda x: (x[0], (x[1][0],x[1][1],x[1][2],x[1][3],x[1][4],x[1][5],x[1][6],\
                                                   0 if x[1][0] == 0 else x[1][7] / x[1][0])))\
                            .collectAsMap()
    return bsn_feature, checkin_feature, photo_feature, tip_feature, user_feature

def train_xgb(X_train, y_train):
    model = XGBRegressor(n_estimators = 500, learning_rate = 0.1, max_depth = 5, eval_metric='rmse')\
                .fit(X_train, y_train)
    return model

if __name__ == '__main__':
    start_time = datetime.datetime.now()

    conf = SparkConf().setAppName("competition").setMaster("local[*]")
    sc = SparkContext(conf = conf)
    sc.setLogLevel("WARN")
    conf.set("spark.executor.memory", "32g")
    conf.set("spark.driver.memory", "32g")

    folder_file = sys.argv[1]
    train_file = folder_file + 'yelp_train.csv'
    test_file = sys.argv[2]
    output_file_path = sys.argv[3]
    business_data_path = folder_file + 'business.json'
    checkin_path = folder_file + 'checkin.json'
    tip_path = folder_file + 'tip.json'
    user_data_path = folder_file + 'user.json'
    photo_path = folder_file + 'photo.json'
    xgb_model_file = './xgb.pickle'

    trainRDD = sc.textFile(train_file).map(lambda x: x.split(','))
    firstline = trainRDD.first()  # user, bsn, stars
    train_set = trainRDD.filter(lambda x: x != firstline).map(lambda x: (x[0], x[1], float(x[2])))

    # 142044
    testRDD = sc.textFile(test_file).map(lambda x: x.split(','))
    first = testRDD.first()
    test_set = testRDD.filter(lambda x: x != first).map(lambda x: (x[0], x[1], float(x[2])))

    bsn_feature, checkin_feature, photo_feature, tip_feature, user_feature = extract_features()

    train_rdd = train_set.map(lambda x: ((x[0], x[1]),user_feature[x[0]],bsn_feature[x[1]],\
                                        checkin_feature[x[1]] if x[1] in checkin_feature else (0, 0),\
                                        photo_feature[x[1]] if x[1] in photo_feature else (0, 0),\
                                        tip_feature[(x[0], x[1])] if (x[0], x[1]) in tip_feature else 0,\
                                        x[2]))\
                    .map(lambda x: (x[0], x[1][0], x[1][1], x[1][2], x[1][3], x[1][4], x[1][5], x[1][6], x[1][7],\
                                x[2][0], x[2][1], x[3][0], x[3][1], x[4][0], x[4][1], x[5], x[6]))
    train_data = train_rdd.collect()
    train_df = pd.DataFrame(train_data,
                        columns =
                        ['user_bsn','u_reviews', 'u_star', 'u_years', 'u_fans', 'u_votes','u_elite','u_elite_1','u_compliment',\
                        'b_stars','b_reviews', 'b_checkin','b_checkin_total','b_photo_food', 'b_photo_env', 'tip','rating'])\
                .set_index('user_bsn')
    X_train = train_df.iloc[:,:-1]
    y_train = train_df.iloc[:,-1]

    test_rdd = test_set.map(lambda x: ((x[0], x[1]),user_feature[x[0]],bsn_feature[x[1]],\
                                        checkin_feature[x[1]] if x[1] in checkin_feature else (0, 0),\
                                        photo_feature[x[1]] if x[1] in photo_feature else (0, 0),\
                                        tip_feature[(x[0], x[1])] if (x[0], x[1]) in tip_feature else 0,\
                                        x[2]))\
                    .map(lambda x: (x[0], x[1][0], x[1][1], x[1][2], x[1][3], x[1][4], x[1][5], x[1][6], x[1][7],\
                                x[2][0], x[2][1], x[3][0], x[3][1], x[4][0], x[4][1], x[5], x[6]))
    test_data = test_rdd.collect()
    test_df = pd.DataFrame(test_data,
                        columns =
                        ['user_bsn','u_reviews', 'u_star', 'u_years', 'u_fans', 'u_votes','u_elite','u_elite_1','u_compliment',\
                        'b_stars','b_reviews', 'b_checkin','b_checkin_total','b_photo_food', 'b_photo_env', 'tip', 'rating'])\
                .set_index('user_bsn')
    X_test = test_df.iloc[:,:-1]
    y_test = test_df.iloc[:,-1]

    # train model
    xgb = train_xgb(X_train, y_train)
    # # load model
    # with open(xgb_model_file, 'rb') as file:
    #     xgb = pickle.load(file)

    user_bsn_id = test_df.index
    xgb_predict = xgb.predict(X_test)

    # write into file
    file = open(output_file_path, 'w')
    file.write('user_id, business_id, prediction')
    for i in range(len(xgb_predict)):
        file.write('\n')
        key = user_bsn_id[i]
        file.write(str(key[0]) + ',' + str(key[1]) + ',' + str(xgb_predict[i]))
    file.close()

    end_time = datetime.datetime.now()
    print((end_time - start_time).seconds)


import requests
kv={'q':'python'}
url='http://www.so.com/s'
try:
    r=requests.get(url,params=kv)
    r.raise_for_status()
    r.encoding=r.apparent_encoding
    print(r.text)
except:
    print('爬虫失败')
#一堆乱码
'''
r=requests.get(url,params=kv)
r.encoding=r.apparent_encoding
print(r.request.url)
#莫名其妙 的百度的搜索关键词这样用不行
'''


import keras
from keras import layers
from keras.datasets import imdb
from keras.preprocessing import sequence
from keras.utils import plot_model

max_features = 2000
max_len = 500

print("载入数据")
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
x_train = sequence.pad_sequences(x_train, maxlen=max_len)
x_test = sequence.pad_sequences(x_test, maxlen=max_len)
print("构造模型")
model = keras.models.Sequential()
model.add(layers.Embedding(max_features, 128, input_length=max_len, name='embed'))
model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.MaxPooling1D(5))
model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.GlobalMaxPooling1D())
model.add(layers.Dense(1))
print("模型结构")
print(model.summary())
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
print("添加回调函数记录信息")
callbacks = [
    keras.callbacks.TensorBoard(
        log_dir='log', # 日志写入位置
        histogram_freq=1, # 每一轮都记录激活直方图
        embeddings_freq=1, # 每一轮之后记录嵌入数据
        embeddings_data=x_test[:100] # 这里需要添加这一行，原文没有
    )
]
history = model.fit(x_train, y_train, epochs=20, batch_size=128, validation_split=0.2, callbacks=callbacks)
print("使用 tensorboard --logdir=log 启动，访问 localhost:6006")
print("绘制模型结构图片")
plot_model(model, to_file='log/model.png', show_shapes=True)


from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.urls import include, path, re_path

from podcasts import sitemaps, views

urlpatterns = (
    [
        path("admin/", admin.site.urls),
        path("health/", views.health, name="health"),
        path("", views.IndexView.as_view(), name="home"),
        path("vsi-podcasti/", views.AllPodcastsView.as_view(), name="all-podcasts"),
        path(
            "<slug:podcast_slug>/ep/<slug:episode_slug>/",
            views.EpisodeView.as_view(),
            name="episode",
        ),
        path(
            "<str:category_slug>-epizode/",
            views.EpisodeCategoryView.as_view(),
            name="latest-episodes-in-category",
        ),
        path("<slug:podcast_slug>/", views.PodcastView.as_view(), name="podcast"),
        path(
            "sitemap.xml",
            sitemap,
            {"sitemaps": sitemaps.sitemaps_dict},
            name="django.contrib.sitemaps.views.sitemap",
        ),
    ]
    + [re_path(r"^api/", include(views.router.urls))]
    + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
)


'''
Author: hdert
Date Started: 13/08/2018
Date Now: 16/08/2018
'''

# -- Librarys --

from tkinter import *

# -- Setup --

root = Tk()
root.title("Ball Game")
root.geometry("700x700+10+10")

# -- Variables --

image_ = 0
img1 = PhotoImage(file = "cat1.gif")
img2 = PhotoImage(file = "cat2.gif")
x = 350
y = 350

# -- Constant Lists --

IMAGE_LIST = [img1, img2]

# -- Functions --

def change(event):
    global x, y, IMAGE_LIST, img1, img2, image_

    if event.char == 'w':
        image = 0
        canvas.delete("all")
        y -= 10
        canvas.create_image(x, y, image = IMAGE_LIST[image_], tags = 'cat')
        canvas.move("cat", x, y)

    elif event.char == 'a':
        if image_ == 0:
            image_ = 1
        else:
            image_ = 0
        canvas.delete("all")
        x -= 10
        canvas.create_image(x, y, image = IMAGE_LIST[image_], tags = 'cat')
        canvas.move("cat", x, y)

    elif event.char == 's':
        image = 0
        canvas.delete("all")
        y += 10
        canvas.create_image(x, y, image = IMAGE_LIST[image_], tags = 'cat')
        canvas.move("cat", x, y)

    elif event.char == 'd':
        if image_ == 0:
                image_ = 1
        else:
            image_ = 0
        canvas.delete("all")
        x += 10
        canvas.create_image(x, y, image = IMAGE_LIST[image_], tags = 'cat')
        canvas.move("cat", x, y)

def remove(event = None):
    root.destroy()

# -- Widgets --

canvas = Canvas(root, bg = "white", width = 700, height = 700)

# -- Code --

root.bind("<w>", change)
root.bind("<a>", change)
root.bind("<s>", change)
root.bind("<d>", change)
root.bind("<Escape>", remove)

canvas.pack(anchor = NW)
canvas.create_image(x, y, image = IMAGE_LIST[image_], tags = 'cat')

root.mainloop()


from django.urls import path
from rest_framework_simplejwt.views import TokenRefreshView

from .views import (
    ViewRegisterAccount,
    ViewRegisterUser, LoginView,
    ViewListUser, ViewListStatus, ProfileView, ViewRegisterNewUser
)

urlpatterns = [
    path('register/account/', ViewRegisterAccount.as_view(), name='register-account'),
    path('register/user/', ViewRegisterUser.as_view(), name='register-user'),
    path('register/profile/', ViewRegisterNewUser.as_view(), name='register-profile'),
    path('login/', LoginView.as_view(), name='token'),
    path('refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('user_list/', ViewListUser.as_view(), name='employee-list'),
    path('status_list/', ViewListStatus.as_view(), name='status-list'),
    path('profile/', ProfileView.as_view(), name='profile'),
]


from time import gmtime, strftime

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, inch
from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Table

from lib.reportLabStyle import getWorksheetStyleSheet
from core.problem_sets import problem_number

class ReportLabDoc():
    default_specs = {
        "qr": True,
        "append_time": True,
        "header": True,
        "font": "Courier",
        "font_size": 16,
        "columns": 2,
        "paper_size": "letter",
        "folder": "sheets",
    }

    paper_size = {
        "letter" : letter
    }
    def __init__(self, problems, specs):

        self.specs = self.default_specs
        #override the defaults with anything that has been set
        for spec in specs:
            self.specs[spec] = specs[spec]

        self.name = self.specs['name']
        self.folder = self.specs['folder']
        self.problems = problems

        self.file_name = self.get_file_name()
        self.styleSheet = getWorksheetStyleSheet()
        doc = SimpleDocTemplate(self.file_name, pagesize=self.paper_size[self.specs['paper_size']])

        # container for the 'Flowable' objects

        self.worksheet = []

        if self.specs['header']:
            self.header()
        # check specs for font and style overrides
        # check specs for header and create one if asked
        # check specs for columns and create table
        # display each problem in a cell
        self.body()
        doc.build(self.worksheet)

    def get_file_name(self):
        if self.specs['append_time']:
            cur_time = strftime("%Y-%m-%d_%H-%M-%S", gmtime())
            file_name = "{}/{}_{}.pdf".format(self.folder, self.name, cur_time)
        else:
            file_name = "{}/{}.pdf".format(self.folder, self.name)
        return file_name

    def header(self):
        company_name = Paragraph("Tiny-Robot", self.styleSheet["Heading3"])
        name = Paragraph("Name:  ______________________", self.styleSheet["Heading3"])
        subject = Paragraph("Addition", self.styleSheet["Heading3"])
        date = Paragraph("Date:  ______________________", self.styleSheet["Heading3"])
        form_code = Paragraph("Form Code: {}".format(self.specs['random_seed']), self.styleSheet["Heading3"])

        # TODO change from if statements and so far, there are 4 layouts (yes/no form code and yes/no qr code)
        has_qr = self.specs.get('qr')
        has_form_code = self.specs.get('form_code')
        if has_qr:
            qr_image = Image(self.specs['qr_file'])
            data = [[company_name, qr_image], [subject, ""], [name, ""], [date, ""]]
            t=Table(data, style=[
                            ("VALIGN", (0,3), (0,3), "TOP"),
                            ('ALIGN', (1,0), (1,3),'RIGHT'),
                            ('SPAN', (1,0), (1,3)),

            ])
        elif has_form_code:
            data = [[company_name, form_code], [subject, ""], [name, ""], [date, ""]]
            t=Table(data, style=[
                            ("VALIGN", (0,3), (0,3), "TOP"),
                            ('ALIGN', (1,0), (1,3),'RIGHT'),

            ])

        else:
            data = [[company_name, name], [subject, date]]
            t=Table(data,colWidths='*', style=[
                            ('ALIGN',(0,0), (0,0),'LEFT'),
                            ('ALIGN',(1,0), (1,0),'RIGHT'),
                            ('ALIGN',(0,1), (0,1),'LEFT'),
                            ('ALIGN',(1,1), (1,1),'RIGHT'),
            ])
        self.worksheet.append(t)

    def body(self):
        data = []
        row = []
        for i, problem in enumerate(self.problems):
            problem_num_text = problem_number(i+1)
            problem_table = problem.reportlab_display()
            #print(problem_table)
            inner_data = [[problem_num_text, problem_table]]
            # TODO find height of problem, find the minimum of pages
            # space the row Heights evenly over those pages
            # or only worry about spacing evenly if it can fit to 1 page
            inner_table = Table(inner_data, colWidths='*', rowHeights=72, style=[
                ("VALIGN", (0,0), (1,0), "TOP")
            ])
            row.append(inner_table)
            if i % self.specs['columns']:
                data.append(row)
                row = []
        if row:
            data.append(row)
        t=Table(data, colWidths='*', style=[])
        self.worksheet.append(t)


from typing import Callable

from helper import choose_puzzle_input, print_solution

year = 2023
day = 10

puzzle_input = choose_puzzle_input(
    y=year,
    d=day,
    # sample_input_path=f"aoc_{year}_{day:02d}_input_sample.txt",
)

start = None

possible_tiles = ["7", "L", ".", "S", "J", "F", "|", "-"]

visited_1 = []
visited_2 = []

def start_connections(maze: list[str], startpos: list[int]) -> list[list[int]]:
    up = startpos[0] - 1
    down = startpos[0] + 1
    left = startpos[1] - 1
    right = startpos[1] + 1
    x, y = startpos[1], startpos[0]

    tile_up, tile_down, tile_left, tile_right = None, None, None, None

    if up >= 0 and maze[up][x] in ["7", "F", "|"]:
        tile_up = {"coord": [up, x], "tile": maze[up][x]}
    if down < len(maze) and maze[down][x] in ["L", "J", "|"]:
        tile_down = {"coord": [down, x], "tile": maze[down][x]}
    if left >= 0 and maze[y][left] in ["L", "F", "-"]:
        tile_left = {"coord": [y, left], "tile": maze[y][left]}
    if right < len(maze[0]) and maze[y][right] in ["7", "J", "-"]:
        tile_right = {"coord": [y, right], "tile": maze[y][right]}

    next_coordinates = [
        [tile["coord"][0], tile["coord"][1]]
        for tile in [tile_up, tile_down, tile_left, tile_right]
        if tile
    ]

    return next_coordinates

def next_connection(
    maze: list[str], startpos: list[int], prevpos: list[list[int]]
) -> list[int]:
    up = startpos[0] - 1
    down = startpos[0] + 1
    left = startpos[1] - 1
    right = startpos[1] + 1
    x, y = startpos[1], startpos[0]

    tile_up, tile_down, tile_left, tile_right = None, None, None, None

    if (
        up >= 0
        and maze[up][x] in ["7", "F", "|"]
        and maze[y][x] in ["L", "J", "|"]
    ):
        tile_up = [up, x]
    if (
        down < len(maze)
        and maze[down][x] in ["L", "J", "|"]
        and maze[y][x] in ["7", "F", "|"]
    ):
        tile_down = [down, x]
    if (
        left >= 0
        and maze[y][left] in ["L", "F", "-"]
        and maze[y][x] in ["7", "J", "-"]
    ):
        tile_left = [y, left]
    if (
        right < len(maze[0])
        and maze[y][right] in ["7", "J", "-"]
        and maze[y][x] in ["L", "F", "-"]
    ):
        tile_right = [y, right]

    next_coordinates = [
        [tile[0], tile[1]]
        for tile in [tile_up, tile_down, tile_left, tile_right]
        if tile and [tile[0], tile[1]] not in prevpos
    ][0]

    return next_coordinates

for y, line in enumerate(puzzle_input):
    start_index = line.find("S")
    if start_index > -1:
        start = [y, start_index]
        break

start_conns = start_connections(maze=puzzle_input, startpos=start)
visited_1.append(start_conns[0])
visited_2.append(start_conns[1])

while visited_1[-1] != visited_2[-1]:
    visited_1.append(
        next_connection(
            maze=puzzle_input, startpos=visited_1[-1], prevpos=visited_1
        )
    )
    visited_2.append(
        next_connection(
            maze=puzzle_input, startpos=visited_2[-1], prevpos=visited_2
        )
    )

solution = len(visited_1) if len(visited_1) == len(visited_2) else None
print_solution(solution=solution, y=year, d=day, part=1)


from fastapi import APIRouter
import model
from typing import Union
from data import Data

api_root = APIRouter()

@api_root.get("/book", response_model=Union[model.Response200, model.Response404])
async def book_description(book_id: str):
    response = Data.book(book_id)
    if response is not None:
        book_info = model.BookInfo(
            book_id=book_id,
            book_name=response.xpath(model.BookXpath.book_name)[0],
            author_name=response.xpath(model.BookXpath.author_name)[0],
            update_time=response.xpath(model.BookXpath.update_time)[0],
            update_chapter=response.xpath(model.BookXpath.update_chapter)[0],
            description=response.xpath(model.BookXpath.description)[0].replace(" ", ""),
            book_state=response.xpath(model.BookXpath.book_state)[0],
            cover_url="https://www.qu-la.com" + response.xpath(model.BookXpath.cover_url)[0],
            catalogue=[
                {"chapter_url": i.attrib['href'], "chapter_name": i.text} for i in
                response.xpath(model.BookXpath.catalogue)
            ]
        )
        return model.Response200(data=book_info.dict())
    return model.Response404(message="get book info failed, book_id is {}".format(book_id))

@api_root.get("/search", response_model=Union[model.Response200, model.Response404])
async def search_api(keyword: str):
    response = Data.search(keyword)
    if response is not None:
        search_result = []
        for index, data in enumerate(response.xpath(model.BookXpath.search_result), start=1):
            search_result.append({
                'index': index,
                'book_name': data.text,
                'book_url': data.attrib['href'].replace('booktxt', '').replace('/', ''),
            })
        return model.Response200(data=model.Search(search_result=search_result).dict())
    return model.Response404(message="search failed, keyword is {}".format(keyword))

@api_root.get("/chapter", response_model=Union[model.Response200, model.Response404])
async def content_api(book_id: Union[str, int] = 0, chapter_id: Union[str, int] = 0):
    if book_id == 0 or chapter_id == 0:
        return model.Response404(message="missing book_id or chapter_id")
    response = Data.chapter(book_id, chapter_id)
    if response is not None:
        chapter_info = model.Chapter(
            chapter_title=response.xpath(model.BookXpath.chapter_title)[0].strip(),
            content='\n'.join(response.xpath(model.BookXpath.content)).replace('\r', '\n')
        )
        return model.Response200(data=chapter_info.dict())
    return model.Response404(message="get chapter info failed, chapter_id is {}".format(chapter_id))

@api_root.get("/rank", response_model=Union[model.Response200, model.Response404])
async def rank_api(page: int, rank_type: model.Rank):
    rank_result = []
    if rank_type == model.Rank.day:
        response = Data.rank(page, model.Rank.day)
    elif rank_type == model.Rank.week:
        response = Data.rank(page, model.Rank.week)
    elif rank_type == model.Rank.month:
        response = Data.rank(page, model.Rank.month)
    elif rank_type == model.Rank.total:
        response = Data.rank(page, model.Rank.total)
    else:
        return model.Response404(message="rank_type error")

    if not response:
        return model.Response404(message="rank failed, page is {}".format(page))
    for index, data in enumerate(response.xpath(model.BookXpath.rank_result), start=1):
        rank_result.append({
            'index': index,
            'type': rank_type,
            'page': page,
            'book_name': data.text,
            'book_id': data.attrib['href'].replace('booktxt', '').replace('/', ''),
        })
    return model.Response200(data=model.Search(search_result=rank_result).dict())

@api_root.get("/class", response_model=Union[model.Response200, model.Response404])
async def class_api(page: int, class_type: model.BookClass):
    class_result = []
    if class_type == model.BookClass.xh:
        response = Data.book_class(page, model.BookClass.xh)
    elif class_type == model.BookClass.wy:
        response = Data.book_class(page, model.BookClass.wy)
    elif class_type == model.BookClass.cy:
        response = Data.book_class(page, model.BookClass.cy)
    elif class_type == model.BookClass.kh:
        response = Data.book_class(page, model.BookClass.kh)
    elif class_type == model.BookClass.finish:
        response = Data.book_class(page, model.BookClass.finish)
    elif class_type == model.BookClass.qt:
        response = Data.book_class(page, model.BookClass.qt)
    elif class_type == model.BookClass.ds:
        response = Data.book_class(page, model.BookClass.ds)
    elif class_type == model.BookClass.xj:
        response = Data.book_class(page, model.BookClass.xj)
    else:
        return model.Response404(message="class_type error")
    if not response is not None:
        return model.Response404(message="class failed, page is {}".format(page))
    for index, data in enumerate(response.xpath(model.BookXpath.class_result), start=1):
        class_result.append({
            'index': index,
            'type': class_type,
            'page': page,
            'book_name': data.text,
            'book_id': data.attrib['href'].replace('booktxt', '').replace('/', ''),
        })
    return model.Response200(data=model.Search(search_result=class_result).dict())


from flask_restful import Api, Resource, reqparse

class HelloApiHandler(Resource):
    def get(self):
        return {
            'resultStatus': 'SUCCESS',
            'message' : 'Hello Api Handler'
        }

    def post(self):
        print(self)
        parser = reqparse.RequestParser()
        parser.add_Argument('type', type=str)
        parser.add_argument('message', type=str)

        args = parser.aprse_args()

        print(args)

        request_type = args['type']
        request_json = args['message']

        ret_status = request_type
        ret_msg = request_json

        if ret_msg:
            message = "Your Message Requested: {}".format(ret_msg)
        else:
            message = "no Msg"

        final_ret = {"status": "Success", "message": message}

        return final_ret


put = input('input: ')
put_list = put.split(' ')

row = int(put_list[0])
col = int(put_list[1])

line = ''

for i in range(0, row) :
    for j in range(0, col) :
        if (i+j)%2 == 0 :
            line = line + '. '
        else :
            line = line + '* '
    line = ''


#Author: Ayan Noorani
#Date: Nov 9 2021
#Purpose: Create a date class which will allow entry and output of a date and print a calendar for the month and year.

from tkinter import *
import math
from tkinter import messagebox

#Purpose: A Date
#Data Elements:
#   Day: 1-31
#   Month: 1-12
#   Year: 1600-2200
#Method:
#   init
#   returnMonthName
#   returnLeapYear
#   returnMaxDay
#   calcZeller
#   returnDayName
#   getPositiveInteger
#   getDate
#   str
#=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class Date:

    def __init__(self): #formally a constructor
        self.intDay = 1
        self.intMonth = 1
        self.intYear = 2019

    #Purpose: to convert the month number into the name
    #Parameters: N/A
    #Return/Output: string conversion
    def returnMonthName(self, intmonth):
        if intmonth == 1:
            mname = "January"
        elif intmonth == 2:
            mname = "Feburary"
        elif intmonth == 3:
            mname = "March"
        elif self.intMonth == 4:
            mname = "April"
        elif intmonth == 5:
            mname = "May"
        elif intmonth == 6:
            mname = "June"
        elif intmonth == 7:
            mname = "July"
        elif intmonth == 8:
            mname = "August"
        elif intmonth == 9:
            mname = "September"
        elif intmonth == 10:
            mname =  "October"
        elif intmonth == 11:
            mname = "November"
        else:
            mname = "December"
        return mname

    #Purpose: to check if the year is a leap year or not
    #Parameters: N/A
    #Return/Output: Boolean True or False
    def returnLeapYear(self):
        if self.intYear % 100 != 0:
            nonCenturyYear = self.intYear
            if self.intYear % 400 == 0 or nonCenturyYear % 4 == 0:
                leapYear = True
                return leapYear
            else:
                leapYear = False
                return leapYear

    #Purpose: calculates the number of days in the month
    #Parameters: N/A
    #Return/Output: integer between 1 and 31
    def returnMaxDay(self, month):
        maxDay = 0
        if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
            maxDay = 31
        elif month == 4 or month == 6 or month == 9 or month == 11:
            maxDay = 30
        else:
            if self.returnLeapYear() == True:
                maxDay = 29
            else:
                maxDay = 28
        return maxDay

    #Purpose: to calculate the zeller of the date
    #Parameters: N/A
    #Return/Output: integer between 0 and 6
    def calcZeller(self, day, month, year):
        m = month - 2
        y = year
        if m <= 0:
            m = m + 12
            y = y - 1
        p = y // 100
        r = y % 100
        return (day + (26 * m - 2) // 10 + r + r // 4 + p // 4 + 5 * p) % 7

    #Purpose: to convert the zeller number into the day name
    #Parameters: N/A
    #Return/Output: string conversion
    def returnDayName(self):
        switcher = {
            0: "Sunday",
            1: "Monday",
            2: "Tuesday",
            3: "Wednesday",
            4: "Thursday",
            5: "Friday",
            6: "Saturday",
        }
        return switcher.get(self.calcZeller(self.intDay, self.intMonth, self.intYear))

    #Purpose: check if the date inputted is valid
    #Parameters: N/A
    #Return/Output: Boolean True or False
    def calcValid(self):
        if self.intDay < 1 or self.intDay > self.returnMaxDay(self.intMonth):
            return False
            self.intDay = 1
            self.intMonth = 1
            self.intYear = 2019
        if self.intMonth < 1 or self.intMonth > 12:
            return False
            self.intDay = 1
            self.intMonth = 1
            self.intYear = 2019
        if self.intYear < 1600 or self.intYear > 2200:
            return False
            self.intDay = 1
            self.intMonth = 1
            self.intYear = 2019
        return True

    #Purpose: get a positive integer from the user
    #Parameters: low, high, prompt
    #Return/Output: a date in three outputs
    def getPositiveInteger (self, low, high, prompt):
        inputprompt = "Please enter the " + prompt + " in the range (" + str(low) + " - " + str(high) + "): "
        n = 0
        while n < 1 or n < low or n > high:
            n = int(input(inputprompt))
        return n

    #Purpose: calls getpositiveinteger and provides the range, then stores the numbers inputted into variables
    #Parameters: N/A
    #Return/Output: N/A
    def getDate(self):
        self.intDay = self.getPositiveInteger(1, 31, "day")
        self.intMonth = self.getPositiveInteger(1, 12, "month")
        self.intYear = self.getPositiveInteger(1600, 2200, "year")

    #Purpose: print the date in form “Thursday, March 30, 2020"
    #Parameters: N/A
    #Return/Output: the date
    def __str__(self):
        str1 = "\n" + self.returnDayName() + ", " + self.returnMonthName(self.intMonth) + " " + str(self.intDay) + ", " + str(self.intYear)
        return str1

    #Purpose: to display the calendar
    #Parameters: N/A
    #Return/Output: a calendar of the month with the month name and year on top
    def displayCalendar(self):
        disCal= ""
        zeller = self.calcZeller(1, self.intMonth, self.intYear)
        #print("\n      " + self.returnMonthName(), self.intYear)
        disCal = disCal + "\n           " + self.returnMonthName(self.intMonth) + '  ' + str(self.intYear) + '\n'
        space = ""
        space = space.rjust(4, " ")
        #print('Su', space, 'Mo', space, 'Tu', space, 'We', space, 'Th', space, 'Fr',space, 'Sa')
        disCal = disCal + 'Su' + space + 'Mo' + space + 'Tu' + space + 'We' + space + 'Th' + space + 'Fr' + space + 'Sa' + '\n'
        #print(self.calcZeller(1, self.intMonth, self.intYear))
        firstDay = 0
        space = space.rjust(5, " ")
        space1 = space.rjust(1, " ")
        space2 = space.rjust(9, " ")
        for i in range(7):
            if i<zeller:
                #print(space1, end="")
                disCal += space2
            else:
                firstDay += 1
                tmp = firstDay
                firstDay = "0" + str(firstDay)
                #print(firstDay, space, end="")
                disCal += firstDay + space1
                firstDay = tmp
        if self.returnLeapYear() == True and self.intMonth == 2:
            daysLeft = (self.returnMaxDay(self.intMonth)-firstDay)//7
        else:
            daysLeft = (self.returnMaxDay(self.intMonth)-firstDay)//7 +1
        for i in range(daysLeft):
            #print(" ")
            disCal += "\n"
            for j in range(7):
                firstDay += 1
                if firstDay<10:
                    tmp = firstDay
                    firstDay = "0" + str(firstDay)
                    #print(firstDay, space, end="")
                    disCal += firstDay + space
                    firstDay = tmp
                else:
                    #print(firstDay, space, end="")
                    disCal += str(firstDay) + space
                if firstDay == self.returnMaxDay(self.intMonth):
                    break
        return disCal

    def dayOfYear(self):
        monthCount = 1
        dayOfYear = 0
        while monthCount < self.intMonth:
            dayOfYear += self.returnMaxDay(monthCount)
            monthCount += 1
        dayOfYear += self.intDay
        imSoSickAndTiredOfMakingNewVariableNamesThereAreLikeAThousandVariablesInThisCodeImRunningOutOfIdeas = "\n \nThe day of the year is " + str(dayOfYear)
        return imSoSickAndTiredOfMakingNewVariableNamesThereAreLikeAThousandVariablesInThisCodeImRunningOutOfIdeas

#GUI===========================================================================================================================================================================

root = Tk()

date = Date()

century = StringVar()
decade = StringVar()
year = StringVar()
month = StringVar()
calendar = StringVar()
dayEnt = StringVar()
monthEnt = StringVar()
yearEnt = StringVar()
fullDate = StringVar()
dayOfYear = StringVar()

def getRoundedYears(yearVal, roundFactor):
    yearVal = yearVal/roundFactor
    yearVal = math.floor(yearVal)
    yearVal = yearVal * roundFactor
    return yearVal

def createDate():
    newDate= Date()
    newDate.intDay = int(dayEnt.get())
    newDate.intMonth = int(monthEnt.get())
    newDate.intYear = int(yearEnt.get())
    if newDate.calcValid() == False:
        var = messagebox.showerror("Error", "Invalid Input")
    else:
        date.intDay = int(dayEnt.get())
        date.intMonth = int(monthEnt.get())
        date.intYear = int(yearEnt.get())
        century.set(getRoundedYears(date.intYear, 100))
        decade.set(getRoundedYears(date.intYear, 10))
        year.set(date.intYear)
        month.set(date.returnMonthName(date.intMonth))
        calendar.set(date.displayCalendar())
        fullDate.set(date.__str__())
        dayOfYear.set(date.dayOfYear())

def centbtn(change):
    if change == 'up':
        date.intYear += 100
        decade.set(getRoundedYears(date.intYear, 10))
        year.set(date.intYear)
        if date.intYear > 2100:
            centupbtn['state'] = DISABLED
        if date.intYear >= 1700:
            centdwnbtn['state'] = NORMAL
        century.set(getRoundedYears(date.intYear, 100))
    else:
        date.intYear -= 100
        decade.set(getRoundedYears(date.intYear, 10))
        year.set(date.intYear)
        if date.intYear <= 2100:
            centupbtn['state'] = NORMAL
        if date.intYear < 1700:
            centdwnbtn['state'] = DISABLED
        century.set(getRoundedYears(date.intYear, 100))
    calendar.set(date.displayCalendar())
    yearEnt.set(date.intYear)
    dayOfYear.set(date.dayOfYear())

def decbtn(change):
    if change == 'up':
        date.intYear += 10
        if date.intYear > 2190:
            decupbtn['state'] = DISABLED
        if date.intYear >= 1610:
            decdwnbtn['state'] = NORMAL
        year.set(date.intYear)
        decade.set(getRoundedYears(date.intYear, 10))
    else:
        date.intYear -= 10
        if date.intYear < 2190:
            centupbtn['state'] = NORMAL
        if date.intYear < 1610:
            centdwnbtn['state'] = DISABLED
        year.set(date.intYear)
        decade.set(getRoundedYears(date.intYear, 10))
    calendar.set(date.displayCalendar())
    yearEnt.set(date.intYear)
    dayOfYear.set(date.dayOfYear())

def yearbtn(change):
    if change == 'up':
        date.intYear += 1
        if date.intYear == 2200:
            yearupbtn['state'] = DISABLED
        if date.intYear == 1601:
            yeardwnbtn['state'] = NORMAL
        year.set(date.intYear)
    else:
        date.intYear -= 1
        if date.intYear == 2199:
            yearupbtn['state'] = NORMAL
        if date.intYear == 1600:
            yeardwnbtn['state'] = DISABLED
        year.set(date.intYear)
    calendar.set(date.displayCalendar())
    yearEnt.set(date.intYear)
    dayOfYear.set(date.dayOfYear())

def monthbtn(change):
    if change == 'up':
        date.intMonth+=1
        if date.intMonth == 13:
            date.intMonth=1
        month.set(date.returnMonthName(date.intMonth))
    else:
        date.intMonth-=1
        if date.intMonth == 0:
            date.intMonth=12
        month.set(date.returnMonthName(date.intMonth))
    calendar.set(date.displayCalendar())
    monthEnt.set(date.intMonth)
    dayOfYear.set(date.dayOfYear())

#main======================================================================================================================
daylbl = Label(root, text="Please enter the day")
monthlbl = Label(root, text="Please enter the month")
yearlbl = Label(root, text="Please enter the year")
dayEntr = Entry(root,textvariable=dayEnt)
monthEntr = Entry(root,textvariable=monthEnt)
yearEntr = Entry(root,textvariable=yearEnt)

centdwnbtn = Button(root, text = '<', command=lambda:centbtn('down'))
centupbtn = Button(root, text= '>', command=lambda:centbtn('up'))
decdwnbtn = Button(root, text= '<', command=lambda:decbtn('down'))
decupbtn = Button(root, text= '>', command=lambda:decbtn('up'))
yeardwnbtn = Button(root, text= '<', command=lambda:yearbtn('down'))
yearupbtn = Button(root, text='>', command=lambda:yearbtn('up'))
monthdwnbtn = Button(root, text= '<', command=lambda:monthbtn('down'))
monthupbtn = Button(root, text='>', command=lambda:monthbtn('up'))

createbtn = Button(root, text = 'Display Date', command = lambda:createDate())

centurylbl = Label(root, textvariable = century)
decadelbl = Label(root, textvariable = decade)
yearlbl1 = Label(root, textvariable = year)
monthlbl1 = Label(root, textvariable = month)
fullDatelbl = Label(root, textvariable = fullDate)
calendarlbl = Label(root, textvariable = calendar, justify=LEFT)
dayOfYearlbl = Label(root, textvariable = dayOfYear)

daylbl.grid(row=1, sticky=W)
dayEntr.grid(column=1, row=1)
monthlbl.grid(row=2, sticky=W)
monthEntr.grid(column=1, row=2)
yearlbl.grid(row=3, sticky=W)
yearEntr.grid(column=1, row=3)

createbtn.grid(row=4, columnspan=2)
centurylbl.grid(row=5, columnspan=2)
decadelbl.grid(row=6, columnspan=2)
fullDatelbl.grid(row=10, columnspan=2)
calendarlbl.grid(row=11, columnspan=2)
dayOfYearlbl.grid(row=12, columnspan=2)
centdwnbtn.grid(row=5)
centupbtn.grid(column=1, row=5)
decdwnbtn.grid(row=6)
decupbtn.grid(column=1, row=6)
yeardwnbtn.grid(row=8)
yearupbtn.grid(column=1, row=8)
monthdwnbtn.grid(row=9)
monthupbtn.grid(column=1, row=9)
yearlbl1.grid(row=8, columnspan=2)
monthlbl1.grid(row=9, columnspan=2)

century.set(getRoundedYears(date.intYear, 100))
decade.set(getRoundedYears(date.intYear, 10))
year.set(date.intYear)
month.set(date.returnMonthName(date.intMonth))
fullDate.set(date.__str__())
calendar.set(date.displayCalendar())
dayOfYear.set(date.dayOfYear())

mainloop()


from setuptools import setup
from glob import glob

package_name = 'fitrobot'

setup(
    name=package_name,
    version='0.0.1',
    packages=[package_name],
    data_files=[
        ("share/ament_index/resource_index/packages", [f"resource/{package_name}"]),
        (f"share/{package_name}", ['package.xml']),
        (f"share/{package_name}/launch", glob("launch/*.launch.py")),
        (f"share/{package_name}/common", glob("common/*.py")),
        (f"share/{package_name}/script", glob("script/*.py")),
        (f"share/{package_name}/data", glob("data/*.json")),
        (f"share/{package_name}/maps", glob("maps/*")),
        (f"share/{package_name}/masks", glob("masks/*")),
    ],
    install_requires=['setuptools'],
    zip_safe=True,
    maintainer='ubuntu',
    maintainer_email='jason.kj.ke@fit-foxconn.com',
    description='TODO: Package description',
    license='TODO: License declaration',
    tests_require=['pytest'],
    entry_points={
        'console_scripts': [
            'tf_converter_node = fitrobot.tf_converter_node:main',
            'server_node = fitrobot.server_node:main',
            'bridge_node = fitrobot.bridge_node:main',
            'master_service = fitrobot.master_service:main',
            'save_map_service = fitrobot.save_map_service:main',
            'list_map_service = fitrobot.list_map_service:main',
            'waypoint_follower = fitrobot.waypoint_follower:main',
            'list_station_service = fitrobot.list_station_service:main',
            'nav2_params_loader = fitrobot.nav2_params_loader:main',
        ],
    },
)


# Infinite Loop
# i = 0
# while i < 50:
# print(i)

i = 0
while i < 50:
    print(i)
    # i = i + 1
    i += 1  # Shorthand
else:
    print("Done with all the work")
    # Here else is Optional.
    # Also, if it successfully runs, it indicates that while loop have finish the work perfectly

j = 0
while j < 50:
    print(j)
    # j = j + 1
    j += 1  # Shorthand
    break
else:
    print("Done with all the work")
    # Here else will not get executed because while loop has not completed his work 100%. While loop is forced to stop using break.

# Thus, Successfull execution of else ensures us that the while loop has completed it's 100% work.


import pandas as pd
import numpy as np
import scipy.stats as ss
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv("./data/HR.csv")
dp_indices = df.groupby(by="department").indices

sales_values = df["left"].iloc[dp_indices["sales"]].values
print(sales_values)

technical_values = df["left"].iloc[dp_indices["technical"]].values
print(technical_values)

print(ss.ttest_ind(sales_values, technical_values))

dp_keys = list(dp_indices.keys())
dp_t_mat = np.zeros((len(dp_keys), len(dp_keys)))
for i in range(len(dp_keys)):
    for j in range(len(dp_keys)):
        p_value = ss.ttest_ind(df["left"].iloc[dp_indices[dp_keys[i]]].values, \
                               df["left"].iloc[dp_indices[dp_keys[j]]].values)[1]
        if p_value < 0.05:
            dp_t_mat[i][j] = -1
        else:
            dp_t_mat[i][j] = p_value
sns.heatmap(dp_t_mat, xticklabels=dp_keys, yticklabels=dp_keys)
plt.show()

# 判断数据之间的关系

piv_tb = pd.pivot_table(df, values="left", index=["promotion_last_5years", "salary"], columns=["Work_accident"],
                        aggfunc=np.mean)

print(piv_tb)

sns.heatmap(piv_tb, vmax=1, vmin=0, cmap=sns.color_palette("Reds", n_colors=12))
plt.show()

# 分组分析


from services.note import NoteService
from models.note import OwnNoteSchema
from db import with_session

from flask_restful import Resource, marshal_with
from flask_jwt_extended import jwt_required
from flasgger import swag_from

specs_dict = {
    "tags": ["Note"],

    "operationId": "resolveNote",

    "summary": "Resolve note",

    "parameters": [
        {
            "in": "path",
            "name": "noteId",
            "schema": { "type": "integer" },
            "required": "true",
            "description": "Note to be resolved"
        },
    ],

    "responses": {
        "200": {
            "description": "Resolved note",
            "content": {
                "application/json": {
                    "schema": OwnNoteSchema.schemaSpecRef()
                }
            }
        }
    }
}

class NoteResolveResource(Resource):
    decorators = [jwt_required()]

    @swag_from(specs_dict)
    @with_session
    @marshal_with(OwnNoteSchema.marshaller())
    def put(self, session, noteId):
        notes = NoteService(session)
        return notes.resolve(noteId)


import logging
import pytz

from typing import Any
from datetime import datetime
from .shipstation_api_helper import ShipStationHelper
from odoo.addons.channel_base_sdk.utils.common import resource_formatter as common_formatter
from odoo.addons.channel_base_sdk.utils.common.exceptions import EmptyDataError

_logger = logging.getLogger(__name__)

class ShipStationOrderHelper:
    _api: ShipStationHelper

    def __init__(self, account):
        self._api = ShipStationHelper.connect_with_account(account)

    def cancel(self, id_on_shipstation):
        ack = self._api.orders.acknowledge(id_on_shipstation)
        ack._data._data = {'orderStatus': 'cancelled', 'orderId': id_on_shipstation}
        return ack.create_or_update_single_order()

class ShipStationOrderImporter:
    channel: Any
    ids: list
    from_date: datetime
    to_date: datetime
    limit: int
    all_records = False

    def do_import(self):
        params = self.prepare_common_params()
        yield from self.get_data(params)

    def prepare_common_params(self):
        res = dict(storeId=self.channel.shipstation_store_id)
        tz = pytz.timezone(self.channel.shipstation_account_id.tz or 'UTC')
        if self.from_date:
            now_tz = self.from_date.replace(tzinfo=pytz.utc).astimezone(tz)
            res['modifyDateStart'] = now_tz.isoformat()
        if self.to_date:
            now_tz = self.to_date.replace(tzinfo=pytz.utc).astimezone(tz)
            res['modifyDateEnd'] = now_tz.isoformat()
        return res

    def get_data(self, kw):
        try:
            res = self.get_first_data(kw)
            yield res
            yield from self.get_next_data(res)
        except Exception as ex:
            _logger.exception("Error while getting order: %s", str(ex))
            raise

    def get_first_data(self, kw):
        api = ShipStationHelper.connect_with_account(self.channel.shipstation_account_id)
        if self.ids:
            vals = []
            for id in self.ids:
                ack = api.orders.acknowledge(id.strip())
                try:
                    vals.append(ack.get_by_id().data)
                except EmptyDataError:
                    pass
            res = api.orders.create_collection_with(vals)
        else:
            if self.to_date:
                kw.update(modifyDateEnd=self.to_date.isoformat())
            res = api.orders.all(**kw)
        return res

    def get_next_data(self, res):
        try:
            while res.data:
                res = res.get_next_page()
                yield res
        except EmptyDataError:
            pass

class ShipStationOrderImportBuilder:
    orders: Any

    def prepare(self):
        if isinstance(self.orders, dict):
            self.orders = [self.orders]
        for order in self.orders:
            yield order


# -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 11:39:37 2019

@author: 10904
"""

import numpy as np
import random
import matplotlib.pyplot as plt
#from GMM_Cluster import GMM_Cluster

class K_Means:
    def __init__(self):
        self.X = None
        self.Ave = None
        self.C = None
        self.Metric = None

    def train(self, data, k, metric='Euc', max_iter=1000):
        #input('K-Means Starting')
        if k > len(data):
            raise Exception('k均值聚类时，k的值超过了样本数量！'+'\n样本数: ' + str(len(data)) +
                            '\nk值: ' + str(k))
        #初始化模型
        #均值初始化为随机k个样本的值
        self.X = np.array(data)
        index = random.sample([i for i in range(self.X.shape[0])], k)
        self.Ave = np.array([self.X[i] for i in index])
        #indexes = [random.sample([i for i in range(self.X.shape[0])], 2*k) for i in range(k)]
        #self.Ave = np.array([np.sum(np.array([self.X[j] for j in indexes[i]]), axis=0)/2*k for i in range(k)
        #print(self.Ave.shape)
        loop = 0
        loop_ctrl = True
        while loop_ctrl and loop < max_iter:
            print(loop)
            loop_ctrl = True
            self.set_cluster(metric)
            for i,cluster in enumerate(self.C):
                total_x = np.zeros(self.X[0].shape)
                for c in cluster:
                    total_x += c
                if len(cluster) != 0:
                    new_ave = total_x/len(cluster)
                    #用于提前停止循环的条件，待优化
                    #loop_ctrl = loop_ctrl or np.sum(np.absolute(new_ave-self.Ave[i])) > 1e-20
                    self.Ave[i] = new_ave
            loop += 1
        self.set_cluster(metric)

    #将所有样本归到对应的簇中
    def set_cluster(self, metric):
        #print(self.Ave.shape)
        self.C = [[] for i in range(len(self.Ave))]
        for x in self.X:
            dist = []
            for i,ave in enumerate(self.Ave):
                dist.append(self.cal_dist(x, ave, metric))
            self.C[list.index(dist, min(dist))].append(x)

    def cal_dist(self, x1, x2, metric):
        if metric == 'Euc':
            return (np.sum((x1-x2)**2)**0.5)
        elif metric == 'Man':
            return np.sum(np.absolute(x1-x2))

if __name__ == '__main__':
    def get_data(x, y, r, num):
        data = []
        for i in range(num):
            theta = random.uniform(-2*np.pi, 2*np.pi)
            R = random.uniform(0,r)
            data.append([x+R*np.cos(theta), y+R*np.sin(theta)])
        return data

    model = K_Means()
    data = []
    data += get_data(-10,10,5,50)
    data += (get_data(0,-5,5,50))
    data += (get_data(10,10,5,50))
    #for i in range(num):
    #    x = random.uniform(-20,20)
    #    y = random.uniform(-20,20)
    #    data.append([x,y])

    model.train(data, k=3, metric='Man')
    clusters = []
    for c in model.C:
        clusters.append(c)
    ave = model.Ave
    #print(clusters)
    plt.xlim(-20,20)
    plt.ylim(-20,20)
    plt.plot([x[0] for x in clusters[0]], [x[1] for x in clusters[0]], 'o', color='red')
    plt.plot([x[0] for x in clusters[1]], [x[1] for x in clusters[1]], 'o', color='green')
    plt.plot([x[0] for x in clusters[2]], [x[1] for x in clusters[2]], 'o', color='blue')
    plt.plot([x[0] for x in ave], [x[1] for x in ave], 'x', color='black')
    print(ave)
    #plt.plot([x[0] for x in clusters[3]], [x[1] for x in clusters[3]], 'o', color='yellow')
    plt.show()


def bubblesort(a):
	for i in range(0,len(a)):
		for j in range(len(a)-1-i,len(a)-1):
			if a[j] > a[j+1]:
				a[j],a[j+1] = a[j+1],a[j]
	return a

def selectionsort(a):
	for i in range(0,len(a)):
		min = i
		for j in range(i+1,len(a)):
			if a[j] < a[min]:
				min = j
		if min != i:
			a[min],a[i] = a[i],a[min]
	return a

if __name__ == "__main__":
	a = [11,1,20,-4,33]
	#print('bubblesort:'+str(bubblesort(a)))
	print('selectionsort:'+str(selectionsort(a)))


"""Script for running transfer attack experiment."""

from __future__ import annotations

import timm

if not timm.__version__.startswith("0.6"):
    from timm.models import xcit

    xcit.XCiT = xcit.Xcit  # pylint: disable=no-member

# pylint: disable=wrong-import-order,wrong-import-position
import argparse
import copy
import logging
import sys
import time
from pathlib import Path
from typing import Any

from main import train_test_main
from src.attack.util import get_saved_adv_name
from src.models.util import ENSEMBLE_MODELS
from src.utils.argparser import get_args_parser, setup_output_dir
from src.utils.metric import safe_pickle
from src.utils.print_result import Aggregator, HiddenPrints, print_result

def _new_config(
    orig_config: dict[str, Any], model: str
) -> tuple[dict[str, Any], Path]:
    new_config = copy.deepcopy(orig_config)
    # "model" format is DATASET_ARCH_TRAIN_SEED
    # ARCH can be
    #   - single model: resnet18
    #   - ensemble: trs_resnet18+resnet50
    #   - ensemble with freeze: trs_freeze_resnet18+resnet50

    ensemble_type = None
    mod_model = model
    for ens in ENSEMBLE_MODELS:
        if f"_{ens}_" in model:
            mod_model = mod_model.replace(f"_{ens}_", "_")
            ensemble_type = ens
            break

    if ensemble_type is not None and "_freeze_" in model:
        # Handle freeze option
        mod_model = mod_model.replace("_freeze_", "_")
        ensemble_type = None

    new_config["ensemble_type"] = ensemble_type
    new_config["arch"] = mod_model.split("_")[1].split("+")
    if ensemble_type is None:
        new_config["arch"] = [new_config["arch"][0]]
    new_config["output_dir"] = f"results/{model}"
    new_config["evaluate"] = True
    output_path = setup_output_dir(new_config)
    return new_config, output_path

def main() -> None:
    """Main function."""
    source_models = config["src_models"]
    target_models = config["tgt_models"]
    attacks = config["transfer_attacks"]
    if not source_models:
        raise ValueError("No source models specified via --src-models.")
    if not target_models:
        raise ValueError("No target models specified via --tgt-models.")
    if not attacks:
        raise ValueError("No attacks specified via --transfer-attacks.")
    config["src_models"] = None
    config["tgt_models"] = None
    config["transfer_attacks"] = None
    run_exp(config, source_models, target_models, attacks)

def run_exp(
    config,  # pylint: disable=redefined-outer-name
    source_models,
    target_models,
    attacks,
) -> None:
    """Run transfer experiments for multiple sources, targets, and attacks.

    WARNING: metrics["idx_correct"] returned from train_test_main() should have
    a fixed length (= num test samples), but there is no guarantee that the
    order of the samples remained the same across runs. We fix random seed in
    all the scripts so the ordering should be correct when run in the same
    environment (same package version and machine), but beyond that is unclear.
    """
    results = {}

    for _, tgt in enumerate(target_models):
        aggregator = Aggregator()
        results[tgt] = {}
        tgt_config, tgt_path = _new_config(config, tgt)

        for src in source_models:
            results[tgt][src] = {}
            src_config, src_path = _new_config(config, src)

            for attack in attacks:
                print(f"{src} -> {tgt} using {attack} attack.")

                if (
                    (attack == "naa" and "robustbench-diffenderfer21" in src)
                    or (attack == "naa" and "imagenet_timm-vgg-11" in src)
                ):
                    print(f"[WARNING] Skipping {attack} on {src}")
                    continue

                start_time = time.time()
                saved_adv_path = src_path / get_saved_adv_name(
                    src_config, attack=attack, partition="test"
                )
                # Check if attack has been generated
                if not saved_adv_path.is_dir():
                    raise NotADirectoryError(
                        f"Given path {saved_adv_path} does not exist or is not "
                        "a directory."
                    )
                if not any(saved_adv_path.iterdir()):
                    raise FileNotFoundError(
                        f"No file found in {saved_adv_path}."
                    )
                # Get full attack name
                adv_name = saved_adv_path.name.replace("saved_", "")

                print("  Evaluating...")
                tgt_config["temperature"] = 1.0  # Reset eval temperature to 1
                tgt_config["test_load_paths"] = [str(saved_adv_path)]
                # Need to set train_load_paths because dataloader requires it
                tgt_config["train_load_paths"] = [str(saved_adv_path)]
                with HiddenPrints(not config["debug"]):
                    metrics = train_test_main(copy.deepcopy(tgt_config))
                # TODO(enhance): Collect metrics from last dataset assuming that
                # it is the adversarial one. Perhaps we can clean this up a bit.
                metrics = metrics["test"][-1]
                elapsed_time = (time.time() - start_time) / 60
                print(
                    f'  accuracy: {metrics["acc0"]:.2f}, time: '
                    f"{elapsed_time:.1f} min",
                    flush=True,
                )

                # Collect successes for best attack across sources and atk algo
                idx_success = ~metrics["idx_correct"]
                aggregator.update((src, attack), idx_success)
                results[tgt][src][adv_name] = idx_success

                # Dump all results after every run
                safe_pickle("results/all_results.pkl", obj=results, load=False)

                # Dump target-specific results
                tgt_result_path = tgt_path / "results.pkl"
                if tgt_result_path.exists():
                    # If results already exist, append to it
                    tgt_results = safe_pickle(tgt_result_path, load=True)
                    if src not in tgt_results:
                        tgt_results[src] = {}
                    tgt_results[src][adv_name] = idx_success
                else:
                    tgt_results = {src: {adv_name: idx_success}}
                safe_pickle(tgt_result_path, obj=tgt_results, load=False)

        print(f"Target: {tgt}")
        errs = print_result(attacks, source_models, aggregator)
        avg_acc, best_acc, overall_best_acc = [100 - err for err in errs]
        # metrics = safe_pickle(f"results/{tgt}/metrics.pkl", load=True)
        # The first metric should be from training
        # metrics = metrics[0]["test"][-1]
        # assert metrics["attack"] in ("none", "no_attack"), metrics
        # clean_acc = metrics["acc0"]
        clean_acc = tgt_results["test"]["none"]  # Gather new result with this line
        print(
            f"Accuracy (clean, avg, best, per-sample best): {clean_acc:.2f}, "
            f"{avg_acc:.2f}, {best_acc:.2f}, {overall_best_acc:.2f}"
        )

    safe_pickle("results/all_results.pkl", obj=results, load=False)
    print("Finished.")

if __name__ == "__main__":
    main_parser = argparse.ArgumentParser(
        "Run multiple transfer attacks across set of source and target models.",
        parents=[get_args_parser()],
    )
    main_parser.add_argument(
        "--tgt-models",
        default=None,
        nargs="+",
        type=str,
        help="List of target models used to evaluate against transfer attacks.",
    )
    args = main_parser.parse_args()
    config: dict[str, Any] = vars(args)

    # Set logging config
    logging.basicConfig(
        stream=sys.stdout,
        format="[%(asctime)s - %(name)s - %(levelname)s]: %(message)s",
        level=logging.DEBUG if args.debug else logging.INFO,
        force=True,
    )
    logging.getLogger("PIL").setLevel(logging.WARNING)

    main()


"""empty message

Revision ID: 9d2828aa95a0
Revises: 452e194acb07
Create Date: 2017-11-08 12:54:00.270559

"""

# revision identifiers, used by Alembic.
revision = '9d2828aa95a0'
down_revision = '452e194acb07'

from alembic import op
import sqlalchemy as sa

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('db_meta_data',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('version', sa.Integer(), nullable=True),
    sa.Column('description', sa.String(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('db_meta_data')
    # ### end Alembic commands ###


class Node:

  def __init__(self,init_data):
    self.data = init_data
    self.next = None

  def get_data(self):
    return self.data

  def get_next(self):
    return self.next

  def set_data(self,new_data):
    self.data = new_data

  def set_next(self,new_next):
    self.next = new_next

class UnorderedList(object):

  def __init__(self):
    self.head = None

  def is_empty(self):
    return self.head == None

  def add(self, item):
    temp = Node(item)
    temp.set_next(self.head)
    self.head = temp

  def size(self):
    current = self.head
    count = 0
    while current != None:
      count = count + 1
      current = current.get_next()
    return count

  def search(self,item):
    current = self.head
    found = False
    while current != None and not found:
      if current.get_data() == item:
        found = True
      else:
        current = current.get_next()
    return found

  def remove(self, item):
    current = self.head
    previous = None
    found = False

    while not found:
      if current.get_data() == item:
        found = True
      else:
        previous = current
        current = current.get_next()

    if previous == None: #jeśli usuwamy pierwszy element
      self.head = current.get_next()
    else:
      previous.set_next(current.get_next())

  def append(self, item):
    """
    Metoda dodająca element na koniec listy.
    Przyjmuje jako argument obiekt, który ma zostać dodany.
    Niczego nie zwraca.
    """

    current = self.head
    previous = None

    while current != None:
      previous = current
      current = current.get_next()
    if previous == current:
      self.add(item)
    else:
      temp = Node(item)
      temp.set_next(current)
      current = temp
      previous.set_next(current)

  def index(self, item):
    """
    Metoda podaje miejsce na liście,
    na którym znajduje się określony element -
    element pod self.head ma indeks 0.
    Przyjmuje jako argument element,
    którego pozycja ma zostać określona.
    Zwraca pozycję elementu na liście lub None w przypadku,
    gdy wskazanego elementu na liście nie ma.
    """
    if self.is_empty():
      return None
    ind = 0
    current = self.head
    while current != None:
      if current.get_data() == item:
        return ind
      current = current.get_next()
      ind += 1
    return None

  def insert(self, pos, item):
    """
    Metoda umieszcza na wskazanej pozycji zadany element.
    Przyjmuje jako argumenty pozycję,
    na której ma umiescić element oraz ten element.
    Niczego nie zwraca.
    Rzuca wyjątkiem IndexError w przypadku,
    gdy nie jest możliwe umieszczenie elementu
    na zadanej pozycji (np. na 5. miejsce w 3-elementowej liście).
    """
    if not pos:
      self.add(item)
    else:
      ind = 0
      current = self.head
      while current != None and ind < pos:
        previous = current
        current = current.get_next()
        ind += 1
      if ind != pos:
        raise IndexError
      else:
        temp = Node(item)
        temp.set_next(current)
        current = temp
        previous.set_next(current)

  def pop(self, pos=-1):
    """
    Metoda usuwa z listy element na zadaniej pozycji.
    Przyjmuje jako opcjonalny argument pozycję,
    z której ma zostać usunięty element.
    Jeśli pozycja nie zostanie podana,
    metoda usuwa (odłącza) ostatni element z listy.
    Zwraca wartość usuniętego elementu.
    Rzuca wyjątkiem IndexError w przypadku,
    gdy usunięcie elementu z danej pozycji jest niemożliwe.
    """
    if pos < 0:
      pos = self.size() - abs(pos)
    current = self.head
    previous = None
    ind = 0
    while current != None and ind < pos:
      previous = current
      current = current.get_next()
      ind += 1
    if ind - pos:
      raise IndexError
    else:
      if previous == None:
        self.head = current.get_next()
      else:
        previous.set_next(current.get_next())
      return current.get_data()

  def __str__(self):
    current = self.head
    li = []
    while current != None:
      li.append(current.get_data())
      current = current.get_next()
    s = "[" + ",".join(["{}"] * len(li)) + "]"
    return s.format(*li)

  def __repr__(self):
    current = self.head
    li = []
    while current != None:
      li.append(current.get_data())
      current = current.get_next()
    s = "[" + ",".join(["{}"] * len(li)) + "]"
    return s.format(*li)

class DequeueUsingUL(object):

  def __init__(self):
    self.items = UnorderedList()

  def is_empty(self):
    """
    Metoda sprawdzajacą, czy kolejka jest pusta.
    Nie pobiera argumentów.
    Zwraca True lub False.
    """
    return self.items.is_empty()

  def add_left(self, item):
    """
    Metoda dodaje element do kolejki z lewej strony.
    Pobiera jako argument element, który ma zostać dodany.
    Niczego nie zwraca.
    """
    self.items.add(item)

  def add_right(self, item):
    """
    Metoda dodaje element do kolejki z prawej strony.
    Pobiera jako argument element, który ma zostać dodany.
    Niczego nie zwraca.
    """
    self.items.append(item)

  def remove_left(self):
    """
    Metoda usuwa element z kolejki z lewej strony.
    Nie pobiera argumentów.
    Zwraca usuwany element.
    W przypadku pustej kolejku rzuca wyjątkiem IndexError
    """

    return self.items.pop(0)

  def remove_right(self):
    """
    Metoda usuwa element z kolejki z prawej strony.
    Nie pobiera argumentów.
    Zwraca usuwany element.
    W przypadku pustej kolejku rzuca wyjątkiem IndexError
    """

    return self.items.pop()

  def size(self):
    """
    Metoda zwraca liczę elementów na w kolejce.
    Nie pobiera argumentów.
    Zwraca liczbę elementów na w kolejce.
    """
    return self.items.size()

  def __str__(self):
    return str(self.items)

def main():
  deq = DequeueUsingUL()
  left = True
  for i in range(20):
    if left:
      deq.add_left(i + 1)
      left = False
      print("Added {} on left".format(i + 1))
    else:
      deq.add_right(i + 1)
      print("Added {} on right".format(i + 1))
      left = True

  print("Size: {}".format(deq.size()))
  print("Object: ", deq)
  treashold = deq.size() // 2
  while deq.size() > treashold:
    print("Removed from left: {}".format(deq.remove_left()))
  while not deq.is_empty():
    print("Removed from right: {}".format(deq.remove_right()))

if __name__ == "__main__":
  main()


def quickSort(arr, low, high):
    if low >= high:
        return
    start = low
    end = high

    mid = start + (end - start) // 2
    pivot = arr[mid]
    while start <= end:
        while arr[start] <= pivot:
            start += 1
        while arr[end] > pivot:
            end += 1
        if start <= end:
            arr[start], arr[end] = arr[end], arr[start]
            start += 1
            end -= 1

    print(arr)

arr = [5, 4, 3, 2, 1]
quickSort(arr, 0, len(arr) - 1)

# TC: o(NLOGN), WORST(O(n^2))


import os
import re

path = os.path.abspath("D:\\osu!\\Songs")
libs = os.listdir(path)

for lib in libs:
	for file in os.listdir(path + "\\" + lib):
		if file.endswith(".osu"):
			f = open(path + "\\" + lib + "\\" + file, encoding='utf-8')
			text = f.read()
			if int(re.search(r'Mode:\s([0-9])', text).group(1)) != 0:
				f.close()
				os.remove(path + "\\" + lib + "\\" + file)


#source: https://machinelearningmastery.com/compare-machine-learning-algorithms-python-scikit-learn/

# Compare Algorithms
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
# load dataset
dataframe = pd.read_csv('data.csv')
features = dataframe.iloc[:, :-1].values
labels = dataframe['RiskLevel']

array = dataframe.values
X = array[:,0:6]
Y = array[:,6]
# prepare configuration for cross validation test harness
seed = 7
# prepare models
models = []
models.append(('SVM', SVC()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('GNB', GaussianNB()))
models.append(('LR', LogisticRegression()))
models.append(('DT', DecisionTreeClassifier()))
models.append(('RF', RandomForestClassifier()))

# evaluate each model in turn
results = []
labels = []
scoring = 'accuracy'
for label, model in models:
    kfold = model_selection.KFold(n_splits=10)
    cv_results = model_selection.cross_val_score(model, X, Y, cv=kfold, scoring=scoring)
    results.append(cv_results)
    labels.append(label)
    msg = "%s: %f (%f)" % (label, cv_results.mean(), cv_results.std())
    print(msg)
# boxplot algorithm comparison
fig = plt.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(labels)
plt.show()


#!/usr/bin/env python3

age = int(input('Enter your age: '))
have_own_car = input('Do you own your car (y/n) ? ')

if age >= 21:
    if have_own_car == 'y':
        print('You are over 21 yeas old and own you car.')
    else:
        print('You are 21 years old and you do Not own your car.')
else:
    if have_own_car == 'y':
        print('You are yanger than 21 and you own your car.')
    else:
        print('You are yanger than 21 and you Do Not own your own car.')


import numpy as np
from . import packed_vectors

class LogicSim:
    def __init__(self, circuit, nvectors=1, vdim=1):
        self.circuit = circuit
        self.nvectors = nvectors
        nbytes = (nvectors - 1) // 8 + 1
        self.interface = list(circuit.interface) + [n for n in circuit.nodes if 'dff' in n.kind.lower()]
        self.state = np.zeros((len(circuit.lines), vdim, nbytes), dtype='uint8')
        self.state_epoch = np.zeros(len(circuit.nodes), dtype='int8') - 1
        self.tmp = np.zeros((5, vdim, nbytes), dtype='uint8')
        self.zero = np.zeros((vdim, nbytes), dtype='uint8')
        if vdim > 1:
            self.zero[1] = 255
        self.epoch = 0

        self.fork_vd1 = self.fork_vdx
        self.const0_vd1 = self.const0_vdx
        self.input_vd1 = self.fork_vd1
        self.output_vd1 = self.fork_vd1
        self.inv_vd1 = self.not_vd1
        self.nbuff_vd1 = self.fork_vd1
        self.xor2_vd1 = self.xor_vd1

        self.fork_vd2 = self.fork_vdx
        self.const0_vd2 = self.const0_vdx
        self.input_vd2 = self.fork_vd2
        self.output_vd2 = self.fork_vd2
        self.inv_vd2 = self.not_vd2
        self.nbuff_vd2 = self.fork_vd2
        self.xor2_vd2 = self.xor_vd2

        self.fork_vd3 = self.fork_vdx
        self.const0_vd3 = self.const0_vdx
        self.input_vd3 = self.fork_vd3
        self.output_vd3 = self.fork_vd3
        self.inv_vd3 = self.not_vd3
        self.nbuff_vd3 = self.fork_vd3
        self.xor2_vd3 = self.xor_vd3

        known_fct = [(f[:-4], getattr(self, f)) for f in dir(self) if f.endswith(f'_vd{vdim}')]
        self.node_fct = []
        for n in circuit.nodes:
            t = n.kind.lower().replace('__fork__', 'fork')
            t = t.replace('__const0__', 'const0')
            t = t.replace('__const1__', 'const1')
            t = t.replace('tieh', 'const1')
            # t = t.replace('xor', 'or').replace('xnor', 'nor')
            fcts = [f for n, f in known_fct if t.startswith(n)]
            if len(fcts) < 1:
                raise ValueError(f'Unknown node kind {n.kind}')
            self.node_fct.append(fcts[0])

    def assign(self, stimuli):
        if isinstance(stimuli, packed_vectors.PackedVectors):
            stimuli = stimuli.bits
        for (stim, node) in zip(stimuli, self.interface):
            if len(node.o) == 0: continue
            outputs = [self.state[line.index] if line else self.tmp[3] for line in node.o_lines]
            self.node_fct[node.index]([stim], outputs)
            for line in node.o_lines:
                if line:
                    self.state_epoch[line.reader.index] = self.epoch
        for n in self.circuit.nodes:
            if (n.kind == '__const1__') or (n.kind == '__const0__'):
                outputs = [self.state[line.index] if line else self.tmp[3] for line in n.o_lines]
                self.node_fct[n.index]([], outputs)
                # print('assign const')
                for line in n.o_lines:
                    if line:
                        self.state_epoch[line.reader.index] = self.epoch

    def capture(self, responses):
        if isinstance(responses, packed_vectors.PackedVectors):
            responses = responses.bits
        for (resp, node) in zip(responses, self.interface):
            if len(node.i) == 0: continue
            resp[...] = self.state[node.i_lines[0].index]

    def propagate(self):
        for node in self.circuit.topological_order():
            if self.state_epoch[node.index] != self.epoch: continue
            inputs = [self.state[line.index] if line else self.zero for line in node.i_lines]
            outputs = [self.state[line.index] if line else self.tmp[3] for line in node.o_lines]
            # print('sim', node)
            self.node_fct[node.index](inputs, outputs)
            for line in node.o_lines:
                self.state_epoch[line.reader.index] = self.epoch
        self.epoch = (self.epoch + 1) % 128

    @staticmethod
    def fork_vdx(inputs, outputs):
        for o in outputs: o[...] = inputs[0]

    def const0_vdx(self, _, outputs):
        for o in outputs: o[...] = self.zero

    # 2-valued simulation

    @staticmethod
    def not_vd1(inputs, outputs):
        outputs[0][0] = ~inputs[0][0]

    def const1_vd1(self, _, outputs):
        for o in outputs: o[...] = self.zero
        self.not_vd1(outputs, outputs)

    @staticmethod
    def and_vd1(inputs, outputs):
        o = outputs[0]
        o[0] = inputs[0][0]
        for i in inputs[1:]: o[0] &= i[0]

    @staticmethod
    def or_vd1(inputs, outputs):
        o = outputs[0]
        o[0] = inputs[0][0]
        for i in inputs[1:]: o[0] |= i[0]

    @staticmethod
    def xor_vd1(inputs, outputs):
        o = outputs[0]
        o[0] = inputs[0][0]
        for i in inputs[1:]: o[0] ^= i[0]

    @staticmethod
    def sdff_vd1(inputs, outputs):
        outputs[0][0] = inputs[0][0]
        if len(outputs) > 1:
            outputs[1][0] = ~inputs[0][0]

    @staticmethod
    def dff_vd1(inputs, outputs):
        outputs[0][0] = inputs[0][0]
        if len(outputs) > 1:
            outputs[1][0] = ~inputs[0][0]

    def nand_vd1(self, inputs, outputs):
        self.and_vd1(inputs, outputs)
        self.not_vd1(outputs, outputs)

    def nor_vd1(self, inputs, outputs):
        self.or_vd1(inputs, outputs)
        self.not_vd1(outputs, outputs)

    def xnor_vd1(self, inputs, outputs):
        self.xor_vd1(inputs, outputs)
        self.not_vd1(outputs, outputs)

    # 4-valued simulation
    # sym [0] [1] (value, care)
    #  0   0   1
    #  1   1   1
    #  -   0   0
    #  X   1   0

    @staticmethod
    def not_vd2(inputs, outputs):
        # 4-valued not:
        # i: 0 1 - X
        # o: 1 0 X X
        # o0 1 0 1 1
        # o1 1 1 0 0

        outputs[0][0] = ~inputs[0][0] | ~inputs[0][1]  # value = 0 or DC
        outputs[0][1] = inputs[0][1]  # care = C

    def and_vd2(self, inputs, outputs):
        # 4-valued:    o[0]:     o[1]:
        #    0 1 - X   0 1 - X   0 1 - X
        # 0  0 0 0 0   0 0 0 0   1 1 1 1
        # 1  0 1 X X   0 1 1 1   1 1 0 0
        # -  0 X X X   0 1 1 1   1 0 0 0
        # X  0 X X X   0 1 1 1   1 0 0 0

        i = inputs[0]
        any0 = self.tmp[0]
        anyd = self.tmp[1]
        any0[0] = ~i[0] & i[1]
        anyd[0] = ~i[1]
        for i in inputs[1:]:
            any0[0] |= ~i[0] & i[1]
            anyd[0] |= ~i[1]
        o = outputs[0]
        o[0] = ~any0[0]  # value = no0
        o[1] = any0[0] | ~anyd[0]  # care = any0 or noDC

    def or_vd2(self, inputs, outputs):
        # 4-valued:    o[0]:     o[1]:
        #    0 1 - X   0 1 - X   0 1 - X
        # 0  0 1 X X   0 1 1 1   1 1 0 0
        # 1  1 1 1 1   1 1 1 1   1 1 1 1
        # -  X 1 X X   1 1 1 1   0 1 0 0
        # X  X 1 X X   1 1 1 1   0 1 0 0

        i = inputs[0]
        any1 = self.tmp[0]
        anyd = self.tmp[1]
        any1[0] = i[0] & i[1]
        anyd[0] = ~i[1]
        for i in inputs[1:]:
            any1[0] |= i[0] & i[1]
            anyd[0] |= ~i[1]
        o = outputs[0]
        o[0] = any1[0] | anyd[0]  # value = any1 or anyDC
        o[1] = any1[0] | ~anyd[0]  # care = any1 or noDC

    def xor_vd2(self, inputs, outputs):
        # 4-valued:    o[0]:     o[1]:
        #    0 1 - X   0 1 - X   0 1 - X
        # 0  0 1 X X   0 1 1 1   1 1 0 0
        # 1  1 0 X X   1 0 1 1   1 1 0 0
        # -  X X X X   1 1 1 1   0 0 0 0
        # X  X X X X   1 1 1 1   0 0 0 0

        i = inputs[0]
        odd1 = self.tmp[0]
        anyd = self.tmp[1]
        odd1[0] = i[0] & i[1]
        anyd[0] = ~i[1]
        for i in inputs[1:]:
            odd1[0] ^= i[0] & i[1]
            anyd[0] |= ~i[1]
        o = outputs[0]
        o[0] = odd1[0] | anyd[0]  # value = odd1 or anyDC
        o[1] = ~anyd[0]  # care = noDC

    def sdff_vd2(self, inputs, outputs):
        self.dff_vd2(inputs, outputs)
        if len(outputs) > 1:
            outputs[1][0] = ~inputs[0][0] | ~inputs[0][1]  # value = 0 or DC
            outputs[1][1] = inputs[0][1]  # care = C

    @staticmethod
    def dff_vd2(inputs, outputs):
        outputs[0][0] = inputs[0][0] | ~inputs[0][1]  # value = 1 or DC
        outputs[0][1] = inputs[0][1]  # care = C

    def nand_vd2(self, inputs, outputs):
        self.and_vd2(inputs, outputs)
        self.not_vd2(outputs, outputs)

    def nor_vd2(self, inputs, outputs):
        self.or_vd2(inputs, outputs)
        self.not_vd2(outputs, outputs)

    def xnor_vd2(self, inputs, outputs):
        self.xor_vd2(inputs, outputs)
        self.not_vd2(outputs, outputs)

    def const1_vd2(self, _, outputs):
        for o in outputs: o[...] = self.zero
        self.not_vd2(outputs, outputs)

    # 8-valued simulation
    # sym [0] [1] [2] (initial value, ~final value, toggles present?)
    #  0   0   1   0
    #  1   1   0   0
    #  -   0   0   0
    #  X   1   1   0
    #  R   0   0   1  _/"
    #  F   1   1   1  "\_
    #  P   0   1   1  _/\_
    #  N   1   0   1  "\/"

    def not_vd3(self, inputs, outputs):
        # 8-valued not:
        # i: 0 1 - X R F P N
        # i0 0 1 0 1 0 1 0 1
        # i1 1 0 0 1 0 1 1 0
        # i2 0 0 0 0 1 1 1 1
        # o: 1 0 X X F R N P
        # o0 1 0 1 1 1 0 1 0
        # o1 0 1 1 1 1 0 0 1
        # o2 0 0 0 0 1 1 1 1
        i = inputs[0]
        dc = self.tmp[0]
        dc[0] = ~(i[0] ^ i[1]) & ~i[2]
        dc = self.tmp[0]
        outputs[0][0] = ~i[0] | dc[0]  # init.v = ~i0 or DC
        outputs[0][1] = ~i[1] | dc[0]  # init.v = ~i1 or DC
        outputs[0][2] = i[2]  # toggles = i2

    def and_vd3(self, inputs, outputs):
        # 8-valued:           o[0]:            o[1]:            o[2]:
        #    0 1 - X R F P N  0 1 - X R F P N  0 1 - X R F P N  0 1 - X R F P N
        # 0  0 0 0 0 0 0 0 0  0 0 0 0 0 0 0 0  1 1 1 1 1 1 1 1  0 0 0 0 0 0 0 0
        # 1  0 1 X X R F P N  0 1 1 1 0 1 0 1  1 0 1 1 0 1 1 0  0 0 0 0 1 1 1 1
        # -  0 X X X X X X X  0 1 1 1 1 1 1 1  1 1 1 1 1 1 1 1  0 0 0 0 0 0 0 0
        # X  0 X X X X X X X  0 1 1 1 1 1 1 1  1 1 1 1 1 1 1 1  0 0 0 0 0 0 0 0
        # R  0 R X X R R P R  0 0 1 1 0 0 0 0  1 0 1 1 0 0 1 0  0 1 0 0 1 1 1 1
        # F  0 F X X R F P F  0 1 1 1 0 1 0 1  1 1 1 1 0 1 1 1  0 1 0 0 1 1 1 1
        # P  0 P X X P P P P  0 0 1 1 0 0 0 0  1 1 1 1 1 1 1 1  0 1 0 0 1 1 1 1
        # N  0 N X X R F P N  0 1 1 1 0 1 0 1  1 0 1 1 0 1 1 0  0 1 0 0 1 1 1 1
        i = inputs[0]
        anyi0 = self.tmp[0]
        anyf0 = self.tmp[1]
        anyd = self.tmp[2]
        any0 = self.tmp[3]
        any_t = self.tmp[4]
        anyd[0] = ~(i[0] ^ i[1]) & ~i[2]
        anyi0[0] = ~i[0] & ~anyd[0]
        anyf0[0] = i[1] & ~anyd[0]
        any_t[0] = i[2]
        any0[0] = anyi0[0] & anyf0[0] & ~i[2]
        for i in inputs[1:]:
            dc = ~(i[0] ^ i[1]) & ~i[2]
            anyd[0] |= dc
            anyi0[0] |= ~i[0] & ~dc
            anyf0[0] |= i[1] & ~dc
            any_t[0] |= i[2]
            any0[0] |= ~i[0] & ~dc & i[1] & ~i[2]
        o = outputs[0]
        o[0] = (~anyi0[0] | anyd[0]) & ~any0[0]  # initial = no_i0 or DC
        o[1] = anyf0[0] | anyd[0]  # ~final = ~no_f0 or DC
        o[2] = any_t[0] & ~(anyd[0] | any0[0])  # toggle = anyT and noDC and no0

    def or_vd3(self, inputs, outputs):
        # 8-valued:           o[0]:            o[1]:            o[2]:
        #    0 1 - X R F P N  0 1 - X R F P N  0 1 - X R F P N  0 1 - X R F P N
        # 0  0 1 X X R F P N  0 1 1 1 0 1 0 1  1 0 1 1 0 1 1 0  0 0 0 0 1 1 1 1
        # 1  1 1 1 1 1 1 1 1  1 1 1 1 1 1 1 1  0 0 0 0 0 0 0 0  0 0 0 0 0 0 0 0
        # -  X 1 X X X X X X  1 1 1 1 1 1 1 1  1 0 1 1 1 1 1 1  0 0 0 0 0 0 0 0
        # X  X 1 X X X X X X  1 1 1 1 1 1 1 1  1 0 1 1 1 1 1 1  0 0 0 0 0 0 0 0
        # R  R 1 X X R N R R  0 1 1 1 0 1 0 0  0 0 1 1 0 0 0 0  1 0 0 0 1 1 1 1
        # F  F 1 X X N F F F  1 1 1 1 1 1 1 1  1 0 1 1 0 1 1 1  1 0 0 0 1 1 1 1
        # P  P 1 X X R F P N  0 1 1 1 0 1 0 1  1 0 1 1 0 1 1 0  1 0 0 0 1 1 1 1
        # N  N 1 X X R F N N  1 1 1 1 0 1 1 1  0 0 1 1 0 1 0 0  1 0 0 0 1 1 1 1
        i = inputs[0]
        anyi1 = self.tmp[0]
        anyf1 = self.tmp[1]
        anyd = self.tmp[2]
        any1 = self.tmp[3]
        any_t = self.tmp[4]
        anyd[0] = ~(i[0] ^ i[1]) & ~i[2]
        anyi1[0] = i[0] & ~anyd[0]
        anyf1[0] = ~i[1] & ~anyd[0]
        any_t[0] = i[2]
        any1[0] = (anyi1[0] & anyf1[0]) & ~i[2]
        for i in inputs[1:]:
            dc = ~(i[0] ^ i[1]) & ~i[2]
            anyd[0] |= dc
            anyi1[0] |= i[0] & ~dc
            anyf1[0] |= ~i[1] & ~dc
            any_t[0] |= i[2]
            any1[0] |= i[0] & ~dc & ~i[1] & ~i[2]
        o = outputs[0]
        o[0] = anyi1[0] | anyd[0]  # initial = i1 or DC
        o[1] = (~anyf1[0] | anyd[0]) & ~any1[0]  # ~final = f1 or DC
        o[2] = any_t[0] & ~(anyd[0] | any1[0])  # toggle = anyT and no(DC or 1)

    def xor_vd3(self, inputs, outputs):
        # 8-valued:           o[0]:            o[1]:            o[2]:
        #    0 1 - X R F P N  0 1 - X R F P N  0 1 - X R F P N  0 1 - X R F P N
        # 0  0 1 X X R F P N  0 1 1 1 0 1 0 1  1 0 1 1 0 1 1 0  0 0 0 0 1 1 1 1
        # 1  1 0 X X F R N P  1 0 1 1 1 0 1 0  0 1 1 1 1 0 0 1  0 0 0 0 1 1 1 1
        # -  X X X X X X X X  1 1 1 1 1 1 1 1  1 1 1 1 1 1 1 1  0 0 0 0 0 0 0 0
        # X  X X X X X X X X  1 1 1 1 1 1 1 1  1 1 1 1 1 1 1 1  0 0 0 0 0 0 0 0
        # R  R F X X P N R F  0 1 1 1 0 1 0 1  0 1 1 1 1 0 0 1  1 1 0 0 1 1 1 1
        # F  F R X X N P F R  1 0 1 1 1 0 1 0  1 0 1 1 0 1 1 0  1 1 0 0 1 1 1 1
        # P  P N X X R F P N  0 1 1 1 0 1 0 1  1 0 1 1 0 1 1 0  1 1 0 0 1 1 1 1
        # N  N P X X F R N P  1 0 1 1 1 0 1 0  0 1 1 1 1 0 0 1  1 1 0 0 1 1 1 1
        i = inputs[0]
        odd0 = self.tmp[0]
        odd1 = self.tmp[1]
        anyd = self.tmp[2]
        anyt = self.tmp[3]
        odd0[0] = i[0]
        odd1[0] = i[1]
        anyd[0] = ~(i[0] ^ i[1]) & ~i[2]
        anyt[0] = i[2]
        for i in inputs[1:]:
            odd0[0] ^= i[0]
            odd1[0] ^= i[1]
            anyd[0] |= ~(i[0] ^ i[1]) & ~i[2]
            anyt[0] |= i[2]
        o = outputs[0]
        o[0] = odd0[0] | anyd[0]
        o[1] = ~odd1[0] | anyd[0]
        o[2] = anyt[0] & ~anyd[0]

    def sdff_vd3(self, inputs, outputs):
        self.dff_vd3(inputs, outputs)
        if len(outputs) > 1:
            i = inputs[0]
            dc = self.tmp[0]
            dc[0] = ~(i[0] ^ i[1]) & ~i[2]
            outputs[1][0] = ~i[0] | dc[0]  # value = 1 or DC
            outputs[1][1] = ~i[1] | dc[0]  # value = 1 or DC
            outputs[1][2] = i[2]  # toggle = T

    def dff_vd3(self, inputs, outputs):
        i = inputs[0]
        dc = self.tmp[0]
        dc[0] = ~(i[0] ^ i[1]) & ~i[2]
        outputs[0][0] = i[0] | dc[0]  # value = 1 or DC
        outputs[0][1] = i[1] | dc[0]  # value = 1 or DC
        outputs[0][2] = i[2]  # toggle = T

    def nand_vd3(self, inputs, outputs):
        self.and_vd3(inputs, outputs)
        self.not_vd3(outputs, outputs)

    def nor_vd3(self, inputs, outputs):
        self.or_vd3(inputs, outputs)
        self.not_vd3(outputs, outputs)

    def xnor_vd3(self, inputs, outputs):
        self.xor_vd3(inputs, outputs)
        self.not_vd3(outputs, outputs)

    def const1_vd3(self, _, outputs):
        for o in outputs: o[...] = self.zero
        self.not_vd3(outputs, outputs)


import pandas as pd
import json
file_name = '/import/cogsci/ravi/datasets/Embeddia/STY_24sata_comments_hr_001.csv'

# file_name = '../../../data/unsup/24h/classify/cro_test.csv'

df = pd.read_csv(file_name)
df['length'] = df.content.str.len()

data = {}
data['max'] = int(df["length"].max())
data['min'] = int(df["length"].min())
data['mean'] = int(df["length"].mean())
data['mode'] = int(df["length"].mode())
data['median'] = int(df["length"].median())

gr_mean = len(df[df['length'] > data['mean']])
gr_mean2 = len(df[df['length'] > 2*data['mean']  ])
gr_mean1 = len(df[df['length'] > 1.5*data['mean']  ])

print(gr_mean)
print(type(gr_mean))
# print(gr_mean.values,type(gr_mean.values))

data['gr_mean'] = gr_mean
data['gr_mean1'] = gr_mean1
data['gr_mean2'] = gr_mean2

# print(df["length"].max(), df["length"].min(), df["length"].mean(),df["length"].mode(), df["length"].median())
# print(df['length'])

with open('dataLen.json','w') as fid:
    json.dump(data,fid)

print(data)
# print(df[df['length']==967].content.values)