from random import choice
line_number = 1
just_saw_newline = 0
current_level_of_nesting = 0
class Node:
    def __init__(self, n_type, value, nesting, children=None, leaf=None, error_node = 0, missing = 0):
        self.type = n_type
        self.value = value
        self.lno = line_number
        self.error = error_node
        self.missing = missing
        self.nesting = nesting
        if children:
            self.children = children
        else:
            self.children = [ ]

        self.leaf = leaf

    def set_parent(self, parent):
        self.parent = parent

    def get_parent(self):
        return self.parent

    def get_prevchild(self, parent):
        return self.parent.children[(self.parent.children.index(self.value)-1)]

    def set_error_node(self):
        self.error = 1

    def set_missing(self):
        self.missing = 1

    def get_missing(self):
        return self.missing

    def add_child(self, child):
        self.children.append(child)

    def remove_child(self, child):
        for i, o in enumerate(self.children):
            if o.value == child.value:
                del self.children[i]
                break

    def __repr__(self, level=0):
        ret = "	"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__repr__(level+1)
        return ret

class temp_node:
    def __init__(self, value, type):
        self.value = value
        self.type = type

selection = []
loop = []
eqoperator = ['EQUALS', 'RIGHT_ASSIGN', 'LEFT_ASSIGN', 'ADD_ASSIGN', 'SUB_ASSIGN', 'MUL_ASSIGN', 'DIV_ASSIGN', 'MOD_ASSIGN', 'AND_ASSIGN', 'XOR_ASSIGN', 'OR_ASSIGN', 'LE_OP', 'GE_OP', 'EQ_OP', 'NE_OP', 'GT_OP', 'LT_OP']
arithoperator = ['PLUS', 'MINUS', 'DIVIDES', 'TIMES', 'MODULUS', 'RIGHT_OP', 'LEFT_OP', 'INC_OP', 'DEC_OP']
booloperator = ['AMP', 'OR', 'AND_OP', 'OR_OP']
bracket = ['LPAREN', 'RPAREN', 'LFPAREN', 'RFPAREN', 'LSQUARE', 'RSQUARE']
token = ['ELLIPSIS', 'ALIGNAS', 'ALIGNOF', 'ATOMIC', 'COMPLEX', 'GENERIC', 'IMAGINARY', 'NORETURN', 'STATIC_ASSERT', 'THREAD_LOCAL', 'FUNC_NAME']
symbol = ['COMMA', 'COLON', 'SCOLON', 'DOT', 'TILDE', 'XOR', 'NOT', 'QMARK', 'PTR_OP']
ignore = ['NEWLINE']
selection=['if', 'else', 'switch', 'case']
loop=['while', 'do', 'for']
reserved = {'void': 'VOID', 'int': 'INT', 'float': 'FLOAT', 'bool': 'BOOL', 'char': 'CHAR', 'double': 'DOUBLE', 'else': 'ELSE', 'if': 'IF', 'while': 'WHILE', 'do': 'DO', 'for': 'FOR', 'auto': 'AUTO', 'break': 'BREAK', 'case': 'CASE', 'const': 'CONST', 'continue': 'CONTINUE', 'default': 'DEFAULT', 'goto': 'GOTO', 'enum': 'ENUM', 'extern': 'EXTERN', 'long': 'LONG', 'register': 'REGISTER', 'return': 'RETURN', 'short': 'SHORT', 'signed': 'SIGNED', 'sizeof': 'SIZEOF', 'static': 'STATIC', 'struct': 'STRUCT', 'typedef': 'TYPEDEF', 'switch': 'SWITCH', 'union': 'UNION', 'unsigned': 'UNSIGNED', 'volatile': 'VOLATILE'}
selection = {'if': 'IF', 'else': 'ELSE', 'switch': 'SWITCH', 'case': 'CASE'}
loop = {'for': 'FOR', 'while': 'WHILE', 'do': 'DO'}
tokens = ['VOID', 'INT', 'FLOAT', 'BOOL', 'CHAR', 'DOUBLE', 'ELSE', 'IF', 'WHILE', 'DO', 'FOR', 'AUTO', 'BREAK', 'CASE', 'CONST', 'CONTINUE', 'DEFAULT', 'GOTO', 'ENUM', 'EXTERN', 'LONG', 'REGISTER', 'RETURN', 'SHORT', 'SIGNED', 'SIZEOF', 'STATIC', 'STRUCT', 'TYPEDEF', 'SWITCH', 'UNION', 'UNSIGNED', 'VOLATILE', 'EQUALS', 'RIGHT_ASSIGN', 'LEFT_ASSIGN', 'ADD_ASSIGN', 'SUB_ASSIGN', 'MUL_ASSIGN', 'DIV_ASSIGN', 'MOD_ASSIGN', 'AND_ASSIGN', 'XOR_ASSIGN', 'OR_ASSIGN', 'LE_OP', 'GE_OP', 'EQ_OP', 'NE_OP', 'GT_OP', 'LT_OP', 'PLUS', 'MINUS', 'DIVIDES', 'TIMES', 'MODULUS', 'RIGHT_OP', 'LEFT_OP', 'INC_OP', 'DEC_OP', 'AMP', 'OR', 'AND_OP', 'OR_OP', 'LPAREN', 'RPAREN', 'LFPAREN', 'RFPAREN', 'LSQUARE', 'RSQUARE', 'ELLIPSIS', 'ALIGNAS', 'ALIGNOF', 'ATOMIC', 'COMPLEX', 'GENERIC', 'IMAGINARY', 'NORETURN', 'STATIC_ASSERT', 'THREAD_LOCAL', 'FUNC_NAME', 'COMMA', 'COLON', 'SCOLON', 'DOT', 'TILDE', 'XOR', 'NOT', 'QMARK', 'PTR_OP', 'NEWLINE', 'NUMBER', 'IDENTIFIER', 'STRING_LITERAL', 'I_CONSTANT', 'F_CONSTANT']

def t_NUMBER(t):
	r'\d+'
	t.type=reserved.get(t.value,'NUMBER')
	global current_level_of_nesting
	t.value = Node('NUMBER', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_EQ_OP(t):
	r'\=='
	t.type=reserved.get(t.value,'EQ_OP')
	global current_level_of_nesting
	t.value = Node('EQ_OP', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_MUL_ASSIGN(t):
	r'\*='
	t.type=reserved.get(t.value,'MUL_ASSIGN')
	global current_level_of_nesting
	t.value = Node('MUL_ASSIGN', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_NE_OP(t):
	r'\!='
	t.type=reserved.get(t.value,'NE_OP')
	global current_level_of_nesting
	t.value = Node('NE_OP', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_GE_OP(t):
	r'\>='
	t.type=reserved.get(t.value,'GE_OP')
	global current_level_of_nesting
	t.value = Node('GE_OP', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_LE_OP(t):
	r'\<='
	t.type=reserved.get(t.value,'LE_OP')
	global current_level_of_nesting
	t.value = Node('LE_OP', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_DOT(t):
	r'\.'
	t.type=reserved.get(t.value,'DOT')
	global current_level_of_nesting
	t.value = Node('DOT', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_PTR_OP(t):
	r'\->'
	t.type=reserved.get(t.value,'PTR_OP')
	global current_level_of_nesting
	t.value = Node('PTR_OP', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_IDENTIFIER(t):
	r'[a-zA-Z_][a-zA-Z0-9_]*'
	t.type=reserved.get(t.value,'IDENTIFIER')
	global current_level_of_nesting
	t.value = Node('IDENTIFIER', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_STRING_LITERAL(t):
	r'\"(\\.|[^"\\])*\"'
	t.type=reserved.get(t.value,'STRING_LITERAL')
	global current_level_of_nesting
	t.value = Node('STRING_LITERAL', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_I_CONSTANT(t):
	r'{(0[xX])}{[a-fA-F0-9]}+{(((u|U)(l|[a-zA-Z_]|ll|[a-zA-Z_][a-zA-Z_])?)|((l|[a-zA-Z_]|ll|[a-zA-Z_][a-zA-Z_])(u|U)?))}? | {[1-9]}{[0-9]}*{(((u|U)(l|[a-zA-Z_]|ll|[a-zA-Z_][a-zA-Z_])?)|((l|[a-zA-Z_]|ll|[a-zA-Z_][a-zA-Z_])(u|U)?))}? | "0"{[0-7]}*{(((u|U)(l|[a-zA-Z_]|ll|[a-zA-Z_][a-zA-Z_])?)|((l|[a-zA-Z_]|ll|[a-zA-Z_][a-zA-Z_])(u|U)?))}? | {(u|U|[a-zA-Z_])}?"\'"([^\'\\\n]|{(\\([\'"\?\\abfnrtv]|[0-7]{1,3}|x[a-fA-F0-9]+))})+"\'"'
	t.type=reserved.get(t.value,'I_CONSTANT')
	global current_level_of_nesting
	t.value = Node('I_CONSTANT', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_F_CONSTANT(t):
	r'{[0-9]}+{([Ee][+-]?{[0-9]}+)}{(f|F|l|[a-zA-Z_])}? | {[0-9]}*"."{[0-9]}+{([Ee][+-]?{[0-9]}+)}?{(f|F|l|[a-zA-Z_])}? | {[0-9]}+"."{([Ee][+-]?{[0-9]}+)}?{(f|F|l|[a-zA-Z_])}? | {(0[xX])}{[a-fA-F0-9]}+{([Pp][+-]?{[0-9]}+)}{(f|F|l|[a-zA-Z_])}? | {(0[xX])}{[a-fA-F0-9]}*"."{[a-fA-F0-9]}+{([Pp][+-]?{[0-9]}+)}{(f|F|l|[a-zA-Z_])}? | {(0[xX])}{[a-fA-F0-9]}+"."{([Pp][+-]?{[0-9]}+)}{(f|F|l|[a-zA-Z_])}?'
	t.type=reserved.get(t.value,'F_CONSTANT')
	global current_level_of_nesting
	t.value = Node('F_CONSTANT', t.value, current_level_of_nesting, leaf = 1)
	return t

def t_EQUALS(t):
	r'\='
	global current_level_of_nesting
	t.value = Node('eqoperator', '=', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_RIGHT_ASSIGN(t):
	r'\>>='
	global current_level_of_nesting
	t.value = Node('eqoperator', '>>=', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_LEFT_ASSIGN(t):
	r'\<<='
	global current_level_of_nesting
	t.value = Node('eqoperator', '<<=', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_ADD_ASSIGN(t):
	r'\+='
	global current_level_of_nesting
	t.value = Node('eqoperator', '+=', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_SUB_ASSIGN(t):
	r'\-='
	global current_level_of_nesting
	t.value = Node('eqoperator', '-=', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_DIV_ASSIGN(t):
	r'\/='
	global current_level_of_nesting
	t.value = Node('eqoperator', '/=', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_MOD_ASSIGN(t):
	r'\%='
	global current_level_of_nesting
	t.value = Node('eqoperator', '%=', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_AND_ASSIGN(t):
	r'\&='
	global current_level_of_nesting
	t.value = Node('eqoperator', '&=', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_XOR_ASSIGN(t):
	r'\^='
	global current_level_of_nesting
	t.value = Node('eqoperator', '^=', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_OR_ASSIGN(t):
	r'\|='
	global current_level_of_nesting
	t.value = Node('eqoperator', '|=', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_GT_OP(t):
	r'\>'
	global current_level_of_nesting
	t.value = Node('eqoperator', '>', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_LT_OP(t):
	r'\<'
	global current_level_of_nesting
	t.value = Node('eqoperator', '<', current_level_of_nesting, leaf = 1)
	t.typee = 'eqoperator'
	return t

def t_PLUS(t):
	r'\+'
	global current_level_of_nesting
	t.value = Node('arithoperator', '+', current_level_of_nesting, leaf = 1)
	t.typee = 'arithoperator'
	return t

def t_MINUS(t):
	r'\-'
	global current_level_of_nesting
	t.value = Node('arithoperator', '-', current_level_of_nesting, leaf = 1)
	t.typee = 'arithoperator'
	return t

def t_DIVIDES(t):
	r'\/'
	global current_level_of_nesting
	t.value = Node('arithoperator', '/', current_level_of_nesting, leaf = 1)
	t.typee = 'arithoperator'
	return t

def t_TIMES(t):
	r'\*'
	global current_level_of_nesting
	t.value = Node('arithoperator', '*', current_level_of_nesting, leaf = 1)
	t.typee = 'arithoperator'
	return t

def t_MODULUS(t):
	r'\%'
	global current_level_of_nesting
	t.value = Node('arithoperator', '%', current_level_of_nesting, leaf = 1)
	t.typee = 'arithoperator'
	return t

def t_RIGHT_OP(t):
	r'>>'
	global current_level_of_nesting
	t.value = Node('arithoperator', '>', current_level_of_nesting, leaf = 1)
	t.typee = 'arithoperator'
	return t

def t_LEFT_OP(t):
	r'<<'
	global current_level_of_nesting
	t.value = Node('arithoperator', '<', current_level_of_nesting, leaf = 1)
	t.typee = 'arithoperator'
	return t

def t_INC_OP(t):
	r'\++'
	global current_level_of_nesting
	t.value = Node('arithoperator', '++', current_level_of_nesting, leaf = 1)
	t.typee = 'arithoperator'
	return t

def t_DEC_OP(t):
	r'\--'
	global current_level_of_nesting
	t.value = Node('arithoperator', '--', current_level_of_nesting, leaf = 1)
	t.typee = 'arithoperator'
	return t

def t_AMP(t):
	r'\&'
	global current_level_of_nesting
	t.value = Node('booloperator', '&', current_level_of_nesting, leaf = 1)
	t.typee = 'booloperator'
	return t

def t_OR(t):
	r'\|'
	global current_level_of_nesting
	t.value = Node('booloperator', '|', current_level_of_nesting, leaf = 1)
	t.typee = 'booloperator'
	return t

def t_AND_OP(t):
	r'\&&'
	global current_level_of_nesting
	t.value = Node('booloperator', '&&', current_level_of_nesting, leaf = 1)
	t.typee = 'booloperator'
	return t

def t_OR_OP(t):
	r'\|\|'
	global current_level_of_nesting
	t.value = Node('booloperator', '|\|', current_level_of_nesting, leaf = 1)
	t.typee = 'booloperator'
	return t

def t_LPAREN(t):
	r'\('
	global current_level_of_nesting
	t.value = Node('bracket', '(', current_level_of_nesting, leaf = 1)
	t.typee = 'bracket'
	return t

def t_RPAREN(t):
	r'\)'
	global current_level_of_nesting
	t.value = Node('bracket', ')', current_level_of_nesting, leaf = 1)
	t.typee = 'bracket'
	return t

def t_LFPAREN(t):
	r'\{'
	global current_level_of_nesting
	t.value = Node('bracket', '{', current_level_of_nesting, leaf = 1)
	t.typee = 'bracket'
	return t

def t_RFPAREN(t):
	r'\}'
	global current_level_of_nesting
	t.value = Node('bracket', '}', current_level_of_nesting, leaf = 1)
	t.typee = 'bracket'
	return t

def t_LSQUARE(t):
	r'\['
	global current_level_of_nesting
	t.value = Node('bracket', '[', current_level_of_nesting, leaf = 1)
	t.typee = 'bracket'
	return t

def t_RSQUARE(t):
	r'\]'
	global current_level_of_nesting
	t.value = Node('bracket', ']', current_level_of_nesting, leaf = 1)
	t.typee = 'bracket'
	return t

def t_ELLIPSIS(t):
	r'\...'
	global current_level_of_nesting
	t.value = Node('token', '...', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_ALIGNAS(t):
	r'_Alignas'
	global current_level_of_nesting
	t.value = Node('token', 'Alignas', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_ALIGNOF(t):
	r'_Alignof'
	global current_level_of_nesting
	t.value = Node('token', 'Alignof', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_ATOMIC(t):
	r'_Atomic'
	global current_level_of_nesting
	t.value = Node('token', 'Atomic', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_COMPLEX(t):
	r'_Complex'
	global current_level_of_nesting
	t.value = Node('token', 'Complex', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_GENERIC(t):
	r'_Generic'
	global current_level_of_nesting
	t.value = Node('token', 'Generic', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_IMAGINARY(t):
	r'_Imaginary'
	global current_level_of_nesting
	t.value = Node('token', 'Imaginary', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_NORETURN(t):
	r'_Noreturn'
	global current_level_of_nesting
	t.value = Node('token', 'Noreturn', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_STATIC_ASSERT(t):
	r'_Static_assert'
	global current_level_of_nesting
	t.value = Node('token', 'Static_assert', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_THREAD_LOCAL(t):
	r'_Thread_local'
	global current_level_of_nesting
	t.value = Node('token', 'Thread_local', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_FUNC_NAME(t):
	r'__func__'
	global current_level_of_nesting
	t.value = Node('token', '_func__', current_level_of_nesting, leaf = 1)
	t.typee = 'token'
	return t

def t_COMMA(t):
	r'\,'
	global current_level_of_nesting
	t.value = Node('symbol', ',', current_level_of_nesting, leaf = 1)
	t.typee = 'symbol'
	return t

def t_COLON(t):
	r'\:'
	global current_level_of_nesting
	t.value = Node('symbol', ':', current_level_of_nesting, leaf = 1)
	t.typee = 'symbol'
	return t

def t_SCOLON(t):
	r'\;'
	global current_level_of_nesting
	t.value = Node('symbol', ';', current_level_of_nesting, leaf = 1)
	t.typee = 'symbol'
	return t

def t_TILDE(t):
	r'\~'
	global current_level_of_nesting
	t.value = Node('symbol', '~', current_level_of_nesting, leaf = 1)
	t.typee = 'symbol'
	return t

def t_XOR(t):
	r'\^'
	global current_level_of_nesting
	t.value = Node('symbol', '^', current_level_of_nesting, leaf = 1)
	t.typee = 'symbol'
	return t

def t_NOT(t):
	r'\!'
	global current_level_of_nesting
	t.value = Node('symbol', '!', current_level_of_nesting, leaf = 1)
	t.typee = 'symbol'
	return t

def t_QMARK(t):
	r'\?'
	global current_level_of_nesting
	t.value = Node('symbol', '?', current_level_of_nesting, leaf = 1)
	t.typee = 'symbol'
	return t

def t_NEWLINE(t):
	r'\n+'
	global current_level_of_nesting
	global line_number
	global just_saw_newline
	just_saw_newline = 1
	current_level_of_nesting = 0
	line_number += 1
	t.value = Node('ignore', 'n+', current_level_of_nesting, leaf = 1)
	pass

def p_start(t):
	'''start : translation_unit'''
	global line_number
	global current_level_of_nesting
	line_number = 1
	print("beginning yacc")
	t[0] = Node("start", "start", current_level_of_nesting, t[1:], leaf = 0)

def p_translation_unit(t):
	'''translation_unit : external_declaration
	| translation_unit external_declaration'''
	t[0] = Node("translation_unit", "translation_unit", current_level_of_nesting, t[1:], leaf = 0)

def p_external_declaration(t):
	'''external_declaration : function_definition
	| declaration'''
	t[0] = Node("external_declaration", "external_declaration", current_level_of_nesting, t[1:], leaf = 0)

def p_function_definition(t):
	'''function_definition : declaration_specifiers declarator declaration_list compound_statement
	| declaration_specifiers declarator compound_statement'''
	t[0] = Node("function_definition", "function_definition", current_level_of_nesting, t[1:], leaf = 0)

def p_declaration_list(t):
	'''declaration_list : declaration
	| declaration_list declaration'''
	t[0] = Node("declaration_list", "declaration_list", current_level_of_nesting, t[1:], leaf = 0)

def p_primary_expression(t):
	'''primary_expression : IDENTIFIER
	| constant
	| string
	| LPAREN expression RPAREN
	| generic_selection
	| NUMBER'''
	t[0] = Node("primary_expression", "primary_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_constant(t):
	'''constant : I_CONSTANT
	| F_CONSTANT'''
	t[0] = Node("constant", "constant", current_level_of_nesting, t[1:], leaf = 0)

def p_enumeration_constant(t):
	'''enumeration_constant : IDENTIFIER'''
	t[0] = Node("enumeration_constant", "enumeration_constant", current_level_of_nesting, t[1:], leaf = 0)

def p_string(t):
	'''string : STRING_LITERAL
	| FUNC_NAME'''
	t[0] = Node("string", "string", current_level_of_nesting, t[1:], leaf = 0)

def p_generic_selection(t):
	'''generic_selection : GENERIC LPAREN assignment_expression COMMA generic_assoc_list RPAREN'''
	t[0] = Node("generic_selection", "generic_selection", current_level_of_nesting, t[1:], leaf = 0)

def p_generic_assoc_list(t):
	'''generic_assoc_list : generic_association
	| generic_assoc_list COMMA generic_association'''
	t[0] = Node("generic_assoc_list", "generic_assoc_list", current_level_of_nesting, t[1:], leaf = 0)

def p_generic_association(t):
	'''generic_association : type_name COLON assignment_expression
	| DEFAULT COLON assignment_expression'''
	t[0] = Node("generic_association", "generic_association", current_level_of_nesting, t[1:], leaf = 0)

def p_postfix_expression(t):
	'''postfix_expression : primary_expression
	| postfix_expression RSQUARE expression LSQUARE
	| postfix_expression LPAREN RPAREN
	| postfix_expression LPAREN argument_expression_list RPAREN
	| postfix_expression DOT IDENTIFIER
	| postfix_expression PTR_OP IDENTIFIER
	| postfix_expression INC_OP
	| postfix_expression DEC_OP
	| LPAREN type_name RPAREN LFPAREN initializer_list RFPAREN LPAREN type_name RPAREN LFPAREN initializer_list COMMA RFPAREN'''
	t[0] = Node("postfix_expression", "postfix_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_argument_expression_list(t):
	'''argument_expression_list : assignment_expression
	| argument_expression_list COMMA assignment_expression'''
	t[0] = Node("argument_expression_list", "argument_expression_list", current_level_of_nesting, t[1:], leaf = 0)

def p_unary_expression(t):
	'''unary_expression : postfix_expression
	| INC_OP unary_expression
	| DEC_OP unary_expression
	| unary_oper cast_expression
	| SIZEOF unary_expression
	| SIZEOF LPAREN type_name RPAREN
	| ALIGNOF LPAREN type_name RPAREN'''
	t[0] = Node("unary_expression", "unary_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_unary_oper(t):
	'''unary_oper : AMP
	| TIMES
	| PLUS
	| MINUS
	| TILDE
	| NOT'''
	t[0] = Node("unary_oper", "unary_oper", current_level_of_nesting, t[1:], leaf = 0)

def p_cast_expression(t):
	'''cast_expression : unary_expression
	| LPAREN type_name RPAREN cast_expression'''
	t[0] = Node("cast_expression", "cast_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_multiplicative_expression(t):
	'''multiplicative_expression : cast_expression
	| multiplicative_expression TIMES cast_expression
	| multiplicative_expression DIVIDES cast_expression
	| multiplicative_expression MODULUS cast_expression'''
	t[0] = Node("multiplicative_expression", "multiplicative_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_additive_expression(t):
	'''additive_expression : multiplicative_expression
	| additive_expression PLUS multiplicative_expression
	| additive_expression MINUS multiplicative_expression'''
	t[0] = Node("additive_expression", "additive_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_shift_expression(t):
	'''shift_expression : additive_expression
	| shift_expression LEFT_OP additive_expression
	| shift_expression RIGHT_OP additive_expression'''
	t[0] = Node("shift_expression", "shift_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_relational_expression(t):
	'''relational_expression : shift_expression
	| relational_expression LT_OP shift_expression
	| relational_expression GT_OP shift_expression
	| relational_expression LE_OP shift_expression
	| relational_expression GE_OP shift_expression'''
	t[0] = Node("relational_expression", "relational_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_equality_expression(t):
	'''equality_expression : relational_expression
	| equality_expression EQ_OP relational_expression
	| equality_expression NE_OP relational_expression'''
	t[0] = Node("equality_expression", "equality_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_and_expression(t):
	'''and_expression : equality_expression
	| and_expression AMP equality_expression'''
	t[0] = Node("and_expression", "and_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_exclusive_or_expression(t):
	'''exclusive_or_expression : and_expression
	| exclusive_or_expression XOR and_expression'''
	t[0] = Node("exclusive_or_expression", "exclusive_or_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_inclusive_or_expression(t):
	'''inclusive_or_expression : exclusive_or_expression
	| inclusive_or_expression OR exclusive_or_expression'''
	t[0] = Node("inclusive_or_expression", "inclusive_or_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_logical_and_expression(t):
	'''logical_and_expression : inclusive_or_expression
	| logical_and_expression AND_OP inclusive_or_expression'''
	t[0] = Node("logical_and_expression", "logical_and_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_logical_or_expression(t):
	'''logical_or_expression : logical_and_expression
	| logical_or_expression OR_OP logical_and_expression'''
	t[0] = Node("logical_or_expression", "logical_or_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_conditional_expression(t):
	'''conditional_expression : logical_or_expression
	| logical_or_expression QMARK expression COLON conditional_expression'''
	t[0] = Node("conditional_expression", "conditional_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_assignment_expression(t):
	'''assignment_expression : conditional_expression
	| unary_expression assignment_oper assignment_expression'''
	t[0] = Node("assignment_expression", "assignment_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_assignment_oper(t):
	'''assignment_oper : EQUALS
	| MUL_ASSIGN
	| DIV_ASSIGN
	| MOD_ASSIGN
	| ADD_ASSIGN
	| SUB_ASSIGN
	| LEFT_ASSIGN
	| RIGHT_ASSIGN
	| AND_ASSIGN
	| XOR_ASSIGN
	| OR_ASSIGN'''
	t[0] = Node("assignment_oper", "assignment_oper", current_level_of_nesting, t[1:], leaf = 0)

def p_expression(t):
	'''expression : assignment_expression
	| expression COMMA assignment_expression'''
	t[0] = Node("expression", "expression", current_level_of_nesting, t[1:], leaf = 0)

def p_constant_expression(t):
	'''constant_expression : conditional_expression'''
	t[0] = Node("constant_expression", "constant_expression", current_level_of_nesting, t[1:], leaf = 0)

def p_declaration(t):
	'''declaration : declaration_specifiers SCOLON
	| declaration_specifiers init_declarator_list SCOLON
	| static_assert_declaration'''
	t[0] = Node("declaration", "declaration", current_level_of_nesting, t[1:], leaf = 0)

def p_declaration_specifiers(t):
	'''declaration_specifiers : storage_class_specifier declaration_specifiers
	| storage_class_specifier
	| type_specifier declaration_specifiers
	| type_specifier
	| type_qualifier declaration_specifiers
	| type_qualifier
	| function_specifier declaration_specifiers
	| function_specifier
	| alignment_specifier declaration_specifiers
	| alignment_specifier
	|'''
	t[0] = Node("declaration_specifiers", "declaration_specifiers", current_level_of_nesting, t[1:], leaf = 0)

def p_init_declarator_list(t):
	'''init_declarator_list : init_declarator
	| init_declarator_list COMMA init_declarator'''
	t[0] = Node("init_declarator_list", "init_declarator_list", current_level_of_nesting, t[1:], leaf = 0)

def p_init_declarator(t):
	'''init_declarator : declarator EQUALS initializer
	| declarator'''
	t[0] = Node("init_declarator", "init_declarator", current_level_of_nesting, t[1:], leaf = 0)

def p_storage_class_specifier(t):
	'''storage_class_specifier : TYPEDEF
	| EXTERN
	| STATIC
	| THREAD_LOCAL
	| AUTO
	| REGISTER'''
	t[0] = Node("storage_class_specifier", "storage_class_specifier", current_level_of_nesting, t[1:], leaf = 0)

def p_type_specifier(t):
	'''type_specifier : VOID
	| CHAR
	| SHORT
	| INT
	| LONG
	| FLOAT
	| DOUBLE
	| SIGNED
	| UNSIGNED
	| BOOL
	| COMPLEX
	| IMAGINARY
	| atomic_type_specifier
	| struct_or_union_specifier
	| enum_specifier'''
	t[0] = Node("type_specifier", "type_specifier", current_level_of_nesting, t[1:], leaf = 0)

def p_struct_or_union_specifier(t):
	'''struct_or_union_specifier : struct_or_union LFPAREN struct_declaration_list RFPAREN
	| struct_or_union IDENTIFIER LFPAREN struct_declaration_list RFPAREN
	| struct_or_union IDENTIFIER'''
	t[0] = Node("struct_or_union_specifier", "struct_or_union_specifier", current_level_of_nesting, t[1:], leaf = 0)

def p_struct_or_union(t):
	'''struct_or_union : STRUCT
	| UNION'''
	t[0] = Node("struct_or_union", "struct_or_union", current_level_of_nesting, t[1:], leaf = 0)

def p_struct_declaration_list(t):
	'''struct_declaration_list : struct_declaration
	| struct_declaration_list struct_declaration'''
	t[0] = Node("struct_declaration_list", "struct_declaration_list", current_level_of_nesting, t[1:], leaf = 0)

def p_struct_declaration(t):
	'''struct_declaration : specifier_qualifier_list SCOLON
	| specifier_qualifier_list struct_declarator_list SCOLON
	| static_assert_declaration'''
	t[0] = Node("struct_declaration", "struct_declaration", current_level_of_nesting, t[1:], leaf = 0)

def p_specifier_qualifier_list(t):
	'''specifier_qualifier_list : type_specifier specifier_qualifier_list
	| type_specifier
	| type_qualifier specifier_qualifier_list
	| type_qualifier'''
	t[0] = Node("specifier_qualifier_list", "specifier_qualifier_list", current_level_of_nesting, t[1:], leaf = 0)

def p_struct_declarator_list(t):
	'''struct_declarator_list : struct_declarator
	| struct_declarator_list COMMA struct_declarator'''
	t[0] = Node("struct_declarator_list", "struct_declarator_list", current_level_of_nesting, t[1:], leaf = 0)

def p_struct_declarator(t):
	'''struct_declarator : COLON constant_expression
	| declarator COLON constant_expression
	| declarator'''
	t[0] = Node("struct_declarator", "struct_declarator", current_level_of_nesting, t[1:], leaf = 0)

def p_enum_specifier(t):
	'''enum_specifier : ENUM LFPAREN enumerator_list RFPAREN
	| ENUM LFPAREN enumerator_list COMMA RFPAREN
	| ENUM IDENTIFIER LFPAREN enumerator_list RFPAREN
	| ENUM IDENTIFIER LFPAREN enumerator_list COMMA RFPAREN
	| ENUM IDENTIFIER'''
	t[0] = Node("enum_specifier", "enum_specifier", current_level_of_nesting, t[1:], leaf = 0)

def p_enumerator_list(t):
	'''enumerator_list : enumerator
	| enumerator_list COMMA enumerator'''
	t[0] = Node("enumerator_list", "enumerator_list", current_level_of_nesting, t[1:], leaf = 0)

def p_enumerator(t):
	'''enumerator : enumeration_constant EQUALS constant_expression
	| enumeration_constant'''
	t[0] = Node("enumerator", "enumerator", current_level_of_nesting, t[1:], leaf = 0)

def p_atomic_type_specifier(t):
	'''atomic_type_specifier : ATOMIC LPAREN type_name RPAREN'''
	t[0] = Node("atomic_type_specifier", "atomic_type_specifier", current_level_of_nesting, t[1:], leaf = 0)

def p_type_qualifier(t):
	'''type_qualifier : CONST
	| VOLATILE
	| ATOMIC'''
	t[0] = Node("type_qualifier", "type_qualifier", current_level_of_nesting, t[1:], leaf = 0)

def p_function_specifier(t):
	'''function_specifier : NORETURN'''
	t[0] = Node("function_specifier", "function_specifier", current_level_of_nesting, t[1:], leaf = 0)

def p_alignment_specifier(t):
	'''alignment_specifier : ALIGNAS LPAREN type_name RPAREN
	| ALIGNAS LPAREN constant_expression RPAREN'''
	t[0] = Node("alignment_specifier", "alignment_specifier", current_level_of_nesting, t[1:], leaf = 0)

def p_declarator(t):
	'''declarator : pointer direct_declarator
	| direct_declarator'''
	t[0] = Node("declarator", "declarator", current_level_of_nesting, t[1:], leaf = 0)

def p_direct_declarator(t):
	'''direct_declarator : IDENTIFIER
	| IDENTIFIER LSQUARE NUMBER RSQUARE
	| LPAREN declarator RPAREN
	| direct_declarator RSQUARE LSQUARE
	| direct_declarator RSQUARE TIMES LSQUARE
	| direct_declarator RSQUARE STATIC type_qualifier_list assignment_expression LSQUARE
	| direct_declarator RSQUARE STATIC assignment_expression LSQUARE
	| direct_declarator RSQUARE type_qualifier_list TIMES LSQUARE
	| direct_declarator RSQUARE type_qualifier_list STATIC assignment_expression LSQUARE
	| direct_declarator RSQUARE type_qualifier_list assignment_expression LSQUARE
	| direct_declarator RSQUARE type_qualifier_list LSQUARE
	| direct_declarator RSQUARE assignment_expression LSQUARE
	| direct_declarator LPAREN parameter_type_list RPAREN
	| direct_declarator LPAREN RPAREN
	| direct_declarator LPAREN identifier_list RPAREN'''
	t[0] = Node("direct_declarator", "direct_declarator", current_level_of_nesting, t[1:], leaf = 0)

def p_pointer(t):
	'''pointer : TIMES type_qualifier_list pointer
	| TIMES type_qualifier_list
	| TIMES pointer
	| TIMES'''
	t[0] = Node("pointer", "pointer", current_level_of_nesting, t[1:], leaf = 0)

def p_type_qualifier_list(t):
	'''type_qualifier_list : type_qualifier
	| type_qualifier_list type_qualifier'''
	t[0] = Node("type_qualifier_list", "type_qualifier_list", current_level_of_nesting, t[1:], leaf = 0)

def p_parameter_type_list(t):
	'''parameter_type_list : parameter_list COMMA ELLIPSIS
	| parameter_list'''
	t[0] = Node("parameter_type_list", "parameter_type_list", current_level_of_nesting, t[1:], leaf = 0)

def p_parameter_list(t):
	'''parameter_list : parameter_declaration
	| parameter_list COMMA parameter_declaration'''
	t[0] = Node("parameter_list", "parameter_list", current_level_of_nesting, t[1:], leaf = 0)

def p_parameter_declaration(t):
	'''parameter_declaration : declaration_specifiers declarator
	| declaration_specifiers abstract_declarator
	| declaration_specifiers'''
	t[0] = Node("parameter_declaration", "parameter_declaration", current_level_of_nesting, t[1:], leaf = 0)

def p_identifier_list(t):
	'''identifier_list : IDENTIFIER
	| identifier_list COMMA IDENTIFIER'''
	t[0] = Node("identifier_list", "identifier_list", current_level_of_nesting, t[1:], leaf = 0)

def p_type_name(t):
	'''type_name : specifier_qualifier_list abstract_declarator
	| specifier_qualifier_list'''
	t[0] = Node("type_name", "type_name", current_level_of_nesting, t[1:], leaf = 0)

def p_abstract_declarator(t):
	'''abstract_declarator : pointer direct_abstract_declarator
	| pointer
	| direct_abstract_declarator'''
	t[0] = Node("abstract_declarator", "abstract_declarator", current_level_of_nesting, t[1:], leaf = 0)

def p_direct_abstract_declarator(t):
	'''direct_abstract_declarator : LPAREN abstract_declarator RPAREN
	| RSQUARE LSQUARE
	| RSQUARE TIMES LSQUARE
	| RSQUARE STATIC type_qualifier_list assignment_expression LSQUARE
	| RSQUARE STATIC assignment_expression LSQUARE
	| RSQUARE type_qualifier_list STATIC assignment_expression LSQUARE
	| RSQUARE type_qualifier_list assignment_expression LSQUARE
	| RSQUARE type_qualifier_list LSQUARE
	| RSQUARE assignment_expression LSQUARE
	| direct_abstract_declarator RSQUARE LSQUARE
	| direct_abstract_declarator RSQUARE TIMES LSQUARE
	| direct_abstract_declarator RSQUARE STATIC type_qualifier_list assignment_expression LSQUARE
	| direct_abstract_declarator RSQUARE STATIC assignment_expression LSQUARE
	| direct_abstract_declarator RSQUARE type_qualifier_list assignment_expression LSQUARE
	| direct_abstract_declarator RSQUARE type_qualifier_list STATIC assignment_expression LSQUARE
	| direct_abstract_declarator RSQUARE type_qualifier_list LSQUARE
	| direct_abstract_declarator RSQUARE assignment_expression LSQUARE
	| LPAREN RPAREN
	| LPAREN parameter_type_list RPAREN
	| direct_abstract_declarator LPAREN RPAREN
	| direct_abstract_declarator LPAREN parameter_type_list RPAREN'''
	t[0] = Node("direct_abstract_declarator", "direct_abstract_declarator", current_level_of_nesting, t[1:], leaf = 0)

def p_initializer(t):
	'''initializer : LFPAREN initializer_list RFPAREN
	| LFPAREN initializer_list COMMA RFPAREN
	| assignment_expression'''
	t[0] = Node("initializer", "initializer", current_level_of_nesting, t[1:], leaf = 0)

def p_initializer_list(t):
	'''initializer_list : designation initializer
	| initializer
	| initializer_list COMMA designation initializer
	| initializer_list COMMA initializer'''
	t[0] = Node("initializer_list", "initializer_list", current_level_of_nesting, t[1:], leaf = 0)

def p_designation(t):
	'''designation : designator_list EQUALS'''
	t[0] = Node("designation", "designation", current_level_of_nesting, t[1:], leaf = 0)

def p_designator_list(t):
	'''designator_list : designator
	| designator_list designator'''
	t[0] = Node("designator_list", "designator_list", current_level_of_nesting, t[1:], leaf = 0)

def p_designator(t):
	'''designator : RSQUARE constant_expression LSQUARE'''
	t[0] = Node("designator", "designator", current_level_of_nesting, t[1:], leaf = 0)

def p_static_assert_declaration(t):
	'''static_assert_declaration : STATIC_ASSERT LPAREN constant_expression COMMA STRING_LITERAL RPAREN SCOLON'''
	t[0] = Node("static_assert_declaration", "static_assert_declaration", current_level_of_nesting, t[1:], leaf = 0)

def p_statement(t):
	'''statement : labeled_statement
	| compound_statement
	| expression_statement
	| selection_statement
	| iteration_statement
	| jump_statement'''
	t[0] = Node("statement", "statement", current_level_of_nesting, t[1:], leaf = 0)

def p_labeled_statement(t):
	'''labeled_statement : IDENTIFIER COLON statement
	| CASE constant_expression COLON statement
	| DEFAULT COLON statement'''
	t[0] = Node("labeled_statement", "labeled_statement", current_level_of_nesting, t[1:], leaf = 0)

def p_compound_statement(t):
	'''compound_statement : LFPAREN RFPAREN
	| LFPAREN  block_item_list RFPAREN'''
	t[0] = Node("compound_statement", "compound_statement", current_level_of_nesting, t[1:], leaf = 0)

def p_block_item_list(t):
	'''block_item_list : block_item
	| block_item_list block_item'''
	t[0] = Node("block_item_list", "block_item_list", current_level_of_nesting, t[1:], leaf = 0)

def p_block_item(t):
	'''block_item : declaration
	| statement'''
	t[0] = Node("block_item", "block_item", current_level_of_nesting, t[1:], leaf = 0)

def p_expression_statement(t):
	'''expression_statement : SCOLON
	| expression SCOLON'''
	t[0] = Node("expression_statement", "expression_statement", current_level_of_nesting, t[1:], leaf = 0)

def p_selection_statement(t):
	'''selection_statement : IF LPAREN expression RPAREN statement ELSE statement
	| IF LPAREN expression RPAREN statement
	| SWITCH LPAREN expression RPAREN statement'''
	t[0] = Node("selection_statement", "selection_statement", current_level_of_nesting, t[1:], leaf = 0)

def p_iteration_statement(t):
	'''iteration_statement : WHILE LPAREN expression RPAREN statement
	| DO statement WHILE LPAREN expression RPAREN SCOLON
	| FOR LPAREN expression_statement expression_statement RPAREN statement
	| FOR LPAREN expression_statement expression_statement expression RPAREN statement
	| FOR LPAREN declaration expression_statement RPAREN statement
	| FOR LPAREN declaration expression_statement expression RPAREN statement'''
	t[0] = Node("iteration_statement", "iteration_statement", current_level_of_nesting, t[1:], leaf = 0)

def p_jump_statement(t):
	'''jump_statement : GOTO IDENTIFIER SCOLON
	| CONTINUE SCOLON
	| BREAK SCOLON
	| RETURN SCOLON
	| RETURN expression SCOLON'''
	t[0] = Node("jump_statement", "jump_statement", current_level_of_nesting, t[1:], leaf = 0)

# Ignored characters
t_ignore = " "

def t_TAB(t):
    r'\t'
    global just_saw_newline
    global current_level_of_nesting
    if just_saw_newline:
        current_level_of_nesting = 1
        just_saw_newline = 0
    else:
        current_level_of_nesting += 1

    pass

def find_column(input, token):
    line_start = input.rfind('\n', 0, token.lexpos) + 1
    return (token.lexpos - line_start) + 1

def p_empty(p):
    'empty :'
    pass

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

def p_error(t):
    print("Syntax error at '%s'" % t.value)

import ply.lex as lex
lexer = lex.lex()

import ply.yacc as yacc
import random
yacc.yacc()

start= 'start'

data = open('programs/c/teacher_programs/input_programs/check_odd.c',"r").read()

#root = yacc.parse(data)
number=0

def printYield(root, reqpos, type):
    # Stack to store all the nodes
    # of tree
    s1 = []
    global number
    number=number+1
    global line_number
    #print("Global Line Number: " + type + " " + str(line_number))
    # Stack to store all the
    # leaf nodes
    s2 = []
    message=""
    # Push the root node
    s1.append(root)
    prev = root
    n=0
    while len(s1) != 0:
        curr = s1.pop()

        # If current node has a left child
        # push it onto the first stack
        for child in curr.children:
            s1.append(child)
            child.set_parent(curr)

        if curr.leaf:
            n+=1
            if n in reqpos:
                if curr.value == "n+" or 'NAME' in curr.type or 'NUMBER' in curr.type or 'IDENTIFIER' in curr.type:
                        #print("LOG: a number/identifier")
                        reqpos.remove(n)
                        reqpos.append(n+1)
                        s2.append(curr)
                        continue

            if type == "remove" and n in reqpos:
                #print("LOG: inside remove")
                # curr.get_parent().remove_child(curr)
                curr.set_missing()
                reqpos.remove(n)
                message=message + "Line no. " + str(curr.lno) + ": " + curr.value + " missing\n"
                print("LOG: inside remove message " + "Line no. " + str(curr.lno) + ": " + curr.value + " missing")

            elif type == "remove" and n not in reqpos:
                #print("LOG: remove and n not in reqpos")
                s2.append(curr)

            elif curr.get_missing() == 1:
                s2.append(curr)

            elif type == "add":
                #print("LOG: inside add")
                s2.append(curr)
                if n in reqpos:

                    if curr.type=="bracket" or curr.type=="symbol":
                        print("LOG: inside add, bracket/sym")
                        temp=curr
                    if(random.random()>0.5):
                        temp=curr
                    else:
                        reqpos.remove(n)
                        valid_to_add = arithoperator
                        #valid_to_add.extend(booloperator)
                        valid_to_add.extend(symbol)
                        valid_to_add.extend(bracket)
                        try:
                            valid_to_add.remove("SCOLON")
                            valid_to_add.remove("SEMI")
                        except:
                            pass
                        tok = choice(valid_to_add)
                        if not tok in list(reserved.values()):
                            #temp = Node(tok, tok.lower(), current_level_of_nesting, leaf = 1, error_node = 1)

                            func_name = "t_" + tok
                            fake_t = temp_node("dummy", ")")
                            temp = eval(func_name + "(fake_t)")
                            temp = temp.value
                            print("LOG: inside add ,not reserved, temp value is ", temp.value)
                    temp.set_error_node()
                    curr.get_parent().add_child(temp)
                    s2.append(temp)
                    message=message + "Line no. " + str(curr.lno) + ": Unknown " + temp.value + " found.\n"
                    print("LOG: inside add, message" + "Line no. " + str(curr.lno) + ": Unknown " + temp.value + " found.")
            elif type == "replace":
                print("LOG: inside replace")
                if n in reqpos:
                    reqpos.remove(n)
                    # tok = choice(tokens)
                    if curr.type == "bracket":
                        print("LOG: inside replace, bracket")
                        while 1:
                            tok = choice(bracket)
                            func_name = "t_" + tok
                            fake_t = temp_node("dummy", ")")
                            temp = eval(func_name + "(fake_t)")
                            temp = temp.value
                            if temp.value != curr.value:
                                break
                    if curr.type == "reserved":
                        print("LOG: inside replace, reserved")
                        while 1:
                            lper=["".join(perm) for perm in itertools.permutations(curr.value)]
                            tok = choice(lper)
                            func_name = "t_" + tok
                            fake_t = temp_node("dummy", ")")
                            temp = eval(func_name + "(fake_t)")
                            temp = temp.value
                            if temp.value != curr.value:
                                break
                    elif curr.type == "arithoperator":
                        print("LOG: inside replace, arithop")
                        while 1:
                            tok = choice(symbol)
                            func_name = "t_" + tok
                            fake_t = temp_node("dummy", ")")
                            temp = eval(func_name + "(fake_t)")
                            temp = temp.value
                            if temp.value != curr.value:
                                break
                    elif curr.type == "eqoperator":
                        print("LOG: inside replace, eqop")
                        while 1:
                            tok = choice(symbol)
                            func_name = "t_" + tok
                            fake_t = temp_node("dummy", ")")
                            temp = eval(func_name + "(fake_t)")
                            temp = temp.value
                            if temp.value != curr.value:
                                break
                    elif curr.type == "loop":
                        print("LOG: inside replace, loop")
                        while 1:
                            tok = choice(loop)
                            func_name = "t_" + tok
                            fake_t = temp_node("dummy", ")")
                            temp = eval(func_name + "(fake_t)")
                            temp = temp.value
                            if temp.value != curr.value:
                                break
                    elif curr.type == "selection":
                        print("LOG: inside replace, selection")
                        while 1:
                            tok = choice(selection)
                            func_name = "t_" + tok
                            fake_t = temp_node("dummy", ")")
                            temp = eval(func_name + "(fake_t)")
                            temp = temp.value
                            if temp.value != curr.value:
                                break
                    elif curr.type == "symbol":
                        print("LOG: inside replace, symbol")
                        while 1:
                            tok = choice(symbol)
                            func_name = "t_" + tok
                            fake_t = temp_node("dummy", ")")
                            temp = eval(func_name + "(fake_t)")
                            temp = temp.value
                            if temp.value != curr.value:
                                break

                    else:
                        print("LOG: inside replace, else")
                        newl = bracket
                        newl.extend(arithoperator)
                        newl.extend(symbol)
                        newl.extend(booloperator)
                        tok = choice(newl)
                        func_name = "t_" + tok
                        fake_t = temp_node("dummy", ")")
                        temp = eval(func_name + "(fake_t)")
                        temp = temp.value
                    temp.set_error_node()
                    curr.set_missing()
                    curr.get_parent().remove_child(curr)
                    curr.get_parent().add_child(temp)
                    s2.append(temp)
                    message=message +"Line no. " + str(curr.lno) + ": Unknown " + temp.value + " found.\n"
                    print("LOG: inside replace, message" + "Line no. " + str(curr.lno) + ": Unknown " + temp.value + " found")
                    message=message +"Line no. " + str(curr.lno) + ": " + curr.value + " missing\n"
                    print("LOG: inside replace, message" + "Line no. " + str(curr.lno) + ": " + curr.value + " missing")

                else:
                    s2.append(curr)

    # Print all the leaf nodes
    level = 0
    code = ""
    code_error_colors = ""
    line_no = 0
    time_for_tabs = 0
    while len(s2) != 0:
        val = s2.pop()
        if val.lno > line_no:
            line_no = val.lno
            code += "\n"
            code_error_colors += "\n"
            time_for_tabs = 1
        if time_for_tabs:
            for i in range(0, val.nesting):
                code += "\t"
                code_error_colors += "\t"
            time_for_tabs = 0
        if val.value == "n+":
            time_for_tabs = 1
        if val.get_missing() == 1:
            code_error_colors = code_error_colors + ' <span style="color:red">' + val.value + '</span> '
        else:
            if val.error == 0:
                code_error_colors = code_error_colors + "" + val.value + " "
            else:
                code_error_colors = code_error_colors + ' <span style="color:red">' + val.value + '</span> '
            code = code + "" + val.value + " "
    code = code[1:]
    code_error_colors = code_error_colors[1:]
    return code, code_error_colors, message, root

def getPgmLen(root):
    s1 = []
    s2 = []
    s1.append(root)
    while len(s1) != 0:
        curr = s1.pop()
        for child in curr.children:
            s1.append(child)

        if curr.leaf:
            s2.append(curr)

    return len(s2)

#### now we will try to introduce errors in the above syntax tree
newroot = yacc.parse(data)
pgmLen = getPgmLen(newroot)
percstring= '30'
percint=int(percstring)
error_len =  percint / 100 * pgmLen
#print("error_len" + str(error_len))
pgms =  5
directory= 'programs/c/teacher_programs/output_programs/'

fname = 'check_odd.c'.split(".")[0]
extension = 'check_odd.c'.split(".")[1]

error_val= int(error_len/3)
#n_add_errors = 1
#n_remove_errors = 3
#n_replace_errors = 1

n_add_errors = int(error_val/3)
n_remove_errors = int(error_val/3)
n_replace_errors = int(error_val/3)
if(n_add_errors < 1):
    n_add_errors=1
if(n_remove_errors < 1):
    n_remove_errors=1
if(n_replace_errors < 1):
    n_replace_errors=1

error_dict = {"remove": n_remove_errors, "replace" : n_replace_errors, "add" : n_add_errors}
for i in range(0,pgms):
    newroot = yacc.parse(data)
    pgmLen = getPgmLen(newroot)
    positions = [i for i in range(1,pgmLen-2)]
    message = ""
    pgm = ""
    for key in error_dict.keys():
        reqpos = []
        for j in range(0,error_dict[key]):
            c = choice(positions)
            reqpos.append(c)
            positions.remove(c)
        pgm, pgm_errors_marked, message1, newroot = printYield(newroot, reqpos, key)
        message += message1
    pgm = pgm.replace("n+", "")
#    pgm_errors_marked = pgm_errors_marked.replace("n+","<br/>")
    pgm_errors_marked = pgm_errors_marked.replace("\n","<br/>")
    pgm_errors_marked = pgm_errors_marked.replace("\t", "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp")
    error_list = message.split("\n")
    sorted_list = []
    sorted_message =""
    for line in error_list:
        thisline =[]
        linenum = line.split(":")
        if len(linenum )>=2:
            error_text = line[line.find(':')+1:]
            linenum = linenum[0].split(".")
            if len(linenum)>=2:
                linenum = linenum[1]
                thisline.append(int(linenum))
                thisline.append( error_text)
                sorted_list.append(thisline)
    sorted_list.sort(key = lambda x: x[0])
    for e in sorted_list :
        sorted_message += "Line no. "+str(e[0])+" : "+e[1]+"\n"

    f = open(directory + fname + "_" + str(i) + "." + extension , "w")
    f_err_cols = open(directory + fname + "_" + str(i) +"_errors_marked" + "." + extension , "w")
    fe=open(directory + "errors/" + fname + "_" + str(i) + "_error." + extension , "w")
    fe.write(sorted_message)
    fe.close()
    f.write(pgm)
    f_err_cols.write(pgm_errors_marked)
    f.close()
    f_err_cols.close()


__author__ = 'Shade390'
import traceback

from flask import Flask, redirect, render_template, session, g, current_app as app, url_for

import sqlite3
from tools.pictures import get_user_profile_pic, get_profile_pic_path

def home_page(username, db):
    posts = []
    try:
        c = db.cursor()
        d= db.cursor()
        t = (username, username, username,)
        c.execute('SELECT DISTINCT postTitle, user, postText, p.postid  \
                    FROM Posts p \
                    LEFT JOIN postTarget pt on p.postid = pt.postid \
                    OR p.user = ? \
                    WHERE (cid IN(SELECT cid From circle_members WHERE user=?) OR p.user = ?)', t)
        for row in c.fetchall():
            pictures = []
            #search for pictures based on postid
            t= (row[3],)
            d.execute('SELECT owner, path From pictures pic INNER JOIN postpictures post on pic.picid=post.picid \
            WHERE post.postid=?',t)
            for stuff in d.fetchall():
                pic= "/images/" + stuff[0] +"/"+ stuff[1]
                pictures.append(pic)
            profileId = get_user_profile_pic(row[1])
            profile_path = get_profile_pic_path(profileId)
            post = (row[0], row[1], row[2], pictures, profile_path)
            posts.append(post)
        posts.reverse()
        return render_template('posts_home.html', posts=posts)
    except sqlite3.OperationalError:
        traceback.print_exc()
    return render_template('posts_home.html', posts=posts)


# I started by adapting from example on page 362 the of book "Cambridge International AS & A-level Computer Science" (Langfield & Dudell)
# However, the code from the book is so wrong that the code below bears almost no resemblance to the original
# It is far from complete as it doesn't deal with collisions
# Requires Python 3.6

# I don't think this approach is widely used these days. It would have been used more in the 70s and 80s when it was
# not possible to load large files entirely into RAM.

# Python has a module called shelve which achieves similar results, i.e. reading/writing data based on a key,
# just like working with a dictionary. However, shelve has the same serious security issues as the 'pickle' - see
# 'CIE sequential file.py' for info about that

import struct
import hashlib

class CarRecord:
    registration_size = 8
    record_size = 12
    string_encoding = 'utf-8'

    def __init__(self, registration, engine_size):
        self.registration = registration    # using this as key field
        self.engine_size = engine_size

        if len(self.registration) > CarRecord.registration_size:
            raise Exception

    def __str__(self):
        return f'{self.registration}     {self.engine_size}'     # f-strings require Python 3.6

    def serialize(self):
        if len(self.registration) > CarRecord.registration_size:
            raise Exception

        reg_encoded = bytes(f'{self.registration:8}', CarRecord.string_encoding)
        return struct.pack('8si', reg_encoded, self.engine_size)

    def deserialize(byte_data):
        data = struct.unpack("8si", byte_data)
        reg = data[0].decode(CarRecord.string_encoding)
        engine = data[1]
        return CarRecord(reg, engine)

    def __hash__(self):
        # I originally used Python's built-in hash but it returns different results on each run of the program
        # for security reasons - see https://stackoverflow.com/questions/27522626/hash-function-in-python-3-3-returns-different-results-between-sessions
        reg_utf8 = self.registration.encode(CarRecord.string_encoding)
        return int(hashlib.sha256(reg_utf8).hexdigest(), 16)

    def __eq__(self, other):
        return self.registration == other.registration and self.engine_size == other.engine_size

filename = 'cars_random.dat'
file_size = 2**10   # 1KiB
num_slots = file_size // CarRecord.record_size

def create_empty_file():
    print(f"Generating empty file of size: {file_size} bytes")
    car_file = open(filename, 'wb')  # open file for binary write
    car_file.write(bytearray(file_size))
    car_file.close()

def write_to_file(data):
    if len(data) == 0:
        return

    print(f"Begin writing - file size: {file_size}, record length {CarRecord.record_size}, num_slots: {num_slots}")

    with open (filename, 'rb+') as car_file:    # open file for binary read and write
        for car in data:
            slot = hash(car) % num_slots
            address = slot * CarRecord.record_size

            serialized = car.serialize()
            assert (len(serialized) == CarRecord.record_size)

            print(f'Writing record to slot {slot}, address {address}')
            car_file.seek(address)
            # TO DO: check for existing record and collision
            car_file.write(serialized)

def verify_file(data):
    with open (filename,'rb') as car_file: # open file for binary read
        for car in data:
            slot = hash(car) % num_slots
            address = slot * CarRecord.record_size
            car_file.seek(address)
            file_data = car_file.read(CarRecord.record_size)
            file_car = CarRecord.deserialize(file_data)
            print(f"Loaded: {file_car}, equal?: {car == file_car}")

    # file is closed automatically as we opened it using 'with'
    return data

###################

cars = [ CarRecord("HU17 IOP", 1400), CarRecord("NH52 EQM", 2000), CarRecord("IK08 DAK", 1000) ]

create_empty_file()
write_to_file(cars)
verify_file(cars)


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def mergeKLists(self, lists) -> ListNode:
        # 分治法
        l = len(lists)

        def merge(l1, l2):
            if not l1: return l2
            if not l2: return l1

            if l1.val <= l2.val:
                l1.next = merge(l1.next, l2)
                return l1
            else:
                l2.next = merge(l1, l2.next)
                return l2

        if l == 1: return lists[0]
        if l == 2: return merge(lists[0], lists[1])
        if l > 2:
            mid = l // 2
            left = self.mergeKLists(lists[:mid])
            right = self.mergeKLists(lists[mid:])
            return merge(left, right)

23. 合并K个排序链表.py

23. 合并K个排序链表.py


import sys

if __name__ == "__main__":
    N = int(sys.stdin.readline().rstrip())

    for i in range(N):
        num = int(sys.stdin.readline().rstrip())
        temp = num
        print(num)

        while temp >= 100:
            strNum = str(temp)
            temp = int(strNum[:-1]) - int(strNum[-1])
            print(temp)

        if (temp % 11 == 0):
            print("The number {} is divisible by 11.".format(num))
        else:
            print("The number {} is not divisible by 11.".format(num))
        print()


import math
import os
import time
import datetime
import pandas as pd
import numpy as np

from settings import data_root, output_folder, station_angle, station_dist

def load_data(file_names):

    if type(file_names) is not list:
        file_names = [file_names]
    df = None
    for file in file_names:
        temp_df = pd.read_csv(os.path.join(data_root, file))
        if df is None:
            df = temp_df
        else:
            df.append(temp_df)
    return df

def utc2local(utc_time: str):
    '''

    '''
    timeArray = time.strptime(utc_time, "%Y-%m-%d %H:%M:%S")
    timestamp = time.mktime(timeArray)
    timestamp += 28800
    local_time = time.localtime(timestamp)
    local_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)

    return local_time

def cal_dis(latitude1, longitude1,latitude2, longitude2):

    latitude1 = (math.pi/180)*latitude1
    latitude2 = (math.pi/180)*latitude2
    longitude1 = (math.pi/180)*longitude1
    longitude2= (math.pi/180)*longitude2

    R = 6378.1
    d =  math.acos(math.sin(latitude1)*math.sin(latitude2)+\
         math.cos(latitude1)*math.cos(latitude2)*math.cos(longitude2-longitude1))*R
    return d  # unit: km

def get_season(date: str):
    '''
    required date formate: 2018-11-11
    only get season in 2017 & 2018 by China's traditional Solar Terms
    '''
    date = date.split('-')
    year = int(date[0])
    month = int(date[1])
    day = int(date[2])

    if month in [12, 1]:
        return 'winter'
    elif month in [3, 4]:
        return 'spring'
    elif month in [6, 7]:
        return 'summer'
    elif month in [9, 10]:
        return 'autumn'

    if year == 2017:
        if month == 2:
            return 'winter' if day < 3 else 'spring'
        elif month == 5:
            return 'spring' if day < 5 else 'summer'
        elif month == 8:
            return 'summer' if day < 7 else 'autumn'
        elif month == 11:
            return 'autumn' if day < 7 else 'winter'
    elif year == 2018:
        if month == 2:
            return 'winter' if day < 4 else 'spring'
        elif month == 5:
            return 'spring' if day < 5 else 'summer'
        elif month == 8:
            return 'summer' if day < 7 else 'autumn'
        elif month == 11:
            return 'autumn' if day < 7 else 'winter'
    return None

def get_solar_term(date: str, periodicity=False):
    '''
    date format: 2018-11-11
    mysterious formula: [Y*D+C]-L
    using idea of solar term to separate date to 24 parts, get label from 0 - 23
    using math.sin enable periodicity

    temperature rising:       2 --> 14    大暑最热 sin 最高点
    temperature dropping:     15 --> 1    大寒最冷 sin 最低点
    shift 7 units: 7->0, 24->7,
    '''
    solar_term = [
                    ["小寒", "大寒"],  # 1月        0  1  2
                    ["立春", "雨水"],  # 2月        2  3  4
                    ["惊蛰", "春分"],  # 3月        4  5  6
                    ["清明", "谷雨"],  # 4月        6  7  8
                    ["立夏", "小满"],  # 5月        8  9  10
                    ["芒种", "夏至"],  # 6月        10 11 12
                    ["小暑", "大暑"],  # 7月        12 13 14
                    ["立秋", "处暑"],  # 8月        14 15 16
                    ["白露", "秋分"],  # 9月        16 17 18
                    ["寒露", "霜降"],  # 10月       18 19 20
                    ["立冬", "小雪"],  # 11月       20 21 22
                    ["大雪", "冬至"]   # 12月       22 23 24
                ]

    D = 0.2422
    Cs = [5.4055, 20.12, 3.87, 18.73, 5.63, 20.646, 4.81, 20.1, 5.52, 21.04,
          5.678, 21.37, 7.108, 22.83, 7.5, 23.13, 7.646, 23.042, 8.318, 23.438,
          7.438, 22.36, 7.18, 21.94]

    date = date.split('-')
    year = int(date[0]) % 100
    month = int(date[1])
    day = int(date[2])

    term_base = 2*month-1

    solar_day_1 = (year * D + Cs[term_base-1]) - ((year-1)/4)     # first solar term in current month
    solar_day_2 = (year * D + Cs[term_base]) - ((year-1)/4)     # second solar term in current month

    if day < solar_day_1:
        term_number = term_base - 1
    elif day < solar_day_2:
        term_number = term_base
    else:
        term_number = term_base + 1

    if term_number == 24:
        term_number = 0

    # shift
    term_shift = term_number + 7
    term_number = term_shift if term_shift <= 24 else term_shift-24

    if periodicity:
        size = 24
        period_param = math.sin((term_number/24)*math.pi)
        term_number = size * period_param

    return term_number

def get_time_label(time: str, periodicity=False):
    '''
    time: 12:00:00
    according to the hottest temperature at 14:00,
    02:00 - 14:00 0 --> 12
    14:00 - 02:00 11 --> 0
    '''
    hour = int(time.split(':')[0])
    #  2-->14  convert to 0-->12
    hour = hour-2 if hour-2>=0 else 2-hour
    if hour < 12:
        label = hour % 12
    else:
        label = 12 - hour % 12
    return label

def get_periodic_time_label(time: str):
    '''
    time: 12:00:00
    according to the hottest temperature at 14:00,
    02:00 - 14:00 0 --> 12
    14:00 - 02:00 11 --> 0
    '''
    hour = int(time.split(':')[0])
    #  2-->14  convert to 0-->12
    hour = hour-2 if hour-2>=0 else 24-(2-hour)
    size = 24
    period_param = math.sin((hour/24)*math.pi)
    label = size * period_param

    return label

# print(get_time_label('04:00:00'))

def cal_wind_projection(s1, s2, ws, wd):
    angle_name = f'{s1}-{s2}'
    angle = station_angle[angle_name]

    if wd > 360 or ws < 0.5:
        return 0
    else:
        included_angle = wd - angle
        projection_rate = math.cos(math.pi*included_angle/180)
        if projection_rate <= 0:
            return 0
        else:
            return ws*projection_rate

def get_max_dist(station, stations):
    stations = [i for i in stations if i != station]
    station_pairs = [sorted([station, i]) for i in stations]
    station_dists = [station_dist[f'{i[0]}-{i[1]}'] for i in station_pairs]
    return max(station_dists)

def construct_train_xy(df, target_station, station_list, only_x=False):
    if only_x:
        input_cols = ['station_id', 'test_id', 'temperature', 'pressure', 'humidity',
                      'periodic_solar_term', 'periodic_time', 'NearTraffic', 'Others', 'SubUrban', 'Urban', 'wind_speed']
    else:
        input_cols = ['station_id', 'temperature', 'pressure', 'humidity',
                      'periodic_solar_term', 'periodic_time', 'NearTraffic', 'Others', 'SubUrban', 'Urban', 'wind_speed']
    output_cols = ['PM2.5', 'PM10', 'O3']
    useful_cols = ['temperature', 'pressure', 'humidity', 'wind_speed', 'wind_direction']

    qry = f'station_id=="{target_station}"'
    input_df = df.query(qry)[input_cols]
    input_df = input_df.reset_index().drop('index', axis=1)     # index other_df will make column cannot be combined

    max_dist = get_max_dist(target_station, station_list)
    for station in station_list:
        if station == target_station:
            continue
        short_stt = station.split('_')[0]
        station_pair = sorted([target_station, station])
        dist = station_dist[f'{station_pair[0]}-{station_pair[1]}']
        dist_rate = 1 - (dist/max_dist)

        qry = f'station_id=="{station}"'
        other_df = df.query(qry)[useful_cols]
        other_df = other_df.reset_index().drop('index', axis=1)

        input_df[f'{short_stt}_temperature'] = other_df['temperature'] * dist_rate
        input_df[f'{short_stt}_pressure'] = other_df['pressure'] * dist_rate
        input_df[f'{short_stt}_humidity'] = other_df['humidity'] * dist_rate

        wind_info = other_df[['wind_speed', 'wind_direction']].values.tolist()
        wind_info = [cal_wind_projection(station, target_station, x[0], x[1])*dist_rate for x in wind_info]
        input_df[f'{short_stt}_wind'] = np.array(wind_info)

    if not only_x:
        return input_df.drop('station_id', axis=1), df.query(qry)[output_cols]
    else:
        return input_df


import os
from moviepy.editor import *
import subprocess

def extractor(a):
    b = a.split('.')
    current = os.getcwd()
    current = current + '\\media\\video\\'
    video_file = current + a
    audio_file = current + 'extracted_' + b[0] +'.mp3'
    audioclip = AudioFileClip(video_file)
    audioclip.write_audiofile(audio_file)

def noaudio(name):
    command = 'cd media & cd video & ffmpeg -i ' + name +  ' -c copy -an silent_' + name
    #command = 'cd media & ffmpeg -i ' + path +  ' -c copy -an silent_' + path
    #command = 'cd media & ffmpeg -i bruh.mp4 -vn -c:a copy soundtrack.m4a'
    print(command)
    subprocess.call(command, shell=True)

def recombine2(name):
    name_only = name.split('.')
    #command = 'ffmpeg -i silent_test.mp4 -i denoised_test.mp3 -c:v copy -c:a aac output.mp4'
    command = 'cd media & cd video & ffmpeg -i silent_test.mp4 -i denoised_test.wav' + ' -c:v copy -c:a aac denoised_' + name
    subprocess.call(command, shell= True)

    #delete silent vid and denoised.wav audio output from model
    command = 'cd media & cd video & del silent_test.mp4 & del denoised_test.wav'
    subprocess.call(command, shell= True)

# extractor()
# noaudio('bruh.mp4')
#recombine2('test.mp4')


# Created by Vinay Jakkali on 12/9/2019

"""
--------------------------------------------------------------------------------------
Problem 4 calculations to minimize the give two dimensional function using Powell's
Method or Quasi-Newton Method
--------------------------------------------------------------------------------------
"""
import numpy as np
from Quasi_Newton import quasi_newton, quasi_newton_surfaceplot, quasi_newton_contourplot

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from mpl_toolkits.mplot3d import Axes3D

def f(x):

    F = (x[0]**2 + x[1] - 11)**2 + (x[0] + x[1]**2 - 7)**2

    return F

def main():

    Fmins = lambda x: f(x)

    Fmaxs = lambda x: -1 * f(x)

    X0 = np.array([[-5., -2.], [5., -2.5], [-3., 3.8], [4.75, 1.8], [3., 2.]])

    Minimums = np.zeros(np.shape(X0))

    Maximums = np.zeros(np.shape(X0))

    F_mins = np.zeros(len(X0))

    F_maxs = np.zeros(len(X0))

    for i in range(len(X0)):

        Minimums[i, :], k1 = quasi_newton(Fmins, X0[i, :])

        F_mins[i] = Fmins(Minimums[i, :])

        Maximums[i, :], k2 = quasi_newton(Fmaxs, X0[i, :])

        F_maxs[i] = Fmaxs(Maximums[i, :])

    return np.around(Minimums, decimals=2), np.around(Maximums, decimals=2), F_mins, F_maxs

if __name__ == '__main__':

    Mins, Maxs, f_mins, f_maxs = main()

    TotalMins = np.unique(f_mins)

    TotalMaxs = np.where(np.unique(f_maxs >= 0.))[0]

    """ Creating points for plotting the objective function """

    fig = plt.figure()
    left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
    ax = fig.add_axes([left, bottom, width, height])

    # Creating Data points for contour plot

    xlist = np.linspace(-5, 5, 100)
    ylist = np.linspace(-5, 5, 100)

    X, Y = np.meshgrid(xlist, ylist)
    Z = f([X, Y])

    # Plotting the contour
    cp = plt.contourf(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

    # Plotting the minimums on the plot surface
    plt.scatter(Mins[:, 0], Mins[:, 1], color='red', marker='*')
#    plt.scatter(Maxs[4, 0], Maxs[4, 1], color='black', marker='o')

    # Annotating the local minimum
#    ax.annotate('local min', xy=(xmin[0], xmin[1]), xytext=(xmin[0]+0.5, xmin[1]+0.5), fontsize=12,
#                ha='center', va='top')

    # Adding the color bar
    plt.colorbar(cp)

    # Adding the title and axes labels
    ax.set_title(" Local Minimums")
    ax.set_xlabel(" x-axis ")
    ax.set_ylabel(" y-axis ")

    plt.show()

#    quasi_newton_contourplot(f, Mins[0, :])
#    quasi_newton_surfaceplot(f, Mins[0, :])

    print("Minimums", Mins)
    print("Maximums", Maxs)
    print("Fmins", f_mins)
    print("Fmaxs", f_maxs)

    print("Total no. of minimums", len(TotalMins))
    print("Total no. of maximums", len(TotalMaxs))


# Dictionary dos contatos
AGENDA = {}

# Método para mostrar todos os contatos da agenda

def mostrar_contatos():
    if(AGENDA):
        for contato in AGENDA:
            print()
            buscar_contatos(contato)
            print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    else:
        print('>>>>Agenda vazia')

# Método que busca um contato em específico passado como paramêtro

def buscar_contatos(contato):
    try:
        print("Nome:", contato)
        print("Telefone:", AGENDA[contato]["telefone"])
        print("Email:", AGENDA[contato]["email"])
        print("Endereço:", AGENDA[contato]["endereco"])
    except KeyError:
        print()
        print('>>>>CONTATO INEXISTENTE')
        print()
    except Exception as error:
        print('>>>>Um erro inesperado ocorreu')

# Método que inclui ou edita novos contatos na lista
def incluir_editar_contatos(contato, telefone, email, endereco):
    AGENDA[contato] = {
        "telefone": telefone,
        'email': email,
        'endereco': endereco,
    }
    salvar()
    print("===>>> {} adicionado/editado com sucesso!".format(contato))

# Método para excluir um contato passado como parâmetro
def excluir_contato(contato):
    try:
        AGENDA.pop(contato)
        salvar()
        print()
        print("===>>> O usuário {} foi removido.".format(contato))
        print()
    except KeyError:
        print()
        print('>>>>CONTATO INEXISTENTE')
        print()
    except Exception as error:
        print('>>>>Um erro inesperado ocorreu')

def ler_detalhes_contato():
    telefone = input('Digite o telefone desejado: ')
    email = input('Digite o email desejado: ')
    endereco = input('Digite o endereço desejado: ')
    return telefone, email, endereco;

def exportar_contatos(file_name):
    try:
        with open(file_name, 'w') as file:
            for contato in AGENDA:
                telefone = AGENDA[contato]['telefone']
                email = AGENDA[contato]['email']
                endereco = AGENDA[contato]['endereco']
                file.write("{}, {}, {}, {}\n".format(
                    contato, telefone, email, endereco))
        print('>>>>Agenda salva')
    except:
        print('>>>>Ocorreu algum erro ao exportar')

def importar_contatos(file_name):
    try:
        with open(file_name, 'r') as file:
            lines = file.readlines()
            for line in lines:
                detalhes = line.strip().split(',')
                nome = detalhes[0]
                telefone = detalhes[1]
                email = detalhes[2]
                endereco = detalhes[3]

                incluir_editar_contatos(nome, telefone, email, endereco)

    except FileNotFoundError:
        print('>>>>Arquivo não encontrado')
    except Exception as error:
        print('>>>>Erro inesperado')
        print(error)

def salvar():
    exportar_contatos('database.csv')

def load():
    try:
        with open('database.csv', 'r') as file:
            lines = file.readlines()
            for line in lines:
                detalhes = line.strip().split(',')
                nome = detalhes[0]
                telefone = detalhes[1]
                email = detalhes[2]
                endereco = detalhes[3]

                AGENDA[nome] = {
                    "telefone": telefone,
                    'email': email,
                    'endereco': endereco,
                }
        print('>>>>Database carregado')
        print('>>>>{} contatos carregados'.format(len(AGENDA)))
    except FileNotFoundError:
        print('>>>>Arquivo não encontrado')
    except Exception as error:
        print('>>>>Erro inesperado')
        print(error)

# Imprime o menu de opcoes pro usuário
def imprimir_menu():
    print('++++++++++++++++++++++ MENU ++++++++++++++++++++++')
    print('1 - Mostrar todos os contatos da agenda')
    print('2 - Buscar contato')
    print('3 - Incluir/Editar contato')
    print('4 - Excluir contato')
    print('5 - Exportar contatos para CSV')
    print('6 - Importar contatos de CSV')
    print('0 - Sair do programa')
    print('++++++++++++++++++++++++++++++++++++++++++++++++++')

# Início do programa
load()
while True:
    imprimir_menu()

    opcao = input('Escolha uma opção: ')
    if(opcao == '1'):
        mostrar_contatos()

    elif(opcao == '2'):
        contato = input('Digite o nome do usuário a ser buscado:')
        print('')
        buscar_contatos(contato)
        print('')

    elif(opcao == '3'):
        contato = input('Digite o nome desejado: ')

        try:
            AGENDA[contato]
            print('>>>> Editando', contato)
            telefone, email, endereco = ler_detalhes_contato()
            incluir_editar_contatos(contato, telefone, email, endereco)
        except KeyError:
            print('>>>>Incluindo contato', contato)
            telefone, email, endereco = ler_detalhes_contato()
            incluir_editar_contatos(contato, telefone, email, endereco)

    elif(opcao == '4'):
        contato = input('Digite o usuário a ser excluído: ')
        excluir_contato(contato)

    elif(opcao == '5'):
        file_name = input('Digite o nome do arquivo a ser exportado: ')
        exportar_contatos(file_name)

    elif(opcao == '6'):
        file_name = input('Digite o nome do arquivo a ser importado: ')
        importar_contatos(file_name)

    elif(opcao == '0'):
        break
    else:
        print('Opção inválida')


## Matplotlib Part 2

import matplotlib.pyplot as plt

x=[1,2,3,4,5,6,7] # week days
y=[964,287,42,390,64,800,523] # views

plt.plot(x,y,label='Youtube views',
         color='r',
         marker='o',
         markerfacecolor='g',
         linestyle='--',
         linewidth=3)
plt.xlabel('Week days')
plt.ylabel('Views')
plt.title('Youtube views on daily basis')
plt.legend(loc='upper left')

plt.show()

Udemy/data science with python/Data Visualization with Matplotlib 2.py


def is_leap_year(year):
    if year % 400 == 0:
        return True
    elif year % 100 == 0:
        return False
    elif year % 4 == 0:
        return True

    return False

def weekday_newyear(year):

    days = 0
    rng = range(1900,(year))

    for i in rng:
        if is_leap_year(i) == True:
            days = days + 366
        else:
            days = days + 365

    day_of_week = days % 7

    return day_of_week

def is_workday(weekday):
    if 0 <= weekday < 5:
        return True
    else:
        return False

def workdays_in_year(year):
    workdays = 0
    day_range = [weekday_newyear(year)]

    if is_leap_year(year) == True:
        for i in range(1,366):
            if day_range[i - 1] == 6:
                day_range.append(0)
            else:
                day_range.append(day_range[i - 1] + 1)
    else:
        for i in range(1,365):
            if day_range[i - 1] == 6:
                day_range.append(0)
            else:
                day_range.append(day_range[i - 1] + 1)

    for x in range(0,len(day_range)):
        if is_workday(day_range[x]) == True:
            workdays = workdays + 1
        else:
            pass

    return workdays

def main():
    years = range(1900,1920)
    day_table = ['man','tir','ons','tor','fre','lør','søn']
    for i in years:
        j = weekday_newyear(i)

        print(i, day_table[j])

    print('============================')

    for i in years:
        j = workdays_in_year(i)

        print(i ,'har', j ,'arbeidsdager')

main()


from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest

class ProgramThinkCrawler:
    @staticmethod
    async def fetch():
        return await CrawlerParsel.fetch(
            __url__='https://program-think.blogspot.com/',
            __post_item_xpath__='//div[@class="blog-posts hfeed"]//h1[@class="post-title entry-title"]/a'
        )

class ProgramThinkCrawlerTester(unittest.TestCase):
    def test_fetch(self):
        CrawlerParsel.test_fetch(ProgramThinkCrawler)


# -*- coding: utf-8 -*-

import json

from django import forms
from django.contrib import admin

from django.core.mail import send_mail

from django.conf import settings

from django.core.exceptions import ImproperlyConfigured

from django.forms.util import flatatt

from django.utils.html import escape, format_html

from django.template.loader import render_to_string

from catalogo.models import Prestacion

class CustomPrestacionesWidget(forms.Widget):

    def render(self, name, value, attrs=None):
        if value is None:
            value = []
        else:
            value = json.loads(value)
        #import pdb;pdb.set_trace()

        html = "
"
        for prestacion_obj in Prestacion.objects.all():
            html += "

%s

" % prestacion_obj.titulo
            for prestacion in prestacion_obj.prestaciones.split('\r\n'):
                if not prestacion:
                    continue
                att = {'type': "checkbox",
                       'value': prestacion,
                       'data-hidden-id': attrs['id'],}

                if prestacion in value:
                    att['checked'] = 'checked'

                html += "<input %s onchange=togglePrestacion(this) /> %s" % (flatatt(att), prestacion)
                html += "
"

        attrs['name'] = name
        attrs['type'] = 'hidden'
        html = "<input %s value=\"%s\" /> %s" % (flatatt(attrs), escape(json.dumps(value)), html)
        html = """

               %s
               """ % html
        return format_html(html)

class VehiculoAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(VehiculoAdminForm, self).__init__(*args, **kwargs)
        self.fields['prestaciones'].widget = CustomPrestacionesWidget()

class ContactForm(forms.Form):
    name = forms.CharField(label=u'Nombre', max_length=100)
    email = forms.EmailField(label=u'Email', max_length=100)
    phone = forms.CharField(label=u'Telefono', max_length=100)
    message = forms.CharField(label=u'Mensaje', widget=forms.Textarea(), max_length=500)

    def send_email(self):
        """
        Send contact form as an email to the address specified in the
        CONTACT_EMAILS setting.
        """
        from_email = self.cleaned_data['email']
        if not hasattr(settings, 'CONTACT_EMAILS'):
            raise ImproperlyConfigured("You need to specify CONTACT_EMAILS in "
                                       "your Django settings file.")
        to_emails = settings.CONTACT_EMAILS
        subject = "Email enviado desde sitio web"
        template_name = 'contact/email.txt'
        message = render_to_string(template_name, self.cleaned_data)

        send_mail(subject, message, from_email, to_emails)


from . import MeasureTransformation, NumpyMeasure, IdentityTransformation
from .activations_iterator import ActivationsIterator
from tmeasures import MeasureResult
from .stats_running import RunningMeanWelford
from .quotient import divide_activations
from .aggregation import DistanceAggregation
import tmeasures as tm

class TransformationDistanceInvariance(NumpyMeasure):
    def __init__(self, distance_aggregation: DistanceAggregation):
        super().__init__()
        self.distance_aggregation = distance_aggregation

    def __repr__(self):
        return f"{self.abbreviation()}(da={self.distance_aggregation})"

    def eval(self, activations_iterator: ActivationsIterator, verbose=False) -> MeasureResult:
        layer_names = activations_iterator.layer_names()
        n_intermediates = len(layer_names)
        mean_running = [RunningMeanWelford() for i in range(n_intermediates)]
        for x, transformation_activations_iterator in activations_iterator.samples_first():
            # transformation_activations_iterator can iterate over all transforms
            for x_transformed, activations in transformation_activations_iterator:
                for j, layer_activations in enumerate(activations):
                    # calculate the distance aggregation only for this batch
                    layer_measure = self.distance_aggregation.apply(layer_activations)
                    # update the mean over all transformation
                    mean_running[j].update(layer_measure)

        # calculate the final mean over all samples (and layers)
        mean_variances = [b.mean() for b in mean_running]
        return MeasureResult(mean_variances, layer_names, self)

    def name(self):
        return "Transformation Distance"

    def abbreviation(self):
        return "TD"

class SampleDistanceInvariance(NumpyMeasure):
    def __init__(self, distance_aggregation: DistanceAggregation):
        super().__init__()
        self.distance_aggregation = distance_aggregation

    def __repr__(self):
        return f"{self.abbreviation()}(da={self.distance_aggregation})"

    def eval(self, activations_iterator: ActivationsIterator, verbose=False) -> MeasureResult:
        layer_names = activations_iterator.layer_names()
        n_layers = len(layer_names)
        mean_running = [RunningMeanWelford() for i in range(n_layers)]

        for transformation, transformation_activations in activations_iterator.transformations_first():
            # calculate the variance of all samples for this transformation
            for x, batch_activations in transformation_activations:
                for j, layer_activations in enumerate(batch_activations):
                    layer_measure = self.distance_aggregation.apply(layer_activations)
                    mean_running[j].update(layer_measure)

        # calculate the final mean over all transformations (and layers)
        mean_variances = [b.mean() for b in mean_running]
        return MeasureResult(mean_variances, layer_names, self)

class NormalizedDistanceInvariance(NumpyMeasure):
    def __init__(self, distance_aggregation: DistanceAggregation,
                 pre_normalization_transformation: MeasureTransformation = IdentityTransformation()):
        self.distance_aggregation = distance_aggregation
        self.td = TransformationDistanceInvariance(distance_aggregation)
        self.sd = SampleDistanceInvariance(distance_aggregation)
        self.pre_normalization_transformation = pre_normalization_transformation

    def eval(self, activations_iterator: ActivationsIterator, verbose=False) -> MeasureResult:
        td_result = self.td.eval(activations_iterator, verbose)
        sd_result = self.sd.eval(activations_iterator, verbose)

        td_result = self.pre_normalization_transformation.apply(td_result)
        sd_result = self.pre_normalization_transformation.apply(sd_result)

        result = divide_activations(td_result.layers, sd_result.layers)
        return MeasureResult(result, activations_iterator.layer_names(), self)

    def __repr__(self):
        return f"{self.abbreviation()}(pnt={self.pre_normalization_transformation},da={self.distance_aggregation})"


from app.search import SearchForm

def test_formatting_data_request():
    """Форматирование аргументов из запроса."""
    data1 = {'email1': 'asd@sdf.bgf', 'phone1': '+79682233415',
             'date1': '2022-12-25'}
    data2 = {'email1': 'asd@sdfbgf', 'text1': '+79682233415',
             'date2': '12.10.1981'}

    res1 = SearchForm._formatting_data_request(data1)
    res2 = SearchForm._formatting_data_request(data2)

    assert res1 == {'email1': 'email', 'phone1': 'phone', 'date1': 'date'}
    assert res2 == {'email1': 'text', 'text1': 'phone', 'date2': 'date'}

# def test_search_all_docs():

# def test_get_set_name_templates():

# def test_get()


import os
import time
import numpy as np
from libensemble.executors.executor import Executor

def run_sim_f(H, persis_info, sim_specs, libE_info):
    """
    Description:
        Simulation user function for running 'train_network' application via the
        Executor. LibEnsemble's workers call this simulation function with a
        (single) row of the History array, corresponding to the input arguments
        for the training function.

    Note:
        Application execution is limited to one app per node. In order to train
        multiple networks simultaneously on one node, multiple processes per
        node are spawned where each process uses a subset of the node CPUs to
        train a unique network.
    """

    # parse hyperparameters from H['in']['alloc id']
    architecture = H['model_type'][0]
    learning_rate = H['learning_rate'][0]
    hid_dim = H['hid_dim'][0]
    epochs = H['epochs'][0]
    dataset = H['dataset'][0]
    permute = H['permute'][0]
    pad = H['pad'][0]
    orientation = H['orientation'][0]
    identifier = H['identifier'][0]
    sim_path = os.getcwd()
    ensemble_end_time = sim_specs['user']['ensemble_end_time']

    args = f'{architecture} {learning_rate} {hid_dim} {epochs} {dataset} {permute} {pad} {orientation} {identifier} {sim_path} {ensemble_end_time}'

    # Specify the Executor object created in the calling script.
    exctr = Executor.executor

    # simulation arguments
    # 10 mpi ranks in total (-n and -N)
    # 4 hardware thread per rank (-d)
    # 1 hardware thread per physical core (-j)
    # 1 OpenMP thread per mpi rank (-e)
    PROCS = 10
    PPN = 10
    d = 4
    OMP = 1
    command_args = f'-n {PROCS} -N {PPN} -d {d} -j 1 -cc depth -e OMP_NUM_THREADS={OMP}'

    # submit application to executor
    task = exctr.submit(app_name='train_network', app_args=args, num_nodes=1, extra_args=command_args)

    exctr.polling_loop(task, timeout=None, delay=1)

    time.sleep(0.2)
    output_path = os.path.join(sim_path, f'training-history-{identifier}-*****.npy')

    # generate and populate libE output history array
    H_out = np.zeros(1, dtype=sim_specs['out'])
    H_out['history_path'] = output_path

    return H_out, persis_info


# DailyCodingProblem #21

import sys

def MinRoomCountThatSucks (arr):
    maxCount = 0
    start = sys.maxsize
    end = 0

    for (a, b) in arr:
        start = a if a < start else start
        end = b if b > end else end

    for i in range(start, end):
        count = 0
        for (a, b) in arr:
            if a < i < b:
                count += 1
        maxCount = count if count > maxCount else maxCount

    return maxCount

def MinRoomCount (arr):
    maxCount = 0
    length = len(arr)
    i = 0

    while (i < length):
        j = 0
        count = 1
        while (j < length):
            if j != i and arr[j][0] <= arr[i][0] < arr[j][1]:
                count += 1
            j += 1
        i += 1
        maxCount = count if count > maxCount else maxCount

    return maxCount

times = [(30, 75), (0, 50), (60, 150)]
count = MinRoomCount(times)
print("For the following schedule: ", times)
print("Minimum number of rooms required is: ", count)
# expected result: 2

# time benchmarks below
'''
if __name__ == "__main__":
    import timeit
    setup = "from __main__ import MinRoomCount"
    print("MinRoomCount: ", timeit.timeit("MinRoomCount([(30, 75), (0, 50), (60, 150)])", setup=setup))
    setup = "from __main__ import MinRoomCountThatSucks"
    print("MinRoomCountThatSucks: ", timeit.timeit("MinRoomCountThatSucks([(30, 75), (0, 50), (60, 150)])", setup=setup))
'''


from django.urls import path

from . import views

app_name = 'fastapi_table'
urlpatterns = [
    path('', views.search_page, name='search_page'),

    # Domain Ip
    path('domain_ip/', views.domain_ip_search, name='domain_ip_search'),
    path('domain_ip_get/', views.domain_ip_redirect, name='domain_ip_redirect'),
    path('domain_ip/<str:object_id>/', views.search_domain_ip, name='search_domain_ip'),

    # Files
    path('files/', views.files_search, name='files_search'),
    path('files_get/', views.files_redirect, name='files_redirect'),
    path('files/<str:file_id>/', views.search_files, name='search_files'),

    # Search
    #path('search/', views.search_page, name='search_page'),
]


from setuptools import setup, find_packages
import os

version = '0.1.1'

setup(name='ewb_case.casclient',
      version=version,
      description="Provides CAS authentication for EWB Case website.",
      long_description=open("README.txt").read() + "\n" +
                       open(os.path.join("docs", "HISTORY.txt")).read(),
      classifiers=[
        "Framework :: Plone",
        "Programming Language :: Python",
        ],
      keywords='',
      author='Matt Bierner',
      author_email='mattbierner@gmail.com',
      url='https://github.com/mattbierner/ewb_case.casclient',
      license='GPL',
      packages=find_packages(exclude=['ez_setup']),
      namespace_packages=['ewb_case', ],
      include_package_data=True,
      zip_safe=False,
      install_requires=[
          'setuptools',
          'anz.casclient',
      ],
      entry_points="""
      # -*- Entry points: -*-

      [z3c.autoinclude.plugin]
      target = plone
      """,
      )


import tensorflow as tf
import sys
import numpy as np

from ngclearn.utils.stat_utils import calc_log_gauss_pdf
from ngclearn.utils.transform_utils import softmax

seed = 69
tf.random.set_seed(seed=seed)

class OUNoise:
    """
    Implements an Ornstein Uhlenbeck (O-H) stochastic (temporal) data generating process.

    Args:
        mean: a (1 x D) vector (numpy) (mean of the process)

        std_deviation: a (1 x D) vector (numpy) (standard deviation of the process)

        theta: meta-parameter to control the drift term of the process (Default = 0.15)

        dt: the integration time step (Default = 1e-2)

        x_initial: the initial value of the process (Default = None, yielding a
            zero vector starting point)
    """
    def __init__(self, mean, std_deviation, theta=0.15, dt=1e-2, x_initial=None):
        self.theta = theta
        self.mean = mean
        self.std_dev = std_deviation
        self.dt = dt
        self.x_initial = x_initial # initial condition
        self.x_prev = None
        self.reset() # ensure at initialization this O-H process starts at the initial condition

    def sample(self):
        """
        Draws a sample from the current state of this O-H temporal process.

        Returns:
            a vector sample of shape (1 x D)
        """
        # Formula below is adapted from https://www.wikipedia.org/wiki/Ornstein-Uhlenbeck_process.
        x = (
            self.x_prev
            + self.theta * (self.mean - self.x_prev) * self.dt
            + self.std_dev * np.sqrt(self.dt) * np.random.normal(size=self.mean.shape)
        )
        x = x.astype(np.float32)
        # Store x sample into x_prev state
        self.x_prev = x # this step ensures that the next noise sample is dependent upon current one
        return x

    def reset(self):
        """
        Resets the temporal noise process back to its initial condition/starting point.
        """
        if self.x_initial is not None:
            self.x_prev = self.x_initial
        else: # reset the noise process back to zero
            self.x_prev = np.zeros_like(self.mean)
        self.x_prev = self.x_prev.astype(np.float32)


import numpy as np
import matplotlib.pyplot as plt

w = np.loadtxt("weatherTaipei.txt",delimiter=',',skiprows=1,usecols=(1,2,3))
x = np.arange(1, 32)

high = w[:,0]
lineHigh, = plt.plot(x, high, '-o', label="High")

ave = w[:,1]
lineAve, = plt.plot(x, ave, '-^', label="Average")

low = w[:,2]
lineLow, = plt.plot(x, low, '-x', label="Low")

plt.legend(handles=[lineHigh, lineAve, lineLow], loc='best')
plt.title("Taipei Weather Report", fontsize=24)
plt.xlabel("Date", fontsize=14)
plt.ylabel("Temperature", fontsize=14)

plt.show()


from io import BytesIO

from PIL import Image as PilImage
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.views import View
from rest_framework import generics, permissions, status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response

from .models import MyImage
from .serializers import MyImageSerializer

# View to list all images or create a new image
class ImageList(generics.ListCreateAPIView):
    queryset = MyImage.objects.all()
    serializer_class = MyImageSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        # set owner of the image to current user

        serializer.save(owner=self.request.user)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

class MyView(View):
    @staticmethod
    def get(request, *args, **kwargs):
        image_id = kwargs['image_id']
        image = MyImage.objects.get(id=image_id)

        with BytesIO(image.original_image.read()) as file:
            with PilImage.open(file) as image:
                thumbnail = image.resize((300, 300))
                buffer = BytesIO()
                thumbnail.save(buffer, format='PNG')

        return HttpResponse(buffer.getvalue(), content_type='image/png')

# View to retrieve, update, or delete an image
class ImageDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = MyImage.objects.all()
    serializer_class = MyImageSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def perform_update(self, serializer):
        # set owner of the image to current user
        serializer.save(owner=self.request.user)

# View to handle expiring image links
@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def image_link(request):
    # check if the user has the necessary plan for generating expiring links
    if request.user.profile.plan != 'Enterprise':
        raise PermissionDenied

    # parse expiration time from request data
    expiration_time = request.data.get('expiration_time')
    if expiration_time is None or not (300 <= expiration_time <= 30000):
        return Response({'error': 'Invalid expiration time'}, status=status.HTTP_400_BAD_REQUEST)

    # generate expiring link and return response
    image_id = request.data.get('image_id')
    try:
        image = MyImage.objects.get(pk=image_id, owner=request.user)
    except MyImage.DoesNotExist:
        return Response({'error': 'Image not found'}, status=status.HTTP_404_NOT_FOUND)
    expiring_link = image.generate_expiring_link(expiration_time)
    return Response({'expiring_link': expiring_link}, status=status.HTTP_200_OK)


from flask import Flask, render_template, request
from functions import *

app = Flask('Flask App', static_folder='static', template_folder="templates")

@app.route('/', methods = ["GET", "POST"])
def home():
  return render_template("index.html")

@app.route('/results', methods = ["GET", "POST"])
def resultsPage():
  prompt = str(request.form.get('prompt'))
  amount = str(request.form.get('amount'))
  images = getData(prompt, amount)
  print(images)
  return render_template("results.html", images = images)

app.run(host = '0.0.0.0', port = 6969, threaded = True)


import numpy as np
import pandas as pd
import math

distr_table =pd.DataFrame({
        'X':[0,0,1,1],
        'Y':[1,2,1,2],
        'pr':[0.30,0.25,0.15,0.30]
        })

class CheckIndependence:
    def __init__(self):
        self.version=1
    def independent(self,table,i,j):
        if table.iloc[i][j]>0:
            if table.iloc[i][j]==table.iloc[j][3]*table.iloc[j][4]:
                return 1
            else:
                print(table.iloc[i][j],end=" ")
                print(table.iloc[j][3]*table.iloc[j][4])
                return 0
        else:
            return 1
    def findIndependent(self,table):
        are_independet=True
        for i in range(len(table)):
            for j in range(len(table)):
                are_independet*=self.independent(table,i,j)

        return bool(are_independet)
    def check_independence(self,distr_table):
        self.pr_in=0
        table=[[ 0 for col in range(3)] for row in range(3)]
        self.prList=[]
        #print(table)
        self.x=[]
        self.y=[]
        self.pr_in=0
        for i in distr_table.pr:
            self.prList.append(i)
        for i in distr_table.X:
            self.x.append(i)
        for i in distr_table.Y:
            self.y.append(i)
        for i in range(len(self.x)):
            for j in range(i,len(self.y)):
                table[self.y[i]][self.x[j]]=self.prList[self.pr_in]
                self.pr_in+=1
                break
        #print(table)
        table=pd.DataFrame(table)
        table['total_Y']=table.sum(axis=1)
        table['total_X']=table.sum()
        print(table)
        are_independet=self.findIndependent(table)
        are_independet=bool(are_independet)
        cov=self.cov(table)
        corr=self.corr(table)
        return dict({'are_independet':are_independet,'cov':cov,'corr':corr})

    def cov(self,table):
        cov=0
        for i in range(len(table)):
            if (table.iloc[0][i]>0):
                cov+=(int(table.iloc[0][i])-self.mouX(table))*(int(table.iloc[1][i])-self.mouY(table))
        return cov
    def mouX(self,table):
        xSum=0
        for i in table.total_X:
            if i>0:
                xSum+=i
        return xSum

    def mouY(self,table):
        ySum=0
        for i in table.total_Y:
         ySum+=i
        return ySum

    def corr(self,table):
        return self.cov(table)/(self.BetaX(table)*self.BetaY(table))

    def BetaX(self,table):
        betaSum=0
        for j in table.total_X:
            betaSum+=j-self.mouX(table)**2
        return math.sqrt(abs(betaSum))
    def BetaY(self,table):
        betaSum=0
        for j in table.total_Y:
            betaSum+=j-self.mouX(table)**2
        return math.sqrt(abs(betaSum))

o=CheckIndependence()
print(o.check_independence(distr_table))