#!/usr/bin/env python3
import pathlib

def partOne():
    """ Given seven segment signals, return how many times 1, 4, 7, 8 show up."""
    filePath = pathlib.Path(__file__).parent.resolve()
    finalCounts = [0] * 10

    with open(f'{filePath}/input.txt') as f:
        lines = f.readlines()
        for line in lines:
            parts = line.split('|')
            outputList = parts[1].split()
            for segment in outputList:
                length = len(segment)
                if length == 2:
                    finalCounts[1] += 1
                elif length == 4:
                    finalCounts[4] += 1
                elif length == 3:
                    finalCounts[7] += 1
                elif length == 7:
                    finalCounts[8] += 1

        result = sum(finalCounts)

    return result

def partTwo():
    """ Given seven segment signals, return how many times 1, 4, 7, 8 show up."""
    filePath = pathlib.Path(__file__).parent.resolve()
    result = 0
    numSegments = [0] * 10

    with open(f'{filePath}/input.txt') as f:
        lines = f.readlines()
        for line in lines:
            numSegments = [0] * 10
            parts = line.split('|')

            # figure out number segments
            guideList = parts[0].split()
            guideList.sort(key=len)

            for index, seg in enumerate(guideList):
                guideList[index] = "".join(sorted(seg))

            # save 7 and 8
            numSegments[7] = guideList[1]
            numSegments[8] = guideList[9]

            # figure out 1 and 4
            numSegments[1] = numberOne = guideList[0]
            numSegments[4] = numberFour = guideList[2]

            # figure out 2 missing letters (diff)
            numberOneSet = set(numberOne)
            numberFourSet = set(numberFour)
            difference = numberFourSet.symmetric_difference(numberOneSet)
            difference = "".join(list(sorted(difference)))

            numberFive = None
            # find len(5) with diff letters - this is number 5
            for index in range(3,6):
                if difference[0] in guideList[index] and difference[1] in guideList[index]:
                    numSegments[5] = numberFive = guideList[index]

            # find len(5) with letters from numberOne - this is number 3; other is number 2
            numberThree = None
            for index in range(3,6):
                if guideList[index] == numberFive:
                    continue
                elif numberOne[0] in guideList[index] and numberOne[1] in guideList[index]:
                    numSegments[3] = numberThree = guideList[index]
                else:
                    numSegments[2] = numberTwo = guideList[index]

            # find len(6) with one of diff letters missing - this is number 0
            for index in range(6,9):
                if difference[0] not in guideList[index] or difference[1] not in guideList[index]:
                    numSegments[0] = numberZero = guideList[index]

            # find len(6) with both letters from numberOne - this is number 9; other number is 6
            for index in range(6,9):
                if guideList[index] == numberZero:
                    continue
                elif numberOne[0] in guideList[index] and numberOne[1] in guideList[index]:
                    numSegments[9] = numberNine = guideList[index]
                else:
                    numSegments[6] = numberSix = guideList[index]

            outputList = parts[1].split()
            currentNumber = ""
            for segment in outputList:
                segment = "".join(sorted(segment))
                currentNumber += str(numSegments.index(segment))

            result += int(currentNumber)

    return result

if __name__ == "__main__":
    print(f"partOne: {partOne()}")
    print(f"partTwo: {partTwo()}")


from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Topic, Entry, Link
from django.http import HttpResponseRedirect
from django.urls import reverse
from .forms import TopicForm, EntryForm, DeleteEntryForm, DeleteTopicForm
from django.contrib.auth.decorators import login_required
# Create your views here.

def index(request):
    t = Topic.objects.order_by("title")
    context = {'topics':t}
    return render(request, "index.html", context)
    #return HttpResponse("
Hello Django
")

@login_required
def topics(request):
    t = Topic.objects.filter(owner=request.user).order_by("title")
    context = {"topics": t}
    return render(request, "topics.html", context)

def resources(request):
    topics = Topic.objects.all()
    topics_links = {}
    for t in topics:
        links = t.link_set.all()
        topics_links[t] = links
    context = {"topics":topics_links} # topics_links ={topic1: links, topic2: links....}

    return render(request, "resources.html", context)

@login_required
def topic(request, topic_id):
    '''show a single topic and all its entries'''
    topic = Topic.objects.filter(owner=request.user).get(id=topic_id)
    entries = topic.entry_set.order_by('date_added')
    context = {"topic": topic, "entries": entries}
    return render(request,"topic.html", context)

@login_required
def new_topic(request):
    '''Add a new topic'''

    if request.method != 'POST':
        form = TopicForm()
    else:
        form = TopicForm(request.POST, request.user)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = request.user
            new_topic.save()
            return HttpResponseRedirect(reverse('logs:topics'))
    context = {'form': form}
    return render(request, 'new_topic.html', context)

@login_required
def edit_topic(request, topic_id):
    '''Edit a new topic'''
    topic = Topic.objects.get(id = topic_id)
    num = len(topic.entry_set.all()) # number of entries under this topic
    if request.method != 'POST':
        form = TopicForm(instance = topic)
    else:
        form = TopicForm(instance=topic, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("logs:topic", args=[topic.id]))
    context = {'topic': topic, 'form': form}
    return render(request, 'edit_topic.html', context)

@login_required
def new_entry(request, topic_id):
    '''Add a new entry for a particular topic'''
    topic = Topic.objects.get(id=topic_id)
    if request.method != 'POST':
        form = EntryForm()
    else:
        form = EntryForm(data = request.POST)
        if form.is_valid():
            new_entry=form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return HttpResponseRedirect(reverse('logs:topic', args=[topic_id]))
    context = {'topic': topic, 'form': form}
    return render(request, 'new_entry.html', context)

@login_required
def edit_entry(request, entry_id):
    '''Edit an existing entry.'''
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic

    if request.method != 'POST':
        form = EntryForm(instance=entry)
    else:
        form = EntryForm(instance =entry, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('logs:topic', args=[topic.id]))
    context = {'entry': entry, 'topic': topic, 'form': form}
    return render(request, 'edit_entry.html', context)

@login_required
def delete_entry(request, entry_id):
    '''delete an existng entry.'''
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    entry_to_delete = get_object_or_404(Entry, id=entry_id)

    if request.method!='POST':
        form = DeleteEntryForm(instance=entry)
    else:
        form = DeleteEntryForm(instance=entry,data=request.POST)
        if form.is_valid():
            entry_to_delete.delete()
            return HttpResponseRedirect(reverse('logs:topic', args=[topic.id]))
    context = {'entry': entry, 'topic': topic, 'form': form}
    return render(request, 'delete_entry.html', context)

@login_required
def delete_topic(request, topic_id):
    '''delete an existng topic.'''
    topic = Topic.objects.get(id=topic_id)
    topic_to_delete = get_object_or_404(Topic, id=topic_id)
    if request.method != 'POST':
        form = DeleteTopicForm(instance=topic)
    else:
        form = DeleteTopicForm(instance=topic, data=request.POST)
        if form.is_valid():
            topic_to_delete.delete()
            return HttpResponseRedirect(reverse('logs:topics'))
    context = {'topic': topic, 'form': form}
    return render(request, 'delete_topic.html', context)


from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
from cassandra.util import uuid

cloud_config= {
  'secure_connect_bundle': 'secure-connect-bety.zip'
}
auth_provider = PlainTextAuthProvider("jxbiZCoHJMGchSaeNztzfbTn", "6y9NvWWsP4jDRFCWZZ72XU8cBrFuY5-qgLzNZQfW3rYwchFtT4G-Arlxni23Sy8DXIrOnhksAeMWzjS4KovDq_BZiuKq_Mc2z-TsT+wL,BdqFB15gdc,kyJWAz_.KfZ6")
cluster = Cluster(cloud=cloud_config, auth_provider=auth_provider)
session = cluster.connect("mercado_livre")

def insert_usuario(session, sobrenome, email, nome, endereco):
    id = uuid.uuid4()
    session.execute("INSERT INTO usuarios (id, sobrenome, email, nome, endereco) VALUES (%s,%s,%s,%s,%s)", [id, sobrenome, email, nome, endereco])

def insert_vendedor(session, nome,sobrenome,email):
  id = uuid.uuid4()
  session.execute("INSERT INTO vendedores (id, sobrenome, email, nome) VALUES (%s,%s,%s,%s)", [id, sobrenome, email, nome])

def insert_produtos(session,nome,quantia,preco):
  id = uuid.uuid4()
  session.execute("INSERT INTO produtos (id, preco, quantia, nome) VALUES (%s,%s,%s,%s)", [id, preco, quantia, nome])

def insert_compras(session,email,produto):
  id = uuid.uuid4()
  session.execute("INSERT INTO compras (id, email, produto) VALUES (%s,%s,%s)", [id, email,produto])

def insert_favoritos(session,email,produto):
  id = uuid.uuid4()
  session.execute("INSERT INTO favoritos (id, email, produto) VALUES (%s,%s,%s)", [id, email,produto])

def insert_relacao(session,email,produto):
  id = uuid.uuid4()
  session.execute("INSERT INTO produtos_vendedor (id, email, produto) VALUES (%s,%s,%s)", [id, email,produto])

def find_clientes():
  result = session.execute("SELECT * FROM usuarios")
  return result

def find_vendedores():
  result = session.execute("SELECT * FROM vendedores")
  return result

def find_produtos():
  result = session.execute("SELECT * FROM produtos")
  return result

def find_compras():
  result = session.execute("SELECT * FROM compras;")
  return result

def find_favoritos():
  result = session.execute("SELECT * FROM favoritos;")
  return result

def delete_usuario(session, email):
    id_result = session.execute("SELECT id FROM usuarios WHERE email = %s", [email])
    id = id_result.one().id if id_result else None
    if id:
        prepared = session.prepare("DELETE FROM usuarios WHERE id = ?")
        session.execute(prepared, [id])
        tudo_ok()
    else:
        print("Usuário não encontrado.")
    voltar_opcoes()

def delete_vendedor(session,email):
    id_result = session.execute("SELECT id FROM vendedores WHERE email = %s", [email])
    id = id_result.one().id if id_result else None
    if id:
        prepared = session.prepare("DELETE FROM vendedores WHERE id = ?")
        session.execute(prepared, [id])
        tudo_ok()
    else:
        print("Vendedor não encontrado.")
    voltar_opcoes()

def delete_produto(session,nome):
    id_result = session.execute("SELECT id FROM produtos WHERE nome = %s", [nome])
    id = id_result.one().id if id_result else None
    if id:
        prepared = session.prepare("DELETE FROM produtos WHERE id = ?")
        session.execute(prepared, [id])
        tudo_ok()
    else:
        print("Produto não encontrado.")
    voltar_opcoes()

def delete_compra(session, email):
    nome_result = session.execute("SELECT nome FROM usuarios WHERE email = %s", [email])
    nome = nome_result.one().nome if nome_result else None
    if nome:
        print(f"Cliente: {nome}")
        compras = session.execute("SELECT * FROM compras WHERE email = %s", [email])
        posicao = 1
        for compra in compras:
            preco = session.execute("SELECT preco FROM produtos WHERE nome = %s", [compra.produto]).one().preco
            nome = compra.produto
            print(f"0{posicao} - Produto: {nome}, Preço: R${str(preco).replace('.', ',')}")
            posicao += 1
        chave = True
        while chave:
            produtoNome = input("Produto a excluir: ")
            chave = (input("Deseja excluir outro produto? (s/n): ") == 's')
            id_result = session.execute("SELECT id FROM compras WHERE email = %s AND produto = %s", [email, produtoNome])
            id = id_result.one().id if id_result else None
            if id:
                prepared = session.prepare("DELETE FROM compras WHERE id = ?")
                session.execute(prepared, [id])
                tudo_ok()
            else:
                print("Compra não encontrada.")
    else:
        print("Usuário não encontrado.")
    voltar_opcoes()

def deletar_favorito(session, email):
    nome_result = session.execute("SELECT nome FROM usuarios WHERE email = %s", [email])
    nome = nome_result.one().nome if nome_result else None
    if nome:
        print(f"Cliente: {nome}")
        favoritos = session.execute("SELECT * FROM favoritos WHERE email = %s", [email])
        posicao = 1
        for favorito in favoritos:
            preco = session.execute("SELECT preco FROM produtos WHERE nome = %s", [favorito.produto]).one().preco
            nome = favorito.produto
            print(f"0{posicao} - Produto: {nome}, Preço: R${str(preco).replace('.', ',')}")
            posicao += 1
        chave = True
        while chave:
            produtoNome = input("Produto a excluir: ")
            chave = (input("Deseja excluir outro produto? (s/n): ") == 's')
            id_result = session.execute("SELECT id FROM favoritos WHERE email = %s AND produto = %s", [email, produtoNome])
            id = id_result.one().id if id_result else None
            if id:
                prepared = session.prepare("DELETE FROM favoritos WHERE id = ?")
                session.execute(prepared, [id])
                tudo_ok()
            else:
                print("Favorito não encontrada.")
    else:
        print("Usuário não encontrado.")
    voltar_opcoes()

def remover_relacao(session, email):
    nome_result = session.execute("SELECT nome FROM vendedores WHERE email = %s", [email])
    nome = nome_result.one().nome if nome_result else None
    if nome:
        print(f"Vendedor: {nome}")
        favoritos = session.execute("SELECT * FROM produtos_vendedor WHERE email = %s", [email])
        posicao = 1
        for favorito in favoritos:
            preco = session.execute("SELECT preco FROM produtos WHERE nome = %s", [favorito.produto]).one().preco
            nome = favorito.produto
            print(f"0{posicao} - Produto: {nome}, Preço: R${str(preco).replace('.', ',')}")
            posicao += 1
        chave = True
        while chave:
            produtoNome = input("Produto a remover: ")
            chave = (input("Deseja remover outro produto? (s/n): ") == 's')
            id_result = session.execute("SELECT id FROM produtos_vendedor WHERE email = %s AND produto = %s", [email, produtoNome])
            id = id_result.one().id if id_result else None
            if id:
                prepared = session.prepare("DELETE FROM produtos_vendedor WHERE id = ?")
                session.execute(prepared, [id])
                tudo_ok()
            else:
                print("Relação não encontrada.")
    else:
        print("Vendedor não encontrado.")
    voltar_opcoes()

#funcoes recebe
def recebe_cadastro_usuario():
    nome = input("Nome: ")
    sobrenome = input("Sobrenome: ")
    email = input("Email: ")
    print("Endereços")
    enderecos = []
    adicao = True
    while adicao:
        cep = input("CEP: ")
        numero = input("Número: ")
        enderecos.append({"cep": cep,"numero": numero})
        adicao = (input("Deseja adicionar outro endereço? (s/n): ") == 's')
    insert_usuario(session, sobrenome, email, nome, enderecos)
    tudo_ok()
    voltar_opcoes()

def recebe_cadastro_vendedor():
    nome = input("Nome: ")
    sobrenome = input("Sobrenome: ")
    email = input("Email: ")
    insert_vendedor(session, nome, sobrenome, email)
    tudo_ok()
    voltar_opcoes()

def recebe_cadastro_produto():
    nome = input("Nome: ")
    valor  = input("Valor: ")
    quantia = input("Quantia em estoque: ")
    insert_produtos(session,nome,quantia,valor)
    tudo_ok()
    voltar_opcoes()

def pega_clientes():
    clientes = find_clientes()
    for cliente in clientes:
        print("Nome: " + cliente.nome)
        print("Sobrenome: " + cliente.sobrenome)
        print("Email: " + cliente.email)
        posicao = 1
        if cliente.endereco is not None:
            print("Endereços: ")
            for endereco in cliente.endereco:
                cep = endereco["cep"]
                numero = endereco["numero"]
                print(f"0{posicao} - CEP: {cep}, Número: {numero}")
                posicao += 1
        print("Favoritos: ")
        pega_favoritos(cliente.email)
        print("")
    tudo_ok()
    voltar_opcoes()

def pega_vendedores():
    vendedores = find_vendedores()
    for vendedor in vendedores:
        print("Nome: " + str(vendedor.nome))
        print("Sobrenome: " + str(vendedor.sobrenome))
        print("Email: " + str(vendedor.email))
        posicao = 1
        produtos = vendedor.produtos
        if produtos is not None:
            print("Vende esses produtos: ")
            for produto in produtos:
                nome = produto.get("nome", "")
                print(f"0{posicao} - Nome do produto: {nome}")
                posicao += 1
        print("Relação com produtos: ")
        pega_relacao(vendedor.email)
        print("")
    tudo_ok()
    voltar_opcoes()

def pega_produtos():
    produtos = find_produtos()
    for produto in produtos:
        print("Nome: " + produto.nome)
        print("Preço: " + produto.preco)
        print("Quantia disponível: " + produto.quantia)
        print("")

def pega_compras():
    clientes = find_clientes()
    for cliente in clientes:
        print(f'Cliente: {cliente.nome}')
        posicao = 1
        total = 0
        compras = session.execute("SELECT * FROM compras WHERE email = %s", [cliente.email])
        for compra in compras:
            preco = session.execute("SELECT preco FROM produtos WHERE nome = %s", [compra.produto]).one().preco
            nome = compra.produto
            print(f"0{posicao} - Produto: {nome}, Preço: R${str(preco).replace('.', ',')}")
            total += float(preco.replace(",", "."))
            posicao += 1
    print(f"Total: R${str(total).replace('.', ',')}")

def pega_favoritos(email):
        posicao = 1
        favoritos = session.execute("SELECT * FROM favoritos WHERE email = %s", [email])
        for favorito in favoritos:
            preco = session.execute("SELECT preco FROM produtos WHERE nome = %s", [favorito.produto]).one().preco
            nome = favorito.produto
            print(f"0{posicao} - Produto: {nome}, Preço: R${str(preco).replace('.', ',')}")
            posicao += 1

def pega_relacao(email):
        posicao = 1
        favoritos = session.execute("SELECT * FROM produtos_vendedor WHERE email = %s", [email])
        for favorito in favoritos:
            preco = session.execute("SELECT preco FROM produtos WHERE nome = %s", [favorito.produto]).one().preco
            nome = favorito.produto
            print(f"0{posicao} - Produto: {nome}, Preço: R${str(preco).replace('.', ',')}")
            posicao += 1

def atualizar_usuario():
    email = input("Email do usuário a atualizar: ")
    row = session.execute("SELECT id FROM usuarios WHERE email = %s", [email]).one()
    if not row:
        print("Usuário não encontrado.")
        voltar_opcoes()
    user_id = row.id
    print("Quais campos deseja atualizar?")
    print("01 - Nome")
    print("02 - Sobrenome")
    print("03 - Email")
    campos = input("Quais campos? (exemplo: 01,02,03): ")
    campos = campos.split(",")
    for campo in campos:
        campo = int(campo)
        if campo == 1:
            nome = input("Novo nome: ")
            session.execute("UPDATE usuarios SET nome = %s WHERE id = %s", [nome, user_id])
        elif campo == 2:
            sobrenome = input("Novo sobrenome: ")
            session.execute("UPDATE usuarios SET sobrenome = %s WHERE id = %s", [sobrenome, user_id])
        elif campo == 3:
            novo_email = input("Novo email: ")
            session.execute("UPDATE usuarios SET email = %s WHERE id = %s", [novo_email, user_id])
    tudo_ok()
    voltar_opcoes()

def atualizar_vendedor():
    email = input("Email do vendedor a atualizar: ")
    row = session.execute("SELECT id FROM vendedores WHERE email = %s", [email]).one()
    if not row:
        print("Vendedor não encontrado.")
        voltar_opcoes()
    user_id = row.id
    print("Quais campos deseja atualizar?")
    print("01 - Nome")
    print("02 - Sobrenome")
    print("03 - Email")
    campos = input("Quais campos? (exemplo: 01,02,03): ")
    campos = campos.split(",")
    for campo in campos:
        campo = int(campo)
        if campo == 1:
            nome = input("Novo nome: ")
            session.execute("UPDATE vendedores SET nome = %s WHERE id = %s", [nome, user_id])
        elif campo == 2:
            sobrenome = input("Novo sobrenome: ")
            session.execute("UPDATE vendedores SET sobrenome = %s WHERE id = %s", [sobrenome, user_id])
        elif campo == 3:
            novo_email = input("Novo email: ")
            session.execute("UPDATE vendedores SET email = %s WHERE id = %s", [novo_email, user_id])
    tudo_ok()
    voltar_opcoes()

def atualizar_produto():
    nome = input("Nome do produto a atualizar: ")
    row = session.execute("SELECT id FROM produtos WHERE nome = %s", [nome]).one()
    if not row:
        print("Produto não encontrado.")
        voltar_opcoes()
    id_prod = row.id
    print("Quais campos deseja atualizar?")
    print("01 - Nome")
    print("02 - Valor")
    print("03 - Quantia")
    campos = input("Quais campos? (exemplo: 01,02,03): ")
    campos = campos.split(",")
    for campo in campos:
        campo = int(campo)
        if campo == 1:
            nome = input("Novo nome: ")
            session.execute("UPDATE produtos SET nome = %s WHERE id = %s", [nome, id_prod])
        elif campo == 2:
            preco = input("Novo valor: ")
            session.execute("UPDATE produtos SET preco = %s WHERE id = %s", [preco, id_prod])
        elif campo == 3:
            quantia = input("Nova quantia: ")
            session.execute("UPDATE produtos SET quantia = %s WHERE id = %s", [quantia, id_prod])
    tudo_ok()
    voltar_opcoes()

def cadastrar_itens(tipo, mensagem, opcao):
    email = input("Email do usuário: ")
    print('')
    print("Produtos disponíveis:")
    pega_produtos()
    itensNome = []
    chave = True
    while chave:
        itemNome = input(mensagem)
        itensNome.append(itemNome)
        chave = (input(opcao) == 's')
    produtos = find_produtos()
    for produto in produtos:
        for itemNome in itensNome:
            if produto.nome == itemNome:
                if tipo == "compras":
                    insert_compras(session, email, produto.nome)
                elif tipo == "favoritos":
                    insert_favoritos(session, email, produto.nome)
                elif tipo == "relacao":
                    insert_relacao(session, email, produto.nome)
    tudo_ok()
    voltar_opcoes()

def cadastrar_compras():
    cadastrar_itens("compras", "Nome do produto comprado: ", "Deseja adicionar outra compra? (s/n): ")

def cadastrar_favoritos():
    cadastrar_itens("favoritos", "Nome do produto favoritado: ", "Deseja adicionar outro favorito? (s/n): ")

def adicionar_relacao():
    cadastrar_itens("relacao", "Nome do produto: ", "Deseja adicionar outro produto? (s/n): ")

# Opções
def opcoes():
    print("Olá, qual opção gostaria?")
    print("01 - Usuário")
    print("02 - Vendedor")
    print("03 - Produtos")
    print("04 - Compras")

    opcao = int(input("Opção: "))
    print("")

    if(opcao == 1):
        opcoes_usuario()

    elif(opcao == 2):
        opcoes_vendedor()

    elif(opcao == 3):
        opcoes_produtos()

    elif(opcao == 4):
        opcoes_compras()

    else:
        print("A opção escolhida não existe!")
        print("-----------------------------")
        opcoes()

def opcoes_usuario():
    print("Qual opção deseja?")
    print("01 - Cadastrar")
    print("02 - Visualizar dados")
    print("03 - Atualizar dados")
    print("04 - Deletar dados")
    print("05 - Adicionar compras")
    print("06 - Adicionar Favoritos")
    print("07 - Remover Favoritos")
    print("00 - Voltar")
    print("")
    opcao = int(input("Opção: "))
    print("")

    if(opcao == 0):
        opcoes()

    elif(opcao == 1):
        recebe_cadastro_usuario()

    elif(opcao == 2):
        pega_clientes()

    elif(opcao == 3):
        atualizar_usuario()

    elif(opcao == 4):
        email = input("Email do usuário: ")
        delete_usuario(session,email)

    elif(opcao == 5):
        cadastrar_compras()

    elif(opcao == 6):
        cadastrar_favoritos()

    elif(opcao == 7):
        email = input("Email do usuário relacionado ao favorito: ")
        deletar_favorito(session,email)

def opcoes_vendedor():
    print("Qual opção deseja?")
    print("01 - Cadastrar")
    print("02 - Visualizar dados")
    print("03 - Atualizar dados")
    print("04 - Deletar dados")
    print("05 - Adicionar relação com produto")
    print("06 - Remover relação com produto")
    print("00 - Voltar")
    print("")
    opcao = int(input("Opção: "))
    print("")

    if(opcao == 0):
        opcoes()

    elif(opcao == 1):
        recebe_cadastro_vendedor()

    elif(opcao == 2):
        pega_vendedores()

    elif(opcao == 3):
        atualizar_vendedor()

    elif(opcao == 4):
        email = input("Email do vendedor: ")
        delete_vendedor(session,email)

    elif(opcao == 5):
        adicionar_relacao()

    elif(opcao == 6):
        email = input("Email do vendedor relacionado ao produto: ")
        remover_relacao(session,email)

def opcoes_produtos():
    print("Qual opção deseja?")
    print("01 - Cadastrar")
    print("02 - Visualizar dados")
    print("03 - Atualizar dados")
    print("04 - Deletar dados")
    print("00 - Voltar")
    print("")
    opcao = int(input("Opção: "))
    print("")

    if(opcao == 0):
        opcoes()

    elif(opcao == 1):
        recebe_cadastro_produto()

    elif(opcao == 2):
        pega_produtos()
        tudo_ok()
        voltar_opcoes()

    elif(opcao == 3):
        atualizar_produto()

    elif(opcao == 4):
        nome = input("Nome do produto: ")
        delete_produto(session,nome)

def opcoes_compras():
    print("Qual opção deseja?")
    print("01 - Visualizar dados")
    print("02 - Deletar dados")
    print("00 - Voltar")
    print("")
    opcao = int(input("Opção: "))
    print("")

    if(opcao == 0):
        opcoes()

    elif(opcao == 1):
        pega_compras()
        tudo_ok()
        voltar_opcoes()

    elif(opcao == 2):
        email = input("Email do usuário relacionado à compra: ")
        delete_compra(session,email)

def tudo_ok():
    print("Sua operação foi realizada!")
    print("---------------------------")
    print("")

def voltar_opcoes():
    print("Escolha uma opção")
    print("01 - Voltar  ao menu")
    print("02 - Sair")
    opcao = int(input("Opção: "))
    print("")
    if(opcao == 1):
        opcoes()

def main():
    session.execute("""
        CREATE TABLE IF NOT EXISTS mercado_livre.usuarios (
            id UUID PRIMARY KEY,
            nome text,
            sobrenome text,
            email text,
            endereco list<frozen<map<text, text>>>
        )
    """)

    session.execute("""
        CREATE TABLE IF NOT EXISTS mercado_livre.vendedores (
            id UUID PRIMARY KEY,
            nome text,
            sobrenome text,
            email text,
            produtos list<text>
        )
    """)

    session.execute("""
        CREATE TABLE IF NOT EXISTS mercado_livre.produtos (
            id UUID PRIMARY KEY,
            nome text,
            quantia text,
            preco text
        )
    """)

    session.execute("""
        CREATE TABLE IF NOT EXISTS mercado_livre.compras (
            id UUID PRIMARY KEY,
            email text,
            produto text
        )
    """)

    session.execute("""
        CREATE TABLE IF NOT EXISTS mercado_livre.favoritos (
            id UUID PRIMARY KEY,
            email text,
            produto text
        )
    """)

    session.execute("""
        CREATE TABLE IF NOT EXISTS mercado_livre.produtos_vendedor (
            id UUID PRIMARY KEY,
            email text,
            produto text
        )
    """)

    session.execute("CREATE INDEX IF NOT EXISTS email_usuario ON usuarios (email);")
    session.execute("CREATE INDEX IF NOT EXISTS email_vendedor ON vendedores (email);")
    session.execute("CREATE INDEX IF NOT EXISTS nome_produto ON produtos (nome);")
    session.execute("CREATE INDEX IF NOT EXISTS email_compra ON compras (email);")
    session.execute("CREATE INDEX IF NOT EXISTS produto_compra ON compras (produto);")
    session.execute("CREATE INDEX IF NOT EXISTS email_favorito ON favoritos (email);")
    session.execute("CREATE INDEX IF NOT EXISTS produto_favorito ON favoritos (produto);")
    session.execute("CREATE INDEX IF NOT EXISTS email_prod_vend ON produtos_vendedor (email);")
    session.execute("CREATE INDEX IF NOT EXISTS produto_prod_vend ON produtos_vendedor (produto);")

main()
opcoes()


# Pablo de Andres
# Deep Learning lab, ML track, exercise 4
# Uni Freiburg WS 2017/18

import argparse
import numpy as np
import os
import sys
import tempfile

from main import Data
from unet import unet

import tensorflow as tf

FLAGS = None

# For running on CPU
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
# tensorboard --logdir=/home/andresp/lab/tensorflow/

def main(_):

  data = Data()

  # Create the model
  x = tf.placeholder(tf.float32, [None, 300, 300, 1])

  # Define loss and optimizer
  y_ = tf.placeholder(tf.int32, [None, 116, 116])

  # Build the graph for the deep net
  y_conv = unet(x)

  with tf.name_scope('loss'):
    loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)
  loss = tf.reduce_mean(loss)
  tf.summary.scalar('loss', loss)

  with tf.name_scope('AdamOptimizer'):
    train_step = tf.train.AdamOptimizer(0.0001, 0.95, 0.99).minimize(loss)

  with tf.name_scope('Accuracy'):
    # Training accuracy
    prediction = tf.argmax(y_conv, 3) # argmax the 3rd dimension, the label
    correct_pix_pred = np.sum(prediction == y_)
    incorrect_pix_pred = np.sum(prediction != y_)
    n_pix = 116 * 116
    train_acc = correct_pix_pred / (incorrect_pix_pred + n_pix)
    # Validation accuracy
    val_acc = 0
    val_images = data.get_test_image_list_and_label_list()
    for i in range(len(val_images[0])):
      x_val = val_images[0][i]
      y_val = val_images[1][i]
      y_conv_acc = unet(x_val)
      prediction = tf.argmax(y_conv_acc, 3)
      correct_pix_pred = np.sum(prediction == y_val)
      incorrect_pix_pred = np.sum(prediction != y_val)
      n_pix = 116 * 116
      val_acc += correct_pix_pred / (incorrect_pix_pred + n_pix)

  train_acc = tf.summary.scalar('Training accuracy', train_acc)
  val_acc = tf.summary.scalar('Validation accuracy', val_acc)

  graph_location = tempfile.mkdtemp()
  print('Saving graph to: %s' % graph_location)
  writer = tf.summary.FileWriter(graph_location)
  writer.add_graph(tf.get_default_graph())

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    writer = tf.summary.FileWriter(FLAGS.log_dir + '/assignment04', sess.graph)
    for i in range(400):
      batch = data.get_train_image_list_and_label_list()
      if i % 100 == 0:
        train_acc, val_acc = sess.run([train_acc, val_acc],
                                      feed_dict={x: batch[0], y_: batch[1]})
        writer.add_summary(train_acc, i)
        writer.add_summary(val_acc, i)
        print('step %d'% (i))
      train_step.run(feed_dict={x: batch[0], y_: batch[1]})
    writer.close()

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  parser.add_argument('--log_dir', type=str,
                      default=os.path.join(os.getenv('HOME', '/home'),
                                           'lab/tensorflow'),
                      help='Summaries log directory')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)


from __future__ import print_function

import sys, os
from optparse import OptionParser

# Change path so we find Xlib
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from Xlib.display import Display
from Xlib.ext import security

def main(argv):
    parser = OptionParser()

    parser.add_option('--generate', action='store_true', default=False)
    parser.add_option('--proto', default='MIT-MAGIC-COOKIE-1')
    parser.add_option('--trusted', action='store_true', default=False)
    parser.add_option('--untrusted', action='store_true', default=False)

    parser.add_option('--revoke', action='store_true', default=False)

    opts, args = parser.parse_args(argv[1:])

    if opts.trusted and opts.untrusted:
        parser.error('--trusted and --untrusted cannot be combined')

    if not any((opts.generate, opts.revoke)):
        parser.error('specify --generate or --revoke')

    display = Display()

    if not display.has_extension('SECURITY'):
        if display.query_extension('SECURITY') is None:
            print('SECURITY extension not supported', file=sys.stderr)
            return 1

    security_version = display.security_query_version()
    print('SECURITY version %s.%s' % (
      security_version.major_version,
      security_version.minor_version,
    ), file=sys.stderr)

    if opts.generate:
        kwargs = {}
        if opts.trusted:
            kwargs['trust_level'] = security.SecurityClientTrusted
        elif opts.untrusted:
            kwargs['trust_level'] = security.SecurityClientUntrusted
        reply = display.security_generate_authorization(opts.proto, **kwargs)
        print(reply.authid)

    elif opts.revoke:
        for arg in args:
            authid = int(arg, 10)
            display.security_revoke_authorization(authid)

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


class Solution:
    def simplifyPath(self, path: str) -> str:
        dirList = []

        for directory in path.split('/') :
            # Ignore
            if not directory or directory == ".":
                continue
            # Directory up a level
            if directory == "..":
                if dirList:
                    dirList.pop()
            # Append it in dirList
            else:
                dirList.append(directory)

        res = "/"
        # Make all dir in dirList add in res
        for directory in dirList:
            res += directory
            res += "/"
        # If res == "/" return it else pop out last string
        return res[:-1] if res != "/" else "/"

Mar 14 71. Simplify Path (Medium)/Solution.py


import os

from spack import *

class Sirius(CMakePackage, CudaPackage, ROCmPackage):
    """Domain specific library for electronic structure calculations"""

    homepage = "https://github.com/electronic-structure/SIRIUS"
    url = "https://github.com/electronic-structure/SIRIUS/archive/v6.1.5.tar.gz"
    list_url = "https://github.com/electronic-structure/SIRIUS/releases"
    git = "https://github.com/electronic-structure/SIRIUS.git"

    maintainers = ["simonpintarelli", "haampie", "dev-zero", "AdhocMan", "toxa81"]

    # Don't upstream this, it's to work around
    # https://github.com/spack/spack/pull/18574 / https://github.com/spack/spack/pull/18838
    build_dirname = "spack-build"

    version("develop", branch="develop")
    version("master", branch="master")

    version(
        "7.3.0",
        sha256="69b5cf356adbe181be6c919032859c4e0160901ff42a885d7e7ea0f38cc772e2",
    )
    version(
        "7.2.7",
        sha256="929bf7f131a4847624858b9c4295532c24b0c06f6dcef5453c0dfc33fb78eb03",
    )
    version(
        "7.2.6",
        sha256="e751fd46cdc7c481ab23b0839d3f27fb00b75dc61dc22a650c92fe8e35336e3a",
    )
    version(
        "7.2.5",
        sha256="794e03d4da91025f77542d3d593d87a8c74e980394f658a0210a4fd91c011f22",
    )
    version(
        "7.2.4",
        sha256="aeed0e83b80c3a79a9469e7f3fe10d80ad331795e38dbc3c49cb0308e2bd084d",
    )
    version(
        "7.2.3",
        sha256="6c10f0e87e50fcc7cdb4d1b2d35e91dba6144de8f111e36c7d08912e5942a906",
    )
    version(
        "7.2.1",
        sha256="01bf6c9893ff471473e13351ca7fdc2ed6c1f4b1bb7afa151909ea7cd6fa0de7",
    )
    version(
        "7.2.0",
        sha256="537800459db8a7553d7aa251c19f3a31f911930194b068bc5bca2dfb2c9b71db",
    )
    version(
        "7.0.2",
        sha256="ee613607ce3be0b2c3f69b560b2415ce1b0e015179002aa90739430dbfaa0389",
        deprecated=True,
    )
    version(
        "7.0.1",
        sha256="cca11433f86e7f4921f7956d6589f27bf0fd5539f3e8f96e66a3a6f274888595",
        deprecated=True,
    )
    version(
        "7.0.0",
        sha256="da783df11e7b65668e29ba8d55c8a6827e2216ad6d88040f84f42ac20fd1bb99",
        deprecated=True,
    )
    version(
        "6.5.7",
        sha256="d886c3066163c43666ebac2ea50351df03907b5686671e514a75f131ba51b43c",
        deprecated=True,
    )
    version(
        "6.5.6",
        sha256="c8120100bde4477545eae489ea7f9140d264a3f88696ec92728616d78f214cae",
        deprecated=True,
    )
    version(
        "6.5.5",
        sha256="0b23d3a8512682eea67aec57271031c65f465b61853a165015b38f7477651dd1",
        deprecated=True,
    )
    version(
        "6.5.4",
        sha256="5f731926b882a567d117afa5e0ed33291f1db887fce52f371ba51f014209b85d",
        deprecated=True,
    )
    version(
        "6.5.3",
        sha256="eae0c303f332425a8c792d4455dca62557931b28a5df8b4c242652d5ffddd580",
        deprecated=True,
    )
    version(
        "6.5.2",
        sha256="c18adc45b069ebae03f94eeeeed031ee99b3d8171fa6ee73c7c6fb1e42397fe7",
        deprecated=True,
    )
    version(
        "6.5.1",
        sha256="599dd0fa25a4e83db2a359257a125e855d4259188cf5b0065b8e7e66378eacf3",
        deprecated=True,
    )
    version(
        "6.5.0",
        sha256="5544f3abbb71dcd6aa08d18aceaf53c38373de4cbd0c3af44fbb39c20cfeb7cc",
        deprecated=True,
    )
    version(
        "6.4.4",
        sha256="1c5de9565781847658c3cc11edcb404e6e6d1c5a9dfc81e977de7a9a7a162c8a",
        deprecated=True,
    )
    version(
        "6.4.3",
        sha256="4d1effeadb84b3e1efd7d9ac88018ef567aa2e0aa72e1112f0abf2e493e2a189",
        deprecated=True,
    )
    version(
        "6.4.2",
        sha256="40b9b66deebb6538fc0f4cd802554d0d763ea6426b9b2f0e8db8dc617e494479",
        deprecated=True,
    )
    version(
        "6.4.1",
        sha256="86f25c71517952a63e92e0a9bcf66d27e4afb2b0d67cf84af480f116b8e7f53c",
        deprecated=True,
    )
    version(
        "6.4.0",
        sha256="bc61758b71dd2996e2ff515b8c3560b2c69c00931cb2811a163a31bcfea4436e",
        deprecated=True,
    )
    version(
        "6.3.4",
        sha256="8839e988b4bb6ef99b6180f7fba03a5537e31fce51bb3e4c2298b513d6a07e0a",
        deprecated=True,
    )
    version(
        "6.3.3",
        sha256="7ba30a4e5c9a545433251211454ec0d59b74ba8941346057bc7de11e7f6886f7",
        deprecated=True,
    )
    version(
        "6.3.2",
        sha256="1723e5ad338dad9a816369a6957101b2cae7214425406b12e8712c82447a7ee5",
        deprecated=True,
    )
    version(
        "6.1.5",
        sha256="379f0a2e5208fd6d91c2bd4939c3a5c40002975fb97652946fa1bfe4a3ef97cb",
        deprecated=True,
    )

    variant("shared", default=True, description="Build shared libraries")
    variant("openmp", default=True, description="Build with OpenMP support")
    variant(
        "boost_filesystem",
        default=False,
        description="Use Boost filesystem for self-consistent field method "
        "mini-app. Only required when the compiler does not "
        "support std::experimental::filesystem nor std::filesystem",
    )
    variant("fortran", default=False, description="Build Fortran bindings")
    variant("python", default=False, description="Build Python bindings")
    variant("memory_pool", default=True, description="Build with memory pool")
    variant("elpa", default=False, description="Use ELPA")
    variant("vdwxc", default=False, description="Enable libvdwxc support")
    variant("scalapack", default=False, description="Enable scalapack support")
    variant("magma", default=False, description="Enable MAGMA support")
    variant(
        "nlcglib", default=False, description="enable robust wave function optimization"
    )
    variant(
        "build_type",
        default="Release",
        description="CMake build type",
        values=("Debug", "Release", "RelWithDebInfo"),
    )
    variant("apps", default=True, description="Build applications")
    variant("tests", default=False, description="Build tests")
    variant(
        "single_precision",
        default=False,
        description="Use single precision arithmetics",
    )
    variant(
        "profiler",
        default=True,
        description="Use internal profiler to measure execution time",
    )

    depends_on("mpi")
    depends_on("gsl")
    depends_on("lapack")
    depends_on("fftw-api@3")
    depends_on("libxc@3.0.0:")
    depends_on("libxc@4.0.0:", when="@7.2.0:")
    depends_on("spglib")
    depends_on("hdf5+hl")
    depends_on("pkgconfig", type="build")

    # Python module
    depends_on("python", when="+python@3.6:", type=("build", "run"))
    depends_on("python", when="@:6", type=("build", "run"))
    depends_on("py-numpy", when="+python", type=("build", "run"))
    depends_on("py-scipy", when="+python", type=("build", "run"))
    depends_on("py-h5py", when="+python", type=("build", "run"))
    depends_on("py-mpi4py", when="+python", type=("build", "run"))
    depends_on("py-pyyaml", when="+python", type=("build", "run"))
    depends_on("py-mpi4py", when="+python", type=("build", "run"))
    depends_on("py-voluptuous", when="+python", type=("build", "run"))
    depends_on("py-pybind11", when="+python", type=("build", "run"))
    extends("python", when="+python")

    depends_on("magma", when="+magma")
    depends_on("boost cxxstd=14 +filesystem", when="+boost_filesystem")

    depends_on("spfft@0.9.6: +mpi", when="@6.4.0:")
    depends_on("spfft@0.9.13:", when="@7.0.1:")
    depends_on("spfft+single_precision", when="+single_precision ^spfft")
    depends_on("spfft+cuda", when="+cuda ^spfft")
    depends_on("spfft+rocm", when="+rocm ^spfft")
    depends_on("spfft+openmp", when="+openmp ^spfft")

    depends_on("spla@1.1.0:", when="@7.0.2:")
    depends_on("spla+cuda", when="+cuda ^spla")
    depends_on("spla+rocm", when="+rocm ^spla")
    depends_on("spla+openmp", when="+openmp ^spla")

    depends_on("nlcglib", when="+nlcglib")

    depends_on("libvdwxc@0.3.0:+mpi", when="+vdwxc")

    depends_on("scalapack", when="+scalapack")

    # rocm
    depends_on("hip", when="+rocm")
    depends_on("rocblas", when="+rocm")

    # FindHIP cmake script only works for < 4.1
    depends_on("hip@:4.0", when="@:7.2.0 +rocm")

    conflicts("+shared", when="@6.3.0:6.4")
    conflicts("+boost_filesystem", when="~apps")
    conflicts("^libxc@5.0.0")  # known to produce incorrect results
    conflicts("+single_precision", when="@:7.2.4")

    # Propagate openmp to blas
    depends_on("openblas threads=openmp", when="+openmp ^openblas")
    depends_on("amdblis threads=openmp", when="+openmp ^amdblis")
    depends_on("blis threads=openmp", when="+openmp ^blis")
    depends_on("intel-mkl threads=openmp", when="+openmp ^intel-mkl")

    depends_on("elpa+openmp", when="+elpa+openmp")
    depends_on("elpa~openmp", when="+elpa~openmp")

    depends_on("eigen@3.4.0:", when="@7.4: +tests")

    depends_on("costa+shared", when="@7.4:")

    # TODO:
    # add support for CRAY_LIBSCI, testing

    patch("strip-spglib-include-subfolder.patch", when="@6.1.5")
    patch("link-libraries-fortran.patch", when="@6.1.5")
    patch("cmake-fix-shared-library-installation.patch", when="@6.1.5")
    patch("mpi_datatypes.patch", when="@:7.2.6")

    @property
    def libs(self):
        libraries = []

        if "@6.3.0:" in self.spec:
            libraries += ["libsirius"]

            return find_libraries(
                libraries,
                root=self.prefix,
                shared="+shared" in self.spec,
                recursive=True,
            )
        else:
            if "+fortran" in self.spec:
                libraries += ["libsirius_f"]

            if "+cuda" in self.spec:
                libraries += ["libsirius_cu"]

            return find_libraries(
                libraries,
                root=self.prefix,
                shared="+shared" in self.spec,
                recursive=True,
            )

    def cmake_args(self):
        spec = self.spec

        args = [
            self.define_from_variant("USE_OPENMP", "openmp"),
            self.define_from_variant("USE_ELPA", "elpa"),
            self.define_from_variant("USE_MAGMA", "magma"),
            self.define_from_variant("USE_NLCGLIB", "nlcglib"),
            self.define_from_variant("USE_VDWXC", "vdwxc"),
            self.define_from_variant("USE_MEMORY_POOL", "memory_pool"),
            self.define_from_variant("USE_SCALAPACK", "scalapack"),
            self.define_from_variant("CREATE_FORTRAN_BINDINGS", "fortran"),
            self.define_from_variant("CREATE_PYTHON_MODULE", "python"),
            self.define_from_variant("USE_CUDA", "cuda"),
            self.define_from_variant("USE_ROCM", "rocm"),
            self.define_from_variant("BUILD_TESTING", "tests"),
            self.define_from_variant("BUILD_APPS", "apps"),
            self.define_from_variant("BUILD_SHARED_LIBS", "shared"),
            self.define_from_variant("USE_FP32", "single_precision"),
            self.define_from_variant("USE_PROFILER", "profiler"),
        ]

        lapack = spec["lapack"]
        blas = spec["blas"]

        args.extend(
            [
                self.define("LAPACK_FOUND", "true"),
                self.define("LAPACK_LIBRARIES", lapack.libs.joined(";")),
                self.define("BLAS_FOUND", "true"),
                self.define("BLAS_LIBRARIES", blas.libs.joined(";")),
            ]
        )

        if "+scalapack" in spec:
            args.extend(
                [
                    self.define("SCALAPACK_FOUND", "true"),
                    self.define(
                        "SCALAPACK_INCLUDE_DIRS", spec["scalapack"].prefix.include
                    ),
                    self.define(
                        "SCALAPACK_LIBRARIES", spec["scalapack"].libs.joined(";")
                    ),
                ]
            )

        if spec["blas"].name in ["intel-mkl", "intel-parallel-studio"]:
            args.append(self.define("USE_MKL", "ON"))

        if "+elpa" in spec:
            elpa_incdir = os.path.join(spec["elpa"].headers.directories[0], "elpa")
            args.append(self.define("ELPA_INCLUDE_DIR", elpa_incdir))

        if "+cuda" in spec:
            cuda_arch = spec.variants["cuda_arch"].value
            if cuda_arch[0] != "none":
                # Specify a single arch directly
                if "@:6" in spec:
                    args.append(
                        self.define(
                            "CMAKE_CUDA_FLAGS", "-arch=sm_{0}".format(cuda_arch[0])
                        )
                    )

                # Make SIRIUS handle it
                elif "@6:7.3" in spec:
                    args.append(self.define("CUDA_ARCH", ";".join(cuda_arch)))
                else:
                    args.append(self.define("CMAKE_CUDA_ARCHITECTURES", ";".join(cuda_arch)))
        if "+rocm" in spec:
            archs = ",".join(self.spec.variants["amdgpu_target"].value)
            if "@:7.3" in spec:
                args.extend(
                    [
                        self.define("HIP_ROOT_DIR", spec["hip"].prefix),
                        self.define("HIP_HCC_FLAGS", "--amdgpu-target={0}".format(archs)),
                        self.define("HIP_CXX_COMPILER", self.spec["hip"].hipcc),
                    ]
                )
            else:
                args.extend([self.define("CMAKE_HIP_ARCHITECTURES", archs)])

        return args


########################
#file: zbw_animShift.py
#Author: zeth willie
#Contact: zeth@catbuks.com, www.williework.blogspot.com
#Date Modified: 4/27/13
#To Use: type in python window  "import zbw_animShift as ash; ash.animShift()"
#Notes/Descriptions: Used to move animation curves based on changes to a base object at a certain frame
########################

import maya.cmds as cmds

class AnimShift(object):

    def __init__(self):

        self.widgets = {}
        self.frame = 1

        #add in the vars for if there's a key on base
        self.txk=False
        self.tyk=False
        self.tzk=False
        self.rxk=False
        self.ryk=False
        self.rzk=False
        self.sxk=False
        self.syk=False
        self.szk=False

        self.baseObj = ""

        self.shiftUI()

    def shiftUI(self, *args):
        """ui for the class"""

        if cmds.window("shiftWin", exists=True):
            cmds.deleteUI("shiftWin")

        self.widgets["win"] = cmds.window("shiftWin", t="zbw_animShift", w=330, h=500)
        self.widgets["mainCLO"] = cmds.columnLayout()

        self.widgets["timeRBG"] = cmds.radioButtonGrp(l="Range Options:", nrb=3, l1="All", l2="Time Slider", l3="Range", sl=1, cw=([1,100], [2,50],[3,100],[4,50]), cal=(1,"left"), cc=self.enableRange)
        self.widgets["rangeFFG"] = cmds.floatFieldGrp(l="Start/End Frames", nf=2, v1=1, v2=10, en=False, cal=((1,"left"),(2,"left")), cw=((1,100), (2,50),(3,50)))

        cmds.separator(h=5, style="single")

        self.widgets["getBaseBut"]  = cmds.button(l="1. Set Base Object and Frame To Drive Shift", w=330, h=40, bgc=(.6,.8,.6), c=self.getBase)
        self.widgets["baseTFG"] = cmds.textFieldGrp(l="Base Object", cal=((1,"left"), (2,"left")), cw=((1,70),(2,250)), ed=False)
        self.widgets["baseFrameFFG"] = cmds.floatFieldGrp(l="Base Frame", cal = ((1, "left"), (2,"left")), cw=((1,100), (2,50)), pre=2, en=False)

        cmds.separator(h=10)

        self.widgets["valueRCL"] = cmds.rowColumnLayout(nc=3, cw=([1,110],[2,110],[3,110]))
        cmds.text("Orig Values")
        cmds.text("Modified Values")
        cmds.text("Difference Value")

        cmds.separator(style="single", h=5)
        cmds.separator(style="single", h=5)
        cmds.separator(style="single", h=5)

        self.widgets["origTxFFG"] = cmds.floatFieldGrp(l="tx", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["modTxFFG"] = cmds.floatFieldGrp(l="tx", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["difTxFFG"] = cmds.floatFieldGrp(l="tx", pre=5, cal=([1,"left"], [2, "left"]), cw=([1, 30], [2,75]))

        self.widgets["origTyFFG"] = cmds.floatFieldGrp(l="ty", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["modTyFFG"] = cmds.floatFieldGrp(l="ty", pre=5, cal=([1,"left"], [2, "left"]),  en=False,cw=([1, 30], [2,75]))
        self.widgets["difTyFFG"] = cmds.floatFieldGrp(l="ty", pre=5, cal=([1,"left"], [2, "left"]), cw=([1, 30], [2,75]))

        self.widgets["origTzFFG"] = cmds.floatFieldGrp(l="tz", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["modTzFFG"] = cmds.floatFieldGrp(l="tz", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["difTzFFG"] = cmds.floatFieldGrp(l="tz", pre=5, cal=([1,"left"], [2, "left"]), cw=([1, 30], [2,75]))

        cmds.separator(style="single", h=5)
        cmds.separator(style="single", h=5)
        cmds.separator(style="single", h=5)

        self.widgets["origRxFFG"] = cmds.floatFieldGrp(l="rx", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["modRxFFG"] = cmds.floatFieldGrp(l="rx", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["difRxFFG"] = cmds.floatFieldGrp(l="rx", pre=5, cal=([1,"left"], [2, "left"]), cw=([1, 30], [2,75]))

        self.widgets["origRyFFG"] = cmds.floatFieldGrp(l="ry", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["modRyFFG"] = cmds.floatFieldGrp(l="ry", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["difRyFFG"] = cmds.floatFieldGrp(l="ry", pre=5, cal=([1,"left"], [2, "left"]), cw=([1, 30], [2,75]))

        self.widgets["origRzFFG"] = cmds.floatFieldGrp(l="rz", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["modRzFFG"] = cmds.floatFieldGrp(l="rz", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["difRzFFG"] = cmds.floatFieldGrp(l="rz", pre=5, cal=([1,"left"], [2, "left"]), cw=([1, 30], [2,75]))

        cmds.separator(style="single", h=5)
        cmds.separator(style="single", h=5)
        cmds.separator(style="single", h=5)

        self.widgets["origSxFFG"] = cmds.floatFieldGrp(l="sx", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["modSxFFG"] = cmds.floatFieldGrp(l="sx", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["difSxFFG"] = cmds.floatFieldGrp(l="sx", pre=5, cal=([1,"left"], [2, "left"]), cw=([1, 30], [2,75]))

        self.widgets["origSyFFG"] = cmds.floatFieldGrp(l="sy", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["modSyFFG"] = cmds.floatFieldGrp(l="sy", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["difSyFFG"] = cmds.floatFieldGrp(l="sy", pre=5, cal=([1,"left"], [2, "left"]), cw=([1, 30], [2,75]))

        self.widgets["origSzFFG"] = cmds.floatFieldGrp(l="sz", pre=5, cal=([1,"left"], [2, "left"]), en=False, cw=([1, 30], [2,75]))
        self.widgets["modSzFFG"] = cmds.floatFieldGrp(l="sz", pre=5, cal=([1,"left"], [2, "left"]), en=False,cw=([1, 30], [2,75]))
        self.widgets["difSzFFG"] = cmds.floatFieldGrp(l="sz", pre=5, cal=([1,"left"], [2, "left"]), cw=([1, 30], [2,75]))

        cmds.separator(style="single", h=5)
        cmds.separator(style="single", h=5)
        cmds.separator(style="single", h=5)

        cmds.setParent(self.widgets["mainCLO"])

        #button to capture and calculate changes to the anim curves
        self.widgets["captureBut"] = cmds.button(l="2. Calculate and Capture Changed Values", w=330, h=30, bgc=(.8,.8,.6), c=self.captureChanges)

        cmds.separator(style="single", h=5)

        self.widgets["moveBut"] = cmds.button(l="3. Shift The Anim Curves For Selected Objects!", w=330, h=30, bgc=(.6,.6,.8), c=self.shiftAnim)

        cmds.separator(style="single", h=5)

        self.widgets["doneText"] = cmds.text(w=330, l="No Status/All Cleared. Select a base object!", vis=True, bgc=(.5,.5,.5), al="center")
        cmds.separator(style="single", h=10)

        #2 column layout to spread these two buttons
        self.widgets["bottomButtonRCL"] = cmds.rowColumnLayout(nc=2, w=330, cw=((1,250), (2,80)))
        self.widgets["clearButton"] = cmds.button(l="Clear All Values!", w=330, h=30, bgc=(.9,.5,.5), c=self.clearAll)
        # self.widgets["restoreButton"] = cmds.button(l="Restore Base", w=80, h=30, bgc=(.8,.5,.5), c=self.restoreBase)
        cmds.showWindow(self.widgets["win"])
        cmds.window(self.widgets["win"], e=True, w=330, h=500)

    #####functions#####

    def getBase(self, *args):

        sel = cmds.ls(sl=True, type="transform", l=True)

        if len(sel)>1:
            cmds.warning("You've selected more than one object. Only one object can be the base of the animation shift")
        else:
            obj = sel[0]
            #put sel in the base obj tfg and get the frame
            cmds.textFieldGrp(self.widgets["baseTFG"], e=True, tx=obj)
            self.frame = cmds.currentTime(q=True)
            cmds.floatFieldGrp(self.widgets["baseFrameFFG"], e=True, v1=self.frame)

            btx = cmds.getAttr("%s.tx"%obj)
            bty = cmds.getAttr("%s.ty"%obj)
            btz = cmds.getAttr("%s.tz"%obj)

            brx = cmds.getAttr("%s.rx"%obj)
            bry = cmds.getAttr("%s.ry"%obj)
            brz = cmds.getAttr("%s.rz"%obj)

            bsx = cmds.getAttr("%s.sx"%obj)
            bsy = cmds.getAttr("%s.sy"%obj)
            bsz = cmds.getAttr("%s.sz"%obj)

            cmds.floatFieldGrp(self.widgets["origTxFFG"], e=True, v1=btx)
            cmds.floatFieldGrp(self.widgets["origTyFFG"], e=True, v1=bty)
            cmds.floatFieldGrp(self.widgets["origTzFFG"], e=True, v1=btz)

            cmds.floatFieldGrp(self.widgets["origRxFFG"], e=True, v1=brx)
            cmds.floatFieldGrp(self.widgets["origRyFFG"], e=True, v1=bry)
            cmds.floatFieldGrp(self.widgets["origRzFFG"], e=True, v1=brz)

            cmds.floatFieldGrp(self.widgets["origSxFFG"], e=True, v1=bsx)
            cmds.floatFieldGrp(self.widgets["origSyFFG"], e=True, v1=bsy)
            cmds.floatFieldGrp(self.widgets["origSzFFG"], e=True, v1=bsz)

            if cmds.keyframe("%s.tx"%(obj), q=True, t=(self.frame, self.frame)):
                self.txk = True
            if cmds.keyframe("%s.ty"%(obj), q=True, t=(self.frame, self.frame)):
                self.tyk = True
            if cmds.keyframe("%s.tz"%obj, q=True, t=(self.frame, self.frame)):
                self.tzk = True

            if cmds.keyframe("%s.rx"%(obj), q=True, t=(self.frame, self.frame)):
                self.rxk = True
            if cmds.keyframe("%s.ry"%(obj), q=True, t=(self.frame, self.frame)):
                self.ryk = True
            if cmds.keyframe("%s.rz"%obj, q=True, t=(self.frame, self.frame)):
                self.rzk = True

            if cmds.keyframe("%s.sx"%(obj), q=True, t=(self.frame, self.frame)):
                self.sxk = True
            if cmds.keyframe("%s.sy"%(obj), q=True, t=(self.frame, self.frame)):
                self.syk = True
            if cmds.keyframe("%s.sz"%obj, q=True, t=(self.frame, self.frame)):
                self.szk = True

            #catch the base object  and frame for later use
            self.baseObj = obj

            cmds.text(self.widgets["doneText"], e=True, l='"Base Obj Set! Base Frame is: %s"'%self.frame, vis=True, bgc=(.5,.6,.5))

    def captureChanges(self, *args):
        """method to capture value changes"""
        obj = cmds.textFieldGrp(self.widgets["baseTFG"], q=True, tx=True)
        frame = cmds.floatFieldGrp(self.widgets["baseFrameFFG"], q=True, v1=True)
        cmds.currentTime(frame, edit=True)

        if obj:
            #poplulate the second column with the new values from the base object
            mtx = cmds.getAttr("%s.tx"%obj)
            mty = cmds.getAttr("%s.ty"%obj)
            mtz = cmds.getAttr("%s.tz"%obj)

            mrx = cmds.getAttr("%s.rx"%obj)
            mry = cmds.getAttr("%s.ry"%obj)
            mrz = cmds.getAttr("%s.rz"%obj)

            msx = cmds.getAttr("%s.sx"%obj)
            msy = cmds.getAttr("%s.sy"%obj)
            msz = cmds.getAttr("%s.sz"%obj)

            cmds.floatFieldGrp(self.widgets["modTxFFG"], e=True, v1=mtx)
            cmds.floatFieldGrp(self.widgets["modTyFFG"], e=True, v1=mty)
            cmds.floatFieldGrp(self.widgets["modTzFFG"], e=True, v1=mtz)

            cmds.floatFieldGrp(self.widgets["modRxFFG"], e=True, v1=mrx)
            cmds.floatFieldGrp(self.widgets["modRyFFG"], e=True, v1=mry)
            cmds.floatFieldGrp(self.widgets["modRzFFG"], e=True, v1=mrz)

            cmds.floatFieldGrp(self.widgets["modSxFFG"], e=True, v1=msx)
            cmds.floatFieldGrp(self.widgets["modSyFFG"], e=True, v1=msy)
            cmds.floatFieldGrp(self.widgets["modSzFFG"], e=True, v1=msz)

            #get orig values
            otx = cmds.floatFieldGrp(self.widgets["origTxFFG"], q=True, v1=True)
            oty = cmds.floatFieldGrp(self.widgets["origTyFFG"], q=True, v1=True)
            otz = cmds.floatFieldGrp(self.widgets["origTzFFG"], q=True, v1=True)

            orx = cmds.floatFieldGrp(self.widgets["origRxFFG"], q=True, v1=True)
            ory = cmds.floatFieldGrp(self.widgets["origRyFFG"], q=True, v1=True)
            orz = cmds.floatFieldGrp(self.widgets["origRzFFG"], q=True, v1=True)

            osx = cmds.floatFieldGrp(self.widgets["origSxFFG"], q=True, v1=True)
            osy = cmds.floatFieldGrp(self.widgets["origSyFFG"], q=True, v1=True)
            osz = cmds.floatFieldGrp(self.widgets["origSzFFG"], q=True, v1=True)

            #now subtract them and put the value in the diff column
            dtx = mtx - otx
            dty = mty - oty
            dtz = mtz - otz

            drx = mrx - orx
            dry = mry - ory
            drz = mrz - orz

            dsx = msx - osx
            dsy = msy - osy
            dsz = msz - osz

            cmds.floatFieldGrp(self.widgets["difTxFFG"], e=True, v1=dtx)
            cmds.floatFieldGrp(self.widgets["difTyFFG"], e=True, v1=dty)
            cmds.floatFieldGrp(self.widgets["difTzFFG"], e=True, v1=dtz)

            cmds.floatFieldGrp(self.widgets["difRxFFG"], e=True, v1=drx)
            cmds.floatFieldGrp(self.widgets["difRyFFG"], e=True, v1=dry)
            cmds.floatFieldGrp(self.widgets["difRzFFG"], e=True, v1=drz)

            cmds.floatFieldGrp(self.widgets["difSxFFG"], e=True, v1=dsx)
            cmds.floatFieldGrp(self.widgets["difSyFFG"], e=True, v1=dsy)
            cmds.floatFieldGrp(self.widgets["difSzFFG"], e=True, v1=dsz)

            cmds.text(self.widgets["doneText"], e=True, l='"Shift Values Captured! Now Select Objs to Shift!"', vis=True, bgc=(.6,.6,.5))
        else:
            cmds.warning("You don't have anything in the base object field!")

    def shiftAnim(self, *args):
        """method that does the shifting"""
#TO-DO----------------possible to-do? Deal with locked or already driven channels?
#TO-DO----------------eval the curve at that point, then set the value in world space, then eval the curve again, then find the difference and move the curve that much (how will this work for rotation?)

        self.getRange()
        #print "start Frame: %s. . . endFrame: %s"%(self.startF, self.endF)

        base = cmds.textFieldGrp(self.widgets["baseTFG"], q=True, tx=True)

        #get vals of changes for each
        self.dtx = cmds.floatFieldGrp(self.widgets["difTxFFG"], q=True, v1=True)
        self.dty = cmds.floatFieldGrp(self.widgets["difTyFFG"], q=True, v1=True)
        self.dtz = cmds.floatFieldGrp(self.widgets["difTzFFG"], q=True, v1=True)

        self.drx = cmds.floatFieldGrp(self.widgets["difRxFFG"], q=True, v1=True)
        self.dry = cmds.floatFieldGrp(self.widgets["difRyFFG"], q=True, v1=True)
        self.drz = cmds.floatFieldGrp(self.widgets["difRzFFG"], q=True, v1=True)

        self.dsx = cmds.floatFieldGrp(self.widgets["difSxFFG"], q=True, v1=True)
        self.dsy = cmds.floatFieldGrp(self.widgets["difSyFFG"], q=True, v1=True)
        self.dsz = cmds.floatFieldGrp(self.widgets["difSzFFG"], q=True, v1=True)

        sel = cmds.ls(sl=True, type="transform", l=True)

        if sel:
            for obj in sel:
                if self.startF:
                    #if there is a frame range, do the stuff with time here
                    cmds.keyframe(obj, at=("tx"), r=True, vc=self.dtx, t=(self.startF, self.endF))
                    cmds.keyframe(obj, at=("ty"), r=True, vc=self.dty, t=(self.startF, self.endF))
                    cmds.keyframe(obj, at=("tz"), r=True, vc=self.dtz, t=(self.startF, self.endF))

                    cmds.keyframe(obj, at=("rx"), r=True, vc=self.drx, t=(self.startF, self.endF))
                    cmds.keyframe(obj, at=("ry"), r=True, vc=self.dry, t=(self.startF, self.endF))
                    cmds.keyframe(obj, at=("rz"), r=True, vc=self.drz, t=(self.startF, self.endF))

                    cmds.keyframe(obj, at=("sx"), r=True, vc=self.dsx, t=(self.startF, self.endF))
                    cmds.keyframe(obj, at=("sy"), r=True, vc=self.dsy, t=(self.startF, self.endF))
                    cmds.keyframe(obj, at=("sz"), r=True, vc=self.dsz, t=(self.startF, self.endF))

                else:
                    #else just do it on the curve with no time argument
                    cmds.keyframe(obj, at=("tx"), r=True, vc=self.dtx)
                    cmds.keyframe(obj, at=("ty"), r=True, vc=self.dty)
                    cmds.keyframe(obj, at=("tz"), r=True, vc=self.dtz)

                    cmds.keyframe(obj, at=("rx"), r=True, vc=self.drx)
                    cmds.keyframe(obj, at=("ry"), r=True, vc=self.dry)
                    cmds.keyframe(obj, at=("rz"), r=True, vc=self.drz)

                    cmds.keyframe(obj, at=("sx"), r=True, vc=self.dsx)
                    cmds.keyframe(obj, at=("sy"), r=True, vc=self.dsy)
                    cmds.keyframe(obj, at=("sz"), r=True, vc=self.dsz)

                if obj==base:
                    #this section is to a) clear the new key if there wasn't one before or b) offset the new key BACK to the rest of the newly moved curve (by neg delta)
                    if self.txk:
                        #offset the value BACK at self.frame
                        cmds.keyframe(obj, at="tx", r=True, vc=-self.dtx, t=(self.frame, self.frame))
                    else:
                        #delete the key at self.frame if it exists
                        cmds.cutKey(obj, at="tx", t=(self.frame, self.frame), cl=True)
                    if self.tyk:
                        cmds.keyframe(obj, at="ty", r=True, vc=-self.dty, t=(self.frame, self.frame))
                    else:
                        cmds.cutKey(obj, at="ty", t=(self.frame, self.frame), cl=True)
                    if self.tzk:
                        cmds.keyframe(obj, at="tz", r=True, vc=-self.dtz, t=(self.frame, self.frame))
                    else:
                        cmds.cutKey(obj, at="tz", t=(self.frame, self.frame), cl=True)

                    if self.rxk:
                        cmds.keyframe(obj, at="rx", r=True, vc=-self.drx, t=(self.frame, self.frame))
                    else:
                        cmds.cutKey(obj, at="rx", t=(self.frame, self.frame), cl=True)
                    if self.ryk:
                        cmds.keyframe(obj, at="ry", r=True, vc=-self.dry, t=(self.frame, self.frame))
                    else:
                        cmds.cutKey(obj, at="ry", t=(self.frame, self.frame), cl=True)
                    if self.rzk:
                        cmds.keyframe(obj, at="rz", r=True, vc=-self.drz, t=(self.frame, self.frame))
                    else:
                        cmds.cutKey(obj, at="rz", t=(self.frame, self.frame), cl=True)

                    if self.sxk:
                        cmds.keyframe(obj, at="sx", r=True, vc=-self.dsx, t=(self.frame, self.frame))
                    else:
                        cmds.cutKey(obj, at="sx", t=(self.frame, self.frame), cl=True)
                    if self.syk:
                        cmds.keyframe(obj, at="sy", r=True, vc=-self.dsy, t=(self.frame, self.frame))
                    else:
                        cmds.cutKey(obj, at="sy", t=(self.frame, self.frame), cl=True)
                    if self.szk:
                        cmds.keyframe(obj, at="sz", r=True, vc=-self.dsz, t=(self.frame, self.frame))
                    else:
                        cmds.cutKey(obj, at="sz", t=(self.frame, self.frame), cl=True)
        else:
            cmds.warning("You've unselected stuff and you need some selections to shift!")

        #clear base object (so we don't double up on keyframe corrections)
        # cmds.textFieldGrp(self.widgets["baseTFG"], e=True, tx="")
        size = len(sel)
        if size == 1:
            cmds.text(self.widgets["doneText"], e=True, l='"%s Shifted! Select Other Objs to Shift or Clear!"'%sel[0], vis=True, bgc=(.5,.5,.6))
        elif size > 1:
            cmds.text(self.widgets["doneText"], e=True, l="%s Objects Shifted! Select Others to Shift or Clear!", vis=True, bgc=(.5,.5,.6))
        else:
            cmds.text(self.widgets["doneText"], e=True, l="You Need To Select Something To Shift!", vis=True, bgc=(.5,.5,.6))

    def clearAll(self, *args):
        """clears all the fields"""
        fieldNames = ["origTxFFG", "origTyFFG", "origTzFFG", "origSxFFG", "origSyFFG", "origSzFFG", "origRxFFG", "origRyFFG", "origRzFFG", "modTxFFG", "modTyFFG", "modTzFFG", "modRxFFG", "modRyFFG", "modRzFFG", "modSxFFG", "modSyFFG", "modSzFFG", "difTxFFG", "difTyFFG", "difTzFFG", "difRxFFG", "difRyFFG", "difRzFFG", "difSxFFG", "difSyFFG", "difSzFFG"]
        cmds.textFieldGrp(self.widgets["baseTFG"], e=True, tx="")
        for field in fieldNames:
            cmds.floatFieldGrp(self.widgets[field], e=True, v1=0)
        cmds.floatFieldGrp(self.widgets["baseFrameFFG"], e=True, v1=0)
        cmds.text(self.widgets["doneText"], e=True, l="No Status/All Cleared. Select a base object!", bgc=(.5,.5,.5))

    # def restoreBase(self, *args):
    # 	"""restores the base obj to the text field"""

    # 	cmds.textFieldGrp(self.widgets["baseTFG"], e=True, tx=self.baseObj)
    # 	cmds.floatFieldGrp(self.widgets["baseFrameFFG"], e=True, v1=self.frame)

    def enableRange(self, *args):
        """toggles the frame range option on/off depending on what's selected in the range radio grp"""
        #get the value of the radio button grp
        sel = cmds.radioButtonGrp(self.widgets["timeRBG"], q=True, sl=True)

        if sel == 3:
            cmds.floatFieldGrp(self.widgets["rangeFFG"], e=True, en=True)
        else:
            cmds.floatFieldGrp(self.widgets["rangeFFG"], e=True, en=False)

    def getRange(self, *args):
        """this finds the frame range and returns the StartFrame and EndFrame"""
        #get time RBG
        sel = cmds.radioButtonGrp(self.widgets["timeRBG"], q=True, sl=True)
        #get start and end frames (or "all")
        if sel == 3:
            #get values from ffg's
            self.startF = cmds.floatFieldGrp(self.widgets["rangeFFG"], q=True, v1=True)
            self.endF = cmds.floatFieldGrp(self.widgets["rangeFFG"], q=True, v2=True)

        if sel==1:
            self.startF = []
            self.endF = []
        if sel==2:
            #capture values from time slider
            self.getSliderRange()

    def getSliderRange(self, *args):
        """gets framerange in current scene and returns start and end frames"""
        #get timeslider range start
        self.startF = cmds.playbackOptions(query=True, min=True)
        self.endF = cmds.playbackOptions(query=True, max=True)

def animShift(*args):
    thisShift = AnimShift()