import nltk
import string
from nltk.corpus import stopwords
from nltk import FreqDist
import os
import pager
import json
import threading

results = []

#input: url + filters + key-terms
#output: a list of reviews
def inputFileToList(url, keywords, type, rating):
	reviewList = pager.startGetPages(url, keywords, type, rating)
	return reviewList

#tester - print
def printLine(lineNo):
	thisList = inputFileToList()

#class Review
#revBody = the review content
#revWeight = ordering variable
class Review:
	def __init__(self, revId, revBody, revWeight):
		self.revId = revId
		self.revBody = revBody
		self.revWeight = revWeight

	def printReview(self):
		#print(self.revId)
		#print(self.revBody + "\n")
		print()

#input: urlm key-terms, type, rating
#output: a list of reviews (reviewArray)
def createRevArray(url, keywords, type, rating):
	counter = 0
	reviewList = inputFileToList(url, keywords, type, rating) # get all the reviews into one long list of strings
	reviewArray = []
	for item in reviewList: # for each review string in review list
		revId = counter ## rev id
		rev = Review(revId, reviewList[counter], 0.0)
		counter = counter + 1
		reviewArray.append(rev)
	return reviewArray

# input: string (key-term or review)
# output: tokens of string (lower case with puctuation removed. all items tokenised)
def getTokens(original):
	lowers = original.lower() #lower case
	transtable = {ord(c): None for c in string.punctuation} #build punctuation
	no_punctuation = lowers.translate(transtable) #remove punctuation
	tokens = nltk.word_tokenize(no_punctuation) #token
	return tokens

from nltk.stem.porter import *
#tokens = getTokens(original)
#filtered = [w for w in tokens if not w in stopwords.words('english')]

# input list
# output list with stop words removed
def textFilter(original):
	filtered = [w for w in original if not w in stopwords.words('english')]
	return filtered

#input list
#output list with items stemmed to base(english dictionary)
def stemTokens(tokens, stemmer):
	stemmed = []
	for item in tokens:
		stemmed.append(stemmer.stem(item))
	return stemmed

#define the stemmer we are using. used in stemTokens
stemmer = PorterStemmer()

#Search C - full searching tool with relative frequency distribution applied
#input: key-terms, list of reviews, long review preference(boolean)
#output: ordered list of reviews.
def searchC(keywords, reviewArray, lenSet):
	global results

	#format key-terms
	keyword = keywords
	keyword = getTokens(keyword)
	keyword = textFilter(keyword)
	keyword = stemTokens(keyword, stemmer)
	resetWeight(reviewArray)
	numReviews = len(reviewArray)

	#threading start
	t1 = threading.Thread(name = "t1", target=sendThreads,args=(reviewArray, numReviews, keyword, lenSet))
	t2 = threading.Thread(name = "t2", target=sendThreads,args=(reviewArray, numReviews, keyword, lenSet))
	t3 = threading.Thread(name = "t3", target=sendThreads,args=(reviewArray, numReviews, keyword, lenSet))
	t4 = threading.Thread(name = "t4", target=sendThreads,args=(reviewArray, numReviews, keyword, lenSet))

	t1.start()
	t2.start()
	t3.start()
	t4.start()

	t1.join()
	t2.join()
	t3.join()
	t4.join()

	results.sort(key = lambda x: x.revWeight)
	results.reverse() #reverse results, higher weighting first.

def sendThreads(reviewArray, numReviews, keyword, lenSet):
	threadGap = int(numReviews/4)

	if threading.current_thread().getName() == "t1":
		orderRev(reviewArray, keyword, lenSet, 0, threadGap * 1)

	elif threading.current_thread().getName() == "t2":
		orderRev(reviewArray, keyword, lenSet, (threadGap * 1 + 1), threadGap * 2)

	elif threading.current_thread().getName() == "t3":
		orderRev(reviewArray, keyword, lenSet, (threadGap * 2 + 1), threadGap * 3)

	elif threading.current_thread().getName() == "t4":
		orderRev(reviewArray, keyword, lenSet, (threadGap * 3 + 1), threadGap * 4)

def orderRev(reviewArray, keyword, lenSet, start, end):
	global results
	for rev in reviewArray[start:end]:
		review = rev.revBody
		#format review body
		review = getTokens(review)
		review = textFilter(review)
		review = stemTokens(review, stemmer)
		fdist = FreqDist(review) #frequency distribution of the review
		for word in keyword:
			if lenSet == "0": #user prefers concise reviews
				length = len(review)+1
				rev.revWeight = (rev.revWeight + (float(fdist[str(word)])) / length)
			else: #user prefer longer reviews
				rev.revWeight = rev.revWeight + (float(fdist[str(word)]))
		results.append(rev)

#clear rev.weight values
def resetWeight(reviews):
	for rev in reviews:
		rev.revWeight = 0;

#input: results, client identifier
#output: JSON file - list of reviews to send to client
def r2json(clientCode):
	global results
	if len(results) == 0:
		rev = Review(1,"Sorry, but no reviews were found for that query. Try widening your search critera.", 1)
		results.append(rev)
	lines = []
	simplejson = json
	f = open(clientCode+".txt","w")
	for rev in results:
		lines.append(rev.revBody)
	simplejson.dump(lines, f)
	f.close()
	results = []

def printHello():
	print("hello from " + str(print(threading.current_thread().getName())))

#main method
#1. interpret message settings
#2. create review array
#3. apply search c
#4. format to json s
def main(message, clientCode):

	args = message.split(",")
	keywords = args[0]

# filtering the search terms for more results.

	newKey = keywords.split()
	newKey2 = textFilter(newKey)
	newKey3 = " ".join(str(n) for n in newKey2)
	print("filtered input: " + newKey3)
	keywords = newKey3

	url = args[1]
	rating = args[2]
	type = args[3]
	lenSet = args[4]
	reviewArray = createRevArray(url, keywords, str(type), str(rating))

	results = searchC(keywords, reviewArray, lenSet)

	r2json(clientCode)


from collections import  Counter
from datetime import datetime, timedelta
from odoo.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError##Warning
import logging
_logger = logging.getLogger(__name__)
Delivery = [
    ('none','None'),
    ('fixed','Fixed'),
    ('base_on_rule','Base on Rule'),

]

class ProductTemplate(models.Model):
    _inherit = "product.template"
    wk_packaging_ids = fields.Many2many(
        'product.packaging',
        'product_tmp_product_packaging_rel',
        'product_tmpl_id',
        'packaging_id',
        string='Packaging'
    )

class SaleOrder(models.Model):
    _inherit = "sale.order"
    carrier_price = fields.Float(
        string='Actual Carrier Charges',
        help="Actual Carrier Charges recive from api "
    )
    delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)

    create_package = fields.Selection(
        string='Create Package',
        selection=[('auto','Automatic'),('manual','Manual')],
        default='auto',
        help='Create  automatic package as per packing max weight limit and  max qty  ',
    )
    wk_packaging_ids = fields.One2many(
        comodel_name='product.package',
        inverse_name='order_id',
        string='Product Package'
    )

    def auto_create_package(self):
        obj = self.filtered(lambda o:o.carrier_id)
        no_carrier = self-obj
        if len(no_carrier):
            raise ValidationError('Select Delivery Method For %s .'%(no_carrier.mapped('name')))
        for order in obj:
            order.carrier_id.wk_set_order_package(order)
        return True
    @api.model
    def wk_get_order_package(self):
        return map(lambda wk_packaging_id:dict(
            packaging_id = wk_packaging_id.packaging_id.id,
            weight = wk_packaging_id.weight,
            width=wk_packaging_id.width,
            length=wk_packaging_id.length,
            height=wk_packaging_id.height,
            cover_amount=wk_packaging_id.cover_amount,
            qty=wk_packaging_id.qty,
        ),self.wk_packaging_ids)

    def _wk_check_carrier_quotation(self,force_carrier_id=None):
        res=True

        try:
            ctx =dict(self._context)
            ctx['wk_website']=1
            res= self.with_context(ctx)._check_carrier_quotation(force_carrier_id)
        except Exception as e:
            _logger.error("Checking carrier quotation #%s" % e)
            res=False
        return res


import os
import json
import argparse

import fiftyone as fo
from fiftyone.types.dataset_types import COCODetectionDataset

parser = argparse.ArgumentParser()
parser.add_argument("--data_path", type=str, default="datasets/coco_benchmark/")
parser.add_argument("--culture_file", type=str, default="datasets/datasetCulture/culture.json")
parser.add_argument("--shape_file", type=str, default="datasets/datasetCulture/shape.json")
args = parser.parse_args()

data_path = args.data_path

dataset = fo.Dataset.from_dir(
    data_path,
    dataset_type=COCODetectionDataset,
    name="benchmark",
    labels_path="annotations.json",
)

culture_file = args.culture_file
shape_file = args.shape_file

if os.path.exists(culture_file):
    with open("datasets/datasetCulture/culture.json") as f:
        culture = json.load(f)

if os.path.exists(shape_file):
    with open("datasets/datasetCulture/shape.json") as f:
        shape = json.load(f)

for sample in dataset:
    image_name = sample.filepath.split("/")[-1]
    image_name_id = int(image_name.split("_")[0])
    for culture_name, culture_id in culture.items():
        if image_name_id in culture_id:
            sample['culture'] = culture_name
    for shape_name, shape_id in shape.items():
        if image_name_id in shape_id:
            sample['shape'] = shape_name
    sample.save()

dataset.save()

session = fo.launch_app(dataset)
session.wait()

exit()


import argparse
import logging

from abc import ABC, abstractmethod
from fall.firmware_updater import FirmwareUpdater
from fall.result_constants import INSTALL_SUCCESS, INPUT_VALIDATION_FAILURE, UNABLE_TO_GET_PLATFORM_INFO_FAILURE, \
    UPGRADE_CHECK_FAILURE, INSTALL_FAILURE, REBOOT_FAILURE, UNSUPPORTED_OS_FAILURE, QUERY_SUCCESS, Result

from falc.falc_exception import FalcException
from falc.utility import search_keyword, get_canonical_representation_of_path
from falc.constant import QUERY, FW

COMMAND_FAIL = "FAIL"
COMMAND_SUCCESS = "SUCCESS"
CACHE = '/var/cache/manageability/repository-tool/'
FW_SUCCESS_MESSAGE_LIST = [INSTALL_SUCCESS]
FW_FAILURE_MESSAGE_LIST = [INPUT_VALIDATION_FAILURE, UNABLE_TO_GET_PLATFORM_INFO_FAILURE,
                           UPGRADE_CHECK_FAILURE, INSTALL_FAILURE, REBOOT_FAILURE, UNSUPPORTED_OS_FAILURE]
QUERY_SUCCESS_MESSAGE_LIST = [QUERY_SUCCESS]
QUERY_FAILURE_MESSAGE_LIST = [UNSUPPORTED_OS_FAILURE, UNABLE_TO_GET_PLATFORM_INFO_FAILURE]

logger = logging.getLogger(__name__)

class Command(ABC):  # pragma: no cover
    """Base class for command objects

    @param cmd_type: name of command to execute
    """

    def __init__(self, cmd_type: str) -> None:
        self._cmd_type = cmd_type

    @abstractmethod
    def trigger_command(self, args: argparse.Namespace) -> int:
        """Trigger the command-line utility tool to invoke update.
        @return: process return code"""
        pass

class FwCommand(Command):
    def __init__(self) -> None:
        """FW command"""
        super().__init__(FW)

    def trigger_command(self, user_input: argparse.Namespace) -> int:  # no pragma cover
        """Trigger the command-line utility tool to invoke update.

        @param user_input: arguments passed to command-line tool.
        @return: exit code for command (0 success, 1 fail)
        """
        payload = FirmwareUpdater().update(path_to_update_package=get_canonical_representation_of_path(user_input.path),
                                           capsule_release_date=user_input.releasedate, bios_vendor=user_input.vendor,
                                           platform_name=user_input.product,
                                           platform_manufacturer=user_input.manufacturer, guid=user_input.guid,
                                           autofill_platform_info=user_input.autofill)
        return self.search_response(payload)

    def search_response(self, payload: Result) -> int:
        """Search for keywords in response message

        @param payload: payload received in which to search
        @return: exit code for command (0 success, 1 fail)
        """
        if search_keyword(payload, FW_SUCCESS_MESSAGE_LIST):
            logger.info(f"\n {self._cmd_type.upper()} Command Execution is Completed")
            return 0
        elif search_keyword(payload, FW_FAILURE_MESSAGE_LIST):
            logger.error(f"\n {self._cmd_type.upper()} Command Execution FAILED")
            return 1
        else:
            raise FalcException('Unable to determine if FW operation is success or failure')

class QueryCommand(Command):
    def __init__(self) -> None:
        """Query command"""
        super().__init__(QUERY)

    def trigger_command(self, user_option: argparse.Namespace) -> int:   # no pragma cover
        """Trigger the command-line utility tool to invoke query request.
        @param user_option:query type to return
        @return: exit code for command (0 success, 1 fail)
        """
        logger.debug(f"command={user_option}")

        payload = FirmwareUpdater().query(user_option.option)
        return self.search_response(payload)

    def search_response(self, payload: Result) -> int:
        """Search for keywords in response message

        @param payload: payload received in which to search
        @return: exit code for command (0 success, 1 fail)
        """
        logger.debug("query search response")
        if search_keyword(payload, QUERY_SUCCESS_MESSAGE_LIST):
            logger.info(f"\n {self._cmd_type.upper()} Command Execution is Completed")
            return 0
        elif search_keyword(payload, QUERY_FAILURE_MESSAGE_LIST):
            logger.error(f"\n {self._cmd_type.upper()} Command Execution FAILED")
            return 1
        else:
            raise FalcException(f'Unable to determine if query operation is success or failure')


import subprocess
import platform
import chardet

def ping(site):
    param = '-n' if platform.system().lower() == 'windows' else '-c'
    args = ['ping', param, '2', site]
    result = subprocess.Popen(args, stdout=subprocess.PIPE)
    for line in result.stdout:
        result = chardet.detect(line)
        line = line.decode(result['encoding']).encode('utf-8')
        print(line.decode('utf-8'))

sites = ['yandex.ru', 'youtube.com']
for site in sites:
    ping(site)


import tensorflow as tf

class WarmUpThenLinDecaySchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
    """
    Learning rate schedule that first increases the learning rate linearly from 0 to initial_learning_rate
    and then decreases it linearly to zero. Note that there is a step when the schedule switches, as the
    linear decrease starts at step 0 and is therefore smaller than initial_learning_rate after the warmup steps.
    This is done to have the schedule equivalent to the one used in the original BERT code.
    See https://github.com/google-research/bert/blob/master/optimization.py for reference. (The step in learning
    rate is not explicitly mentioned there, but a closer inspection of the code reveals it).
    """
    def __init__(self, initial_learning_rate, warm_up_steps, total_steps):
        self.warm_up_steps = warm_up_steps
        self.warm_up_schedule = tf.keras.optimizers.schedules.PolynomialDecay(initial_learning_rate=0.0,
                                                                              decay_steps=warm_up_steps,
                                                                              end_learning_rate=initial_learning_rate)
        self.decay_schedule = tf.keras.optimizers.schedules.PolynomialDecay(initial_learning_rate=initial_learning_rate,
                                                                            decay_steps=total_steps,
                                                                            end_learning_rate=0.0)

    def __call__(self, step):
        return tf.cond(step < self.warm_up_steps,
                       lambda: self.warm_up_schedule(step), lambda: self.decay_schedule(step))

GRAD_CLIP_NORM = 1.0  # default in BERT, see https://github.com/google-research/bert/blob/master/optimization.py

class ClipAdam(tf.keras.optimizers.Adam):
    """
    Small workaround wrapper to clip gradients, as gradient clipping is otherwise ignored in Keras TF2.1 and bug
    fix will only ship with TF2.2.
    See https://github.com/tensorflow/tensorflow/commit/69da929ad4d5ba605507efa1f52b382a55b6a969 for reference.
    """
    def apply_gradients(self, grads_and_vars, name=None, **kwargs):
        grads = []
        vars = []
        for grad, var in grads_and_vars:
            grads.append(tf.clip_by_norm(grad, GRAD_CLIP_NORM))
            vars.append(var)
        return super(ClipAdam, self).apply_gradients(zip(grads, vars), name=name, **kwargs)


import os
from datetime import datetime

import pandas as pd
from dotenv import load_dotenv
from prefect import flow, get_run_logger, task
from prefect_gcp.cloud_storage import GcsBucket

load_dotenv()

GCS_BUCKET_PATH = os.getenv(
    "GCS_BUCKET_PATH_BRONZE"
)  # <--- make sure your path file is right

@task(name="Convert-Data-to-Pandas-DataFrame")
def convert_data_to_pandas_dataframe(data: list[dict]) -> pd.DataFrame:
    return pd.DataFrame(data=data)

@task(name="Load-DF-to-Parquet-and-Upload-to-GCS")
def load_df_to_parquet_and_upload_to_gcs(
    df, serialization_format: str = "parquet"
) -> None:
    gcs_bucket_block = GcsBucket.load(
        "default"
    )  # <--- your bucket block name from /utils/create_blocks.py

    DATETIME_UPLOADED = datetime.now().strftime("year=%Y/month=%m/day=%d")
    HOUR_UPLOADED = datetime.now().strftime("%H%M%S")
    SEARCH_TERM = df["search_term"][0]
    CITY = df["store_city"][0]

    destination_gcs_path = f"{GCS_BUCKET_PATH}/{DATETIME_UPLOADED}/term={SEARCH_TERM}/city={CITY}/{SEARCH_TERM}_{HOUR_UPLOADED}"  # example: 'bronze/year=2023/month=07/day=21/term=twix/city=FLN/twix_195250.parquet'
    gcs_bucket_block.upload_from_dataframe(
        df, to_path=destination_gcs_path, serialization_format=serialization_format
    )
    return destination_gcs_path

@flow(name="Load-to-Parquet-and-Upload-to-GCS")
def load_to_parquet_and_upload_to_gcs(data: list[dict]) -> str:
    logger = get_run_logger()

    logger.info("---Starting Load to Parquet and Upload to GCS---")

    logger.info("Converting data to Pandas DataFrame")
    df = convert_data_to_pandas_dataframe(data=data)

    logger.info("Loading DF to Parquet and Uploading to GCS")
    gcs_filename = load_df_to_parquet_and_upload_to_gcs(df=df)

    logger.info("---Finished Loading Data to Parquet File in GCS---")

    return gcs_filename

if __name__ == "__main__":
    load_to_parquet_and_upload_to_gcs()


from typing import List

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        n, start = len(nums), 0
        output = []
        for end, x in enumerate(nums):
            if end == n - 1 or nums[end + 1] > x + 1:
                output += (
                    [str(nums[start]) + "->" + str(x)] if end > start else [str(x)]
                )
                start = end + 1

        return output


from prediction.model.series_model.lstm import LSTM
from prediction.model.series_model.bi_lstm_attention import BiLSTMAttention
import torch
from torch import optim
from tensorboardX import SummaryWriter
import pandas as pd
import numpy as np
import copy

# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

writer = SummaryWriter("prediction/resources/tensorboards")

def loss_function():
    return torch.nn.MSELoss()

def train(optimizer, model, lstm_data_loader, autoencoder):
    model.train()
    if autoencoder is not None:
        autoencoder.eval()
    train_loss = 0
    for batch_idx, (seq_in, target) in enumerate(lstm_data_loader):
        optimizer.zero_grad()

        seq_in = seq_in.to(device)
        target = target.to(device)

        if autoencoder is not None:
            h = autoencoder.encode(seq_in)
            y = model(h)
        else:
            y = model(seq_in)

        loss = loss_function()(y, target)

        loss.backward()
        optimizer.step()

        train_loss += loss.item()

    train_loss /= len(lstm_data_loader.dataset)
    return train_loss

    '''
    print('====> Epoch: {} Average loss: {:.4f}'.format(
        epoch, train_loss / len(lstm_data_loader.dataset)))

    # ================================================================== #
    #                        Tensorboard Logging                         #
    # ================================================================== #
    # ref: https://blog.csdn.net/qq_39575835/article/details/89160828
    # 1. Log scalar values (scalar summary)
    info = {'loss': train_loss / len(lstm_data_loader.dataset)}

    for tag, value in info.items():
        writer.add_scalars('data/scalar_group', info, epoch)

    # 2. Log values and gradients of the parameters (histogram summary)
    for tag, value in models.named_parameters():
        tag = tag.replace('.', '/')
        writer.add_histogram(tag, value.data.cpu().numpy(), epoch)
        writer.add_histogram(tag + '/grad', value.grad.data.cpu().numpy(), epoch)
    '''

def validate(epoch, model, lstm_data_loader, autoencoder):
    y_cpu = None
    target_cpu = None

    model.eval()
    if autoencoder is not None:
        autoencoder.eval()
    vad_loss = 0
    with torch.no_grad():
        for batch_idx, (seq_in, target) in enumerate(lstm_data_loader):
            seq_in = seq_in.to(device)
            target = target.to(device)

            if autoencoder is not None:
                h = autoencoder.encode(seq_in)
                y = model(h)
            else:
                y = model(seq_in)

            loss = loss_function()(y, target)
            vad_loss += loss.item()

            y_cpu = y.cpu().detach().numpy()
            target_cpu = target.cpu().detach().numpy()

    vad_loss /= len(lstm_data_loader.dataset)

    # ================================================================== #
    #                       Plot Graph                                   #
    # ================================================================== #
    if epoch % 10 == 0:
        dates = pd.date_range('2020-01-01', periods=len(lstm_data_loader.dataset))
        results = np.zeros((len(lstm_data_loader.dataset), 2))
        for i in range(len(lstm_data_loader.dataset)):
            results[i, 0] = y_cpu[i, 0]
            results[i, 1] = target_cpu[i, 0]
        print(results)

    return vad_loss

def train_lstm(epochs, train_lstm_data_loader, vad_lstm_data_loader, state_dict=None, autoencoder=None):
    if autoencoder is not None:
        model = LSTM(input_dim=autoencoder.encode_dim, seq_len=train_lstm_data_loader.dataset.seq_length).to(device)
    else:
        model = LSTM(seq_len=train_lstm_data_loader.dataset.seq_length).to(device)

    if state_dict is not None:
        model.load_state_dict(state_dict)
        return model.eval()

    optimizer = optim.Adam(model.parameters(), lr=1e-3)

    best_loss = 10000.0
    best_ep = 0
    best_model_wts = copy.deepcopy(model.state_dict())

    for epoch in range(1, epochs + 1):
        train_loss = train(optimizer, model, train_lstm_data_loader, autoencoder)
        val_loss = validate(epoch, model, vad_lstm_data_loader, autoencoder)
        if val_loss < best_loss:
            best_loss = val_loss
            best_ep = epoch
            best_model_wts = copy.deepcopy(model.state_dict())
        print(f'Epoch {epoch}: train loss {train_loss} val loss {val_loss}')
        print("Best val Loss:", best_loss, "in epoch:", best_ep)
        if epoch - best_ep > 150:
            print('early stop')
            break

    model.load_state_dict(best_model_wts)
    return model.eval()

def test_lstm(model, lstm_data_loader, autoencoder):
    y_cpu = None

    model.eval()
    if autoencoder is not None:
        autoencoder.eval()
    test_loss = 0
    with torch.no_grad():
        for batch_idx, (seq_in, target) in enumerate(lstm_data_loader):
            seq_in = seq_in.to(device)
            target = target.to(device)

            if autoencoder is not None:
                h = autoencoder.encode(seq_in)
                y = model(h)
            else:
                y = model(seq_in)

            loss = loss_function()(y, target)
            test_loss += loss.item()

            y_cpu = y.cpu().detach().view(-1).numpy()

    test_loss /= len(lstm_data_loader.dataset)
    return test_loss, pd.DataFrame(y_cpu, columns=['Predicted_Close'])


from django.conf import settings
from django import forms

from dal import autocomplete

I18N_PATH = 'autocomplete_light/i18n/'

class CustomModelSelect2(autocomplete.ModelSelect2):

    # class Media:
    #     css = {
    #         'screen': ('css/custom_autocomplete.css',)
    #     }

    # @property
    # def media(self):
    #     base_media = super().media
    #     custom_media = forms.Media(css={'screen': ('css/custom_autocomplete.css',)})
    #     # return base_media + custom_media
    #     res = base_media + custom_media
    #     print(res._css_lists)
    #     return res

    @property
    def media(self):
        """Return JS/CSS resources for the widget."""
        extra = '' if settings.DEBUG else '.min'
        i18n_name = self._get_language_code()
        i18n_file = (
            '%s%s.js' % (I18N_PATH, i18n_name),
        ) if i18n_name else ()

        return forms.Media(
            js=(
                'admin/js/vendor/select2/select2.full.js',
                'autocomplete_light/autocomplete_light%s.js' % extra,
                'autocomplete_light/select2%s.js' % extra,
            ) + i18n_file,
            css={
                'screen': (
                    'admin/css/vendor/select2/select2%s.css' % extra,
                    'admin/css/autocomplete.css',
                    'autocomplete_light/select2.css',
                    'css/custom_autocomplete.css',
                ),
            },
        )


import pygame
import random
import sys
from setting import SCREEN_WIDTH, SCREEN_HEIGHT, MAIN_DIR, SCREEN, CLOCK
import os
from tools import transform_image_constant, obj_is_mask
import time

DINO_RUN_IMG = [
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Dinosaur/run1.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Dinosaur/run2.png"))
]
GUN_IMG = [
    transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/Gun/Gun1.png")), width=50),
    transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/Gun/Gun2.png")), width=50),
    transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/Gun/Gun3.png")), width=80),
    transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/Gun/Gun4.png")), width=80),
    transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/Gun/Gun5.png")), width=80)
]
BULLET_IMG = [
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Bullet/bullet1.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Bullet/bullet2.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Bullet/bullet3.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Bullet/bullet4.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Bullet/bullet5.png"))
]
HELMET_IMG = [
    transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/head/Helmet1.png")), width=55),
    transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/head/Helmet2.png")), width=55),
    transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/head/Helmet3.png")), width=55)
]
CACTUS_IMG = [
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Cactus/LargeCactus1.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Cactus/LargeCactus2.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Cactus/LargeCactus3.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Cactus/SmallCactus1.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Cactus/SmallCactus2.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Cactus/SmallCactus3.png"))
]
WYVERN_IMG = [
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Wyvern/wyvern1.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Wyvern/wyvern2.png"))
]
BOSS_IMG = [
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Boss/boss1.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Boss/boss1.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Boss/boss.png")),
    pygame.image.load(os.path.join(MAIN_DIR, "Image/Boss/boss.png"))
]
BOOM_IMG = [
    transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/explosion/ex1.png")), width=100),
    transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/explosion/ex2.png")), width=100)
]

GUN_ITEM_IMG = transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/Gun/Gun_item.png")), width=50)
HELMET_ITEM_IMG = transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/head/Helmet_item.png")), width=50)
HEALTH_ITEM_IMG = transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/Other/Health_item.png")), width=50)
GAME_OVER_IMG = pygame.image.load(os.path.join(MAIN_DIR, "Image/Other/wasted.png"))
GAME_OVER_WIN_IMG = transform_image_constant(pygame.image.load(os.path.join(MAIN_DIR, "Image/Other/Win.png")), width=400)
RESET_IMG = pygame.image.load(os.path.join(MAIN_DIR, "Image/Other/Reset.png"))
RESET_WIN_IMG = pygame.image.load(os.path.join(MAIN_DIR, "Image/Other/Reset_win.png"))
GROUND_IMG = pygame.image.load(os.path.join(MAIN_DIR, "Image/Other/Ground.png"))

SHOOT_MUSIC = pygame.mixer.Sound(os.path.join(MAIN_DIR, "Music/gun.wav"))
MAIN_THEME_MUSIC = os.path.join(MAIN_DIR, "Music/backgroudMusic.wav")
GAME_OVER_MUSIC = os.path.join(MAIN_DIR, "Music/title.wav")

class Ground:
    def __init__(self):
        self.speed = 5
        self.ground_list = []
        for i in range(SCREEN_WIDTH):
            if random.random() > 0.95:
                img_rect = GROUND_IMG.get_rect()
                img_rect.x = random.randint(0, GROUND_IMG.get_width())
                img_rect.w = random.randint(120, min(300, max(120, GROUND_IMG.get_width() - img_rect.x)))
                draw_pos = [i, random.randint(0, SCREEN_HEIGHT)]
                self.ground_list.append([img_rect, draw_pos])

    def draw(self):
        if random.random() > 0.8:
            img_rect = GROUND_IMG.get_rect()
            img_rect.x = random.randint(0, GROUND_IMG.get_width())
            img_rect.w = random.randint(120, min(300, max(120, GROUND_IMG.get_width()-img_rect.x)))
            draw_pos = [SCREEN_WIDTH, random.randint(0, SCREEN_HEIGHT)]
            self.ground_list.append([img_rect, draw_pos])

        new_ground_list = []
        for g in self.ground_list:
            if g[1][0] < -g[0].w:
                del g
            else:
                g[1][0] -= self.speed
                new_ground_list.append(g)
        self.ground_list = new_ground_list
        for g in self.ground_list:
            SCREEN.blit(GROUND_IMG, (g[1][0], g[1][1]), g[0])

class Item:
    def __init__(self, item_type=0):
        self.x_speed = 3
        self.y_speed = 3
        self.item_type = item_type
        if item_type==0:
            self.img = GUN_ITEM_IMG
        elif item_type==1:
            self.img = HELMET_ITEM_IMG
        else:
            self.img = HEALTH_ITEM_IMG

        self.rect = self.img.get_rect()
        self.mask = pygame.mask.from_surface(self.img.convert_alpha())
        self.rect.x = SCREEN_WIDTH
        self.rect.y = random.randint(0, SCREEN_HEIGHT-self.img.get_height())
        self.direct = random.randint(0, 1)

    def draw(self):
        if random.random() > 0.9:
            self.direct = 1 - self.direct
        if self.direct:
            self.rect.y -= self.y_speed
        else:
            self.rect.y += self.y_speed
        self.rect.y = max(min(self.rect.y, SCREEN_HEIGHT-self.img.get_height()), 0)
        self.rect.x -= self.x_speed
        SCREEN.blit(self.img, self.rect)

class Bullet:
    def __init__(self, bullet_idx, centerx, centery, speed_x, speed_y):
        self.speed_x = speed_x
        self.speed_y = speed_y
        self.bullet_idx = bullet_idx
        self.img = BULLET_IMG[bullet_idx]
        self.mask = pygame.mask.from_surface(self.img.convert_alpha())
        self.rect = self.img.get_rect()
        self.rect.centerx = centerx
        self.rect.centery = centery

    def draw(self):
        SCREEN.blit(self.img, self.rect)
        self.rect.centerx += self.speed_x
        self.rect.centery += self.speed_y

class Explosion:
    def __init__(self, obj):
        self.obj = obj
        self.step = 0
        self.max_step = 20

    def draw(self):
        img = BOOM_IMG[min(self.max_step - 1, self.step)//(self.max_step//2)]
        rect = img.get_rect()
        rect.centerx = self.obj.rect.centerx
        rect.centery = self.obj.rect.centery
        SCREEN.blit(img, rect)
        self.step += 1

class Dinosaur:
    def __init__(self):
        self.move_speed = 8
        self.health = 100
        self.rect = DINO_RUN_IMG[0].get_rect()
        self.rect.x = 88
        self.rect.y = 425 - self.rect.height
        self.mask = pygame.mask.from_surface(DINO_RUN_IMG[0].convert_alpha())
        self.gun_idx = 0
        self.helmet_idx = -1
        self.gun_img = GUN_IMG[self.gun_idx]
        self.gun_rect = self.gun_img.get_rect()
        self.helmet_img = None
        self.helmet_rect = None
        self.update_gun()
        self.step = 0

    def draw(self):
        img = DINO_RUN_IMG[self.step // 10]
        rect = img.get_rect()
        self.rect.w = rect.w
        self.rect.h = rect.h
        self.mask = pygame.mask.from_surface(img.convert_alpha())
        self.update_gun()
        self.update_helmet()

        SCREEN.blit(img, self.rect)
        if self.helmet_idx >= 0:
            SCREEN.blit(self.helmet_img, self.helmet_rect)
        SCREEN.blit(self.gun_img, self.gun_rect)

        # draw health bar
        pygame.draw.rect(SCREEN, (0, 0, 0), (49, 19, 102, 22), 1)
        pygame.draw.rect(SCREEN, (0, 255, 0), (50, 20, self.health, 20), 0)

    def update_health(self, state):
        # state: heal = 0, shot = 1, hit = 2
        if state==0:
            self.health += 20
        elif state==1:
            if self.helmet_idx >= 0:
                self.helmet_idx -= 1
            else:
                self.health -= 5
        else:
            self.health -= 50
        self.health = min(max(0, self.health), 100)

    def update_gun(self):
        self.gun_idx = min(max(0, self.gun_idx), 4)
        self.gun_img = GUN_IMG[self.gun_idx]
        self.gun_rect = self.gun_img.get_rect()
        if self.gun_idx==0 or self.gun_idx==1:
            self.gun_rect = self.gun_img.get_rect()
            self.gun_rect.x = self.rect.x + 50
            self.gun_rect.y = self.rect.y + 15
        else:
            self.gun_rect = self.gun_img.get_rect()
            self.gun_rect.x = self.rect.x + 40
            self.gun_rect.y = self.rect.y + 20

    def update_helmet(self):
        self.helmet_idx = min(max(-1, self.helmet_idx), 2)
        if self.helmet_idx < 0:
            self.helmet_img = None
            self.helmet_rect = None
        else:
            self.helmet_img = HELMET_IMG[self.helmet_idx]
            self.helmet_rect = self.helmet_img.get_rect()
            self.helmet_rect.x = self.rect.x + 35
            self.helmet_rect.y = self.rect.y - 10

    def update(self, keys):
        if keys[pygame.K_UP] and not keys[pygame.K_DOWN]:
            self.rect.y -= self.move_speed
        elif keys[pygame.K_DOWN] and not keys[pygame.K_UP]:
            self.rect.y += self.move_speed
        self.rect.y = min(max(0, self.rect.y), SCREEN_HEIGHT-self.rect.h)

        if keys[pygame.K_LEFT] and not keys[pygame.K_RIGHT]:
            self.rect.x -= self.move_speed
        elif keys[pygame.K_RIGHT] and not keys[pygame.K_LEFT]:
            self.rect.x += self.move_speed
        self.rect.x = min(max(0, self.rect.x), SCREEN_WIDTH-self.rect.w)
        self.step = (self.step + 1) % 20

    def shoot(self):
        SHOOT_MUSIC.play()
        self.update_gun()
        begin_x = self.gun_rect.x + self.gun_rect.w
        begin_y = self.gun_rect.y + self.gun_rect.h // 2 - 5
        bullet_list = []

        if self.gun_idx == 0:
            bullet_list.append(Bullet(0, begin_x, begin_y, speed_x=15, speed_y=0))
            return bullet_list

        bullet_list.append(Bullet(0, begin_x, begin_y-5, speed_x=15, speed_y=0))
        bullet_list.append(Bullet(0, begin_x, begin_y+5, speed_x=15, speed_y=0))
        if self.gun_idx == 1:
            return bullet_list

        delta = 10
        speed_y = 2
        for i in range(2, self.gun_idx+1):
            bullet_list.append(Bullet(1, begin_x, begin_y - delta, speed_x=15, speed_y=-speed_y))
            bullet_list.append(Bullet(1, begin_x, begin_y + delta, speed_x=15, speed_y=speed_y))
            delta += 5
            speed_y += 2
        return bullet_list

class Boss:
    def __init__(self):
        self.health = 200
        self.speed = 2
        self.bullet_speed = 10
        self.direct_x = 1
        self.direct_y = 1
        self.last_shoot_time = 0
        self.img = BOSS_IMG[0]
        self.rect = self.img.get_rect()
        self.rect.x = SCREEN_WIDTH
        self.rect.y = random.randint(0, SCREEN_HEIGHT-self.rect.h)
        self.mask = pygame.mask.from_surface(self.img.convert_alpha())
        self.step = 0

    def update_health(self, state):
        self.health -= 2

    def draw(self):
        if self.health > 100:
            self.img = BOSS_IMG[self.step // 10]
        else:
            self.img = BOSS_IMG[self.step // 10 + 2]
        rect = self.img.get_rect()
        rect.x = self.rect.x
        rect.y = self.rect.y
        self.mask = pygame.mask.from_surface(self.img.convert_alpha())
        self.rect = rect

        # x direction move
        if self.rect.x > SCREEN_WIDTH - self.rect.width:
            self.direct_x = -1
        elif self.rect.x < SCREEN_WIDTH * 2 / 3:
            self.direct_x = 1
        elif random.random() > 0.9:
            self.direct_x = -1 * self.direct_x
        self.rect.x = self.rect.x + self.direct_x * self.speed

        # y direction move
        if self.rect.y > SCREEN_HEIGHT - self.rect.height:
            self.direct_y = -1
        elif self.rect.y < self.rect.height // 2:
            self.direct_y = 1
        elif random.random() > 0.95:
            self.direct_y = -1 * self.direct_y
        self.rect.y = self.rect.y + self.direct_y * self.speed

        SCREEN.blit(self.img, self.rect)
        self.step = (self.step + 1) % 20

        # draw health
        pygame.draw.rect(SCREEN, (0, 0, 0), (1299, 19, 102, 22), 1)
        if self.health > 100:
            pygame.draw.rect(SCREEN, (255, 0, 0), (1300, 20, self.health-100, 20), 0)
        else:
            pygame.draw.rect(SCREEN, (255, 0, 0), (1300, 20, self.health, 20), 0)

    def get_bullet(self):
        if self.health > 100:
            bullet_list = [Bullet(3, self.rect.centerx, self.rect.centery, speed_x=-self.bullet_speed, speed_y=0),
                           Bullet(3, self.rect.centerx, self.rect.centery, speed_x=-self.bullet_speed, speed_y=-3),
                           Bullet(3, self.rect.centerx, self.rect.centery, speed_x=-self.bullet_speed, speed_y=3),
                           Bullet(3, self.rect.centerx, self.rect.centery, speed_x=-self.bullet_speed, speed_y=-6),
                           Bullet(3, self.rect.centerx, self.rect.centery, speed_x=-self.bullet_speed, speed_y=6)]
        else:
            bullet_list = [Bullet(4, self.rect.centerx, self.rect.centery, speed_x=-self.bullet_speed, speed_y=0),
                           Bullet(4, self.rect.centerx, self.rect.centery, speed_x=-self.bullet_speed, speed_y=-3),
                           Bullet(4, self.rect.centerx, self.rect.centery, speed_x=-self.bullet_speed, speed_y=3),
                           Bullet(4, self.rect.centerx, self.rect.centery, speed_x=-self.bullet_speed, speed_y=-6),
                           Bullet(4, self.rect.centerx, self.rect.centery, speed_x=-self.bullet_speed, speed_y=6)]

        return bullet_list

    def shoot(self, dino):
        if (time.time() - self.last_shoot_time) > 0.2:
            self.last_shoot_time = time.time()
            return self.get_bullet()
        return []

class Cactus:
    def __init__(self):
        self.speed = 1
        self.health = 100
        self.bullet_speed = 8
        self.last_shoot_time = time.time()
        self.img = random.choice(CACTUS_IMG)
        self.rect = self.img.get_rect()
        self.rect.x = SCREEN_WIDTH + random.randint(0, 200)
        self.rect.y = random.randint (0, SCREEN_HEIGHT-self.rect.h)
        self.mask = pygame.mask.from_surface(self.img.convert_alpha())

    def update_health(self, state):
        # state: shot = 0, hit = 1
        if state==0:
            self.health -= 15
        else:
            self.health = 0

    def draw(self):
        self.rect.x -= self.speed
        SCREEN.blit(self.img, self.rect)

    def get_bullet(self, dinosaur):
        min_x = dinosaur.rect.x - 50
        max_x = dinosaur.rect.x + dinosaur.rect.w + 50
        dinosaur_target_x = random.random() * (max_x-min_x) + min_x

        min_y = dinosaur.rect.y - 50
        max_y = dinosaur.rect.y + dinosaur.rect.h + 50
        dinosaur_target_y = random.random() * (max_y-min_y) + min_y

        distance_x = abs(dinosaur_target_x-self.rect.centerx)
        distance_y = abs(dinosaur_target_y-self.rect.centery)
        distance = (distance_x**2 + distance_y**2)**0.5
        speed_x = self.bullet_speed * distance_x / distance
        speed_y = self.bullet_speed * distance_y / distance
        if dinosaur_target_x < self.rect.centerx:
            speed_x = -speed_x
        if dinosaur_target_y < self.rect.centery:
            speed_y = -speed_y
        return [Bullet(bullet_idx=3, centerx=self.rect.centerx, centery=self.rect.centery, speed_x=speed_x, speed_y=speed_y)]

    def shoot(self, dinosaur):
        if (time.time() - self.last_shoot_time) > (random.random()+0.3):
            self.last_shoot_time = time.time()
            return self.get_bullet(dinosaur)
        return []

class Wyvern:
    def __init__(self):
        self.health = 100
        self.speed = 2
        self.bullet_speed = 8
        self.direct_x = 1
        self.direct_y = 1
        self.last_shoot_time = 0
        self.shoot_times = 0
        self.img = WYVERN_IMG[0]
        self.rect = self.img.get_rect()
        self.rect.x = SCREEN_WIDTH
        self.rect.y = random.randint(0, SCREEN_HEIGHT-self.rect.h)
        self.mask = pygame.mask.from_surface(self.img.convert_alpha())
        self.step = 0

    def update_health(self, state):
        # state: shot = 0 (health - 10), hit = 1 (die);
        if state == 0:
            self.health -= 20
        else:
            self.health = 0

    def draw(self):
        self.img = WYVERN_IMG[self.step // 10]
        rect = self.img.get_rect()
        rect.x = self.rect.x
        rect.y = self.rect.y
        self.mask = pygame.mask.from_surface(self.img.convert_alpha())
        self.rect = rect

        # x direction move
        if self.rect.x > SCREEN_WIDTH - self.rect.width:
            self.direct_x = -1
        elif self.rect.x < self.rect.width:
            self.direct_x = 1
        elif random.random() > 0.9:
            self.direct_x = -1 * self.direct_x
        self.rect.x = self.rect.x + self.direct_x * self.speed

        # y direction move
        if self.rect.y > SCREEN_HEIGHT - self.rect.height:
            self.direct_y = -1
        elif self.rect.y < self.rect.height // 2:
            self.direct_y = 1
        elif random.random() > 0.95:
            self.direct_y = -1 * self.direct_y
        self.rect.y = self.rect.y + self.direct_y * self.speed

        SCREEN.blit(self.img, self.rect)
        self.step = (self.step + 1) % 20

    def get_bullet(self, dinosaur):
        min_x = dinosaur.rect.x - 20
        max_x = dinosaur.rect.x + dinosaur.rect.w + 20
        dinosaur_target_x = random.random() * (max_x-min_x) + min_x

        min_y = dinosaur.rect.y - 20
        max_y = dinosaur.rect.y + dinosaur.rect.h + 20
        dinosaur_target_y = random.random() * (max_y-min_y) + min_y

        distance_x = abs(dinosaur_target_x-self.rect.centerx)
        distance_y = abs(dinosaur_target_y-self.rect.centery)
        distance = (distance_x**2 + distance_y**2)**0.5
        speed_x = self.bullet_speed * distance_x / distance
        speed_y = self.bullet_speed * distance_y / distance
        if dinosaur_target_x < self.rect.centerx:
            speed_x = -speed_x
        if dinosaur_target_y < self.rect.centery:
            speed_y = -speed_y
        return [Bullet(bullet_idx=2, centerx=self.rect.centerx, centery=self.rect.centery, speed_x=speed_x, speed_y=speed_y)]

    def shoot(self, dinosaur):
        if self.shoot_times == 3:
            if (time.time() - self.last_shoot_time) > (0.8 + random.random()):
                self.shoot_times = 1
                self.last_shoot_time = time.time()
                return self.get_bullet(dinosaur)
        else:
            if (time.time() - self.last_shoot_time) > 0.6:
                self.shoot_times += 1
                self.last_shoot_time = time.time()
                return self.get_bullet(dinosaur)
        return []

class Restart:
    def __init__(self):
        self.game_over_img = GAME_OVER_IMG
        self.game_over_win_img = GAME_OVER_WIN_IMG
        self.reset_img = RESET_IMG
        self.reset_win_img = RESET_WIN_IMG
        self.game_over_pos = (
            SCREEN_WIDTH//2-self.game_over_img.get_width()//2,
            SCREEN_HEIGHT//4 - 100
        )
        self.game_win_pos = (
            SCREEN_WIDTH//2-self.game_over_win_img.get_width()//2,
            SCREEN_HEIGHT//4 - 100
        )
        self.reset_pos = (
            SCREEN_WIDTH//2-self.reset_img.get_width()//2,
            SCREEN_HEIGHT//2 + 50
        )
        self.reset_win_pos = (
            SCREEN_WIDTH//2-self.reset_img.get_width()//2,
            SCREEN_HEIGHT//2 + 200
        )
        self.font = pygame.font.SysFont("SimHei", 30)

    def draw(self, cost_time, is_win):
        text1 = self.font.render("Game Duration: %.2f s" % cost_time, True, (0, 0, 0))
        text_rect1 = text1.get_rect()
        text2 = self.font.render("Press Enter to Restart Game", True, (0, 0, 0))
        text_rect2 = text2.get_rect()
        if is_win:
            SCREEN.blit(self.game_over_win_img, self.game_win_pos)
            SCREEN.blit(self.reset_win_img, self.reset_win_pos)
            text_rect1.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 100)
            text_rect2.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 150)
        else:
            SCREEN.blit(self.game_over_img, self.game_over_pos)
            SCREEN.blit(self.reset_img, self.reset_pos)
            text_rect1.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 3 + 70)
            text_rect2.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 3 + 120)

        SCREEN.blit(text1, text_rect1)
        SCREEN.blit(text2, text_rect2)

class ShootingMain:
    def __init__(self):
        self.item_time = None
        self.ground = None
        self.dinosaur = None
        self.item_list = None
        self.boom_list = None
        self.enemy_list = None
        self.enemy_config = None
        self.last_kill_all_enemy_time = None
        self.bullet_list = None
        self.restart = None
        self.back_ground_music =None
        self.game_over = None
        self.start_time = None
        self.game_over_time = None
        self.start()

    def start(self):
        self.item_time = 0  # time.time()
        self.ground = Ground()
        self.dinosaur = Dinosaur()
        self.item_list = []
        self.boom_list = []
        self.enemy_list = []
        self.enemy_config = [
            {"wyvern": 3, "cactus": 0, "boss": 1},
            {"wyvern": 6, "cactus": 4, "boss": 0},
            {"wyvern": 5, "cactus": 3, "boss": 0},
            {"wyvern": 4, "cactus": 2, "boss": 0},
            {"wyvern": 3, "cactus": 1, "boss": 0}
        ]
        self.last_kill_all_enemy_time = None
        self.bullet_list = []
        self.restart = Restart()
        self.back_ground_music = 0  # no music = 0，in-game music = 1，game_over music = 2
        self.game_over = 0 # in-game = 0, loss = 1, win = 2
        self.start_time = time.time()
        self.game_over_time = None

    def draw(self):
        SCREEN.fill((255, 255, 255))
        if self.game_over:
            self.restart.draw(cost_time=self.game_over_time-self.start_time, is_win=self.game_over==2)
        else:
            self.ground.draw()
            self.dinosaur.draw()
            for item in self.item_list:
                item.draw()
            for bullet in self.bullet_list:
                bullet.draw()
            for e in self.enemy_list:
                e.draw()
            for b in self.boom_list:
                b.draw()

    def main_loop(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_ESCAPE:
                        pygame.mixer.music.stop()
                        return
                if event.type == pygame.KEYDOWN:
                    if self.game_over and event.key==pygame.K_RETURN:
                        self.start()
                    elif event.key == pygame.K_SPACE:
                        bullet_list = self.dinosaur.shoot()
                        self.bullet_list.extend(bullet_list)

            if time.time()-self.item_time > 3:
                self.item_time = time.time()
                self.item_list.append(Item(item_type=random.randint(0, 2)))

            # dinosaur moving
            keys = pygame.key.get_pressed()
            self.dinosaur.update(keys)

            # check if got the first aid bag
            new_item_list = []
            for item in self.item_list:
                if item.rect.x > -item.rect.w:
                    if obj_is_mask(self.dinosaur, item):
                        if item.item_type==0:
                            self.dinosaur.gun_idx += 1
                        elif item.item_type==1:
                            self.dinosaur.helmet_idx += 1
                        else:
                            self.dinosaur.update_health(state=0)
                        del item
                    else:
                        new_item_list.append(item)
                else:
                    del item
            self.item_list = new_item_list

            # Spawn Enemy
            if len(self.enemy_list) == 0 and len(self.enemy_config):
                if self.last_kill_all_enemy_time is None:
                    self.last_kill_all_enemy_time = time.time()
                elif self.last_kill_all_enemy_time is not None and (time.time()-self.last_kill_all_enemy_time) > 5:
                    enemy_config = self.enemy_config.pop()
                    for _ in range(enemy_config["wyvern"]):
                        self.enemy_list.append(Wyvern())
                    for _ in range(enemy_config["cactus"]):
                        self.enemy_list.append(Cactus())
                    for _ in range(enemy_config["boss"]):
                        self.enemy_list.append(Boss())
                    self.last_kill_all_enemy_time = None

            # Check enemy alive and hit check
            for e in self.enemy_list:
                if obj_is_mask(self.dinosaur, e):
                    self.dinosaur.update_health(state=2)
                    e.update_health(state=1)
            new_enemy_list = []
            for e in self.enemy_list:
                if e.health > 0:
                    new_enemy_list.append(e)
                else:
                    self.boom_list.append(Explosion(e))
            self.enemy_list = new_enemy_list

            # Enemy shoot
            for e in self.enemy_list:
                b = e.shoot(self.dinosaur)
                self.bullet_list.extend(b)

            # bullet hit check
            new_bullet_list = []
            for bullet in self.bullet_list:
                if bullet.rect.x > SCREEN_WIDTH or bullet.rect.x < -bullet.rect.width:
                    del bullet
                elif bullet.rect.y > SCREEN_HEIGHT or bullet.rect.y < -bullet.rect.height:
                    del bullet
                else:
                    is_del = False
                    if bullet.bullet_idx <= 1:
                        for e in self.enemy_list:
                            if obj_is_mask(bullet, e):
                                e.update_health(state=0)
                                del bullet
                                is_del = True
                                break
                    elif obj_is_mask(bullet, self.dinosaur):
                        self.dinosaur.update_health(state=1)
                        del bullet
                        is_del = True
                    if not is_del:
                        new_bullet_list.append(bullet)
            self.bullet_list = new_bullet_list

            # check if enemy die
            new_enemy_list = []
            for e in self.enemy_list:
                if e.health > 0:
                    new_enemy_list.append(e)
                else:
                    self.boom_list.append(Explosion(e))
            self.enemy_list = new_enemy_list

            # check explode effect
            self.boom_list = [b for b in self.boom_list if b.step <= b.max_step]

            # check if game over
            if len(self.enemy_list) == 0 and len(self.enemy_config) == 0 and self.game_over == 0:
                self.game_over = 2
                self.game_over_time = time.time()
            elif self.dinosaur.health <= 0 and not self.game_over:
                self.game_over = 1
                self.game_over_time = time.time()

            self.draw()
            CLOCK.tick(60)
            pygame.display.update()

            if self.game_over and self.back_ground_music != 2:
                pygame.mixer.music.load(GAME_OVER_MUSIC)
                pygame.mixer.music.play(loops=-1)
                self.back_ground_music = 2
            elif self.back_ground_music == 0:
                self.back_ground_music = 1
                pygame.mixer.music.load(MAIN_THEME_MUSIC)
                pygame.mixer.music.play(loops=-1)


from typing import Dict, List, Literal, Optional

from dash import ClientsideFunction, Input, Output, State, clientside_callback, dcc, html

try:
    from pydantic.v1 import Field, PrivateAttr, validator
except ImportError:  # pragma: no cov
    from pydantic import Field, PrivateAttr, validator

from vizro.models import Action, VizroBaseModel
from vizro.models._action._actions_chain import _action_validator_factory
from vizro.models._components.form._form_utils import (
    set_default_marks,
    validate_max,
    validate_slider_value,
    validate_step,
)
from vizro.models._models_utils import _log_call

class RangeSlider(VizroBaseModel):
    """Numeric multi-selector `RangeSlider`.

    Can be provided to [`Filter`][vizro.models.Filter] or
    [`Parameter`][vizro.models.Parameter]. Based on the underlying
    [`dcc.RangeSlider`](https://dash.plotly.com/dash-core-components/rangeslider).

    Args:
        type (Literal["range_slider"]): Defaults to `"range_slider"`.
        min (Optional[float]): Start value for slider. Defaults to `None`.
        max (Optional[float]): End value for slider. Defaults to `None`.
        step (Optional[float]): Step-size for marks on slider. Defaults to `None`.
        marks (Optional[Dict[float, str]]): Marks to be displayed on slider. Defaults to `{}`.
        value (Optional[List[float]]): Default start and end value for slider. Must be 2 items. Defaults to `None`.
        title (str): Title to be displayed. Defaults to `""`.
        actions (List[Action]): See [`Action`][vizro.models.Action]. Defaults to `[]`.
    """

    type: Literal["range_slider"] = "range_slider"
    min: Optional[float] = Field(None, description="Start value for slider.")
    max: Optional[float] = Field(None, description="End value for slider.")
    step: Optional[float] = Field(None, description="Step-size for marks on slider.")
    marks: Optional[Dict[float, str]] = Field({}, description="Marks to be displayed on slider.")
    value: Optional[List[float]] = Field(
        None, description="Default start and end value for slider", min_items=2, max_items=2
    )
    title: str = Field("", description="Title to be displayed.")
    actions: List[Action] = []

    # Component properties for actions and interactions
    _input_property: str = PrivateAttr("value")

    # Re-used validators
    _validate_max = validator("max", allow_reuse=True)(validate_max)
    _validate_value = validator("value", allow_reuse=True)(validate_slider_value)
    _validate_step = validator("step", allow_reuse=True)(validate_step)
    _set_default_marks = validator("marks", allow_reuse=True, always=True)(set_default_marks)
    _set_actions = _action_validator_factory("value")

    @_log_call
    def build(self):
        value = self.value or [self.min, self.max]  # type: ignore[list-item]

        output = [
            Output(f"{self.id}_start_value", "value"),
            Output(f"{self.id}_end_value", "value"),
            Output(self.id, "value"),
            Output(f"temp-store-range_slider-{self.id}", "data"),
        ]
        inputs = [
            Input(f"{self.id}_start_value", "value"),
            Input(f"{self.id}_end_value", "value"),
            Input(self.id, "value"),
            State(f"temp-store-range_slider-{self.id}", "data"),
            State(f"{self.id}_callback_data", "data"),
        ]

        clientside_callback(
            ClientsideFunction(namespace="clientside", function_name="update_range_slider_values"),
            output=output,
            inputs=inputs,
        )

        return html.Div(
            [
                dcc.Store(
                    f"{self.id}_callback_data",
                    data={
                        "id": self.id,
                        "min": self.min,
                        "max": self.max,
                    },
                ),
                html.P(self.title) if self.title else None,
                html.Div(
                    [
                        dcc.RangeSlider(
                            id=self.id,
                            min=self.min,
                            max=self.max,
                            step=self.step,
                            marks=self.marks,
                            value=value,
                            persistence=True,
                            persistence_type="session",
                            className="range_slider_control" if self.step else "range_slider_control_no_space",
                        ),
                        html.Div(
                            [
                                dcc.Input(
                                    id=f"{self.id}_start_value",
                                    type="number",
                                    placeholder="start",
                                    min=self.min,
                                    max=self.max,
                                    step=self.step,
                                    value=value[0],
                                    size="24px",
                                    persistence=True,
                                    persistence_type="session",
                                    className="slider_input_field_left"
                                    if self.step
                                    else "slider_input_field_no_space_left",
                                ),
                                dcc.Input(
                                    id=f"{self.id}_end_value",
                                    type="number",
                                    placeholder="end",
                                    min=self.min,
                                    max=self.max,
                                    step=self.step,
                                    value=value[1],
                                    persistence=True,
                                    persistence_type="session",
                                    className="slider_input_field_right"
                                    if self.step
                                    else "slider_input_field_no_space_right",
                                ),
                                dcc.Store(id=f"temp-store-range_slider-{self.id}", storage_type="session"),
                            ],
                            className="slider_input_container",
                        ),
                    ],
                    className="range_slider_inner_container",
                ),
            ],
            className="selector_container",
            id=f"{self.id}_outer",
        )


#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'appendAndDelete' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
#  1. STRING s
#  2. STRING t
#  3. INTEGER k
#

def appendAndDelete(s, t, k):
    # Write your code here
    l = 0
    for i in range(min(len(s), len(t))):
        if s[i] != t[i]:
            l = i
            break
        else:
            l = i + 1

    d = len(s) - l + len(t) - l

    if k >= len(s) + len(t):
        return "Yes"
    elif d <= k and (d % 2) == (k % 2):
        return "Yes"
    else:
        return "No"

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    t = input()

    k = int(input().strip())

    result = appendAndDelete(s, t, k)

    fptr.write(result + '\n')

    fptr.close()

Algorithms/02 - Implementation/Append and Delete.py


import sys
input = sys.stdin.readline

R, C = map(int, input().split())
board = []
word = []

for i in range(R):
    board.append(input().rstrip())

for r in range(R):
    for c in range(C):
        if board[r][c] == "#": continue
        tempW = ""
        rr, cc = r, c
        if c<1 or board[r][c-1]=="#":
            while cc<C and board[r][cc]!="#":
                tempW += board[r][cc]
                cc += 1
            if len(tempW)>1:
                word.append(tempW)
        tempW = ""
        rr, cc = r, c
        if r<1 or board[r-1][c]=="#":
            while rr<R and board[rr][c]!="#":
                tempW += board[rr][c]
                rr += 1
            if len(tempW)>1:
                word.append(tempW)

print(sorted(word)[0])


import unittest
import index

class TestStringMethods(unittest.TestCase):
    def test_parse_plain(self):
        dict = {
            1: 'one',
            2: 'two',
            3: 'three',
            4: 'four',
            8: 'eight',
            9: 'nine'
        }
        for number, word in dict.items():
            self.assertEqual(index.parse_plain(number), word)

    def test_parse_from_10_to_20(self):
        dict = {
            11: 'eleven',
            13: 'thirteen',
            14: 'fourteen',
            18: 'eighteen',
            19: 'nineteen'
        }
        for number, word in dict.items():
            self.assertEqual(index.parse(number), word)

    def test_parse_from_21_to_99(self):
        dict = {
            22: 'twenty two',
            97: 'ninety seven',
            66: 'sixty six',
            77: 'seventy seven'
        }
        for number, word in dict.items():
            self.assertEqual(index.parse_decades(number), word)

    def test_parse_from_100_to_999(self):
        dict = {
            100: 'one hundred',
            101: 'one hundred and one',
            201: 'two hundred and one',
            323: 'three hundred and twenty three',
            342: 'three hundred and forty two',
            944: 'nine hundred and forty four',
        }
        for number, word in dict.items():
            self.assertEqual(index.parse_hundreds(number), word)

    def test_symbols(self):
        numbers = range(1, 6)
        sum = 0

        for number in numbers:
            word = index.parse(number).replace(' ', '')
            sum += len(word)

        self.assertEqual(19, sum)

        word = index.parse(115).replace(' ', '')
        sum = len(word)

        self.assertEqual(sum, 20)

        word = index.parse(342).replace(' ', '')
        sum = len(word)

        self.assertEqual(sum, 23)

        numbers = range(1, 1001)
        sum = 0

        for number in numbers:
            word = index.parse(number).replace(' ', '')
            sum += len(word)
        print(sum)

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


def convertToKnownDatatype(datatype):
    """
        Convert the name of the data type to a conventional name
    """

    if datatype == 'geography':
        return "geography(POINT)"
    elif datatype == 'float8':
        return "Float"
    elif datatype == 'int4':
        return "Int"
    elif datatype == 'varchar':
        return "VARCHAR(255)"
    else:
        return datatype

def checkPointType(number, typ):
    """
        Return a point in decimal form
    """
    if typ == 'degree':
        return convertDegreeToDecimal(number)
    elif typ == 'decimal':
        return number

def convertDegreeToDecimal(number):
    """
    Converte graus,minutos,segundos para um valor decimal
    """
    if len(number.split("-")) == 1:
        positive = True
    else:
        positive = False

    split = number.split("\u00b0")
    d = float(split[0])    #Degree
    split = split[1].split("'")
    m = float(split[0])   #minute
    s = float(split[1].split('"')[0])  #second
    if positive:
        return d + (m/60) + (s/3600)
    else:
        return -1*(-1*d + (m/60) + (s/3600))

def convertDecimalToDegree(number):
    """
    Converte um valor decimal para um valor em graus,minutos,segundos
    """
    if number < 0:
        negative = True
        number *=-1
    else:
        negative = False
    d = int(number)
    m = int((number-d)*60)
    s = round((number-d-m/60)*3600)
    if negative:
        return "-%d\u00b0%s'%s''"%(d,convertNumtoStr(m),convertNumtoStr(s))
    else:
        return "%d\u00b0%s'%s''"%(d,convertNumtoStr(m),convertNumtoStr(s))

def convertNumtoStr(number):
    if number < 10:
        return "0%d"%(number)
    else:
        return "%d"%(number)


import requests
import sys
import logging
from discord.ext import commands

APPROVED_URL = 'http://localhost:5000/approved'
SUGGESTED_URL = 'http://localhost:5000/suggested'

f = open("strife.conf", "r")
for line in f:
    if line[0] == "#":
        continue
    elif "commoners_roleid" in line:
        commoners_roleid = int(line.split("=")[-1:][0].strip())
    elif "owner_roleid" in line:
        owner_roleid = int(line.split("=")[-1:][0].strip())
    elif "admin_roleid" in line:
        admin_roleid = int(line.split("=")[-1:][0].strip())
    elif "seniorMod_roleid" in line:
        seniorMod_roleid = int(line.split("=")[-1:][0].strip())
    elif "moderator_roleid" in line:
        moderator_roleid = int(line.split("=")[-1:][0].strip())
    elif "clerk_roleid" in line:
        clerk_roleid = int(line.split("=")[-1:][0].strip())

    elif "cbbb" in line:
        cbbb = int(line.split("=")[-1:][0].strip())

# START CATEGORIES FUNCTIONS
#return questions for a specific category
async def category(category, approved):
    if approved:
        r = requests.get(APPROVED_URL)
    else:
        r = requests.get(SUGGESTED_URL)
    batch = []
    topics = "```"
    for topic in r.json():
        if topic['CATEGORY'] == category:
            t = topic['TOPIC'] + "\n"
            if len(t) + len(topics) > 1950:
                batch.append(topics + '```')
                topics = "```" + t
            else:
                topics += t
    batch.append(topics + '```')

    if batch[0] == "``````":
        if approved:
            batch[0] = "There are currently no approved category matching "  + category
        else:
            batch[0] = "There are currently no suggested category matching " + category
    return batch

#return the categories
async def categories(approved):
    if approved:
        r = requests.get(APPROVED_URL)
    else:
        r = requests.get(SUGGESTED_URL)
    cats  = []
    for topic in r.json():
        category = str(topic['CATEGORY'])
        if category not in cats:
            cats.append(category)
    catString = '\n'.join(cats)
    categories = "```\n" + catString + "```"
    if len(categories) > 1900:
        categories = categories[:1900]
        categories += "RESULTS TRUNCATED"
    if categories == "``````":
        if approved:
            topics = "There are currently no approved category "
        else:
            topics = "There are currently no suggested category "
    return categories

# END CATEGORIES FUNCTIONS

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

# START CATEGORIES COMMANDS

    #Returns all topics for a suggested category
    @commands.command(pass_context=True, name='suggestedcategory', aliases=['cs'])
    @commands.has_any_role(owner_roleid, admin_roleid, seniorMod_roleid, moderator_roleid, clerk_roleid, cbbb)
    async def suggestedcategory(self, ctx):
        """Returns all topics for a suggested category"""
        sys.stdout.write(f'{ctx.message.author} ran command "suggestedcategory"\n')
        sys.stdout.flush()
        logging.info(f'{ctx.message.author} ran command "suggestedcategory"')
        if ctx.message.content.lower().strip().startswith('suggestedcategory '):
            cat = ctx.message.content[len('suggestedcategory '):].strip()
        else:
            cat = ctx.message.content[len('cs '):].strip()
        topics = await category(cat, False)
        await ctx.send(topics)

    @suggestedcategory.error
    async def suggestedcategory_error(self, ctx, error):
        logging.error('Command "suggestedcategory" failed due to the following error:')
        logging.error(error)
        await ctx.send('Error processing that request')

    #__________________________________________________

    #Returns all suggested categories
    @commands.command(pass_context=True, name='suggestedcategories', aliases=['acs'])
    @commands.has_any_role(owner_roleid, admin_roleid, seniorMod_roleid, moderator_roleid, clerk_roleid, cbbb)
    async def suggestedcategories(self, ctx):
        """Returns all suggested categories"""
        sys.stdout.write(f'{ctx.message.author} ran command "suggestedcategories"\n')
        sys.stdout.flush()
        logging.info(f'{ctx.message.author} ran command "suggestedcategories"')
        cats = await categories(False)
        await ctx.send(cats)

    @suggestedcategories.error
    async def suggestedcategories_error(self, ctx, error):
        logging.error('Command "suggestedcategories" failed due to the following error:')
        logging.error(error)
        await ctx.send('Error processing that request')

    #__________________________________________________

    #Returns all categories
    @commands.command(pass_context=True, name='categories', aliases=['ac'])
    @commands.has_any_role(owner_roleid, admin_roleid, seniorMod_roleid, moderator_roleid, cbbb)
    async def categories(self, ctx):
        """Returns all categories"""
        sys.stdout.write(f'{ctx.message.author} ran command "categories"\n')
        sys.stdout.flush()
        logging.info(f'{ctx.message.author} ran command "categories"')
        cats = await categories(True)
        await ctx.send(cats)

    @categories.error
    async def categories_error(self, ctx, error):
        logging.error('Command "categories" failed due to the following error:')
        logging.error(error)
        await ctx.send('Error processing that request')

    #__________________________________________________

    #Returns all topics for a category
    @commands.command(pass_context=True, name='category', aliases=['c'])
    @commands.has_any_role(owner_roleid, admin_roleid, seniorMod_roleid, moderator_roleid, cbbb)
    async def category(self, ctx):
        """Returns all topics for a category"""
        sys.stdout.write(f'{ctx.message.author} ran command "category"\n')
        sys.stdout.flush()
        logging.info(f'{ctx.message.author} ran command "category"')
        if ctx.message.content.lower().strip().startswith('category '):
            cat = ctx.message.content[len('category '):].strip()
        else:
            cat = ctx.message.content[len('c '):].strip()
        topics = await category(cat, True)
        for msg in topics:
            await ctx.send(msg)

    @category.error
    async def category_error(self, ctx, error):
        logging.error('Command "category" failed due to the following error:')
        logging.error(error)
        await ctx.send('Error processing that request')

    #__________________________________________________

# END CATEGORIES COMMANDS

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


import copy
import torch
import math
# from math import ceil as up

def HeteroAvg(w): # [0]: weight, [1]: dropout probability
    w_glob = copy.deepcopy(w[0][0])
    w_avg = copy.deepcopy(w[0][0])

    '''initialization'''
    for key in w_avg.keys():
        w_avg[key] = 0*w_avg[key]

    for key in w_glob.keys():
        cnt = 0
        for i in range(1, len(w)):
            w_local = copy.deepcopy(w[i][0])
            model_idx = w[i][1]

            if key in w_local.keys():
                cnt += 1
                w_avg[key] += w_local[key]
        if cnt == 0:
            w_avg[key] = w_glob[key]
        else:
            w_avg[key] = w_avg[key] / cnt
    return w_avg

def HeteroAvg_auxnet(w, auxiliary_models):
    # w는 [[aux_net 1 weight 모음],[aux_net 2 weight 모음],[aux_net 3 weight 모음],[aux_net 4 weight 모음],[aux_net 5 weight 모음]]으로 이뤄진 list임
    aux_models = copy.deepcopy(auxiliary_models)
    for idx in range(len(w)):
        if not w[idx]:    # w[i]가 비어있음
            continue
        else:
            num = len(w[idx])   # w[idx]를 사용한 클라이언트 수
            w_avg = copy.deepcopy(w[idx][0])
            # Initialization
            for key in w_avg.keys():
                w_avg[key] = 0*w_avg[key]
            # Aggregation
            for key in w_avg.keys():
                for i in range(num):
                    w_local = copy.deepcopy(w[idx][i])
                    w_avg[key] += w_local[key]
                w_avg[key] = w_avg[key] / num
            aux_models[idx].load_state_dict(w_avg)
    return aux_models

def HeteroAvg_cs(w_c, w_s): # [0]: weight, [1]: dropout probability
    w_c_glob = copy.deepcopy(w_c[0][0])

    w_c_avg = copy.deepcopy(w_c[0][0])
    # w_s_avg = copy.deepcopy(w_s[0][0])

    '''initialization'''
    for key in w_c_avg.keys():
        w_c_avg[key] = 0*w_c_avg[key]

    for key in w_c_glob.keys():
        cnt = 0
        for i in range(1, len(w_c)):    # len(w_c) = 한 라운드에 참여한 클라이언트 수 + 1
            w_c_local = copy.deepcopy(w_c[i][0])
            w_s_local = copy.deepcopy(w_s[i][0])
            if key in w_c_local.keys():
                cnt += 1
                w_c_avg[key] += w_c_local[key]
            elif key in w_s_local.keys():
                cnt += 1
                w_c_avg[key] += w_s_local[key]
        if cnt == 0:
            w_c_avg[key] = w_c_glob[key]
        else:
            w_c_avg[key] = w_c_avg[key] / cnt
    return w_c_avg

def HeteroAvg_new(w, BN_layers, com_layers, sing_layers,bn_keys, args, cs_opt): # [0]: weight, [1]: dropout probability
    w_glob = copy.deepcopy(w[0][0])
    w_avg = copy.deepcopy(w[0][0])

    b = [0] * args.num_models
    for i in range(1, len(w)):
        ind = w[i][1]
        b[ind] += 1
    '''initialization'''
    # 1) w/o bn layer 제외
    for key in w_avg.keys():
        if 'bn' not in key:
            w_avg[key] = 0*w_avg[key]
    # 2) bn layer
    for k in range(len(BN_layers)):
        if b[k]!=0:
            for key in BN_layers[k].keys():
                if 'num_batches_tracked' not in key:
                    BN_layers[k][key] = 0*BN_layers[k][key]

    for i in range(1, len(w)):
        index = w[i][1]
        for key in BN_layers[index].keys():
            if 'num_batches_tracked' not in key:
                BN_layers[index][key] += w[i][0][key]/b[index]
            else:
                BN_layers[index][key] += w[i][0][key]

    '''Averaging'''
    for key in w_avg.keys():
        if 'bn' in key or 'downsample.1' in key:
            pass
        cnt = 0
        for i in range(1, len(w)):
            w_local = copy.deepcopy(w[i][0])
            if key in w_local.keys():
                cnt +=1
                w_avg[key] += w_local[key]
        if cnt!=0:
            w_avg[key] = torch.div(w_avg[key], cnt)
        else:
            w_avg[key] = w_glob[key]
    if cs_opt == 'c':
        for key in BN_layers[-1].keys():
            w_avg[key] = copy.deepcopy(BN_layers[-1][key])
    elif cs_opt == 's':
        for key in BN_layers[0].keys():
            w_avg[key] = copy.deepcopy(BN_layers[0][key])
    return w_avg, BN_layers

def F_Avg(w, bn_keys, args): # [0]: weight, [1]: dropout probability

    w_avg = copy.deepcopy(w[0][0]) # global model

    a = [0]*(len(w)-1) # 10
    acc_num = [len(w)-1]*(args.num_models+1) # [10]*5+1. accumulated number of models.
    b = [0]*args.num_models # 5. number of model idxs for federation.

    for n in range(1, len(w)):
        a[n-1] = w[n][1]

    for i in range(len(b)):
        b[i] = a.count(i)
        acc_num[i+1] = acc_num[i] - b[i]

    zero_idx = 0
    for o in range(1,args.num_models):
        if acc_num[o] == 0:
            break
        zero_idx += 1
    max_p_updated = args.ps[zero_idx] # define a maximum size of model that is updated
    # print(max_p_updated)
    '''
      Initialization
    '''
    for key in w_avg.keys():
        shape = w_avg[key].shape
        if len(shape) == 4:
            if key == 'conv1.weight':
                w_avg[key][0:up(shape[0]*max_p_updated), :, :, :] = 0*w_avg[key][0:up(shape[0]*max_p_updated), :, :, :]
            else: # other conv layers (layer1.0.conv1.weight -> shape = [16, 16, 3, 3]. layer2.0.conv1.weight -> hsape = [32, 16, 3, 3])
                w_avg[key][0:up(shape[0]*max_p_updated), 0:up(shape[1]*max_p_updated), :, :] = 0*w_avg[key][0:up(shape[0]*max_p_updated), 0:up(shape[1]*max_p_updated), :, :]

        elif len(shape) == 2: # linear.weight,
            w_avg[key][:, 0:up(shape[1]*max_p_updated)] = 0*w_avg[key][:, 0:up(shape[1]*max_p_updated)]

        else: # bn1.weight
            w_avg[key] = 0*w_avg[key]
    list_ps = copy.deepcopy(args.ps)
    list_ps.insert(0, 0)
    '''Aggregation'''
    for key in w_avg.keys():
        if key not in bn_keys:
            shape = w_avg[key].shape
            for i in range(1, len(w)):
                index = w[i][1]
                for j in range(index+1):
                    if len(shape) > 1:  # conv1.weight & linear.weight
                        li = up(shape[0]*list_ps[j])
                        hi = up(shape[0]*list_ps[j+1])
                        li2 = up(shape[1]*list_ps[j])
                        hi2 = up(shape[1]*list_ps[j+1])
                        if len(shape) == 4:
                            if key == 'conv1.weight': # w[key][out_ch, in_ch, kernel_size, kernel_size]
                                w_avg[key][li:hi, :, :, :] += w[i][0][key][li:hi, :, :, :]/acc_num[j]
                            else: # other conv layers
                                w_avg[key][li:hi, li2:hi2, :, :] += w[i][0][key][li:hi, li2:hi2, :, :]/acc_num[j]
                                if j!=0:
                                    w_avg[key][0:li, li2:hi2, :, :] += w[i][0][key][0:li, li2:hi2, :, :]/acc_num[j]
                                    w_avg[key][li:hi, 0:li2, :, :] += w[i][0][key][li:hi, 0:li2, :, :]/acc_num[j]
                        elif len(shape) == 2: # linear.weight
                            w_avg[key][:, li2:hi2] += w[i][0][key][:, li2:hi2]/acc_num[j]
                if key == 'linear.bias': # independent of j
                    w_avg[key] += w[i][0][key]/acc_num[0]
        else:
            shape = w_avg[key].shape
            for i in range(1, len(w)):
                index = w[i][1]
                for j in range(index+1):
                    if len(shape) > 0:
                        li = up(shape[0]*list_ps[j])
                        hi = up(shape[0]*list_ps[j+1])
                        w_avg[key][li:hi] += w[i][0][key][li:hi]/acc_num[j]
                    else:
                        w_avg[key] = w_avg[key] +  w[i][0][key]/acc_num[j]
    return w_avg

def up(value):
  return math.ceil(value)


# -*- coding: utf-8 -*-
"""snake game state definitions
"""
import enum
import logging
import collections
import itertools
import random

logger = logging.getLogger("snakai")

class Direction(enum.IntEnum):
    """direction"""
    LEFT = 0
    RIGHT = 1
    UP = 2
    DOWN = 3
    NONE = 4

Point = collections.namedtuple('Point', "x, y")

class SnakeStateMachine(object):
    """snake-state-machine
    only keep inner status, the IO logic should be impl in the other class.

    the state mainly including 3 elements:
    1. environment: should be viewed as a matrix,
        with w = width, h = height
        the matrix is consisted of points, each has position.
        the position starts with 0.
        so all the points should bound in: x \in [0, w), y \in [0, h)
    2. snake: could be viewed as a list of continuous points and a direction.
        snake is some continuous points in the environments. it has a direction.
    3. feed: a point in the environment.

    what's more, some extra elements is used for game:
    1. score: game score, currently equals to the food eaten
    2. steps: move steps. each update on not-ended state should increase the steps.
    3. remaining-steps: max remaining steps before game-over.
        if food not eaten while remaining-steps == 0, then game over.
        else if food has been eaten, the remaining steps will be refilled.
        This is used to avoid `circle` operations.
    """
    class InnerStatus(object):
        """inner status"""
        RUNNING = 0
        FAIL = 1
        SUCCESS = 2
        UN_INIT = 3

    def __init__(self, width, height):
        """init
        """
        # type: collections.deque
        self.snake = None
        # type: Point
        self.food = None
        self.direction = Direction.NONE
        # type: int
        self.steps = None
        # type: fint
        self.remaining_steps = None
        # type: float
        self.score = None

        self._w = width
        self._h = height
        self._status = self.InnerStatus.UN_INIT
        self._rng = random.Random()

    def is_state_ok(self) -> bool:
        """query whether current state is ok
        """
        return self._status == self.InnerStatus.RUNNING

    def update_state(self, d: Direction) -> bool:
        """
        Parameters
        ------------
        d: Direction

        Returns
        ---------
        Boolean
            whether game is ok.
        """
        def _udpate_direction():
            if not DirectionUtil.is_effective(d) or DirectionUtil.is_opposite(d, self.direction):
                return
            self.direction = d

        def _add_snake_head():
            current_head_p = self.head
            d = self.direction
            new_head = gen_next_step_point(current_head_p, d)
            # no need to check collision
            self.snake.appendleft(new_head)

        def _is_new_head_collide():
            new_head = self.head
            # case1: new-head collide on the edge
            if new_head.x in [-1, self._w] or new_head.y in [-1, self._h]:
                return True
            # case2: new-head collide on self body
            for test_point in itertools.islice(self.snake, 1, len(self.snake)):
                if new_head == test_point:
                    return True
            return False

        def _is_exceed_max_steps():
            return self.remaining_steps <= 0

        def _has_eaten_food():
            new_head = self.head
            return new_head == self.food

        def _has_succeeded():
            return len(self.snake) == self._h * self._w

        def _update_food():
            # if snake is too long and occupies almost all space,
            # this logic may dramatically costly
            while True:
                x = self._rng.randrange(0, self._w)
                y = self._rng.randrange(0, self._h)
                new_food = Point(x, y)
                if new_food in self.snake:
                    continue
                else:
                    break
            self.food = new_food

        if not self.is_state_ok():
            return False

        self.steps += 1
        self.remaining_steps -= 1
        _udpate_direction()

        _add_snake_head()
        if _is_new_head_collide() or _is_exceed_max_steps():
            self._status = self.InnerStatus.FAIL
            return False

        if _has_eaten_food():
            logger.debug("eat food! score = %s", self.score)
            self.score += 1
            self.remaining_steps = _calc_max_remaining_steps(self)
            if _has_succeeded():
                self._status = self.InnerStatus.SUCCESS
                return False
            _update_food()
        else:
            # remove tail to make a moving illusion
            self.snake.pop()

        return True

    def new_state(self):

        SNAKE_LENGTH = 3

        def _random_snake_head():
            """init a snake.
            left space for snake body
            """
            head_x = self._rng.randrange(SNAKE_LENGTH + 1, self._w - SNAKE_LENGTH - 1)
            head_y = self._rng.randrange(SNAKE_LENGTH + 1, self._h - SNAKE_LENGTH - 1)
            return Point(head_x, head_y)

        def _random_food(snake_head):
            # rand a food, can't in snake
            while True:
                x = self._rng.randrange(0, self._w)
                y = self._rng.randrange(0, self._h)
                if x == snake_head.x or y == snake_head.y:
                    # food should not be in the same x and y with snake head.
                    continue
                return Point(x, y)

        def _get_direction(snake_head, food):
            # in init, we let snake only has left & right direction
            # should head for the food in the initialization.
            return Direction.RIGHT if snake_head.x <= food.x else Direction.LEFT

        def _init_snake(snake_head, direction):
            # in init, only left/right direction
            tail_x_offset = -1 if direction == Direction.RIGHT else 1
            snake = collections.deque([snake_head])
            for i in range(1, SNAKE_LENGTH):
                tail = Point(snake_head.x + tail_x_offset * i, snake_head.y)
                snake.append(tail)
            return snake

        snake_head = _random_snake_head()
        food = _random_food(snake_head)
        direction = _get_direction(snake_head, food)
        snake = _init_snake(snake_head, direction)

        self.snake = snake
        self.food = food
        self.direction = direction
        self.score = 0
        self.steps = 0
        self.remaining_steps = _calc_max_remaining_steps(self)
        self._status = self.InnerStatus.RUNNING

    def is_success(self):
        """whether SUCCESS
        """
        return self._status == self.InnerStatus.SUCCESS

    def is_fail(self):
        """whether fail
        """
        return self._status == self.InnerStatus.FAIL

    def is_outer_point_collide2snake(self, p: Point) -> bool:
        """whether collide to the snake body?
        here we don't consider the window-edge.
        """
        for test_point in self.snake:
            if test_point == p:
                return True
        return False

    @property
    def state_width(self):
        """get width"""
        return self._w

    @property
    def state_height(self):
        """get height"""
        return self._h

    @property
    def head(self):
        """head"""
        return self.snake[0]

    def __str__(self):
        return f"food={self.food}, snake={self.snake}, step={self.steps}, score={self.score}"

def gen_next_step_point(p: Point, direction: Direction) -> Point:
    """generate next step point according to current point and direction
    """
    if not DirectionUtil.is_effective(direction):
        raise ValueError(f"not effective direction {direction}")

    x = p.x
    y = p.y
    if direction == Direction.LEFT:
        return Point(x - 1, y)
    elif direction == Direction.RIGHT:
        return Point(x + 1, y)
    elif direction == Direction.UP:
        return Point(x, y - 1)
    elif direction == Direction.DOWN:
        return Point(x, y + 1)

    raise ValueError(f"impossible direction [{direction}], something must wrong.")

class DirectionUtil(object):
    """direction util
    """
    _OPPOSITE_DIRECTION_SET = {
        (Direction.LEFT, Direction.RIGHT), (Direction.RIGHT, Direction.LEFT),
        (Direction.UP, Direction.DOWN), (Direction.DOWN, Direction.UP)
    }
    _OPPOSITE_DIRECTION_MAP = dict(_OPPOSITE_DIRECTION_SET)
    _EFFECTIVE_DIRECTION = {Direction.LEFT, Direction.RIGHT, Direction.UP, Direction.DOWN}

    @classmethod
    def get_opposite(cls, d: Direction):
        """get opposite direction
        """
        opposite_direction_dict = cls._OPPOSITE_DIRECTION_MAP
        if d not in opposite_direction_dict:
            raise ValueError(f"not effective action: {d}")
        return opposite_direction_dict[d]

    @classmethod
    def is_opposite(cls, a: Direction, b: Direction) -> bool:
        """whether a and b are the opposite directions
        """
        return (a, b) in cls._OPPOSITE_DIRECTION_SET

    @classmethod
    def is_valid(cls, d: Direction) -> bool:
        """whether d is a valid direction
        """
        return d in {cls.LEFT, cls.RIGHT, cls.UP, cls.DOWN, cls.NONE}

    @classmethod
    def get_effective(cls) -> set:
        """get effective directions
        """
        return cls._EFFECTIVE_DIRECTION

    @classmethod
    def is_effective(cls, d: Direction) -> bool:
        """whether d is a effective direction
        """
        return d in cls.get_effective()

def _calc_max_remaining_steps(game_state: SnakeStateMachine):
    """Calc max remaing steps.
    currently we naively impl it:
        1. if only 1 node, go to food, need max `Width + Height`
        2. for a snake line, the head need to bypass the body, most at `snake-body`
        3. duplicated operations, at most 1.2 -> 2 times (when body short, duplicated op should be less)
    """
    _dist_base = game_state.state_width + game_state.state_height
    _body_len_base = len(game_state.snake)
    _multiplier =  1.2 + 0.8 * (_body_len_base / (game_state.state_width * game_state.state_height))
    _max_val = (_dist_base + _body_len_base) * _multiplier
    _max_val = int(_max_val)
    return _max_val


import readchar
import time

from objects.bomb import Bomb
from objects.sizeable import Sizeable
import objects.utils as utils

class Character(Sizeable): # layer 2
    def __init__(self, map):
        super(Character, self).__init__()
        self.alive = True
        self._set_pos(map[0, 0].x, map[0, 0].y)
        self._set_size(map[0, 0].w, map[0, 0].h)

    def _move(self):
        if self.alive:
            print('player on move.')
        else:
            print('dead already')

    def _get_killed(self):
        self.alive = False
        print('is dead!')

    def _drop_bomb(self, map):
        bomb = Bomb()
        cell = self._curr_cell(map)
        bomb._dropped(cell)
        print('drop bomb.')
        return bomb

    def _rendered(self, screen, **kwargs):
        utils.drawPolygon(screen, pointlist=[(self.x + self.w / 2, self.y + self.h / 2),
                                            (self.x - self.w / 2, self.y + self.h / 2),
                                            (self.x, self.y - self.h / 2)], **kwargs)

    def _curr_cell(self, map):
        return map[int(self.x * map.cols // map.w), int(self.y * map.rows // map.h)]


#         Build train Model
#           Xiaochen  Han
#            Apr 26 2019
#    guillermo_han97@sjtu.edu.cn
#

import tensorflow as tf
import numpy as np
import LoadData as LD
import DefineParam as DP
import tensorflow_probability as tfp
from tensorflow.contrib.layers.python.layers import batch_norm

# Get param
pixel, batchSize, nPhase, nTrainData, trainScale, learningRate, nEpoch, nFrame, ncpkt, trainFile, testFile, maskFile, saveDir, modelDir, name = DP.get_param()

# Build Model
def build_model(phi, restore=False):
    # pre-process
    Xinput, Xoutput, Phi, PhiT, Yinput = LD.pre_calculate(phi)

    # build model
    prediction, predictionSymmetric, transField = build_fista(Xinput, Phi, PhiT, Yinput, reuse=False)

    # loss function
    costMean, costSymmetric, costSparsity = compute_cost(prediction, predictionSymmetric, Xoutput, transField)
    costAll = costMean + 0.01*costSymmetric + 0.001*costSparsity
    optmAll = tf.train.AdamOptimizer(learning_rate=learningRate).minimize(costAll)

    # set up
    init = tf.global_variables_initializer()
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    saver = tf.train.Saver(tf.global_variables(), max_to_keep=100)
    sess = tf.Session(config=config)

    if restore is False:                                       # training
        sess.run(init)
        return sess, saver, Xinput, Xoutput, costAll, optmAll, Yinput, prediction
    else:                                                      # reconstruction
        saver.restore(sess, '%s/%d.cpkt' % (modelDir, ncpkt))
        return sess, saver, Xinput, Xoutput, Yinput, prediction

# Add weight
def get_filter(wShape, nOrder):
    weight = tf.get_variable(shape=wShape, initializer=tf.contrib.layers.xavier_initializer_conv2d(), name='weight_%d' % (nOrder))
    return weight

def build_one_phase(layerxk, layerzk, Phi, PhiT, Yinput):
    # params
    lambdaStep = tf.Variable(0.1, dtype=tf.float32)
    softThr = tf.Variable(0.1, dtype=tf.float32)
    t = tf.Variable(1, dtype=tf.float32)
    convSize1 = 64
    convSize2 = 64
    convSize3 = 64
    filterSize1 = 3
    filterSize2 = 3
    filterSize3 = 3

    # get rk from zk
    rk = tf.reduce_sum(tf.multiply(Phi, layerzk[-1]), axis=3)
    rk = tf.reshape(rk, shape=[-1, pixel, pixel, 1])
    rk = tf.subtract(rk, Yinput)
    rk = tf.multiply(PhiT, tf.tile(rk, [1, 1, 1, nFrame]))
    rk = tf.scalar_mul(lambdaStep, rk)
    rk = tf.subtract(layerzk[-1], rk)

    # F(rk)
    weight0 = get_filter([filterSize1, filterSize1, nFrame, convSize1], 0)
    weight11 = get_filter([filterSize2, filterSize2, convSize1, convSize2], 11)
    weight12 = get_filter([filterSize3, filterSize3, convSize2, convSize3], 12)
    Frk = tf.nn.conv2d(rk, weight0, strides=[1, 1, 1, 1], padding='SAME')
    tmp = Frk
    Frk = tf.nn.conv2d(Frk, weight11, strides=[1, 1, 1, 1], padding='SAME')
    Frk = tf.nn.relu(Frk)
    Frk = tf.nn.conv2d(Frk, weight12, strides=[1, 1, 1, 1], padding='SAME')

    # soft threshold, soft(F(rk), softThr)
    softFrk = tf.multiply(tf.sign(Frk), tf.nn.relu(tf.subtract(tf.abs(Frk), softThr)))

    # ~F(soft(F(rk), softThr))
    weight13 = get_filter([filterSize3, filterSize3, convSize3, convSize2], 53)
    weight14 = get_filter([filterSize2, filterSize2, convSize2, convSize1], 54)
    weight6 = get_filter([filterSize1, filterSize1, convSize1, nFrame], 6)
    FFrk = tf.nn.conv2d(softFrk, weight13, strides=[1, 1, 1, 1], padding='SAME')
    FFrk = tf.nn.relu(FFrk)
    FFrk = tf.nn.conv2d(FFrk, weight14, strides=[1, 1, 1, 1], padding='SAME')
    FFrk = tf.nn.conv2d(FFrk, weight6, strides=[1, 1, 1, 1], padding='SAME')

    # xk = rk + ~F(soft(F(rk), softThr))
    xk = tf.add(rk, FFrk)
    zk = (1 + t)*xk - t*layerxk[-1]

    # Symmetric constraint
    sFFrk = tf.nn.conv2d(Frk, weight13, strides=[1, 1, 1, 1], padding='SAME')
    sFFrk = tf.nn.relu(sFFrk)
    sFFrk = tf.nn.conv2d(sFFrk, weight14, strides=[1, 1, 1, 1], padding='SAME')
    symmetric = sFFrk - tmp
    return xk, zk, symmetric, Frk

# compute fista once (one epoch)
def build_fista(Xinput, Phi, PhiT, Yinput, reuse):
    layerxk = []
    layerzk = []
    layerSymmetric = []
    transField = []
    layerxk.append(Xinput)                            # x0 = x0
    layerzk.append(Xinput)                            # z0 = x0
    for i in range(nPhase):
        with tf.variable_scope('conv_%d' % (i), reuse=reuse):
            xk, zk, convSymmetric, field = build_one_phase(layerxk, layerzk, Phi, PhiT, Yinput)
            layerxk.append(xk)
            layerzk.append(zk)
            layerSymmetric.append(convSymmetric)
            transField.append(field)
    return layerxk, layerSymmetric, transField

# compute loss function
def compute_cost(prediction, predictionSymmetric, Xoutput, transField):
    costMean = 0
    costMean += tf.reduce_mean(tf.square(prediction[-1] - Xoutput))
    costSymmetric = 0
    for k in range(nPhase):
        costSymmetric += tf.reduce_mean(tf.square(predictionSymmetric[k]))
    costSparsity = 0
    for k in range(nPhase):
        costSparsity += tf.reduce_mean(tf.abs(transField[k]))
    return costMean, costSymmetric, costSparsity


#Desenvolva um prgrama que leia o primeiro termo e a razao de uma P.A.
#NO final,mostre os 10 primeiros termos dessa progressao
primeiro=int(input("digite o primeiro termo da P.A.:"))
razao=int(input("Digite a Razão:"))
decimo=primeiro+(10-1)*razao

for c in range(primeiro,decimo+razao,razao):
    print(c, end= " > ")

print("acabou!!")