import os
import secrets
import shutil
import subprocess
import tempfile

from fakeredis import FakeRedis
import pytest

from sirendb.core.db import db as db_
from sirendb.core.redis import redis as redis_
from sirendb.web.flask import create_app

@pytest.fixture(autouse=True)
def redis(app, client):
    yield

    if type(redis_.__local) != FakeRedis:
        assert False, 'you should be using fakeredis!'
        return

    redis_.flushall()

class DBFixtureNotIncluded:
    pass

@pytest.fixture(scope='session')
def app():
    os.environ['FLASK_CONFIG'] = ''

    app = create_app(
        config={
            'SQLALCHEMY_DATABASE_URI': DBFixtureNotIncluded,
            'SQLALCHEMY_TRACK_MODIFICATIONS': False,
            'SECRET_KEY': secrets.token_hex(24),
            'RQ_ASYNC': False,
            'RQ_CONNECTION_CLASS': 'fakeredis.FakeRedis',
            'TESTING': True,
            'BIN_DIR': '/app/bin',
            'GEO_BUILD_DIR': '/app/geo/build',

            # 'IMAGE_STORE_TYPE': 'fs',
            # 'IMAGE_STORE_PATH': './images',
            # 'IMAGE_STORE_BASE_URL': 'http://10.120.70.4:3550/media',

            # 'BIN_DIR': '/home/static/projects/sirendb/bin',
            # 'GEO_BUILD_DIR': '/home/static/projects/sirendb/geoapp/build',
            # 'USE_REAL_NGINX': True,
            # 'USE_REAL_CHROME': True,

            'IMAGE_STORE_TYPE': 'test',
            'IMAGE_STORE_BASE_URL': 'http://localhost:5000/media',
            # 'SQLALCHEMY_ECHO': True,
        }
    )
    yield app

@pytest.fixture
def client(app):
    with app.app_context():
        yield app.test_client()

@pytest.fixture(scope='session')
def postgresql():
    temp_dir = tempfile.mkdtemp(prefix='sirendb.')

    subprocess.run([
        'pg_ctl', 'initdb', '--pgdata', temp_dir
    ], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)

    subprocess.run([
        'pg_ctl', '--pgdata', temp_dir, '--wait', '--options', f'-h "" -k "{temp_dir}"', 'start'
    ], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)

    subprocess.run([
        'createdb', '-h', temp_dir, 'sirendb_test'
    ], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)

    yield f'postgresql+psycopg2:///sirendb_test?host={temp_dir}'

    try:
        subprocess.run([
            'pg_ctl', '-D', temp_dir, '-m', 'immediate', 'stop'
        ], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
    finally:
        shutil.rmtree(temp_dir)

@pytest.fixture(scope='session')
def database(app, postgresql):
    app.config['SQLALCHEMY_DATABASE_URI'] = postgresql

    with app.app_context():
        db_.create_all()

    yield db_

    db_.session.remove()

    with app.app_context():
        db_.drop_all()

@pytest.fixture
def db(database, monkeypatch):
    def flush_with_expire(*args, **kwargs):
        database.session.flush(*args, **kwargs)
        database.session.expire_all()

    monkeypatch.setattr(database.session, 'commit', flush_with_expire)
    monkeypatch.setattr(database.session, 'remove', lambda: None)

    yield database

    database.session.rollback()
    database.session.remove()


"""
Fast, flying enemy
"""

import numpy as np

from .enemy import Enemy
from ...constants import BAT_HEALTH, BAT_VELOCITY, BAT_DAMAGE, BAT_WING_FREQUENCY, BAT_SCORE, BAT_NOISE_INTERVAL
from ...constants import FRAMES_TO_ENEMIES_TURN, PLAYER_HEAR_DISTANCE
from ...setup import graphics_dict, sound_dict

class Bat(Enemy):
    """
    Enemy, with low damage, but is fast and bypasses obstacles
    """
    def __init__(self, position):
        super().__init__(position, graphics_dict["bat"].get_image(0))
        self.health = BAT_HEALTH
        self.velocity = BAT_VELOCITY*FRAMES_TO_ENEMIES_TURN
        self.score = BAT_SCORE
        self.looking_angle = 0
        self.damage = BAT_DAMAGE
        self.flying = True
        self.flying_pose = 0
        self.frame = 0
        self.last_noise_time = 0

    def get_damage(self):
        """
        Returns bat's damage.
        """
        return self.damage

    def hurt(self, damage):
        """
        Decreases bat health by damage
        """
        self.health = self.health - damage
        if self.health < 0:
            self.health = 0
            sound_dict['dying_bat'].play()

    def draw(self, screen):
        """
        Draws the bat's sprite in a dynamic way
        in order to create animation
        """
        self.frame += 1
        if self.frame >= BAT_WING_FREQUENCY:
            self.flying_pose += 1
            self.flying_pose %= 4
            self.frame = 0
        self.update_sprite(graphics_dict["bat"].get_image(self.flying_pose), self.looking_angle - 90)
        super().draw(screen)

    def ai_move(self, target, valid_pos, obstacle_pos):
        """
        Trajectory planner for bat
        It goes over structures, so it simply follows the
        straigth line between itself and the player, coupled
        with a flying effect in the form of a MHS
        """
        self.previous_pos = self.curr_pos
        self.curr_pos = self.get_position()

        diff = target - self.get_position()

        diff = diff/np.linalg.norm(diff)
        self.move(diff[0]*self.velocity, diff[1]*self.velocity)

        velocity_vector = self.estimate_velocity()
        if np.linalg.norm(velocity_vector):
            self.looking_angle = -np.degrees(np.arctan2(velocity_vector[1], velocity_vector[0]))

    def play_noise(self, time, player_position):
        """
        Plays a bat's wings sfx
        """
        if np.linalg.norm(player_position - self.get_position()) < PLAYER_HEAR_DISTANCE:
            if time - self.last_noise_time >= BAT_NOISE_INTERVAL:
                self.last_noise_time = time
                sound_dict['bat_wings'].play()


import numpy as np
import sys
import random
from ypstruct import structure

def run(problem, params):

    # Problem Information
    costfunc = problem.costfunc
    nvar = problem.nvar
    varmin = problem.varmin
    varmax = problem.varmax

    # Parameters
    maxit = params.maxit
    npop = params.npop
    pc = params.pc
    nc = int(np.round(pc*npop/2)*2)
    gamma = params.gamma
    mu = params.mu

    # Empty Individual Template
    empty_individual = structure()
    empty_individual.analysts = None
    empty_individual.cost = None

    # Best Solution Ever Found
    bestsol = empty_individual.deepcopy()
    bestsol.cost = np.inf

    # Initialize Population
    pop = empty_individual.repeat(npop)
    for i in range(npop):
        pop[i].analysts = np.array(random.sample(range(varmin, varmax + 1), nvar))
        pop[i].cost = costfunc(pop[i].analysts)
        if pop[i].cost < bestsol.cost:
            bestsol = pop[i].deepcopy()

    # Best Cost of Iterations
    bestcost = np.empty(maxit)
    meancost = np.empty(maxit)
    worstcost = np.empty(maxit)

    # Main Loop
    for it in range(maxit):

        popc = []
        for _ in range(nc//2):

            # Select Parents
            q = np.random.permutation(npop)
            p1 = pop[q[0]]
            p2 = pop[q[1]]

            # Perform Crossover
            c1, c2 = crossover(p1, p2, gamma)

            # Perform Mutation
            c1 = mutate(c1, mu, varmin, varmax)
            c2 = mutate(c2, mu, varmin, varmax)

            # Evaluate First Offspring
            c1.cost = costfunc(c1.analysts)

            # Evaluate Second Offspring
            c2.cost = costfunc(c2.analysts)

            # Add Offsprings to popc
            popc.append(c1)
            popc.append(c2)

        # Merge, Sort and Select
        pop += popc
        pop = sorted(pop, key=lambda x: x.cost)
        pop = pop[0:npop]

        # Store Best Cost
        bestsol = pop[0]
        bestcost[it] = bestsol.cost
        meancost[it] = pop[nc//2].cost
        worstcost[it] = pop[npop-1].cost

        # Show Iteration Information
        print("Iteration {}: Best Cost = {}".format(it, bestcost[it]))

    # Output
    out = structure()
    out.pop = pop
    out.bestsol = bestsol
    out.bestcost = bestcost
    out.meancost = meancost
    out.worstcost = worstcost
    return out

def crossover(p1, p2, gamma=5):
    c1 = p1.deepcopy()
    c2 = p1.deepcopy()
    c1.analysts = np.append(p1.analysts[:gamma], p2.analysts[gamma:])
    c2.analysts = np.append(p2.analysts[:gamma], p1.analysts[gamma:])
    return c1, c2

def mutate(x, mu, varmin, varmax):
    y = x.deepcopy()
    flag = np.random.rand(*x.analysts.shape) <= mu
    ind = np.argwhere(flag)
    y.analysts[ind] = random.randint(varmin, varmax)
    return y


# -*- coding: utf-8 -*-
"""
Created on Tue Sep 21 19:06:54 2021

@author: Bishop
"""

class mongoProcess:
    def get_database():
        from pymongo import MongoClient
        import pymongo

        # Provide the mongodb atlas url to connect python to mongodb using pymongo
        #CONNECTION_STRING = "mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/myFirstDatabase"
        CONNECTION_STRING = "mongodb://localhost:27017/blogusers"
        # mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false
        # Create a connection using MongoClient. You can import MongoClient or use pymongo.MongoClient
        from pymongo import MongoClient
        client = MongoClient(CONNECTION_STRING)

        # Create the database for our example (we will use the same database throughout the tutorial
        return client['blogusers']

if __name__ == "__main__":

    item_1 = {
    "_id" : "U1IT00001",
    "item_name" : "Blender",
    "max_discount" : "10%",
    "batch_number" : "RR450020FRG",
    "price" : 340,
    "category" : "kitchen appliance"
    }

    item_2 = {
    "_id" : "U1IT00002",
    "item_name" : "Egg",
    "category" : "food",
    "quantity" : 12,
    "price" : 36,
    "item_description" : "brown country eggs"
    }

    dbname =  mongoProcess.get_database()
    print(dbname)
    collection_name = dbname["blogusers"] # get the collection
    #collection_name = dbname["blogusers"]
    collection_name.insert_many([item_1,item_2])


from torch.nn.modules.loss import L1Loss
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import numpy as np
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torchvision import transforms
import pandas as pd
from torchsummary import summary
from torch.utils.data import Dataset , DataLoader
from torch.nn import Conv2d , Linear , Dropout2d , BatchNorm2d , MaxPool2d , L1Loss , MSELoss , SiLU , Dropout , init , ReLU , CrossEntropyLoss ,Softmax , Upsample , LeakyReLU
import time
from torch.nn import Sequential
from .common import PredictionNeurons , NeuronBlock , BConvBlock, ResidualBlock,ScalePrediction,ConvBlock
from .config import *

class MultiLayerCreator(nn.Module):

  def __init__ (self,config,resulution,num_classes,in_channel=3,information=False):

    super(MultiLayerCreator,self).__init__()
    self.information=information
    self.resulotion = resulution
    self.num_classes = num_classes
    self.config = config
    self.in_channel = in_channel
    self.layers = self.layer_creator()

  def layer_creator(self):
    layers = nn.ModuleList()

    for conf in self.config:
      if isinstance(conf,list):
        out_c , kernel , sp  = conf
        layers.append(

                ConvBlock(
                    self.in_channel,
                    out_c,
                    kernel_size=kernel,
                    padding=1 if kernel == 3 else 0,
                    stride=sp
                    ).to(device)

        )
        self.in_channel = out_c

      elif isinstance(conf,tuple):
        types , time = conf
        if types == 'B':
          layers +=[
            ResidualBlock( self.in_channel,num_repeat=time)
          ]

        elif types == 'M':
          for i in range(time):
            layers.append(
              ResidualBlock( self.in_channel,time)
            )
        elif types == "S":

          layers += [
            ResidualBlock(self.in_channel,use_residual=False,num_repeat=1),
            ConvBlock(self.in_channel,self.in_channel//2,kernel_size=1),
            ScalePrediction(self.in_channel//2,num_classes=self.num_classes,stride=time)
          ]
          self.in_channel //=2

      elif isinstance(conf , str):

        if conf == "O":
          layers.append(
              NeuronBlock(self.in_channel*84.5, self.num_classes,act=False).to(device)
          )
        elif conf == "P":
          layers.append(
              PredictionNeurons(self.in_channel*3, self.num_classes,act=False).to(device)
          )
        elif conf == "S":

          layers += [
                ResidualBlock(self.in_channel,use_residual=False,num_repeat=1),
                ConvBlock(self.in_channel,self.in_channel//2,kernel_size=1),
                ScalePrediction(self.in_channel//2,num_classes=self.num_classes)
          ]
          self.in_channel //=2

        elif conf == "U":
          layers.append(nn.Upsample(scale_factor=1))
          self.in_channel*=9

    return layers

  def forward(self,x):

    output = []

    route_connections = []

    i=0
    for layer in self.layers:

      if isinstance(layer , ScalePrediction):

        if  self.information:
          print('[INFO] Running On ScalePrediction Layer')
          stp = time.time()

        output.append((layer.forward(x).to(device)))

        if  self.information:
          # print(f'[INFO] Output From Scale Prediction : {x.shape}')
          ttp = (time.time()-stp)
          print('[INFO] Finished On ScalePrediction Layer in {} Sec'.format(ttp) )

        continue
      if  self.information:
        print(f'[INFO] befor the predict : {x.shape}')
      x = layer.forward(x)
      if  self.information:
        print(f"[INFO] Layer is runing on {i} index")
        if isinstance(layer,nn.Upsample) != True:
          print(f"[INFO] Layer Information : in channels : {layer.c_in} ")
        else:
          print("[INFO] Upsample Layer Is Running ")
        print(f'[INFO] after the predict : {x.shape}\n-------------')

      i+=1
      if isinstance(layer,ResidualBlock) and layer.num_repeat==2:

        if  self.information:

          print('[INFO] Repeats ON this Layer : {}'.format(layer.num_repeat))
          strb = time.time()
          print('[INFO] Running On ResidualBlock Layer')

        route_connections.append(x)

        # if  self.information:
        #   routecopy = torch.stack(route_connections).to('cpu').detach().numpy()
        #   vrb = np.array(routecopy)
        #   print('[INFO] Shape  On route connections : {} '.format(vrb.shape))

        if  self.information:
          ttrb = (time.time()-strb)
          print('[INFO] Finished On ResidualBlock Layer in {} Sec'.format(ttrb))

      elif isinstance(layer,nn.Upsample):

        if  self.information:
          print('[INFO] Running On Upsample Layer')
          stu = time.time()

        x = torch.cat((x,route_connections[-1]),dim=1)
        route_connections.pop()

        if  self.information:
          ttu = (time.time()-stu)
          print('[INFO] Finished On Upsample Layer in {} Sec'.format(ttu))

    return output


# -*- coding: PYTHON3 -*-
# @Author: Santosh
# @Last Modified by:   Santosh

""" Fourier transform of musical instruments"""

import matplotlib.pyplot as plt
import numpy as np
import math

# READING DATA FROM PIANO.TXT AND STORING IT IN ARRAY
f1 = open('piano.txt', 'r')
lines = f1.readlines()
y_piano = []
for line in lines:
    p = line.split()
    y_piano.append(float(p[0]))
y_piano = np.array(y_piano)
t_piano = np.linspace(0, 2*math.pi, len(y_piano))

#REAL FOURIER TRANSFORM
fk_piano = np.fft.rfft(y_piano)
freq_piano = np.fft.rfftfreq(t_piano.shape[-1])
fk_piano_abs = []

for i in range(len(freq_piano)):
	fk_piano_abs.append(math.hypot(fk_piano.real[i],fk_piano.imag[i]))

#PLOTTING THE PIANO.TXT FILE AND ITS FOURIER TRANSFORM
plt.suptitle("Piano file and its fourier transform")
plt.subplot(211)
plt.plot(t_piano,y_piano)
plt.xlabel('Time')
plt.ylabel(r'$f(t)$')

plt.subplot(212)
plt.xlabel(r'$k$')
plt.ylabel(r'$F(k)$')
plt.plot(freq_piano[0:10000],fk_piano_abs[0:10000])
plt.savefig('piano.png',bbox_inches = 'tight')
plt.show()
plt.clf()

# READING DATA FROM TRUMPET.TXT AND STORING IT IN ARRAY
f2 = open('trumpet.txt', 'r')
lines = f2.readlines()
y_trumpet = []
for line in lines:
    p = line.split()
    y_trumpet.append(float(p[0]))
y_trumpet = np.array(y_trumpet)
t_trumpet = np.linspace(0, 2*math.pi, len(y_trumpet))

#REAL FOURIER TRANSFORM
fk_trumpet = np.fft.rfft(y_trumpet)
freq_trumpet = np.fft.rfftfreq(t_trumpet.shape[-1])
fk_trumpet_abs = []

for i in range(len(freq_trumpet)):
	fk_trumpet_abs.append(math.hypot(fk_trumpet.real[i],fk_trumpet.imag[i]))

#PLOTTING THE TRUMPET.TXT FILE AND ITS FOURIER TRANSFORM
plt.suptitle("Trumpet file and its fourier transform")
plt.subplot(211)
plt.plot(t_trumpet,y_trumpet)
plt.xlabel('Time')
plt.ylabel(r'$f(t)$')

plt.subplot(212)
plt.xlabel(r'$k$')
plt.ylabel(r'$F(k)$')
plt.plot(freq_trumpet[0:10000],fk_trumpet_abs[0:10000])
plt.savefig('trumpet.png',bbox_inches = 'tight')
plt.show()
plt.clf()


from fastapi import FastAPI
import datetime
from pydantic import BaseModel
from pydantic import BaseModel, Field
from typing import Optional

tags_metadata = [
    {
        "name": "users",
        "description": "Operations with users. The **login** logic is also here.",
    },
    {
        "name": "items",
        "description": "Manage items. So _fancy_ they have their own docs.",
        "externalDocs": {
            "description": "Items external docs",
            "url": "https://fastapi.tiangolo.com/",
        },
    },
]

app = FastAPI(openapi_tags=tags_metadata)

class Item(BaseModel):
    """ Item class description
    - You can itemize
    - You can write `code`
    """
    item_id: int
    name: str
    description: Optional[str] = Field(
        None, title="The description of the item", max_length=300
    )
    price: float = Field(..., gt=0, description="The price must be greater than zero")
    tax: Optional[float] = None

@app.get("/")
def read_items():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    return {"item_name": item.name, "item_id": item_id}


#!/usr/bin/python

import sys

particles = []

i = 0
for line in sys.stdin:

  line = line.split()

  pos = line[0][3:].strip('>,')
  pos = pos.split(',')

  vel = line[1][3:].strip('>,')
  vel = vel.split(',')

  acl = line[2][3:].strip('>')
  acl = acl.split(',')

  particles.append({})

  particles[i]['pos'] = []
  for p in pos:
    particles[i]['pos'].append(int(p))

  particles[i]['vel'] = []
  for v in vel:
    particles[i]['vel'].append(int(v))

  particles[i]['acl'] = []
  for a in acl:
    particles[i]['acl'].append(int(a))

  i += 1

for _ in range(10000):

  min_manhattan = 99999999999
  min_particle = 0

  for i, particle in enumerate(particles):

    particle['vel'][0] += particle['acl'][0]
    particle['vel'][1] += particle['acl'][1]
    particle['vel'][2] += particle['acl'][2]

    particle['pos'][0] += particle['vel'][0]
    particle['pos'][1] += particle['vel'][1]
    particle['pos'][2] += particle['vel'][2]

    manhattan = abs(particle['pos'][0]) + abs(particle['pos'][1]) + abs(particle['pos'][2])
    if manhattan < min_manhattan:
      min_manhattan = manhattan
      min_particle = i

print(min_particle)


from copy import copy, deepcopy

from Britefury.GL.GL import *
from Britefury.GL.GLU import *

from Britefury.Math.Math import Colour3f, Vector3, Matrix4, Plane

from Britefury.Graphics.Graphics import glColor4Colour3fA, glVertex3Point3

from Britefury.FileIO.IOXml import IOXmlEnum, ioXmlReadBoolNode, ioXmlWriteBoolNode, ioObjectFactoryRegister

from Britefury.View.View import PaintLayer

from Britefury.WorkArea.Viewport import ViewportEventHandler, ViewportScrollListener
from Britefury.WorkArea.Viewport3d import Viewport3d, Viewport3dPainter

from Britefury.gSculptConfig import gSculptConfig

from Britefury.UI.FormLayout import FormLayoutFactory

from Britefury.Util.CoEventHandler import CoEventHandler

from Britefury.Kernel.Enum import *

from Britefury.Cell.Cell import *

from Britefury.CellEdit.ChoiceCellEditRadioGroup import ChoiceCellEditRadioGroup

from Britefury.Sheet.Sheet import *
from Britefury.SheetEdit.FieldEditors import *

from Britefury.ProceduralCore.GSProcedure import *

from Britefury.ProceduralTool.GSProcedureTool import *
from Britefury.ProceduralTool.GSProcedureAdjustableInvoker import GSProcedureAdjustableInvoker

from Britefury.Manipulator.Manipulator import *
from Britefury.Manipulator.FieldManipulators import *

from Britefury.Model import ModelDraw
from Britefury.Model.TargetList import TargetList
from Britefury.Model.TargetListFieldEdit import TargetListFieldEdit
from Britefury.Model.Pick3d import Pick3d

from Britefury.Mesh.Mesh import GSProductMesh, CppMeshTweakComponent, CppMeshTweakComponentList, pyMeshTweakComponentList_to_CppMeshTweakComponentList, MeshTweakComponentTarget

from Britefury.MeshTools.MeshEditComponent import MeshEditComponent

# XML IO for MeshTweakComponentTarget

targetIOXmlEnum = IOXmlEnum( MeshTweakComponentTarget, 'MeshTweakComponentTarget', MeshTweakComponentTarget.VERTICES )
targetIOXmlEnum.value( MeshTweakComponentTarget.VERTICES, 'vertices' )
targetIOXmlEnum.value( MeshTweakComponentTarget.EDGES, 'edges' )
targetIOXmlEnum.value( MeshTweakComponentTarget.EDGERINGS, 'edge_rings' )
targetIOXmlEnum.value( MeshTweakComponentTarget.EDGELOOPS, 'edge_loops' )
targetIOXmlEnum.value( MeshTweakComponentTarget.FACES, 'faces' )

ioXmlReadMeshTweakComponentTargetProp = targetIOXmlEnum.propReader
ioXmlReadMeshTweakComponentTargetNode = targetIOXmlEnum.nodeReader
ioXmlWriteMeshTweakComponentTargetProp = targetIOXmlEnum.propWriter
ioXmlWriteMeshTweakComponentTargetNode = targetIOXmlEnum.nodeWriter

# Cell for MeshTweakComponentTarget

class MeshTweakComponentTargetCell (Cell):
	valueClass = MeshTweakComponentTarget
	bAllowNone = False

registerCellType( MeshTweakComponentTarget, MeshTweakComponentTargetCell )

# Cell editor for MeshTweakComponentTarget

class MeshTweakComponentTargetCellEditRadioGroup (ChoiceCellEditRadioGroup):
	def __init__(self):
		super( MeshTweakComponentTargetCellEditRadioGroup, self ).__init__()
		self.vertices = self.addChoice( MeshTweakComponentTarget.VERTICES, _( 'Vertices' ) )
		self.edges = self.addChoice( MeshTweakComponentTarget.EDGES, _( 'Edges' ) )
		self.edgeRings = self.addChoice( MeshTweakComponentTarget.EDGERINGS, _( 'Edge rings' ) )
		self.edgeLoops = self.addChoice( MeshTweakComponentTarget.EDGELOOPS, _( 'Edge loops' ) )
		self.faces = self.addChoice( MeshTweakComponentTarget.FACES, _( 'Faces' ) )

# Field editor for MeshTweakComponentTarget

class MeshTweakComponentTargetFieldEditRadioGroup (BasicSingleFieldWidgetEditor):
	__componentnames__ = [ 'vertices', 'edges', 'edgeRings', 'edgeLoops', 'faces' ]
	def createElement(self, sheetEditContext):
		return MeshTweakComponentTargetCellEditRadioGroup()

#
# MeshTweakComponent class
#

class MeshTweakComponent (object):
	def __init__(self, pick=None, target=MeshTweakComponentTarget.VERTICES, bClearSelection=True, translation=None):
		super( MeshTweakComponent, self ).__init__()
		if pick is None:
			pick = Pick3d()
		self.pick = pick
		self.target = target
		self.bClearSelection = bClearSelection
		if translation is None:
			translation = Vector3()
		self.translation = translation

	def toCppMeshTweakComponent(self):
		return CppMeshTweakComponent( self.pick.toMPick(), self.target, self.bClearSelection, self.translation )

	def __readxml__(self, xmlNode):
		xmlNode.getChild( 'pick' )  >>  self.pick
		self.target = ioXmlReadMeshTweakComponentTargetNode( xmlNode.getChild( 'target' ), self.target )
		self.bClearSelection = ioXmlReadBoolNode( xmlNode.getChild( 'b_clear_selection' ), self.bClearSelection )
		xmlNode.getChild( 'translation' )  >>  self.translation

	def __writexml__(self, xmlNode):
		xmlNode.addChild( 'pick' )  <<  self.pick
		ioXmlWriteMeshTweakComponentTargetNode( xmlNode.addChild( 'target' ), self.target )
		ioXmlWriteBoolNode( xmlNode.addChild( 'b_clear_selection' ), self.bClearSelection )
		xmlNode.addChild( 'translation' )  <<  self.translation

	def __copy__(self):
		return MeshTweakComponent( copy( self.pick ), self.target, self.bClearSelection, copy( self.translation ) )

ioObjectFactoryRegister( 'MeshTweakComponent', MeshTweakComponent )

class ProcMeshTweakComponents (GSProcedure):
	description = _( 'Tweak components' )

	tweaks = Field( TargetList, TargetList() )
	bRestoreSelection = Field( bool, True )

	inputClass = GSProductMesh

	def procedureInvoke(self, inputObject, errorHandler):
		cppTweaks = CppMeshTweakComponentList()
		pyMeshTweakComponentList_to_CppMeshTweakComponentList( [ tweak.toCppMeshTweakComponent()   for tweak in self.tweaks ], cppTweaks )
		inputObject.tweakComponents( cppTweaks, self.bRestoreSelection )
		return inputObject

# Constraints enumeration
class TweakConstraints (Enum):
	NONE = 0
	X_PLANE = 1
	Y_PLANE = 2
	Z_PLANE = 3
	X_AXIS = 4
	Y_AXIS = 5
	Z_AXIS = 6

# Cell class for TweakConstraints
class TweakConstraintsCell (Cell):
	valueClass = TweakConstraints
	bAllowNone = False

registerCellType( TweakConstraints, TweakConstraintsCell )

# Cell editor for TweakConstraints

class TweakConstraintsCellEditRadioGroup (ChoiceCellEditRadioGroup):
	def __init__(self):
		super( TweakConstraintsCellEditRadioGroup, self ).__init__()
		self.none = self.addChoice( TweakConstraints.NONE, 'XYZ' )
		self.xPlane = self.addChoice( TweakConstraints.X_PLANE, 'YZ' )
		self.yPlane = self.addChoice( TweakConstraints.Y_PLANE, 'XZ' )
		self.zPlane = self.addChoice( TweakConstraints.Z_PLANE, 'XY' )
		self.xAxis = self.addChoice( TweakConstraints.X_AXIS, 'X' )
		self.yAxis = self.addChoice( TweakConstraints.Y_AXIS, 'Y' )
		self.zAxis = self.addChoice( TweakConstraints.Z_AXIS, 'Z' )

# Field editor for TweakConstraints

class TweakConstraintsFieldEditRadioGroup (BasicSingleFieldWidgetEditor):
	__componentnames__ = [ 'none', 'xPlane', 'yPlane', 'zPlane', 'xAxis', 'yAxis', 'zAxis' ]

	def createElement(self, rowEditContext):
		return TweakConstraintsCellEditRadioGroup()

class MeshTweakComponentsManipulator (Manipulator, ViewportEventHandler, ViewportScrollListener, Viewport3dPainter):
	EV_BUTTON_DOWN = 0
	EV_BUTTON_UP = 1
	EV_MOTION = 2
	EV_LEAVE = 3
	EV_TARGET = 4
	EV_RESET = 5
	EV_OUTPUTCHANGED = 6

	class Event (object):
		def __init__(self, eventType, **kwargs):
			self.eventType = eventType
			self.__dict__.update( kwargs )

	class ResetException:
		pass

	def __init__(self):
		super( MeshTweakComponentsManipulator, self ).__init__()

		self._tweaksCell = None
		self._targetCell = None
		self._constraintsCell = None

		self._coEventHandler = None

		self._highlightVertexPosition = None
		self._highlightEdgeSegment = None
		self._highlightEdgeRingOrLoopSegments = []
		self._highlightFaceTriangles = None
		self._initialTargetCentre = None
		self._targetCentre = None

		self._f_onAdjustTranslation = None

		self._meshCell = None

		self._o_setUISensitivity( False )

	def manipAttachToView(self, view):
		assert self._view is None, 'already attached to a view'
		super( MeshTweakComponentsManipulator, self ).manipAttachToView( view )
		self._coEventHandler = CoEventHandler( self._p_tweakLoop )
		self._coEventHandler.start()
		self._view.addEventHandler( self, Viewport3d )
		self._view.addScrollListener( self, Viewport3d )
		self._view.addPainter( self, Viewport3d )
		self._view.postRedraw()

	def manipDetachFromView(self):
		assert self._view is not None, 'not attached to a view'
		self._view.removeEventHandler( self, Viewport3d )
		self._view.removeScrollListener( self, Viewport3d )
		self._view.removePainter( self, Viewport3d )
		self._view.postRedraw()
		self._coEventHandler.terminate()
		self._coEventHandler = None
		super( MeshTweakComponentsManipulator, self ).manipDetachFromView()

	def attachCells(self, tweaks, target, constraints):
		self._tweaksCell = tweaks
		self._targetCell = target
		self._constraintsCell = constraints
		self._targetCell.changedSignal.connect( self._p_onTarget )
		self._constraintsCell.changedSignal.connect( self._p_onConstraints )

	def detachCells(self):
		self._targetCell.changedSignal.disconnect( self._p_onTarget )
		self._constraintsCell.changedSignal.disconnect( self._p_onConstraints )
		self._tweaksCell = None
		self._targetCell = None
		self._constraintsCell = None

	def _o_setUISensitivity(self, bSensitive):
		pass

	def attachMeshCell(self, cell):
		assert self._meshCell is None, 'mesh cell already attached'
		self._meshCell = cell
		self._meshCell.changedSignal.connect( self._p_onOutputMeshCellValueChanged )

	def detachMeshCell(self):
		assert self._meshCell is not None, 'no mesh cell attached'
		self._meshCell.changedSignal.disconnect( self._p_onOutputMeshCellValueChanged )
		self._meshCell = None

	def attachInputMeshCell(self, cell):
		cell.changedSignal.connect( self._p_onMeshCellValueChanged )

	def detachInputMeshCell(self, cell):
		cell.changedSignal.disconnect( self._p_onMeshCellValueChanged )

	def _p_getTarget(self, viewport, targetComponentIndex, ringSeedToRing, loopSeedToLoop, ringSeedToRingSegs, loopSeedToLoopSegs):
		mesh = self._p_getMesh()
		targetPick = viewport.createPick()

		target = self._targetCell.value
		if target == MeshTweakComponentTarget.VERTICES:
			# Target vertices
			vertexIndex, thruFaceIndex = mesh.pickVertex( targetPick.toMPick() )

			if vertexIndex != targetComponentIndex:
				if vertexIndex != -1:
					# Highlight the vertex
					self._highlightVertexPosition = mesh.getVertexPosition( vertexIndex )
					self._initialTargetCentre = self._highlightVertexPosition
				else:
					self._highlightVertexPosition = None
					self._initialTargetCentre = None
				self._view.postRedraw()

			targetComponentIndex = vertexIndex
		elif target == MeshTweakComponentTarget.EDGES:
			edgeIndex, closestPoint, thruFaceIndex = mesh.pickEdge( targetPick.toMPick() )

			if edgeIndex != targetComponentIndex:
				if edgeIndex != -1:
					# Highlight the edge
					self._highlightEdgeSegment = mesh.getEdgeSegment( edgeIndex )
					self._initialTargetCentre = self._highlightEdgeSegment.getMidPoint()
				else:
					self._highlightEdgeSegment = None
					self._initialTargetCentre = None
				self._view.postRedraw()

			targetComponentIndex = edgeIndex
		elif target == MeshTweakComponentTarget.EDGERINGS  or  target == MeshTweakComponentTarget.EDGELOOPS:
			seedIndex, closestPoint, thruFaceIndex = mesh.pickEdge( targetPick.toMPick() )

			if seedIndex != targetComponentIndex:
				if seedIndex != -1:
					def getHighlight(seedToList, seedToSegs, discoverFunction):
						segs = []
						try:
							segs = seedToSegs[seedIndex]
						except KeyError:
							try:
								edgeIndices = seedToList[seedIndex]
							except KeyError:
								edgeIndices = discoverFunction( seedIndex )
								seedToList[seedIndex] = edgeIndices
							segs = [ mesh.getEdgeSegment( edgeIndex )   for edgeIndex in edgeIndices ]
							seedToSegs[seedIndex] = segs
						return segs

					# Highlight the edges
					if target == MeshTweakComponentTarget.EDGERINGS:
						self._highlightEdgeRingOrLoopSegments = getHighlight( ringSeedToRing, ringSeedToRingSegs, mesh.discoverEdgeRing )
					elif target == MeshTweakComponentTarget.EDGELOOPS:
						self._highlightEdgeRingOrLoopSegments = getHighlight( loopSeedToLoop, loopSeedToLoopSegs, mesh.discoverEdgeLoop )
					self._initialTargetCentre = mesh.getEdgeSegment( seedIndex ).getMidPoint()
				else:
					self._highlightEdgeRingOrLoopSegments = []
					self._initialTargetCentre = None
				self._view.postRedraw()

			targetComponentIndex = seedIndex
		elif target == MeshTweakComponentTarget.FACES:
			faceIndex, intersectionPoint = mesh.pickFace( targetPick.toMPick() )

			if faceIndex != targetComponentIndex:
				if faceIndex != -1:
					# Highlight the face
					self._highlightFaceTriangles = mesh.getFaceTriangles( faceIndex )
					self._initialTargetCentre = mesh.getFaceCentroid( faceIndex )
				else:
					self._highlightFaceTriangles = None
					self._initialTargetCentre = None
				self._view.postRedraw()

			targetComponentIndex = faceIndex
		else:
			assert False, 'invalid target'

		return targetPick, targetComponentIndex

	def _p_getTweakFromUser(self, ringSeedToRing, loopSeedToLoop):
		self._highlightVertexPosition = None
		self._highlightEdgeSegment = None
		self._highlightEdgeRingOrLoopSegments = []
		self._highlightFaceTriangles = None
		self._initialTargetCentre = None
		self._targetCentre = None
		targetComponentIndex = -1
		targetPick = None
		translation = Vector3()
		targetDistance = None
		ringSeedToRingSegs = {}
		loopSeedToLoopSegs = {}
		viewport = None

		if self._view.pointerViewport is not None:
			targetPick, targetComponentIndex = self._p_getTarget( self._view.pointerViewport, targetComponentIndex, ringSeedToRing, loopSeedToLoop, ringSeedToRingSegs, loopSeedToLoopSegs )

		event = self._coEventHandler.waitForNextEvent()

		# Get the target component
		while not ( event.eventType == MeshTweakComponentsManipulator.EV_BUTTON_DOWN  and  targetComponentIndex != -1 ):
			if event.eventType == MeshTweakComponentsManipulator.EV_RESET:
				self._view.postRedraw()
				raise MeshTweakComponentsManipulator.ResetException

			if event.eventType == MeshTweakComponentsManipulator.EV_TARGET  or  event.eventType == MeshTweakComponentsManipulator.EV_OUTPUTCHANGED:
				self._highlightVertexPosition = None
				self._highlightEdgeSegment = None
				self._highlightEdgeRingOrLoopSegments = []
				self._highlightFaceTriangles = None
				targetComponentIndex = -1
				if event.eventType == MeshTweakComponentsManipulator.EV_OUTPUTCHANGED:
					ringSeedToRingSegs = {}
					loopSeedToLoopSegs = {}

				if self._view.pointerViewport is not None:
					targetPick, targetComponentIndex = self._p_getTarget( self._view.pointerViewport, targetComponentIndex, ringSeedToRing, loopSeedToLoop, ringSeedToRingSegs, loopSeedToLoopSegs )
			else:
				viewport = event.viewport

			if event.eventType != MeshTweakComponentsManipulator.EV_LEAVE  and  viewport is not None:
				targetPick, targetComponentIndex = self._p_getTarget( viewport, targetComponentIndex, ringSeedToRing, loopSeedToLoop, ringSeedToRingSegs, loopSeedToLoopSegs )

			self._targetCentre = self._initialTargetCentre

			event = self._coEventHandler.waitForNextEvent()

		# We have a target component
		# Remove the highlight
		self._highlightVertexPosition = None
		self._highlightEdgeSegment = None
		self._highlightEdgeRingOrLoopSegments = []
		self._highlightFaceTriangles = None

		# If the selection is valid
		if self._initialTargetCentre is not None:
			self._targetCentre = self._initialTargetCentre
			targetDistance = event.viewport.camera.transformWorldToCameraZ( self._initialTargetCentre )
			startPoint = event.viewport.camera.transformScreenToWorldCameraZ( event.viewport.pointerStatus.positionF, targetDistance )
			bScaledMotion = event.bScaledMotion

			# Handle constraints
			constraints = self._constraintsCell.value
			constraintPlane = None
			if constraints == TweakConstraints.X_PLANE:
				constraintPlane = Plane( Vector3( 1.0, 0.0, 0.0 ), self._initialTargetCentre )
			elif constraints == TweakConstraints.Y_PLANE:
				constraintPlane = Plane( Vector3( 0.0, 1.0, 0.0 ), self._initialTargetCentre )
			elif constraints == TweakConstraints.Z_PLANE:
				constraintPlane = Plane( Vector3( 0.0, 0.0, 1.0 ), self._initialTargetCentre )
			elif constraints == TweakConstraints.X_AXIS  or  constraints == TweakConstraints.Y_AXIS  or  constraints == TweakConstraints.Z_AXIS:
				if constraints == TweakConstraints.X_AXIS:
					shaftAxis = Vector3( 1.0, 0.0, 0.0 )
				elif constraints == TweakConstraints.Y_AXIS:
					shaftAxis = Vector3( 0.0, 1.0, 0.0 )
				elif constraints == TweakConstraints.Z_AXIS:
					shaftAxis = Vector3( 0.0, 0.0, 1.0 )
				q = shaftAxis.cross( event.viewport.camera.cameraPosition.forwardAxis )
				if abs( q.sqrLength() )  >=  1.0e-6:
					normal = shaftAxis.cross( q )
					constraintPlane = Plane( normal, self._initialTargetCentre )

			startPointOnPlane = None
			if constraintPlane is not None:
				raySegment = event.viewport.camera.computeRay( event.viewport.pointerStatus.positionF )
				bSuccess, t, hitPoint = raySegment.intersect( constraintPlane )
				if bSuccess:
					startPointOnPlane = hitPoint

			# Add the tweak object to the tweak list
			self._tweaksCell.literalValue = self._tweaksCell.value + [ MeshTweakComponent( deepcopy( targetPick ), self._targetCell.value, not event.viewport.pointerStatus.bControlKey, Vector3() ) ]
		else:
			return

		event = self._coEventHandler.waitForNextEvent()

		# Now, track the translation
		while not( event.eventType == MeshTweakComponentsManipulator.EV_BUTTON_UP  and  event.bScaledMotion == bScaledMotion ):
			if event.eventType == MeshTweakComponentsManipulator.EV_RESET:
				self._view.postRedraw()
				raise MeshTweakComponentsManipulator.ResetException

			if not( event.eventType == MeshTweakComponentsManipulator.EV_TARGET  or  event.eventType == MeshTweakComponentsManipulator.EV_OUTPUTCHANGED ):
				endPoint = event.viewport.camera.transformScreenToWorldCameraZ( event.viewport.pointerStatus.positionF, targetDistance )
				endPointOnPlane = None

				if startPointOnPlane is not None  and  constraintPlane is not None:
					raySegment = event.viewport.camera.computeRay( event.viewport.pointerStatus.positionF )
					bSuccess, t, hitPoint = raySegment.intersect( constraintPlane )
					if bSuccess:
						endPointOnPlane = hitPoint

				if endPointOnPlane is not None:
					translation = endPointOnPlane - startPointOnPlane
				else:
					translation = endPoint - startPoint

					if constraints == TweakConstraints.X_PLANE:
						translation.projectOntoPlane( Vector3( 1.0, 0.0, 0.0 ) )
					elif constraints == TweakConstraints.Y_PLANE:
						translation.projectOntoPlane( Vector3( 0.0, 1.0, 0.0 ) )
					elif constraints == TweakConstraints.Z_PLANE:
						translation.projectOntoPlane( Vector3( 0.0, 0.0, 1.0 ) )

				if constraints == TweakConstraints.X_AXIS  or  constraints == TweakConstraints.Y_AXIS  or  constraints == TweakConstraints.Z_AXIS:
					if constraints == TweakConstraints.X_AXIS:
						shaftAxis = Vector3( 1.0, 0.0, 0.0 )
					elif constraints == TweakConstraints.Y_AXIS:
						shaftAxis = Vector3( 0.0, 1.0, 0.0 )
					elif constraints == TweakConstraints.Z_AXIS:
						shaftAxis = Vector3( 0.0, 0.0, 1.0 )
					translation = translation.projectOntoUnitVector( shaftAxis )

				if bScaledMotion:
					translation *= gSculptConfig.manipulatorFineTuneMotionScale
				self._targetCentre = self._initialTargetCentre + translation
				if self._f_onAdjustTranslation is not None:
					self._f_onAdjustTranslation( translation )
				self._view.forceRedraw()

			event = self._coEventHandler.waitForNextEvent()

		assert len( self._tweaksCell.value ) > 0, 'no tweaks'
		topTweak = self._tweaksCell.value[-1]
		newTopTweak = MeshTweakComponent( topTweak.pick, topTweak.target, topTweak.bClearSelection, translation )
		tweaks = self._tweaksCell.value
		tweaks[-1] = newTopTweak
		self._tweaksCell.literalValue = tweaks
		self._p_commandHistoryBreak()

	def _p_tweakLoop(self):
		ringSeedToRing = {}
		loopSeedToLoop = {}
		while True:
			try:
				self._p_getTweakFromUser( ringSeedToRing, loopSeedToLoop )
			except MeshTweakComponentsManipulator.ResetException:
				ringSeedToRing = {}
				loopSeedToLoop = {}
				self._view.postRedraw()

	def evPrimaryButtonDown(self, viewport):
		super( MeshTweakComponentsManipulator, self ).evPrimaryButtonDown( viewport )
		self._coEventHandler.sendEvent( MeshTweakComponentsManipulator.Event( MeshTweakComponentsManipulator.EV_BUTTON_DOWN, viewport=viewport, bScaledMotion=False ) )

	def evPrimaryButtonUp(self, viewport):
		super( MeshTweakComponentsManipulator, self ).evPrimaryButtonUp( viewport )
		self._coEventHandler.sendEvent( MeshTweakComponentsManipulator.Event( MeshTweakComponentsManipulator.EV_BUTTON_UP, viewport=viewport, bScaledMotion=False ) )

	def evSecondaryButtonDown(self, viewport):
		super( MeshTweakComponentsManipulator, self ).evPrimaryButtonDown( viewport )
		self._coEventHandler.sendEvent( MeshTweakComponentsManipulator.Event( MeshTweakComponentsManipulator.EV_BUTTON_DOWN, viewport=viewport, bScaledMotion=True ) )

	def evSecondaryButtonUp(self, viewport):
		super( MeshTweakComponentsManipulator, self ).evPrimaryButtonUp( viewport )
		self._coEventHandler.sendEvent( MeshTweakComponentsManipulator.Event( MeshTweakComponentsManipulator.EV_BUTTON_UP, viewport=viewport, bScaledMotion=True ) )

	def evMotion(self, viewport, point):
		super( MeshTweakComponentsManipulator, self ).evMotion( viewport, point )
		self._coEventHandler.sendEvent( MeshTweakComponentsManipulator.Event( MeshTweakComponentsManipulator.EV_MOTION, viewport=viewport ) )

	def evEnter(self, viewport, point):
		super( MeshTweakComponentsManipulator, self ).evMotion( viewport, point )
		self._coEventHandler.sendEvent( MeshTweakComponentsManipulator.Event( MeshTweakComponentsManipulator.EV_MOTION, viewport=viewport ) )

	def evLeave(self, viewport, point):
		super( MeshTweakComponentsManipulator, self ).evMotion( viewport, point )
		self._coEventHandler.sendEvent( MeshTweakComponentsManipulator.Event( MeshTweakComponentsManipulator.EV_LEAVE, viewport=viewport ) )

	def evScroll(self, viewport, x, y):
		if viewport.pointerStatus.bShiftKey:
			v = self._constraintsCell.value
			v -= y
			while v < TweakConstraints.NONE:
				v += ( TweakConstraints.Z_AXIS + 1 )
			while v > TweakConstraints.Z_AXIS:
				v -= ( TweakConstraints.Z_AXIS + 1 )
			self._constraintsCell.literalValue = TweakConstraints( v )
		else:
			v = self._targetCell.value
			v -= y
			while v < MeshTweakComponentTarget.VERTICES:
				v += ( MeshTweakComponentTarget.FACES + 1 )
			while v > MeshTweakComponentTarget.FACES:
				v -= ( MeshTweakComponentTarget.FACES + 1 )
			self._targetCell.literalValue = MeshTweakComponentTarget( v )

	def evPaint3d(self, viewport, paintLayer):
		# Paint the target highlight
		if self._highlightVertexPosition is not None:
			ModelDraw.drawVertexPickHighlight( self._highlightVertexPosition, ModelDraw.TARGET_HIGHLIGHT_COLOUR, paintLayer )
		if self._highlightEdgeSegment is not None:
			ModelDraw.drawEdgePickHighlight( self._highlightEdgeSegment, ModelDraw.TARGET_HIGHLIGHT_COLOUR, paintLayer )
		for seg in self._highlightEdgeRingOrLoopSegments:
			ModelDraw.drawEdgePickHighlight( seg, ModelDraw.TARGET_HIGHLIGHT_COLOUR, paintLayer )
		if self._highlightFaceTriangles is not None:
			ModelDraw.drawFacePickHighlight( self._highlightFaceTriangles, ModelDraw.TARGET_HIGHLIGHT_COLOUR, paintLayer )
		if paintLayer == PaintLayer.PAINTLAYER_OVERLAY_BLEND_NODEPTH:
			if self._targetCentre is not None:
				constraints = self._constraintsCell.value
				if constraints != TweakConstraints.NONE:
					targetDistance = viewport.camera.transformWorldToCameraZ( self._targetCentre )
					mag = viewport.camera.transformDistanceAcrossScreenToDistanceThruWorld( ModelDraw.TWEAK_CONSTRAINT_WIDGET_SIZE * viewport.size.y, targetDistance )

					glLineWidth( 4.0 )

					if constraints == TweakConstraints.X_AXIS  or  constraints == TweakConstraints.Y_PLANE  or  constraints == TweakConstraints.Z_PLANE:
						glColor4Colour3fA( Colour3f( 1.0, 0.0, 0.0 ) * ModelDraw.TWEAK_CONSTRAINT_WIDGET_BRIGHTNESS, ModelDraw.TWEAK_CONSTRAINT_WIDGET_ALPHA )
						glBegin( GL_LINES )
						glVertex3Point3( self._targetCentre - Vector3( mag, 0.0, 0.0 ) )
						glVertex3Point3( self._targetCentre + Vector3( mag, 0.0, 0.0 ) )
						glEnd()

					if constraints == TweakConstraints.Y_AXIS  or  constraints == TweakConstraints.X_PLANE  or  constraints == TweakConstraints.Z_PLANE:
						glColor4Colour3fA( Colour3f( 0.0, 1.0, 0.0 ) * ModelDraw.TWEAK_CONSTRAINT_WIDGET_BRIGHTNESS, ModelDraw.TWEAK_CONSTRAINT_WIDGET_ALPHA )
						glBegin( GL_LINES )
						glVertex3Point3( self._targetCentre - Vector3( 0.0, mag, 0.0 ) )
						glVertex3Point3( self._targetCentre + Vector3( 0.0, mag, 0.0 ) )
						glEnd()

					if constraints == TweakConstraints.Z_AXIS  or  constraints == TweakConstraints.X_PLANE  or  constraints == TweakConstraints.Y_PLANE:
						glColor4Colour3fA( Colour3f( 0.125, 0.375, 1.0 ) * ModelDraw.TWEAK_CONSTRAINT_WIDGET_BRIGHTNESS, ModelDraw.TWEAK_CONSTRAINT_WIDGET_ALPHA )
						glBegin( GL_LINES )
						glVertex3Point3( self._targetCentre - Vector3( 0.0, 0.0, mag ) )
						glVertex3Point3( self._targetCentre + Vector3( 0.0, 0.0, mag ) )
						glEnd()

					glLineWidth( 1.0 )

	def _p_onTarget(self):
		self._coEventHandler.sendEvent( MeshTweakComponentsManipulator.Event( MeshTweakComponentsManipulator.EV_TARGET ) )

	def _p_onConstraints(self):
		self._view.postRedraw()

	def _p_onMeshCellValueChanged(self):
		if self._coEventHandler is not None:
			self._coEventHandler.sendEvent( MeshTweakComponentsManipulator.Event( MeshTweakComponentsManipulator.EV_RESET ) )

	def _p_onOutputMeshCellValueChanged(self):
		if self._coEventHandler is not None:
			self._coEventHandler.sendEvent( MeshTweakComponentsManipulator.Event( MeshTweakComponentsManipulator.EV_OUTPUTCHANGED ) )

	def _p_getMesh(self):
		if self._meshCell is not None:
			return self._meshCell.getValueAsClass( GSProductMesh )
		else:
			return None

class MeshTweakComponentsFieldManipulator (GSProcedureToolFieldManipulator):
	def __init__(self, tweaksField, targetField, constraintsField):
		super( MeshTweakComponentsFieldManipulator, self ).__init__()
		self._tweaksField = tweaksField
		self._targetField = targetField
		self._constraintsField = constraintsField

	def createElement(self, sheetEditContext):
		return MeshTweakComponentsManipulator()

	def destroyElement(self, element, sheetEditContext):
		del sheetEditContext.sheetEditor.tweakManip

	def initialiseElement(self, element, sheetEditContext):
		tweaks = self._p_getCell( self._tweaksField, sheetEditContext )
		target = self._p_getCell( self._targetField, sheetEditContext )
		constraints = self._p_getCell( self._constraintsField, sheetEditContext )
		element.attachCells( tweaks, target, constraints )
		if sheetEditContext.commandHistory is not None:
			element.commandHistory = sheetEditContext.commandHistory

	def shutdownElement(self, element, sheetEditContext):
		element.detachCells()
		element.commandHistory = None

	def installElementEventHandlers(self, element, sheetEditContext):
		element.manipAttachToView( sheetEditContext.view )

	def uninstallElementEventHandlers(self, element, sheetEditContext):
		element.manipDetachFromView()

	def attachInputProductCell(self, element, cell):
		element.attachInputMeshCell( cell )

	def detachInputProductCell(self, element, cell):
		element.detachInputMeshCell( cell )

	def attachOutputProductCell(self, element, cell):
		element.attachMeshCell( cell )

	def detachOutputProductCell(self, element, cell):
		element.detachMeshCell()

class TweakComponentsAdjustableInvoker (GSProcedureAdjustableInvoker):
	functionClass = ProcMeshTweakComponents

	def initInvoke(self):
		# Initialise with full pre-compute. This will remove the cost of the full pre-compute which would normally occur on each modification of the tweak list
		self._inputObject.preComputeFull()

	def main(self):
		self.mesh = deepcopy( self._inputObject )
		cppTweaks = CppMeshTweakComponentList()
		pyMeshTweakComponentList_to_CppMeshTweakComponentList( [ tweak.toCppMeshTweakComponent()   for tweak in self._proc.tweaks ], cppTweaks )
		self.mesh.tweakComponents( cppTweaks, False )

	def save(self):
		self.mesh.saveMarkedComponentPositions()

	def restore(self):
		self.mesh.restoreMarkedComponentPositions()

	def adjustTranslation(self, translation):
		self.mesh.restoreMarkedComponentPositions()
		self.mesh.transformMarkedComponents( Matrix4.translate( translation ) )

	def getResult(self):
		return self.mesh

class ToolMeshTweakComponents (GSProcedureTool):
	sheet = SheetRefField( ProcMeshTweakComponents )

	functionClass = ProcMeshTweakComponents
	adjustableInvoker = TweakComponentsAdjustableInvoker
	pageTitle = _( 'Tweak' )
	titleText = _( 'Tweak Components' )

	tweakTarget = Field( MeshTweakComponentTarget, MeshTweakComponentTarget.VERTICES )
	tweakConstraints = Field( TweakConstraints, TweakConstraints.NONE )

	tweakListLabel = FieldLabelWithFn( sheet.tweaks, _( 'Tweaks:' ) )
	tweakListEditor = TargetListFieldEdit( sheet.tweaks, targetLabelText=_( '%d tweak' ), pluralTargetLabelText=_( '%d tweaks' ), removeTargetButtonText=_( 'Remove tweak' ) )

	tweakManip = MeshTweakComponentsFieldManipulator( sheet.tweaks, tweakTarget, tweakConstraints )
	tweakManip.enable()

	targetRadio = MeshTweakComponentTargetFieldEditRadioGroup( tweakTarget )

	constraintsRadio = TweakConstraintsFieldEditRadioGroup( tweakConstraints )

	layout = FormLayoutFactory()
	layout.textBlock( _( 'Click and drag to move. Selection is cleared on each click, unless <control> is pressed.\n'  'Use the scroll wheel to switch between component types.\n'  'Use the scroll wheel, with <shift> held to switch between constraints.' ) )
	layout.row()
	layout.row()  <<  _( 'Component type:' )
	layout.row()  <<  targetRadio.vertices
	layout.row()  <<  targetRadio.edges
	layout.row()  <<  targetRadio.edgeRings
	layout.row()  <<  targetRadio.edgeLoops
	layout.row()  <<  targetRadio.faces
	layout.row()
	layout.row()  <<  tweakListLabel.label
	layout.row()  <<  tweakListEditor.numTargets
	layout.row()  <<  None  <<  ( tweakListEditor.removeTarget, 2 )  <<  None
	layout.row()
	layout.row()  <<  _( 'Constraints:' )
	layout.row()  <<  None  <<  constraintsRadio.none  <<  None
	layout.row()  <<  constraintsRadio.xPlane  <<  constraintsRadio.yPlane  <<  constraintsRadio.zPlane
	layout.row()  <<  constraintsRadio.xAxis  <<  constraintsRadio.yAxis  <<  constraintsRadio.zAxis
	layout.row()
	layout.finalise()

	def __init__(self, view, editorSettings, parentWindow, commandHistory, painterFactory):
		super( ToolMeshTweakComponents, self ).__init__( view, editorSettings, parentWindow, commandHistory, painterFactory )
		self.tweakManip._f_onAdjustTranslation = self._onAdjustTranslation

	def shutdownTool(self):
		self.tweakManip._f_onAdjustTranslation = None
		super( ToolMeshTweakComponents, self ).shutdownTool()

	def _onAdjustTranslation(self, translation):
		self._adjustableInvoker.adjustTranslation( translation )

	def setTarget(self, target):
		self.tweakTarget = target

#
#
# OLD VERSION OF TWEAK
#
#

class _MeshTweak (object):
	def __init__(self, pick=None, bClearSelection=True, translation=None):
		super( _MeshTweak, self ).__init__()
		if pick is None:
			pick = Pick3d()
		self.pick = pick
		self.bClearSelection = bClearSelection
		if translation is None:
			translation = Vector3()
		self.translation = translation

	def toMeshTweakComponent(self, target):
		return MeshTweakComponent( self.pick, target, self.bClearSelection, self.translation )

	def __readxml__(self, xmlNode):
		xmlNode.getChild( 'pick' )  >>  self.pick
		self.bClearSelection = ioXmlReadBoolNode( xmlNode.getChild( 'b_clear_selection' ), self.bClearSelection )
		xmlNode.getChild( 'translation' )  >>  self.translation

	def __writexml__(self, xmlNode):
		xmlNode.addChild( 'pick' )  <<  self.pick
		ioXmlWriteBoolNode( xmlNode.addChild( 'b_clear_selection' ), self.bClearSelection )
		xmlNode.addChild( 'translation' )  <<  self.translation

	def __copy__(self):
		return _MeshTweak( copy( self.pick ), self.bClearSelection, copy( self.translation ) )

ioObjectFactoryRegister( 'MeshTweak', _MeshTweak )

class _ProcMeshTweak (GSProcedure):
	__iotypename__ = 'ProcMeshTweak'

	description = '**DEPRACATED**'

	targetComponent = Field( MeshEditComponent, MeshEditComponent.VERTICES )
	tweaks = Field( TargetList, TargetList() )
	bRestoreSelection = Field( bool, True )

	inputClass = GSProductMesh

	# Handle old version of 'ProcMeshTweak', which did not have the @bRestoreSelection field.
	# It should default to False. Any newer version will override this value if present.
	def __readxml__(self, xmlNode):
		self.bRestoreSelection = False
		super( _ProcMeshTweak, self ).__readxml__( xmlNode )

	def __ioreplacement__(self):
		target = MeshTweakComponentTarget.VERTICES

		inTarget = self.targetComponent
		if inTarget == MeshEditComponent.VERTICES:
			target = MeshTweakComponentTarget.VERTICES
		elif inTarget == MeshEditComponent.EDGES:
			target = MeshTweakComponentTarget.EDGES
		elif inTarget == MeshEditComponent.FACES:
			target = MeshTweakComponentTarget.FACES

		proc = ProcMeshTweakComponents()
		proc.bRestoreSelection = self.bRestoreSelection
		tweaks = TargetList()
		for tweak in self.tweaks:
			tweaks.append( tweak.toMeshTweakComponent( target ) )
		proc.cells.tweaks.literalValue = tweaks
		return proc


from relationalai import LocalConnection

import os
import tempfile
import unittest

class TestInstallSource(unittest.TestCase):

    def testInstallSource(self):
        conn = LocalConnection(dbname="python-sdk")
        conn.debug_level = 1
        self.assertTrue(conn.create_database(overwrite=True))
        self.assertTrue(len(conn.install_source(src_name="src_1", src_str="def foo = 1").get("problems")) == 0)

        # create a tempfile
        fd, path = tempfile.mkstemp()
        with os.fdopen(fd, "w") as tmp:
            tmp.write("def bar = 3")
        self.assertTrue(len(conn.install_source(src_name="src_3", src_path=path).get("problems")) == 0)
        self.assertTrue(len(conn.install_source(src_name="src_2", src_str="def foo = ").get("problems")) == 2)

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


from itertools import combinations_with_replacement

def solution(n, info):
    score = -1
    answer = [-1]
    i = list(combinations_with_replacement(range(0,11),n))
    for a in i:
        tmp = calculate(a, info, n)
        if tmp[0] > score:
            score = tmp[0]
            answer = tmp[1]
    return answer

def calculate(a, info, n):
    tmp = [0] * 11
    rion = 0
    peach = 0
    for i in a:
        tmp[10 - i] += 1
    for i in range(len(tmp)):
        if not (tmp[i] == 0 and info[i] == 0):
            if tmp[i] > info[i]:
                rion += 10 - i
            else:
                peach += 10 - i
    if rion > peach:
        return [rion - peach, tmp]
    else:
        return [-1, [-1]]


import random, sys, time

wins, losses, ties = 0, 0, 0

while True:
	time.sleep(0.5)
	print("%s Wins, %s Losses, %s Ties" %(wins, losses, ties))
	while True:
		time.sleep(0.5)
		print("Enter your move! 'R' for Rock, 'P' for Paper and 'S' for Scissor ('q' for exit): ")
		player = input().lower()
		if player == "q":
			print("Good Bye!")
			sys.exit()
		if player == "r" or player == "p" or player == "s":
			break
		print("Please tpye r or p or s or q only!")

	if player == "r":
		print("Rock versus...")
	elif player == "p":
		print("Paper versus...")
	elif player == "s":
		print("Scissor versus...")
	time.sleep(0.5)
	randomNumber = random.randint(1,3)
	if randomNumber == 1:
		computer = "r"
		print("Rock")
	elif randomNumber == 2:
		computer = "p"
		print("Paper")
	elif randomNumber == 3:
		computer = "s"
		print("Scissor")

	time.sleep(0.3)
	if player==computer:
		ties+=1
		print("Tie!")

	#Wins
	elif player=="r" and computer=="s":
		print("You won!")
		wins+=1
	elif player=="s" and computer=="p":
		print("You won!")
		wins+=1
	elif player=="p" and computer=="r":
		print("You won!")
		wins+=1

	#Loses
	elif player=="r" and computer=="p":
		print("You lose!")
		losses+=1
	elif player=="p" and computer=="s":
		print("You lose!")
		losses+=1
	elif player== "s" and computer=="r":
		print("You lose")
		losses+=1


# coding=utf-8
# filename: benchmark.py

"""
This file includes the procedure to process the data from iperf3 with single
thread, i.e. "iperf3 -c hostname [-i time]" and draws a LINE CHART for it.
"""
import json
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
import re
import statsmodels.api as sm
import matplotlib.patches as mpatches
import pandas as pd
from scipy import stats

import itertools

def read_text_file(file_name):
    target_file = open(file_name)
    lines = target_file.readlines()

    target_file.close()
    return lines

def get_result_dictionary(intervals, keys):
    result = {}

    #   Create entries in dictionary for all flows
    for i in range(len(keys)):
        flow_table = {}
        rtt_list = []
        snd_cwnd_list = []
        bits_per_second_list = []
        retransmits_list = []
        flow_table["rtt"] = rtt_list
        flow_table["snd_cwnd"] = snd_cwnd_list
        flow_table["bits_per_second"] = bits_per_second_list
        flow_table["retransmits"] = retransmits_list
        #   Add entry
        result[keys[i]] = flow_table

    # Load data for each flow
    for i in range(0, len(intervals)):
        for j in range(len(intervals[i]['streams'])):
            ID = intervals[i]['streams'][j]['socket']
            #   Convert rtt from us to ms
            result[ID]["rtt"].append(
                intervals[i]['streams'][j]['rtt'] / 1000.0)
            #   Convert from bit to Kbits
            result[ID]["snd_cwnd"].append(
                intervals[i]['streams'][j]['snd_cwnd'] / 1024)
            #   Convert from bit to Mbit
            result[ID]["bits_per_second"].append(
                intervals[i]['streams'][j]['bits_per_second'] / (1024 * 1024))
            result[ID]["retransmits"].append(
                intervals[i]['streams'][j]['retransmits'])

    return result

def sort_by_value(d):
    items = d.items()
    back_items = [[v[1], v[0]] for v in items]
    back_items.sort()
    return [back_items[i][1] for i in range(0, len(back_items))]

def flip(items, ncol):
    return itertools.chain(*[items[i::ncol] for i in range(ncol)])

def main():
    """
    Main Function, nothing to comment
    """

    algorithms = ["bbr", "scalable", "bic", "cubic", "highspeed", "htcp",
                  "hybla", "illinois", "vegas", "yeah", "reno"]
    names = ["BBR", "Scalable", "BIC", "CUBIC", "High Speed", "H-TCP", "Hybla",
             "Illinois", "Vegas", "YeAH", "Reno"]
    file_path = "../lab-record/result/true_topo/"
    # round_name = ["round_0/", "round_1/", "round_2/", "round_3/", "round_4/",
    # "round_5/"]
    round_name = ["round_0/"]

    markers = [".", ",", "o", "v", "^", "<", ">", "1", "2", "3", "4", "s"]
    colors = ["black", "red", "peru", "darkorange", "gold", "yellowgreen",
              "deeppink", "darkviolet", "slateblue", "deepskyblue",
              "mediumturquoise", "lime"]

    scenarios = ["lan_to_dc1/", "aliyun2_to_dc2/", "amazon_to_aliyun1/"]

    # tests = ["test_0/", "test_1/"]
    tests = ["test_0/"]

    scenario = scenarios[2]

    fsize = 52

    result = {}
    avg = {}
    for algorithm in algorithms:
        result[algorithm] = []
        avg[algorithm] = []

    # data
    for t in tests:
        for algorithm in algorithms:
            for r in round_name:
                file_name = file_path + scenario + t + r + algorithm + ".log"
                json_object = json.loads("".join(read_text_file(file_name)))
                intervals = json_object["intervals"]
                for i in range(0, len(intervals)):
                    result[algorithm].append(
                        intervals[i]["streams"][0]["bits_per_second"] /
                        (1024.0 * 1024.0))

    for algorithm in algorithms:
        for i in range(1, 21):
            temp = []
            for j in range(0, 30):
                temp.append(result[algorithm][i - j])
            avg[algorithm].append(np.average(temp))

    # plot bandwidth in fig 2
    time = []
    for i in range(0, 20):
        time.append((i + 1) * 30)

    for i in range(len(algorithms)):
        plt.plot(time, avg[algorithms[i]], linewidth=3,
                 label=names[i], color=colors[i], marker=markers[i])

    plt.xlabel("Time(s)", fontsize=fsize)
    plt.xticks(fontsize=fsize)
    # plt.xlim(0, 3)
    plt.ylabel("Throughput(Mbps)", fontsize=fsize)
    plt.yticks(fontsize=fsize)
    # plt.ylim(1.05, 1.2)

    ax = plt.subplot(111)
    handles, labels = ax.get_legend_handles_labels()
    # plt.legend(fontsize=35, loc='upper center')
    plt.legend(flip(handles, 3), flip(labels, 3),
               loc="upper center", ncol=4, fontsize=35)

    plt.show()

    return 0

#   Function Main
if __name__ == '__main__':
    main()


import numpy as np
from sklearn.metrics import RocCurveDisplay
import matplotlib.pyplot as plt
import os

cert_or_unm = 'snd-cert' if False else 'snd-unm'
path = os.path.join('.', 'negative-selection', 'syscalls', cert_or_unm)
jarfile = os.path.join('.', 'negative-selection', 'negsel2.jar')

filename = rf'{path}\{cert_or_unm}'
trainfile = f'{filename}-proc.train'
v = 1
testfile = f'{filename}.{v}-proc.test'
outfile = f'{filename}.{v}.out'

n = 12
r = 4

def preprocess(file):
    chunk = n
    step = 1
    result = ""
    with open(file) as f:
        for line in f.read().split():
            if len(line) < chunk:
                result += line*(chunk//len(line))+line[:chunk % len(line)]+'\n'

            i = 0
            while i+chunk <= len(line):
                result += line[i:i+chunk]+'\n'
                i += step
            result += '\n'

    return result[:-1]

def plot_base():

    plt.plot([0, 1], [0, 1], "k--", label="chance level (AUC = 0.5)")
    plt.axis("square")
    plt.grid(alpha=0.5)
    plt.title(f'natural selection with n={n}')
    plt.legend(loc='lower right')
    plt.tight_layout()

    plt.show()

if __name__ == '__main__':
    # preprocess train and test
    with open(trainfile, 'w') as out:
        out.write(preprocess(f'{filename}.train'))

    with open(testfile, 'w') as out:
        out.write(preprocess(f'{filename}.{v}.test'))

    ax = plt.gca()
    for r in range(3, 9):
        # negative selection
        os.system(
            f'cmd /c "java -jar {jarfile} -self {trainfile} -alphabet file://{filename}.alpha -n {n} -r {r} -c -l < {testfile} > {outfile}')

        # post process output
        with open(outfile) as file:
            lines = file.read().split('NaN')
            pred = []
            for l in lines:
                scores = np.array(l.split(), dtype=np.float)
                pred.append(np.max(scores))

        pred = np.array(pred)

        with open(f'{filename}.{v}.labels') as file:
            label = np.array(file.read().split(), dtype=np.float)

        RocCurveDisplay.from_predictions(
            label, pred, name=f'negative selection (r={r})', ax=ax)

    plot_base()


import numpy as np

from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Activation, Input, Dropout
from tensorflow.keras.models import Model, load_model

from tensorflow.keras.layers import BatchNormalization, Concatenate, Lambda, Flatten, Dense

from tensorflow.keras.regularizers import l2
from tensorflow.keras import backend as K

from numpy import genfromtxt
from io import StringIO

import sys

def get_siamese_model(input_shape):
    """
        Model architecture based on the one provided in: http://www.cs.utoronto.ca/~gkoch/files/msc-thesis.pdf
    """

    # Define the tensors for the two input images
    left_input = Input(input_shape)
    right_input = Input(input_shape)

    # Neural Network
    model = Sequential()
    model.add(Dense(256, input_shape=input_shape, activation="tanh"))
    # , bias_initializer='he_uniform'))#, kernel_regularizer=l2(1e-3))) # , bias_initializer='he_uniform'))
    model.add(Dropout(0.5))
    model.add(Dense(256, activation='tanh'))
    # , kernel_regularizer=l2(1e-3))#, bias_initializer='he_uniform'))
    model.add(Dropout(0.5))

    #     model2 = Sequential()
    #     model2.add(Dense(512, activation='relu', input_shape=input_shape, bias_initializer='he_uniform'))
    #     model2.add(Dropout(0.1))
    #     model2.add(Dense(512, activation='sigmoid', kernel_regularizer=l2(1e-3)))  # , bias_initializer='he_uniform'))

    # Generate the encodings (feature vectors) for the two images
    encoded_l = model(left_input)
    encoded_r = model(right_input)

    # Add a customized layer to compute the absolute difference between the encodings
    L1_layer = Lambda(lambda tensors: K.abs(tensors[0] - tensors[1]))
    L1_distance = L1_layer([encoded_l, encoded_r])

    # Add a dense layer with a sigmoid unit to generate the similarity score
    prediction = Dense(1, activation='sigmoid')(L1_distance)  # ,bias_initializer=initialize_bias

    # Connect the inputs with the outputs

    siamese_net = Model(inputs=[left_input, right_input], outputs=prediction)

    # return the model
    return siamese_net

def load_my_model(model_file_name, number_of_features):
    model = get_siamese_model((number_of_features,))
    model.load_weights(model_file_name)

    optimizer = Adam(lr=0.00006)
    model.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=['accuracy'])
    return model

def apply_siamese_model(model, number_of_features, left_input_str, right_input_str):
    left_input = genfromtxt(StringIO(left_input_str), delimiter=',')
    right_input = genfromtxt(StringIO(right_input_str), delimiter=',')

    if len(left_input.shape) == 1:
        left_input = np.array([left_input])
    if len(right_input.shape) == 1:
        right_input = np.array([right_input])

    n_examples = len(left_input)

    # print("n_examples: "+str(n_examples))
    pairs = [np.zeros((n_examples, number_of_features)) for i in range(2)]

    for i in range(0, n_examples):
        pairs[0][i] = left_input[i]
        pairs[1][i] = right_input[i]

    # print("#Pairs: ",len(pairs))

    # print(pairs)

    predictions = model.predict(pairs)

    result = ""
    for i in range(0, n_examples):
        result = result + str(predictions[i][0]) + " "

    return result

# print(sys.argv[3])

model = load_my_model(sys.argv[1], int(sys.argv[2]))

res = apply_siamese_model(model, int(sys.argv[2]), sys.argv[3], sys.argv[4])
print(res)


from os import makedirs, path, umask
from time import time
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
from moviepy.editor import AudioFileClip

OUTPUT_DIR = "videos"

class VideoMaker:
    def __init__(self, audio_path: str, images_path: str, duration: float, number_of_images: int, user_name: str):
        self.audio_path = audio_path
        self.images_path = images_path
        self.duration = duration
        self.number_of_images = number_of_images
        self.user_name = user_name
        self.create_videos_folder()
        self.create_video()

    def create_videos_folder(self):
        if not path.exists(OUTPUT_DIR):
            umask(0)
            makedirs(OUTPUT_DIR, exist_ok=True)

    def create_video(self):
        fps =  self.number_of_images / self.duration

        audio_clip = AudioFileClip(self.audio_path)
        audio_clip = audio_clip.set_end(self.duration)

        video_clip = ImageSequenceClip(self.images_path, fps=fps)
        video_clip.audio = audio_clip

        video_file_path = "{0}/{1}_{2}.mp4".format(OUTPUT_DIR, self.user_name, int(time()))
        video_clip.write_videofile(video_file_path)


# A class is referred to as a Data Structure or Type
# Holds data and behaviours these are called Attributes and Methods
# We create multiple's from one definition

# Syntax: class MyClass

# Attributes
# Variables that belong to that class
# Always public ( can be accessed after the '.')
# MyClass.MyAttribute

# Methods
# Function that belong to a class
# Either does something to he classes data or does something with the classes data

# Objects
# Objects are much like a variable, however hold a whole classes information inside
# Can creat multiple instance of an object/class, Hence 'Object'
# Can store an manipulate information inside the object, Much like we do with string class/object

class MyClass:
	number = 0
	name = "nonname"

def Main():
	# create an object of our class
	me = MyClass()
	me.number = 127
	me.name = "Jonatan Sala"

	friend = MyClass()
	friend.number = 3
	friend.name = "Igor"

	empty = MyClass()

	print("Name: " + me.name + " Number: " + str(me.number))
	print("Name: " + friend.name + " Number: " + str(friend.number))
	print("Name: " + empty.name + " Number: "+  str(empty.number))

if __name__ == '__main__':
	Main()


from module_basic.phonebook import phonebookmanager2 as pbm
import sys

while True:
    print('====================================')
    print('메뉴 : \n(1) 정보 입력 \n(2) 리스트 출력 \n(3) 검색 \n(4) 삭제 \n(5) 종료')

    choice = input('\n메뉴 번호를 입력해주세요. >>')

    if choice == '1':
        pbm.insertMember()
    elif choice == '2':
        pbm.showList()
    elif choice == '3':
        pbm.searchInfo()
    elif choice == '4':
        pbm.deleteInfo()
    elif choice == '5':
        sys.exit
    else :
        print('\n메뉴 번호를 확인해주세요.\n')


from db.run_sql import run_sql
from models.vet import Vet
from models.pet import Pet
import pdb;

def delete_all():
    sql = "DELETE FROM vets"
    run_sql(sql)

def delete(id):
    sql = "DELETE FROM vets WHERE id = %s"
    values = [id]
    run_sql(sql, values)

def save(vet):
    sql = "INSERT INTO vets (name, email, phone) VALUES (%s, %s, %s) RETURNING id"
    values = [vet.name, vet.email, vet.phone]
    results = run_sql(sql, values)
    id = results[0]['id']
    vet.id = id
    return vet

def select_all():
    vets = []
    sql = "SELECT * FROM vets"
    results = run_sql(sql)

    for result in results:
        vet = Vet(result["name"], result["email"], result["phone"], result["id"])
        vets.append(vet)
    return vets

def select(id):
    vet = None
    sql = "SELECT * FROM vets WHERE id = %s"
    values = [id]
    results = run_sql(sql, values)
    if results:
        result = results[0]
        vet = Vet(result['name'], result['email'], result['phone'], result['id'])
    return vet

def show_all(id):
    pets = []
    sql = "SELECT * FROM pets WHERE vet_id = %s"
    values = [id]
    results = run_sql(sql, values)
    for result in results:
        if results:
            # result = results[0]
            pet = Pet(result["name"], result["dob"], result["type"], result["treatment_notes"], result["owner_id"], result["vet_id"], result["id"])
            pets.append(pet)
            print(pets)
    return pets

def update(vet):
    sql = "UPDATE vets SET (name, email, phone) = (%s, %s, %s) WHERE id = %s"
    values = [vet.name, vet.email, vet.phone, vet.id]
    run_sql(sql, values)


@namespace
class SpriteKind:
    enemy_projectile = SpriteKind.create()
    # GH2
    boss = SpriteKind.create()
    # end GH2

# variables
deceleration = 0.9
player_speed = 20
player_shot_speed = -100
enemy_shot_speed = 70
# GH1
powerup_overheated = False
# end GH1

# sprites
ship = sprites.create(assets.image("ship"), SpriteKind.player)
ship.y = 108
ship.z = 5
ship.set_stay_in_screen(True)
formation_center = sprites.create(image.create(1, 1))
formation_center.set_bounce_on_wall(True)
formation_center.set_velocity(randint(-10, 10), randint(-10, 10))
# GH1
powerup_bar = statusbars.create(60, 3, StatusBarKind.magic)
powerup_bar.set_position(128, 118)
powerup_bar.max = 100
powerup_bar.value = 0
# end GH1

# setup
info.set_life(3)
info.set_score(0)
effects.star_field.start_screen_effect()

def set_offset(enemy: Sprite):
    x_offset = randint(-4, 4) * 16
    y_offset = randint(-3, 1) * 16
    sprites.set_data_number(enemy, "x_offset", x_offset)
    sprites.set_data_number(enemy, "y_offset", y_offset)

def spawn_enemy(start_x, start_y):
    enemy = sprites.create(assets.image("enemy ship 1"), SpriteKind.enemy)
    if randint(1, 2) == 2:
        enemy.set_image(assets.image("enemy ship 2"))
    enemy.set_position(start_x, start_y)
    set_offset(enemy)

def spawn_wave():
    start_x = randint(0, 1) * 160
    start_y = randint(0, 90)
    for i in range(randint(3, 6)):
        spawn_enemy(start_x, start_y)
game.on_update_interval(7500, spawn_wave)

# GH2
def spawn_boss():
    boss = sprites.create(assets.image("boss"), SpriteKind.boss)
    boss.set_position(randint(20, 140), -20)
    boss.z = -5
    sprites.set_data_number(boss, "x_offset", randint(-50, 50))
    sprites.set_data_number(boss, "y_offset", randint(-5, -25))
    boss_healthbar = statusbars.create(50, 4, StatusBarKind.health)
    boss_healthbar.attach_to_sprite(boss, -5)
    boss_healthbar.max = 100
    boss_healthbar.value = boss_healthbar.max
info.on_score(5000, spawn_boss)
# end GH2

def destroy_enemy(projectile, enemy):
    if randint(1, 10) == 1 and len(sprites.all_of_kind(SpriteKind.food)) < 1:
        shield = sprites.create(assets.image("shield falling"), SpriteKind.food)
        shield.set_position(enemy.x, enemy.y)
        shield.set_velocity(0, 50)
        shield.set_flag(SpriteFlag.AUTO_DESTROY, True)
    if not powerup_overheated:
        powerup_bar.value += 5
    info.change_score_by(100)
    projectile.destroy()
    enemy.destroy(effects.fire, 100)
sprites.on_overlap(SpriteKind.projectile, SpriteKind.enemy, destroy_enemy)

# GH2
def boss_hit(projectile, boss):
    boss_healthbar = statusbars.get_status_bar_attached_to(StatusBarKind.health, boss)
    boss_healthbar.value -= 2
    powerup_bar.value += 5
    if boss_healthbar.value < 1:
        boss.destroy(effects.fire)
        info.change_score_by(2500)
    projectile.destroy()
sprites.on_overlap(SpriteKind.projectile, SpriteKind.boss, boss_hit)
# end GH2

def player_hit(player, enemy):
    info.change_life_by(-1)
    enemy.destroy()
sprites.on_overlap(SpriteKind.player, SpriteKind.enemy, player_hit)
sprites.on_overlap(SpriteKind.player, SpriteKind.enemy_projectile, player_hit)

def activate_shield(player, shield):
    shield.set_position(player.x, player.y)
    shield.follow(player, 500, 500)
    shield.set_image(assets.image("shield"))
    shield.scale = 2
    shield.z = 10
sprites.on_overlap(SpriteKind.player, SpriteKind.food, activate_shield)

def destroy_shield(projectile, shield):
    if shield.overlaps_with(ship):
        shield.destroy(effects.disintegrate)
        projectile.destroy()
sprites.on_overlap(SpriteKind.enemy_projectile, SpriteKind.food, destroy_shield)

def player_fire():
    sprites.create_projectile_from_sprite(assets.image("player projectile"), ship, 0, player_shot_speed)
controller.A.on_event(ControllerButtonEvent.PRESSED, player_fire)

# GH1
def fire_at_angle(angle):
    angle_in_radians = spriteutils.degrees_to_radians(angle)
    projectile = sprites.create(assets.image("player projectile"), SpriteKind.projectile)
    projectile.set_position(ship.x, ship.y)
    projectile.set_flag(SpriteFlag.AUTO_DESTROY, True)
    spriteutils.set_velocity_at_angle(projectile, angle_in_radians, player_shot_speed)
    music.thump.play()
    pause(20)

def burst_fire():
    global powerup_overheated
    if powerup_bar.value == powerup_bar.max:
        powerup_overheated = True
        powerup_bar.value = 0
        powerup_bar.set_color(2, 2)
        launch_angle = 0
        for i in range(2):
            for j in range(18):
                launch_angle += 10
                fire_at_angle(launch_angle)
            for j in range(18):
                launch_angle -= 10
                fire_at_angle(launch_angle)
        powerup_cooldown()
controller.B.on_event(ControllerButtonEvent.PRESSED, burst_fire)

def powerup_cooldown():
    global powerup_overheated
    pause(5000)
    powerup_overheated = False
    powerup_bar.set_color(8, 11)
    music.jump_up.play()
# end GH1

def player_movement():
    if controller.left.is_pressed():
        ship.vx -= player_speed
    if controller.right.is_pressed():
        ship.vx += player_speed
    ship.vx *= deceleration

def enemy_fire(enemy: Sprite):
    proj = sprites.create_projectile_from_sprite(assets.image("enemy projectile"), enemy, 0, enemy_shot_speed)
    proj.set_kind(SpriteKind.enemy_projectile)
    music.pew_pew.play()

def update_enemy_position(enemy: Sprite, formation_center: Sprite):
    x_offset = sprites.read_data_number(enemy, "x_offset")
    y_offset = sprites.read_data_number(enemy, "y_offset")
    enemy.vx = (formation_center.x + x_offset - enemy.x)
    enemy.vy = (formation_center.y + y_offset - enemy.y)

def enemy_behaviour():
    for enemy in sprites.all_of_kind(SpriteKind.enemy):
        if randint(0, 250) == 0:
            enemy_fire(enemy)
        update_enemy_position(enemy, formation_center)

# GH2
def boss_behaviour():
    boss_sprite = sprites.all_of_kind(SpriteKind.boss)[0]
    update_enemy_position(boss_sprite, formation_center)
    if randint(0, 120) == 120:
        sprites.set_data_number(boss_sprite, "x_offset", randint(-50, 50))
        sprites.set_data_number(boss_sprite, "y_offset", randint(-5, -25))
    if randint(0, 60) == 60:
        enemy_fire(boss_sprite)
        lasers = sprites.all_of_kind(SpriteKind.enemy_projectile)
        lasers[len(lasers) - 1].scale = 5
# end GH2

def constrain_formation_position():
    if formation_center.x < 70:
        formation_center.vx = randint(5, 10)
    if formation_center.x > 90:
        formation_center.vx = randint(-5, -10)
    if formation_center.y < 55:
        formation_center.vy = randint(5, 10)
    if formation_center.y > 65:
        formation_center.vy = randint(-5, -10)

def tick():
    player_movement()
    if len(sprites.all_of_kind(SpriteKind.enemy)) > 0:
        enemy_behaviour()
    # GH2
    if len(sprites.all_of_kind(SpriteKind.boss)) > 0:
        boss_behaviour()
    # end GH2
    constrain_formation_position()
game.on_update(tick)


from __future__ import annotations

import argparse
from pathlib import Path

import vortex.manage.cli as cli

from tornado.tasks.all import AllGroup

self_path = Path(__file__).parent.parent.parent

if __name__ == "__main__":
    tasks = AllGroup(self_path / "source")

    parser = argparse.ArgumentParser(
        description="Tornado power supply controller development automation tool",
        usage="python -m tornado.manage <component>.<task> [options...]",
    )
    cli.add_parser_args(parser, tasks)

    args = parser.parse_args()

    try:
        params = cli.read_run_params(args, tasks, self_path / "target")
    except cli.ReadRunParamsError as e:
        print(e)
        exit(1)

    cli.setup_logging(params, ["vortex", "tornado"])
    cli.run_with_params(params)


import sys, os

class HeadFile(object):

    def __init__(self, f, headsize=1024):
        self.f = f
        self.headsize = headsize

        # A cache of the beginning bytes of the file.
        self.head = ''
        self.pos = self.realpos = 0

    def __getattr__(self, key):
        return getattr(self.f, key)

    def tell(self):
        return self.pos

    def realread(self, nbytes):
        assert self.realpos < self.headsize, (self.realpos, self.headsize)
        r = self.f.read(nbytes)
        rbytes = len(r)
        ldiff = len(self.head) + rbytes - self.headsize
        self.head += (r[:-ldiff] if ldiff > 0 else r)
        self.realpos += rbytes
        if self.realpos >= self.headsize:
            self.realread = self.realread_nocache
        return r

    def realread_nocache(self, nbytes):
        r = self.f.read(nbytes)
        self.realpos += len(r)
        return r

    def read(self, nbytes):
        lenhead = len(self.head)
        assert self.realpos >= lenhead, "Invariant failed."
        if self.pos == self.realpos:
            r = self.realread(nbytes)
            self.pos += len(r)
        else:
            assert self.pos < self.realpos, (self.pos, self.realpos)
            beg = self.pos
            end = beg + nbytes
            if end > self.headsize:
                raise OSError("Head overflow of non-seekable file.")
            if end > lenhead:
                # Make sure we read all needed unread bytes.
                ebytes = lenhead - end
                self.realread(ebytes)
            # Return the part of the cache we need to read.
            r = self.head[beg:end]
            self.pos += len(r)
        return r

    def seek(self, offset, whence=os.SEEK_SET):
        if (whence != os.SEEK_SET or
            (offset > len(self.head) and offset != self.realpos)):
            trace(offset, len(self.head), self.realpos)
            raise OSError("File is not seekable.")
        else:
            assert offset <= len(self.head) or offset == self.realpos
            self.pos = offset

def test():
    "Cat a file larger than 2048 bytes in stdin and this should succeed."

    f = HeadFile(sys.stdin, 1024)

    f.seek(0)
    b1 = f.read(128)
    f.seek(0)
    b2 = f.read(128)
    assert b1 == b2, (b1, b2)
    f.read(2048)
    f.seek(1000)
    f.seek(2048+128)
    f.read(128)
    f.seek(1024)
    f.read(10)

if __name__ == '__main__':
    test()


import random
#Se importa el modulo random

def partido(nombreDeJugadorUno, nombreDeJugadorDos):
    # Inicializar variables
    # contadores y listas globales para resultados
    jugadorUnoSets = 0
    jugadorDosSets = 0
    jugadorUnoGames = 0
    jugadorDosGames = 0
    tantosJugadorUno = []
    tantosJugadorDos = []
    setsJugadorUno = []
    setsJugadorDos = []
    contadorGeneral = 1

    listaTantos = ["15", "30", "40", "win"]
    listaJugadores = [nombreDeJugadorUno, nombreDeJugadorDos]
    print(f"\n🏆{nombreDeJugadorUno} VS {nombreDeJugadorDos}🏆")

    while jugadorUnoSets < 2 and jugadorDosSets < 2:
        #contadores y listas por juego
        jugadorUnoTantos = 0
        jugadorDosTantos = 0
        gameTantosJugadorUno = []
        gameTantosJugadorDos = []

        # Mostrar el título del juego actual
        print(f"\n---- Juego {contadorGeneral} 🎾----")

        while jugadorUnoTantos < 4 and jugadorDosTantos < 4:
            # Seleccionar resultado aleatorio para determinar los tantos
            resultado = random.choice(listaJugadores)
            if resultado == nombreDeJugadorUno:
                ganador = nombreDeJugadorUno
                tantosJugador = jugadorUnoTantos
            else:
                ganador = nombreDeJugadorDos
                tantosJugador = jugadorDosTantos

            # Agregar tantos al jugador y mostrar el resultado
            gameTantos = listaTantos[tantosJugador]
            if resultado == nombreDeJugadorUno:
                gameTantosJugadorUno.append(gameTantos)
                jugadorUnoTantos += 1
            else:
                gameTantosJugadorDos.append(gameTantos)
                jugadorDosTantos += 1
            print(f"{ganador}: {gameTantos}")

        if jugadorUnoTantos == 4:
            # El jugador uno gana el set
            jugadorUnoSets += 1
            jugadorUnoGames += 1  # Incrementar el contador de games para el jugador uno
            setsJugadorUno.append(jugadorUnoSets)
            setsJugadorDos.append(jugadorDosSets)
            for tanto in gameTantosJugadorUno:
                tantosJugadorUno.append(tanto)
            for tanto in gameTantosJugadorDos:
                tantosJugadorDos.append(tanto)
            print(f"\n{nombreDeJugadorUno} gana el set.")
        elif jugadorDosTantos == 4:
            # El jugador dos gana el set
            jugadorDosSets += 1
            jugadorDosGames += 1  # Incrementar el contador de games para el jugador dos
            setsJugadorUno.append(jugadorUnoSets)
            setsJugadorDos.append(jugadorDosSets)
            for tanto in gameTantosJugadorUno:
                tantosJugadorUno.append(tanto)
            for tanto in gameTantosJugadorDos:
                tantosJugadorDos.append(tanto)
            print(f"\n{nombreDeJugadorDos} gana el set.")

        contadorGeneral +=1

        # Mostrar el número de juegos ganados por cada jugador hasta el momento
        print(f"\nResultados hasta ahora:")
        print(f"{nombreDeJugadorUno}: {jugadorUnoGames} juegos")
        print(f"{nombreDeJugadorDos}: {jugadorDosGames} juegos")

    # Mostrar resultado final
    print("\nResultado final")
    print(f"{nombreDeJugadorUno}: {jugadorUnoSets} sets")
    print(f"{nombreDeJugadorDos}: {jugadorDosSets} sets")

    # Mostrar al jugador ganador
    if jugadorUnoSets == 2:
        jugadorGanador = nombreDeJugadorUno
    else:
        jugadorGanador = nombreDeJugadorDos

    print(f"🎾 Ganador del juego: {jugadorGanador} 🏆")

tenistasChilenos = ["Nicolás Jarry","Christian Garin","Daniela Seguel","Fernanda Brito",
    "Alejandro Tabilo","Alexa Guarachi","Tomás Barrios","Bárbara Gatica","Gonzalo Lama","Cecilia Costa Melgar"]

# Seleccionar dos jugadores aleatorios de la lista
tenistaRandom1, tenistaRandom2 = random.sample(tenistasChilenos, 2)

# Iniciar el partido con los jugadores seleccionados
partido(tenistaRandom1, tenistaRandom2)


def triangleNumber(nums):
    count = 0

    nums.sort()

    for i1 in range(len(nums)):
        for i2 in range(i1 + 1, len(nums)):
            for i3 in range(i2 + 1, len(nums)):

                condition1 = nums[i1] +  nums[i2] >  nums[i3]
                condition2 = nums[i1] +  nums[i3] >  nums[i2]
                condition3 = nums[i2] +  nums[i3] >  nums[i1]

                if condition1 and condition2 and condition3:  count += 1

    return count

nums = [2,2,3,4]

print("Number of valid triplets -> ", triangleNumber(nums))

033. Valid Triangle Number/BruteForce.py


#Exercício101

def voto(idade):

    """
    Função para descobrir se uma pessoa pode votar com a idade de acordo com o ano de nascimento.

    Idade: É calculado o ano que vocês nasceu menos o ano atual.
    """

    from datetime import datetime

    atual = datetime.now().year - idade

    if atual < 16:
        print(f'Com {atual} anos, o voto é NEGADO.')
    elif atual <= 16 or atual < 18 or atual > 70:
        print(f'Com {atual} anos, o voto é OPCIONAL.')
    else:
        print(f'Com {atual} anos, o voto é OBRIGATÓRIO.')

idade = int(input('Insira o ano de nascimento: '))

voto(idade)


#!/bin/python

# Importing Sqlite3 module
import sqlite3

# Creating Connection to movies database file with sqlite3
conn = sqlite3.connect('Find-All-Tarantino-Movies.db')

# Creating Cursor
c = conn.cursor()

# Creating Table
# c.execute("CREATE TABLE movies( title text, year integer, director text)")

# Creating List and putting values in list and tuples
movie_list = [
		('Rushmore', 1998, 'Wes Anderson'),
		('Isle of Dogs', 2018, 'Wes Anderson'),
		('Pulp Fiction', 1994, 'Tarantino'),
		('The Shining', 1980, 'Stanley Kubric'),
		('Django', 2012, 'Tarantino')
				]

# Inserting values in Table
# c.executemany("INSERT INTO movies VALUES(?,?,?)", movie_list)

# Query
c.execute("SELECT title, year FROM movies WHERE director = 'Tarantino'")

# Creating Variable to prints Query
movieshow = c.fetchall()
for movie in movieshow:
  print (movie)

# Displaying All Values
# print (" Show Table: All ")
# for movie in movie_list:
#   print (movie)

# Commiting to database
conn.commit()

# Closing Connection
conn.close()

SQL/Find All Tarantino Movies/Find-All-Tarantino-Movies.py


# main.py
#
# Programmeertheorie
# Merel Florian, Michael Verdel, Joshua van Zanten
#
# - Implements several algorithms to connect houses to batteries with capacity.

from code.algorithms.random_greedy import RandomGreedy
from code.classes.smartgrid import Smartgrid
from code.algorithms.hillclimber import Hillclimber
from code.algorithms.sim_annealing import SimulatedAnnealing
from code.algorithms.random import Random
from code.grid import grid
from sys import argv
import time
import statistics

runtime = time.time()

if __name__ == "__main__":

    # check command line
    if len(argv) != 4:
        print("Usage: python3 smartgrid.py [district_number] random/greedy/climber/sim shared:y/n")
        exit(1)
    # Load the requested files
    if len(argv) == 4:
        district_int = argv[1]
        shared = argv[3]
        algorithm = argv[2]

        if argv[3] == "shared:y":
            shared = True
        elif argv[3] == "shared:n":
            shared = False
        else:
            print("Usage: python3 smartgrid.py [district_number] random/greedy/climber/sim shared:y/n")
            exit(1)

    housesf = f"database/district_{district_int}/district-{district_int}_houses.csv"
    batteriesf = f"database/district_{district_int}/district-{district_int}_batteries.csv"

    # load houses and batteries dict
    smartgrid = Smartgrid(housesf, batteriesf)

    # get info of case
    all_costs = []
    all_runtimes = []
    # amount of times algorithm needs to run
    N = 30
    # amount of iterations
    IT = 10000

    for n in range(N):
    #------------------------------random algorithm-------------------------------
        if algorithm == "random":
            random_a = Random(smartgrid)
            final_connections_dict = random_a.run()

    #---------------------------random greedy algorithm---------------------------
        elif algorithm == "greedy":
            randomgreedy_a = RandomGreedy(smartgrid)
            final_connections_dict = randomgreedy_a.run()

    #----------------------------hillclimber algorithm----------------------------
        elif algorithm == "climber":
            randomgreedy_a = RandomGreedy(smartgrid)
            connections_dict = randomgreedy_a.run()
            climber = Hillclimber(smartgrid, connections_dict)
            final_connections_dict = climber.run(IT)

    # -----------------------------simulated annealing-----------------------------
        elif algorithm == "sim":
            randomgreedy_a = RandomGreedy(smartgrid)
            connections_dict = randomgreedy_a.run()
            s_annealing = SimulatedAnnealing(smartgrid, connections_dict)
            final_connections_dict = s_annealing.run(IT)
        else:
            print("Error: algorithm name must be random/greedy/climber/sim")
            exit(1)

        total_cost = smartgrid.costs(final_connections_dict, smartgrid.batteries_dict, shared)
        print(total_cost)
        print(time.time()-runtime)
        all_costs.append(total_cost)
        all_runtimes.append(time.time()-runtime)

    average_costs  = sum(all_costs) / N
    average_runtime = sum(all_runtimes) / N
    print(average_costs, statistics.stdev(all_costs))

# compute costs
total_cost = smartgrid.costs(final_connections_dict, smartgrid.batteries_dict, shared)
# create grid picture
grid.create_grid(smartgrid.houses_dict, smartgrid.batteries_dict, final_connections_dict)
# export output to json file
smartgrid.output(final_connections_dict, total_cost, (time.time()-runtime), argv[1], shared)


import logging
from gi.repository import Adw
from gi.repository import Gtk, GLib, GObject
from gettext import gettext as _

logger = logging.getLogger("Vanilla:Container")

@Gtk.Template(resource_path='/org/vanillaos/ControlCenter/gtk/container.ui')
class VanillaApxContainer(Adw.ActionRow):
    __gtype_name__ = "VanillaApxContainer"
    btn_shell = Gtk.Template.Child()
    btn_init = Gtk.Template.Child()

    def __init__(self, window: Gtk.Widget, container: dict):
        super().__init__()
        self.__window = window
        self.__container = container
        self.__build_ui()

    def __build_ui(self):
        self.set_title(self.__container["Name"])
        self.set_subtitle(self.__container["Alias"])

        self.btn_init.set_visible(not self.__container["Status"] == 0)
        self.btn_shell.set_visible(self.__container["Status"] == 0)

        self.btn_shell.connect("clicked", self.__on_btn_shell_clicked)
        self.btn_init.connect("clicked", self.__on_btn_init_clicked)

    def __on_btn_shell_clicked(self, widget):
        GLib.spawn_command_line_async(self.__container["ShellCmd"])
        self.__window.toast(_("Shell opened for container '{}'").format(self.__container["Name"]))

    def __on_btn_init_clicked(self, widget):
        res = GLib.spawn_command_line_async(self.__container["InitCmd"])
        if res:
            self.btn_init.set_visible(False)
            self.btn_shell.set_visible(True)
            self.__window.toast(_("Container '{}' initialized").format(self.__container["Name"]))


import os
import sys
import pandas as pd
import numpy as np

os.environ['CUDA_VISIBLE_DEVICES'] = '0'

_cur_dir = os.path.split(os.path.abspath(__file__))[0]
_root_dir = os.path.split(_cur_dir)[0]
sys.path.append(_root_dir)

from server.interfaces.data.data_add_values import data_add_values, DataInput
from server.interfaces.data.data_add_avg_values import data_add_avg_values, DataAvgInput
from config.path import VALUE_DIR
from core.processor import d_column_2_zh_name
from core.encode import encode

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1].lower() == '--drop_all':
        from lib.milvus import o_milvus

        o_milvus.recreate_collection(o_milvus.VALUE_NAME)
        o_milvus.recreate_collection(o_milvus.AVG_VALUE_NAME)

    file_names = list(filter(lambda x: not x.startswith('.'), os.listdir(VALUE_DIR)))

    # 添加 avg value embeddings 到 milvus
    for file_name in file_names:
        column = file_name.split(".")[0]

        # 过滤王永和端不支持的字段
        if column not in d_column_2_zh_name:
            continue

        file_path = os.path.join(VALUE_DIR, file_name)

        df = pd.read_csv(file_path)

        # 过滤空数据
        tmp_pairs = list(map(lambda x: [f'{x[0]}' if pd.notna(x[0]) else '', x[1]], zip(df['text'], df['freq'])))
        text_freq_pairs = list(filter(lambda x: x[0].strip(), tmp_pairs))
        texts, freqs = list(zip(*text_freq_pairs))

        # encode 成 embedding
        embeddings = encode(texts)
        data = list(map(lambda x: {'emb': x[0], 'freq': x[1]}, zip(embeddings, freqs)))

        # 获取 加权平均向量
        total_freq = np.sum(np.sqrt(np.array(freqs)))
        embeddings = np.array(list(map(lambda x: np.array(x['emb']) * np.sqrt(x['freq']) / total_freq, data)))
        weighted_sum_embeddings = np.sum(embeddings, axis=0)
        weighted_sum_embeddings = list(map(float, weighted_sum_embeddings))

        # 插入 初始加权平均向量
        print(f'inserting avg embeddings for {column}')
        print(data_add_avg_values(DataAvgInput(
            column=column,
            embedding=weighted_sum_embeddings,
            count=total_freq,
        )))

    # 添加 value embeddings 到 milvus
    for file_name in file_names:
        column = file_name.split(".csv")[0]

        # 过滤王永和端不支持的字段
        if column not in d_column_2_zh_name:
            continue

        file_path = os.path.join(VALUE_DIR, file_name)

        df = pd.read_csv(file_path)
        texts = list(map(lambda x: f'{x}' if pd.notna(x) else '', df['text']))
        texts = list(filter(lambda x: x.strip(), texts))

        if texts:
            print(data_add_values(DataInput(
                column=column,
                data=texts
            )))

    print('\ndone')