from flask import Flask,render_template,request,url_for
import pandas as pd
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from nltk import pos_tag, word_tokenize
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import svm
from sklearn.metrics import confusion_matrix

data = pd.read_csv("spam2.csv", encoding = "latin-1")
data = data[['v1', 'v2']]
data = data.rename(columns = {'v1': 'label', 'v2': 'text'})

lemmatizer = WordNetLemmatizer()
stopwords = set(stopwords.words('english'))

def review_messages(msg):
    msg = msg.lower()

    return msg

def review_messages2(msg):

    msg=msg.lower()
    nltk_pos = [tag[1] for tag in pos_tag(word_tokenize(msg))]
    msg = [tag[0] for tag in pos_tag(word_tokenize(msg))]
    wnpos = ['a' if tag[0] == 'J' else tag[0].lower() if tag[0] in ['N', 'R', 'V'] else 'n' for tag in nltk_pos]
    msg = " ".join([lemmatizer.lemmatize(word, wnpos[i]) for i, word in enumerate(msg)])
    msg = [word for word in msg.split() if word not in stopwords]
    return msg
data['text'] = data['text'].apply(review_messages)
X_train, X_test, y_train, y_test = train_test_split(data['text'], data['label'], test_size = 0.27, random_state = 1)
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(X_train)
svm = svm.SVC(C=1000)
svm.fit(X_train, y_train)
X_test = vectorizer.transform(X_test)
y_pred = svm.predict(X_test)
print(confusion_matrix(y_test, y_pred))
def pred(msg):
    msg = vectorizer.transform([msg])
    prediction = svm.predict(msg)
    return prediction[0]
app=Flask(__name__)
@app.route('/',methods=['GET','POST'])
def func():
    if request.method=='POST':
        text=request.form['Description']
        res=pred(text)
        return render_template('base.html',msg=res)
    return render_template('base.html')
if __name__=='__main__':
    app.run(debug=True)


from typing import *

class Solution:
    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
        res = []
        path = [0]
        N = len(graph)

        def dfs(start):
            if start == N - 1:
                res.append(path[:])     # copy its value
                return
            for _next in graph[start]:
                path.append(_next)
                dfs(_next)
                path.pop()

        dfs(0)
        return res

def test(test_name, graph, expected):
    res = Solution().allPathsSourceTarget(graph)
    res.sort(), expected.sort()
    if res == expected:
        print(test_name + ' succeed')
    else:
        print(test_name + ' fail')

if __name__ == '__main__':
    graph1 = [[1,2],[3],[3],[]]
    expected1 =  [[0,1,3],[0,2,3]]
    test('test1', graph1, expected1)

    graph2 = [[4,3,1],[3,2,4],[3],[4],[]]
    expected2 = [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
    test('test2', graph2, expected2)

    graph3 = [[1],[]]
    expected3 = [[0,1]]
    test('test3', graph3, expected3)

    graph4 = [[1,2,3],[2],[3],[]]
    expected4 = [[0,1,2,3],[0,2,3],[0,3]]
    test('test4', graph4, expected4)

    graph5 = [[1,3],[2],[3],[]]
    expected5 =  [[0,1,2,3],[0,3]]
    test('test5', graph5, expected5)


import time
from Option import *

def main():
    print("=== Aplikasi Penyimpan Artikel ===")
    count = 0
    run = True

    try:
        while run:
            print("\nPilih sesuai angka 1 - 5\n1. Tampilkan Artikel\n2. Tambahkan Artikel\n3. Hapus Artikel\n4. Update Artikel\n5. exit.\n")
            count +=1
            choise = int(input("masukkan pilihan = "))
            if choise == 1:
                print("\n=== SHOW ARTIKEL ===")
                getData()
            elif choise == 2:
                inserData()
                print("\n***Artikel berhasil di tambah***")
                time.sleep(1.3)
            elif choise == 3:
                if(len(datas) >= 1):
                    getData()
                    temp = deleteData()
                    if(temp):
                        datas.clear()
                        datas.extend(temp)
                        print("\n***Artikel berhasil di Hapus***")
                        time.sleep(1.3)
                    else:
                        print("Artikel tidak ada di penyimpanan, pilih yang lain !!!")
                else:
                    print("Artikel minimal memiliki satu untuk dihapus !!!")
                    time.sleep(1)
            elif choise == 4:
                if (len(datas) >= 1):
                    print(30 * "=")
                    getData()
                    updateData()
                    time.sleep(1.3)
                else:
                    print("Artikel minimal memiliki satu untuk diupdate !!!")
                    time.sleep(1)
            elif choise == 5:
                print(f"Program dijalankan sebanyak = {count}")
                exit()
                break
            else:
                print("\nPilih dari 1 - 5")

    except ValueError as err:
        print(f"Error message : {err}")
main()


# test_IM_GetTopicApi   查询主题接口    /as_stock_information/api/topic/v1/get
import json
import logging
import random

import allure
import pytest

from Common.getConsoleLogin import getConsoleLogin_token
from Common.get_time_stamp import stampToTime

from Common.sign import get_sign

from Common.requests_library import Requests
from Common.tools.read_write_json import get_json

from glo import BASE_DIR, HTTP, JSON

# @pytest.mark.skip(reason="调试中 ")
@allure.feature('资讯app_查询主题接口')
class TestIMGetTopicApi():
    @classmethod
    def setup_class(cls) -> None:
        cls.session = Requests().get_session()

    def tearDown(self) -> None:
        Requests(self.session).close_session()

    # @pytest.mark.skip(reason="调试中 ")
    @pytest.mark.parametrize('info',
                             get_json(BASE_DIR + r"/TestData/testIMData/test_IM_GetTopicApi.json"))
    def test_IM_GetTopicApi(self, info):
        url = HTTP + "/as_stock_information/api/topic/v1/get"
        header = {}
        header.update(JSON)

        paylo = info
        # print(paylo)
        sign1 = {"sign": get_sign(paylo)}  # 把参数签名后通过sign1传出来
        payload1 = {}
        payload1.update(paylo)
        payload1.update(sign1)
        headers = {}
        headers.update(header)
        # print(token)
        # print(type(token))
        token = {"token": getConsoleLogin_token()}
        headers.update(token)  # 将token更新到headers
        # print(headers)
        payload = json.dumps(dict(payload1))
        # time.sleep(60.01)

        r = Requests(self.session).post(
            url=url, headers=headers, data=payload, title="查询主题接口"
        )

        j = r.json()
        # print(j)
        assert r.status_code == 200
        assert j.get("code") == "000000"
        assert j.get("msg") == "ok"
        if "data" in j:
            if len(j.get("data")) != 0:
                assert "id" in j.get("data")
                assert "categoryId" in j.get("data")
                assert "name" in j.get("data")
                assert "description" in j.get("data")
                if "backgroundImg" in j.get("data"):
                    assert "https://zhuorui-public-test.oss-cn-shenzhen.aliyuncs.com/information/" \
                           in j.get("data").get("backgroundImg")
                elif "headImg" in j.get("data"):
                    assert j.get("data").get("headImg") == \
                           "https://zhuorui-public-test.oss-cn-shenzhen.aliyuncs.com/" \
                           "information/20210621/13bd8850-d25a-11eb-94bb-5904ce8ea223.jpg"
                else:
                    raise AssertionError(j.get("data"))
            else:
                logging.info("data为空")
        else:
            logging.info("data不在j中")


#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import time
source = ['"D:\\text"']
#spaces in it.
target_dir='D:\\backup'
#target_dir='"F:\\biqiqi\\backup"'
#using
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
#zip_command="zip -qr {0} {1}".format(target ,' '.join(source))
#打开好压的EXE文件
if not os.path.exists(target_dir):
    os.mkdir(target_dir)
zip_command = "makecab  \"%s\" \"%s\"" % (target, ' '.join(source))

# Run the backup
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
    print('Successful backup to', target)
else:
    print('Backup FAILED')


class Solution:

    # Sliding window
    def strStr(self, haystack,needle):
        # What should we return when needle is an empty string? This is a great question to ask during an interview.

        if len(needle) < 1:
            return 0

        windowFront = 0

        windowBack = len(needle)-1

        while windowBack < len(haystack):
            if haystack[windowFront:windowBack+1] == needle:
                return windowFront
            windowFront += 1
            windowBack += 1

        return -1

# Runtime: 32 ms, faster than 94.08% of Python3 online submissions for Implement strStr().
# Memory Usage: 14 MB, less than 12.31% of Python3 online submissions for Implement strStr().


"""
20세기 (1901년 1월 1일 ~ 2000년 12월 31일) 에서, 매월 1일이 일요일인 경우는 총 몇 번?
"""
from py_modules.timer import logging_time
import datetime

@logging_time
def solution():
    result = 0
    for y in range(1901, 2001):
        for m in range(1, 13):
            d = datetime.date(y, m, 1)
            if d.weekday() == 6:
                result += 1
    return result

if __name__ == '__main__':
    solution()


import scrapy
from tutorial.items import DmozItem

class DomzSpider(scrapy.Spider):
    name = 'tencent'
    allowed_domains = ["tencent.com"]
    start_urls = [
        "https://security.tencent.com/index.php/blog",
        ]

    def parse(self, response):
        for sel in response.xpath('//*[@class="mod-itemlist-article"]'):
            item=DmozItem()
            item['title'] = sel.xpath('li/div[@class="item_content"]/div[@class="content_title"]/a/text()').extract()
            #print item['title']
            item['link'] = sel.xpath('li/div[@class="item_content"]/div[@class="content_title"]/a/@href').extract()
            item['dat'] = sel.xpath(
                'li/div[@class="item_content"]/div[@class="content_info"]/span[@class="info_date"]/span/text()').extract()
            item['hot'] = sel.xpath(
                'li/div[@class="item_content"]/div[@class="content_info"]/span[@class="info_watched"]/span/text()').extract()
            item['info'] = sel.xpath(
                'li/div[@class="item_content"]/div[@class="content_brief"]/p/text()').extract()
            #print title,link,desc
            yield item


from mpu6050_i2c import *
import math as Math

time.sleep(5)

print('recording data')
a = 0
while a < 2:
    a = a + 1
    try:
        ax,ay,az,wx,wy,wz = mpu6050_conv()
        mx,my,mz = AK8963_conv()
    except:
        continue

    print('{}'.format('-'*30))
    print('accel [g]: x = {0:2.2f}, y = {1:2.2f}, z = {2:2.2f}'.format(ax, ay, az))
    print('gyro [dps]: x = {0:2.2f}, y = {1:2.2f}, z = {2:2.2f}'.format(wx, wy, wz))
    print('mag [uT]: x = {0:2.2f}, y = {1:2.2f}, z = {2:2.2f}'.format(mx, my, mz))
    print('head [deg] h = {0:3.2f}'.format(Math.atan2(my/180, mx/180)*180.0))
    print('{}'.format('-'*30))
    time.sleep(1)