import os
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

import config
from attributes_cleaner import NumAttributesCleaner
from attributes_cleaner import CatAttributesCleaner
from attributes_cleaner import CatAttributesEncoder

import joblib
import pandas as pd
import numpy as np

from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LinearRegression
from sklearn import metrics

def run(fold):
    df = pd.read_csv(config.AIRBNB_TRAIN_FOLDS_FILE).drop("id", axis=1)

    attribs = [f for f in df.columns if f not in ["price", "kfold"]]
    cat_attribs = ["zipcode",
                   "neighbourhood_cleansed",
                   "room_type",
                   "bed_type",
                   "cancellation_policy",
                   "security_deposit"]

    num_attribs = [f for f in attribs if f not in cat_attribs]

    df_train, df_valid = df[df.kfold != fold], df[df.kfold == fold]

    X_train, y_train = df_train[attribs].copy(), df_train["price"].copy()
    X_valid, y_valid = df_valid[attribs].copy(), df_valid["price"].copy()

    num_transformer = Pipeline([
        ("num_cleaner", NumAttributesCleaner(num_attribs)),
        ("std_scaler", StandardScaler())])

    cat_transformer = Pipeline([
        ("cat_cleaner", CatAttributesCleaner(cat_attribs)),
        ("cat_encoder", CatAttributesEncoder(cat_attribs))])

    transformer = ColumnTransformer([
        ("num", num_transformer, num_attribs),
        ("cat", cat_transformer, cat_attribs)])

    X_train_tr = transformer.fit_transform(X_train)
    X_valid_tr = transformer.transform(X_valid)

    model = LinearRegression()
    model.fit(X_train_tr, y_train)
    train_preds = model.predict(X_train_tr)
    valid_preds = model.predict(X_valid_tr)

    train_scores = {"r2_score": metrics.r2_score(y_train, train_preds),
                    "rmse_score": np.sqrt(metrics.mean_squared_error(y_train, train_preds))}

    valid_scores = {"r2_score": metrics.r2_score(y_valid, valid_preds),
                    "rmse_score": np.sqrt(metrics.mean_squared_error(y_valid, valid_preds))}

    print(f"Fold={fold} (train): ",
          f"r2_score = {train_scores['r2_score'].round(2)}", "--- ",
          f"rmse_score = {train_scores['rmse_score'].round(2)}")

    print(f"Fold={fold} (valid): ",
          f"r2_score = {valid_scores['r2_score'].round(2)}", "--- ",
          f"rmse_score = {valid_scores['rmse_score'].round(2)}")
    print("")
    joblib.dump(model, os.path.join(config.MODEL_OUTPUT, f"lr_{fold}.bin"))

if __name__ == "__main__":
    for fold in range(5):
        run(fold)


# kubectl_tool.py
# A langchain tool that use kubectl
#
from langchain.agents import Tool
from langchain.utilities import BashProcess
import json

def kubectl_tool(command) -> str:
    bash = BashProcess()
    result = bash.run(command)
    return result

name = "kubectl_tool"
description = "This is a tool for kubernetes cluster. The input is the kubectl command with jsonpath-as-json format, e.g. kubectl get pod --output=jsonpath-as-json={{.items..metadata.name}}  The output will be a JSON data structure."

# create an instance of the custom langchain tool
Kubectl = Tool(
    name=name,
    func=kubectl_tool,
    description=description,
    return_direct=False
)

if __name__ == '__main__':
    print(kubectl_tool("kubectl get pod"))


from datetime import date

from nominations.models import ArtNomination, VocalNomination

def base_context(request):
	start = False

	dte = date.today()
	dte_deadline = date(2023,10,13)
	register_block = True
	if dte<dte_deadline:
		register_block = False

	if not request.user.is_authenticated:
		start = True

	arts = ArtNomination.objects.all()
	vocals = VocalNomination.objects.all()

	args = {
		'start': start,
		'register_block': register_block,
		'arts': arts,
		'vocals': vocals
	}

	return args


"""
Clasa - este o "reteta" blueprint prin care noi cream obiecte.
Clasa contine urmatoarele elemente importante :
- numele clasei, unic, concis, sa intelegem ce fel de obiecte putem crea.
- contructor  = o functie speciala apelata ori de cate ori vrem sa cream un obiect,
    practic aici se face initializarea obiectului => __init__
- atribute =  variabile care apartin unui obiect, si care sunt descriptive pt toate obiectele din acea clasa.
- metode - functii care pot fi apelate pe acele obiecte

self = parametru care apare in toate metodele, si mentine o referinta catre obiectul curent

Obiectul este o instanta a unei clase de aceea zicem ca instantiem.

"""

class Person:  # numele de clase se incep cu litera mare, si folosesc CamelCase
    def __init__(self, name, age, gender, nationality='Ro'):
        # De obicei, in constructor, pastram valorile atributelor obiectului pe self
        self.name = name
        self.age = age
        self.gender = gender
        self.nationality = nationality

    def say_hi(self):
        print('Konnichiwa')
        print(f'Ma numesc {self.name}, am {self.age} ani si sunt {self.nationality}')

madalin = Person('Madalin', 24, 'M')
madalin.say_hi()
kevin = Person('Kevin', 27, 'M', 'FR')
kevin.say_hi()


# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, root):
        # write code here
        if root == 0:
            return 0
        if root == 1:
            return 1
        a0 = 0
        a1 = 1
        for i in range(2, root + 1):
            b = a0 + a1
            a0 = a1
            a1 = b
        return a1

s = Solution()
print(s.Fibonacci(9))


import re
from datetime import datetime, timedelta, timezone, tzinfo
from typing import Mapping, Match, Optional, Pattern, cast

__all__ = ['parse']

# Adapted from http://delete.me.uk/2005/03/iso8601.html
RE_ISO8601: Pattern = re.compile(  # noqa
    r'(?P<year>[0-9]{4})(-(?P<month>[0-9]{1,2})(-(?P<day>[0-9]{1,2})'
    r'((?P<separator>.)(?P<hour>[0-9]{2}):(?P<minute>[0-9]{2})'
    r'(:(?P<second>[0-9]{2})(\.(?P<microsecond>[0-9]+))?)?'
    r'(?P<timezone>Z|(([-+])([0-9]{2}).?([0-9]{2})))?)?)?)?')
RE_TIMEZONE: Pattern = re.compile(
    '(?P<prefix>[+-])(?P<hours>[0-9]{2}).?(?P<minutes>[0-9]{2})$')

class InvalidTZ(Exception):
    """Isoformat date does not have a valid timezone."""

def parse(datetime_string: str) -> datetime:
    """Parse and convert ISO 8601 string into a datetime object."""
    m = RE_ISO8601.match(datetime_string)
    if not m:
        raise ValueError(
            f'unable to parse date string {datetime_string!r}')
    groups = cast(Mapping[str, str], m.groupdict())
    return datetime(
        int(groups['year']),
        int(groups['month']),
        int(groups['day']),
        int(groups['hour'] or 0),
        int(groups['minute'] or 0),
        int(groups['second'] or 0),
        int(groups['microsecond'] or 0),
        parse_tz(groups['timezone']) if groups['timezone'] else None,
    )

def parse_tz(tz: str) -> tzinfo:
    if tz == 'Z':
        return timezone.utc
    match: Optional[Match] = RE_TIMEZONE.match(tz)
    if match is not None:
        prefix, hours, minutes = match.groups()
        return _apply_tz_prefix(prefix, int(hours), int(minutes))
    raise InvalidTZ(f'Missing or invalid timezone information: {tz!r}')

def _apply_tz_prefix(prefix: str, hours: int, minutes: int) -> tzinfo:
    if prefix == '-':
        hours = -hours
        minutes = -minutes
    return timezone(timedelta(minutes=(minutes + (hours * 60))))


#-*-coding:utf-8-*-
import os
import pdb
import urllib2

import requests
from bs4 import BeautifulSoup
from lxml import etree
from PIL import Image
from ZFCheckCode import recognizer, trainner

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
    'Referer': 'http://jwgl1.hbnu.edu.cn/(S(nxuiogv1kq4coqvvhltax145))/default2.aspx?'
}

baseurl = 'http://jwgl1.hbnu.edu.cn'
s=requests.Session()
html = s.get(baseurl, headers=headers, allow_redirects=False )
loc = html.headers['location']
loginurl = baseurl + loc
codeu = loginurl[0:54]
codeurl = codeu + '/CheckCode.aspx?'

# 获取验证码并自动识别
def checkcode():
    img=s.get(codeurl, stream=True, headers=headers)
    with open('checkcode.gif','wb') as f:
        f.write(img.content)
    trainner.update_model()
    code = recognizer.recognize_checkcode('/home/fty/new-system/checkcode.gif')
    #print(code)
    return code

def spider_login(id, passwd):
    #构造表单字典
    payload={'__VIEWSTATE':'',
        'txtUserName':'',
        'Textbox1':'',
        'TextBox2':'',
        'txtSecretCode':'',
        'RadioButtonList1':'',
        'Button1':'',
        'lbLanguage':'',
        'hidPdrs':'',
        'hidsc':'',
        '__EVENTVALIDATION':'',
        }

    #获取表单字典数据
    index = s.get(loginurl, headers=headers)
    soup = BeautifulSoup(index.content,'lxml')
    value1=soup.find('input',id='__VIEWSTATE')['value']
    value2=soup.find('input',id='__EVENTVALIDATION')['value']
    payload['txtUserName']=id
    payload['TextBox2']=passwd
    code = checkcode()
    payload['txtSecretCode']= code
    payload['RadioButtonList1']=u"学生".encode('gb2312','replace')
    payload['__VIEWSTATE']=value1
    payload['__EVENTVALIDATION']=value2
    payload['RadioButtonList1']= '%D1%A7%C9%FA'

    loginresponse = s.post(loginurl, data=payload, headers=headers)
    content = loginresponse.content.decode('gb2312')
    soup = BeautifulSoup(content, 'lxml')
    uname=soup.find('span', id='xhxm')
    xsxm =  uname.text

    # 返回学生姓名
    return xsxm

def getgrades(id, name):

    payload1={'__VIEWSTATE':'',
          'ddlXN':'',
          'ddlXQ':'' ,
          'Button1':'',
          '__EVENTVALIDATION':'',

}
    #url2 = spider_login(id, passwd)
    name = name[0:9]
    cname = urllib2.quote(name.encode('gb2312'))
    xingming = urllib2.quote(cname)

    req_url = codeu + '/xscj_gc.aspx?xh=' + str(id) + '&xm=' + xingming + '&gnmkdm=N121603'
    req2 = s.get(req_url, headers=headers)

    soup = BeautifulSoup(req2.content,'lxml')
    value3=soup.find('input',id='__VIEWSTATE')['value']
    value4=soup.find('input',id='__EVENTVALIDATION')['value']
    payload1['__VIEWSTATE']=value3
    payload1['__EVENTVALIDATION']=value4
    pos = s.post(req_url, data=payload1, headers=headers)
    grades = pos.content.decode('gbk')

    return grades

def parser(id, grades):

    # 根据HTML网页字符串创建BeautifulSoup
    soup = BeautifulSoup(
        grades,  # HTML文档字符串
        'html.parser',  # HTML解析器
    )

    tables = soup.findAll('table')
    filename = '/home/fty/new-system/templates/score/'+ str(id) +'.html'
    #filename = '/home/fty/new-system/templates/score/'+ id +'.html'
    with open(filename, 'w') as f:  # 如果filename不存在会自动创建， 'w'表示写数据，写之前会清空文件中的原有数据！
        tab = tables[0]
        list = [6, 10, 14, 16]
        f.write("{% extends 'student.html' %}")
        f.write('\n')
        f.write("{% block page_name %}成绩{% endblock %}")
        f.write('\n')
        f.write('{% block body_part2 %}')
        f.write('\n')
        f.write('
')
        for tr in tab.findAll('tr'):
            count = 0
            f.write('
')
            for td in tr.findAll('td'):
                count = count + 1
                if (count not in list):
                    f.write('')
                    f.write(' ')
                    f.write(td.getText().encode('utf-8'))
                    f.write('	')
            f.write('
')
            f.write('\n')
        f.write('
')
        f.write('\n')
        f.write('{% endblock %}')

'''a = raw_input('学号：')
b = raw_input('密码：')
name = '付同永同学'
'''
# 将unicode编码编码成utf8
#getname = spider_login(a, b).encode('utf8')
# 将utf8解码成unicode
#name = name.decode('utf8')


#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals

AUTHOR = u'H. Yi\u011fit G\xfcler'
AUTHOR_SMALL_AVATAR_URL = "/about/yigit_avatar.jpg"
SITENAME = u'Portu\xe7'
SITEURL = ''
STATIC_URL = '/'

TIMEZONE = 'Istanbul/Turkey'

DEFAULT_LANG = u'tr'

# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None

# Blogroll
LINKS = (
    ('Hipo', 'http://hipolabs.com/'),
)

# Social widget
SOCIAL = (
    ('Twitter', 'https://twitter.com/HYigitGuler/'),
)

DEFAULT_PAGINATION = 5

# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True

STATIC_PATHS = ['stylesheets', 'images', 'extra/CNAME', 'js']
EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}

GOOGLE_ANALYTICS = "UA-51361525-1"
TWITTER_USERNAME = "hyigitguler"
DISQUS_SITENAME = "portuc"
THEME = "themes/readable/"


import time
import threading

start = time.perf_counter()

def do_something():
    # print('Sleeping 1 second...')
    print('Sleeping 1 second...\n', end='')
    time.sleep(1)
    # print('Done sleeping...')
    print('Done sleeping...\n',end='')

"""
When using print in a multi-threaded environment, you can
end up switching threads between those two distinct steps;
threads 1, 2 and 3 can all end up writing the printed
message first, switch threads, and only after the other
thread has written their message is the newline written.

By adding \n to your message instead, you make sure that the
newline is written at the same time. You really are writing
two newlines to sys.stdout in that case.
"""
t1 = threading.Thread(target=do_something)
t2 = threading.Thread(target=do_something)

t1.start()
t2.start()

t1.join()
t2.join()

finish = time.perf_counter()

print(f'Finished in {round(finish - start, 2)} second(s)')


from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static

def trigger_error(request):
    division_by_zero = 1 / 0

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", TemplateView.as_view(template_name="main.html")),
    path("members/", include("members.urls")),
    path("leaves/", include("leaves.urls")),
    path("orders/", include("orders.urls")),
    path("grants/", include("grants.urls")),
    path("signs/", include("signs.urls")),
    path("push/", include("push.urls")),
    path('paul-sentry-debug/', trigger_error),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        path('__debug__/', include(debug_toolbar.urls))
    ]
    # 미디어 서빙(디버깅)
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)