import re
import requests
import time
from pymongo import MongoClient
from bs4 import BeautifulSoup

def init_mongodb():
    #Mongo database and table
    db_client = MongoClient()
    db = db_client['case_test']
    # db = db_client['case_databse']
    coll = db.cases2001
    return db.cases2001
    # coll = db.cases
    # return db.cases

def case_scrape(cfile):
    '''
    need multiple queries, one for the actual text, one for cases ref(note: not all cases have the related case tag, might need to implement some RE to grap the rest), grab case title?
    '''
    r = requests.get(cfile)
    web_data=r.text
    soup = BeautifulSoup(web_data,'html.parser')
    '''
    from http://law.justia.com/cases/federal/appellate-courts/ca10/2000/ grabs all links of listed 2000 court cases
    note: started with 2017 cases but most were listed as pdf files while the 2000 cases were in a text format
    '''
    link_list=[]
    mylinks=soup.findAll('a',{'class':'case-name'})
    for l in mylinks:
        link_list.append(l['href'])
    return link_list

def link_scape(list_of_links, table):
    '''
    links in list_of_links only contain the second half of neede link, need to add base link to query them
    '''
    base_link='http://law.justia.com/'

    for i,v in enumerate(list_of_links):
        list_of_links[i]=base_link+v

    for lnk in list_of_links:
        link_r = requests.get(lnk)
        new_data=link_r.text
        link_soup = BeautifulSoup(new_data,'html.parser')
        #grabs full case text
        link_text=''
        for page in link_soup.findAll('div',{'class':'page'}):
            link_text+=page.get_text()
        title_text=''
        for x in link_soup.findAll('h1',{'class':'heading-1'}):
            title_text+=x.get_text()
        #makes list of case_ref
        #re expression to pull case refs
        re_list = re.findall('(\d+\s\D\.\D*\w+\s\d*)',link_text)
        add_new = [{'case_title':title_text,'case_text':link_text, 'case_ref':re_list}]
        table.insert(add_new)
        time.sleep(9)

        # outdated code, not all case refs had a class
        # case_ref=[]
        # mya = soup.findAll('a',{'class':'related-case'})
        # for a in mya:
        #     case_ref.append(a.text.strip())
if __name__ == '__main__':
    #start db
    # cases = init_mongodb()
    cases2001 = init_mongodb()
    #get links to scrape
    linklist = case_scrape('http://law.justia.com/cases/federal/appellate-courts/ca10/2001/')
    # case_scrape('http://law.justia.com/cases/federal/appellate-courts/ca10/2000/')

    #scrape and add data, just cases for train set
    link_scape(linklist,cases2001)


"""
This is a simple test file for working out how to use PyQt5 for our Schrodinger's Hack project.

This file simply creates a window application with a menu bar with additional submenus.

Author: Kondapuram Aditya Seshadri
Date: October 24, 2020
"""

import sys
from PyQt5.QtWidgets import (QMainWindow, QApplication, QStackedLayout,
                             QWidget, QPalette, QColor)

class Example(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # Comment
        stacklayout = QStackedLayout()

        stacklayout.addWidget(Color('red'))
        stacklayout.addWidget(Color('green'))
        stacklayout.addWidget(Color('blue'))
        stacklayout.addWidget(Color('yellow'))

        stacklayout.setCurrentIndex(3)

        widget = QWidget()
        widget.setLayout(stacklayout)

        self.setGeometry(0, 0, 1440, 1080)
        self.setWindowTitle('Stack Layout')
        self.show()

class Color(QWidget):

    def __init__(self, color):
        super().__init__()
        self.setAutoFillBackground(True)

        palette = self.palette()
        palette.setColor(QPalette.Window, QColor(color))
        self.setPalette(palette)

def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


from typing import List

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 3:
            return n
        num = 1
        cur = 1
        p = 1
        while p < n:
            if nums[p] != nums[p-1]:
                nums[cur] = nums[p]
                cur += 1
                p += 1
                num = 1
            elif nums[p] == nums[p-1] and num < 2:
                nums[cur] = nums[p]
                cur += 1
                p += 1
                num += 1
            else:
                p += 1
        return cur

if __name__ == '__main__':
    solu = Solution()
    nums = [0,0,1,1,1,1,2,3,3]
    ans = solu.removeDuplicates(nums)
    print(ans)


import math

def jump_search(arr, val):
    length = len(arr)
    jump = int(math.sqrt(length))
    left, right = 0, 0

    while left < length and arr[left] <= val:
        print(arr[left])
        right = min(length - 1, left + jump)
        if arr[left] <= val <= arr[right]:
            break
        left += jump

    if left >= length or arr[left] > val:
        return -1

    right = min(length - 1, right)
    i = left
    while i <= right and arr[i] <= val:
        if arr[i] == val:
            return i
        i += 1
    return -1

print(jump_search([1, 2, 3, 4, 9, 19, 45], 19))


"""
    databases page
"""

import zoom
import zoom.html as h

def get_isolation_level(db):
    if db.connect_string.startswith('mysql'):
        return str(list(db('select @@TX_ISOLATION'))[0][0])
    else:
        return ''

class DatabaseView(zoom.View):
    """display database information"""

    def index(self):
        engine = zoom.system.site.config.get('database', 'engine')
        if engine == 'mysql':

            db = zoom.system.site.db

            sections = [
                ('Settings', [
                    ('Connection', str(zoom.tools.websafe(zoom.system.site.db))),
                    ('Isolation Level', get_isolation_level(zoom.system.site.db))
                ]),
                ('Process List', zoom.system.site.db('show processlist')),
                ('Status', zoom.system.site.db('show status')),
            ]

            content = zoom.Component(
                *((h.h2(title), h.table(code)) for title, code in sections),
                css="""
                .content table { width: 100%; }
                .content table td {width: 50%; }
                """
            )

        else:
            content = 'not available for {} database engine'.format(engine)
        return zoom.page(content, title='Database')

main = zoom.dispatch(DatabaseView)


import numpy as np
from bounding_box.zonotope_tree import *
from visualization.visualize import *
from pypolycontain.visualization.visualize_2D import visualize_2D_zonotopes as visZ

def test_with_dataset():
    #FIXME: Import issues
    from utils.PWA_Control_utils import polytree_to_zonotope_tree
    import pickle
    with open("zonotope_datasets/inverted_pendulum.pkl", "rb") as f:
        state_tree = pickle.load(f)
    f.close()
    # extract zonotopes
    zonotope_tree = polytree_to_zonotope_tree(state_tree)
    zonotope_count = len(zonotope_tree.zonotopes)

    query_point = np.asarray([(np.random.rand(1) - 0.5) * 0.24,
                              (np.random.rand(1) - 0.5) * 2])
    print(query_point)
    query_point = query_point.reshape(-1, 1)
    closest_zonotope, candidate_boxes, query_box = zonotope_tree.find_closest_polytopes(query_point)
    print(('Query point: ', query_point))
    ax_lim = np.asarray([-zonotope_count, zonotope_count, -zonotope_count, zonotope_count]) * 1.1
    fig, ax = visZ(zonotope_tree.zonotopes, title="", alpha=0.2, axis_limit=ax_lim)
    fig, ax = visZ(closest_zonotope, title="", fig=fig, ax=ax, alpha=1, axis_limit=ax_lim)
    fig, ax = visualize_box_nodes(zonotope_tree.box_nodes, fig=fig, ax=ax, alpha=0.4, linewidth=0.5)
    fig, ax = visualize_boxes(candidate_boxes, fig=fig, ax=ax, alpha=1)
    print(('Evaluating %d zonotopes out of %d' % (len(candidate_boxes), len(zonotope_tree.zonotopes))))
    fig, ax = visualize_boxes([query_box], fig=fig, ax=ax, alpha=0.3, fill=True)
    plt.scatter(query_point[0], query_point[1], s=20, color='k')
    print(('Closest Zonotope: ', closest_zonotope))
    plt.show()

def zonotope_reduction_line_nd(zonotope_count, dim, num_of_queries):
    zonotopes = []
    centroid_range = zonotope_count*5
    generator_range = 10
    for i in range(zonotope_count):
        m = np.random.random_integers(dim, 2*dim)
        G = 2*(np.random.rand(dim, m) - 0.5) * generator_range * 1
        x = 2*(np.random.rand(dim-1,1) - 0.5)
        x = np.vstack([2*(np.random.rand(1,1) - 0.5) * centroid_range,x])
        # print(x)
        zonotopes.append(zonotope(x, G))
    zt = PolytopeTree_Old(zonotopes)

    query_points = (np.random.rand(dim-1,num_of_queries)-0.5)
    query_points = np.vstack([2*(np.random.rand(1, num_of_queries) - 0.5) * centroid_range,query_points])
    # print(query_points)
    reduction_ratios = np.zeros([num_of_queries])
    for i, q in enumerate(query_points.T):
        closest_zonotope, candidate_boxes, query_box = zt.find_closest_polytopes(q)
        reduction_ratios[i] = len(candidate_boxes)/(zonotope_count*1.)

    if dim ==2:
        fig, ax = visZ(zt.polytopes, title="", alpha=0.2)
        ax.scatter(query_points[0,:], query_points[1,:],s=3)
        ax.set_xlim([-centroid_range*1.2,centroid_range*1.2])
        ax.set_ylim([-centroid_range * 1.2, centroid_range * 1.2])
        plt.xlabel('x')
        plt.ylabel('y')
        plt.title('Zonotope and Query Point Distribution')

        plt.show()

    return np.average(reduction_ratios), np.std(reduction_ratios)

def zonotope_reduction_line_over_d(zonotope_count, d_start,d_end, num_of_queries):
    d = np.arange(d_start,d_end)
    reduction_ratios = np.zeros([d.shape[0],2])
    for i, d_i in enumerate(d):
        print(('Evaluating %d-D' %d_i))
        reduction_ratios[i,0],reduction_ratios[i,1] = zonotope_reduction_line_nd(d_i**zonotope_count,d[i],num_of_queries)
    print(reduction_ratios)
    plt.errorbar(d,100*reduction_ratios[:,0],100*reduction_ratios[:,1],marker='.',ecolor='r',elinewidth=0.3,capsize=2,linewidth=0.5,markersize=7)
    plt.xlabel('Dimension')
    plt.ylabel('% of zonotopes evaluated')
    plt.title('Line Distributed Zonotope Set Reduction with Bounding Boxes')
    plt.show()

def zonotope_reduction_box_nd(zonotope_count, dim, num_of_queries):
    zonotopes = []
    centroid_range = zonotope_count*8
    generator_range = zonotope_count
    print(('Centroid range: %d' %centroid_range))
    print(('Generator range: %d' %generator_range))
    for i in range(zonotope_count):
        m = np.random.random_integers(dim, 2*dim)
        G = (np.random.rand(dim, m) - 0.5) * generator_range * 1
        x = 2*(np.random.rand(dim,1) - 0.5)*centroid_range
        # print(x)
        zonotopes.append(zonotope(x, G))
    zt = PolytopeTree_Old(zonotopes)
    #query points in a line
    # query_points = (np.random.rand(dim-1,num_of_queries)-0.5)
    # query_points = np.vstack([query_points, 2*(np.random.rand(1, num_of_queries) - 0.5) * centroid_range*2])
    #query points anywhere in space
    query_points = 2 * (np.random.rand(dim, num_of_queries) - 0.5) * centroid_range * 2
    reduction_ratios = np.zeros([num_of_queries])
    for i, q in enumerate(query_points.T):
        closest_zonotope, candidate_boxes, query_box = zt.find_closest_polytopes(q)
        reduction_ratios[i] = len(candidate_boxes)/(zonotope_count*1.)
    if dim ==2:
        fig, ax = visZ(zt.polytopes, title="", alpha=0.2)
        ax.scatter(query_points[0,:], query_points[1,:],s=3)
        plt.xlabel('x')
        plt.ylabel('y')
        plt.title('Zonotope and Query Point Distribution')

        plt.show()
    return np.average(reduction_ratios), np.std(reduction_ratios)

def zonotope_reduction_box_over_d(zonotope_count, d_start,d_end, num_of_queries):
    d = np.arange(d_start,d_end)
    reduction_ratios = np.zeros([d.shape[0],2])
    for i, d_i in enumerate(d):
        print(('Evaluating %d-D' %d_i))
        reduction_ratios[i,0],reduction_ratios[i,1] = zonotope_reduction_box_nd(d_i**zonotope_count,d[i],num_of_queries)
    print(reduction_ratios)
    plt.errorbar(d,100*reduction_ratios[:,0],100*reduction_ratios[:,1],marker='.',ecolor='r',elinewidth=0.3,capsize=2,linewidth=0.5,markersize=7)
    plt.xlabel('Dimension')
    plt.ylabel('% of zonotopes evaluated')
    plt.title('Box Distributed Zonotope Set Reduction with Bounding Boxes')
    plt.show()

if __name__ == '__main__':
    plt.rcParams["font.family"] = "Times New Roman"
    zonotope_reduction_box_over_d(5,2,5,100)


'''
from selenium import webdriver as wd

driver = wd.Chrome("./chromedriver.exe")
url = "https://www.naver.com"
driver.get(url)
'''
import time
import os
from selenium import webdriver
from bs4 import BeautifulSoup as soups

def search_selenium(search_name, search_path, search_limit) :
    search_url = "https://www.google.com/search?q=" + str(search_name) + "&hl=ko&tbm=isch"
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("headless")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("lang=ko_KR")
    browser = webdriver.Chrome('./chromedriver.exe',chrome_options=chrome_options)
    browser.get(search_url)

    image_count = len(browser.find_elements_by_tag_name("img"))

    print("로드된 이미지 개수 : ", image_count)

    browser.implicitly_wait(2)

    for i in range( search_limit ) :
        image = browser.find_elements_by_tag_name("img")[i]
        time.sleep(0.5)
        image.screenshot(search_path + str(i) + ".png")

    browser.close()

if __name__ == "__main__" :

    search_name = ['너에게 닿기를 아라이 카즈이치','너에게 닿기를 쿠로누마 사와코','너에게 닿기를 쿠루미자와 우메','원피스 나미','원피스 니코 로빈','원피스 비비','원피스 보아 핸콕','나루토 사쿠라','나루토 히나타','나루토 츠나데','나루토 ',' 나루토 텐텐','도라에몽 이슬이','포켓몬스터 꼬북이','포켓몬스터 이슬이','포켓몬스터 간호순','포켓몬스터 여경','코난 미란이','코난 카즈하','코난 하이바라 아이','인사이드 아웃 슬픔이','겨울왕국 안나','겨울왕국 엘사','뽀로로 루피','코코몽 코코몽','뽀로로 뽀로로']
    search_limit = 150
    for i in search_name:
        print(i)
        directory = "E:/AI/crawl/download/여캐/"+i
        search_path = "E:/AI/crawl/download/여캐/"+i+"/"+i
        if not os.path.exists(directory):
            os.makedirs(directory)
    # search_maybe(search_name, search_limit, search_path)
        search_selenium(i, search_path, search_limit)


#
# @lc app=leetcode id=206 lang=python3
#
# [206] Reverse Linked List
#

# @lc code=start
# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next: ListNode | None = next

class Solution:
    def reverseList(self, head: ListNode | None) -> ListNode | None:
        if not head:
            return head

        fake_head = ListNode(-1, head)

        prev_node = fake_head
        curr_node: ListNode | None = head
        next_node = head.next

        while curr_node is not None:
            curr_node.next = prev_node
            prev_node = curr_node
            curr_node = next_node

            if next_node is not None:
                next_node = next_node.next

        if fake_head.next is not None:
            fake_head.next.next = None

        return prev_node
# @lc code=end


import hero_data
import rules
import facts
import time

TEAM =1
ENEMY =-1
RULES_HEAD = ['strong_against']
FACTS_HEAD = ['counter','ability','range','tier','difficulty']
VARIABLE_LIST = ['A','B','C','D','X']
def sortFunc(e):
  return e.tier

heroes = hero_data.generateList()
# heroes.sort(key = sortFunc)
fact_list = facts.generateList(heroes.values())

Enemy = []
Team = []
favorites = []
suggestions = {}
current_team = ENEMY

def query(resolvent,statement,pick):

	# While the resolvent is not emepty do:
	if len(resolvent) >0:
		# choose a goal from the resolvent

		goal = resolvent.pop()
		# choose a clause from rules
		if goal.predicate in RULES_HEAD or goal.predicate in rules.test_head:
			for rule in rules.rule_list:
				if rule.head.predicate == goal.predicate:
					for small_goal in rule.body:
						small_goal.substitude(rule.head.atoms,goal.atoms)

						resolvent.append(small_goal)

					query(resolvent,statement,pick)

		# or choose a clase from facts
		elif goal.predicate in FACTS_HEAD:

			# loop through each fact

			for fact in fact_list[goal.predicate]:

				variables = 0
				unequal_terms = 0
				i = 0
				while i < len(fact.atoms) :
					if goal.atoms[i] in VARIABLE_LIST:
						variables = variables + 1
						if goal.atoms[i] == 'X':
							pick = fact.atoms[i]
					elif goal.atoms[i] != fact.atoms[i]:
						break

					i = i+1

				if i == len(fact.atoms):

					new_resolvent = []
					for sgoal in resolvent:
						new_resolvent.append(sgoal.copy())

					new_statement = statement + ' ' +fact.__repr__()+ '.'
					if variables != 0:
						for j in range(0, len(new_resolvent)):

							new_resolvent[j].substitude(goal.atoms,fact.atoms)

					else:
						# if the resolvent is empty, a solution is found
						if len(resolvent)==0:

							suggestions[pick] = new_statement

					#Whenever we find an substitution, we recursively call the query with new resolvent.
					query(new_resolvent,new_statement,pick)

	else:
		if len(resolvent)==0:

			suggestions[pick] = statement
# for i in range(1,11):
# 	start = time.time()
# 	query([rules.Goal(str(i),['X'])],'explain: ','X')
# 	end = time.time()
# 	print end-start

def deduce():

    for pick in Enemy:
    	query([rules.Clause('strong_against',['X',pick.name])],'explain: ','X')

def strong_against(heroA, heroB):
	return False
def weak_against(heroA, heroB):
	return strong_against(heroB, heroA)

def teamPick(heroname):
	if len(Team)<=5:
		if heroes[heroname] not in Team and heroes[heroname] not in Enemy:
			Team.append(heroes[heroname])

def enemyPick(heroname):
	if len(Enemy)<=5:
		if heroes[heroname] not in Enemy and heroes[heroname] not in Team :
			Enemy.append(heroes[heroname])

def redo():
	removePick()
	suggestions.clear()
def removePick():
	if current_team == ENEMY:
		if len(Enemy) >=1:
			Enemy.pop()
		elif len(Team) >=1:
			Team.pop()
	else:
		if len(Team) >=1:
			Team.pop()
		elif len(Enemy) >=1:
			Enemy.pop()
def redoSuggest():
	suggestions.clear()


# Write a Python program to print the even numbers from a given list.

def even1(n):
    list=[]
    for items in n:
        if items%2==0:
            list.append(items)
    return list

list1=[]

x=int(input("Enter the number of elements in the list: "))

for i in range(x):
    y=int(input())
    list1.append(y)

list1=even1(list1)

print(list1)


#!/usr/bin/python3
#	Check if a Python module is installed
#	Usage: is_python_module_installed.py module_name
#
#	Exit code 1 if installed (or no module specified)
#
#	2021 Brian Walton (riban@zynthian.org)

import sys
import pkg_resources

try:
	module = sys.argv[1]
except:
	sys.exit(1)

if module in {pkg.key for pkg in pkg_resources.working_set}:
	sys.exit(1)
else:
	sys.exit(0)


import argparse
import multiprocessing
import os
from importlib import import_module
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader

from dataset import TestDataset, MaskBaseDataset

def load_model(saved_model, num_classes, device):
    model_cls = getattr(import_module("model"), args.model)
    model = model_cls(
        num_classes=num_classes
    )
    model_path = os.path.join(saved_model, 'best.pth')
    model.load_state_dict(torch.load(model_path, map_location=device))

    return model

@torch.no_grad()
def inference(data_dir, model_dir, output_dir, args):
    """
    """
    use_cuda = torch.cuda.is_available()
    device = torch.device("cuda" if use_cuda else "cpu")

    num_classes = MaskBaseDataset.num_classes
    model_dir_list = os.listdir(model_dir)
    oof_pred = None
    for fold_model in model_dir_list:
        fold_model_path = os.path.join(model_dir, fold_model)
        model = load_model(fold_model_path, num_classes, device).to(device)
        model.eval()

        img_root = os.path.join(data_dir, 'images')
        info_path = os.path.join(data_dir, 'info.csv')
        info = pd.read_csv(info_path)

        img_paths = [os.path.join(img_root, img_id) for img_id in info.ImageID]
        dataset = TestDataset(img_paths, args.resize)
        loader = torch.utils.data.DataLoader(
            dataset,
            batch_size=args.batch_size,
            num_workers=multiprocessing.cpu_count() // 2,
            shuffle=False,
            pin_memory=use_cuda,
            drop_last=False,
        )

        print("Calculating inference results..")
        preds = []
        with torch.no_grad():
            for idx, images in enumerate(loader):
                images = images.to(device)
                pred = model(images)
                preds.extend(pred.cpu().numpy())
            fold_pred = np.array(preds)
        n_splits = len(model_dir_list)
        # 확률 값으로 앙상블을 진행하기 때문에 'k'개로 나누어줍니다.
        if oof_pred is None:
            oof_pred = fold_pred / n_splits
        else:
            oof_pred += fold_pred / n_splits

    info['ans'] = np.argmax(oof_pred, axis=1)
    save_path = os.path.join(output_dir, f'output.csv')
    info.to_csv(save_path, index=False)
    print(f"Inference Done! Inference result saved at {save_path}")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    # Data and model checkpoints directories
    parser.add_argument('--batch_size', type=int, default=1000, help='input batch size for validing (default: 1000)')
    parser.add_argument('--resize', type=int, nargs="+", default=(128, 96), help='resize size for image when you trained (default: (224, 224))')
    parser.add_argument('--model', type=str, default='MyModel', help='model type (default: BaseModel)')

    # Container environment
    parser.add_argument('--data_dir', type=str, default=os.environ.get('SM_CHANNEL_EVAL', '/opt/ml/input/data/eval'))
    parser.add_argument('--model_dir', type=str, default=os.environ.get('SM_CHANNEL_MODEL', './model/exp'))
    # parser.add_argument('--output_dir', type=str, default=os.environ.get('SM_OUTPUT_DATA_DIR', './output'))
    #parser.add_argument('--model_name', type=str, default=os.environ.get('SM_CHANNEL_MODEL', 'exp'))
    args = parser.parse_args()

    data_dir = args.data_dir
    model_dir = args.model_dir #os.path.join('./results', args.model_name)
    output_dir = model_dir

    os.makedirs(output_dir, exist_ok=True)

    inference(data_dir, model_dir, output_dir, args)


#!/usr/bin/env python3
"""Writing strings to Redis"""
import redis
import uuid
from typing import Union, Callable
from functools import wraps

def count_calls(method: Callable) -> Callable:
    """ Count calls to a method in the database"""
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        key = method.__name__
        count_key = f"{key}_count"
        self._redis.incr(count_key)
        return method(self, *args, **kwargs)
    return wrapper

def call_history(method: Callable) -> Callable:
    """Returns the callable that will be called"""
    key = method.__qualname__
    inputs = key + ":inputs"
    outputs = key + ":outputs"

    @wraps(method)
    def wrapper(self, *args, **kwds):
        """Returns the method wrapped by this method call"""
        self._redis.rpush(inputs, str(args))
        data = method(self, *args, **kwds)
        self._redis.rpush(outputs, str(data))
        return data
    return wrapper

class Cache:
    """Cache implementation for a single cache object"""
    def __init__(self):
        """Construct a new Cache instance with the given arguments"""
        self._redis = redis.Redis()
        self._redis.flushdb()

    @count_calls
    @call_history
    def store(self, data: Union[str, bytes, int, float]) -> str:
        """Store the given data in the given database
        and return it as a string"""
        key = str(uuid.uuid4())
        if isinstance(data, (str, bytes)):
            self._redis.set(key, data)
        elif isinstance(data, (int, float)):
            self._redis.set(key, str(data))
        return key

    def get(self, key: str, fn: Callable = None)\
            -> Union[str, bytes, int, float]:
        """ Get the value of the given key from the given function"""
        data = self._redis.get(key)
        if data is not None:
            if fn is not None:
                return fn(data)
            return data
        return None

    def get_str(self, key: str) -> str:
        """ Returns the string representation
        of the given key in the given format"""
        return self.get(key, fn=lambda x: x.decode("utf-8"))

    def get_int(self, key: str) -> int:
        """ Returns the value of the given key in the given"""
        return self.get(key, fn=int)

def replay(c: Cache):
    """Retrieving lists"""
    r = c._redis
    key = c.store.__qualname__
    inputs_key = f"{key}:inputs"
    outputs_key = f"{key}:outputs"

    inputs = r.lrange(inputs_key, 0, -1)
    outputs = r.lrange(outputs_key, 0, -1)

    call_count = len(inputs)

    print(f"{key} was called {call_count} times:")

    for input_data, output_data in zip(inputs, outputs):
        input_args = eval(input_data.decode("utf-8"))
        output_key = output_data.decode("utf-8")
        print(f"{key}{input_args} -> {output_key}")


# -*- coding: utf-8 -*-
import os,sys

# Import Qt modules
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from model import *
from utils import _date_from_str
from datetime import date
# Import the compiled UI module
sys.path.append("ui")
from deliver_form_ui import Ui_deliver_form
from add_drug_form import AddDrugForm
from new_distributor_form import NewDistributorForm
from new_financing_form import NewFinancingForm
from time import strftime

from appy.pod.renderer import Renderer
from os import popen, path
class DeliverWindow(QFrame):

	def initForm(self):
		QFrame.__init__(self)
		self.ui = Ui_deliver_form()
		self.ui.setupUi(self)

		self.ui.distributor_combo.setEditable(False)
		self.drawDistributorCombo()
		self.drawFinancingCombo()
		QObject.connect(self.ui.tableWidget, SIGNAL("cellDoubleClicked(int, int)"), self.showAddDrugForm)
		QObject.connect(self.ui.save_close_btn, SIGNAL("clicked()"), self.saveAcceptDeliver)
		QObject.connect(self.ui.save_btn, SIGNAL("clicked()"), self.saveDeliver)
		QObject.connect(self.ui.print_bill_btn, SIGNAL("clicked()"), self.createReport)
		QObject.connect(self.ui.close_btn, SIGNAL("clicked()"), self.closeme)

	def initNewDeliver(self):
		self.deliver = Deliver()
		self.deliver.create_date = date.today()
		self.ui.bill_number_date.setText(QString.fromUtf8(repr(self.deliver)))
		self.ui.deliver_date.setText(QString.fromUtf8(self.deliver.create_date.strftime("%d.%m.%Y")))
		self.drawTable()

	def __init__(self,deliver=None):
		self.initForm()
		if deliver == None:
			self.initNewDeliver()
		else:
			self.deliver = deliver
			self.ui.bill_number_date.setText(QString.fromUtf8(repr(self.deliver)))
			self.ui.deliver_date.setText(self.deliver.deliver_date.strftime("%d.%m.%Y"))
			self.ui.distributor_combo.setCurrentIndex(self.ui.distributor_combo.findText(self.deliver.distributor.name))
			self.ui.financing_combo.setCurrentIndex(self.ui.financing_combo.findText(self.deliver.financing.name))
			self.drawTable()

			if self.deliver.accepted:
				self.ui.save_btn.setDisabled(True)
				self.ui.save_close_btn.setDisabled(True)
				self.ui.distributor_combo.setDisabled(True)
				self.ui.financing_combo.setDisabled(True)
				self.ui.deliver_date.setDisabled(True)
	def drawTable(self):
		self.ui.tableWidget.clear()
		self.ui.tableWidget.setRowCount(1)
		self.ui.tableWidget.setColumnCount(7)
		self.ui.tableWidget.setHorizontalHeaderLabels([QString.fromUtf8('ИД'), QString.fromUtf8('Название препарата'), QString.fromUtf8('Производитель'), QString.fromUtf8('Серийный номер'), QString.fromUtf8('Годен до'), QString.fromUtf8('Цена'),QString.fromUtf8('Количество')])
		self.summ = 0
		for m in self.deliver.maps:
			if not m.count == 0:
				data = []
				data.append(str(m.drug.id))
				data.append(QString.fromUtf8(m.drug.name()))
				data.append(m.drug.manufacter.name)
				data.append(str(m.drug.serial))
				data.append(m.drug.best_before.strftime("%d.%m.%Y"))
				data.append(str(m.drug.price))
				data.append(str(m.count))

				self.summ = self.summ + m.count*m.drug.price
				for i in range(0,7):
					tableitem = QTableWidgetItem()
					tableitem.setText(data[i])
					tableitem.font = QFont("Arial", 10)
					tableitem.font.setBold(True)
					tableitem.textcolor = QColor("black")
					tableitem.setBackgroundColor(QColor('White'))
					self.ui.tableWidget.setItem(self.ui.tableWidget.rowCount() - 1,i,tableitem)
				self.ui.tableWidget.setRowCount(self.ui.tableWidget.rowCount()+1)
			else:
				self.deliver.maps.remove(m)
		self.ui.label_3.setText(QString.fromUtf8("Всего лс на сумму " + str(self.summ) + "р."))
		self.ui.tableWidget.resizeColumnsToContents()

	def drawDistributorCombo(self):
		distributors = query_session.query(Distributor).all()
		self.ui.distributor_combo.clear()
		for item in distributors:
			self.ui.distributor_combo.addItem(item.name)

		self.ui.distributor_combo.addItem(QString.fromUtf8('Новый поставщик'))
		QObject.connect(self.ui.distributor_combo, SIGNAL("currentIndexChanged(int)"), self.setDistributor)
		self.setDistributor(0)

	def drawFinancingCombo(self):
		fin = query_session.query(Financing).all()
		self.ui.financing_combo.clear()

		for item in fin:
			self.ui.financing_combo.addItem(item.name)

		self.ui.financing_combo.addItem(QString.fromUtf8('Новый источник финансирования'))
		QObject.connect(self.ui.financing_combo, SIGNAL("currentIndexChanged(int)"), self.setFinancing)
		self.setFinancing(0)

	def showAddDrugForm(self, row, col):
		if row == self.ui.tableWidget.rowCount() - 1:
			self.add_drug_form = AddDrugForm(self)
			self.add_drug_form.setWindowModality(2)
			QObject.connect(self.add_drug_form.count_form, SIGNAL("drugAdded()"), self.drawTable)
			self.add_drug_form.showMaximized()

	def saveAcceptDeliver(self):
		self.deliver.accepted = True
		self.saveDeliver()

	def saveDeliver(self):
		self.deliver.deliver_date = _date_from_str(self.ui.deliver_date.text())
		self.deliver.distributor = self.distributor
		self.deliver.financing = self.financing
		s = Session()
		s.add(self.deliver)
		s.commit()
		s.close()

		self.parent().close()

	def setDistributor(self,num):
		if (num < self.ui.distributor_combo.count() - 1):
			distributor = query_session.query(Distributor).filter_by(name=unicode(self.ui.distributor_combo.itemText(num))).one()
			self.distributor = distributor
		else:
			self.new_distributor_form = NewDistributorForm(self)
			self.new_distributor_form.setWindowModality(2)
			QObject.connect(self.new_distributor_form, SIGNAL("distributorAdded()"), self.drawTable)
			QObject.connect(self.new_distributor_form, SIGNAL("distributorAdded()"), self.drawDistributorCombo)
			self.new_distributor_form.show()

	def setFinancing(self,num):
		if (num < self.ui.financing_combo.count() - 1):
			financing = query_session.query(Financing).filter_by(name=unicode(self.ui.financing_combo.itemText(num))).one()
			self.financing = financing
		else:
			self.new_financing_form = NewFinancingForm(self)
			self.new_financing_form.setWindowModality(2)
			QObject.connect(self.new_financing_form, SIGNAL("financingAdded()"), self.drawTable)
			QObject.connect(self.new_financing_form, SIGNAL("financingAdded()"), self.drawFinancingCombo)
			self.new_financing_form.show()

	def createReport(self):
		fileName = '%sdeliver%d.pdf' % ('reports/', self.deliver.id)
		if path.exists(fileName):
			os.popen('evince %s' % fileName)
		else:
			opts = {'deliver': self.deliver}
			renderer = Renderer('appy/templates/deliver.odt', opts, fileName)
			renderer.run()

		os.popen('evince %s' % fileName)

	def closeme(self):
		self.parent().close()


import os
import shutil
import subprocess

SOURCE_FILE = "~/repos/cleantrace/azure-pipelines.yml"
SUBDIRS_DIRECTORY = "~/repos/cleantrace"

# set source file path
source_path = os.path.expanduser(SOURCE_FILE)

# set destination directory path
destination_dir = os.path.expanduser(SUBDIRS_DIRECTORY)

# get a list of all subdirectories in the destination directory that start with "cleantrace-cloud"
subdirs = [os.path.join(destination_dir, subdir) for subdir in os.listdir(destination_dir) if os.path.isdir(
    os.path.join(destination_dir, subdir)) and subdir.startswith("cleantrace-cloud-lambda")]

# copy the source file to each subdirectory
for subdir in subdirs:
    destination_path = os.path.join(subdir, "azure-pipelines.yml")

    try:
        shutil.copy2(source_path, destination_path, follow_symlinks=True)
        os.chdir(subdir)
        print(f"File copied to {subdir}. Pushing changes now.")
    except (FileNotFoundError, PermissionError) as e:
        print(f"Error copying file to {subdir}: {e}")

    # pushing the latest changes to their respective GH repos
    try:
        subprocess.run(["git", "checkout", "dev"])
        subprocess.run(["git", "config", "pull.rebase", "false"])
        subprocess.run(["git", "pull"])
        subprocess.run(["git", "add", "."])
        subprocess.run(
            ["git", "commit", "-m", "updated azure pipeline template"])
        subprocess.run(["git", "push"])
    except subprocess.CalledProcessError as e:
        print(e)


import logging
import time
from ckip_transformers.nlp import CkipWordSegmenter, CkipPosTagger, CkipNerChunker

# 对input.txt的文件分词输出到output.txt中
# 开20个进程

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

ws_driver = CkipWordSegmenter(level=3,device=-1)

# ------------------test--------------------------#
# text = [
#    "傅達仁今將執行安樂死，卻突然爆出自己20年前遭緯來體育台封殺，他不懂自己哪裡得罪到電視台。",
#    "美國參議院針對今天總統布什所提名的勞工部長趙小蘭展開認可聽證會，預料她將會很順利通過參議院支持，成為該國有史以來第一位的華裔女性內閣成員。",
#    "空白 也是可以的～",
# ]
# ws  = ws_driver(text)
# print(ws)
# ------------------test--------------------------#

#
output = open('ckip.txt', 'w', encoding='utf-8')
with open('chinese.txt', 'r', encoding='utf-8') as content :
    for texts_num, line in enumerate(content):
        line = line.strip('\n')
        # words = jieba.cut(line, cut_all=False)
        line = str(line)
        line = [(line)]
        # print(line)
        words = ws_driver(line)
        # print(words)
        for word in words:
            # print("Here")
            # print(word)
            word = str(word)
            output.write(word + ' ')
        output.write('\n')

        if (texts_num + 1) % 10000 == 0:
            logging.info("已完成前 %d 行的斷詞" % (texts_num + 1))
output.close()


from django.shortcuts import render

# Create your views here.
from .models import MyData
from django.http import HttpResponse
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
import numpy as np
import pickle

# Create your views here.
def home(request):
    return render(request,'Hm.html')

def display(request):
    return render(request,'application.html')

def save(request):
    if request.method=="POST":
        s=MyData()
        s.Name=request.POST.get('ht_name')
        s.Last_Name=request.POST.get('ht_Lname')
        s.Mobile=request.POST.get('ht_Mnum')
        s.Email=request.POST.get('ht_Email')
        s.Gender=request.POST.get('ht_Male')
        s.TOFEL=request.POST.get('ht_tofel')
        s.GRE=request.POST.get('ht_gre')
        s.UNI_rating=request.POST.get('ht_Uni_rating')
        s.SOP=request.POST.get('ht_sop')
        s.LOR=request.POST.get('ht_lor')
        s.CGPA=request.POST.get('ht_cgpa')
        s.Research_Ex=request.POST.get('ht_research')
        s.save()

        #read the data in data frame
        data=[[s.GRE,s.TOFEL,s.UNI_rating,s.SOP,s.LOR,s.CGPA,s.Research_Ex]]
        newx=pd.DataFrame(data,columns=["GRE_Score","TOEFL_Score","University_Rating","SOP","LOR","CGPA","Research"])

        #loading model and data using  pickle
        filename = 'C:\\Users\\Vipin Kumar\\Desktop\\admission\\myapp\\data\\admission_model.sav'

        # load the model from disk

        model,x = pickle.load(open(filename, 'rb'))

        #apply minMax scaler for scaling the data
        scalerX = MinMaxScaler(feature_range=(0, 1))
        x[x.columns] = scalerX.fit(x[x.columns])

        newx[newx.columns] = scalerX.transform(newx[newx.columns])

        #here we predict the score on new data
        y_predict = model.predict(newx)

        #return HttpResponse('Record submitted successfully')
        return render(request,'Output.html', {'score':y_predict})


from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from elasticsearch import Elasticsearch
from kafka import KafkaConsumer
from kafka import KafkaProducer
from .. import views
import json
import datetime
import random
import arrow

class ListingFormTests(TestCase):
  #fixtures = ['db']  # load from DB

  def setUp(self): # try to indice some fixtures to elasticsearch
    self.client = Client()

    fixtureA = {"listing_id":1,"drone": 2, "owner": 2, "description": "please rent myseediestdrone!", "time_posted": "2016-10-24T04:28:48.932Z", "price_per_day": 10.0}
    fixtureB = {"listing_id":2,"drone": 3, "owner": 3, "description": "please rent myforgeddrone!", "time_posted": "2016-10-24T04:28:48.991Z", "price_per_day": 14.0}

    es = Elasticsearch(['es'])
    es.index(index='listing_index', doc_type='listing', id=fixtureA['listing_id'], body=fixtureA)
    es.index(index='listing_index', doc_type='listing', id=fixtureB['listing_id'], body=fixtureB)
    es.indices.refresh(index='listing_index')
    producer.send('new-listings-topic', json.dumps(some_new_listing).encode('utf-8'))

    response = self.client.post(reverse('create-listing'), fixtureA)
    print("test_create_listing POST " + str(response))

    resp = json.loads(response.content.decode('utf8'))
    self.assertEquals(response.status_code, 200)
    print("listing_atts" + str(resp))

  # append number to test to get python to run defs in correct order
  def est1_DroneForm(self): # not passing
    response = self.client.get(reverse('inspect_drone', kwargs={'drone_id':201}))
    resp = json.loads(response.content.decode('utf8'))

    print("test_drone_attributes GET " + str(resp))
    self.assertEquals(resp["ok"],True)
    self.assertEquals(resp['resp']['model_name'], 'prehistorians_inexpugnably100')

  def est2_Drone_Invalid_id(self):
    response = self.client.get(reverse('inspect_drone', kwargs={'drone_id':300}))
    resp = json.loads(response.content.decode('utf8'))
    self.assertEquals(resp["ok"], False)

  def est4_Drones_Available_For_hire(self):
    available_drones = models.Drone.objects.filter(available_for_hire = True)
    self.assertGreater(len(available_drones),0)

  def tearDown(self):
    del self.client


# -*- coding: utf-8 -*-
"""
testbed of unsupervised time series anomaly detection
@Author: Hongzuo Xu <hongzuoxu@126.com, xuhongzuo13@nudt.edu.cn>
"""

import os
import argparse
import getpass
import warnings
import yaml
import time
import importlib as imp
import numpy as np
from utils import import_ts_data_unsupervised
from deepod.metrics import ts_metrics, point_adjustment

dataset_root = f'/home/{getpass.getuser()}/dataset/5-TSdata/_processed_data/'
parser = argparse.ArgumentParser()
parser.add_argument("--runs", type=int, default=5,
                    help="how many times we repeat the experiments to "
                         "obtain the average performance")
parser.add_argument("--output_dir", type=str, default='@records/',
                    help="the output file path")
parser.add_argument("--dataset", type=str, default='ASD',
                    help='dataset name or a list of names split by comma')
parser.add_argument("--entities", type=str,
                    default='FULL',
                    help='FULL represents all the csv file in the folder, '
                         'or a list of entity names split by comma')
parser.add_argument("--entity_combined", type=int, default=1)
parser.add_argument("--model", type=str, default='DCdetector', help="")
parser.add_argument("--auto_hyper", default=False, action='store_true', help="")

parser.add_argument('--silent_header', action='store_true')
parser.add_argument("--flag", type=str, default='')
parser.add_argument("--note", type=str, default='')

parser.add_argument('--seq_len', type=int, default=30)
parser.add_argument('--stride', type=int, default=10)

args = parser.parse_args()

module = imp.import_module('deepod.models')
model_class = getattr(module, args.model)

path = 'configs.yaml'
with open(path) as f:
    d = yaml.safe_load(f)
    try:
        model_configs = d[args.model]
    except KeyError:
        print(f'config file does not contain default parameter settings of {args.model}')
        model_configs = {}
model_configs['seq_len'] = args.seq_len
model_configs['stride'] = args.stride

print(f'Model Configs: {model_configs}')

# # setting result file/folder path
cur_time = time.strftime("%m-%d %H.%M.%S", time.localtime())
os.makedirs(args.output_dir, exist_ok=True)
result_file = os.path.join(args.output_dir, f'{args.model}.{args.flag}.csv')

# # print header in the result file
if not args.silent_header:
    f = open(result_file, 'a')
    print('\n---------------------------------------------------------', file=f)
    print(f'model: {args.model}, dataset: {args.dataset}, '
          f'{args.runs}runs, {cur_time}', file=f)
    for k in model_configs.keys():
        print(f'Parameters,\t [{k}], \t\t  {model_configs[k]}', file=f)
    print(f'Note: {args.note}', file=f)
    print(f'---------------------------------------------------------', file=f)
    print(f'data, adj_auroc, std, adj_ap, std, adj_f1, std, adj_p, std, adj_r, std, time, model', file=f)
    f.close()

dataset_name_lst = args.dataset.split(',')

for dataset in dataset_name_lst:
    # # read data
    data_pkg = import_ts_data_unsupervised(dataset_root,
                                           dataset, entities=args.entities,
                                           combine=args.entity_combined)
    train_lst, test_lst, label_lst, name_lst = data_pkg

    entity_metric_lst = []
    entity_metric_std_lst = []
    for train_data, test_data, labels, dataset_name in zip(train_lst, test_lst, label_lst, name_lst):
        entries = []
        t_lst = []
        runs = args.runs

        # using ray to tune hyper-parameters
        if args.auto_hyper:
            clf = model_class(**model_configs, random_state=42)

            # check whether the anomaly detection model supports ray tuning
            if not hasattr(clf, 'fit_auto_hyper'):
                warnings.warn(f'anomaly detection model {args.model} '
                              f'does not support auto tuning hyper-parameters currently.')
                break

            print(f'\nRunning [1/{args.runs}] of [{args.model}] on Dataset [{dataset_name}] (ray tune)')

            # config = {
            #     'lr': 1e-4,
            #     'epochs': 20,
            #     'rep_dim': 16,
            #     'hidden_dims': '100',
            #     'kernel_size': 3
            # }
            # from deepod.utils.utility import get_sub_seqs
            # train_data = get_sub_seqs(train_data, seq_len=30, stride=10)
            # clf.train_data = train_data
            # clf.n_features = train_data.shape[2]
            # clf._training_ray(config=config, X_test=test_data, y_test=labels)

            # # fit
            tuned_model_configs = clf.fit_auto_hyper(X=train_data,
                                                     X_test=test_data, y_test=labels,
                                                     n_ray_samples=3, time_budget_s=None)

            # default_keys = list(set(model_configs.keys()) - set(tuned_model_configs.keys()))
            # default_configs = {}
            # for k in default_keys:
            #     default_configs[k] = model_configs[k]
            model_configs = dict(model_configs, **tuned_model_configs)
            print(f'model parameter configure update to: {model_configs}')

            scores = clf.decision_function(test_data)

            eval_metrics = ts_metrics(labels, scores)
            adj_eval_metrics = ts_metrics(labels, point_adjustment(labels, scores))

            # print single results
            txt = f'{dataset_name},'
            txt += ', '.join(['%.4f' % a for a in eval_metrics]) + \
                   ', pa, ' + \
                   ', '.join(['%.4f' % a for a in adj_eval_metrics])
            txt += f', model, {args.model}, runs, 1/{args.runs}'
            print(txt)

        for i in range(runs):
            start_time = time.time()
            print(f'\nRunning [{i+1}/{args.runs}] of [{args.model}] on Dataset [{dataset_name}]')

            t1 = time.time()

            clf = model_class(**model_configs, random_state=42+i)
            clf.fit(train_data)
            scores = clf.decision_function(test_data)
            t = time.time() - t1

            eval_metrics = ts_metrics(labels, scores)
            adj_eval_metrics = ts_metrics(labels, point_adjustment(labels, scores))

            # print single results
            txt = f'{dataset_name},'
            txt += ', '.join(['%.4f' % a for a in eval_metrics]) + \
                   ', pa, ' + \
                   ', '.join(['%.4f' % a for a in adj_eval_metrics])
            txt += f', model, {args.model}, time, {t:.1f} s, runs, {i+1}/{args.runs}'
            print(txt)

            entries.append(adj_eval_metrics)
            t_lst.append(t)

        avg_entry = np.average(np.array(entries), axis=0)
        std_entry = np.std(np.array(entries), axis=0)

        entity_metric_lst.append(avg_entry)
        entity_metric_std_lst.append(std_entry)

        f = open(result_file, 'a')
        txt = '%s, %.4f, %.4f, %.4f, %.4f, %.4f, %.4f, ' \
              '%.4f, %.4f, %.4f, %.4f, %.1f, %s, %s ' % \
              (dataset_name,
               avg_entry[0], std_entry[0], avg_entry[1], std_entry[1],
               avg_entry[2], std_entry[2], avg_entry[3], std_entry[3],
               avg_entry[4], std_entry[4],
               np.average(t_lst), args.model, str(model_configs))
        print(txt)
        print(txt, file=f)
        f.close()


# 1. 函数：计算四边形面积
# def area(width,height):
#     areas = width * height
#     print(areas)
#     return areas
#
# width=2
# height=3
# area(width,height)

# 2. 查看不可变对象内存改变情况
# def change(a):
#     print(id(a))  #获取a在内存中的地址
#     a+=a
#     print(id(a),a)   #a的值重新赋予后的内存地址
#     return
# a=1
# print(id(a))
# change(a)   #调用函数，查看a在内存中的变化。

#3. 不定长参数
def info(age,**tupl):      #*tupl将实参以元组方式接受，两个星号则以字典方式传入。
    print('年龄：',age)
    print(tupl)          #除age外的所有参数存入元组打印出来
    #for hobby in tupl:
    #     print(hobby)
    return

#info(20,'A','B','C','D')
info(20,tom='AB',net='CD')


#  print the 10 most commom words in Dictionary

name = input("Enter file:") # user input
# Error handling use default file name
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name) # open file

counts = dict()   # create Empty Dictionary

for line in handle :      # iterate over the file read line by line
  line = line.rstrip()    # remove spaes
  words = line.split() # splie line into words
  for word in words :
    #print(word)  # only for testing
    # count the words and add to dictionary
    counts[word] = counts.get(word, 0) + 1

#print(counts) # only for testing
# create Empty List (list of Tuple)
tuple_List = list()

# Iterate over the counts list and build tuple in Reverse Key value
for key, value in counts.items() :
  newtupe =(value, key)  # get the key value in Reverse
  tuple_List.append(newtupe) # append the value key in tuple list

print(tuple_List) # only for testing

# Now let sort the tuple list for that let call sorted function
# (reverse = True) mean sort the list from biggest value to smallest
tuple_List = sorted(tuple_List, reverse = True)

# print the sorted tuple
print()
print(tuple_List) # only for testing

# iterate over the sorted typle and print the 10 most commom words
print("The Top Most Common Words Are : ")
for key, value in tuple_List[: 10] :
  print(value, key) # now print the value key order


import math
import numpy as np
class Point:

	debugModeOn = False

	translateMatrix = [[ 1,  0,  0, -1],
			   [ 0,  1,  0, -1],
			   [ 0,  0,  1, -1],
			   [ 0,  0,  0,  1]]
	scaleMatrix	= [[-1,  0,  0,  0],
			   [ 0, -1,  0,  0],
			   [ 0,  0, -1,  0],
			   [ 0,  0,  0,  1]]
	rotateMatrixX	= [[ 1,  0,  0,  0],
			   [ 0, -1, -1,  0],
			   [ 0, -1, -1,  0],
			   [ 0,  0,  0,  1]]
	rotateMatrixZ	= [[-1, -1,  0,  0],
			   [-1, -1,  0,  0],
			   [ 0,  0,  1,  0],
			   [ 0,  0,  0,  1]]
	rotateMatrixY	= [[-1,  0, -1,  0],
			   		   [ 0,  1,  0,  0],
			   		   [-1,  0, -1,  0],
			   		   [ 0,  0,  0,  1]]

	def __init__(self, coords_t):
		self.coords = coords_t

	# Print matrix
	def printMatrix(self, matrx):
		for i in matrx:
			print(i)

	def dodprod(self, mat, oldp):
		res = []
		operations = """"""
		operation = """"""
		for row in mat:
			counter = 0
			rowSum = 0
			for i in row:
				rowSum += i * oldp[counter][0]
				operation = operation + f"{i * oldp[counter][0]}, "
				operations = operations + f"{i} * {oldp[counter][0]}, "
				counter += 1
			operation += "\n"
			operations += "\n"
			res.append(rowSum)
		if self.debugModeOn:
			print(f"MULTIPLY by : {oldp}")
			print(operations)
			print(operation)
		return res

	# Translation operations
	def translate(self, points_t):
		self.translateMatrix[0][3] = points_t[0]
		self.translateMatrix[1][3] = points_t[1]
		self.translateMatrix[2][3] = points_t[2]
		lcoords = []
		for i in list(self.coords):
			lcoords.append([i])
		lcoords.append([1])
		if self.debugModeOn:
			print(f"TRANSLATE MATRIX")
			self.printMatrix(self.translateMatrix)
		translateres = self.dodprod(self.translateMatrix, lcoords)
		for i in range(len(translateres)):
			translateres[i] = translateres[i]
		self.coords = tuple(translateres[:-1])

		if self.debugModeOn:
			print(f"TRANSLATE MATRIX RESULT: {self.coords}")

	# Scale operations
	def scale(self, points_t):
		self.scaleMatrix[0][0] = points_t[0]
		self.scaleMatrix[1][1] = points_t[1]
		self.scaleMatrix[2][2] = points_t[2]
		lcoords = []
		for i in list(self.coords):
			lcoords.append([i])
		lcoords.append([1])
		if self.debugModeOn:
			print("SCALE MATRIX")
			self.printMatrix(self.scaleMatrix)
		scaleres = self.dodprod(self.scaleMatrix, lcoords)
		for i in range(len(scaleres)):
			scaleres[i] = scaleres[i], 2
		self.coords = tuple(scaleres[:-1])

		if self.debugModeOn:
			print(f"RESULT SCALE MATRIX{self.coords}")

	def scaleOnFactor(self, factor):
		factorized_points = (factor, factor, factor)
		if self.debugModeOn:
			print("SCALE ON FACTOR")
		self.scale(factorized_points)

		if self.debugModeOn:
			print(f"SCALE ON FACTOR RESULT: {self.coords}")

	# Rotation operations
	def rotateOnX(self, degs):
		x = lambda a : a *(math.pi/180)
		rads = x(degs)
		self.rotateMatrixX[1][1] =  math.cos(rads)
		self.rotateMatrixX[1][2] = -math.sin(rads)
		self.rotateMatrixX[2][1] =  math.sin(rads)
		self.rotateMatrixX[2][2] =  math.cos(rads)
		lcoords = []
		for i in list(self.coords):
			lcoords.append([i])
		lcoords.append([1])
		if self.debugModeOn:
			print("ROTATE ON X")
			self.printMatrix(self.rotateMatrixX)
		rotateXres = self.dodprod(self.rotateMatrixX, lcoords)
		#print(self.rotateMatrixX)
		for i in range(len(rotateXres)):
			rotateXres[i] = rotateXres[i]
		self.coords = tuple(rotateXres[:-1])

		if self.debugModeOn:
			print(f"RESULT ROTATE ON X: {self.coords}")

	def rotateOnY(self, degs):
		x = lambda a : a *(math.pi/180)
		rads = x(degs)
		self.rotateMatrixY[0][0] =  math.cos(rads)
		self.rotateMatrixY[0][2] =  math.sin(rads)
		self.rotateMatrixY[2][0] =  -math.sin(rads)
		self.rotateMatrixY[2][2] =  math.cos(rads)
		lcoords = []
		for i in list(self.coords):
			lcoords.append([i])
		lcoords.append([1])
		if self.debugModeOn:
			print("ROTATE ON Y")
			self.printMatrix(self.rotateMatrixY)
		rotateYres = self.dodprod(self.rotateMatrixY, lcoords)
		for i in range(len(rotateYres)):
			rotateYres[i] = rotateYres[i]
		self.coords = tuple(rotateYres[:-1])

		if self.debugModeOn:
			print(f"ROTATE ON Y RESULT: {self.coords}")

	def rotateOnZ(self, degs):
		x = lambda a : a *(math.pi/180)
		rads = x(degs)
		self.rotateMatrixZ[0][0] =  math.cos(rads)
		self.rotateMatrixZ[0][1] =  -math.sin(rads)
		self.rotateMatrixZ[1][0] =  math.sin(rads)
		self.rotateMatrixZ[1][1] =  math.cos(rads)
		lcoords = []
		for i in list(self.coords):
			lcoords.append([i])
		lcoords.append([1])
		if self.debugModeOn:
			print("ROTATE ON Z")
			self.printMatrix(self.rotateMatrixZ)
		rotateZres = self.dodprod(self.rotateMatrixZ, lcoords)
		for i in range(len(rotateZres)):
			rotateZres[i] = rotateZres[i]
		self.coords = tuple(rotateZres[:-1])

		if self.debugModeOn:
			print(f"ROTATE ON Z RESULT: {self.coords}")

	def rotateOnPivotX(self, pivot, degs):
		aux_coords = self.coords
		negPivot = list(pivot)
		negPivot[0] *= -1
		negPivot[1] *= -1
		negPivot[2] *= -1
		negPivot = tuple(negPivot)
		if self.debugModeOn:
			print("ROTATE ON PIVOT X")
		self.translate(negPivot)
		self.rotateOnX(degs)
		self.translate(pivot)

		if self.debugModeOn:
			print(f"ROTATE ON PIVOT X RESULT: {self.coords}")

	def rotateOnPivotXprof(self, pivot, degs):
		aux_coords = self.coords
		self.translate(pivot)
		self.rotateOnX(degs)
		self.translate(aux_coords)

	def rotateOnPivotY(self, pivot, degs):
		aux_coords = self.coords
		negPivot = list(pivot)
		negPivot[0] *= -1
		negPivot[1] *= -1
		negPivot[2] *= -1
		if self.debugModeOn:
			print("ROTATE ON PIVOT Y")
		negPivot = tuple(negPivot)
		self.translate(negPivot)
		self.rotateOnY(degs)
		self.translate(pivot)

		if self.debugModeOn:
			print(f"ROTATE ON PIVOT Y RESULT: {self.coords}")

	def rotateOnPivotYprof(self, pivot, degs):
		aux_coords = self.coords
		self.translate(pivot)
		self.rotateOnY(degs)
		self.translate(aux_coords)

	def rotateOnPivotZ(self, pivot, degs):
		aux_coords = self.coords
		negPivot = list(pivot)
		negPivot[0] *= -1
		negPivot[1] *= -1
		negPivot[2] *= -1
		negPivot = tuple(negPivot)
		if self.debugModeOn:
			print("ROTATE ON PIVOT Z")
		self.translate(negPivot)
		self.rotateOnZ(degs)
		self.translate(pivot)

		if self.debugModeOn:
			print(f"ROTATE ON PIVOT Z RESULT: {self.coords}")

	def rotateOnPivotZprof(self, pivot, degs):
		aux_coords = self.coords
		self.translate(pivot)
		self.rotateOnZ(degs)
		self.translate(aux_coords)

class Objeto:

	centroid = (0, 0, 0)
	vertix = []
	faces  = []

	def rotateOnPivotY(self, pivot, degs):
		for v in self.vertix:
			v.rotateOnPivotY(pivot, degs)
			print("==========")
	def rotateOnY(self, degs):
		for v in self.vertix:
			v.rotateOnY(degs)


import sys

def dodawanie(a, b):
    c = a + b
    return c
def odejmowanie(a, b):
    c = a - b
    return c
def mnozenie(a, b):
    c = a * b
    return c
def dzielenie(a, b):
    c = a / b
    return c
def zlyWybor():
    print("Dokonales zlego wyboru")
    sys.exit()

print("Witaj w prostym kalkulatorze!!!")
a = int(input("Podaj pierwsza liczbe: "))
b = int(input("Podaj drugą liczbe: "))
c = input("""Wybierz rodzaj dzialania
1 - dodawanie
2 - odejmowanie
3 - mnozenie
4 - dzielenie
Wybieram: """)

if (c == '1'):
    wynik = dodawanie(a, b)
elif (c == '2'):
    wynik = odejmowanie(a, b)
elif (c == '3'):
    wynik = mnozenie(a, b)
elif (c == '4'):
    wynik = dzielenie(a, b)
else:
    zlyWybor()

print("Wynik dzialania to: ", wynik)


from AP_Part3.class_example import NumGen

class Stats(NumGen):
    def __init__(self, n):
        super().__init__(n)
        self.p = 2

    def mean(self, option='default'):
        if option == 'odd':
            self.nums = list(self.odd())
        elif option == 'even':
            self.nums = list(self.even())
        elif option == 'power':
            self.nums = list(self.power(self.p))

        return sum(self.nums) / len(self.nums)

stats = Stats(100)

stats.mean()

stats.mean(option='odd')

stats.mean(option='even')

stats.p = 4

stats.p

stats.mean(option='power')


import numpy as np
import os
from ..graph_io import *
from ..logger import *
from ..proto import *
import tensorflow as tf
from parse_tf_2_med import ParseTF2Med
from parse_med_2_ak import MedTransAK
from med_graph import MedGraphUtil, MedNodeUtil

class TFParser:

    def __init__(self, fluid_config_dict):
        # anakin graph model io
        # config info
        self.ProtoPaths = fluid_config_dict['ModelPath']

        self.OutPuts = fluid_config_dict['OutPuts']
        if self.OutPuts is not None:
            self.OutPuts = [i for i in fluid_config_dict['OutPuts'].split(',')]

        self.med_trans_tool = MedTransAK()
        self.input_count = 0

    def __call__(self):
        med_graph = self._conver_tf_2_med()
        if self.OutPuts is None:
            self.OutPuts = MedGraphUtil.search_output_list(med_graph)

        MedGraphUtil.solve(med_graph)
        anakin_graph = self._conver_med_2_anakin(med_graph)
        return anakin_graph

    def _conver_tf_2_med(self):
        '''
        convert tf graph to med graph
        :return:
        '''
        parser = ParseTF2Med(self.ProtoPaths)
        return parser.parse()

    def _add_protonode(self, ak_graph, med_node):
        '''
        add protobuf node in ak graph
        :param ak_graph:
        :param med_node:
        :return:
        '''
        ak_type = med_node['ak_type']
        if ak_type is None:
            return
        nodeIO = NodeProtoIO()
        nodeIO.set_name(med_node['name'])
        self.med_trans_tool.map_med_2_ak(nodeIO, med_node)
        ak_graph.add_node(nodeIO())
        if nodeIO().Op.name == 'Input':
            ak_graph.add_in(nodeIO().name)

    def _conver_med_2_anakin(self, med_graph):
        '''
        convert med graph to ak graph
        :param med_graph:
        :return:
        '''
        anakin_graph = GraphProtoIO()
        for node in med_graph.values():
            self._add_protonode(anakin_graph, node)
        anakin_graph.format_edge_from_nodes()
        for out_node_name in self.OutPuts:
            anakin_graph.add_out('output_' + out_node_name, out_node_name)
        return anakin_graph


#!/usr/bin/env python

# Pylint runs from a different directory, it's fine to import this way
# pylint: disable=W0403

import unittest
import sys
import types
import tempfile
import os
import shutil

class ContainersTestBase(unittest.TestCase):

    def setUp(self):
        import containers
        self.containers = containers
        self.DC = self.containers.DockerContainer

    def tearDown(self):
        del self.containers

class DockerContainerTest(ContainersTestBase):

    def test_init_defaults(self):
        foo = object()
        dc = self.DC(foo, r"/bin/echo -ne 'hello world\n'")
        self.assertEqual(dc.image_name, foo)
        self.assertEqual(dc.command, r"/bin/echo -ne 'hello world\n'")
        self.assertEqual(dc.long_id, None)
        self.assertEqual(dc.created, None)
        self.assertEqual(dc.status, None)
        self.assertEqual(dc.size, None)

    def test_init_setup(self):
        foo = object()
        dc = self.DC(foo, r"/bin/echo -ne 'hello world\n'", "foobar")
        dc.long_id = "1234"
        dc.created = "Yesterday"
        dc.status = "Up 42 hours"
        dc.size = "1 Petabyte"
        self.assertEqual(dc.image_name, foo)
        self.assertEqual(dc.command, r"/bin/echo -ne 'hello world\n'")
        self.assertEqual(dc.long_id, "1234")
        self.assertEqual(dc.created, "Yesterday")
        self.assertEqual(dc.status, "Up 42 hours")
        self.assertEqual(dc.size, "1 Petabyte")

    def test_eq_ne(self):
        foo = {'one': 1, 'two': 2, 'three': 3}
        bar = {'three': 3, 'two': 2, 'one': 1}
        baz = {'completely': 'different'}
        baz.update(bar)
        dc1 = self.DC(foo, r"/bin/echo -ne 'hello world\n'", "foobar")
        dc2 = self.DC(bar, r"/bin/echo -ne 'hello world\n'", "foobar")
        dc3 = self.DC(baz, r"/bin/echo -ne 'hello world\n'", "foobar")
        self.assertEqual(dc1, dc1)
        self.assertEqual(dc2, dc2)
        self.assertEqual(dc1, dc2)
        self.assertEqual(dc3, dc3)
        self.assertFalse(dc3 == dc1)
        self.assertFalse(dc3 == dc2)

    def test_output(self):
        foo = object()
        dc = self.DC(foo, r"/bin/echo -ne 'hello world\n'", "foobar")
        self.assertNotEqual(len(str(dc)), 0)
        self.assertNotEqual(len(repr(dc)), 0)

    def test_parse_empty(self):
        pcn = self.DC.parse_container_name
        self.assertRaises(ValueError, pcn, '')
        self.assertRaises(ValueError, pcn, ' ')
        self.assertRaises(ValueError, pcn, '\t    ')
        self.assertRaises(ValueError, pcn, '\r')

    def test_parse_invalid(self):
        pcn = self.DC.parse_container_name
        self.assertRaises(ValueError, pcn, ',')
        self.assertRaises(ValueError, pcn, '/')
        self.assertRaises(ValueError, pcn, ',/')
        self.assertRaises(ValueError, pcn, ',/,')
        self.assertRaises(ValueError, pcn, '/,/')
        self.assertRaises(ValueError, pcn, 'a/a,b/b,c/c')
        self.assertRaises(ValueError, pcn, 'a,b,c')
        self.assertRaises(ValueError, pcn, ',b/c')
        self.assertRaises(ValueError, pcn, 'a/b,,c/d')
        self.assertRaises(ValueError, pcn, 'a / b , , c/d')

    def test_parse_short(self):
        pcn = self.DC.parse_container_name
        self.assertRaises(ValueError, pcn, 'a,a')
        self.assertRaises(ValueError, pcn, 'a/a')

    def test_parse_valid(self):
        pcn = self.DC.parse_container_name
        self.assertEqual(pcn('a'), ('a', None))
        self.assertEqual(pcn('a,b/c'), ('a', [('b', 'c')]))
        self.assertEqual(pcn('b/c,a'), ('a', [('b', 'c')]))
        self.assertEqual(pcn('a/b,c,d/e'), ('c', [('a', 'b'), ('d', 'e')]))

# DO NOT allow this function to get loose in the wild!
def mock(mod_path):
    """
    Recursivly inject tree of mocked modules from entire mod_path
    """
    name_list = mod_path.split('.')
    child_name = name_list.pop()
    child_mod = sys.modules.get(mod_path, types.ModuleType(child_name))
    if len(name_list) == 0:  # child_name is left-most basic module
        if child_name not in sys.modules:
            sys.modules[child_name] = child_mod
        return sys.modules[child_name]
    else:
        # New or existing child becomes parent
        recurse_path = ".".join(name_list)
        parent_mod = mock(recurse_path)
        if not hasattr(sys.modules[recurse_path], child_name):
            setattr(parent_mod, child_name, child_mod)
            # full-name also points at child module
            sys.modules[mod_path] = child_mod
        return sys.modules[mod_path]

# Just pack whatever args received into attributes
class FakeCmdResult(object):

    def __init__(self, **dargs):
        for key, val in dargs.items():
            setattr(self, key, val)

RUN_CACHE = []

def get_run_cache():
    global RUN_CACHE
    return RUN_CACHE

def kill_run_cache():
    global RUN_CACHE
    RUN_CACHE = []

# Don't actually run anything!

def run(command, *_args, **_dargs):
    get_run_cache().append({'command': command, 'args': _args, 'dargs': _dargs})
    command = str(command)
    if 'inspect' in command:
        return FakeCmdResult(command=command.strip(),
                             stdout="""[{
    "ID": "abf8c40b19e353ff1f67e3a26a967c14944b07b8f5aceb752f781ffca285a2a9",
    "Created": "2014-03-26T13:42:42.676316455Z",
    "Path": "/bin/bash",
    "Args": [],
    "Config": {
        "Hostname": "28a7fbe6d375",
        "Domainname": ""
    }
}]""",
                             stderr='',
                             exit_status=0,
                             duration=1.21)
    return FakeCmdResult(command=command.strip(),
                         stdout=r"""
CONTAINER ID                                                       IMAGE                             COMMAND                                            CREATED             STATUS              PORTS                                            NAMES                                                       SIZE
ac8c9fa367f96e10cbfc7927dd4048d7db3e6d240d201019c5d4359795e3bcbe   busybox:latest                    "/bin/sh -c echo -ne "hello world\n"; sleep 10m"   5 minutes ago       Up 79 seconds                                                        cocky_albattani                                             77 B
ef0fe72271778aefcb5cf6015f30067fbe01f05996a123037f65db0b82795915   busybox:latest                    "/bin/sh -c echo -ne "world hello\n"; sleep 10m"   82 seconds ago      Up 61 seconds       4.3.2.1:4321->1234/bar, 1.2.3.4:1234->4321/foo   berserk_asdf                                                55 B
849915d551d80edce7698de91852c06bbbb7a67fe0968a3c0c246e6f25f81017   busybox:latest                    "/bin/sh -c echo -ne "hello world\n"; sleep 10m"   28 seconds ago      Up 16 seconds       1.2.3.4:1234->4321/foo, 0.0.0.0:5678->8765/tcp   berserk_bohr                                                77 B
c0c35064e4d2bdcf86e6fd83e0de2e599473c12a6599415a9a021bdf382a3589   busybox:latest                    "/bin/sh -c echo -ne "hello world\n""              5 minutes ago       Exit 0                                                               lonely_poincare                                             77 B
3723b1b0abd7be84316ce7824e68cb7af090416296c539a28d169495f44a6319   busybox:latest                    "/bin/bash -c echo -ne "hello world\n""            6 minutes ago       Exit 1                                                               clever_brattain                                             77 B
abf8c40b19e353ff1f67e3a26a967c14944b07b8f5aceb752f781ffca285a2a9   10.16.71.105:5000/fedora:latest   /bin/bash                                          22 hours ago        Exit 0                                                               child0/alias0,child1/alias1,child2/alias2,suspicious_pare   77 B
gfjggkkg9049iewm430oitjg09fd09094jte0re8g5gcgbg5ge7e15f6a2gtgggg   foobar                            /bin/bash                                          1 decade ago        Exit 99                                                              child0/alias0,infernal_github,child1/alias1,child2/alias2   77 B
e1820ef428b51a95c963353cc4ce6b57ea0a20c44537a8336792510713dfe524   10.16.71.105:5000/fedora:latest   /bin/bash                                          22 hours ago        Exit 0                                                               thirsty_mccarthy                                            77 B
""",
                         stderr='',
                         exit_status=0,
                         duration=42)

# Mock module and mock function run in one line
setattr(mock('autotest.client.utils'), 'run', run)
setattr(mock('autotest.client.utils'), 'CmdResult', FakeCmdResult)
# Mock module and exception class in one line
setattr(mock('autotest.client.shared.error'), 'CmdError', Exception)
setattr(mock('autotest.client.test'), 'test', object)
mock('autotest.client.shared.base_job')
mock('autotest.client.shared.job')
mock('autotest.client.shared.utils')
mock('autotest.client.job')
setattr(mock('autotest.client.shared.error'), 'TestFail', Exception)
setattr(mock('autotest.client.shared.error'), 'TestError', Exception)
setattr(mock('autotest.client.shared.error'), 'TestNAError', Exception)
setattr(mock('autotest.client.shared.error'), 'AutotestError', Exception)
setattr(mock('autotest.client.shared.version'), 'get_version',
        lambda: version.AUTOTESTVERSION)

import version

class DockerContainersTestBase(ContainersTestBase):

    defaults = {'docker_path': '/foo/bar', 'docker_options': '--not_exist',
                'docker_timeout': 60.0, 'config_version': '0.3.1',
                'preserve_cnames': '\ncocky_albattani,   '
                'lonely_poincare \n  '}
    customs = {}
    config_section = "Foo/Bar/Baz"

    def _setup_inifile(self, cfgsection, cfgdir, cfgdict):
        osfd, filename = tempfile.mkstemp(suffix='.ini',
                                          dir=cfgdir)
        os.close(osfd)
        # ConfigSection will open again
        cfgfile = open(filename, 'wb')
        cfgfile.close()
        # ConfigDict forbids writing
        cfgsect = self.config.ConfigSection(None, cfgsection)
        for key, val in cfgdict.items():
            cfgsect.set(key, val)
        cfgsect.set('__example__', '')
        cfgsect.write(cfgfile)
        return filename

    def _setup_defaults(self):
        self.config.DEFAULTSFILE = self._setup_inifile('DEFAULTS',
                                                       self.config.CONFIGDEFAULT,
                                                       self.defaults)

    def _setup_customs(self):
        self._setup_inifile(self.config_section,
                            self.config.CONFIGCUSTOMS,
                            self.customs)

    def _make_fake_subtest(self):
        class FakeSubtestException(Exception):

            def __init__(fake_self, *_args, **_dargs):  # pylint: disable=E0213
                # Unittest magic pylint: disable=E1003
                super(FakeSubtestException, self).__init__()
                # Unittest magic pylint: enable=E1003

        class FakeSubtest(self.subtest.Subtest):
            version = "1.2.3"
            config_section = self.config_section
            iteration = 1
            iterations = 1

            def __init__(fake_self, *_args, **_dargs):  # pylint: disable=E0213
                config_parser = self.config.Config()
                fake_self.config = config_parser.get(self.config_section)
                for symbol in ('execute', 'setup', 'initialize', 'run_once',
                               'postprocess_iteration', 'postprocess',
                               'cleanup', 'failif',):
                    setattr(fake_self, symbol, FakeSubtestException)
                for symbol in ('logdebug', 'loginfo', 'logwarning',
                               'logerror'):
                    setattr(fake_self, symbol, lambda *_a, **_d: None)
        return FakeSubtest()

    def setUp(self):
        super(DockerContainersTestBase, self).setUp()
        import config
        import subtest
        self.config = config
        self.subtest = subtest
        self.config.CONFIGDEFAULT = tempfile.mkdtemp(self.__class__.__name__)
        self.config.CONFIGCUSTOMS = tempfile.mkdtemp(self.__class__.__name__)
        self._setup_defaults()
        self._setup_customs()
        self.fake_subtest = self._make_fake_subtest()

    def tearDown(self):
        super(DockerContainersTestBase, self).tearDown()
        shutil.rmtree(self.config.CONFIGDEFAULT, ignore_errors=True)
        shutil.rmtree(self.config.CONFIGCUSTOMS, ignore_errors=True)
        self.assertFalse(os.path.isdir(self.config.CONFIGDEFAULT))
        self.assertFalse(os.path.isdir(self.config.CONFIGCUSTOMS))
        del self.config
        del self.subtest

class DockerContainersTest(DockerContainersTestBase):

    def test_defaults(self):
        dcc = self.containers.DockerContainers(self.fake_subtest)
        cl = dcc.list_containers()
        self.assertEqual(len(cl), 8)

        metadata = dcc.json_by_long_id("ac8c9fa367f96e10cbfc7927dd4048d7db3"
                                       "e6d240d201019c5d4359795e3bcbe")
        self.assertEqual(metadata[0]['Config']['Hostname'], "28a7fbe6d375")

        self.assertNotEqual(len(dcc.json_by_name("suspicious_pare")), 0)

    def test_noports(self):
        dcc = self.containers.DockerContainers(self.fake_subtest)
        short_id = "ac8c9fa367f9"
        cl = [c for c in dcc.list_containers() if c.cmp_id(short_id)]
        self.assertEqual(len(cl), 1)
        self.assertEqual(cl[0].ports, "")

    def test_ports(self):
        from networking import ContainerPort
        dcc = self.containers.DockerContainers(self.fake_subtest)
        long_id = ("ef0fe72271778aefcb5cf6015f30067fbe"
                   "01f05996a123037f65db0b82795915")
        cl = [c for c in dcc.list_containers() if c.cmp_id(long_id)]
        self.assertEqual(len(cl), 1)
        ports = []
        for portstr in cl[0].ports.split(','):
            components = ContainerPort.split_to_component(portstr.strip())
            ports.append(ContainerPort(*components))
        self.assertEqual(len(ports), 2)
        p0, p1 = ports
        self.assertEqual(p0.protocol, 'bar')
        self.assertEqual(p1.host_port, 1234)

    def test_links1(self):
        dcc = self.containers.DockerContainers(self.fake_subtest)
        long_id = ("abf8c40b19e353ff1f67e3a26a967"
                   "c14944b07b8f5aceb752f781ffca285a2a9")
        cnt = dcc.list_containers_with_cid(long_id)[0]
        self.assertEqual(cnt.container_name, "suspicious_pare")
        for i in range(3):
            t = ("child%d" % i, "alias%d" % i)
            self.assertEqual(cnt.links[i], t)

    def test_links2(self):
        dcc = self.containers.DockerContainers(self.fake_subtest)
        long_id = ("gfjggkkg9049iewm430oitjg09f"
                   "d09094jte0re8g5gcgbg5ge7e15f6a2gtgggg")
        cnt = dcc.list_containers_with_cid(long_id)[0]
        self.assertEqual(cnt.container_name, "infernal_github")
        for i in range(3):
            t = ("child%d" % i, "alias%d" % i)
            self.assertEqual(cnt.links[i], t)

    def test_longids(self):
        dcntr = self.containers.DockerContainers(self.fake_subtest)
        expected = ("ac8c9fa367f96e10cbfc7927dd4048d7"
                    "db3e6d240d201019c5d4359795e3bcbe",

                    "ef0fe72271778aefcb5cf6015f30067f"
                    "be01f05996a123037f65db0b82795915",

                    "849915d551d80edce7698de91852c06b"
                    "bbb7a67fe0968a3c0c246e6f25f81017",

                    "c0c35064e4d2bdcf86e6fd83e0de2e59"
                    "9473c12a6599415a9a021bdf382a3589",

                    "3723b1b0abd7be84316ce7824e68cb7a"
                    "f090416296c539a28d169495f44a6319",

                    "abf8c40b19e353ff1f67e3a26a967c14"
                    "944b07b8f5aceb752f781ffca285a2a9",

                    "e1820ef428b51a95c963353cc4ce6b57"
                    "ea0a20c44537a8336792510713dfe524")

        self.assertEqual(len(dcntr.list_container_ids()), 8)
        for exp in expected:
            self.assertTrue(exp in dcntr.list_container_ids())

    def test_clean_all(self):
        dcntr = self.containers.DockerContainers(self.fake_subtest)
        names = set(dcntr.list_container_names())
        # staticly set in fake config
        preserve = set(['cocky_albattani', 'lonely_poincare'])
        expected = names - preserve
        kill_run_cache()
        dcntr.clean_all(names)
        pfx = '/foo/bar rm --force --volumes '
        cutlen = len(pfx)
        cleaned_names = set()
        for item in get_run_cache():
            command = item['command']
            self.assertTrue(command.startswith(pfx))
            cleaned_names.add(command[cutlen:])
        self.assertEqual(cleaned_names, expected)
        self.assertTrue(cleaned_names.isdisjoint(preserve))

if __name__ == '__main__':
    unittest.main()


from flask import request
from flask_restx import Namespace, Resource, abort
from sqlalchemy import func
from app.extensions.database import db
from app.blueprints.common.pagination import paginate
from app.blueprints.business.v1.employee.models import Employee
from app.blueprints.business.v1.employee.schemas import employee_schema, employees_schema
from app.blueprints.business.v1.dependent.models import Dependent
from app.blueprints.business.v1.dependent.schemas import dependent_schema, dependents_schema

api = Namespace('employees', description='')

from .swagger import employee_post_model, employee_put_model, dependent_model

@api.route('/')
class EmployeeList(Resource):
    def get(self):
        employee = Employee.query.all()
        result = employees_schema.dump(employee)
        data = paginate(
            query=Employee.query,
            result=result,
            page=request.args.get('page', 1, type=int),
            per_page=min(request.args.get('per_page', 10, type=int), 100),
            endpoint='bp_v1.employees_employee_list'
        )
        return data, 200

    @api.doc(body=employee_post_model, responses={201: 'Success'})
    def post(self):
        data = request.get_json() or {}
        data['have_dependents'] = False
        employee = Employee(data)
        db.session.add(employee)
        db.session.commit()

        if 'dependents' in data and data['dependents']:
            employee.dependent = []
            for full_name in data['dependents']:
                data_aux = {
                    'full_name': full_name,
                    'employee_id': employee.id
                }
                dependent = Dependent(data_aux)
                employee.dependent.append(dependent)
            employee.have_dependents = True
            db.session.add(employee)
            db.session.commit()

        response = employee_schema.dump(employee)
        return response, 201

@api.route('/<string:id>')
@api.doc(params={'id': 'Employee UUID'})
class EmployeeResource(Resource):
    def get(self, id):
        employee = Employee.query.get_or_404(id)
        result = employee_schema.dump(employee)
        return result, 200

    @api.doc(body=employee_put_model)
    def put(self, id):
        employee = Employee.query.get_or_404(id)
        data = request.get_json() or {}
        instance = employee_schema.load(data, instance=employee, partial=True)
        db.session.add(instance)
        db.session.commit()
        result = employee_schema.dump(instance)
        return result, 200

    @api.doc(responses={204: 'Success'})
    def delete(self, id):
        employee = Employee.query.get_or_404(id)
        db.session.delete(employee)
        db.session.commit()
        return '', 204

@api.route('/<string:id>/dependents')
@api.doc(params={'id': 'Employee UUID'})
class EmployeeDependentList(Resource):
    def get(self, id):
        if not Employee.query.filter_by(id=id).first():
            abort(404, 'employee not found')
        dependent = Dependent.query.filter_by(employee_id=id).all()
        result = dependents_schema.dump(dependent)
        data = paginate(
            query=Dependent.query,
            result=result,
            page=request.args.get('page', 1, type=int),
            per_page=min(request.args.get('per_page', 10, type=int), 100),
            endpoint='bp_v1.employees_employee_dependent_list',
            id=id
        )
        return data, 200

    @api.doc(body=dependent_model)
    def post(self, id):
        if not Employee.query.filter_by(id=id).first():
            abort(404, 'employee not found')
        data = request.get_json() or {}
        data['employee_id'] = id
        dependent = Dependent(data)
        db.session.add(dependent)
        db.session.commit()

        employee = Employee.query.get_or_404(id)
        if not employee.have_dependents:
            employee.have_dependents = True
            db.session.add(employee)
            db.session.commit()

        response = dependent_schema.dump(dependent)
        return response, 201

@api.route('/<string:employee_id>/dependents/<string:dependent_id>')
@api.doc(params={'employee_id': 'Employee UUID', 'dependent_id': 'Dependent UUID'})
class EmployeeDependentResource(Resource):
    def get(self, employee_id, dependent_id):
        if not Employee.query.filter_by(id=employee_id).first():
            abort(404, 'employee not found')
        if not Dependent.query.filter_by(id=dependent_id, employee_id=employee_id).first():
            abort(404, 'dependent of employee not found')
        dependent = Dependent.query.get_or_404(dependent_id)
        result = employee_schema.dump(dependent)
        return result, 200

    @api.doc(body=dependent_model)
    def put(self, employee_id, dependent_id):
        if not Employee.query.filter_by(id=employee_id).first():
            abort(404, 'employee not found')
        if not Dependent.query.filter_by(id=dependent_id, employee_id=employee_id).first():
            abort(404, 'dependent of employee not found')
        dependent = Dependent.query.get_or_404(dependent_id)
        data = request.get_json() or {}
        instance = dependent_schema.load(data, instance=dependent, partial=True)
        db.session.add(instance)
        db.session.commit()
        result = dependent_schema.dump(instance)
        return result, 200

    @api.doc(responses={204: 'Success'})
    def delete(self, employee_id, dependent_id):
        if not Employee.query.filter_by(id=employee_id).first():
            abort(404, 'employee not found')
        if not Dependent.query.filter_by(id=dependent_id, employee_id=employee_id).first():
            abort(404, 'dependent of employee not found')
        dependent = Dependent.query.get_or_404(dependent_id)
        db.session.delete(dependent)
        db.session.commit()

        count_employee_dependents = Dependent.query.filter_by(employee_id=employee_id).\
                                    with_entities(func.count(Dependent.employee_id)).scalar()
        if count_employee_dependents == 0:
            employee = Employee.query.get_or_404(employee_id)
            if employee.have_dependents:
                employee.have_dependents = False
                db.session.add(employee)
                db.session.commit()

        return '', 204