"""
Init script run by brython-runner for revealjs-ace-brython.
"""
import browser
import sys
import traceback

MSG_TYPE_PREFIX = 'revealjs-ace-brython.'

def send_msg(_type, value):
    """
    Send a message back to the main thread.
    """
    _type = f'{MSG_TYPE_PREFIX}{_type}'
    browser.self.send({'type': _type, 'value': value})

def handler(_type):
    """
    Decorator for defining a handler function.
    """
    def decorator(fn):
        handler.handlers[_type] = fn
        return fn
    return decorator
handler.handlers = {}

@browser.bind(browser.self, 'message')
def handle_message(evt):
    """
    Function that will handle a message from the main thread and route it to
    the appropriate handler.
    """
    if not evt.data.type.startswith(MSG_TYPE_PREFIX):
        return

    _type = evt.data.type[len(MSG_TYPE_PREFIX):]
    if _type not in handler.handlers:
        raise Exception(f'revealjs-ace-brython: no handler found for message type: {_type}')

    handler.handlers[_type](**evt.data.value)

class CustomOuputStream:
    def __init__(self, session_id, code_idx, parent_stream, msg_type_prefix):
        self.session_id = session_id
        self.code_idx = code_idx
        self.parent_stream = parent_stream
        self.msg_type_prefix = msg_type_prefix

    def write(self, data=''):
        send_msg(
            f'{self.msg_type_prefix}-write',
            {
                'session_id': self.session_id,
                'code_idx': self.code_idx,
                'data': str(data),
            },
        )
        self.parent_stream.write(data)

    def flush(self):
        send_msg(
            f'{self.msg_type_prefix}-flush',
            {
                'session_id': self.session_id,
                'code_idx': self.code_idx,
            },
        )
        self.parent_stream.flush()

@handler('exec')
def handle_exec(session_id, codes):
    g = {}
    send_msg('exec-started', {'session_id': session_id})
    saved_stdout = sys.stdout
    saved_stderr = sys.stderr
    try:
        for code_idx, code in enumerate(codes):
            send_msg(
                'exec-code-started',
                {'code_idx': code_idx, 'session_id': session_id},
            )

            sys.stdout = CustomOuputStream(
                session_id=session_id,
                code_idx=code_idx,
                parent_stream=saved_stdout,
                msg_type_prefix='exec-code-stdout',
            )

            sys.stderr = CustomOuputStream(
                session_id=session_id,
                code_idx=code_idx,
                parent_stream=saved_stderr,
                msg_type_prefix='exec-code-stderr',
            )

            try:
                exec(code, g)
            except:
                etype, evalue, tb = sys.exc_info()
                send_msg(
                    'exec-code-error',
                    {
                        'code_idx': code_idx,
                        'session_id': session_id,
                        'error': str(evalue),
                    },
                )
                traceback.print_exception(etype, evalue, tb)
                raise evalue
            else:
                send_msg(
                    'exec-code-success',
                    {'code_idx': code_idx, 'session_id': session_id},
                )
    except Exception as e:
        send_msg('exec-error', {'session_id': session_id, 'error': str(e)})
    else:
        send_msg('exec-success', {'session_id': session_id})
    finally:
        sys.stdout = saved_stdout
        sys.stderr = saved_stderr


from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, JsonResponse
import json
import datetime
from .models import DHTSensor, Watering, Fan

def all_dhtSensor(request, dht_id):
    data = DHTSensor.objects.get(id=dht_id)
    contex = {
        "temperature": str(data.temperature),
        "humidity": str(data.humidity),
    }
    return JsonResponse(contex, safe=False)

def all_watering(request, water_id):
    data = Watering.objects.get(id=water_id)
    contex = {
        "status": str(data.water_request),
        "watering_month": str(data.water_time.month),
        "watering_day": str(data.water_time.day),
        "watering_hour": str(data.water_time.hour),
        "watering_minute": str(data.water_time.minute),
    }
    return JsonResponse(contex, safe=False)

def all_fan(request, fan_id):
    data = Fan.objects.get(id=fan_id)
    contex = {
        "status": str(data.fan_request),
        "fan_month": str(data.fan_time.month),
        "fan_day": str(data.fan_time.day),
        "fan_hour": str(data.fan_time.hour),
        "fan_minute": str(data.fan_time.minute),
    }
    return JsonResponse(contex, safe=False)

@csrf_exempt
def last_dhtSensor(request):
    if request.method == "POST":

        new_dht = json.loads(request.body.decode("utf-8"))
        self_temperature = new_dht["temperature"]
        self_humidity = new_dht["humidity"]

        data = DHTSensor(temperature=self_temperature, humidity=self_humidity)
        data.save()

    elif request.method == "GET":
        data = DHTSensor.objects.latest("id")

    contex = {
        "temperature": str(data.temperature),
        "humidity": str(data.humidity),
    }
    return JsonResponse(contex, safe=False)

@csrf_exempt
def last_watering(request):
    if request.method == "POST":

        if request.POST:
            new_watering = request.POST
            water_req = new_watering["water_request"]
        else:
            new_watering = json.loads(request.body.decode("utf-8"))
            water_req = new_watering["status"]

        water_self_time = datetime.datetime.now()

        w = Watering(water_request=water_req, water_time=water_self_time)
        w.save()

    elif request.method == "GET":
        w = Watering.objects.latest("id")

    contex = {
        "status": str(w.water_request),
        "watering_month": str(w.water_time.month),
        "watering_day": str(w.water_time.day),
        "watering_hour": str(w.water_time.hour),
        "watering_minute": str(w.water_time.minute),
    }
    return JsonResponse(contex, safe=False)

@csrf_exempt
def last_fan(request):
    if request.method == "POST":

        if request.POST:
            new_fan = request.POST
            fan_req = new_fan["fan_request"]
        else:
            new_fan = json.loads(request.body.decode("utf-8"))
            fan_req = new_fan["status"]

        fan_self_time = datetime.datetime.now()

        f = Fan(fan_request=fan_req, fan_time=fan_self_time)
        f.save()

    elif request.method == "GET":
        f = Fan.objects.latest("id")

    contex = {
        "status": str(f.fan_request),
        "fan_month": str(f.fan_time.month),
        "fan_day": str(f.fan_time.day),
        "fan_hour": str(f.fan_time.hour),
        "fan_minute": str(f.fan_time.minute),
    }
    return JsonResponse(contex, safe=False)


"""Import disciplines to Datababse."""
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand

from users.models import Discipline

User = get_user_model()

DISCIPLINES = {
    "iqfoil": {"title": "iQFOiL", "slug": "iqfoil"},
    "openfoil": {"title": "Open Foil", "slug": "openfoil"},
    # "formula": {"title": "Formula", "slug": "formula"},
}

class Command(BaseCommand):
    def import_disciplines(self):
        for discipline in DISCIPLINES:
            try:
                discipline, created = Discipline.objects.get_or_create(
                    title=DISCIPLINES[discipline]["title"],
                    slug=DISCIPLINES[discipline]["slug"],
                )
                if created:
                    discipline.save()
                    display_format = "Discipline, {}, has been saved."
                    print(display_format.format(discipline))
                else:
                    print(f"Discipline -{discipline}- already exists")
            except Exception as ex:
                print(str(ex))
                msg = "\n\nSomething went wrong saving this discipline: "
                "{}\n{}".format(discipline, str(ex))
                print(msg)

    def handle(self, *args, **options):
        """Call the function to import data."""
        self.import_disciplines()


from django.conf import settings
from django.core import mail
from django.test import TestCase, override_settings, tag
from django.urls import reverse

from django_otp.oath import TOTP
from django_otp.plugins.otp_totp.models import TOTPDevice
from magicauth import settings as magicauth_settings

from aidants_connect_web.tests.factories import AidantFactory

@tag("usagers")
class LoginTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.aidant = AidantFactory(
            is_active=False,
            post__with_otp_device=True,
            post__with_carte_totp=True,
        )
        cls.aidant_with_totp_card = AidantFactory(post__with_carte_totp=True)

    def test_inactive_aidant_with_valid_totp_cannot_login(self):
        response = self.client.post(
            "/accounts/login/", {"email": self.aidant.email, "otp_token": "123456"}
        )
        self.assertEqual(response.status_code, 200)
        # Check explicit message is displayed
        self.assertContains(
            response, "Votre compte existe mais il n’est pas encore actif."
        )
        # Check no email was sent
        self.assertEqual(len(mail.outbox), 0)

    def test_magicauth_login_redirects(self):
        response = self.client.get(f"/{magicauth_settings.LOGIN_URL}")

        self.assertRedirects(response, reverse("login"), status_code=301)

    # Prevent being throttled between test attemps
    @override_settings(OTP_TOTP_THROTTLE_FACTOR=0)
    def test_tolerance_on_otp_challenge(self):
        totp_device: TOTPDevice = self.aidant_with_totp_card.carte_totp.totp_device
        token_generator = TOTP(
            totp_device.bin_key,
            totp_device.step,
            totp_device.t0,
            totp_device.digits,
            totp_device.drift,
        )

        def login_and_assert(token, tolerance=1):
            response = self.client.post(
                "/accounts/login/",
                {"email": self.aidant_with_totp_card.email, "otp_token": token},
            )

            self.assertEqual(200, response.status_code)
            totp_device.refresh_from_db()
            self.assertEqual(tolerance, totp_device.tolerance)

        login_and_assert(token_generator.token() + 1, 1)
        login_and_assert(token_generator.token() + 1, 1)
        login_and_assert(
            token_generator.token() + 1, settings.DRIFTED_OTP_CARD_TOLERANCE
        )

        # Login with correct token
        response = self.client.post(
            "/accounts/login/",
            {
                "email": self.aidant_with_totp_card.email,
                "otp_token": token_generator.token(),
            },
        )

        self.assertEqual(302, response.status_code)
        # Simulate proper login
        self.client.force_login(self.aidant_with_totp_card)
        totp_device.refresh_from_db()
        self.assertEqual(1, totp_device.tolerance)


import markdown
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from django.views import generic

from oj.models import Course, Assignment

def index(request):
    return render(request, 'oj/index.html')

class CourseListview(LoginRequiredMixin, generic.ListView):
    model = Course
    paginate_by = 10
    template_name = "oj/course_list.html"

    def get_queryset(self):
        return Course.objects.filter(student=self.request.user)

class CourseDetailView(LoginRequiredMixin, generic.DetailView):
    model = Course
    template_name = 'oj/course/index.html'
    slug_url_kwarg = 'course_identifier'

    def get_slug_field(self):
        return 'identifier'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        assignments = Assignment.objects.filter(course=self.object)
        context['assignments'] = assignments
        self.object.detail_description = markdown.markdown(self.object.detail_description,
                                                           extensions=[
                                                               'markdown.extensions.extra',
                                                               'markdown.extensions.codehilite',  # 代码高亮
                                                               'markdown.extensions.toc'
                                                           ])
        return context

class CourseAssignmentView(LoginRequiredMixin, generic.DetailView):
    template_name = 'oj/course/assignment.html'

    def get_queryset(self):
        self.course = get_object_or_404(Course, identifier=self.kwargs['course_identifier'])
        return Assignment.objects.filter(course=self.course).filter(pk=self.kwargs['pk'])

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # TODO: get extra user related data, such as submission history

        # Needed for left sidebar
        assignments = Assignment.objects.filter(course=self.course).order_by('id')
        context['assignments'] = assignments
        context['course'] = self.course

        # Previous, Next
        previous_assignment = assignments.filter(id__lte=self.object.id).exclude(id=self.object.id).order_by('id')
        next_assignment = assignments.filter(id__gte=self.object.id).exclude(id=self.object.id).order_by('id')
        context['previous_assignment'] = previous_assignment.last()
        context['next_assignment'] = next_assignment.first()

        # Rendered assignment description
        self.object.description = markdown.markdown(self.object.description,
                                                    extensions=[
                                                        'markdown.extensions.extra',
                                                        'markdown.extensions.codehilite',  # 代码高亮
                                                        'markdown.extensions.toc'
                                                    ])

        # Check if deadline is passed.
        context['pass_deadline'] = timezone.now() > self.object.deadline

        # Submission records
        submissions = Submission.objects.filter(user=self.request.user).filter(assignment=self.object)
        context['submissions'] = submissions

        # Get best score
        graded_submissions = submissions.filter(gradereport__isnull=False)
        if len(graded_submissions) == 0:
            best_submission = None
        else:
            best_submission = graded_submissions.order_by('gradereport__grade')[0]
        context['best_submission'] = best_submission

        return context

from .forms import SubmissionForm
from .models import Submission
from bootstrap_modal_forms.generic import BSModalCreateView

class SubmissionCreateView(LoginRequiredMixin, BSModalCreateView):
    template_name = 'oj/course/component/assignment/submit.html'
    form_class = SubmissionForm
    success_message = 'Success: Submission was created.'

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.assignment = get_object_or_404(Assignment,
                                                     id=self.kwargs.get('assignment_pk'))  # new line
        return super().form_valid(form)

    def get_success_url(self):
        return self.request.META.get('HTTP_REFERER')


from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse

from application.models import Application, ApplicantPersonalDetails, AdultInHome

def cancel_app(request):
    """
    This is the page where you can cancel your application and delete all your data
    :param request: HTTP Request
    :return: HTTP Response
    """
    if request.method == 'GET':
        app_id = request.GET["id"]
        variables = {
            'application_id': app_id
        }
        return render(request, 'cancel-application.html', variables)

    if request.method == 'POST':
        app_id = request.POST["id"]
        delete_app(app_id)
        return HttpResponseRedirect(reverse('Cancel-Application-Confirmation'))

def cancel_app_confirmation(request):
    """
    This is one of the cancel application confirmation pages
    :param request: Http Request
    :return: Http Response
    """
    variables = {'AUTHENTICATED': False}
    return render(request, 'cancel-application-confirmation.html', variables)

def cr_cancel_app(request):
    """
    This is the page where you can cancel your application and delete all your data
    :param request: HTTP Request
    :return: HTTP Response
    """
    if request.method == 'GET':
        app_id = request.GET["id"]
        variables = {
            'application_id': app_id
        }
        return render(request, 'cr-cancel-application.html', variables)

    if request.method == 'POST':

        app_id = request.POST["id"]
        delete_app(app_id)

        return HttpResponseRedirect(reverse('CR-Cancel-Application-Confirmation'))

def cl_cancel_app(request):
    """
    Method returning the service unavailable page
    :param request: a request object used to generate the HttpResponse
    :return: an HttpResponse object with the rendered Service unavailable template
    """

    if request.method == 'GET':
        app_id = request.GET["id"]
        variables = {
            'application_id': app_id
        }
        return render(request, 'cl-cancel-application.html', variables)

    if request.method == 'POST':

        app_id = request.POST["id"]
        delete_app(app_id)

        # The cr-cancel-application-confirmation is an appropriate template for both the cl and cr journey.
        return HttpResponseRedirect(reverse('CR-Cancel-Application-Confirmation'))

def cr_cancel_app_confirmation(request):
    """
    This is one of the cancel application confirmation pages
    :param request: Http Request
    :return: Http Response
    """
    return render(request, 'cr-cancel-application-confirmation.html')

def delete_app(app_id):
    """
    Method for deleting an existing application.
    :param app_id: ID of the app to be deleted.
    :return: None.
    """
    AdultInHome.objects.filter(application_id=app_id).delete()
    ApplicantPersonalDetails.objects.filter(application_id=app_id).delete()
    Application.objects.filter(application_id=app_id).delete()


from cs115 import *
#Michael Sanchez
#I pledge my honor that I have abided by the Stevens Honor System
def reverse(a):
    '''reverses a list'''
    if a==[]:
        return []
    else:
        return reverse(a[1:]) + [a[0]]

def change(amount, coins):
    '''Returns the min amount of coins'''
    if coins==[]:
        return float("inf")
    elif coins==[1]:
        return amount
    elif coins[0]==1:
        change(amount,reverse(coins))
    elif amount >= coins[0]:
        c=amount%coins[0]
        return (amount-c)/coins[0]+change(c,coins[1:])
    elif amount < coins[0]:
        return change(amount,coins[1:])


import datetime
from typing import Union
from tweepy import OAuthHandler, Stream, API, Cursor
from tweepy.streaming import StreamListener

import conf.credentials as credentials

class TweepyListener(StreamListener):
    def __init__(self, num_tweets):
        super().__init__()
        self.counter = 0
        self.limit = num_tweets
        self.tweets = []

    # TODO:
    def on_status(self, data):
        try:
            # userid = status.user.id_str
            # print(data)
            self.tweets.append(data)
            self.counter += 1
            if self.counter < self.limit:
                return True
            else:
                return False
        except BaseException as e:
            print('failed on_status,',str(e))

class TwitterAuthenticator():
    def authenticate(self):
        auth = OAuthHandler(credentials.CONSUMER_KEY, credentials.CONSUMER_SECRET)
        auth.set_access_token(credentials.ACCESS_TOKEN, credentials.ACCESS_TOKEN_SECRET)

        return auth

class TweepyDAO():
    def __init__(self):
        self.auth = TwitterAuthenticator().authenticate()
        self.twitter_api = API(self.auth, wait_on_rate_limit=True)

    def get_tweets_by_timeframe_user(self, id, start_date, end_date, num_tweets=None):
        if num_tweets is None:
            total_tweets = Cursor(self.twitter_api.user_timeline, id=id).items()
        else:
            total_tweets = Cursor(self.twitter_api.user_timeline, id=id).items(num_tweets)

        def pred(tweet):
                is_correct_date = tweet.created_at > start_date and tweet.created_at < end_date
                is_correct_user = tweet.user.id == id or tweet.user.screen_name == id
                return is_correct_date and is_correct_user

        tweet_objects = list(filter(pred, total_tweets))
        json_tweets = list(map(lambda t: t._json, tweet_objects))
        return json_tweets

    def get_tweets_by_user(self, id, num_tweets=None):
        if num_tweets is None:
            total_tweets = Cursor(self.twitter_api.user_timeline, id=id).items()
        else:
            total_tweets = Cursor(self.twitter_api.user_timeline, id=id).items(num_tweets)

        json_tweets = list(map(lambda t: t._json, total_tweets))

        return json_tweets

    def get_random_tweets(self):
        listener = TweepyListener(1)

        stream = Stream(self.auth, listener)
        # filter out all non-English Tweets
        stream.filter(languages=["en"])
        stream.sample()

        random_tweet = listener.tweets[0] if len(listener.tweets) != 0 else None
        if random_tweet != None:
            json_tweet = random_tweet._json
            # list(map(lambda t: t._json, random_tweets))
            return json_tweet

        return None

    def get_friends_by_screen_name(self, screen_name, num_friends=None):
        if num_friends is None:
             friends = Cursor(self.twitter_api.friends_ids, screen_name=screen_name).items()
        else:
            friends = Cursor(self.twitter_api.friends_ids, screen_name=screen_name).items(num_friends)

        friends_ids = [friend_id for friend_id in friends]

        return [self.twitter_api.get_user(user_id=friend_id).screen_name for friend_id in friends_ids]

    def get_friends_by_id(self, id, num_friends=None):
        if num_friends is None:
            [friend_id for friend_id in Cursor(self.twitter_api.friends_ids, user_id=id).items()]
        else:
            return [friend_id for friend_id in Cursor(self.twitter_api.friends_ids, user_id=id).items(num_friends)]

    def get_following_by_screen_name(self, screen_name, num_following=None):
        if num_following is None:
            following_users_id = [following_id for following_id in Cursor(self.twitter_api.followers_ids, screen_name=screen_name).items()]
        else:
            following_users_id = [following_id for following_id in Cursor(self.twitter_api.followers_ids, screen_name=screen_name).items(num_following)]

        return [self.twitter_api.get_user(user_id=following_id).screen_name for following_id in following_users_id]

    def get_following_by_id(self, id, num_following=None):
        if num_following is None:
            return [following_id for following_id in Cursor(self.twitter_api.followers_ids, user_id=id).items()]
        else:
            return [following_id for following_id in Cursor(self.twitter_api.followers_ids, user_id=id).items(num_following)]


import socketio
import eventlet
from template_matching import get_game_state
from algorithm import get_command

# create a Socket.IO server
sio = socketio.Server()

@sio.on('send_screenshot')
def send_screenshot(sid, screenshot):
	game_state = get_game_state(screenshot.replace('data:image/png;base64,', ''))
	trex = game_state['trex_location']
	obstacles = game_state['obstacle_locations']
	command = get_command(trex, obstacles)
	sio.emit('execute_command', command)

def main():
	# wrap with a WSGI application
	app = socketio.WSGIApp(sio)
	eventlet.wsgi.server(eventlet.listen(('', 8000)), app)

if __name__ == '__main__':
	main()


# coding: utf-8

line1 = input().rstrip().split(" ")
xc = int(line1[0])
yc = int(line1[1])
r_1 = int(line1[2])
r_2 = int(line1[3])

a = r_1 ** 2
d = r_2 ** 2

n = int(input().rstrip())

results = []

for i in range(n):
    line = input().rstrip().split(" ")
    x_n = int(line[0])
    y_n = int(line[1])

    b = (x_n - xc) ** 2
    c = (y_n - yc) ** 2

    if a <= b + c and b + c <= d:
        results.append("yes")
    else:
        results.append("no")

for result in results:
    print(result)


# GetPopular
# A simple Python3 script to pull top 5 threads from queried subreddits

import requests, sys, json

class GetPopular:
    # Constructor
    def __init__(self):
        self.args = sys.argv[1:]
        self.threads = {}

    def Fetch(self):
        """ Fetch data from Reddit
        """
        for arg in self.args:
            self.threads[arg] = []
            req = requests.get('http://www.reddit.com/r/' + arg + '/.json?limit=3', headers = {'User-agent': 'GetPopular 0.1 by JAFTEM'})
            dump = json.loads(req.text)
            if "data" not in dump:
                print("ERROR 429: Too many requests.")
                return
            data = dump["data"]
            children = data["children"]

            for thread in children:
                d = thread["data"]
                threadData = {}
                threadData["title"] = d["title"]
                threadData["ups"] = d["ups"]
                threadData["url"] = d["url"]
                self.threads[arg].append(threadData)

    def Dump(self):
        """ Dump data from Reddit to command line
        """
        template = "{0:14} {1:30}"
        for key, value in self.threads.items():
            print("+ \033[1m" + key.upper() + "\033[0m")
            for t in value:
                print(template.format("    [+" + str(t["ups"]) + "]", '\033[1m' + t["title"] + '\033[0m'))
                print(template.format(" ", t["url"]))

            print("\n")

if __name__ == "__main__":
    gp = GetPopular()
    gp.Fetch();
    gp.Dump();


import json

from flask import Response

class Controller(object):
    def __init__(self, config):
        self.config = config

    def format_response(self, response):
        if isinstance(response, dict) or isinstance(response, list):
            response = json.dumps(response)
        response = Response(response, mimetype='application/json')
        response.headers['Access-Control-Allow-Origin'] = (
            self.config['CORS_ORIGINS']
        )
        return response

    def create_response(self, service_result, cases):
        code, result = service_result
        # no cases can be considered as fine
        if not isinstance(cases, dict):
            data = {}
            status = 200
        # if the result is True, returns 200
        elif service_result[0] in cases:
            if isinstance(cases[code], tuple):
                data = {'message': cases[code][0], 'code': code.name}
                status = cases[code][1]
            elif callable(cases[code]):
                data = cases[code](result)
                status = 200
            else:
                data = cases[code]
                status = 200
        else:
            data = {'message': "Unknown error"}
            status = 500

        return data, status


class NodoAVL(object):
    def __init__(self, cuenta,monto):
        self._correlativo = 1
        self.cuenta = cuenta#Este es el atributo id (pero con otro nombre...)
        self.monto = monto

        self._izquierdo = None
        self._altura=0
        self._derecho = None
        self._id = self._correlativo =self._correlativo+1

    def insertar(self, val):
        if val.compareTo(self._valor) < 0:
            if self._izquierdo == None:
                self._izquierdo = NodoAVL(val)
            else:
                self._izquierdo.insertar(val)
        elif val.compareTo(self._valor) > 0:
            if self._derecho == None:
                self._derecho = NodoAVL(val)
            else:
                self._derecho.insertar(val)
        else:
            print("No se permiten los valores duplicados: \"" + str.valueOf(val) + "\".")

    def getCodigoGraphviz(self):
        return "digraph grafica{\n" + "rankdir=TB;\n" + "node [shape = record, style=filled, fillcolor=seashell2];\n" + self.getCodigoInterno() + "}\n"

    def getCodigoInterno(self):
        if self._izquierdo == None and self._derecho == None:
            etiqueta = "nodo1" + " [ label =\"" + self.cuenta+"\n"+self.monto+"\n"+ "\"];\n"
        else:
            etiqueta = "nodo2"  + " [ label =\"<C0>|" + self.cuenta + "|<C1>\"];\n"
        if self._izquierdo != None:
            etiqueta = etiqueta + self._izquierdo.getCodigoInterno() + "nodo1"  ":C0->nodo" + str(self._izquierdo._id) + "\n"
        if self._derecho != None:
            etiqueta = etiqueta + self._derecho.getCodigoInterno() + "nodo2" ":C1->nodo" + str(self._derecho._id) + "\n"
        return etiqueta


class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dp = [0] * (len(nums)+1)

        for i in range(len(nums)):
            dp[i+1] = max(0, nums[i]+dp[i])

        if max(dp) == 0:
            return max(nums)

        return max(dp)

42. 连续子数组的最大和.py


#You are creating a fantasy video game. The data structure to model
#the player's inventory will be a dictionary where the keys are
#string values describing the item in the inventory and the value is
#an integer value detailing how many of that item the player has.
#For example, the dictionary value
#{'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
#means the player has 1 rope, 6 torches, 42 gold coins, and so on.

#Write a function named displayInventory() that would take any
#possible "inventory" and display it like the following:
#Inventory:
#12 arrow
#42 gold coin
#1 rope
#6 torch
#1 dagger
#Total number of items: 62

#Hint: you can use a for loop to loop through all the keys in a dictionary.

#Create inventory dictionary
stuff = {'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}

def displayInventory(inventory):
    print("Inventory:")
    item_total=0 #Initialize total item count
    for k,v in inventory.items():
        print(str(v)+' '+k) #Display both item name and quantity
        item_total = item_total + inventory.get(k,0) #Add quantity to total through 'get'ting the item name
    print("Total number of items: "+str(item_total)) #Display total

displayInventory(stuff) #Call function


from django.urls import path
from . import views

app_name = 'posts'

urlpatterns = [

        path('',views.PostListView.as_view(),name='post'),
        path('<slug:slug>/<int:pk>/',views.PostDetailView.as_view(),name='post_detail'),
        path('createpost/',views.CreatePostView.as_view(),name='createPost'),
        path('delete/<int:pk>/',views.DeletePostView.as_view(),name='delete'),
        path('by/<slug:username>/',views.UserPost.as_view(),name='for_user')
]


from flask import Flask, render_template, request, redirect, url_for
from dbfunctions import (
    add_new_task,
    get_complete_tasks,
    get_incomplete_tasks,
    mark_task_complete,
)

app = Flask(__name__, template_folder="client/templates")

@app.route("/")
def index():
    complete = get_complete_tasks()
    incomplete = get_incomplete_tasks()
    return render_template("index.html", complete=complete, incomplete=incomplete)

@app.route("/add", methods=["POST"])
def add():
    task = request.form["todoitem"]
    add_new_task(task)
    return redirect(url_for("index"))

@app.route("/complete/<task>")
def complete(task):
    mark_task_complete(task)
    return redirect(url_for("index"))

if __name__ == "__main__":
    app.run(debug=True)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import numpy as np
import common

def load_json(filename):
    with open(filename, "r") as f:
        return json.load(f)

def load_data(filename):
    j = load_json(filename)
    return j["nsamples"], np.array(j["vx"]), np.array(j["vy"])

# PDFs for velocity components
def velocity_pdfs(dir_sol, dir_fig, lx, show_plot, save_plot, plot_id):

    fn = dir_sol+'measuredData_lx'+str(lx)+'.json'
    nsamples, data_vx, data_vy = load_data(fn)

    titles = [r'Measured at $(x,y) = (0.50, 0.25)$',
              r'Measured at $(x,y) = (0.50, 0.50)$',
              r'Measured at $(x,y) = (0.50, 0.75)$']

    yMaxLims = [35, 70, 140, 280, 560]

    myPlotDict = {}
    myPlotDict['show_plot'] = show_plot
    myPlotDict['save_plot'] = save_plot
    #myPlotDict['xlim'] = [-0.4, 1.2]
    myPlotDict['xlim'] = [-0.8, 1.25]

    if plot_id == 1:
        nbins = [14, 4, 12]
        # nbins = [30, 6, 30]
        myPlotDict['xlabel'] = r'velocity in $x$'
        myPlotDict['ylabel'] = r'number of samples'
        myPlotDict['ylim'] = [0, yMaxLims[lx-3]]
        for n in range(0,3):
            myPlotDict['title'] = titles[n]
            myPlotDict['nbins'] = nbins[n]
            myPlotDict['out_filename'] = dir_fig+"svs_vx"+str(n)+"_lx"+str(lx)+".pdf"
            common.plotHist(data_vx[n*nsamples:(n+1)*nsamples], myPlotDict)

    elif plot_id == 2:
        nbins = [12, 12, 12]
        # nbins = [20, 20, 20]
        myPlotDict['xlabel'] = r'velocity in $y$'
        myPlotDict['ylabel'] = r'number of samples'
        myPlotDict['ylim'] = [0, yMaxLims[lx-3]]
        for n in range(0,3):
            myPlotDict['title'] = titles[n]
            myPlotDict['nbins'] = nbins[n]
            myPlotDict['out_filename'] = dir_fig+"svs_vy"+str(n)+"_lx"+str(lx)+".pdf"
            common.plotHist(data_vy[n*nsamples:(n+1)*nsamples], myPlotDict)

if __name__ == "__main__":

    show_plot = True
    save_plot = True

    dir_sol = '../../output/uq_pincompNS_svs/'
    dir_fig = '../../figures/uq_incompNS/uq_svs/pdfs/'

    lx = 4
    plot_id = 1
    velocity_pdfs(dir_sol, dir_fig, lx, show_plot, save_plot, plot_id)

# End of file


import pommerman
from pommerman import agents
from enum import Enum
import numpy as np
import tensorflow as tf

class Item(Enum):
	"""The Items in the game.

	When picked up:
	  - ExtraBomb increments the agent's ammo by 1.
	  - IncrRange increments the agent's blast strength by 1.
	  - Kick grants the agent the ability to kick items.

	AgentDummy is used by team games to denote the third enemy and by ffa to
	denote the teammate.
	"""
	Passage = 0
	Rigid = 1
	Wood = 2
	Bomb = 3
	Flames = 4
	Fog = 5
	ExtraBomb = 6
	IncrRange = 7
	Kick = 8
	AgentDummy = 9
	Agent0 = 10
	Agent1 = 11
	Agent2 = 12
	Agent3 = 13

def state_to_matrix(obs):
    #In this implementation I just concatenate everything in one big matrix

    #for e in obs['enemies']:
    #    print(e)
    #    print(Item(e))
    #TODO enemies
    my_position = np.asmatrix(obs['position'])
    bomb_life = np.asmatrix(obs['bomb_life'])
    board = np.asmatrix(obs['board'])
    bombs = np.asmatrix(obs['bomb_blast_strength'])
    #enemies = np.asmatrix([Item_en(e) for e in obs['enemies']])
    can_kick = np.asmatrix(int(1 if obs['can_kick'] else 0))
    ammo = np.asmatrix(int(obs['ammo']))
    blast_strength = np.asmatrix(int(obs['blast_strength']))

    m = np.max([my_position.shape[1], bomb_life.shape[1], board.shape[1], bombs.shape[1],  can_kick.shape[1], ammo.shape[1], blast_strength.shape[1]])

    my_position1 = np.concatenate((my_position, np.zeros(( my_position.shape[0], m - my_position.shape[1]))), axis=1)
    bomb_life1 = np.concatenate((bomb_life, np.zeros((bomb_life.shape[0], m - bomb_life.shape[1]))), axis=1)
    board1 = np.concatenate((board, np.zeros((board.shape[0], m - board.shape[1]))), axis=1)
    bombs1 = np.concatenate((bombs, np.zeros((bombs.shape[0], m - bombs.shape[1]))), axis=1)
    #enemies1 = np.concatenate((enemies, np.zeros((enemies.shape[0], m - enemies.shape[1]))), axis=1)
    can_kick1 = np.concatenate((can_kick, np.zeros((can_kick.shape[0], m - can_kick.shape[1]))), axis=1)
    ammo1 = np.concatenate((ammo, np.zeros((ammo.shape[0], m - ammo.shape[1]))), axis=1)
    blast_strength1 = np.concatenate((blast_strength, np.zeros((blast_strength.shape[0], m - blast_strength.shape[1]))), axis=1)

    result = np.concatenate((my_position1, bomb_life1, board1, board1, bombs1, can_kick1, ammo1, blast_strength1), axis=0)
    return np.asmatrix(result)

# def state_to_matrixes(obs):
#     #In this implementation I put all vector in matrix and concatenate this matrixes
#     def get_map(board, item):
#         map = np.zeros(shape)
#         map[board == item] = 1
#         return map

#     def convert_bombs(bomb_map):
#         ret = []
#         locations = np.where(bomb_map > 0)
#         for r, c in zip(locations[0], locations[1]):
#             ret.append({
#                 'position': (r, c),
#                 'blast_strength': int(bomb_map[(r, c)])
#             })
#         return ret

#     board = np.array(obs['board'])

#     rigid_map = get_map(board, 1)  # Rigid = 1
#     wood_map = get_map(board, 2)  # Wood = 2
#     bomb_map = get_map(board, 3)  # Bomb = 3
#     flames_map = get_map(board, 4)  # Flames = 4
#     fog_map = get_map(board, 5)  # Fog = 5
#     extra_bomb_map = get_map(board, 6)  # ExtraBomb = 6
#     incr_range_map = get_map(board, 7)  # IncrRange = 7
#     kick_map = get_map(board, 8)  # Kick = 8
#     skull_map = get_map(board, 9)  # Skull = 9

#     my_position = np.asmatrix(tuple(obs['position']))
#     bomb_life = np.array(obs['bomb_life'])
#     bombs = convert_bombs(np.array(obs['bomb_blast_strength']))
#     enemies = np.asmatrix([constants.Item(e) for e in obs['enemies']])
#     can_kick = np.asmatrix(int(obs['Can Kick']))
#     ammo = np.asmatrix(int(obs['ammo']))
#     blast_strength = np.asmatrix(int(obs['blast_strength']))

#     m = np.max([my_position.shape[1], bomb_life.shape[1], board.shape[1], bombs.shape[1], enemies.shape[1], can_kick.shape[1], ammo.shape[1], blast_strength.shape[1]])

#     my_position1 = np.concatenate((my_position, np.zeros(( my_position.shape[0], m - my_position.shape[1]))), axis=1)
#     bomb_life1 = np.concatenate((bomb_life, np.zeros((bomb_life.shape[0], m - bomb_life.shape[1]))), axis=1)
#     board1 = np.concatenate((board, np.zeros((board.shape[0], m - board.shape[1]))), axis=1)
#     bombs1 = np.concatenate((bombs, np.zeros((bombs.shape[0], m - bombs.shape[1]))), axis=1)
#     enemies1 = np.concatenate((enemies, np.zeros((enemies.shape[0], m - enemies.shape[1]))), axis=1)
#     can_kick1 = np.concatenate((can_kick, np.zeros((can_kick.shape[0], m - can_kick.shape[1]))), axis=1)
#     ammo1 = np.concatenate((ammo, np.zeros((ammo.shape[0], m - ammo.shape[1]))), axis=1)
#     blast_strength1 = np.concatenate((blast_strength, np.zeros((blast_strength.shape[0], m - blast_strength.shape[1]))), axis=1)

#     result = np.concatenate((my_position1, bomb_life1, board1, board1, bombs1, enemies1, can_kick1, ammo1, blast_strength1, rigid_map, wood_map,\
#                              bomb_map, flames_map, fog_map, fog_map, extra_bomb_map, incr_range_map, kick_map, skull_map), axis=0)
#     return result

def state_to_matrix_with_action(obs, action):
    # In this implementation I just concatenate everything in one big matrix

    # for e in obs['enemies']:
    #    print(e)
    #    print(Item(e))
    # TODO enemies
    my_position = np.asmatrix(obs['position'])
    bomb_life = np.asmatrix(obs['bomb_life'])
    board = np.asmatrix(obs['board'])
    bombs = np.asmatrix(obs['bomb_blast_strength'])
    # enemies = np.asmatrix([Item_en(e) for e in obs['enemies']])
    can_kick = np.asmatrix(int(1 if obs['can_kick'] else 0))
    ammo = np.asmatrix(int(obs['ammo']))
    blast_strength = np.asmatrix(int(obs['blast_strength']))

    m = np.max([my_position.shape[1], bomb_life.shape[1], board.shape[1], bombs.shape[1], can_kick.shape[1], ammo.shape[1],
         blast_strength.shape[1]])

    my_position1 = np.concatenate((my_position, np.zeros((my_position.shape[0], m - my_position.shape[1]))), axis=1)
    bomb_life1 = np.concatenate((bomb_life, np.zeros((bomb_life.shape[0], m - bomb_life.shape[1]))), axis=1)
    board1 = np.concatenate((board, np.zeros((board.shape[0], m - board.shape[1]))), axis=1)
    bombs1 = np.concatenate((bombs, np.zeros((bombs.shape[0], m - bombs.shape[1]))), axis=1)
    # enemies1 = np.concatenate((enemies, np.zeros((enemies.shape[0], m - enemies.shape[1]))), axis=1)
    can_kick1 = np.concatenate((can_kick, np.zeros((can_kick.shape[0], m - can_kick.shape[1]))), axis=1)
    ammo1 = np.concatenate((ammo, np.zeros((ammo.shape[0], m - ammo.shape[1]))), axis=1)
    blast_strength1 = np.concatenate((blast_strength, np.zeros((blast_strength.shape[0], m - blast_strength.shape[1]))), axis=1)
    action = np.asmatrix(action)
    action1 = np.concatenate((action, np.zeros((action.shape[0], m - action.shape[1]))), axis=1)
#     print(my_position1.shape, bomb_life1.shape, board1.shape, bombs1.shape, can_kick1.shape, ammo1.shape,
#           blast_strength1.shape, action.shape, action1.shape)
    result = np.concatenate((my_position1, bomb_life1, board1, bombs1, can_kick1, ammo1, blast_strength1, action1),
                            axis=0)
    return np.asmatrix(result)

def normalize(inputs,
              epsilon = 1e-8,
              scope="ln",
              reuse=None):
    '''Applies layer normalization.

    Args:
      inputs: A tensor with 2 or more dimensions, where the first dimension has
        `batch_size`.
      epsilon: A floating number. A very small number for preventing ZeroDivision Error.
      scope: Optional scope for `variable_scope`.
      reuse: Boolean, whether to reuse the weights of a previous layer
        by the same name.

    Returns:
      A tensor with the same shape and data dtype as `inputs`.
    '''
    with tf.variable_scope(scope, reuse=reuse):
        inputs_shape = inputs.get_shape()
        params_shape = inputs_shape[-1:]

        mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True)
#         print('mean', mean, 'variance', variance)
        beta= tf.Variable(tf.zeros(params_shape))
#         print('beta', beta)
        gamma = tf.Variable(tf.ones(params_shape))
#         print('gamma', gamma)
        normalized = (inputs - mean) / ( (variance + epsilon) ** (.5) )
#         print('normalized before', normalized)
        ##Because normalized has float64 type. Need to change to float32 to operate.
        normalized = tf.cast(normalized, tf.float32)
#         print('normalized after', normalized)
        outputs = gamma * normalized + beta
#         print('outputs', outputs)

    return outputs

def embedding(inputs,
              vocab_size,
              num_units,
              zero_pad=True,
              scale=True,
              scope="embedding",
              reuse=None):
    '''Embeds a given tensor.

    Args:
      inputs: A `Tensor` with type `int32` or `int64` containing the ids
         to be looked up in `lookup table`.
      vocab_size: An int. Vocabulary size.
      num_units: An int. Number of embedding hidden units.
      zero_pad: A boolean. If True, all the values of the fist row (id 0)
        should be constant zeros.
      scale: A boolean. If True. the outputs is multiplied by sqrt num_units.
      scope: Optional scope for `variable_scope`.
      reuse: Boolean, whether to reuse the weights of a previous layer
        by the same name.

    Returns:
      A `Tensor` with one more rank than inputs's. The last dimensionality
        should be `num_units`.

    For example,

    ```
    import tensorflow as tf

    inputs = tf.to_int32(tf.reshape(tf.range(2*3), (2, 3)))
    outputs = embedding(inputs, 6, 2, zero_pad=True)
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        print sess.run(outputs)
    >>
    [[[ 0.          0.        ]
      [ 0.09754146  0.67385566]
      [ 0.37864095 -0.35689294]]

     [[-1.01329422 -1.09939694]
      [ 0.7521342   0.38203377]
      [-0.04973143 -0.06210355]]]
    ```

    ```
    import tensorflow as tf

    inputs = tf.to_int32(tf.reshape(tf.range(2*3), (2, 3)))
    outputs = embedding(inputs, 6, 2, zero_pad=False)
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        print sess.run(outputs)
    >>
    [[[-0.19172323 -0.39159766]
      [-0.43212751 -0.66207761]
      [ 1.03452027 -0.26704335]]

     [[-0.11634696 -0.35983452]
      [ 0.50208133  0.53509563]
      [ 1.22204471 -0.96587461]]]
    ```
    '''
    with tf.variable_scope(scope, reuse=reuse):
        lookup_table = tf.get_variable('lookup_table',
                                       dtype=tf.float32,
                                       shape=[vocab_size, num_units],
                                       initializer=tf.contrib.layers.xavier_initializer())
        if zero_pad:
            lookup_table = tf.concat((tf.zeros(shape=[1, num_units]),
                                      lookup_table[1:, :]), 0)
            print('lookup_table', lookup_table)
            print('inputs', inputs)
        outputs = tf.nn.embedding_lookup(lookup_table, inputs)
        print('outputs', outputs)

        if scale:
            outputs = outputs * (num_units ** 0.5)

    return outputs

def positional_encoding(inputs,
                        num_units,
                        zero_pad=True,
                        scale=True,
                        scope="positional_encoding",
                        reuse=None):
    '''Sinusoidal Positional_Encoding.

    Args:
      inputs: A 2d Tensor with shape of (N, T).
      num_units: Output dimensionality
      zero_pad: Boolean. If True, all the values of the first row (id = 0) should be constant zero
      scale: Boolean. If True, the output will be multiplied by sqrt num_units(check details from paper)
      scope: Optional scope for `variable_scope`.
      reuse: Boolean, whether to reuse the weights of a previous layer
        by the same name.

    Returns:
        A 'Tensor' with one more rank than inputs's, with the dimensionality should be 'num_units'
    '''

    N, T = inputs.get_shape().as_list()
    with tf.variable_scope(scope, reuse=reuse):
        position_ind = tf.tile(tf.expand_dims(tf.range(T), 0), [N, 1])

        # First part of the PE function: sin and cos argument
        position_enc = np.array([
            [pos / np.power(10000, 2.*i/num_units) for i in range(num_units)]
            for pos in range(T)])

        # Second part, apply the cosine to even columns and sin to odds.
        position_enc[:, 0::2] = np.sin(position_enc[:, 0::2])  # dim 2i
        position_enc[:, 1::2] = np.cos(position_enc[:, 1::2])  # dim 2i+1

        # Convert to a tensor
        lookup_table = tf.convert_to_tensor(position_enc)

        if zero_pad:
            lookup_table = tf.concat((tf.zeros(shape=[1, num_units]),
                                      lookup_table[1:, :]), 0)
        outputs = tf.nn.embedding_lookup(lookup_table, position_ind)

        if scale:
            outputs = outputs * num_units**0.5

        return outputs

def multihead_attention(queries,
                        keys,
                        num_units=None,
                        num_heads=8,
                        dropout_rate=0,
                        is_training=True,
                        causality=False,
                        scope="multihead_attention",
                        reuse=None):
    '''Applies multihead attention.

    Args:
      queries: A 3d tensor with shape of [N, T_q, C_q].
      keys: A 3d tensor with shape of [N, T_k, C_k].
      num_units: A scalar. Attention size.
      dropout_rate: A floating point number.
      is_training: Boolean. Controller of mechanism for dropout.
      causality: Boolean. If true, units that reference the future are masked.
      num_heads: An int. Number of heads.
      scope: Optional scope for `variable_scope`.
      reuse: Boolean, whether to reuse the weights of a previous layer
        by the same name.

    Returns
      A 3d tensor with shape of (N, T_q, C)
    '''
    with tf.variable_scope(scope, reuse=reuse):
        # Set the fall back option for num_units
        if num_units is None:
            num_units = queries.get_shape().as_list[-1]

        # Linear projections
        Q = tf.layers.dense(queries, num_units, activation=tf.nn.relu) # (N, T_q, C)
        K = tf.layers.dense(keys, num_units, activation=tf.nn.relu) # (N, T_k, C)
        V = tf.layers.dense(keys, num_units, activation=tf.nn.relu) # (N, T_k, C)

        # Split and concat
        Q_ = tf.concat(tf.split(Q, num_heads, axis=2), axis=0) # (h*N, T_q, C/h)
        K_ = tf.concat(tf.split(K, num_heads, axis=2), axis=0) # (h*N, T_k, C/h)
        V_ = tf.concat(tf.split(V, num_heads, axis=2), axis=0) # (h*N, T_k, C/h)

        # Multiplication
        outputs = tf.matmul(Q_, tf.transpose(K_, [0, 2, 1])) # (h*N, T_q, T_k)

        # Scale
        outputs = outputs / (K_.get_shape().as_list()[-1] ** 0.5)

        # Key Masking
        key_masks = tf.sign(tf.abs(tf.reduce_sum(keys, axis=-1))) # (N, T_k)
        key_masks = tf.tile(key_masks, [num_heads, 1]) # (h*N, T_k)
        key_masks = tf.tile(tf.expand_dims(key_masks, 1), [1, tf.shape(queries)[1], 1]) # (h*N, T_q, T_k)

        paddings = tf.ones_like(outputs)*(-2**32+1)
        outputs = tf.where(tf.equal(key_masks, 0), paddings, outputs) # (h*N, T_q, T_k)

        # Causality = Future blinding
        if causality:
            diag_vals = tf.ones_like(outputs[0, :, :]) # (T_q, T_k)
            tril = tf.linalg.LinearOperatorLowerTriangular(diag_vals).to_dense() # (T_q, T_k)
            masks = tf.tile(tf.expand_dims(tril, 0), [tf.shape(outputs)[0], 1, 1]) # (h*N, T_q, T_k)

            paddings = tf.ones_like(masks)*(-2**32+1)
            outputs = tf.where(tf.equal(masks, 0), paddings, outputs) # (h*N, T_q, T_k)

        # Activation
        outputs = tf.nn.softmax(outputs) # (h*N, T_q, T_k)

        # Query Masking
        query_masks = tf.sign(tf.abs(tf.reduce_sum(queries, axis=-1))) # (N, T_q)
        query_masks = tf.tile(query_masks, [num_heads, 1]) # (h*N, T_q)
        query_masks = tf.tile(tf.expand_dims(query_masks, -1), [1, 1, tf.shape(keys)[1]]) # (h*N, T_q, T_k)
        outputs *= query_masks # broadcasting. (N, T_q, C)

        # Dropouts
        outputs = tf.layers.dropout(outputs, rate=dropout_rate, training=tf.convert_to_tensor(is_training))

        # Weighted sum
        outputs = tf.matmul(outputs, V_) # ( h*N, T_q, C/h)

        # Restore shape
        outputs = tf.concat(tf.split(outputs, num_heads, axis=0), axis=2 ) # (N, T_q, C)

        # Residual connection
        outputs += queries
#         print('outputs', outputs)
        # Normalize
        outputs = normalize(outputs) # (N, T_q, C)

    return outputs

def feedforward(inputs,
                num_units=[2048, 512],
                scope="multihead_attention",
                reuse=None):
    '''Point-wise feed forward net.

    Args:
      inputs: A 3d tensor with shape of [N, T, C].
      num_units: A list of two integers.
      scope: Optional scope for `variable_scope`.
      reuse: Boolean, whether to reuse the weights of a previous layer
        by the same name.

    Returns:
      A 3d tensor with the same shape and dtype as inputs
    '''
    with tf.variable_scope(scope, reuse=reuse):
        # Inner layer
        params = {"inputs": inputs, "filters": num_units[0], "kernel_size": 1,
                  "activation": tf.nn.relu, "use_bias": True}
        outputs = tf.layers.conv1d(**params)

        # Readout layer
        params = {"inputs": outputs, "filters": num_units[1], "kernel_size": 1,
                  "activation": None, "use_bias": True}
        outputs = tf.layers.conv1d(**params)

        # Residual connection
        outputs += inputs

        # Normalize
        outputs = normalize(outputs)

    return outputs

def label_smoothing(inputs, epsilon=0.1):
    '''Applies label smoothing. See https://arxiv.org/abs/1512.00567.

    Args:
      inputs: A 3d tensor with shape of [N, T, V], where V is the number of vocabulary.
      epsilon: Smoothing rate.

    For example,

    ```
    import tensorflow as tf
    inputs = tf.convert_to_tensor([[[0, 0, 1],
       [0, 1, 0],
       [1, 0, 0]],

      [[1, 0, 0],
       [1, 0, 0],
       [0, 1, 0]]], tf.float32)

    outputs = label_smoothing(inputs)

    with tf.Session() as sess:
        print(sess.run([outputs]))

    >>
    [array([[[ 0.03333334,  0.03333334,  0.93333334],
        [ 0.03333334,  0.93333334,  0.03333334],
        [ 0.93333334,  0.03333334,  0.03333334]],

       [[ 0.93333334,  0.03333334,  0.03333334],
        [ 0.93333334,  0.03333334,  0.03333334],
        [ 0.03333334,  0.93333334,  0.03333334]]], dtype=float32)]
    ```
    '''
    K = inputs.get_shape().as_list()[-1] # number of channels
    return ((1-epsilon) * inputs) + (epsilon / K)

def model_NN1(features, labels, mode):
    #Implement 3 seperate preprocessing and combine them together
    # implementation of NN with 3 inputs: https://stackoverflow.com/questions/40318457/how-to-build-a-multiple-input-graph-with-tensor-flow

    # First state preprocessing
    input_layer_state1 = tf.reshape(features["state1"], [-1, 49, 11, 1])
    conv1_state1 = tf.layers.conv2d(
        inputs=input_layer_state1,
        filters=32,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)
    # Output Tensor Shape: [batch_size, 49, 11, 32]
    pool1_state1 = tf.layers.max_pooling2d(inputs=conv1_state1, pool_size=[2, 2], strides=2)
    # Output Tensor Shape: [batch_size, 24, 6, 32]
    conv2_state1 = tf.layers.conv2d(
        inputs=pool1_state1,
        filters=64,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)
    # Output Tensor Shape: [batch_size, 24, 5, 64]
    pool2_state1 = tf.layers.max_pooling2d(inputs=conv2_state1, pool_size=[2, 2], strides=2)
    pool2_flat_state1 = tf.reshape(pool2_state1, [-1, 12 * 2 * 64])

    # Second state preprocessing
    # Outputs equal to state1
    input_layer_state2 = tf.reshape(features["state2"], [-1, 49, 11, 1])
    conv1_state2 = tf.layers.conv2d(
        inputs=input_layer_state2,
        filters=32,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)
    pool1_state2 = tf.layers.max_pooling2d(inputs=conv1_state2, pool_size=[2, 2], strides=2)
    conv2_state2 = tf.layers.conv2d(
        inputs=pool1_state2,
        filters=64,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)

    pool2_state2 = tf.layers.max_pooling2d(inputs=conv2_state2, pool_size=[2, 2], strides=2)
    pool2_flat_state2 = tf.reshape(pool2_state2, [-1, 12 * 2 * 64])

    whole_model = tf.concat([pool2_flat_state2, pool2_flat_state1], 1) # (1,3072)

    dense = tf.layers.dense(inputs=whole_model, units=1024, activation=tf.nn.relu) #(1, 1024)

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

    decoder_inputs = tf.concat((tf.ones_like(labels[:, :1])*2, labels[:, :-1]), -1) #(1,120)
# #     print('decoder_inputs', decoder_inputs)

    # Encoder
    with tf.variable_scope("encoder"):

        ## Positional Encoding
        enc = positional_encoding(dense, num_units=512, zero_pad=False, scale=False, scope="enc_pe")

        ## Dropout
        enc = tf.layers.dropout(enc, rate=0.1, training=tf.convert_to_tensor(True))

        ## Blocks
        for i in range(6):
            with tf.variable_scope("num_blocks_{}".format(i)):
                ### Multihead Attention
                enc = multihead_attention(queries=enc, keys=enc, num_units=512, num_heads=8,
                                          dropout_rate=0.1, is_training=True, causality=False)

                ### Feed Forward
                enc = feedforward(enc, num_units=[4*512, 512])

    # Decoder
    with tf.variable_scope("decoder"):

        ## Positional Encoding
        dec = positional_encoding(decoder_inputs, num_units=512, zero_pad=False, scale=False, scope="dec_pe")

        ## Dropout
        dec = tf.layers.dropout(dec, rate=0.1, training=tf.convert_to_tensor(True))

        ## Blocks
        for i in range(6):
            with tf.variable_scope("num_blocks_{}".format(i)):
                ## Multihead Attention ( self-attention)
                dec = multihead_attention(queries=dec, keys=dec, num_units=512, num_heads=8, dropout_rate=0.1,
                                          is_training=True,causality=True, scope="self_attention")

                ## Multihead Attention ( vanilla attention)
                dec = multihead_attention(queries=dec, keys=dec, num_units=512, num_heads=8, dropout_rate=0.1,
                                          is_training=True,causality=False, scope="vanilla_attention")

                ## Feed Forward
                dec = feedforward(dec, num_units=[4*512, 512])

        # Final linear projection
        dec = tf.layers.dense(dec, 1024)
        dec = tf.reshape(dec, [1, -1])

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

    # Output Tensor Shape: [batch_size, 1024]
    dropout = tf.layers.dropout(inputs=dec, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)
    print('dropout', dropout) #(1, 120, 1024)

    logits = tf.layers.dense(inputs=dropout, units=120) # shape of matrix -- 30 * 4

    predictions = {
        "classes": tf.argmax(input=logits, axis=1),
        "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
    }

    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

    print('labels', labels, 'logits', logits) #labels: (1,120), logits: (1,120,120)

    loss = tf.losses.mean_squared_error(labels=labels, predictions=logits)

    if mode == tf.estimator.ModeKeys.TRAIN:
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
        train_op = optimizer.minimize(
            loss=loss,
            global_step=tf.train.get_global_step())
        return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

    eval_metric_ops = {
        "accuracy": tf.metrics.accuracy(
            labels=labels, predictions=predictions["classes"])}

    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)

def model_NN2(features, labels, mode):
    # Implement 2 seperate preprocessing of state and graph and combine them together

    # implementation of NN with 3 inputs: https://stackoverflow.com/questions/40318457/how-to-build-a-multiple-input-graph-with-tensor-flow

    # First state preprocessing
    input_layer_state1 = tf.reshape(features["state1"], [-1, 49, 11, 1])
    conv1_state1 = tf.layers.conv2d(
        inputs=input_layer_state1,
        filters=32,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)
    pool1_state1 = tf.layers.max_pooling2d(inputs=conv1_state1, pool_size=[2, 2], strides=2)
    conv2_state1 = tf.layers.conv2d(
        inputs=pool1_state1,
        filters=64,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)
    pool2_state1 = tf.layers.max_pooling2d(inputs=conv2_state1, pool_size=[2, 2], strides=2)
    pool2_flat_state1 = tf.reshape(pool2_state1, [-1, 12 * 2 * 64])

    # Graph preprocessing
    input_layer = tf.reshape(features["graph"], [-1, 4, 30, 1])
    conv1 = tf.layers.conv2d(
        inputs=input_layer,
        filters=32,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)
    pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)
    conv2 = tf.layers.conv2d(
        inputs=pool1,
        filters=64,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)
    conv2_flat = tf.reshape(conv2, [-1, 2 * 15 * 64])

    whole_model = tf.concat([pool2_flat_state1, conv2_flat], 1)

    dense = tf.layers.dense(inputs=whole_model, units=1024, activation=tf.nn.relu)
    dropout = tf.layers.dropout(
        inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)
    logits = tf.layers.dense(inputs=dropout, units=10)

    predictions = {
        "classes": tf.argmax(input=logits, axis=1),
        "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
    }

    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

    onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10)
#     print('H')
    loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=logits)
#     print(loss.shape, onehot_labels.shape)

    # Configure the Training Op (for TRAIN mode)
    if mode == tf.estimator.ModeKeys.TRAIN:
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
        train_op = optimizer.minimize(
            loss=loss,
            global_step=tf.train.get_global_step())
        return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode=mode, loss=loss, predictions=predictions["classes"])

    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, predictions=predictions)

def main():

	# Print all possible environments in the Pommerman registry
	print(pommerman.registry)
	# sess = tf.Session()
	#sess = tf_debug.TensorBoardDebugWrapperSession(sess, 'localhost:6064')

	# Create a set of agents (exactly four)
	agent_list = [
	    agents.SimpleAgent(),
	    agents.SimpleAgent(),
	    agents.RandomAgent(),
	    agents.RandomAgent(),
	    # agents.DockerAgent("pommerman/simple-agent", port=12345),
	]
	env = pommerman.make('PommeFFACompetition-v0', agent_list)

	# Create the Estimator
	estimator_nn1 = tf.estimator.Estimator(model_fn=model_NN1, model_dir="/tmp/sa_nn1")
	# Set up logging for predictions
	tensors_to_logNN1 = {"probabilities": "softmax_tensor"}
	logging_hook_nn1 = tf.train.LoggingTensorHook(tensors=tensors_to_logNN1, every_n_iter=50)

	# Create the Estimator
	estimator_nn2 = tf.estimator.Estimator(model_fn=model_NN2, model_dir="/tmp/sa_nn2")
	# Set up logging for predictions
	tensors_to_logNN2 = {"probabilities": "softmax_tensor"}
	logging_hook_nn2 = tf.train.LoggingTensorHook(tensors=tensors_to_logNN2, every_n_iter=50)

	r_sum = np.zeros(1)
	for i in range(1):
	    # Make the "Free-For-All" environment using the agent list
	    env.reset()
	    # Run the episodes just like OpenAI Gym
	    for i_episode in range(1):
	        state = env.reset()

	        done = False
	        curr_state = None
	        prev_state = None
	        graph = np.random.rand(4, 30).astype("float32") + 0.0001
	#         print(graph)
	        pr_action = None
	        pr_pr_action = None

	        while not done:
	#             env.render()
	            actions = env.act(state)
	            state, reward, done, info = env.step(actions)
	            r_sum[i] += reward[0]

	            # as basic implementation I consider only one agent
	            prev_state = curr_state
	            curr_state = state

	            if pr_pr_action is not None:
	                # Train the model
	                for agent_num in range(4):
	                    train_input_NN2 = tf.estimator.inputs.numpy_input_fn(
	                        x={"state1": np.resize(
	                                state_to_matrix_with_action(curr_state[agent_num], action=pr_action[agent_num])\
	                                .astype("float32"), (1, 49*11)),
	                           "graph": np.resize(graph, (1, 4*30))
	                          },
	                        y=np.asarray([actions[agent_num]]),
	                        batch_size=1,
	                        num_epochs=None,
	                        shuffle=True)

	                    train_input_NN1 = tf.estimator.inputs.numpy_input_fn(
	                        x={"state1": np.resize(
	                                state_to_matrix_with_action(prev_state[agent_num], action=pr_pr_action[agent_num])\
	                                .astype("float32"), (1, 49 * 11)),
	                           "state2": np.resize(
	                                state_to_matrix_with_action(curr_state[agent_num], action=pr_action[agent_num])\
	                               .astype("float32"), (1, 49 * 11))},
	                        y=np.asmatrix(graph.flatten()),
	                        batch_size=1,
	                        num_epochs=None,
	                        shuffle=True)

	                    estimator_nn1.train(
	                        input_fn=train_input_NN1,
	                        steps=200,
	                        hooks=[logging_hook_nn1])

	                    estimator_nn2.train(
	                        input_fn=train_input_NN2,
	                        steps=200,
	                        hooks=[logging_hook_nn2])
	                    predictions = estimator_nn2.predict(input_fn=train_input_NN2)
	                    #next_action = np.array(list(p['classes'] for p in predictions))
	            pr_pr_action = pr_action
	            pr_action = actions
	        if i_episode > 300:
	            break
	    print('Game {} finished'.format(i))

	np.savetxt('result_2simple_2random.csv', r_sum, fmt='%1.4e')
	env.close()

if __name__ == '__main__':
	main()


import numpy as np

def read_yuv420(filename, w, h, n_frame, start_frame=0):

    y_size = int(w*h)
    uv_size = int(w/2*h/2)
    y_sequence = []
    uv_sequence = []

    # file read
    f = open(filename, "rb")

    # start_frame offset
    if start_frame > 0:
        frame_size = y_size + (2*uv_size)
        f.seek(start_frame * frame_size)

    for i in range(0, n_frame):
        plane_y = np.fromfile(f, dtype=np.uint8, count=y_size).reshape(h, w)
        plane_u = np.fromfile(f, dtype=np.uint8, count=uv_size).reshape(int(h/2), int(w/2))
        plane_v = np.fromfile(f, dtype=np.uint8, count=uv_size).reshape(int(h/2), int(w/2))

        ## normalize
        #plane_y = plane_y / 255.
        #plane_u = plane_u / 255.
        #plane_v = plane_v / 255.

        # reshape
        plane_y = plane_y.reshape((plane_y.shape[0], plane_y.shape[1], 1))
        plane_u = plane_u.reshape((plane_u.shape[0], plane_u.shape[1], 1))
        plane_v = plane_v.reshape((plane_v.shape[0], plane_v.shape[1], 1))

        # make UV of shape [height, width, color_plane]
        uv = np.concatenate((plane_u, plane_v), axis=2)

        # append to list
        y_sequence.append(plane_y)
        uv_sequence.append(uv)

    f.close()

    # Make list to numpy array. With this transform
    y_array = np.asarray(y_sequence) # [n_frames, h, w, 3]
    uv_array = np.asarray(uv_sequence) # [n_frames, h, w, 3]

    return y_array, uv_array


#!/usr/bin/env python3

import os
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
FILENAME = '{}/../input.txt'.format(SCRIPT_PATH)

# Read the challenge input
with open(FILENAME, 'r') as input_file:
    PUZZLE_INPUT = input_file.readlines()

support_ssl = 0

for ip in PUZZLE_INPUT:
    abas = {}
    babs = {}
    inside_brackets = False
    for letter_idx in range(len(ip) - 2):
        if ip[letter_idx] == '[':
            inside_brackets = True
            continue
        if ip[letter_idx] == ']':
            inside_brackets = False
            continue

        if ip[letter_idx] == ip[letter_idx + 2] and ip[letter_idx] != ip[letter_idx + 1]:
            code = ip[letter_idx:letter_idx + 3]
            corresponding_code = code[1] + code[0] + code[1]
            if inside_brackets:
                babs[code] = letter_idx
                if corresponding_code in abas:
                    support_ssl += 1
                    break
            else:
                abas[code] = letter_idx
                if corresponding_code in babs:
                    support_ssl += 1
                    break

print(support_ssl, 'IPs support SSL.')


"""
Training code for Adversarial patch training using Faster RCNN based on mmdetection
Redo UPC in PyTorch

"""
import os
os.environ["CUDA_VISIBLE_DEVICES"] = '0,1,2,3'

import PIL
import cv2
# from load_data import *
import copy
from tqdm import tqdm
from mmdet import __version__
from mmdet.apis import init_detector, inference_detector, show_result_pyplot, get_Image_ready
import mmcv
from mmcv.ops import RoIAlign, RoIPool
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel

import torch
import gc
import matplotlib.pyplot as plt
from torch import autograd
from torchvision import transforms

import subprocess
# from utils.utils import *
import numpy as np
import pickle

# import patch_config as patch_config
import sys
import time

# from brambox.io.parser.annotation import DarknetParser as anno_darknet_parse
# from utils import *
from skimage.segmentation import slic
from skimage.util import img_as_float
from skimage import io
from skimage.segmentation import mark_boundaries
import os
from PIL import Image
import torch.optim as optim
import torch.nn.functional as F
import skimage.io as io
from train_patch_frcn_measure_no_stop_gray_step_3_0920 import measure_region_with_attack
import math
from dataset.coco_train_1000_PERSON import CocoTrainPerson
from dataset.sp_geter_dataset import SuperPixelGet

from torch.utils.data import DataLoader,Dataset
from utils.tv_loss import TVLoss
from utils.iou import compute_iou_tensor

seed = 2020
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)

csv_name = 'x_result2.csv'
# torch.cuda.set_device(0)

def gkern(kernlen=21, nsig=3):
    """Returns a 2D Gaussian kernel array."""
    import scipy.stats as st

    x = np.linspace(-nsig, nsig, kernlen)
    kern1d = st.norm.pdf(x)
    kernel_raw = np.outer(kern1d, kern1d)
    kernel = kernel_raw / kernel_raw.sum()
    return kernel

class PatchTrainer(object):
    def __init__(self, mode):
        # self.config = patch_config.patch_configs[mode]()

        # self.darknet_model = Darknet(self.config.cfgfile)
        # self.darknet_model.load_weights(self.config.weightfile)
        # self.darknet_model = self.darknet_model.eval().cuda() # TODO: Why eval?

        self.ocpy_list = []
        for i in range(4):
            if i ==0:
                ocpy_tensor = torch.rand(500,500,500,3).cuda(i)
                self.ocpy_list.append(ocpy_tensor)
                continue

            ocpy_tensor = torch.rand(500,500,500,6).cuda(i)
            self.ocpy_list.append(ocpy_tensor)

        self.config_file = './configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py'
        self.checkpoint_file = '../common_data/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth'
        self.Faster_RCNN = init_detector(self.config_file, self.checkpoint_file, device='cpu').cuda()

        # self.Faster_RCNN = MMDistributedDataParallel(
        #     self.Faster_RCNN.cuda(),
        #     device_ids=[torch.cuda.current_device()],
        #     broadcast_buffers=False)

        self.Faster_RCNN = torch.nn.DataParallel(self.Faster_RCNN)

        # self.patch_applier = PatchApplier().cuda()
        # self.patch_transformer = PatchTransformer().cuda()
        # self.prob_extractor = MaxProbExtractor(0, 80, self.config).cuda()
        # self.nps_calculator = NPSCalculator(self.config.printfile, self.config.patch_size).cuda()
        # self.total_variation = TotalVariation().cuda()
        self.mean = torch.Tensor([123.675, 116.28, 103.53]).unsqueeze(0).unsqueeze(-1).unsqueeze(-1).cuda()
        self.std = torch.Tensor([58.395, 57.12, 57.375]).unsqueeze(0).unsqueeze(-1).unsqueeze(-1).cuda()

        # self.writer = self.init_tensorboard(mode)

    def Transform_Patch(self, patch):
        # clamp_patch = torch.clamp(patch, 0.01, 254.99)
        clamp_patch = patch
        unsqueezed_patch = clamp_patch.unsqueeze(0)
        resized_patch = F.interpolate(unsqueezed_patch, (800, 800), mode='bilinear').cuda()
        normalized_patch = (resized_patch - self.mean) / self.std
        return normalized_patch

    def Transform_Patch_batch(self, patch):
        clamp_patch = torch.clamp(patch, 0.01, 254.99)
        resized_patch = F.interpolate(clamp_patch, (800, 800), mode='bilinear').cuda()
        normalized_patch = (resized_patch - self.mean) / self.std
        return normalized_patch

    def train(self):
        """
        Optimize a patch to generate an adversarial example.
        :return: Nothing
        """

        img_size = 800
        batch_size = 1
        n_epochs = 5000
        max_lab = 14

        ATTACK_TASK = 'target'

        # TARGET_CLASS = 'dog'
        TARGET_CLASS = 16
        # ATTACK_TASK = 'untarget'

        time_str = time.strftime("%Y%m%d-%H%M%S")

        conv_size = 2
        kernel1 = gkern(2*conv_size+1, 3).astype(np.float32)
        stack_kernel1 = np.stack([kernel1, kernel1, kernel1]).swapaxes(2, 0)
        stack_kernel1 = np.expand_dims(stack_kernel1, 3)
        stack_kernel1 = torch.from_numpy(stack_kernel1).permute(2,3,0,1).float()

        # Dataset prepare

        data_obj = CocoTrainPerson(dataType='train2017',num_use=500)
        dataloader_obj = DataLoader(data_obj, batch_size=1,shuffle=False) #使用DataLoader加载数据

        # img info prepare
        img_frcn = get_Image_ready(self.Faster_RCNN.module, '1016.png')
        img_frcn['img_metas'][0][0]['filename'] = None
        img_frcn['img_metas'][0][0]['ori_filename'] = None
        img_frcn['img_metas'][0][0]['ori_shape'] = None
        img_frcn['img_metas'][0][0]['pad_shape'] = None
        img_frcn['img_metas'][0][0]['scale_factor'] = None

        # attack_area_rate = 0.2
        ATTACK_AREA_RATE = 0.1
        evo_step_num = 20
        batch_size_sp = 12
        population_num = 72 # 36
        optim_step_num = 300
        k = 0
        for i_batch, batch_data in enumerate(dataloader_obj):
            img, mask, bbox, class_label = batch_data[0][0], batch_data[1][0], batch_data[2][0], batch_data[3][0]
            # img  : 3,500,500
            # mask : 500,500
            # bbox : x1,y1,w,h
            # class_label : tensor[]

            img_name = batch_data[4][0]

            print('---------------')
            print(img_name)
            print('---------------')

            save_dir = os.path.join('../common_data/NES_search_test_1107/', img_name.split('.')[0])
            if os.path.exists(save_dir):
                continue
            time0 = time.time()

            # use segment SLIC
            base_SLIC_seed_num = 3000
            img_np = img.numpy().transpose(1,2,0)
            mask_np = mask.numpy()
            numSegments = int(base_SLIC_seed_num/(500*500)*torch.sum(mask))
            segments_np = slic(image=img_np, n_segments=numSegments, sigma=0, slic_zero=True, mask=mask_np)
            segments_tensor = torch.from_numpy(segments_np).float().cuda()
            segments_label = torch.unique(segments_tensor)
            segments_label = segments_label[1:]

            # define theta_m
            # pay attention to the center and the boundary

            # (0) prepare stack of sp
            # (1) find the center sp
            # (2) find the boundary sp

            # (0) prepare stack of sp
            zero_layer = torch.zeros_like(segments_tensor)
            one_layer = torch.ones_like(segments_tensor)
            segments_stack = torch.stack([torch.where(segments_tensor==segments_label[j], segments_tensor, zero_layer) for j in range(segments_label.shape[0])], dim=0)
            segments_stack = segments_stack.cpu()

            mask_area = torch.sum(mask)
            # (1) find the center sp
            bbox_x1 = bbox[0]
            bbox_y1 = bbox[1]
            bbox_w = bbox[2]
            bbox_h = bbox[3]

            bbox_x_c = bbox_x1 + bbox_w/2
            bbox_y_c = bbox_y1 + bbox_h/2
            bbox_x_c_int = int(bbox_x_c)
            bbox_y_c_int = int(bbox_y_c)

            # if segments_tensor[bbox_y_c_int, bbox_x_c_int] == 0:
            #     # no sp in center
            #     center_sp = torch.Tensor().cuda()
            # else:
            #     center_sp = segments_tensor[bbox_y_c_int, bbox_x_c_int].unsqueeze(0)
            #     center_sp_layer = torch.where(segments_tensor==center_sp, one_layer, zero_layer)
            #     center_sp_layer_np = center_sp_layer.cpu().numpy()
            #     kernel = np.ones((3,3),np.uint8)
            #     center_sp_layer_dilate = cv2.dilate(center_sp_layer_np, kernel, iterations = 2)
            #     center_sp_layer_dilate = torch.from_numpy(center_sp_layer_dilate)
            #     center_sp_layer_dilate_stack = center_sp_layer_dilate.unsqueeze(0).repeat(segments_stack.shape[0],1,1)

            #     cross_stack = center_sp_layer_dilate_stack * segments_stack
            #     cross_ = torch.sum(cross_stack, dim=0)
            #     neighborhoods = torch.unique(cross_)[1:]
            #     center_sps = neighborhoods
            #     cross_stack = cross_stack.cpu()
            #     center_sp_layer_dilate_stack = center_sp_layer_dilate_stack.cpu()

            #     # we also need center sp's neighborhoods

            # # (2) find the boundary sp

            # # boundary_erode
            # kernel = np.ones((3,3),np.uint8)
            # mask_erosion = cv2.erode(mask_np, kernel, iterations = 2)
            # boundary_erode = mask_np - mask_erosion
            # boundary_erode = torch.from_numpy(boundary_erode)
            # # boundary_erode_pil = transforms.ToPILImage()(boundary_erode.cpu())
            # # boundary_erode_pil.show()

            # boundary_erode_stack = boundary_erode.unsqueeze(0).repeat(segments_stack.shape[0],1,1)
            # boundary_mul_segments_stack = boundary_erode_stack * segments_stack
            # boundary_mul_segments = torch.sum(boundary_mul_segments_stack, dim=0)
            # # boundary_mul_segments_pil = transforms.ToPILImage()(boundary_mul_segments.cpu())
            # # boundary_mul_segments_pil.show()
            # boundary_mul_segments_unique = torch.unique(boundary_mul_segments)
            # boundary_mul_segments_unique = boundary_mul_segments_unique[1:]
            # boundary_sp = boundary_mul_segments_unique

            # shan dian
            # init grid
            densy = 7
            unit_w = 13*densy
            unit_h = 13*densy
            sandian = torch.zeros(unit_w,unit_h)
            '''
            log:
            10,5,10,5 : 0.04   work! at 700
            10,5,10,6 : 0.0333 work! at 2040
            '''
            sandian = sandian.reshape(13,densy,13,densy)
            sandian[:,int((densy-1)/2),:,int((densy-1)/2)] = 1
            sandian = sandian.reshape(unit_w, unit_h)
            sandian = sandian.unsqueeze(0).unsqueeze(0)
            sandian = F.interpolate(sandian, (500, 500), mode='nearest').squeeze()
            sandian_stack = sandian.unsqueeze(0).repeat(segments_stack.shape[0],1,1)
            sandian_mul_segments_stack = sandian_stack * segments_stack
            sandian_mul_segments = torch.sum(sandian_mul_segments_stack, dim=0)
            sandian_mul_segments_pil = transforms.ToPILImage()(sandian_mul_segments.cpu())
            sandian_mul_segments_pil.show()
            sandian_mul_segments_unique = torch.unique(sandian_mul_segments)
            sandian_mul_segments_unique = sandian_mul_segments_unique[1:]
            sandian_sp = sandian_mul_segments_unique

            # pay attention
            # spot_sp = torch.cat((center_sps, boundary_sp), dim=0)
            spot_sp = sandian_sp
            spot_sp = torch.unique(spot_sp).long()

            sandian_stack = sandian_stack.cpu()
            # boundary_erode_stack = boundary_erode_stack.cpu()
            # boundary_mul_segments_stack = boundary_mul_segments_stack.cpu()
            segments_stack = segments_stack.cpu()

            torch.cuda.empty_cache()

            # show_tensor = img.clone().cuda()
            # for i in range(spot_sp.shape[0]):
            #     sp = spot_sp[i]
            #     show_tensor = torch.where(segments_tensor==sp, zero_layer.fill_(1).unsqueeze(0).repeat(3,1,1),show_tensor)

            # show_tensor_pil = transforms.ToPILImage()(show_tensor.cpu())
            # show_tensor_pil.show()

            # generate theta_m
            # for sp id from 1 to 128
            uniform_ratio = torch.Tensor([ATTACK_AREA_RATE])[0]
            higher_ratio =  uniform_ratio*1.5
            uniform_ratio_theta = 1/2*torch.log(uniform_ratio/(1-uniform_ratio))
            higher_ratio_theta = 1/2*torch.log(higher_ratio/(1-higher_ratio))
            theta_m = torch.zeros_like(segments_label).cpu().fill_(uniform_ratio_theta)
            theta_m[spot_sp-1] = higher_ratio_theta

            for evo_step in range(evo_step_num):
                # prepare sp dataset
                g_theta_m = 1/2*(torch.tanh(theta_m)+1)
                data_sp = SuperPixelGet(segments_label = segments_label,
                                    segments_tensor=segments_tensor,
                                    g_theta_m=g_theta_m,
                                    data_num=population_num)
                dataloader_sp = DataLoader(data_sp, batch_size=batch_size_sp,shuffle=False) #使用DataLoader加载数据

                F_value_restore = torch.Tensor()
                select_m_restore = torch.Tensor()

                for j_sp_batch , sp_batch_data in enumerate(dataloader_sp):

                    attack_mask_batch, select_m = sp_batch_data[0].unsqueeze(1), sp_batch_data[1]
                    select_m_restore = torch.cat((select_m_restore, select_m.cpu()))

                    batch_size_now = attack_mask_batch.shape[0]
                    ## start at gray
                    adv_patch_w_batch = torch.zeros(batch_size_now,3,500,500).cuda()

                    adv_patch_w_batch.requires_grad_(True)

                    ## optimizer and scheduler
                    # optimizer = optim.Adam([
                    #     {'params': adv_patch, 'lr': 0.01*255}
                    # ], amsgrad=True)
                    optimizer = optim.Adam([
                        {'params': adv_patch_w_batch, 'lr': 0.1}
                    ], amsgrad=True)

                    L_value_step = torch.ones(batch_size_now ,optim_step_num)*1000
                    for step in tqdm(range(optim_step_num)):

                        # prepare batch data to feed the frcn
                        img_batch = img.cuda().unsqueeze(0).repeat(batch_size_now,1,1,1)
                        adv_patch_batch = torch.sigmoid(adv_patch_w_batch/2)
                        patched_img_batch = torch.where(attack_mask_batch > 0, adv_patch_batch, img_batch)
                        patched_img_batch_255 = patched_img_batch * 255.
                        patched_img_batch_rsz = F.interpolate(patched_img_batch_255, (800, 800), mode='bilinear').cuda()
                        patched_img_batch_nom_rsz = (patched_img_batch_rsz - self.mean) / self.std

                        # output
                        img_new = copy.deepcopy(img_frcn)
                        img_new['img'][0] = patched_img_batch_nom_rsz
                        # [0] = patched_img_batch_nom_rsz
                        img_new['img_metas'][0] = [img_new['img_metas'][0][0] for i in range(batch_size_now)]
                        frcn_output = self.Faster_RCNN(return_loss=False, rescale=False,  **img_new)
                        # output formate is [x1,y1,x2,y2]

                        # compute loss
                        proposals_4507 = frcn_output[1]
                        proposals_score_4507 = frcn_output[2]
                        det_bboxes, det_labels, proposals = frcn_output[0]

                        det_bboxes = torch.cat(det_bboxes,dim=0)/800*500
                        proposals = torch.cat(proposals,dim=0)/800*500
                        det_labels = torch.cat(det_labels,dim=0)

                        attack_prob = det_labels[:,class_label]
                        training_confidence_threshold = 0.28
                        ov_thrs_index = torch.where(attack_prob > training_confidence_threshold)[0] # for certain class
                        pbbox_attack_cls = det_bboxes[:, class_label*4:(class_label+1)*4]

                        # cls loss
                        attack_class_score = det_labels[:,class_label]
                        top_sort_class_score = torch.sort(attack_class_score, descending=True)[0][:10]
                        cls_loss = torch.sum(top_sort_class_score)

                        # iou loss
                        bbox_x1 = bbox[0]/500*416
                        bbox_y1 = bbox[1]/500*416
                        bbox_w = bbox[2]/500*416
                        bbox_h = bbox[3]/500*416
                        ground_truth_bbox = [bbox_x1, bbox_y1, bbox_x1+bbox_w, bbox_y1 + bbox_h]
                        ground_truth_bbox = torch.Tensor(ground_truth_bbox).unsqueeze(0).cuda()
                        iou_all = compute_iou_tensor(det_bboxes[:, class_label*4:(class_label+1)*4], ground_truth_bbox)
                        iou_positive = iou_all[iou_all>0.15]
                        iou_loss = torch.sum(iou_all)

                        # class loss selected by IoU
                        attack_class_score = det_labels[:,class_label]
                        attack_class_score_iou = attack_class_score[iou_all>0.45]
                        attack_class_score_iou_sort = torch.sort(attack_class_score_iou, descending=True)[0][:30]
                        cls_iou_loss = torch.sum(attack_class_score_iou_sort)

                        final_roi = pbbox_attack_cls[ov_thrs_index]  # for certain class
                        final_roi = final_roi[:,:4]
                        final_ctx = (final_roi[:,0] + final_roi[:,2])/2
                        final_cty = (final_roi[:,1] + final_roi[:,3])/2
                        final_ctx = final_ctx.unsqueeze(-1)
                        final_cty = final_cty.unsqueeze(-1)
                        final_roi_target = torch.cat([final_ctx,final_cty,final_ctx,final_cty], dim=-1)
                        reg_loss = 10* l1_norm(final_roi-final_roi_target) / final_roi.shape[0] /500

                        # RPN loss
                        # r1 : from score
                        # r2 : from x,y,w,h

                        # rpn score target is 0
                        rpn_score = proposals[:, 4]
                        loss_r1 = l2_norm(rpn_score - 0)

                        # rpn box target is smaller the boxes
                        rpn_ctx = (proposals[:,0] + proposals[:,2])/2
                        rpn_cty = (proposals[:,1] + proposals[:,3])/2
                        rpn_box = proposals[:,:4]
                        rpn_ctx = rpn_ctx.unsqueeze(-1)
                        rpn_cty = rpn_cty.unsqueeze(-1)
                        rpn_box_target = torch.cat([rpn_ctx,rpn_cty,rpn_ctx,rpn_cty], dim=-1)
                        # loss_r2 = l1_norm(rpn_score.unsqueeze(-1).repeat(1,4)*(rpn_box - rpn_box_target)) / 500
                        loss_r2 = l1_norm((rpn_box - rpn_box_target)) / 500

                        lambda_balance1 = 0.02
                        # rpn_loss = loss_r1 + lambda_balance1 * loss_r2
                        rpn_loss = lambda_balance1 * loss_r2
                        # rpn_loss = loss_r1

                        total_loss = cls_loss + reg_loss + rpn_loss
                        total_loss = cls_loss + cls_iou_loss + reg_loss + rpn_loss

                        # if epoch > 500:
                        #     total_loss = rpn_loss + cls_loss_new + reg_loss

                        total_loss.backward()
                        optimizer.step()
                        optimizer.zero_grad()

                        # compute F(m,t*;y)

                        # L in disappearing
                        # i think we better use iou>0.45 in prediction, all bbox's person class confidence sum

                        bbox_x1 = bbox[0]
                        bbox_y1 = bbox[1]
                        bbox_w = bbox[2]
                        bbox_h = bbox[3]
                        ground_truth_bbox = [bbox_x1, bbox_y1, bbox_x1+bbox_w, bbox_y1 + bbox_h]
                        ground_truth_bbox = torch.Tensor(ground_truth_bbox).unsqueeze(0).cuda()
                        iou_all = compute_iou_tensor(det_bboxes[:, class_label*4:(class_label+1)*4], ground_truth_bbox)

                        iou_select_index = iou_all > 0.45

                        for ib in range(batch_size_now):

                            det_labels_one = det_labels[ib:(ib+1)*1000, class_label]

                            iou_select_index_one = iou_select_index[ib:(ib+1)*1000]

                            cls_conf_iou_select = det_labels_one[iou_select_index_one]

                            cls_conf_iou_select = cls_conf_iou_select[cls_conf_iou_select>0.25]

                            cls_conf_iou_select_top = torch.sort(cls_conf_iou_select, descending=True)[0][:10]

                            L_value_step[ib, step] = torch.sum(cls_conf_iou_select_top).detach().clone()
                            pass
                        if (torch.min(L_value_step, dim=1)[0] == torch.zeros(batch_size_now)).all():
                            break

                        pass
                    L_value = - torch.min(L_value_step, dim=1)[0]
                    F_value = L_value - torch.sum(torch.sum(sp_batch_data[0], dim=-1), dim=-1).cpu()/mask_area*10 ###!!!!
                    F_value_restore = torch.cat((F_value_restore, F_value))

                    pass
                # print(F_value_restore)
                # now we have F value

                delta_J_theta = 1/population_num * F_value_restore.unsqueeze(1) * 2 * (select_m_restore.cpu().float() - g_theta_m)

                delta_J_theta = torch.sum(delta_J_theta, dim=0)
                theta_m = theta_m + delta_J_theta
                g_theta_m = 1/2*(torch.tanh(theta_m)+1)

                select_sp_index = torch.sort(theta_m)[1][:int(theta_m.shape[0]*ATTACK_AREA_RATE)]

                attack_region_show = zero_layer.clone().squeeze().cuda()
                flag = torch.zeros_like(segments_label)
                flag[select_sp_index] = 1
                for i in range(segments_label.shape[0]):

                    color = g_theta_m[i]
                    color_layer = torch.zeros_like(segments_tensor).fill_(color)
                    sp =  segments_label[i]

                    attack_region_show = torch.where(segments_tensor==sp, color_layer, attack_region_show)
                attack_region_show = attack_region_show / torch.max(attack_region_show)

                attack_region_show = (attack_region_show + img.cuda())/2

                attack_region_show_pil = transforms.ToPILImage()(attack_region_show.cpu())

                save_dir = os.path.join('../common_data/NES_search_test_1107/', img_name.split('.')[0])
                if not os.path.exists(save_dir):
                    os.makedirs(save_dir)
                save_path = os.path.join(save_dir, str(evo_step)+'_pop_'+str(population_num)+'_'+str(base_SLIC_seed_num)+'.png')
                attack_region_show_pil.save(save_path)

                time1 = time.time()

                time_cost = time1 - time0

                if time_cost > 1800:
                    break

                print(g_theta_m)
        print(assasasasasasa)
        pass

    def generate_patch(self, type):
        """
        Generate a random patch as a starting point for optimization.

        :param type: Can be 'gray' or 'random'. Whether or not generate a gray or a random patch.
        :return:
        """
        if type == 'gray':
            adv_patch_cpu = torch.full((3, 500, 500), 0.5)
        elif type == 'random':
            adv_patch_cpu = torch.rand((3, 500, 500))
        if type == 'trained_patch':
            patchfile = 'patches/object_score.png'
            patch_img = Image.open(patchfile).convert('RGB')
            patch_size = self.config.patch_size
            tf = transforms.Resize((patch_size, patch_size))
            patch_img = tf(patch_img)
            tf = transforms.ToTensor()
            adv_patch_cpu = tf(patch_img)

        return adv_patch_cpu

    def read_image(self, path):
        """
        Read an input image to be used as a patch

        :param path: Path to the image to be read.
        :return: Returns the transformed patch as a pytorch Tensor.
        """
        patch_img = Image.open(path).convert('RGB')
        tf = transforms.Resize((self.config.patch_size, self.config.patch_size))
        patch_img = tf(patch_img)
        tf = transforms.ToTensor()

        adv_patch_cpu = tf(patch_img)
        return adv_patch_cpu

def connected_domin_detect(input_img):
    from skimage import measure
    # detection
    if input_img.shape[0] == 3:
        input_img_new = (input_img[0] + input_img[1] + input_img[2])
    else:
        input_img_new = input_img
    ones = torch.Tensor(input_img_new.size()).fill_(1)
    zeros = torch.Tensor(input_img_new.size()).fill_(0)
    input_map_new = torch.where((input_img_new != 0), ones, zeros)
    # img = transforms.ToPILImage()(input_map_new.detach().cpu())
    # img.show()
    input_map_new = input_map_new.cpu()
    labels = measure.label(input_map_new[:, :], background=0, connectivity=2)
    label_max_number = np.max(labels)
    return float(label_max_number)

def get_obj_min_score(boxes):
    if type(boxes[0][0]) is list:
        min_score_list = []
        for i in range(len(boxes)):
            score_list = []
            for j in range(len(boxes[i])):
                score_list.append(boxes[i][j][4])
            min_score_list.append(min(score_list))
        return np.array(min_score_list)
    else:
        score_list = []
        for j in range(len(boxes)):
            score_list.append(boxes[j][4])
        return np.array(min(score_list))

def l2_norm(tensor):
    return torch.sqrt(torch.sum(torch.pow(tensor,2)))

def l1_norm(tensor):
    return torch.sum(torch.abs(tensor))

def main():

    trainer = PatchTrainer('paper_obj')
    trainer.train()

if __name__ == '__main__':
    main()