from City import City
from City import create_cities
from City import tour_distance

import time

def travel_next(city, city_list, tour, all_tours):
    """Searches onward recursively
    Searches recursively and saves a full tour
    when the endconditions are met.

    Arguments:
        city (City): current location
        city_list (list): the full searchfield
        all_tours (list): a list of all tours
    """
    city.traversed = 1
    tour.append(city)
    is_end = True

    for next_city in city_list:
        if(next_city.traversed is not 1):
            travel_next(next_city, city_list, tour, all_tours)
            next_city.traversed = 0
            is_end = False
    if(is_end):
        endtour = tour.copy()
        all_tours.append(endtour)
    tour.remove(city)

def recursive_travel(city_list):
    """Start the recursive search

    Arguments:
        city_list (list): list of cities
    Returns:
        all_tours (list): list of tours
    """
    tour = []
    all_tours = []

    for city in city_list:
            travel_next(city, city_list,tour, all_tours)
            city.traversed = 0
    return all_tours

def shortest_tour(all_tours):
    """Returns the shortest tour from a list of all_tours

    Arguments:
        all_tours (list): List of all tours
    Returns:
        shortest (list)          : Shortest tour
    """
    shortest = all_tours[0]

    for tour in all_tours:
        if tour_distance(shortest) > tour_distance(tour):
            shortest = tour
    return shortest

def exhaustive_search(city_list,until):
    """Runs exhaustive search for a given amount of cities

    Arguments:
        city_list (list): list of cities
        until (integer) : amount of cities to search
    """
    all_tours = recursive_travel(city_list[0:until])
    shortest = shortest_tour(all_tours)
    return shortest

def brute_force(city_list):
    """Runs the exhaustive search and collects data

    Arguments:
        city_list (list): list of cities
    """
    start = time.time()*1000
    shortest = exhaustive_search(city_list,6)
    stop = time.time()*1000
    print("Shortest tour for 6 first cities:", tour_distance(shortest))
    print ("Time spent on 6 first cities:", "%.2f" % (stop-start), "ms")
    print("-")

    start = time.time()*1000
    shortest = exhaustive_search(city_list,7)
    stop = time.time()*1000
    print("Shortest tour for 7 first cities:", tour_distance(shortest))
    print ("Time spent on 7 first cities:", "%.2f" % (stop-start), "ms")
    print("-")

    start = time.time()*1000
    shortest = exhaustive_search(city_list,8)
    stop = time.time()*1000
    print("Shortest tour for 8 first cities:", tour_distance(shortest))
    print ("Time spent on 8 first cities:", "%.2f" % (stop-start), "ms")
    print("-")

    start = time.time()*1000
    shortest = exhaustive_search(city_list,9)
    stop = time.time()*1000
    print("Shortest tour for 9 first cities:", tour_distance(shortest))
    print ("Time spent on 9 first cities:", "%.2f" % (stop-start), "ms")
    print("-")

    start = time.time()*1000
    shortest = exhaustive_search(city_list,10)
    stop = time.time()*1000
    print("Shortest tour for 10 first cities:", tour_distance(shortest))
    print ("Time spent on 10 first cities:", "%.2f" % (stop-start), "ms")
    print(" ")


import logging
from subscription_manager import *

LOGGER = logging.getLogger(__name__)

class SubscriptionStatusManager():
    """Manager for accessing subscription statuses"""

    @classmethod
    def match_braintree_state(cls):
        """
        Update all braintree customer info to make them synchronous with braintree
        """
        # Find all created subscriptions
        subscribed_users = BraintreeUser.objects.exclude(subscription_id="").exclude(subscription_id=None)
        for user in subscribed_users:
            try:
                subscription = SubscriptionManager.fetch_subscription_from_braintree(user)
                if SubscriptionManager.is_braintree_subscription_active(subscription):
                    user.active = True
                    user.expiry_date = subscription.billing_period_end_date
                elif SubscriptionManager.is_braintree_subscription_in_terminating_state(subscription):
                    user.subscription_id = ""
                    user.active = False
                    user.expiry_date = None
                    user.pending_cancel = False
                else:
                    user.active = False
                    user.expiry_date = subscription.billing_period_end_date
                user.save()
            except BraintreeError as e:
                LOGGER.exception("Could not match braintree state for user %s",user)

    @classmethod
    def cancel_all_pending_cancel(cls, days_left=1):
        """
        Cancel all susbcriptions that are about to be renewed where a Pending Cancel state has been reached.
        Does this by selecting all subscriptions that would expire within days_left number of days AFTER the next billing date
        :return:
        """
        threshold = timezone.make_aware(SubscriptionManager.construct_next_billing_datetime() +
                                        timezone.timedelta(days=days_left),pytz.utc)

        LOGGER.info("Threshold date for cancellation: %s",str(threshold))
        users_pending_cancel = BraintreeUser.objects.filter(pending_cancel=True).filter(expiry_date__lte=threshold)
        for user in users_pending_cancel:
            try:
                SubscriptionManager.cancel_on_braintree(user)
            except BraintreeError as e:
                LOGGER.exception("Could not cancel subscription for %s on braintree. Needs to be done manually!",user)


from django.core.management.base import BaseCommand
from portfolio.lib.etl import Extraction, Transformation, Loading

class Command(BaseCommand):

    def handle(self, *args, **kwargs):

        extraction = Extraction()
        extraction.run()
        extraction_data = extraction.data

        transformation = Transformation(extraction_data)
        transformation.run()
        transformation_data = transformation.data

        loading = Loading(transformation_data)
        loading.run()


import json
import boto3

def lambda_handler(event, context):

    sns = boto3.client('sns')
    print(event)

    email_body = event['email']
    print(email_body)

    response1 = sns.subscribe(
        TopicArn='arn:aws:sns:us-east-1:357054887258:processing-complete',
        Protocol='email',
        Endpoint=email_body,

        ReturnSubscriptionArn=True
    )
    response =  {
        'statusCode': 200,
        'body': json.dumps('Email sent successfully!')
    }

    response["headers"] = {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
    }

    return response;


from discord.ext import commands

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

    @commands.command(help='Check if the bot is alive')
    async def heartbeat(self, ctx):
        await ctx.send('Hi! :heart: :heart: :heart: \n Are you ready for some ' +
                       'Factoriooo?! :construction_site:')

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author == self.bot.user:
            return

        if 'penguin' in message.content:
            await message.channel.send(':penguin:')

        if 'train' in message.content:
            await message.channel.send("Let's build a TRAAIINN :train2:")

        if 'science' in message.content:
            await message.channel.send(":man_scientist: Let's do some SCIENCE :woman_scientist:")


# -*- coding:utf-8 -*-
"""
For the convenient dotenv things, there are two dotenv library "django-dotenv"
and "python-dotenv" which all install itself as "dotenv" but not compatible,
and there is always something missing for each of them, what a shit!

Stop thinking which "dotenv" is the imported library, just use ourselves.
This module is copied from django-dotenv 1.4.1 and python-dotenv 0.7.1.
"""

import os
import re
import sys
import warnings

line_re = re.compile(r"""
    ^
    (?:export\s+)?      # optional export
    ([\w\.]+)           # key
    (?:\s*=\s*|:\s+?)   # separator
    (                   # optional value begin
        '(?:\'|[^'])*'  #   single quoted value
        |               #   or
        "(?:\"|[^"])*"  #   double quoted value
        |               #   or
        [^#\n]+         #   unquoted value
    )?                  # value end
    (?:\s*\#.*)?        # optional comment
    $
""", re.VERBOSE)

variable_re = re.compile(r"""
    (\\)?               # is it escaped with a backslash?
    (\$)                # literal $
    (                   # collect braces with var for sub
        \{?             #   allow brace wrapping
        ([A-Z0-9_]+)    #   match the variable
        \}?             #   closing brace
    )                   # braces end
""", re.IGNORECASE | re.VERBOSE)

def _walk_to_root(path):
    """
    Yield directories starting from the given directory up to the root
    """
    if not os.path.exists(path):
        raise IOError('Starting path not found')

    if os.path.isfile(path):
        path = os.path.dirname(path)

    last_dir = None
    current_dir = os.path.abspath(path)
    while last_dir != current_dir:
        yield current_dir
        parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir))
        last_dir, current_dir = current_dir, parent_dir

def find_dotenv(filename='.env', raise_error_if_not_found=True, usecwd=False):
    """
    Search in increasingly higher folders for the given file

    Returns path to the file if found, or an empty string otherwise
    """
    if usecwd or '__file__' not in globals():
        # should work without __file__, e.g. in REPL or IPython notebook
        path = os.getcwd()
    else:
        # will work for .py files
        frame_filename = sys._getframe().f_back.f_code.co_filename
        path = os.path.dirname(os.path.abspath(frame_filename))

    for dirname in _walk_to_root(path):
        check_path = os.path.join(dirname, filename)
        if os.path.exists(check_path):
            return check_path

    if raise_error_if_not_found:
        raise IOError('File not found')

    return ''

def read_dotenv(dotenv=None, override=False):
    """
    Read a .env file into os.environ.

    If not given a path to a dotenv path, does filthy magic stack backtracking
    to find manage.py and then find the dotenv.
    """
    if dotenv is None:
        frame_filename = sys._getframe().f_back.f_code.co_filename
        dotenv = os.path.join(os.path.dirname(frame_filename), '.env')

    if os.path.isdir(dotenv) and os.path.isfile(os.path.join(dotenv, '.env')):
        dotenv = os.path.join(dotenv, '.env')

    if os.path.exists(dotenv):
        with open(dotenv) as f:
            for k, v in parse_dotenv(f.read()).items():
                if override:
                    os.environ[k] = v
                else:
                    os.environ.setdefault(k, v)
    else:
        warnings.warn("Not reading {0} - it doesn't exist.".format(dotenv),
                      stacklevel=2)

def parse_dotenv(content):
    env = {}

    for line in content.splitlines():
        m1 = line_re.search(line)

        if m1:
            key, value = m1.groups()

            if value is None:
                value = ''

            # Remove leading/trailing whitespace
            value = value.strip()

            # Remove surrounding quotes
            m2 = re.match(r'^([\'"])(.*)\1$', value)

            if m2:
                quotemark, value = m2.groups()
            else:
                quotemark = None

            # Unescape all chars except $ so variables can be escaped properly
            if quotemark == '"':
                value = re.sub(r'\\([^$])', r'\1', value)

            if quotemark != "'":
                # Substitute variables in a value
                for parts in variable_re.findall(value):
                    if parts[0] == '\\':
                        # Variable is escaped, don't replace it
                        replace = ''.join(parts[1:-1])
                    else:
                        # Replace it with the value from the environment
                        replace = env.get(
                            parts[-1],
                            os.environ.get(parts[-1], '')
                        )

                    value = value.replace(''.join(parts[0:-1]), replace)

            env[key] = value

        elif not re.search(r'^\s*(?:#.*)?$', line):  # not comment or blank
            warnings.warn(
                "Line {0} doesn't match format".format(repr(line)),
                SyntaxWarning
            )

    return env


'''
io文件读写
'''

# 在磁盘上读写文件的功能都是由操作系统提供的
# 现代操作系统不允许普通的程序直接操作磁盘
# 所以，读写文件就是请求操作系统打开一个文件对象（通常称为文件描述符）

# 标示符'r'表示读，这样，我们就成功地打开了一个文件。
f = open('__init__.py',"r")

# 接下来，调用read()方法可以一次读取文件的全部内容
r = f.read()

# 关闭文件
f.close()

# 由于文件读写时都有可能产生IOError，一旦出错，后面的f.close()就不会调用。
# 所以，为了保证无论是否出错都能正确地关闭文件
# 我们可以使用try ... finally来实现
try:
    f = open('__init__.py', "r")
    print(f.read())
finally:
    if f:
        f.close()

# 但是每次都这么写实在太繁琐
# Python引入了with语句来自动帮我们调用close()方法：
with open('__init__.py', "r") as f:
    print(f.read())

# 调用read()会一次性读取文件的全部内容, read(size)读取指定大小的内容
# 调用readline()可以每次读取一行内容
# 用readlines()一次读取所有内容并按行返回list
f = open('__init__.py', "r")

for line in f.readlines():
    print(line)

# 　默认读取文本文件，并且是UTF-8编码的文本文件。
# 要读取二进制文件，比如图片、视频等等，用'rb'模式打开文件即可：
f = open('__init__.py', "rb")
r = f.read()

# 要读取非UTF-8编码的文本文件，需要给open()函数传入encoding参数，例如，读取GBK编码的文件
# 遇到有些编码不规范的文件，你可能会遇到UnicodeDecodeError
# 简单的方式是直接忽略
f = open('__init__.py', 'r', encoding='utf-8', errors
='ignore')

print(r)

f = open('file','w')
f.write('file io')
f.close()

# 希望追加到文件末尾怎么办？可以传入'a'以追加（append）模式写入
with open('file', 'a') as f:
    f.write('Hello, world!')

'''
我们写文件时，操作系统往往不会立刻把数据写入磁盘，
而是放到内存缓存起来，空闲的时候再慢慢写入。
只有调用close()方法时，操作系统才保证把没有写入的数据全部写入磁盘。
忘记调用close()的后果是数据可能只写了一部分到磁盘，剩下的丢失了。
所以，还是用with语句来得保险
'''


"""
283. Move Zeroes
Easy

5431

170

Add to List

Share
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:

Input: nums = [0]
Output: [0]

Constraints:

1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1

Follow up: Could you minimize the total number of operations done?

"""
from typing import List

"""
Two Pointers

i iterate entire array from n-1 to 0, j points at first non-zero from right
if nums[i] is zero, insert nums[i] to right of nums[j], and move nums[i+1:j+1] one step to left

time O(N^2)
space O(1)
"""

class Solution0:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)

        i, j = n - 1, n - 1
        for i in range(n - 1, -1, -1):
            if nums[i] == 0:
                # insert nums[i] to right of nums[j]
                # and shift all elements betwee i+1...j to left by one
                tmp = nums[i]
                for k in range(i + 1, j + 1):
                    nums[k - 1] = nums[k]
                nums[j] = tmp
                j -= 1

"""
Two Pointers

pointer j counts index of non-zero element found so far
pointer i iterate the array, from 0 to n-1, if nums[i] is non-zero, replace nums[j] with nums[i], then set nums[i] to zero

once the above loop is done, we need to set all elements from j to n-1 to zero (these are all the zeros to right)

time O(N)
space O(1)

mistakes:
1. nums[i] could be negative
"""

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)

        if n == 1:
            return

        j = 0  # index after last non-zero elements stored
        for i in range(n):
            if nums[i] != 0:
                nums[j] = nums[i]  # this would be no op if j==i (all beginning non-zero elements)
                j += 1

        # set all elements from j to n-1 to zero
        for i in range(j, n):
            nums[i] = 0


# 2231 분해합

N = int(input())
result = False
for i in range(1, N+1):
    S = i + sum(map(int, str(i)))
    if S == N:
        print(i)
        result = True
        break
if not result:
    print(0)


import os
import unittest
import rasterio
import numpy as np
import pytest

from geopyspark import geotiff
from geopyspark.geotrellis import (Extent,
                                   ProjectedExtent,
                                   TileLayout,
                                   Tile,
                                   LayoutDefinition,
                                   GlobalLayout,
                                   LocalLayout,
                                   SpatialPartitionStrategy,
                                   catalog)
from geopyspark.geotrellis.constants import LayerType
from geopyspark.geotrellis.layer import Pyramid, RasterLayer
from geopyspark.tests.base_test_class import BaseTestClass
from geopyspark.tests.python_test_utils import file_path

class PyramidingTest(BaseTestClass):

    @pytest.fixture(autouse=True)
    def tearDown(self):
        yield
        BaseTestClass.pysc._gateway.close()

    def test_pyraminding_with_partitioner(self):
        arr = np.zeros((1, 16, 16))
        epsg_code = 3857
        extent = Extent(0.0, 0.0, 10.0, 10.0)

        tile = Tile(arr, 'FLOAT', False)
        projected_extent = ProjectedExtent(extent, epsg_code)

        rdd = BaseTestClass.pysc.parallelize([(projected_extent, tile)])
        raster_rdd = RasterLayer.from_numpy_rdd(LayerType.SPATIAL, rdd)
        tile_layout = TileLayout(32, 32, 16, 16)
        new_extent = Extent(-20037508.342789244, -20037508.342789244, 20037508.342789244,
                            20037508.342789244)

        layout_def = LayoutDefinition(new_extent, tile_layout)
        laid_out = raster_rdd.tile_to_layout(GlobalLayout(tile_size=16))

        strategy = SpatialPartitionStrategy(4)

        pyramided = laid_out.pyramid(partition_strategy=strategy)

        self.assertEqual(pyramided.levels[0].get_partition_strategy(), strategy)

    def test_correct_base(self):
        arr = np.zeros((1, 16, 16))
        epsg_code = 3857
        extent = Extent(0.0, 0.0, 10.0, 10.0)

        tile = Tile(arr, 'FLOAT', False)
        projected_extent = ProjectedExtent(extent, epsg_code)

        rdd = BaseTestClass.pysc.parallelize([(projected_extent, tile)])
        raster_rdd = RasterLayer.from_numpy_rdd(LayerType.SPATIAL, rdd)
        tile_layout = TileLayout(32, 32, 16, 16)
        new_extent = Extent(-20037508.342789244, -20037508.342789244, 20037508.342789244,
                            20037508.342789244)
        layout_def = LayoutDefinition(new_extent, tile_layout)

        laid_out = raster_rdd.tile_to_layout(GlobalLayout(tile_size=16))
        result = laid_out.pyramid()
        self.pyramid_building_check(result)

    # collect_metadata needs to be updated for this to work
    '''
    def test_no_start_zoom(self):
        arr = np.zeros((1, 16, 16))
        epsg_code = 3857
        extent = Extent(0.0, 0.0, 10.0, 10.0)

        tile = Tile(arr, 'FLOAT', None)
        projected_extent = ProjectedExtent(extent, epsg_code)

        rdd = BaseTestClass.pysc.parallelize([(projected_extent, tile)])
        raster_rdd = RasterLayer.from_numpy_rdd(LayerType.SPATIAL, rdd)
        tile_layout = TileLayout(32, 32, 16, 16)
        new_extent = Extent(-20037508.342789244, -20037508.342789244, 20037508.342789244,
                            20037508.342789244)

        layout_def = LayoutDefinition(new_extent, tile_layout)
        metadata = raster_rdd.collect_metadata(layout=layout_def)
        laid_out = raster_rdd.tile_to_layout(metadata)
        reprojected = laid_out.reproject(3857, layout=GlobalLayout(zoom=laid_out.zoom_level))

        result = reprojected.pyramid(end_zoom=1)

        self.pyramid_building_check(result)
    '''

    def test_local_pyramid(self):
        arr = np.zeros((1, 256, 256))
        epsg_code = 3857
        extent = Extent(0.0, 0.0, 10.0, 10.0)

        tile = Tile(arr, 'FLOAT', None)
        projected_extent = ProjectedExtent(extent, epsg_code)

        rdd = BaseTestClass.pysc.parallelize([(projected_extent, tile)])

        raster_rdd = RasterLayer.from_numpy_rdd(LayerType.SPATIAL, rdd)
        laid_out = raster_rdd.tile_to_layout(LocalLayout(256))

        # Single tile is at level 0
        result = laid_out.pyramid()
        assert result.max_zoom == 0

        laid_out = raster_rdd.tile_to_layout(LocalLayout(16))
        result = laid_out.pyramid()

        assert result.max_zoom == 4
        assert result.levels[4].layer_metadata.tile_layout.layoutCols == 16
        assert result.levels[3].layer_metadata.tile_layout.layoutCols == 8
        assert result.levels[2].layer_metadata.tile_layout.layoutCols == 4
        assert result.levels[1].layer_metadata.tile_layout.layoutCols == 2
        assert result.levels[0].layer_metadata.tile_layout.layoutCols == 1

    def test_pyramid_class(self):
        arr = np.zeros((1, 16, 16))
        epsg_code = 3857
        extent = Extent(0.0, 0.0, 10.0, 10.0)

        tile = Tile(arr, 'FLOAT', False)
        projected_extent = ProjectedExtent(extent, epsg_code)

        rdd = BaseTestClass.pysc.parallelize([(projected_extent, tile)])
        raster_rdd = RasterLayer.from_numpy_rdd(LayerType.SPATIAL, rdd)
        tile_layout = TileLayout(1, 1, 16, 16)
        reprojected = raster_rdd.tile_to_layout(layout=GlobalLayout(tile_size=16), target_crs=3857)

        result = reprojected.pyramid()
        hist = result.get_histogram()

        self.assertEqual(result.max_zoom, reprojected.zoom_level)
        self.assertTrue(set(result.levels.keys()).issuperset(range(1, 13)))
        self.assertEqual(hist.mean(), 0.0)
        self.assertEqual(hist.min_max(), (0.0, 0.0))

    def pyramid_building_check(self, result):
        previous_layout_cols = None
        previous_layout_rows = None

        values = sorted(list(result.levels.items()), reverse=True, key=lambda tup: tup[0])

        for x in values:
            metadata = x[1].layer_metadata
            layout_cols = metadata.tile_layout.layoutCols
            layout_rows = metadata.tile_layout.layoutRows

            if previous_layout_cols and previous_layout_rows:
                self.assertEqual(layout_cols*2, previous_layout_cols)
                self.assertEqual(layout_rows*2, previous_layout_rows)
            else:
                self.assertTrue(layout_cols % 2 == 0)
                self.assertTrue(layout_rows % 2 == 0)

            previous_layout_cols = layout_cols
            previous_layout_rows = layout_rows

    def test_write_pyramid_layers(self):
        max_zoom = 5
        tif = file_path('srtm_52_11.tif')
        raster_layer = geotiff.get(layer_type=LayerType.SPATIAL, uri=tif)
        tiled_raster_layer = raster_layer.tile_to_layout(GlobalLayout(zoom=max_zoom), target_crs=3857)
        pyramided_layer = tiled_raster_layer.pyramid()

        layer_name = 'pyramid-test-layer'
        path = file_path('pyramid-test-catalog')
        uri = 'file:///' + path

        if os.path.isdir(path):
            import shutil
            shutil.rmtree(path)

        pyramided_layer.write(uri, layer_name)

        self.assertTrue(catalog.read_layer_metadata(uri, layer_name, 0))
        self.assertTrue(catalog.read_layer_metadata(uri, layer_name, max_zoom))

if __name__ == "__main__":
    unittest.main()


#!/usr/bin/python3
"""Unittest for Base class"""
import unittest
import os
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square

class TestBase(unittest.TestCase):
    """Runs tests for base.py"""

    @classmethod
    def setUpClass(cls):
        """Sets up the testing environment"""

        Base._Base__nb_objects = 0
        cls.b1 = Base()
        cls.b2 = Base()
        cls.b3 = Base(22)
        cls.b4 = Base(2.2)
        cls.b5 = Base("two")
        cls.r1 = Rectangle(10, 7, 2, 8)
        cls.r2 = Rectangle(2, 4)

    def test_0_0_create(self):
        """Tests the creation of a Base class"""

        self.assertTrue(self.b1)

    def test_0_1_create_id(self):
        """Tests the creation of class Base with a specified id"""

        self.b1.id = 5
        self.assertEqual(self.b1.id, 5)

    def test_0_2_id_inc(self):
        """Test to see if id is incrementing correctly"""

        self.b1.id = 1
        test = self.b1.id
        test2 = self.b2.id
        self.assertEqual(test, test2 - 1)

    def test_0_3_id_inc2(self):
        """More id incrementation tests"""

        test = self.b1.id
        test2 = self.b2.id
        test3 = self.b3.id
        self.assertEqual(test, test2 - 1)
        self.assertEqual(test3, 22)

    def test_0_4_id_test(self):
        """Checks ids"""

        self.assertTrue(self.b1, 1)
        self.assertTrue(self.b2, 2)
        self.assertTrue(self.b3, 22)
        self.assertTrue(self.b4, 2.2)
        self.assertTrue(self.b5, "two")

    def test_15_0_toJsonString(self):
        """Tests if the JSON string representation is working"""

        dictionary = self.r1.to_dictionary()
        json_dictionary = Base.to_json_string([dictionary])
        self.assertTrue(type(dictionary), dict)
        self.assertTrue(type(json_dictionary), str)

    def test_16_0_saveToFile(self):
        """Checks to make sure a file is created and written to"""

        Rectangle.save_to_file([self.r1, self.r2])
        self.assertTrue(os.path.isfile("Rectangle.json"))

    def test_17_0_fromJsonString(self):
        """Checks a list of JSON string format"""

        list_input = [
            {'id': 89, 'width': 10, 'height': 4},
            {'id': 7, 'width': 1, 'height': 7}
        ]
        json_list_input = Rectangle.to_json_string(list_input)
        list_output = Rectangle.from_json_string(json_list_input)
        self.assertTrue(type(list_input), list)
        self.assertTrue(type(json_list_input), str)
        self.assertTrue(type(list_output), list)

    def test_18_0_create(self):
        """Tests the create method"""

        r1_dict = self.r1.to_dictionary()
        r = Rectangle.create(**r1_dict)
        self.assertFalse(self.r1 == r)
        self.assertFalse(self.r1 is r)

    @classmethod
    def tearDownClass(cls):
        """Breaks down the testing environment"""

        pass


class Solution(object):
    def numDistinctIslands(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        ret = set()
        m = len(grid)
        if m == 0:
            return 0
        n = len(grid[0])
        for i in xrange(m):
            for j in xrange(n):
                if grid[i][j] == 1:
                    ret.add(self.helper(grid, i, j, [(0,-1), (0,1), (-1,0), (1,0)]))
        return len(ret)
    def helper(self, grid, i, j, offsets):
        m = len(grid)
        n = len(grid[0])
        q = collections.deque()
        q.append((i, j))
        grid[i][j] = 0
        ret = []
        while q:
            x, y = q.pop()
            for dx, dy in offsets:
                xx = x + dx
                yy = y + dy
                if xx >= 0 and yy >= 0 and xx < m and yy < n and grid[xx][yy] == 1:
                    ret.append((xx-i, yy-j))
                    q.append((xx,yy))
                    grid[xx][yy] = 0
        return tuple(ret)


import os
import shutil
import tempfile
from unittest import TestCase, main

import basf2
from basf2 import pickle_path as b2pp

# @cond internal_test

class PathSerialisationTestCase(TestCase):

    def setUp(self):
        # Create a temporary directory
        self.test_dir = tempfile.mkdtemp()
        self.pickle_file = os.path.join(self.test_dir, "output.pkl")

    def tearDown(self):
        # Remove the directory after the test
        shutil.rmtree(self.test_dir)

    def check_if_paths_equal(self, path1, path2):
        self.assertEqual(len(path1.modules()), len(path2.modules()))

        for module1, module2 in zip(path1.modules(), path2.modules()):
            self.assertEqual(module1.name(), module2.name())
            self.assertEqual(module1.type(), module2.type())
            self.assertEqual(module1.description(), module2.description())
            self.assertEqual(module1.package(), module2.package())

            self.assertEqual(len(module1.available_params()), len(module2.available_params()))
            for param1, param2 in zip(module1.available_params(), module2.available_params()):
                self.assertEqual(param1.name, param2.name)
                self.assertEqual(param1.description, param2.description)
                self.assertEqual(param1.values, param2.values)

            self.assertEqual(len(module1.get_all_conditions()), len(module2.get_all_conditions()))
            for cond1, cond2 in zip(module1.get_all_conditions(), module2.get_all_conditions()):
                self.assertEqual(cond1.get_value(), cond2.get_value())
                self.assertEqual(cond1.get_operator(), cond2.get_operator())
                self.assertEqual(cond1.get_after_path(), cond2.get_after_path())

                self.check_if_paths_equal(cond1.get_path(), cond2.get_path())

    def pickle_and_check(self, path):
        b2pp.write_path_to_file(path, self.pickle_file)
        pickled_path = b2pp.get_path_from_file(self.pickle_file)

        self.check_if_paths_equal(pickled_path, path)

    def test_simple_path(self):
        path = basf2.create_path()
        path.add_module("EventInfoSetter", evtNumList=[42])

        self.pickle_and_check(path)

    def test_condition_path(self):
        path = basf2.create_path()
        module = path.add_module("EventInfoSetter", evtNumList=[42])

        condition_path_1 = basf2.create_path()
        condition_path_1.add_module("Geometry", components=["SVD"])
        condition_path_2 = basf2.create_path()
        condition_path_2.add_module("Geometry", components=["CDC"])

        module.if_value("<3", condition_path_1)
        module.if_value(">5", condition_path_2)

        self.pickle_and_check(condition_path_1)
        self.pickle_and_check(condition_path_2)
        self.pickle_and_check(path)

    def test_high_level_things(self):
        self.assertNotEqual(0, os.system('basf2 --execute-path /this/path/doesnot/exist'))

        pathFile = tempfile.NamedTemporaryFile(prefix='b2pathtest_')

        # uses Python modules, this should fail
        steeringFile = basf2.find_file('framework/tests/module_paths.py')
        self.assertNotEqual(0, os.system('basf2 --dump-path ' + pathFile.name + ' ' + steeringFile))

        # test actual execution
        outputFile = tempfile.NamedTemporaryFile(prefix='b2pathtest_')

        path = basf2.create_path()
        path.add_module('EventInfoSetter', evtNumList=[2, 1], expList=[1, 1], runList=[1, 2])
        path.add_module('RootOutput', outputFileName=outputFile.name)

        # equivalent to --dump-path
        basf2.set_pickle_path(pathFile.name)
        basf2.process(path)

        # path dumped, but not executed
        pathSize = os.stat(pathFile.name).st_size
        self.assertNotEqual(0, pathSize)
        self.assertEqual(0, os.stat(outputFile.name).st_size)

        # equivalent to --execute-path
        self.assertEqual(basf2.get_pickle_path(), pathFile.name)
        basf2.process(None)

        # path unmodified, output file created
        self.assertEqual(pathSize, os.stat(pathFile.name).st_size)
        self.assertNotEqual(0, os.stat(outputFile.name).st_size)

if __name__ == '__main__':
    main()

# @endcond


import click
import itertools
import queue

from typing import (
    List,
    Optional,
    Tuple,
)

DEBUG = False

class Amplifier(object):

    def __init__(self,
                 name: str,
                 memory: List[str],
                 next_amp,
                 ):
        self.name = name
        self.memory = memory
        self.modified = False
        self.ip = 0
        self.input_buffer = queue.Queue()
        self.output_buffer = queue.Queue()
        self.next_amp: Amplifier = next_amp
        self.running = False
        self.waiting_on_input = False

    def display_memory(self) -> str:
        return(' '.join([self.memory[i] if self.ip != i else '['+self.memory[i]+']' for i in range(len(self.memory))]))

    def add_input(self, val: str) -> None:
        self.input_buffer.put(val)

    def empty_input(self) -> bool:
        if self.input_buffer.empty():
            return True
        return False

    def get_input(self) -> str:
        return self.input_buffer.get(block=True, timeout=None)

    def set_ip(self, address: int) -> None:
        self.ip = address

    def set_memory(self, address: int, val: str) -> None:
        self.memory[address] = val

    def set_modified(self, val: bool) -> None:
        self.modified = val

    def set_next_amp(self, amp) -> None:
        self.next_amp = amp

    def set_running(self, val: bool) -> None:
        self.running = val

class Instruction(object):

    def __init__(self,
                 op: int,
                 params: List[int],
                 modes: List[int],
                 jump: int,
                ):
        self.op = op
        self.params = params
        self.modes = modes
        self.jump = jump

OP_INFO = {
    1: {
        "FUNC": lambda x, y: add(x, y),
        "PARAMS": 3,
        "NAME": "ADD",
    },
    2: {
        "FUNC": lambda x, y: mult(x, y),
        "PARAMS": 3,
        "NAME": "MULTIPLY",
    },
    3: {
        "FUNC": lambda x, y: _in(x, y),
        "PARAMS": 1,
        "NAME": "INPUT",
    },
    4: {
        "FUNC": lambda x, y: out(x, y),
        "PARAMS": 1,
        "NAME": "OUTPUT",
    },
    5: {
        "FUNC": lambda x, y: jnz(x, y),
        "PARAMS": 2,
        "NAME": "JNZ",
    },
    6: {
        "FUNC": lambda x, y: jz(x, y),
        "PARAMS": 2,
        "NAME": "JZ",
    },
    7: {
        "FUNC": lambda x, y: lt(x, y),
        "PARAMS": 3,
        "NAME": "LT",
    },
    8: {
        "FUNC": lambda x, y: eq(x, y),
        "PARAMS": 3,
        "NAME": "EQ",
    },
}

def add(inst: Instruction, amp: Amplifier) -> None:
    val_a, val_b = get_correct_values(inst, amp)
    amp.set_memory(inst.params[2], str(val_a + val_b))

def decode(amp: Amplifier) -> Instruction:
    IP = amp.ip
    opcode = amp.memory[IP]
    op = int(opcode[-2:])

    if op == 99:
        return Instruction(op, [], [], 0)

    modes = opcode[:-2]
    modes_list = list(reversed([int(x) for x in modes]))

    jump = OP_INFO[op]["PARAMS"] + 1

    diff = OP_INFO[op]["PARAMS"] - len(modes)
    for i in range(diff):
        modes_list.append(0)

    params: List[int] = []
    for i in range(1, jump):
        params.append(int(amp.memory[IP+i]))

    return Instruction(op, params, modes_list, jump)

def eq(inst: Instruction, amp: Amplifier) -> None:
    val_a, val_b = get_correct_values(inst, amp)
    address = inst.params[2]

    if val_a == val_b:
        amp.set_memory(address, '1')
    else:
        amp.set_memory(address, '0')

def get_correct_values(inst: Instruction, amp: Amplifier) -> Tuple[int, Optional[int]]:
    val_a = inst.params[0] if inst.modes[0] == 1 else int(amp.memory[inst.params[0]])
    if len(inst.params) > 1:
        val_b = inst.params[1] if inst.modes[1] == 1 else int(amp.memory[inst.params[1]])
    else:
        val_b = None
    return val_a, val_b

def _in(inst: Instruction, amp: Amplifier) -> None:
    if amp.empty_input():
        amp.waiting_on_input = True
        return
    inp = amp.get_input()

    address = inst.params[0]

    amp.set_memory(address, inp)

def is_int(s: str) -> bool:
    try:
        int(s)
        return True
    except ValueError:
        return False

def jnz(inst: Instruction, amp: Amplifier) -> None:
    val_a, address = get_correct_values(inst, amp)

    if val_a != 0:
        amp.set_ip(address)
        amp.set_modified(True)

def jz(inst: Instruction, amp: Amplifier) -> None:
    val_a, address = get_correct_values(inst, amp)

    if val_a == 0:
        amp.set_ip(address)
        amp.set_modified(True)

def lt(inst: Instruction, amp: Amplifier) -> None:
    val_a, val_b = get_correct_values(inst, amp)
    address = inst.params[2]

    if val_a < val_b:
        amp.set_memory(address, '1')
    else:
        amp.set_memory(address, '0')

def mult(inst: Instruction, amp: Amplifier) -> None:
    val_a, val_b = get_correct_values(inst, amp)
    amp.set_memory(inst.params[2], str(val_a * val_b))

def out(inst: Instruction, amp: Amplifier) -> None:
    output, _ = get_correct_values(inst, amp)
    amp.next_amp.add_input(str(output))

def run_program(amp: Amplifier) -> None:
    amp.set_running(True)
    inst = decode(amp)
    while inst.op != 99:

        if DEBUG:
            opname = OP_INFO[inst.op]["NAME"]
            print(f"=== {amp.name} ===")
            print(f"inst op: {inst.op} -- {opname}")
            print(f"params: {inst.params}")
            print(f"modes: {inst.modes}")
            print(f"IP: {amp.ip}")
            print("Input buf: ", list(amp.input_buffer.queue))
            print("Output buf: ", list(amp.output_buffer.queue))
            print(amp.display_memory())
            input()

        func = OP_INFO[inst.op]["FUNC"]
        func(inst, amp)

        if amp.waiting_on_input:
            amp.waiting_on_input = False
            return

        jump = inst.jump

        if amp.modified:
            amp.set_modified(False)
        else:
            amp.set_ip(amp.ip + jump)

        inst = decode(amp)

    amp.set_running(False)

    if DEBUG:
        print('run program finished')

@click.command()
@click.option('-p', '--program', type=click.Path(exists=True, dir_okay=False),
              default='input_7.txt', help='Point at a program file to run')
@click.option('--debug/--no-debug', default=False,
              help='Show debugging messages')
def main(program, debug):
    if debug:
        global DEBUG
        DEBUG = True

    with open(program, 'r') as fh:
        raw = fh.read()

    master_memory= raw[:-1].split(',')

    amp_names = ["A", "B", "C", "D", "E"]

    combos = list(itertools.permutations(range(5, 10)))

    largest_output = 0
    best_sequence = ''

    for combo in combos:
        amps = []

        old_amp = None
        for i, a_n in enumerate(amp_names):
            new_amp = Amplifier(a_n, master_memory.copy(), None)
            new_amp.add_input(str(combo[i]))
            amps.append(new_amp)

            if old_amp is not None:
                old_amp.set_next_amp(new_amp)

            old_amp = new_amp

        amp_A = amps[0]
        amp_E = amps[-1]
        amp_E.set_next_amp(amp_A)
        amp_A.add_input('0')

        running = True
        i = -1
        while running:
            if i == len(amps) -1:
                i = 0
            else:
                i += 1
            amp = amps[i]
            run_program(amp)
            running = any([x.running for x in amps])
        outp = amp_A.get_input()
        if int(outp) > int(largest_output):
            largest_output = outp
            best_sequence = ','.join(map(lambda x: str(x),  combo))

    print(f"Largest output: {largest_output}")
    print(f"Best sequence: {best_sequence}")
    print("Finished!")

if __name__ == '__main__':
    main()


import PySimpleGUI as sg
import random
import configuracion
from pattern.es import verbs, tag, spelling, lexicon
import string

## eje 9, 10, 11

boardConfig1=configuracion.Config1()

def comprobarPalabra(palabra):

	if not palabra.lower() in verbs:

		if not palabra.lower() in spelling:

			if (not(palabra.lower() in lexicon) and not(palabra.upper() in lexicon) and not(palabra.capitalize() in lexicon)):

			#print('no existe la palabra')
				sg.Popup('la palabra no existe')
			else:
				print('existe')
				sg.Popup('la palabra existe')

		else:
			print('existe')
			sg.Popup('la palabra existe')

	else:
		print('existe')
		sg.Popup('la palabra existe')

def msj():
	print(button)
	##print(initial_atril[3])
	if boardConfig1[button[0]][button[1]].get_estado() == True:
		print('esta ocupado')
	else:
					#print('libre')
		window[i].update('')
		window[button].update(initial_atril[i])
		#palabra += letra
		p2=palabra[0]
		p2=p2+letra
		palabra[0]=p2
		initial_atril[i]=''
		boardConfig1[button[0]][button[1]].set_estado(True)

lista=['a','b','c','d','e','f','g','l','m','n','o','p','q','r','s','t','u','v','w','y','z','x']
initial_atril=[]
for i in range(0,7):
	initial_atril.append(random.choice(lista))

def tablero():
	def render(key):
		return sg.Button('',key=key,size=(4,2))
	print('')
	tablero=[]
	for i in range(10):

		row=[]
		for j in range(10):
			row.append(render(key=(i,j)))
		tablero.append(row)
	return tablero

def atril(lista):
	def render(key,texto=''):
		return sg.Button(texto,key=key,size=(4,2))
	atril=[]
	for i in range(7):
		#print(lista[i])
		teo=lista[i]
		row=[]
		row.append(render(texto=teo,key=i))
		atril.append(row)
	return atril

tab=tablero()
atr=atril(initial_atril)
boar_tab=[[sg.Button('CHECK')],[sg.Column(atr),sg.Column(tab)]]

window=sg.Window('hola',default_button_element_size=(10,2)).layout(boar_tab)
#palabra='' ## chequear para el siguiente turno
palabra=['']
i=0
cant=0
T1=True
T2= True

F=0
C=0
#lista=[]
while True:
	letra=''
	l=-1
	button , value = window.Read()
	if button == 'CHECK':
		##obj_tablero.get_word()
		if palabra[0] == '':
			sg.Popup('todavia no formo una palabra')
		else:
		    #print(palabra[0])
		    comprobarPalabra(palabra[0])

	if button in (None , 'EXIT'):
		exit()

	if type(button) is int:

		if initial_atril[button] !='':
			letra= initial_atril[button]
			#palabra += letra
			i=button

			button , value = window.Read()
			if type(button) is tuple:

				if cant<1:
					cant=cant+1
					msj()
					F=button[0]
					C=button[1]

				else:
				###hoy
					if(button[0]==F)and T1:
						if C<button[1]:
							T2=False
							msj()
							C=button[1]
					if(button[1]==C)and T2:
						if F<button[0]:
							print(button)
							T1=False
							msj()
							F=button[0]

				l=0

	if type(button) is tuple:
		if l ==-1:

			sg.Popup('movimiento incorrecto')


class Node:
    def __init__(self, value, left = None, right=None):
        self.value = value
        self.left = left
        self.right =  right

def preOrder_iter(head):
    if head is None:
        return
    stack = []
    stack.append(head)
    while stack:
        head = stack.pop()
        print(head.value, end=' ')
        if head.right:
            stack.append(head.right)
        if head.left:
            stack.append(head.left)

root=Node(1,Node(2), Node(3))
preOrder_iter(root)

if __name__ == '__main__':

    pass


train_sched = [
{'train': "72C", 'frequency_in_minutes': 15, 'direction': "north"},
{'train': "72D", 'frequency_in_minutes': 15, 'direction': "south"},
{'train': "610", 'frequency_in_minutes': 5, 'direction': "north"},
{'train': "611", 'frequency_in_minutes': 5, 'direction': "south"},
{'train': "80A", 'frequency_in_minutes': 30, 'direction': "east"},
{'train': "80B", 'frequency_in_minutes': 30, 'direction': "west"},
{'train': "110", 'frequency_in_minutes': 15, 'direction': "north"},
{'train': "111", 'frequency_in_minutes': 15, 'direction': "south"}
]

def find_dict(list, key, value):
    for dict in list:
        if dict[key] == value:
            return dict

train111 = find_dict(train_sched, 'train', "111" )

train111_dir = train111['direction']

train80B = find_dict(train_sched, 'train', '80B')

train80B_freq = train80B['frequency_in_minutes']

train610 = find_dict(train_sched, 'train', '610')

train610_dir = train610['direction']

# def find_north_trains(list, value):
#     north_trains = []
#     for dict in list:
#         if dict['direction'] == 'north':
#             north_trains.append(dict['train'])
#     print(north_trains)

# find_trains(train_sched, 'north')

def find_trains(list, value):
    trains_list = []
    for dict in list:
        if dict['direction'] == value:
            trains_list.append(dict['train'])
    print(f"{value} bound trains: {trains_list}")

find_trains(train_sched, 'north')

find_trains(train_sched, 'east')

train111.update({'first_departure_time' : 6})

def re_sort_trains():
    trains_by_frequency = {}

    for train in train_sched:
        freq = train['frequency_in_minutes']
        name = train['train']
        if freq in trains_by_frequency:
            trains_by_frequency[freq].append(name)
        else:
            trains_by_frequency[freq] = [name]

    print(trains_by_frequency)

re_sort_trains()


from argparse import ArgumentParser
from math import ceil
from pathlib import Path

import torch
import pytorch_lightning as pl
import pandas as pd

from classification.train_base import MultiPartitioningClassifier
import torchvision
from classification.dataset import StreetViewDataset

def parse_args():
    args = ArgumentParser()
    # model
    args.add_argument(
        "--checkpoint",
        type=Path,
        default=Path("models/base_M/epoch=014-val_loss=18.4833.ckpt"),
        help="Checkpoint to already trained model (*.ckpt)",
    )
    args.add_argument(
        "--hparams",
        type=Path,
        default=Path("models/base_M/hparams.yaml"),
        help="Path to hparams file (*.yaml) generated during training",
    )
    args.add_argument(
        "--image_dir",
        required=True,
        help="Whitespace separated list of image folders to evaluate",
    )
    args.add_argument(
        "--ocr_json_dir",
    )
    args.add_argument(
        "--ocr_feat_dir",
    )
    args.add_argument(
        "--label_dir",
        required=True,
    )
    args.add_argument(
        "--gpu",
        action="store_true",
        help="Use GPU for inference if CUDA is available",
    )
    args.add_argument(
        "--precision",
        type=int,
        default=32,
        help="Full precision (32), half precision (16)",
    )
    args.add_argument("--batch_size", type=int, default=64)
    args.add_argument(
        "--num_workers",
        type=int,
        default=4,
        help="Number of workers for image loading and pre-processing",
    )
    return args.parse_args()

args = parse_args()
print("Load model from checkpoint", args.checkpoint)
model = MultiPartitioningClassifier.load_from_checkpoint(
    checkpoint_path=str(args.checkpoint),
    hparams_file=str(args.hparams),
    map_location=None,
)

hparams = model.hparams

if args.gpu and torch.cuda.is_available():
    args.gpu = 1
else:
    args.gpu = None
trainer = pl.Trainer(gpus=args.gpu, precision=args.precision)

print("Init Testset")

tfm = torchvision.transforms.Compose(
    [
        torchvision.transforms.Resize(256),
        torchvision.transforms.CenterCrop(224),
        torchvision.transforms.ToTensor(),
        torchvision.transforms.Normalize(
            (0.485, 0.456, 0.406), (0.229, 0.224, 0.225)
        ),
    ]
)

dataset = StreetViewDataset(
    data_path=args.image_dir,
    ocr_json_path=args.ocr_json_dir,
    ocr_feat_path=args.ocr_feat_dir,
    label_path=args.label_dir,
    use_ocr=hparams.ocr_params['use_ocr'],
    shuffle=False,
    transformation=tfm,
    give_latlng=True,
)
dataloader = [torch.utils.data.DataLoader(
    dataset,
    batch_size=hparams.batch_size,
    shuffle=False,
    num_workers=args.num_workers,
)]

print("Testing")
r = trainer.test(model, test_dataloaders=dataloader, verbose=False)
# formatting results
dfs = []
for results, name in zip(r, [Path(args.image_dir).stem]):
    df = pd.DataFrame(results).T
    df["dataset"] = name
    df["partitioning"] = df.index
    df["partitioning"] = df["partitioning"].apply(lambda x: x.split("/")[-1])
    df.set_index(keys=["dataset", "partitioning"], inplace=True)
    dfs.append(df)

df = pd.concat(dfs)

print(df)
fout = Path(args.checkpoint).parent / ("test-" + "_".join(
    [str(Path(args.image_dir).stem)]) + ".csv")
print("Write to", fout)
df.to_csv(fout)


import json

def parseLine(line, fpOut):
    lineSplited = line.split("word='")

    lineSplitedSplited = lineSplited[1].split("' ")

    lineSplitedSplitedSplited = lineSplitedSplited[2].split("'")

    words.append(str(lineSplitedSplited[0].strip()))
    points.append(int(lineSplitedSplitedSplited[1].strip()))

words = []
points = []
matrix = []

filepath = 'cities_txt.txt'
fileOut = 'topic_cities.json'

fp = open(filepath)
fpOut = open(fileOut)

for line in fp:
    parseLine(line, fpOut)

for i in range(len(words)):
    words[i] = words[i].replace("\"", "")
    matrix.append([words[i], points[i]])

#print(matrix)

with open(fileOut, 'w') as f:
    json.dump(matrix, f, sort_keys=False, indent=4, ensure_ascii=False)


""""

HDF5 attributions:
hdf5 file: 'total frames', 'total frame dataset', 'dataset titles'
frame dataset: 'title', 'dataset number', properties...
properties dataset: 'title', 'dataset number'
"""

import numpy as np
import h5py

class Frames(object):
    """
    for frame in frames
    frames[index]
    frames[start:end]
    """

    def __init__(self):
        self.dset = None

    def __iter__(self):
        pass

    def __next__(self):
        pass

    def __getitem__(self, index):
        pass

    def __len__(self):
        pass

class H5Reader(object):
    """

    """

    def __init__(self, file_name, mode: str = None):
        self.file_name = file_name
        self.mode = mode if mode in ('r', 'r+', 'w', 'w-', 'x', 'a') else 'r'
        self.h5file = h5py.File(self.file_name, self.mode)
        self.index_array = self._form_index_array()

    def __enter__(self):
        return self

    def __exit__(self, *excinfo):
        self.h5file.close()

    # Frame generator
    @property
    def frames(self):
        for key in self.h5file['Capture data']:
            if key != 'Properties':
                for frame in self.h5file['Capture data'][key]:
                    yield frame

    def frames_dset(self, dset_number):
        for frame in self.get_dataset(dset_number):
            yield frame

    # File information
    def show_info(self):
        self.h5file.visititems(print)

    # Get data from file
    def get_dataset(self, number, title='frames'):
        def find(name, obj):
            if obj.attrs.get('title') == title and obj.attrs.get('dataset number') == number:
                return obj

        if title in self.h5file.attrs['dataset titles'] and -1 < number <= self.h5file.attrs['total frame dataset']:
            ret = self.h5file.visititems(find)
            print(ret)
            return ret
        else:
            return False

    def get_frame(self, index=0, dset_number=0, dset_index=0):
        if index:
            dset_number, dset_index = self.convert_index(index)
        dset = self.get_dataset(dset_number)
        return dset[dset_index]

    def get_frame_properties(self, index=0, dset_number=0, dset_index=0):
        if index:
            dset_number, dset_index = self.convert_index(index)
        dset = self.get_dataset(dset_number)
        prop_dict = {}
        for name, val in dset.attrs.items():
            if isinstance(val, h5py.Reference):
                prop_dict[name] = self.h5file[dset.attrs[name]][dset_index]
            else:
                prop_dict[name] = val
        return prop_dict

    def convert_index(self, index):
        """
        convert the global index to dset_number and dset_index (index in a dataset        )
        :param index: index for all datasets
        :return: (dset_number, dset_index)
        """
        left, right = 0, len(self.index_array) - 1
        while left < right:
            mid = (left + right) // 2
            if self.index_array[mid] < index:
                left = mid + 1
            elif self.index_array[mid] > index:
                right = mid
            else:
                left = mid + 1
                break
        dset_number = left
        dset_index = index - self.index_array[dset_number - 1] if dset_number > 0 else index
        return dset_number, dset_index

    def convert_dset_loc(self, dset_number, dset_index):
        """
        convert dset_number, dset_index to a global index
        """
        return dset_index if dset_number == 0 else self.index_array[dset_number - 1] + dset_index

    def _form_index_array(self):
        index_temp = 0
        index_array = np.empty(self.h5file.attrs['total frame dataset'], dtype=int)
        for key in self.h5file['Capture data']:
            if key != 'Properties':
                dset = self.h5file['Capture data'][key]
                index_temp += dset.shape[0]
                index_array[dset.attrs['dataset number']] = index_temp
        return index_array

    # TODO
    # Generate video
    def video(self, *args):
        if len(args) == 0:
            start, end = 0, self.h5file.attrs['total frames']
        elif len(args) == 1:
            dset_number = args
            if dset_number > self.h5file.attrs['total frame dataset'] - 1:
                raise IndexError('Dataset index out of range')
        elif len(args) == 2:
            start, end = args
            if end > self.h5file.attrs['total frames']:
                raise IndexError('Frame index out of range')
        else:
            raise ValueError


from django.db import models

from accounts.models import User, UserProfile
from accounts.utils import send_notification

class Vendor(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, related_name='user')
    user_profile = models.OneToOneField(
        UserProfile, on_delete=models.CASCADE, related_name='userprofile')
    vendor_name = models.CharField(max_length=50)
    vendor_license = models.ImageField(upload_to='vendor/license')
    is_aproved = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    modifiet_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.vendor_name

    def save(self, *args, **kwargs):
        if self.pk is not None:
            # update
            orig = Vendor.objects.get(pk=self.pk)
            if orig.is_aproved != self.is_aproved:

                mail_template = 'accounts/emails/admin_approval_email.html'
                context = {
                    'user': self.user,
                    'is_aproved': self.is_aproved,
                }

                if self.is_aproved == True:
                    # send notification email
                    mail_subject = 'congratulations, your restaurante has been approved'
                    send_notification(mail_subject, mail_template, context)
                else:
                    # send notification email
                    mail_subject = 'we are not eligible for publish in marketplace'
                    send_notification(mail_subject, mail_template, context)
        return super(Vendor, self).save(*args, **kwargs)


import Image
import pylab

def get_polygon(list_of_points):
    return [(list_of_points[idx], list_of_points[idx+1]) for idx in xrange(len(list_of_points)-1)]

def get_track(x1, y1, x2, y2):
    # Bresengham algorithm
    list_of_points = list()

    dx = abs(x1 - x2)
    dy = abs(y1 - y2)

    x_step = 1 if x1 < x2 else -1
    y_step = 1 if y1 < y2 else -1

    error = dx - dy

    while x1 != x2 and y1 != y2:
        list_of_points.append((x1, y1))

        doubled_error = 2 * error
        if doubled_error > -dy:
            error -= dy
            x1 += x_step

        if doubled_error < dx:
            error += dx
            y1 += y_step

    list_of_points.append((x2, y2))
    return list_of_points

def get_track_of_polygon(polygon):
    return [get_track(p1[0], p1[1], p2[0], p2[1]) for p1, p2 in polygon]

def get_image_cross_section(image, polygon):
    crossection_points = reduce(list.__add__, get_track_of_polygon(polygon))
    crossection_pixels = map(lambda point: image.getpixel(point), crossection_points)

    return crossection_pixels

def draw_the_track_cross_section(image, crossection_points):
    track_polygon = get_polygon(crossection_points)
    cross_section = get_image_cross_section(image, track_polygon)

    pylab.plot(map(lambda pixel: 255 - pixel[2], cross_section))
    pylab.ylim(0, 255)
    pylab.xlim(0, len(cross_section))
    pylab.xticks([])
    pylab.autoscale(False)
    pylab.show()

def main():
    demo_image = Image.open("temporary-image.jpg", "r")

    # Some points
    p1 = (62, 1022)
    p2 = (30, 890)
    p3 = (415, 555)
    p4 = (252, 918)

    track1 = [p1, p4]
    track2 = [p1, p2, p3, p4]

    draw_the_track_cross_section(demo_image, track1)
    draw_the_track_cross_section(demo_image, track2)

if __name__ == '__main__':
    main()


import argparse
from Bio import SeqIO
from Bio.Alphabet import IUPAC

import shutil
import os.path
import requests
import re

from .translator import translate as _

def load_fasta_parser():
  load_fasta_parser = argparse.ArgumentParser(description=_("app.cmd.fasta.description"))
  load_fasta_parser.add_argument("-n", type=int, default=0, help=_("app.cmd.fasta.number"))
  load_fasta_parser.add_argument("-f", "--separator", type=str, help=_("app.cmd.fasta.separator"))
  load_fasta_parser.add_argument("-s", "--starting-index", default=None, type=int, help=_("app.cmd.fasta.starting_index"))
  load_fasta_parser.add_argument("-e", "--ending-index", default=None, type=int, help=_("app.cmd.fasta.ending_index"))
  load_fasta_parser.add_argument("fasta", help=_("app.cmd.fasta.fasta"))
  return load_fasta_parser

def load_fasta(handler, input_handler, printer, state, args):
  maybe_id = None
  maybe_pdb_id = None
  maybe_pdb_file_name = None
  try:

    read_sequence = list(SeqIO.parse(args.fasta, "fasta", alphabet=IUPAC.unambiguous_dna))[args.n]
    starting_index = 0
    ending_index = len(read_sequence)

    if args.starting_index :
      starting_index = args.starting_index
    if args.ending_index :
      ending_index = args.ending_index

    sequence = read_sequence[starting_index-1:ending_index]

    if args.separator:
      maybe_id = ask_id_info(input_handler, printer, read_sequence, args.separator)
      maybe_pdb_id = lookup_id_pdb_info(maybe_id, input_handler, printer)

    if maybe_pdb_id:
      maybe_pdb_file_name = fetch_pdb_file(handler, maybe_pdb_id, printer)

    protein = sequence.translate(to_stop = True)

    state.set_up_read_sequence(read_sequence, sequence, protein, starting_index, ending_index, maybe_id, maybe_pdb_id, maybe_pdb_file_name)

  except:
    printer.error(lambda err : f'{_("app.error.fasta.cant_read")} {args.fasta}, {_("app.error.fasta.cant_read_refer")}: {err[0]} {err[1]}')

def fetch_pdb_file(handler, pdb_id, printer):
  filename = None
  printer.log(_("app.guide.fasta.pdb_lookup.start"))
  handler.do_shell(f"pymol -Qcd 'set fetch_path, /usr/src/pdb; fetch {pdb_id}, type=pdb, async=0'")
  path = f"/usr/src/pdb/{pdb_id}.pdb"
  if os.path.exists(path):
    printer.log(_("app.guide.fasta.pdb_lookup.found"))
    shutil.copyfile(path, f"/usr/src/pdb/mutated_{pdb_id}.pdb")
    filename = path
  else:
    printer.log(_("app.guide.fasta.pdb_lookup.not_found"))
  return filename

def ask_id_info(input_handler, printer, sequence, separator):
  options = [i for i in sequence.description.split(separator) if i != '' ]
  return input_for_list(input_handler, printer, options, _("app.guide.fasta.select"))

def lookup_id_pdb_info(maybe_id, input_handler, printer):
  selected = None
  if maybe_id:
    printer.log(_("app.guide.fasta.id_lookup.start"))
    response = requests.get(f'https://www.uniprot.org/uniprot/?query={maybe_id}&format=tab&columns=database%28PDB%29')
    if response.status_code == 200:
      match = re.search('((\w|\d)+\;)+', response.text)[0]
      options = [i.lower() for i in match.split(';') if i != '']
      printer.debug(options)
      selected = input_for_list(input_handler, printer, options, _("app.guide.fasta.id_lookup.found_select"))
      printer.debug(selected)
  return selected

def input_for_list(input_handler, printer, list_options, text, include_none = True):
  options_number = [i+1 for i in range(len(list_options) + (1 if include_none else 0))]
  options_show = list_options + ([_("app.guide.fasta.none_of_above")] if include_none else [] )
  iterator = zip(options_number, options_show)
  answer = None
  selected = None
  while answer not in options_number:
    printer.log(text)
    for num, name in iterator:
      printer.log(f' {num}) {name}')
    answer = int(input_handler.read_input(''))
  try :
    selected = list_options[answer-1]
  except:
    pass
  return selected


from django.urls import path
from .views import (
    PaymentListView,
    PaymentDetailView,
    PaymentCreateView,
    PaymentUpdateView,
    PaymentDeleteView,
    UserPaymentListView
)
from . import views

urlpatterns = [
    path('', PaymentListView.as_view(), name='payments'),
    path('user/<str:username>', UserPaymentListView.as_view(), name='user-payments'),
    path('payment/<int:pk>/', PaymentDetailView.as_view(), name='payment-detail'),
    path('Payment/new/', PaymentCreateView.as_view(), name='payment-create'),
    path('payment/<int:pk>/update/', PaymentUpdateView.as_view(), name='payment-update'),
    path('payment/<int:pk>/delete/', PaymentDeleteView.as_view(), name='payment-delete'),

]


import math
print("ВВедите стороны треугольника:")
a=int(input("a= "))
b=int(input("b= "))
c=int(input("c= "))

if ((a+b)<=c) or ((a+c)<=b) or ((b+c)<=a):
	print("Треугольника с такими сторонами не существует")
else:
	p=float((a+b+c)/2)
	s=math.sqrt(p*(p-a)*(p-b)*(p-c))

	print("Площадь равна: "+ str("%.2f" % s))


import argparse
import os
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt

from scannet_utils import get_scenes, get_ground_truth
from ai_utils import graph, predict
from partition.felzenszwalb import partition_from_probs
from partition.partition import Partition
from sp_utils import partition
from exp_utils import \
    match_score,\
    get_csv_header,\
    save_csv,\
    mkdir,\
    load_exp_data

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--min_k", type=float, default=100, help="Minimum k parameter of FH04 segmentation algorithm.")
    parser.add_argument("--max_k", type=float, default=1000, help="Maximum k parameter of FH04 segmentation algorithm.")
    parser.add_argument("--step_k", type=float, default=100, help="Step size to which the k parameter of FH04 segmentation algorithm will be varied.")
    # cp params
    parser.add_argument("--reg_strength", default=0.1, type=float, help="Regularization strength for the minimal partition. Increase lambda for a coarser partition. ")
    parser.add_argument("--k_nn_geof", default=45, type=int, help="Number of neighbors for the geometric features.")
    parser.add_argument("--k_nn_adj", default=10, type=int, help="Adjacency structure for the minimal partition.")
    parser.add_argument("--lambda_edge_weight", default=1., type=float, help="Parameter determine the edge weight for minimal part.")
    parser.add_argument("--d_se_max", default=0, type=float, help="Max length of super edges.")
    parser.add_argument("--max_sp_size", default=-1, type=int, help="Maximum size of a superpoint.")
    #
    #parser.add_argument("--pkg_size", default=5, type=int, help="Number of packages to save a csv")
    parser.add_argument("--csv_dir", default="./", type=str, help="Directory where we save the csv.")
    #
    parser.add_argument("--sn_id", default=0, type=int, help="Scannet scene id in the range of [0,707]")
    args = parser.parse_args()

    if args.min_k >= args.max_k:
        raise Exception("min_k {0} should be smaller than max_k {1}".format(args.min_k, args.max_k))
    if args.step_k >= args.max_k:
        raise Exception("step_k {0} should be smaller than max_k {1}".format(args.step_k, args.max_k))
    k_params = np.arange(start=args.min_k, stop=args.max_k, step=args.step_k)

    max_sn_id = 707
    min_sn_id = 0
    if args.sn_id > max_sn_id or args.sn_id < min_sn_id:
        raise Exception("Scannet ID {0} should be between {1} and {2}.".format(args.sn_id, min_sn_id, max_sn_id))
    scenes, _, scannet_dir = get_scenes(blacklist=[])
    scene_name = scenes[args.sn_id]

    csv_header = get_csv_header()
    csv_name = "fh04_k_id{0}".format(args.sn_id)

    verbose = False
    model = None

    mesh, p_vec_gt, file_gt = get_ground_truth(scannet_dir=scannet_dir, scene=scene_name)
    xyz = np.asarray(mesh.vertices)
    rgb = np.asarray(mesh.vertex_colors)
    P = np.hstack((xyz, rgb))

    graph_dict, sp_idxs, part_cp = graph(
        cloud=P,
        k_nn_adj=args.k_nn_adj,
        k_nn_geof=args.k_nn_geof,
        lambda_edge_weight=args.lambda_edge_weight,
        reg_strength=args.reg_strength,
        d_se_max=args.d_se_max,
        max_sp_size=args.max_sp_size,
        verbose=verbose,
        return_p_vec=True)

    unions, probs, model = predict(graph_dict=graph_dict, dec_b=0.8, return_model=True, verbose=False)

    ooas = []
    sizes = []
    all_data = []
    partition_gt = None
    sortation = None

    partition_gt = Partition(partition=p_vec_gt)
    #ooa_cp, partition_gt, sortation = ooa(par_v_gt=p_vec_gt, par_v=part_cp, partition_gt=partition_gt, sortation=sortation)
    _, _, ooa_cp, _, _ = match_score(
        gt_partition=partition_gt, partition=Partition(partition=part_cp), return_ooa=True)
    size_cp = len(sp_idxs)

    for i in tqdm(range(k_params.shape[0]), desc="Vary K of FH04", disable=verbose):
        k = k_params[i]
        part_fh04 = partition_from_probs(graph_dict=graph_dict, sim_probs=probs, k=k, P=P, sp_idxs=sp_idxs)
        #ooa_fh04, partition_gt, sortation = ooa(par_v_gt=p_vec_gt, par_v=part_fh04, partition_gt=partition_gt, sortation=sortation)
        _, _, ooa_fh04, _, _ = match_score(
            gt_partition=partition_gt, partition=Partition(partition=part_fh04), return_ooa=True)
        #_, _, ooa_fh04, _, _ = match_score(
        #    gt_partition=partition_gt, partition=partition_gt, return_ooa=True)
        size_fh04 = np.unique(part_fh04).shape[0]
        ooas.append(ooa_fh04)
        sizes.append(size_fh04)
        all_data.append([scene_name, k, ooa_fh04, size_fh04, ooa_cp, size_cp])

    save_csv(res=all_data, csv_dir=args.csv_dir, csv_name=csv_name, data_header=csv_header)

    ooas = np.array(ooas)
    sizes = np.array(sizes)

    ooa_cps = np.zeros((ooas.shape[0], ))
    ooa_cps[:] = ooa_cp

    plt.plot(k_params, ooas, ".")
    plt.plot(k_params, ooa_cps, "-")
    #plt.xticks(k_params)
    plt.savefig(fname="fh04_k_ooa_id{0}.jpg".format(args.sn_id))
    plt.show()

    sizes_cps = np.zeros((sizes.shape[0], ))
    sizes_cps[:] = size_cp
    plt.plot(k_params, sizes, ".")
    plt.plot(k_params, sizes_cps, "-")
    #plt.xticks(k_params)
    plt.savefig(fname="fh04_k_sizes_id{0}.jpg".format(args.sn_id))
    plt.show()

def all_scenes():
    parser = argparse.ArgumentParser()
    # cp params
    parser.add_argument("--reg_strength", default=0.1, type=float, help="Regularization strength for the minimal partition. Increase lambda for a coarser partition. ")
    parser.add_argument("--k_nn_geof", default=45, type=int, help="Number of neighbors for the geometric features.")
    parser.add_argument("--k_nn_adj", default=10, type=int, help="Adjacency structure for the minimal partition.")
    parser.add_argument("--lambda_edge_weight", default=1., type=float, help="Parameter determine the edge weight for minimal part.")
    parser.add_argument("--d_se_max", default=0, type=float, help="Max length of super edges.")
    parser.add_argument("--max_sp_size", default=-1, type=int, help="Maximum size of a superpoint.")
    #
    parser.add_argument("--pkg_size", default=5, type=int, help="Number of packages to save a csv")
    parser.add_argument("--csv_dir", default="./csvs_vary_k", type=str, help="Directory where we save the csv.")
    parser.add_argument("--load_exp", default=False, type=bool, help="Use data from pre calculated dataset")
    parser.add_argument("--h5_dir", default="./exp_data", type=str, help="Directory where we load the h5 files.")
    parser.add_argument("--cc", default=False, type=bool, help="Use connected components")
    args = parser.parse_args()

    mkdir(args.csv_dir)

    k_params = [0.001, 0.1, 1, 2, 10, 100]
    if args.cc:
        k_params = [0.55, 0.6, 0.65, 0.7]

    scenes, _, scannet_dir = get_scenes(blacklist=[])
    header = ["Name", "K"]
    algorithms=["FH04", "CP"]
    if args.cc:
        header = ["Name", "T"]
        algorithms=["CC", "CP"]

    csv_header = get_csv_header(header=header, algorithms=algorithms,
        algo_stats=["OOA", "|S|", "MS", "RS", "NFOM", "NSOM", "NTOM", "DFOM", "DSOM", "DTOM"])

    verbose = False
    model = None

    desc = "Vary K"
    if args.cc:
        desc = "Vary T"
    for j in tqdm(range(len(scenes)), desc=desc, disable=False):
        scene_name = scenes[j]
        mesh, p_vec_gt, file_gt = get_ground_truth(
            scannet_dir=scannet_dir, scene=scene_name)
        xyz = np.asarray(mesh.vertices)
        rgb = np.asarray(mesh.vertex_colors)
        P = np.hstack((xyz, rgb))

        if args.load_exp:
            exp_dict, sp_idxs = load_exp_data(fdir=args.h5_dir, fname=scene_name)
            graph_dict = {
                "nodes": exp_dict["node_features"],
                "senders": exp_dict["senders"],
                "receivers": exp_dict["receivers"]
            }
            probs = exp_dict["probs_gnn"]
            #print("mean: {0}, std: {1}".format(np.mean(probs), np.std(probs)))
            p_vec_gt = exp_dict["p_gt"]
            part_cp = exp_dict["p_cp"]
        else:
            sortation = np.argsort(p_vec_gt)
            sortation = sortation.astype(np.uint32)
            p_vec_gt = p_vec_gt[sortation]
            xyz = xyz[sortation]
            rgb = rgb[sortation]
            P = P[sortation]
            graph_dict, sp_idxs, part_cp = graph(
                cloud=P,
                k_nn_adj=args.k_nn_adj,
                k_nn_geof=args.k_nn_geof,
                lambda_edge_weight=args.lambda_edge_weight,
                reg_strength=args.reg_strength,
                d_se_max=args.d_se_max,
                max_sp_size=args.max_sp_size,
                verbose=verbose,
                return_p_vec=True)
            if model is None:
                _, probs, model = predict(graph_dict=graph_dict, dec_b=0.8, return_model=True, verbose=False)
            else:
                _, probs = predict(graph_dict=graph_dict, dec_b=0.8, model=model, verbose=False)

        ooas = []
        sizes = []
        all_data = []
        partition_gt = None

        partition_gt = Partition(partition=p_vec_gt)
        ms_cp, raw_score_cp, ooa_cp, match_stats_cp, dens_stats_cp = match_score(
            gt_partition=partition_gt, partition=Partition(partition=part_cp), return_ooa=True)
        size_cp = np.unique(part_cp).shape[0]

        for i in range(len(k_params)):
            k = k_params[i]
            #k = 0.99
            if args.cc:
                unions = probs >= k
                part_fh04 = partition(graph_dict=graph_dict, unions=unions, P=P, sp_idxs=sp_idxs, half=False, verbose=verbose)
            else:
                part_fh04 = partition_from_probs(graph_dict=graph_dict, sim_probs=probs, k=k, P=P, sp_idxs=sp_idxs)

            ms_fh04, raw_score_fh04, ooa_fh04, match_stats_fh04, dens_stats_fh04 = match_score(
                gt_partition=partition_gt, partition=Partition(partition=part_fh04), return_ooa=True)

            size_fh04 = np.unique(part_fh04).shape[0]
            #print("k:", k, "size:", size_fh04, "len sp_idxs:", len(sp_idxs))
            #return
            ooas.append(ooa_fh04)
            sizes.append(size_fh04)
            all_data.append([
                scene_name, k, ooa_fh04, size_fh04, ms_fh04, raw_score_fh04,
                match_stats_fh04[0], match_stats_fh04[1], match_stats_fh04[2],
                dens_stats_fh04[0], dens_stats_fh04[1], dens_stats_fh04[2],
                #
                ooa_cp, size_cp, ms_cp, raw_score_cp,
                match_stats_cp[0], match_stats_cp[1], match_stats_cp[2],
                dens_stats_cp[0], dens_stats_cp[1], dens_stats_cp[2]
                ])
        save_csv(res=all_data, csv_dir=args.csv_dir, csv_name=str(j), data_header=csv_header)
        all_data.clear()

if __name__ == "__main__":
    #main()
    all_scenes()


import os
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as spig

f=lambda y,t: ((2*t-1)*np.exp(t)-(t-1)*y)/t

pen=['g', 'b', 'r', 'c']
init=[7.6, -1, 5,1]

for y0, col in zip(init,pen):
    T=np.linspace(2,-2,100)
    Z=spig.odeint(f,y0,T)
    plt.plot(T,Z,col+'-')
    plt.plot(T[0],y0,col+'o')
    xx,XX=min(T), max(T)

plt.title(r"$ty'+(t-1)y=(2t-1)\exp(t)$",fontsize=20)
plt.ylim(-10,8) # limite l'axe des ordonnées

# trace les axes
xx,XX= -3,2
yy,YY=plt.ylim()
plt.plot([0,0],[yy,YY],'k-', [xx,XX],[0,0],'k-')
#plt.axes().set_aspect('equal')

plt.grid()

FichierCourant=os.path.basename(__file__)
plt.savefig(FichierCourant[:-2]+"pdf")
#plt.show()


from openpyxl import Workbook, load_workbook
import csv

wb1 = load_workbook('FY22_Spending.xlsx')
ws1 = wb1.active

wb2 = load_workbook('FRSE TR.xlsx')
ws2 = wb2.active
cell_obj2 = ws2.cell(row = 1, column = 1)

cell_obj1 = ws1.cell(row = 1, column = 1)

file = open('FY22_Spending.csv')
reader = csv.reader(file)
header = []
header = next(reader)
rows = []
for row in reader:
    rows.append(row)

print(rows)
file.close()

print(cell_obj2.value)
print(cell_obj1.value)


R_price = int(input())
number = int(input())
N_price = 0

for _ in range(number) :
    price, nums = map(int, input().split())
    N_price += price * nums

if N_price == R_price :
    print("Yes")
else :
    print("No")


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

class Linkedlist(object):
    def __init__(self, maxsize=None ):  # maxsize为None说明长度无限
        self.maxsize = maxsize
        self.root = Node()
        self.length = 0
        self.tailnode = None  # 尾节点

    def __len__(self):
        return self.length

    def append(self, value):
        if self.maxsize is not None and len(self) > self.maxsize:
            raise Exception('Full')

        node = Node(value)
        tailnode = self.tailnode

        if tailnode is None:  # 说明只有一个root节点
            self.root.next = node
        else:
            tailnode.next = node
        self.tailnode = node
        self.length += 1

    def appendleft(self, value):  # 每一个都插入到root节点的后面
        '''
        首节点在root节点之后
        将要插入的node节点插入到root的next
        将node.next指向之前的首节点
        '''
        headnode = self.root.next
        node = Node(value)
        self.root.next = node
        node.next = headnode
        self.length += 1

    def __iter__(self):
        for node in self.iter_node():
            yield node.value

    def iter_node(self):
        currnode = self.root.next
        while currnode is not self.tailnode:
            yield currnode
            currnode = currnode.next
        yield currnode

    def remove(self, value):  # O(n)复杂度
        previrnode = self.root
        currnode = self.root.next

        for currnode in self.iter_node():     # 代替原 while currnode is not None
            if currnode.value == value:
                previrnode.next = currnode.next
                if currnode is self.tailnode:
                    self.tailnode = currnode
                del currnode
                self.length -= 1
                return 1  # 表示删除成功
            else:
                previrnode = currnode
            return -1

    def find(self, value):  # O(n)复杂度
        index = 0
        for node in self.iter_node():
            if node.value == value:
                return index
            index += 1
        return -1  # 用来标识

    def popleft(self):  # O(1)复杂度 ， 可用来实现两端队列
        if self.root.next is None:
            raise Exception('pop from empty Linkedlist')
        headnode = self.root.next
        self.root.next = headnode.next
        self.length -= 1
        value = headnode.value
        del headnode
        return value

    def clear(self):
        for node in self.iter_node():
            del node

        self.length = 0
        self.root.next = None
##############################
#       以下是queue实现
##############################
class FullError(Exception):
    pass

class EmptyError(Exception):
    pass

class Queue(object):
    def __init__(self, maxsize=None, ):
        self.maxsize = maxsize
        self._item_linked_list = Linkedlist()

    def __len__(self):
        return len(self._item_linked_list)

    def push(self, item):
        if self.maxsize is not None and len(self) >= self.maxsize:
            raise FullError('queue is full')
        return self._item_linked_list.append(item)

    def pop(self):
        if len(self) <= 0:
            raise EmptyError('queue is empty')
        return self._item_linked_list.popleft()

def test_queue():
    q = Queue()
    q.push(0)
    q.push(1)
    q.push(2)

    assert len(q) == 3

    assert q.pop() == 0
    assert q.pop() == 1
    assert q.pop() == 2

    import pytest
    with pytest.raises(EmptyError) as empinfo:
        q.pop()
    assert 'empty' in str(empinfo.value)


""" Test basic page """
import unittest
from app.app import BENDER as app

class BenderHomeUnitTest(unittest.TestCase):
    """ For unit testing bender homepage """
    def setUp(self):
        super(BenderHomeUnitTest, self).setUp()
        app.testing = True
        self.app = app.test_client()

    def test_home_code(self):
        """ Test home response code, expect 200 """
        response = self.app.get('/')
        assert response.status_code == 200

    def test_home_response(self):
        """ Test home page response, expect html content """
        response = self.app.get('/')
        assert response.headers['content-type'] == "text/html; charset=utf-8"

if __name__ == '__main__':
    unittest.main()


import numpy as np
#from scipy.special import legendre
#from scipy.special import lpmv
import torch
from torch.autograd import grad as grad
from torch.autograd.functional import hessian
import math
import random
from timeit import default_timer as timer

nx = 5
nspin = 2
rho = torch.rand(nx,nspin)
drho = torch.rand(nx,nspin,3)
ddrhoTmp = torch.rand(nx,nspin,9)
ddrhoTmpRS = torch.reshape(ddrhoTmp, (nx,nspin,3,3))
ddrho = 0.5*(ddrhoTmpRS + torch.transpose(ddrhoTmpRS, -2, -1))
X = torch.zeros(nx,8)
X[:,0:nspin] = rho
for iSpin in range(2):
    index = nspin + 3*iSpin
    X[:,index:index+3] = drho[:,iSpin]

X.requires_grad_()

rhoA = X[:,0]
rhoB = X[:,1]
drhoA = X[:,2:5]
drhoB = X[:,5:8]
moddrhoA = ((drhoA**2.0).sum(dim=1))**0.5
moddrhoB = ((drhoB**2.0).sum(dim=1))**0.5

#Y = (rhoA**2.0+ rhoB**2.0)*(moddrhoA**2.0 + moddrhoB**2.0)#(rhoA**2.0 + rhoB**3.0)*(moddrhoA**3.0)*(moddrhoB**2.0)
Y = (rhoA**2.0 + rhoB**3.0)*(moddrhoA**3.0)*(moddrhoB**2.0)
g = grad(Y,X,torch.ones_like(Y),retain_graph=True, create_graph=True)[0]

vxc = torch.zeros(nx,nspin)
for iSpin in range(nspin):
    id1 = nspin+3*iSpin
    vxc[:,iSpin] = g[:,iSpin]
    gdrho = g[:,id1:id1+3]
    for jSpin in range(nspin):
        id2 = nspin+3*jSpin
        t1 = grad(gdrho,X, drho[:,jSpin], retain_graph=True)[0]
        vxc[:,iSpin] = vxc[:,iSpin] - t1[:,jSpin]
        t21 = grad(gdrho, X, ddrho[:,jSpin,0], retain_graph=True)[0]
        t22 = grad(gdrho, X, ddrho[:,jSpin,1], retain_graph=True)[0]
        t23 = grad(gdrho, X, ddrho[:,jSpin,2], retain_graph=True)[0]
        vxc[:,iSpin] = vxc[:,iSpin] - (t21[:,id2+0] + t22[:,id2+1] + t23[:,id2+2])

uAA = (drhoA*drhoA).sum(dim=1)
uAB = (drhoA*drhoB).sum(dim=1)
uBB = (drhoB*drhoB).sum(dim=1)
vA = torch.einsum('ijk,ik->ij',ddrho[:,0],drhoA)
vB = torch.einsum('ijk,ik->ij',ddrho[:,1],drhoB)
vAA = (vA*drhoA).sum(dim=1)
vAB = (vA*drhoB).sum(dim=1)
vBA = (vB*drhoA).sum(dim=1)
vBB = (vB*drhoB).sum(dim=1)
rhoLapA = torch.diagonal(ddrho[:,0], dim1=-2, dim2=-1).sum(dim=-1)
rhoLapB = torch.diagonal(ddrho[:,1], dim1=-2, dim2=-1).sum(dim=-1)
print(rhoLapA.shape)
#vxcA = 2.0*rhoA*(moddrhoA**2.0 + moddrhoB**2.0) - 4.0*rhoA*uAA\
#       - 4.0*rhoB*uAB -2.0*(rhoA**2.0+rhoB**2.0)*rhoLapA
vxcA = 2.0*rhoA*(moddrhoA**3.0)*(moddrhoB**2.0) -\
       3.0*moddrhoA*(moddrhoB**2.0)*(2.0*rhoA*uAA + 3.0*rhoB**2.0*uAB)-\
       3.0*(rhoA**2.0 + rhoB**3.0)*(moddrhoB**2.0)*vAA/moddrhoA -\
       6.0*(rhoA**2.0 + rhoB**3.0)*moddrhoA*vBA -\
       3.0*(rhoA**2.0 + rhoB**3.0)*moddrhoA*(moddrhoB**2.0)*rhoLapA

diffA = vxc[:,0]-vxcA
print(diffA)


from time import perf_counter

cubes: set[tuple[int, ...]] = set()

sides: list[list[int]] = [[-1, 0, 0], [1, 0, 0],
                          [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1]]

with open('./data.txt', 'r') as data:
    for line in data:
        x, y, z = line[:-1].split(',')
        cubes.update({(int(x), int(y), int(z))})

start: int = perf_counter()
free_sides: int = 0
for cube in cubes:
    for side in sides:
        gen_adjecent = tuple([c+s for c, s in zip(cube, side)])

        if gen_adjecent not in cubes:
            free_sides += 1

print(perf_counter() - start)
print(free_sides)


# coding: utf-8
import cv2
import sys

#Función para atender los eventos del ratón
def EventoRaton(evento, x, y, flags,datos):
    global color
    if evento == cv2.EVENT_MOUSEMOVE:
    # Este evento se genera cada vez que el ratón se mueve por encima de la
    # ventana. Se pueden generar varios eventos similares por segundo.
    # Por ese motivo, si el evento no es necesario, es conveniente salir
    # inmediatamente de la función para no bloquear la aplicación.
        pass

    elif evento == cv2.EVENT_LBUTTONDBLCLK:
        print("Doble click botón izquierdo\n")
        cv2.circle(img, (x,y), 3, color, -1)
    elif evento == cv2.EVENT_LBUTTONDOWN:
        print("Pulsar botón izquierdo\n")
    elif evento == cv2.EVENT_LBUTTONUP:
        print("Soltar botón izquierdo\n")
    else:
        print("Otro evento\n")

    print("Coordenadas: x=", x, ", y=", y, "\n")
    #Refrescamos la imagen en pantalla.
    cv2.imshow("Imagen", img);

#Abrimos la imagen indicada en el primer argumento
try:
    img=cv2.imread(sys.argv[1], cv2.IMREAD_UNCHANGED);
except:
    print("ERROR al abrir la imagen\n")
    sys.exit(1)

#Comprobamos si la imagen se ha abierto correctamente.
if img is None:
    print("ERROR: Imagen: ", sys.argv[1], " no existe\n")
else:
    #Creamos una ventana donde mostrar la imagen.
    cv2.namedWindow("Imagen", cv2.WINDOW_AUTOSIZE)
    #Mostramos la imagen en pantalla.
    cv2.imshow("Imagen", img)

    #  Asociamos la función de manejo de eventos a esta ventana.
    #  Pasamos la imagen como argumento a la función. Tener en
    #  cuenta la conversión a puntero void para poder realizar
    #  el paso. Observar en la callback como se deshace la
    #  conversión.
    color=(0,0,255)
    cv2.setMouseCallback("Imagen", EventoRaton)
    #Variable en la que capturaremos la tecla pulsada.
    c=0
    #Creamos un bucle infinito, que sólo finalizará al pulsar Esc.
    while not c==27:
        #Esperamos a que el usuario pulse una tecla.
        c=cv2.waitKey(0) & 0xFF
        #Imprimimos la tecla pulsada.
        print(c,"\n")

    #Liberamos la ventana creada.
    cv2.destroyWindow("Imagen")


import os, sys
import numpy as np
import random

from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.optimizers import Adam, RMSprop

root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root)

from src.utils.mining_data_tb import Preprocessor

###########################################################################################################################################

class LSTM_Generator(Preprocessor):

    def __init__(self, df, maxlen=40, step=3, option='character', min_word_frequency=3, model_type=1):
        """Class for creating a LSTM Model.
            - Args:
                - df: Base Quote Dataframe.
                - maxlen: Sequence length into which the corpus is divided. This will result in the number of rows of each X array.
                - step: Affects the number of sequences to be generated.
                - option: 'character' for character-based models and 'word' for word-based models.
                - min_word_frequency: Minimum word frequency to take into account when creating the word dictionary.
                                    Affects the number of columns
                - model_type: 1 for basic LSTM and 2 for Bidirectional LSTM.
        """
        Preprocessor.__init__(self, df)
        self.maxlen = maxlen
        self.step = step
        self.option = option

        self.preprocess(maxlen=self.maxlen, step=self.step, option=option, mode='base', min_word_frequency=min_word_frequency)

        self.model = self.base_model(model_type=model_type)

    def base_model(self, model_type=1):
        """Returns a basic or bidirectional LSTM model."""

        if model_type == 1:
            model = keras.Sequential([
                layers.InputLayer(input_shape=(self.maxlen, len(self.tokens))),
                layers.LSTM(128),
                layers.Dense(len(self.tokens), activation="softmax")
            ])

        if model_type == 2:
            model = keras.Sequential([
                layers.InputLayer(input_shape=(self.maxlen, len(self.tokens))),
                layers.Bidirectional(layers.LSTM(128)),
                layers.LeakyReLU(alpha=0.3),
                layers.Dropout(0.3),
                layers.Dense(len(self.tokens), activation="softmax")
            ])

        model.summary()
        optimizer = RMSprop(learning_rate=0.01)
        model.compile(loss="categorical_crossentropy", optimizer=optimizer, metrics=["RootMeanSquaredError"])

        return model

    def train(self, epochs=1, batch_size=128):
        """Trains model.
            - Args:
                - epochs: Number of epochs.
                - batch_size: number of input arrays to be used in each epoch."""

        print(f'Training {self.option} LSTM model for [epochs:{epochs}, batch_size:{batch_size}]')
        self.model.fit(self.X, self.Y, batch_size=batch_size, epochs=epochs)
        print('Finished training.')

    def predict(self, option='character', quote_len=40, sentence=False, temperature=1.0, verbose=False):
        """Returns a prediction:
            - Args:
                - option: 'character' for character-based models and 'word' for word-based models.
                - quote_len: Number of characters/words to show in output. Only affects LSTM models.
                - sentence: Input string. If false, the model predicts with a random input.
                - temperature: Sequence variance distortion. Recommended low values for character based models.
                - verbose: If True, prints generations steps."""

        prediction = self.generate(self.model, mode='base', option=option, quote_len=quote_len,
                                    sentence=sentence, temperature=temperature, verbose=verbose)

        return prediction

    def save_model(self, filepath):
        """Saves model into desired path."""

        self.model.save(filepath)
        print('Model saved.')

###########################################################################################################################################

class GAN(Preprocessor):

    def __init__(self, df, maxlen=40, step=3, option='character', min_word_frequency=3):
        """Class for creating a LSTM Model.
            - Args:
                - df: Base Quote Dataframe.
                - maxlen: Sequence length into which the corpus is divided. This will result in the number of rows of each X array.
                - step: Affects the number of sequences to be generated.
                - option: 'character' for character-based models and 'word' for word-based models.
                - min_word_frequency: Minimum word frequency to take into account when creating the word dictionary.
                                    Affects the number of columns
        """
        Preprocessor.__init__(self, df)
        self.maxlen = maxlen
        self.step = step
        self.option = option
        self.disc_loss = []
        self.gen_loss = []

        self.preprocess(maxlen=self.maxlen, step=self.step, option=option, mode='gan', min_word_frequency=min_word_frequency)

        optimizer = Adam(learning_rate=0.0002, beta_1=0.5)

        # Build and compile the discriminator
        self.discriminator = self.build_discriminator()
        self.discriminator.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])

        # Build the generator
        self.generator = self.build_generator()

        # For the combined model we will only train the generator
        self.discriminator.trainable = False

        # Build the GAN Model
        self.gan = self.build_gan(self.generator, self.discriminator)
        self.gan.compile(loss='binary_crossentropy', optimizer=optimizer)

    def get_latent_points(self, n_samples):
        """Returns a random Latent Point array."""

        x_input = np.zeros((n_samples, self.maxlen, len(self.tokens)))

        for i, element in enumerate(x_input):
            for j, row in enumerate(element):
                number = random.randint(0, len(row))
                for k in range(len(row)):
                    if k == number:
                        x_input[i][j][k] = 1

        return x_input

    def generate_fake_samples(self, model, n_samples):
        """Returns a latent point array labeled as fake samples."""

        x_input = self.get_latent_points(n_samples)

        X_fake = model.predict(x_input, verbose=0)
        y_fake = np.zeros(n_samples)

        return X_fake, y_fake

    def generate_real_samples(self, n_samples):
        """Returns real sequence arrays labeled as real samples."""

        X_true = np.array(random.sample(list(self.X), n_samples))
        y_true = np.ones(n_samples)

        return X_true, y_true

    def generate_gan_samples(self, n_samples):
        """Returns a latent point array labeled as real samples."""

        X_gan = self.get_latent_points(n_samples)
        y_gan = np.ones(len(X_gan))

        return X_gan, y_gan

    def build_discriminator(self):
        """Returns a discriminator model with the [Convolution -> LeakyRelu -> Dropout] Layer Layout."""

        discriminator = keras.Sequential([
            layers.Conv1D(filters=len(self.tokens), kernel_size=(3), input_shape=(self.maxlen, len(self.tokens)), padding='same'),
            layers.LeakyReLU(alpha=0.2),
            layers.Dropout(0.2),
            layers.Conv1D(filters=len(self.tokens), kernel_size=(3), input_shape=(self.maxlen, len(self.tokens)), padding='same'),
            layers.LeakyReLU(alpha=0.2),
            layers.Dropout(0.2),
            layers.Conv1D(filters=len(self.tokens), kernel_size=(3), input_shape=(self.maxlen, len(self.tokens)), padding='same'),
            layers.LeakyReLU(alpha=0.2),
            layers.Dropout(0.2),
            layers.Dense(1, activation='sigmoid')
        ])

        discriminator.summary()

        return discriminator

    def build_generator(self):
        """Returns a generator model with the [Dense -> LeakyRelu -> BatchNormalization] Layer Layout."""

        generator = keras.Sequential([
            layers.Dense((len(self.tokens)), input_shape=(self.maxlen, len(self.tokens))),
            layers.LeakyReLU(alpha=0.2),
            layers.BatchNormalization(momentum=0.8),
            layers.Dense(512),
            layers.LeakyReLU(alpha=0.2),
            layers.BatchNormalization(momentum=0.8),
            layers.Dense(len(self.tokens)),
            layers.LeakyReLU(alpha=0.2),
            layers.BatchNormalization(momentum=0.8),
            layers.Reshape((self.maxlen, len(self.tokens))),
            layers.Conv1DTranspose(len(self.tokens), 2, padding="same", activation='softmax')
        ])

        generator.summary()

        return generator

    def build_gan(self, g_model, d_model):
        """Returns the GAN model."""

        gan = keras.Sequential([
            layers.InputLayer(input_shape=(self.maxlen, len(self.tokens))),
            g_model,
            d_model
        ])
        gan.summary()

        return gan

    def train(self, epochs, batch_size=128, sample_interval=50, verbose=True):
        """Trains the GAN model.
            - Args:
                - epochs: Number of epochs
                - batch_size: For each epoch, the whole data is divided into batches of the desired size.
                - sample interval: Number of trains before printing the metrics.
                - verbose: 1 for printing the sample interval and 2 or more for printing training steps."""

        batch_per_epoch = len(self.X)//batch_size
        half_batch = batch_size//2
        # Training the model
        for epoch in range(epochs):

            for n in range(batch_per_epoch):

                # Training the discriminator
                # Select a random batch of character sequences
                if verbose > 1:
                    print(f'Generating real samples: {n+1}/{batch_per_epoch}')
                X_real, y_real = self.generate_real_samples(half_batch)

                # Generate a batch of fake character sequences
                if verbose > 1:
                    print(f'Generating fake samples: {n+1}/{batch_per_epoch}')
                X_fake, y_fake = self.generate_fake_samples(self.generator, half_batch)

                # Train the discriminator
                if verbose > 1:
                    print(f'Training Discriminator: {n+1}/{batch_per_epoch}')
                d_loss_real = self.discriminator.train_on_batch(X_real, y_real)
                d_loss_fake = self.discriminator.train_on_batch(X_fake, y_fake)
                #d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)

                #  Training the Generator
                if verbose > 1:
                    print(f'Generating GAN samples: {n+1}/{batch_per_epoch}')
                X_gan, y_gan = self.generate_gan_samples(batch_size)

                # Train the generator (to have the discriminator label samples as real)
                if verbose > 1:
                    print(f'Training Generator: {n+1}/{batch_per_epoch}')
                g_loss = self.gan.train_on_batch(X_gan, y_gan)

                # Print the progress and save into loss lists
                if epoch % sample_interval == 0 and verbose > 0:
                    print(f"{epoch}:{n+1}/{batch_per_epoch}: [DR_acc: {round(d_loss_real[1],3)}, DF_acc: {round(d_loss_fake[1],3)}] [G loss: {g_loss}]")
                    self.disc_loss.append((d_loss_real, d_loss_fake))
                    self.gen_loss.append(g_loss)

    def predict(self, option='character', quote_len=40, sentence=False, temperature=1.0, verbose=False):
        """Returns a prediction:
            - Args:
                - option: 'character' for character-based models and 'word' for word-based models.
                - quote_len: Number of characters/words to show in output. Only affects LSTM models.
                - sentence: Input string. If false, the model predicts with a random input.
                - temperature: Sequence variance distortion. Recommended low values for character based models.
                - verbose: If True, prints generations steps."""

        prediction = self.generate(self.generator, mode='gan', option=option, quote_len=quote_len,
                                    sentence=sentence, temperature=temperature, verbose=verbose)

        return prediction

    def get_mean_scores(self):
        """Returns Mean Loss and Accuracy for real and fake samples"""
        gan_loss = (self.disc_loss[-1][0][0] + self.disc_loss[-1][1][0])/2
        gan_acc = (self.disc_loss[-1][0][1] + self.disc_loss[-1][1][1])/2

        return gan_loss, gan_acc

    def save_model(self, filepath):
        """Saves model into desired location."""

        self.generator.save(filepath)
        print('GAN Generator model saved.')


from django import forms
from django.conf import settings
from django.contrib.gis.forms.widgets import OSMWidget

from geodjango_tag import models as geodjango_tag_models

class TaggedLocationForm(forms.ModelForm):

    class Meta:
        model = geodjango_tag_models.TaggedLocation
        fields = ['name', 'location', 'tags']

        widgets = {
            'location': OSMWidget
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['location'].widget.attrs['default_zoom'] = settings.DEFAULT_ZOOM
        self.fields['location'].widget.attrs['default_lon'] = settings.DEFAULT_LOCATION['longitude']
        self.fields['location'].widget.attrs['default_lat'] = settings.DEFAULT_LOCATION['latitude']


from tkinter import *
import wikipedia

def get_me():

    ta.delete(1.0,END)
    ev = entry.get()
    try:
        tav = wikipedia.summary(ev)
    except:
        print("Check your input or internet connection!!")
    ta.insert(INSERT,tav)

root =Tk()
root.title("Search App")

f1=Frame(root)
entry=Entry(f1)
entry.pack()
b=Button(f1,text="Search",command=get_me)
b.pack()
f1.pack(side=TOP)

f2=Frame(root)
scroll=Scrollbar(f2)
scroll.pack(side=RIGHT,fill=Y)
ta=Text(f2,width=50,height=20,yscrollcommand=scroll.set,wrap=WORD)
ta.pack()
scroll.config(command=ta.yview)
f2.pack()

root.geometry("500x500+250+250")
root.mainloop()


from sympy.printing.latex import latex
import re

## define a function that takes a dict and does format operation for each value then returns new dict
def format_dict(dict):
    derivative = dict.get("derivative")
    function = dict.get("function")
    points = dict.get("points")

    derivative = latex(derivative, ln_notation=True)
    function = latex(function, ln_notation=True)

    # \right) and \left( are not supported by katex, renderer used in frontend
    derivative = re.sub(r"\\right", "", derivative)
    dict["derivative"] = re.sub(r"\\left", "", derivative)

    function = re.sub(r"\\right", "", function)
    dict["function"] = re.sub(r"\\left", "", function)

    for i in range(len(points)):
        x_0 = points[i].get("x_0")
        y_0 = points[i].get("y_0")

        x_0 = latex(x_0, ln_notation=True)
        y_0 = latex(y_0, ln_notation=True)

        x_0 = re.sub(r"\\right", "", x_0)
        dict["points"][i]["x_0"] = re.sub(r"\\left", "", x_0)

        y_0 = re.sub(r"\\right", "", y_0)
        dict["points"][i]["y_0"] = re.sub(r"\\left", "", y_0)

    return dict


n, x, y = map(int, input().split())
a = list(map(int, input().split()))

# Grundy数を求める
# grundy[i] : 石がi個のGrundy数
# transit[i] : grundy数がiとなるような遷移ができるか
# 各山の個数のgrundy数を求める
# 後でそれぞれの山のgrundy数のxorをとる
grundy = [0] * (10**6 + 1)
for i in range(10**6 + 1):
    # 遷移できるかどうかを調べる
    transit = [False] * 3
    if i >= x:
        transit[grundy[i - x]] = True
    if i >= y:
        transit[grundy[i - y]] = True

    # 遷移できるならgrundy数を求める
    # i = 0: grundy[0] = 0
    if not transit[0]:
        grundy[i] = 0
    elif not transit[1]:
        grundy[i] = 1
    else:
        grundy[i] = 2

xor_sum = 0
for i in range(n):
    xor_sum ^= grundy[a[i]]
if xor_sum != 0:
    print("First")
else:
    print("Second")