import json
from kubernetes import client, config, watch
import logging
import os

DOMAIN = "rules-k8s.bazel.io"

def main():
    config.load_incluster_config()

    # Exposed to us through the downward API.
    namespace = os.environ["MY_NAMESPACE"]

    crds = client.CustomObjectsApi()

    def mark_done(event, obj):
        metadata = obj.get("metadata")
        if not metadata:
            logging.error("No metadata in object, skipping: %s", json.dumps(obj, indent=1))
            return
        name = metadata.get("name")

        obj["spec"]["done"] = True
        obj["spec"]["comment"] = "DEMO "

        logging.error("Updating: %s", name)
        crds.replace_namespaced_custom_object(DOMAIN, "v1", namespace, "todos", name, obj)

    resource_version = ''
    while True:
        stream = watch.Watch().stream(crds.list_namespaced_custom_object,
                                      DOMAIN, "v1", namespace, "todos",
                                      resource_version=resource_version)
        for event in stream:
            obj = event["object"]

            spec = obj.get("spec")
            if not spec:
                logging.error("No 'spec' in object, skipping event: %s", json.dumps(obj, indent=1))
            else:
                if not spec.get("done", True):
                    mark_done(event, obj)

            # Configure where to resume streaming.
            metadata = obj.get("metadata")
            if metadata:
                resource_version = metadata["resourceVersion"]

if __name__ == "__main__":
    main()


myDict = {"Bob": {"position": "waiter", "salary": 15},
          "Sue": {"position": "host", "salary": 17},
          "Rick": {"position": "cook", "salary": 20}
          }

#Write myDict to a file
f = open('testDictOut.txt', 'w')
try:
    f.write(myDict.__str__())
finally:
    f.close()

#Read myDict back
myNewDict = open('testDictOut.txt', 'r').read()
print(type(myNewDict), myNewDict)

#####################
#What happened?
#####################

#Lets try saving it using Pickles
import pickle
f = open("testDictOut.pkl", "wb")
pickle.dump(myDict, f)
f.close()

G = open("testDictOut.pkl", "rb")
myNewDict2 = pickle.load(G)
print(type(myNewDict2), myNewDict2)
######################
# What happened now?
######################


from bs4 import BeautifulSoup
import requests
import re
import pandas as pd
from logger import SmoothValue

###################################################################################################
# Note set params with {'q' : 'author:' + authorname} to parse the articles form specify author   #
###################################################################################################

FORUM = 'Gossiping'

class PTT:

    def __init__(
        self,
        forum='Gossiping',
        num_pages=1,
        headers={},
        params={},
        txt_path = 'logger.txt',
    ):

        self.forum = forum
        self.headers = headers
        self.params = params
        self.num_pages = num_pages
        self.parse_info = []
        self.txt_path = txt_path
        SmoothValue.setting(file_path=self.txt_path)

    def fetch(self):

        if bool(self.params):
            self.params['page'] = 1
            idx = list(range(1, self.num_pages + 1))
            list(map(self._fetch_kw, idx))
        else:
            self.params['page'] = 0
            self.params['q'] = ''
            idx = self.parse_newest_index()
            idx = list(range(idx - self.num_pages + 1, idx + 1))
            idx.reverse()
            list(map(self._fetch_forum, idx))

        SmoothValue.durationTime()
        SmoothValue.info(
            forum=self.forum,
            keyword=self.params['q'],
            pages=self.num_pages,
            save_path=self.txt_path,
            )
        SmoothValue.writeInfo()

    def _fetch_forum(self, idx):

        url = f'https://www.ptt.cc/bbs/{self.forum}/index{idx}.html'
        ent = self.get_article_info(
            url=url,
            headers=self.headers,
            params=self.params,
            )
        self.params['page'] = self.params['page'] + 1
        for e in ent:
            try:
                ent_info = self.ent2info(e, self.forum)
                info = self.parse_ent_content(ent_info, self.headers, self.params)
                self.parse_info.append(info)
                SmoothValue.addCallback('success', self.params['page'])
            except:
                SmoothValue.addCallback('fail', self.params['page'])

    def _fetch_kw(self, page):

        url = f'https://www.ptt.cc/bbs/{self.forum}/search?'
        self.params['page'] = page
        ent = self.get_article_info(url=url, headers=self.headers, params=self.params)
        for e in ent:
            try:
                ent_info = self.ent2info(e, self.forum)
                info = self.parse_ent_content(ent_info, self.headers, self.params)
                self.parse_info.append(info)
                SmoothValue.addCallback('success', page)
            except:
                SmoothValue.addCallback('fail', page)

    def parse_newest_index(self):

        url = f'https://www.ptt.cc/bbs/{self.forum}/index.html'

        r = requests.get(
            url=url,
            headers=self.headers,
            params=self.params,
            cookies={'over18': '1'}
        )
        doc = BeautifulSoup(r.text, features="lxml")
        newest_anchor = doc.find_all("a", {"class": "btn"})[-3].get('href')
        index = re.findall(r"\d+", newest_anchor)[0]

        return int(index) + 1

    def to_csv(self, save_path=None):
        import pandas as pd
        df_list = []
        try:
            for dct in self.parse_info:
                df = pd.DataFrame(dct, index=[0])
                df_list.append(df)
            df = pd.concat(df_list)
        except:
            SmoothValue.error()
        if save_path is not None:
            df.to_csv(save_path)
            SmoothValue.info(save_path=save_path)
        else:
            df.to_csv(f'ptt_{self.forum}.csv')
            SmoothValue.info(save_path=f'ptt_{self.forum}.csv')

    def to_xlsx(self, save_path=None):
        import openpyxl
        wb = openpyxl.Workbook()
        titles = ['title', 'url', 'author', 'date', 'recommand', 'content']
        ws = wb.active
        ws.append(titles)
        try:
            for dct in self.parse_info:
                l = []
                for title in titles:
                    l.append(dct[title])
                ws.append(l)
        except:
            SmoothValue.error()
        if save_path is not None:
            wb.save(save_path)
            SmoothValue.info(save_path=save_path)
        else:
            wb.save(f'ptt_{self.forum}.xlsx')
            SmoothValue.info(save_path=f'ptt_{self.forum}.xlsx')

    @staticmethod
    def content_cleaner(content):

        text = content.split('--')[0]
        text = text.split('\n')[2:]
        text = '\n'.join(text)
        text = re.sub('[^\w\s]','', text)

        return text \
            .replace('\n', '').replace('\t', '') \
            .replace('[', '').replace(']', '')  \
            .replace('>>', '').replace('<<', '')

    @staticmethod
    def ent2info(ent, forum=None):

        info_dict = {
            'title': ent.find('a', href=re.compile(f"^/bbs/{forum}/M")).text,
            'url': 'https://www.ptt.cc' + ent.find('a', href=re.compile(f"^/bbs/{forum}/M")).get('href'),
            'author': ent.find('div', {'class': 'author'}).text,
            'date': ent.find('div', {'class': 'date'}).text,
            'recommand': ent.find('div', {'class': 'nrec'}).text,
        }

        return info_dict

    def parse_ent_content(self, ent_dict, headers=None, params=None):

        url = ent_dict['url']
        r = requests.get(
            url=url,
            headers=headers,
            params=params,
            cookies={'over18': '1'}
        )
        doc = BeautifulSoup(r.text, 'html.parser')
        ent = doc.find(id='main-container')
        ent_dict['content'] = self.content_cleaner(ent.text)

        return ent_dict

    @staticmethod
    def get_article_info(url, headers, params):

        r = requests.get(
            url=url,
            headers=headers,
            params=params,
            cookies={'over18': '1'}
        )
        doc = BeautifulSoup(r.text, 'html.parser')
        ent = doc.find_all('div', class_='r-ent')

        return ent


import random
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,
         'Queen':10, 'King':10, 'Ace':11}
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')

playing = True
class Card:
    def __init__(self,rank,suit):
        self.rank =rank
        self.suit = suit
        self.value =values[rank]
    def __str__(self):
        return self.rank + " of " + self.suit

class Hand:
    def __init__(self):
         self.cards = []
         self.value = 0
         self.aces = 0

    def add_card(self,card):
        self.cards.append(card)
        self.value += values[card.rank]
        if card.rank == "Ace":
            self.aces +=1

    def adjust_for_aces(self):
        while self.value > 21 and self.aces:
            self.value -= 10
            self.aces -= 1

class Deck:
    def __init__(self):
        self.deck = []
        for rank in ranks:
            for suit in suits:
                self.deck.append(Card(rank,suit))
    def shuffle(self):
        random.shuffle(self.deck)
    def deal(self):
        return self.deck.pop()
    def __str__(self):
        comp = ""
        for card in self.deck:
            comp += '\n' + card.__str__()
        return "Deck has " + comp

class Chips:
    def __init__(self,amount):
        self.amount = amount
        self.bet = 0
    def win_bet(self):
        self.amount += self.bet

    def lost_bet(self):
        self.amount -= self.bet
    #def add_chips(self,more):
        #self.amount += more

def take_bet(chips):
    while True:
        try:
            chips.bet = int(input(" How many Chips would you like to bet "))
            print("\n")
        except:
            print("sorry, please provide number")
        else:
            if chips.bet > chips.amount:
                print("not enough. You have {} ".format(chips.amount))
            else:
                break

def hit(deck,hand):
    single_card = deck.deal()
    hand.add_card(single_card)
    hand.adjust_for_aces()

def hit_or_stay(deck,hand):
    global playing

    while True:
        x = input("Hit or Stay: Press H or S ")
        if x[0].lower() == 'h':
            hit(deck,hand)
        elif x[0].lower() == 's':
            print("Player Stays")
            playing = False
        else:
            print("Please Press H or S")
            continue
        break

def show_some(player,dealer):
    print("Dealer's hand : \n")
    print("One Card Hidden")
    print(dealer.cards[1])
    print('\n')
    print("Player's hand :")
    print('\n')
    for card in player.cards:
        print(card)

def show_all(player,dealer):
    print("Dealer's Hand :")

    for card in dealer.cards:
        print(card)
    #print("\n")
    print("Player's Cards: ")
    for card in player.cards:
        print(card)

def player_bust(player,dealer,chips):
    print("Player Busts")
    chips.lost_bet()
def player_wins(player,dealer,chips):
    print("player Wins")
    chips.win_bet()
def dealer_bust(player,dealer,chips):
    print("Dealer Busts")
    chips.win_bet()
def dealer_wins(player,dealer,chips):
    print("Dealer Wins")
    chips.lost_bet()
def push(player,dealer):
    print("It's a Tie")

print("Welcome to Simple BlackJack"+ "\n" + "You have 1,000 chips. Use them wisely")
player_chips = Chips(1000)
while True:

    deck = Deck()
    deck.shuffle()

    player_hand = Hand()
    player_hand.add_card(deck.deal())
    player_hand.add_card(deck.deal())
    dealer_hand = Hand()
    dealer_hand.add_card(deck.deal())
    dealer_hand.add_card(deck.deal())

    #player_chips = Chips(100)
    take_bet(player_chips)
    show_some(player_hand,dealer_hand)

    while playing:

        hit_or_stay(deck,player_hand)
        show_some(player_hand,dealer_hand)
        if player_hand.value > 21:
            player_bust(player_hand,dealer_hand,player_chips)
            break
    if player_hand.value <= 21:
        while dealer_hand.value < 17:
            hit(deck,dealer_hand)
        show_all(player_hand,dealer_hand)
        if dealer_hand.value > 21:
            dealer_bust(player_hand,dealer_hand,player_chips)
        elif dealer_hand.value > player_hand.value:
            dealer_wins(player_hand,dealer_hand,player_chips)
        elif dealer_hand.value < player_hand.value:
            player_wins(player_hand,dealer_hand,player_chips)
        else:
            push(player_hand,dealer_hand)
    #player_chips.add_chips(player_chips.amount)
    print("\n Player total chips at {} ".format(player_chips.amount))
    if (player_chips.amount == 0):
        print("Sorry, no more money")
        break
    new_game = input("Would you want to play another hand? : y/n ")
    if new_game[0].lower() == 'y':
        playing = True
        continue
    else:
        print("Thanks for playing")
        break

#test_deck = Deck()
#test_deck.shuffle()
#print(test_deck)
#p1 = Hand()
#sample_card = test_deck.deal()
#print(sample_card)
#p1.add_card(sample_card)
#print(p1.value)


# /usr/bin/python
# -*- coding:utf-8 -*-
import time
from io import BytesIO
import numpy as np
import matplotlib as mpl
from matplotlib.font_manager import *
from matplotlib import pyplot as plt
import logging
myfont = FontProperties(fname='/usr/share/fonts/msyh.ttf')
mpl.rcParams['axes.unicode_minus'] = False

def autolabel(rects, ax, xpos='center'):
    """
    Attach a text label above each bar in *rects*, displaying its height.

    *xpos* indicates which side to place the text w.r.t. the center of
    the bar. It can be one of the following {'center', 'right', 'left'}.
    """

    xpos = xpos.lower()  # normalize the case of the parameter
    ha = {'center': 'center', 'right': 'left', 'left': 'right'}
    offset = {'center': 0.5, 'right': 0.57, 'left': 0.43}  # x_txt = x + w*off

    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width() * offset[xpos], 1.01 * height,
                '{}'.format(height), ha=ha[xpos], va='bottom')

class multiColumn:
    def __init__(self, request):
        self.request = request

    def result(self):
        coordinate = self.request.json.get('coordinate')
        data = self.request.json.get('data')
        logging.error(self.request.json)
        return self.draw(coordinate, data)

    @staticmethod
    def draw(coordinate, data):
        '''
        :param coordinate: {'x':[],'y':'金额'}
        :param data = [
                    {'value':[300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3],'label':'平均值'},
                    {'value':[30.2, 53.3, 75.9, 5862.5, 979.6, 1289.7, 1958.3],'label':'最大值'}
                ]
        :return:文件流
        '''
        try:
            # 柱状图的个数
            n = len(data)
            total_width = 0.8
            ind = np.arange(len(coordinate['x']))
            width = total_width / n
            fig, ax = plt.subplots()
            # y轴
            ax.set_ylabel(coordinate['y'],fontproperties=myfont)
            # x轴
            ax.set_xticks(ind)
            ax.set_xticklabels(coordinate['x'],fontproperties=myfont)

            ind = ind - (total_width - width) / 2
            i = 0
            for x in data:
                temp = ax.bar(ind + i * width, x['value'], width, label=x['label'])
                i += 1
                autolabel(temp, ax)

            ax.legend(prop=myfont)
            # 文件流
            canvas = fig.canvas
            buffer = BytesIO()
            canvas.print_png(buffer)
            stream = buffer.getvalue()
            buffer.close()
            return stream
        except Exception as e:
            return '参数错误，图片生成失败', 400


from process import load_chinese_dataset
from pytorch_transformers import BertTokenizer

chinese_data_set = load_chinese_dataset()
train_chinese_data_set = chinese_data_set['train']

sent, tag = train_chinese_data_set[0]
sent = ["[CLS]"] + sent + ["[SEP]"]
tag = ['<pad>'] + tag + ['<pad>']
print(sent)
print(tag)

tokenizer = BertTokenizer.from_pretrained('bert-base-chinese', do_lower_case=True)
tokens = tokenizer.tokenize(''.join(sent))
x = tokenizer.convert_tokens_to_ids(tokens)
print(x)


from argparse import ArgumentParser

from . import start_dev, build_app

if __name__ == "__main__":
    parser = ArgumentParser(
        prog="react_cli",
        description="A command-line interface used for developing React-like web applications using Python and PyScript",
    )
    parser.add_argument("command", choices=["dev", "build"])

    args = parser.parse_args()
    if args.command == "dev":
        start_dev()
    elif args.command == "build":
        build_app()


import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

def keypoint_match(path_of_image1, path_of_image2):

    img1 = cv.imread(path_of_image1, cv.IMREAD_GRAYSCALE)
    img2 = cv.imread(path_of_image2, cv.IMREAD_GRAYSCALE)

    # Initiate SIFT detector
    sift = cv.xfeatures2d.SIFT_create()

    # find the keypoints and descriptors with SIFT
    kp1, des1 = sift.detectAndCompute(img1, None)
    kp2, des2 = sift.detectAndCompute(img2, None)

    # FLANN parameters
    FLANN_INDEX_KDTREE = 1
    index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
    search_params = dict(checks=50)  # or pass empty dictionary
    flann = cv.FlannBasedMatcher(index_params, search_params)
    matches = flann.knnMatch(des1, des2, k=2)

    # Need to draw only good matches, so create a mask
    matchesMask = [[0, 0] for i in range(len(matches))]
    # ratio test as per Lowe's paper
    c = 0
    for i, (m, n) in enumerate(matches):
        if m.distance < 0.7 * n.distance:
            matchesMask[i] = [1, 0]
            c = c + 1
    # print(matchesMask)
    print(c)
    draw_params = dict(matchColor=(0, 255, 0),
                       singlePointColor=(255, 0, 0),
                       matchesMask=matchesMask,
                       flags=cv.DrawMatchesFlags_DEFAULT)
    img3 = cv.drawMatchesKnn(img1, kp1, img2, kp2, matches, None, **draw_params)
    plt.imshow(img3, ), plt.show()

keypoint_match('D:/MintM/deo_classifier/data/fogg/40001571_2-fogg-fragrance-body-spray-paradise_.jpg',
               'D:/MintM/deo_classifier/data/fogg/40001570_2-fogg-fragrance-body-spray-royal.jpg')


from rest_framework import generics, status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from ..serializers import *

class InterestsAPI(generics.ListCreateAPIView):
    queryset = Interests.objects.all()
    serializer_class = InterestsSerializer

    @api_view(['POST'])
    def get_interests_by_categories(request):
        if request.method == 'POST':
            categories = InterestCategories.objects.all()
            interests = Interests.objects.all()
            interests2 = []
            exists = 0

            for category in categories:
                if category.name == request.data['category']:
                    exists = 1
                    category_id = category.id

            if exists:
                for interest in interests:
                    if interest.category_id == category_id:
                        interests2.append(interest)

                interests_serializer = InterestsSerializer(interests2, many=True)
                return Response(interests_serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response('Category does not exist')


from math import sqrt

class Point:
    def __init__(self, a, b):
        self.a = a
        self.b = b

class Triangle:
    def __init__(self, p1, p2, p3):
        self.p1 = p1
        self.p2 = p2
        self.p3 = p3

    def distance(self, p1, p2):
        return sqrt((p1.a - p2.a) ** 2 + (p1.b - p2.b) ** 2)

    def sum(self):
        a = self.distance(self.p1, self.p2)
        b = self.distance(self.p1, self.p3)
        c = self.distance(self.p2, self.p3)
        if max(a, b, c) * 2 >= a+b+c:
            return 'INVALID'
        return '{:.3f}'.format(a+b+c)

A = []
test = int(input())
for _ in range(test):
    A += [float(i) for i in input().split()]
i = 0
for index in range(test):
    print(Triangle(Point(A[i], A[i+1]), Point(A[i+2], A[i+3]), Point(A[i+4], A[i+5])).sum())
    i += 6


import requests, bs4
from bs4 import BeautifulSoup

def twitter_search(name,pren):
    url = "https://twstalker.com/search/?q={} {}".format(pren,name)
    r = requests.get(url)
    page = r.content
    features = "html.parser"
    soup = BeautifulSoup(page, features)

    usernames = []

    username = soup.find_all('div',{'class':'user-request-dt'})

    for i in username:
        i = str(i).split('@')[1].split('</span')[0].replace('\'','')
        usernames.append('@'+i.strip())

    return usernames


import ast

def compare_pair(left, right):
    if type(left) == list and type(right) == list:
        while len(left) > 0 and len(right) > 0:
            if type(left[0]) == int and type(right[0]) == int:
                if left[0] < right[0]:
                    return True
                if left[0] > right[0]:
                    return False
                if left[0] == right[0]:
                    left.remove(left[0])
                    right.remove(right[0])
            elif type(left[0]) == list and type(right[0]) == list:
                ret = compare_pair(left[0], right[0])
                if ret:
                    return True
                elif type(ret) == bool:
                    return False
                else:
                    left.remove(left[0])
                    right.remove(right[0])
            else:
                if type(left[0]) == int:
                    left[0] = [left[0]]
                elif type(right[0]) == int:
                    right[0] = [right[0]]
        if len(left) < len(right):
            return True
        if len(left) > len(right):
            return False
        return None

with open("input.txt") as f:
    txt = f.read().split('\n')
    pairs = []
    p = []
    for line in txt:
        if line is '':
            pairs.append(p)
            p = []
        else:
            p.append(ast.literal_eval(line))
    index = 1
    sum = 0
    for p in pairs:
        ret = compare_pair(p[0], p[1])
        print(f'{index}: {ret}')
        if ret:
            sum += index
        index += 1
    print(sum)


from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml import OxmlElement
from docx.shared import Inches
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.shared import Inches
from docx.shared import Cm
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.section import WD_SECTION
from docx.enum.section import WD_ORIENT
from docx.api import Document

"""

2x4_phonics_slips.docx

"""
def set_cell_border( _Cell, **kwargs):
    """
    Set cell`s border
    Usage:

    set_cell_border(
        cell,
        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
        bottom={"sz": 12, "color": "#00FF00", "val": "single"},
        start={"sz": 24, "val": "dashed", "shadow": "true"},
        end={"sz": 12, "val": "dashed"},
    )
    """
    tc = _Cell._tc
    tcPr = tc.get_or_add_tcPr()

    # check for tag existnace, if none found, then create one
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)

    # list over all available tags
    for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)

            # check for tag existnace, if none found, then create one
            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)

            # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))

# read word list
def createdocs(docname,content):
 items = list(content)
 i = len(items)
 print(items, i)
 document = Document()

 #### set font
 style = document.styles['Normal']
 font = style.font
 font.name = 'Sofia Pro Soft'
 font.size = Pt(120)

 #### set Document/Margins
 for sec in document.sections:
    sec.left_margin = Inches(1)
    sec.right_margin = Inches(1)
    sec.top_margin = Inches(1)
    sec.bottom_margin = Inches(1)

 ##### Table setting
 if (i % 2) == 0:
  nr=i/2
  table = document.add_table(rows=nr, cols=2, style='Table Grid')
 else:
     f=i+1
     nr = f / 2
     table = document.add_table(rows=nr, cols=2, style='Table Grid')
 for col in table.columns:
    for cell in col.cells:
        for par in cell.paragraphs:
            par.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
 d = 0  # type: int
 while d < nr:
     set_cell_border(
         table.cell(d, 0),
         top={"val": "dashed"},
         bottom={"val": "dashed"},
         start={"val": "dashed"},
         end={"val": "dashed"},
     )
     set_cell_border(
         table.cell(d, 1),
         top={"val": "dashed"},
         bottom={"val": "dashed"},
         start={"val": "dashed"},
         end={"val": "dashed"},
     )

     d = d + 1

 e = 0
 while e < nr:
    table.cell(e, 0).height = Cm(5.92)
    table.cell(e, 0).width = Cm(8.26)
    table.cell(e, 1).height = Cm(5.92)
    table.cell(e, 1).width = Cm(8.26)
    e = e + 1

 table.autofit = False
 #### Add table content
 if (i % 2) == 0:
  a = 0
  b = 0
  while b < nr:
    table.cell(b, 0).text = items[a]
    table.cell(b, 1).text = items[a+1]
    table.cell(b, 0).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.cell(b, 1).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.cell(b, 0).paragraphs[0].paragraph_format.space_before = Pt(18)
    table.cell(b, 1).paragraphs[0].paragraph_format.space_before = Pt(18)
    b = b + 1
    a = a + 2
  document.save(docname+'.docx')
 else:
     items.append(' ')
     i=len(items)
     nr=i/2
     a = 0
     b = 0
     while b < nr:
         print(b,a,items[a+1])
         table.cell(b, 0).text = items[a]
         table.cell(b, 1).text = items[a + 1]
         table.cell(b, 0).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
         table.cell(b, 1).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
         table.cell(b, 0).paragraphs[0].paragraph_format.space_before = Pt(18)
         table.cell(b, 1).paragraphs[0].paragraph_format.space_before = Pt(18)
         b = b + 1
         a = a + 2
     document.save(docname + '.docx')

document = Document('phonics_letter_slips_table.docx')
table = document.tables[0]
##Getting the original data from the document to a list
ls =[]
for column in table.columns:
    for cell in column.cells:
        for paragraph in cell.paragraphs:
            ls.append(paragraph.text)
ls = filter(None, ls)
i=len(ls)
print(ls)
print(i)

n=0
m=i/2
while n< i/2:
    docname=ls[n]
    content=ls[m]
    createdocs(docname, content)
    m=m+1
    n=n+1


from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db.models import Sum
from repo.models import Shop, ShopRecord, SendOutShop, ShopOrder
from repo.serializers.ShopSerializer import ShopSerializer, ShopNameSerializer, ShopRecordSerializer
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
import logging
from .. import filters
from repo.util import sum_shop

log = logging.getLogger(__name__)

class ShopViewSet(ModelViewSet):
    queryset = Shop.objects.all()
    filterset_class = filters.ShopFilter
    filter_backends = (OrderingFilter, DjangoFilterBackend )
    ordering_fields = ('id', 'order_no')

    def get_serializer_class(self):
        params = self.request.query_params.dict()
        if params.get('simple') == "yes":
            return ShopNameSerializer
        return ShopSerializer

    @action(detail=True, methods=['get'])
    def detail_num(self, request, pk=None):
        shop_object = self.get_object()
        detail_num = {}
        detail_num['stock_num'] = shop_object.shop_num
        total_out = SendOutShop.objects.filter(shop=shop_object, option='Bring', send__status='Process').aggregate(Sum('out_num'))
        total_in = SendOutShop.objects.filter(shop=shop_object, option='Bring', send__status='Process').aggregate(Sum('in_num'))
        total_out_sum = total_out['out_num__sum'] if total_out['out_num__sum'] else 0
        total_in_sum = total_in['in_num__sum'] if total_in['in_num__sum'] else 0
        detail_num['send_num'] = total_out_sum - total_in_sum

        total_order = ShopOrder.objects.filter(shop=shop_object, status='Process').aggregate(Sum('num'))
        total_back = ShopOrder.objects.filter(shop=shop_object, status='Process').aggregate(Sum('in_num'))
        total_order_sum = total_order['num__sum'] if total_order['num__sum'] else 0
        total_back_sum = total_back['in_num__sum'] if total_back['in_num__sum'] else 0
        detail_num['order_num'] = total_order_sum - total_back_sum
        return Response(detail_num)

# 直接入库和售出
    @action(detail=True, methods=['put'])
    def change_num(self, request, pk=None):
#       data= {
#          id: 32,
#          date: '2021-03-04 17:05',
#          num: 100,
#          option: 'increase',
#          remark: '备注'
#        }

        data = request.data
        shop = self.get_object()
        if data.get('option') == 'increase':
            shop.shop_num = shop.shop_num + data.get('num')
            sr_object = ShopRecord.objects.create(shop_no=shop.shop_no, shop_name=shop.shop_name, date=data.get('date'),
                                                  change_num=data.get('num'), option='Inrepo', remark=data.get('remark'),
                                                  creator=request.user.last_name)
        else:
            shop.shop_num = shop.shop_num - data.get('num')
            sr_object = ShopRecord.objects.create(shop_no=shop.shop_no, shop_name=shop.shop_name, date=data.get('date'),
                                                  change_num=data.get('num'), option='Sale', remark=data.get('remark'),
                                                  creator=request.user.last_name)
        shop.save()
        sum_shop(shop)
        return Response()

# 设置预警阀值
    @action(detail=True, methods=['put'])
    def set_threshold(self, request, pk=None):
        data = request.data
        shop = self.get_object()
        if data.get('threshold'):
            shop.threshold = data.get('threshold')
        shop.remark = data.get('remark', '')
        shop.save()
        return Response()

class ShopRecordViewSet(ModelViewSet):
    queryset = ShopRecord.objects.all()
    serializer_class = ShopRecordSerializer
    filterset_class = filters.ShopRecordFilter
    filter_backends = (OrderingFilter, DjangoFilterBackend )
    ordering_fields = ('created_time',)

    def destroy(self, request, pk):
        delete_object = self.get_object()
        shop = Shop.objects.get(shop_no=delete_object.shop_no)
        if delete_object.option == 'Sale':
            shop.shop_num += delete_object.change_num
        else:
            shop.shop_num -= delete_object.change_num
        shop.save()
        sum_shop(shop)
        delete_object.delete()
        return Response(status=204)


from dataclasses import field, make_dataclass
from unittest.mock import patch

from botorch.utils.containers import DenseContainer, SliceContainer
from botorch.utils.datasets import (
    BotorchDataset,
    FixedNoiseDataset,
    RankingDataset,
    SupervisedDataset,
)
from botorch.utils.testing import BotorchTestCase
from torch import rand, randperm, Size, stack, tensor

class TestDatasets(BotorchTestCase):
    def test_base(self):
        with patch.object(BotorchDataset, "_validate", new=lambda self: 1 / 0):
            with self.assertRaises(ZeroDivisionError):
                BotorchDataset()

        dataset = BotorchDataset()
        self.assertTrue(dataset._validate() is None)

    def test_supervised_meta(self):
        X = rand(3, 2)
        Y = rand(3, 1)
        A = DenseContainer(rand(3, 5), event_shape=Size([5]))

        SupervisedDatasetWithDefaults = make_dataclass(
            cls_name="SupervisedDatasetWithDefaults",
            bases=(SupervisedDataset,),
            fields=[
                ("default", DenseContainer, field(default=A)),
                ("factory", DenseContainer, field(default_factory=lambda: A)),
            ],
        )

        # Check that call signature is property enforced
        with self.assertRaisesRegex(RuntimeError, "Missing .* `X`"):
            SupervisedDatasetWithDefaults(Y=Y)

        with self.assertRaisesRegex(RuntimeError, "Missing .* `Y`"):
            SupervisedDatasetWithDefaults(X=X)

        with self.assertRaisesRegex(TypeError, "Expected <BotorchContainer | Tensor>"):
            SupervisedDatasetWithDefaults(X=X, Y=Y.tolist())

        # Check handling of default values and factories
        dataset = SupervisedDatasetWithDefaults(X=X, Y=Y)
        self.assertEqual(dataset.default, A)
        self.assertEqual(dataset.factory, A)

        # Check type coercion
        dataset = SupervisedDatasetWithDefaults(X=X, Y=Y, default=X, factory=Y)
        self.assertIsInstance(dataset.X, DenseContainer)
        self.assertIsInstance(dataset.Y, DenseContainer)
        self.assertEqual(dataset.default, dataset.X)
        self.assertEqual(dataset.factory, dataset.Y)

    def test_supervised(self):
        # Generate some data
        Xs = rand(4, 3, 2)
        Ys = rand(4, 3, 1)

        # Test `__post_init__`
        dataset = SupervisedDataset(X=Xs[0], Y=Ys[0])
        for name in ("X", "Y"):
            field = getattr(dataset, name)
            self.assertIsInstance(field, DenseContainer)
            self.assertEqual(field.event_shape, field.values.shape[-1:])

        # Test `_validate`
        with self.assertRaisesRegex(ValueError, "Batch dimensions .* incompatible."):
            SupervisedDataset(X=rand(1, 2), Y=rand(2, 1))

        # Test `dict_from_iter` and `__eq__`
        datasets = SupervisedDataset.dict_from_iter(X=Xs.unbind(), Y=Ys.unbind())
        self.assertIsInstance(datasets, dict)
        self.assertEqual(tuple(datasets.keys()), tuple(range(len(Xs))))
        for i, dataset in datasets.items():
            self.assertEqual(dataset, SupervisedDataset(Xs[i], Ys[i]))
        self.assertNotEqual(datasets[0], datasets)

        datasets = SupervisedDataset.dict_from_iter(X=Xs[0], Y=Ys.unbind())
        self.assertEqual(len(datasets), len(Xs))
        for i in range(1, len(Xs)):
            self.assertEqual(datasets[0].X, datasets[i].X)

    def test_fixedNoise(self):
        # Generate some data
        Xs = rand(4, 3, 2)
        Ys = rand(4, 3, 1)
        Ys_var = rand(4, 3, 1)

        # Test `dict_from_iter`
        datasets = FixedNoiseDataset.dict_from_iter(
            X=Xs.unbind(),
            Y=Ys.unbind(),
            Yvar=Ys_var.unbind(),
        )
        for i, dataset in datasets.items():
            self.assertTrue(dataset.X().equal(Xs[i]))
            self.assertTrue(dataset.Y().equal(Ys[i]))
            self.assertTrue(dataset.Yvar().equal(Ys_var[i]))

        # Test handling of Tensor-valued arguments to `dict_from_iter`
        datasets = FixedNoiseDataset.dict_from_iter(
            X=Xs[0],
            Y=Ys[1],
            Yvar=Ys_var.unbind(),
        )
        for dataset in datasets.values():
            self.assertTrue(Xs[0].equal(dataset.X()))
            self.assertTrue(Ys[1].equal(dataset.Y()))

    def test_ranking(self):
        # Test `_validate`
        X_val = rand(16, 2)
        X_idx = stack([randperm(len(X_val))[:3] for _ in range(1)])
        X = SliceContainer(X_val, X_idx, event_shape=Size([3 * X_val.shape[-1]]))

        with self.assertRaisesRegex(ValueError, "out-of-bounds"):
            RankingDataset(X=X, Y=tensor([[-1, 0, 1]]))
        RankingDataset(X=X, Y=tensor([[2, 0, 1]]))

        with self.assertRaisesRegex(ValueError, "out-of-bounds"):
            RankingDataset(X=X, Y=tensor([[0, 1, 3]]))
        RankingDataset(X=X, Y=tensor([[0, 1, 2]]))

        with self.assertRaisesRegex(ValueError, "missing zero-th rank."):
            RankingDataset(X=X, Y=tensor([[1, 2, 2]]))
        RankingDataset(X=X, Y=tensor([[0, 1, 1]]))

        with self.assertRaisesRegex(ValueError, "ranks not skipped after ties."):
            RankingDataset(X=X, Y=tensor([[0, 0, 1]]))
        RankingDataset(X=X, Y=tensor([[0, 0, 2]]))


from hashtables.linked_list import *

class HashTable:

    def __init__(self, size = 1024):
        self.size = size
        self._buckets = [None] *self.size

    def hash(self,key:str)->int:
        '''
        Return hased index

         Take Key and Convert it from to index

        parameters:
         Key -> string
        return:
         index -> Number

        '''

        value=0
        for x in key:
            value += ord(x)
        index = (value * 7) % self.size
        return index

    def add(self,key,value):
        '''
    add a value to the hashtable by its key
    parameters:
        key: a string
        value: any type
    Arrgument: key and value
    return: nothing
        '''

        index = self.hash(key)

        if not self._buckets[index]:
         self._buckets[index] = LinkedList()

        self._buckets[index].append([key,value])

    def find(self,key:str):
        """this function will search in the hashtable about the key and return the value
        parameters:
        key: a string
        return: the value
        """
        index = self.hash(key)
        if self._buckets[index]:
            cuurrent=self._buckets[index].head
            while cuurrent:
                if cuurrent.value[0]==key:
                    print(cuurrent.value[1])
                    return cuurrent.value[1]
                cuurrent=cuurrent.next
        else:
            return None

    def contains(self,key:str):
        """this function will check if the there is a value for the key
        parameters:
        key: a string
        return: a boolean
        """
        index=self.hash(key)
        if self._buckets[index]:
         return self._buckets[index].includes(key)
        else:
            return False

    def get_buckets(self):
        '''Return Hashtable Buckets

        parameters: None
        Return: List

         '''
        return self._buckets

def hashmap_left_join(hash1,hash2):

    buckets=hash1.get_buckets()
    arr=[]
    for i in buckets:
        if i:
            current=i.head
            while current:
                x=hash2.find(current.value[0])
                if not x:
                    x='Null'
                current.value.append(x)
                arr.append(current.value)
                current=current.next
    return arr

h1=HashTable(10)
h2=HashTable(10)

h1.add("a1","A1")
h1.add("c1","C1")

h1.add("b1","B1")

h2.add("a1","A2")
h2.add("b1","B2")
h2.add("D1","B2")

one = HashTable()
one.add('pond', 'enamored')
one.add('rath', 'anger')
one.add('adiligent', 'employed')
one.add('poutfit', 'garb')
one.add('hangguide', 'usher')

two = HashTable()
two.add('fond', 'averse')
two.add('wrath', 'delight')
two.add('diligent', 'idle')
two.add('guide', 'follow')
two.add('flow', 'jam')

print(hashmap_left_join(one,two))


import json

with open('idf.json', 'r') as f:
    idf = json.load(f)

from lyricsToBow import lyrics_to_bow

lyrics = input("Enter your Query: ")
print(lyrics)

query = lyrics_to_bow(lyrics)

IDF_values = []

for term in query:
	if term in idf.keys():
		IDF_values.append((idf[term],term))

IDF_values.sort(reverse=True)
# print(IDF_values)
Combo_L = []

from itertools import combinations

for r in range(len(IDF_values),0,-1):
	combo_r = list(combinations(IDF_values, r))
	# print(combo_r)
	combo_r.sort(reverse = True)
	Combo_L.append(combo_r)

# print(Combo_L)

for l in Combo_L:
	print(l)
	print(end='\n\n')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May  2 09:05:51 2020

@author: piumallick
"""
# Problem 771: Jewels and Stones
'''
You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in S is a type of stone you have.  You want to know how many of the stones you have are also jewels.

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:

Input: J = "z", S = "ZZ"
Output: 0
Note:

S and J will consist of letters and have length at most 50.
The characters in J are distinct.
'''

def numJewelsInStones(J, S):
    Jset = set(J)
    #return sum(1 for stone in S if stone in Jset)
    return sum(s in Jset for s in S)

def numJewelsInStones2(J, S):
    Jset = set(J)
    return sum(1 for stone in S if stone in Jset)
    #return sum(s in Jset for s in S)

# Testing
import dis

J = "aA"
S = "aAAbbbb"
#print(numJewelsInStones(J, S))

print("------------- numJewelsInStones ------------")
dis.dis(numJewelsInStones)

print("------------- numJewelsInStones ------------")
dis.dis(numJewelsInStones2)


import pandas as pd
from langdetect import detect
import re

class DataSetCleaner:

    def __init__(self):
        #data = pd.read_csv('train.csv')
        #self.removeLanguage(data, "en", "trainEnglish.csv")
        return

    def writeToFile(self, data, fileName):
        data.to_csv(fileName)

    #This function removes the article from the dataset if its not the desired language.
    def removeLanguage (self, dataToTraverse, languageToKeep):
        for index, row in dataToTraverse.iterrows():
            try:
                if detect(row['text']) != languageToKeep:
                    dataToTraverse = dataToTraverse.drop(index)

            except:
                pass

    def removeHTML(self, data):
        cleaner = re.compile('<.*?>')
        for index, row in data.iterrows():
            row['text'] = re.sub(cleaner, '', str(row['text']))
        return data


""" Module to parse DocumentRevisions database """
import codecs
import logging
import os
import sqlite3
import riplib.osxripper_time
from riplib.plugin import Plugin

__author__ = 'osxripper'
__version__ = '0.1'
__license__ = 'GPLv3'

class DocumentRevisions(Plugin):
    """
    Parse information from /.DocumentRevisions-V100/db-V1/db.sqlite
    """

    def __init__(self):
        """
        Initialise the class.
        """
        super().__init__()
        self.set_name("Document Revisions")
        self.set_description("Parse information from /.DocumentRevisions-V100/db-V1/db.sqlite")
        self.set_data_file("db.sqlite")
        self.set_output_file("DocumentRevisions.txt")  # this will have to be defined per user account
        self.set_type("sqlite")

    def parse(self):
        """
        Read the db.sqlite SQLite database
        """
        with codecs.open(os.path.join(self._output_dir, self._output_file), "a", encoding="utf-8") as output_file:
            output_file.write("="*10 + " " + self._name + " " + "="*10 + "\r\n")
            file = os.path.join(self._input_dir, ".DocumentRevisions-V100", "db-V1", self._data_file)
            output_file.write("Source File: {0}\r\n\r\n".format(file))
            if self._os_version in ["big_sur", "catalina"]:
                logging.info("This version of OSX is not supported by this plugin.")
                print("[INFO] This version of OSX is not supported by this plugin.")
                output_file.write("[INFO] This version of OSX is not supported by this plugin.\r\n")
            elif self._os_version in ["mojave", "high_sierra", "sierra", "el_capitan", "yosemite", "mavericks",
                                      "mountain_lion", "lion"]:
                query = "SELECT file_row_id,file_name,file_parent_id,file_path,file_inode,file_last_seen," \
                        "file_status, file_storage_id FROM files"
                if os.path.isfile(file):
                    conn = None
                    try:
                        conn = sqlite3.connect(file)
                        conn.row_factory = sqlite3.Row
                        with conn:
                            cur = conn.cursor()
                            cur.execute(query)
                            rows = cur.fetchall()
                            for row in rows:
                                file_last_seen = riplib.osxripper_time.get_unix_seconds(row["file_last_seen"])
                                output_file.write("Row ID         : {0}\r\n".format(row["file_row_id"]))
                                output_file.write("File Name      : {0}\r\n".format(row["file_name"]))
                                output_file.write("Parent ID      : {0}\r\n".format(row["file_parent_id"]))
                                output_file.write("File Path      : {0}\r\n".format(row["file_path"]))
                                output_file.write("File Inode     : {0}\r\n".format(row["file_inode"]))
                                output_file.write("File Last Seen : {0}\r\n".format(file_last_seen))
                                output_file.write("File Status     : {0}\r\n".format(row["file_status"]))
                                output_file.write("File Storage ID : {0}\r\n".format(row["file_storage_id"]))
                                output_file.write("\r\n")
                    except sqlite3.Error as error:
                        logging.error("%s", error.args[0])
                        print("[ERROR] {0}".format(error.args[0]))
                    finally:
                        if conn:
                            conn.close()
                else:
                    logging.warning("File: %s does not exist or cannot be found.\r\n", file)
                    output_file.write("[WARNING] File: {0} does not exist or cannot be found.\r\n".format(file))
                    print("[WARNING] File: {0} does not exist or cannot be found.\r\n".format(file))
            elif self._os_version == "snow_leopard":
                logging.info("This version of OSX is not supported by this plugin.")
                print("[INFO] This version of OSX is not supported by this plugin.")
                output_file.write("[INFO] This version of OSX is not supported by this plugin.\r\n")
            else:
                logging.warning("Not a known OSX version.")
                print("[WARNING] Not a known OSX version.")
            output_file.write("="*40 + "\r\n\r\n")
        output_file.close()


import json

from pydriller import RepositoryMining
from dateutil.relativedelta import relativedelta
import datetime
from resources.url_resource import URLResource
import progressbar
import dateutil.parser
import pytz
import csv
import re

resources = {
    "search_repo": URLResource("https://api.github.com/search/repositories", "search"),
}

aspectJ_query = "aspectj pushed:>=2016-01-01"
spring_aop_query = "spring aop pushed:>=2016-01-01"
aop_topic_query = "topic:aop pushed:>=2016-01-01"
java_query = "language:Java pushed:>=2016-01-01"
general_query = "pushed:>=2016-01-01"
haskell_query = "language:Haskell pushed:>=2016-01-01"
date_format = "%Y-%m"
start_date = datetime.date(2016, 1, 1)
utc = pytz.UTC

# This method is used to find out the number of repos for a given query
def fetch_number_of_repos(query):
    params = {"q": query}
    result = resources["search_repo"].get(params).json()
    print(f'The total count of active repos is: {result["total_count"]}')

# Fetch information about all repos and save to json file for a given query
def fetch_all_repos(query, out_file):
    params = {"q": query}
    result = resources["search_repo"].get_multiple_pages(params)
    with open(out_file, "w") as outfile:
        json.dump({'repos': result}, outfile)

# Retrieves the activeness for all repositories, this function performs the actual mining of commits and can take
# quite some time. The input file must be a result returned by fetch_all_repos.
def get_activeness_for_repos(out_file, in_file):
    with open(in_file) as file:
        json_repos = json.load(file)
    repos = json_repos["repos"]
    result = {"total_issues": 0,
              "total_forks": 0,
              "repos": []
              }
    bar = progressbar.ProgressBar(maxval=len(repos),
                                  widgets=[progressbar.Bar('=', '[', ']'), ' ',
                                           progressbar.SimpleProgress()]
                                  )
    bar.start()
    rc = 0
    for repo in repos:
        append_info = {
            "id": repo["id"],
            "name": repo["name"],
            "html_url": repo["html_url"],
            "url": repo["url"],
            "created_at": repo["created_at"],
            "updated_at": repo["updated_at"],
            "pushed_at": repo["pushed_at"],
            "open_issues": repo["open_issues"],
            "number_of_commits": 0,
            "commits": [],
            "forks": repo["forks"],
            "failed": False
        }

        try:
            for c in RepositoryMining(repo["html_url"]).traverse_commits():
                append_info["commits"].append({
                    "deletions": c.deletions,
                    "insertions": c.insertions,
                    "lines": c.lines,
                    "files": c.files,
                    "message": c.msg,
                    "date": c.committer_date.isoformat().format()
                })
                append_info["number_of_commits"] = append_info["number_of_commits"] + 1
            result["total_issues"] += repo["open_issues"]
            result["total_forks"] += repo["forks"]
        except Exception:
            append_info["failed"] = True

        result["repos"].append(append_info)
        rc = rc + 1
        bar.update(rc)

    with open(out_file, "w") as outfile:
        json.dump({'repos': result}, outfile)

# This function writes the activeness to a csv file for a given activeness json file created by get_activeness_for_repos
def plot_activeness(out_file, in_file):
    with open(in_file) as file:
        repos = json.load(file)["repos"]["repos"]
    commit_info = create_month_range({
        "insertions": 0,
        "deletions": 0,
        "number_of_commits": 0,
        "files": 0,
        "lines": 0
    })
    for repo in repos:
        for commit in repo["commits"]:
            date = dateutil.parser.isoparse(commit["date"])
            if date >= utc.localize(datetime.datetime.combine(start_date, datetime.datetime.min.time())):
                key = date.strftime(date_format)
                commit_info[key]["insertions"] += commit["insertions"]
                commit_info[key]["deletions"] += commit["deletions"]
                commit_info[key]["number_of_commits"] += 1
                commit_info[key]["files"] += commit["files"]
                commit_info[key]["lines"] += commit["lines"]
    csv_columns = ["date", "insertions", "deletions", "number_of_commits", "files", "lines"]
    with open(out_file, 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=csv_columns)
        writer.writeheader()
        for date, info in commit_info.items():
            info["date"] = date
            writer.writerow(info)

# This function prints the amount of issues per month to a csv file
def plot_issues(out_file, in_file):
    with open(in_file) as file:
        issues = json.load(file)["issues"]
    issue_info = create_month_range({"created": 0, "updated": 0})
    for issue in issues:

        c_date = dateutil.parser.isoparse(issue["created_at"])
        key_c = c_date.strftime(date_format)
        u_date = dateutil.parser.isoparse(issue["updated_at"])
        key_u = u_date.strftime(date_format)

        if datetime.date(2016, 1, 1) <= c_date.date():
            issue_info[key_c]["created"] += 1
        if datetime.date(2016, 1, 1) <= u_date.date():
            issue_info[key_u]["updated"] += 1
    csv_columns = ["date", "created", "updated"]
    with open(out_file, 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=csv_columns)
        writer.writeheader()
        for date, info in issue_info.items():
            info["date"] = date
            writer.writerow(info)

# Helper function to create a month range of the period used in the research
def create_month_range(content):
    result = {}
    current = datetime.date(2016, 1, 1)
    today = datetime.date.today()
    while current <= today:
        result[current.strftime(date_format)] = content.copy()
        current += relativedelta(months=1)
    return result

# This function retrieves all issues for the repositories in a given file, these are returned by
# get_activeness_for_repos
def get_issues(out_file, in_file):
    with open(in_file) as file:
        json_repos = json.load(file)
        repos = json_repos["repos"]
        issues = []
        for repo in repos:
            if repo["open_issues_count"] > 0:
                url = repo["issues_url"].replace('{/number}', '')
                response = URLResource(url, "core").get().json()
                issues = issues + response
    with open(out_file, "w") as outfile:
        json.dump({'issues': issues}, outfile)

# This function returns topics based on a given search query and writes these to a file
def get_topics(query, out_file):
    params = {"q": query}
    labels = {}
    result = resources["search_repo"].get_multiple_pages(params)
    for repo in result:
        topics = repo["topics"]
        for name in topics:
            if name in labels:
                labels[name] += 1
            else:
                labels[name] = 0
    with open(out_file, 'w') as f:
        for key in labels.keys():
            f.write("%s,%s\n" % (key, labels[key]))

# Prints all mentions from an issue file returned by get_issues, and an activeness file returned by
# get_activeness_for_repos. Mentions can be fetched based on a given list of patterns
def get_mentions(activeness_file_name, issue_file_name, patterns):
    with open(activeness_file_name) as a_file:
        repos = json.load(a_file)["repos"]["repos"]
    with open(issue_file_name) as i_file:
        issues = json.load(i_file)["issues"]
    count = 0
    for repo in repos:
        for commit in repo["commits"]:
            message = commit["message"]
            should_print = False
            for pattern in patterns:
                if re.search(pattern, message, re.IGNORECASE):
                    should_print = True
            if should_print:
                count = count + 1
                print("\n======================= Commit (" + str(count) + ") =================================")
                print(message)
                print(repo["html_url"])
                print(commit["date"])
    count = 0
    for issue in issues:
        message = issue["body"]
        should_print = False
        for pattern in patterns:
            if re.search(pattern, message, re.IGNORECASE):
                should_print = True
        if should_print:
            count = count + 1
            print("\n======================= Issue (" + str(count) + ") =================================")
            print(message)
            print(issue["html_url"])

if __name__ == '__main__':
    print("please call one of the operations in the main function")

    # Examples of how the functions can be called:
    # fetch_number_of_repos("aspectj")
    # fetch_number_of_repos(spring_aop_query)
    #
    # fetch_all_repos(spring_aop_query, "spring_repos.json")
    #
    # get_activeness_for_repos("activeness/aspectj_activeness.json", "activeness/aspectJ_repos.json")
    #
    # get_mentions("activeness/aspectj_activeness.json", "activeness/issues_AspectJ.json",
    #              ["spring aop", "springaop", "aop spring"])
    #
    # get_topics(aop_topic_query)
    #
    # plot_issues("activeness/issues_spring_total.csv", "activeness/issues_spring_aop.json")


from odoo import models, fields, api
from odoo.exceptions import ValidationError

class ProjectTask(models.Model):
    _inherit = 'project.task'

    def write(self, values):
        res = super().write(values)
        emails = []
        total_time = 0.0
        mail_template = self.env.ref(
            'clinic_management.follower_project_email_template')
        for item in self.message_follower_ids:
            emails.append(item.email)
        project = self.browse(self.id)
        hours = project.planned_hours
        perc = self.env['ir.config_parameter'].sudo(
        ).get_param('percentage', default=0)
        buffer = int(perc)/100
        extra = hours + buffer
        for i in reversed(project.timesheet_ids):
            total_time += i.unit_amount
        if total_time >= extra:
            mail_template.with_context({
                'email_to': emails[0],
                'email_cc': ", ".join(emails[1:]),
                'emp_name': item.partner_id.name,
            }).send_mail(self.id, force_send=True)
        return res

    def send_follower_email(self):
        emails = []
        mail_template = self.env.ref(
            'clinic_management.follower_project_email_template')
        for item in self.message_follower_ids:
            print("\n\n\n item email==========", item.email)
            emails.append(item.email)
        print("\n\n\n emails========", emails)
        mail_template.with_context({
            'email_to': emails[0],
            'email_cc': [mail for mail in emails[1:]],
            'emp_name': item.partner_id.name,
        }).send_mail(self.id, force_send=True)
        print("\n\n\n Success")

class ResConfigSetting(models.TransientModel):
    _inherit = 'res.config.settings'

    percentage = fields.Integer(string='Percentage:')
    @api.model
    def set_values(self):
        self.env['ir.config_parameter'].sudo().set_param(
            'percentage', self.percentage)
        super().set_values()

    @api.model
    def get_values(self):
        res = super().get_values()
        res['percentage'] = int(
            self.env['ir.config_parameter'].sudo().get_param('percentage', default=0))
        return res


# This script uses a similar approach to the MatLab stereo camera calibrator
# Firstly, the chessboard needs to be detected in each camera.
# Once a chessboard is detected -> pressing the 'b'-button saves the coordinates
# After re-placing the chessboard somewhere in the room: the 'n'-button needs to be pressed.
# Save coordinates using 'b'
# Repeat...

# Lastly: After gathering sufficient 3d-coordinates: press the 't'-button to estimate the affine transformation
# ..using the opencv-function estimateAffine3D

import pyrealsense2 as rs
import numpy as np
import cv2

pTime = 0
cTime = 0
num = 0
posList = []
posList2 = []
# cv2.estimateTranslation3D()
# initialize shared coordinate system lists
coordinates_3d_top_view_lst = []
coordinates_3d_side_view_lst = []

# Configure depth and color streams...
# width, height
width = 1280
height = 720
fps = 30
alpha = 0.5

# misc variables
test_set_ready = True

# Configure depth and color streams...
# ...of Camera 1
pipeline_1 = rs.pipeline()
config_1 = rs.config()
config_1.enable_device("151422254978")
config_1.enable_stream(rs.stream.depth, width, height, rs.format.z16, fps)
config_1.enable_stream(rs.stream.color, width, height, rs.format.bgr8, fps)
# ...of Camera 2
pipeline_2 = rs.pipeline()
config_2 = rs.config()
config_2.enable_device("151422254651")
config_2.enable_stream(rs.stream.depth, width, height, rs.format.z16, fps)
config_2.enable_stream(rs.stream.color, width, height, rs.format.bgr8, fps)

# Start streaming from both cameras
pipeline_profile_1 = pipeline_1.start(config_1)
pipeline_profile_2 = pipeline_2.start(config_2)

# Activate RealSense colorizer
colorizer = rs.colorizer()

# Chessboard specifics
chessboardSize = (9, 7)
frameSize = (width, height)
size_of_chessboard_squares_mm = 25

# Termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((chessboardSize[0] * chessboardSize[1], 3), np.float32)
objp[:, :2] = np.mgrid[0 : chessboardSize[0], 0 : chessboardSize[1]].T.reshape(-1, 2)
objp = objp * size_of_chessboard_squares_mm

# Arrays to store object points and image points from all the images.
objpoints = []  # 3d point in real world space
imgpointsL = []  # 2d points in image plane.
imgpointsR = []  # 2d points in image plane.

# pixelpoints
pixelpoints_top_view_lst = []
pixelpoints_side_view_lst = []
delta_lst = []
shared_3d = []

alpha_0 = 0.5

# stream specific data
depth_scale_1 = pipeline_profile_1.get_device().first_depth_sensor().get_depth_scale()
depth_scale_2 = pipeline_profile_2.get_device().first_depth_sensor().get_depth_scale()

try:
    while True:
        frames_1 = pipeline_1.wait_for_frames()
        depth_frame_1 = frames_1.get_depth_frame()
        color_frame_1 = frames_1.get_color_frame()

        # Intrinsic and extrinsic matrices of camera 1
        color_intrinsic_1 = (
            color_frame_1.profile.as_video_stream_profile().intrinsics
        )  #
        depth_intrinsic_1 = (
            depth_frame_1.profile.as_video_stream_profile().intrinsics
        )  #
        depth_to_color_extrinsic_1 = depth_frame_1.profile.get_extrinsics_to(
            color_frame_1.profile
        )
        color_to_depth_extrinsic_1 = color_frame_1.profile.get_extrinsics_to(
            depth_frame_1.profile
        )

        if not depth_frame_1 or not color_frame_1:
            continue

        # Convert images to numpy arrays
        depth_image_1 = np.asanyarray(depth_frame_1.get_data())
        color_image_1 = np.asanyarray(color_frame_1.get_data())
        color_image_1 = cv2.cvtColor(color_image_1, cv2.COLOR_BGR2RGB)

        # align depth_to_rgb 1
        align_1 = rs.align(rs.stream.color)
        frames_1 = align_1.process(frames_1)
        aligned_depth_frame_1 = frames_1.get_depth_frame()
        colorized_depth_1 = np.asanyarray(
            colorizer.colorize(aligned_depth_frame_1).get_data()
        )

        # Camera 2
        # Wait for a coherent pair of frames: depth and color
        frames_2 = pipeline_2.wait_for_frames()
        depth_frame_2 = frames_2.get_depth_frame()
        color_frame_2 = frames_2.get_color_frame()

        color_intrinsic_2 = (
            color_frame_2.profile.as_video_stream_profile().intrinsics
        )  #
        depth_intrinsic_2 = (
            depth_frame_2.profile.as_video_stream_profile().intrinsics
        )  #
        depth_to_color_extrinsic_2 = depth_frame_2.profile.get_extrinsics_to(
            color_frame_2.profile
        )
        color_to_depth_extrinsic_2 = color_frame_2.profile.get_extrinsics_to(
            depth_frame_2.profile
        )

        if not depth_frame_2 or not color_frame_2:
            continue

        # Convert images to numpy arrays
        depth_image_2 = np.asanyarray(depth_frame_2.get_data())
        color_image_2 = np.asanyarray(color_frame_2.get_data())

        # align depth_to_rgb 2
        align_2 = rs.align(rs.stream.color)
        frames_2 = align_2.process(frames_2)
        aligned_depth_frame_2 = frames_2.get_depth_frame()
        # depth visualization
        # colorized_depth_2 = np.asanyarray(colorizer.colorize(filtered_2).get_data())
        colorized_depth_2 = np.asanyarray(
            colorizer.colorize(aligned_depth_frame_2).get_data()
        )

        # prepare chessboard detection by graying images
        grayL = cv2.cvtColor(color_image_2, cv2.COLOR_BGR2GRAY)
        grayR = cv2.cvtColor(color_image_1, cv2.COLOR_BGR2GRAY)

        # find chessboard corners
        retL, cornersL = cv2.findChessboardCorners(grayL, chessboardSize, None)
        retR, cornersR = cv2.findChessboardCorners(grayR, chessboardSize, None)

        # side view
        if cv2.waitKey(33) == ord("b"):
            if test_set_ready:
                for x in range(len(cornersR)):
                    rs.rs2_project_color_pixel_to_depth_pixel(
                        depth_frame_2.get_data(),
                        depth_scale_2,
                        0.2,
                        1,
                        depth_intrinsic_2,
                        color_intrinsic_2,
                        depth_to_color_extrinsic_2,
                        color_to_depth_extrinsic_2,
                        [cornersR[x][0][0], cornersR[x][0][1]],
                    )
                    coordinates_3d_top_shared = rs.rs2_deproject_pixel_to_point(
                        depth_intrinsic_2,
                        [cornersR[x][0][0], cornersR[x][0][1]],
                        depth_frame_2.get_distance(
                            int(cornersR[x][0][0]), int(cornersR[x][0][1])
                        ),
                    )
                    # coordinates_3d_top_shared = rs.rs2_deproject_pixel_to_point(color_intrinsic_2, [cornersR[x][0][0], cornersR[x][0][1]],
                    #                                                             aligned_depth_frame_2.get_distance(int(cornersR[x][0][0]), int(cornersR[x][0][1])))
                    coordinates_3d_top_view_lst.append(coordinates_3d_top_shared)
                    pixelpoints_top_view_lst.append(
                        [cornersR[x][0][0], cornersR[x][0][1]]
                    )
                # top view
                for y in range(len(cornersL)):
                    rs.rs2_project_color_pixel_to_depth_pixel(
                        depth_frame_1.get_data(),
                        depth_scale_1,
                        0.2,
                        1,
                        depth_intrinsic_1,
                        color_intrinsic_1,
                        depth_to_color_extrinsic_1,
                        color_to_depth_extrinsic_1,
                        [cornersR[y][0][0], cornersR[y][0][1]],
                    )
                    coordinates_3d_side_shared = rs.rs2_deproject_pixel_to_point(
                        depth_intrinsic_1,
                        [cornersR[y][0][0], cornersR[y][0][1]],
                        depth_frame_1.get_distance(
                            int(cornersR[y][0][0]), int(cornersR[y][0][1])
                        ),
                    )

                    coordinates_3d_side_view_lst.append(coordinates_3d_side_shared)
                    pixelpoints_side_view_lst.append(
                        [cornersL[y][0][0], cornersL[y][0][1]]
                    )

                if len(coordinates_3d_top_view_lst) >= 54:

                    test_set_ready = False
                    print("Saved 3d coordinates of corresponding points in each view.")
                    print("Change position of chessboard.")
                    print('Press "n" once ready.')

        # ready up next test_set
        if cv2.waitKey(33) == ord("n"):
            print('Getting new set of coordinates upon "b" press..')
            print("TOP-LIST:", coordinates_3d_top_view_lst)
            print("SIDE-LIST:", coordinates_3d_side_view_lst)
            test_set_ready = True

        # Clear/Empty current calibration check list on 'c' press
        if cv2.waitKey(33) == ord("c"):
            coordinates_3d_top_view_lst.clear()
            coordinates_3d_side_view_lst.clear()
            pixelpoints_side_view_lst.clear()
            pixelpoints_top_view_lst.clear()
            delta_lst.clear()
            print("..cleared lists")

        if cv2.waitKey(33) == ord("t"):
            if coordinates_3d_side_view_lst:
                coordinates_3d_top_np = np.asarray(coordinates_3d_top_view_lst)
                coordinates_3d_side_np = np.asarray(coordinates_3d_side_view_lst)
                print("TOP 3D asarray:", coordinates_3d_top_np)
                print("SIDE 3D asarray:", coordinates_3d_side_np)
                ret_val, transformation_3x4, inliers = cv2.estimateAffine3D(
                    coordinates_3d_side_np, coordinates_3d_top_np
                )
                print("Estimated 3D Affine:")
                print(transformation_3x4)

        if retL and retR:
            cornersL = cv2.cornerSubPix(grayL, cornersL, (11, 11), (-1, -1), criteria)
            imgpointsL.append(cornersL)

            cornersR = cv2.cornerSubPix(grayR, cornersR, (11, 11), (-1, -1), criteria)
            imgpointsR.append(cornersR)

            # Draw and display the corners
            cv2.drawChessboardCorners(color_image_2, chessboardSize, cornersL, retL)
            # cv2.imshow('img top', color_image_2)
            cv2.drawChessboardCorners(color_image_1, chessboardSize, cornersR, retR)
            # cv2.imshow('img side', color_image_1)
            cv2.waitKey(1)

        cv2.imshow("Color Stream Side", color_image_2)
        cv2.imshow("Color Stream Top", color_image_1)

    # cv2.waitKey(1)
    # cv2.destroyAllWindows()

finally:
    pass


import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn
from tensorflow.examples.tutorials.mnist import input_data

sess = tf.Session()
mnist = input_data.read_data_sets('data', one_hot=True)
print(mnist.train.images.shape)

# 设置参数
lr = 1e-3
input_size = 28 # 每行输入28个特征点
timestep_size = 28 # 持续输入28行
hidden_size = 256 # 隐含层的数量
layer_num = 2 # LSTM layer的层数
class_num = 10 # 10分类问题

_X = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, class_num])

batch_size = tf.placeholder(tf.int32, [])
keep_prob = tf.placeholder(tf.float32,[])

# 定义网络结构
X = tf.reshape(_X, [-1, 28, 28])

def lstm_cell():
    cell = rnn.LSTMCell(hidden_size, reuse=tf.get_variable_scope().reuse)
    return rnn.DropoutWrapper(cell, output_keep_prob=keep_prob)

# 堆叠两层LSTM
mlstm_cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(layer_num)], state_is_tuple = True)

# 全0初始化状态
init_state = mlstm_cell.zero_state(batch_size, dtype=tf.float32)


from flask import Flask, request, render_template
from datetime import datetime
from twilio.rest import TwilioRestClient
import time
import threading

account_sid = "put account sid here"
auth_token = "put auth token here"
client = TwilioRestClient(account_sid, auth_token)

def makeAppointment(seconds, message,phonenumber):
    print('thread started')
    time.sleep(seconds)
    sendSMS(message,phonenumber)
    return None

def sendSMS(message, phonenumber):
    client.messages.create(to="+1"+str(phonenumber), from_="put phone number here",body=message)
    return None

app = Flask(__name__, static_url_path='')

#GET for setting appointment
@app.route('/')
def index():
    return app.send_static_file('landingPage.html')

@app.route('/makeapointment',methods=['POST'])
def appointment():
        if request.method == 'POST':
                phonenumber = request.form['phone']
                message = request.form['message']
                time = request.form['dateandtime']
                year = int(time.split('-')[0])
                day =  int(time.split('-')[2].split('T')[0])
                month = int(time.split('-')[1])
                hour = int(time.split('T')[1].split(':')[0])
                minute = int(time.split('T')[1].split(':')[1])
                date = datetime(year,month,day,hour,minute)
                # get the total seconds between the current time and time the sms is due
                difference = int((date - datetime.now()).total_seconds())
                if difference > 0:
                    t = threading.Thread(target=makeAppointment, args=(difference,message,phonenumber))
                    t.start()
                    return 'Reminder Set'
                else:
                    return "Try again bois"
        else:
            index()
if __name__ == "__main__": app.run(host='0.0.0.0', debug=True)


# Form / Spinbox / Trigger
# Enable the `trigger` attribute in order to handle live changes to a spinbox.
# #form #spinbox #trigger
# ---
from typing import Optional
from h2o_wave import main, app, Q, ui

def get_form_items(value: Optional[float]):
    return [
        ui.text(f'spinbox_trigger={value}'),
        ui.spinbox(name='spinbox_trigger', label='Pick a number', trigger=True),
    ]

@app('/demo')
async def serve(q: Q):
    if not q.client.initialized:
        q.page['example'] = ui.form_card(box='1 1 4 4', items=get_form_items(None))
        q.client.initialized = True
    if q.args.spinbox_trigger is not None:
        q.page['example'].items = get_form_items(q.args.spinbox_trigger)

    await q.page.save()


import numpy as np

from .monitor import Monitor
from .cie_monitor_helpers import rgb2xyz, xyz2rgb
from .matlab import matlab_rgb2xyz

lab_delta = 6/29
def lab_f(t):
    if t > np.power(lab_delta, 3):
        return np.power(t, 0.3333333333333333)
    else:
        return t/(3 * (np.power(lab_delta, 2))) + 4/29

def xyz2lab(mon: Monitor, XYZ):
    xyz_s = XYZ / mon.monWP
    xsf = lab_f(xyz_s[0])
    ysf = lab_f(xyz_s[1])
    zsf = lab_f(xyz_s[2])

    l = 116 * ysf - 16
    a = 500 * (xsf - ysf)
    b = 200 * (ysf - zsf)

    return np.array([l, a, b])

def xyz2lab_wo_mon(WP, XYZ):
    xyz_s = XYZ / WP
    xsf = lab_f(xyz_s[0])
    ysf = lab_f(xyz_s[1])
    zsf = lab_f(xyz_s[2])

    l = 116 * ysf - 16
    a = 500 * (xsf - ysf)
    b = 200 * (ysf - zsf)

    return np.array([l, a, b])

def lab_inv_f(t):
    if t > lab_delta:
        return np.power(t, 3)
    else:
        return (3 * (np.power(lab_delta, 2))) * (t - 4/29)

def lab2xyz(mon: Monitor, LAB):
    """
    Convert a color from CIELAB color space to XYZ color space.

    Args:
        mon (Monitor): The monitor object containing the white point values.
        LAB (tuple): A tuple containing the L, a, and b values of the color.

    Returns:
        numpy.ndarray: An array containing the X, Y, and Z values of the color in the XYZ color space.
    """
    l = LAB[0]
    a = LAB[1]
    b = LAB[2]

    x_pre_f = (l+16)/116 + (a/500)
    y_pre_f = (l+16)/116
    z_pre_f = (l+16)/116 - b/200

    X = mon.monWP[0] * lab_inv_f(x_pre_f)
    Y = mon.monWP[1] * lab_inv_f(y_pre_f)
    Z = mon.monWP[2] * lab_inv_f(z_pre_f)

    return np.array([X, Y, Z])

def rgb2lab(mon: Monitor, rgb):
    """
    Convert an RGB color to the CIELAB color space.

    Args:
        mon (Monitor): The monitor object.
        rgb (tuple): A tuple containing the red, green, and blue values of the color.

    Returns:
        tuple: A tuple containing the L*, a*, and b* values of the color in the CIELAB color space.
    """
    xyz = rgb2xyz(mon, rgb)
    return xyz2lab(mon, xyz)

def lab2rgb(mon: Monitor, lab):
    """
    Convert a color from CIELAB color space to RGB color space.

    Args:
        mon (Monitor): The monitor object.
        lab (tuple): The CIELAB color values.

    Returns:
        tuple: The RGB color values.
    """
    xyz = lab2xyz(mon, lab)
    return xyz2rgb(mon, xyz)

def matlab_rgb2lab(mon: Monitor, rgb):
    xyz = matlab_rgb2xyz(mon, rgb)
    return xyz2lab(mon, xyz)

def lstar(mon: Monitor, rgb):
    """
    Convert an RGB color to the L* component of the CIELAB color space.

    Args:
        mon (Monitor): The monitor on which the color is displayed.
        rgb (tuple): A tuple containing the red, green, and blue values of the color.

    Returns:
        float: The L* component of the color in the CIELAB color space.
    """
    lab = rgb2lab(mon, rgb)
    return lab[0]

def chroma(mon: Monitor, rgb):
    """
    Calculates the chroma value of an RGB color using the CIELAB color space.

    Args:
        mon (Monitor): The monitor object used to convert the RGB color to CIELAB.
        rgb (tuple): A tuple containing the red, green, and blue values of the color.

    Returns:
        float: The chroma value of the color.
    """
    lab = rgb2lab(mon, rgb)
    a = lab[1]
    b = lab[2]
    return np.sqrt(np.power(a, 2) + np.power(b, 2))

def hue(lab):
    """
    Calculates the hue value of a color in the CIELAB color space.

    Args:
        lab (tuple): A tuple containing the L*, a*, and b* values of the color.

    Returns:
        float: The hue value of the color in radians.
    """
    a = lab[1]
    b = lab[2]

    h = np.arctan2(b, a)
    if h < 0:
        return h + 2*np.pi

    return h


import random
from art import logo

print(logo)

def get_card():
    """return a random card from the deck"""
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    card = random.choice(cards)
    return card

def calculate_score(cards):

    if sum(cards) == 21 and len(cards) == 2:
        return 0
    return sum(cards)
    if 11 in cards and sum(cards) > 21:
        cards.remove(11)
        card.append(1)

def compare(userScore, computerScore):
    if user_score == computer_score:
        return "draw"
    elif computer_score == 0:
        return "lose, opponent has blackjack"
    elif userScore == 0:
        return "win with a black jack"
    elif user_score > 21:
        return "you went over, you loose"
    elif computerScore == 21:
        return "Opponent went over, you win"
    elif user_score > computer_score:
        return "you win"
    else:
        return "you loose"

is_game_over = False
user_cards = []
computer_card = []

for _ in range(2):
    user_cards.append(get_card())
    computer_card.append(get_card())

while not is_game_over:

    user_score = calculate_score(user_cards)
    computer_score = calculate_score(computer_card)
    print(" Your cars:{}, currrent socore: {}".format(user_cards, user_score))
    print(" Computer first card {} ".format(
        computer_card[0]))
    if user_cards == 0 or computer_score or user_score > 21:
        is_game_over = True
    else:
        new_card = input("type 'y' to get another card, type 'n' to pass: ")
        if new_card == "y":
            user_cards.append(get_card())
        else:
            is_game_over = True
while computer_score != 0 and computer_score < 17:
    computer_card.append(get_card())
    computer_score = calculate_score(computer_card)

print(compare(user_score, computer_score))


#! python3.5
# regex_search.py - Searches all .txt files in directory for user-supplied regular expression.
# It then prints the results to the screnn

import os
import re

final_list = []

# text file regex
text = re.compile(r'\w+.txt')

# get input
print('Enter regular expression to search for:')
regex_input = input()
print('\n')
user_regex = re.compile('{0}'.format(regex_input))

for file in os.listdir('.'):
    if text.search(file):
        text_file = open(file, 'r')
        text_file_content = text_file.readlines()
        for string in text_file_content:
            if user_regex.search(string):
                final_list.append(string)
        text_file.close()

for string in final_list:
    print(string, end='')


def three_pair():
    '''finds the words that have 3 consecutive pairs of letters'''
    with open("words.txt") as file:
        for line in file:
            if len(line) >=6:
                for i in range(len(line)-6):
                    if line[i] == line[i+1] and line[i+2] == line[i+3] and line[i+4]==line[i+5]:
                        print(line)

if __name__ == "__main__":
    three_pair()


import streamlit as st
import pandas as pd
from streamlit_lottie import st_lottie
import requests
from helper import get_used_languages, init_lang_dict_complete, get_lang
from streamlit_option_menu import option_menu
from enum import Enum
import datetime

import nbcn

__version__ = "0.0.12"
__author__ = "Lukas Calmbach"
__author_email__ = "lcalmbach@gmail.com"
VERSION_DATE = "2023-09-18"
APP_NAME = "ClimateSciGraph"
GIT_REPO = "https://github.com/lcalmbach/nbcn-browser"
PAGE = "app"

lang = {}
LOTTIE_URL = "https://assets9.lottiefiles.com/temp/lf20_rpC1Rd.json"
LOTTIE_URL = "https://lottie.host/016f9a14-ca58-4ade-85fa-ccce6bbc9318/ApQE6zjqWN.json"

class Menu(Enum):
    ABOUT = 0
    STATIONS = 1
    BROWSE = 2
    MONTHLY = 3
    TREND = 4
    RESSOURCES = 5

def init():
    st.set_page_config(
        page_title=APP_NAME,
        page_icon="🌡",
        layout="wide",
        initial_sidebar_state="expanded",
    )
    if not ("lang" in st.session_state):
        # first item is default language
        st.session_state["lang_dict"] = {}
        init_lang_dict_complete("app.py", PAGE)
        st.session_state["used_languages_dict"] = get_used_languages(
            st.session_state["lang_dict"][PAGE]
        )
        st.session_state["lang"] = next(
            iter(st.session_state["used_languages_dict"].items())
        )[0]
        st.session_state["last_data_refresh"] = datetime.datetime.now().strftime("%x")

def get_menu_selection(menu_options):
    # https://icons.getbootstrap.com/
    with st.sidebar:
        st.markdown(f"## {APP_NAME}")
        return option_menu(
            None,
            menu_options,
            icons=["house", "geo", "database", "calendar-month", "graph-up", "archive"],
            menu_icon="cast",
            default_index=0,
        )

def get_app_info():
    """
    Returns a string containing information about the application.
    Returns:
    - info (str): A formatted string containing details about the application.
    """
    created_by = lang["created-by"]
    powered_by = lang["powered-by"]
    version = lang["version"]
    translation = lang["translation"]
    data_source = lang["data-source"]

    info = f"""

    {created_by} {__author__}

    {version}: {__version__} ({VERSION_DATE})

    {data_source}: MeteoSwiss

    {powered_by} Streamlit, pymannkendall

    {translation} PolyglotGPT

    git-repo

    """
    return info

def display_language_selection():
    """
    The display_info function displays information about the application. It
    uses the st.expander container to create an expandable section for the
    information. Inside the expander, displays the input and output format.
    """
    index = list(st.session_state["used_languages_dict"].keys()).index(
        st.session_state["lang"]
    )
    x = st.sidebar.selectbox(
        label=f'🌐{lang["language"]}',
        options=st.session_state["used_languages_dict"].keys(),
        format_func=lambda x: st.session_state["used_languages_dict"][x],
        index=index,
    )
    if x != st.session_state["lang"]:
        st.session_state["lang"] = x
        st.experimental_rerun()

@st.cache_data(show_spinner=False)
def get_lottie():
    """Performs a GET request to fetch JSON data from a specified URL.

    Returns:
        tuple: A tuple containing the JSON response and a flag indicating the
        success of the request.

    Raises:
        requests.exceptions.RequestException: If an error occurs during the
        GET request. ValueError: If an error occurs while parsing the JSON
        response.
    """
    ok = True
    r = None
    try:
        response = requests.get(LOTTIE_URL)
        r = response.json()
    except requests.exceptions.RequestException as e:
        print(lang["get-request-error"]).format(e)
        ok = False
    except ValueError as e:
        print(lang["json-parsing-error"].format(e))
        ok = False
    return r, ok

def show_lottie():
    """
    Displays lottie animation if it is available.
    """
    lottie_search_names, ok = get_lottie()
    if ok:
        with st.sidebar:
            st_lottie(lottie_search_names, height=140, loop=20)
    else:
        pass

def main() -> None:
    """
    This function runs an app that classifies text data. Depending on the user's
    input option, it retrieves data from a demo or an uploaded file. Then,
    randomly selects a fixed number of records from the dataframe provided using
    record_selection function. The selected dataframe and dictionary of categories
    are previewed on the screen. If the user presses classify, the function runs the
    Classifier class on the selected dataframe, returns a response dataframe, and
    offers the user the option to download the dataframe to a CSV file.
    """
    global lang

    init()

    lang = get_lang(PAGE)
    with st.spinner(lang["loading-data"]):
        # if not ("ncbn" in st.session_state):
        st.session_state.ncbn = nbcn.NCBN(APP_NAME)
    show_lottie()
    ncbn = st.session_state.ncbn
    ncbn.menu_selection = get_menu_selection(ncbn.menu_options)
    display_language_selection()
    st.sidebar.markdown(get_app_info(), unsafe_allow_html=True)

if __name__ == "__main__":
    main()


from instatelemod import setting
from configparser import SafeConfigParser

class getlang:
	def __init__(self, comm, mVal):
		dirutama = setting.dirutama()
		lang = SafeConfigParser()
		lang.read(dirutama+'/instatelemod/lang/id_ID.ini')
		msg = lang.get(comm, mVal)
		self.msg = msg

def pesan(comm, mVal):
	lang = getlang(comm, mVal)
	message = (lang.msg)
	return message

def info(comm, mVal, fVal, sVal):
	f = fVal
	s = sVal
	lang = getlang(comm, mVal)
	msg = lang.msg
	message = (msg + f + ' paling banyak ' + s + ' like.')
	return message


import lightbulb
from decouple import config
from hikari import MessageFlag

debug_plugin = lightbulb.Plugin("Debug")

@debug_plugin.command
@lightbulb.add_checks(lightbulb.has_roles(config("ELEVATED_ROLES", cast=int)))
@lightbulb.command("debug", "Manage internal settings for the bot", hidden=True)
@lightbulb.implements(lightbulb.SlashCommandGroup, lightbulb.PrefixCommandGroup)
async def module_group(ctx: lightbulb.Context) -> None:
  pass

@module_group.child
@lightbulb.option("module_name", "The module to target.", type=str)
@lightbulb.command("reload", "Reloads a module.", inherit_checks=True)
@lightbulb.implements(lightbulb.SlashSubCommand, lightbulb.PrefixSubCommand)
async def reload_module(ctx: lightbulb.Context):
  """Reload a module in Tanjun"""

  module_name = getModuleName(ctx)

  try:
    ctx.bot.reload_extensions(module_name)
  except ValueError:
    ctx.bot.load_extensions(module_name)

  #await ctx.bot.declare_global_commands()
  await ctx.respond(f"Reloaded module {module_name}", flags=MessageFlag.EPHEMERAL)

# @module_group.child
# @lightbulb.option("module_name", "The module to target.")
# @lightbulb.command("unload", "Removes a module.", inherit_checks=True)
# @lightbulb.implements(lightbulb.SlashSubCommand, lightbulb.PrefixSubCommand)
# async def unload_module(ctx: lightbulb.Context):
#   """Unload a module in Tanjun"""

#   module_name = getModuleName(ctx)

#   try:
#     ctx.bot.unload_extensions(module_name)
#   except lightbulb.errors.ExtensionMissingUnload or lightbulb.errors.ExtensionNotFound:
#     await ctx.respond(f"Couldn't unload module {module_name}", flags=MessageFlag.EPHEMERAL)
#     return

#   # Set global commands again?
#   await ctx.respond("Unloaded!")

# @module_group.child
# @lightbulb.option("module_name", "The module to reload.")
# @lightbulb.command("load", "Loads a module.", inherit_checks=True)
# @lightbulb.implements(lightbulb.SlashSubCommand, lightbulb.PrefixSubCommand)
# async def load_module(ctx: lightbulb.Context):
#   """Load a module in Tanjun"""

#   module_name = getModuleName(ctx)

#   try:
#     ctx.bot.load_extensions(module_name)
#   except lightbulb.errors.ExtensionAlreadyLoaded or lightbulb.errors.ExtensionMissingLoad:
#     await ctx.respond(f"Can't find module {module_name}", flags=MessageFlag.EPHEMERAL)
#     return

#   #await ctx.bot.declare_global_commands()
#   await ctx.respond("Loaded!")

@module_group.child
@lightbulb.command("test", "Puts the bot in testing mode.", inherit_checks=True)
@lightbulb.implements(lightbulb.SlashSubCommand, lightbulb.PrefixSubCommand)
async def test_module(ctx: lightbulb.Context):
  """Put a module into test mode"""
  if not ctx.bot.d.testmode:
    ctx.bot.d.testmode = True
  else:
    ctx.bot.d.testmode = not ctx.bot.d.testmode

  prefix = "en" if ctx.bot.d.testmode else "dis"
  await ctx.respond(f"Test mode {prefix}abled!")

def load(bot: lightbulb.BotApp) -> None:
  bot.add_plugin(debug_plugin)

def getModuleName(ctx: lightbulb.Context) -> str:
  return f"modules.{ctx.options.module_name}"


import argparse
from collections import Counter
import code
import os
import logging
from tqdm import tqdm, trange
import random

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset

from transformers import AdamW, WarmupLinearSchedule
from transformers import BertConfig, BertForSequenceClassification, BertTokenizer
from transformers import glue_convert_examples_to_features as convert_examples_to_features
from transformers.data.processors.utils import DataProcessor, InputExample

import numpy as np
import pandas as pd

logger = logging.getLogger(__name__)

def set_seed(args):
	random.seed(args.seed)
	np.random.seed(args.seed)
	torch.manual_seed(args.seed)

class FAQProcessor(DataProcessor):
	"""Processor for the FAQ problem
		modified from https://github.com/huggingface/transformers/blob/master/transformers/data/processors/glue.py#L154
	"""
	def get_train_examples(self, data_dir):
		return self._create_examples(
			os.path.join(data_dir, "train.csv"))

	def get_dev_examples(self, data_dir):
		return self._create_examples(
			os.path.join(data_dir, "dev.csv"))

	def get_labels(self):
		return [0, 1]

	def _create_examples(self, path):
		df = pd.read_csv(path)
		examples = []
		titles = [str(t)[:100] for t in df["title"].tolist()]
		replies = [str(t)[:100] for t in df["reply"].tolist()]
		labels = df["is_best"].astype("int").tolist()
		for i in range(len(labels)):
			examples.append(
				InputExample(guid=i, text_a=titles[i], text_b=replies[i], label=labels[i]))
		return examples

def train(args, train_dataset, model, tokenizer):
	"""Train the model"""
	train_sampler = RandomSampler(train_dataset)
	train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)

	if args.max_steps > 0:
		t_total = args.max_steps
		args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
	else:
		t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs

	no_decay = ['bias', 'LayerNorm.weight']
	optimizer_grouped_parameters = [
		{'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay},
		{'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
		]
	optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
	scheduler = WarmupLinearSchedule(optimizer, warmup_steps=args.warmup_steps, t_total=t_total)

	logger.info("***** Running training *****")
	logger.info("  Num examples = %d", len(train_dataset))
	logger.info("  Num Epochs = %d", args.num_train_epochs)
	logger.info("  Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
	logger.info("  Total optimization steps = %d", t_total)

	global_step = 0
	tr_loss, logging_loss = 0.0, 0.0
	model.zero_grad()
	train_iterator = trange(int(args.num_train_epochs), desc="Epoch")
	set_seed(args)
	for _ in train_iterator:
		epoch_iterator = tqdm(train_dataloader, desc="Iteration")
		for step, batch in enumerate(epoch_iterator):
			model.train()
			batch = tuple(t.to(args.device) for t in batch)
			inputs = {'input_ids':      batch[0],
					'attention_mask': batch[1],
					'token_type_ids': batch[2],
					'labels':         batch[3]}
			outputs = model(**inputs)
			loss = outputs[0]
			if args.gradient_accumulation_steps > 1:
				loss = loss / args.gradient_accumulation_steps
			loss.backward()
			torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
			tr_loss += loss.item()
			if (step + 1) % args.gradient_accumulation_steps == 0:
				scheduler.step()  # Update learning rate schedule
				optimizer.step()
				model.zero_grad()
				global_step += 1
			if args.max_steps > 0 and global_step > args.max_steps:
				epoch_iterator.close()
				break
		if args.max_steps > 0 and global_step > args.max_steps:
			train_iterator.close()
			break

	return global_step, tr_loss / global_step

def evaluate(args, model, tokenizer):
	pass
	# 请同学们自己完成这一部分

def load_and_cache_examples(args, tokenizer, evaluate=False):
	""" modified from https://github.com/huggingface/transformers/blob/702f589848baba97ea4897aa3f0bb937e1ec3bcf/examples/run_glue.py#L261"""
	processor = FAQProcessor()
	cached_features_file = "cached_{}".format("dev" if evaluate else "train")
	if os.path.exists(cached_features_file):
		features = torch.load(cached_features_file)
	else:
		label_list = processor.get_labels()
		examples = processor.get_dev_examples(args.data_dir) if evaluate else processor.get_train_examples(args.data_dir)
		features = convert_examples_to_features(
			examples=examples,
			tokenizer=tokenizer,
			max_length=args.max_seq_length,
			label_list=label_list,
			output_mode="classification",
			pad_on_left=False,
			pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0],
			pad_token_segment_id=0)
		logger.info("Saving features into cached file %s", cached_features_file)
		torch.save(features, cached_features_file)

	all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
	all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
	all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long)
	all_label = torch.tensor([f.label for f in features], dtype=torch.long)
	dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_label)
	return dataset

def main():
	parser = argparse.ArgumentParser()
	parser.add_argument('--seed', type=int, default=42,
						help="random seed for initialization")
	parser.add_argument("--data_dir", default=None, type=str, required=True,
						help="directory containing the data")
	parser.add_argument("--output_dir", default="BERT_output", type=str, required=True,
						help="The model output save dir")
	parser.add_argument("--do_train", action='store_true', help="Whether to run training.")
	parser.add_argument("--do_eval", action='store_true', help="Whether to run eval on the dev set.")
	parser.add_argument("--evaluate_during_training", action='store_true',
						help="Run evaluation during training at each logging step.")

	parser.add_argument("--max_seq_length", default=128, type=int, required=False,
						help="maximum sequence length for BERT sequence classificatio")
	parser.add_argument("--max_steps", default=-1, type=int,
						help="If > 0: set total number of training steps to perform. Override num_train_epochs.")
	parser.add_argument("--warmup_steps", default=0, type=int,
						help="Linear warmup over warmup_steps.")
	parser.add_argument('--gradient_accumulation_steps', type=int, default=1,
						help="Number of updates steps to accumulate before performing a backward/update pass.")
	parser.add_argument("--num_train_epochs", default=3.0, type=float,
						help="Total number of training epochs to perform.")
	parser.add_argument("--learning_rate", default=5e-5, type=float,
						help="The initial learning rate for Adam.")
	parser.add_argument("--weight_decay", default=0.0, type=float,
						help="Weight deay if we apply some.")
	parser.add_argument("--max_grad_norm", default=1.0, type=float,
						help="Max gradient norm.")
	parser.add_argument("--adam_epsilon", default=1e-8, type=float,
						help="Epsilon for Adam optimizer.")

	parser.add_argument("--train_batch_size", default=64, type=int, required=False,
						help="batch size for train and eval")
	parser.add_argument('--logging_steps', type=int, default=50,
						help="Log every X updates steps.")

	args = parser.parse_args()
	logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s -   %(message)s',
						datefmt = '%m/%d/%Y %H:%M:%S',
						level = logging.INFO)

	# load dataset
	processor = FAQProcessor()
	tokenizer = BertTokenizer.from_pretrained('bert-base-chinese', cache_dir="./cache")
	model = BertForSequenceClassification.from_pretrained('bert-base-chinese', cache_dir="./cache")

	label_list = processor.get_labels()
	num_labels = len(label_list)
	args.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
	model = model.to(args.device)
	# code.interact(local=locals())

	if args.do_train:
		train_dataset = load_and_cache_examples(args, tokenizer, evaluate=False)
		global_step, tr_loss = train(args, train_dataset, model, tokenizer)
		logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)

		if not os.path.exists(args.output_dir):
			os.makedirs(args.output_dir)

		logger.info("Saving model checkpoint to %s", args.output_dir)
		model_to_save = model.module if hasattr(model, 'module') else model
		model_to_save.save_pretrained(args.output_dir)
		tokenizer.save_pretrained(args.output_dir)
		torch.save(args, os.path.join(args.output_dir, 'training_args.bin'))
		model = BertForSequenceClassification.from_pretrained(args.output_dir)
		tokenizer = BertTokenizer.from_pretrained(args.output_dir)
		model = model.to(args.device)

	""" if args.do_eval:
			run evaluation code
	"""

if __name__ == "__main__":
	main()