#We need to calculate the amount of fuel needed to launch modules.
#Fuel required is based on mass.

masses=[]

with open('input.txt') as fp:
    for _, line in enumerate(fp):
        masses.append(float(line))

#To get the fuel needed for a given mass, divide the mass by three, round down, and subtract 2.
def calculate_fuel(mass):
    return max(0, int(mass / 3.0) - 2)

sum=0

for mass in masses:
    fuel_needed=calculate_fuel(mass)

    while fuel_needed > 0.0:
        sum+=fuel_needed
        fuel_needed=calculate_fuel(fuel_needed)

print(sum)


from django.shortcuts import render
from django.views import View
from django.http import JsonResponse,HttpResponseServerError,HttpResponseNotFound,HttpResponseBadRequest,HttpResponseRedirect
import json, pdb, re, datetime
from pymongo import MongoClient

# Create your views here.

class AccountsIndexView(AnyView):
    def __init__(self ,*args, **kwargs):
        # this is where the view gets initialized
        AnyView.__init__(self,*args, **kwargs)
        self.useraccounts = self.pifarm['useraccounts']
    def hateoas_replace_links(self, request,result):
        """This is to transform the object to hateoas compliant links"""
        def replace_links(acc):
            if not acc is None and 'license' in acc:
                acc['license'] = request.build_absolute_uri('/accounts/{}/license'.format(acc['login']))
        if isinstance(result, list):
            for item in result:
                replace_links(item)
        else:
            replace_links(result)
        return result
    def accountok(self,acc):
        """this is to assess the shape of the account object that is send in from the http client
        """
        if acc is None or isinstance(acc, dict) ==False:
            return False
        if not 'login' in acc or not 'pin' in acc:
            return False
        if acc['login']=='' or acc['pin']=='':
            return False
        if re.match(r'[a-zA-Z0-9_-]{3,12}', acc['login']) is None:
            return False
        if re.match(r'[0-9]{3,12}', acc['pin']) is None:
            return False
        return True
    def get (self, request):
        """this is to get the index of all the accounts from the database"""
        if not self.pifarm is None:
            try:
                result = list(self.useraccounts.find({}))
                if not result is None :
                    return JsonResponse(self.hateoas_replace_links(request,self.friendly_json(result)), safe=False)
                else:
                    return JsonResponse([], safe=False)
            except Exception as e:
                return HttpResponseServerError('Inernal server error: Failed query on the database')
    def post(self, request):
        payload=json.loads(request.body.decode('utf-8'))
        if not payload is None and self.accountok(payload) ==True:
            duplicate = self.useraccounts.find_one({'login':payload['login']})
            if duplicate is None:
                inserted_id =self.useraccounts.insert(payload)
                inserted = self.useraccounts.find_one({'_id':inserted_id})
                # return JsonResponse(self.friendly_json(inserted))
                return HttpResponseRedirect(request.build_absolute_uri('/useraccounts/{}'.format(inserted['login'])))
            else:
                return HttpResponseBadRequest('Bad Request: Account with the same login is already registered')
        else:
            return HttpResponseBadRequest('Bad Request: The account object to be added is not in shape.')
class AccountDetailView(AccountsIndexView):
    def __init__(self ,*args, **kwargs):
        # this is where the view gets initialized
        AccountsIndexView.__init__(self,*args, **kwargs)
    def get(self, request, login):
        """This is to get a single account details from the database"""
        result =self.useraccounts.find_one({"login":login})
        if not result is None:
            return JsonResponse(self.hateoas_replace_links(request,self.friendly_json(result)), safe=False)
        else:
            return JsonResponse({}, safe=False)
    def put(self, request, login):
        """This can help changing the direct properties of the account"""
        payload =json.loads(request.body.decode('utf-8'))
        if not payload is None and 'pin' in payload:
            account_exists =(True, False)[self.useraccounts.find_one({'login':login}) is None]
            if account_exists ==True:
                new_pin  = payload['pin']
                self.useraccounts.update({'login':login}, {'$set':{'pin':new_pin}})
                return HttpResponseRedirect(request.build_absolute_uri('/useraccounts/{}'.format(login)))
            else:
                # this is the case when you are trying to update an account that does not exists
                return HttpResponseBadRequest('Bad request: no acocunt with {} login exists '.format(login))
        else:
            return HttpResponseBadRequest('Bad Request :Account not in valid shape for updation, check for the fields required and send again')
class AccountDevices(AnyView):
    def __init__(self, *args, **kwargs):
        AnyView.__init__(self, *args,**kwargs)
        self.devices = self.pifarm['devices']
    def get(self, request,login):
        """This is for getting the details of all the devices for the login account"""
        result  = list(self.devices.find({'login':login}))
        return JsonResponse(self.friendly_json(result), safe=False)


# To run this, you can install BeautifulSoup
# https://pypi.python.org/pypi/beautifulsoup4

# Or download the file
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
# url='http://py4e-data.dr-chuck.net/known_by_Fikret.html'
# position = 2
position = input('Enter position:')
position = int(position) - 1
# repeat = 4
repeat = input('Enter Count:')
repeat = int(repeat)

# Retrieve all of the anchor tags
def anchor():
    html = urllib.request.urlopen(url, context=ctx).read()
    soup = BeautifulSoup(html, 'html.parser')
    links=list()
    tags = soup('a')
    for tag in tags:
        # print(tag)
        tag=(tag.get('href', None))
        # print(tag)
        links.append(tag)
    #print(links)
    link=links[position]
    #print('New URL', link)
    return link

while repeat > 0:
    nurl = anchor()
    #print(nurl)
    url=nurl
    print(url)
    repeat=repeat - 1


from math import isclose, sqrt

def error_gen(actual, rounded):
    divisor = sqrt(1.0 if actual < 1.0 else actual)
    return abs(rounded - actual) ** 2 / divisor

def round_to_100(percents):
    if not isclose(sum(percents), 100):
        raise ValueError
    n = len(percents)
    rounded = [int(x) for x in percents]
    up_count = 100 - sum(rounded)
    errors = [(error_gen(percents[i], rounded[i] + 1) - error_gen(percents[i], rounded[i]), i) for i in range(n)]
    rank = sorted(errors)
    for i in range(up_count):
        rounded[rank[i][1]] += 1
    return rounded

def round_percentages(percentages):
    # list will be like [[1.0, 54.5], [2.0, 40.9]... etc]
    # so pick out the numbers to round
    list_to_round = []
    for p in percentages:
        list_to_round.append(p[1])

    rounded = round_to_100(list_to_round)
    # make a new list to return
    _return = []
    for i,p in enumerate(percentages):
        _return.append([p[0], rounded[i]])

    return _return

#rounded = round_percentages([[1.0, 54.54545454545454], [3.0, 40.909090909090914], [4.0, 4.545454545454546]])


"""Coinflip Guessing Game."""

from random import randint

__author__ = "730318766"

PENSIVE_FACE: str = "\U0001F614"
THUMBS_UP: str = "\U0001F44D"
player: str = ""
points: int = 0
what_next: str = ""

def main() -> None:
    """The entrypoint of the program, when run as a module."""
    global points
    greet()
    what_next: str = str(input("*Coin Flip* Heads, Tails, or End Game? (h/t/e) "))
    if what_next == "e":
        print(f"So sad to see you go {PENSIVE_FACE} You accumulated {points} points! Goodbye.")
    else:
        if what_next == "h":
            points = option_1(points)
        else:
            if what_next == "t":
                option_2()

def greet() -> None:
    """Prints a welcome message for context and asks for player's name."""
    global player
    player = str(input("What's your name? "))
    print(f"Welcome {player}, this game flips a coin & you guess heads or tails. How many can you guess correctly?")

def coin_flip() -> str:
    """Returns heads or tails from random coin flip."""
    coin: int = int(randint(1, 2))
    if coin == 1:
        return "h"
    else:
        return "t"

def option_1(points: int) -> int:
    """Returns points from Heads option."""
    if what_next == coin_flip:
        print(f"Correct {player} , here's 1 point!")
        points += 1
        total: str = str(input("Would you like to see your total points? (y/n) "))
        if total == "y":
            print(f"You currently have {points} point(s).")
        option_3()
    else:
        if what_next != coin_flip:
            print(f"Sorry, that is incorrect {player} {PENSIVE_FACE}")
            total: str = str(input("Would you like to see your total points? (y/n) "))
            if total == "y":
                print(f"You currently have {points} point(s).")
            option_3()
    return points

def option_2() -> None:
    """Reassigns points from Tails option."""
    global points
    if what_next == coin_flip:
        print(f"Correct {player} , here's 1 point!")
        points += 1
        total: str = str(input("Would you like to see your total points? (y/n) "))
        if total == "y":
            print(f"You currently have {points} points.")
        option_3()
    else:
        if what_next != coin_flip:
            print(f"Sorry, that is incorrect {player} {PENSIVE_FACE}")
            total: str = str(input("Would you like to see your total points? (y/n) "))
            if total == "y":
                print(f"You currently have {points} points.")
            option_3()

def option_3() -> None:
    """Starts game over or ends game."""
    global points
    next_step: str = str(input("Would you like to Try Again or End Game? (t/e) "))
    if next_step == "t":
        print("Congrats, here's an extra point to start you off!")
        points += 1
        main()
    else:
        if next_step == "e":
            print(f"So sad to see you go {PENSIVE_FACE} You accumulated {points} points! Goodbye.")

if __name__ == "__main__":
    main()


# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------

from msrest.serialization import Model

class PreValidateEnableBackupRequest(Model):
    """Contract to validate if backup can be enabled on the given resource in a
    given vault and given configuration.
    It will validate followings
    1. Vault capacity
    2. VM is already protected
    3. Any VM related configuration passed in properties.

    :param resource_type: ProtectedItem Type- VM, SqlDataBase, AzureFileShare
     etc. Possible values include: 'Invalid', 'VM', 'FileFolder', 'AzureSqlDb',
     'SQLDB', 'Exchange', 'Sharepoint', 'VMwareVM', 'SystemState', 'Client',
     'GenericDataSource', 'SQLDataBase', 'AzureFileShare', 'SAPHanaDatabase',
     'SAPAseDatabase'
    :type resource_type: str or
     ~azure.mgmt.recoveryservicesbackup.models.DataSourceType
    :param resource_id: ARM Virtual Machine Id
    :type resource_id: str
    :param vault_id: Specifies the arm resource id of the vault
    :type vault_id: str
    :param properties: Configuration of VM if any needs to be validated like
     OS type etc
    :type properties: str
    """

    _attribute_map = {
        'resource_type': {'key': 'resourceType', 'type': 'str'},
        'resource_id': {'key': 'resourceId', 'type': 'str'},
        'vault_id': {'key': 'vaultId', 'type': 'str'},
        'properties': {'key': 'properties', 'type': 'str'},
    }

    def __init__(self, **kwargs):
        super(PreValidateEnableBackupRequest, self).__init__(**kwargs)
        self.resource_type = kwargs.get('resource_type', None)
        self.resource_id = kwargs.get('resource_id', None)
        self.vault_id = kwargs.get('vault_id', None)
        self.properties = kwargs.get('properties', None)


import os
import re
import socket

import trello
from hugin.flowcells import Flowcell
from flowcell_status import FlowcellStatus, FC_STATUSES

FC_NAME_RE = r'(\d{6})_([ST-]*\w+\d+)_\d+_([AB]?)([A-Z0-9\-]+)'

COLORS = [
    'red',
    'blue',
    'green',
    'yellow',
    'orange',
    'purple',
    'lime',
    'pink',
    'sky',
    'black'
]

class FlowcellMonitor(object):
    def __init__(self, config):
        self._config = config
        # initialize None values for @property functions
        self._trello_board = None
        self._data_folders = None
        self._trello_cards = None
        self._trello_lists = None

    @property
    def config(self):
        return self._config

    @property
    def trello_board(self):
        if not self._trello_board:
            if not self.config.get('trello'):
                raise RuntimeError("'trello' must be in config file")

            config = self.config.get('trello')
            # todo check if board exist

            api_key = config.get('api_key')
            token = config.get('token')
            api_secret = config.get('api_secret')
            client = trello.TrelloClient(api_key=api_key, token=token, api_secret=api_secret)
            board_id = config.get('board_id')
            self._trello_board  = client.get_board(board_id)

        return self._trello_board

    @property
    def data_folders(self):
        if not self._data_folders:
            self._data_folders = self.config.get('data_folders')
            if self._data_folders is None:
                raise RuntimeError("'data_folders' must be in config file")
        return self._data_folders

    @property
    def trello_cards(self):
        if self._trello_cards is None:
            self._trello_cards = self.trello_board.all_cards()
        return self._trello_cards

    @property
    def trello_lists(self):
        if self._trello_lists is None:
            self._trello_lists = self.trello_board.all_lists()
        return self._trello_lists

    def update_trello_board(self):
        for data_folder in self.data_folders:
            self._check_running_flowcells(data_folder)
            self._check_nosync_flowcells(data_folder)
            # move deleted flowcells to the archive list
            self._check_archived_flowcells(data_folder)

    def _check_running_flowcells(self, data_folder):
        # go through subfolders
        subfolders = filter(os.path.isdir, [os.path.join(data_folder, fc_path) for fc_path in os.listdir(data_folder)])
        for flowcell_path in subfolders:
            # skip non-flowcell folders
            if not re.match(FC_NAME_RE, os.path.basename(flowcell_path)):
                continue

            status = FlowcellStatus(flowcell_path)
            # depending on the type, return instance of related class (hiseq, hiseqx, miseq, etc)
            flowcell = Flowcell.init_flowcell(status)
            if flowcell.check_status():
                # todo: add comment
                # todo: if comment has been added
                pass
            # update flowcell on trello board
            self._update_card(flowcell)

    def _check_nosync_flowcells(self, data_folder):
        # check nosync folder
        nosync_folder = os.path.join(data_folder, 'nosync')
        if os.path.exists(nosync_folder):
            # move flowcell to nosync list
            for nosync_flowcell in os.listdir(nosync_folder):
                flowcell_path = os.path.join(nosync_folder, nosync_flowcell)
                # skip non-flowcell folders
                if not re.match(FC_NAME_RE, os.path.basename(flowcell_path)):
                    continue
                card = self._get_card_by_name(nosync_flowcell)
                # if the card is not on Trello board, create it
                if card is None:
                    status = FlowcellStatus(flowcell_path)
                    flowcell = Flowcell.init_flowcell(status)
                    self._update_card(flowcell)
                else:
                    nosync_list = self._get_list_by_name(FC_STATUSES['NOSYNC'])
                    card.change_list(nosync_list.id)

    def _check_archived_flowcells(self, data_folder):
        # if nosync folder exists
        if os.path.exists(os.path.join(data_folder, FC_STATUSES['NOSYNC']).lower()):
            # get cards from the nosync list
            for card in self._get_cards_by_list(FC_STATUSES['NOSYNC']):
                localhost = socket.gethostname()
                # if the flowcell belongs to the server
                if localhost in card.description:
                    # check if the flowcell has been deleted from the nosync folder
                    if card.name not in os.listdir(os.path.join(data_folder, FC_STATUSES['NOSYNC'].lower())):
                        archived_list = self._get_list_by_name(FC_STATUSES['ARCHIVED'])
                        card.change_list(archived_list.id)

    def _update_card(self, flowcell):
        # todo: beautify the method
        trello_card = self._get_trello_card(flowcell) # None
        flowcell_list = self._get_list_by_name(flowcell.trello_list)

        # if not card on trello board
        if trello_card is None:
            return self._create_card(flowcell)
        else:
            # skip aborted list
            if flowcell.trello_list == FC_STATUSES['ABORTED']:
                return trello_card
            # if card is in the wrong list
            if trello_card.list_id != flowcell_list.id:
                # move card
                trello_card.change_list(flowcell_list.id)

            # if card is in the right list
            else:
                # todo: checkstatus -> taking too long?
                return trello_card

            # update due_time
            trello_card.set_due(flowcell.due_time)
            if flowcell.trello_list == FC_STATUSES['CHECKSTATUS']:
                trello_card.comment(flowcell.status.warning)
            return trello_card

    def _create_card(self, flowcell):
        trello_list = self._get_list_by_name(flowcell.trello_list)
        if not trello_list:
            raise RuntimeError('List {} cannot be found in TrelloBoard {}'.format(flowcell.status, self.trello_board))

        trello_card = trello_list.add_card(name=flowcell.full_name, desc=flowcell.get_formatted_description())
        if flowcell.trello_list == FC_STATUSES['CHECKSTATUS']:
            trello_card.comment(flowcell.status.warning)
        trello_card.set_due(flowcell.due_time)
        self._add_label(trello_card, flowcell)

    def _add_label(self, card, flowcell):
        server = flowcell.server
        label = self._get_label_by_name(server)
        if label is None:
            color = self._get_next_color()
            label = self.trello_board.add_label(name=server, color=color)
        if label.id not in [label.id for label in card.labels]:
            card.add_label(label)

    def _get_label_by_name(self, name):
        labels = self.trello_board.get_labels()
        for label in labels:
            if label.name == name:
                return label
        return None

    def _get_list_by_name(self, list_name):
        for item in self.trello_lists:
            if item.name == list_name:
                return item
        return None

    def _get_cards_by_list(self, list_name):
        trello_list = self._get_list_by_name(list_name)
        result = []
        for card in self.trello_cards:
            if card.list_id == trello_list.id:
                result.append(card)
        return result

    def _get_card_by_name(self, card_name):
        for card in self.trello_cards:
            if card.name == card_name:
                return card

    def _get_trello_card(self, flowcell):
        for card in self.trello_cards:
            if flowcell.full_name == card.name:
                return card
        return None

    def _get_next_color(self):
        labels = self.trello_board.get_labels()
        colors = [label.color for label in labels] if labels else []
        # if all colors are used take the first one
        if colors == COLORS:
            return COLORS[0]

        # if not all the colors are used, take the one which is not used
        elif set(colors) != set(COLORS):
            for color in COLORS:
                if color not in colors:
                    return color

        else: # set(colors) == set(COLORS):
            # otherwise take the color which is used the least
            color_groups = {} # how many times each color has been used already
            for color in COLORS:
                color_groups[color] = colors.count(color)

            for color, count in color_groups:
                if count == min(color_groups.values()):
                    return color


# -*- encoding: utf-8 -*-

import base64

import time
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import tools

import logging

# _logger = logging.getLogger(__name__)

class account_rus_import(osv.osv_memory):
    _name = 'account.rus.import'
    _description = 'Import Russian statements file'
    _columns = {
        'file_data': fields.binary('Import statements File', required=True),
        'file_fname': fields.char('Import statements Filename', size=128, required=True),
        'note': fields.text('Log'),
        'temporary_account_id': fields.many2one('account.account', 'Temporary Account', help="It acts as a temporary account for general amount", required=True),  # domain="[('type','!=','view')]"
    }

    def _get_default_tmp_account(self, cr, uid, context):
        tmp_accounts = self.pool.get('account.account').search(cr, uid, [('code', '=', '490000')])
        if tmp_accounts and len(tmp_accounts) > 0:
            tmp_account_id = tmp_accounts[0]
        else:
            tmp_account_id = False
        return tmp_account_id

    _defaults = {
        'file_fname': lambda *a: '',
        'temporary_account_id': _get_default_tmp_account,
    }

    def file_parsing(self, cr, uid, ids, context=None, batch=False, rfile=None, rfilename=None):

        def acc_number_parsing(obj, line_number):
            acc_res = {}
            acc_res_number = ''
            while rmspaces(obj[line_number][0]) != u'КонецРасчСчет':  # !!! Документ
                if obj[line_number][0] == u'ДатаНачала':
                    acc_res['begin_date'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT,
                                                          time.strptime(rmspaces(obj[line_number][1]), '%d.%m.%Y'))
                elif obj[line_number][0] == u'ДатаКонца':
                    acc_res['end_date'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT,
                                                        time.strptime(rmspaces(obj[line_number][1]), '%d.%m.%Y'))
                elif obj[line_number][0] == u'РасчСчет':
                    acc_res_number = rmspaces(obj[line_number][1])
                elif obj[line_number][0] == u'НачальныйОстаток':
                    acc_res['balance_start'] = float(rmspaces(obj[line_number][1]))
                elif obj[line_number][0] == u'ВсегоПоступило':
                    acc_res['balance_plus'] = float(rmspaces(obj[line_number][1]))
                elif obj[line_number][0] == u'ВсегоСписано':
                    acc_res['balance_minus'] = float(rmspaces(obj[line_number][1]))
                elif obj[line_number][0] == u'КонечныйОстаток':
                    acc_res['balance_end'] = float(rmspaces(obj[line_number][1]))
                line_number += 1
            line_number += 1
            return acc_res_number, acc_res, line_number

        if context is None:
            context = {}
        if batch:
            rfile = str(rfile)
            rfilename = rfilename
        else:
            data = self.browse(cr, uid, ids)[0]
            try:
                rfile = data.file_data
                rfilename = data.file_fname
                temporaryaccount = data.temporary_account_id.id
            except:
                raise osv.except_osv(_('Error'), _('Wizard in incorrect state. Please hit the Cancel button'))
                # return {}
        recordlist = unicode(base64.decodestring(rfile), 'windows-1251', 'strict').split('\n')
        strobj = []
        for line in recordlist:
            strobj.append(line.split('='))

        format_import_file = ''
        encoding_file = ''
        statements = {}
        note = []
        inc_desc = 1
        if rmspaces(recordlist[0]) != '1CClientBankExchange':
            raise osv.except_osv(_('Error'), _('Incorrect description of import file'))

        if strobj[inc_desc][0] == u'ВерсияФормата':
            format_import_file = rmspaces(strobj[inc_desc][1])
            note.append(recordlist[inc_desc] + '\n')
            inc_desc += 1
        else:
            raise osv.except_osv(_('Error'), _('Incorrect description of import file'))

        if strobj[inc_desc][0] == u'Кодировка':
            encoding_file = rmspaces(strobj[inc_desc][1])
            note.append(recordlist[inc_desc] + '\n')
            inc_desc += 1
        else:
            raise osv.except_osv(_('Error'), _('Incorrect description of import file'))

        if strobj[inc_desc][0] == u'Отправитель':
            note.append(recordlist[inc_desc] + '\n')
            inc_desc += 1
        if strobj[inc_desc][0] == u'Получатель':
            note.append(recordlist[inc_desc] + '\n')
            inc_desc += 1
        else:
            raise osv.except_osv(_('Error'), _('Incorrect description of import file'))

        if strobj[inc_desc][0] == u'ДатаСоздания':
            note.append(recordlist[inc_desc] + '\n')
            inc_desc += 1
        if strobj[inc_desc][0] == u'ВремяСоздания':
            note.append(recordlist[inc_desc] + '\n')
            inc_desc += 1

        if strobj[inc_desc][0] == u'ДатаНачала':
            note.append(recordlist[inc_desc] + '\n')
            statements['begin_date'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT,
                                                     time.strptime(rmspaces(strobj[inc_desc][1]), '%d.%m.%Y'))
            tmp_acc, tmp_acc_res, slide_i = acc_number_parsing(strobj, inc_desc)
            inc_desc += 1
        else:
            raise osv.except_osv(_('Error'), _('Incorrect description of import file'))
        if strobj[inc_desc][0] == u'ДатаКонца':
            note.append(recordlist[inc_desc] + '\n')
            statements['end_date'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT,
                                                   time.strptime(rmspaces(strobj[inc_desc][1]), '%d.%m.%Y'))
            inc_desc += 1
        else:
            raise osv.except_osv(_('Error'), _('Incorrect description of import file'))
        acc_numbers = []
        while strobj[inc_desc][0] == u'РасчСчет':
            acc_number = {}
            acc_number['detail'] = []
            acc_number['statement_line'] = []
            acc_number['acc_number'] = rmspaces(strobj[inc_desc][1])
            acc_number['journal_id'] = False
            acc_number['bank_account'] = False
            bank_ids = self.pool.get('res.partner.bank').search(cr, uid,
                                                                [('acc_number', '=', acc_number['acc_number'])])
            if bank_ids and len(bank_ids) > 0:
                bank_accs = self.pool.get('res.partner.bank').browse(cr, uid, bank_ids)
                for bank_acc in bank_accs:
                    if bank_acc.journal_id.id:
                        acc_number['journal_id'] = bank_acc.journal_id
                        acc_number['bank_account'] = bank_acc
                        break
            if not acc_number['bank_account']:
                raise osv.except_osv(_('Error'), _("No matching Bank Account (with Account Journal) found.\n\n"
                                                   "Please set-up a Bank Account with as Account Number '%s' "
                                                   "and an Account Journal.") % (acc_number['acc_number']))
            acc_numbers.append(acc_number)
            inc_desc += 1

        def statement_line_parsing(obj, line_number):
            statementLine = {}
            statementLine['note'] = []
            while rmspaces(obj[line_number][0]) != u'КонецДокумента':
                if obj[line_number][0] == u'Номер':
                    statementLine['ref'] = rmspaces(obj[line_number][1])
                elif obj[line_number][0] == u'Дата':
                    statementLine['date'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT, time.strptime(rmspaces(obj[line_number][1]),'%d.%m.%Y'))
                elif obj[line_number][0] == u'Сумма':
                    statementLine['amount'] = rmspaces(obj[line_number][1])
                elif obj[line_number][0] == u'ПлательщикСчет':
                    statementLine['payer_acc'] = rmspaces(obj[line_number][1])
                elif obj[line_number][0] == u'Плательщик':
                    statementLine['payer'] = rmspaces(obj[line_number][1])
                elif obj[line_number][0] == u'ПлательщикИНН':
                    statementLine['payer_inn'] = rmspaces(obj[line_number][1])
                elif obj[line_number][0] == u'ПолучательСчет':
                    statementLine['recipient_acc'] = rmspaces(obj[line_number][1])
                elif obj[line_number][0] == u'Получатель':
                    statementLine['recipient'] = rmspaces(obj[line_number][1])
                elif obj[line_number][0] == u'ПолучательИНН':
                    statementLine['recipient_inn'] = rmspaces(obj[line_number][1])
                elif obj[line_number][0] == u'НазначениеПлатежа':
                    statementLine['name'] = rmspaces(obj[line_number][1])
                else:
                    statementLine['note'].append(obj[line_number][0] + ': ' + obj[line_number][1])
                line_number += 1
            line_number += 1
            return statementLine, line_number

        #for i in range(inc_desc,len(strobj)-1):
        i = inc_desc
        while rmspaces(strobj[i][0]) != u'КонецФайла':
            # _logger = logging.getLogger(__name__)
            # _logger.info('ENDFILE %s %s %s', i, len(strobj)-1, strobj[i][0])
            if strobj[i][0] == u'СекцияРасчСчет':  # Документ
                # _logger = logging.getLogger(__name__)
                # _logger.info('SEC RASH')
                for acc_one in acc_numbers:
                    if acc_one['acc_number'] == tmp_acc:
                        acc_one['detail'].append(tmp_acc_res)
                        break

            elif strobj[i][0] == u'СекцияДокумент':
                tmp_statementLine, slide_i = statement_line_parsing(strobj, i)
                # _logger = logging.getLogger(__name__)
                # _logger.info('SEC DOC')
                for acc_one in acc_numbers:
                    if acc_one['acc_number'] == tmp_statementLine['payer_acc'] or \
                                    acc_one['acc_number'] == tmp_statementLine['recipient_acc']:
                        tmp_statementLine['sequence'] = len(acc_one['statement_line']) + 1
                        acc_one['statement_line'].append(tmp_statementLine)
                        break
            if i < (len(strobj)-2):
                i += 1

        for slide_i, statement in enumerate(acc_numbers):
            period_id = self.pool.get('account.period').search(cr, uid,
                                                        [('company_id', '=', statement['journal_id'].company_id.id),
                                                        ('date_start', '<=', statements['end_date']),
                                                        ('date_stop', '>=', statements['end_date'])])
            if not period_id and len(period_id) == 0:
                raise osv.except_osv(_('Error'), _("The Statement New Balance date doesn't fall within a defined Accounting Period! Please create the Accounting Period for date %s for the company %s.") % (statements['end_date'], statement['journal_id'].company_id.name))
            statement['period_id'] = period_id[0]

            statement['note'] = note
            cr.execute('SELECT balance_end_real \
            FROM account_bank_statement \
            WHERE journal_id = %s and date <= %s \
            ORDER BY date DESC,id DESC LIMIT 1', (statement['journal_id'].id, statements['begin_date']))
            res = cr.fetchone()
            balance_start_check = res and res[0]
            if balance_start_check == None:
                if statement['journal_id'].default_debit_account_id and (statement['journal_id'].default_credit_account_id == statement['journal_id'].default_debit_account_id):
                    balance_start_check = statement['journal_id'].default_debit_account_id.balance
                else:
                    raise osv.except_osv(_('Error'), _("Configuration Error in journal %s!\nPlease verify the Default Debit and Credit Account settings.") % statement['journal_id'].name)
            if balance_start_check != tmp_acc_res['balance_start']:  # statement['balance_start']
                statement['note'].append(_("The Statement %s Starting Balance (%.2f) does not correspond with the previous Closing Balance (%.2f) in journal %s!") % (statement['acc_number'] + ' #' + statements['begin_date'] + ':' + statements['end_date'], tmp_acc_res['balance_start'], balance_start_check, statement['journal_id'].name))
            if not(statement.get('period_id')):
                raise osv.except_osv(_('Error'), _(' No transactions or no period in file !'))
            data = {
                'name': statement['acc_number'] + ' #' + statements['begin_date'] + ':' + statements['end_date'],
                'date': datetime.now(),
                'journal_id': statement['journal_id'].id,
                'period_id': statement['period_id'],
                'balance_start': tmp_acc_res['balance_start'],   # 'balance_start': statement['balance_start'],
                'balance_end_real': tmp_acc_res['balance_end'],
            }
            statement['id'] = self.pool.get('account.bank.statement').create(cr, uid, data, context=context)
            for line in statement['statement_line']:
                partner = None
                partner_id = None
                invoice = False
                if line['payer_acc'] == statement['acc_number']:
                    pass
                else:
                    ids = self.pool.get('res.partner.bank').search(cr, uid, [('acc_number', '=', str(line['payer_acc']))])
                    _logger = logging.getLogger(__name__)
                    _logger.info('IDS %s', ids)
                    p_id = None

                    if ids and len(ids) > 0:
                        partner = self.pool.get('res.partner.bank').browse(cr, uid, ids[0], context=context)
                        _logger = logging.getLogger(__name__)
                        _logger.info('PARTNER %s', partner)
                        p_id = partner.partner_id.id
                        line['account'] = partner.partner_id.property_account_receivable.id
                        ids = ids[0]
                    else:
                        _logger = logging.getLogger(__name__)
                        _logger.info('PARTNER_NO %s', ids)
                        ids = ''
                    if not partner and not invoice:
                        line['account'] = temporaryaccount
                        line['name'] = line['name'] + '\n' + line['payer_inn']
                    data = {
                        'name': line['name'],
                        'note': '\n'.join(line['note']),
                        'date': line['date'],
                        'amount': line['amount'],
                        'partner_id': p_id,
                        #'account_id': line['account'], #Looks like reconsilation will not work with it
                        'statement_id': statement['id'],
                        'ref': line['ref'],
                        'sequence': line['sequence'],
                        'bank_account_id': ids,
                    }
                    data_check = {
                        'date': line['date'],
                        'amount': line['amount'],
                        'ref': line['ref'],
                        'account_id': line['account'],
                    }
                    ids_line_statement = self.pool.get('account.bank.statement.line').search(cr, uid,
                                                                                [('date', '=', data_check['date']),
                                                                                ('amount', '=', data_check['amount']),
                                                                                ('ref', '=', data_check['ref']),
                                                                                #('account_id', '=', data_check['account_id'])
                                                                                ])
                    if ids_line_statement:
                        statement['note'].append(_('Statement line %s from %s alredy exist.') %
                                                (data_check['ref'], data_check['date']))
                    else:
                        self.pool.get('account.bank.statement.line').create(cr, uid, data, context=context)

                if statement['note']:
                    self.pool.get('account.bank.statement').write(cr, uid, [statement['id']],
                                                              {'rusimport_note': '\n'.join(statement['note'])},
                                                              context=context)
        model, action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid,
                                                                               'account', 'action_bank_statement_tree')
        action = self.pool[model].browse(cr, uid, action_id, context=context)
        return {
            'name': action.name,
            'view_type': action.view_type,
            'view_mode': action.view_mode,
            'res_model': action.res_model,
            'domain': action.domain,
            'context': action.context,
            'type': 'ir.actions.act_window',
            'search_view_id': action.search_view_id.id,
            'views': [(v.view_id.id, v.view_mode) for v in action.view_ids]
        }

def rmspaces(s):
    return " ".join(s.split())


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('newshub', '0021_society'),
    ]

    operations = [
        migrations.RenameField(
            model_name='society',
            old_name='administrators',
            new_name='admins',
        ),
    ]


##ex 1
##Faça um algoritmo que leia as informações dos alunos:
##MATRICULA, NOTA1, NOTA2, NOTA3, com o fim das informções indicado por
##MATRICULA=999. Para cada aluno, deve ser calculada a média de acordo com a
##seguinte fórmula:

##Média final = (2*NOTA1 + 3*NOTA2 + 4*NOTA3) / 9
##Se média >= 7.0 => Imprima ‘APROVADO’, além da MATRICULA e Média final.
##Se média < 7.0 => Imprima ‘REPROVADO’, além da MATRICULA e Média final.

##mat = int(input("Insira a matrícula:\n"))
##reg =[]
##
##while mat != 999:
##
##    n1 = float(input("Insira a nota 1:\n"))
##    n2 = float(input("Insira a nota 2:\n"))
##    n3 = float(input("Insira a nota 3:\n"))
##    media = (2*n1+3*n2+4*n3)/9
##    if media >= 7.0:
##        status = ["Aprovado", mat, media]
##        print ("Aprovado", mat, media)
##    else:
##        status = ["Reprovado", mat, media]
##        print ("Reprovado", mat, media)
##
##    reg.append(status)
##    mat = int(input("Insira a matrícula:\n"))

####ex2
##Dados dois números inteiros positivos x e y,
##fazer a divisão de x por y sem usar o operador de divisão.
##
##x,y = int(input("Insira um número inteiro positivo:\n")),int(input("Insira outro número inteiro positivo:\n"))
##count = 0
##valini=x
##while x > y:
##    x-=y
##    count+=1
##
##print(valini,"dividido por",y,"é igual à",count, "com resto", x)

##ex3

##a = 1
##b = 50
##alpha = 0
##while a <= 50:
##    alpha += (2**a)/b
##    a+=1
##    b-=1
##
##print(alpha,a,b)

##ex4

##n = int(input("Insira um valor inteir n para clacular pi, n > 0:\n"))
##count = 1
##pi = 0
##while count <= n:
##    pi += 4/count
##    count +=2

##Ex 5
import math, cmath
x = float(input("Insira um angulo para calcular seu cosseno:\n"))
x = x*cmath.pi/180
print (x)
n = int(input("Insira um valor inteir n para clacular cos x, n > 0:\n"))
count = 1
cos = 1.0
fat = 0.0
while count <= n:
    fat =(math.factorial(2*n) )
    cos +=(-1**count)*(x**(2*count))/fat
    print(cos)
    count +=1
print(cos)

## ex7
##
##ent = int(input("Insira um número inteiro maior ou igual a 10:\n"))
##
##vetor = []
##resto = 1
##counti = 0
##countj = 0
##indicador = 0
##while ent > 0:
##
##    resto = ent%10
##    vetor.append(resto)
##    ent =ent//10
##
##comp = len(vetor)
##
##while counti < comp:
##    countj = counti+1
##    while countj<comp:
##        if(vetor[counti] == vetor[countj]):
##            print("há dois núemros",vetor[counti] ,"iguais adjacentes")
##            indicador = 1
##
##        countj+=1
##    counti+=1
##if(indicador ==0):
##    print("não há dois núemros iguais adjacentes")

## ex 8

##num = int(input("Insira um número inteiro na base 10:\n"))
##resto = 0
##vetor = []
##while num >=1:
##    resto = num%2
##    vetor.append(resto)
##    num = num//2
##
##tamanho = len(vetor)
##tamanho -= 1
##inicio = 0
##aux = 0
##
##while tamanho > inicio:
##    aux = vetor[tamanho]
##    vetor[tamanho]= vetor[inicio]
##    vetor[inicio] = aux
##    tamanho -= 1
##    inicio += 1
##
##print (vetor)


# imports
import sys
import os

sys.path.insert(1, 'models')
# ===================================== Import Architectures =====================================

# Imports needed for the following code to work

import NishNet as NN
import VGG16 as VGG
import ResNet as RN
import LeNet as LN

class userInput:
    def __init__(self):
        # Store values that are used in the main.py
        # File names
        self.SAVE = False
        self.DATA_REBUILD = False
        self.DATA_LOCATION = "data"
        self.SAVE_LOCATION = "edited"
        self.MODEL_SAVE = "saved"
        self.MODEL_NAME = ""

        # Hyper-Parameter Settings
        self.MOMENTUM = 0.9
        self.WEIGHT_DECAY = 0.0005
        self.LR = 0.01
        self.BATCH_SIZE = 64
        self.EPOCHS = 100
        self.IMAGE_SIZE = -1
        self.FACTOR = 0.1
        self.TRAIN_PERCENT = 0.7

        # Model
        self.SELECTED_MODEL = None
        self.FUNCTION = -1;

    # Function that deals with error handling with regards of choosing a range between x1 -> x2
    # Returns true or false
    @staticmethod
    def askRange(start, end, question: str, reply=None):
        questionAsked = False
        if reply is None:
            reply = question

        while True:
            try:
                if not questionAsked:
                    questionAsked = True
                    rng = int(input(question))
                else:
                    rng = int(input(reply))
            except ValueError or TypeError:
                print("Invalid string input, please enter an integer value \n")
                continue

            if not start <= rng <= end:
                print("Invalid input, please enter value between 1 and {}\n".format(end))
                continue
            else:
                return rng

    # Function that asks user for an integer where the negative is true when the program wants something greater than
    # 0
    @staticmethod
    def askDigit(question: str, reply=None, negative=True):
        questionAsked = False
        if reply is None:
            reply = question

        while True:
            try:
                if not questionAsked:
                    questionAsked = True
                    dgt = int(input(question))
                else:
                    dgt = int(input(reply))
            except ValueError or TypeError:
                print("Invalid string input, please enter an integer value \n")
                continue

            if dgt <= 0 and negative:
                print("Invalid input, please enter value greater than 0\n")
                continue
            else:
                return dgt

    @staticmethod
    # Checks if the user gave a float as an answer
    def askFloat(question: str, reply=None, negative=True):
        questionAsked = False
        if reply is None:
            reply = question

        while True:
            try:
                if not questionAsked:
                    questionAsked = True
                    dgt = float(input(question))
                else:
                    dgt = float(input(reply))
            except ValueError or TypeError:
                print("Invalid string input, please enter an integer value \n")
                continue

            if dgt <= 0 and negative:
                print("Invalid input, please enter value greater than 0\n")
                continue
            else:
                return dgt

    # Function that detects asks the user yes or no and outputs true or false
    @staticmethod
    def askYesNo(question: str):
        answer = input(question)

        while answer != "y" and answer != "n":
            print("Invalid input, please enter either 'y' or 'n' \n")
            answer = input("(y/n): ")

        return answer == "y"

    # Function that asks user the necessary information to operate the program
    def initValues(self):
        # A
        models = {
            1: LN.LeNet(),
            2: NN.NishNet(),
            3: VGG.CustomVGG13(),
            4: RN
        }

        imageSize = {
            1: 32,
            2: 64,
            3: 64,
            4: 64
        }

        ResNet = {
            1: RN.ResNet50(),
            2: RN.ResNet101(),
            3: RN.ResNet152(),
            4: RN.ResNet34(),
            5: RN.ResNet18(),
            6: RN.ResNet56()
        }

        # ========================== USER INPUT ========================== #
        print(
            """
            +=======================================================+
            |                                                       |
            |                EMOTION RECOGNITION CNN                |
            |                                                       |
            |       Created by: Jason Buquiran and Shiyao Wang      |
            |                                                       |
            +=======================================================+

            """
        )
        #Asks the user to input which settings they want to do
        choice = self.askRange(1, 3, "Select which tasks you would like to choose: \n"
                                     "1. Train new network \n"
                                     "2. Train pre-existing network \n"
                                     "3. Evaluate pre-existing network \n"
                                     "\n"
                                     "CHOICE: ")
        self.FUNCTION = choice
        # Choose a network to start training on
        modelOption = self.askRange(1, len(models),
                                    "Please select Architecture to use, enter a number to select the model: \n"
                                    "1. LeNet-5 \n"
                                    "2. VGG11 \n"
                                    "3. VGG13 \n"
                                    "4. ResNet \n"
                                    "\n"
                                    "MODEL: ", "MODEL: ")

        self.SELECTED_MODEL = models[modelOption]

        # More options for ResNet
        if self.SELECTED_MODEL == RN:
            option_Resnet = self.askRange(1, len(models),
                                          "Please select specific ResNet Model: \n"
                                          "1. ResNet50 \n"
                                          "2. ResNet101 \n"
                                          "3. ResNet152 \n"
                                          "4. ResNet34 \n"
                                          "5. ResNet18 \n"
                                          "6. ResNet110 \n"
                                          "\n"
                                          "ResNet: ", "ResNet: ")
            self.SELECTED_MODEL = ResNet[option_Resnet]

        # Automatically deals with image size
        self.IMAGE_SIZE = imageSize[modelOption]
        print("Image Size is " + str(self.IMAGE_SIZE))

        if choice == 1:

            print(
                """\n
                +==============================================================+
                |                   HYPER-PARAMETER SETTINGS                   |
                +==============================================================+
                \n""")

            # Hyper-Parameter settings
            if not self.askYesNo("Do you want to use the default values? "):
                self.EPOCHS = self.askDigit("Number of Epoch: ")
                self.BATCH_SIZE = self.askDigit("Batch size: ")
                self.LR = self.askFloat("Learning rate: ")
                self.MOMENTUM = self.askFloat("Momentum: ")
                self.WEIGHT_DECAY = self.askFloat("Weight Decay: ")
                self.FACTOR = self.askFloat("Factor: ")

            print("")

            print(
                """\n
                +==============================================================+
                |                 MODEL AND DATA SAVE LOCATION                 |
                +==============================================================+
                \n""")

            # Splits the file to its training, validation and testing sets
            if len(os.listdir(self.SAVE_LOCATION)) == 0:
                print("Folder still needs to be sorted")
                self.DATA_REBUILD = True
            else:
                print("Folder already sorted")

            # Asks user for their model's name
            self.MODEL_NAME = str(input("Name of saved model: "))

        elif choice == 2:

            print(
                """\n
                +==============================================================+
                |                   HYPER-PARAMETER SETTINGS                   |
                +==============================================================+
                \n""")

            self.EPOCHS = self.askDigit("Number of Epoch: ")
            self.BATCH_SIZE = self.askDigit("Batch size: ")

            print(
                """\n
                +==============================================================+
                |                 MODEL AND DATA LOAD LOCATION                 |
                +==============================================================+
                \n""")

            # Splits the file to its training, validation and testing sets
            if len(os.listdir(self.SAVE_LOCATION)) == 0:
                print("Folder still needs to be sorted")
                self.DATA_REBUILD = True
            else:
                print("FOLDER ALREADY SORTED")

            # Asks user for their model's name
            self.MODEL_NAME = str(input("Name of saved model: "))
        else:

            print(
                """\n
                +==============================================================+
                |                 MODEL AND DATA LOAD LOCATION                 |
                +==============================================================+
                \n""")

            # Splits the file to its training, validation and testing sets
            if len(os.listdir(self.SAVE_LOCATION)) == 0:
                print("Folder still needs to be sorted")
                self.DATA_REBUILD = True
            else:
                print("FOLDER ALREADY SORTED")

            # Asks user for their model's name
            self.MODEL_NAME = str(input("Name of saved model: "))


# coding: utf-8

import os
from fabkit import filer, sudo, env, local, scp, Package
from fablib.base import SimpleBase
# from fablib import git
from fablib.python import Python
from oslo_config import cfg

CONF = cfg.CONF

class FabPackage(SimpleBase):
    def __init__(self):
        self.data_key = 'fabkit_tools'
        self.data = {
            'user': 'nobody',
            'group': 'nobody',
            'task_patterns': 'local.*,check.*',
            'use_package': False,
            'package_name': 'fabkit',
        }

        self.services = [
            'fabagent',
            'fabagent-central',
        ]

        self.packages = {
            'CentOS Linux 7.*': [
                'epel-release',
                'nodejs',
                'npm',
            ],
            'Ubuntu 14.*': [
                'nodejs',
                'npm',
            ]
        }

    def init_before(self):
        self.python = Python(CONF.client.package_prefix)

    def init_after(self):
        self.data['owner'] = '{0}:{1}'.format(self.data['user'], self.data['group'])
        self.data['host'] = env.host
        self.data['prefix'] = CONF.client.package_prefix

    def setup(self):
        data = self.init()

        var_dir = CONF.client.package_var_dir
        tmp_dir = os.path.join(var_dir, 'tmp')
        log_dir = '/var/log/fabkit'
        common_repo = '{0}/fabkit-repo-common'.format(var_dir)
        client_repo = '{0}/fabkit-repo-client'.format(var_dir)
        server_repo = '{0}/fabkit-repo-server'.format(var_dir)

        if data['use_package']:
            Package(data['package_name']).install()
            return

        self.install_packages()
        self.python.setup()
        filer.mkdir(var_dir, owner=data['owner'])
        filer.mkdir(log_dir, owner=data['owner'])
        filer.mkdir(tmp_dir, owner=data['owner'], mode='777')

        filer.mkdir(common_repo, owner=data['owner'])
        filer.mkdir(client_repo, owner=data['owner'])
        filer.mkdir(server_repo, owner=data['owner'])

        sudo('rm -rf {0}/fabfile*'.format(tmp_dir))
        fabfile_tar_gz = os.path.join(tmp_dir, 'fabfile.tar.gz')
        scp('/tmp/fabfile.tar.gz', fabfile_tar_gz)

        sudo('rm -rf {0}/fabfile'.format(common_repo))
        sudo('cd {0} && tar xzf {1} && '
             'cp -r fabfile {2}/fabfile'.format(
                 tmp_dir, fabfile_tar_gz, common_repo))

        sudo('{0}/bin/pip install -r {1}/fabfile/requirements.txt'.format(
             CONF.client.package_prefix, common_repo))

        data['repo'] = client_repo
        filer.template('{0}/bin/fabclient'.format(CONF.client.package_prefix),
                       src='fabric.sh', data=data, mode='755')

        data['repo'] = server_repo
        filer.template('{0}/bin/fabserver'.format(CONF.client.package_prefix),
                       src='fabric.sh', data=data, mode='755')

        filer.template('{0}/bin/fabnode'.format(CONF.client.package_prefix),
                       src='fabnode.sh', data=data, mode='755')

        filer.template('/etc/systemd/system/fabagent.service',
                       src='systemd.service', data={
                           'description': 'fabagent',
                           'exec': '/opt/fabkit/bin/fabclient agent',
                           'user': 'root',
                       })

        filer.template('/etc/systemd/system/fabagent-central.service',
                       src='systemd.service', data={
                           'description': 'fabagent',
                           'exec': '/opt/fabkit/bin/fabclient agent_central',
                           'user': 'root',
                       })

        filer.template('/etc/systemd/system/fabnode.service',
                       src='systemd.service', data={
                           'description': 'fabnode',
                           'exec': '/opt/fabkit/bin/fabnode',  # noqa
                           'user': 'root',
                       })

        sudo('systemctl daemon-reload')

        sudo('npm install -g coffee-script')
        sudo('cd {0}/fabfile/core/webapp/fabnode && '
             'npm install'.format(common_repo))

    def create_tar(self):
        if env.host == env.hosts[0]:
            local(
                'rm -rf /tmp/fabfile && '
                'cp -r {0} /tmp/fabfile && '
                'find /tmp/fabfile -name .git | xargs rm -rf && '
                'cd /tmp/ && tar cfz fabfile.tar.gz fabfile'.format(CONF._fabfile_dir)
            )


from django.contrib import admin

from django.contrib.admin import AdminSite
from django.http import HttpResponse, HttpResponseRedirect

from .models import Category,Item,SalesMeasure,Presentation,OrderItems,Order,Customer,Payment,Shop
from django.shortcuts import render,redirect
from django.contrib.admin import *

from GorceryDelivery.forms import OrderDisplayForm
from GorceryDelivery.modules.PDFGenerator import *
from GorceryDelivery.modules.AggregateOrderPDF import *
from datetime import datetime

class MyAdminSite(AdminSite):

    def __init__(self, *args, **kwargs):
        """
        allows complete inheritance from the default admin: default registration of USER and GROUP in admin
        :param args:
        :param kwargs:
        """
        super(MyAdminSite, self).__init__(*args, **kwargs)
        self._registry.update(site._registry)  # PART 2

    def get_urls(self):
        from django.urls import path,re_path
        urls = super().get_urls()
        urls += [

            path('customer_orders/', self.admin_view(self.get_daily_orders)),
            path('customer_orders/<str:delivery_date>/', self.admin_view(self.display_daily_orders)),
            re_path(r'^download_single_order/(\d+)/$', self.admin_view(self.download_single_order)),
            re_path(r'^customer_orders/details/(\d+)/$', self.admin_view(self.display_order_details)),
            path('customer_orders/items_by_day/<str:delivery_date>/', self.admin_view(self.aggregate_daily_orders))
            #path('customer_orders/print_all/<str:delivery_date>/', self.admin_view(self.print_orders_by_day))
        ]
        return urls

    def get_daily_orders(self, request):
        """
        View function: allows displays of all order given a specific delivery date
        :param request: Http request
        :return: Http redirect to display page; if method is not 'POST', renders delivery date form
        """

        if request.method == 'POST':
            form = OrderDisplayForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                next_url = '/admin/customer_orders/' + cd.get('date') + '/'
                #assert False
                return HttpResponseRedirect(next_url)# redirect to url of 'display daily orders'

        else:
            form = OrderDisplayForm()

        return  render(request, 'admin/get_orders.html', {'form': form})

    def display_daily_orders(self, request, delivery_date):
        """
        View function: actually dispays the orders
        :param request: Http request
        :param delivery_date: delivery date to query
        :return: renders a tabled list of all the orders
        """

        date_error = False
        # convert the date first
        try:#since date input is exposed using get: anticipating incorrect input
            objDate = datetime.strptime(delivery_date, '%d-%m-%Y')
            delivery_date = objDate.strftime('%Y-%m-%d')
        except:
            delivery_date = None
            date_error = True

        date_orders = Order.objects.filter(delivery_date=delivery_date)

        return render(request, 'admin/show_orders.html', {'orders': date_orders,
                                                          'date': delivery_date,
                                                          'date_error': date_error})

    def download_single_order(self, request, order_Id):
        """
        View function: downloads the user order form the 'display daily orders' list as pdf
        :param request: Http request
        :param order_Id: pk of the order in db
        :return: pdf file as Http response
        """

        bought_items = None
        order_details = None

        order_Id = int(order_Id)

        try:
            order_details = Order.objects.get(id=order_Id)
        except:
            order_details = None

        bought_items = OrderItems.objects.filter(order=order_details)

        if not bought_items == None:
            the_report = PDFGenerator(request,order_details, bought_items)
            return the_report.download_user_order()

    def display_order_details(self, request, order_id):
        """
        View function: displays the details of a selected custmer order
        :param request: Http request
        :param order_id: pk of the selected order
        :return: renders the details
        """

        order_details = None
        bought_items = None
        order_id = int(order_id)

        try:
            order_details = Order.objects.get(id=order_id)
        except:
            order_details = None

        bought_items = OrderItems.objects.filter(order=order_details)

        return render(request,'admin/display_order_details.html', { 'order': order_details,
                                                                    'bought_items': bought_items})

    def aggregate_daily_orders(self, request, delivery_date):
        """
        View Function: downloads aggregated orders for a given date showi ng an item and how many times it was ordered.
        :param request: Http request
        :param delivery_date: delivery date
        :return: pdf file as http response
        """

        date_error = False
        try:
            objDate = datetime.strptime(delivery_date, '%Y-%m-%d')
            delivery_date = objDate.strftime('%Y-%m-%d')
        except:
            date_error = True

        order_items_list = []

        if not date_error:
            order_list = Order.objects.filter(delivery_date = delivery_date)
            for order in order_list:
                item_list = OrderItems.objects.filter(order= order)
                order_items_list.append(item_list)

            daily_order = AggregateOrderPDF(order_items_list, delivery_date)
            daily_order.compute_aggregate_list()
            return  daily_order.download_aggregate_order()

        #assert False

admin_site = MyAdminSite()

@admin.register(Item, site= admin_site)
class AdminItem(admin.ModelAdmin):
    list_display = ('name', 'description', 'price', 'discounted_price', 'availability')
    list_filter = ('category', 'availability')
    search_fields = ('name',)
    list_per_page = 10

@admin.register(Category, site =admin_site)
class AdminCategory(admin.ModelAdmin):
    list_display = ('name', 'description')
    list_per_page = 10
    search_fields = ('name',)

@admin.register(Customer, site =admin_site)
class AdminCustomer(admin.ModelAdmin):
    list_display = ('user_profile','gender', 'phone_no', 'preffered_delivery_addr')
    list_per_page = 10

@admin.register(Order, site=admin_site)
class AdminOrder(admin.ModelAdmin):
    list_display =('buyer_firstname', 'buyer_lastname', 'buyer_gender','buyer_email', 'buyer_phone_no',
                   'order_date', 'paid_for','delivery_date','order_total','delivery_addr', 'customer' )
    list_per_page = 10
    list_filter = ('buyer_gender', 'paid_for', 'order_date', 'delivery_date')
    search_fields = ( 'buyer_firstname', 'buyer_lastname','buyer_phone_no','buyer_email')

@admin.register(SalesMeasure, site =admin_site)
class AdminSalesMeasure(admin.ModelAdmin):
    list_display = ('name','description', 'item', 'price')
    list_per_page = 10
    search_fields = ('item__name','name')
    list_filter = ('item',)

@admin.register(Presentation, site = admin_site)
class AdminPresentation(admin.ModelAdmin):
    list_per_page = 10
    list_display = ('name', 'description', 'item')

@admin.register(Payment, site = admin_site)
class AdminPayment(admin.ModelAdmin):
    list_display = ('order', 'payment_amount',  'timestamp', 'transaction_reference', 'status','description' )
    list_per_page = 10

    def payment_amount(self, obj):
        return obj.order.order_total

@admin.register(OrderItems, site=admin_site)
class AdminOrderItem(admin.ModelAdmin):
    list_display = ('order_item_desc', 'order_item_price', 'quantity', 'price_by_qty')
    list_per_page = 10
    list_filter = ('item', 'order')
    search_fields = ('item__name', 'order__buyer_firstname')

@admin.register(Shop, site=admin_site)
class Shop(admin.ModelAdmin):
    list_display = ('shop_name','site_domain', 'address', 'email', 'phone_number', 'phone_number_2', 'is_active')


import torch
from .lowrank import LowRank
from .exceptions import VectorError

def sigmoid(t):
    return 2.0 * (torch.sigmoid(t) - 0.5)

class AlmostOrthogonal(LowRank):
    fs = {"sigmoid": sigmoid, "tanh": torch.tanh, "sin": torch.sin}

    def __init__(self, size, lam, f="sin", triv="expm"):
        r"""
        Manifold of matrices with singular values in the interval :math:`(1-\lambda, 1+\lambda)`.

        The possible default maps are the :math:`\sin,\,\tanh` functions and a rescaled
        sigmoid. The sigmoid is rescaled as :math:`\operatorname{sigmoid}(x) = 2\sigma(x) - 1`
        where :math:`\sigma` is the usual sigmoid function.

        Args:
            size (torch.size): Size of the tensor to be applied to
            lam (float): Radius. A float in the interval [0, 1]
            f (str or callable): Optional. One of `["sigmoid", "tanh", "sin"]`
                or a callable that maps real numbers to the interval [-1, 1].
                Default: `"sin"`
            triv (str or callable): Optional.
                A map that maps :math:`\operatorname{Skew}(n)` onto the orthogonal
                matrices surjectively. This is used to optimize the Q in the eigenvalue
                decomposition. It can be one of `["expm", "cayley"]` or a custom
                callable. Default: `"expm"`

        """
        super().__init__(size, AlmostOrthogonal.rank(size), triv=triv)
        if f not in AlmostOrthogonal.fs.keys() and not callable(f):
            raise ValueError(
                "Argument f was not recognized and is "
                "not callable. Should be one of {}. Found {}".format(
                    list(AlmostOrthogonal.fs.keys()), f
                )
            )

        if lam < 0.0 or lam > 1.0:
            raise ValueError("The radius has to be between 0 and 1. Got {}".format(lam))

        if callable(f):
            self.f = f
        else:
            self.f = AlmostOrthogonal.fs[f]

        self.lam = lam

    @classmethod
    def rank(cls, size):
        if len(size) < 2:
            raise VectorError(cls.__name__, size)
        return min(*size[-2:])

    def fibration(self, X):
        U, S, V = X
        S = 1.0 + self.lam * self.f(S)
        return super().fibration((U, S, V))


import time
import io

def parseFastaFile1(infile, db):
    with open(infile, 'r') as inFile:
        for line in inFile:
            if line[0] == ">":
                ident, desc = line[1:].strip().split(maxsplit=1)
                db.append({'id': ident, 'description': desc, 'sequence': "", 'raw': line})
            else:
                db[-1]['sequence'] += line.rstrip()
                db[-1]['raw'] += line

def parseFastaFile2(infile, db):
    with open(infile, "rb") as inFile:
        for line in inFile:
            if line[0] == 62:  # bin token for ">"
                ident, desc = line[1:].strip().split(maxsplit=1)
                db.append({'id': ident,
                           'description': desc,
                           'sequence': bytearray(),
                           'raw': bytearray(line)})
            else:
                db[-1]['sequence'] += (line.rstrip())
                db[-1]['raw'] += (line)

# version using StringIO
def parseFastaFile3(infile, db):
    with open(infile, "r") as inFile:
        for line in inFile:
            if line[0] == ">":
                ident, desc = line[1:].strip().split(maxsplit=1)
                db.append({'id': ident,
                           'description': desc,
                           'sequence': io.StringIO(),
                           'raw': io.StringIO(line)})
            else:
                db[-1]['sequence'].write(line.rstrip())
                db[-1]['raw'].write(line)

# version using BytesIO
def parseFastaFile4(infile, db):
    with open(infile, "rb") as inFile:
        for line in inFile:
            if line[0] == 62:  # bin token for ">"
                ident, desc = line[1:].strip().split(maxsplit=1)
                db.append({'id': ident,
                           'description': desc,
                           'sequence': io.BytesIO(),
                           'raw': io.BytesIO(line)})
            else:
                db[-1]['sequence'].write(line.rstrip())
                db[-1]['raw'].write(line)

# Stop time of function calls
def stop_time(func, *args, **kargs):
    start = time.time()

    result = func(*args, **kargs)

    end = time.time()
    print("Function {} takes {:.3} seconds".format(func.__name__, end - start))
    return result

d = []

res1 = stop_time(parseFastaFile1, "../examples/long.fasta", db=d)
res2 = stop_time(parseFastaFile2, "../examples/long.fasta", db=d)
res3 = stop_time(parseFastaFile3, "../examples/long.fasta", db=d)
res4 = stop_time(parseFastaFile4, "../examples/long.fasta", db=d)

# Compare both sequences
print(d[0]['sequence'] == d[1]['sequence'].decode())
print(d[0]['sequence'] == d[2]['sequence'].getvalue())
print(d[0]['sequence'] == d[3]['sequence'].getvalue().decode())


from utils import *

def create_model(input_shape, anchors, num_classes, freeze_body=False):
    K.clear_session()  # get a new session
    image_input = Input(shape=(None, None, 3))
    h, w = input_shape
    num_anchors = len(anchors)
    y_true = [Input(shape=(h // {0: 32, 1: 16, 2: 8}[l], w // {0: 32, 1: 16, 2: 8}[l], \
                           num_anchors // 3, num_classes + 5)) for l in range(3)]

    model_body = yolo_body(image_input, num_anchors // 3, num_classes)
    print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))
    model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',
                        arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})(
        [*model_body.output, *y_true])
    model = Model([model_body.input, *y_true], model_loss)
    return model

def train(model, annotation_path, input_shape, anchors, num_classes):
    model.compile(optimizer='adam', loss={
        'yolo_loss': lambda y_true, y_pred: y_pred})
    checkpoint = ModelCheckpoint("my.h5",
                                 monitor='val_loss', save_weights_only=True, save_best_only=True, period=1)
    batch_size = 10
    val_split = 0.1
    with open(annotation_path) as f:
        lines = f.readlines()
    np.random.shuffle(lines)
    num_val = int(len(lines) * val_split)
    num_train = len(lines) - num_val
    print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))
    model.fit_generator(data_generator_wrap(lines[:num_train], batch_size, input_shape, anchors, num_classes),
                        steps_per_epoch=max(1, num_train // batch_size),
                        validation_data=data_generator_wrap(lines[num_train:], batch_size, input_shape, anchors,
                                                            num_classes),
                        validation_steps=max(1, num_val // batch_size),
                        epochs=500,
                        callbacks=[checkpoint],
                        initial_epoch=0)

if __name__ == '__main__':
    label_path = 'label.txt'  # 标签地址
    classes_path = 'model_data/classes.txt'  # 类别文件
    anchors_path = 'model_data/yolo_anchors.txt'  # anchors文件
    class_names = get_classes(classes_path)
    anchors = get_anchors(anchors_path)
    input_shape = (416, 416)
    model = create_model(input_shape, anchors, len(class_names))
    train(model, label_path, input_shape, anchors, len(class_names))


import argparse
import csv
import math
import os
import os.path as osp

import joblib
import numpy as np
import src.ast_toolbox.mcts.BoundedPriorityQueues as BPQ
# from example_save_trials import *
import tensorflow as tf
from CartPole.cartpole_simulator import CartpoleSimulator
# from garage.tf.algos.trpo import TRPO
from garage.baselines.linear_feature_baseline import LinearFeatureBaseline
from garage.misc import logger
from garage.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy
from src.ast_toolbox import TRPO
from src.ast_toolbox import ASTEnv
from src.ast_toolbox import TfEnv
from src.ast_toolbox.rewards import ASTRewardS

os.environ["CUDA_VISIBLE_DEVICES"] = "-1"  # just use CPU

# Logger Params
parser = argparse.ArgumentParser()
parser.add_argument('--exp_name', type=str, default='cartpole')
parser.add_argument('--nd', type=int, default=1)
parser.add_argument('--sut_itr', type=int, default=5)
parser.add_argument('--n_trial', type=int, default=10)
parser.add_argument('--trial_start', type=int, default=0)
parser.add_argument('--n_itr', type=int, default=1000)
parser.add_argument('--step_size', type=float, default=5.0)
parser.add_argument('--batch_size', type=int, default=2000)  # 50000
parser.add_argument('--snapshot_mode', type=str, default="none")
parser.add_argument('--snapshot_gap', type=int, default=500)
parser.add_argument('--log_dir', type=str, default='./Data/AST/TRPO')
parser.add_argument('--args_data', type=str, default=None)
args = parser.parse_args()
args.log_dir += ('B' + str(args.batch_size) + 'Step' + str(args.step_size))

top_k = 10
max_path_length = 100
open_loop = False

tf.set_random_seed(0)
sess = tf.Session()
sess.__enter__()

# Instantiate the env
data = joblib.load("../CartPole/ControlPolicy/itr_" + str(args.sut_itr) + ".pkl")
sut = data['policy']
reward_function = ASTRewardS()

simulator = CartpoleSimulator(sut=sut, max_path_length=100, use_seed=False, nd=args.nd)
env = TfEnv(ASTEnv(open_loop=open_loop,
                   simulator=simulator,
                   fixed_init_state=True,
                   s_0=[0.0, 0.0, 0.0 * math.pi / 180, 0.0],
                   reward_function=reward_function,
                   ))

# Create policy
policy = GaussianMLPPolicy(
    name='ast_agent',
    env_spec=env.spec,
    hidden_sizes=(128, 64, 32)
)

with open(osp.join(args.log_dir, 'total_result.csv'), mode='w') as csv_file:
    fieldnames = ['step_count']
    for i in range(top_k):
        fieldnames.append('reward ' + str(i))
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()

    for trial in range(args.trial_start, args.trial_start + args.n_trial):
        # Create the logger
        log_dir = args.log_dir + '/' + str(trial)

        tabular_log_file = osp.join(log_dir, 'process.csv')
        text_log_file = osp.join(log_dir, 'text.txt')
        params_log_file = osp.join(log_dir, 'args.txt')

        logger.set_snapshot_dir(log_dir)
        logger.set_snapshot_mode(args.snapshot_mode)
        logger.set_snapshot_gap(args.snapshot_gap)
        logger.log_parameters_lite(params_log_file, args)
        if trial > args.trial_start:
            old_log_dir = args.log_dir + '/' + str(trial - 1)
            logger.pop_prefix()
            logger.remove_text_output(osp.join(old_log_dir, 'text.txt'))
            logger.remove_tabular_output(osp.join(old_log_dir, 'process.csv'))
        logger.add_text_output(text_log_file)
        logger.add_tabular_output(tabular_log_file)
        logger.push_prefix("[" + args.exp_name + '_trial ' + str(trial) + "]")

        np.random.seed(trial)

        params = policy.get_params()
        sess.run(tf.variables_initializer(params))
        baseline = LinearFeatureBaseline(env_spec=env.spec)
        # optimizer = ConjugateGradientOptimizer(hvp_approach=FiniteDifferenceHvp(base_eps=1e-5))

        top_paths = BPQ.BoundedPriorityQueue(top_k)
        algo = TRPO(
            env=env,
            policy=policy,
            baseline=baseline,
            batch_size=args.batch_size,
            step_size=args.step_size,
            n_itr=args.n_itr,
            store_paths=True,
            # optimizer= optimizer,
            max_path_length=max_path_length,
            top_paths=top_paths,
            plot=False,
        )

        algo.train(sess=sess, init_var=False)

        row_content = dict()
        row_content['step_count'] = args.n_itr * args.batch_size
        i = 0
        for (r, action_seq) in algo.top_paths:
            row_content['reward ' + str(i)] = r
            i += 1
        writer.writerow(row_content)


# Eric Sanchez @ericd34n on 20180329

def selection_sort(A):
    for i in range(len(A)):
        key, mindex = A[i], i
        for j in range(i, len(A)):
            if A[j] < key:
                key = A[j]
                mindex = j
        if mindex > i:
            A[i], A[mindex] = A[mindex], A[i]


from flask_restful import Resource, reqparse, abort, fields, marshal_with
from datetime import datetime
from . import citizen_api
from ..database_models import Citizen
from .. import data_handler, sms_handler
from app import db

# Parser to check that required arguments are sent to add a citizen to the database
citizen_put_args = reqparse.RequestParser()
citizen_put_args.add_argument("id_citizen", type=str, required=True,
                              help="The ID of the citizen is required. The argument should be a String.")
citizen_put_args.add_argument("email", type=str, required=True,
                              help="The email of the citizen is required. The argument should be a String.")
citizen_put_args.add_argument("name", type=str, required=True,
                              help="The name of the citizen is required. The argument should be a String.")
citizen_put_args.add_argument("surname", type=str, required=True,
                              help="The surname of the citizen is required. The argument should be a String.")
citizen_put_args.add_argument("date_of_birth", type=str, required=True,
                              help="The date of birth of the citizen is required in the format YYYY-MM-DD. "
                                   "The argument should be a String.")
citizen_put_args.add_argument("mobile_num", type=str, required=True,
                              help="The mobile number of the citizen is required. The argument should be a String.")
citizen_put_args.add_argument("medical_aid", type=str,
                              help="The medical aid number of the citizen should be a String.")
citizen_put_args.add_argument("citizen_address", type=str,
                              help="The citizen address should be a String.")

# Parser to check that required arguments are sent to get a citizen from the database
citizen_get_args = reqparse.RequestParser()
citizen_get_args.add_argument("id_citizen", type=str, required=True,
                              help="The ID of the citizen is required. The argument should be a String.")

# Parser to check that required arguments are sent to update a citizen in the database
citizen_patch_args = reqparse.RequestParser()
citizen_patch_args.add_argument("id_citizen", type=str, required=True,
                                help="The ID of the citizen is required. The argument should be a String.")
citizen_patch_args.add_argument("email", type=str,
                                help="The citizen email address should be a String.")
citizen_patch_args.add_argument("name", type=str,
                                help="The citizen name should be a String.")
citizen_patch_args.add_argument("surname", type=str,
                                help="The citizen surname should be a String.")
citizen_patch_args.add_argument("date_of_birth", type=str,
                                help="The date of birth of the citizen is should be in the format YYYY-MM-DD. "
                                     "The argument should be a String.")
citizen_patch_args.add_argument("mobile_num", type=str,
                                help="The mobile number of the citizen should be a String")
citizen_patch_args.add_argument("medical_aid", type=str,
                                help="The medical aid number of the citizen should be a String.")
citizen_patch_args.add_argument("citizen_address", type=str,
                                help="Address is required in string format")

# Parser to check that required arguments are sent to delete a citizen from the database
citizen_del_args = reqparse.RequestParser()
citizen_del_args.add_argument("id_citizen", type=str, required=True,
                              help="The ID of the citizen is required. The argument should be a String.")

# Fields to marshal the responses
resource_fields = {
    'id_citizen': fields.String,
    'email': fields.String,
    'name': fields.String,
    'surname': fields.String,
    'date_of_birth': fields.String,
    'mobile_num': fields.String,
    'medical_aid': fields.String,
    'citizen_address': fields.String
}

# Class to handle methods related to citizens
class CitizenResource(Resource):
    @marshal_with(resource_fields)
    def get(self):
        args = citizen_get_args.parse_args()
        data_handler.clean_data(args)
        return get_citizen(args), 200

    def put(self):
        args = citizen_put_args.parse_args()
        data_handler.clean_data(args)
        add_citizen(args)
        return {"message": "Added to database"}, 201

    def patch(self):
        args = citizen_patch_args.parse_args()
        data_handler.clean_data(args)
        update_citizen(args)
        return {"message": "Updated the database"}, 200

    def delete(self):
        args = citizen_del_args.parse_args()
        data_handler.clean_data(args)
        delete_citizen(args)
        return {"message": "Deleted from database"}, 204

# Add resource to the API
citizen_api.add_resource(CitizenResource, "")

# Get a citizen by their ID and return the full database entry
def get_citizen(args):
    result = Citizen.query.filter_by(id_citizen=args["id_citizen"]).first()
    if result:
        return result
    else:
        abort(404, message="A citizen with this ID does not exist")

# Add a citizen to the database
def add_citizen(args):
    result = Citizen.query.filter_by(id_citizen=args["id_citizen"]).first()
    if result:
        abort(409, message="A citizen with this ID already exists")
    else:
        try:
            date = datetime.strptime(args["date_of_birth"], '%Y-%m-%d')
            new_citizen = Citizen(id_citizen=args["id_citizen"], email=args["email"], name=args["name"],
                                  surname=args["surname"], date_of_birth=date, mobile_num=args["mobile_num"],
                                  medical_aid=args["medical_aid"],
                                  citizen_address=args["citizen_address"])
            db.session.add(new_citizen)
            db.session.commit()
            sms_handler.send_mock_sms("You have been added", args["mobile_num"])
        except ValueError:
            abort(400, message="The date should be in format YYYY-MM-DD")

# Update the citizen in the database
def update_citizen(args):
    result = Citizen.query.filter_by(id_citizen=args["id_citizen"]).first()
    if not result:
        abort(404, message="Citizen with this ID does not exist, cannot update")
    else:
        if args["email"]:
            result.email = args["email"]
        if args["name"]:
            result.name = args["name"]
        if args["surname"]:
            result.surname = args["surname"]
        if args["date_of_birth"]:
            try:
                date = datetime.strptime(args["date_of_birth"], '%Y-%m-%d')
                result.date_of_birth = date
            except ValueError:
                abort(400, message="The date should be in format YYYY-MM-DD")
        if args["mobile_num"]:
            result.mobile_num = args["mobile_num"]
        if args["medical_aid"]:
            result.medical_aid = args["medical_aid"]
        if args["citizen_address"]:
            result.citizen_address = args["citizen_address"]
        db.session.commit()

# Delete a citizen from the database
def delete_citizen(args):
    result = Citizen.query.filter_by(id_citizen=args["id_citizen"]).first()
    if not result:
        abort(404, message="Citizen with this ID does not exist, cannot delete")
    else:
        db.session.delete(result)
        db.session.commit()