# Author: Aadiba Haque
# Assignment / Part: HW1 - Q4
# Date due: 2020-02-14
# I pledge that I have completed this assignment without
# collaborating with anyone else, in conformance with the
# NYU School of Engineering Policies and Procedures on
# Academic Misconduct.

print("Please enter your amount in the format of dollars and cents in the two separate lines.")
dollars = int(input())
cents = int(input())
money = (dollars*100) + cents

quarter = money // 25
dime = (money - (25* quarter)) // 10
nickel = (money - ((25*quarter)+(10*dime))) // 5
penny = money - ((25*quarter)+(10*dime)+(5*nickel))

print(dollars,"dollars and",cents, "cents are:", quarter,"quarters,",dime,"dimes,",nickel, \
      "nickels,", "and", penny, "pennies.")


"""
Tumbnail Render
Author: Brandon Bower

Renders images of all fbx files within a root folder.
Saves the images within the same folder as the fbx file rendered
"""

import maya.cmds as cmds
import os

WIDTH = 250 # constant for width of window

def openRenderDelete(path, fbxFile):
    '''
    (string, string) -> none

    imports fbxFile, renders an image of the file,
    saves that image in the same folder as the file,
    then deletes all imported elements
    '''
    # Complete path to fbx file
    fName = f"{path}/{fbxFile}"
    imported = cmds.file(fName,  i=True, rnn=True)
    # render image
    cmds.render(cmds.listCameras()[0])
    # example.fbx gets saved as example.png
    fileSavePath = f"{path}/{os.path.splitext(fbxFile)[0]}"
    # save render image
    editor = 'renderView'
    cmds.renderWindowEditor(editor, e=True, writeImage=fileSavePath)
    # Select and delete all aspects of the imported meshes
    cmds.select(imported)
    cmds.Delete()
    return

def renderModels(*args):
    '''
    (*args) -> None

    Explores all sub-folders of the root folder. Renders a snapshot of all applicable
    models, and stores the images in the same folder as the object rendered

    Note that *args are passed in, as Maya requires it, but are not used
    '''

    # Query button label to get path to root folder
    path = cmds.button("pButton", q=True, l=True)
    # Walk through all sub-folders and files in root folder
    for (dirpath, dirnames, filenames) in os.walk(path):
        for name in filenames:
            # Only open fbx files
            if name.endswith('.fbx'):
                openRenderDelete(dirpath, name)
    cmds.deleteUI('Thumbnail_Render')
    return

def findPath(*args):
    '''
    (*args) -> None

    Finds path to first image in sequence, updates button label to that path
    called by windowCall

    Note that *args are passed in, as Maya requires it, but are not used
    '''
    #multipleFilters = "Compatible files (*.jpg *.jpeg *.png);;jpeg (*.jpeg *.jpg);;png (*.png);;All Files (*.*)"
    # Launch dialog to select root folder
    fPath = cmds.fileDialog2(cap='Select root folder', fm=2, ds=2)
    if(fPath is not None):
       # Update path button and enable the 'Go' button
       cmds.button("pButton", e=True ,l=fPath[0])
       cmds.button('Go', e=True, en=True)
    return

def windowCall():
    '''
    () -> None
    Creates user interface window
    '''
    # Check that window doesn't already exist
    if cmds.window('Thumbnail_Render', ex=True):
        cmds.deleteUI('Thumbnail_Render')
    cmds.window('Thumbnail_Render')
    cmds.columnLayout("SnapRender_layout")
    # Button for selecting root folder
    pathButton = cmds.button("pButton", l='Select root folder of objects to be rendered', w=WIDTH)
    cmds.button(pathButton, e=True, c=findPath)
    # Button for starting script
    cmds.button('Go', en=False, w=250, c=renderModels)
    cmds.window('Thumbnail_Render', e=True, h=20, w=WIDTH)
    cmds.showWindow('Thumbnail_Render')
    return

def main():
    '''function driver for program'''
    windowCall()
    return

# Dont run if imported by another file
if __name__ == "__main__":
    main()


#!/usr/bin/env python

import os
import random
import subprocess
from itertools import product

def main():
    edgelist_dir = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), '..', 'data', 'artificial')
    edgelist_list = [
        os.path.join(edgelist_dir, fn)
        for fn in os.listdir(edgelist_dir) if fn.endswith('.edgelist')]
    bin_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), 'exp-compare-performance')

    output_path = os.path.join(os.path.dirname(__file__),
                               'artificial-performance-comparison.csv')
    num_results = 100
    with open(output_path, 'w') as fp:
        fp.write('network,query,is-directed,is-weighted,is-connected,max-diff,time-proposed,time-igraph\n')
        for path, directed in product(edgelist_list, (True, False)):
            for _ in range(num_results):
                rseed = random.randint(0, 1000000)
                proc = subprocess.run(
                    [bin_path]
                    + (['-d'] if directed else [])
                    + ['-s', str(rseed), path, 'delete'],
                    capture_output=True,
                )
                stdout = proc.stdout.decode('utf-8')\
                                    .replace(edgelist_dir+'/', '')\
                                    .replace('.edgelist', '')
                fp.write(stdout)

if __name__ == '__main__':
    main()


from zope.component import adapts
from zope.interface import implements

from Products.ZenRelations.RelSchema import ToOne, ToMany, ToManyCont

from Products.Zuul.decorators import info
from Products.Zuul.form import schema
from Products.Zuul.infos import ProxyProperty
from Products.Zuul.infos.component import ComponentInfo
from Products.Zuul.interfaces.component import IComponentInfo
from Products.Zuul.utils import ZuulMessageFactory as _t

from ZenPacks.zenoss.AWS import CLASS_NAME, MODULE_NAME
from ZenPacks.zenoss.AWS.AWSComponent import AWSComponent
from ZenPacks.zenoss.AWS.utils import updateToMany

class EC2Image(AWSComponent):
    '''
    Model class for EC2Image.
    '''

    meta_type = portal_type = 'EC2Image'

    location = None
    state = None
    owner_id = None
    architecture = None
    # platform = None
    image_type = None
    kernel_id = None
    ramdisk_id = None
    description = None
    block_device_mapping = None
    root_device_type = None
    root_device_name = None
    virtualization_type = None
    hypervisor = None

    _properties = AWSComponent._properties + (
        {'id': 'location', 'type': 'string'},
        {'id': 'state', 'type': 'string'},
        {'id': 'owner_id', 'type': 'boolean'},
        {'id': 'architecture', 'type': 'string'},
        # {'id': 'platform', 'type': 'string'},
        {'id': 'image_type', 'type': 'string'},
        {'id': 'kernel_id', 'type': 'string'},
        {'id': 'ramdisk_id', 'type': 'string'},
        {'id': 'description', 'type': 'boolean'},
        {'id': 'block_device_mapping', 'type': 'string'},
        {'id': 'root_device_type', 'type': 'string'},
        {'id': 'root_device_name', 'type': 'string'},
        {'id': 'virtualization_type', 'type': 'string'},
        {'id': 'hypervisor', 'type': 'boolean'},
    )

    _relations = AWSComponent._relations + (
        ('region', ToOne(
            ToManyCont, MODULE_NAME['EC2Region'], 'images')),

        ('instances', ToMany(
            ToOne, MODULE_NAME['EC2Instance'], 'image')),
    )

    def getInstanceIds(self):
        return sorted(self.instances.objectIds())

    def setInstanceIds(self, ids):
        updateToMany(
            relationship=self.instances,
            root=self.region().instances,
            type_=CLASS_NAME['EC2Instance'],
            ids=ids)

class IEC2ImageInfo(IComponentInfo):
    '''
    API Info interface for EC2Image.
    '''

    account = schema.Entity(title=_t(u'Account'))
    region = schema.Entity(title=_t(u'Region'))
    location = schema.TextLine(title=_t(u'Location'))
    # state = schema.TextLine(title=_t(u'State'))
    owner_id = schema.TextLine(title=_t(u'Owner ID'))
    architecture = schema.TextLine(title=_t(u'Architecture'))
    # platform = schema.TextLine(title=_t(u'Platform'))
    image_type = schema.TextLine(title=_t(u'Image Type'))
    kernel_id = schema.TextLine(title=_t(u'Kernel ID'))
    ramdisk_id = schema.TextLine(title=_t(u'RAM Disk ID'))
    description = schema.TextLine(title=_t(u'Description'))
    block_device_mapping = schema.TextLine(title=_t(u'Block Device Mapping'))
    root_device_type = schema.TextLine(title=_t(u'Root Device Type'))
    root_device_name = schema.TextLine(title=_t(u'Root Device Name'))
    virtualization_type = schema.TextLine(title=_t(u'Virtualization Type'))
    hypervisor = schema.TextLine(title=_t(u'Hypervisor'))
    instance_count = schema.Int(title=_t(u'Number of Instances'))

class EC2ImageInfo(ComponentInfo):
    '''
    API Info adapter factory for EC2Image.
    '''

    implements(IEC2ImageInfo)
    adapts(EC2Image)

    location = ProxyProperty('location')
    state = ProxyProperty('state')
    owner_id = ProxyProperty('owner_id')
    architecture = ProxyProperty('architecture')
    # platform = ProxyProperty('platform')
    image_type = ProxyProperty('image_type')
    kernel_id = ProxyProperty('kernel_id')
    ramdisk_id = ProxyProperty('ramdisk_id')
    description = ProxyProperty('description')
    block_device_mapping = ProxyProperty('block_device_mapping')
    root_device_type = ProxyProperty('root_device_type')
    root_device_name = ProxyProperty('root_device_name')
    virtualization_type = ProxyProperty('virtualization_type')
    hypervisor = ProxyProperty('hypervisor')

    @property
    @info
    def account(self):
        return self._object.device()

    @property
    @info
    def region(self):
        return self._object.region()

    @property
    def instance_count(self):
        return self._object.instances.countObjects()

    @property
    @info
    def status(self):
        return self.state


#!/usr/bin/env python
from distutils.core import setup

version = '0.1.2'

setup(
    name='django-model-inflect',
    version=version,
    description='Inflect Django models.',
    long_description=(
        'The model_inflect application can be used to inflect dynamic '
        'content of existing models.'),
    author='Aleksandr Alekseev',
    author_email='alekseevavx@gmail.com',
    url='https://github.com/AlekseevAV/django-model-inflect',
    packages=['model_inflect'],
    install_requires=['pymorphy2'],
    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Operating System :: OS Independent',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Framework :: Django',
        'License :: OSI Approved :: BSD License'],
    license='New BSD')


import json
import logging.config
from environs import Env

from flask import Flask, request, jsonify
from flask_smorest import Api

from .config import Config

def create_flask_app(config: Config) -> Flask:
    # Create the Flask App
    app = Flask(__name__)
    app.logger = logging.getLogger('console')

    """ Log each API/APP request
    """

    @app.before_request
    def before_request():
        """ Log every requests """
        app.logger.info(f'>-- {request.method} {request.path} from {request.remote_addr}')
        app.logger.debug(f'       Args: {request.args.to_dict()}')
        app.logger.debug(f'    Headers: {request.headers.to_wsgi_list()}')
        app.logger.debug(f'       Body: {request.get_data()}')

    @app.after_request
    def after_request(response):
        """ Log response status, after every request. """
        app.logger.info(f'--> Response status: {response.status}')
        app.logger.debug(f'      Body: {response.json}')
        return response

    app.logger.info('.------------------.')
    app.logger.info('| MFE Python-Flask|')
    app.logger.info('.------------------.')

    # Update config from given one
    app.config.update(**config.json)
    app.logger.info(f"Config: {json.dumps(config.json, indent=4)}")
    app.debug = config.FLASK_ENV

    # Configure mongo client
    from mongoengine import connect
    connect(config.MONGODB_DATABASE, host=config.MONGODB_URI)

    # Index routes
    @app.route('/')
    def index():
        res = {
            'name': config.SERVICE_NAME,
        }
        return jsonify(res)

    rest_api = Api(app)

    from .views.users import users_blp
    rest_api.register_blueprint(users_blp)

    app.logger.debug(f"URL Map: \n{app.url_map}")
    return app


N = int(input())

searchedWords = []

for searchedWord in range(N):
    word = input()
    searchedWords.append(word)

Q = int(input())

for query in range(Q):
    correspondingWords = []
    lenOfTheWords = []

    queryWord = input()
    queryWordLen = len(queryWord)

    for words in searchedWords:
        if queryWord in words[0:queryWordLen]:
            correspondingWords.append(words)
            lenOfTheWords.append(len(words))

    lenOfTheWords.sort(reverse=True)

    if len(correspondingWords) > 0:
        print(len(correspondingWords), lenOfTheWords[0])
    else:
        print(-1)


class Student:

    def __init__(self, name, reg_no, gpa, is_regular):
        self.name = name
        self.reg_no = reg_no
        self.gpa = gpa
        self.is_regular = is_regular

    def on_first_class(self):
        if self.gpa >= 4.5:
            return True
        else:
            return False


from odoo import api, fields, models

class WorkAcceptance(models.Model):
    _inherit = "work.acceptance"
    _tier_validation_manual_config = True  # We need more buttons

    wa_tier_validation = fields.Boolean(
        string="Paperless WA",
        readonly=True,
        default=True,
        states={"draft": [("readonly", False)]},
        tracking=True,
        help="If checked, WA created will be approved by committee by tier valiation."
        "Each committee will be notified (by email or inbox) to approve WA.\n"
        "If not checked, WA will be approved by paper outside Odoo, "
        "and the result of WA will be filled in by procurement officer",
    )
    work_acceptance_committee_ids = fields.One2many(
        comodel_name="work.acceptance.committee",
        inverse_name="wa_id",
        string="Work Acceptance Committees",
        copy=True,
    )
    completeness = fields.Float(
        string="Progress",
        compute="_compute_completeness",
        store=True,
    )

    @api.depends("work_acceptance_committee_ids.status")
    def _compute_completeness(self):
        for rec in self:
            committees = len(rec.work_acceptance_committee_ids)
            rec.completeness = 0
            if committees:
                reviewed = len(rec.work_acceptance_committee_ids.filtered("status"))
                rec.completeness = reviewed / committees * 100

    @api.model
    def _get_under_validation_exceptions(self):
        res = super()._get_under_validation_exceptions()
        res.append("evaluation_result_ids")
        return res

    def _clear_data_committee(self):
        """Clear data work acceptance committee"""
        self.mapped("work_acceptance_committee_ids").write(
            {
                "status": "",
                "note": "",
            }
        )

    def button_draft(self):
        self._clear_data_committee()
        return super().button_draft()


from datasets import Dataset, load_dataset
import pandas as pd
import random
import numpy as np

def enhance_from_v5():
    df = pd.read_csv('promptset_v5.csv')

    # add a column called note
    df['note'] = None

    # set cfgscale to 7
    df['cfgScale'] = 7

    # set sampler to 'Eular a'
    df['sampler'] = 'Eular a'

    # change the prompt_id of prompt tagged civitai
    for idx in range(len(df)):
        if df.loc[idx, 'tag'] == 'civitai':
            df.loc[idx, 'note'] == df.loc[idx, 'prompt_id']
            df.loc[idx, 'prompt_id'] = idx + 1

    # copy the first 9 prompts and add to the end, with note 'extended'
    for idx in range(9):
        df.loc[idx, 'note'] = 'original'
        df.loc[len(df)] = [len(df)+1, df.loc[idx, 'tag'], df.loc[idx, 'size'], df.loc[idx, 'seed'], df.loc[idx, 'prompt'], df.loc[idx, 'negativePrompt'], df.loc[idx, 'sampler'], df.loc[idx, 'cfgScale'], 'extended']

    df.to_csv('promptset_v6.csv', index = False)

def sort_v6():
    df = pd.read_csv('promptset_v6.csv')
    df.sort_values(by=['tag', 'size', 'prompt'], inplace=True)
    df.reset_index(drop=True, inplace=True)
    # rewrite prompt_id
    df['prompt_id'] = df.index + 1

    df.to_csv('promptset_v6.csv', index = False)

def move_modifier():
    df = pd.read_csv('promptset_v6.csv')
    for idx in range(len(df)):
        if df.loc[idx, 'prompt'].startswith("masterpiece, best quality, best shadow, intricate, "):
            df.loc[idx, 'prompt'] = df.loc[idx, 'prompt'][len("masterpiece, best quality, best shadow, intricate, "):] + ", masterpiece, best quality, best shadow, intricate"

    df.to_csv('promptset_v6.csv', index = False)

def resize_prompts():
    df = pd.read_csv('promptset_v6.csv')
    for idx in range(len(df)):
        width, height = df.loc[idx, 'size'].split('x')
        if width < height:
            df.loc[idx, 'size'] = '512x768'
        elif width > height:
            df.loc[idx, 'size'] = '768x512'
        else:
            df.loc[idx, 'size'] = '512x512'

    df.to_csv('promptset_v6.csv', index = False)

def change_note_datatype():
    df = pd.read_csv('promptset_v6.csv')

    # check datatypes
    datatypes = []
    for idx in range(len(df)):
        data = df.loc[idx, 'note']
        datatype = type(data)
        if datatype not in datatypes:
            datatypes.append(datatype)

    print(datatypes)

    # pick all rows with 'note' as str type, while it is digit, and change the datatype to numpy.int64, and save to pandas
    df.loc[df['note'].apply(lambda x: type(x) == str and x.isdigit()), 'note'] = df.loc[df['note'].apply(lambda x: type(x) == str and x.isdigit()), 'note'].astype("int64")

    # check datatypes
    datatypes = []
    for idx in range(len(df)):
        data = df.loc[idx, 'note']
        datatype = type(data)
        if datatype not in datatypes:
            datatypes.append(datatype)

    print(datatypes)

    df.to_csv('promptset_v6.csv', index = False)

    df2 = pd.read_csv('promptset_v6.csv')
    datatypes2 = []
    for idx in range(len(df2)):
        data = df2.loc[idx, 'note']
        datatype = type(data)
        if datatype not in datatypes2:
            datatypes2.append(datatype)

    print(datatypes2)

if __name__ == "__main__":
    # enhance_from_v5()
    # move_modifier()
    # resize_prompts()
    # sort_v6()
    change_note_datatype()


import json
from django.http import JsonResponse, HttpResponseNotFound, HttpResponseBadRequest, HttpResponse, HttpResponseForbidden
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.forms.models import model_to_dict
from skelbiameAPI.models import Advert, Comment, User, Tag
from .generalFunctions import IsValid, IsFullValid
import datetime
from skelbiameAPI.Tokens import TokenCanEdit, TokenUser, ToPureToken

def allComments(request):
    if request.method == "GET":
        data = Comment.objects.all().values("text", "date", "id", "advertid", "user")
        converted = [entry for entry in data]
        return JsonResponse(converted, safe=False, json_dumps_params={'indent': 2})
    else:
        return HttpResponse(status=405)

def commentsByAdvert(request, advert):
    if request.method == "GET":
        try:
            requestedAdvert = Advert.objects.get(id=advert)
        except ObjectDoesNotExist:
            return HttpResponseNotFound()
        data = Comment.objects.filter(advertid=advert).values("text", "date", "id", "advertid", "user")
        converted = [entry for entry in data]
        return JsonResponse(converted, safe=False, json_dumps_params={'indent': 2})
    elif request.method == "POST":
        return createComment(request, advert)
    else:
        return HttpResponse(status=405)

def comment(request, id):
    try:
        requestedComment = Comment.objects.get(id = id)
    except ObjectDoesNotExist:
        return HttpResponseNotFound()

    if request.method == "GET":
        requestedComment = model_to_dict(requestedComment)
        return JsonResponse(requestedComment, safe=False, json_dumps_params={'indent': 2})

    token = ToPureToken(request.headers.get("Authorization"))

    if not TokenCanEdit(token, requestedComment.user.username):
        return HttpResponseForbidden()

    if request.method == "DELETE":
        requestedComment.delete()
        return HttpResponse()
    elif request.method == "PUT" or request.method == "PATCH":
        body = json.loads(request.body)
        if len(body) != 0 and IsValid(body, ["text"]):
            requestedComment.text = body["text"]
            try:
                requestedComment.clean_fields()
            except ValidationError:
                return HttpResponse(status=422)
            requestedComment.save()
            return JsonResponse(model_to_dict(requestedComment), status=200, safe=False, json_dumps_params={'indent': 2})
    else:
        return HttpResponse(status=405)

def createComment(request, advert):
    token = ToPureToken(request.headers.get("Authorization"))

    username = TokenUser(token)
    if username is None:
        return HttpResponseForbidden()

    body = json.loads(request.body)
    if IsFullValid(body, ["text"]):
        try:
            requestedAdvert = Advert.objects.get(id=advert)
        except ObjectDoesNotExist:
            return HttpResponse(status=404)
        newComment = Comment()
        newComment.text = body["text"]
        newComment.advertid = requestedAdvert
        newComment.date = datetime.datetime.now()

        requestedUser = User.objects.get(username=username)
        newComment.user = requestedUser

        try:
            newComment.clean_fields()
        except ValidationError:
            return HttpResponse(status=422)
        newComment.save()
        return JsonResponse(model_to_dict(newComment), status=201, safe=False, json_dumps_params={'indent': 2})
    else:
        return HttpResponseBadRequest()

def commentsByTag(request, tag):
    if request.method == "GET":
        try:
            requestedTag = Tag.objects.get(tag=tag)
        except ObjectDoesNotExist:
            return HttpResponseNotFound()
        adverts = Advert.objects.filter(tag=requestedTag)
        ans = []
        for i in adverts:
            newComments = Comment.objects.filter(advertid=i).values("text", "date", "id", "advertid", "user")
            ans.extend([entry for entry in newComments])
        return JsonResponse(ans, safe=False, json_dumps_params={'indent': 2})
    else:
        return HttpResponse(status=405)


import discord
from discord.ext import commands
import requests

class InfoRetrieval(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name='info', help='Retrieves information from the internet.')
    async def info(self, ctx, *, query: str):
        response = requests.get(f"https://www.google.com/search?q={query}")
        await ctx.send(response.text)

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


def to_email(lst):
    res=set()
    for i in lst:
        mail=i.split('@')   #根据@符号分割，第一项为本地名称，第二项为域名
        s=''
        for j in mail[0]:   #对本地名称进行.与+的符号操作
            if j=='.':
                continue
            elif j=='+':
                break
            else:
                s=s+j
        res.add(s+mail[1])  #对集合添加目标邮件地址
    return len(res)
if __name__=='__main__':
    lst=["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","tes temail+david@lee.tcode.com"]
    print(to_email(lst))


import turtle
snapy=turtle.Turtle()
snapy.shape("turtle")
snapy.speed(10)
snapy.pendown()
snapy.color("yellow")
snapy.fillcolor("yellow")
snapy.begin_fill()
snapy.circle(100)
snapy.end_fill()
snapy.right(90)
snapy.color("red")
snapy.fillcolor("red")
snapy.begin_fill()
snapy.circle(50)
snapy.end_fill()
snapy.penup()
snapy.right(90)
snapy.right(45)
snapy.forward(30)
snapy.pendown()
snapy.color("orange")
snapy.fillcolor("orange")
snapy.begin_fill()
snapy.circle(50)
snapy.end_fill()
snapy.penup()
snapy.forward(100)
snapy.pendown()
snapy.color("gold")
snapy.fillcolor("gold")
snapy.begin_fill()
snapy.circle(50)
snapy.end_fill()
snapy.penup()
snapy.right(60)
snapy.forward(50)
snapy.pendown()
snapy.color("limegreen")
snapy.fillcolor("limegreen")
snapy.begin_fill()
snapy.circle(50)
snapy.end_fill()
snapy.right(45)
snapy.penup()
snapy.forward(65)
snapy.pendown()
snapy.color("deepskyblue")
snapy.fillcolor("deepskyblue")
snapy.begin_fill()
snapy.circle(50)
snapy.end_fill()
snapy.right(45)
snapy.penup()
snapy.forward(70)
snapy.pendown()
snapy.color("darkorchid")
snapy.fillcolor("darkorchid")
snapy.begin_fill()
snapy.circle(50)
snapy.end_fill()
snapy.penup()
snapy.right(45)
snapy.forward(70)
snapy.pendown()
snapy.color("orchid")
snapy.fillcolor("orchid")
snapy.begin_fill()
snapy.circle(50)
snapy.end_fill()


from nltk.tokenize import word_tokenize
import nltk
from textblob import TextBlob
def AdjectivePolarity(sample):
	sam=word_tokenize(sample)
	tags=nltk.pos_tag(sam)
	adjpol=[]
	TagValue=['RB','RBR','RBS','JJS','JJ','JJR']
	for i in tags:
		if i[1] not in TagValue:
			print(i)
			analysis=TextBlob(i[0])
			sentemp=analysis.sentiment.polarity
			#print(sentemp)
			if sentemp>0:
				adjpol.append("positive")
			elif sentemp<0:
				adjpol.append("negative")
			else:
				adjpol.append("neutral")
	return adjpol


from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QPixmap
from PyQt5.QtWidgets import QGraphicsTextItem, QGraphicsPixmapItem

from client.constants import IMAGES_DIR
from client.models.abstract.info_scene import InfoScene
from client.models.enums.button_state import ButtonState
from client.models.menu_objects.button import Button
from common.constants import SCENE_WIDTH, SCENE_HEIGHT
from common.enums.direction import Direction
from common.enums.info_scenes import InfoScenes
from common.enums.player import Player

class MatchEnd(InfoScene):
    def __init__(self, parent):
        super().__init__()
        self.__parent__ = parent

        self.font = QFont()
        self.font.setPointSize(20)
        self.my_points = QGraphicsTextItem(str(self.__parent__.my_score))
        self.my_points.setDefaultTextColor(Qt.white)
        self.my_points.setFont(self.font)
        self.opponent_points = QGraphicsTextItem(str(self.__parent__.opponent_score))
        self.opponent_points.setDefaultTextColor(Qt.white)
        self.opponent_points.setFont(self.font)
        self.logo = QGraphicsPixmapItem()

        self.logo.setPos((SCENE_WIDTH - 600) / 2, 50)

        if self.__parent__.player == Player.PLAYER_1:
            self.my_points.setPos(50, 250)
            self.opponent_points.setPos(SCENE_WIDTH - (50 + self.opponent_points.boundingRect().width()), 250)
        else:
            self.opponent_points.setPos(50, 250)
            self.my_points.setPos(SCENE_WIDTH - (50 + self.opponent_points.boundingRect().width()), 250)

        self.buttons = [Button(self.__parent__.load_info_scene, InfoScenes.MAIN_MENU.value, (SCENE_WIDTH - 300) / 2, SCENE_HEIGHT - 100,
                               IMAGES_DIR + "menu/continue_highlighted.png", IMAGES_DIR + "menu/continue_highlighted.png",
                               ButtonState.HIGHLIGHTED)]

        if self.__parent__.my_score == self.__parent__.opponent_score:
            self.logo.setPixmap(QPixmap(IMAGES_DIR + "menu/draw.png"))
        elif self.__parent__.my_score > self.__parent__.opponent_score:
            self.logo.setPixmap(QPixmap(IMAGES_DIR + "menu/you_won.png"))
        else:
            self.logo.setPixmap(QPixmap(IMAGES_DIR + "menu/you_lost.png"))

        self.__draw_menu_buttons()
        self.addItem(self.my_points)
        self.addItem(self.opponent_points)
        self.addItem(self.logo)

    """ Handles keyboard presses """
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_W:
            self.__change_button_focus(Direction.UP)
        elif event.key() == Qt.Key_S:
            self.__change_button_focus(Direction.DOWN)
        elif event.key() == Qt.Key_Return:
            self.__execute_button()

    """ Draws buttons in the scene """
    def __draw_menu_buttons(self):
        for button in self.buttons:
            self.addItem(button.graphics_item)

    """ Executes button logic """
    def __execute_button(self):
        for index in range(len(self.buttons)):
            self.buttons[index].execute()

    """ Changes button focus """
    def __change_button_focus(self, direction: Direction):
        if direction is None:
            return

        count = len(self.buttons)
        old_index = -1
        new_index = -1
        for index in range(count):
            if self.buttons[index].state is ButtonState.HIGHLIGHTED:
                old_index = index
                if direction is Direction.UP:
                    if index - 1 > 0:
                        new_index = index - 1
                    else:
                        new_index = 0
                elif direction is Direction.DOWN:
                    if index + 1 > count - 1:
                        new_index = count - 1
                    else:
                        new_index = index + 1

        self.buttons[old_index].set_state(ButtonState.NORMAL)
        self.buttons[new_index].set_state(ButtonState.HIGHLIGHTED)


from bson.errors import InvalidId

from requests.article import retrieve_article
from requests.files import retrieve_file
from schema.user import User

async def validate_files(file_ids: list, user: User):
    for file_id in file_ids:
        try:
            file = await retrieve_file(file_id)
            if not file:
                raise ValueError(f'File with id: "{file_id}" not exists')
            if file['owner'] != user['username']:
                raise ValueError(f'File with id: "{file_id}" not available for you')
        except InvalidId:
            raise ValueError(f'File id: "{file_id}" is not valid bson id')

async def validate_articles(articles_ids: list, user: User):
    for articles_id in articles_ids:
        try:
            article = await retrieve_article(articles_id)
            if not article:
                raise ValueError(f'Article with id: "{articles_id}" not exists')
            if article['owner'] != user['username']:
                raise ValueError(f'Article with id: "{articles_id}" not available for you')
        except InvalidId:
            raise ValueError(f'Article id: "{articles_id}" is not valid bson id')


# Imports

import csv
import cv2
import cv2.aruco as aruco
import numpy as np
import math
import os
import shlex
import subprocess
import tempfile

import olympe
from olympe.messages.ardrone3.Piloting import TakeOff, Landing
from olympe.messages.ardrone3.Piloting import moveBy
from olympe.messages.ardrone3.PilotingState import FlyingStateChanged
from olympe.messages.ardrone3.PilotingSettings import MaxTilt
from olympe.messages.ardrone3.GPSSettingsState import GPSFixStateChanged
from time import sleep

class Stream:

    def __init__(self):

        # Initalize the olympe.Drone object from its IP address
        self.drone = olympe.Drone(
            "192.168.42.1",
            loglevel=0,
        )
        self.tempd = tempfile.mkdtemp(prefix="olympe_streaming_test_")
        print("Olympe streaming example output dir: {}".format(self.tempd))
        self.h264_frame_stats = []
        self.h264_stats_file = open(
            os.path.join(self.tempd, 'h264_stats.csv'), 'w+')
        self.h264_stats_writer = csv.DictWriter(
            self.h264_stats_file, ['fps', 'bitrate'])
        self.h264_stats_writer.writeheader()

    def start(self):
        # Establish a connection the the drone
        self.drone.connection()

        self.drone.set_streaming_output_files(
            h264_data_file=os.path.join(self.tempd, 'h264_data.264'),
            h264_meta_file=os.path.join(self.tempd, 'h264_metadata.json'),
        )

        # Setup callback functions to perform live video processing
        self.drone.set_streaming_callbacks(
            raw_cb=self.yuv_frame_cb,
            h264_cb=self.h264_frame_cb
        )

        # Begin video streaming
        self.drone.start_video_streaming()
        self.drone(
            TakeOff()
            >> FlyingStateChanged(state="hovering", _timeout=5)
        ).wait()

    def navigate(self):
        self.reachedDest = False
        while not self.reachedDest:
            if not self.corners:
                self.drone(moveBy(0, 0, 0, 0.5, _timeout=5)).wait().success()
            else:
                for corner in self.corners:
                    offset = False
                    x, y, width, height = cv2.boundingRect(corner)

                    vert = 0
                    hor = 0
                    dist = 0

                    top_dist = y
                    left_dist = x
                    bottom_dist = self.cv2frame.shape[0] - y - height
                    right_dist = self.cv2frame.shape[1] - x - width

                    vert_dist = top_dist - bottom_dist
                    hor_dist = left_dist - right_dist

                    threshold = cv2.contourArea(corner)

                    if offset:
                        self.drone(moveBy(dist * 0.25, hor * 0.1, vert * 0.1, 0, _timeout=5)).wait().success()
                        offset = False

                    if abs(top_bot_diff) >100:
                        if top_bot_diff>0:
                            offset = True
                            vert = 1
                            print('D-ADJUST')
                        else:
                            offset = True
                            vert = -1
                            print('U-ADJUST')

                    if abs(left_right_diff) >150:
                        if left_right_diff>0:
                            offset = True
                            hor = 1
                            print('R-ADJUST')
                        else:
                            offset = True
                            hor = -1
                            print('L-ADJUST')

                    if threshold < self.cv2frame.shape[0] * self.cv2frame.shape[1] * 0.065:
                        offset = True
                        dist = 1
                        print('F-ADJUST')
                    else:
                        self.reachedDest = True
                        break

    def stop(self):
        # Disconnect both the video stream and the drone
        self.drone(Landing()).wait()
        self.drone.stop_video_streaming()
        self.drone.disconnection()
        self.h264_stats_file.close()

    def yuv_frame_cb(self, yuv_frame):

        info = yuv_frame.info()
        height, width = info["yuv"]["height"], info["yuv"]["width"]

        # Convert PDRAW YUV flag to an OpenCV YUV flag
        cv2_cvt_color_flag = {
            olympe.PDRAW_YUV_FORMAT_I420: cv2.COLOR_YUV2BGR_I420,
            olympe.PDRAW_YUV_FORMAT_NV12: cv2.COLOR_YUV2BGR_NV12,
        }[info["yuv"]["format"]]

        # Utilize OpenCV to convert the YUV frame to RGB
        self.cv2frame = cv2.cvtColor(yuv_frame.as_ndarray(), cv2_cvt_color_flag)

        gray = self.cv2frame
        aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_250)
        parameters =  aruco.DetectorParameters_create()

        self.corners, self.ids, self.rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)

        gray = aruco.drawDetectedMarkers(gray, self.corners)

        # Use OpenCV to display this frame
        cv2.imshow("Test Frame", gray)
        cv2.waitKey(1)

    def h264_frame_cb(self, h264_frame):
        """
        This function will be called by Olympe for each new h264 frame.
            :type yuv_frame: olympe.VideoFrame
        """

        # Get a ctypes pointer and size for this h264 frame
        frame_pointer, frame_size = h264_frame.as_ctypes_pointer()

        # Compute some stats and dump them in a csv file
        info = h264_frame.info()
        frame_ts = info["ntp_raw_timestamp"]
        if not bool(info["h264"]["is_sync"]):
            if len(self.h264_frame_stats) > 0:
                while True:
                    start_ts, _ = self.h264_frame_stats[0]
                    if (start_ts + 1e6) < frame_ts:
                        self.h264_frame_stats.pop(0)
                    else:
                        break
            self.h264_frame_stats.append((frame_ts, frame_size))
            h264_fps = len(self.h264_frame_stats)
            h264_bitrate = (
                8 * sum(map(lambda t: t[1], self.h264_frame_stats)))
            self.h264_stats_writer.writerow(
                {'fps': h264_fps, 'bitrate': h264_bitrate})

if __name__ == "__main__":
    # Instantiate stream object
    stream = Stream()

    # Begin script
    stream.start()

    # Proceed with navigation method
    stream.navigate()

    # Stop video streaming and commence landing
    stream.stop()


'''
Take thee again another scroll, and write in it all the former words that
were in the first scroll, which Jehoiakim the king of Judah hath burned.
Jeremiah 36:28
'''

import sys
from PyQt5.QtWidgets import QApplication
from main_window import MainWindow

class Khartes():

    def __init__(self, app):
        window = MainWindow("χάρτης", app)
        self.app = app
        self.window = window
        window.show()

app = QApplication(sys.argv)

khartes = Khartes(app)
app.exec()


from django.db import models
from django.urls import reverse
from django.conf import settings
from django.utils.html import format_html
from django.templatetags.static import static

from model_utils.models import TimeStampedModel
from autoslug import AutoSlugField

class PostQuerySet(models.QuerySet):
    def published(self):
        return self.filter(
            is_published=True,
            is_approved=True,
        )

class Post(TimeStampedModel):
    title = models.CharField(
        'Título',
        max_length=255,
    )
    subtitle = models.CharField(
        'Título secundario',
        default='',
        max_length=255,
    )
    slug = AutoSlugField(
        null=False,
        unique=True,
        populate_from='title',
    )
    header_image = models.ImageField(
        'Imagen',
        blank=True,
        null=True,
        upload_to='posts'
    )
    content = models.TextField(
        verbose_name='Contenido',
        default='',
        help_text=format_html(
            'Puedes usar Markdown '
            'para dar formato al texto.',
            '/markdown',
        ),
    )

    is_published = models.BooleanField(
        'Está publicado',
        default=True,
        help_text='Indica si la entrada va a aparecer en la página',
    )
    is_approved = models.BooleanField(
        'Está aprobado', default=True,
        help_text='Campo de uso exclusivo para el administrador del sitio',
    )

    created_by_desparchado = models.BooleanField(
        'Está publicado a nombre de la plataforma',
        default=False,
    )
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        verbose_name='Creado por',
        related_name='created_posts',
        on_delete=models.DO_NOTHING,
    )

    related_events = models.ManyToManyField(
        'events.Event',
        related_name='posts',
        blank=True,
    )

    objects = PostQuerySet().as_manager()

    class Meta:
        ordering = ['-created']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog:post_detail', args=[self.slug])

    def get_image_url(self):
        if self.header_image:
            return self.header_image.url
        return static('images/default_event_image.png')

    def get_author_name(self):
        if self.created_by_desparchado:
            return 'desparchado.co'
        return self.created_by.username


class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def push(head_ref, new_data):
    new_node = Node()
    new_node.val = new_data
    new_node.next = (head_ref)
    (head_ref) = new_node
    return head_ref

class MyLinkedList:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.head = None

    def get(self, index: int) -> int:
        """
        Get the value of the index-th node in the linked list. If the index is invalid, return -1.
        """
        current = self.head
        count = 0

        while (current):
            if (count == index):
                return current.data
            count += 1
            current = current.next
        return -1

    def addAtHead(self, val: int) -> None:
        """
        Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
        """
        cur = Node(val)
        cur.next = self.head
        self.head = cur

    def addAtTail(self, val: int) -> None:
        """
        Append a node of value val to the last element of the linked list.
        """
        cur = Node(val)
        if self.head is None:
            self.head = cur
        temp = self.head
        while temp.next:
            temp = temp.next
        temp.next = cur

    def getNode(self, data):

        # allocating space
        newNode = Node(data)
        return newNode

    def addAtIndex(self, index: int, val: int) -> None:
        """
        Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
        """
        new_node = Node(val)

        if self.head is None:
            if index != 0:
                return
            else:
                self.head = new_node

        if self.head != None and index == 0:
            new_node.next = self.head
            self.head = new_node
            return

        current = self.head
        prev = None

        i = 0
        while i < index:
            prev = current
            current = current.next

            if not current:
                break
            i += 1

        new_node.next = current
        prev.next = new_node

    def deleteAtIndex(self, index: int) -> None:
        """
        Delete the index-th node in the linked list, if the index is valid.
        """
        if self.head == None:
            return
        temp = self.head
        if index == 0:
            self.head = temp.next
            temp = None
            return

        for i in range(index - 1):
            temp = temp.next
            if temp is None:
                break

        if temp is None:
            return
        if temp.next is None:
            return
        next = temp.next.next
        temp.next = None

        temp.next = next

    def hasCycle(self, head):
        slow_p = head
        fast_p = head
        while(slow_p and fast_p and fast_p.next):
            slow_p = slow_p.next
            fast_p = fast_p.next.next
            if slow_p == fast_p:
                return True
        return False

    # for 2 sorted linked lists
    def getIntersectionNode(self, a, b):
        dummy = Node()
        tail = dummy
        dummy.next = None

        while (a != None and b != None):
            if (a.val == b.val):
                tail.next = push((tail.next), a.val)
                tail = tail.next
                a = a.next
                b = b.next

            elif(a.val < b.val):
                a = a.next
            else:
                b = b.next
        return (dummy.next)

    def removeNthFromEnd(self, head, n):
        fast = head
        slow = head

        while n:
            fast = fast.next
            n -= 1

        if not fast:
            return head.next

        while fast.next:
            slow = slow.next
            fast = fast.next

        slow.next = slow.next.next
        return head


import sys
import random
import secrets
from character import Character
from monster import Dragon
from monster import Goblin
from monster import Troll

class Game:

    def setup(self):
        self.player = Character()
        self.monsters = [
            Goblin(),
            Troll(),
            Dragon()
        ]
        self.monster = self.get_next_monster()

    def get_next_monster(self):
        try:
            index = secrets.randbelow((len(self.monsters)))
            if isinstance(self.monsters[index], Dragon) and len(self.monsters) > 1:
                return self.get_next_monster()
            else:
                return self.monsters.pop(index)
        except ValueError:
            return None

    def monster_turn(self):
        if self.monster.attack():
            print('{} is attacking'.format(self.monster))
            if input('Dodge? Y/n').lower() == 'y':
                if self.player.dodge():
                    print('You dodge the attack')
                else:
                    print('You got hit anyway')
                    self.player.hit_points -= 1
            else:
                print('{} hit you for 1 damage'.format(self.monster))
                self.player.hit_points -= 1
        else:
            print("{} isn't attacking this turn".format(self.monster))

    def player_turn(self):
        player_choice = input('[A]ttack, [R]est, [Q]uit?').lower()
        if player_choice == 'a':
            print("You're attacking {}!".format(self.monster))
            if self.player.attack():
                if self.monster.dodge():
                    print("{} dodged your attack".format(self.monster))
                else:
                    if self.player.leveled_up():
                        self.monster.hit_points -= (self.player.weapon.damage() + 1)
                    else:
                        self.monster.hit_points -= self.player.weapon.damage()
                    print("You hit {} with your {}".format(self.monster, self.player.weapon))
            else:
                print('You missed!')
        elif player_choice == 'r':
            self.player.rest()
        elif player_choice == 'q':
            sys.exit()
        else:
            self.player_turn()

    def cleanup(self):
        if self.monster.hit_points <= 0:
            self.player.exp += self.monster.exp
            print("You killed {}!".format(self.monster))
            self.monster = self.get_next_monster()

    def __init__(self):
        self.setup()

        while self.player.hit_points and (self.monster or self.monsters):
            print('\n' + '=' * 20)
            print(self.player)
            self.monster_turn()
            print('-'*20)
            self.player_turn()
            self.cleanup()
            print('\n' + '=' * 20)

        if self.player.hit_points:
            print('You win')
        elif self.monsters or self.monster:
            print('You lose')
        sys.exit()

Game()


from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10

class CarManager():
    def __init__(self):
        self.all_cars = []
        self.car_speed = STARTING_MOVE_DISTANCE

    def create_car(self):
        x = random.randint(1, 6)
        if x == 1:
            new_car = Turtle("square")
            new_car.turtlesize(stretch_len=2, stretch_wid=1)
            new_car.penup()
            new_car.setheading(180)
            # self.car_move()
            y_position = random.randint(-250, 250)
            new_car.color(random.choice(COLORS))
            new_car.goto(300, y_position)
            self.all_cars.append(new_car)

    def car_move(self):
         for car in self.all_cars:
             car.forward(self.car_speed)

    def car_reset(self):
        self.car_speed += MOVE_INCREMENT


import traci
import _config
import _reporting
import _platoonmanager

warn = _reporting.Warner("simpla")
_mgr = None
_useStepListener = 'addStepListener' in dir(traci)
_emergencyDecelImplemented = 'VAR_EMERGENCY_DECEL' in dir(traci.constants)

if not _emergencyDecelImplemented:
    # Old traci version. No emergency decel present.
    warn("Using old traci version assuming emergency decel == decel", 0, True)
    # Set emergency decel to decel
    traci.constants.VAR_EMERGENCY_DECEL = 0x7b
    traci.vehicletype.getEmergencyDecel = traci.vehicletype.getDecel

def load(config_filename):
    '''
    Load the config from file and create a Platoon Manager
    '''
    global _mgr
    _config.load(config_filename)
    _mgr = _platoonmanager.PlatoonManager()
    if _useStepListener:
        # For SUMO version >= 0.30
        traci.addStepListener(_mgr)

def stop():
    '''
    Stop the PlatoonManager
    '''
    global _mgr
    if _mgr is not None:
        _mgr.stop()
    _mgr = None

def update():
    '''
    Function called each simulation step. Only to be used for SUMO version < 1.0
    '''
    global _mgr, warn
    if _mgr is not None:
        _mgr.step()
    else:
        warn("call simpla.init(<config_file>) before simpla.update()!")


from collections import deque

def check(r, c):
    global ret
    qu = deque([[r, c, MAP[r][c]]])
    while qu:
        y, x, num = qu.popleft()
        if len(num) == 7:
            ret.add(num)
            continue
        for i in range(4):
            ny, nx = y + dy[i], x + dx[i]
            if 0 <= ny < 4 and 0 <= nx < 4:
                qu.append([ny, nx, num + MAP[ny][nx]])
    return

dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]

for tc in range(int(input())):
    MAP = [input().split() for _ in range(4)]
    ret = set()
    for i in range(4):
        for j in range(4):
            check(i, j)
    print('#{} {}'.format(tc+1, len(ret)))


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

from cobradb.models import *
from cobradb import settings
from cobradb.model_dumping import dump_model
from cobradb import parse
from cobradb.util import (increment_id, check_pseudoreaction, load_tsv,
                          get_or_create_data_source, format_formula, scrub_name,
                          check_none, get_or_create, timing)

from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy import func
import re
import logging
from collections import defaultdict
import os
from os.path import join, basename, abspath, dirname
from difflib import SequenceMatcher
try:
    from itertools import ifilter as filter
except ImportError:
    pass
import cobra.io
import six

class GenbankNotFound(Exception):
    pass

def get_model_list():
    """Get the models that are available, as SBML, in ome_data/models"""
    return [x.replace('.xml', '').replace('.mat', '') for x in
            os.listdir(join(settings.data_directory, 'models'))
            if '.xml' in x or '.mat' in x]

def check_for_model(name):
    """Check for model, case insensitive, and ignore periods and underscores"""
    def min_name(n):
        return n.lower().replace('.','').replace(' ','').replace('_','')
    for x in get_model_list():
        if min_name(name)==min_name(x):
            return x
    return None

def _sim(name1, name2):
    """Return true if the names are similar"""
    clean1, clean2 = [n.lower().replace(' ', '') for n in [name1, name2]]
    return SequenceMatcher(None, clean1, clean2).ratio() > 0.7

def improve_name(session, db, new_name):
    """If the new_name is a better descriptive name for the reaction or metabolite,
    then update.

    """
    cur_name = db.name
    cur_id = db.bigg_id
    # New name is not None and not similar to bigg_id
    if (new_name is not None and not _sim(new_name, cur_id) and
        (cur_name is None or _sim(cur_name, cur_id))):
        logging.debug('Replacing name %s with %s' % (cur_name, new_name))
        db.name = new_name
    session.commit()

@timing
def load_model(model_filepath, pub_ref, genome_ref, session):
    """Load a model into the database. Returns the bigg_id for the new model.

    Arguments
    ---------

    model_filepath: the path to the file where model is stored.

    pub_ref: a publication PMID or doi for the model, as a tuple like this:

        ('doi', '10.1128/ecosalplus.10.2.1')

        ('pmid', '21988831')

        Can be None

    genome_ref: A tuple specifying the genome accession type and value. The
    first element can be ncbi_accession, ncbi_assembly, or organism.

    session: An instance of Session.

    """
    # apply id normalization
    logging.debug('Parsing SBML')
    model, old_parsed_ids = parse.load_and_normalize(model_filepath)
    model_bigg_id = model.id

    # check that the model doesn't already exist
    if session.query(Model).filter_by(bigg_id=model_bigg_id).count() > 0:
        raise AlreadyLoadedError('Model %s already loaded' % model_bigg_id)

    # check for a genome annotation for this model
    if genome_ref is not None and genome_ref[0] == 'organism':
        genome_id = None
        organism = genome_ref[1]
    elif genome_ref is not None and genome_ref[0] in ['ncbi_accession', 'ncbi_assembly']:
        genome_db = (session
                     .query(Genome)
                     .filter(Genome.accession_type==genome_ref[0])
                     .filter(Genome.accession_value==genome_ref[1])
                     .first())
        if genome_db is None:
            raise GenbankNotFound('Genome for model {} not found with genome_ref {}'
                                  .format(model_bigg_id, genome_ref))
        genome_id = genome_db.id
        organism = genome_db.organism
    else:
        logging.info('No Genome reference or organism provided for model {}'.format(model_bigg_id))
        genome_id = None
        organism = None

    # Load the model objects. Remember: ORDER MATTERS! So don't mess around.
    logging.debug('Loading objects for model {}'.format(model.id))
    published_filename = os.path.basename(model_filepath)
    model_database_id = load_new_model(session, model, genome_id, pub_ref,
                                       published_filename, organism)

    # metabolites/components and linkouts
    # get compartment names
    if os.path.exists(settings.compartment_names):
        with open(settings.compartment_names, 'r') as f:
            compartment_names = {}
            for line in f.readlines():
                sp = [x.strip() for x in line.split('\t')]
                try:
                    compartment_names[sp[0]] = sp[1]
                except IndexError:
                    continue
    else:
        logging.warning('No compartment names file')
        compartment_names = {}
    comp_comp_db_ids, final_metabolite_ids = load_metabolites(session, model_database_id, model,
                                                              compartment_names,
                                                              old_parsed_ids['metabolites'])

    # reactions
    model_db_rxn_ids = load_reactions(session, model_database_id, model,
                                      old_parsed_ids['reactions'],
                                      comp_comp_db_ids, final_metabolite_ids)

    # genes
    load_genes(session, model_database_id, model, model_db_rxn_ids,
               old_parsed_ids['genes'])

    # count model objects for the model summary web page
    load_model_count(session, model_database_id)

    session.commit()

    return model_bigg_id

def load_new_model(session, model, genome_db_id, pub_ref, published_filename,
                   organism):
    """Load the model.

    Arguments:
    ---------

    session: A SQLAlchemy session.

    model: A COBRApy model.

    genome_db_id: The database ID of the genome. Can be None.

    pub_ref: a publication PMID or doi for the model, as a string like this:

        doi:10.1128/ecosalplus.10.2.1

        pmid:21988831

        Can be None

    organism: The organism. Can be None.

    Returns:
    -------

    The database ID of the new model row.

    """
    model_db = Model(bigg_id=model.id, genome_id=genome_db_id,
                     published_filename=published_filename, organism=organism)
    session.add(model_db)
    if pub_ref is not None:
        ref_type, ref_id = pub_ref
        publication_db = (session
                            .query(Publication)
                            .filter(Publication.reference_type==ref_type)
                            .filter(Publication.reference_id==ref_id)
                            .first())
        if publication_db is None:
            publication_db = Publication(reference_type=ref_type,
                                                reference_id=ref_id)
            session.add(publication_db)
            session.commit()
        publication_model_db = (session
                                .query(PublicationModel)
                                .filter(PublicationModel.publication_id == publication_db.id)
                                .filter(PublicationModel.model_id == model_db.id)
                                .first())
        if publication_model_db is None:
            publication_model_db = PublicationModel(model_id=model_db.id,
                                                            publication_id=publication_db.id)
            session.add(publication_model_db)
    session.commit()
    return model_db.id

def load_metabolites(session, model_id, model, compartment_names,
                     old_metabolite_ids):
    """Load the metabolites as components and model components.

    Arguments:
    ---------

    session: An SQLAlchemy session.

    model_id: The database ID for the model.

    model: The COBRApy model.

    old_metabolite_ids: A dictionary where keys are new IDs and values are old
    IDs for compartmentalized metabolites.

    Returns
    -------

    comp_comp_db_ids: A dictionary where keys are the original compartmentalized
    metabolite ids and the values are the database IDs for the compartmentalized
    components.

    final_metabolite_ids: A new dictionary where keys are original
    compartmentalized metabolite IDs from the model and values are the new
    compartmentalized metabolite IDs.

    """
    comp_comp_db_ids = {}
    final_metabolite_ids = {}

    # only grab this once
    data_source_id = get_or_create_data_source(session, 'old_bigg_id')

    # get metabolite id duplicates
    met_dups = load_tsv(settings.metabolite_duplicates)
    def _check_metabolite_duplicates(bigg_id):
        """Return a new ID if there is a preferred ID, otherwise None."""
        for row in met_dups:
            if bigg_id in row[1:]:
                return row[0]
        return None

    # for each metabolite in the model
    for metabolite in model.metabolites:
        metabolite_id = parse.remove_duplicate_tag(metabolite.id)

        try:
            component_bigg_id, compartment_bigg_id = parse.split_compartment(metabolite_id)
        except Exception:
            logging.error(('Could not find compartment for metabolite %s in'
                            'model %s' % (metabolite_id, model.id)))
            continue

        preferred = _check_metabolite_duplicates(component_bigg_id)
        new_bigg_id = preferred if preferred else component_bigg_id

        # look for the formula in these places
        formula_fns = [lambda m: getattr(m, 'formula', None), # support cobra v0.3 and 0.4
                       lambda m: m.notes.get('FORMULA', None),
                       lambda m: m.notes.get('FORMULA1', None)]
        # Cast to string, but not for None
        strip_str_or_none = lambda v: str(v).strip() if v is not None else None
        # Ignore the empty string
        ignore_empty_str = lambda s: s if s != '' else None
        # Use a generator for lazy evaluation
        values = (ignore_empty_str(strip_str_or_none(formula_fn(metabolite)))
                  for formula_fn in formula_fns)
        # Get the first non-null result. Otherwise _formula = None.
        _formula = format_formula(next(filter(None, values), None))
        # Check for non-valid formulas
        if parse.invalid_formula(_formula):
            logging.warning('Invalid formula %s for metabolite %s in model %s' % (_formula, metabolite_id, model.id))
            _formula = None

        # get charge
        try:
            charge = int(metabolite.charge)
            # check for float charge
            if charge != metabolite.charge:
                logging.warning('Could not load charge {} for {} in model {}'
                             .format(metabolite.charge, metabolite_id, model.id))
                charge = None
        except Exception:
            if hasattr(metabolite, 'charge') and metabolite.charge is not None:
                logging.debug('Could not convert charge to integer for metabolite {} in model {}: {}'
                              .format(metabolite_id, model.id, metabolite.charge))
            charge = None

        # If there is no metabolite, add a new one.
        metabolite_db = (session
                         .query(Component)
                         .filter(Component.bigg_id == new_bigg_id)
                         .first())

        # if necessary, add the new metabolite, and keep track of the ID
        new_name = scrub_name(getattr(metabolite, 'name', None))
        if metabolite_db is None:
            # make the new metabolite
            metabolite_db = Component(bigg_id=new_bigg_id, name=new_name)
            session.add(metabolite_db)
            session.commit()
        else:
            # If the metabolite is not new, consider improving the descriptive name
            improve_name(session, metabolite_db, new_name)

        # add the deprecated id if necessary
        if metabolite_db.bigg_id != component_bigg_id:
            get_or_create(session, DeprecatedID, deprecated_id=component_bigg_id,
                          type='component', ome_id=metabolite_db.id)

        # if there is no compartment, add a new one
        compartment_db = (session
                          .query(Compartment)
                          .filter(Compartment.bigg_id == compartment_bigg_id)
                          .first())
        if compartment_db is None:
            try:
                name = compartment_names[compartment_bigg_id]
            except KeyError:
                logging.warning('No name found for compartment %s' % compartment_bigg_id)
                name = ''
            compartment_db = Compartment(bigg_id=compartment_bigg_id, name=name)
            session.add(compartment_db)
            session.commit()

        # if there is no compartmentalized compartment, add a new one
        comp_component_db = (session
                             .query(CompartmentalizedComponent)
                             .filter(CompartmentalizedComponent.component_id == metabolite_db.id)
                             .filter(CompartmentalizedComponent.compartment_id == compartment_db.id)
                             .first())
        if comp_component_db is None:
            comp_component_db = CompartmentalizedComponent(component_id=metabolite_db.id,
                                                           compartment_id=compartment_db.id)
            session.add(comp_component_db)
            session.commit()

        # remember for adding the reaction
        comp_comp_db_ids[metabolite.id] = comp_component_db.id
        final_metabolite_ids[metabolite.id] = '%s_%s' % (new_bigg_id, compartment_bigg_id)

        # if there is no model compartmentalized compartment, add a new one
        model_comp_comp_db = (session
                              .query(ModelCompartmentalizedComponent)
                              .filter(ModelCompartmentalizedComponent.compartmentalized_component_id == comp_component_db.id)
                              .filter(ModelCompartmentalizedComponent.model_id == model_id)
                              .first())
        if model_comp_comp_db is None:
            model_comp_comp_db = ModelCompartmentalizedComponent(model_id=model_id,
                                                                 compartmentalized_component_id=comp_component_db.id,
                                                                 formula=_formula,
                                                                 charge=charge)
            session.add(model_comp_comp_db)
            session.commit()
        else:
            if model_comp_comp_db.formula is None:
                model_comp_comp_db.formula = _formula
            if model_comp_comp_db.charge is None:
                model_comp_comp_db.charge = charge
            session.commit()

        # add synonyms
        for old_bigg_id_c in old_metabolite_ids[metabolite.id]:
            # Add Synonym and  OldIDSynonym
            synonym_db = (session
                          .query(Synonym)
                          .filter(Synonym.type == 'compartmentalized_component')
                          .filter(Synonym.ome_id == comp_component_db.id)
                          .filter(Synonym.synonym == old_bigg_id_c)
                          .filter(Synonym.data_source_id == data_source_id)
                          .first())
            if synonym_db is None:
                synonym_db = Synonym(type='compartmentalized_component',
                                     ome_id=comp_component_db.id,
                                     synonym=old_bigg_id_c,
                                     data_source_id=data_source_id)
                session.add(synonym_db)
                session.commit()
            old_id_db = (session
                         .query(OldIDSynonym)
                         .filter(OldIDSynonym.type == 'model_compartmentalized_component')
                         .filter(OldIDSynonym.ome_id == model_comp_comp_db.id)
                         .filter(OldIDSynonym.synonym_id == synonym_db.id)
                         .first())
            if old_id_db is None:
                old_id_db = OldIDSynonym(type='model_compartmentalized_component',
                                         ome_id=model_comp_comp_db.id,
                                         synonym_id=synonym_db.id)
                session.add(old_id_db)
                session.commit()

            # Also add Synonym and OldIDSynonym for the universal metabolite
            try:
                new_style_id = parse.id_for_new_id_style(
                    parse.fix_legacy_id(old_bigg_id_c, use_hyphens=False),
                    is_metabolite=True
                )
                old_bigg_id_c_without_compartment = parse.split_compartment(new_style_id)[0]
            except Exception as e:
                logging.warning(e.message)
            else:
                synonym_db_2 = (session
                                .query(Synonym)
                                .filter(Synonym.type == 'component')
                                .filter(Synonym.ome_id == metabolite_db.id)
                                .filter(Synonym.synonym == old_bigg_id_c_without_compartment)
                                .filter(Synonym.data_source_id == data_source_id)
                                .first())
                if synonym_db_2 is None:
                    synonym_db_2 = Synonym(type='component',
                                        ome_id=metabolite_db.id,
                                        synonym=old_bigg_id_c_without_compartment,
                                        data_source_id=data_source_id)
                    session.add(synonym_db_2)
                    session.commit()
                old_id_db = (session
                            .query(OldIDSynonym)
                            .filter(OldIDSynonym.type == 'model_compartmentalized_component')
                            .filter(OldIDSynonym.ome_id == model_comp_comp_db.id)
                            .filter(OldIDSynonym.synonym_id == synonym_db_2.id)
                            .first())
                if old_id_db is None:
                    old_id_db = OldIDSynonym(type='model_compartmentalized_component',
                                            ome_id=model_comp_comp_db.id,
                                            synonym_id=synonym_db_2.id)
                    session.add(old_id_db)
                    session.commit()

    return comp_comp_db_ids, final_metabolite_ids

def _new_reaction(session, reaction, bigg_id, reaction_hash, model_db_id, model,
                  is_pseudoreaction, comp_comp_db_ids):
    """Add a new universal reaction with reaction matrix rows."""

    # name is optional in cobra 0.4b2. This will probably change back.
    name = check_none(getattr(reaction, 'name', None))
    reaction_db = Reaction(bigg_id=bigg_id, name=scrub_name(name),
                           reaction_hash=reaction_hash,
                           pseudoreaction=is_pseudoreaction)
    session.add(reaction_db)
    session.commit

    # for each reactant, add to the reaction matrix
    for metabolite, stoich in six.iteritems(reaction.metabolites):
        # get the component in the model
        try:
            comp_comp_db_id = comp_comp_db_ids[metabolite.id]
        except KeyError:
            logging.error('Could not find metabolite {!s} for model {!s} in the database'
                          .format(metabolite.id, model.id))
            continue

        # check if the reaction matrix row already exists
        found_reaction_matrix = (session
                                .query(ReactionMatrix)
                                .filter(ReactionMatrix.reaction_id == reaction_db.id)
                                .filter(ReactionMatrix.compartmentalized_component_id == comp_comp_db_id)
                                .count() > 0)
        if not found_reaction_matrix:
            new_object = ReactionMatrix(reaction_id=reaction_db.id,
                                        compartmentalized_component_id=comp_comp_db_id,
                                        stoichiometry=stoich)
            session.add(new_object)
        else:
            logging.debug('ReactionMatrix row already present for model {!s} metabolite {!s} reaction {!s}'
                          .format(model.id, metabolite.id, reaction_db.bigg_id))

    return reaction_db

def _is_deprecated_reaction_id(session, reaction_id):
    return (session.query(DeprecatedID)
            .filter(DeprecatedID.type == 'reaction')
            .filter(DeprecatedID.deprecated_id == reaction_id)
            .first() is not None)

def load_reactions(session, model_db_id, model, old_reaction_ids,
                   comp_comp_db_ids, final_metabolite_ids):
    """Load the reactions and stoichiometries into the model.

    TODO if the reaction is already loaded, we need to check the stoichometry
    has. If that doesn't match, then add a new reaction with an incremented ID
    (e.g. ACALD_1)

    Arguments
    ---------

    session: An SQLAlchemy session.

    model_db_id: The database ID for the model.

    model: The COBRApy model.

    old_reaction_ids: A dictionary where keys are new IDs and values are old IDs
    for reactions.

    comp_comp_db_ids: A dictionary where keys are the original compartmentalized
    metabolite ids and the values are the database IDs for the compartmentalized
    components.

    final_metabolite_ids: A new dictionary where keys are original
    compartmentalized metabolite IDs from the model and values are the new
    compartmentalized metabolite IDs.

    Returns
    -------

    A dictionary with keys for reaction BiGG IDs in the model and values for the
    associated ModelReaction.id in the database.

    """

    # only grab this once
    data_source_id = get_or_create_data_source(session, 'old_bigg_id')

    # get reaction hash_prefs
    hash_prefs = load_tsv(settings.reaction_hash_prefs)
    def _check_hash_prefs(a_hash, is_pseudoreaction):
        """Return the preferred BiGG ID for a_hash, or None."""
        for row in hash_prefs:
            marked_pseudo = len(row) > 2 and row[2] == 'pseudoreaction'
            if row[0] == a_hash and marked_pseudo == is_pseudoreaction:
                return row[1]
        return None

    # Generate reaction hashes, and find reactions in the same model in opposite
    # directions.
    reaction_hashes = {r.id: parse.hash_reaction(r, final_metabolite_ids)
                       for r in model.reactions}
    reverse_reaction_hashes = {r.id: parse.hash_reaction(r, final_metabolite_ids, reverse=True)
                               for r in model.reactions}
    reverse_reaction_hashes_rev = {v: k for k, v in six.iteritems(reverse_reaction_hashes)}
    reactions_not_to_reverse = set()
    for r_id, h in six.iteritems(reaction_hashes):
        if h in reverse_reaction_hashes_rev:
            reactions_not_to_reverse.add(r_id)
            reactions_not_to_reverse.add(reverse_reaction_hashes_rev[h])

    model_db_rxn_ids = {}
    for reaction in model.reactions:
        # Drop duplicates label
        reaction_id = parse.remove_duplicate_tag(reaction.id)

        # Get the reaction
        reaction_db = (session
                       .query(Reaction)
                       .filter(Reaction.bigg_id == reaction_id)
                       .first())

        # check for pseudoreaction
        is_pseudoreaction = check_pseudoreaction(reaction_id)

        # calculate the hash
        reaction_hash = reaction_hashes[reaction.id]
        hash_db = (session
                   .query(Reaction)
                   .filter(Reaction.reaction_hash == reaction_hash)
                   .filter(Reaction.pseudoreaction == is_pseudoreaction)
                   .first())
        # If there wasn't a match for the forward hash, also check the reverse
        # hash. Do not check reverse hash for reactions with both directions
        # defined in the same model (e.g. SUCDi and FRD7).
        if not hash_db and reaction.id not in reactions_not_to_reverse:
            reverse_hash_db = (session
                               .query(Reaction)
                               .filter(Reaction.reaction_hash == reverse_reaction_hashes[reaction.id])
                               .filter(Reaction.pseudoreaction == is_pseudoreaction)
                               .first())
        else:
            reverse_hash_db = None

        # bigg_id match  hash match b==h  pseudoreaction  example                   function
        #  n               n               n            first GAPD                _new_reaction (1)
        #  n               n               y            first EX_glc_e            _new_reaction (1)
        #  y               n               n            incorrect GAPD            _new_reaction & increment (2)
        #  y               n               y            incorrect EX_glc_e        _new_reaction & increment (2)
        #  n               y               n            GAPDH after GAPD          reaction = hash_reaction (3a)
        #  n               y               y            EX_glc__e after EX_glc_e  reaction = hash_reaction (3a)
        #  y               y         n     n            ?                         reaction = hash_reaction (3a)
        #  y               y         n     y            ?                         reaction = hash_reaction (3a)
        #  y               y         y     n            second GAPD               reaction = bigg_reaction (3b)
        #  y               y         y     y            second EX_glc_e           reaction = bigg_reaction (3b)
        # NOTE: only check pseudoreaction hash against other pseudoreactions
        # 4a and 4b are 3a and 3b with a reversed reaction

        def _find_new_incremented_id(session, original_id):
            """Look for a reaction bigg_id that is not already taken."""
            new_id = increment_id(original_id)
            while True:
                # Check for existing and deprecated reaction ids
                if (session.query(Reaction).filter(Reaction.bigg_id == new_id).first() is None and
                    not _is_deprecated_reaction_id(session, new_id)):
                    return new_id
                new_id = increment_id(new_id)

        # Check for a preferred ID in the preferences, based on the forward
        # hash. Don't check the reverse hash in preferences.
        preferred_id = _check_hash_prefs(reaction_hash, is_pseudoreaction)

        # no reversed by default
        is_reversed = False
        is_new = False

        # (0) If there is a preferred ID, make that the new ID, and increment any old IDs
        if preferred_id is not None:
            # if the reaction already matches, just continue
            if hash_db is not None and hash_db.bigg_id == preferred_id:
                reaction_db = hash_db
            # otherwise, make the new reaction
            else:
                # if existing reactions match the preferred reaction find a new,
                # incremented id for the existing match
                preferred_id_db = session.query(Reaction).filter(Reaction.bigg_id == preferred_id).first()
                if preferred_id_db is not None:
                    new_id = _find_new_incremented_id(session, preferred_id)
                    logging.warning('Incrementing database reaction {} to {} and prefering {} (from model {}) based on hash preferences'
                                .format(preferred_id, new_id, preferred_id, model.id))
                    preferred_id_db.bigg_id = new_id
                    session.commit()

                # make a new reaction for the preferred_id
                reaction_db = _new_reaction(session, reaction, preferred_id,
                                            reaction_hash, model_db_id, model,
                                            is_pseudoreaction, comp_comp_db_ids)
                is_new = True

        # (1) no bigg_id matches, no stoichiometry match or pseudoreaction, then
        # make a new reaction
        elif reaction_db is None and hash_db is None and reverse_hash_db is None:
            # check that the id is not deprecated
            if _is_deprecated_reaction_id(session, reaction.id):
                logging.error(('Keeping bigg_id {} (hash {} - from model {}) '
                               'even though it is on the deprecated ID list. '
                               'You should add it to reaction-hash-prefs.txt')
                              .format(reaction_id, reaction_hash, model.id))
            reaction_db = _new_reaction(session, reaction, reaction_id,
                                        reaction_hash, model_db_id, model,
                                        is_pseudoreaction, comp_comp_db_ids)
            is_new = True

        # (2) bigg_id matches, but not the hash, then increment the BIGG_ID
        elif reaction_db is not None and hash_db is None and reverse_hash_db is None:
            # loop until we find a non-matching find non-matching ID
            new_id = _find_new_incremented_id(session, reaction.id)
            logging.warning('Incrementing bigg_id {} to {} (from model {}) based on conflicting reaction hash'
                        .format(reaction_id, new_id, model.id))
            reaction_db = _new_reaction(session, reaction, new_id,
                                        reaction_hash, model_db_id, model,
                                        is_pseudoreaction, comp_comp_db_ids)
            is_new = True

        # (3) but found a stoichiometry match, then use the hash reaction match.
        elif hash_db is not None:
            # WARNING TODO this requires that loaded metabolites always match on
            # bigg_id, which should be the case.

            # (3a)
            if reaction_db is None or reaction_db.id != hash_db.id:
                reaction_db = hash_db
            # (3b) BIGG ID matches a reaction with the same hash, then just continue
            else:
                pass

        # (4) but found a stoichiometry match, then use the hash reaction match.
        elif reverse_hash_db is not None:
            # WARNING TODO this requires that loaded metabolites always match on
            # bigg_id, which should be the case.

            # Remember to switch upper and lower bounds
            is_reversed = True
            logging.info('Matched {} to {} based on reverse hash'
                         .format(reaction_id, reverse_hash_db.bigg_id))

            # (4a)
            if reaction_db is None or reaction_db.id != reverse_hash_db.id:
                reaction_db = reverse_hash_db
            # (4b) BIGG ID matches a reaction with the same hash, then just continue
            else:
                pass

        else:
            raise Exception('Should not get here')

        # If the reaction is not new, consider improving the descriptive name
        if not is_new:
            new_name = scrub_name(check_none(getattr(reaction, 'name', None)))
            improve_name(session, reaction_db, new_name)

        # Add reaction to deprecated ID list if necessary
        if reaction_db.bigg_id != reaction_id:
            get_or_create(session, DeprecatedID, deprecated_id=reaction_id,
                          type='reaction', ome_id=reaction_db.id)

        # If the reaction is reversed, then switch upper and lower bound
        lower_bound = -reaction.upper_bound if is_reversed else reaction.lower_bound
        upper_bound = -reaction.lower_bound if is_reversed else reaction.upper_bound

        # subsystem
        subsystem = check_none(reaction.subsystem.strip())

        # get the model reaction
        model_reaction_db = (session
                             .query(ModelReaction)
                             .filter(ModelReaction.reaction_id == reaction_db.id)
                             .filter(ModelReaction.model_id == model_db_id)
                             .filter(ModelReaction.lower_bound == lower_bound)
                             .filter(ModelReaction.upper_bound == upper_bound)
                             .filter(ModelReaction.gene_reaction_rule == reaction.gene_reaction_rule)
                             .filter(ModelReaction.objective_coefficient == reaction.objective_coefficient)
                             .filter(ModelReaction.subsystem == subsystem)
                             .first())
        if model_reaction_db is None:
            # get the number of existing copies of this reaction in the model
            copy_number = (session
                           .query(ModelReaction)
                           .filter(ModelReaction.reaction_id == reaction_db.id)
                           .filter(ModelReaction.model_id == model_db_id)
                           .count()) + 1
            # make a new reaction
            model_reaction_db = ModelReaction(model_id=model_db_id,
                                              reaction_id=reaction_db.id,
                                              gene_reaction_rule=reaction.gene_reaction_rule,
                                              original_gene_reaction_rule=reaction.gene_reaction_rule,
                                              upper_bound=upper_bound,
                                              lower_bound=lower_bound,
                                              objective_coefficient=reaction.objective_coefficient,
                                              copy_number=copy_number,
                                              subsystem=subsystem)
            session.add(model_reaction_db)
            session.commit()

        # remember the changed ids
        model_db_rxn_ids[reaction.id] = model_reaction_db.id

        # add synonyms
        #
        # get the id from the published model
        for old_bigg_id in old_reaction_ids[reaction.id]:
            # add a synonym
            synonym_db = (session
                          .query(Synonym)
                          .filter(Synonym.type == 'reaction')
                          .filter(Synonym.ome_id == reaction_db.id)
                          .filter(Synonym.synonym == old_bigg_id)
                          .filter(Synonym.data_source_id == data_source_id)
                          .first())
            if synonym_db is None:
                synonym_db = Synonym(type='reaction',
                                     ome_id=reaction_db.id,
                                     synonym=old_bigg_id,
                                     data_source_id=data_source_id)
                session.add(synonym_db)
                session.commit()

            # add OldIDSynonym
            old_id_db = (session
                         .query(OldIDSynonym)
                         .filter(OldIDSynonym.type == 'model_reaction')
                         .filter(OldIDSynonym.ome_id == model_reaction_db.id)
                         .filter(OldIDSynonym.synonym_id == synonym_db.id)
                         .first())
            if old_id_db is None:
                old_id_db = OldIDSynonym(type='model_reaction',
                                         ome_id=model_reaction_db.id,
                                         synonym_id=synonym_db.id)
                session.add(old_id_db)
                session.commit()

    return model_db_rxn_ids

# find gene functions
def _match_gene_by_fns(fn_list, session, gene_id, chromosome_ids):
    """Go through each funciton and look for a match.

    """
    for fn in fn_list:
        match, is_alternative_transcript = fn(session, gene_id, chromosome_ids)
        if len(match) > 0:
            if len(match) > 1:
                logging.warning('Multiple matches for gene {} with function {}. Using the first match.'
                            .format(gene_id, fn.__name__))
            return match[0], is_alternative_transcript
    return None, False

def _by_bigg_id(session, gene_id, chromosome_ids):
    # look for a matching model gene
    gene_db = (session
               .query(Gene)
               .filter(func.lower(Gene.bigg_id) == func.lower(gene_id))
               .filter(Gene.chromosome_id.in_(chromosome_ids))
               .all())
    return gene_db, False

def _by_name(session, gene_id, chromosome_ids):
    gene_db = (session
               .query(Gene)
               .filter(func.lower(Gene.name) == func.lower(gene_id))
               .filter(Gene.chromosome_id.in_(chromosome_ids))
               .all())
    return gene_db, False

def _by_synonym(session, gene_id, chromosome_ids):
    gene_db = (session
               .query(Gene)
               .join(Synonym, Synonym.ome_id == Gene.id)
               .filter(Gene.chromosome_id.in_(chromosome_ids))
               .filter(func.lower(Synonym.synonym) == func.lower(gene_id))
               .all())
    return gene_db, False

def _by_alternative_transcript(session, gene_id, chromosome_ids):
    """Function to check for the alternative transcript match."""
    check = re.match(r'(.*)_AT[0-9]{1,2}$', gene_id)
    if not check:
        gene_db = []
    else:
        # find the old gene
        gene_db = (session
                   .query(Gene)
                   .filter(Gene.chromosome_id.in_(chromosome_ids))
                   .filter(func.lower(Gene.bigg_id) == func.lower(check.group(1)))
                   .filter(Gene.alternative_transcript_of.is_(None))
                   .all())
    return gene_db, True

def _by_alternative_transcript_name(session, gene_id, chromosome_ids):
    """Function to check for the alternative transcript match."""
    check = re.match(r'(.*)_AT[0-9]{1,2}$', gene_id)
    if not check:
        gene_db = []
    else:
        # find the old gene
        gene_db = (session
                   .query(Gene)
                   .filter(Gene.chromosome_id.in_(chromosome_ids))
                   .filter(func.lower(Gene.name) == func.lower(check.group(1)))
                   .filter(Gene.alternative_transcript_of.is_(None))
                   .all())
    return gene_db, True

def _by_alternative_transcript_synonym(session, gene_id, chromosome_ids):
    """Function to check for the alternative transcript match."""
    check = re.match(r'(.*)_AT[0-9]{1,2}$', gene_id)
    if not check:
        gene_db = []
    else:
        # find the old gene
        gene_db = (session
                   .query(Gene)
                   .join(Synonym, Synonym.ome_id == Gene.id)
                   .filter(Gene.chromosome_id.in_(chromosome_ids))
                   .filter(func.lower(Synonym.synonym) == func.lower(check.group(1)))
                   .filter(Gene.alternative_transcript_of.is_(None))
                   .all())
    return gene_db, True

def _by_bigg_id_no_underscore(session, gene_id, chromosome_ids):
    """Matches for T maritima genes"""
    # look for a matching model gene
    gene_db = (session
               .query(Gene)
               .filter(func.lower(Gene.bigg_id) == func.lower(gene_id.replace('_', '')))
               .filter(Gene.chromosome_id.in_(chromosome_ids))
               .all())
    return gene_db, False

def _replace_gene_str(rule, old_gene, new_gene):
    return re.sub(r'\b'+old_gene+r'\b', new_gene, rule)

def load_genes(session, model_db_id, model, model_db_rxn_ids, old_gene_ids):
    """Load the genes for this model.

    Arguments:
    ---------

    session: An SQLAlchemy session.

    model_db_id: The database ID for the model.

    model: The COBRApy model.

    model_db_rxn_ids: A dictionary with keys for reactions in the model and
    values for the associated ModelReaction.id in the database.

    old_gene_ids: A dictionary where keys are new IDs and values are old IDs for
    genes.

    """
    # only grab this once
    data_source_id = get_or_create_data_source(session, 'old_bigg_id')

    # find the model in the db
    model_db = session.query(Model).get(model_db_id)

    # find the chromosomes in the db
    chromosome_ids = (session
                      .query(Chromosome.id)
                      .filter(Chromosome.genome_id == model_db.genome_id)
                      .all())
    if len(chromosome_ids) == 0:
        logging.warning('No chromosomes for model %s' % model_db.bigg_id)

    # keep track of the gene-reaction associations
    gene_bigg_id_to_model_reaction_db_ids = defaultdict(set)
    for reaction in model.reactions:
        # find the ModelReaction that corresponds to this particular reaction in
        # the model
        model_reaction_db = (session
                             .query(ModelReaction)
                             .get(model_db_rxn_ids[reaction.id]))
        if model_reaction_db is None:
            logging.error('Could not find ModelReaction {} for {} in model {}. Cannot load GeneReactionMatrix entries'
                          .format(model_db_rxn_ids[reaction.id], reaction.id, model.id))
            continue
        for gene in reaction.genes:
            gene_bigg_id_to_model_reaction_db_ids[gene.id].add(model_reaction_db.id)

    # load the genes
    for gene in model.genes:
        if len(chromosome_ids) == 0:
            gene_db = None; is_alternative_transcript = False
        else:
            # find a matching gene
            fns = [_by_bigg_id, _by_name, _by_synonym, _by_alternative_transcript,
                   _by_alternative_transcript_name, _by_alternative_transcript_synonym,
                   _by_bigg_id_no_underscore]
            gene_db, is_alternative_transcript = _match_gene_by_fns(fns, session,
                                                                    gene.id,
                                                                    chromosome_ids)

        if not gene_db:
            # add
            if len(chromosome_ids) > 0:
                logging.warning('Gene not in genbank file: {} from model {}'
                            .format(gene.id, model.id))
            gene_db = Gene(bigg_id=gene.id,
                           # name is optional in cobra 0.4b2. This will probably change back.
                           name=scrub_name(getattr(gene, 'name', None)),
                           mapped_to_genbank=False)
            session.add(gene_db)
            session.commit()

        elif is_alternative_transcript:
            # duplicate gene for the alternative transcript
            old_gene_db = gene_db
            ome_gene = {}
            ome_gene['bigg_id'] = gene.id
            ome_gene['name'] = old_gene_db.name
            ome_gene['leftpos'] = old_gene_db.leftpos
            ome_gene['rightpos'] = old_gene_db.rightpos
            ome_gene['chromosome_id'] = old_gene_db.chromosome_id
            ome_gene['strand'] = old_gene_db.strand
            ome_gene['mapped_to_genbank'] = True
            ome_gene['alternative_transcript_of'] = old_gene_db.id
            gene_db = Gene(**ome_gene)
            session.add(gene_db)
            session.commit()

            # duplicate all the synonyms
            synonyms_db = (session
                           .query(Synonym)
                           .filter(Synonym.ome_id == old_gene_db.id)
                           .all())
            for syn_db in synonyms_db:
                # add a new synonym
                ome_synonym = {}
                ome_synonym['type'] = syn_db.type
                ome_synonym['ome_id'] = gene_db.id
                ome_synonym['synonym'] = syn_db.synonym
                ome_synonym['data_source_id'] = syn_db.data_source_id
                synonym_object = Synonym(**ome_synonym)
                session.add(synonym_object)

        # add model gene
        model_gene_db = (session
                         .query(ModelGene)
                         .filter(ModelGene.gene_id == gene_db.id)
                         .filter(ModelGene.model_id == model_db_id)
                         .first())
        if model_gene_db is None:
            model_gene_db = ModelGene(gene_id=gene_db.id,
                                      model_id=model_db_id)
            session.add(model_gene_db)
            session.commit()

        # add old gene synonym
        for old_bigg_id in old_gene_ids[gene.id]:
            synonym_db = (session
                          .query(Synonym)
                          .filter(Synonym.type == 'gene')
                          .filter(Synonym.ome_id == gene_db.id)
                          .filter(Synonym.synonym == old_bigg_id)
                          .filter(Synonym.data_source_id == data_source_id)
                          .first())
            if synonym_db is None:
                synonym_db = Synonym(type='gene',
                                     ome_id=gene_db.id,
                                     synonym=old_bigg_id,
                                     data_source_id=data_source_id)
                session.add(synonym_db)
                session.commit()
            # add OldIDSynonym
            old_id_db = (session
                         .query(OldIDSynonym)
                         .filter(OldIDSynonym.type == 'model_gene')
                         .filter(OldIDSynonym.ome_id == model_gene_db.id)
                         .filter(OldIDSynonym.synonym_id == synonym_db.id)
                         .first())
            if old_id_db is None:
                old_id_db = OldIDSynonym(type='model_gene',
                                        ome_id=model_gene_db.id,
                                        synonym_id=synonym_db.id)
                session.add(old_id_db)
                session.commit()

        # find model reaction
        try:
            model_reaction_db_ids = gene_bigg_id_to_model_reaction_db_ids[gene.id]
        except KeyError:
            # error message above
            continue

        for mr_db_id in model_reaction_db_ids:
            # add to the GeneReactionMatrix, if not already present
            found_gene_reaction_row = (session
                                       .query(GeneReactionMatrix)
                                       .filter(GeneReactionMatrix.model_gene_id == model_gene_db.id)
                                       .filter(GeneReactionMatrix.model_reaction_id == mr_db_id)
                                       .count() > 0)
            if not found_gene_reaction_row:
                new_object = GeneReactionMatrix(model_gene_id=model_gene_db.id,
                                                model_reaction_id=mr_db_id)
                session.add(new_object)

            # update the gene_reaction_rule if the gene id has changed
            if gene.id != gene_db.bigg_id:
                mr = session.query(ModelReaction).get(mr_db_id)
                new_rule = _replace_gene_str(mr.gene_reaction_rule, gene.id,
                                             gene_db.bigg_id)
                (session
                .query(ModelReaction)
                .filter(ModelReaction.id == mr_db_id)
                .update({ModelReaction.gene_reaction_rule: new_rule}))

def load_model_count(session, model_db_id):
    metabolite_count = (session
                        .query(ModelCompartmentalizedComponent.id)
                        .filter(ModelCompartmentalizedComponent.model_id == model_db_id)
                        .count())
    reaction_count = (session
                      .query(ModelReaction.id)
                      .filter(ModelReaction.model_id == model_db_id)
                      .count())
    gene_count = (session
                  .query(ModelGene.id)
                  .filter(ModelGene.model_id == model_db_id)
                  .count())
    mc = ModelCount(model_id=model_db_id,
                    gene_count=gene_count,
                    metabolite_count=metabolite_count,
                    reaction_count=reaction_count)
    session.add(mc)


file = open("JamesmiRNA.csv",'r')
out = open("JamesmiRNA_Tim.csv",'w')
for line in file:
    line=line.rstrip()
    gene = line.split(",")[6]
    period=gene.find(".")
    flag = -1
    for i in range(period + 1, len(gene)):
        if gene[i].isalpha() or gene[i] == ".":
            flag = i
            break

    if flag==-1: line+=","+gene+"\n"
    else: line+=","+gene[:flag]+"\n"

    out.write(line)


# Viết một hàm để đếm số lần xuất hiện của một từ trong chuỗi nhập vào từ bàn phím
def count_word_occurrences(string, word):
    count = 0
    words = string.split()
    for w in words:
        if w == word:
            count += 1
    return count

input_string = input("Enter a string: ")
word_to_count = input("Enter a word to count: ")

occurrences = count_word_occurrences(input_string, word_to_count)
print("Number of occurrences:", occurrences)


n = int(input())
lista = [0,1]
i, t1 = 0, 0
t2 = 1
for e in range(n):
    f = int(input())
    while i < 60:
        t3 = t1 + t2
        lista.append(t3)
        t1 = t2
        t2 = t3
        i += 1
    print("Fib(%d) = %d" % (f, lista[f]))