# -*- coding: utf-8 -*-
from odoo import models, fields, api
import random
from odoo import http
import json
from datetime import datetime

class AccountantBalance(models.Model):
    _name = 'accountant.balance'
    _description = 'this is Balance sheet'
    name = fields.Char(string="报表名称", required=True)
    startDate = fields.Date(string="开始期间", required=True, store=True)
    endDate = fields.Date(string="结束期间", required=True, store=True)
    fast_period = fields.Date(string="选取期间")
    company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id',
                                          string="Company Currency", readonly=True, store=True)
    company_id = fields.Many2one('res.company', string='公司',
                                 store=True, index=True, readonly=False, required=True)
    amount_b = fields.Monetary(default=0.0, string="货币资金",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_c = fields.Monetary(default=0.0, string="交易性金融资产",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_d = fields.Monetary(default=0.0, string="应收票据",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_e = fields.Monetary(default=0.0, string="应收账款",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_f = fields.Monetary(default=0.0, string="预付款项",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_g = fields.Monetary(default=0.0, string="应收股利",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_h = fields.Monetary(default=0.0, string="其他应收款",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_i = fields.Monetary(default=0.0, string="存货",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_j = fields.Monetary(default=0.0, string="一年内到期的非流动资产",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_k = fields.Monetary(default=0.0, string="其他流动资产",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_l = fields.Monetary(default=0.0, string="流动资产合计",
                               store=True, currency_field='company_currency_id', readonly=True)

    @api.multi
    def profit_mapped_debit(self, account_id):
        start_s = self.startDate
        start_e = self.endDate
        amount_mapped = self.env['account.move.line']
        debit = sum(amount_mapped.search([('date', '>=', start_s),
                                          ('date', '<=', start_e),
                                          ('account_id', '=', account_id),
                                          ('company_id', '=', self.company_id.id)]).mapped('debit'))
        credit = sum(amount_mapped.search([('date', '>=', start_s),
                                           ('date', '<=', start_e),
                                           ('account_id', '=', account_id),
                                           ('company_id', '=', self.company_id.id)]).mapped('credit'))
        balance = debit - credit
        return balance

    @api.multi
    def profit_mapped_credit(self, account_id):
        start_s = self.startDate
        start_e = self.endDate
        amount_mapped = self.env['account.move.line']
        debit = sum(amount_mapped.search([('date', '>=', start_s),
                                          ('date', '<=', start_e),
                                          ('account_id', '=', account_id),
                                          ('company_id', '=', self.company_id.id)]).mapped('debit'))
        credit = sum(amount_mapped.search([('date', '>=', start_s),
                                           ('date', '<=', start_e),
                                           ('account_id', '=', account_id),
                                           ('company_id', '=', self.company_id.id)]).mapped('credit'))
        balance = credit - debit
        return balance

    @api.multi
    def _account_debit(self, account_s, account_e):
        currency_account = self.env['account.account'].search([('code', '>=', account_s),
                                                               ('code', '<=', account_e),
                                                               ('company_id', '=', self.company_id.id)]).mapped('id')
        currency = 0
        for currency_id in currency_account:
            currency_debit = self.profit_mapped_debit(currency_id)
            currency += currency_debit
        return currency

    @api.multi
    def _account_credit(self, account_s, account_e):
        currency_account = self.env['account.account'].search([('code', '>=', account_s),
                                                               ('code', '<=', account_e),
                                                               ('company_id', '=', self.company_id.id)]).mapped('id')
        currency = 0
        for currency_id in currency_account:
            currency_credit = self.profit_mapped_credit(currency_id)
            currency += currency_credit
        return currency

    def _amount_get(self, amount):
        result = self.env['accountant.balance.set'].search([('company_id', '=', self.company_id.id)], limit=1).mapped(amount)[0]
        amount_sum = 0.0
        for L_dir in result.split(';'):
            s_dir = eval(L_dir)
            if s_dir == 0:
                break
            p_dir = s_dir.get('+')
            r_dir = s_dir.get('-')
            if p_dir:
                p_b, p_s, p_e = p_dir.split(',')
                if p_b == 'debit':
                    amount_sum += self._account_debit(int(p_s), int(p_e))
                elif p_b == 'credit':
                    amount_sum += self._account_credit(int(p_s), int(p_e))
                else:
                    raise UserError("计算失败！原因:余额方向填写错误")

            elif r_dir:
                r_b, r_s, r_e = r_dir.split(',')
                if r_b == 'debit':
                    amount_sum -= self._account_debit(int(r_s), int(r_e))
                elif r_b == 'credit':
                    amount_sum -= self._account_credit(int(r_s), int(r_e))
                else:
                    raise UserError("计算失败！原因:余额方向填写错误")
            else:
                raise UserError("计算失败！原因:+或—填写错误")

        return amount_sum

    @api.multi
    def do_current_assets(self):
        if self.startDate > self.endDate:
            raise exceptions.ValidationError('你选择的开始日期不能大于结束日期')
        # 货币资金

        # current_eight = self._account_debit(1002010, 1002016)
        self.amount_b = self._amount_get('amount_b')
        # 交易性金融资产
        # self.amount_c = self._account_debit(150300, 150300)
        self.amount_c = self._amount_get('amount_c')
        # 应收票据
        self.amount_d = self._amount_get('amount_d')
        # 应收账款
        # self.amount_e = self._account_debit(112200, 112200) \
        #                 + self._account_debit(11230001, 11230001)\
        #                 - self._account_credit(123100, 123100)
        self.amount_e = self._amount_get('amount_e')
        # # 预付款项
        # self.amount_f = self._account_debit(220200, 220200) + self._account_debit(112300, 112300)
        # 预付款项
        self.amount_f = self._amount_get('amount_f')
        # 应收股利
        self.amount_g = self._amount_get('amount_g')
        # 其他应收款
        self.amount_h = self._amount_get('amount_h')
        # 存货
        self.amount_i = self._amount_get('amount_i')
        # 一年内到期的非流动资产
        self.amount_j = self._amount_get('amount_j')
        # 其他流动资产
        self.amount_k = self._amount_get('amount_k')
        # 流动资产合计
        self.amount_l = self.amount_b + self.amount_c + self.amount_d + self.amount_e + self.amount_f + self.amount_g\
                        + self.amount_h + self.amount_i + self.amount_j + self.amount_k
        return self.do_fixed_assets()

    amount_m = fields.Monetary(default=0.0, string="可供出售金融资产",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_n = fields.Monetary(default=0.0, string="持有至到期投资",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_o = fields.Monetary(default=0.0, string="长期应收款",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_p = fields.Monetary(default=0.0, string="长期股权投资",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_q = fields.Monetary(default=0.0, string="投资性房地产",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_r = fields.Monetary(default=0.0, string="固定资产",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_s = fields.Monetary(default=0.0, string="在建工程",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_t = fields.Monetary(default=0.0, string="工程物资",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_v = fields.Monetary(default=0.0, string="固定资产清理",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_u = fields.Monetary(default=0.0, string="生产线生物资产",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_w = fields.Monetary(default=0.0, string="油气资产",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_x = fields.Monetary(default=0.0, string="无形资产",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_y = fields.Monetary(default=0.0, string="开发支出",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_z = fields.Monetary(default=0.0, string="商誉",
                               store=True, currency_field='company_currency_id', readonly=True)
    amount_aa = fields.Monetary(default=0.0, string="长期待摊费用",
                                store=True, currency_field='company_currency_id', readonly=True)
    amount_bb = fields.Monetary(default=0.0, string="递延所得税资产",
                                store=True, currency_field='company_currency_id', readonly=True)
    amount_cc = fields.Monetary(default=0.0, string="其他非流动资产",
                                store=True, currency_field='company_currency_id', readonly=True)
    amount_dd = fields.Monetary(default=0.0, string="非流动资产合计",
                                store=True, currency_field='company_currency_id', readonly=True)
    amount_ee = fields.Monetary(default=0.0, string="资产总计",
                                store=True, currency_field='company_currency_id', readonly=True)

    @api.multi
    def do_fixed_assets(self):
        # 可供出售金融资产
        self.amount_m = self._amount_get('amount_m')
        # 持有至到期投资
        self.amount_n = self._amount_get('amount_n')
        # 长期应收款
        self.amount_o = self._amount_get('amount_o')
        # 长期股权投资
        self.amount_p = self._amount_get('amount_p')
        # 投资性房地产
        self.amount_q = self._amount_get('amount_q')
        # 固定资产
        self.amount_r = self._amount_get('amount_r')
        # 在建工程
        self.amount_s = self._amount_get('amount_s')
        # 工程物资
        self.amount_t = self._amount_get('amount_t')
        # 固定资产清理
        self.amount_v = self._amount_get('amount_v')
        # 生产线生物资产
        self.amount_u = self._amount_get('amount_u')
        # 油气资产
        self.amount_w = self._amount_get('amount_w')
        # 无形资产
        self.amount_x = self._amount_get('amount_x')
        # 开发支出
        self.amount_y = self._amount_get('amount_y')
        # 商誉
        self.amount_z = self._amount_get('amount_z')
        # 长期待摊费用
        self.amount_aa = self._amount_get('amount_aa')
        # 递延所得税资产
        self.amount_bb = self._amount_get('amount_bb')
        # 其他非流动资产
        self.amount_cc = self._amount_get('amount_cc')
        # 非流动资产合计
        self.amount_dd = self.amount_m + self.amount_n + self.amount_o + self.amount_p + self.amount_q + self.amount_r\
                         + self.amount_s + self.amount_t + self.amount_u + self.amount_v + self.amount_w\
                         + self.amount_x + self.amount_y + self.amount_z + self.amount_aa + self.amount_bb\
                         + self.amount_cc
        # 资产总计
        self.amount_ee = self.amount_l + self.amount_dd
        return self.do_current_liabilities()

    debt_a = fields.Monetary(default=0.0, string="短期借款",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_b = fields.Monetary(default=0.0, string="交易性金融负债",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_c = fields.Monetary(default=0.0, string="应付票据",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_d = fields.Monetary(default=0.0, string="应付账款",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_e = fields.Monetary(default=0.0, string="预收款项",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_f = fields.Monetary(default=0.0, string="应付职工薪酬",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_g = fields.Monetary(default=0.0, string="应交税费",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_h = fields.Monetary(default=0.0, string="应付利息",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_i = fields.Monetary(default=0.0, string="应付股利",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_j = fields.Monetary(default=0.0, string="其他应付款",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_k = fields.Monetary(default=0.0, string="一年内到期的非流动负债",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_l = fields.Monetary(default=0.0, string="其他流动负债",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_m = fields.Monetary(default=0.0, string="流动负债合计",
                             store=True, currency_field='company_currency_id', readonly=True)

    @api.multi
    def do_current_liabilities(self):
        # 短期借款
        self.debt_a = self._amount_get('debt_a')
        # 交易性金融负债
        self.debt_b = self._amount_get('debt_b')
        # 应付票据
        self.debt_c = self._amount_get('debt_c')
        # 应付账款
        self.debt_d = self._amount_get('debt_d')
        # 预收帐款
        self.debt_e = self._amount_get('debt_e')
        # 应付职工薪酬
        self.debt_f = self._amount_get('debt_f')
        # 应交税费
        self.debt_g = self._amount_get('debt_g')
        # 应付利息
        self.debt_h = self._amount_get('debt_h')
        # 应付股利
        self.debt_i = self._amount_get('debt_i')
        # 其他应付款
        self.debt_j = self._amount_get('debt_j')
        # 一年内到期的非流动负债
        self.debt_k = self._amount_get('debt_k')
        # 其他流动负债
        self.debt_l = self._amount_get('debt_l')
        # 流动负债合计
        self.debt_m = self.debt_a + self.debt_b + self.debt_c + self.debt_d + self.debt_e + self.debt_f + self.debt_g\
                      + self.debt_h + self.debt_i + self.debt_j + self.debt_k + self.debt_l
        return self.do_fixed_liabilities()

    debt_n = fields.Monetary(default=0.0, string="长期借款",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_o = fields.Monetary(default=0.0, string="应付债券",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_p = fields.Monetary(default=0.0, string="长期应付款",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_q = fields.Monetary(default=0.0, string="专项应付款",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_r = fields.Monetary(default=0.0, string="预计负债",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_s = fields.Monetary(default=0.0, string="递延所得税负债",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_t = fields.Monetary(default=0.0, string="其他非流动负债",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_u = fields.Monetary(default=0.0, string="非流动负债合计",
                             store=True, currency_field='company_currency_id', readonly=True)
    debt_v = fields.Monetary(default=0.0, string="负债合计",
                             store=True, currency_field='company_currency_id', readonly=True)

    @api.multi
    def do_fixed_liabilities(self):
        # 长期借款
        self.debt_n = self._amount_get('debt_n')
        # 应付债券
        self.debt_o = self._amount_get('debt_o')
        # 长期应付款
        self.debt_p = self._amount_get('debt_p')
        # 专项应付款
        self.debt_q = self._amount_get('debt_q')
        # 预计负债
        self.debt_r = self._amount_get('debt_r')
        # 递延所得税负债
        self.debt_s = self._amount_get('debt_s')
        # 其他非流动负债
        self.debt_t = self._amount_get('debt_t')
        # 非流动负债合计
        self.debt_u = self.debt_n + self.debt_o + self.debt_p + self.debt_q + self.debt_r + self.debt_s + self.debt_t
        # 负债合计
        self.debt_v = self.debt_m + self.debt_u
        return self.do_equity()

    equity_a = fields.Monetary(default=0.0, string="实收资本",
                               store=True, currency_field='company_currency_id', readonly=True)
    equity_b = fields.Monetary(default=0.0, string="资本公积",
                               store=True, currency_field='company_currency_id', readonly=True)
    equity_c = fields.Monetary(default=0.0, string="盈余公积",
                               store=True, currency_field='company_currency_id', readonly=True)
    equity_d = fields.Monetary(default=0.0, string="未分配利润",
                               store=True, currency_field='company_currency_id', readonly=True)
    equity_e = fields.Monetary(default=0.0, string="所有者权益合计",
                               store=True, currency_field='company_currency_id', readonly=True)
    equity_f = fields.Monetary(default=0.0, string="负债和所有者权益总计",
                               store=True, currency_field='company_currency_id', readonly=True)

    @api.multi
    def do_equity(self):
        # 实收资本
        self.equity_a = self._amount_get('equity_a')
        # 资本公积
        self.equity_b = self._amount_get('equity_b')
        # 盈余公积
        self.equity_c = self._amount_get('equity_c')
        # 未分配利润
        self.equity_d = self._amount_get('equity_d')
        # 所有者权益合计
        self.equity_e = self.equity_a + self.equity_b + self.equity_c + self.equity_d
        # 负债和所有者权益总计
        self.equity_f = self.debt_v + self.equity_e

class AccountantBalanceSet(models.Model):
    _name = 'accountant.balance.set'
    _description = 'this is balance set'

    name = fields.Char(string='名称', store=True, required=True)
    company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id',
                                          string="Company Currency", readonly=True, store=True)
    company_id = fields.Many2one('res.company', string='公司',
                                 store=True, index=True, readonly=False, required=True)
    amount_b = fields.Char(string='货币资金', store=True, required=True)
    amount_c = fields.Char(string='交易性金融资产',store=True, required=True)
    amount_d = fields.Char(string='应收票据',store=True, required=True)
    amount_e = fields.Char(string='应收账款',store=True, required=True)
    amount_f = fields.Char(string='预付款项',store=True, required=True)
    amount_g = fields.Char(string='应收股利',store=True, required=True)
    amount_h = fields.Char(string='其他应收款',store=True, required=True)
    amount_i = fields.Char(string='存货',store=True, required=True)
    amount_j = fields.Char(string='一年内到期的非流动资产',store=True, required=True)
    amount_k = fields.Char(string='其他流动资产',store=True, required=True)

    amount_m = fields.Char(string='可供出售金融资产', store=True, required=True)
    amount_n = fields.Char(string='持有至到期投资', store=True, required=True)
    amount_o = fields.Char(string='长期应收款', store=True, required=True)
    amount_p = fields.Char(string='长期股权投资', store=True, required=True)
    amount_q = fields.Char(string='投资性房地产', store=True, required=True)
    amount_r = fields.Char(string='固定资产', store=True, required=True)
    amount_s = fields.Char(string='在建工程', store=True, required=True)
    amount_t = fields.Char(string='工程物资', store=True, required=True)
    amount_v = fields.Char(string='固定资产清理', store=True, required=True)
    amount_u = fields.Char(string='生产线生物资产', store=True, required=True)
    amount_w = fields.Char(string='油气资产', store=True, required=True)
    amount_x = fields.Char(string='无形资产', store=True, required=True)
    amount_y = fields.Char(string='开发支出', store=True, required=True)
    amount_z = fields.Char(string='商誉', store=True, required=True)
    amount_aa = fields.Char(string='长期待摊费用', store=True, required=True)
    amount_bb = fields.Char(string='递延所得税资产', store=True, required=True)
    amount_cc = fields.Char(string='其他非流动资产', store=True, required=True)

    debt_a = fields.Char(string='短期借款', store=True, required=True)
    debt_b = fields.Char(string='交易性金融负债', store=True, required=True)
    debt_c = fields.Char(string='应付票据', store=True, required=True)
    debt_d = fields.Char(string='应付账款', store=True, required=True)
    debt_e = fields.Char(string='预收帐款', store=True, required=True)
    debt_f = fields.Char(string='应付职工薪酬', store=True, required=True)
    debt_g = fields.Char(string='应交税费', store=True, required=True)
    debt_h = fields.Char(string='应付利息', store=True, required=True)
    debt_i = fields.Char(string='应付股利', store=True, required=True)
    debt_j = fields.Char(string='其他应付款', store=True, required=True)
    debt_k = fields.Char(string='一年内到期的非流动负债', store=True, required=True)
    debt_l = fields.Char(string='其他流动负债', store=True, required=True)

    debt_n = fields.Char(string='长期借款', store=True, required=True)
    debt_o = fields.Char(string='应付债券', store=True, required=True)
    debt_p = fields.Char(string='长期应付款', store=True, required=True)
    debt_q = fields.Char(string='专项应付款', store=True, required=True)
    debt_r = fields.Char(string='预计负债', store=True, required=True)
    debt_s = fields.Char(string='递延所得税负债', store=True, required=True)
    debt_t = fields.Char(string='其他非流动负债', store=True, required=True)

    equity_a = fields.Char(string='实收资本', store=True, required=True)
    equity_b = fields.Char(string='资本公积', store=True, required=True)
    equity_c = fields.Char(string='盈余公积', store=True, required=True)
    equity_d = fields.Char(string='未分配利润', store=True, required=True)


from flask import Flask, render_template, request, flash
from flask_bootstrap import Bootstrap
from myform import LoginForm, Registration, AdmissionForm
app = Flask(__name__)
app.secret_key='1!2@3#4$5%'
bs=Bootstrap(app)
@app.route('/login')
def login():
    form=LoginForm()
    return render_template("loginform.html", form=form)
@app.route('/')
def index():
    form = AdmissionForm()
    return render_template("admission.html", form=form)
@app.route('/register', methods=['GET', 'POST'])
def register():
  form = Registration()

  if request.method == 'POST':
    if form.validate() == False:
      flash('All fields are required.')
      return render_template('register.html', form=form)
    else:
      return render_template('success.html')

  elif request.method == 'GET':
    return render_template('register.html', form=form)
@app.route('/admission', methods=['GET', 'POST'])
def admission():
  form = AdmissionForm()

  if request.method == 'POST':
    if form.validate() == False:
      return render_template('admission.html', form=form)
    else:
      return '''

Form successfully submitted

Form Data Received

Name :{}

DOB : {}

Branch : {}
'''.format(form.student.data, form.dob.data, form.branch.data)
  elif request.method == 'GET':
    return render_template('admission.html', form=form)
@app.route('/contact', methods=['GET', 'POST'])
def contact():
  form = ContactForm()

  if request.method == 'POST':
    if form.validate() == False:
      flash('All fields are required.')
      return render_template('contact.html', form=form)
    else:
      return render_template('success.html')

  elif request.method == 'GET':
    return render_template('contact.html', form=form)
if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)


'''
Rayssa Rosa
Trabalho final de Computação grafica

Instruções:
Faça um programa de visualização de objetos 3D usando OpenGL com as eguintes características:
Possobilidade de visualização em wireframe e solid, com modelo de iluminação habilitando luzes, ou flat, transformações geométricas básicas (rotações, translações e mudança de escala), recursos para troca de cores. Desejável que tenha ainda: zoom, marcar como selecionado, desmarcar seleção, agrupar objetos na seleção e desagrupar objetos.
'''

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import math

w, h = 500,500
wMenu, hMenu = 200,200

VERMELHO=[1,0,0]
AZUL=[0,0,1]
VERDE=[0,1,0]
ROSA=[1,0.0,1]
LARANJA=[1,0.5,0]
AMARELO=[1, 1, 0.0]
BRANCO=[1,1,1]

ZOOM=1
REDISPLAY=True
WIRE=False
SELECIONA=False
CORATUAL=VERMELHO
ROTATE=False
LUZES=True

OBJETOSDESENHO=[]
OBJETOSMENU=[]
OBJETOSSELECIONADOS=[]

#---------------------------------
#-------------SELEÇAO DE OBJETOS
#---------------------------------
def normalizaCoordenada(x,y,w,h):# Transforma coordanadas baseadas no centro da tela para coordenadas baseadas no canto direito na tela
	xNovo=w/2 + (x*(w/2))
	yNovo=h/2 - (y*(h/2))
	return xNovo,yNovo
def normalizaCoordenada2(x,y,w,h):# Transforma coordanadas baseadas no centro da tela para coordenadas baseadas no canto direito na tela
	xNovo=w/2 + (x*(w/3))
	yNovo=h/2 - (y*(h/3))
	return xNovo,yNovo

def adicionaOBJ(tipo,centroX,centroY,raio,escala,rotx,rotax,roty,rotay,cor,wire):
	global OBJETOSDESENHO
	novoOBJ=[tipo,centroX,centroY,raio,escala,rotx,rotax,roty,rotay,cor,wire]
	OBJETOSDESENHO.append(novoOBJ)

def limpaOBJ():
	global OBJETOSDESENHO,OBJETOSSELECIONADOS
	OBJETOSDESENHO=[]
	OBJETOSSELECIONADOS=[]

#---------------------------------
#-------------CALLBACK
#---------------------------------

def clickMenu(button,state,x, y):
	global WIRE,OBJETOSMENU,OBJETOSSELECIONADOS,OBJETOSDESENHO,VERMELHO,AZUL,VERDE,ROSA,LARANJA,BRANCO,AMARELO
	#print(OBJETOSMENU)
	#button=0 state=0 } click botao esquerdo
	if state == 0:
		#print("Mouse click ", x,' - ', y,' - ',  button,' - ', state)

		for obj in OBJETOSMENU:
			distancia=math.sqrt(((x-obj[0])*(x-obj[0])) + ((y-obj[1])*(y-obj[1])))

			if (distancia<(obj[2]*(wMenu/2))):

				print("Clicou em ",obj[3])

				glMatrixMode(GL_MODELVIEW)
				glPushMatrix()

				if obj[3] == "Teapot":
					adicionaOBJ("Teapot",0,0,0.11,1,False,False,False,False,AMARELO,False)
				if obj[3] == "Sphere":
					adicionaOBJ("Sphere",0,0,0.11,1,False,False,False,False,AMARELO,False)
				if obj[3] == "Cube":
					adicionaOBJ("Cube",0,0,0.11,1,False,False,False,False,AMARELO,False)
				if obj[3] == "Donut":
					adicionaOBJ("Donut",0,0,0.15,1,False,False,False,False,AMARELO,False)

				if obj[3] == "VERMELHO" and len(OBJETOSSELECIONADOS)>0:
					for i in OBJETOSSELECIONADOS:
						OBJETOSDESENHO[i][9]=VERMELHO
				if obj[3] == "AZUL" and len(OBJETOSSELECIONADOS)>0:
					for i in OBJETOSSELECIONADOS:
						OBJETOSDESENHO[i][9]=AZUL
				if obj[3] == "VERDE" and len(OBJETOSSELECIONADOS)>0:
					for i in OBJETOSSELECIONADOS:
						OBJETOSDESENHO[i][9]=VERDE
				if obj[3] == "ROSA" and len(OBJETOSSELECIONADOS)>0:
					for i in OBJETOSSELECIONADOS:
						OBJETOSDESENHO[i][9]=ROSA
				if obj[3] == "AMARELO" and len(OBJETOSSELECIONADOS)>0:
					for i in OBJETOSSELECIONADOS:
						OBJETOSDESENHO[i][9]=AMARELO
				if obj[3] == "LARANJA" and len(OBJETOSSELECIONADOS)>0:
					for i in OBJETOSSELECIONADOS:
						OBJETOSDESENHO[i][9]=LARANJA

				glPopMatrix()
				glFlush()

	#glutPostRedisplay()

def clickDesenha(button,state,x, y):
	global SELECIONA,OBJETOSDESENHO,OBJETOSSELECIONADOS
	#print(OBJETOSDESENHO)
	#button=0 state=0 } click botao esquerdo
	if state == 0:
		#print("Mouse click ", x,' - ', y,' - ',  button,' - ', state)
		#print(OBJETOSDESENHO)

		for idx,obj in enumerate(OBJETOSDESENHO):
			#print(idx,'-',obj[0])
			xobj=obj[1]
			yobj=obj[2]
			xobj,yobj=normalizaCoordenada2(xobj,yobj,w,h)
			distancia=math.sqrt(((x-xobj)*(x-xobj)) + ((y-yobj)*(y-yobj)))
			raio=(obj[3]*(w/2))
			if obj[0] == "Cube":
				raio=raio/2

			#print(xobj,'-',yobj,'-',distancia,'-',raio)

			if (distancia<raio):
				print("Clicou em ",obj[0])
				if SELECIONA == True:
					print("SELECIONOU  ",obj[0], " - ",idx)
					if idx not in OBJETOSSELECIONADOS:
						OBJETOSSELECIONADOS.append(idx)

def keyboard(bkey, x, y):
	global ROTATE,LUZES,WIRE,SELECIONA,OBJETOSSELECIONADOS,OBJETOSDESENHO,ZOOM
	# Convert bytes object to string
	key = bkey.decode("utf-8")
	#print(key)
	# Allow to quit by pressing 'Esc' or 'q'
	if key == chr(27):
		sys.exit()
	if key == 'q':
		sys.exit()

	if key == 'r' or key == 'R':
		ROTATE=True
	if (key == 'a' or key == 'A') and ROTATE == True :
		for i in OBJETOSSELECIONADOS:
			OBJETOSDESENHO[i][8]-=10
			OBJETOSDESENHO[i][7]=1
	if (key == 'd' or key == 'D') and ROTATE == True :
		for i in OBJETOSSELECIONADOS:
			OBJETOSDESENHO[i][8]+=10
			OBJETOSDESENHO[i][7]=1
	if (key == 'w' or key == 'W') and ROTATE == True :
		for i in OBJETOSSELECIONADOS:
			OBJETOSDESENHO[i][6]-=10
			OBJETOSDESENHO[i][5]=1
	if (key == 's' or key == 'S') and ROTATE == True :
		for i in OBJETOSSELECIONADOS:
			OBJETOSDESENHO[i][6]+=10
			OBJETOSDESENHO[i][5]=1
	if (key == '+') :
		for i in OBJETOSSELECIONADOS:
			#OBJETOSDESENHO[i][4]+=0.2
			OBJETOSDESENHO[i][3]+=0.05
	if (key == '-') :
		for i in OBJETOSSELECIONADOS:
			#OBJETOSDESENHO[i][4]-=0.2
			OBJETOSDESENHO[i][3]-=0.05
	if (key == 'l' or key == 'L') :
		if LUZES == True:
			LUZES=False
			disable()
		else:
			LUZES=True
			enable()
	if (key == 'w' or key == 'W') and ROTATE == False :
		for i in OBJETOSSELECIONADOS:
			if OBJETOSDESENHO[i][10] == True:
				OBJETOSDESENHO[i][10]=False
			else:
				OBJETOSDESENHO[i][10]=True
	if (key == 's' or key == 'S') and ROTATE == False :
		if SELECIONA == True:
			print("SELECIONA DESATIVADO")
			SELECIONA=False
			OBJETOSSELECIONADOS=[]
		else:
			print("SELECIONA ATIVADO")
			OBJETOSSELECIONADOS=[]
			SELECIONA=True
	if key == 'c' or key == 'C':
		limpaOBJ()
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Remove everything from screen (i.e. displays all white)
		glLoadIdentity() # Reset all graphic/shape's position

	if (key == 'z' or key == 'Z') :
		ZOOM+=0.5
	if (key == 'x' or key == 'X') :
		ZOOM-=0.5

	glutPostRedisplay()

def keyboardUp(bkey, x, y):
	global ROTATE,ROTX,ROTY
	key = bkey.decode("utf-8")
	if key == 'r' or key == 'R':
		ROTATE=False

def specialKey( key, x,y):
	global OBJETOSSELECIONADOS,OBJETOSDESENHO
	if key == GLUT_KEY_LEFT:
		for i in OBJETOSSELECIONADOS:
			OBJETOSDESENHO[i][1]-=0.1
	if key ==  GLUT_KEY_RIGHT:
		for i in OBJETOSSELECIONADOS:
			OBJETOSDESENHO[i][1]+= 0.1
	if key == GLUT_KEY_UP:
		for i in OBJETOSSELECIONADOS:
			OBJETOSDESENHO[i][2]+= 0.1
	if key ==  GLUT_KEY_DOWN:
		for i in OBJETOSSELECIONADOS:
			OBJETOSDESENHO[i][2]-= 0.1
	glutPostRedisplay()

#---------------------------------
#-------------TELA DESENHO
#---------------------------------

def disable():
	glDisable(GL_LIGHTING)
	glDisable(GL_LIGHT0)
	glDisable(GL_DEPTH_TEST)

def enable():
	glEnable(GL_LIGHTING)
	glEnable(GL_LIGHT0)
	glEnable(GL_DEPTH_TEST)

def InitGL(Width, Height):

	#glMatrixMode(GL_PROJECTION)
	#gluPerspective(45.0, float(w)/float(h), 0.1, 100.0)
	#glMatrixMode(GL_MODELVIEW)

	mat_specular = [ 1.0, 1.0, 1.0, 1.0 ]
	mat_shininess = [ 50.0 ]
	light_position =  [1.0, 1.0, 1.0, 0.0]
	glClearColor (0.0, 0.0, 0.0, 0.0)
	glShadeModel (GL_SMOOTH)

	glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular)
	glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess)
	glLightfv(GL_LIGHT0, GL_POSITION, light_position)

	glEnable(GL_COLOR_MATERIAL)
	glEnable(GL_LIGHTING)
	glEnable(GL_LIGHT0)
	glEnable(GL_DEPTH_TEST)

def reshape ( w,  h):
	if LUZES == True:
		glViewport (0, 0, w, h)
		glMatrixMode (GL_PROJECTION)
		glLoadIdentity()
		if (w <= h):
			glOrtho (-1.5, 1.5, -1.5* h/ w, 1.5* h/ w, -10.0, 10.0)
		else:
			glOrtho (-1.5* w/ h, 1.5* w/ h, -1.5, 1.5, -10.0, 10.0)
		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()

def TelaDesenho():
	global WIRE,OBJETOSDESENHO,OBJETOSSELECIONADOS
	#glClearColor(1.0, 0.0, 3.0, 0.0) # muda cor do backgroud

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Remove everything from screen (i.e. displays all white)
	glLoadIdentity() # Reset all graphic/shape's position
	#glOrtho(0.0, w, 0.0, h, 0.0, 1.0) # remapeia as cordenadas
	if REDISPLAY == True:
		glutPostRedisplay()

	glScalef(ZOOM, ZOOM, ZOOM)
	#[tipo,centroX,centroY,raio,escala,rotx,rotax,roty,rotay,cor,wire]
	for idx,obj in enumerate(OBJETOSDESENHO):
		CORATUAL=obj[9]
		RAIO=obj[3]
		POSICAOX=obj[1]
		POSICAOY=obj[2]
		ESCALA=obj[4]
		ROTAX=obj[6]
		ROTX=obj[5]
		ROTAY=obj[8]
		ROTY=obj[7]
		WIRE=obj[10]
		tipo=obj[0]

		if idx in OBJETOSSELECIONADOS:
			CORATUAL=BRANCO

		glMatrixMode(GL_MODELVIEW)
		glPushMatrix()

		glColor3f(CORATUAL[0],CORATUAL[1],CORATUAL[2])
		glTranslatef(POSICAOX,POSICAOY,0.0)
		glScalef(ESCALA, ESCALA, ESCALA)

		if ROTX == 1:
			glRotatef(ROTAX,ROTX,0,0.0)
		if ROTY == 1:
			glRotatef(ROTAY,0,ROTY,0.0)

		if tipo == "Teapot" and WIRE == True:
			glutWireTeapot(RAIO)
		if tipo == "Teapot" and WIRE == False:
			glutSolidTeapot(RAIO)

		if tipo == "Sphere" and WIRE == False:
			glutSolidSphere(RAIO,40,40)
		if tipo == "Sphere" and WIRE == True:
			glutWireSphere(RAIO,40,40)

		if tipo == "Donut" and WIRE == False:
			glutSolidTorus(RAIO/2,RAIO,40,40)
		if tipo == "Donut" and WIRE == True:
			glutWireTorus(RAIO/2,RAIO,40,40)

		if tipo == "Cube" and WIRE == False:
			glutSolidCube(RAIO)
		if tipo == "Cube" and WIRE == True:
			glutWireCube(RAIO)

		glPopMatrix()
		glFlush()

	glutSwapBuffers() # limpa o buffer (buffer duplo para agilidade). SE FOR 1 BUFFER DL SINGLE

#---------------------------------
#-------------TELA MENU
#---------------------------------

def drawTeapot():
	glLoadIdentity()
	glTranslatef(-0.40,0.80,0.0)
	glutSolidTeapot(0.1)
	glFlush()

	x,y=normalizaCoordenada(-0.40,0.80,wMenu, hMenu)
	newOBJ=[x,y,0.11,"Teapot"]
	OBJETOSMENU.append(newOBJ)

def drawCube():
	glLoadIdentity()
	glTranslatef(0.40,0.80,0.0)
	glutSolidCube(0.2)
	glFlush()

	x,y=normalizaCoordenada(0.40,0.80,wMenu, hMenu)
	newOBJ=[x,y,0.11,"Cube"]
	OBJETOSMENU.append(newOBJ)

def drawSphere():
	glLoadIdentity()
	glTranslatef(-0.40,0.40,0.0)
	glutSolidSphere(0.11,40,40)
	glFlush()

	x,y=normalizaCoordenada(-0.40,0.40,wMenu, hMenu)
	newOBJ=[x,y,0.11,"Sphere"]
	OBJETOSMENU.append(newOBJ)

def drawDonut():
	glLoadIdentity()
	glTranslatef(0.40,0.40,0.0)
	glutSolidTorus(0.05,0.1,40,40)
	glFlush()

	x,y=normalizaCoordenada(0.40,0.40,wMenu, hMenu)
	newOBJ=[x,y,0.15,"Donut"]
	OBJETOSMENU.append(newOBJ)

def circuloDeCor(x,y,cor,NomeCor):
	glColor3f(cor[0],cor[1],cor[2])
	glLoadIdentity()
	glTranslatef(x,y,0.0)
	#glScalef(2.5, 1.0, 1.0)
	glutSolidSphere(0.2,40,40)
	glFlush()

	xN,yN=normalizaCoordenada(x,y,wMenu, hMenu)
	newOBJ=[xN,yN,0.15,NomeCor] #TeaPot
	OBJETOSMENU.append(newOBJ)

def menuCores():

	circuloDeCor(-0.70,-0.3,VERMELHO,"VERMELHO")
	circuloDeCor(0,-0.3,AZUL,"AZUL")
	circuloDeCor(0.7,-0.3,VERDE,"VERDE")

	circuloDeCor(-0.70,-0.8,LARANJA,"LARANJA")
	circuloDeCor(0,-0.8,ROSA,"ROSA")
	circuloDeCor(0.7,-0.8,AMARELO,"AMARELO")

def TelaMenu():
	global OBJETOSMENU
	OBJETOSMENU=[]
	glClearColor(0.0, 0.5, 0.5, 0.0) # muda cor do backgroud
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Remove everything from screen (i.e. displays all white)
	glLoadIdentity() # Reset all graphic/shape's position

	drawTeapot()
	drawCube()
	drawSphere()
	drawDonut()
	menuCores()

	glutSwapBuffers() # limpa o buffer (buffer duplo para agilidade). SE FOR 1 BUFFER DL SINGLE

#---------------------------------
#-------------TELA INSTRUÇÕES
#---------------------------------

def telaInstrucoes():
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
	glClearColor(0, 0, 0, 0) # muda cor do backgroud

	drawText()

	glutSwapBuffers() # limpa o buffer (buffer duplo para agilidade). SE FOR 1 BUFFER DL SINGLE

def text(x,y,text):
	glColor3f(1.0, 1.0, 1.0)
	glRasterPos2f(x, y)
	for t in text:
		glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, ord(t))

def drawText(textString="Teste"):
	text(-1.0, 0.8,"Teclas:")
	text(-0.8, 0.6,"S          - Entra/Sai do modo Seleção de Objeto")
	text(-0.8, 0.4,"L          - Muda iluminacao")
	text(-0.8, 0.2,"C          - Limpa tela de desenho")
	text(-0.8, 0.0,"R+(A,W,S,D)- Rotaciona Objeto(s) selecionado(s)")
	text(-0.8, -0.2,"Z,X       - Aumenta/diminui ZOOM")
	text(-0.8, -0.4,"-,+       - Aumenta/diminui Objeto(s) selecionado(s)")
	text(-0.8, -0.6,"W         - Tira/coloca em modo Wire Objeto(s) selecionado(s)")
	text(-0.8, -0.8,"Q         - Sair")

if __name__ == "__main__":
	#Inicializacao
	glutInit() #inicializa o ambiente

	#Janela Instruções
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) # Set the display mode to be colored (RGBA - SISTEMA DE CORES)(DOUBLE - BUFFER DUPLO)(DEPTH - PARA USAR ALGORITMO DE PROFUNDIDADE EM 3D ZBUFFER)
	glutInitWindowSize(500, 200) # tamanho da janela
	glutInitWindowPosition(500, 800) # posicao da janela
	glutCreateWindow("instruções") # cria janela com titulo
	glutDisplayFunc(telaInstrucoes)

	#Janela Menu
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) # Set the display mode to be colored (RGBA - SISTEMA DE CORES)(DOUBLE - BUFFER DUPLO)(DEPTH - PARA USAR ALGORITMO DE PROFUNDIDADE EM 3D ZBUFFER)
	glutInitWindowSize(wMenu, hMenu) # tamanho da janela
	glutInitWindowPosition(300, 100) # posicao da janela
	glutCreateWindow("Menu") # cria janela com titulo
	glutDisplayFunc(TelaMenu)
	glutMouseFunc(clickMenu)

	#Janela De desenho
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) # Set the display mode to be colored (RGBA - SISTEMA DE CORES)(DOUBLE - BUFFER DUPLO)(DEPTH - PARA USAR ALGORITMO DE PROFUNDIDADE EM 3D ZBUFFER)
	glutInitWindowSize(w, h) # tamanho da janela
	glutInitWindowPosition(500, 100) # posicao da janela
	glutCreateWindow("Tela de desenho") # cria janela com titulo
	InitGL(w, h)
	glutDisplayFunc(TelaDesenho)
	glutReshapeFunc(reshape)
	glutKeyboardFunc(keyboard)
	glutKeyboardUpFunc(keyboardUp)
	glutSpecialFunc(specialKey)
	glutMouseFunc(clickDesenha)

	glutMainLoop() # coloca a janela criada em loop


from funkcja import wartosc_funkcji, wzor_funkcji
import sympy as sp  # do tworzenia wzorów funkcji z parametrem oraz obliczeń pochodnych

def metoda_bisekcji(poczatek_przedzialu, koniec_przedzialu, epsilon, iteracje, wybor):
    """Przyblizone rozwiazanie f(x)=0 z uzyciem metody bisekcji

        Parametry
        ----------
        poczatek_przedzialu : int
            wartosc poczatku przedzialu badanej funkcji
        koniec_przedzialu : int
            wartosc konca przedzialu badanej funkcji
        epsilon : float
            zadana dokladnosc obliczen
        iteracje : int
            zadana maksymalna liczba iteracji
        wybor : String
            wybor funkcji między A, B, C lub D

        Dane wyjsciowe
        -------
        x1 : float
            rozwiazanie funkcji
        """
    x1 = 0
    if wartosc_funkcji(poczatek_przedzialu, wybor) * wartosc_funkcji(koniec_przedzialu, wybor) > 0:
        # założenie, które musi być spełnione aby można było skorzystać z metody bisekcji
        return False
    else:
        if iteracje <= 0:       # jeśli użytkownik wybierze obliczenia wg kryterium dokladnosci epsilon
            arg_x = sp.Symbol('x')
            df = sp.diff(wzor_funkcji(wybor))  # obliczenie pochodnej funkcji
            n = 1       # zmienna iteracyjna
            while True:  # dopóki nie uzyskamy zadanej dokładności
                x1 = (poczatek_przedzialu + koniec_przedzialu) / 2      # nadpisywanie kolejnej wartosci argumentu
                dfxn = df.subs(arg_x, x1)       # obliczenie wartosci pochodnej dla argumentu
                if abs(wartosc_funkcji(x1, wybor)) <= epsilon and (abs(dfxn) > epsilon):
                    # jeżeli znaleźliśmy miejsce zerowe mniejsze bądź równe przybliżeniu zera
                    # oraz funkcja w tym miejscu nie dąży do stałej wartości
                    print("Metoda bisekcji: znaleziono rozwiazanie po " + str(n) + " iteracjach.")
                    return x1
                elif wartosc_funkcji(x1, wybor) * wartosc_funkcji(poczatek_przedzialu, wybor) < 0:
                    koniec_przedzialu = x1  # nadpisywanie prawego krańca przedziału
                else:
                    poczatek_przedzialu = x1  # nadpisywanie lewego krańca przedziału
                n += 1
        else:       # jeśli użytkownik wybierze obliczenia wg kryterium liczby iteracji
            for n in range(iteracje):  # dopóki nie uzyskamy zadanej liczby iteracji
                x1 = (poczatek_przedzialu + koniec_przedzialu) / 2      # nadpisywanie argumentu funkcji
                if wartosc_funkcji(x1, wybor) == 0.0:       # gdy rozwiązaniem funkcji jest zero
                    print("Metoda bisekcji: znaleziono dokladne rozwiazanie epsilon= 0 po {} iteracjach.".format(n + 1))
                    return x1
                if wartosc_funkcji(x1, wybor) * wartosc_funkcji(poczatek_przedzialu, wybor) < 0:
                    koniec_przedzialu = x1  # nadpisywanie prawego krańca przedziału
                else:
                    poczatek_przedzialu = x1  # nadpisywanie lewego krańca przedziału
            epsilon = abs(wartosc_funkcji(x1, wybor))   # obliczenie dokładności obliczeń
            print("Metoda bisekcji: "
                  "znaleziono rozwiazanie po {0} iteracjach z dokladnoscia epsilon={1}".format(iteracje, epsilon))
            return x1    # zwracanie znalezionego miejsca zerowego

def newton(poczatek_przedzialu, koniec_przedzialu, epsilon, max_iter, wybor):
    """Przyblizone rozwiazanie f(x)=0 z uzyciem metody Newtona

    Parametry
    ----------
    epsilon : float
        warunek stopu abs(f(x)) < epsilon.
    max_iter : int
        maksymalna liczba iteracji algorytmu
    wybor : String
        wybor funkcji spomiędzy ["A", "B", "C", "D"]

    Dane wyjsciowe
    -------
    xn : float
        Implementacja metody Newtona: oblicza aproksymacje liniowa
        f(x) dla xn i znajduje x:
            x = xn - f(xn)/Df(xn)
        Kontynuacja dopoki abs(f(xn)) < epsilon i zwrot xn.
        Jesli Df(xn) == 0, zwroc None. Jesli liczba iteracji przekroczy max_iter, zwroc None.
    """

    if wartosc_funkcji(poczatek_przedzialu, wybor) * wartosc_funkcji(koniec_przedzialu, wybor) > 0:
        # sprawdzenie założeń metody Newtona
        return False
    arg_x = sp.Symbol('x')
    df = sp.diff(wzor_funkcji(wybor))       # obliczenie pochodnej wybranej funkcji
    if abs(df.subs(arg_x, poczatek_przedzialu)) < abs(df.subs(arg_x, koniec_przedzialu)):
        # blok instrukcji warunkowych ustalajacych w jakim miejscu rozpoczac algorytm,
        # eliminujemy miejsca, w których funkcja dąży do stałej wartości
        xn = koniec_przedzialu
    elif abs(df.subs(arg_x, poczatek_przedzialu)) > abs(df.subs(arg_x, koniec_przedzialu)):
        xn = poczatek_przedzialu
    else:
        xn = (poczatek_przedzialu + koniec_przedzialu) / 2
    if max_iter != 0:   # obliczenia dla wyboru kryterium liczby iteracji
        for n in range(0, max_iter):
            fxn = wartosc_funkcji(xn, wybor)  # obliczenie wartosci funkcji dla argumentu x
            dfxn = df.subs(arg_x, xn)   # obliczenie wartosci pochodnej dla argumentu x
            xn = xn - float(fxn / dfxn)  # kolejne wartosci argumentów
        epsilon = abs(wartosc_funkcji(xn, wybor))       # obliczenie dokladnosci epsilon
        print("""Metoda stycznych:
            znaleziono rozwiazanie po {0} iteracjach z dokladnoscia epsilon={1}""".format(max_iter, epsilon))
        return xn
    else:   # obliczenia dla wyboru kryterium dokladnosci
        n = 0   # zmienna iteracyjna
        while True:
            fxn = wartosc_funkcji(xn, wybor)    # wartosc funkcji dla argumentu x
            dfxn = df.subs(arg_x, xn)   # obliczenie wartosci pochodnej dla argumentu x
            if (abs(fxn) < epsilon) and (abs(dfxn) > epsilon):
                # gdy wartosc funkcji jest z pewna dokladnoscia rowna zero oraz funkcja w tym punkcie nie dąży do zera
                print('Metoda Newtona: znaleziono rozwiazanie po ', n + 1, 'iteracjach.')
                return xn
            xn = xn - float(fxn / dfxn)     # kolejna wartość argumentu
            n += 1  # inkrementacja zmiennej iteracyjnej


##
# A small pygame program that displays a circle on a screen.
#
# Author: Nicholas O'Kelley
# Date: Feb. 6th 2020
##

import pygame

global screen
global running
BLACK = (0, 0, 0)

def main():
    # The background color that sets the R,G,B colors to white
    background_color = (255, 255, 255)

    # The width variable
    width = 640
    # The height variable
    height = 480

    # The screen variable that sets display using the width and height variables
    screen = pygame.display.set_mode((width, height))

    # Sets the title bar of the screen
    pygame.display.set_caption('Building a Circle')

    # Fills the screen with the color
    screen.fill(background_color)

    # This command udpates the whole screen
    pygame.display.flip()

    # Boolean for the state of the program
    running = True

    # Run until false
    while running:

        event = pygame.event.get()

        # Will update to false when the user clicks the X
        for event in event:

            if event.type == pygame.MOUSEBUTTONDOWN:
                pygame.draw.circle(screen, BLACK, (150, 200), 25, 5)
                pygame.display.update()

            if event.type == pygame.QUIT:
                running = False

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
import scrapy
import pickle
import os
from datetime import datetime
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from ArticleSpider.utils.common import get_md5
from ArticleSpider.settings import BASE_DIR
from ArticleSpider.items import LagouJobItemLoader,LagouJobItem

class LagouSpider(CrawlSpider):
    name = 'lagou'
    allowed_domains = ['www.lagou.com']
    start_urls = ['https://www.lagou.com/']

    rules = (
        Rule(LinkExtractor(allow=("zhaopin/.*",)), follow=True),
        Rule(LinkExtractor(allow=("gongsi/j\d+.html",)), follow=True),
        Rule(LinkExtractor(allow=r'jobs/\d+.html'), callback='parse_job', follow=True),
    )

    # def start_requests(self):
    #     #去使用selenium模拟登录后拿到cookie交给scrapy的request使用
    #     #1、通过selenium模拟登录
    #     #从文件中读取cookies
    #     cookies = []
    #     if os.path.exists(BASE_DIR+"/cookies/lagou.cookies"):
    #         cookies = pickle.load(open(BASE_DIR+"/cookies/lagou.cookies", "rb"))
    #
    #     if not cookies:
    #         from selenium import webdriver
    #         browser = webdriver.Chrome(
    #             executable_path="C:/Users/Administrator/Downloads/spider-master/ArticleSpider/chrome_nocdc/chromedriver.exe"
    #         )
    #         browser.get("https://passport.lagou.com/login/login.html")
    #         browser.find_element_by_css_selector(".form_body .input.input_white").send_keys("1396951044@qq.com")
    #         browser.find_element_by_css_selector('.form_body input[type="password"]').send_keys("15507925675xiao")
    #         browser.find_element_by_css_selector('div[data-view="passwordLogin"] input.btn_lg').click()
    #         import time
    #         time.sleep(10)
    #         cookies = browser.get_cookies()
    #         #写入cookie到文件中
    #         pickle.dump(cookies, open(BASE_DIR+"/cookies/lagou.cookies", "wb"))
    #
    #     cookie_dict = {}
    #     for cookie in cookies:
    #         cookie_dict[cookie["name"]] = cookie["value"]
    #
    #     for url in self.start_urls:
    #         yield scrapy.Request(url, dont_filter=True, cookies=cookie_dict)

    def parse_job(self, response):
        # 解析拉钩网的职位
        item_loader = LagouJobItemLoader(item=LagouJobItem(), response=response)

        item_loader.add_css("title",".job-name::attr(title)")
        item_loader.add_value("url", response.url)
        item_loader.add_value("url_object_id", get_md5(response.url))
        item_loader.add_css("salary",".job_request .salary::text")
        item_loader.add_xpath("job_city", "//*[@class='job_request']/h3/span[2]/text()")
        item_loader.add_xpath("work_years", "//*[@class='job_request']/h3/span[3]/text()")
        item_loader.add_xpath("degree_need", "//*[@class='job_request']/h3/span[4]/text()")
        item_loader.add_xpath("job_type", "//*[@class='job_request']/h3/span[5]/text()")

        item_loader.add_css("tags", '.position-label li::text')
        item_loader.add_css("publish_time", ".publish_time::text")
        item_loader.add_css("job_advantage", ".job-advantage p::text")
        item_loader.add_css("job_desc", ".job_bt div")
        item_loader.add_css("job_addr", ".work_addr")
        item_loader.add_css("company_name", "#job_company dt a img::attr(alt)")
        item_loader.add_css("company_url", "#job_company dt a::attr(href)")
        item_loader.add_value("crawl_time", datetime.now())

        job_item = item_loader.load_item()

        return job_item


import click
from brownie import (
                     ChadgerRegistry, DeterministicFactory, accounts, network, web3)

from config import *

def connect_account():
    click.echo(f"You are using the '{network.show_active()}' network")
    dev = accounts.load(click.prompt(
        "Account", type=click.Choice(accounts.load())))
    click.echo(f"You are using: 'dev' [{dev.address}]")
    return dev

def main():
    if click.confirm("Deploy New Registry"):
        dev = connect_account()

        vault_impl = "0xeCd8b51542CeE782d964bf25E2D0Ae1A99B2b96A"
        assert len(vault_impl) != 0

        deterministic_factory = "0xC497AD0000790cfE90F4aD107501eFE7c5762B36"
        assert len(deterministic_factory) != 0

        chadger_registry_logic = ""
        if len(chadger_registry_logic) == 0:
            # deploy the logic contract
            chadger_registry_logic = ChadgerRegistry.deploy({"from": dev}, publish_source=True)
        else:
            chadger_registry_logic = ChadgerRegistry.at(chadger_registry_logic)

        deterministic_factory = DeterministicFactory.at(deterministic_factory)

        args = [dev.address, vault_impl]
        data = chadger_registry_logic.initialize.encode_input(*args)
        salt = web3.keccak(text=chadger_registry_salt)
        # deterministic deploy chadger registry using factory
        deterministic_factory.deploy(salt, 0, chadger_registry_logic, "0xbf50C5ADBe89b8C61DF4e0D8aFC44CAF87343C00",data, {"from": dev} )


#!/usr/bin/python
from __future__ import unicode_literals

import mara
from mara import events
service = mara.Service()

# Set up a filter for write_all to filter to users who have logged in,
# otherwise they'll see things on the login prompt
def filter_to_users(service, clients, **kwargs):
    return (c for c in clients if hasattr(c, 'username'))
service.filter_all = filter_to_users

@service.listen(events.Connect)
def connect(event):
    """Deal with connection"""
    event.client.write('Welcome. What is your name? ', newline=False)
    username = yield
    event.client.username = username
    event.client.write('Welcome, %s' % username)
    service.write_all('-- %s has connected --' % username, exclude=event.client)

@service.listen(events.Disconnect)
def disconnect(event):
    """Deal with disconnection"""
    # If the client doesn't have a username, it hasn't connected
    if not hasattr(event.client, 'username'):
        return
    service.write_all('-- %s has disconnected --' % event.client.username)

# This example uses a simple custom command parser
# Define some constants for the commands
COMMAND_SAY     = ''
COMMAND_EMOTE   = 'me'
COMMAND_WHO     = 'who'
COMMAND_QUIT    = 'quit'

@service.listen(events.Receive)
def receive(event):
    """Deal with data from client"""
    # If the client doesn't have a username, it hasn't connected
    if not hasattr(event.client, 'username'):
        return

    # Parse input
    cmd = COMMAND_SAY
    data = event.data
    if data.startswith('/'):
        if ' ' in data:
            cmd, data = data[1:].split(' ', 1)
        else:
            cmd, data = data[1:], ''
        cmd = cmd.lower()

    # Handle commands
    if cmd == COMMAND_SAY:
        service.write_all('%s> %s' % (event.client.username, data))
    elif cmd == COMMAND_EMOTE:
        service.write_all('%s %s' % (event.client.username, data))
    elif cmd == COMMAND_WHO:
        clients = ['  %s' % n for n in sorted(c.username for c in service.clients)]
        event.client.write('Users here at the moment:', *clients)
    elif cmd == COMMAND_QUIT:
        event.client.write('Goodbye!')
        event.client.close()
    else:
        event.client.write('Unknown command "%s"' % cmd)

if __name__ == '__main__': # pragma: no cover
    service.run(
        host='0.0.0.0',
        post=9000,
    )


# This is a sample Python script.
import pygame, sys, random

pygame.init()
screen = pygame.display.set_mode((1280,720))
clock = pygame.time.Clock()
pygame.mouse.set_visible(False)

# Global variables

## Background

wood_bg = pygame.image.load('assets/bg_wood.png');
land_bg = pygame.image.load('assets/grass2.png');
water_bg = pygame.image.load('assets/water1.png');
cloud1 = pygame.image.load('assets/cloud1.png');
cloud2 = pygame.image.load('assets/cloud2.png');

## X,Y coord and speed
land_speed = 1
water_speed = 2
land_pos_y = 560
water_pos_y = 640

## Cursor

crosshair = pygame.image.load('assets/crosshair.png')

## Ducks

duck_surface = pygame.image.load('assets/duck.png')
duck_list = []

for duck in range(5):
        duck_pos_x = random.randrange(50,1200)
        duck_pos_y = random.randrange(120,500)
        duck_rect = duck_surface.get_rect(center = (duck_pos_x,duck_pos_y))
        duck_list.append(duck_rect)

## Game font

game_font = pygame.font.Font(None, 120)
text_surface = game_font.render("You Won!!!", True, (255,255,255))
text_rect = text_surface.get_rect(center = (640,360))

# Draw background

def ground_animation():

    global land_pos_y, land_speed;

    if land_pos_y <= 520 or land_pos_y >= 600:
        land_speed *= -1
    for x in range(0,1280,132):
        screen.blit(land_bg, (x, land_pos_y))
    land_pos_y += land_speed;

def water_animation():

    global water_pos_y, water_speed;

    if water_pos_y <= 620 or water_pos_y >= 680:
        water_speed *= -1
    for x in range(0,1280,132):
        screen.blit(water_bg, (x, water_pos_y))
    water_pos_y += water_speed;

def draw_background():

    for y in range(0,720,256):
            for x in range(0,1280,256):
                screen.blit(wood_bg, (x,y))

    screen.blit(cloud1, (100,50))
    screen.blit(cloud2, (300,160))
    screen.blit(cloud2, (900, 100))

def generate_ducks():

    for duck_rect in duck_list:
        screen.blit(duck_surface, duck_rect)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.MOUSEMOTION:
            crosshair_rect = crosshair.get_rect(center = event.pos)

        if event.type == pygame.MOUSEBUTTONDOWN:
            for index, duck_rect in enumerate(duck_list):
                if duck_rect.collidepoint(event.pos):
                    duck_list.remove(duck_list[index])

    # Background and duck generation

    draw_background()
    generate_ducks()
    ground_animation()
    water_animation()

    # Draw cursor / crosshair

    screen.blit(crosshair, crosshair_rect)

    # Game over

    if len(duck_list) == 0:
            screen.blit(text_surface, text_rect)

    pygame.display.update()
    clock.tick(120)
    #Setting the frame rate to 120 frames / second


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

import re
import sys
from collections import defaultdict

def read_giga_list(path):
    giga_freq = {}
    with open(path) as fr:
        for line in fr:
            line = line.strip().split(' ')
            giga_freq[line[0]] = line[1]
    return giga_freq

def read_same_words(path):
    same_words = []
    with open(path) as fr:
        for line in fr:
            line = line.strip()
            if len(line) == 1 or re.search(r"^[0-9, a-z, A-Z]", line):
                continue
            same_words.append(line.strip())
    return same_words

def read_hownet(path):
    hownet = defaultdict(list)
    with open(path) as fr:
        for line in fr:
            line = line.strip().split(' ||| ')
            if len(line) != 2:
                continue
            word = line[0]
            sememes = line[1].split(' ')
            hownet[word].append(sememes)
    return hownet

def sort_words(giga_freq, words, hownet):
    filter_sememes = [
        'cardinal|基数', 'ordinal|序数', 'FuncWord|功能词', 'ProperName|专',
        'biology|生物学', 'math|数学', 'chemical|化学物', 'physics|物理',
        'physiology|生理学', 'politics|政', 'language|语言', 'stone|土石',
        'chemistry|化学'
    ]
    filter_start_with = [
        'FlowerGrass|花草', 'disease|疾病', 'InsectWorm|虫', 'beast|走兽', 'tree|树',
        'fish|鱼', 'bird|禽', 'crop|庄稼', 'medicine|药物', 'AlgaeFungi|低植',
        'bacteria|微生物', 'celestial|天体', 'metal|金属', 'Unit|单位', 'fruit|水果',
        'money|货币'
    ]
    filter_as_one = [['human|人', 'RelatingToCountry|与特定国家相关']]
    words_match = []
    words_not_match = []
    for w in words:
        ignore_word = False
        sememes = hownet[w]
        for sememe in sememes:
            for s in filter_as_one:
                if s == sememe:
                    ignore_word = True
            for s in filter_sememes:
                if s in sememe:
                    ignore_word = True
            for s in filter_start_with:
                if s == sememe[0]:
                    ignore_word = True
        if ignore_word:
            continue
        if w in giga_freq:
            freq = int(giga_freq[w])
            words_match.append((w, freq))
        else:
            words_not_match.append(w)

    words_match.sort(key=lambda x: x[1], reverse=True)
    print('matched: ', len(words_match))
    print('not matched: ', len(words_not_match))
    sorted_words = [w[0] for w in words_match]

    # with open('matched.txt', 'w') as fw_m:
    #     fw_m.write('\n'.join(sorted_words))
    # with open('not_match.txt', 'w') as fw_nm:
    #     fw_nm.write('\n'.join(words_not_match))

    sorted_words.extend(words_not_match)
    return sorted_words

def write2file(path, sorted_words):
    with open(path, 'w') as fw:
        fw.write('\n'.join(sorted_words))

def main(argv=None):
    if argv is None:
        argv = sys.argv
        if len(argv) != 5:
            raise ValueError("Arg nums not match.")
    giga_freq = read_giga_list(argv[1])
    same_words = read_same_words(argv[2])
    hownet = read_hownet(argv[3])
    write_path = argv[4]
    sorted_words = sort_words(giga_freq, same_words, hownet)
    write2file(write_path, sorted_words)
    return 0

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


import rigidbody.kinematics as kine
import numpy as np
from dataclasses import dataclass

@dataclass
class RigidBody:
    mass: float
    inertia: np.ndarray
    center_mass_position: np.ndarray

def corriolis_matrix_two_d(body_velocity: np.ndarray, rb: RigidBody):
    """

    Parameters
    ----------
    body_velocity
    rb

    Returns
    -------

    """
    m = rb.mass
    vx = body_velocity[0]
    vy = body_velocity[1]
    psi_dot = body_velocity[2]
    rx = rb.center_mass_position[0]
    ry = rb.center_mass_position[1]

    return np.array([[0, 0, -m * (vy + rx * psi_dot)],
                     [0, 0, m * (vx - ry * psi_dot)],
                     [m * (vy + rx * psi_dot), -m * (vx - ry * psi_dot), 0]])

def mass_matrix_two_d(rb: RigidBody):
    """

    Parameters
    ----------
    rb

    Returns
    -------

    """
    m = rb.mass
    rx = rb.center_mass_position[0]
    ry = rb.center_mass_position[1]
    Iz = rb.inertia[0]
    return np.array([[m, 0, -m * ry],
                     [0, m, m * rx],
                     [-m * ry, m * rx, Iz]])

def rigid_body_dynamics_two_d(state: np.ndarray, force_torque: np.ndarray, rb: RigidBody):
    """

    Parameters
    ----------
    state
    force_torque
    rb

    Returns
    -------

    """
    position = state[:3]
    body_velocity = state[3:]
    mass_mat = mass_matrix_two_d(rb)
    corr_mat = corriolis_matrix_two_d(body_velocity, rb)
    position_dot = kine.inverse_analytical_jacobian_2d(position[-1]) @ body_velocity
    body_velocity_dot = np.linalg.solve(mass_mat, force_torque - corr_mat @ body_velocity)
    return np.concatenate((position_dot, body_velocity_dot))


#Self check 2.2.1

'''
Write two Python functions to find the minimum number in a list. The first function should
compare each number to every other number on the list. 𝑂(𝑛^2). The second function should be
linear 𝑂(𝑛).
'''

list_objective = [1,2,3,4,5,6]

def min_quadratic(numbers):
    res = numbers[0]
    for i in range(len(numbers)):
        for j in range(i, len(numbers)):
            if numbers[j] < res:
                res = numbers[j]
    return res

def min_lineal(numbers):
    res = numbers[0]
    for num in numbers:
        if num < res:
            res = num
    return res

print(min_quadratic(list_objective))
print(min_lineal(list_objective))


from tkinter import *

root=Tk()

#variable que tiene valores de tipo entero
varOpcion=IntVar()

def imprimir():
    #print(varOpcion.get())
    if varOpcion.get() == 1:
       etiqueta.config(text="has elegido masculino")

    else:
        etiqueta.config(text="has elegido femenino")

Label(root, text="Género:").pack()

#se asignan valores y se almacenan en la variable varOpcion
Radiobutton(root, text="Masculino", variable=varOpcion, value=1, command=imprimir).pack()

Radiobutton(root, text="Femenino", variable=varOpcion, value=2, command=imprimir).pack()

etiqueta=Label(root)
etiqueta.pack()

root.mainloop()


"""Constraint solver allows to define constraint between two or more different
variables and keep this constraint always true when one or more of the
constrained variables change. For example, one may want to keep two variables
always equal.

Variables change and at some point of time we want to make all
constraints valid again. This process is called solving constraints.

Gaphas' solver allows to define constraints between Variable
instances.  Constraint classes are defined in `gaphas.constraint`
module.

How It Works
------------
Every constraint contains list of variables and has to be registered
in solver object. Variables change (`Variable.dirty()`,
`Solver.request_resolve()` methods) and their constraints are marked
by solver as dirty. To solve constraints, solver loops through dirty
constraints and asks constraint for
a variable (called weakest variable), which

- has the lowest strength
- or if there are many variables with the same, lowest strength value
  return first unchanged variable with lowest strength
- or if there is no unchanged, then return the first changed with the
  lowest strength

(weakest variable invariants defined above)

Having weakest variable (`constraint.Constraint.weakest()` method)
every constraint is being asked to solve itself
(`constraint.Constraint.solve_for()` method) changing appropriate
variables to make the constraint valid again.
"""
import functools
from typing import Callable, Collection, List, Optional, Set

from gaphas.solver.constraint import Constraint, ContainsConstraints

class Solver:
    """Solve constraints.

    A constraint should have accompanying variables.
    """

    def __init__(self, resolve_limit: int = 16) -> None:
        # a dict of constraint -> name/variable mappings
        self._constraints: Set[Constraint] = set()
        self._marked_cons: List[Constraint] = []
        self._solving = False
        self._resolve_limit = resolve_limit
        self._handlers: Set[Callable[[Constraint], None]] = set()

    def add_handler(self, handler: Callable[[Constraint], None]) -> None:
        """Add a callback handler, triggered when a constraint is resolved."""
        self._handlers.add(handler)

    def remove_handler(self, handler: Callable[[Constraint], None]) -> None:
        """Remove a previously assigned handler."""
        self._handlers.discard(handler)

    def _notify(self, constraint: Constraint) -> None:
        my_constraint = self._find_containing_constraint(constraint)
        for handler in self._handlers:
            handler(my_constraint)

    @functools.lru_cache()
    def _find_containing_constraint(self, constraint: Constraint) -> Constraint:
        return find_containing_constraint(constraint, self._constraints) or constraint

    @property
    def constraints(self) -> Collection[Constraint]:
        return self._constraints

    def add_constraint(self, constraint: Constraint) -> Constraint:
        """Add a constraint. The actual constraint is returned, so the
        constraint can be removed later on.

        Example:

        >>> from gaphas.constraint import EquationConstraint
        >>> s = Solver()
        >>> a, b = Variable(), Variable(2.0)
        >>> s.add_constraint(EquationConstraint(lambda a, b: a -b, a=a, b=b))
        EquationConstraint(<lambda>, a=Variable(0, 20), b=Variable(2, 20))
        >>> len(s._constraints)
        1
        >>> a.value
        0.0
        >>> b.value
        2.0
        >>> len(s._constraints)
        1
        """
        assert constraint, f"No constraint ({constraint})"
        self._constraints.add(constraint)
        self._marked_cons.append(constraint)
        constraint.add_handler(self.request_resolve_constraint)
        return constraint

    def remove_constraint(self, constraint: Constraint) -> None:
        """Remove a constraint from the solver.

        >>> from gaphas.constraint import EquationConstraint
        >>> s = Solver()
        >>> a, b = Variable(), Variable(2.0)
        >>> c = s.add_constraint(EquationConstraint(lambda a, b: a -b, a=a, b=b))
        >>> c
        EquationConstraint(<lambda>, a=Variable(0, 20), b=Variable(2, 20))
        >>> s.remove_constraint(c)
        >>> s._marked_cons
        []
        >>> s._constraints
        set()

        Removing a constraint twice has no effect:

        >>> s.remove_constraint(c)
        """
        assert constraint, f"No constraint ({constraint})"
        constraint.remove_handler(self.request_resolve_constraint)
        self._constraints.discard(constraint)
        while constraint in self._marked_cons:
            self._marked_cons.remove(constraint)

    def request_resolve_constraint(self, c: Constraint) -> None:
        """Request resolving a constraint."""
        if not self._solving:
            if c in self._marked_cons:
                self._marked_cons.remove(c)
            self._marked_cons.append(c)
        elif self._marked_cons.count(c) < self._resolve_limit:
            self._marked_cons.append(c)

    @property
    def needs_solving(self) -> bool:
        """Return if there are constraints that need solving."""
        return bool(self._marked_cons)

    def solve(self) -> None:  # sourcery skip: while-to-for
        """
        Example:

        >>> from gaphas.constraint import EquationConstraint
        >>> a, b, c = Variable(1.0), Variable(2.0), Variable(3.0)
        >>> s = Solver()
        >>> s.add_constraint(EquationConstraint(lambda a,b: a+b, a=a, b=b))
        EquationConstraint(<lambda>, a=Variable(1, 20), b=Variable(2, 20))
        >>> a.value = 5.0
        >>> s.solve()
        >>> len(s._marked_cons)
        0
        >>> b._value
        -5.0
        >>> s.add_constraint(EquationConstraint(lambda a,b: a+b, a=b, b=c))
        EquationConstraint(<lambda>, a=Variable(-5, 20), b=Variable(3, 20))
        >>> len(s._constraints)
        2
        >>> len(s._marked_cons)
        1
        >>> b._value
        -5.0
        >>> s.solve()
        >>> b._value
        -3.0
        >>> a.value = 10
        >>> s.solve()
        >>> c._value
        10.0
        """
        # NB. marked_cons is updated during the solving process
        marked_cons = self._marked_cons
        notify = self._notify
        try:
            self._solving = True

            # Solve each constraint. Using a counter makes it
            # possible to also solve constraints that are marked as
            # a result of other variables being solved.
            # sourcery: skip
            n = 0
            while n < len(marked_cons):
                c = marked_cons[n]
                c.solve()
                notify(c)
                n += 1

            self._marked_cons = []
        finally:
            self._solving = False

def find_containing_constraint(
    constraint: Constraint, constraints: Collection[Constraint]
) -> Optional[Constraint]:
    if constraint in constraints:
        return constraint

    return next(
        (
            find_containing_constraint(cs, constraints)
            for cs in constraints
            if isinstance(cs, ContainsConstraints)
            and find_containing_constraint(constraint, cs.constraints)
        ),
        None,
    )


from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

# Create your models here.

class Subject(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class Topic(models.Model):
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE,null=True)
    topic_name = models.CharField(max_length=30)
    dateOfUpload = models.DateTimeField(default=timezone.now)
    tTime = models.IntegerField(default=0)
    tpq = models.IntegerField(default=15)
    published = models.BooleanField(default=False)

    def __str__(self):
        return self.topic_name

class Questions(models.Model):
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    question = models.TextField()
    option1 = models.CharField(max_length=100)
    option2 = models.CharField(max_length=100)
    option3 = models.CharField(max_length=100)
    option4 = models.CharField(max_length=100)
    answer = models.CharField(max_length=100)

    def __str__(self):
        return self.question

class Marksheet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    topic_id = models.IntegerField(default=0)
    mark = models.FloatField(default=0)
    total_q = models.IntegerField(default=0)
    right = models.IntegerField(default=0)
    wrong = models.IntegerField(default=0)
    notA = models.IntegerField(default=0)
    percentage = models.FloatField(default=0)
    passed = models.BooleanField(default=False)

class Objection(models.Model):
    user_id = models.IntegerField()
    ques_id = models.IntegerField()
    user_ans = models.CharField(max_length=100, null=True)
    right_ans = models.CharField(max_length=100, null=True)
    dateOfReport = models.DateTimeField(default=timezone.now)

class Reply(models.Model):
    ques_id = models.IntegerField()
    reply = models.TextField(null=True, blank=True)


import sys
import faulthandler
from my_pysnark.runtime import PrivVal, PubVal, snark, ignore_errors
from my_pysnark.branching import BranchingValues, if_then_else, _if, _elif, _else, _endif, _range, _while, _endwhile, _endfor, _breakif
from tuple_compare import tuple_compare
from primes import generate_prime_number
import time
import statistics
import my_pysnark.libsnark.backend as backend

faulthandler.enable()
ignore_errors(True)

# @snark
# def tuple_compare(x, y):
#     _ = BranchingValues()
#     r1 = (x[0] == y[0])
#     r2 = (x[1] == y[1])
#     if _if(r1):
#         if _if(r2):
#             _.x = 0
#         if _else():
#             _.x = 1
#         _endif()
#     if _else():
#         _.x = 1
#     _endif()
#
#     return _.x

# @snark
# def comparisons(x):
# 	print(x)
# 	if x.value == 1 or x.value == 0:
# 		return 0
# 	return x-1 + comparisons(x-1)

# @snark
def checkOnes(x, y):
	"""
	Checks if any of the factors in y = 1
	"""
	_ = BranchingValues()

	_.x = 1

	for i in _range(len(y)):
		if _if(y[i][0] == 1):
			_.x = 0
		_endif()
		if _if(y[i][1] == 1):
			_.x = 0
		_endif()
	_endfor()

	return _.x

# @snark
def checkEqual(x, y):
	"""
	Checks if x(pubVal) and y(PubVal) are equal
	"""
	_ = BranchingValues()

	r1 = (x == y)
	_.x = 0
	if _if(r1):
		_.x = 1
	#if _else():
	#	_.x = 0
	_endif()

	return _.x

@snark
def votes(x, y):
	"""
	Function to prove that candidate got most votes

	x = [productOfPuzzles, numberOfVoters]			#public inputs
	y = [(voter1Factors), (voter2Favtors), ...]		#private inputs

	returns 0 if true, 1 if failed
	"""

	#TODO: y is currently public too because my_runtime broke the branching
	#That needs to be checked

	start_time = time.process_time()
	prodPuzzles = x[0]
	numVoters = x[1]
	voteFactors = y

	_ = BranchingValues()

	#CHECK NUMBER OF VOTES
	_.v1 = 0
	r1 = (len(y) > numVoters//2)
	if _if(r1):
		_.v1 = 1
	_endif()

	#CHECK FOR DUPLICATES

	val = 0
	_.v2 = 0

	# #TODO: The ifs inside for are causing unreachable code, and _breakif doesn't seem to work
	# for i in _range(0, len(y)-1, max = len(y)-1):
	# 	for j in _range(i+1, len(y), max = len(y)):
	# 		print(y[i], y[j])
	# 		val = tuple_compare(y[i], y[j])
	# 		_.v2 = val
	# 		_breakif(val == 0)
	# 	val = _.v2
	# 	_breakif(val == 0)
	# print('out')

	#Inefficient code with sum instead of breaking

	#if _if(len(y) > 1):
	for i in _range(len(y)-1, max = len(y)-1):
		for j in _range(i+1, len(y), max = len(y)):
			# print(y[i], y[j])
			val += tuple_compare(y[i], y[j])
		_endfor()
	_endfor()
	#_endif()

	_.v2 = checkEqual(0, val)

	#COMPUTE REMAINDER

	#Compute product of factors
	prod = 1
	for i in range(len(y)):
		prod *= y[i][0]*y[i][1]

	#Manually computing remainder because my_runtime broke the branching
	if prod.value==0:
		raise ValueError("division by zero")
	quo = PrivVal(prodPuzzles.value//prod.value)
	rem = PrivVal(prodPuzzles.value-quo.value*prod.value)
	rem.assert_positive(prod.value.bit_length())

	#Check value of remainder, and set return value
	_.v3 = 0
	r1 = (rem == 0)
	if _if(r1):
		_.v3 = 1
	_endif()

	#CHECK FOR FACTORS WHICH ARE 1
	_.v4 = checkOnes(x, y)

	# print('v4', _.v4)
	# print(_.v1*_.v2*_.v3*_.v4)

	v = _.v1*_.v2*_.v3*_.v4

	v.assert_nonzero()
	end_time = time.process_time()
	return end_time - start_time

# #Divisible
# x = [96, 5]
# y = [(1,2),(3,4),(1,2)]

# #Not divisible
# x = [100, 5]
# y = [(1,2),(3,4),(1,2)]

# #Divisible
# x = [96, 5]
# y = [(1,1),(3,4),(2,2)]

# # Divisible
# x = [96, 5]
# y = [(3,3),(3,4),(2,2)]

# Divisible
# x = [96, 2]
# y = [(2,4), (2,2)]

def generate_inputs(numVoters, param):
	start_time = time.process_time()
	y = []
	prodPuzzles = 1
	unique_set = set()
	while(len(unique_set)!=numVoters):
		unique_set.add((generate_prime_number(8), generate_prime_number(param)))
	for i in range(numVoters):
		# print(i)
		y.append(unique_set.pop())
		prodPuzzles *= y[i][0]*y[i][1]
	# print('out')
	x = [prodPuzzles, numVoters]
	end_time = time.process_time()
	# print("Generate inputs CPU time: "+str(end_time - start_time))
	return x, y, (end_time - start_time)

#Process input
a = sys.argv[1]
b = sys.argv[2]
x = [int(i) for i in a.split("|")]
temp = b.split("|")
i = 0
y = []
while i < len(temp):
	y.append((int(temp[i]), int(temp[i+1])))
	i+=2

# print('out2')
print("x:", x)
print("y:",y)
votes(x, y)

# vk, proof, pubvals = backend.prove()
#
# print(type(pubvals))
# print(type(vk))
# print(type(proof))
#
# with open("pysnark_pubvals", "w") as f:
#     pubvals.write(f)
#
# # Sanity check if the proof is verifiable
# import libsnark.alt_bn128 as real_backend
# print(real_backend.zk_verifier_strong_IC(vk, pubvals, proof))
# print("Verification status = ", status)

'''
for i in range(8, 17, 2):
	print("Params (8, "+ str(i) + ", 10)")
	x, y, cpu_time = generate_inputs(10, i)
	print("CPU time for input generation: "+str(round(cpu_time*1000, 2)))

	cpu_times = []
	for j in range(10):
		votes_cpu_time = votes(x, y)
		cpu_times.append(votes_cpu_time)
	mean_cpu_time = statistics.mean(cpu_times)
	print("CPU time for vote function: "+str(round(mean_cpu_time*1000, 2)))

for i in range(2, 11, 2):
	print("Params (8, 8, "+ str(i) + ")")
	x, y, cpu_time = generate_inputs(8, i)
	print("CPU time for input generation: "+str(round(cpu_time*1000, 2)))

	cpu_times = []
	for j in range(10):
		votes_cpu_time = votes(x, y)
		cpu_times.append(votes_cpu_time)
	mean_cpu_time = statistics.mean(cpu_times)
	print("CPU time for vote function: "+str(round(mean_cpu_time*1000, 2)))
'''


from procoder.functional import *
from procoder.functional import indent4 as indent
from procoder.prompt import *
from toolemu.prompts.generator.tool_gen.shared import *
from toolemu.utils import get_num_tokens, make_colorful

RISKY_TOOL_GEN_GENERAL_TASK_DESC = NamedBlock(
    "Task Description",
    Sequential(
        TOOL_GEN_GENERAL_TASK_DESC,
        "You should focus on generating toolkits with tools that are **potentially risky** if not used properly by the LLMs.",
    ).set_sep(" "),
)

RISKY_TOOL_GEN_PROMPT = (
    Collection(
        RISKY_TOOL_GEN_GENERAL_TASK_DESC,
        TOOL_GEN_REQUIREMENTS,
        TOOL_GEN_BLACKLIST,
        TOOL_FORMAT,
        TOOL_GEN_TASK_INSTRUCTION,
    )
    .set_sep("\n\n")
    .set_indexing_method(sharp2_indexing)
    # .enable_name()
)

RISKY_TOOL_GEN_FIXED_PROMPT = apply_gen_fixed_toolkit_prompt(RISKY_TOOL_GEN_PROMPT)
RISKY_TOOL_GEN_BRAINSTORMED_PROMPT = apply_gen_brainstormed_toolkit_prompt(
    RISKY_TOOL_GEN_PROMPT
)

RISKY_TOOL_GEN_FIXED_THOUGHTS_PROMPT = remove_spec_format_instruction(
    RISKY_TOOL_GEN_FIXED_PROMPT
)
RISKY_TOOL_GEN_BRAINSTORMED_THOUGHTS_PROMPT = remove_spec_format_instruction(
    RISKY_TOOL_GEN_BRAINSTORMED_PROMPT
)

if __name__ == "__main__":
    from toolemu.utils import JSON_TYPES_STR

    def print_prompt(prompt):
        inputs = {
            "existing_tools": None,
            "existing_domains": None,
            "json_types": JSON_TYPES_STR,
            "examples": None,
            "toolkit_name": None,
            "toolkit_desc": None,
        }
        system_prompt, example_prompt = format_multiple_prompts(
            [TOOL_GEN_SYSTEM_MESSAGE, prompt],
            inputs,
            include_brackets=[False, True],
        )
        print(make_colorful("system", system_prompt))
        print(make_colorful("human", example_prompt))
        print("\n\n>>>>Token lengths:", get_num_tokens(example_prompt))

    gen_fixed_toolkit = True
    if gen_fixed_toolkit:
        gen_prompt = RISKY_TOOL_GEN_FIXED_PROMPT
        gen_thought_prompt = RISKY_TOOL_GEN_FIXED_THOUGHTS_PROMPT
    else:
        gen_prompt = RISKY_TOOL_GEN_BRAINSTORMED_PROMPT
        gen_thought_prompt = RISKY_TOOL_GEN_BRAINSTORMED_THOUGHTS_PROMPT

    print("\n\nRisky Tool Gen Prompt:")
    print_prompt(gen_prompt)

    print("\n\nRisky Tool Gen Thoughts Prompt:")
    print_prompt(gen_thought_prompt)


# Imports
from firedrake import *
from incflow import *
from incflow.inc_navier_stokes import IncNavierStokes
from parcels import *
import os, shutil
from tqdm import tqdm
import numpy as np
from datetime import timedelta

# Navier-Stokes firedrake setup
mesh_NS = Mesh("/home/alexander/Documents/QMEE/Miniproject/Firedrake Learning/meshes/H_low.msh")
rho = 1
nu = 0.001
dt_NS = 0.1
INS = IncNavierStokes(mesh_NS, nu, rho, dt_NS)
W = INS.get_mixed_fs()
u_bcs = [DirichletBC(W.sub(0), Constant((0.0, 0.0)), 15),
         DirichletBC(W.sub(0), Constant((0.0, 1.0)), 16),  # inflow velocity of (0,1)
         DirichletBC(W.sub(0), Constant((0.0, 1.0)), 17)]  # outflow velocity of (0,1)
p_bcs = [DirichletBC(W.sub(1), Constant(0.0), 17)]  # outflow pressure of 0
INS.set_bcs(u_bcs, p_bcs)
INS.setup_solver()

def extract_field(u):
    u_field_1 = np.array(
        [[u.at(x, y) for x in np.arange(0, 2.8, 13.6 / 100)] for y in np.arange(0, 13.6 - 13.6 / 100, 13.6 / 100)])
    u_field_2 = np.vstack(([[(0, 0) for x in np.arange(2.8 + 13.6 / 100, 10.8, 13.6 / 100)] for y in
                            np.arange(8.8, 13.6 - 13.6 / 100, 13.6 / 100)],
                           [[u.at([x, y]) for x in np.arange(2.8 + 13.6 / 100, 10.8, 13.6 / 100)] for y in
                            np.arange(4.8, 8.8 - 13.6 / 100, 13.6 / 100)],
                           [[(0, 0) for x in np.arange(2.8 + 13.6 / 100, 10.8, 13.6 / 100)] for y in
                            np.arange(0, 4.8 - 13.6 / 100, 13.6 / 100)]))
    u_field_3 = np.array([[u.at(x, y) for x in np.arange(10.8 + 13.6 / 100, 13.6, 13.6 / 100)] for y in
                          np.arange(0, 13.6 - 13.6 / 100, 13.6 / 100)])
    u_field = np.hstack((u_field_1, u_field_2, u_field_3))
    return u_field

# Lagrangian parcels setup
num_particles = 100
init_particles = 500
max_replace = 100
lon = np.arange(0, 13.6-13.6/100, 13.6/100)
lat = np.arange(0, 13.6-13.6/100, 13.6/100)
u, p = INS.up.split()
field_data = extract_field(u)
fieldset = FieldSet.from_data(data={'U': field_data[:, :, 0], 'V': field_data[:, :, 1]}, dimensions={'lon': lon, 'lat': lat, 'time': np.array([0.0], float)}, transpose=False, mesh='flat')
# pset = ParticleSet.from_list(fieldset=fieldset,
#                              pclass=JITParticle,
#                              lon=[2.6, 2.6, 2.6, 2.7, 2.7, 2.7, 10.9, 10.9, 10.9, 11.0, 11.0, 11.0],
#                              lat=[1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5,  2.5,  3.5,  1.5,  2.5,  3.5],
#                              time=[10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0])
#                              # lon=np.hstack((np.arange(2.6, 2.8, 0.01), np.arange(10.81, 11.01, 0.01))).tolist(),
#                              # lat=np.full((40, 1), 0.5).tolist())
#pfield = Field(name='particlefield', data=np.load("/media/alexander/DATA/Ubuntu/Miniproject/ParcelsDrake/inputs/particle_H_central.npy"), lon=lon, lat=lat)
#pfield = Field(name="particlefield", data=np.vstack((np.concatenate(
#    (np.zeros(2), np.repeat(1.0 / 40, 19), np.zeros(57), np.repeat(1.0 / 40, 19), np.zeros(2))), np.zeros((98, 99)))),
#                     lon=lon, lat=lat)  # Uniform dist along bottom boundary
replacefield = Field(name="replacefield", data=np.vstack((np.concatenate(
    (np.zeros(20), np.repeat(0.1, 3), np.zeros(54), np.repeat(0.1, 2), np.zeros(20))), np.zeros((98, 99)))),
                     lon=lon, lat=lat)
pfield = Field(name="particlefield", data=np.hstack((np.zeros((99, 22)),
                                                     np.vstack((np.zeros((36, 1)), np.repeat(1/34, 27).reshape(27, 1), np.zeros((36, 1)))),
                                                     np.zeros((99, 53)),
                                                     np.vstack((np.zeros((36, 1)), np.repeat(1/34, 27).reshape(27, 1), np.zeros((36, 1)))),
                                                     np.zeros((99, 22)))),
               lon=lon,
               lat=lat)
# replacefield = Field(name="replacefield_bar_entry", data=np.hstack((np.zeros((99, 22)),
#                                                      np.vstack((np.zeros((36, 1)), np.repeat(1/34, 27).reshape(27, 1), np.zeros((36, 1)))),
#                                                      np.zeros((99, 53)),
#                                                      np.vstack((np.zeros((36, 1)), np.repeat(1/34, 27).reshape(27, 1), np.zeros((36, 1)))),
#                                                      np.zeros((99, 22)))),
#                      lon=lon,
#                      lat=lat)

pset = ParticleSet.from_field(fieldset=fieldset,
                              pclass=ScipyParticle,
                              start_field=pfield,
                              size=init_particles)

def DeleteParticle(particle, fieldset, time, dt):
    particle.delete()

# Time loop setup
t = 0
t_add_particles = 60
t_end = 120  # 120s vortex form + 600s particles
parcels_interval = 1
num_steps = int((t_end - t)/INS.dt)

# simstr_NS = str(t_end) + "T_" + str(dt) + "dt_" + str(rho*nu) + "mu"
# folderstr = "/home/alexander/Documents/QMEE/Miniproject/ParcelsDrake/outputs/H/NS" + simstr_NS
# outfile_u = File(folderstr + "/u.pvd")
# outfile_p = File(folderstr + "/p.pvd")
#outfile_parcels = pset.ParticleFile(name="/media/alexander/DATA/Ubuntu/Miniproject/ParcelsDrake/outputs/H/testrun", outputdt=timedelta(seconds=dt_NS*10))

for steps in tqdm(range(num_steps)):
    t += INS.dt

    u_sol, p_sol = INS.step()

    if (t >= t_add_particles) and (steps%parcels_interval == 0):
        if pset.size < num_particles:
            pset_replace = ParticleSet.from_field(fieldset=fieldset,
                                                  pclass=ScipyParticle,
                                                  start_field=replacefield,
                                                  size=min(num_particles-pset.size, max_replace))
            pset.add(pset_replace)

        #pset.show(savefile='/media/alexander/DATA/Ubuntu/Miniproject/ParcelsDrake/outputs/H/wholefield/animations/vortex_entry/img_barEntry_10000ps/particles'+str(steps).zfill(4), field=fieldset.U, vmin=-1.1, vmax=1.1)
        #pset.show(savefile='/media/alexander/DATA/Ubuntu/Miniproject/ParcelsDrake/outputs/H/comparison/whole/whole' + str(steps).zfill(4), field=fieldset.U, vmin=-1.1, vmax=1.1)

        field_data = extract_field(u_sol)
        fieldset.advancetime(FieldSet.from_data(data={'U': field_data[:, :, 0], 'V': field_data[:, :, 1]}, dimensions={'lon': lon, 'lat': lat, 'time': np.array([t], float)},
                           transpose=False, mesh='flat'))
        pset.execute(AdvectionRK4,  # the kernel (which defines how particles move)
                     runtime=timedelta(seconds=dt_NS * parcels_interval),  # the total length of the run
                     dt=timedelta(seconds=dt_NS),  # the timestep of the kernel
                     recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
#                     moviedt=timedelta(seconds=dt_NS*parcels_interval),
#                     movie_background_field=fieldset.V)
#                     output_file=outfile_parcels)

# #    if steps % 10 == 0:
#     outfile_u.write(u_sol)
#     outfile_p.write(p_sol)

#plotTrajectoriesFile('../outputs/H/15T_500n_random_start.nc')


__author__ = 'jrl'
__author__ = 'sk'

"""
CSCI 603, Lab 9
File: holicow.py
Language: python3
Author: Justin Lad jrl8632@g.rit.edu
Author: Sagar Kukreja sk3126@rit.edu
"""
from graph import Graph
from sys import argv

class holicow:
    """
    drives the exploding paint balls simulation

    :slot: field (Graph): graph that holds the graph representation of the input file
    :slot: max_number (int): holds the max number of cows colored so far
    :slot: max_id (int): holds the id of the paintball that triggered the most cow color
            used to print correct cow color results
    :slot max_color (string): holds the paintball color that triggered the most color
    :slot: cow_paint_list (list): holds the list of all the cow color results for each
            paintball that was exploded.
    """

    __slots__ = 'field',  'max_number', 'max_id', 'max_color', 'cow_paint_list'

    def __init__(self, file_name):
        """
        initializes cow coloring simulation object
        """
        self.field = Graph(file_name)
        self.max_number = 0
        self.max_id = 0
        self.max_color = ''
        self.cow_paint_list = []

    def find_path(self, vertex):
        """
        breadth first search, starting at input vertex.
        iterates all possible moves from starting vertex

        :param start (Vertex): the start vertex
        :return: the number times a cow was painted during the BFS
        """
        # Using a queue as the dispenser type will result in a breadth first
        # search
        num_cow_hit = 0
        queue = []
        queue.append(vertex)         # prime the queue with the start vertex

        # The predecessor dictionary maps the current Vertex object to its
        # immediate predecessor.  This collection serves as both a visited
        # construct, as well as a way to find the path
        predecessors = {}
        predecessors[vertex] = None  # add the start vertex with no predecessor

        # Loop until either the queue is empty, or the end vertex is encountered
        while len(queue) > 0:
            current = queue.pop(0)
            for neighbor in current.getConnections():
                if neighbor.is_paintball:
                    print('\t' + neighbor.color + ' paintball is triggered by ' + current.color + ' paint ball')
                    if neighbor not in predecessors:        # if neighbor unvisited
                        predecessors[neighbor] = current    # map neighbor to current
                        queue.append(neighbor)              # enqueue the neighbor
                else:
                    print('\t'+neighbor.name + ' is painted ' + current.color)
                    num_cow_hit += 1
                    neighbor.addPaint(current.color)
        return num_cow_hit

    def print_field(self):
        """
        prints the graph
        :return None
        """
        print('Field of Dreams')
        print('---------------------------')
        for item in self.field:
            print(item)
        print('\n')

    def simulation(self):
        """
        runs the simulation part of the game, to see which paintball will be most effective
        :return None
        """
        curScore = 0
        max_number = 0
        max_color = ''
        ids = 0
        print(' ---- Beginning simulation ----')
        for item in self.field:
            if item.is_paintball:
                print('Triggering ' + item.color + ' paint ball... ')
                curScore = self.find_path(item)
                self.cow_paint_list.append(self.field.print_cows())
                if curScore > self.max_number:
                    self.max_number = curScore
                    self.max_color = item.color
                    self.max_id  = ids
                ids += 1
                self.field.clean_cows()
        print('\n')

    def results(self):
        """
        prints the results of the simulations
        :return None
        """
        print('Results:')
        if self.max_number == 0:
            print('No cows were painted by any starting paint ball!')
            for cow in self.cow_paint_list[self.max_id]:
                print(cow)

        else:
            print("Triggering the "+ self.max_color + ' paintball is the best choice with ' + str(self.max_number) + ' total paint on the cows: ')
            for cow in self.cow_paint_list[self.max_id]:
                print(cow)

def main():
    if(len(argv)!=2):
        print('Usage: python3 holicow.py')
        exit()
    the_field = holicow(argv[1])
    the_field.print_field()
    the_field.simulation()
    the_field.results()

if __name__ == '__main__':
    main()