import collections
import random
import json
import os

import sys
root_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(root_dir)
# print(f'{sys.path}')

from torch.utils.data import Dataset, DataLoader

from model.hoho_utils import *
from model.hoho_config import *

class CChessGame:

    def __init__(self, state=INIT_BOARD_STATE, restrict_count=RESTRICT_ROUND_NUM, winner=None, current_player=PLAYER_RED):
        self.state = state
        self.restrict_count = restrict_count
        self.winner = winner
        self.current_player = current_player

        print(f'{LOG_TAG_CCHESSGAME} CChessGame created!')

    def step(self, action):
        state_new = do_action_on_board(self.state, action)
        z = 0
        done = False
        if 'K' not in state_new:
            z = -1
            done = True
            self.winner = PLAYER_BLACK
        elif 'k' not in state_new:
            z = 1
            done = True
            self.winner = PLAYER_RED
        else:
            # hoho_todo: 增加restrict_count的逻辑
            pass

        self.state = state_new
        return state_new, z, done

    def reset(self):
        self.state = INIT_BOARD_STATE
        self.restrict_count = RESTRICT_ROUND_NUM
        self.winner = None
        self.current_player = PLAYER_RED

class ChessDataset(Dataset):

    def __init__(self, data_list=None):
        super(ChessDataset, self).__init__()
        # 注意：需要在这里将list转换为tensor, 否则dataloader取每个batch时，batch_size不会在第0维
        self.data_list = [(exp[0], torch.tensor(exp[1], dtype=torch.float), exp[2]) for exp in data_list]

    def __len__(self):
        return len(self.data_list)

    def __getitem__(self, idx):
        experience = self.data_list[idx]
        return experience[0], experience[1], experience[2]

    @staticmethod
    def load_from_dir(dirpath, version=None):
        if not os.path.exists(dirpath):
            return None

        all_data_list = list()
        for filename in os.listdir(dirpath):
            if filename.endswith('json') and filename.startswith('replay_buffer'):
                if version is  None:
                    with open(os.path.join(dirpath, filename), 'r') as f:
                        jsonstr = f.read()
                        data_list = json.loads(jsonstr)
                        all_data_list.extend(data_list)
                else:
                    name = filename.split('.')[0]
                    items = name.split('_')
                    if len(items) == 4:
                        check_version = int(items[3])
                        if version == check_version:
                            with open(os.path.join(dirpath, filename), 'r') as f:
                                jsonstr = f.read()
                                data_list = json.loads(jsonstr)
                                all_data_list.extend(data_list)

        dataset = ChessDataset(all_data_list)
        return dataset

class ReplayBuffer:
    ''' 经验回放池 '''
    def __init__(self, capacity=10000, data_list=None):
        self.buffer = collections.deque(maxlen=capacity)  # 队列,先进先出
        if data_list is not None:
            self.buffer.extend(data_list)

    def add(self, state, pi, z):
        """将数据加入buffer"""

        self.buffer.append((state, pi, z))

    def sample(self, batch_size):
        """从buffer中采样数据,数量为batch_size"""

        transitions = random.sample(self.buffer, batch_size)
        states, pis, zs = zip(*transitions)
        return states, pis, zs

    def size(self):
        """当前buffer中数据的数量"""

        return len(self.buffer)

    def clear(self):
        self.buffer.clear()

    def save(self, expand_data=None):
        filedir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'output', 'data')
        if not os.path.exists(filedir):
            os.makedirs(filedir)

        model_version = 0
        if expand_data is not None:
            model_version = expand_data.get('model_version')
        filename = 'replay_buffer_{}_{}.json'.format(int(time.time()), model_version)
        filepath = os.path.join(filedir, filename)

        with open(filepath, 'w') as f:
            jsonstr = json.dumps(list(self.buffer))
            f.write(jsonstr)

    @staticmethod
    def load_from_file(filepath):
        data_list = []
        with open(filepath, 'r') as f:
            jsonstr = f.read()
            data_list = json.loads(jsonstr)
        replay_buffer = ReplayBuffer(data_list=data_list)
        return replay_buffer

    @staticmethod
    def load_from_dir(dirpath):
        if not os.path.exists(dirpath):
            return

        all_data_list = list()
        for filename in os.listdir(dirpath):
            if filename.endswith('json') and filename.startswith('replay_buffer'):
                filepath = os.path.join(dirpath, filename)
                with open(filepath, 'r') as f:
                    jsonstr = f.read()
                    data_list = json.loads(jsonstr)
                    all_data_list.extend(data_list)
        replay_buffer = ReplayBuffer(data_list=all_data_list)
        return replay_buffer

if __name__ == '__main__':
    # s = 'ERIOC<VGK1234q24ds'
    # print(('k' in s))

    # q = collections.deque(maxlen=100)
    # q.append(('23', [123, 23], 0))
    # q.append(('24', [123, 23], 0))
    # q.append(('256', [123, 23], 0))
    # print(q)
    # print(list(q))
    # result = json.dumps(list(q))
    # print(result)

    # result_load = json.loads(result)
    # print(result_load)

    # filepath = '../output/data/replay_buffer_1656040190.json'
    # rb = ReplayBuffer.load(filepath)
    # print(rb.buffer)

    dataset = ChessDataset.load_from_dir('../output/data')
    dataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)
    for i, (batch_states, batch_pis, batch_zs) in enumerate(dataloader):
        print(len(batch_states), batch_pis.size(), batch_zs)
        if i == 0:
            break


import torch
import torch.nn as nn
from .rnn_encoder import RNNEncoder

# 自编码器
class AutoEncoder(nn.Module):
    def __init__(self, args, embedding_weights):
        super(AutoEncoder, self).__init__()
        self._args = args

        embed_dim = embedding_weights.shape[1]
        self._wd_embed = nn.Embedding.from_pretrained(torch.from_numpy(embedding_weights))

        self._bidirectional = True
        nb_directions = 2 if self._bidirectional else 1

        self.encoder = RNNEncoder(input_size=embed_dim,
                                  hidden_size=args.hidden_size,
                                  num_layers=args.num_layers,
                                  bidirectional=self._bidirectional,
                                  batch_first=True,
                                  rnn_type='lstm')

        self.decoder = RNNEncoder(input_size=nb_directions * args.hidden_size,
                                  hidden_size=embed_dim // nb_directions,
                                  num_layers=args.num_layers,
                                  bidirectional=self._bidirectional,
                                  batch_first=True,
                                  rnn_type='lstm')

        # self._hidden2tag = nn.Linear(args.hidden_size * nb_directions, args.tag_size)

        self._embed_dropout = nn.Dropout(args.embed_dropout)
        self._linear_dropout = nn.Dropout(args.linear_dropout)

    def forward(self, wd_idxs, non_pad_mask=None):
        '''
        :param wd_idxs: (bz, seq_len)
        :param non_pad_mask: (bz, seq_len)  非填充部分mask
        :return:
        '''
        seq_len = wd_idxs.size(1)

        if non_pad_mask is None:
            # 非取mask
            non_pad_mask = wd_idxs.ne(self._args.pad)

        # (bz, seq_len, embed_dim)
        wd_embed = self._wd_embed(wd_idxs)

        if self.training:
            embed = self._embed_dropout(wd_embed)
        else:
            embed = wd_embed

        # (num_layers, batch_size, nb_directions * hidden_size)
        # 编码器输出词序列的句向量
        _, hidden_n = self.encoder(embed, non_pad_mask)
        # (batch_size, nb_directions * hidden_size)
        # sent_vec = hidden_n[0][-1]  # 句向量

        # (batch_size, nb_directions * hidden_size) ->
        # (batch_size, seq_len, nb_directions * hidden_size)
        sent_enc = hidden_n[0][-1].unsqueeze(1).repeat(1, seq_len, 1)

        if self.training:
            sent_enc = self._linear_dropout(sent_enc)

        # (batch_size, seq_len, embed_dim)
        dec_out, _ = self.decoder(sent_enc, non_pad_mask)

        # 用于计算编码MSE误差(无监督)
        return dec_out, wd_embed


import logging

from pyrogram import Client, filters
from pyrogram.types import Message

from korone.locale import StringResource
from korone.utils.misc import get_language_code

log = logging.getLogger(__name__)

@Client.on_message(group=1)
async def catchall(_a: Client, _b: Message) -> None:
    log.debug("New message!")

@Client.on_message(filters.command("greet") & filters.togglable)  # type: ignore
async def command_greet(_: Client, message: Message) -> None:
    language_code: str = get_language_code(message)

    await message.reply(
        StringResource.get(language_code, "strings/greet/message"),
    )

@Client.on_message(filters.command("farewell") & filters.togglable)  # type: ignore
async def command_farewell(_: Client, message: Message) -> None:
    language_code: str = get_language_code(message)

    await message.reply(
        StringResource.get(language_code, "strings/farewell/message"),
    )


import requests,sys,os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')))
from config import hosts

class List(object):
	url = hosts.testuri['mt06'] + 'api/v2/wd/info/fengChuListV2'
	res = requests.get(url)
	resp = res.json()
	#print(res.status_code)

	def get_id(self,res,resp):
		id = {}
		#print(len(resp['data']['targets']))
		for i in range(len(resp['data']['targets'])):
			res = requests.get(self.url)
			resp = res.json()
			id[i] = resp['data']['targets'][i]['id']
		print(id)
		return id

if __name__ == '__main__':
	obj = List()
	id = obj.get_id(obj.res,obj.resp)


from django import template
from django.template import Template, Context
from ndstats.models import TEAM_EMP

register = template.Library()

@register.filter(name='lookup')
def cut(value, arg):
    try:
        return value[arg]
    except (IndexError, KeyError):
        return ''

@register.simple_tag
def player_line(player, team, is_comm=False):
    if not player:
        return Template("	").render(Context())
    if is_comm:
        ptime = player.time_empire_cmd if team == TEAM_EMP else player.time_consortium_cmd
    else:
        ptime = player.time_empire if team == TEAM_EMP else player.time_consortium

    if ptime:
        m, s = int(ptime / 60), ptime % 60
    else:
        m, s = 0, 0

    return Template('''
        {{ player }}
      {{ player.score }}
      {{ player.kills }}
      {{ player.buildings }}
      {{ time_m }}:{{ time_s }}
    ''').render(Context({
        'player': player,
        'time_m': m,
        'time_s': ('0%s' % s)[-2:],
    }))


# from django.test import TestCase
#
# # Create your tests here.
#
# a = """
#
#         नाम : सुगनाई
#         पति का नाम : गेपरराम
#         मकान संख्या: 262 शाणं० 8
#         आयु : 59 लिंग: स्त्री #ैएक800७
#
#         """
#
# a = """
# उमः +! : पुष्पा
#
# पिता का नाम : जितेन्द्र
# मकान संख्या: 83 शिण०8
# आयु : 33 लिंग: स्त्री #४80।॥9
#
# """
# """
# जा | : चन्द्रकान्ता
#
# पति का नाम : कमलेश
# मकान संख्या: 83 शाण० 8
# आयु : 27 लिंग: स्त्री #४80॥9
#
# '३().])376943
#
# """
#
# """
# >>ीस्‍ि.) : सुगरी
#
# पति का नाम : जमालखां
# मकान संख्या: 8 शाण० 8
# आयु : 79 लिंग: स्त्री 0]
#
#
#
#
# """
# a = """
# दम. िड| : नीतू
#
# पिता का नाम : पुसाराम
# मकान संख्या: 322 शिीणं0 8
# आयु : 20 लिंग: पुरुष #एकॉ8009
#
#
#
#
#
# """
# import re
# a = a.split("\n")
#
# name = ""
# age = ""
# father_name = ""
# husband_name = ""
# gender = ""
# print(a)
# for item in a[:]:
#     if item=="":
#         a.remove("")
# print(a)
# def get_user_name(str_t, name):
#     str_t = str_t.split(":")
#     if str_t.__len__()==2:
#         name = str_t[1].strip()
#     print(name)
#     return name
# for o in a:
#     if re.search("नाम :", o) and not (re.search("पति का नाम :", o) or re.search("पिता का नाम :", o)):
#         asd = o.split("नाम :")
#         name = asd[1].strip()
#     if re.search("पिता का नाम :", o):
#         asd = o.split("पिता का नाम :")
#         father_name = asd[1].strip()
#         if not name and a.index(o) != 0:
#             name = get_user_name(a[a.index(o)-1], name)
#
#     if re.search("पति का नाम :", o):
#         asd = o.split("पति का नाम :")
#         husband_name = asd[1].strip()
#         if not name and a.index(o) != 0:
#             name = get_user_name(a[a.index(o)-1], name)
#
#     if re.search("आयु :", o) or re.search("आयु:", o):
#         asdd = ["", ""]
#         asd = ""
#         if re.search("आयु :", o):
#             asd = o.split("आयु :")
#         else:
#             asd = o.split("आयु:")
#
#         if re.search("लिंग:", asd[1]) or re.search("लिंग :", asd[1]):
#             if re.search("लिंग:", asd[1]):
#                 asdd = asd[1].split("लिंग:")
#             else:
#                 asdd = asd[1].split("लिंग :")
#             age = asdd[0]
#         if re.search("स्त्री", asdd[1]):
#             gender = "स्त्री"
#         elif re.search("पुरुष", asdd[1]):
#             gender = "पुरुष"
#
# print(name, father_name, husband_name, age, gender)
# print("---")

import multiprocessing

def worker(procnum, return_li):
    print(str(procnum) + " represent!")
    # return_dict[procnum] = procnum
    return_li.extend([1])
    return {"ok"}

if __name__ == "__main__":
    manager = multiprocessing.Manager()
    return_li = manager.list()
    li = []
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i, return_li))
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()
    print(return_li)
    print(li)


#!/usr/bin/env python3

# Welcome to my test server
# Comments are just to explain (to myself mainly) how each of the commands work

from http.server import HTTPServer, BaseHTTPRequestHandler
import os
import logging
from datetime import datetime

port = 8000

class SimpleRequestHandler(BaseHTTPRequestHandler):
# This class is called into existence when the HTTPD server gets a request on the above port
# It currently only handles GET and POST actions

    def do_GET(self):
        if self.path == '/':
            self.path = '/serverbaby_test.html'
            # if this is a directory [ends in /], use file called serverbaby_test.html

        try:
            file_to_open = open(self.path[1:]).read()
            # open serverbaby_test.html
            server_time_local = self.log_date_time_string()
            # take the current LOCAL time from the server
            date_obj = datetime.strptime(server_time_local, '%d/%b/%Y %H:%M:%S')
            # identify the components that make up the server time
            served_on_time = datetime.strftime(date_obj, '%d-%m-%Y %I:%M:%S %p')
            # Turn those components into a string in the desired format to display the time
            amended_file = file_to_open.replace("XXXXXXXXXX", str(served_on_time))
            # XXXXXXXXXX is a a placeholder in the serverbaby_test.html file to insert the time
            # replace the placeholder with the actual time from the server
            self.send_response(200)
            # send an "OK" response from the server

        except:
            # this is a bare except, which means it will catch any and all exceptions.
            # Bare excepts are not usually recommended but desired for this example.
            amended_file = "404 Not Found - Whoops! You broke the Interwebz"
            # if for any reason the file serverbaby_test.html can't be located opened, read, amended etc
            # This error message will display on the browser instead
            self.send_response(404)
            # 404 Not Found - Requested resource could not be found.
            # Subsequent requests by the client permissible.
        self.end_headers()
        # tells the program this line is the end of what to display as html
        self.wfile.write(bytes(amended_file, 'utf-8'))
        # take the text contents of whatever is currently saved in "amended_file",
        # either the amended version of serverbaby_test.html or the error message,
        # and display it in the browser window

def run(server_class=HTTPServer, handler_class=SimpleRequestHandler, variable_port=port):
    logging.basicConfig(level=logging.INFO)
    # info(msg, *args, **kwargs)  Logs a message with level INFO on this logger.
    server_address = ('', port)
    # any IP address for server, port == the port listed above [8000]
    httpd = server_class(server_address, handler_class)
    local_path = os.getcwd()
    # os.getcwd() == absolute path of the current working directory
    message = 'serving from {0} at port {1}'
    print(message.format(local_path, variable_port))
    # print the welcome message with the following details:
    # format:   0 == local_path, 1 == variable_port
    logging.info('Starting server, use <Ctrl-C> to stop...\n')
    # this message is displayed, and the logging info is displayed after this message
    try:
        # This is where the listener is set up
        httpd.serve_forever()
        # if the code works, and there is no Keyboard Interrupt, it leaves the server running
    except KeyboardInterrupt:
        # KeyboardInterrupt - Raised when the user presses Ctrl+c, Ctrl+z or Delete
        httpd.server_close()
        # if a KeyboardInterrupt is entered, close the server and print the below message
        logging.info('<Ctrl-C> entered, shutting down server\n')

if __name__ == '__main__':
    run()
    # this makes it all run....


"""
Write a Python program to find unique triplets
whose three elements gives the sum of zero from an array of n integers
"""

import itertools

def find_unique_triplets(nums):
    res = []
    n = len(nums)
    zs = set(nums)
    for i in range(n):
        for j in range(i, n):
            x, y = nums[i], nums[j]
            if x == y:
                continue
            z = -(x + y)
            if x == z or y == z:
                continue
            if z in zs:
                t = sorted((x, y, z))
                if t not in res:
                    res.append(t)
                break
    return res

xs = [3, 5, -7, 11, 2]
print(find_unique_triplets(xs))  # 2, 5, -7

ys = [1, -6, 4, 2, -1, 0, 2, 0, -2, 0]
print(find_unique_triplets(ys))  # -6, 4, 2 or 1, -1, 0 or 2, 0, -2

# use built-in combinations
print(list(filter(lambda t: sum(t) == 0, itertools.combinations(set(xs), 3))))
print(list(filter(lambda t: sum(t) == 0, itertools.combinations(set(ys), 3))))


from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
from keras.optimizers import RMSprop
from keras.optimizers import SGD
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd

# get the data set
def read_dataset():
    # read the csv and replaces some string to integers
    df = pd.read_csv("train.csv").replace({np.nan: -10, ' ': ''})
    # all to lower
    df = df.apply(lambda x: x.str.lower() if(x.dtype == 'object') else x)

    df.columns = map(str.lower, df.columns)

    # get all input collumn with string
    columns_to_encode = df.drop(['advies', 'studentnummer', 'plaats', 'reden_stoppen', 'voorkeursopleiding'], axis=1).select_dtypes(
        include=['object']).columns.values
    # Converting categorical data into numbers
    df = pd.get_dummies(df, columns=columns_to_encode)

    df.rename(columns={
              'nadereori�ntatieopeenad-opleidingin�s-hertogenbosch': 'hertogenbosch'}, inplace=True)

    df.columns = [c.replace(' ', '') for c in df.columns]
    df.columns = [c.replace('+', '') for c in df.columns]
    df.columns = [c.replace('&', '') for c in df.columns]
    df.columns = [c.replace(',', '') for c in df.columns]
    df.columns = [c.replace('(', '') for c in df.columns]
    df.columns = [c.replace(')', '') for c in df.columns]
    df.columns = [c.replace('%', '') for c in df.columns]
    df.columns = [c.replace("'", '') for c in df.columns]

    # all the values of the csv
    X = df[df.drop(['advies', 'studentnummer', 'plaats',
                    'reden_stoppen', 'voorkeursopleiding'], axis=1).columns[0:192]]

    # get the expected output
    y = df[df.columns[3]]
    # encode the output
    Y = pd.get_dummies(y)

    return(X, Y)

# read the data set
X, Y = read_dataset()

# split the dataset into train and test part
train_x, test_x, train_y, test_y = train_test_split(
    X, Y, test_size=0.13986013986013987)

# create model
model = Sequential()
model.add(Dense(12, input_dim=75, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(3, activation='softmax'))

# the optimizer
adam = Adam(lr=0.01)
sgd = SGD(lr=0.01)
rmsprop = RMSprop(lr=0.01)

# Compile model
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['binary_accuracy', 'categorical_accuracy'])

# Fit/train the model
model.fit(train_x, train_y, epochs=500, shuffle=False, batch_size=10, validation_data=(test_x, test_y))

# evaluate the model
scores = model.evaluate(test_x, test_y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
print("\n%s: %.2f%%" % (model.metrics_names[2], scores[2]*100))

# # calculate predictions
# predictions = model.predict(test_x)
# # round predictions
# rounded = [round(x[0]) for x in predictions]
# print(rounded)

'''
010 positief
100 negatief
001 twijfel
'''


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('ndstats', '0011_matchevent'),
    ]

    operations = [
        migrations.AlterField(
            model_name='matchevent',
            name='team',
            field=models.PositiveSmallIntegerField(choices=[(0, b'UNASSIGNED'), (1, b'CONSORTIUM'), (2, b'EMPIRE')]),
        ),
    ]


"""Equals (#=): evaluate and update script

Usage:
    equals [options] <input>

Options:
    -i, --in-place
    -d, --debug
    -o PATH, --output PATH
    -u, --updates-only
    -l LANG, --language LANG

"""

import sys
import logging
import fileinput
import json
import docopt
from equals.languages import langmap
from equals.utils import process_script_output

APP_NAME = 'equals'

log = logging.getLogger(APP_NAME)

import argparse
import pathlib

def parse_args(args=None) -> argparse.Namespace:

    epilog="""

    Known languages:
    """
    epilog += ', '.join(langmap.keys())

    # command line interface
    parser = argparse.ArgumentParser(prog=APP_NAME, epilog=epilog)

    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument('-i', '--in-place', action='store_true', help='Update the input file in place.')
    group.add_argument('-o', '--output', type=pathlib.Path, help='Output file')
    group.add_argument('-u', '--updates-only', action='store_true', help="Print out only updateted values in json format.")

    parser.add_argument('-d', '--debug', action='store_true', help="Run in debug mode.")
    parser.add_argument('-l', '--lang', type=str, help='Input language')
    parser.add_argument('input', type=str, help="Input file, for input from stdin use '-' as in input.")

    return parser.parse_args(args)

def main():
    args = parse_args()

    in_place = args.in_place
    debug = args.debug
    output = args.output
    updates_only = args.updates_only
    language = args.lang
    filepath = args.input

    # setup logging
    logging.basicConfig(level='DEBUG' if debug else 'INFO')

    # get language
    lang = langmap[language]

    # if editing in place output is same as input
    if in_place and not filepath == '-':
        output = filepath

    # read file into list of lines, without linebreaks
    f = fileinput.input(files=(filepath, ))
    lines_in = []
    for line in f:
        lines_in.append(line[:-1])
    f.close()

    # preprocessing
    lines_pp, lines_eq = lang.preprocess(lines_in)

    # execute the modified code
    text = '\n'.join(lines_pp)
    stdout, stderr = lang.execute(text)

    # print error and exit if there is one
    if stderr:
        print("There was an error in the input:", file=sys.stderr)
        print(stderr, file=sys.stderr)
        print("The input is:", file=sys.stderr)
        print(text, file=sys.stderr)
        sys.exit(1)

    # post processing
    for i, value in process_script_output(stdout.split('\n')):
        lines_eq[i].value = value

    # print updates if required
    if updates_only:
        updates = []
        for el in lines_eq.values():
            updates.append(el.as_dict())
        print(json.dumps(updates))
        sys.exit(0)

    # appli updates
    lines_out = []
    for i, line in enumerate(lines_in):
        if i in lines_eq:
            lines_out.extend(lines_eq[i].get_updated_lines())
        else:
            lines_out.append(line)

    # output
    text = '\n'.join(lines_out)
    if output:
        with open(output, 'w') as f:
            f.write(text)
    else:
        print(text, end='')


#!/opt/rh/rh-python35/root/usr/bin/python

import sys
import re
from f5.bigip import ManagementRoot

def usage():
    print('\nusage: %s <mode> [ <environment> ] [ <ip> | <pattern> ]' % sys.argv[0])
    print('\n Modes:')
    print('\n  -n               node mode: the lookup is done by all nodes (or specified by IP address) and finds all virtuals servers that use the node(s) in the backend.')
    print('\n  -vs              VIP mode: the lookup is done by virtual server and lists all the nodes for all (or specified by pattern or IP address) virtual servers.')
    print('\n Environments:')
    print('\n                   Valid environments are prod, prod-b and appver. If no environment is specified - by default it is appver.\n')
    sys.exit(0)

env = 'appver'
ip = None
vs = None

options = [ opt for opt in sys.argv[1:] if opt != '-n' and opt != '-vs' ]
mode_list = [ opt for opt in sys.argv[1:] if opt == '-n' or opt == '-vs' ]

if len(options) > 2:
    print('Too many options')
    usage()
    sys.exit(2)

if len(options) > 0:
    for opt in options:
        if opt.lower() == 'prod' or opt.lower() == 'prod-b' or opt.lower() == 'appver':
            env = opt.lower()
        elif re.search('^\d+\.\d+\.\d+\.\d+$', opt):
            ip = opt
        elif opt.lower() == '-h':
            usage()
        else:
            vs = str(opt)

if len(mode_list) != 1:
    print('\n1 mode must be specified: "-n" - for node lookup, "-vs" for VIP lookup')
    usage()
    sys.exit(2)

mode = mode_list[0]

if env == 'appver':
    server = 'servername'
elif env == 'prod':
    server = 'servername'
elif env == 'prod-b':
    server = 'servername'

mgmt = ManagementRoot(server, 'user', 'password')

virtuals = mgmt.tm.ltm.virtuals.get_collection()

if mode == '-vs':
    print('\nEnvironment: ' + env + '\n')
results = {}
for virt in virtuals:
    partition = virt.partition
    try:
        pool_name = virt.pool.split('/')[2]
        pool = mgmt.tm.ltm.pools.pool.load(name = pool_name, partition = partition)
        members = pool.members_s.get_collection()
        if mode == '-vs':
            if vs:
                if re.search('.*%s.*' % vs.lower(), virt.name.lower()):
                    print('\n' + virt.name + ' (' + virt.destination.split('/')[2] + ')')
            elif ip:
                if re.search('^' + ip + '%.*', virt.destination.split('/')[2]):
                    print('\n' + virt.name + ' (' + virt.destination.split('/')[2] + ')')
            else:
                print('\n' + virt.name + ' (' + virt.destination.split('/')[2] + ')')
        for member in members:
            if mode == '-n':
                try:
                    results[member.name.split('%')[0]].append( virt.name + ' (' + virt.destination.split('/')[2] + ')' )
                except KeyError:
                    results[member.name.split('%')[0]] = [ virt.name + ' (' + virt.destination.split('/')[2] + ')' ]
                    continue
            if mode == '-vs':
                if vs:
                    if re.search('.*%s.*' % vs.lower(), virt.name.lower()):
                        print(' ' + member.name.split('%')[0])
                elif ip:
                    if re.search('^' + ip + '%.*', virt.destination.split('/')[2]):
                        print(' ' + member.name.split('%')[0])
                else:
                    print(' ' + member.name.split('%')[0])
    except:
        continue

if mode == '-vs':
    sys.exit()

print('\nEnvironment: ' + env + '\n')
for ke,va in results.items():
    if ip:
        if ip == ke:
            print(ke + ':')
            for vs in va:
                print(' ' + vs)
    else:
        print('\n' + ke + ':')
        for vs in va:
            print(' ' + vs)


import os
import sys
import json
import re
from datetime import datetime, timedelta
import getopt
from getpass import getpass

import requests

sys.path.insert(1, sys.path[0] + '/pyrsa')
from PyRsa.pyrsa import RsaKey
from PyRsa.pyb64 import Base64

class Jwxt(object):
    def __init__(self, domain, student_number, pwd):
        self.__ua = 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2'
        self.__domain = domain
        self.__student_number = student_number
        self.session = requests.session()

        self.__csrf_token, self.__cookies_route = self.__get_csrf_token()
        self.__modulus, self.__exponent = self.__get_public_key()
        self.__jsessionid = self.__get_jsessionid(pwd)

    def __get_public_key(self):
        url = f'https://{self.__domain}/xtgl/login_getPublicKey.html'

        headers = {
            'Host': self.__domain,
            'User-Agent': self.__ua,
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'Accept-Encoding': 'gzip, deflate, br',
            'X-Requested-With': 'XMLHttpRequest',
            'DNT': '1',
            'Connection': 'keep-alive',
            'Referer': f'https://{self.__domain}/xtgl/login_slogin.html',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin'
        }

        res = self.session.get(url, headers=headers)
        res_json = res.json()
        return res_json.get('modulus'), res_json.get('exponent')

    def __get_csrf_token(self):
        url = f'https://{self.__domain}/xtgl/login_slogin.html'

        headers = {
            'Host': self.__domain,
            'User-Agent': self.__ua,
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'Accept-Encoding': 'gzip, deflate, br',
            'DNT': '1',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-User': '?1',
        }

        res = self.session.get(url, headers=headers)
        route = requests.utils.dict_from_cookiejar(res.cookies)
        csrf_line = re.findall(r"value=\"[0-9a-z\-,]+\"", res.text)
        csrf = re.findall(r"[0-9a-z\-,]+", csrf_line[0])
        return csrf[1], route

    def __get_jsessionid(self, pwd):
        rsakey = RsaKey()
        rsakey.set_public(Base64().b64tohex(self.__modulus), Base64().b64tohex(self.__exponent))
        rr = rsakey.rsa_encrypt(pwd)
        enpsw = Base64().hex2b64(rr)

        data = {
            'csrftoken': self.__csrf_token,
            'yhm': self.__student_number,
            'mm': enpsw
        }
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;'
                      'q=0.8,application/signed-exchange;v=b3',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Cache-Control': 'max-age=0',
            'Connection': 'keep-alive',
            'Content-Length': '470',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Host': self.__domain,
            'Origin': f'https://{self.__domain}',
            'Referer': f'https://{self.__domain}/xtgl/login_slogin.html',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': self.__ua
        }
        url = f'https://{self.__domain}/xtgl/login_slogin.html'

        res = self.session.post(url, headers=headers, data=data)
        if len(res.history) and res.history[0].status_code == 302:
            cookies = requests.utils.dict_from_cookiejar(res.history[0].cookies)
            return cookies

    def dump_class_json(self, academic_year, term):
        term_map = {'1': '3', '2': '12', '3': '16'}

        url = f'https://{self.__domain}/kbcx/xskbcx_cxXsKb.html?gnmkdm=N2151&su={self.__student_number}'
        headers = {
            'Host': f'{self.__domain}',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0',
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'Accept-Encoding': 'gzip, deflate, br',
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Origin': f'https://{self.__domain}',
            'DNT': '1',
            'Connection': 'keep-alive',
            'Referer': f'https://{self.__domain}/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default&su={self.__student_number}',
            'Cookie': f"JSESSIONID={self.__jsessionid['JSESSIONID']}; route={self.__cookies_route['route']}",
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'Cache-Control': 'no-cache',
        }
        data = {
            'xnm': academic_year,
            'xqm': term_map[term],
            'kzlx': 'ck'
        }

        res = self.session.post(url=url, headers=headers, data=data)
        return json.loads(res.text)

class ClassTable(object):
    def __init__(self, start_date):
        self.__start_date = start_date
        self.class_table = []

    def read_class(self, json_obj):
        for i in json_obj['kbList']:
            weeks_group = i.get('zcd').split(',')
            weeks_group = list(map(lambda s: re.findall(r"\d+", s), weeks_group))
            weeks_group = list(map(lambda s: s + s if len(s) == 1 else s, weeks_group))  # 单周补齐list最后一个元素
            weeks_group = list(map(lambda s: list(map(lambda y: int(y), s)), weeks_group))  # str to int
            # 因为套了2层list，最外层map的参数是[[]]（给lambda的参数是[]]），内层map参数是[](给lambda就是单个元素）

            self.class_table.append(dict(name=i.get('kcmc'), start_end_time=i.get('jcs').split('-'),
                                         weekday=int(i.get('xqj')),
                                         week_start_end=weeks_group,
                                         location=i.get('cdmc'), teacher=i.get('xm')))
        return self.class_table

    def cal_gen(self, file_name):
        begin_time = {'1': timedelta(hours=8, minutes=0), '2': timedelta(hours=8, minutes=50),
                      '3': timedelta(hours=10, minutes=0), '4': timedelta(hours=10, minutes=50),
                      '5': timedelta(hours=13, minutes=30), '6': timedelta(hours=14, minutes=20),
                      '7': timedelta(hours=15, minutes=15), '8': timedelta(hours=16, minutes=5),
                      '9': timedelta(hours=18, minutes=0), '10': timedelta(hours=18, minutes=50),
                      '11': timedelta(hours=19, minutes=40)}

        end_time = {'1': timedelta(hours=8, minutes=45), '2': timedelta(hours=9, minutes=35),
                    '3': timedelta(hours=10, minutes=45), '4': timedelta(hours=11, minutes=35),
                    '5': timedelta(hours=14, minutes=15), '6': timedelta(hours=15, minutes=5),
                    '7': timedelta(hours=16, minutes=00), '8': timedelta(hours=16, minutes=50),
                    '9': timedelta(hours=18, minutes=45), '10': timedelta(hours=19, minutes=35),
                    '11': timedelta(hours=20, minutes=25)}

        payload = 'BEGIN:VCALENDAR\nPRODID:-//wirano@github//CJLU ClassTable ' \
                  'Gen//EN\nVERSION:2.0\nCALSCALE:GREGORIAN\nBEGIN:VTIMEZONE\nTZID:Asia/Shanghai\nTZURL:http' \
                  '://tzurl.org/zoneinfo-outlook/Asia/Shanghai\nX-LIC-LOCATION:Asia/Shanghai\nBEGIN:STANDARD' \
                  '\nTZOFFSETFROM:+0800\nTZOFFSETTO:+0800\nTZNAME:CST\nDTSTART:19700101T000000\nEND:STANDARD\nEND' \
                  ':VTIMEZONE'

        for i in self.class_table:
            for j in i['week_start_end']:
                payload += '\nBEGIN:VEVENT\nDTSTAMP:' + datetime.now().strftime("%Y%m%dT%H%M%SZ") + \
                           '\nDTSTART;TZID=Asia/Shanghai:' + \
                           (self.__start_date + timedelta(weeks=j[0] - 1, days=i['weekday'] - 1) + begin_time[
                               i['start_end_time'][0]]).strftime("%Y%m%dT%H%M%S") + \
                           '\nDTEND;TZID=Asia/Shanghai:' + \
                           (self.__start_date + timedelta(weeks=j[0] - 1, days=i['weekday'] - 1) + end_time[
                               i['start_end_time'][1]]).strftime("%Y%m%dT%H%M%S") + \
                           '\nRRULE:FREQ=WEEKLY;COUNT=' + str(j[1] - j[0] + 1) + \
                           '\nSUMMARY:' + i['name'] + \
                           '\nLOCATION:' + i['location'] + \
                           '\nDESCRIPTION:' + i['teacher'] + \
                           '\nBEGIN:VALARM' + '\nTRIGGER:-PT15M' + '\nREPEAT:1' + '\nDURATION:PT1M' + '\nEND:VALARM' + '\nEND:VEVENT'
        payload += '\nEND:VCALENDAR'

        f = open(file_name, 'w')
        f.write(payload)
        f.close()

def main(argv):
    doc = f"Usage: {os.path.basename(sys.argv[0])} <options...>\n" + "    -s, --student_number <student number>    Your student number\n" + "    -d, --start_date <date>                  Term start date(ISO format e.g. 2021-09-06)\n" + "    -o, --output <file name>                 Output file name\n"
    file_name = 'timetable.ics'
    try:
        opts, args = getopt.getopt(argv[1:], "hs:d:o", ["help", "student_number=", "start_date=", "output"])
    except getopt.GetoptError:
        print(doc)
        sys.exit(2)

    for opt, arg in opts:
        if opt in ('-s', '--student_number'):
            s_num = arg
        elif opt in ('-d', '--start_date'):
            start_date = datetime.fromisoformat(arg)
            if start_date.month > 6:
                term = '1'
                academic_year = str(start_date.year)
            else:
                term = '2'
                academic_year = str(start_date.year - 1)
        elif opt in ('-o', '--output'):
            file_name = arg
        else:
            print(doc)
            sys.exit(0)

    jw = Jwxt('jwxt.cjlu.edu.cn', s_num, getpass('Enter your password:'))
    table = jw.dump_class_json(academic_year, term)
    ct = ClassTable(start_date)
    ct.read_class(table)
    ct.cal_gen(file_name)

if __name__ == '__main__':
    main(sys.argv)


def Output_Formatting():
    import reprlib
    print(reprlib.repr(set('supercalifragilisticexpialidocious')))

    import pprint
    t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]]
    pprint.pprint(t, width=30)

    import textwrap
    doc = """The wrap() method is just like fill() except that it returns
    a list of strings instead of one big string with newlines to separate
    the wrapped lines."""
    print(textwrap.fill(doc, width=40))

    import locale
    locale.setlocale(locale.LC_ALL, 'English_United States.1252')
    conv = locale.localeconv()  # get a mapping of conventions
    x = 1234567.8
    # locale.format("%d", x, grouping=True) #DeprecationWarning: This method will be removed in a future version of Python. Use 'locale.format_string()' instead. locale.format("%d", x, grouping=True)
    locale.format_string("%s%.*f", (conv['currency_symbol'],
                                    conv['frac_digits'], x), grouping=True)

def Templating():
    from string import Template
    t = Template('${village}folk send $$10 to $cause.')
    s = t.substitute(village='Nottingham', cause='the ditch fund')
    print(s)

    t = Template('Return the $item to $owner.')
    d = dict(item='unladen swallow')
    # substitute = t.substitute(d) #error
    # print(substitute)
    safe_substitute = t.safe_substitute(d)
    print(safe_substitute)

    import time, os.path
    photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']

    class BatchRename(Template):
        delimiter = '%'
        fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')

    t = BatchRename(fmt)
    date = time.strftime('%d%b%y')
    for i, filename in enumerate(photofiles):
        base, ext = os.path.splitext(filename)
        newname = t.substitute(d=date, n=i, f=ext)
        print('{0} --> {1}'.format(filename, newname))

def Working_with_Binary_Data_Record():
    import struct

    with open('myfile.zip', 'rb') as f:
        data = f.read()

    start = 0
    for i in range(3):  # show the first 3 file headers
        start += 14
        fields = struct.unpack('<IIIHH', data[start:start + 16])
        crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

        start += 16
        filename = data[start:start + filenamesize]
        start += filenamesize
        extra = data[start:start + extra_size]
        print(filename, hex(crc32), comp_size, uncomp_size)

        start += extra_size + comp_size  # skip to the next header

def Multi_threading():
    import threading, zipfile

    class AsyncZip(threading.Thread):
        def __init__(self, infile, outfile):
            threading.Thread.__init__(self)
            self.infile = infile
            self.outfile = outfile

        def run(self):
            f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
            f.write(self.infile)
            f.close()
            print('Finished background zip of:', self.infile)

    background = AsyncZip('mydata.txt', 'myarchive.zip')
    background.start()
    print('The main program continues to run in foreground.')

    background.join()  # Wait for the background task to finish
    print('Main program waited until background was done.')

def Logging():
    import logging
    logging.debug('Debugging information')
    logging.info('Informational message')
    logging.warning('Warning:config file %s not found', 'server.conf')
    logging.error('Error occurred')
    logging.critical('Critical error -- shutting down')

def Tools_for_Working_with_Lists():
    from array import array
    a = array('H', [4000, 10, 700, 22222])
    print(sum(a))
    print(a[1:3])

    from collections import deque
    d = deque(["task1", "task2", "task3"])
    d.append("task4")
    print("Handling", d.popleft())

    import bisect
    scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
    bisect.insort(scores, (300, 'ruby'))
    print(scores)

    from heapq import heapify, heappop, heappush
    data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
    heapify(data)  # rearrange the list into heap order
    heappush(data, -5)  # add a new entry
    a = [heappop(data) for i in range(3)]  # fetch the three smallest entries
    print(a)

if __name__ == "__main__":
    # Output_Formatting()
    # Templating()
    # Working_with_Binary_Data_Record()
    # Multi_threading()
    # Logging()
    Tools_for_Working_with_Lists()


import json
from typing import Any, Dict

import httpx
import pytest
from pytest_httpx import HTTPXMock

import assemblyai as aai
from assemblyai.api import ENDPOINT_TRANSCRIPT
from tests.unit import factories

aai.settings.api_key = "test"

def __submit_request(httpx_mock: HTTPXMock, **params) -> Dict[str, Any]:
    """
    Helper function to abstract calling transcriber with given parameters,
    and perform some common assertions.

    Returns the body (dictionary) of the initial submission request.
    """
    summary = "example summary"

    mock_transcript_response = factories.generate_dict_factory(
        factories.TranscriptCompletedResponseFactory
    )()

    # Mock initial submission response
    httpx_mock.add_response(
        url=f"{aai.settings.base_url}{ENDPOINT_TRANSCRIPT}",
        status_code=httpx.codes.OK,
        method="POST",
        json=mock_transcript_response,
    )

    # Mock polling-for-completeness response, with mock summary result
    httpx_mock.add_response(
        url=f"{aai.settings.base_url}{ENDPOINT_TRANSCRIPT}/{mock_transcript_response['id']}",
        status_code=httpx.codes.OK,
        method="GET",
        json={**mock_transcript_response, "summary": summary},
    )

    # == Make API request via SDK ==
    transcript = aai.Transcriber().transcribe(
        data="https://example.org/audio.wav",
        config=aai.TranscriptionConfig(
            **params,
        ),
    )

    # Check that submission and polling requests were made
    assert len(httpx_mock.get_requests()) == 2

    # Check that summary field from response was traced back through SDK classes
    assert transcript.summary == summary

    # Extract and return body of initial submission request
    request = httpx_mock.get_requests()[0]
    return json.loads(request.content.decode())

@pytest.mark.parametrize("required_field", ["punctuate", "format_text"])
def test_summarization_fails_without_required_field(
    httpx_mock: HTTPXMock, required_field: str
):
    """
    Tests whether the SDK raises an error before making a request
    if `summarization` is enabled and the given required field is disabled
    """
    with pytest.raises(ValueError) as error:
        __submit_request(httpx_mock, summarization=True, **{required_field: False})

    # Check that the error message informs the user of the invalid parameter
    assert required_field in str(error)

    # Check that the error was raised before any requests were made
    assert len(httpx_mock.get_requests()) == 0

    # Inform httpx_mock that it's okay we didn't make any requests
    httpx_mock.reset(False)

def test_summarization_disabled_by_default(httpx_mock: HTTPXMock):
    """
    Tests that excluding `summarization` from the `TranscriptionConfig` will
    result in the default behavior of it being excluded from the request body
    """
    request_body = __submit_request(httpx_mock)
    assert request_body.get("summarization") is None

def test_default_summarization_params(httpx_mock: HTTPXMock):
    """
    Tests that including `summarization=True` in the `TranscriptionConfig`
    will result in `summarization=True` in the request body.
    """
    request_body = __submit_request(httpx_mock, summarization=True)
    assert request_body.get("summarization") == True

def test_summarization_with_params(httpx_mock: HTTPXMock):
    """
    Tests that including additional summarization parameters along with
    `summarization=True` in the `TranscriptionConfig` will result in all
    parameters being included in the request as well.
    """

    summary_model = aai.SummarizationModel.conversational
    summary_type = aai.SummarizationType.bullets

    request_body = __submit_request(
        httpx_mock,
        summarization=True,
        summary_model=summary_model,
        summary_type=summary_type,
    )

    assert request_body.get("summarization") == True
    assert request_body.get("summary_model") == summary_model
    assert request_body.get("summary_type") == summary_type

def test_summarization_params_excluded_when_disabled(httpx_mock: HTTPXMock):
    """
    Tests that additional summarization parameters are excluded from the submission
    request body if `summarization` itself is not enabled.
    """
    request_body = __submit_request(
        httpx_mock,
        summarization=False,
        summary_model=aai.SummarizationModel.conversational,
        summary_type=aai.SummarizationType.bullets,
    )

    assert request_body.get("summarization") is None
    assert request_body.get("summary_model") is None
    assert request_body.get("summary_type") is None


import torch
from transformers import BartForConditionalGeneration, BartTokenizer

# Set device to the GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Load pre-trained model for text summarization
bart_model = BartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
bart_model.to(device)
# Load BART tokenizer
bart_tok = BartTokenizer.from_pretrained("facebook/bart-large-cnn")

def summarize(sentences):
    # Define function for single text summarization
    def single_summarise(input_sent_ids):
        # Generate summary
        summary_ids = bart_model.generate(input_sent_ids, max_length=510, num_beams=4, early_stopping=True)
        # Decode summary back to text
        summary_text = bart_tok.decode(summary_ids[0], skip_special_tokens=True)
        # Return summarized text
        return summary_text

    # Define function for summarization of too large texts
    def large_summarize(input_ids):
        # Initialize result as an empty tensor
        summ = torch.tensor([], dtype=torch.long).to(device)
        # While there is more then 1024 ids in input
        while len(input_ids[0])>1024:
            # Get first 1023 ids and add SEP token at the end
            part = torch.cat((input_ids[0][:1023].unsqueeze(-2), torch.tensor([2]).unsqueeze(-2).to(device)), dim=-1)
            # Generate summary of this firs 1024 tokens
            sum_part = bart_model.generate(part, max_length=510, num_beams=4, early_stopping=True)
            # Add summary to the result
            summ = torch.cat((summ, sum_part), dim=-1)
            # Remove summurized ids and add [CLS] in the beggining
            input_ids = torch.cat((torch.tensor([0]).unsqueeze(-2).to(device), input_ids[0][1023:].unsqueeze(-2)), dim=-1)
        # After loop is done, get summary of the last ids
        sum_part = bart_model.generate(input_ids, max_length=510, num_beams=4, early_stopping=True)
        # And add it to the result
        summ = torch.cat((summ, sum_part), dim=-1)
        # Return the result
        return summ

    # For every sentence...
    for i in range(len(sentences)):
        if i%10000 == 0:
            print(f'Processed over {i} elements')

        # Tokenize the text and add `[CLS]` and `[SEP]` tokens.
        input_ids = bart_tok.encode(sentences[i], return_tensors="pt").clone().detach().requires_grad_(False).to(device)

        # If sentence length is between 512 and 1024
        if 512<len(input_ids[0])<=1024:
            # Summarize sententce to max 510 tokens
            sentences[i] = single_summarise(input_ids)
        # If sentence is more then 1024 tokens
        elif len(input_ids[0])>1024:
            # While its more then 510 tokens
            while len(input_ids[0])>510:
                # Summurize it
                input_ids = large_summarize(input_ids)
            # After its summurized, decode it and update the sentence
            sentences[i] = bart_tok.decode(input_ids[0], skip_special_tokens=True)


"""
Define ssd net using resnet_50 as backbone network.
"""
import tensorflow as tf
from tensorflow.contrib import slim
from nets import resnet_v2
from utils import anchorsUtil
from utils import confUtil, lossUtil
import numpy as np

def multibox_predict(input_layer, class_num, layer_name, weight_decay):
  """
  Compute predictions for input layer.
  :param input_layer: Input feature layer
  :param class_num: number of output classes.
  :param layer_name: layer name.
  :param weight_decay: weight decay.
  :return: prediction p, and localizatoin l.
  """

  # Get anchors for each layer.
  layer_anchors = anchorsUtil.get_layer_anchors(layer_name)
  layer_shape = layer_anchors.shape
  anchor_num = layer_shape[2]

  with tf.variable_scope('pred/%s' % layer_name):
    with slim.arg_scope([slim.conv2d],
                        activation_fn=tf.nn.relu,
                        weights_regularizer=slim.l2_regularizer(weight_decay)):

      pred = slim.conv2d(input_layer, anchor_num * (class_num + 4), kernel_size=[3, 3])

  # Reshape output tensor to extract each anchor prediction.
  pred = tf.reshape(pred, [-1, layer_shape[0], layer_shape[1], anchor_num, class_num + 4])
  pred_cls = tf.slice(pred, [0, 0, 0, 0, 0], [-1, layer_shape[0], layer_shape[1], anchor_num, class_num])
  pred_cls = tf.reshape(pred_cls, [-1, layer_shape[0]*layer_shape[1]*anchor_num, class_num])

  pred_pos = tf.slice(pred, [0, 0, 0, 0, class_num], [-1, layer_shape[0], layer_shape[1], anchor_num, 4])
  pred_pos = tf.reshape(pred_pos, [-1, layer_shape[0] * layer_shape[1] * anchor_num, 4])

  return pred_cls, pred_pos

def init(class_num, weight_decay, is_training):
  """
  Init and build net.
  :param class_num: number of class.
  :return: a callable object, e.g. network.
  """

  def predict(image):
    """
    Do predict using image.
    :param image: input image, shape [batch, w, h, c]
    :return: predicted raw logits.
    """

    # Load resnet50
    with slim.arg_scope(resnet_v2.resnet_arg_scope(weight_decay=weight_decay,
                                                   use_batch_norm=False)):
      resnet, endpoints = resnet_v2.resnet_v2_50(inputs=image,
                                                 num_classes=class_num,
                                                 is_training=is_training)

    end_feats = {}
    net = endpoints['resnet_v2_50/block3']
    end_feats['resnet_v2_50/block3'] = net
    net = endpoints['resnet_v2_50/block4']
    end_feats['resnet_v2_50/block4'] = net

    # Create SSD conv layers.
    with tf.variable_scope('SSDNet'):
      with slim.arg_scope([slim.conv2d],
                          activation_fn=tf.nn.relu,
                          weights_regularizer=slim.l2_regularizer(weight_decay)):
        block = 'block-1'
        with tf.variable_scope(block):  # 14x14x512 -> 7x7x512
          net = slim.layers.conv2d(net, 256, kernel_size=[1, 1], activation_fn=tf.nn.relu)
          net = slim.layers.conv2d(net, 512, kernel_size=[3, 3], stride=2, activation_fn=tf.nn.relu)
        end_feats[block] = net

        block = 'block-2'
        with tf.variable_scope(block):  # 7x7x512 -> 4x4x256
          net = slim.layers.conv2d(net, 128, kernel_size=[1, 1], activation_fn=tf.nn.relu)
          net = slim.layers.conv2d(net, 256, kernel_size=[3, 3], stride=2, activation_fn=tf.nn.relu)
        end_feats[block] = net

        block = 'block-3'
        with tf.variable_scope(block):  # 4x4x256 -> 2x2x256
          net = slim.layers.conv2d(net, 128, kernel_size=[1, 1], activation_fn=tf.nn.relu)
          net = slim.layers.conv2d(net, 256, kernel_size=[3, 3], activation_fn=tf.nn.relu)
        end_feats[block] = net

        block = 'block-4'
        with tf.variable_scope(block):  # 2x2x256 -> 1x1x256
          net = slim.layers.conv2d(net, 128, kernel_size=[1, 1], activation_fn=tf.nn.relu)
          net = slim.layers.conv2d(net, 256, kernel_size=[3, 3], activation_fn=tf.nn.relu, padding='VALID')
        end_feats[block] = net

    """
    Add classifier conv layers to each added feature map(including the last layer of backbone network).
    Prediction and localisations layers.
    """
    logits = []
    locations = []
    for layer_name in end_feats.keys():
      logit, location = multibox_predict(end_feats[layer_name], class_num, layer_name, weight_decay)

      logits.append(logit)
      locations.append(location)

    # Concat all feature layer outputs.
    logits = tf.concat(logits, axis=1)
    locations = tf.concat(locations, axis=1)

    return logits, locations, end_feats

  return predict

def posMask(bbox, anchors):
  """
  Create a boolean mask of shape [anchor_num].
  :param bboxes: ground truth bbox of shape[4]
  :param anchors: anchors of current layer , shape [anchor_num, 4]
  :return: a boolean mask of shape [anchor_num]
  """

  # Compute jaccard overlap.
  overlap = lossUtil.jaccardIndex(bbox, anchors)

  # Get positive and negtive mask accoding to overlap.
  pos_mask = tf.greater(overlap, 0.5)

  return pos_mask

def classLoss(logits, label, pos_mask):
  """
  Classification loss.
  :param logits: predicted logits, shape [anchor_num, class_num]
  :param label: scalar
  :param pos_mask: shape [anchor_num]
  :return: loss
  """
  neg_mask = tf.logical_not(pos_mask)

  # Loss for each postition.
  conf_loss = tf.log(tf.nn.softmax(logits, axis=1))

  pos_loss = tf.slice(conf_loss, [0, label], [-1, 1])
  pos_loss = tf.boolean_mask(pos_loss, pos_mask)
  pos_loss = tf.reduce_sum(pos_loss)

  neg_loss = tf.slice(conf_loss, [0, 0], [-1, 1])
  neg_loss = tf.boolean_mask(neg_loss, neg_mask)

  # Top-k negative loss.
  pos_num = tf.reduce_sum(tf.cast(pos_mask, dtype=tf.int32))
  neg_num = tf.reduce_sum(tf.cast(neg_mask, dtype=tf.int32))
  neg_loss = tf.cond(tf.equal(tf.multiply(neg_num, pos_num), 0),
                     lambda: tf.constant(0, dtype=tf.float32),
                     lambda: tf.nn.top_k(neg_loss, tf.minimum(neg_num, tf.multiply(pos_num, 3)))[0])
  neg_loss = tf.reduce_sum(neg_loss)

  conf_loss = tf.negative(tf.add(pos_loss, neg_loss))

  return conf_loss

def locationLoss(location, gbbox, pos_mask):
  """
  Compute location loss.
  :param location: predicted location, shape [anchor_num, 4]
  :param gbbox: ground truth bbox, shape [anchor_num, 4]
  :param pos_mask: shape [anchor_num]
  :return: location loss
  """
  diff = tf.subtract(location, gbbox)
  loc_loss = lossUtil.smoothL1(diff)
  loc_loss = tf.boolean_mask(loc_loss, pos_mask)
  loc_loss = tf.reduce_sum(loc_loss)

  return loc_loss

def ssdLoss(logits, locations, labels, alpha, batch_size):
  """
  Compute SSD loss.
  :param logits: a tensor of raw prediction, shape [batch, total_anchor_num, class_num]
  :param locations: a tensor of location prediction, shape [batch, total_anchor_num, 4]
  :param labels: a dict,
            labels['bbox_num']: shape [batch, 1]
            labels['labels']: shape [batch, bbox_num],
            labels['bboxes']: shape [batch, bbox_num, 4]
  :param alpha: weight between classification loss and location loss.
  :return:
  """
  anchors = tf.constant(anchorsUtil.get_all_layer_anchors(), dtype=tf.float32)
  total_loss = tf.constant(0, dtype=tf.float32)

  for bi in range(batch_size):
    label = labels['labels'][bi]
    bboxes = labels['bboxes'][bi]

    """For each ground truth box, compute loss"""
    for bbox, cur_label in zip(tf.unstack(bboxes), tf.unstack(label)):
      # Transform bbox.
      g_bbox = lossUtil.encodeBBox(bbox, anchors)

      pos_mask = posMask(bbox, anchors)
      pos_num = tf.reduce_sum(tf.cast(pos_mask, dtype=tf.float32))

      cls_loss = classLoss(logits[bi], cur_label, pos_mask)
      loc_loss = locationLoss(locations[bi], g_bbox, pos_mask)

      total_loss += (cls_loss + alpha * loc_loss) / pos_num

  tf.losses.add_loss(total_loss)

  return total_loss


"""Test cli translate module."""
import json
from click.testing import CliRunner

from honeybee.model import Model

from honeybee_radiance.cli.edit import add_room_sensors, add_face3d_sensors, \
    mirror_model_sensors, reset_resource_ids

def test_reset_resource_ids():
    runner = CliRunner()
    input_hb_model = './tests/assets/model/shoe_box_mod_set.hbjson'

    c_args = [input_hb_model, '-uuid']
    result = runner.invoke(reset_resource_ids, c_args)
    assert result.exit_code == 0
    model_dict = json.loads(result.output)
    new_model = Model.from_dict(model_dict)
    new_con_set = new_model.properties.radiance.modifier_sets[0]
    old_id = 'ClimateZone_2_ModifierSet'
    assert new_con_set.identifier.startswith(old_id)
    assert new_con_set.identifier != old_id

def test_add_room_sensors():
    runner = CliRunner()
    input_hb_model = './tests/assets/model/model_radiance_dynamic_states.hbjson'

    result = runner.invoke(add_room_sensors, [input_hb_model])
    assert result.exit_code == 0
    model_dict = json.loads(result.output)
    new_model = Model.from_dict(model_dict)
    assert len(new_model.properties.radiance.sensor_grids) == 2

def test_add_face3d_sensors():
    runner = CliRunner()
    input_hb_model = './tests/assets/model/model_radiance_dynamic_states.hbjson'
    input_file = './tests/assets/model/face3d_array.json'

    result = runner.invoke(add_face3d_sensors, [input_hb_model, input_file])
    assert result.exit_code == 0
    model_dict = json.loads(result.output)
    new_model = Model.from_dict(model_dict)
    assert len(new_model.properties.radiance.sensor_grids) == 1

def test_mirror_model_sensors():
    runner = CliRunner()
    input_hb_model = './tests/assets/model/two_rooms.hbjson'

    result = runner.invoke(mirror_model_sensors, [input_hb_model])
    assert result.exit_code == 0
    model_dict = json.loads(result.output)
    new_model = Model.from_dict(model_dict)
    assert len(new_model.properties.radiance.sensor_grids) == 4


import re
import csv
from time import sleep
from bs4 import BeautifulSoup
import requests
import pandas as pd

request = 'https://news.search.yahoo.com/search?p={}'

headers = {
    'accept': '*/*',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
    'referer': 'https://www.google.com',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.44'
}

def scrape_news(query):
    """
    :param query: string to search on "yahoo.news"

    :return df: dataframe containing all the results

        Scraping over all the results within each page.
        If the button "next" (referred to the page) is available,
        it continues to iterate over all the pages
    """

    url = request.format(query)

    titles = []
    sources = []
    posted = []
    descriptions = []

    # iterate over all the available pages
    while True:

        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, 'html.parser')

        # there is a "NewsArticle" class for each news headline
        # returns an array with all the articles
        articles = soup.find_all('div','NewsArticle')

        # each element has a specific tag and class
        # in order to extract the text from the html tag, use ".text"
        for article in articles:

            titles.append(article.find('h4','s-title').text.strip())
            sources.append(article.find('span','s-source').text.strip())
            posted.append(article.find('span','s-time').text.replace('.', '').strip())
            descriptions.append(article.find('p','s-desc').text.strip())

        try:
            # look for the "next" button
            # and get the link
            url = soup.find('a','next').get('href')
            time.sleep(1)
        except AttributeError:
            # otherwise exit
            break

    df = pd.DataFrame({'title' : titles, 'source' : sources, 'posted' : posted, 'description' : descriptions})

    # it might have duplicates over all the pages
    return df.drop_duplicates()

df_scraped = scrape_news('Apple')

df_scraped.to_csv('../data/AAPL-News.csv',index=False)


#!/usr/bin/env python
"""
Change unit vectors of the system from the original a1, a2, and a3
to ax1, ax2, and ax3, each of them is written as (x1,x2,x3) that are
multiplying factors to a1, a2, and a3, respectively.
For example, if ax1 = (x1,x2,x3), the new a1 vector is given as:
  a1_new = x1*a1 +x2*a2 +x3*a3

Usage:
  cell_convert.py [options] INFILE

Options:
  -h,--help  Show this message and exit.
  --ax1 AX1  Factors to be multiplied to a1,a2,a3, comma separated. [default: 1.0,0.0,0.0]
  --ax2 AX2  Factors to be multiplied to a1,a2,a3, comma separated. [default: 0.0,1.0,0.0]
  --ax3 AX3  Factors to be multiplied to a1,a2,a3, comma separated. [default: 0.0,0.0,1.0]
"""
from __future__ import print_function

import os,sys,copy
from docopt import docopt
import numpy as np

#sys.path.append(__file__)
import nappy
from nappy.napsys import NAPSystem

__author__ = 'Ryo KOBAYASHI'
__version__ = '221117'

def convert_by_multiply(nsys,ax1,ax2,ax3):
    """Convert the input nsys by using ax1,ax2,ax3, each of them is written as (x1,x2,x3) that are
multiplying factors to a1, a2, and a3, respectively.
For example, if ax1 = (x1,x2,x3), the new a1 vector is given as:
  a1_new = x1*a1 +x2*a2 +x3*a3
    """
    nsys.assign_pbc()
    #...Reset alc to 1.0
    nsys.a1 = nsys.a1 *nsys.alc
    nsys.a2 = nsys.a2 *nsys.alc
    nsys.a3 = nsys.a3 *nsys.alc
    nsys.alc = 1.0
    print(' a1  = ',nsys.a1)
    print(' a2  = ',nsys.a2)
    print(' a3  = ',nsys.a3)

    pos = nsys.get_real_positions()
    spos = nsys.get_scaled_positions()
    symbols = nsys.get_symbols()
    for i in range(min(len(nsys.atoms),10)):
        print(' {0:5d} {1:s}'.format(i,symbols[i])
              +' {0:12.5f} {1:12.5f} {2:12.5f}'.format(spos[i,0],
                                                       spos[i,1],
                                                       spos[i,2])
              +' {0:12.5f} {1:12.5f} {2:12.5f}'.format(pos[i,0],
                                                       pos[i,1],
                                                       pos[i,2]))

    hmat = nsys.get_hmat()
    hmati= nsys.get_hmat_inv()
    a1new = ax1[0]*nsys.a1 +ax1[1]*nsys.a2 +ax1[2]*nsys.a3
    a2new = ax2[0]*nsys.a1 +ax2[1]*nsys.a2 +ax2[2]*nsys.a3
    a3new = ax3[0]*nsys.a1 +ax3[1]*nsys.a2 +ax3[2]*nsys.a3
    #...Check if a1.(a2xa3) > 0
    if np.dot(a1new,np.cross(a2new,a3new)) < 0.0:
        raise ValueError('a1.(a2xa3) < 0 of new axes, which is now allowed in VASP.')
    sa1new = np.dot(hmati,a1new)
    sa2new = np.dot(hmati,a2new)
    sa3new = np.dot(hmati,a3new)
    print(' new a1 =',a1new)
    print(' new a2 =',a2new)
    print(' new a3 =',a3new)
    psnew = NAPSystem(specorder=nsys.specorder)
    psnew.set_lattice(nsys.alc,a1new,a2new,a3new)

    # Expand the original system for the search of atoms to be included
    # in the new system.
    # First, compute how much we have to expand the original system
    hi = np.linalg.inv(hmat)
    icsa1new = [0,0,0]
    icsa2new = [0,0,0]
    icsa3new = [0,0,0]
    for i in range(3):
        if sa1new[i] < 0.0:
            icsa1new[i] = int(sa1new[i]-1.0)
        else:
            icsa1new[i] = int(sa1new[i]+1.0)
        if sa2new[i] < 0.0:
            icsa2new[i] = int(sa2new[i]-1.0)
        else:
            icsa2new[i] = int(sa2new[i]+1.0)
        if sa3new[i] < 0.0:
            icsa3new[i] = int(sa3new[i]-1.0)
        else:
            icsa3new[i] = int(sa3new[i]+1.0)
    print(' icsa1new: ',icsa1new)
    print(' icsa2new: ',icsa2new)
    print(' icsa3new: ',icsa3new)
    for i in range(3):
        if icsa1new[i] == 0:
            raise RuntimeError('icsa1new[i] == 0')
        if icsa2new[i] == 0:
            raise RuntimeError('icsa2new[i] == 0')
        if icsa3new[i] == 0:
            raise RuntimeError('icsa3new[i] == 0')
    irange1 = (min(icsa1new[0],icsa2new[0],icsa3new[0]),
               max(icsa1new[0],icsa2new[0],icsa3new[0]))
    irange2 = (min(icsa1new[1],icsa2new[1],icsa3new[1]),
               max(icsa1new[1],icsa2new[1],icsa3new[1]))
    irange3 = (min(icsa1new[2],icsa2new[2],icsa3new[2]),
               max(icsa1new[2],icsa2new[2],icsa3new[2]))

    print(' irange1: ',irange1)
    print(' irange2: ',irange2)
    print(' irange3: ',irange3)
    expos = []
    symbols = nsys.get_symbols()
    print(' symbols :',symbols)
    exsymbols = []
    print(' Expanding the original system...')
    for n3 in range(min(0,irange3[0]),irange3[1]):
        for n2 in range(min(0,irange2[0]),irange2[1]):
            for n1 in range(min(0,irange1[0]),irange1[1]):
                for ia in range(len(spos)):
                    sposi = copy.deepcopy(spos[ia])
                    sposi[0] += n1
                    sposi[1] += n2
                    sposi[2] += n3
                    posi = np.dot(hmat,sposi)
                    symbol = symbols[ia]
                    # print(ia,n1,n2,n3,symbol,sposi)
                    expos.append(posi)
                    exsymbols.append(symbol)

    print(' Extracting the atoms inside the new unit vectors...')
    hmat= psnew.get_hmat()
    hi = np.linalg.inv(hmat)
    for ia,posi in enumerate(expos):
        sposi = np.dot(hi,posi)
        if 0.0 <= sposi[0] < 1.0 and \
           0.0 <= sposi[1] < 1.0 and \
           0.0 <= sposi[2] < 1.0:
            symbol = exsymbols[ia]
            # print(' {0:5d} {1:s}'.format(ia,symbol)
            #       +' {0:12.5f} {1:12.5f} {2:12.5f}'.format(sposi[0],
            #                                                sposi[1],
            #                                                sposi[2]))

            # atom.set_symbol(symbol)
            # atom.set_pos(sposi[0],sposi[1],sposi[2])
            # psnew.add_atom(atom)
            psnew.add_atoms([symbol],[sposi])

    # tmp = None
    # #tmp = raw_input('Input periodic shift vector if you want: ')
    # tmp = ' 0.5, 0.0, 0.5'
    # if tmp:
    #     shift = [ float(x) for x in tmp.split(',')]
    #     for a in psnew.atoms:
    #         a.pos[0] += shift[0]
    #         a.pos[1] += shift[1]
    #         a.pos[2] += shift[2]
    #     psnew.assign_pbc()
    # psnew.write_POSCAR(infile+'.new')
    # print('Check '+infile+'.new')

    psnew.assign_pbc()

    #...Remove atoms that are too close each other
    psnew.make_pair_list(rcut=1.0)
    poss = psnew.get_scaled_positions()
    hmat = psnew.get_hmat()
    to_remove = []
    for i in range(len(psnew)):
        pi = poss[i]
        pinorm = np.dot(pi,pi)
        for j in psnew.neighbors_of(i):
            if i in to_remove or j in to_remove:
                continue
            pj = poss[j]
            rij = pj-pi -np.round(pj-pi)
            dij2 = np.dot(rij,rij)
            #...dij2 < 0.1 Ang is too close, either one of them must be removed
            if dij2 < 0.1:
                pjnorm = np.dot(pj,pj)
                if pjnorm < pinorm:
                    to_remove.append(j)
                else:
                    to_remove.append(i)

    psnew.remove_atoms(*to_remove)

    return psnew

def main():
    args = docopt(__doc__,version=__version__)
    infile = args['INFILE']
    ax1 = [ float(x) for x in args['--ax1'].split(',') ]
    ax2 = [ float(x) for x in args['--ax2'].split(',') ]
    ax3 = [ float(x) for x in args['--ax3'].split(',') ]
    if len(ax1) != 3:
        raise ValueError('len(ax1) != 3')
    if len(ax2) != 3:
        raise ValueError('len(ax2) != 3')
    if len(ax3) != 3:
        raise ValueError('len(ax3) != 3')

    nsys = nappy.io.read(infile)
    newsys = convert_by_multiply(nsys,ax1,ax2,ax3)
    nappy.io.write(newsys,infile+'_new')
    return None

if __name__ == '__main__':

    main()


import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
import warnings
from matplotlib import style
from collections import Counter
style.use('fivethirtyeight')

dataset ={'k':[[1,2],[2,3],[3,1]], 'r':[[6,5],[7,7],[8,6]]}

new_features = [5,5]

def k_nearst_neighbors(data, predict, k=3):
    if len(data)>=k:
        warnings.warn('k is set to a value than total voting groups!')

    distances = []
    for group in data:
        print(group)
        for features in data[group]:
            print(features)
            #euclidean_distance = sqrt( (features[0]-predict[0])**2 + (features[1]-predict[1])**2 )
            euclidean_distance = np.linalg.norm(np.array(features)-np.array(predict))
            distances.append([euclidean_distance, group])
    votes = [i[1] for i in sorted(distances) [:k]]
    print(Counter(votes).most_common(1))
    vote_result = Counter(votes).most_common(1)[0][0]

    return vote_result

result = k_nearst_neighbors(dataset, new_features, k=3)
print(result)


# max x + y
# s.t. ax + by <= 1
#       x, y   >= 0
#
# infeasible: a,b < 0
# unlimited: a < 0, b > 0
# one solution: a,b > 0 && (a != b)
# multiple solutions: a = b && a,b > 0

import sys
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import numpy as np
from pulp import *

def target(x):
    return -x

# a,b = -1
def infeasible(x):
    return -x - 1

# a = -1, b = 1
def unlimited(x):
    return x + 1

# a = 1, b = 2
def oneSol(x):
    return -x/2 + 1/2

# a,b = 1
def multSol(x):
    return -x + 1

x = np.array([-2, -1, 0, 1, 2])

fig, axs = plt.subplots(2,2)
fig.suptitle('Parameterized Lp')

for i in range(2):
    for j in range(2):
        axs[i][j].plot(x, target(x), color='red')
        axs[i][j].spines['bottom'].set_position('zero')
        axs[i][j].spines['left'].set_position('zero')
        axs[i][j].spines['top'].set_visible(False)
        axs[i][j].spines['right'].set_visible(False)
        axs[i][j].grid()

axs[0][0].plot(x, infeasible(x), color='violet')
axs[0][0].set_title('Infeasible')
verts = [(0,0), (2,0),(2,2),(0,2)]
axs[0][0].add_patch(Polygon(verts, color='pink'))
verts = [(-2,1), (2,-3),(-2,-3)]
axs[0][0].add_patch(Polygon(verts, color='pink'))

axs[0][1].plot(x, unlimited(x), color='yellow')
axs[0][1].set_title('Unlimited')
verts = [(0,0), (2,0),(2,3),(0,1)]
axs[0][1].add_patch(Polygon(verts, color='pink'))

axs[1][0].plot(x, oneSol(x), color='green')
axs[1][0].set_title('One solution')
verts = [(0,0), (1,0),(0,1/2)]
axs[1][0].add_patch(Polygon(verts, color='pink'))

axs[1][1].plot(x, multSol(x), color='blue')
axs[1][1].set_title('Multiple solutions')
verts = [(0,0), (1,0),(0,1)]
axs[1][1].add_patch(Polygon(verts, color='pink'))

plt.show()

if len(sys.argv) > 1:
    prob = LpProblem('para', LpMaximize)
    x = LpVariable('x', 0)
    y = LpVariable('y', 0)
    prob.setObjective(x+y)
    if sys.argv[1] == 'mult':
        prob += x + y <= 1
        prob.solve()
    if sys.argv[1] == 'unbounded':
        prob += -x + y <= 1
        prob.solve()
    if sys.argv[1] == 'infeasible':
        prob += -x - y <= 1
        prob.solve()
    if sys.argv[1] == 'one':
        prob += x + 2 * y <= 1
        prob.solve()

    print(LpStatus[prob.status], '\n')
    if(prob.status):
        print("objective value: ", value(prob.objective))
        print(f"x: {value(x)}")
        print(f"y: {value(y)}")


from turtle import color
from matplotlib import pyplot
companies=['hp','acer','lenovo','dell','apple']
itemsold=[122,54,88,121,158]
clrs=['red','green','blue','yellow','gray']

pyplot.bar(companies,itemsold,color=clrs)
pyplot.xlabel('laptop')
pyplot.ylabel('sales')
pyplot.title('laptop sales in 2022')
pyplot.show()