def calculate_answer(s, domain):
    """Calculates a string using sympy.

    :param s: String to be calculated
    :param domain: The domain of the variables.
    :return: A latex version of the calculated string.
    """

    try:
        domain = json.loads(domain)
    except ValueError:
        pass
    try:
        if not is_number(s):  # Small optimization
            s = remove_unnecessary(s)
            s = str(latex_to_sympy(s))
            s = s.replace('*)', ')*')
            s = s.replace('?)@', ')?@')
            s = parse_expr(s, transformations=standard_transformations +
                           (convert_xor, implicit_multiplication_application,), global_dict=None, evaluate=False)
            s = latex(sympify(str(s)))
            # Sometimes sympify returns the value 'zoo'
        else:
            if domain != '':
                s = round_answer(domain, float(s))
    except Exception as e:
        print('exception in calculate answer')
        print(e)
    return str(s)
def test_template(template):
    """Tests if the creation of a template ends up with a valid template. Returns 1/0 for success/failure."""
    got_trough_test = 0  # 1 if template got through test, and 0 if not.
    # Make numbers, check condition, check calculations
    random_domain = template.random_domain
    # Efficiency note: it might be faster to pass the domain list, instead of getting them from template every time.
    answer = template.answer
    question = template.question_text
    solution = template.solution
    conditions = template.conditions
    conditions = remove_unnecessary(conditions)

    variable_dict = generate_valid_numbers(question, random_domain, "", False)
    inserted_conditions = string_replace(conditions, variable_dict)
    if len(conditions) > 1:
        conditions_pass = sympify(latex_to_sympy(inserted_conditions))
    else:
        conditions_pass = True
    if conditions_pass:
        answer = string_replace(answer, variable_dict)
        solution = string_replace(solution, variable_dict)

        try:
            answer = parse_answer(answer, random_domain)
            parse_solution(solution, random_domain)  # Checks if solution can be parsed
            got_trough_test = 1
        except Exception:
            pass
        if answer == 'error':
            got_trough_test = 0
    return got_trough_test