from django import forms

from games.models import List

class AuthorListForm(forms.ModelForm):
    class Meta:
        model = List
        fields = [
            'title',
            'description',
            'games'
        ]

        labels = {
           'title': 'Nome da Lista',
           'description': 'Descrição',
           'games': ''
        }
        error_messages = {
            'title': {
                'required': 'Esse campo não pode ficar vazio.',
            },
            'description': {
                'required': 'Esse campo não pode ficar vazio.',
            },
            'games': {
                'required': 'Esse campo não pode ficar vazio.'
            },
        }
        widgets = {
            'title': forms.TextInput(attrs={
                'class': 'editInput',
                'id': 'title',
                'autocomplete': 'off',
                'required': 'true',
                'placeholder': 'Nome da Lista',
            }),
            'description': forms.Textarea(attrs={
                'class': 'editInput',
                'id': 'description',
                'autocomplete': 'off',
                'required': 'true',
                'placeholder': 'Digite aqui a descrição da lista...'
            }),
            'games': forms.SelectMultiple(attrs={
                'class': 'editInput',
                'id': 'games',
                'required': 'true',
                'placeholder': 'Games'
            }),
        }


from typing import List, Tuple

def sum_product(numbers: List[int]) -> Tuple[int, int]:
    """ For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.
    Empty sum should be equal to 0 and empty product should be equal to 1.
    """
    if not numbers:
        return (0, 1)
    else:
        return (sum(numbers), 1)

for i in numbers:
    result *= i

return (result, sum_result)


import os
import sys
import shutil
import warnings

from io import open
from pathlib import Path
from setuptools import setup, find_packages
from setuptools.command.install import install

here = Path(__file__).parent.resolve()

sys.path.insert(0, str(here / 'jax_meta'))
from version import VERSION

class InstallCommand(install):
    def run(self):
        super().run()

        if 'JAX_META_REPOSITORY' in os.environ:
            repository = Path(os.environ['JAX_META_REPOSITORY'])
            if not repository.exists():
                warnings.warn(f'Repository not found (ignoring): {repository}')
                return

            destination = Path(self.install_lib) / 'jax_meta' / 'datasets' / 'assets'
            shutil.copy(repository, destination / 'repository.json')

# Get the long description from the README file
with open(here / 'README.md', encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='jax_meta',
    version=VERSION,
    description='Collection of meta-learning algorithms in Jax',
    long_description=long_description,
    long_description_content_type='text/markdown',
    license='MIT',
    author='Tristan Deleu',
    author_email='tristan.deleu@gmail.com',
    url='https://github.com/tristandeleu/jax-meta-learning',
    keywords=['meta-learning', 'jax', 'few-shot', 'few-shot learning'],
    packages=find_packages(exclude=['data', 'contrib', 'docs', 'tests', 'examples']),
    install_requires=[
        'jax',
        'jaxlib',
        'tqdm',
        'simple-parsing',
        'Pillow>=7.0.0',
        'dm-haiku',
        'optax'
    ],
    package_data={'jax_meta': ['jax_meta/datasets/assets/*']},
    include_package_data=True,
    cmdclass={'install': InstallCommand},
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Topic :: Scientific/Engineering :: Artificial Intelligence',
        'Intended Audience :: Science/Research',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'License :: OSI Approved :: MIT License',
    ],
)


#!/usr/bin/env python
# Code by Lachlan Marnoch, 20XX

import os

import astropy.units as units

import craftutils.utils as u

import lib

description = """
Derives the imaging limits.
"""

def main(
        output_dir: str,
        input_dir: str
):
    lib.set_input_path(input_dir)
    lib.set_output_path(output_dir)

    fld = lib.fld
    frb210912 = fld.frb

    lib.load_images()
    image_dict = {
        "unsubtracted": {
            "g_HIGH": lib.g_img,
            "R_SPECIAL": lib.R_img,
            "I_BESS": lib.I_img,
            "Ks": lib.K_img
        },
        "trimmed": {
            "g_HIGH": lib.g_img_trimmed,
            "R_SPECIAL": lib.R_img_trimmed,
            "I_BESS": lib.I_img_trimmed,
            "Ks": lib.K_img
        },
        "WISE": {
            "W1": lib.W1_img,
            "W2": lib.W2_img,
            "W3": lib.W3_img,
            "W4": lib.W4_img
        }
    }

    output_dir = os.path.join(output_dir, "limits")
    u.mkdir_check_nested(output_dir, False)

    for dict_name in image_dict:
        d = image_dict[dict_name]
        limits = {}
        output_dir_this = os.path.join(output_dir, dict_name)
        u.mkdir_check(output_dir_this)
        print("\n=====================================================")
        print("5-sigma imaging limits,", dict_name)
        for fil in d:
            img = d[fil]
            psf = img.extract_header_item("PSF_FWHM")
            if psf is None:
                if fil == "W4":
                    psf = 16.5
                else:
                    psf = 8.25

            ap_radius = 2 * psf * units.arcsec
            if img.zeropoint_best is None:
                img.zeropoint()
            results = img.test_limit_location(
                coord=frb210912.position,
                ap_radius=ap_radius
            )
            limits[fil] = results
            results.write(os.path.join(output_dir_this, f"limits_{dict_name}_{fil}.ecsv"), overwrite=True)
            print(fil, ":", results[4]["mag"],) #img.get_zeropoint(cat_name="best", img_name="self"))

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(
        description=description
    )

    parser.add_argument(
        "-o",
        help="Path to output directory.",
        type=str,
        default=lib.default_output_path
    )
    parser.add_argument(
        "-i",
        help="Path to directory containing input files.",
        type=str,
        default=lib.default_input_path
    )

    args = parser.parse_args()
    output_path = args.o
    input_path = args.i
    main(
        output_dir=output_path,
        input_dir=input_path
    )


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

import time
from multiprocessing import Process

from sl4p import *

cfg = {
    "LOG": {
        "logging_format": "detail",
        "logging_level": "DEBUG",
        "logfile_name": "MP_EXAMPLE_1",
        "logfile_savedir": "mp_logs",
        "console_stdout": True,
        "console_colorlog_kwargs": dict(no_color=True)
    }
}

log = sl4p.getLogger(__file__, cfg, debugprt=1)

def do_mprocess(pi):
    llog = sl4p.getLogger(__file__, debugprt=1)
    print("Sub-process {}, logger = {}".format(pi, llog))
    print("Equal?? : {}".format(log == llog))
    for a in ['a', 'b', 'c', 'd', 'e']:
        time.sleep(0.7)
        llog.info("MP {} msg {}!".format(pi, a))

if __name__ == '__main__':

    print("Primary logger = {}".format(log))
    procs = list()

    n_proc = 20
    for i in range(n_proc):
        procs.append(Process(target=do_mprocess, args={"mp_{}".format(i)}))

    for i in range(n_proc):
        procs[i].start()

    for i in range(n_proc):
        procs[i].join()

    log.info("finished!")


from src.database.db import db
from sqlalchemy.orm import relationship
from collections import OrderedDict

class Product(db.Model):
    __tablename__ = 'products'
    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(100))
    name = db.Column(db.String(100))
    price = db.Column(db.Integer)
    is_buyable = db.Column(db.Boolean, default=False)
    carts = relationship('Cart', secondary='cart_items', back_populates='products')
    orders = relationship('Order', secondary='order_items', back_populates='products')

    def __init__(self, code, name, price, is_buyable):
        self.code = code
        self.name = name
        self.price = price
        self.is_buyable = is_buyable

    @staticmethod
    def create(code, name, price, is_buyable):
        try:
            new_product = Product(code, name, price, is_buyable)
            db.session.add(new_product)
            db.session.commit()
            return OrderedDict(error=None, status_code=201)
        except Exception as e:
            return OrderedDict(error=str(e), status_code=500)

    @staticmethod
    def get_all():
        try:
            products = Product.query.all()
            return OrderedDict(found_products=products, error=None, status_code=200)
        except Exception as e:
            return OrderedDict(found_products=None, error=str(e), status_code=500)

    @staticmethod
    def get_one(code):
        try:
            product = Product.query.filter_by(code=code).first()
            if not product:
                return OrderedDict(found_product=None, error='Product not found', status_code=404)

            return OrderedDict(found_product=product, error=None, status_code=200)
        except Exception as e:
            return OrderedDict(found_product=None, error=str(e), status_code=500)

    @staticmethod
    def update_one(product_id, product_data):
        try:
            product = Product.query.get(product_id)
            if not product:
                return OrderedDict(updated_product=None, error='Product not found', status_code=404)

            # Update product
            for key, value in product_data.items():
                if value:
                    setattr(product, key, value)
            db.session.commit()
            return OrderedDict(updated_product=product, error=None, status_code=200)
        except Exception as e:
            return OrderedDict(updated_product=None, error=str(e), status_code=500)

    @staticmethod
    def delete_one(product_id):
        try:
            product = Product.query.get(product_id)
            if not product:
                return OrderedDict(error='Product not found', status_code=404)

            db.session.delete(product)
            db.session.commit()
            return OrderedDict(error=None, status_code=204)
        except Exception as e:
            return OrderedDict(error=str(e), status_code=500)


M = int(input())
N = int(input())
lst = list(range(M,N+1))
lst2 = []

for i in lst:
    error = 0
    for j in range(2,i+1):
        if i%j == 0:
            error+=1
    if error == 1:
        lst2.append(i)

if len(lst2) == 0:
    print('-1')
else:
    print(sum(lst2))
    print(min(lst2))