#!/usr/bin/env python
import numpy as np
import random
import itertools as it
import os
import copy

import gym
from gym import spaces

class ConnectNEnv(gym.Env):
    """
    Methods this class has to contain:

    def reset() --> state
    def step(action) --> state, reward, done, info
    def render() --> # Render board

    """
    metadata = {'render.modes': ['human']}

    VISUALISATION = {
        1.: '\x1b[0;31;40m' + 'X' + '\x1b[0m',  # Color red
        -1.: '\x1b[0;32;40m' + 'O' + '\x1b[0m',  # Color green
        0.: ' '
    }

    def __init__(self, game_mode=['learner', 'random'], agent=None):
        # Game mode must be lenght of tow
        assert len(game_mode) == 2
        # Only specific game modes are allowed
        for gm in game_mode:
            assert gm in ['learner', 'random', 'human', 'agent']

        self.game_mode = game_mode

        self.__version__ = "0.1.0"

        self.n = 3  # Required disks to win
        self.m = 4  # Size of field

        self.curr_step = -1

        self.agent = agent

        self.name = f'Connect{self.n}'

        self.action_space = spaces.Discrete(self.m)
        self.observation_space = spaces.Box(low=-1, high=1, dtype=np.int, shape=(self.m, self.m))
        #self.observation_space = spaces.Discrete(self.m*self.m)

        self.curr_episode = -1
        self.action_episode_memory = []

        # Manipulate rewards
        self.reward_win = 1
        self.reward_lost = -10
        self.reward_set_on_full_column = -0.5
        self.reward_draw = 0

        self.create_winning_templates()
        self.reset()

    def _step_learner(self, action):
        # Check for valid turn. If not, add a small negative reward
        if action not in self.possible_turns:
            return self.board, self.reward_set_on_full_column, True, {}

        # Place disk
        self._place_disk(action)

        # Check for winning
        if self.check_for_winning():
            return self.board, self.reward_win, True, {}

        # Board is full --> no winner
        elif self.disks_set >= self.m * self.m:
            return self.board, self.reward_draw, True, {}

        # Game goes on, toggle the disk
        self.toggle_disk()

        # Default return
        return self.board, 0, False, {}

    def _step_agent(self):
        # Evaluate action from agent
        self.agent.training = False
        action = self.agent.forward(self.board)
        self.agent.training = True

        # If turn is invalid, choose random turn
        if action not in self.possible_turns:
            action = self._get_random_action()

        # Place disk and evaluate
        self._evaluate_opponent_turn(action)

    def _step_random(self):
        # Choose random (possible) action
        action = self._get_random_action()

        # Place disk and evaluate
        self._evaluate_opponent_turn(action)

    def _step_human(self, action):
        # TODO: Write human interface here
        return

    def _evaluate_opponent_turn(self, action):
        # Place disk
        self._place_disk(action)

        # Check for winning
        if self.check_for_winning():
            return self.board, self.reward_lost, True, {}

        # Board is full --> no winner
        elif self.disks_set >= self.m * self.m:
            return self.board, self.reward_draw, True, {}

        # Game goes on, toggle the disk
        self.toggle_disk()

        # Default return
        return self.board, 0, False, {}

    def _place_disk(self, action):
        # Place disk
        disks_in_column = np.sum(np.abs(self.board[:, action]))
        self.board[int(self.m - disks_in_column - 1), action] = \
            self.current_disk

        # Adjust turn options, of column is full
        if disks_in_column + 1 == self.m:
            self.possible_turns.remove(action)

        # Count up
        self.disks_set += 1

    def step(self, action):
        result = self._step_learner(action)
        if result is not None:
            return result

        if 'random' in game_mode:
            result = self._step_random()
            if result is not None:
                return result

    def single_step(self, action):
        # Check for valid turn
        if action not in self.possible_turns:
            return self.board, -0.5, True, {}

        # Turn is valid
        self.disks_set += 1

        # Place disk
        disks_in_column = np.sum(np.abs(self.board[:, action]))
        self.board[int(self.m - disks_in_column - 1), action] = \
            self.current_disk

        # Adjust turn options, of column is full
        if disks_in_column + 1 == self.m:
            self.possible_turns.remove(action)

        # Check if learner won the game
        if self.check_for_winning():
            return self.board, 1, True, {}

        # Board is full --> no winner
        elif self.disks_set >= self.m * self.m:
            return self.board, 0, True, {}

        self.toggle_disk()

    def reset(self):
        """
        Reset the state of the environment and returns an initial observation.
        Returns
        -------
        observation (object): the initial observation of the space.
        """
        # Update statistics
        self.curr_episode += 1
        self.action_episode_memory.append([])

        self.possible_turns = set(range(self.m))
        self.board = self.create_empty_board()

        self.disks = it.cycle([1, -1])
        self.toggle_disk()

        self.disks_set = 0
        self.game_over = False

        self.winner = None

        self.reward = 0
        self.terminal = False

        return self.board

    def seed(self, seed):
        random.seed(seed)
        np.random.seed

    def observe(self):
        return self.board, self.reward, self.terminal

    def execute_action(self, action):
        self.update(action)

    def toggle_disk(self):
        self.current_disk = next(self.disks)

    def create_empty_board(self):
        return np.zeros((self.m, self.m))

    def create_winning_templates(self):
        # Horizontal and vertical
        winning_templates = []
        for row in range(self.m):
            for col in range(self.m):

                # Horizontal lines
                if col + self.n <= self.m:
                    board_hor = self.create_empty_board()
                    board_hor[row, col:int(col+self.n)] = 1
                    winning_templates.append(board_hor)

                # Vertical lines
                if row + self.n <= self.m:
                    board_ver = self.create_empty_board()
                    board_ver[row:int(row+self.n), col] = 1
                    winning_templates.append(board_ver)

                # Diagonal lines (up and down)
                if (col + self.n <= self.m) & (row + self.n <= self.m):
                    board_diag_down = self.create_empty_board()
                    board_diag_down[row:, col:][np.diag_indices(self.n)] = 1
                    board_diag_up = np.fliplr(board_diag_down)
                    winning_templates.append(board_diag_down)
                    winning_templates.append(board_diag_up)

        self.winning_templates = np.array(winning_templates)

    def check_for_winning(self):
        if np.max(
            np.abs(
                np.sum(
                    np.sum(self.board * self.winning_templates, axis=1),
                    axis=1
                )
            )
        ) == self.n:
            return True
        return False

    def set_disk(self, column):
        # Check for valid turn
        if column not in self.possible_turns:
            print(
                f'Not possible, player {self.current_disk}. Please choose one of the following '
                f'columns: {self.possible_turns}. Your choice: {column}'
            )
            return False

        # Place disk
        disks_in_column = np.sum(np.abs(self.board[:, column]))
        self.board[int(self.m - disks_in_column - 1), column] = \
            self.current_disk

        # Adjust turn options, of column is full
        if disks_in_column + 1 == self.m:
            self.possible_turns.remove(column)

        return True

    def display_board(self):
        for row in self.board:
            text = '|' + ''.join([self.VISUALISATION[val] for val in row]) + '|'
            print(text)
        # Make it more human readable
        print(f' {"".join([str(i) for i in range(self.m)])} ')

    def _get_random_action(self):
        self.set_disk(np.random.choice(list(self.possible_turns)))

    def render(self, mode='human', close=False):
        self.display_board()
        return

    def stack_on_top(self):
        # Try to find a good turn
        for row in range(self.m - 1, -1, -1):
            row_ = self.board[row]
            for i, col in enumerate(row_):
                if col != 0 and i in self.possible_turns:
                    self.set_disk(int(i))
                    return

        # Otherwise, apply random turn
        self._get_random_action()


import sqlite3
conn=sqlite3.connect('newdb')
c=conn.cursor()
#c.execute("CREATE TABLE if not exists record(name text,age int)")

for i in range(1):
    a=input('enter_name:')
    b=input('enter_age:')
c.execute("insert into record values(?,?)",(a,b))
conn.commit()
conn.close()


#!/usr/bin/python
# -*- coding: utf-8 -*-
# j3nnn1 - 0.0.0 -
#Solo python2
#toma en cuenta el primer campo como id de transaccion.

inputfile = open("../data/transacciones_Nofrecuente.csv", "r")
outputfile = open("transacciones.basket", "w")

newfile ={}

for line in inputfile:
    fields = line.split(',')
    newfile[fields[0]]=[]

inputfile.seek(0)

for line in inputfile:
    fields = line.split(',')
    for i, v in enumerate(fields):
        if i>0:
            v = v.replace("\n", '')
            if v not in newfile[fields[0]]:
                newfile[fields[0]].append(v)

#print type(newfile)
for k, v in newfile.iteritems():
    newfile[k].insert(0,k)
    linenew = ','.join(newfile[k])
    outputfile.write(linenew+"\n")
    #print ";".join(newfile[k])


"""Units are created using this class, and they will be placed in an appropriate Building class to construct."""
# ============================================================== #
#  SECTION: Imports                                              #
# ============================================================== #

from classes.settings import CONFIG
from classes.settings import LOG

# Unit does not keep track of whether it is chronoboosted, only if it should tick as if it is chronoboosted.

class Unit:
    def __init__(self, unitname):
        self.name = unitname
        self.mincost = CONFIG[unitname]["mincost"]
        self.gascost = CONFIG[unitname]["gascost"]
        self.time_to_construct = CONFIG[unitname]["time"]
        self.build_time_remaining = self.time_to_construct
        self.supply = CONFIG[unitname]["supply"]
        # for units that produce other units/buildings, like workers! and carriers?
        self.current_production = []
        self.is_constructed = False
        self.chronoboost_speed = CONFIG["chronoboost"]["speedboost"]
        self.completed_units = []
        self.worker_travel_time = 3 # only used for workers

    def tick(self):
        if(self.build_time_remaining > 0):
            self.build_time_remaining -= 1
        else:
            self.is_constructed = True

        if(self.is_constructed and self.current_production != []):
            if current_production[0].build_time_remaining > 0:
                current_production.build_time_remaining -= 1
            else:
                self.completed_units.append(current_production[0])

    def chronoboost_tick(self):
        if(self.build_time_remaining > 0):
            self.build_time_remaining -= self.chronoboost_speed
        else:
            self.is_constructed = True

    # we don't handle whether or not it is OK to morph this building here.
    # instead, we only handle if it is OK to morph (i.e., if there is free production to do so, if unit is built yet, etc)
    def morph(self, new_building):
        return False


from base64 import b64decode
from io import BytesIO

import cv2
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
from onnxruntime import InferenceSession
from torch.nn.functional import log_softmax
from torchvision import transforms
from werkzeug.datastructures import FileStorage

from utils import TARGET_SIZE, TORCH_MODEL, PADDING, BLACK

class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(in_channels=1, out_channels=10, kernel_size=5),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(10, 20, 3),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        self.dense = nn.Sequential(
            nn.Linear(20 * 5 * 5, 100),
            nn.ReLU(),
            nn.Linear(100, 10)
        )

    def forward(self, x):
        in_size = x.size(0)
        conv1 = self.conv1(x)
        conv2 = self.conv2(conv1)
        res = conv2.view(in_size, -1)
        out = self.dense(res)
        out = log_softmax(out, dim=1)
        return out

def load_model():
    """
    load model from saved model
    :return: MNIST model
    """
    model = Net()
    model.load_state_dict(torch.load(TORCH_MODEL))
    model.eval()
    return model

def predict(model, tensor: torch.Tensor):
    """
    use model to predict the input value
    :param model: MNIST model
    :param tensor: input tensor
    :return: predict result
    """
    tensor = tensor.view(-1, 1, 28, 28)
    with torch.no_grad():
        output = model(tensor)
        pred = torch.max(output, 1)[1]
    return pred[0].item()

def read_image(image: FileStorage) -> np.ndarray:
    """
    preprocessed the image into designated size tensor
    :param image: origin image (FileStorage type)
    :return: preprocessed ndarray of image
    """
    stream = image.read()
    image = cv2.imdecode(np.asarray(bytearray(stream)), 0)
    resized = cv2.resize(image, TARGET_SIZE, interpolation=cv2.INTER_AREA)
    return resized

def convert_base64(string: str) -> torch.Tensor:
    """
    Load base64 string from canvas and convert to tensor
    :param string: base64 string
    :return: preprocessed tensor of image
    """
    x = b64decode(string)
    image = Image.open(BytesIO(x))
    image = image.getchannel(3)
    image = transforms.Resize(TARGET_SIZE)(image)
    tensor = transforms.ToTensor()(image)
    return tensor

def convert_b64(string: str) -> np.ndarray:
    """
    Load base64 string form canvas and convert to ndarray
    :param string: base64 string
    :return: preprocessed ndarray of image
    """
    x = b64decode(string)
    image = cv2.imdecode(np.asarray(bytearray(x)), -1)
    gray = np.copy(image[:, :, -1])
    cropped = crop(gray)
    resized = cv2.resize(cropped, TARGET_SIZE, interpolation=cv2.INTER_AREA)
    return resized

def onnx_predict(sess: InferenceSession, x: np.ndarray):
    """
    use ONNX runtime session to predict result
    :param sess: ONNX runtime session
    :param x: input ndarray
    :return: predicted result
    """
    x = x.reshape((-1, 1, 28, 28))
    input_name = sess.get_inputs()[0].name
    label_name = sess.get_outputs()[0].name
    pred = sess.run([label_name], {input_name: x.astype("float32")})[0]
    return np.argmax(pred, axis=1)[0]

def crop(img: np.ndarray):
    """
    Crop the image to centralise stroke and add some padding
    :param img: image array
    :return: cropped image
    """
    bimg, contours, hier = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    (x, y, w, h) = cv2.boundingRect(contours[0])
    cropped = img.copy()[y: y + h, x: x + w]
    if h > w:
        length = h + PADDING
    else:
        length = w + PADDING
    v_pad = (length-h) // 2
    h_pad = (length-w) // 2
    enlarged = cv2.copyMakeBorder(cropped, v_pad, v_pad, h_pad, h_pad, cv2.BORDER_CONSTANT, value=BLACK)
    return enlarged


"""
Proszę zaimplementować funkcję void SumSort(int A[], int B[], int n). Funkcja ta przyjmuje na wejściu dwie n2-elementowe tablice (A i B) i zapisuje w tablicy B taką permutację elementów z A, że:
n−1 2n−1 n2−1 􏰁B[i]􏰀 􏰁 B[i]􏰀...􏰀 􏰁 B[i]. i=0 i=n i=n2 −n
Proszę zaimplementować funkcję SumSort tak, by działała możliwie jak najszybciej. Proszę oszacować i podać jej złożoność czasową.
"""
def partition(A, p, r):
    x = A[r]
    i = p - 1

    for j in range(p,r):
        if A[j] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]

    A[i + 1], A[r] = A[r], A[i + 1]
    return i + 1

def quick_select(A, p, r, k):
    if p == k:
        return A[k]
    q = partition(A, p, r)
    if q == k:
        return A[k]
    elif k < q:
        return quick_select(A, p, q - 1, k)
    else:
        return quick_select(A, q + 1, r, k)

def sumSort(A, n):
    for podzial in range(1,n):
        quick_select(A, (podzial - 1) * n, len(A) - 1, podzial * n)
    return A

"""
n = 3
A = [ 4, 2, 3, 1, 9 ,8, 2, 5, 7]
B = [ 0 ] * n * n

SumSort(A, B, n)
"""

####zadanie2

def insertion_sort(tab):
    for i in range(1,len(tab)):
        key = tab[i]
        j = i - 1
        while j >= 0 and key < tab[j]:
            tab[j + 1] = tab[j]
            j -= 1
        tab[j + 1] = key

def merge_tabs( A, B ):
    #scalamy 2 posortowane tablice
    A_idx = 0
    B_idx = 0
    result = []
    while(A_idx != len(A) and B_idx != len(B)):
        if A[ A_idx ] % 2 == 0:
            A_idx += 1

        elif A[ A_idx ] < B[ B_idx ]:
            result.append( A[ A_idx ] )
            A_idx += 1

        else:
            result.append( B[ B_idx ] )
            B_idx += 1

    while A_idx != len(A):
        if A[ A_idx ] % 2 == 1:
            result.append( A[ A_idx ] )
        A_idx += 1

    while B_idx != len(B):
        result.append( B[ B_idx ] )
        B_idx += 1

    return result

def Sort_logn_different( A ):
    #liczby nparzyste posortowane sa rosnaca wiec ich juz nie musimy sortowac
    #zajmujemy sie wiec jedynie posortowaniem liczb parzystych a nastepnie scalamy dwie posortowane listy
    #przegladamy liniowo tablice A i w momencie napotkania elementu parzystego dodajemy go do tablicy tmp
    tmp = []

    for each in A:
        if each % 2 == 0:
            tmp.append(each)

    insertion_sort(tmp)
    print(tmp)
    return merge_tabs(A, tmp)

"""
T = [1,3,12,7,9,13,19,2,27,33]
print(Sort_logn_different(T))
"""

#####zadanie3
class Node:
    def __init__(self, value = None, next = None):
        self.value = value
        self.next = next

def printlist( L ):
  while L != None:
    print( L.value, "->", end=" ")
    L = L.next
  print("|")

def add_element_at_the_end(first, value):
    if first == None:
        first = Node(value)
    else:
        pom = first
        while pom.next:
            pom = pom.next
        pom.next = Node(value)
    return first

def tab2list( A ):
  H = Node()
  C = H
  for i in range(len(A)):
    X = Node()
    X.value = A[i]
    C.next = X
    C = X
  return H.next

def fixSortedList( L ):
    if L == None:
        return L

    if L.value == None:
        return L

    tmp = None
    prev = None
    curr = L
    while curr.next:
        if curr.value > curr.next.value:
            tmp = curr
            prev.next = curr.next #usuwamy element z listy
            curr = curr.next
            #wstawiamy usuniety element we w   lasciwe miejsce
            while curr and tmp.value > curr.value:
                prev = curr
                curr = curr.next

            #print(curr.value)
            #print(prev.value)
            #print(tmp.value)
            prev.next = tmp
            tmp.next = curr
            break
        prev = curr
        curr = curr.next
    return L

T = [1,2,3,4,5,6,8,9,10,13] #brakuje edge case na pierwszy element
head = tab2list( T )
head = fixSortedList(head)
printlist(head)


import matplotlib.pyplot as plt
import numpy as np

dataArray = np.genfromtxt('csv_file.csv', delimiter=',', names=True)

plt.figure()
for col_name in dataArray.dtype.names:
    if(col_name == dataArray.dtype.names[1]):
        continue
    plt.plot(dataArray[col_name], label=col_name)
plt.legend()
plt.show()

ECE 484 MPs/Final Project/Dec 6/gen_graph.py


import jwt
import json
import requests
from time import time
from datetime import timedelta
from hashlib import sha256
from api import cfg
from flask import Flask, request, redirect, session, url_for
from app import app

app.secret_key = cfg['secret_key']

clannel_id = cfg['line_login']['clannel_id']
clannel_secret = cfg['line_login']['clannel_secret']
login_url = 'http://%s/login' % (cfg['web_url'])

line_login_url = 'https://access.line.me/oauth2/v2.1/authorize?' + '&'.join([
    'redirect_uri=%s' % login_url,
    'client_id=%s' % clannel_id,
    'response_type=code',
    'scope=openid+profile',
    'state=%s' % cfg['line_login']['state'],
    'nonce=%s' % cfg['line_login']['nonce'],
    'bot_prompt=normal',
])

@app.route('/login')
def login():
    code = request.args.get('code')
    state = request.args.get('state')
    error = request.args.get('error', None)

    if error is not None:
        return '登入失敗=%s' % error

    token_time = time()
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    token = requests.post('https://api.line.me/oauth2/v2.1/token', headers=headers, data={
        'redirect_uri':login_url,
        'client_id':clannel_id,
        'client_secret':clannel_secret,
        'grant_type':'authorization_code',
        'code':code,
    })

    token = json.loads(token.text)
    if 'error' in token:
        return '登入失敗=%s' % token.get('error_description')

    token_id = jwt.decode(token['id_token'], clannel_secret, audience=clannel_id, issuer='https://access.line.me', algorithms=['HS256'])
    if token_id['iss'] != 'https://access.line.me': return '驗證失敗1'
    if token_id['aud'] != clannel_id: return '驗證失敗2'
    if token_id['nonce'] != cfg['line_login']['nonce']: return '驗證失敗3'
    if token_id['exp'] < token_time: return '驗證失敗4'

    token = sha256((cfg['line_login']['state'] + token_id['sub']).encode()).hexdigest()
    session['token'] = token

    session['uid'] = token_id['sub']
    #session['user_name'] = token_id['name']
    #session['user_picture'] = token_id['picture']

    #session['group_id'] = None if state == str(None) else state

    return redirect('/') #redirect('/g/%s' % session['group_id']) if 'group_id' in session else redirect('/')

'''
@app.before_request
def make_session_permanent(): #session 有效時間
    session.permanent = True
    app.permanent_session_lifetime = timedelta(days=7)

'''


def has_loop(inst):
    accumulator = 0
    idx = 0
    used = {}
    while idx not in used and idx < len(inst):
        used[idx] = 1
        if inst[idx][0] == 'nop':
            idx += 1
        elif inst[idx][0] == 'jmp':
            idx += inst[idx][1]
        elif inst[idx][0] == 'acc':
            accumulator += inst[idx][1]
            idx += 1
        else:
            assert False
    return idx < len(inst), accumulator

def rec_fill(idx):
    global visited, is_sink, inp
    nxt = 0
    visited[idx] = True
    if inp[idx][0] == 'jmp':
        nxt = idx + inp[idx][1]
    else:
        nxt = idx + 1
    if nxt >= len(inp):
        is_sink[idx] = True
    elif visited[nxt] == True:
        is_sink[idx] = is_sink[nxt]
    else:
        rec_fill(nxt)
        is_sink[idx] = is_sink[nxt]

def label_sinks():
    global visited, is_sink, inp
    for i in range(len(inp)):
        if visited[i] == False:
            rec_fill(i)

def find_replacement(idx):
    global visited, is_sink, inp
    while is_sink[idx] == False:
        if inp[idx][0] == 'jmp' and is_sink[idx + 1] == True:
            #print(idx)
            inp[idx][0] = 'nop'
            idx += 1
        elif inp[idx][0] == 'nop' and is_sink[idx + inp[idx][1]]:
            #print(idx)
            inp[idx][0] = 'jmp'
            idx += inp[idx][1]
        elif inp[idx][0] == 'jmp':
            idx += inp[idx][1]
        else:
            idx += 1

# Main Starts Here
f = open("./2020/input/2020_08.txt")
inp = f.read().splitlines()
f.close()

inp = [x.split(' ') for x in inp]
inp = [[x[0], int(x[1])] for x in inp]

visited = [False for x in inp]
is_sink = [False for x in inp]

print('part1', has_loop(inp))
label_sinks()
find_replacement(0)
print('part2 O(n)', has_loop(inp))


import cv2 as cv

img = cv.imread("/home/bkha0016/Documents/opencv-course-master/Resources/Photos/cat.jpg")
cv.imshow("cat", img)

#converting to grayscale
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow("Gray", gray)

imgBost = cv.imread("/home/bkha0016/Documents/opencv-course-master/Resources/Photos/park.jpg")
#blur the image
imgBostBlur = cv.GaussianBlur(imgBost, (3,3), cv.BORDER_DEFAULT)
cv.imshow("Boston", imgBostBlur)

#Edge cascade
canny = cv.Canny(imgBost, 125, 175)
cv.imshow("Canny", canny)

#dilating the image
dilate = cv.dilate(canny,(3,3), iterations = 1)
cv.imshow("Dilated", dilate)

#eroding the image
eroded = cv.erode(dilate, (3,3), iterations = 1)
cv.imshow("Eroded", eroded)

#Resize
resized = cv.resize(img, (500,500))
cv.imshow("Resized", resized)

#cropping
cropped = img[50:200, 200:400]
cv.imshow("cropped", cropped)

cv.waitKey(0)

opencv-course-master/Section #1 - Basics/basic1.py


import cv2
import matplotlib.pyplot as plt

img = cv2.imread("images/child.jpg")

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #Convert BGR to RGB
ax = plt.subplot(221)
plt.imshow(img)

img2 = cv2.flip(img, 2)
ax = plt.subplot(222)
plt.imshow(img2)

img3 = cv2.flip(img, 0)
ax = plt.subplot(223)
plt.imshow(img3)

img4 = cv2.flip(img, -1)
ax = plt.subplot(224)
plt.imshow(img4)

plt.show()


#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'breakingRecords' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY scores as parameter.
#

def breakingRecords(scores):
    # Write your code here
    max_score = float("-inf")
    min_score = float("inf")
    max_ctr = -1
    min_ctr = -1
    records = []
    for score in scores:
        if max_score < score:
            max_score = score
            max_ctr += 1
        if min_score > score:
            min_score = score
            min_ctr += 1
    record = [max_ctr, min_ctr]
    return record

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    scores = list(map(int, input().rstrip().split()))

    result = breakingRecords(scores)

    fptr.write(' '.join(map(str, result)))
    fptr.write('\n')

    fptr.close()


"""
sideinfo.py : get the side information for an MP3 frame
"""

import json

from collections import defaultdict
from .util.bits import Bits
from .header import ChannelEncodings, MP3Header

class ChannelSideInfo(object):
    """
    ChannelSideInfo : container for all that pesky side information per channel

    Attributes :
    - part2_3_length : 1 value
    - big_values : 1 value
    - global_gain : 1 value
    - scalefac_compress : 1 value
    - window_switching_flag : 1 value
    - block_type : 1 value
    - mixed_block_flag : 1 value
    - table_select : 2 values
    - region0_count : 1 value
    - region0_count : 1 value
    - sub_block_gain : 3 values
    - preflag : 1 value
    - scalefac_scale : 1 value
    - count1_table_select : 1 value
    """

    def __init__(self, index: int, bits: Bits):
        self.index = index
        # self.bits = bits # do we actually want to keep a copy of the bitstring here?

        self.part2_3_length = bits.read_bits_as_int(12)
        self.big_values = bits.read_bits_as_int(9)
        self.global_gain = bits.read_bits_as_int(8)
        self.scalefac_compress = bits.read_bits_as_int(4)
        self.window_switch_flag = bits.read_bits_as_int(1)
        self.table_select = [0] * 3
        self.sub_block_gain = [0] * 3
        if self.window_switch_flag == 1:
            self.block_type = bits.read_bits_as_int(2)
            self.mixed_block_flag = bits.read_bits_as_int(1)
            for i in range(0, 2):
                self.table_select[i] = bits.read_bits_as_int(5)
            for i in range(0, 3):
                self.sub_block_gain[i] = bits.read_bits_as_int(3)
            # the below code is present in
            # https://github.com/hajimehoshi/go-mp3/blob/master/internal/sideinfo/sideinfo.go
            # but it's making my tests fail so (shrug)

            # UPDATE: I think it's time to bring this back
            if (self.block_type == 2 and self.mixed_block_flag == 0):
                self.region0_count = 8
            else:
                self.region0_count = 7
            # TODO: come back and look at this later if stuff starts failing
            self.region1_count = 20 - self.region0_count
        else:
            for i in range(0, 3):
                self.table_select[i] = bits.read_bits_as_int(5)
            self.region0_count = bits.read_bits_as_int(4)
            self.region1_count = bits.read_bits_as_int(3)
            # I don't think we need to set block_type or mixed_blog_flag
            # if window_switch_flag isn't set
            self.block_type = 0
            self.mixed_block_flag = 0
            for _ in range(0, 3):
                self.sub_block_gain[i] = 0
        self.preflag = bits.read_bits_as_int(1)
        self.scalefac_scale = bits.read_bits_as_int(1)
        self.count1_table_select = bits.read_bits_as_int(1)

    def __str__(self):
        """
        __str__ : string representation of a channel
        """
        return json.dumps({
            'part2_3_length' : self.part2_3_length,
            'big_values' : self.big_values,
            'global_gain' : self.global_gain,
            'scalefac_compress' : self.scalefac_compress,
            'window_switch_flag' : self.window_switch_flag,
            'block_type' : self.block_type,
            'mixed_block_flag' : self.mixed_block_flag,
            'table_select' : self.table_select,
            'region0_count' : self.region0_count,
            'region0_count' : self.region0_count,
            'sub_block_gain' : self.sub_block_gain,
            'preflag' : self.preflag,
            'scalefac_scale' : self.scalefac_scale,
            'count1_table_select' : self.count1_table_select,
        })

class Granule(object):
    """
    Granule : basically just a container for a two-tuple of Channels
    """

    def __init__(self, index, bits):
        self.index = index
        self.bits = bits
        self.channels = []
        self.channels.append(ChannelSideInfo(0, self.bits))
        self.channels.append(ChannelSideInfo(1, self.bits))

    def collect_channel_values(self, key):
        """
        collect_channel_values : collect all the channel values associated with the given key
        """
        result = []
        for chan in self.channels:
            result.append(chan.__getattribute__(key))
        return result

    def __str__(self):
        """
        __str__ : string representation of a granule
        """
        return json.dumps({
            'index' : self.index,
            'channels' : [str(c) for c in self.channels],
        })

class SideInfo(object):
    """
    SideInfo : parse the side information for an MP3 frame

    Attributes:
        main_data_begin - 9 bits
        private_bits - 5 bites for mono; 3 bits for stereo
        scfsi
        granule_one:
        - part2_3_length
        - big_values
        - global_gain
        - scalefac_compress
        - window_switching_flag
        - block_type
        side_info for gr2 (granule 2)
    """

    def __init__(self, header: MP3Header, raw_bytes):
        """
        __init__ : read the given mp3_file and parse the side information
        this expected the mp3_file file object to already be pointing to the side information
        this will modify the mp3_file file object to point to the first byte
            after the side information
        """
        channels = 1
        if header.channel != ChannelEncodings.MONO:
            channels = 2
        bits = Bits()
        for i in raw_bytes:
            bits.add_bits(i)
        self._bitstring = bits
        # each entry into the two granules object will be an array with each index
        # corresponding to the channel - 1
        self.granules = {
            0 : defaultdict(list),
            1 : defaultdict(list),
        }
        self.main_data_begin = self._bitstring.read_bits_as_int(9)
        if header.channel == ChannelEncodings.MONO:
            self.private_bits = self._bitstring.read_bits_as_int(5)
        else:
            self.private_bits = self._bitstring.read_bits_as_int(3)
        self.scfsi_band = [0] * channels
        for i in range(0, channels):
            self.scfsi_band[i] = [0] * 4
            for j in range(0, 4):
                self.scfsi_band[i][j] = self._bitstring.read_bits_as_int(1)
        for i in range(0, 2):
            self.granules[i] = Granule(i, self._bitstring)

    def __str__(self):
        """
        __str__ : string representation of each thing
        """
        return json.dumps({
            'granules' : [str(self.granules[g]) for g in self.granules],
            'main_data_begin' : self.main_data_begin,
            'private_bits' : self.private_bits,
            'scfsi_band' : self.scfsi_band,
        }).replace('"', '')


"""
Script som henter data fra NVDB og lagrer som geopackage-fil (.gpkg), et moderne GIS-format

Scriptet forutsetter at vi har dette biblioteket her: https://github.com/LtGlahn/nvdbapi-V3
Filene apiforbindelse.py, nvdbapiv3.py og nvdbgeotricks.py er hentet derfra.

Data som hentes:
  - Vegnett
  - Rekkverk som brukes til midtdeler eller midtrekkverk
  - Vegoppmerking som brukes til gulstripe
  - Vegbredde (tre ulike objekttyper i NVDB)

Datanedlasting tar ca 10-15 minutter på en grei bredbåndslinje (200mb)
"""

import nvdbgeotricks

filnavn_gpkg = 'nvdbdata.gpkg'

mittfilter = { 'vegsystemreferanse' : 'Ev,Rv' }

# Henter Rekkverk (objekttype 5) med bruksområde = Midtdeler eller Midtrekkverk
# Samtidig henter vi vegnettsdata (default vegnett=True)
mittfilter['egenskap'] = '(1248=11789 OR 1248=11788)'
nvdbgeotricks.nvdb2gpkg( 5, filnavn=filnavn_gpkg, mittfilter=mittfilter, vegsegmenter=True, geometri=False )

# Henter Vegoppmerking, langsgående (objekttype 99) med bruksområde = midtlinje
# henter ikke vegnett enda en gang
mittfilter['egenskap'] = "4520=5342"
nvdbgeotricks.nvdb2gpkg( 99, filnavn=filnavn_gpkg, mittfilter=mittfilter, vegsegmenter=True, geometri=False, vegnett=False  )

# Henter data for vegbredde. Disse antar vi det blir en del fikling med før vi har  optimale terskelverdier for
# de ulike variantene av vegbredde, så vi henter rubb og rake.
mittfilter.pop('egenskap', None)
breddetyper = [647, 583,838]
nvdbgeotricks.nvdb2gpkg( breddetyper, filnavn=filnavn_gpkg, mittfilter = mittfilter, vegsegmenter=True, geometri=False, vegnett=False )


from configobj import ConfigObj

# Points to parent directory #
# basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))

config = ConfigObj()

config.filename = 'config.py'

# If set to True, Flask-SQLAlchemy will track modifications of objects and emit signals.
# The default is None, which enables tracking but issues a warning that it will be disabled by default in the future.
# This requires extra memory and should be disabled if not needed. #
# SQLALCHEMY_TRACK_MODIFICATIONS = True

# the URI is required by flask-sqlalchemy extension. This is the path of the database file #
# SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'database.db')

# the REPO is where the migration files are stored #
# SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')

""" Initialize Flask Configurations """

config['WTF_CSRF_ENABLED'] = True
config['SECRET_KEY'] = 'abc123'


import pika, os

def publish_data(data, url_path):
# Access the CLODUAMQP_URL environment variable and parse it (fallback to localhost)
    # url = os.environ.get('CLOUDAMQP_URL', url_path)
    # params = pika.URLParameters(url)
    # connection = pika.BlockingConnection(params)
    # channel = connection.channel() # start a channel
    # channel.queue_declare(queue='ccass1') # Declare a queue
    # channel.basic_publish(exchange='',
    #                     routing_key='ccass1',
    #                     body=data)

    # print(f" [x] Sent {data}")
    # connection.close()

    connection_parameters = pika.ConnectionParameters(
    host='services.irn1.chabokan.net',
    port=60560,  # Default AMQPS port
    virtual_host='/',
    credentials=pika.PlainCredentials('patricia', 'M5oDa0NsJZQ5zAkJ'),
    )

    # Establish the connection
    connection = pika.BlockingConnection(connection_parameters)

    # Create a channel and perform your publishing operations
    channel = connection.channel()
    channel.queue_declare(queue='ccass1')
    channel.basic_publish(exchange='',
                        routing_key='ccass1',
                         body=data)
    # ...

    # Don't forget to close the connection when you're done
    connection.close()


import tkinter
import tkinter.filedialog as fd
import json
import pandas
import numpy

class results(object):
    def __init__(self, researchName):
        self.name = researchName
        self.researchers = []
        self.groups = []
        self.conditions = []
        self.description = []

    def set_researchers(self, researchers):
        self.researchers.append(researchers)

    def set_groups(self, groups):
        self.groups.append(groups)

    def set_conditions(self, conditions):
        self.conditions.append(conditions)

    def set_description(self, description):
        self.description.append(description)

    def chooseFile(self):
        root = tkinter.Tk()
        root.withdraw()  # use to hide tkinter window

        fname = fd.askopenfilename(filetypes=(("All files", "*.type"), ("All files", "*")))
        print(fname)
        print(type(fname))

        if  (fname == ""):
            print("no file")
        elif not (fname.endswith(('xlsx', 'xls'))):
            print("wrong file extension")

        return fname

    def uploadResults(self, file_path):
        # With the attribute "usecols" we will load only the right columns, every third column.
        # Our excel files are without "header".
        excelFile = pandas.read_excel(file_path, header=None, usecols = lambda x: x%3==0 in range(69))
        # print(excelFile)
        return excelFile

    def data_section(self, section_number=3.0):
        file_data = self.uploadResults(self.chooseFile())
        # "numpy.einsum" - Evaluates the Einstein summation convention on the operands.
        # Using the Einstein summation convention, many common multi-dimensional, linear algebraic array operations can be represented in a simple fashion. In implicit mode einsum computes these values.
        # In explicit mode, einsum provides further flexibility to compute other array operations that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels.
        print("inside data section: ")
        print(file_data)
        # Number of lines
        print(file_data.shape[0])
        print(type(file_data))
        numpy_file_data = file_data.to_numpy()
        print(numpy_file_data)

        # fill needed rows with the same values as the last row - copy the last row many times as needed
        print(file_data.iloc[-1])
        print(type(file_data.iloc[-1]))
        print(file_data.iloc[[-1]])
        print(type(file_data.iloc[[-1]]))

        remainder = section_number - (file_data.shape[0] % section_number)
        new_file = file_data.append([file_data.iloc[-1]] * remainder, ignore_index=True)
        print(section_number)
        print(remainder)
        print(new_file)
        new_file_data = new_file.to_numpy()
        return pandas.DataFrame(numpy.einsum('ijk->ik', new_file_data.reshape(-1, int(section_number), new_file_data.shape[1])) / section_number)

    def correlation_matrix(self, matrix):
        return matrix.corr()

    def binary_matrix(self, matrix, threshold):
        temp_binary_matrix = pandas.DataFrame()
        print(type(temp_binary_matrix))
        print(matrix[0])
        print(matrix[0].apply(lambda x: 1 if x>threshold else 0))
        for col in range(len(matrix)):
            newCol = matrix.T.loc[col].apply(lambda x: 1 if x>threshold else 0)
            print(newCol)
            print(type(newCol))
            temp_binary_matrix[col] = newCol

        # ------- JSON -----------

        # with open("data_file.json", "w") as write_file:
        #     json.dump(temp_binary_matrix, write_file)
        # --------------------------

        temp_binary_matrix.to_csv(self.name + ".csv", index=False)
        return temp_binary_matrix

if __name__ == '__main__':
    r1 = results("name")
    r1.data_section(5)


from matplotlib.colors import ListedColormap
from sklearn.svm import SVC
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

# dataset and targets
X = np.c_[(0, 0), (1, 1), (0, 1), (1, 0)].T
Y = [0] * 2 + [1] * 2
Y = np.array(Y)
X = np.array(X)

# create xor dataset
np.random.seed(0)
X_xor = np.random.randn(200, 2)
y_xor = np.logical_xor(X_xor[:, 0] > 0, X_xor[:, 1] > 0)
y_xor = np.where(y_xor, 1, -1)

# SVM

def plot_decision_regions(X, y, classifier, axs, test_idx=None, resolution=0.02):
    # setup marker generator and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('green', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    axs.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
    axs.set_xlim(xx1.min(), xx1.max())
    axs.set_ylim(xx2.min(), xx2.max())
    axs.set_xticks(())
    axs.set_yticks(())

    # plot all samples
    X_test, y_test = X[test_idx, :], y[test_idx]
    for idx, cl in enumerate(np.unique(y)):
        axs.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
                    alpha=0.8, c=colors[idx],
                    marker=markers[idx], label=cl)
    # highlight test samples
    if test_idx:
        X_test, y_test = X[test_idx, :], y[test_idx]
        axs.scatter(X_test[:, 0], X_test[:, 1], c='',
                    alpha=1.0, linewidth=1, marker='o',
                    s=55, label='test set')

fig, axs = plt.subplots(3, 3, figsize=(15, 6), facecolor='w', edgecolor='k')
C = [0.1, 1, 100]
gamma = 2

j = 0
for kernel in ('sigmoid', 'poly', 'rbf'):
    i = 0
    for c in C:
        if(kernel == "poly"):
            clf = SVC(kernel=kernel, gamma=gamma, C=c, degree=2)
        else:
            clf = SVC(kernel=kernel, gamma=gamma, C=c)
        clf.fit(X_xor, y_xor)
        plot_decision_regions(X_xor, y_xor, clf, axs[i, j])
        axs[i, j].set_title(
            'Kernel : {} , C : {}, Gamma : {}'.format(kernel, c, gamma))
        i += 1
    j += 1
plt.legend(loc='upper left')
plt.show()

# axs[i,j].scatter(X_xor[:, 0], X_xor[:, 1], c=Y, zorder=10, cmap="winter",
#             edgecolors='k')
# # plt.axis('tight')
# x_min = -3
# x_max = 3
# y_min = -3
# y_max = 3
# XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
# Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])
# # Put the result into a color plot
# Z = Z.reshape(XX.shape)
# axs[i,j].pcolormesh(XX, YY, Z > 0, cmap="winter")
# axs[i,j].contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'],
#             levels=[-.5, 0, .5])


# Written by Cameron Haddock
# Written as a solution for Advent of Code 2020

# https://adventofcode.com/2020/day/6

with open('2020/06/input.txt','r') as input_file:
    count_1,count_2 = 0,0
    group_1 = set()
    group_2 = set('abcdefghijklmnopqrstuvwxyz')

    for line in input_file:
        line = line.strip()
        if line:
            group_1 |= set(line)
            group_2 &= set(line)
        else:
            count_1 += len(group_1)
            count_2 += len(group_2)
            group_1 = set()
            group_2 = set('abcdefghijklmnopqrstuvwxyz')
    print(f'Group 1: {count_1}, Group 2: {count_2}')


# class Node:
#     def __init__(self,info):
#         self.info = info
#         self.left = None
#         self.right = None
#     def insert(self,item):
#         if item <self.info:
#             if self.left is None:
#                 self.left =Node(item)
#             else:
#                 self.left.insert(item)
#         else:
#             if self.right is None:
#                 self.right =Node(item)
#             else:
#                 self.right.insert(item)
#     def inorder(self):
#         if self.left is not None:
#             self.left.inorder()
#         print(self.info,end=" ")
#         if self.right is not None:
#             self.right.inorder()

class Node:
    left = None
    info = 0
    right = None

    def __init__(self, info):
        self.info = info

class BST:
    root = None

    def insert(self, item):
        node = Node(item)
        if (self.root == None):
            self.root = node
            return
        post = None
        p = self.root
        while (p != None):
            if (p.info > item):
                post = p
                p = p.left
            elif (p.info < item):
                post = p
                p = p.right
        if (post.info > item):
            post.left = node
        else:
            post.right = node

    def __inorderTraversal(self, p):
        if p != None:
            if p.left is not None:
                self.__inorderTraversal(p.left)
            print(p.info, end=" ")
            if p.right is not None:
                self.__inorderTraversal(p.right)

    def inorder(self):
        p = self.root
        self.__inorderTraversal(p)

test = BST()
for i in range(7):
    x = int(input())
    test.insert(x)
test.inorder()


import json
from uuid import uuid4
from flask import Flask, request

def process_query_string(qs):
    params = request.query_string.decode().split('&')
    keys = {}

    for p in params:
        pair = p.split('=')
        keys[pair[0]] = pair[1]

    return keys

def create_app():
    app = Flask(__name__)

    @app.route('/', methods=['GET'])
    def index():
        message = '''
        Routes:

        '/': Show this page

        '/hello': Says hello

        '/hello?name=<your name>': Says hello to you!

        '/secret': Tells you a secret
        '''

        return message, 200

    @app.route('/hello', methods=['GET'])
    def hello():
        message = "Hello!"
        qs = request.query_string

        if len(qs) > 0:
            name = process_query_string(qs).get('name', 'Human')
            message = 'Hello {}!'.format(name)

        return message, 200

    @app.route('/secret')
    def secret():
        secret = "This is a secret: {}

Don't tell anyone."
        return secret.format(uuid4().hex), 200

    return app

if __name__ == '__main__':
    app = create_app()
    app.run(debug=True)


n =  int(input("Enter the length of the sequence: ")) # Do not change this line
#initializing values for the formula
n1 = 0
n2 = 1
n3 = 2

for i in range(n):
    seq = n1 + n2 + n3 #The sum of the 3 numbers in the sequence
    n1 = n2            #Moving the values around to continue with the sequence
    n2 = n3            #Moving the values around to continue with the sequence
    n3 = seq           #n3 now has the value of the next number in the sequence
    print(n1)          #Here the sequence is printed
                       #All the other variables will give the same sequence but will not satisfy the test
                       #So in order to satisfy the test, n1 must be printed


a = int(input())
b = list(map(int, input().split()))
def foo(b):
    s = []
    for i in range(0, len(b)-1):
        if b[i] < b[i+1]:
            s.append('p')
        elif b[i] > b[i+1]:
            s.append('v')
        else:
            break
        if len(s) >= 2 and s[i - 1] == s[i]:
            break
    else:
        print(1)
        return
    print(0)

foo(b)


"""
=============================================
Polyhedron (:mod:`microgen.shape.polyhedron`)
=============================================
"""
import cadquery as cq
import pyvista as pv
import numpy as np
import copy

from .basicGeometry import BasicGeometry

class Polyhedron(BasicGeometry):
    """
    Class to generate a Polyhedron with a given set of faces and vertices

    .. jupyter-execute::
       :hide-code:

       import microgen

       shape = microgen.Polyhedron().generateVtk()
       shape.plot(color='white')
    """

    def __init__(
        self,
        center: tuple[float, float, float] = (0, 0, 0),
        orientation: tuple[float, float, float] = (0, 0, 0),
        dic: dict[str, list] = {
            "vertices": [
                (1.0, 1.0, 1.0),
                (1.0, -1.0, -1.0),
                (-1.0, 1.0, -1.0),
                (-1.0, -1.0, 1.0),
            ],
            "faces": [
                {"vertices": [0, 1, 2]},
                {"vertices": [0, 3, 1]},
                {"vertices": [0, 2, 3]},
                {"vertices": [1, 2, 3]},
            ],
        },
    ) -> None:
        """
        .. warning:
            Give a center parameter only if the polyhedron must be translated from its original position.
        """
        super().__init__(shape="Polyhedron", center=center, orientation=orientation)
        self.dic = dic
        self.faces_ixs = [face["vertices"] for face in dic["faces"]]
        for ixs in self.faces_ixs:
            ixs.append(ixs[0])

    def generate(self) -> cq.Shape:
        faces = []
        for ixs in self.faces_ixs:
            lines = []
            for v1, v2 in zip(ixs, ixs[1:]):
                # tuple(map(sum, zip(a, b))) -> sum of tuples value by value
                vertice_coords1 = tuple(
                    map(sum, zip(self.center, self.dic["vertices"][v1]))
                )
                vertice_coords2 = tuple(
                    map(sum, zip(self.center, self.dic["vertices"][v2]))
                )
                lines.append(
                    cq.Edge.makeLine(
                        cq.Vector(*vertice_coords1), cq.Vector(*vertice_coords2)
                    )
                )
            wire = cq.Wire.assembleEdges(lines)
            faces.append(cq.Face.makeFromWires(wire))
        shell = cq.Shell.makeShell(faces)
        solid = cq.Solid.makeSolid(shell)
        return cq.Shape(solid.wrapped)

    def generateVtk(self) -> pv.PolyData:
        facesPv = copy.deepcopy(self.faces_ixs)
        for vertices_in_face in facesPv:
            del vertices_in_face[-1]
            vertices_in_face.insert(0, len(vertices_in_face))

        vertices = np.array(self.dic["vertices"])
        faces = np.hstack(facesPv)

        return pv.PolyData(vertices, faces)

def read_obj(filename: str):
    """
    Reads vertices and faces from obj format file for polyhedron
    """
    dic = {"vertices": [], "faces": []}
    with open(filename, "r") as f:
        for line in f:
            data = line.split(" ")
            if data[0] == "v":
                x = float(data[1])
                y = float(data[2])
                z = float(data[3])
                dic["vertices"].append([x, y, z])
            elif data[0] == "f":
                vertices = data[1:]
                for i in range(len(vertices)):
                    vertices[i] = int(vertices[i]) - 1
                dic["faces"].append({"vertices": vertices})
    return dic


from provworkflow import Block, PROVWF
from rdflib import Literal
from rdflib.namespace import OWL, RDF, XSD

def test_prov_to_graph():
    """A basic Block should prov_to_graph an Activity which is specialised as provwf:Block

    :return: None
    """

    b = Block()
    g = b.prov_to_graph()

    # check typing
    assert (b.uri, RDF.type, PROVWF.Block) in g, "g must contain a provwf:Block"

    assert (
        b.uri,
        OWL.versionIRI,
        Literal(b.version_uri, datatype=XSD.anyURI),
    ) in g, "g must contain an owl:versionIRI property for a provwf:Block instance"

if __name__ == "__main__":
    test_prov_to_graph()


import frappe
from frappe import (throw, _, msgprint)
from frappe.exceptions import DuplicateEntryError

import json
from typing import TYPE_CHECKING, Dict, List

from rq import Queue, Worker

from frappe.utils.data import convert_utc_to_system_timezone, format_datetime
from frappe.utils.background_jobs import get_redis_conn
from frappe.utils.scheduler import is_scheduler_inactive

if TYPE_CHECKING:
	from rq.job import Job

JOB_COLORS = {
	'queued': 'orange',
	'failed': 'red',
	'started': 'blue',
	'finished': 'green'
}

@frappe.whitelist()
def get_info(show_failed=False) -> List[Dict]:
	if isinstance(show_failed, str):
		show_failed = json.loads(show_failed)

	conn = get_redis_conn()
	queues = Queue.all(conn)
	workers = Worker.all(conn)
	jobs = []

	def add_job(job: 'Job', name: str) -> None:
		if job.kwargs.get('site') == frappe.local.site:
			job_info = {
				'job_name': job.kwargs.get('kwargs', {}).get('playbook_method')
					or job.kwargs.get('kwargs', {}).get('job_type')
					or str(job.kwargs.get('job_name')),
				'status': job.get_status(),
				'queue': name,
				'creation': format_datetime(convert_utc_to_system_timezone(job.created_at)),
				'color': JOB_COLORS[job.get_status()]
			}

			if job.exc_info:
				job_info['exc_info'] = job.exc_info

			jobs.append(job_info)

	# show worker jobs
	for worker in workers:
		job = worker.get_current_job()
		if job:
			add_job(job, worker.name)

	for queue in queues:
		# show active queued jobs
		if queue.name != 'failed':
			for job in queue.jobs:
				add_job(job, queue.name)

		# show failed jobs, if requested
		if show_failed:
			fail_registry = queue.failed_job_registry
			for job_id in fail_registry.get_job_ids():
				job = queue.fetch_job(job_id)
				add_job(job, queue.name)

	return jobs

@frappe.whitelist()
def remove_failed_jobs():
	conn = get_redis_conn()
	queues = Queue.all(conn)
	for queue in queues:
		fail_registry = queue.failed_job_registry
		for job_id in fail_registry.get_job_ids():
			job = queue.fetch_job(job_id)
			fail_registry.remove(job, delete_job=True)

@frappe.whitelist()
def get_scheduler_status():
	if is_scheduler_inactive():
		return [_("Inactive"), "red"]
	return [_("Active"), "green"]

__version__ = '0.0.1'

def publish_progress(docname, id, achieved, total, description, field_name=None, done_message="Done", title="Loading", reload=False):
    frappe.publish_realtime(id,
                            {
                                "title": title,
                                "count": achieved,
                                "total": total,
                                "percentage": achieved / total * 100,
                                "description": f"Progress: {achieved}/{total} {description}",
                                "reload": reload,
                                "fieldname": field_name,
                                "done_message": done_message
                            },
                            user=frappe.session.user,
                            after_commit=False,
                            docname=docname)

def backgroud_jobs_check(function_path):
    list_of_jobs = get_info()
    if list_of_jobs:
        for job in list_of_jobs:
            if job['job_name'] == function_path:
                throw(_([f"Current Job Status: {job['status']}",
                        f"Job has been created at: {job['creation']}"]),
                    DuplicateEntryError,
                    "This job already in progress",
                    as_list=True)


from torch import nn

from alpha_network.policy_head import PolicyHead
from alpha_network.feature_extractor import FeatureExtractor

from alpha_network.value_head import ValueHead

import torch
import numpy as np
import pickle

from utils import logger, CUDA, CHECKPOINTS_DIR

class AlphaNetwork(nn.Module):
    def __init__(self, residual_depth, single_channel_size, num_input_channels,
                 num_possible_actions):
        super(AlphaNetwork, self).__init__()

        INTERMIDATE_RESIDUAL_NUM_CHANNELS = 256

        self.feature_extractor = FeatureExtractor(residual_depth,
                                                  num_input_channels,
                                                  INTERMIDATE_RESIDUAL_NUM_CHANNELS)
        self.value_head = ValueHead(INTERMIDATE_RESIDUAL_NUM_CHANNELS,
                                    single_channel_size)
        self.policy_extractor = PolicyHead(INTERMIDATE_RESIDUAL_NUM_CHANNELS,
                                           single_channel_size,
                                           num_possible_actions)

    def _forward(self, x):
        x = self.feature_extractor.forward(x)
        return self.policy_extractor.forward(x), self.value_head.forward(x)

    def predict(self, x):
        assert x.size()[0] == 1, 'Predict on only one state at a time'

        with torch.no_grad():
            policy, value = self._forward(x)

            # last layer is a log max, for prediction, undo log
            # remove batch dimension as-well.
            return policy.exp()[0], value[0]

    @staticmethod
    def _policy_loss(outputs, targets):
        """
        Cross-entropy loss as defined in the paper.
        :note: The outputs are expected to be log-softmax probabilities
        :return: The cross-entropy losses between the output probabilities and expected probabilities
                 averaged over the number of samples in the batch
        """
        return -torch.sum(outputs * targets) / outputs.size()[0]

    @staticmethod
    def _value_loss(outputs, targets):
        """
        :return: The square error between the outputs and target values, averaged over the sample size.
        """
        return torch.sum((targets - outputs) ** 2) / outputs.size()[0]

    def forward_batch(self, states, target_policies, target_values):
        """
        :param states: the batch of states
        :param target_policies: the target policy for each state in the batch
        :param target_values: the target value for each state in the batch
        :return: the total loss for the network as defined in the paper (averaged cross entropy losses for all
                 policies summed with the averaged squared error for each value)
        """
        policies, values = self._forward(states)
        return self._policy_loss(policies, target_policies) + self._value_loss(
            values, target_values)

    def train(self, train_examples, epochs, batch_size=32):
        """
        :param train_examples: train examples, a list of tuples of form:
                <state, expected policy, value>
        :param epochs: number of epochs to train
        :param batch_size: batch size to use

        :return: the loss at the end of each epoch
        """

        # copy the list, since we shuffle it in-place
        train_examples = list(train_examples)

        optimizer = torch.optim.SGD(self.parameters(), lr=0.01, momentum=0.9)
        losses = list()

        num_batches = np.floor(len(train_examples) / batch_size)
        logger.info("beginning training")
        for epoch in range(epochs):
            logger.debug(f'Epoch {epoch}')
            np.random.shuffle(train_examples)
            batch_index = 0
            epoch_loss = 0.0
            while batch_index < num_batches:
                optimizer.zero_grad()

                states, policies, values = list(zip(*train_examples[
                                                     batch_index * batch_size: (
                                                                                batch_index + 1) * batch_size]))
                states = torch.cat(states)
                policies = torch.cat(policies)
                values = torch.cat(values)

                loss = self.forward_batch(states, policies, values)

                # compute gradient and do SGD step
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()

                batch_index += 1
                epoch_loss += loss.item()

            losses += [epoch_loss / num_batches]

        return losses

    def save_checkpoint(self, game_name, examples_history):
        import datetime
        file_name = game_name + datetime.datetime.now().isoformat()\
            .replace(':', '_').replace('.', '_')
        file_path = CHECKPOINTS_DIR / file_name
        history_path = CHECKPOINTS_DIR / (file_name + "_history")

        logger.info(f"Storing checkpoint at {file_path}")
        with open(file_path, 'wb') as f:
            torch.save({
                'state_dict': self.state_dict(),
            }, f)

        with open(history_path, 'wb') as f:
            f.write(pickle.dumps(examples_history))

    def load_checkpoint(self, file_name, load_history=True):
        checkpoint_path = CHECKPOINTS_DIR / file_name
        history_path = CHECKPOINTS_DIR / (file_name + "_history")
        logger.info(f"Loading CPU checkpoint from {checkpoint_path}")
        with open(checkpoint_path, 'rb') as f:
            checkpoint = torch.load(f, map_location='cpu')
            self.load_state_dict(checkpoint['state_dict'])

        if not load_history:
            return

        with open(history_path, 'rb') as f:
            result = pickle.loads(f.read())
        if CUDA:
            result = [(item[0].cuda(), item[1].cuda(), item[2].cuda()) for item
                      in result]
        return result


import functools
import itertools
import json
import pathlib

from ._escape_utils import conditional_escape, mark_safe

class Octicon():

    def __init__(self, data):
        self.width = data['width']
        self.height = data['height']
        self.name = data['name']
        self.keywords = data['keywords']
        self.path = data['path']
        self.viewBox = data.get('viewBox', None)

    @staticmethod
    def key_exists(opts, key):
        return opts.get(key, None) is not None

    @staticmethod
    def escape_attr(key, value):
        if value is True:
            return key
        elif value is False or value is None:
            return ''
        elif key == 'class':
            if not isinstance(value, str):
                value = ' '.join(map(str.strip, value))
        return '%s="%s"' % (key, conditional_escape(value))

    def as_html(self, **opts):
        raw_attrs = self.build_attributes(opts)
        attrs = ' '.join(filter(None, itertools.starmap(
            self.escape_attr, raw_attrs.items())))
        return mark_safe("<svg %s>%s</svg>" % (attrs, self.path))

    def build_attributes(self, opts):
        opts = {k.replace('_', '-'): v for k, v in opts.items()}
        key_exists = functools.partial(self.key_exists, opts)

        defaults = self.default_attrs
        overrides = {}
        if key_exists('width') and not key_exists('height'):
            # Generate the correct height from the aspect ratio
            overrides['height'] = opts["width"] / self.size_ratio
        elif key_exists('height') and not key_exists('width'):
            # Generate the correct width from the aspect ratio
            overrides['width'] = opts["height"] * self.size_ratio
        for class_key in ['class', 'classes']:
            if key_exists(class_key):
                if isinstance(opts[class_key], str):
                    # A string.
                    overrides["class"] = [
                        *defaults['class'],
                        *opts[class_key].split(),
                    ]
                else:
                    # An iterable of some sort.
                    overrides["class"] = [
                        *defaults['class'],
                        *opts[class_key],
                    ]
                # Remove it so that `classes` doesn't get output into the html
                del opts[class_key]
        if key_exists('aria-label'):
            overrides["aria-label"] = opts["aria-label"]
            overrides["role"] = "img"
            # Un-hide the icon
            del defaults["aria-hidden"]
        out_attrs = dict(defaults)
        out_attrs.update(opts)
        out_attrs.update(overrides)
        return {
            key: value
            for key, value in out_attrs.items()
            # If we've defined custom rules on what is considered 'present'
            # Apply them here as well so that they're applied to all values
            if self.key_exists(out_attrs, key)
        }

    @property
    def size_ratio(self):
        return self.width / self.height

    @property
    def default_attrs(self):
        if self.viewBox:
            return {
                "version": "1.1",
                "width": self.width,
                "height": self.height,
                "viewBox": "%s" % (self.viewBox),
                "class": ["octicon", "octicon-" + self.name],
                "aria-hidden": "true"
            }
        return {
            "version": "1.1",
            "width": self.width,
            "height": self.height,
            "viewBox": "0 0 %s %s" % (self.width, self.height),
            "class": ["octicon", "octicon-" + self.name],
            "aria-hidden": "true"
        }

class OcticonStore():

    @classmethod
    def from_file(cls, file=None, additional_file=None):
        if file is None:
            file = pathlib.Path(__file__).parent / 'data.json'
        else:
            file = pathlib.Path(file)
        if additional_file:
            additional_file = pathlib.Path(additional_file)
            with file.open() as f, additional_file.open() as g:
                data = json.load(f)
                data.update(json.load(g))
                return cls(data)
        with file.open() as f:
                return cls(json.load(f))

    def __init__(self, data_dict, *, Octicon=Octicon):
        raw_icons = [
            Octicon(data)
            for data in data_dict.values()
        ]
        self.icons = dict([
            (icon.name, icon)
            for icon in raw_icons
        ] + [
            (keyword, icon)
            for icon in raw_icons
            for keyword in icon.keywords
        ])

    def get_icon(self, name):
        return self.icons[name]

    def __getitem__(self, name):
        return self.get_icon(name)

    def get_as_html(self, name, **opts):
        return self[name].as_html(**opts)


import unittest

from ..method import Method, method

from . import scratch

class MethodTest(unittest.TestCase):
    def _process(self, m):
        list(m.process(
            scratch, 'header',
            {'class_name': 'MethodTest'}))
        list(m.process(
            scratch, 'impl',
            {'class_name': 'MethodTest'}))

    def test_simple(self):
        '''Verify that it runs at all.'''
        m = Method('testMethod')
        self._process(m)

    def test_return_type(self):
        m = Method('testMethod', return_type='int')
        self._process(m)

    def test_signature(self):
        m = Method(
            'testMethod',
            signature=(('int', 'x'),
                       ('Widget', 'w')))
        self._process(m)

    def test_const(self):
        m = Method(
            'testMethod',
            const=True)
        self._process(m)

    def test_python_name(self):
        m = Method(
            'testMethod',
            python_name='wombat')
        self._process(m)

    def test_virtual(self):
        m = Method(
            'testMethod',
            virtual=True)
        self._process(m)

    def test_method(self):
        m = method('virtual int foo() const')
        self._process(m)

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


# Line tracking - By: chenxiao - 周二 6月 7 2022

# In atio 1, task 1, use openmv to do line tracking

import sensor, image, time, math
import ustruct
from pid import PID
from pyb import UART

theta_pid = PID(p=0.45, i=0.2)
# initializes the PI controller and envalues the parameters

GRAYSCALE_THRESHOLD = [(128, 255)]
sensor.reset() # resets and initializes the sensor.
sensor.set_pixformat(sensor.RGB565) # sets pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA) # sets frame size to QVGA (320x240)
sensor.skip_frames(time = 2000) # waits for settings take effect.
clock = time.clock() # creates a clock object to track the FPS.

# set uart
uart = UART(3, 9600)
uart.init(9600,bits=8,parity=None,stop=1)

ROIS = [
(10, 50, 300, 30 ,0.15),
(10, 100, 300, 30, 0.15),
(10, 150, 300, 30, 0.3),
(10, 200, 300, 30, 0.4)
]
# defines four regions of interest

weight_sum = 0 # initializes weight values
for r in ROIS: weight_sum += r[4] # defines calculation for weigted

thresh=[(30, 79, -7, 30, 6, 23)]
clock.tick() # initiates timer

while(True):
    # updates the FPS clock.
    img = sensor.snapshot() # takes a picture and return the image
   # img.rotation_corr(z_rotation=180) # rectify the image because it is shot upside down
    img = img.to_grayscale() # converts to grayscale image
    img = img.find_edges(image.EDGE_CANNY, threshold=(140, 140))
    # one−step realization of Canny detection
    img = img.dilate(1)
    # makes white spots more present

    centroid_sum = 0
    # initializes the weighted distance from centroids to the central line
    for r in ROIS: # for each centroid of ROI
        blobs = img.find_blobs(GRAYSCALE_THRESHOLD , roi=r[0:4], merge=True)
        # r[0:4] is roi tuple.
        # finds all white spots and merge as one (connecting each other with lines)

        # searching for lines in ROI
        if blobs:
            # indentifies the bolb index with the most lines
            largest_blob = 0
            most_pixels = 0
            for i in range(len(blobs)):
            # there might be several line clusters in ROI, but identify the larges as the target line
                if blobs[i].pixels() > most_pixels:
                    most_pixels = blobs[i].pixels()
                    # update the value if there is any larger pixel clusters
                    largest_blob = i

            img.draw_rectangle(blobs[largest_blob].rect(),color = 0)
            # draws a rectangle around the largest pixel cluster
            img.draw_cross(blobs[largest_blob].cx(), blobs[largest_blob].cy(),color = 0)
            # marks the largest pixel cluster with a white cross

            centroid_sum += blobs[largest_blob].cx() *r[4]
            # accumulates the weighted distances to obtain the final result

    center_pos = (centroid_sum / weight_sum) # determines the center of line

    # converts the result above to an angle, using unlinear operations
    deflection_angle = 0
    # initializes the angle to turn for the robot
    deflection_angle = - math.atan((center_pos -160)/60)
    # obtains the result (in radian)
    deflection_angle = math.degrees(deflection_angle)
    # converts result to degrees

    output = theta_pid.get_pid(deflection_angle ,1)

    # generate instructions in different level
    if output<-4: # turn right
        if output>-10:
            sign = '4'
        elif output>-15:
            sign = '5'
        else:
            sign = '6'

    elif output>4: # turn left
        if output<10:
            sign = '3'
        elif output<15:
            sign = '2'
        else:
            sign = '1'
    else: # go straight
        sign = '0'
    #sign = str(sign)

    sign='1'
    print(sign)
    # write data and send
    uart.write(sign)


from django.db import models

class Event(models.Model):
    id = models.PositiveIntegerField(primary_key=True)
    name = models.CharField(max_length=255)
    image = models.CharField(max_length=9999)
    long = models.FloatField(blank=False)
    lat = models.FloatField(blank=False)
    address = models.CharField(max_length=255)
    start = models.DateTimeField(auto_now=False, auto_now_add=False)
    end = models.DateTimeField(auto_now=False, auto_now_add=False)
    keywords = models.CharField(max_length=255)
    prices = models.CharField(max_length=255)
    max = models.CharField(max_length=255)
    tickets_amount = models.CharField(max_length=255)
    desc = models.CharField(max_length=9999)

    def images_as_list(self):
        return self.image.split(',')

    def keywords_as_list(self):
        return self.keywords.split(',')

    def desc_paragraphs(self):
        return self.desc.split('<br>')

    def price_range(self):
        Dict = dict((x.strip(), y.strip())
        for x, y in (element.split(':')
        for element in self.prices.split(',')))
        vals = Dict.values()
        priceInt = []
        for val in vals:
            priceInt.append(int(val))
        if max(priceInt) != min(priceInt):
            ma = '{:,}'.format(max(priceInt)).replace(',', '.')
            mi = '{:,}'.format(min(priceInt)).replace(',', '.')
            return '{} - {}'.format(mi, ma)
        ma = '{:,}'.format(max(priceInt)).replace(',', '.')
        return ma

    def tickets_left(self):
        sold = dict((x.strip(), y.strip())
        for x, y in (element.split(':')
        for element in self.tickets_amount.split(',')))
        soldInt = []
        for val in sold.values():
            soldInt.append(int(val))

        maxT = dict((x.strip(), y.strip())
        for x, y in (element.split(':')
        for element in self.max.split(',')))
        maxInt = []
        for val in maxT.values():
            maxInt.append(int(val))

        left = []
        for i in range(len(sold.values())):
            left.append(maxInt[i] - soldInt[i])
        re = sum(left)
        if sum(left) < 1000:
            return re
        return '{:,}'.format(sum(left)).replace(',', '.')

    def total_tickets(self):
        t = dict((x.strip(), y.strip())
        for x, y in (element.split(':')
        for element in self.max.split(',')))
        totInt = []
        for val in t.values():
            totInt.append(int(val))
        if sum(totInt) < 1000:
            return sum(totInt)
        return '{:,}'.format(sum(totInt)).replace(',', '.')


from flask import Flask
from flask_pymongo import PyMongo
from config import Config
from dotenv import load_dotenv
import os

app = Flask(__name__)

load_dotenv()

#select environment variables and configure db

if os.getenv('ENV') == 'dev':
    print('Running in development Mode')
    app.config["MONGO_URI"] = Config.MONGO_URI_DEV
elif os.getenv('ENV') == 'prod':
    print('Running in production Mode')
    app.config["MONGO_URI"] = Config.MONGO_URI_PROD

elif os.getenv('ENV') == 'test':
    print('Running in test Mode')
    app.config["MONGO_URI"] = Config.MONGO_URI_TEST
else:
    print("No environment variable set. Please set ENV to 'dev' or 'prod'")
    exit()

mongo = PyMongo(app)

from backend_api import routes


import graphene

from django.core.exceptions import NON_FIELD_ERRORS
from graphql_jwt.decorators import login_required
from internalapi.definitions.campaign import Campaign
from campaign.models.campaign import Campaign as DjangoCampaign

class LeaveCampaignInput(graphene.InputObjectType):
    room_code = graphene.String(required=True)

class LeaveCampaignFieldName(graphene.Enum):
    ROOM_CODE = 'room_code'

class LeaveCampaignInvalidField(graphene.ObjectType):
    field_name = graphene.Field(LeaveCampaignFieldName, required=True)
    errors = graphene.List(graphene.NonNull(graphene.String), required=True)

class LeaveCampaignError(graphene.ObjectType):
    non_field_errors = graphene.List(graphene.NonNull(graphene.String), required=True)
    field_errors = graphene.List(
        graphene.NonNull(LeaveCampaignInvalidField), required=True
    )

class LeaveCampaignSuccess(graphene.ObjectType):
    message = graphene.String(required=True)

class LeaveCampaignPayload(graphene.Union):
    class Meta:
        types = (LeaveCampaignError, LeaveCampaignSuccess)

class LeaveCampaign(graphene.Mutation):
    class Arguments:
        input_data = LeaveCampaignInput(required=True, name="input")

    Output = graphene.NonNull(LeaveCampaignPayload)

    @login_required
    def mutate(self, info, input_data):

        campaign = DjangoCampaign.objects.get(room_code=input_data.room_code)
        if campaign:
            info.context.user.campaigns.remove(campaign)

            #if owner then delete campagin - create owner field as its not always created_by
            if campaign.owner == info.context.user:
                campaign.delete()

            elif campaign.user_set.count()<1:
                campaign.delete()

            return LeaveCampaignSuccess(message="success")
        print("fail")
        # field_errors = []
        # non_field_errors = []
        # for field, errors in form.errors.items():
        #     if field == NON_FIELD_ERRORS:
        #         non_field_errors.extend(errors)
        #         continue
        #     field_name = LeaveCampaignFieldName.get(field)
        #     field_errors.append(
        #         LeaveCampaignInvalidField(field_name=field_name.value, errors=errors)
        #     )

        # return LeaveCampaignError(
        #     non_field_errors=non_field_errors, field_errors=field_errors
        # )


__author__ = 'BrianAguirre'

import unittest
from hw2_set import OurSet

class MySetTest(unittest.TestCase):

    def union_test(self, set1, set2):
        test_obj = OurSet()
        set1 = test_obj
        test_obj1 = OurSet()
        set2 = test_obj1

        item = 1
        assert (test_obj.add(item) == True)
    def intersection_test(self, set1, set2):
        test_obj = OurSet()
        set1 = test_obj
        test_obj1 = OurSet()
        set2 = test_obj1

        item = 1
        assert (test_obj.add(item) == True)

if __name__ == "__main__":
    test1 = OurSet()
    test2 = OurSet()
    unit_test = MySetTest()

    unit_test.intersection_test(test1, test2)
    unit_test.union_test(test1,test2)


# -*- coding: utf-8 -*-
from openerp import models, fields, api, tools

class LoanCustomerAgreementView(models.Model):
    _name = 'loan.customer.agreement.view'
    _auto = False

    id = fields.Integer(
        string='ID',
        readonly=True,
    )
    loan_agreement_id = fields.Many2one(
        'loan.customer.agreement',
        string='Loan Agreement',
        readonly=True,
    )
    invoice_id = fields.Many2one(
        'account.invoice',
        string='Invoice',
        readonly=True,
    )

    def _get_sql_view(self):
        sql_view = """
            SELECT ROW_NUMBER() OVER(ORDER BY lca.id, inv.id) AS id,
                   lca.id AS loan_agreement_id,
                   inv.id AS invoice_id
            FROM loan_customer_agreement lca
            LEFT JOIN account_invoice inv ON lca.id = inv.loan_agreement_id
        """
        return sql_view

    def init(self, cr):
        tools.drop_view_if_exists(cr, self._table)
        cr.execute("""CREATE OR REPLACE VIEW %s AS (%s)"""
                   % (self._table, self._get_sql_view()))

class XLSXReportCDReceivableBalanceSheetSummary(models.TransientModel):
    _name = 'xlsx.report.cd.receivable.balance.sheet.summary'
    _inherit = 'report.account.common'

    partner_ids = fields.Many2many(
        'res.partner',
        'cd_receivable_balance_sheet_summary_partner_rel',
        'report_id', 'partner_id',
        string='Customers',
    )
    mou_ids = fields.Many2many(
        'loan.bank.mou',
        'cd_receivable_balance_sheet_summary_mou_rel',
        'report_id', 'mou_id',
        string='MOU',
    )
    account_ids = fields.Many2many(
        'account.account',
        'cd_receivable_balance_sheet_summary_account_rel',
        'report_id', 'account_id',
        string='Accounts',
        default=lambda self: self.env['account.account'].search(
            [('code', '=', '1190019900')]),
        readonly=True,
    )
    results = fields.One2many(
        'cd.receivable.balance.sheet.summary',
        'wizard_id',
        string='Balance Sheet Summary Results',
    )

    @api.multi
    def get_dom_loan_agreement(self):
        dom = [('state', 'in', ('bank_paid', 'done')),
               ('sale_id.state', 'in', ('progress', 'done'))]
        if self.partner_ids:
            dom += [('borrower_partner_id', 'in', self.partner_ids.ids)]
        if self.mou_ids:
            dom += [('mou_id', 'in', self.mou_ids.ids)]
        if self.account_ids:
            dom += [('account_receivable_id', 'in', self.account_ids.ids)]
        return dom

    @api.multi
    def get_dom_brought_forward(self, loan_agreements):
        Fiscalyear = self.env['account.fiscalyear']
        date_start = \
            Fiscalyear.search([], order="date_start", limit=1).date_start
        if self.fiscalyear_start_id:
            date_start = self.fiscalyear_start_id.date_start
        if self.period_start_id:
            date_start = self.period_start_id.date_start
        if self.date_start:
            date_start = self.date_start
        dom = [('loan_agreement_id', 'in', loan_agreements.ids),
               ('invoice_id.state', '=', 'paid'),
               ('invoice_id.date_due', '<', date_start)]
        return dom

    @api.multi
    def get_dom_common_invoice(self, loan_agreements):
        Fiscalyear = self.env['account.fiscalyear']
        date_start = \
            Fiscalyear.search([], order="date_start", limit=1).date_start
        date_end = \
            Fiscalyear.search([], order="date_stop desc", limit=1).date_stop
        if self.fiscalyear_start_id:
            date_start = self.fiscalyear_start_id.date_start
        if self.fiscalyear_end_id:
            date_end = self.fiscalyear_end_id.date_stop
        if self.period_start_id:
            date_start = self.period_start_id.date_start
        if self.period_end_id:
            date_end = self.period_end_id.date_stop
        if self.date_start:
            date_start = self.date_start
        if self.date_end:
            date_end = self.date_end
        dom = [('loan_agreement_id', 'in', loan_agreements.ids),
               ('invoice_id.state', '=', 'paid'),
               ('invoice_id.date_due', '>=', date_start),
               ('invoice_id.date_due', '<=', date_end)]
        return dom

    @api.multi
    def get_dom_supplier_payment(self, loan_agreements):
        dom = self.get_dom_common_invoice(loan_agreements)
        return dom + [('invoice_id.type', '=', 'in_invoice')]

    @api.multi
    def get_dom_customer_invoice(self, loan_agreement):
        dom = self.get_dom_common_invoice(loan_agreement)
        return dom + [('invoice_id.type', '=', 'out_invoice')]

    @api.multi
    def get_loan_agreements(self):
        LoanAgreement = self.env['loan.customer.agreement']
        dom = self.get_dom_loan_agreement()
        loan_agreements = LoanAgreement.search(dom)
        return loan_agreements

    @api.multi
    def get_brought_forwards(self, loan_agreements):
        LoanAgreementView = self.env['loan.customer.agreement.view']
        dom = self.get_dom_brought_forward(loan_agreements)
        brought_forwards = LoanAgreementView.search(dom)
        return brought_forwards

    @api.multi
    def get_supplier_payments(self, loan_agreements):
        LoanAgreementView = self.env['loan.customer.agreement.view']
        dom = self.get_dom_supplier_payment(loan_agreements)
        supplier_payments = LoanAgreementView.search(dom)
        return supplier_payments

    @api.multi
    def get_customer_invoices(self, loan_agreements):
        LoanAgreementView = self.env['loan.customer.agreement.view']
        dom = self.get_dom_customer_invoice(loan_agreements)
        customer_invoices = LoanAgreementView.search(dom)
        return customer_invoices

    @api.multi
    def get_execute_datas(self, loan_agreements, brought_forwards,
                          supplier_payments, customer_invoices):
        # Set loan agreement ids
        loan_agreement_ids = loan_agreements.ids
        if len(loan_agreement_ids) in [0, 1]:
            loan_agreement_ids.extend([0, 0])
        # Set brought forward ids
        brought_forward_ids = brought_forwards.ids
        if len(brought_forward_ids) in [0, 1]:
            brought_forward_ids.extend([0, 0])
        # Set supplier payment ids
        supplier_payment_ids = supplier_payments.ids
        if len(supplier_payment_ids) in [0, 1]:
            supplier_payment_ids.extend([0, 0])
        # Set customer invoice ids
        customer_invoice_ids = customer_invoices.ids
        if len(customer_invoice_ids) in [0, 1]:
            customer_invoice_ids.extend([0, 0])
        self._cr.execute("""
            SELECT lca.id AS loan_agreement_id, bf.brought_forward,
                   sp.loan, ci.received
            FROM loan_customer_agreement lca
            LEFT JOIN (SELECT lcav.loan_agreement_id,
                              SUM(CASE WHEN inv.type = 'in_invoice' THEN
                                  inv.amount_total ELSE (-1) * inv.amount_total
                                  END) AS brought_forward
                       FROM loan_customer_agreement_view lcav
                       LEFT JOIN account_invoice inv ON
                        lcav.invoice_id = inv.id
                       WHERE lcav.id IN %s
                       GROUP BY lcav.loan_agreement_id) bf
                ON lca.id = bf.loan_agreement_id
            LEFT JOIN (SELECT lcav.loan_agreement_id, SUM(av.amount) AS loan
                       FROM loan_customer_agreement_view lcav
                       LEFT JOIN account_voucher_line avl
                        ON lcav.invoice_id = avl.invoice_id
                       LEFT JOIN account_voucher av ON avl.voucher_id = av.id
                       WHERE lcav.id IN %s AND av.state = 'posted'
                       GROUP BY lcav.loan_agreement_id) sp
                ON lca.id = sp.loan_agreement_id
            LEFT JOIN (SELECT lcav.loan_agreement_id,
                              SUM(inv.amount_total) AS received
                       FROM loan_customer_agreement_view lcav
                       LEFT JOIN account_invoice inv ON
                        lcav.invoice_id = inv.id
                       WHERE lcav.id IN %s
                       GROUP BY lcav.loan_agreement_id) ci ON
                        lca.id = ci.loan_agreement_id
            WHERE lca.id IN %s
            ORDER BY lca.borrower_partner_id, lca.id
        """ % (str(tuple(map(int, brought_forward_ids))),
               str(tuple(map(int, supplier_payment_ids))),
               str(tuple(map(int, customer_invoice_ids))),
               str(tuple(loan_agreement_ids))))
        return self._cr.fetchall()

    @api.multi
    def prepare_cd_receivable_balance_sheet_summary(self, datas):
        LoanAgreement = self.env['loan.customer.agreement']
        lines = []
        for rec in datas:
            # Not have brought forward, loan and received
            if not (rec[1] or rec[2] or rec[3]):
                continue
            # --
            loan_agreement = LoanAgreement.browse(rec[0])
            lines.append((0, 0, {
                'loan_agreement_id': loan_agreement.id,
                'brought_forward': rec[1],
                'loan': rec[2],
                'received': rec[3],
                'outstanding': (rec[1] or 0) + (rec[2] or 0) - (rec[3] or 0),
            }))
        return lines

    @api.multi
    def create_cd_receivable_balance_sheet_summary(self):
        # Get loan agreements
        loan_agreements = self.get_loan_agreements()

        # Get brought forwards
        brought_forwards = self.get_brought_forwards(loan_agreements)

        # Get supplier payments
        supplier_payments = self.get_supplier_payments(loan_agreements)

        # Get customer invoices
        customer_invoices = self.get_customer_invoices(loan_agreements)

        # Get execute datas
        datas = self.get_execute_datas(
            loan_agreements, brought_forwards, supplier_payments,
            customer_invoices)

        # Prepare cd receivable balance sheet summary
        lines = self.prepare_cd_receivable_balance_sheet_summary(datas)

        # Write data
        self.write({'results': lines})
        return True

    @api.multi
    def action_get_report(self):
        self.create_cd_receivable_balance_sheet_summary()
        res = super(XLSXReportCDReceivableBalanceSheetSummary, self) \
            .action_get_report()
        return res

class CDReceivableBalanceSheetSummary(models.TransientModel):
    _name = 'cd.receivable.balance.sheet.summary'
    _order = 'id'

    loan_agreement_id = fields.Many2one(
        'loan.customer.agreement',
        string='Loan Agreement',
    )
    brought_forward = fields.Float(
        string='Brought Forward',
    )
    loan = fields.Float(
        string='Loan',
    )
    received = fields.Float(
        string='Received',
    )
    outstanding = fields.Float(
        string='Outstanding',
    )
    wizard_id = fields.Many2one(
        'xlsx.report.cd.receivable.balance.sheet.summary',
        string='CD Receivable Balance Sheet Summary Wizard',
    )


import time
import datetime
# a python test of Big O calculations for Week 6

n = 100
cnt = 0

# Q1 - compute the tightest Big ) running time bound of the following...
def timer(start):
	print("\tTime for this process: ",(time.time()-start))
	print("\tn = ", n)

def banner(s):
	print("-"*70)
	print(s)
	print("-"*70)

def q1():
	banner("Question 1 - 2 for-i in range; j in range")
	start = time.time()
	for i in range(n):
		for j in range(n^2):
			x = i + j  #print(i + j)
	timer(start)
	print("\t i iterations = ",i)

def q2():
	banner("Question 2 - while j < i")
	i = n
	j = 1
	start = time.time()
	while j < i:
		i *= 100
		j *= 101
		# print("\t", i + j)

	timer(start)
	print("\t j iterations = ",j)

def q3():
	banner("Question 3 - while and for")
	i = 0
	j = 1
	start = time.time()
	while i < n:
		for k in range(j):
			i += 1
		j *= 2
	timer(start)
	print("\t i iterations = ",i)

def q4(i):
	start = time.time()
	cnt = 0
	if i < 1:
		cnt += 1
		return 1
	else:
		cnt += 1
		return q4(i-1) + q4(i-1)
	print(q4(n))
	timer(start)
	print("\ncount [constant] ", cnt)

banner("Starting Big-O tests")
q1()
q2()
q3()
q4(n)

banner("All Done.")


dataset = {
    "action" : ["matrix","batman","superman","dabang","avengers","thor",
                "hulk","krrish","ironman",'kgf'],
    "comedy" : ["the mask","dhamaal","bala","housefull","golmaal",
                "hera pheri","golmaal 2","dhamaal 2","hera pheri 2"],
    "drama" : ["dabang","krrish","hera pheri","bala","kahani","batla house",
               "kgf","zero","sultan"],
    "thriller" : ["kahani","kgf","batla house","madras cafe","uri",
                  "raw","lucy","the ring","oculus"],
    "horror" : ["oculus","the ring","it","the ring 2","evil dead",
                "conjuring","conjuring 2","bhootnath","aatma"]
}

user_1 = {"kgf", "zero", "superman", "batman", "evil dead", "sultan",
          "golmaal", "krrish", "bala"}

user_2 = {"kgf", "zero", "superman", "batman", "evil dead", "sultan",
          "golmaal", "krrish", "bala"}


import random, vk_api
from vk_api.keyboard import VkKeyboard

def init(v):
    global vk
    vk = v

def say(man, text, response):
    try:
        string = '___________________\n'
        string += f'  | сообщение от {response[0]["first_name"]} {response[0]["last_name"]}\n\|/\n'

        string += text + '\n/|\ \n  | конец\n___________________'
        write_msg(man, string)
    except:
        return False
    return True

def write_msg(user_id, message, attachment='', keyboard=None):
    vk.messages.send(user_id=user_id,
                     message=message,
                     random_id=random.randint(0, 2 ** 64),
                     attachment=attachment,
                     keyboard=create_keyboard())

def create_keyboard():
    keyboard = vk_api.keyboard.VkKeyboard(one_time=False)
    keyboard.add_button("ответы")
    keyboard.add_button("добавить ответ")
    keyboard.add_line()
    keyboard.add_button("help")
    keyboard.add_button("Описание")
    keyboard.add_line()
    keyboard.add_button("расписание на сегодня")

    return keyboard.get_keyboard()


from .trace_tx import trace_tx_tron
from .lookup_details import lookup_details_tron
from .transforms import columns

import os
import pandas

def trace_txs_tron(tronObj,txs,layerNum=3,traceType='From',ignoreAmount=1,traceLimit=10000,storeEachLayer=False,storePath='tmp//',debugMode=False):
    if 'Layer' in txs.columns and 'TxNo' in txs.columns:
        traceResults = txs[columns+['Layer','TxNo']].copy()
        layerCount = int(txs['Layer'].max())
    else:
        traceResults = txs[columns].copy()
        traceResults['Layer'] = 0
        traceResults['TxNo'] = [f'{i+1}' for i in range(len(traceResults))]
        layerCount = 0

    if storeEachLayer and not os.path.exists(storePath):
        os.makedirs(storePath)

    while layerCount < layerNum:
        print(f'Tracing Layer {layerCount}...')
        toTrace = traceResults[traceResults['Layer'] == layerCount]
        toTrace = toTrace.reset_index(drop=True)

        layerCount += 1
        # 追查internal交易會導致同一筆txid可能會有兩筆以上不同的交易內容
        # 追查相同錢包也會導致同一筆txid有兩筆以上相同的交易內容
        for i,(txid,grouped) in enumerate(toTrace.groupby(by=['TxID'])):
            grouped = grouped.drop_duplicates(subset=['From','To','Contract','Value'])
            row = grouped.iloc[-1] #追查最後一筆
            addrInfo = tronObj.get_account_info(row[traceType])
            addrType = ''
            if addrInfo['accountType'] == 0:
                addrType = 'Account'
            elif addrInfo['accountType'] == 2:
                addrType = 'Contract'
            if addrInfo.get('addressTag') is None:
                addrInfo['addressTag'] = ''
            # 交易所
            if addrType == 'Account' and len(addrInfo['addressTag']) > 0:
                print('***交易所***',addrType,row[traceType])
                continue
            if addrType == 'Contract':
                print('***智能合約***',addrType,row[traceType])
                lookups = lookup_details_tron(tronObj,row)
                lookups.loc[lookups['Token']=='TRX','Contract'] = 'trc10'
                if traceType == 'From':
                    lookup_trace = lookups.iloc[0]
                else:
                    lookup_trace = lookups.iloc[-1]
                if debugMode:
                    print(lookup_trace)
                traceResults = pandas.concat([traceResults,lookups])
                res = trace_tx_tron(tronObj,lookup_trace,traceType=traceType,
                                             traceLimit=traceLimit,traceTolerance=ignoreAmount,debugMode=debugMode)
            else:
                res = trace_tx_tron(tronObj,row,traceType=traceType,
                                             traceLimit=traceLimit,traceTolerance=ignoreAmount,debugMode=debugMode)
            print(f">第{layerCount}層-第{i+1}筆:{row[traceType]};追蹤結果:{len(res[res['Value']>=ignoreAmount])}/{len(res)}筆")
            if len(res) == 0:
                continue

            res = res[res['Value'] >= ignoreAmount]
            res.loc[:,['Layer']] = [layerCount for _ in range(len(res))]
            ## 因為internal交易所以相同的txid可能會有多筆，就必須用去除重複的交易序號來編號
            txids = res['TxID'].drop_duplicates().tolist()
            res.loc[:,['TxNo']] = res['TxID'].apply(lambda txid: f"{row['TxNo']}_{txids.index(txid)+1}")
            #print(res)
            traceResults = pandas.concat([traceResults,res])

        if storeEachLayer:
            traced = traceResults[traceResults['Layer'] == layerCount]
            traced.to_excel(f'{storePath}layer{layerCount}.xlsx',index=False)

    return traceResults


from __future__ import unicode_literals, print_function, division

import io
import os
import tempfile

from dbmp.utils import ASSETS, exe

FIO_DEFAULT = os.path.join(ASSETS, 'fiotemplate.fio')

def gen_fio(fiofile, dev_or_folders):
    fio = _setup(fiofile, dev_or_folders)
    with tempfile.NamedTemporaryFile(delete=False) as tf:
        tf.write(fio)
        tf.flush()
        print()
        print("Generating FIO job: {}".format(tf.name))
        print("------------------")
        print(fio)

def run_fio_from_file(fiofile):
    print("Running FIO job")
    print(fiofile)
    exe("sudo fio {}".format(fiofile))

def _setup(fiofile, dev_or_folders):
    fiobase = None
    if not fiofile:
        fiofile = FIO_DEFAULT
    with io.open(fiofile, 'r') as f:
        fiobase = f.readlines()
    found_size = False
    for line in fiobase:
        if 'size' in line:
            found_size = True
            break
    if not found_size:
        fiobase.append('size=1G')
    for df in dev_or_folders:
        fiobase.append('[fio-job]')
        _add_directory(fiobase, df)
    return '\n'.join((elem.strip() for elem in fiobase)) + '\n'

def _add_directory(fiobase, folder):
    if '/dev' in folder:
        fiobase.append('filename=/{}'.format(folder.strip('/')))
    else:
        fiobase.append('directory=/{}'.format(folder.strip('/')))


input_nome = input('Enter a file name: ')
handle = open(input_nome)
value = 0
dicionario = dict()

for lines in handle :
    lines = lines.rstrip()
    words = lines.split()
    for word in words :
        value = value + 1
        dicionario[word] = value
print(dicionario)


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   插入排序.py
@Time    :   2020/03/27 12:55:48
@Author  :   望
@Version :   1.0
@Contact :   2521664384@qq.com
@Desc    :   None
'''

# here put the import lib
'''
 插入排序，其原理是通过构建一个初始的有序序列，然后从无需序列中抽取元素，插入到有序序列的相对排序位置，就像将一堆编号混乱的书，一本一本的放到书架上，找到上下编号之间的位置插入，最后完成整理。
'''
def insert_sort(items):
    for i in range(1, len(items)):
        # 从第i个元素开始向前比较，如果小于前一个元素，交换位置
        for j in range(i, 0, -1):
            if items[j] < items[j-1]:
                items[j], items[j-1] = items[j-1], items[j]
    return items