print ("Solving Ax = b")
n = input("Enter size of matrix A")
A = list()
for i in range(n):
    A.append(list())
for i in A:
    for j in range(n):
        i.append(input())
print ("now enter values of b")
b = list()
for i in range(n):
    b.append(input())

print ("matrix afzoode is : ")

j =0
for i in A:
        i.append(b[j])
        j+=1
        print (i)
j=0
i=0
while j < n:
    i = j
    while i < n:
        if (A[i])[j] != 0:
            A[i] , A[j] = A[j] , A[i]
            print ("how u doin ? : ",(A[j]),A[i])
            break
        i+=1
    i=j+1
    while i < n:
        if (A[i])[j] != 0:
            reduce = float(float((A[i])[j])/(float((A[j])[j])))
            m=0
            while m <= n:
                A[i][m] -= reduce*(A[j])[m]
                m+=1
        i+=1
    j+=1
j=n-1
while j>=0:
    if (A[j])[j] != 1 and (A[j])[j] != 0:
        m=j+1
        while m <=n:
            A[j][m] =float (float (A[j][m]) /float (A[j][j]))
            m+=1
        A[j][j] = 1
    j-=1

print (A)
j=n-2
while j>=0:
    if (A[j])[j+1] != 0 and (A[j+1][j+1]) != 0:
        m=j+1
        reduce = float (A[j][j+1]) /float (A[j+1][j+1])
        while m <=n:
            A[j][m] -=float ( reduce* float (A[j+1][m]))
            m+=1
    j-=1
print (A)
answerNum = 1

answer = list()
if A[n-1][n-1] == 0:
    if A[n-1][n] != 0:
        answerNum = 0
    else:
        answerNum = 2
if answerNum == 0:
    print ("doesn't have answer!")
elif answerNum == 1:
    j=0
    while j<n:
        answer.append(A[j][n])
        j+=1
else:
    j=0
    while j<n:
        i=j+1
        answer.append("")
        if A[j][j] == 0:
            answer[j]+= "x" + str(j+1)
            j+=1
            continue
        while i<n:
            answer[j] +="(" +str(-A[j][i])+"x"+str(i+1) + ")+"
            i+=1
        answer[j] += str(A[j][n])
        j+=1
print ("answer : ",answer)


"""Constants used by the Netatmo component."""

DOMAIN = "enertalk"
MANUFACTURER = "EnerTalk"

REAL_TIME_MON_COND = {
    'real_time_usage': ['Real Time', 'Usage', 'W', 'mdi:pulse']
}
BILLING_MON_COND = {
    'today_usage': ['Today', 'Usage', 'kWh', 'mdi:trending-up'],
    'today_charge': ['Today', 'Charge', '원', 'mdi:currency-krw'],
    'yesterday_usage': ['Yesterday', 'Usage', 'kWh', 'mdi:trending-up'],
    'yesterday_charge': ['Yesterday', 'Charge', '원', 'mdi:currency-krw'],
    'month_usage': ['Month', 'Usage', 'kWh', 'mdi:trending-up'],
    'month_charge': ['Month', 'Charge', '원', 'mdi:currency-krw'],
    'estimate_usage': ['Estimate', 'Usage', 'kWh', 'mdi:calendar-question'],
    'estimate_charge': ['Estimate', 'Charge', '원', 'mdi:currency-krw']
}
MONITORED_CONDITIONS = list(REAL_TIME_MON_COND.keys()) + \
                        list(BILLING_MON_COND.keys())

AUTH = "enertalk_auth"
CONF_REAL_TIME_INTERVAL = 'real_time_interval'
CONF_BILLING_INTERVAL = 'billing_interval'

OAUTH2_AUTHORIZE = "https://auth.enertalk.com/authorization"
OAUTH2_TOKEN = "https://auth.enertalk.com/token"
API_ENDPOINT = 'https://api2.enertalk.com'

DATA_CONF = "enertalk_conf"


#!/usr/bin/env python3
from collections import defaultdict
import time
import re
import os
import sys
import textwrap
import argparse
import urllib.request
import ssl
from urllib.error import HTTPError
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)

parser = argparse.ArgumentParser(
    prog="silva-survey.py",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description=textwrap.dedent('''
    Developed by Arkadiy Garber; University of Delaware, Geological Sciences
    Please send comments and inquiries to arkg@udel.edu
    '''))

parser.add_argument('-taxa', help='taxanomic affiliation of organism that you would like to investigate')
parser.add_argument('-silva_DB', help="location of SILVA database")
parser.add_argument('-out_dir', help="directory to which the output file will be written")

if len(sys.argv) == 1:
    parser.print_help(sys.stderr)
    sys.exit(0)

args = parser.parse_known_args()[0]

def replace(stringOrlist, list, item):
    emptyList = []
    for i in stringOrlist:
        if i not in list:
            emptyList.append(i)
        else:
            emptyList.append(item)
    outString = "".join(emptyList)
    return outString

def remove(stringOrlist, list):
    emptyList = []
    for i in stringOrlist:
        if i not in list:
            emptyList.append(i)
        else:
            pass
    outString = "".join(emptyList)
    return outString

def fasta(fasta_file):
    seq = ''
    header = ''
    Dict = defaultdict(lambda: defaultdict(lambda: 'EMPTY'))
    for i in fasta_file:
        i = i.rstrip()
        if re.match(r'^>', i):
            if len(seq) > 0:
                Dict[header] = seq
                header = i[1:]
                seq = ''
            else:
                header = i[1:]
                seq = ''
        else:
            seq += i
    Dict[header] = seq
    return Dict

silva = open(args.silva_DB, "r")
silva =fasta(silva)
outfile = open(args.out_dir + "/" + args.taxa + "_SILVA.csv", "w")
outfile.write(args.taxa + "_strain" + "," + "Source" + "," + "Reference" + "," + "16S_seq" + "\n")

for i in silva.keys():
    if re.findall(args.taxa, i):
        print(i)
        time.sleep(2)
        outfile.write(i + ",")
        id = i.split(" ")[0]
        id = id.split(".")[0]
        fp = urllib.request.urlopen("https://www.ebi.ac.uk/ena/data/view/%s&display=text" % id, context=gcontext)
        mybytes = fp.read()
        mystr = mybytes.decode("utf8")
        fp.close()
        lines = mystr.split('\n')
        string = ''
        count = 0
        ref = ''
        for j in lines:
            if re.findall(r'isolation_source', j) or re.findall(r'tissue_type', j) or \
                    re.findall(r'Source of Isolate', j):
                count += 1
                try:
                    string = j.split("\"")[1]
                    string = replace(string, [","], ";")
                except IndexError:
                    string = j
                    string = replace(j, [","], ";")
                count += 1
            if re.match(r'^RT', j) and len(j) > 6:
                ref += j
        if count == 0:
            outfile.write("No_data" + ",")
        else:
            outfile.write(replace(string, [","], ";") + ",")
        ref = (replace(ref, [","], ";"))
        ref = remove(ref, ["RT"])
        outfile.write(ref + ",")
        outfile.write(silva[i] + "\n")


#! /Users/robertpoenaru/.pyenv/shims/python

import numpy as np

class MOI:

    def __init__(self, I_0):
        self.I_0 = I_0
        # self.beta = beta
        # self.gamma = gamma

    # R0 = lambda A: 1.20 * np.power(A, 1.0 / 3.0)
    R0 = lambda A: 1.20

    def Hydro(self, gamma):
        c = 4.0 / 3.0 * self.I_0
        hydro = lambda k: np.power(np.sin(gamma + 2.0 * np.pi / 3.0 * k), 2)
        mois = [c * hydro(1), c * hydro(2), c * hydro(3)]
        return mois

    def Rigid(self, beta, gamma):
        c = self.I_0 / (1.0 + np.sqrt(5.0 / (16.0 * np.pi) * beta))
        rigid = lambda k: 1 - \
            np.sqrt(5.0 / (4.0 * np.pi)) * beta * \
            np.cos(gamma + 2.0 * np.pi * k / 3.0)
        mois = [c * rigid(1), c * rigid(2), c * rigid(3)]
        return mois

    @ staticmethod
    def Irr(A, m, beta, gamma):
        c = 3.0 / (2.0 * np.pi) * m * A * np.power(MOI.R0(A), 2)
        irr_k = lambda k: np.power(
            beta, 2) * np.power(np.sin(gamma - (2.0 * np.pi) / 3.0 * k))
        mois = [irr_k(1), irr_k(2), irr_k(3)]
        return c * mois

    @ staticmethod
    def Rig(A, m, beta, gamma):
        c = 2.0 / 5.0 * m * A * np.power(MOI.R0(A), 2)
        rig_k = lambda k: 1 - \
            np.sqrt(5.0 / (4.0 * np.pi)) * beta * \
            np.cos(gamma - (2 * np.pi) / 3.0 * k)
        mois = [rig_k(1), rig_k(2), rig_k(3)]
        return c * mois

    @ staticmethod
    def I_k(B_2, beta, gamma):
        c = 4.0 * B_2
        i_k = lambda k: np.power(beta, 2) * \
            np.sin(gamma - (2.0 * np.pi) / 3.0 * k)
        mois = [i_k(1), i_k(2), i_k(3)]
        return c * mois


# a dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

person = {
    "name": "John Doe",
    "age": 40,
    "nationality": "Kenyan",
    "occupation": "Student",
    "height": "1.69cm"
}

# print(person["height"])
# print(person.get("occupation"))

person["hobbies"] = "Hiking" # adding key-value pairs to a dictionary

del person["name"]

person["age"] = 28 #reassingment in dictionaries

# print(person.keys())
# print(person.values())

xtra_features = {"Sex": "man", "race": "Latino"}

person.update(xtra_features)
# print(person)

for property in person:
    if person[property] == "Hiking":
        print("You can hike!")

def personValue(value):
    for property in person:
        if person[property] == value:
            print("The value is", value)
        else:
            print("The value doesn't exist!")

personValue("kenya")


"""
:module: hard_core_unit_test
:platform: Unix, Windows, OS
:synopsis: unit test for HardCore

.. moduleauthor:: Alex Travesset <trvsst@ameslab.gov>, May2020
.. history:
..                Kevin Marin <marink2@tcnj.edu>, May2020
..                  - changes
"""
import numpy as np
import unittest
import aqpolypy.salts_theory.HardCore as hc

class TestHardCore(unittest.TestCase):

    def test_free_energy_hc_excess(self):
        # parameters in [[concentration of the different species (M)], ion size (A), free energy excess]
        param = np.array([[np.array([2.4, 2.4, 0.6]), 4, -0.00085523],
                          [np.array([2.4, 2.4, 0.6]), 6, -0.00493081],
                          [np.array([1.6, 1.6, 0.4]), 4, -0.00036299],
                          [np.array([1.6, 1.6, 0.4]), 6, -0.00159263],
                          [np.array([4.0, 4.0, 1.0]), 4, -0.00263848],
                          [np.array([4.8, 4.8, 1.2]), 4, -0.0040378]])

        obj_hc = hc.HardCore()
        for i in range(len(param)):
            free_energy = obj_hc.free_energy_hc_excess(param[i, 0], param[i, 1])
            # testing params up to a precision of 10^-8
            test = np.allclose(free_energy, param[i, 2], 0, 1e-8)
            self.assertTrue(test)

    def test_pot_chem_hc_excess(self):
        # parameters in [[concentration of the different species (M)], ion size (A), [pot chem excess]]
        param = np.array([[np.array([2.4, 2.4, 0.6]), 4, [0.53372128, 0.53372128, 0.80445306]],
                          [np.array([2.4, 2.4, 0.6]), 6, [4.71590808, 4.71590808, 7.91555483]],
                          [np.array([1.6, 1.6, 0.4]), 4, [0.33147242, 0.33147242, 0.49551186]],
                          [np.array([1.6, 1.6, 0.4]), 6, [1.71084249, 1.71084249, 2.68706435]],
                          [np.array([4.0, 4.0, 1.0]), 4, [1.05121781, 1.05121781, 1.61562475]],
                          [np.array([4.8, 4.8, 1.2]), 4, [1.39524554, 1.39524554, 2.1696644]]])

        obj_hc = hc.HardCore()
        for i in range(len(param)):
            for j in range (3):
                pot_chem = obj_hc.pot_chem_hc_excess(param[i, 0], param[i, 1])
                # testing params up to a precision of 10^-8
                test = np.allclose(pot_chem[j], param[i, 2][j], 0, 1e-8)
                self.assertTrue(test)

    def test_pressure_hc_excess(self):
        # parameters in [[concentration of the different species (M)], ion size (A), pressure excess]
        param = np.array([[np.array([2.4, 2.4, 0.6]), 4, 0.00423018],
                          [np.array([2.4, 2.4, 0.6]), 6, 0.01481318],
                          [np.array([1.6, 1.6, 0.4]), 4, 0.00256312],
                          [np.array([1.6, 1.6, 0.4]), 6, 0.00451955],
                          [np.array([4.0, 4.0, 1.0]), 4, 0.00881886],
                          [np.array([4.8, 4.8, 1.2]), 4, 0.01210029]])

        obj_hc = hc.HardCore()
        for i in range(len(param)):
            press = obj_hc.pressure_hc_excess(param[i, 0], param[i, 1])
            # testing params up to a precision of 10^-8
            test = np.allclose(press, param[i, 2], 0, 1e-8)
            self.assertTrue(test)


"""create accout table

Revision ID: 33e33f064c9f
Revises: 35a80b511eb7
Create Date: 2015-12-19 04:29:02.108568

"""

# revision identifiers, used by Alembic.
revision = '33e33f064c9f'
down_revision = '35a80b511eb7'

from alembic import op
import sqlalchemy as sa
from studio.core.sqla.types import JSONType

def upgrade():
    op.create_table('role',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('name', sa.String(length=80), nullable=False),
        sa.Column('description', sa.String(length=255), nullable=True),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('name')
    )
    op.create_table('account',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('nickname', sa.Unicode(length=256), nullable=True),
        sa.Column('email', sa.Unicode(length=1024), nullable=True),
        sa.Column('is_email_confirmed', sa.Boolean(), server_default='false', nullable=False),
        sa.Column('password', sa.String(length=128), nullable=False),
        sa.Column('info', JSONType(), nullable=True),
        sa.Column('date_created', sa.DateTime(timezone=True), server_default=sa.func.current_timestamp(), nullable=False),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_account_date_created'), 'account', ['date_created'], unique=False)
    op.create_index(op.f('ix_account_email'), 'account', ['email'], unique=False)
    op.create_table('roles_accounts',
    sa.Column('account_id', sa.Integer(), nullable=True),
    sa.Column('role_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['account_id'], [u'account.id'], ),
    sa.ForeignKeyConstraint(['role_id'], [u'role.id'], )
    )
    op.alter_column(u'staff', 'name',
                    existing_type=sa.VARCHAR(length=256),
                    nullable=False)
    op.alter_column(u'staff', 'synopsis',
                    existing_type=sa.TEXT(),
                    nullable=False)

def downgrade():
    op.alter_column(u'staff', 'synopsis',
                    existing_type=sa.TEXT(),
                    nullable=True)
    op.alter_column(u'staff', 'name',
                    existing_type=sa.VARCHAR(length=256),
                    nullable=True)
    op.drop_table('roles_accounts')
    op.drop_index(op.f('ix_account_email'), table_name='account')
    op.drop_index(op.f('ix_account_date_created'), table_name='account')
    op.drop_table('account')
    op.drop_table('role')


import sqlite3
from datetime import date

class Database:
    def __init__(self, mydb):
        self.con = sqlite3.connect(mydb)
        self.cur = self.con.cursor()
        qiu = """
        CREATE TABLE IF NOT EXISTS survey_px(
            id Integer Primary Key,
            EMR text,
            age text,
            gender text,
            ward text,
            cubicle text
        )
        """
        self.cur.execute(qiu)
        self.con.commit()

    # Insert Function
    def insert(self, emr, age_group, gender, ward, cubicle):
        self.cur.execute("insert into survey_px values (NULL,?,?,?,?,?)",
                         (emr, age_group, gender, ward, cubicle))
        self.con.commit()

    # Fetch All Data from DB
    def fetch(self):
        self.cur.execute("SELECT * from survey_px")
        rows = self.cur.fetchall()
        # print(rows)
        return rows

    # Delete a Record in DB
    def remove(self, id):
        self.cur.execute("delete from survey_px where id=?", (id,))
        self.con.commit()

    # Update a Record in DB
    def update(self, id, emr, age_group, gender, ward, cubicle):
        self.cur.execute(
            "update survey_px set emr=?, age=?, ward=?, gender=?, cubicle=?, where id=?",
            (emr, age_group, ward, gender, cubicle, id))
        self.con.commit()

    # Print a pdf
    def pdf_print(self, id):
        self.cur.execute("SELECT 'ward'||'cubicle' from survey_px, where id =?", (id, ))
        self.con.commit()

        # dcode = '''SELECT 'ward'||'cubicle' FROM survey_px'''
        # dcode = self.cur.execute(dcode)
        # dday = date.today()
        # dday = dday.strftime(format='%y%m%d')
        # d = dday+dcode


from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from food.models import Food
from order.models import OrderItem
from .cart import Cart
from .forms import CartAddProductForm, CartAddFromRecipeForm
from recipe_scrapers import scrape_me

# Create your views here.
@require_POST
def cart_add(request, food_id):
    cart = Cart(request)
    food = get_object_or_404(Food, id=food_id)
    form = CartAddProductForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        cart.add(food=food,
                 quantity=cd['quantity'],
                 update_quantity=cd['update'])
    return redirect('cart:cart_detail')

def cart_readd(request, order_id):
    cart = Cart(request)
    order_items = OrderItem.objects.filter(order_id = order_id)
    if len(order_items) > 0:
        for item in order_items:
            cart.add(food=item.food,
                    quantity=item.quantity)
    return redirect('cart:cart_detail')

"""
def cart_add_from_recipe(request, web_url):
    cart = Cart(request)
    scraper = scrape_me(web_url)
    ingredients = scraper.ingredients()
    for ing in ingredients:
        query = Food.objects.filter(name=ing)
        if len(query) > 0:
            food = get_object_or_404(Food,id=query[0].id)
            cart.add(food=food,quantity=1,update_quantity=false)
    return redirect('cart:cart_detail')
"""

def get_recipe_url(request):
    cart = Cart(request)
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],
                                                                   'update': True})

    if request.method == "POST":
        form = CartAddFromRecipeForm(request.POST)
        if form.is_valid():
            cart = Cart(request)
            cd = form.cleaned_data
            url = cd['recipe_url']
            scraper = scrape_me(url)
            ingredients = scraper.ingredients()
            print(ingredients)
            for ing in ingredients:
                words = ing.split(" ")
                for word in words:
                    query = Food.objects.filter(name=word)

                    if len(query) > 0:
                        cur_food = food=query[0]
                        cart.add(food=cur_food)

            return render(request,'cart/detail.html', { 'recipe_url_form':form })
    else:
        form = CartAddFromRecipeForm()

    return render(request,'cart/detail.html', { 'recipe_url_form':form })

def cart_remove(request, food_id):
    cart = Cart(request)
    food = get_object_or_404(Food, id=food_id)
    cart.remove(food)
    return redirect('cart:cart_detail')

def cart_clear(request):
    cart = Cart(request)
    cart.clear()
    return redirect('cart:cart_detail')

def cart_detail(request):
    cart = Cart(request)
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],
                                                                   'update': True})
    return render(request, 'cart/detail.html', {'cart': cart})


from typing import Any, Dict, List, Tuple
from pynput.keyboard import Key

from ui.definitions.interactible import Interactible, InteractionControl
from ui.definitions.position import Position
from ui.definitions.renderable import Renderable
from ui.definitions.utils import Utils

class Container(Interactible):
    def __init__(self, position: Position = None, configs: Dict[str, Any] = None, elements: List[Renderable] = None) -> None:
        super().__init__(position)

        self.__configs = configs if configs is not None else dict()

        if 'width' in self.__configs.keys():
            self.__configs['max-width'] = configs['width']
            self.__configs['min-width'] = configs['width']

        if 'height' in self.__configs.keys():
            self.__configs['max-height'] = configs['height']
            self.__configs['min-height'] = configs['height']

        default_configs = {
            'flex': 'column',
            'border': False,
            'max-width': None,
            'max-height': None,
            'min-width': None,
            'min-height': None,
            'vertical-align': 'start',
            'horizontal-align': 'start',
        }

        for config_key in default_configs.keys():
            if config_key not in self.__configs:
                self.__configs[config_key] = default_configs[config_key]

        self.__elements_depth_ordered = list() if elements is None else elements
        self.__elements_depth_ordered.sort(key=lambda e: e.get_position().depth)
        for element in self.__elements_depth_ordered:
            element.set_parent(self)

        self.__interacting_element = None

    def add_element(self, element: Renderable) -> Any:
        self.__elements_depth_ordered.append(element)
        self.__elements_depth_ordered.sort(key=lambda e: e.get_position().depth)
        element.set_parent(self)
        return self

    def __mod__(self, other):
        self.add_element(other)
        return self

    def render(self) -> List[str]:
        current_render = []

        for element in self.__elements_depth_ordered:
            current_render = self.__add_element_to_render(element, current_render)

        current_render = self.__pad_lines(current_render)
        current_render = self.__add_borders(current_render)
        return current_render

    def __pad_lines(self, current_render: List[str]) -> List[str]:
        # Pad all lines to get the same size
        expected_size = self.__get_render_sizes(current_render)
        width = expected_size[0]
        height = expected_size[1]

        min_width = self.__configs['min-width']
        if min_width is not None:
            width = max(width, min_width)

        max_width = self.__configs['max-width']
        if max_width is not None:
            if self.__configs['border']:
                max_width -= 2
            width = min(width, max_width)

        min_height = self.__configs['min-height']
        if min_height is not None:
            height = max(height, min_height)

        max_height = self.__configs['max-height']
        if max_height is not None:
            if self.__configs['border']:
                max_height -= 2
            height = min(height, max_height)

        vertical_align = self.__configs['vertical-align']
        horizontal_align = self.__configs['horizontal-align']

        vertical_base = max(0 if vertical_align != 'center' else (height - len(current_render)) // 2, 0)

        padded_render = list()
        for line_idx in range(0, height):
            if line_idx < vertical_base or line_idx - vertical_base >= len(current_render):
                padded_render.append(' ' * width)
                continue

            if line_idx >= len(padded_render):
                padded_render.append('')

            current_render_line_raw = current_render[line_idx - vertical_base]
            current_render_line = Utils.remove_escape_seqs(current_render_line_raw)
            horizontal_base = max(0 if horizontal_align != 'center' else (width - len(current_render_line)) // 2, 0)

            padded_render_line = ' ' * horizontal_base + current_render_line_raw
            padded_render_line += ' ' * (width - (horizontal_base + len(current_render_line)))
            padded_render[line_idx] = padded_render_line

        current_render = padded_render
        return current_render

    def __get_render_sizes(self, current_render: List[str]) -> Tuple[int, int]:
        if len(current_render) == 0:
            return (0, 0)

        max_row_len = max(map(lambda line: len(Utils.remove_escape_seqs(line)), current_render))
        return (max_row_len, len(current_render))

    def __add_borders(self, current_render: List[str]) -> List[str]:
        if self.__configs['border']:
            current_size = self.__get_render_sizes(current_render)
            up_down_borders = '―' * current_size[0]
            current_render.insert(0, up_down_borders)
            current_render.append(up_down_borders)

            for line_idx in range(0, len(current_render)):
                render_line = current_render[line_idx]

                if line_idx == 0:
                    render_line = '┌' + render_line + '┐'
                elif line_idx == len(current_render) - 1:
                    render_line = '└' + render_line + '┘'
                else:
                    render_line = '│' + render_line + '│'

                current_render[line_idx] = render_line

        return current_render

    def __add_element_to_render(self, element: Renderable, current_render: List[str]) -> List[str]:
        if self.__configs['flex'] == 'column':
            element.set_position(Position(len(current_render), element.get_position().col))
        if self.__configs['flex'] == 'row':
            max_col = max(map(lambda line: len(Utils.remove_escape_seqs(line)), current_render)) if len(current_render) > 0 else 0
            element.set_position(Position(element.get_position().row, max_col))

        element_rendered = element.render()
        element_position = element.get_position()

        # Bottom pad the current render with empty lines until
        # there are enough lines to put the element lines
        current_render += [''] * ((len(element_rendered) + element_position.row) - len(current_render))

        for line_idx in range(0, len(element_rendered)):
            element_rendered_line_raw = element_rendered[line_idx]
            element_rendered_line = Utils.remove_escape_seqs(element_rendered_line_raw)
            current_render_line = current_render[line_idx + element_position.row]

            # Right pad the current render with spaces until there is enough
            # space to put the element rendered line
            current_render_line += ' ' * ((len(element_rendered_line) + element_position.col) - len(current_render_line))

            current_render_line = Utils.replace_keeping_escape_seqs(current_render_line, element_rendered_line_raw, element_position.col)
            current_render[line_idx + element_position.row] = current_render_line

        return current_render

    def __get_next_element(self, direction: str):
        interactibles = list(filter(lambda e: Interactible.is_interactible(e), self.__elements_depth_ordered))

        if len(interactibles) == 0:
            return None

        if len(interactibles) == 1 and self.__interacting_element is not None:
            return None

        if self.__interacting_element is None:
            return interactibles[0]

        filtered: List[Interactible] = []
        current_row = self.__interacting_element.get_position().row
        current_col = self.__interacting_element.get_position().col

        if direction in ['up', 'down']:
            if direction == 'up':
                filtered = list(filter(lambda e: e.get_position().row < current_row, interactibles))
            else:
                filtered = list(filter(lambda e: e.get_position().row > current_row, interactibles))

            if len(filtered) == 0:
                return None

            filtered.sort(key=lambda e: abs(current_row - e.get_position().row))
            return filtered[0]
        elif direction in ['left', 'right']:
            if direction == 'left':
                filtered = list(filter(lambda e: e.get_position().col < current_col, interactibles))
            else:
                filtered = list(filter(lambda e: e.get_position().col > current_col, interactibles))

            if len(filtered) == 0:
                return None

            filtered.sort(key=lambda e: abs(current_col - e.get_position().col))
            return filtered[0]

        return None

    def handle_key(self, key: Key, control: InteractionControl):
        next_element: Interactible = None

        if key == Key.up:
            next_element = self.__get_next_element('up')
        elif key == Key.down:
            next_element = self.__get_next_element('down')
        elif key == Key.left:
            next_element = self.__get_next_element('left')
        elif key == Key.right:
            next_element = self.__get_next_element('right')
        else:
            return

        if next_element is None:
            if self._parent is not None:
                self.__interacting_element = None
                control.pass_control(self._parent)
            elif self.__interacting_element is not None:
                self.__interacting_element.set_parent(self)
                control.pass_control(self.__interacting_element)

            return

        control.key_to_handle = None
        self.__interacting_element = next_element
        self.__interacting_element.set_parent(self)
        control.pass_control(next_element)

    def take_control(self, control: InteractionControl):
        interactibles = list(filter(lambda e: Interactible.is_interactible(e), self.__elements_depth_ordered))

        if len(interactibles) == 0:
            return

        if self.__interacting_element is None:
            self.__interacting_element = interactibles[0]
            self.__interacting_element.set_parent(self)
            control.key_to_handle = None
            control.pass_control(self.__interacting_element)
            return

        if control.key_to_handle is not None:
            key_to_handle = control.key_to_handle
            self.handle_key(key_to_handle, control)


import unittest

from mock import patch

import koan
import koan.utils
from koan.virtinstall import build_commandline
from koan.virtinstall import create_image_file

# FIXME: This is not yet converted to pytest

def setup():
    try:
        from virtinst import version as vi_version

        koan.virtinstall.virtinst_version = vi_version.__version__.split(".")
    except:
        koan.virtinstall.virtinst_version = 6

class OsPathMock:
    _dir_path = [
        "/path/to/imagedir",
    ]
    _exist_files = [
        "/path/to/imagedir/existfile",
    ]

    def isdir(self, path):
        if path in self._dir_path:
            return True
        return False

    def exists(self, path):
        if path in self._exist_files:
            return True
        return False

class KoanVirtInstallTest(unittest.TestCase):
    def testXenPVBasic(self):
        cmd = build_commandline(
            "xen:///",
            name="foo",
            ram=256,
            uuid="ad6611b9-98e4-82c8-827f-051b6b6680d7",
            vcpus=1,
            bridge="br0",
            disks=[("/tmp/foo1.img", 8), ("/dev/foo1", 0)],
            virt_type="xenpv",
            qemu_driver_type="virtio",
            qemu_net_type="virtio",
            profile_data={
                "kernel_local": "kernel",
                "initrd_local": "initrd",
            },
            extra="ks=http://example.com/ks.ks",
        )

        cmd = " ".join(cmd)
        self.assertEqual(
            cmd,
            (
                "virt-install --connect xen:/// --name foo --ram 256 --vcpus 1 "
                "--uuid ad6611b9-98e4-82c8-827f-051b6b6680d7 --vnc --paravirt "
                "--boot kernel=kernel,initrd=initrd,kernel_args=ks=http://example.com/ks.ks "
                "--disk path=/tmp/foo1.img,size=8 --disk path=/dev/foo1 "
                "--network bridge=br0 "
                "--wait 0 --noautoconsole"
            ),
        )

    def testXenFVBasic(self):
        cmd = build_commandline(
            "xen:///",
            name="foo",
            ram=256,
            vcpus=1,
            disks=[("/dev/foo1", 0)],
            fullvirt=True,
            arch="x86_64",
            bridge="br0,br1",
            virt_type="xenfv",
            profile_data={
                "breed": "redhat",
                "os_version": "fedora14",
                "interfaces": {
                    "eth0": {
                        "interface_type": "na",
                        "mac_address": "11:22:33:44:55:66",
                    },
                    "eth1": {
                        "interface_type": "na",
                        "mac_address": "11:22:33:33:22:11",
                    },
                },
            },
        )

        cmd = " ".join(cmd)
        self.assertEqual(
            cmd,
            (
                "virt-install --connect xen:/// --name foo --ram 256 --vcpus 1 "
                "--vnc --hvm --pxe --arch x86_64 "
                "--os-variant fedora14 --disk path=/dev/foo1 "
                "--network bridge=br0,mac=11:22:33:44:55:66 "
                "--network bridge=br1,mac=11:22:33:33:22:11 "
                "--wait 0 --noautoconsole"
            ),
        )

    def testQemuCDROM(self):
        cmd = build_commandline(
            "qemu:///system",
            name="foo",
            ram=256,
            vcpus=1,
            disks=[("/tmp/foo1.img", 8), ("/dev/foo1", 0)],
            fullvirt=True,
            virt_type="qemu",
            bridge="br0",
            profile_data={
                "breed": "windows",
                "file": "/some/cdrom/path.iso",
            },
        )

        cmd = " ".join(cmd)
        self.assertEqual(
            cmd,
            (
                "virt-install --connect qemu:///system --name foo --ram 256 "
                "--vcpus 1 --vnc --virt-type qemu --machine pc --hvm --cdrom /some/cdrom/path.iso "
                "--os-type windows --disk path=/tmp/foo1.img,size=8 "
                "--disk path=/dev/foo1 --network bridge=br0 "
                "--wait 0 --noautoconsole"
            ),
        )

    def testQemuURL(self):
        cmd = build_commandline(
            "qemu:///system",
            name="foo",
            ram=256,
            vcpus=1,
            disks=[("/tmp/foo1.img", 8), ("/dev/foo1", 0)],
            fullvirt=True,
            arch="i686",
            bridge="br0",
            virt_type="qemu",
            qemu_driver_type="virtio",
            qemu_net_type="virtio",
            profile_data={
                "breed": "ubuntu",
                "os_version": "natty",
                "install_tree": "http://example.com/some/install/tree",
            },
            extra="ks=http://example.com/ks.ks text kssendmac",
        )

        cmd = " ".join(cmd)
        self.assertEqual(
            cmd,
            (
                "virt-install --connect qemu:///system --name foo --ram 256 "
                "--vcpus 1 --vnc --virt-type qemu --machine pc --hvm "
                "--extra-args=ks=http://example.com/ks.ks text kssendmac "
                "--location http://example.com/some/install/tree/ --arch i686 "
                "--os-variant ubuntunatty "
                "--disk path=/tmp/foo1.img,size=8,bus=virtio "
                "--disk path=/dev/foo1,bus=virtio "
                "--network bridge=br0,model=virtio --wait 0 --noautoconsole"
            ),
        )

    def testKvmURL(self):
        cmd = build_commandline(
            "qemu:///system",
            name="foo",
            ram=256,
            vcpus=1,
            disks=[("/tmp/foo1.img", 8), ("/dev/foo1", 0)],
            fullvirt=None,
            arch="i686",
            bridge="br0",
            virt_type="kvm",
            qemu_driver_type="virtio",
            qemu_net_type="virtio",
            qemu_machine_type="pc-1.0",
            profile_data={
                "breed": "ubuntu",
                "os_version": "natty",
                "install_tree": "http://example.com/some/install/tree",
            },
            extra="ks=http://example.com/ks.ks text kssendmac",
        )

        cmd = " ".join(cmd)
        self.assertEqual(
            cmd,
            (
                "virt-install --connect qemu:///system --name foo --ram 256 "
                "--vcpus 1 --vnc --virt-type kvm --machine pc-1.0 "
                "--extra-args=ks=http://example.com/ks.ks text kssendmac "
                "--location http://example.com/some/install/tree/ --arch i686 "
                "--os-variant ubuntunatty "
                "--disk path=/tmp/foo1.img,size=8,bus=virtio "
                "--disk path=/dev/foo1,bus=virtio "
                "--network bridge=br0,model=virtio --wait 0 --noautoconsole"
            ),
        )

    def testImage(self):
        cmd = build_commandline(
            "import",
            name="foo",
            ram=256,
            vcpus=1,
            fullvirt=True,
            bridge="br0,br2",
            disks=[],
            qemu_driver_type="virtio",
            qemu_net_type="virtio",
            profile_data={
                "file": "/some/install/image.img",
                "network_count": 2,
            },
        )

        cmd = " ".join(cmd)
        self.assertEqual(
            cmd,
            (
                "virt-install --name foo --ram 256 --vcpus 1 --vnc --import "
                "--disk path=/some/install/image.img --network bridge=br0 "
                "--network bridge=br2 --wait 0 --noautoconsole"
            ),
        )

    def testVirtVersionCheckTest(self):
        tss = [
            ("19.19.19", "2.2.2", True),
            ("1.19.19", "2.2.2", False),
            ("2.19.19", "2.2.2", True),
            ("2.2.19", "2.2.2", True),
            ("1.1.0", "2.2.2", False),
            ("1.2.1", "2.2.2", False),
            ("2.2.2", "2.2.2", True),
        ]
        for t in tss:
            self.assertTrue(utils.check_version_greater_or_equal(t[0], t[1]) == t[2])

    @patch("koan.virtinstall.utils.subprocess_call")
    @patch("koan.virtinstall.utils.os.path", new_callable=OsPathMock)
    def test_create_qcow_file(self, mock_path, mock_subprocess):
        disks = [
            ("/path/to/imagedir/new_qcow_file", "30", "qcow"),
            ("/path/to/imagedir/new_qcow2_file", "30", "qcow2"),
            ("/path/to/imagedir/new_raw_file", "30", "raw"),
            ("/path/to/imagedir/new_vmdk_file", "30", "vmdk"),
            ("/path/to/imagedir/new_qcow_file", "30"),
            ("/path/to/imagedir/new_qcow2_file", "0", "qcow2"),
            ("/path/to/imagedir/existfile", "30", "qcow2"),
            ("/path/to/imagedir", "30", "qcow2"),
        ]

        create_image_file(disks)
        res = []
        for args, kargs in mock_subprocess.call_args_list:
            res.append(" ".join(args[0]))

        self.assertEqual(
            res,
            [
                "qemu-img create -f qcow /path/to/imagedir/new_qcow_file 30G",
                "qemu-img create -f qcow2 /path/to/imagedir/new_qcow2_file 30G",
                "qemu-img create -f raw /path/to/imagedir/new_raw_file 30G",
                "qemu-img create -f vmdk /path/to/imagedir/new_vmdk_file 30G",
            ],
        )


import func
import numpy as np
from time import sleep
# X1 = np.array([[0.], [1.], [2.], [3.], [4.]])
# theta1 = np.array([[2.], [4.]])
# Y1 = np.array([[2.], [7.], [12.], [17.], [22.]])
# X3 = np.array([[0.2, 2., 20.], [0.4, 4., 40.], [0.6, 6., 60.], [0.8, 8.,80.]])
# X2 = np.array([[1], [2], [3], [5], [8]])
# theta2 = np.array([[2.]])
# theta3 = np.array([[0.05], [1.], [1.], [1.]])
X1 = np.array([[0.], [1.], [2.], [3.], [4.]])
theta1 = np.array([[1.], [1.]])
Y1 = np.array([[2.], [6.], [10.], [14.], [18.]])

def predict__(theta, X):
	print(theta.shape)
	print(X.shape)
	if (X.shape[1], 1) != theta.shape:
		print("incompatible dimension match between X and theta")
		return None
	return func.mat_vec_prod(X,theta)

# print(predict__(theta3,X3))

def cost_elem__(theta, X, Y):
	y_pred = predict__(theta, X)
	print(y_pred.shape)
	print(Y.shape)
	M = X.shape[0]
	return 0.5 * M * (y_pred - Y) ** 2

def cost__(theta1, X1, Y1):
	y_pred = predict__(theta1, X1)
	return func.vec_mse(y_pred, Y1) * 0.5

# print(cost_elem__(theta1, X1, Y1))
# print(cost__(theta1, X1, Y1))

# def ft_vec_gradient(x, y, theta):
# 	M = x.shape[0]
# 	N = x.shape[1]
# 	add = np.ones((x.shape[0],1))
# 	fix = np.concatenate((add, x),axis=1)
# 	# print(theta.shape)
# 	# print(x.shape)
# 	# print(y.shape)
# 	hp = predict__(theta, fix) - y
# 	if (M,1) != y.shape or (N,1) != theta.shape:
# 		print("incompatible")
# 		return None
# 	y = func.reshape(y)
# 	theta = func.reshape(theta)
# 	return func.dot(x, hp) / x.shape[0]

def	fit__(theta, X, Y,alpha=0.01,n_cycle=2000):
	M = X.shape[0]
	add = np.ones((X.shape[0],1))
	fix = np.concatenate((add, X),axis=1)
	for _ in range(n_cycle):
		hp = predict__(theta, fix) - Y
		grad = func.dot(fix, hp) * 0.5 * M
		theta = theta - alpha * 0.5 * M * func.vec_gradient(fix, Y, theta)
		# theta[0] = tmp0
	return theta
# add = np.ones((X1.shape[0],1))
# print(add.shape)
# print(type(add))

# print(X1.shape)
# print(np.concatenate((add, X1),axis=1))
print(fit__(theta1, X1,Y1))
# print(predict__(theta1, X1))


from django.conf import settings
from django.template.loader import render_to_string
from django.core.mail import EmailMessage

def send_inquiry_email(
    request,
    mail_subject,
    email_template,
    message,
    full_name,
    email,
):
    from_email = settings.EMAIL_HOST_USER
    message = render_to_string(
        email_template,
        {"full_name": full_name, "message": message, "email": email},
    )

    to_email = settings.EMAIL_HOST_USER
    mail = EmailMessage(
        mail_subject,
        message,
        from_email,
        to=[to_email],
    )
    mail.send()


"""
"""
from collections import defaultdict, deque

class Solution:
    def minJumps(self, arr: List[int]) -> int:
        n = len(arr)
        d = [float('inf')] * n
        v_to_i = defaultdict(list)
        for i, num in enumerate(arr):
            v_to_i[num].append(i)
        d[0] = 0
        que = deque([0])
        while que:
            node = que.popleft()
            cost = d[node] + 1

            for neighbor in [neighbor for neighbor in v_to_i[arr[node]] + [node - 1, node + 1] if 0 <= neighbor < n]:

                if d[neighbor] > cost:
                    d[neighbor] = cost
                    que.append(neighbor)
            v_to_i[arr[node]]=[]
        # print(d)
        return d[n-1]


##### Using the raspberry pi to detect people in security camera pictures
#
# Author: Sahas Munamala
# Date: 4/5/2020
# Description:
# This object of this program is to detect which images from the security camera
# contain people. Currently, the camera sends an email every time movement is detected.
# Howver, I do not want to get emails of my neighbor's cat every day, so this program
# will run every image through a tensorflow model to detect if people are present.
# The program will be running 24/7 on a raspberry pi.

import os
import cv2
import numpy as np
import tensorflow as tf
import sys
import logging

logging.basicConfig(filename='logs/model.log', level=logging.INFO, format='%(asctime)s : %(levelname)s: %(message)s')

from utils import label_map_util

THRESHOLD = 0.5

class odmodel :
    """
    This class abstracts the tensorflow model so its main functions
    can be used without concern for the lower-level implementation
    """
    def __init__ (self) :

        self.MODEL_NAME = 'ssdlite_mobilenet_v2_coco_2018_05_09'
        self.CWD_PATH = os.getcwd()

        self.PATH_TO_CKPT = os.path.join(self.CWD_PATH,self.MODEL_NAME,'frozen_inference_graph.pb')
        self.PATH_TO_LABELS = os.path.join(self.CWD_PATH,'data','mscoco_label_map.pbtxt')
        self.NUM_CLASSES = 90

        self.label_map = label_map_util.load_labelmap(self.PATH_TO_LABELS)
        self.categories = label_map_util.convert_label_map_to_categories(self.label_map, \
                max_num_classes=self.NUM_CLASSES, \
                use_display_name=True)
        self.category_index = label_map_util.create_category_index(self.categories)

        detection_graph = tf.Graph()
        with detection_graph.as_default():
            od_graph_def = tf.GraphDef()
            with tf.gfile.GFile(self.PATH_TO_CKPT, 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')

            self.sess = tf.Session(graph=detection_graph)

        self.image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
        self.detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

        self.detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
        self.detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')

        self.num_detections = detection_graph.get_tensor_by_name('num_detections:0')

    def _runmodel (self, frame_expanded, frame) :
        print( "Running model" )
        (boxes, scores, classes, num) = self.sess.run([self.detection_boxes, \
                self.detection_scores, \
                self.detection_classes, \
                self.num_detections], \
                feed_dict={self.image_tensor: frame_expanded})
        return (boxes, scores, classes, num)

    def runimage (self, imagefile) :
        frame = cv2.imread(imagefile, cv2.IMREAD_COLOR)
        frame.setflags(write=1)
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frame_expanded = np.expand_dims(frame_rgb, axis=0)

        (boxes, scores, classes, num) = self._runmodel(frame_expanded, frame)

    def findPerson (self, imagefile) :
        """Find a person in a given image
        Run imagefile through object detection model and parse the output for
        indication of a person

        Parameters:
        imagefile   : filesystem path to image to process

        Returns:
        True    : Person has been detected in image
        False   : No Person inside the image
        """
        frame = cv2.imread(imagefile, cv2.IMREAD_COLOR)
        frame.setflags(write=1)
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frame_expanded = np.expand_dims(frame_rgb, axis=0)

        (boxes, scores, classes, num) = self._runmodel(frame_expanded, frame)

        if (classes is not None) :
            confidence = scores[0,0]
            logging.info("confidence: %f" % confidence)
            if confidence > THRESHOLD:
                logging.info("person detected")
                return True
        return False

if __name__ == "__main__" :
    odm = odmodel()
    (boxes, scores, classes, num) = odm.run_image('/home/sahas/Desktop/Wallpapers/nomanssky2.jpg')
    print("finished model" )


def check(a,b):
    if a<b:
        temp=a
        a=b
        b=temp
    while a%b!=0:
        temp=a%b
        a=b
        b=temp
    if b>1:
        return True
    else:
        return False
nums=[int(x) for x in input().split(',')]
groups=[[x] for x in nums]
for i in nums:
    j=0
    while j<len(groups):
        if i not in groups[j]:
            for k in groups[j]:
                if check(k,i):
                    for l in range(len(groups)):
                        if i in groups[l]:
                            groups[j]=groups[j]+groups[l]
                            del groups[l]
                            j-=1
                            break
                    break
        j+=1
maximum=0
for i in groups:
    maximum=max(maximum,len(i))
print(maximum)


from dataclasses import dataclass
from typing import List

from api.api_v1.response import User
from src.db import UserDB
from src.exceptions.contact_exceptions import (
    ContactAlreadyExistsException
)
from src.repositories.contact_repository import ContactRepository
from src.repositories.user_repository import UserRepository
from src.request_schemas.contact_schemas import ContactListIn, ContactIn
from src.schemas.orm_schemas.contact_schemas import Contact

@dataclass
class AddUserContactsUsecase:
    """Usecase for adding user's contacts in bulk."""

    contact_repository: ContactRepository
    user_repository: UserRepository
    contacts_limit: int = 10

    async def add_user_contacts(self, user_id: int,
                                contacts_in: ContactListIn):
        existing_contacts = await self.contact_repository.get_user_contacts(
            user_id=user_id
        )

        existing_users = await self.user_repository.get_users_by_phone(
            [contact.phone for contact in contacts_in.contacts]
        )

        await self._validate_contacts_do_not_exist(
            existing_contacts=existing_contacts,
            existing_users=existing_users
        )

        await self.create_new_users_by_phone(
            existing_users=existing_users,
            contacts=contacts_in.contacts
        )

        users = await self.user_repository.get_users_by_phone(
            [contact.phone for contact in contacts_in.contacts]
        )

        await self.contact_repository.bulk_create_contacts(
            [{"user_id": user_id, "contact_id": user.id} for user in users]
        )

    async def _validate_contacts_do_not_exist(
            self,
            existing_contacts: List[Contact],
            existing_users: List[User]
    ):
        existing_contact_ids = [contact.contact_id for contact in
                                existing_contacts]
        for user in existing_users:
            if user.id in existing_contact_ids:
                raise ContactAlreadyExistsException(
                    message=f'Contact {user.phone} is already present '
                            f'in contact list.'
                )

    async def create_new_users_by_phone(
            self,
            existing_users: List[User],
            contacts: List[ContactIn]
    ):
        """Create new users."""
        new_users = [
            contact for contact in contacts if
            contact.phone not in [user.phone for user in existing_users]
        ]

        await self.user_repository.bulk_create_users(
            [{"phone": user.phone, "name": user.name,
              "status": UserDB.StatusChoices.invited} for user in new_users]
        )


#Problem 2
#Find the total profit/loss of each trader working in a trading firm. Information regarding number of traders and number of transactions is unknown.

empID = input('Enter employee ID: ')
while(empID != '-1'):
    trade = int(input('Enter the trade amount: '))
    profit_loss = 0
    while(trade != 0 ):
        trade = int(input('Enter the trade amount: '))
    print(f'Profit/loss for employee {empID} is {profit_loss}')
    empID = input('Enter employee ID: ')

week 1-4/Tutorial on nested loops/profit_loss.py


from pathlib import Path
from scipy.io import wavfile  # type: ignore
from time import sleep
import argparse
import logging
import typing as ty

from tqdm import tqdm  # type: ignore
import librosa  # type: ignore
import numpy as np  # type: ignore
import sounddevice as sd  # type: ignore

from utils import setup_logger
from utils import find_free_file_index

def parse_arguments() -> argparse.Namespace:
    """Setup CLI interface"""
    parser = argparse.ArgumentParser(description="")

    parser.add_argument(
        "-rt",
        "--recording_type",
        type=str,
        default="record_samples",
        choices=["record_samples", "split_noise"],
        help="What to execute",
    )

    parser.add_argument(
        "-dl",
        "--do_loud",
        dest="do_loud",
        action="store_true",
        help="Extract half a second samples",
    )

    parser.add_argument(
        "-nr",
        "--num_rec",
        type=int,
        default=5,
        help="How many samples to record",
    )

    parser.add_argument(
        "-ls",
        "--len_sec",
        type=int,
        default=10,
        help="The duration of each recording",
    )

    # last line to parse the args
    args = parser.parse_args()
    return args

def setup_env() -> argparse.Namespace:
    setup_logger("DEBUG")
    args = parse_arguments()
    # build command string to repeat this run
    # FIXME if an option is a flag this does not work, sorry
    recap = "python3 background_noise.py"
    for a, v in args._get_kwargs():
        recap += f" --{a} {v}"
    logmain = logging.getLogger(f"c.{__name__}.setup_env")
    logmain.info(recap)
    return args

def record_samples(len_sec: int, num_rec: int) -> None:
    """MAKEDOC: what is record_samples doing?

    Record 10s samples, rescale them at 16KHz and save them
    """
    logg = logging.getLogger(f"c.{__name__}.record_samples")
    # logg.setLevel("INFO")
    logg.debug("Start record_samples")

    # the location of this file
    this_file_folder = Path(__file__).parent.absolute()
    logg.debug(f"this_file_folder: {this_file_folder}")

    # where to save the recorded audios
    audio_folder = this_file_folder / "background_audios"
    if not audio_folder.exists():
        audio_folder.mkdir(parents=True, exist_ok=True)

    # audio path template name
    audio_path_fmt = "recorded_audio_{:03d}.wav"

    rec_samplerate = 16000
    # len_sec = 10
    rec_length = int(len_sec * rec_samplerate)
    # num_rec = 2

    for i in range(num_rec):
        logg.debug(f"Start recording {i+1:03d}/{num_rec:03d}")

        # record
        myrecording = sd.rec(rec_length, samplerate=rec_samplerate, channels=1)
        for _ in range(len_sec):
            print(".", end="", flush=True)
            sleep(1)
        print()
        sd.wait()  # Wait until recording is finished

        # resample
        # new_sig = librosa.resample(orig_sig, orig_sr, new_sr)

        # find a free file and save it there
        rec_index = find_free_file_index(audio_folder, audio_path_fmt)
        audio_path = audio_folder / audio_path_fmt.format(rec_index)
        logg.debug(f"Saving in {audio_path}")
        wavfile.write(audio_path, rec_samplerate, myrecording)

def split_noise(do_loud) -> None:
    """MAKEDOC: what is split_noise doing?"""
    logg = logging.getLogger(f"c.{__name__}.split_noise")
    # logg.setLevel("INFO")
    logg.debug("Start split_noise")

    # the location of this file
    this_file_folder = Path(__file__).parent.absolute()
    logg.debug(f"this_file_folder: {this_file_folder}")

    # the raw audio folder for the dataset
    raw_word_fol = Path("data_raw")

    # the location of the original dataset(s)
    base_folders = []

    # my audios
    audio_folder = this_file_folder / "background_audios"
    base_folders.append(audio_folder)

    # Google Speech Commands audios
    gcsd_background = raw_word_fol / "_background_noise_"
    logg.debug(f"gcsd_background: {gcsd_background}")
    base_folders.append(gcsd_background)

    # the desired samplerate
    silence_samplerate = 16000

    # find all wav files and load the wavs
    all_signals_orig: ty.List[np.ndarray] = []
    for base_folder in base_folders:
        # logg.debug(f"base_folder: {base_folder}")

        for a_file in base_folder.iterdir():
            if not a_file.suffix == ".wav":
                continue

            # logg.debug(f"Processing {a_file}")
            orig_sig, orig_sr = librosa.load(a_file, sr=None)

            if orig_sr != silence_samplerate:
                logg.warn(f"Resampling: {a_file}")
                orig_sig = librosa.resample(orig_sig, orig_sr, silence_samplerate)

            # logg.debug(f"orig_sig.shape: {orig_sig.shape}")
            all_signals_orig.append(orig_sig)

    all_silence = np.concatenate(all_signals_orig)
    recap = f"all_silence.shape: {all_silence.shape}"
    recap += f" or {all_silence.shape[0]//silence_samplerate} seconds"
    logg.debug(recap)

    # how long is the silence available as numpy
    silence_sig_len = all_silence.shape[0]

    # how long is the desired sample saved
    if do_loud:
        silence_sample_len = 8000
        loud_tag = "_loud"
    else:
        silence_sample_len = 16000
        loud_tag = ""

    # where to save the split samples
    background_label = f"_background{loud_tag}"
    background_folder = Path("data_raw") / background_label
    logg.debug(f"background_folder: {background_folder}")
    if not background_folder.exists():
        background_folder.mkdir(parents=True, exist_ok=True)

    # the file to list the file names for the testing fold
    val_list_path = raw_word_fol / f"validation_list_background{loud_tag}.txt"
    word_val_list: ty.List[str] = []
    test_list_path = raw_word_fol / f"testing_list_background{loud_tag}.txt"
    word_test_list: ty.List[str] = []

    # the sizes of the test and validation folds
    val_fold_size = 0.1
    test_fold_size = 0.1

    # a random number generator to use
    rng = np.random.default_rng(12345)

    # numpy template name
    sample_name_template = "background_{:06d}.wav"

    # how many splits to extract
    num_silence_samples = 5000

    # how much to leave from the end
    end_sample = silence_sig_len - silence_sample_len - 10

    for i in tqdm(range(num_silence_samples)):
        sample_name = sample_name_template.format(i)

        start = rng.integers(0, end_sample)
        end = start + silence_sample_len

        silence_sample = all_silence[start:end]
        # recap = f"silence_sample.shape: {silence_sample.shape}"
        # recap += f" {start} : {end}"
        # logg.debug(recap)

        # the ID of the sample
        sample_id = f"{background_label}/{sample_name}"

        # split in trainin/validation/testing
        x = rng.random()
        if x < test_fold_size:
            word_test_list.append(sample_id)
        elif x < test_fold_size + val_fold_size:
            word_val_list.append(sample_id)

        sample_path = background_folder / sample_name
        wavfile.write(sample_path, silence_samplerate, silence_sample)

    # save the IDs
    word_val_str = "\n".join(word_val_list)
    val_list_path.write_text(word_val_str)
    word_test_str = "\n".join(word_test_list)
    test_list_path.write_text(word_test_str)

def run_background_noise(args: argparse.Namespace) -> None:
    """TODO: What is background_noise doing?"""
    logg = logging.getLogger(f"c.{__name__}.run_background_noise")
    logg.debug("Starting run_background_noise")

    recording_type = args.recording_type
    len_sec = args.len_sec
    num_rec = args.num_rec
    do_loud = args.do_loud

    if recording_type == "record_samples":
        record_samples(len_sec, num_rec)
    elif recording_type == "split_noise":
        split_noise(do_loud)

if __name__ == "__main__":
    args = setup_env()
    run_background_noise(args)


import multiprocessing
import cv2
import numpy as np
import json
import os
import imageio
import shutil

# img_src is numpy array, affine matrix is 2*3 matrix
# image index is col, row
# keep all pixels in the source image
# return img_dst, off_set
def warp_affine(img_src, affine_matrix, no_blank_margin=True):
    height, width = img_src.shape[:2]

    # compute bounding box
    bbx = np.dot(affine_matrix, np.array([[0, width, width, 0],
                                          [0, 0, height, height],
                                          [1, 1, 1, 1]]))

    if no_blank_margin:
        col = np.sort(bbx[0, :])
        row = np.sort(bbx[1, :])

        # leave some small margin
        col_min = int(col[1]) + 3
        row_min = int(row[1]) + 3
        w = int(col[2]) - col_min - 3
        h = int(row[2]) - row_min - 3
    else:
        col_min = np.min(bbx[0, :])
        col_max = np.max(bbx[0, :])
        row_min = np.min(bbx[1, :])
        row_max = np.max(bbx[1, :])

        w = int(np.round(col_max - col_min + 1))
        h = int(np.round(row_max - row_min + 1))

    # add offset to the affine_matrix
    affine_matrix[0, 2] -= col_min
    affine_matrix[1, 2] -= row_min

    off_set = (-col_min, -row_min)

    # warp image
    img_dst = cv2.warpAffine(img_src, affine_matrix, (w, h))

    assert (h == img_dst.shape[0] and w == img_dst.shape[1])

    return img_dst, off_set, affine_matrix

def skew_correct_worker(perspective_img_dir, img_name, params, pinhole_img_dir):
    fx = params[2]
    fy = params[3]
    cx = params[4]
    cy = params[5]
    s = params[6]
    qvec = params[7:11]
    tvec = params[11:14]

    # compute homography and update s, cx
    norm_skew = s / fy
    cx = cx - s * cy / fy
    s = 0.

    # warp image
    affine_matrix = np.array([[1., -norm_skew, 0.],
                              [0., 1., 0.]])
    img_src = imageio.imread(os.path.join(perspective_img_dir, img_name))
    img_dst, off_set, affine_matrix = warp_affine(img_src, affine_matrix)
    imageio.imwrite(os.path.join(pinhole_img_dir, img_name), img_dst)

    new_h, new_w = img_dst.shape[:2]
    # add off_set to camera parameters
    cx += off_set[0]
    cy += off_set[1]

    return norm_skew, affine_matrix, [new_w, new_h, fx, fy, cx, cy,
            qvec[0], qvec[1], qvec[2], qvec[3],
            tvec[0], tvec[1], tvec[2]]

def skew_correct(data_dir):
    # input
    perspective_img_dir = os.path.join(data_dir, 'images')
    perspective_file = os.path.join(data_dir, 'perspective_cameras.json')
    with open(perspective_file) as fp:
        perspective_dict = json.load(fp)

    # output
    out_dir = os.path.join(data_dir, 'skew_correct')
    pinhole_img_dir = os.path.join(out_dir, 'images')
    if os.path.exists(pinhole_img_dir):
        shutil.rmtree(pinhole_img_dir)
    os.makedirs(pinhole_img_dir)
    pinhole_file = os.path.join(out_dir, 'pinhole_cameras.json')
    warping_file = os.path.join(out_dir, 'affine_warpings.json')

    pinhole_dict = {}
    affine_warping_dict = {}
    info_txt = 'img_name, skew (s/fy)\n'

    perspective_images = sorted(os.listdir(perspective_img_dir))
    pool_size = min(multiprocessing.cpu_count(), len(perspective_images))
    pool = multiprocessing.Pool(pool_size)

    results = []
    arguments = []
    for img_name in perspective_images:
        # w, h, fx, fy, cx, cy, s, qvec, t
        params = perspective_dict[img_name]
        w = params[0]
        h = params[1]
        arguments.append((img_name, w, h))
        results.append(pool.apply_async(skew_correct_worker, (perspective_img_dir, img_name, params, pinhole_img_dir)))

    for i, r in enumerate(results):
        img_name, w, h = arguments[i]
        norm_skew, affine_matrix, pinhole = r.get()
        affine_warping_dict[img_name] = affine_matrix
        info_txt += '{}, {}\n'.format(img_name, norm_skew)
        pinhole_dict[img_name] = pinhole

        print('removed normalized skew: {} in image: {}, original size: {}, {}, new image size: {}, {}'.format(
               norm_skew, img_name, w, h, pinhole[0], pinhole[1]))

    pool.close()
    pool.join()

    # dump the results to disk
    with open(pinhole_file, 'w') as fp:
        json.dump(pinhole_dict, fp, indent=2)

    with open(warping_file, 'w') as fp:
        for img_name in affine_warping_dict.keys():
            matrix = affine_warping_dict[img_name]
            affine_warping_dict[img_name] = list(matrix.reshape((6,)))
        json.dump(affine_warping_dict, fp, indent=2)

    with open(os.path.join(out_dir, 'skews.csv'), 'w') as fp:
        fp.write(info_txt)

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Remove Skew from Images')
    parser.add_argument('--data_dir', type=str,
                    help='data directory for the site')

    args = parser.parse_args()
    skew_correct(args.data_dir)


# -*- coding: utf-8 -*-
"""
Created on Mon Jun  6 21:26:43 2022

@author: WLDru
"""

import pygame as pg
import random as rand
import sys

pg.init()

#%% Constants

black = (0, 0, 0)
white = (255, 255, 255)
dark_grey = (25, 25, 25)
light_grey = (150, 150, 150)
top = (125, 125, 125)
bottom = (75, 75, 75)
grey = (100, 100, 100)
red = (255, 0, 0)
green = (0, 255, 0)
yellow = (255, 255, 0)
orange = (200, 100, 0)
blue = (0, 0, 255)

W = 1920
H = 1080

#%% setup

screen = pg.display.set_mode((W, H))

clock = pg.time.Clock()

run = True

#%% variables

animate = False

random = False

loop = False

res = 300
r = 0

#%% points

points = []

curve = []

#%% Actions

#%% While loop

while run:

    n = len(points)

#%% Events

    for event in pg.event.get():
        if event.type == pg.QUIT:
            run = False
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                run = False
            if event.key == pg.K_RETURN:
                if n > 2:
                    animate = True
                    curve = []
            if event.key == pg.K_BACKSPACE:
                animate = False
            if event.key == pg.K_DELETE:
                if not animate:
                    points = []
                    curve = []
            if event.key == pg.K_r:
                if not animate:
                    random = True
                    points = []
                    curve = []
            if event.key == pg.K_l:
                if not animate:
                    loop = True
                    points = []
                    curve = []
        if event.type == pg.MOUSEBUTTONDOWN:
            if event.button == 1:
                x, y = pg.mouse.get_pos()
                points.append([x, y])

    n = len(points)

#%% Random Drawing

    if random:
        randcount = rand.randint(5, 30)
        for i in range(randcount):
            points.append([rand.randint(0, W-1), rand.randint(0, H-1)])
            if i == randcount-1:
                random = False

    n = len(points)

#%% Animation

    if animate:

        if r < res:
            r += 1

            lines = []
            lines.append(points)

            for i in range(n-1, 0, -1):
                if i == 1:
                    curve.append([int((r/res)*(lines[-1][-1][0]-lines[-1][-2][0])+lines[-1][-2][0]),
                                  int((r/res)*(lines[-1][-1][1]-lines[-1][-2][1])+lines[-1][-2][1])])
                else:
                    line = []
                    for j in range(i):
                        line.append([((r/res)*(lines[-1][j+1][0] - lines[-1][j][0])) + lines[-1][j][0],
                                     ((r/res)*(lines[-1][j+1][1] - lines[-1][j][1])) + lines[-1][j][1]])
                    lines.append(line)

            for i, sequence in enumerate(lines):
                for j, point in enumerate(sequence):
                    lines[i][j][0] = int(lines[i][j][0])
                    lines[i][j][1] = int(lines[i][j][1])

        else:
            animate = False
            r = 0

#%% Drawing to Screen

    screen.fill(black)

    if n == 1:
        pg.draw.circle(screen, light_grey, points[0], 5)
    if n > 1:
        pg.draw.lines(screen, light_grey, False, points,  1)
        pg.draw.circle(screen, light_grey, points[0], 5)
        for point in points:
            pg.draw.circle(screen, light_grey, point, 5)

    if animate:
        for s, sequence in enumerate(lines):
            color = ((((s+1)/n)*255), (((s+1)/n)*255), (((s+1)/n)*255))
            if s != 0:
                pg.draw.lines(screen, color, False, sequence, 1)
    if len(curve) > 1:
        pg.draw.lines(screen, red, False, curve, 3)

#%% Loop

    if loop:
        if not animate:
            random = True
            animate = True
            points = []
            curve = []

#%% Update Frame

    pg.display.update()
    clock.tick(60)

#%% Exit Statement

pg.quit()
sys.exit()


import numpy
from pandas import concat, DataFrame
from rodan.jobs.base import RodanTask
from vis.analyzers.indexers.offset import FilterByOffsetIndexer

import logging
logger = logging.getLogger('rodan')

class VROffsetIndexer(RodanTask):

	name = 'Offset Indexer'
	author = 'Marina Borsodi-Benson'
	description = 'Filters by offset'
	settings = {
		'title': 'Offset Indexer Settings',
		'type': 'object',
		'properties': {
			'Quarternote length': {
				'type': 'number',
				'default': 1.0,
				'minimum': 0.001,
				'description': 'The quarternote length duration between observations desired in the output.'
			},
			'Forward Fill': {
				'type': 'boolean',
				'default': True,
				'description': 'Forward fill fills in the missing indices with the previous value. This is useful for vertical intervals, but not for horizontal.'
			}
		}
	}

	enabled = True
	category = 'VIS - Indexer'
	interactive = False

	input_port_types = [{
		'name': 'NoteRest Indexer Result',
		'resource_types': ['application/x-vis_noterest_pandas_series+csv'],
		'minimum': 1,
		'maximum': 1,
	}]
	output_port_types = [{
		'name': 'NoteRest Indexer Result',
		'resource_types': ['application/x-vis_noterest_pandas_series+csv'],
		'minimum': 1,
		'maximum': 1
	}]

	def run_my_task(self, inputs, settings, outputs):

		infile = inputs['NoteRest Indexer Result'][0]['resource_path']
		outfile = outputs['NoteRest Indexer Result'][0]['resource_path']

		wrapper_settings = dict([(k, settings[k]) for k in ('Quarternote length', 'Forward Fill')])
		execution_settings = dict()
		execution_settings['quarterLength'] = wrapper_settings['Quarternote length']
		if wrapper_settings['Forward Fill'] == True:
			execution_settings['method'] = 'ffill'
		else:
			execution_settings['method'] = 'None'
		execution_settings['mp'] = False

		noterest = DataFrame.from_csv(infile, header = [0, 1])
		offset_indexed = FilterByOffsetIndexer(noterest, execution_settings).run()
		offset_indexed.to_csv(outfile)

		return True


import os
import sys
from setuptools import setup

import torch
from torch.utils.cpp_extension import BuildExtension, CUDAExtension

root = '/'.join(os.path.abspath(__file__).split('/')[:-1])
if os.getcwd() != root:
    os.chdir(root)

with open('version.txt', 'r') as f:
    version = f.read()

def make_extension(
        belong: str, name: str,
        extra_compile_args: dict,
        extra_file: list = None, define_macros: list = None
):
    return CUDAExtension(
        name=f'ove_ext.{belong}.{name}',
        sources=[
            f'extension/{belong}/{name}/{f}'
            for f in (
                'cuda_kernel.cu', 'cuda.cc',
                *([] if extra_file is None else extra_file)
            )
        ],
        **({} if define_macros is None else {'define_macros': define_macros}),
        extra_compile_args=extra_compile_args
    )

if torch.cuda.is_available():
    if len(sys.argv) > 2:
        cc = sys.argv[2].split(',')
        del sys.argv[2:]
    else:
        cc = ['%d%d' % torch.cuda.get_device_capability()]
    print(f"Building for CUDA Compatibility {','.join(cc)}")
else:
    print('No available CUDA device.')
    exit(1)

dain_extra_compile_args = {
    'cxx': ['-std=c++17', '-w'],
    'nvcc': ['-w']
}
for i in cc:
    dain_extra_compile_args['nvcc'].extend(['-gencode', f'arch=compute_{i},code=sm_{i}'])

basicsr_extra_compile_args = {
    'cxx': [],
    'nvcc': [
        '-D__CUDA_NO_HALF_OPERATORS__',
        '-D__CUDA_NO_HALF_CONVERSIONS__',
        '-D__CUDA_NO_HALF2_OPERATORS__'
    ]
}

ext_modules = [
    *[make_extension(
        belong='dain',
        name=name,
        extra_compile_args=dain_extra_compile_args
    ) for name in (
        'correlation', 'depth_flow_projection', 'filter_interpolation', 'flow_projection'
    )],
    make_extension(
        belong='basicsr',
        name='dcn',
        extra_compile_args=basicsr_extra_compile_args,
        define_macros=[('WITH_CUDA', None)],
        extra_file=['ext.cc']
    )
]

setup(
    name='ove_ext',
    version=version,
    packages=['extension'],
    ext_modules=ext_modules,
    cmdclass={'build_ext': BuildExtension},
    zip_safe=False
)


import bpy
import bmesh
import numpy as np
from math import *
from mathutils import *

### Using blender 2.82a
## How to use:
### ./blender --background --python fiber_bundle_IJRR.py &&
###  convert -trim ~/image.png ~/image.png && display ~/image.png

diameterState = 0.45
mobiusStripThickness = 0.1
pathThickness = 0.3
circleThickness = 0.3

cameraFocusPoint = Vector((0,-8,-7))
cameraLocation = Vector((-15,-8,+10))
distanceCamera = 35
offsetAnnulusLeft = Vector((-3, +1, -15))
offsetAnnulusRight = Vector((-3,-15, -15))

torusMinorRadius = 2.3
torusMajorRadius = 4.1
torusLocation = (0,-14,0)

colorStartState = (0.0, 1.0, 0.0, 1.0)
colorGoalState = (0.7, 0.0, 0.0, 1.0)

minor_radius = 2
major_radius = 5

materialGreen = bpy.data.materials.new(name="Green")
materialGreen.diffuse_color = (0.0, 1.0, 0.0, 1.0)
materialGreen.metallic = 0.0
materialGreen.specular_intensity = 0.0

materialMagenta = bpy.data.materials.new(name="Magenta")
materialMagenta.diffuse_color = (0.45, 0.05, 0.72, 1.0)
materialMagenta.diffuse_color = (0.575, 0.12, 1.0, 1.0)
materialMagenta.diffuse_color = (0.205, 0.0, 0.37, 1.0)
materialMagenta.metallic = 0.9
materialMagenta.specular_intensity = 0.9

def arrow_mesh(position, length, width=-1, headlength=-1, headwidth = -1):
    verts = []
    faces = []

    if width < 0:
      width = 0.15*length
    if headlength < 0:
      headlength = 0.3*length
    if headwidth < 0:
      headwidth = 2*width

    v1 = position
    v2 = Vector((position[0], position[1] - 0.5*headwidth, position[2] + headlength))
    v3 = Vector((position[0], position[1] - 0.5*width, position[2] + headlength))
    v4 = Vector((position[0], position[1] - 0.5*width, position[2] + length))

    v5 = Vector((position[0], position[1] + 0.5*headwidth, position[2] + headlength))
    v6 = Vector((position[0], position[1] + 0.5*width, position[2] + headlength))
    v7 = Vector((position[0], position[1] + 0.5*width, position[2] + length))

    #   3---6
    #   |   |
    #   |   |
    #1--2---5--4
    # \       /
    #  \     /
    #   \   /
    #    \ /
    #     0

    # verts.extend([v1, v2])
    verts.extend([v1, v2, v3, v4, v5, v6, v7])
    faces.append([0, 1, 2])
    faces.append([0, 2, 5])
    faces.append([0, 5, 4])
    faces.append([2, 3, 6])
    faces.append([2, 6, 5])

    mesh = bpy.data.meshes.new("arrow")
    mesh.from_pydata(verts, [], faces)

    for p in mesh.polygons:
        p.use_smooth=True

    return mesh

def annulus_mesh(resolution, inner_radius, outer_radius):
    verts = []
    faces = []

    for i in range(resolution):
        theta = 2*pi * i/resolution
        rot = Matrix.Rotation(theta, 3, [0,0,1])
        v1 = rot @ Vector([inner_radius, 0, 0])
        v2 = rot @ Vector([outer_radius, 0, 0])

        i1 = len(verts)
        verts.extend([v1,v2])

        if i+1<resolution:
            ia = i1+2
            ib = i1+3
        else:
            ia = 0
            ib = 1

        faces.append( [i1,i1+1,ib,ia])

    mesh = bpy.data.meshes.new("annulus")
    mesh.from_pydata(verts, [], faces)

    for p in mesh.polygons:
        p.use_smooth=True

    return mesh

def mobius_mesh(resolution, thick):

    verts = []
    faces = []

    for i in range(resolution):

        theta = 2*pi * i/resolution
        phi = pi * i/resolution

        rot1 = Matrix.Rotation(phi, 3, [0,1,0])
        rot2 = Matrix.Rotation(theta, 3, [0,0,1])
        c1 = Vector([major_radius, 0, 0])
        v1 = rot2 @ (c1 + rot1 @ Vector([-thick / 2, 0, minor_radius]) )
        v2 = rot2 @ (c1 + rot1 @ Vector([thick / 2, 0, minor_radius]) )
        v3 = rot2 @ (c1 + rot1 @ Vector([thick / 2, 0, -minor_radius]) )
        v4 = rot2 @ (c1 + rot1 @ Vector([-thick / 2, 0, -minor_radius]) )

        i1 = len(verts)
        verts.extend([v1,v2,v3,v4])

        if i+1<resolution:
            ia = i1+4
            ib = i1+5
            ic = i1+6
            id = i1+7
        else:
            ia = 2
            ib = 3
            ic = 0
            id = 1

        # faces.append( [i1+j for j in range(4) ])
        faces.append( [i1,i1+1,ib,ia])
        faces.append( [i1+1,i1+2,ic,ib])
        faces.append( [i1+2,i1+3,id,ic])
        faces.append( [i1+3,i1,ia,id])

    mesh = bpy.data.meshes.new("mobius")
    mesh.from_pydata(verts, [], faces)

    for p in mesh.polygons:
        p.use_smooth=True

    return mesh

def addPath():
    ## create curve OBJ
    curve = bpy.data.curves.new(name="L1FF", type='CURVE')
    curve.dimensions = '3D'
    path_obj = bpy.data.objects.new("path", curve)
    path_obj.location = (0,0,0)

    ### create milestones
    poly = curve.splines.new('POLY')
    X = np.arange(0.45,-0.01,-0.01)
    poly.points.add(2 + len(X) - 1)
    poly.points[0].co = getVectorOnStrip4D(0.45, 0.1)
    poly.points[1].co = getVectorOnStrip4D(0.45, 0.9)
    ctr = 2
    for x in X:
      poly.points[ctr].co = getVectorOnStrip4D(x, 0.9)
      ctr = ctr+1

    bpy.context.collection.objects.link(path_obj)

    curve.fill_mode = 'FULL'
    curve.bevel_depth = pathThickness

    path_obj.data.materials.append(materialGreen)

    # mesh = bpy.data.meshes.new("path_mesh")
    # mesh.from_pydata(verts, edges, [])

def addPathAnnulus():
    ## create curve OBJ
    curve = bpy.data.curves.new(name="PATH_ANNULUS", type='CURVE')
    curve.dimensions = '3D'
    path_obj = bpy.data.objects.new("path", curve)
    path_obj.location = (0,0,0)

    ### create milestones
    poly = curve.splines.new('POLY')
    X = np.arange(0.45,-0.01,-0.01)
    poly.points.add(len(X) - 1)
    ctr = 0
    for x in X:
      theta = x*(2*pi)
      rot = Matrix.Rotation(theta, 3, [0,0,1])
      v = (rot @ Vector([major_radius, 0, 0])) + offsetAnnulusLeft
      poly.points[ctr].co = (v[0],v[1],v[2],1)
      ctr = ctr+1

    bpy.context.collection.objects.link(path_obj)

    curve.fill_mode = 'FULL'
    curve.bevel_depth = pathThickness

    path_obj.data.materials.append(materialGreen)

def addPathTorusAnnulus():
    curve = bpy.data.curves.new(name="PATH_TORUS_ANNULUS", type='CURVE')
    curve.dimensions = '3D'
    path_obj = bpy.data.objects.new("path_torus_annulus", curve)
    path_obj.location = (0,0,0)

    ### create milestones
    poly = curve.splines.new('POLY')
    X = np.arange(0.55,0.85,+0.01)
    poly.points.add(len(X) - 1)
    ctr = 0
    for x in X:
      theta = x*(2*pi)
      rot = Matrix.Rotation(theta, 3, [0,0,1])
      v = (rot @ Vector([major_radius, 0, 0])) + offsetAnnulusRight
      poly.points[ctr].co = (v[0],v[1],v[2],1)
      ctr = ctr+1

    bpy.context.collection.objects.link(path_obj)

    curve.fill_mode = 'FULL'
    curve.bevel_depth = pathThickness

    path_obj.data.materials.append(materialGreen)

def update_camera(camera, focus_point=Vector((0.0, 0.0, 0.0)), distance=10.0):
    """
    Focus the camera to a focus point and place the camera at a specific distance from that
    focus point. The camera stays in a direct line with the focus point.

    :param camera: the camera object
    :type camera: bpy.types.object
    :param focus_point: the point to focus on (default=``Vector((0.0, 0.0, 0.0))``)
    :type focus_point: Vector
    :param distance: the distance to keep to the focus point (default=``10.0``)
    :type distance: float
    """
    looking_direction = camera.location - focus_point
    rot_quat = looking_direction.to_track_quat('Z', 'Y')

    camera.rotation_mode = 'XYZ'
    camera.rotation_euler = rot_quat.to_euler()
    camera.location = camera.location + rot_quat @ Vector((0.0, 0.0, distance))

def getVectorOnStrip4D(x_1, x_2):
    v = getVectorOnStrip(x_1, x_2)
    return (v[0],v[1],v[2],1)

def getVectorOnStrip(x_1, x_2):
    theta = x_1*(2*pi)
    phi = x_1*pi
    dx = -minor_radius+x_2*(2*minor_radius)

    rot1 = Matrix.Rotation(phi, 3, [0,1,0])
    rot2 = Matrix.Rotation(theta, 3, [0,0,1])
    c1 = Vector([major_radius, 0, 0])
    return rot2 @ (c1 + rot1 @ Vector([0, 0, dx]) )

def addSphere(pos, name, color=(1.0, 1.0, 1.0, 1.0)):
    xi_mesh = bpy.data.meshes.new("init_state_mesh_"+name)
    xi_obj = bpy.data.objects.new("init_state_"+name, xi_mesh)
    xi_obj.location = xi_obj.location + pos

    bpy.context.collection.objects.link(xi_obj)

    ## select active object
    bpy.context.view_layer.objects.active = xi_obj
    xi_obj.select_set(True)

    ## add mesh
    bm = bmesh.new()
    bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16,
        diameter=diameterState)
    bm.to_mesh(xi_mesh)
    bm.free()

    bpy.ops.object.modifier_add(type='SUBSURF')
    bpy.ops.object.shade_smooth()

    ## add color
    mat = bpy.data.materials.new("PKHG")
    mat.diffuse_color = color
    mat.metallic = 0.0
    mat.specular_intensity = 0.0
    xi_obj.active_material = mat

def addState(x_1, x_2, name, color=(1.0, 1.0, 1.0, 1.0)):

    pos = getVectorOnStrip(x_1, x_2)
    addSphere(pos, name, color)

def addStateTorus(u, v, color=(1.0,1.0,1.0,1.0)):
    r0 = torusMajorRadius
    r1 = torusMinorRadius
    x = ((r0 + r1*cos(2*pi*v))*cos(2*pi*u), \
         (r0 + r1*cos(2*pi*v))*sin(2*pi*u), \
         r1*sin(2*pi*v))
    pos = Vector((x[0]+torusLocation[0],x[1]+torusLocation[1],x[2]+torusLocation[2]))
    addSphere(pos, "x_on_torus", color)

def addStateAnnulusLeft(x_1, name, color=(1.0, 1.0, 1.0, 1.0)):
    addStateAnnulus(x_1, name, color, offsetAnnulusLeft)

def addStateAnnulusRight(x_1, name, color=(1.0, 1.0, 1.0, 1.0)):
    addStateAnnulus(x_1, name, color, offsetAnnulusRight)

def addStateAnnulus(x_1, name, color=(1.0, 1.0, 1.0, 1.0), offset =
    offsetAnnulusLeft):

    theta = x_1*(2*pi)
    rot = Matrix.Rotation(theta, 3, [0,0,1])
    pos = (rot @ Vector([major_radius, 0, 0])) + offset
    addSphere(pos, name, color)

def addLightSource():

    light_data = bpy.data.lights.new(name="light_2.80", type='SUN')
    light_data.energy = 5
    light_object = bpy.data.objects.new(name="light_2.80",
      object_data=light_data)
    bpy.context.collection.objects.link(light_object)
    light_object.location = (0, 0, 20)

    light_2 = bpy.data.lights.new(name="light_source", type='AREA')
    light_2.energy = 400
    light_2.size = 13
    light_2_object = bpy.data.objects.new(name="light_source",
      object_data=light_2)
    bpy.context.collection.objects.link(light_2_object)
    light_2_object.location = offsetAnnulusLeft + Vector((0, 0, +1))

    light_3 = bpy.data.lights.new(name="light_source", type='AREA')
    light_3.energy = 400
    light_3.size = 13
    light_3_object = bpy.data.objects.new(name="light_source",
      object_data=light_2)
    bpy.context.collection.objects.link(light_3_object)
    light_3_object.location = offsetAnnulusRight + Vector((0, 0, +1))

def addCamera(location):
    cam = bpy.data.cameras.new("Camera")
    cam_ob = bpy.data.objects.new("Camera", cam)
    bpy.context.collection.objects.link(cam_ob)
    cam_ob.location = location
    bpy.context.scene.camera = cam_ob
    bpy.context.view_layer.objects.active = cam_ob
    update_camera(cam_ob, focus_point=cameraFocusPoint, distance=distanceCamera)

def torusRestriction_mesh(torusLocation):
    r0 = torusMajorRadius
    r1 = torusMinorRadius
    U = np.arange(0.55, 0.86, 0.01)
    V = np.arange(0,1.01,0.01)
    ctr = 0
    verts = []
    faces = []
    for u in U:
      M = len(verts)
      for v in V:
        x = ((r0 + r1*cos(2*pi*v))*cos(2*pi*u), \
             (r0 + r1*cos(2*pi*v))*sin(2*pi*u), \
             r1*sin(2*pi*v))
        x = Vector((x[0]+torusLocation[0],x[1]+torusLocation[1],x[2]+torusLocation[2]))
        verts.extend([x])

      N = len(V)
      if ctr < len(U) - 1:
          for k in range(M,M + N - 1):
            faces.append( [k,k+1,k+N])
            faces.append( [k+1,k+1+N, k+N])

      ctr = ctr + 1

    mesh = bpy.data.meshes.new("trestrict")
    mesh.from_pydata(verts, [], faces)

    for p in mesh.polygons:
        p.use_smooth=True

    return mesh

def addTorus(position):

    torus_mesh = bpy.ops.mesh.primitive_torus_add(major_radius = torusMajorRadius,
        minor_radius = torusMinorRadius-0.05,
        major_segments = 64, minor_segments = 32, location=position)
    torus_obj = bpy.context.object
    torus_obj.name = 'Torus'
    torus_obj.data.materials.append(materialMagenta)

def drawScene(scn, resolution, thick):

    ###########################################################################
    ### DELETE ALL OBJECTS
    ###########################################################################
    bpy.ops.object.select_all(action='SELECT')
    bpy.ops.object.delete()

    ###########################################################################
    ### Add Light
    ###########################################################################
    addLightSource()

    ###########################################################################
    ### Add Camera
    ###########################################################################
    addCamera(cameraLocation)

    ###########################################################################
    ### MOBIUS STRIP
    ###########################################################################

    mobius_strip_mesh = mobius_mesh(resolution, thick)
    mobius_strip_obj = bpy.data.objects.new("mobius strip", mobius_strip_mesh)
    bpy.context.collection.objects.link(mobius_strip_obj)
    bpy.context.view_layer.objects.active = mobius_strip_obj
    mod = mobius_strip_obj.modifiers.new("edge split", 'EDGE_SPLIT')

    mobius_strip_obj.data.materials.append(materialMagenta)
    # mobius_strip_obj.show_transparent = True

    ###########################################################################
    ### ANNULUS LEFT
    ###########################################################################
    annulus_strip_mesh = annulus_mesh(resolution, major_radius -
        circleThickness, major_radius + circleThickness)
    annulus_strip_obj = bpy.data.objects.new("annulus", annulus_strip_mesh)
    annulus_strip_obj.location = offsetAnnulusLeft

    bpy.context.collection.objects.link(annulus_strip_obj)
    bpy.context.view_layer.objects.active = annulus_strip_obj
    mod = annulus_strip_obj.modifiers.new("edge split", 'EDGE_SPLIT')

    annulus_strip_obj.data.materials.append(materialMagenta)

    ###########################################################################
    ### ANNULUS RIGHT
    ###########################################################################
    annulus_r_strip_mesh = annulus_mesh(resolution, major_radius -
        circleThickness, major_radius + circleThickness)
    annulus_r_strip_obj = bpy.data.objects.new("annulus", annulus_r_strip_mesh)
    annulus_r_strip_obj.location = offsetAnnulusRight

    bpy.context.collection.objects.link(annulus_r_strip_obj)
    bpy.context.view_layer.objects.active = annulus_r_strip_obj
    mod = annulus_r_strip_obj.modifiers.new("edge split", 'EDGE_SPLIT')

    annulus_r_strip_obj.data.materials.append(materialMagenta)

    ###########################################################################
    ### ARROW
    ###########################################################################
    arrow_strip_mesh = arrow_mesh(Vector((0,0,+7.5)), length = 2.0, width = 0.5)
    arrow_strip_obj = bpy.data.objects.new("arrow", arrow_strip_mesh)
    arrow_strip_obj.location = offsetAnnulusLeft + Vector((0,-0.8,0))
    bpy.context.collection.objects.link(arrow_strip_obj)
    bpy.context.view_layer.objects.active = arrow_strip_obj

    arrow_r_strip_mesh = arrow_mesh(Vector((0,0,+8.0)), length = 2.0, width = 0.5)
    arrow_r_strip_obj = bpy.data.objects.new("arrow", arrow_r_strip_mesh)
    arrow_r_strip_obj.location = offsetAnnulusRight + Vector((0,0.8,0))
    bpy.context.collection.objects.link(arrow_r_strip_obj)
    bpy.context.view_layer.objects.active = arrow_r_strip_obj

    addTorus(torusLocation)

    restriction_torus_mesh = torusRestriction_mesh(torusLocation)
    restriction_torus_obj = bpy.data.objects.new("arrow", restriction_torus_mesh)
    # restriction_torus_obj.location = offsetAnnulusLeft + Vector((0,-0.8,0))
    bpy.context.collection.objects.link(restriction_torus_obj)
    restriction_torus_obj.data.materials.append(materialGreen)

    ###########################################################################
    ### INITIAL STATE
    ###########################################################################

    addState(0.45, 0.1, "xi", color=colorStartState)
    addState(0, 0.9, "xg", color=colorGoalState)

    addStateAnnulusLeft(0.45, "xi", color=colorStartState)
    addStateAnnulusLeft(0, "xg", color=colorGoalState)

    addStateAnnulusRight(0.55, "xi", color=colorStartState)
    addStateAnnulusRight(0.85, "xg", color=colorGoalState)

    addStateTorus(0.55, 0.1, color=colorStartState)
    addStateTorus(0.85, 0.4, color=colorGoalState)

    addPath()
    addPathAnnulus()

    addPathTorusAnnulus()

    ### RESET ACTIVE OBJECT TO MOBIUS STRIP
    bpy.context.view_layer.objects.active = mobius_strip_obj

    ### SAVE IMAGE
    bpy.context.scene.render.film_transparent = True
    bpy.context.scene.render.image_settings.color_mode = 'RGBA'
    bpy.context.scene.render.filepath = '/home/aorthey/image.png'
    bpy.ops.render.render(write_still = True)

    print(bpy.context.scene.render.filepath)

drawScene(bpy.context.scene, 72, mobiusStripThickness)


from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten
from keras.preprocessing.image import ImageDataGenerator
import pandas  as pd
import numpy as np
import os
import scipy

data_dir = "C:/Users/chenn/OneDrive/Desktop/MUSIC_PLAYER/data"

train_data = ImageDataGenerator(rescale=1./255)
validation_data = ImageDataGenerator(rescale=1./255)

train_generator = train_data.flow_from_directory(
    os.path.join(data_dir,'train'),
    target_size=(48,48),
    batch_size=64,
    color_mode="grayscale",
    class_mode="categorical",
)

validation_generator = validation_data.flow_from_directory(
    os.path.join(data_dir,'test'),
    target_size=(48, 48),
    batch_size=64,
    color_mode="grayscale",
    class_mode="categorical",
)

emotion_model = Sequential()

emotion_model.add(Conv2D(32,kernel_size=(3,3), activation='relu', input_shape=(48, 48, 1)))
emotion_model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
emotion_model.add(MaxPooling2D(pool_size=(2,2)))
emotion_model.add(Dropout(0.25))

emotion_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
emotion_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
emotion_model.add(Dropout(0.25))

emotion_model.add(Flatten())
emotion_model.add(Dense(1024, activation='relu'))
emotion_model.add(Dropout(0.5))

emotion_model.add(Dense(6, activation='softmax'))

emotion_model.compile(loss='categorical_crossentropy',metrics=['accuracy'])

emotion_model_info = emotion_model.fit(
    train_generator,
    steps_per_epoch= 26709//64,

    epochs=50,
    validation_data= validation_generator,
    validation_steps=6578//64
)

model_json = emotion_model.to_json()
with open('emotion_model.json','w') as json_file:
    json_file.write(model_json)

emotion_model.save_weights('emotion_model.h5')