"""
This module deals with the prediction of sales for a year into the future.

This is done by finding the growth rates for each day in the csv file and multiplying
that to the latest data point for each beer over and over until all the growth rates have
been multiplied.
In addition, the module can plot past data and the prediction using
matplotlib and find the total predicted sale of a given time period.
"""
import os
from datetime import datetime, timedelta
from typing import List, Tuple, Dict
import logging
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from read_file import parse_data

ABS_PATH = os.path.abspath(__file__)
D_NAME = os.path.dirname(ABS_PATH)
os.chdir(D_NAME)

LOGGER = logging.getLogger("sales_predictions")
LOGGER.setLevel(logging.DEBUG)
F_HANDLER = logging.FileHandler('log_file.log')
F_FORMAT = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
F_HANDLER.setFormatter(F_FORMAT)
LOGGER.addHandler(F_HANDLER)

def calculate_growth(start_date_obj: datetime, end_date_obj: datetime,
                     x_list: List[datetime], y_list: List[int], days: int = 1) -> int:
    """
    This function calculates the growth % given two dates and the sales for those dates.

    This function can also calculate the growth rate between two periods.

    :param start_date_obj: First date.
    :param end_date_obj: Second date.
    :param x_list: List of dates.
    :param y_list: List of sales.
    :param days: Length of time period.

    :return: Growth % as a rounded integer.
    """
    x_index = x_list.index(start_date_obj)
    start_data = sum(y_list[x_index:x_index+days])  # Summing the sales values for the given period.
    if start_data == 0:
        # Setting a default replacement value for 0 so prediction division by 0 doesn't occur.
        LOGGER.debug("Start data changed to 1.1")
        start_data = 1.1
    x_index = x_list.index(end_date_obj)
    if x_index+days <= len(y_list):
        # Summing the sales values in the next given period.
        end_data = sum(y_list[x_index:x_index+days])
    else:
        end_data = sum(y_list[x_index:])  # If the end of the list is reached.
    growth_percent = round((end_data - start_data) / start_data, 5) * 100
    return growth_percent

def multiply_rate(value: int, percent_list: List[int],
                  index: int = 0, new_list: List = None) -> List[int]:
    """
    This function multiplies all the growth rates recursively.

    :param value: Value for the growth % to be applied to.
    :param percent_list: List of growth %.
    :param index: Index of the growth % to be applied.
    :param new_list: List of the new values after growth % was applied.

    :return: After recursion is finished, a list of the new values is returned.
    """
    if new_list is None:
        new_list = []

    if index >= len(percent_list):
        return new_list
    value += 1  # To avoid the prediction flat-lining.
    value *= ((percent_list[index]) / 100) + 1
    new_list.append(value)
    index += 1
    return multiply_rate(value, percent_list, index, new_list)

def plot_past_data(key_name: str = None) -> List[Line2D]:
    """
    This function plots the past data using matplotlib.

    The optional argument allows you to see the graph for only one beer type.

    :param key_name: A specific type of beer to be shown.
    :return: The plot.
    """
    LOGGER.info("Plotting past data")
    data_dict = parse_data()
    for key in data_dict['x']:
        if key_name is None or key == key_name:
            x_data = data_dict['x'][key]
            y_data = data_dict['y'][key]
            line_2d = plt.plot(x_data, y_data, label=key, marker=".", linewidth=0.5, markersize=1)

    plt.legend()
    return line_2d

def plot_growth_percent(days: int = 1, key_name: str = None, plot: bool = True,
                        start_date: datetime = None) -> Tuple[List[datetime], Dict[str, List[int]]]:
    """
    This function returns the growth rates for each beer.

    The growth can be calculated for a total of a given period or day by day. It can
    also be calculated for all the beers or just one specific beer.
    This module also has the capability to plot the grow rates using matplotlib.

    :param days: The period to sum the data.
    :param key_name: The name of the specific beer.
    :param plot: Whether to plot the graph or not.
    :param start_date: The date to start the growth rate list from.

    :return: A dictionary of the growth rates and the corresponding dates.
    """
    LOGGER.info("Calculating growth rates")
    data_dict = parse_data()
    growth_dict = {}

    for key in data_dict['x']:  # Iterating through each beer.
        if key_name is None or key_name == key:
            x_data, y_data = data_dict['x'][key], data_dict['y'][key]

            growth_rates = []
            dates = []

            # Iterating through the dates in required steps.
            for index in range(0, len(x_data)-days, days):
                date = x_data[index]
                if start_date is None or start_date <= date:
                    dates.append(date)
                    growth = calculate_growth(date, date + timedelta(days), x_data, y_data, days)
                    growth_rates.append(growth)
            LOGGER.debug("Data and date added")

            growth_dict[key] = growth_rates

            if plot:
                plt.plot(dates, growth_rates,
                         label=key + " growth % "+str(days),
                         linestyle='None', marker="D", markersize=2)

    if plot:
        plt.legend()
    return dates, growth_dict

def plot_next_year(days: int = 1, key_name: str = None, next_year: bool = True,
                   start_date: datetime = None, date_range: int = None)\
        -> Tuple[List[datetime], Dict[str, List[int]]]:
    """
    This module calculates the predictions for 1 year from the latest data in the csv file.

    The module has several options including calculating the data for just the given period.
    A prediction is made by calculating the growth rates per day in the csv file, and multiplying
    that to the latest sales made in the csv file.

    :param days:
    The period in which to calculate growth.
    Set this to values other than one to predict using time periods.
    :param key_name: Can be set to find the prediction for just one beer.
    :param next_year: Whether to adjust the dates for prediction.
    :param start_date: The date to start the prediction from.
    :param date_range: The number of days in the future the prediction should go on for.

    :return: A dictionary of predicted data and the corresponding dates.
    """
    LOGGER.info("Calculating next year")
    data_dict = parse_data()
    start_past_date = data_dict['x']['Organic Red Helles'][-1] - timedelta(days=364)
    dates, percent_dict = plot_growth_percent(days=days, key_name=key_name, plot=False,
                                              start_date=start_past_date)

    if dates is None:
        return None, None

    dates = [date + timedelta(days=days-1) for date in dates]
    prediction_dict = {}

    if next_year:
        dates = [date + timedelta(days=365) for date in dates]

    # Start date + date range is larger than date list
    if start_date is not None and start_date + timedelta(date_range) not in dates:
        return False, False

    for key, percent_list in percent_dict.items():
        start_sale = data_dict['y'][key][-1]

        LOGGER.debug("Multiplying rate")
        prediction_dict[key] = multiply_rate(start_sale, percent_list)

        if start_date is not None:
            index = dates.index(start_date)
            prediction_dict[key] = prediction_dict[key][index:]
        if date_range is not None:
            prediction_dict[key] = prediction_dict[key][:date_range]

    LOGGER.debug("All rates multiplied")
    if start_date is not None:
        dates = dates[index:]
    if date_range is not None:
        dates = dates[:date_range]

    return dates, prediction_dict

def get_total(start_date: datetime, date_range: datetime,
              data_tuple: Tuple[List[datetime], Dict[str, List[int]]]) -> Dict[str, int]:
    """
    This module gets the total sales in a given time period.

    :param start_date: The date to start counting the sales.
    :param date_range: The period in which to calculate the total.
    :param data_tuple: The list of dates and the dictionary which holds the sales data.

    :return:
    A dictionary containing the total for each beer.
    """
    LOGGER.info("Getting total from %s", str(start_date))
    dates, data = data_tuple
    return_dict = {}
    for key, batch in data.items():
        if start_date not in dates:
            LOGGER.warning("start date not in dates")
            return None

        index = dates.index(start_date)
        if index + date_range >= len(batch):
            LOGGER.warning("Date range out of range of batch list")
            return None

        return_dict[key] = sum(batch[index:index+date_range])
    return return_dict

if __name__ == "__main__":
    plot_past_data(key_name="Organic Pilsner")
    # plot_next_year(days=1, key_name="Organic Pilsner", next_year=False)
    # plot_growth_percent(days=7, key_name="Organic Pilsner")
    # plot_average_growths(days=3, key_name="Organic Pilsner")
    # dates, data = plot_next_year(plot=False)
    # print(get_total(datetime(2019, 12, 2), 7, dates, data))
    plt.show()


import pytest
from unittest import mock
from truco_cord.models import Suit, CardValue, Card, Deck, Turn, Game, Round
from truco_cord.exceptions import GameException

@pytest.mark.parametrize(
    "suit, suit_value", [("diamonds", 0), ("spades", 1), ("hearts", 2), ("clubs", 3)]
)
def test_suit_create(suit, suit_value):
    obj = Suit(suit)
    assert obj
    assert obj.suit == suit_value

def test_suit_invalid_suit_raises_exception():
    with pytest.raises(ValueError):
        Suit("InvalidSuit")

@pytest.mark.parametrize("suit_name", ["diamonds", "spades", "hearts", "clubs"])
def test_suit_suit_name(suit_name):
    suit = Suit(suit_name)
    assert suit.suit_name() == suit_name

def test_suit_equal_special_method():
    obj = Suit("spades")
    same_value_obj = Suit("spades")
    different_value_obj = Suit("hearts")
    different_obj = object()
    assert obj == obj
    assert obj == same_value_obj
    assert obj != different_value_obj
    assert obj != different_obj

@pytest.mark.parametrize("value", "4567QJKA23")
def test_cardvalue_create(value):
    obj = CardValue(value)
    assert obj
    assert obj.value == value

def test_cardvalue_invalid_value_raises_exception():
    with pytest.raises(ValueError):
        CardValue("InvalidValue")

def test_card_value_equal_special_method():
    obj = CardValue("A")
    same_value_obj = CardValue("A")
    different_value_obj = CardValue("7")
    different_obj = object()
    assert obj == obj
    assert obj == same_value_obj
    assert obj != different_value_obj
    assert obj != different_obj

def test_card_create(suit, card_value):
    obj = Card(suit, card_value)
    assert obj
    assert obj.suit is suit
    assert obj.card_value is card_value

def test_card_create_method():
    obj = Card.create("spades", "A")
    assert isinstance(obj, Card)
    assert obj.card_value.value == "A"
    assert obj.suit.suit_name() == "spades"

def test_card_create_raises_exception_on_invalid_suit(card_value):
    invalid_suit = object()
    with pytest.raises(TypeError):
        Card(suit=invalid_suit, value=card_value)

def test_card_create_raises_exception_on_invalid_value(suit):
    invalid_value = object()
    with pytest.raises(TypeError):
        Card(suit=suit, value=invalid_value)

def test_card_equal_special_method():
    suit = Suit("spades")
    value = CardValue("A")
    obj = Card(suit, value)
    same_value_obj = Card(suit, value)
    different_value_obj = Card(Suit("spades"), CardValue("K"))
    different_obj = object()
    assert obj == obj
    assert obj == same_value_obj
    assert obj != different_value_obj
    assert obj != different_obj

def test_card_str(card):
    expected = "A of spades"
    assert str(card) == expected

def test_card_repr(card):
    expected = "<A of spades>"
    assert card.__repr__() == expected

@mock.patch("truco_cord.models.Deck.create_cards")
def test_deck_create(create_cards_mock, card):
    create_cards_mock.return_value = [card]
    obj = Deck()

    create_cards_mock.assert_called_once()
    assert obj
    assert obj.cards == [card]
    assert obj.shuffled == False

@mock.patch.multiple("truco_cord.models.CardValue", values=["A"])
@mock.patch.multiple("truco_cord.models.Suit", suits=["spades"])
def test_deck_create_cards_specific_card():
    cards = Deck.create_cards()
    assert len(cards) == 1
    assert cards[0].card_value.value == "A"
    assert cards[0].suit.suit_name() == "spades"

def test_deck_create_cards():
    cards = Deck.create_cards()
    assert len(cards) == 40

@mock.patch("random.shuffle")
def test_deck_shuffle(shuffle_mock, deck):
    deck.shuffle()

    shuffle_mock.assert_called_once_with(deck.cards)
    assert deck.shuffled == True

def test_deck_draw_card(deck):
    last_card = deck.cards[-1]
    original_length = len(deck.cards)
    card_drawn = deck.draw_card()

    assert last_card is card_drawn
    assert len(deck.cards) == (original_length - 1)

def test_game_create():
    handler = object()
    blue_players = [object() for _ in range(2)]
    red_players = [object() for _ in range(2)]
    game = Game(handler, blue_players, red_players)

    assert game
    assert game.handler is handler
    assert game.blue_players == blue_players
    assert game.red_players == red_players
    assert game.rounds == []
    assert game.score == (0, 0)

def test_game_new_round(game):
    result = game.new_round()

    assert game.rounds == [result]
    assert isinstance(result, Round)

def test_turn_create(card):
    player = object()
    turn = Turn(player=player, card=card)

    assert turn
    assert turn.player is player
    assert turn.card == card

def test_round_create(game):
    obj = Round(game)

    assert obj
    assert obj.game == game
    assert obj.turns == []

def test_round_player_turn(round, card):
    round.validate_turn = mock.Mock()
    player = object()
    result = round.player_turn(player, card)

    round.validate_turn.assert_called_once_with(card)
    assert isinstance(result, Turn)
    assert result.card == card
    assert result.player == player
    assert round.turns == [result]

def test_round_validate_turn_raises_exception_with_repeated_card(round, card):
    round.turns = [Turn(player=object(), card=card)]
    with pytest.raises(GameException):
        round.validate_turn(card)


from django.conf.urls import url, include

from .api import UserList, UserDetail
from .api import CatList, CatDetail, UserCatList
from .api import PhotoList, PhotoDetail, CatPhotoList, UserPhotoList
from .api import api_root

user_urls = [
    url(r'^/(?P<id>\d+)/cats$', UserCatList.as_view(), name='usercat-list'),
    url(r'^/(?P<id>\d+)$', UserDetail.as_view(), name='user-detail'),
    url(r'^$', UserList.as_view(), name='user-list'),
]

cat_urls = [
    url(r'^/(?P<id>\d+)/photos$', CatPhotoList.as_view(), name='catphoto-list'),
    url(r'^/(?P<id>\d+)/photos/(?P<pk>\d+)$', CatPhotoList.as_view()),
    url(r'^/(?P<id>\d+)$', CatDetail.as_view(), name='cat_detail'),
    url(r'^$', CatList.as_view(), name='cat-list'),
]

photo_urls = [
#    url(r'^/add/(?P<cat_id>\d+)$', PhotoAdd.as_view(), name='photo-add'),
    url(r'^/(?P<user_id>\d+)/(?P<pk>\d+)$', PhotoDetail.as_view(), name='photo-detail'),
    url(r'^/(?P<user_id>\d+)$', UserPhotoList.as_view(), name='userphoto-list'),
    url(r'^$', PhotoList.as_view(), name='photo-list')
]

urlpatterns = [
    url(r'^$', api_root),
    url(r'^users', include(user_urls)),
    url(r'^cats', include(cat_urls)),
    url(r'^photos', include(photo_urls)),
]


# -*- coding: utf-8 -*-
import scrapy
import json
import re

class TgcSpider(scrapy.Spider):
    name = 'tgc'
    datas = []

    # 爬虫开始时执行，有且仅执行一次
    def start_requests(self):
        for i in range(1, 931):
            self.datas.append({
                'agent': '7',
                'spm': '407.802989.5386188.1',
                'page': str(i),
                'pageSize': '40',
            })
        for data in self.datas:
            yield scrapy.FormRequest(
                url='https://leaseconsumer.souche.com//v1/secondCarSearchApi/querySecondCarListV2.json',
                callback=self.parse, formdata=data)

    def parse(self, response):
        d = json.loads(response.body.decode('utf-8'))
        d = d['data']['items']
        for i in d:
            item = {}
            item['seriesName'] = i['seriesName']
            item['modelName'] = i['modelName']
            item['modelName'] = re.sub('\s', '', item['modelName'])
            carId = i['id']
            item['mileageStr'] = i['mileageStr']
            item['prepaidAmountStr'] = i['prepaidAmountStr']
            item['cityName'] = i['cityName']
            item['installmentStr'] = i['installmentStr']
            yield scrapy.FormRequest(url='https://leaseconsumer.souche.com//v1/followShopApi/getSecCarShopPage.json',
                                     callback=self.parse_item,
                                     formdata={'agent': '7',
                                               'spm': '407.802989.5386188.1',
                                               'page': '1',
                                               'pageSize': '1000',
                                               'carType': '1',
                                               'carId': carId, },
                                               meta={'item': item})

    def parse_item(self, response):
        item = response.meta['item']
        d = json.loads(response.body.decode('utf-8'))
        d = d['data']['items']
        for i in d:
            item['shopName'] = i['shopName']
            item['shopAddr'] = i['shopAddr']
            item['tel'] = i['contactTel']
            yield item


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 31 11:51:02 2017

@author: David Dinkevich
"""

import matplotlib.pyplot as plt

# Create a 2-dimensional array of iris characteristics
def parse_data(lines, num_lines):
    # To store each characteristic of an iris
    data = [[], [], [], [], []]
    # For each line
    for i in range(num_lines):
        # Break up the line
        line = lines[i].split(',')
        # For each list in data
        for j in range(len(data)):
            # Add each component of the line to each
            # sub-array in data
            data[j].append(line[j])
    return data

with open('iris.csv') as f:
    # Store 2d array of iris characteristics
    flowers = parse_data(f.readlines(), 40)

plt.plot(flowers[0])

plt.xlabel('Flowers (index in dataset)')
plt.ylabel('Sepal Length')
plt.title('Sepal Length of Flowes in Iris')
plt.grid(True)
plt.savefig("graph.png")
plt.show()


import json

from django.http import HttpResponse

from users.models import User

successResponseText = "УСПЕШНО: информация о Вас была сохранена на сервере"
failResponseText = "ОШИБКА: Вы ничего не прислали"

# сюда приходит информация из мобильного приложения Seffectle
def users(request):
    if request.method == 'GET':
        if not request.GET:
            # Если в Get запросе ничего не было прислано
            return HttpResponse(json.dumps(failResponseText, ensure_ascii=False))

        user_data = request.GET['data']

        user_data_dict = json.loads(user_data)
        print('Пришла такая инфа о юзере:')
        for key, value in user_data_dict.items():
            print('\t', key, ':', value)

        user_info = User()
        user_info.save_dict_to_class(user_data_dict)

        try:
            user_info = User.objects.get(vk_ID=user_info.vk_ID)
        except User.DoesNotExist:
            # если такого пользователя не было, то добавить в БД
            user_info.save()

        return HttpResponse(json.dumps(successResponseText, ensure_ascii=False))
    else:
        return HttpResponse("???")


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

import numpy as np
from sklearn import datasets

from ztlearn.utils import *
from ztlearn.dl.models import Sequential
from ztlearn.dl.optimizers import register_opt
from ztlearn.dl.layers import BatchNormalization, Dense

data = datasets.load_digits()
plot_digits_img_samples(data)

img_rows = 8
img_cols = 8
img_dim = 64  # img_rows * img_cols
latent_dim = 4
init_type = 'he_normal'

def stack_encoder_layers(init):
    model = Sequential(init_method = init)
    model.add(Dense(256, activation = 'relu', input_shape = (img_dim,)))
    model.add(BatchNormalization())
    model.add(Dense(128, activation = 'relu'))
    model.add(BatchNormalization())
    model.add(Dense(latent_dim, activation = 'relu'))

    return model

def stack_decoder_layers(init):
    model = Sequential(init_method = init)
    model.add(Dense(128, activation = 'relu', input_shape = (latent_dim,)))
    model.add(BatchNormalization())
    model.add(Dense(256, activation = 'relu'))
    model.add(BatchNormalization())
    model.add(Dense(img_dim, activation = 'sigmoid'))

    return model

encoder = stack_encoder_layers(init = init_type)
decoder = stack_decoder_layers(init = init_type)

opt = register_opt(optimizer_name = 'adam', momentum = 0.01, learning_rate = 0.0001)

autoencoder = Sequential(init_method = init_type)
autoencoder.layers.extend(encoder.layers)
autoencoder.layers.extend(decoder.layers)
autoencoder.compile(loss = 'categorical_crossentropy', optimizer = opt)

images = range_normalize(data.data.astype(np.float32), 0, 1)  # rescale to range [0, 1]
train_data, test_data, train_label, test_label = train_test_split(images,
                                                                  images,
                                                                  test_size = 0.2,
                                                                  random_seed = 15)

model_epochs = 500
fit_stats = autoencoder.fit(train_data,
                            train_label,
                            batch_size = 64,
                            epochs = model_epochs,
                            validation_data = (test_data, test_label),
                            shuffle_data = True)

# generate non rescaled test labels for use in generated digits plot
_, _, _, test_label = train_test_split(data.data, data.target, test_size = 0.2, random_seed = 15)
predictions = autoencoder.predict(test_data).reshape((-1, img_rows, img_cols))

plot_generated_digits_samples(unhot(one_hot(test_label)), predictions)
plot_metric('Loss', model_epochs, fit_stats['train_loss'], fit_stats['valid_loss'])
plot_metric('Accuracy', model_epochs, fit_stats['train_acc'], fit_stats['valid_acc'])


# -*- coding: utf-8 -*-
import scrapy
from scrapy_splash import SplashRequest
from ..items import QunarCrawlItem
import re

class QunarFinSpider(scrapy.Spider):
    name = 'qunar_fin'
    allowed_domains = ['qunar.com']
    start_urls = ['https://train.qunar.com/stationToStation.htm?fromStation=%E4%B8%8A%E6%B5%B7&toStation=%E5%8C%97%E4%BA%AC&date=2017-11-11&drainage=']

    script = """
        function main(splash)
            assert(splash:go(splash.args.url))
            splash:wait(3)
            return splash:html()
        end
    """

    tackle_method = {
        1: 'self.get_train_code',
        2: 'self.get_start_end_station',
        3: 'self.get_start_end_time',
        4: 'self.get_duration',
        5: 'self.get_site_info',
        6: 'self.get_rest_tickets',
    }

    site_info = {
        1: ['sit_1', 'price_1', 'rest_ticket_1'],
        2: ['sit_2', 'price_2', 'rest_ticket_2'],
        3: ['sit_3', 'price_3', 'rest_ticket_3'],
        4: ['sit_4', 'price_4', 'rest_ticket_4'],
        5: ['sit_5', 'price_5', 'rest_ticket_5'],
    }

    link_pattern = re.compile(r'https://.*?drainage=')

    def start_requests(self):
        """处理处理url"""
        for url in self.start_urls:
            yield SplashRequest(url, self.parse_link, endpoint='execute',
                                args={'lua_source':self.script})

    def parse_link(self, response):
        link_list = self.link_pattern.finditer(response.body.decode())
        for link in link_list:
            link = re.sub(r'amp;', '', link.group())
            yield SplashRequest(link, self.parse_content, args={'lua_source': self.script},
                                endpoint='execute')

    def parse_content(self, response):
        """获取内容"""
        info_list = response.xpath('//ul[@class="tbody"]/li')
        date = re.search(r'(?<=date=)((.*)?)&', response.url).group(2)
        for info in info_list:
            item = QunarCrawlItem()
            item['date'] = date
            self.assignment(info, item)
            yield item

    def assignment(self, info, item):
        """任务分派"""
        task_list = info.xpath('./div/div')
        for index, task in enumerate(task_list[:6], 1):
            # self.get_train_code()
            eval(self.tackle_method[index])(task, item)

    def get_train_code(self, task, item):
        """获取火车号"""
        item['code'] = task.xpath('./h3/text()').extract_first().strip()

    def get_start_end_station(self, task, item):
        """获取起始站"""
        item['start_station'] = task.xpath('./p[@class="start"]/span/text()').extract_first().strip()
        item['end_station'] = task.xpath('./p[@class="end"]/span/text()').extract_first().strip()

    def get_start_end_time(self, task, item):
        """获取出发时间和到达时间"""
        item['start_time'] = task.xpath('./time[@class="startime"]/text()').extract_first().strip()
        item['end_time'] = task.xpath('./time[@class="endtime daytime"]/text()').extract_first().strip()

    def get_duration(self, task, item):
        """获取所需时间"""
        item['duration'] = task.xpath(r'./time/text()').extract_first()

    def get_site_info(self, task, item):
        """获取座位信息"""
        sit_info_list = task.xpath('./p')
        for index, sit_info in enumerate(sit_info_list, 1):
            which_site = self.site_info[index]
            item[which_site[0]] = sit_info.xpath('./text()').extract_first().strip()
            item[which_site[1]] = '¥' + sit_info.xpath('./span/text()').extract_first()

    def get_rest_tickets(self, task, item):
        """获取剩余票数"""
        ticket_info_list = task.xpath('./p')
        for index, ticket_info in enumerate(ticket_info_list, 1):
            which_site = self.site_info[index]
            try:
                item[which_site[2]] = ticket_info.xpath('./text()').extract()[0]
            except:
                item[which_site[2]] = None


import torch
from abc import ABC, abstractmethod

class BaseModelConstructor:
    """
    This class is an abstract base class (ABC) for models
    """
    def __init__(self, opts):
        self.opts = opts
        self.model_name = opts.model_name
        self.model_object = opts.model_object
        self.input_size = opts.input_size

    def __str__(self):
        return str(self.opts)

    @abstractmethod
    def create(self, num_classes):
        """
        gather the informations from self and return the model
        :return: model object
        """
        pass

    @staticmethod
    def load_checkpoint(model, checkpoint):
        """
        :param model: pytorch model object
        :param checkpoint: checkpoint path
        :return: model.
        """
        checkpoint = torch.load(checkpoint, map_location="cpu")

        # Check the checkpoint object is Dataparallel module or not
        checkpoint_keys = [key for key in checkpoint.keys()]

        if "module" == checkpoint_keys[0][:6]:
            # If Dataparallel module use,
            # the model architecture and weights are registered as
            # "module" instance of the Dataparalle module.
            print("{} was saved as torch.nn.Dataparallel module.")
            for key in checkpoint_keys:
                checkpoint[key[7:]] = checkpoint.pop(key)

        model.load_state_dict(checkpoint)
        return model

def check_model_information(model_constructor_object):
    """
    Check the where modules models constructor objects come from.
    :param model_constructor_object
    :return: <str>
    # Cadene's pretrained-models
        # https://github.com/Cadene/pretrained-models.pytorch
        # Cadene's modules supports imagenet when defining function.
        # pretrained argument must be "imagenet"
    # Torchvision model
        # pretrained argument must be False or True.
        "spark" : models comes from spark.
        pretrained argument at SLMCModelConsturctor must be imagenet or pth path.

        "unknow" :  Unknown or User-defined Model.
                    Only supports on pth weight file.
    """
    package_source = model_constructor_object.__globals__["__package__"].split(".")[0]
    if package_source == "pretrainedmodels":
        return "pretrainedmodels"
    elif package_source == "torchvision":
        return "torchvision"
    elif package_source == "spark":
        return "spark"
    else:
        return "unknown"


import os
from cffi import FFI

ffibuilder = FFI()

ffibuilder.set_source(
    "grblas.backends.suitesparse._suitesparse_grblas",
    r"""#include "GraphBLAS.h" """,
    libraries=["graphblas"],
)

thisdir = os.path.dirname(__file__)

gb_cdef = open(os.path.join(thisdir, "suitesparse_graphblas_3.3.3.h"))

ffibuilder.cdef(gb_cdef.read())

if __name__ == "__main__":
    ffibuilder.compile(verbose=True)


from __future__ import print_function

import tensorflow as tf
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Flatten
from keras.optimizers import RMSprop

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

print('tensorflow:', tf.__version__)
print('keras:', keras.__version__)

#load (first download if necessary) the MNIST dataset
# (the dataset is stored in your home direcoty in ~/.keras/datasets/mnist.npz
#  and will take  ~11MB)
# data is already split in train and test datasets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# x_train : 60000 images of size 28x28, i.e., x_train.shape = (60000, 28, 28)
# y_train : 60000 labels (from 0 to 9)
# x_test  : 10000 images of size 28x28, i.e., x_test.shape = (10000, 28, 28)
# x_test  : 10000 labels
# all datasets are of type uint8

#To input our values in our network Conv2D layer, we need to reshape the datasets, i.e.,
# pass from (60000, 28, 28) to (60000, 28, 28, 1) where 1 is the number of channels of our images
img_rows, img_cols = x_train.shape[1], x_train.shape[2]
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)

#Convert to float
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')

#Normalize inputs from [0; 255] to [0; 1]
x_train = x_train / 255
x_test = x_test / 255

print('x_train.shape=', x_train.shape)
print('x_test.shape=', x_test.shape)
print('y_train.shape=', y_train.shape)
print('y_test.shape=', y_test.shape)

num_classes = 10
epochs = 1
batch_size = 64
filters = 64

#Convert class vectors to binary class matrices ("one hot encoding")
## Doc : https://keras.io/utils/#to_categorical
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# num_classes is computed automatically here
# but it is dangerous if y_test has not all the classes
# It would be better to pass num_classes=np.max(y_train)+1

#Let start our work: creating a convolutional neural network

# creation du modele
model = Sequential()

# ajout des couches
model.add(Conv2D(filters, kernel_size=(3,3), strides=1, padding='same', activation='relu'))
model.add(Conv2D(filters, kernel_size=(3,3), strides=1, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(num_classes, activation='softmax'))

# compiler le modele
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # multiclass

# entrainer le reseau
hist = model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_data=(x_test, y_test))

# evaluer le modele
score = model.evaluate(x_test, y_test)
print('Score apres' , epochs, 'epochs =', score)

plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.title('model loss')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

# utilisation du modele
y = model.predict(x_test)

# comparaison des resultats uniquement sur la classe valide
y_err1 = y * y_test

# comparaison des resultats sur les 10 classes
y_err2 = np.absolute(y - y_test);

# sommes des resultats des comparaisons
y_err1 = np.sum(y_err1, axis=1)
y_err2 = np.sum(y_err2, axis=1)

# tris des comparaisons
y_err1_sorted = np.argsort(y_err1)
y_err2_sorted = np.argsort(y_err2)

# Affichage des 10 images les moins bien classees

for i in range(10) :
  plt.imshow(x_test[y_err1_sorted[i],:].reshape(28, 28), cmap = matplotlib.cm.binary)
  plt.axis("off")
  plt.show()


import numpy as np
import random
import tensorflow as tf
from tqdm import trange

# tf.keras.mixed_precision.experimental.set_policy('mixed_float16')

class QNetwork():
    def __init__(self, state_dim):
        self.model = tf.keras.Sequential([
            tf.keras.layers.Input(state_dim),
            tf.keras.layers.Dense(64, activation='relu'),
            tf.keras.layers.Dense(64, activation='relu'),
            tf.keras.layers.Dense(2, activation='linear')
        ])
        self.loss = tf.keras.losses.MeanSquaredError()
        self.optimizer = tf.keras.optimizers.SGD(learning_rate=0.2)

    def predict(self, state):
        if state.ndim == 1:
            state = np.expand_dims(state, axis=0)
        return self.model(state)

    def train(self, experiences, gamma):
        states = np.stack(experiences[:, 0])
        actions = experiences[:, 1]
        rewards = experiences[:, 2]
        states_next = np.stack(experiences[:, 3])
        terminals = experiences[:, 4]

        q_next = self.predict(states_next)
        q_expected = rewards + (1 - terminals) * \
            gamma * np.max(q_next, axis=1)
        with tf.GradientTape() as tape:
            q = self.predict(states)
            q_train = np.copy(q)
            for i, action in enumerate(actions):
                q_train[i][action] = q_expected[i]

            loss = self.loss(q, q_train)
            grads = tape.gradient(loss, self.model.trainable_variables)
            self.optimizer.apply_gradients(
                zip(grads, self.model.trainable_variables))

class ReplayBuffer():
    def __init__(self, size=5000):
        self.buffer = []
        self.size = size

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

    def add(self, experiences):
        new_size = len(self.buffer) + len(experiences)
        if new_size > self.size:
            del self.buffer[0:new_size-self.size]
        self.buffer.extend(experiences)
        assert len(self.buffer) <= self.size

    def sample(self, n):
        return np.array(random.sample(self.buffer, n))

class DqnAgent():
    def __init__(self, env, state_dim, action_space):
        self.state_dim = state_dim
        self.action_space = action_space
        self.epsilon = 0.2
        self.gamma = 1.

        self.env = env
        self.q_network = QNetwork(state_dim)
        self.replay_buffer = ReplayBuffer()

    def get_action(self, state, explore=True):
        if explore and np.random.rand() < self.epsilon:
            return np.random.randint(self.action_space)
        q_values = self.q_network.predict(state)
        return np.argmax(q_values[0])

    def train(self, n_episodes, n_batch_size, t_train_interval):
        for t in trange(n_episodes, desc='Training', ncols=100):
            state = self.env.reset()
            terminal = False

            episode = []
            while not terminal:
                action = self.get_action(state)
                state_next, reward, terminal = self.env.step(action)
                episode.append(
                    np.array([state, action, reward, state_next, terminal]))
                state = state_next
            self.replay_buffer.add(episode)

            if t % t_train_interval == 0 and len(self.replay_buffer) >= n_batch_size:
                batch = self.replay_buffer.sample(n_batch_size)
                self.q_network.train(batch, self.gamma)

    def test(self, n_episodes):
        rewards = []
        for _ in trange(n_episodes, desc='Testing', ncols=100):
            state = self.env.reset()
            terminal = False
            cummulative_reward = 0

            while not terminal:
                action = self.get_action(state, explore=False)
                state, reward, terminal = self.env.step(action)
                cummulative_reward += reward

            rewards.append(cummulative_reward)
        return np.mean(rewards)


"""
 DefendersGame
 Kevin Chen
 Version 1.0
 This code opens up a game where you control a player block with the mouse.
 The goal is to score as many points as possible.
 Blue blocks add 1 point, red blocks deduct 1 point,
 and purple blocks reset your score to 0 AND sets your lives to 1, so be careful.
 Mouseclick or press the space key to shoot a bullet.
"""
import pygame
import random
import time

# Define some colors
from pygame import mixer

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (250, 238, 3)
PURPLE = (135, 3, 250)
BACKGROUND = (239, 229, 255)
# --- extra functions
FALL_SPEED = 1
MOVING_SPEED = 10
lives = 3

# --- Classes

class Block(pygame.sprite.Sprite):
    """ This class represents the blocks. """

    def __init__(self, color):
        # Call the parent class (Sprite) constructor
        super(Block, self).__init__()

        self.image = pygame.Surface([30, 15])
        self.image.fill(color)

        self.rect = self.image.get_rect()
        self.rect.x = 0
        self.rect.y = 0

class Player(pygame.sprite.Sprite):
    """ This class represents the Player. """

    def __init__(self):
        """ Set up the player on creation. """
        # Call the parent class (Sprite) constructor
        super(Player, self).__init__()

        self.image = pygame.Surface([20, 20])
        self.image.fill(BLACK)

        self.rect = self.image.get_rect()

    def update(self):
        """ Update the player's position. """
        # Get the current mouse position. This returns the position
        # as a list of two numbers.
        pos = pygame.mouse.get_pos()

        # Set the player x position to the mouse x position and sets bounds
        if pos[0] < 0:
            self.rect.x = 0
        elif pos[0] > 680:
            self.rect.x = 680
        else:
            self.rect.x = pos[0]

class Bullet(pygame.sprite.Sprite):
    """ This class represents the bullet. """

    def __init__(self):
        # Call the parent class (Sprite) constructor
        super(Bullet, self).__init__()

        self.image = pygame.Surface([4, 10])
        self.image.fill(BLACK)

        self.rect = self.image.get_rect()

    def update(self):
        """ Move the bullet. """
        self.rect.y -= 5

# Initialize Pygame and sound
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load("bgm.ogg")

# Set the height and width of the screen
screen_width = 700
screen_height = 500
screen = pygame.display.set_mode([screen_width, screen_height])
# --- Sprite lists

# This is a list of every sprite. All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()

# List of good sprites in the game
good_blocks_list = pygame.sprite.Group()

# List of each bullet
bullet_list = pygame.sprite.Group()

# List of bad sprites
bad_blocks_list = pygame.sprite.Group()

# List of super sprites
god_blocks_list = pygame.sprite.Group()
mad_blocks_list = pygame.sprite.Group()
# --- Create the sprites

for i in range(40):
    # This represents a mad block
    madblock = Block(PURPLE)

    # Set a random location for the block
    madblock.rect.x = random.randrange(0, 670)
    madblock.rect.y = random.randrange(-4000, -800)

    # Add the block to the list of objects
    mad_blocks_list.add(madblock)
    all_sprites_list.add(madblock)

for i in range(4):
    # This represents a god block
    godblock = Block(YELLOW)

    # Set a random location for the block
    godblock.rect.x = random.randrange(0, 670)
    godblock.rect.y = random.randrange(-15000, -3000)

    # Add the block to the list of objects
    god_blocks_list.add(godblock)
    all_sprites_list.add(godblock)

for i in range(120):
    # This represents a good block
    goodblock = Block(BLUE)

    # Set a random location for the block
    goodblock.rect.x = random.randrange(0, 670)
    goodblock.rect.y = random.randrange(-5500, 200)

    # Add the block to the list of objects
    good_blocks_list.add(goodblock)
    all_sprites_list.add(goodblock)

for i in range(80):
    # This represents a bad block
    badblock = Block(RED)

    # Set a random location for the block
    badblock.rect.x = random.randrange(0, 670)
    badblock.rect.y = random.randrange(-5500, 200)

    # Add the block to the list of objects
    bad_blocks_list.add(badblock)
    all_sprites_list.add(badblock)

# Create a black player block
player = Player()
all_sprites_list.add(player)

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

score = 0

print("Welcome to the Defenders game!")
print("The goal is to get as many points as possible before you run out of lives.")
print("You have 3 lives. Don't let the blue blocks reach the bottom!")
print("Use the mouse to control your position, and mouseclick or press the space key to fire a bullet!")
print("Avoid hitting red and purple blocks!")
time.sleep(4)
print("Get ready!")
time.sleep(1)
print("Game starts in 3...")
time.sleep(1)
print("2...")
time.sleep(1)
print("1...")
time.sleep(1)
pygame.mixer.music.play(-1)
done = False

# helper function to make a new block
def makenewblock(colour):
    newblock = Block(colour)
    newblock.rect.x = random.randrange(0, 670)
    newblock.rect.y = random.randrange(-5500, -15)
    all_sprites_list.add(newblock)
    return newblock

# -------- Main Program Loop -----------

while not done:
    # --- Event Processing

    for badblock in bad_blocks_list:
        badblock.rect.y += FALL_SPEED

    for goodblock in good_blocks_list:
        goodblock.rect.y += FALL_SPEED

    for godblock in god_blocks_list:
        godblock.rect.y += FALL_SPEED * 2
        godblock.rect.x += MOVING_SPEED * 3

    for madblock in mad_blocks_list:
        madblock.rect.y += FALL_SPEED
        madblock.rect.x += MOVING_SPEED

    for Player in all_sprites_list:
        player.rect.y = 480

    # Loop until the user clicks the close button.
    for event in pygame.event.get():
        pygame.key.set_repeat(0)
        key_press = pygame.key.get_pressed()
        if event.type == pygame.QUIT:
            done = True

        elif event.type == pygame.MOUSEBUTTONDOWN or key_press[pygame.K_SPACE]:
            # Fire a bullet if the user clicks the mouse button or space key
            bullet = Bullet()
            # Set the bullet so it is where the player is
            bullet.rect.x = player.rect.x + 8
            bullet.rect.y = player.rect.y
            # Add the bullet to the lists
            all_sprites_list.add(bullet)
            bullet_list.add(bullet)

        # Does same thing as above, except mouse can be held down for rapid fire
        # elif pygame.mouse.get_pressed()[0] or key_press[pygame.K_SPACE]:
        #     # Fire a bullet if the user clicks the mouse button or space key
        #     bullet = Bullet()
        #     # Set the bullet so it is where the player is
        #     bullet.rect.x = player.rect.x + 8
        #     bullet.rect.y = player.rect.y
        #     # Add the bullet to the lists
        #     all_sprites_list.add(bullet)
        #     bullet_list.add(bullet)

    # --- Game logic
    for madblock in mad_blocks_list:
        if madblock.rect.x >= 670:
            MOVING_SPEED = -5
        elif madblock.rect.x <= 0:
            MOVING_SPEED = 5

    for godblock in god_blocks_list:
        if godblock.rect.x >= 680:
            MOVING_SPEED = -5
        elif godblock.rect.x <= 0:
            MOVING_SPEED = 5
    # Call the update() method on all the sprites
    all_sprites_list.update()

    # Calculate mechanics for each bullet
    for bullet in bullet_list:

        # See if it hit a block
        good_block_hitlist = pygame.sprite.spritecollide(bullet, good_blocks_list, True)
        bad_block_hitlist = pygame.sprite.spritecollide(bullet, bad_blocks_list, True)
        god_block_hitlist = pygame.sprite.spritecollide(bullet, god_blocks_list, True)
        mad_block_hitlist = pygame.sprite.spritecollide(bullet, mad_blocks_list, True)
        # For each block hit, remove the bullet and add to the score
        for block in good_block_hitlist:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            score += 1
            print("You gained a point!")
            good_blocks_list.add(makenewblock(BLUE))

        for block in bad_block_hitlist:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            score -= 1
            print("You lost a point!")
            bad_blocks_list.add(makenewblock(RED))

        for block in god_block_hitlist:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            god_blocks_list.remove(block)
            score += 50
            lives += 3
            FALL_SPEED = 0
            print("WOW!! YOU HIT THE SECRET BLOCK!!")
            time.sleep(1)
            print("You gained 50 points and 3 lives!!")
            time.sleep(2)
            print("Well done! Game resumes in 3...")
            time.sleep(1)
            print("2...")
            time.sleep(1)
            print("1...")
            time.sleep(1)
            FALL_SPEED = 1

        for block in mad_block_hitlist:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            mad_blocks_list.add(makenewblock(PURPLE))
            score = 0
            lives = 1
            print("You hit an evil block!!")
            print("Your score was reset and you have 1 life left.")
            print("Be careful!")

        # Remove the bullet if it flies up off the screen
        if bullet.rect.y < -10:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)

    # --- Check if blocks went off the screen

    # Check if good block went off the screen
    for goodblock in good_blocks_list:
        if goodblock.rect.y >= 500:
            pygame.mixer.pause()
            good_blocks_list.remove(goodblock)
            all_sprites_list.remove(goodblock)
            lives -= 1
            if lives <= 0:
                pygame.mixer.music.stop()
                print("Game over.. you have no lives left!")
                time.sleep(1)
                print("Your final score is " + str(score) + ". Good game!")
                done = True
            else:
                FALL_SPEED = 0
                print("You lost a life!")
                time.sleep(2)
                if lives >= 2:
                    print("You have " + str(lives) + " lives left.")
                    time.sleep(1.5)
                else:
                    print("You have " + str(lives) + " life left.")
                    time.sleep(1.5)
                    print("Be careful!")
                    time.sleep(1)
                print("Resetting board...")
                for block in all_sprites_list:
                    block.rect.y -= 500
                    block.rect.x = random.randrange(20, 680)
                time.sleep(1.5)
                print("Resuming in 3...")
                time.sleep(1)
                print("2...")
                time.sleep(1)
                print("1...")
                time.sleep(1)
                pygame.mixer.music.unpause()
                FALL_SPEED = 1

    # Check if bad block went off the screen
    for badblock in bad_blocks_list:
        if badblock.rect.y >= 500:
            # Reset random location for the bad block
            badblock.rect.x = random.randrange(20, 680)
            badblock.rect.y = random.randrange(-5000, 0)

    # Check if god block went off the screen
    for godblock in god_blocks_list:
        if godblock.rect.y >= 500:
            # Delete god block
            god_blocks_list.remove(godblock)
            all_sprites_list.remove(godblock)

    # Check if mad block went off the screen
    for madblock in mad_blocks_list:
        if madblock.rect.y >= 500:
            # Reset random location for the bad block
            madblock.rect.x = random.randrange(20, 680)
            madblock.rect.y = random.randrange(-2500, -200)

    # Clear the screen
    screen.fill(BACKGROUND)

    # Draw all the sprites
    all_sprites_list.draw(screen)

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 20 frames per second
    clock.tick(60)

pygame.quit()


import os
import cherrypy
import mako.lookup

class TemplateTool(cherrypy.Tool):

    _engine = None
    '''Mako lookup instance'''

    def __init__(self, path):
        viewPath = os.path.join(path, 'static')
        self._engine = mako.lookup.TemplateLookup(directories=[viewPath])

        cherrypy.Tool.__init__(self, 'before_handler', self.render)

    def __call__(self, *args, **kwargs):
        if args and isinstance(args[0], (types.FunctionType, types.MethodType)):
            # @template
            args[0].exposed = True
            return cherrypy.Tool.__call__(self, **kwargs)(args[0])
        else:
            # @template()
            def wrap(f):
                f.exposed = True
                return cherrypy.Tool.__call__(self, *args, **kwargs)(f)
            return wrap

    def render(self, name=None):
        cherrypy.request.config['template'] = name

        handler = cherrypy.serving.request.handler

        def wrap(*args, **kwargs):
            return self._render(handler, *args, **kwargs)
        cherrypy.serving.request.handler = wrap

    def _render(self, handler, *args, **kwargs):
        template = cherrypy.request.config['template']
        if not template:
            parts = []
            if hasattr(handler.callable, '__self__'):
                parts.append(handler.callable.__self__.__class__.__name__.lower())
            if hasattr(handler.callable, '__name__'):
                parts.append(handler.callable.__name__.lower())
            template = '/'.join(parts)

        data = handler(*args, **kwargs) or {}
        renderer = self._engine.get_template('{}'.format(template))

        return renderer.render(**data)


from flask import Blueprint, jsonify
from flask import current_app as app

blueprint_api = Blueprint('doggy_api', __name__)

@blueprint_api.route('/list', methods=['GET'])
def get_list():
    data = [{ 'name': 'dog_aaa' }, { 'name': 'dog_bbb' }]
    app.logger.info('API_list called, will return %d objects', len(data))
    return jsonify(data)

@blueprint_api.route('/count', methods=['GET'])
def get_count():
    data = { 'count': 10 }
    return jsonify(data)


import cv2
import numpy as np

image=cv2.imread('test.png',1)

cv2.imshow('test',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

class imageOutput():
    def __init__(self,image):
        self.image = image
        self.lsb = []
        self.message=''

    def lsbHolder(self,shape):
        lsbbyte=[]
        for i in range(shape[0]):
            for j in range(shape[1]):
                for k in range(shape[2]):
                    if(self.image[i][j][k]>253):
                        self.lsb.append([self.image[i][j][k],i,j,k])
        for i in range(len(self.lsb)):
            lsbbyte.append("{0:b}".format(self.lsb[i][0]))
        return lsbbyte

    def decoder(self,lists):
        st=''
        z=0
        for i in range(len(lists)):
            st+= lists[i][7]
        for i in range(len(st)):
            z+= int(st[i])*(2**(len(st)-i-1))
        return z

    def result(self,z):
        self.message += chr(z)

obj = imageOutput(image)                                  #creating object

lsb = obj.lsbHolder(list(image.shape))                    #getting all pixel bytes >253

for i in range(0,len(lsb),8):
    z=obj.decoder(lsb[i:i+8])                             #decodes the message present in image
    if(z==32 or (z>64 and z<90) or (z>96 and z<123) ):
        obj.result(z)
    else:
        break

print(obj.message)


#**********************************************************************
# Copyright 2020 Advanced Micro Devices, Inc
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#********************************************************************
import MaterialX as mx

import bpy
from bpy_extras.io_utils import ExportHelper

from . import HdUSD_Panel, HdUSD_ChildPanel, HdUSD_Operator
from ..mx_nodes.node_tree import MxNodeTree

class HDUSD_MATERIAL_PT_context(HdUSD_Panel):
    bl_label = ""
    bl_context = "material"
    bl_options = {'HIDE_HEADER'}

    @classmethod
    def poll(cls, context):
        if context.active_object and context.active_object.type == 'GPENCIL':
            return False
        else:
            return (context.material or context.object) and super().poll(context)

    def draw(self, context):
        layout = self.layout

        material = context.material
        object = context.object
        slot = context.material_slot
        space = context.space_data

        if object:
            is_sortable = len(object.material_slots) > 1
            rows = 1
            if is_sortable:
                rows = 4

            row = layout.row()

            row.template_list("MATERIAL_UL_matslots", "", object, "material_slots", object,
                              "active_material_index", rows=rows)

            col = row.column(align=True)
            col.operator("object.material_slot_add", icon='ADD', text="")
            col.operator("object.material_slot_remove", icon='REMOVE', text="")

            col.menu("MATERIAL_MT_context_menu", icon='DOWNARROW_HLT', text="")

            if is_sortable:
                col.separator()

                col.operator("object.material_slot_move", icon='TRIA_UP', text="").direction = 'UP'
                col.operator("object.material_slot_move", icon='TRIA_DOWN', text="").direction = 'DOWN'

            if object.mode == 'EDIT':
                row = layout.row(align=True)
                row.operator("object.material_slot_assign", text="Assign")
                row.operator("object.material_slot_select", text="Select")
                row.operator("object.material_slot_deselect", text="Deselect")

        split = layout.split(factor=0.65)

        if object:
            split.template_ID(object, "active_material", new="material.new")
            row = split.row()

            if slot:
                row.prop(slot, "link", text="")
            else:
                row.label()
        elif material:
            split.template_ID(space, "pin_id")
            split.separator()

class HDUSD_MATERIAL_PT_preview(HdUSD_Panel):
    bl_label = "Preview"
    bl_context = "material"
    bl_options = {'DEFAULT_CLOSED'}

    @classmethod
    def poll(cls, context):
        return context.material and super().poll(context)

    def draw(self, context):
        self.layout.template_preview(context.material)

class HDUSD_MATERIAL_OP_new_mx_node_tree(bpy.types.Operator):
    """Create new MaterialX node tree for selected material"""
    bl_idname = "hdusd.material_new_mx_node_tree"
    bl_label = "New"

    def execute(self, context):
        mat = context.material
        mx_node_tree = bpy.data.node_groups.new(f"MX_{mat.name}", type=MxNodeTree.bl_idname)
        mx_node_tree.create_basic_nodes(
            'RPR_rpr_uberv2' if context.scene.hdusd.use_rpr_mx_nodes else 'PBR_standard_surface')

        mat.hdusd.mx_node_tree = mx_node_tree
        return {"FINISHED"}

class HDUSD_MATERIAL_OP_link_mx_node_tree(bpy.types.Operator):
    """Link MaterialX node tree to selected material"""
    bl_idname = "hdusd.material_link_mx_node_tree"
    bl_label = ""

    mx_node_tree_name: bpy.props.StringProperty(default="")

    def execute(self, context):
        context.material.hdusd.mx_node_tree = bpy.data.node_groups[self.mx_node_tree_name]
        return {"FINISHED"}

class HDUSD_MATERIAL_OP_unlink_mx_node_tree(bpy.types.Operator):
    """Unlink MaterialX node tree from selected material"""
    bl_idname = "hdusd.material_unlink_mx_node_tree"
    bl_label = ""

    def execute(self, context):
        context.material.hdusd.mx_node_tree = None
        return {"FINISHED"}

class HDUSD_MATERIAL_MT_mx_node_tree(bpy.types.Menu):
    bl_idname = "HDUSD_MATERIAL_MT_mx_node_tree"
    bl_label = "MX Nodetree"

    def draw(self, context):
        layout = self.layout
        node_groups = bpy.data.node_groups

        for ng in node_groups:
            if ng.bl_idname != 'hdusd.MxNodeTree':
                continue

            row = layout.row()
            row.enabled = bool(ng.output_node)
            op = row.operator(HDUSD_MATERIAL_OP_link_mx_node_tree.bl_idname,
                              text=ng.name, icon='MATERIAL')
            op.mx_node_tree_name = ng.name

class HDUSD_MATERIAL_PT_material(HdUSD_Panel):
    bl_label = ""
    bl_context = "material"

    @classmethod
    def poll(cls, context):
        return context.material and super().poll(context)

    def draw(self, context):
        mat_hdusd = context.material.hdusd
        layout = self.layout

        split = layout.row(align=True).split(factor=0.4)
        col = split.column()
        col.alignment = 'RIGHT'
        col.label(text="MaterialX")
        col = split.column()
        row = col.row(align=True)
        col1 = row.column()
        col1.enabled = any(ng.bl_idname == 'hdusd.MxNodeTree' for ng in bpy.data.node_groups)
        col1.menu(HDUSD_MATERIAL_MT_mx_node_tree.bl_idname, text="", icon='MATERIAL')

        if mat_hdusd.mx_node_tree:
            row.prop(mat_hdusd.mx_node_tree, 'name', text="")
            row.operator(HDUSD_MATERIAL_OP_unlink_mx_node_tree.bl_idname, icon='X')

        else:
            row.operator(HDUSD_MATERIAL_OP_new_mx_node_tree.bl_idname, icon='ADD')

    def draw_header(self, context):
        layout = self.layout
        layout.label(text=f"Material: {context.material.name}")

class HDUSD_MATERIAL_PT_output_node(HdUSD_ChildPanel):
    bl_label = ""
    bl_parent_id = 'HDUSD_MATERIAL_PT_material'

    @classmethod
    def poll(cls, context):
        return not bool(context.material.hdusd.mx_node_tree)

    def draw(self, context):
        layout = self.layout

        node_tree = context.material.node_tree

        output_node = context.material.hdusd.output_node
        if not output_node:
            layout.label(text="No output node")
            return

        input = output_node.inputs[self.bl_label]
        layout.template_node_view(node_tree, output_node, input)

class HDUSD_MATERIAL_PT_output_surface(HDUSD_MATERIAL_PT_output_node):
    bl_label = "Surface"

class HDUSD_MATERIAL_PT_output_displacement(HDUSD_MATERIAL_PT_output_node):
    bl_label = "Displacement"
    bl_options = {'DEFAULT_CLOSED'}

class HDUSD_MATERIAL_PT_output_volume(HDUSD_MATERIAL_PT_output_node):
    bl_label = "Volume"
    bl_options = {'DEFAULT_CLOSED'}

class HDUSD_MATERIAL_OP_export_mx_file(HdUSD_Operator, ExportHelper):
    bl_idname = "hdusd.material_export_mx_file"
    bl_label = "MaterialX Export to File"
    bl_description = "Export material as MaterialX node tree to .mtlx file"

    filename_ext = ".mtlx"
    filepath: bpy.props.StringProperty(
        name="File Path",
        description="File path used for exporting material as MaterialX node tree to .mtlx file",
        maxlen=1024, subtype="FILE_PATH"
    )
    filter_glob: bpy.props.StringProperty(default="*.mtlx", options={'HIDDEN'}, )

    def execute(self, context):
        doc = context.material.hdusd.export(context.object)
        if not doc:
            return {'CANCELLED'}

        mx.writeToXmlFile(doc, self.filepath)
        return {'FINISHED'}

class HDUSD_MATERIAL_OP_export_mx_console(HdUSD_Operator):
    bl_idname = "hdusd.material_export_mx_console"
    bl_label = "MaterialX Export to Console"
    bl_description = "Export material as MaterialX node tree to console"

    def execute(self, context):
        doc = context.material.hdusd.export(context.object)
        if not doc:
            return {'CANCELLED'}

        print(mx.writeToXmlString(doc))
        return {'FINISHED'}

class HDUSD_MATERIAL_PT_export_mx(HdUSD_Panel):
    bl_label = "MaterialX Export"
    bl_space_type = "NODE_EDITOR"
    bl_region_type = "UI"
    bl_category = "Tool"

    @classmethod
    def poll(cls, context):
        tree = context.space_data.edit_tree
        return super().poll(context) and tree and \
               tree.bl_idname == bpy.types.ShaderNodeTree.__name__

    def draw(self, context):
        layout = self.layout

        layout.operator(HDUSD_MATERIAL_OP_export_mx_file.bl_idname)
        layout.operator(HDUSD_MATERIAL_OP_export_mx_console.bl_idname)

def depsgraph_update(depsgraph):
    context = bpy.context
    mx_node_tree = None
    if context.object and context.object.active_material:
        mx_node_tree = context.object.active_material.hdusd.mx_node_tree

    # trying to show MaterialX area with node tree or Shader area
    screen = context.screen
    if mx_node_tree:
        for area in screen.areas:
            if area.ui_type not in ('hdusd.MxNodeTree', 'ShaderNodeTree'):
                continue

            area.ui_type = 'hdusd.MxNodeTree'
            space = next(s for s in area.spaces if s.type == 'NODE_EDITOR')
            space.node_tree = mx_node_tree

    else:
        for area in screen.areas:
            if area.ui_type != 'hdusd.MxNodeTree':
                continue

            area.ui_type = 'ShaderNodeTree'


# By: Riasat Ullah
# This file contains the variables that will be used for testing.

from objects.assignee import Assignee
from objects.events import AcknowledgeEvent, DispatchEvent, EscalateEvent
from objects.group import Group
from objects.group_level import GroupLevel
from objects.group_rotation import GroupRotation
from objects.group_routine import GroupRoutine
from objects.instance_state import InstanceState
from objects.policy import GroupPolicy, UserPolicy
from objects.task import Task
from objects.user import User
from utils import constants, times, var_names
import datetime

# User variables
correct_username = 'testuser_one'
correct_first_name = 'John'
correct_last_name = 'Smith'
correct_email = 'john.smith@gmail.com'
correct_country_code = 1
correct_phone = '3152624399'
correct_birth_year = 1994
correct_birth_month = 5
correct_birth_day = 17
correct_verified = True
correct_account_type = constants.personal
correct_policy_id = 3

correct_user = User(correct_username, correct_first_name, correct_last_name,
                    correct_email, correct_country_code, correct_phone,
                    correct_birth_year, correct_birth_month, correct_birth_day,
                    correct_verified, correct_account_type, correct_policy_id)

correct_user_2 = User(correct_username, correct_first_name, correct_last_name,
                      correct_email, correct_country_code, correct_phone,
                      correct_birth_year, correct_birth_month, correct_birth_day,
                      correct_verified, correct_account_type, 99)

correct_user_3 = User('testuser_two', 'Robert', 'Brown', 'robert.brown@gmail.com',
                      1, '5163429878', 1992, 2, 24, True, constants.personal, 8)

# Group variables
correct_group_id = 2
correct_group_policy_id = 3
correct_group_name = 'Test Group 1'
correct_group_email = None
correct_routine_id = 11
correct_routine_name = 'Test Routine 1'
correct_valid_start = datetime.datetime.strptime('2018-10-01 00:00:00', constants.timestamp_format)
correct_valid_end = datetime.datetime.strptime('9999-01-01 00:00:00', constants.timestamp_format)

correct_routine_start = datetime.datetime.strptime('8:0', constants.time_format).time()
correct_routine_end = datetime.datetime.strptime('12:0', constants.time_format).time()
incorrect_routine_end = datetime.datetime.strptime('7:0', constants.time_format).time()

correct_group_rotation_1 = GroupRotation(correct_routine_id, 1, 1, 7, correct_user.username)
correct_group_rotation_2 = GroupRotation(correct_routine_id, 1, 8, 14, correct_user_2.username)
correct_group_level = GroupLevel(correct_routine_id, 1, 15, 14, 7, [correct_group_rotation_1, correct_group_rotation_2])
correct_group_routine = GroupRoutine(correct_group_id, correct_routine_id, correct_routine_name,
                                     correct_valid_start, correct_valid_end,
                                     correct_routine_start, correct_routine_end,
                                     [correct_group_level], False)

correct_admin_name = 'testuser_one'
invalid_admin_name = 'testuser_eight'
correct_group = Group(correct_group_id, correct_group_policy_id, correct_group_name, correct_group_email,
                      [correct_group_routine], [], [correct_admin_name])

# Policy variables
test_user_policy_1 = UserPolicy(3, correct_user)
test_user_policy_2 = UserPolicy(8, correct_user_3)
test_group_policy = GroupPolicy(3, correct_group)

# Assignee variables
test_user_assignee_1 = Assignee(correct_user.username, test_user_policy_1, 1, 15)
test_user_assignee_2 = Assignee(correct_user_3.username, test_user_policy_2, 2, 15)
test_group_assignee_1 = Assignee(correct_user.username, test_group_policy, 1, 15)

# Task variable
test_task_details = {var_names.created_by: correct_user.username,
                     var_names.task_title: 'Test task title 1',
                     var_names.task_timezone: 'US/Eastern',
                     var_names.task_hour: 8,
                     var_names.task_minute: 12,
                     var_names.repeat: [constants.monday, constants.thursday],
                     var_names.text_msg: 'test task 1',
                     var_names.voice_msg_location: '',
                     var_names.video_msg_location: '',
                     var_names.with_completion_notice: True,
                     var_names.require_all_assignees_response: False,
                     var_names.urgency_level: constants.low_urgency}
test_task_assignees = [test_user_assignee_1, test_user_assignee_2]
test_task = Task(3, test_task_details, test_task_assignees)

# Instance and Event variables
test_instance_id = 43
test_instance_timestamp = times.get_current_timestamp()
test_instance_next_alert = test_instance_timestamp + datetime.timedelta(9)

test_acknowledge_event_timestamp = test_instance_timestamp - datetime.timedelta(9)
test_acknowledge_event = AcknowledgeEvent(test_instance_id, test_acknowledge_event_timestamp,
                                          constants.app, test_user_assignee_2.assignee_name)

test_dispatch_event_timestamp = test_instance_timestamp - datetime.timedelta(20)
test_dispatch_event_to = [(test_user_assignee_1.assignee_name, test_user_policy_1.policy_id)]
test_dispatch_event_next_alert = test_instance_timestamp + datetime.timedelta(10)
test_dispatch_event = DispatchEvent(test_instance_id, test_dispatch_event_timestamp,
                                    constants.app, test_dispatch_event_to,
                                    test_dispatch_event_next_alert)

test_escalate_event_timestamp = test_instance_timestamp - datetime.timedelta(10)
test_escalate_event = EscalateEvent(test_instance_id, test_escalate_event_timestamp,
                                    constants.app, constants.internal, 2)

test_instance_state_1 = InstanceState(test_instance_id, test_instance_timestamp, 2, constants.app,
                                      test_instance_timestamp, test_instance_next_alert,
                                      constants.acknowledged_state, [test_user_assignee_2],
                                      test_task, [test_dispatch_event, test_escalate_event, test_acknowledge_event])


import cv2 #import cv2 library
import numpy as np

#to start the camera
capture = cv2.VideoCapture(0)

#load xml feature file so that we can detect face from image
face_haar_data = cv2.CascadeClassifier(r"C:\Users\Py.Developer_Aniket\Desktop\AI Python\Mini_Project\Face_Mask_Detection_Machine_Learning\haarcascade_frontalface_default.xml")

#collect all faces into this data
data =[]
cnt = 0
while(1):
    #load the image from camera
    flag,img = capture.read()
    #check camera is working or not
    if flag :
        #this function return array for faces from image
        faces = face_haar_data.detectMultiScale(img)
        for x,y,w,h in faces:
            #draw rectangle over face
            #cv2.rectangle(img,(x,y),(w,h),(r,g,b),boarder_thickness)
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,255),2)
            #slice the face from image
            face = img[y:y+w,x:x+w,:]
            #resize the face into one size .pixel
            face = cv2.resize(face,(50,50))
            #collect only 200 faces
            print(len(data))
            if(len(data) < 100):
                #store faces into dataset
                data.append(face)
                cnt = cnt + 1
                print(cnt)
        cv2.imshow("output",img) #show image
        # 27 is ASCII value of escapse key
        #It will wait for ESC button
        #if you not use this function then it will not load image
        if((cv2.waitKey(2) == 27)):
            #save data into file
            np.save("without_mask.npy",data)
            # you have to give the name '.npy' to save the data
            break;
cv2.destroyAllWindows()


from __future__ import absolute_import

from django.conf.urls import patterns, url
from django.views.generic import TemplateView

from contact_form.views import contact_form

from .forms import FoundationContactForm

urlpatterns = patterns('',
    url(
        regex=r'^foundation/$',
        view=contact_form,
        kwargs=dict(
            form_class=FoundationContactForm,
            template_name='contact/foundation.html',
        ),
        name='contact_foundation',
    ),
    url(
        regex=r'^sent/',
        view=TemplateView.as_view(template_name='contact/sent.html'),
        name='contact_form_sent',
    )
)


# optional flask dependency
from flask import Flask
from flask import request
from flask import jsonify
from metadate import parse_date

app = Flask(__name__)

@app.route("/metadate", methods=["GET", "POST"])
def root():
    text = request.args.get("text")
    print(text)
    future = request.args.get("future")
    future = future.lower() == 'true' if future else True
    res = parse_date(text, future)
    if res:
        res = res.to_dict()
    return jsonify(res)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8002)


import logging
import platform
import getpass
import datetime

from crontab import CronTab
from taca.utils import statusdb
from taca.utils.config import CONFIG

def _parse_crontab():
    result = {}
    user = getpass.getuser()
    logging.info('Getting crontab for user {}'.format(user))
    try:
        crontab = CronTab(user=user)
    except Exception as e:
        logging.error('Cannot get a crontab for user: {}'.format(user))
        logging.error(e.message)
    else:
        result[user] = []
        for job in crontab.crons:
            # this is for special syntax like @monthly or @reboot
            special_syntax = str(job).split()[0] if str(job).startswith('@') else ''
            result[user].append({'Command': job.command,
                           'Comment': job.comment,
                           'Enabled': job.enabled,
                           'Minute': str(job.minutes),
                           'Hour': str(job.hours),
                           'Day of month' : str(job.dom),
                           'Month': str(job.month),
                           'Day of week': str(job.dow),
                           'Special syntax': special_syntax})
    return result

def update_cronjob_db():
    server = platform.node().split('.')[0]
    timestamp = datetime.datetime.now()
    # parse results
    result = _parse_crontab()
    # connect to db
    statusdb_conf = CONFIG.get('statusdb')
    logging.info('Connecting to database: {}'.format(CONFIG.get('statusdb', {}).get('url')))
    try:
        couch_connection = statusdb.StatusdbSession(statusdb_conf).connection
    except Exception as e:
        logging.error(e.message)
    else:
        # update document
        crontab_db = couch_connection['cronjobs']
        view = crontab_db.view('server/alias')
        # to be safe
        doc = {}
        # create doc if not exist
        if not view[server].rows:
            logging.info('Creating a document')
            doc = {
                'users': {user: cronjobs for user, cronjobs in result.items()},
                'Last updated': str(timestamp),
                'server': server,
            }
        # else: get existing doc
        for row in view[server]:
            logging.info('Updating the document')
            doc = crontab_db.get(row.value)
            doc['users'].update(result)
            doc['Last updated'] = str(timestamp)
        if doc:
            try:
                crontab_db.save(doc)
            except Exception as e:
                logging.error(e.message)
            else:
                logging.info('{} has been successfully updated'.format(server))
        else:
            logging.warning('Document has not been created/updated')


import numpy
import matplotlib.pyplot as plt

def plot_stochastic_processes(processes, title):
    """
    This method plots a list of stochastic processes with a specified title
    :return: plots the graph of the two
    """
    plt.style.use(['bmh'])
    fig, ax = plt.subplots(1)
    fig.suptitle(title, fontsize=16)
    ax.set_xlabel('Time, t')
    ax.set_ylabel('Simulated Asset Price')
    x_axis = numpy.arange(0, len(processes[0]), 1)
    for i in range(len(processes)):
        plt.plot(x_axis, processes[i])
    plt.show()


from datetime import (
    timedelta,
    datetime
)
from flask import current_app
from sqlalchemy import desc

from app import db
from app.dao.dao_utils import transactional
from app.models import InboundSms
from app.statsd_decorators import statsd

@transactional
def dao_create_inbound_sms(inbound_sms):
    db.session.add(inbound_sms)

def dao_get_inbound_sms_for_service(service_id, limit=None, user_number=None):
    q = InboundSms.query.filter(
        InboundSms.service_id == service_id
    ).order_by(
        InboundSms.created_at.desc()
    )

    if user_number:
        q = q.filter(InboundSms.user_number == user_number)

    if limit:
        q = q.limit(limit)

    return q.all()

def dao_get_paginated_inbound_sms_for_service(
    service_id,
    older_than=None,
    page_size=None
):
    if page_size is None:
        page_size = current_app.config['PAGE_SIZE']

    filters = [InboundSms.service_id == service_id]

    if older_than:
        older_than_created_at = db.session.query(
            InboundSms.created_at).filter(InboundSms.id == older_than).as_scalar()
        filters.append(InboundSms.created_at < older_than_created_at)

    query = InboundSms.query.filter(*filters)

    return query.order_by(desc(InboundSms.created_at)).paginate(
        per_page=page_size
    ).items

def dao_count_inbound_sms_for_service(service_id):
    return InboundSms.query.filter(
        InboundSms.service_id == service_id
    ).count()

@statsd(namespace="dao")
@transactional
def delete_inbound_sms_created_more_than_a_week_ago():
    seven_days_ago = datetime.utcnow() - timedelta(days=7)

    deleted = db.session.query(InboundSms).filter(
        InboundSms.created_at < seven_days_ago
    ).delete(synchronize_session='fetch')

    return deleted

def dao_get_inbound_sms_by_id(service_id, inbound_id):
    return InboundSms.query.filter_by(
        id=inbound_id,
        service_id=service_id
    ).one()


from PyQt5 import QtCore, QtGui, QtWidgets
import encodeUi as eui
import decodeUi as dui
import Steganography.audio_to_text

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(450, 450)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setContentsMargins(10, 10, 10, 10)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.frame = QtWidgets.QFrame(self.centralwidget)
        self.frame.setStyleSheet("QFrame\n"
"{\n"
"    background-color: rgb(56, 67, 84);\n"
"    \n"
"    color: rgb(255, 255, 255);\n"
"    border-radius:10px;\n"
"}")
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setObjectName("frame")

        #encode button
        self.Encode_Btn = QtWidgets.QPushButton(self.frame)
        self.Encode_Btn.setGeometry(QtCore.QRect(170, 150, 89, 31))
        self.Encode_Btn.setObjectName("Encode_Btn")
        self.Encode_Btn.clicked.connect(self.encode_call)

        #decode button
        self.Decode_Btn = QtWidgets.QPushButton(self.frame)
        self.Decode_Btn.setGeometry(QtCore.QRect(170, 220, 89, 31))
        self.Decode_Btn.setObjectName("Decode_Btn")
        self.Decode_Btn.clicked.connect(self.decode_call)

        self.verticalLayout.addWidget(self.frame)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def encode_call(self):
        self.encode_window = QtWidgets.QMainWindow()
        self.encode_ui = eui.Ui_MainWindow()
        self.encode_ui.setupUi(self.encode_window)
        self.encode_window.show()

    def decode_call(self):
        self.decode_window = QtWidgets.QMainWindow()
        self.decode_ui = dui.Ui_MainWindow()
        self.decode_ui.setupUi(self.decode_window)
        self.decode_window.show()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.Encode_Btn.setText(_translate("MainWindow", "Encode"))
        self.Decode_Btn.setText(_translate("MainWindow", "Decode"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, render_to_response
from django.contrib import auth
from django.core.context_processors import csrf
#cross-site request forgery --> method for people hacking into website
from GradeTracker.models import Student, Course, Graded_Activities, SubGraded_Activities, Templates
from GradeTracker.forms import courseAdd, activityAdd, subactivityAdd, MyRegistrationForm

def addSub(request, student_id, course_id, graded_activity_id ):
    if request.user.is_authenticated():
        student = Student.objects.filter(user=request.user)[0]
        activity = get_object_or_404( Graded_Activities, pk=graded_activity_id )
        course = get_object_or_404( Course, pk=course_id )
        if request.method == 'POST':
            form = subactivityAdd(request.POST)
            if form.is_valid():
                activity.subgraded_activities_set.create( subactivity_name = form.cleaned_data['subactivityName'], subgrade_weight = form.cleaned_data['subactivityWeight'] )
                return HttpResponseRedirect('/GT/' + str(student.id) +'/' + str(activity.course.id)  + '/' + str(activity.id))
        else:
            form = subactivityAdd()
        return render(request, 'GradeTracker/activities.html', {'form':form, 'activity':activity, 'student':student, 'course':course} )
    else:
        return render(request, 'GradeTracker/login.html')

def deleteSubGradedActivity(request, subactivity_id):
    subactivity = get_object_or_404(SubGraded_Activities, pk=subactivity_id)
    activityReturned = subactivity.main_category.id
    subactivity.delete()
    return HttpResponseRedirect('/GT/' + str(activityReturned) )

def editSubGradedActivity(request):
    pass


import os, sys, getopt
import json
import datetime
from shutil import rmtree
import string
import scipy.stats as stat
import numpy as np
from dateutil.relativedelta import *
from calendar import monthrange
from geotiff import *
from lmoments3 import distr

import matplotlib.pylab as plt
import matplotlib as mpl

def simple_plot_index(a,title="", save_img=False,save_dir='.'):
    fig, ax = plt.subplots()
    #cmap='RdBu'
    cmap = mpl.colors.LinearSegmentedColormap.from_list("", ["red","orange","yellow","white","pink","violet", "#0f0f0f"])
    plt.title(title)
    im = plt.imshow(a, interpolation='none',cmap=cmap)
    plt.colormaps()
    # cbar = fig.colorbar(cax,ticks=[-1, 0, 1, 2, 10],orientation='vertical')
    cbar = fig.colorbar(im, orientation='vertical')
    #plt.clim(-3,3)
    # cbar.ax.set_yticklabels(['< -1', '0', 1, 2,'> 10'])# vertically oriented
    # colorbar
    #ax.format_coord = Formatter(im)
    if save_img:
        plt.savefig(os.path.join(save_dir,title+'.png'))
    else:
        plt.show()

def displayHelp():

    print ('\nOptions available:')
    print ('          -n | --nostats                do not update statistics ')
    print ('          -h | --help                   display this help')

def get_all_dates(foldAdd, nameIndex):
    # remove path separator from end of folder address
    if foldAdd[-1] == os.path.sep:
        foldAdd = foldAdd[:-1]

    # get list of all files
    allFiles = [x[2] for x in os.walk(foldAdd)]

    # get dates from file names
    count = len(nameIndex)
    result = []
    for str in allFiles:
        if len(str) > 0:
            for stf in str:
                if nameIndex in stf:
                    date=stf.split('_')[1].split(".")[0]
                    #date = stf[count+1:count+9]
                     # print(date)
                    result.append(date)

    result.sort()
    return result

def get_date(dateStr):
    year = int(dateStr[0:4])
    month = int(dateStr[4:6])
    day = int(dateStr[6:8])
    return year, month, day

def diff_date_str(curDate, refDate):
    dateVal = datetime.datetime.strptime(curDate, "%Y%m%d").date()
    refDateVal = datetime.datetime.strptime(refDate, "%Y%m%d").date()
    return (dateVal - refDateVal).days

def convert_to_monthly_data (VARfold, VARprefix, indexFold, monthCount, maskFile):

    dateList = get_all_dates(VARfold, VARprefix)
    dateList.sort()

    dateListMonths = [i[0:6] for i in dateList ]

    oDateFrom = datetime.datetime.strptime(dateList[0],"%Y%m%d")
    oDateTo =   datetime.datetime.strptime(dateList[-1],"%Y%m%d")

    #in case month was not completed
    oDateTo = oDateTo.replace(day=1) + relativedelta(months=+1) + relativedelta(days=-1)

    print(oDateFrom.strftime("%Y%m%d"))
    print(oDateTo.strftime("%Y%m%d"))

    #oDateFrom = oDateFrom + relativedelta(months=monthCount)
    oDate = oDateFrom
    while (oDate <= oDateTo):

        if oDate < oDateFrom + relativedelta(months=monthCount-1):
            # remove the first monthCount from dateList
            #dateList = [s for s in dateList if oDate.strftime("%Y%m") not in s]
            oDate = oDate +relativedelta(months=+1)
            continue

        if oDate.strftime("%Y%m")  in dateListMonths:

            dateInMonth = []

            for m in range(monthCount):

                for date in dateList:

                    oDateAggr=oDate + relativedelta(months = -m)

                    year = oDateAggr.strftime("%Y")
                    month = oDateAggr.strftime("%m")

                    if  year+month in date[0:6]:

                        dateInMonth.append(date)

            if len(dateInMonth)>0:

                calculate_monthly_average(indexFold, VARfold, VARprefix, dateInMonth, oDate.strftime("%Y"), oDate.strftime("%m"), monthCount, maskFile)

            #dateListMonths.append(oDate.strftime("%Y%m"))
        else:
            print ("Missing data for : "+ oDate.strftime("%Y%m"))

        oDate = oDate +relativedelta(months=+1)

def calculate_monthly_average(indexFold, VARfold, VARprefix, dateInMonth, year, month, monthCount, maskFile):

    mask , col, row, geoTrans, geoproj = readGeotiff (maskFile)

    data3d = np.zeros((row, col, len (dateInMonth)))

    for i, key in enumerate(dateInMonth):
        #daFold = os.path.join(foldAdd, key[0:4], key[4:6], key[6:8])
        fileName = os.path.join(VARfold, key[0:4], key[4:6], key[6:8],VARprefix + "_" + key + ".tif")
        data , col, row, geoTrans, geoproj = readGeotiff (fileName)
        #simple_plot_index(data,key)
        data3d [:,:,i] = data

    data3d[data3d<1]=0
    data_mean = np.nanmean(data3d,axis=2)
    BandName="Prec_accumulation"

    os.system("mkdir -p "+os.path.join(indexFold,str(monthCount)+"-Month-Files"))

    outFileName= os.path.join(indexFold,str(monthCount)+"-Month-Files", VARprefix + "_" +year+month+".tif".format(year, month))

    #simple_plot_index(data_mean)
    print (outFileName)

    writeGeotiffSingleBand(outFileName, geoTrans, geoproj, data_mean,nodata=np.nan, BandName=BandName)

def create_statistics(mainFoldAdd, newFold, nameIndex, monthCount, maskFile):
    dateList = get_all_dates(mainFoldAdd, nameIndex)
    dateList.sort()
#    newFold = os.path.join(mainFoldAdd, "Normal PDF")
    if not(os.path.isdir(newFold)):
        os.system ("mkdir -p "+newFold)

    for month in range(1, 13):
        fileNames = []
        for str in dateList:
            yy = int(str[0:4])
            mm = int(str[4:6])
            if mm == month:
                fileNames.append(nameIndex + "_" + str + ".tif")
        compute_statistics (mainFoldAdd, fileNames, newFold, monthCount, month,nameIndex, maskFile)

def compute_statistics(mainFoldAdd, fileNames, newFold, monthCount, month,nameIndex, maskFile):
    print("Create statistics GeoTiff for {:d} months from month {:02d}".
          format(monthCount, month))

    mask, col, row, geoTrans, geoproj=  readGeotiff(maskFile)

    #data , col, row, geoTrans, geoproj = readGeotiff ("GSMAP_20200501.tif")

    data3d = np.zeros((row,col,len(fileNames)))

    for i, f in enumerate(fileNames):

        data , col, row, geoTrans, geoproj = readGeotiff (os.path.join(mainFoldAdd,f))

        data3d [:,:,i]= data

    distr_param =np.zeros((row,col,4))*np.nan

    invalid_pixels = 0

    for i in range(row):
        for j in range(col):

            if sum(np.isnan(data3d[i,j,:])) ==len(fileNames):
                continue

            d1d = data3d[i,j,:]
            dpd = d1d[np.where(d1d > 0)]  # only non null values
            zeros = d1d[d1d==0]
            if len(dpd) < 4:
                print ("Not enough valid values in time series, impossible fitting!")
                continue

            fit_dict = distr.gam.lmom_fit(dpd)
            fit = (fit_dict['a'],fit_dict['loc'],fit_dict['scale'])

            max_distance, p_value = stat.kstest(dpd,"gamma",args=fit)
            if p_value < 0.5:
                invalid_pixels += 1

                continue
                #print("Kolmogorov-Smirnov test for goodness of fit: "+str(round(p_value*100))+"%, max distance: "+str(max_distance))

            distr_param[i,j,0] = fit[0]
            distr_param[i,j,1] = fit[1]
            distr_param[i,j,2] = fit[2]
            distr_param[i,j,3] = len(zeros) / len(d1d)    # zero probability

    print ("Invalid pixel: " + str(round(invalid_pixels/(row*col)*100))+"%")
    name = "Statistics-"+ nameIndex +"-{:02d}months-Month{:02d}.tif".format(monthCount, month)
    fileStatsOut = os.path.join(newFold, name)

    writeGeotiff(fileStatsOut,geoTrans, geoproj,distr_param, nodata=np.nan, BandNames=list(fit_dict.keys()).append("P0")
                 ,globalDescr = "SPI_distr_param_c_loc_scale_P0")

def main(argv):
    with open('SPI_config.json') as jf:
        params = json.load(jf)

        # get FAPARFold tif files

        PrecFold = params["Prec_folder"]
        if PrecFold[-1] == os.path.sep:
            PrecFold = PrecFold[:-1]

        IndexFold = params["Index_folder"]
        if IndexFold[-1] == os.path.sep:
            IndexFold = PrecFold[:-1]

        PrecNameIndex = params["Prec_prefix"]

        maskFile = params["mask_file"]

        statsFold = params["Stats_folder"]

        aggMonths = params["Agg_months"]

        PrecmonthlyFold = os.path.join(IndexFold,PrecNameIndex+"-Monthly-Files")

        stats = True

        opts, a1Args = getopt.getopt(argv,"hn",["help","nostats"])

        for opt, arg in opts:
            if opt in ("-n", "--nostats"):
                stats = False

        for nmonths in aggMonths:

            # monthly averages

            convert_to_monthly_data(PrecFold, PrecNameIndex, PrecmonthlyFold, nmonths, maskFile)

            monthsFold = os.path.join(PrecmonthlyFold, "{:d}-Month-Files".format(nmonths))

            if stats:

                create_statistics(monthsFold, statsFold, PrecNameIndex, nmonths, maskFile)

if __name__ == '__main__':
    argv=sys.argv[1:]
    main(argv)
else:
    pass


# coding=utf-8
from __future__ import print_function

from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.clock import Clock

from scenes import scenes_list, scenes

class MultiLineLabel(Label):
    """ Use this class for spliting long text on new lines if need

    """
    def __init__(self, **kwargs):
        super(MultiLineLabel, self).__init__( **kwargs)
        self.text_size = self.size
        self.bind(size=self.on_size)
        self.bind(text=self.on_text_changed)
        self.size_hint_y = None # Not needed here

    def on_size(self, widget, size):
        self.text_size = size[0], None
        self.texture_update()
        self.width = self.parent.width
        if self.size_hint_y is None and self.size_hint_x is not None:
            self.height = max(self.texture_size[1], self.line_height)
        elif self.size_hint_x is None and self.size_hint_y is not None:
            self.width = self.texture_size[0]

    def on_text_changed(self, widget, text):
        self.on_size(self, self.size)

class GUI(FloatLayout):
    """ Main game window

    """
    def __init__(self, **kwargs):
        super(GUI, self).__init__(**kwargs)

    def start_game(self):
        """ Game starts here

        :return:
        """
        self.clear_widgets()
        menu = RenderMenu(pos_hint={'x': 0}, size_hint_y=None,)
        self.add_widget(menu)
        menu.show_menu()

class RenderMenu(Widget):
    """ Build main menu of the app

    """
    def show_menu(self, **kwargs):
        """ Redner main menu of the game

        :param kwargs:
        :return:
        """
        btn = Button(text=u'Новая игра', pos_hint={'x': 0}, size_hint_y=None,)
        btn.bind(on_press=self.new_game)
        self.parent.add_widget(btn)

    def new_game(self, instance):
        """ Start new game

        :param instance:
        :return:
        """
        start_game = RenderScene(name='first_scene')
        self.parent.add_widget(start_game)
        self.parent.remove_widget(instance)
        start_game.start()

class RenderScene(Widget):
    """ Render scenes of the app

    """
    def __init__(self, **kwargs):
        super(RenderScene, self).__init__(**kwargs)
        self.first_scene = kwargs.pop('name')
        self.name = self.first_scene
        self.scene_count = 0
        self.finished = False
        self.prev_scene = None

    def start(self):
        self.show_next_situation()

    def on_touch_down(self, touch):
        """ Render scenes on touch

        :param touch:
        :return:
        """
        if not self.finished:
            self.show_next_situation()
        else:
            self.show_main()

    def show_next_situation(self):
        """ Render and switching between scenes of the game

        :return:
        """
        self.finished = False
        # if we showed all text - then we could show new scene in other case - show all text
        if not self.prev_scene or (self.prev_scene and self.prev_scene.finished):
            if self.prev_scene:
                self.parent.remove_widget(self.prev_scene)
            scene = scenes.get(self.name, [])
            if len(scene) > self.scene_count:
                text = RenderText(**scene[self.scene_count])
                self.parent.add_widget(text)
                text.start_show()
                self.scene_count += 1
                self.prev_scene = text
            else:
                index = scenes_list.index(self.name)
                if len(scenes_list) > index+1:
                    self.scene_count = 0
                    self.name = scenes_list[index+1]
                    scene = scenes.get(self.name, [])
                    text = RenderText(**scene[self.scene_count])
                    self.parent.add_widget(text)
                    text.start_show()
                    self.scene_count += 1
                    self.prev_scene = text
                else:
                    text = RenderText(text='Game ended')
                    self.parent.add_widget(text)
                    text.start_show()
                    self.finished = True
                    self.prev_scene = text
        else:
            self.prev_scene.show_all()

    def show_main(self):
        """ Return to the main menu

        :return:
        """
        self.finished = False
        self.parent.start_game()

class RenderText(MultiLineLabel):
    """ Use for rendering text
        :text_speed - speed of the showing text. TBD

    """

    def __init__(self, **kwargs):
        self.text_speed = kwargs.get('text_speed', 100)
        self.full_text = list(reversed(kwargs.pop('text', ''))) # need to make reverse to show in correct order
        self.finished = False
        super(RenderText, self).__init__(**kwargs)

    def start_show(self):
        """ Show text with interval

        :return:
        """
        show_time = 1/self.text_speed
        Clock.schedule_interval(self.text_update, show_time)

    def show_all(self):
        """ Show all text by clicking on screen

        :return:
        """
        Clock.unschedule(self.text_update)
        if self.full_text:
            self.finished = True
            self.text += ''.join(list(reversed(self.full_text)))

    def text_update(self, dt):
        """ update text of the label

        :param dt: needed for the Clock function
        :return:
        """
        if self.full_text:
            self.text += self.full_text.pop()
        else:
            self.finished = True
            return False


import joblib
import json
import os
import pandas as pd

def init():
    global model
    model_path = os.path.join(os.getenv("AZUREML_MODEL_DIR"), "hd_model.pkl")
    model = joblib.load(model_path)

def run(request):
    data = json.loads(request)
    feats = pd.DataFrame.from_records(data)
    print("Received matchup = ", feats)
    result = model.predict(feats)
    print("Prediction : 0 for Team1, 1 for Team2 = ", result)
    return result.tolist()


"""empty message

Revision ID: c139e0419ea4
Revises: 785210c85a4e
Create Date: 2021-08-11 11:51:29.391270

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'c139e0419ea4'
down_revision = '785210c85a4e'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('experience', sa.Column('total_number_of_guests', sa.Integer(), nullable=True))
    op.drop_column('experience', 'Total_number_of_guests')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('experience', sa.Column('Total_number_of_guests', sa.INTEGER(), autoincrement=False, nullable=True))
    op.drop_column('experience', 'total_number_of_guests')
    # ### end Alembic commands ###


from euler import primes
from itertools import islice
from sys import exit

all_primes = list(islice(primes(), 1000))

def decompose(n):
    for p in all_primes:
        if p*p > n: break
        while n % p == 0:
            n //=p
            yield p
    if n > 1:
        yield n

i = 2*3*5*7
while True:
    j = 0
    while len(set(decompose(i))) == 4:
        i += 1
        j += 1
        if j == 4:
            print(i-4)
            exit(0)
    i += 1