import tensorflow as tf
import numpy as np
import pandas as pd
from tensorflow.keras.layers import Dense, Input, Reshape, Flatten, LeakyReLU
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from Input_Handler import InputHandler
import logging
tf.get_logger().setLevel(logging.ERROR)

class WGAN():

    def __init__(self, input_shape=(68,), noise_dim=100, gen_hidden_dim=256, dis_hidden_dim=64, learning_rate=0.0002, batch_size=64, n_critic=5):
        print("[*] Starting WGAN __init__")
        self.input_shape = input_shape
        self.noise_dim = noise_dim
        self.gen_hidden_dim = gen_hidden_dim
        self.dis_hidden_dim = dis_hidden_dim
        self.learning_rate = learning_rate
        self.batch_size = batch_size
        self.n_critic = n_critic
        self.clip_value = 0.01
        print("[+] Initialized basic vars...")
        # Build and compile the discriminator
        self.discriminator = self.build_discriminator()
        self.discriminator.compile(loss=self.wasserstein_loss, optimizer=Adam(learning_rate, beta_1=0.5, beta_2=0.9))
        print("[+] Finished generating discriminator...")
        # Build the generator
        self.generator = self.build_generator()
        print("[+] Finished generating generator...")
        # Build the combined model
        self.combined = self.build_combined()
        print("[+] Finished generating combined...")
        # Load the data
        self.input_handler = InputHandler()
        test_data, train_data = self.input_handler.get_data_from_csv(unNorm=False)
        self.test_data = test_data.drop('malicious', axis=1)
        self.test_data_label = test_data['malicious']
        self.train_data = train_data.drop('malicious', axis=1)
        self.train_data_label = train_data['malicious']
        print("[+] Extracted data completely...")

    def wasserstein_loss(self, y_true, y_pred):
        return tf.keras.backend.mean(y_true * y_pred)

    def build_generator(self):
        input_noise = Input(shape=(self.noise_dim,))
        x = Dense(self.gen_hidden_dim, activation='relu')(input_noise)
        x = Dense(self.gen_hidden_dim, activation='relu')(x)
        x = Dense(np.prod(self.input_shape), activation='tanh')(x)
        output = Reshape(self.input_shape)(x)
        model = Model(input_noise, output)
        return model

    def build_discriminator(self):
        input_data = Input(shape=self.input_shape)
        x = Flatten()(input_data)
        x = Dense(self.dis_hidden_dim)(x)
        x = LeakyReLU(alpha=0.2)(x)
        x = Dense(self.dis_hidden_dim)(x)
        x = LeakyReLU(alpha=0.2)(x)
        output = Dense(1)(x)
        model = Model(input_data, output)
        return model

    def build_combined(self):
        input_noise = Input(shape=(self.noise_dim,))
        generated_data = self.generator(input_noise)
        validity = self.discriminator(generated_data)
        model = Model(input_noise, validity)
        model.compile(loss=self.wasserstein_loss, optimizer=Adam(self.learning_rate, beta_1=0.5, beta_2=0.9))
        return model

    def generate_samples(self, num_samples):
        noise = np.random.normal(0, 1, (num_samples, self.noise_dim))
        generated_samples = self.generator.predict(noise)
        return generated_samples

    def generate_noise(self, n_samples):
        return np.random.normal(0, 1, (n_samples, self.noise_dim))

    def train(self, epochs=5000):
        print("[*] Starting Training...")
#        self.train_data = np.array(self.train_data)
#        self.train_data = np.reshape(self.train_data, (-1, self.input_shape[0]))
        for epoch in range(epochs):
            # Train the discriminator for n_critic iterations
            for _ in range(self.n_critic):
                # Select a random batch of data
                idx = np.random.randint(0, self.train_data.shape[0], self.batch_size)
                real_data = self.train_data.iloc[idx]
                # Generate a batch of fake data
                noise = np.random.normal(0, 1, (self.batch_size, self.noise_dim))
                fake_data = self.generator.predict(noise)
                # Clip the weights of the discriminator
                for layer in self.discriminator.layers:
                    weights = layer.get_weights()
                    weights = [np.clip(w, -self.clip_value, self.clip_value) for w in weights]
                    layer.set_weights(weights)
                # Train the discriminator on real and fake data
                d_loss_real = self.discriminator.train_on_batch(real_data, -np.ones((self.batch_size, 1)))
                d_loss_fake = self.discriminator.train_on_batch(fake_data, np.ones((self.batch_size, 1)))
                d_loss = 0.5 * np.add(d_loss_fake, d_loss_real)
            self.discriminator.trainable = False
            # Train generator
            gan_input = self.generate_noise(len(self.train_data))
            y_gen = -np.ones((len(self.train_data), 1))
            g_loss = self.combined.train_on_batch(gan_input, y_gen)
            # Print progress
            print("[+] Epoch: %d  Discriminator Loss: %f  Generator Loss: %f" % (epoch, d_loss, g_loss))
            # Save generator every 500 epochs
#            if epoch % 500 == 0:
#                self.save_model(epoch)


from attacks.reverseconnectionhandler import ReverseConnectionHandler

class TestReverseConnectionHandler:
    handler = ReverseConnectionHandler(None, "127.0.0.1", "80")

    def test_msf_command(self):
        msf_command = self.handler._msf_command()
        expected_msf_command = (
            "msfconsole --exec-command "
            "\""
            "use exploit/multi/handler;"
            "set payload windows/x64/meterpreter/reverse_http;"
            "set lhost 127.0.0.1;"
            "set lport 80;"
            "set ReverseListenerBindAddress 127.0.0.1;"
            "set ListenerTimeout 330;"
            "exploit;"
            "\"")
        assert msf_command == expected_msf_command


"""charsooghe_ir URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from django.urls import path, include
from store import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
    path('login/', views.loginuser, name='loginuser'),
    path('logout/', views.logoutuser, name='logoutuser'),
    path('signup/', views.signupuser, name='signupuser'),
    path('sell/', views.sell, name='sell'),
    path('userprofile', views.userprofile, name='userprofile'),
    path('cart', views.cart, name='cart'),
    path('checkout', views.checkout, name='checkout'),
    path('update_item/', views.updateItem, name='update_item'),
    path('process_order/', views.processOrder, name='process_order'),
    path('delete/', views.delete, name='delete'),
    path('zarinpal', include('zarinpal.urls')),
    path('product<int:product_id>', views.product, name='product')
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import os
import cv2
import glob
import numpy as np

def rotate_bound(image, angle):
    (h, w) = image.shape[:2]
    (cX, cY) = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))
    M[0, 2] += (nW / 2) - cX
    M[1, 2] += (nH / 2) - cY
    return cv2.warpAffine(image, M, (nW, nH))

root_dir= '../stitcher_img/'
sub_dir='20211119-181414/'
images = []
for i, file_name in enumerate(glob.glob(os.path.join(root_dir, sub_dir,"*.jpeg"))):
    img_path = f'{root_dir}/{sub_dir}/292_{str(i)}.jpeg'
    if img_path.__contains__('info'):
        continue
    image_data = cv2.imread(img_path)
    image_data=image_data[0: 2048, 320: 3072]
    image_data=rotate_bound(image_data,-2)
    image_data=cv2.resize(image_data,(image_data.shape[1]//2,image_data.shape[0]//2))
    print(img_path)
    # cv2.imshow(f"img {i}", image_data)
    # cv2.waitKey(0)
    images.append(image_data)
img_res=np.hstack(images)
cv2.imwrite('res3.jpeg', img_res)


# Longest K unique characters substring

def longestKSubstr(s, k):
    # code here
    i = 0
    j = 0
    max_val = -1
    dic = {}
    n = len(s)
    while j < n:
        if s[j] in dic:
            dic[s[j]] += 1
        else:
            dic[s[j]] = 1

        if len(dic) < k:
            j += 1

        if len(dic) == k:
            max_val = max(max_val, j-i+1)
            j += 1
        elif len(dic) > k:
            while (len(dic) > k):
                dic[s[i]] -= 1
                if dic[s[i]] == 0:
                    del dic[s[i]]
                i += 1
            j += 1

    return max_val

s = "aabacbebebe"
k = 3
print(longestKSubstr(s, k))


from time import sleep
import board
from adafruit_ms8607 import MS8607

i2c = board.I2C()
sensor = MS8607(i2c)

while True:

    print("Pressure: %.2f hPa" % sensor.pressure)
    print("Temperature: %.2f C" % sensor.temperature)
    print("Humidity: %.2f %% rH" % sensor.relative_humidity)
    sleep(1)


import pathlib

import snip_copy
from snip_copy.ipynb.json_ipynb import IPYNB

folder = pathlib.Path(snip_copy.__file__).parents[1] / 'test' / 'ex_hw'
f_ipynb = folder / 'simple.ipynb'

def test_ipynb():
    ipynb0 = IPYNB.from_file(f_ipynb=f_ipynb)
    ipynb1 = ipynb0.with_text(['a', 'b'])

    assert ipynb0 != ipynb1

    ipynb1.del_cell([1])
    assert ipynb1.text_list == ['a']


from django.views.generic import View
from django.shortcuts import render
from projects.models import Project
from django.shortcuts import get_object_or_404
from events.models import Event
# Create your views here.

def project_view(request):
    project = Project.objects.all()
    context = {
        'project': project
    }
    return render(request, 'projects/project.html', context)

class ProjectView(View):
    def get(self, request, *args, **kwargs):
        project = get_object_or_404(Project, slug=kwargs['slug'])
        try:
            events = Event.objects.filter(project=project)
            context = {
                'project': project,
                'events': events}
        except Event.DoesNotExist:
            context = {
                'project': project
                }
        return render(request, 'projects/project.html', context)


#program 01 multiple of 2
a=int(input())
l=[]
m=0
for i in range(1,6):
	i=i*a
	l.append(i)
print(l)
s=sum(l)
print(s)
if s%2==0:
	print("the given number is even")
else:
	print("the given number is odd")
x=int(m%10)
y=int(m/10)
print(x,y)

#program 02 palindrome or not
str=(input())
if(str==str[::-1]):
	print("the string is palindrome")
else:
	print("the string is not palindrome")


from helpers import *

from mobject.tex_mobject import TexMobject
from mobject import Mobject
from mobject.image_mobject import ImageMobject
from mobject.vectorized_mobject import *

from animation.animation import Animation
from animation.transform import *
from animation.simple_animations import *
from animation.continual_animation import *
from animation.playground import *
from topics.geometry import *
from topics.characters import *
from topics.functions import *
from topics.fractals import *
from topics.number_line import *
from topics.combinatorics import *
from topics.numerals import *
from topics.three_dimensions import *
from topics.objects import *
from topics.probability import *
from topics.complex_numbers import *
from scene import Scene
from scene.reconfigurable_scene import ReconfigurableScene
from scene.zoomed_scene import *
from camera import Camera
from mobject.svg_mobject import *
from mobject.tex_mobject import *

E_COLOR = BLUE
M_COLOR = YELLOW

class OscillatingVector(ContinualAnimation):
    CONFIG = {
        "tail" : ORIGIN,
        "frequency" : 1,
        "A_vect" : [1, 0, 0],
        "phi_vect" : [0, 0, 0],
        "vector_to_be_added_to" : None,
    }
    def setup(self):
        self.vector = self.mobject

    def update_mobject(self, dt):
        f = self.frequency
        t = self.internal_time
        angle = 2*np.pi*f*t
        vect = np.array([
            A*np.exp(complex(0, angle + phi))
            for A, phi in zip(self.A_vect, self.phi_vect)
        ]).real
        self.update_tail()
        self.vector.put_start_and_end_on(self.tail, self.tail+vect)

    def update_tail(self):
        if self.vector_to_be_added_to is not None:
            self.tail = self.vector_to_be_added_to.get_end()

class OscillatingVectorComponents(ContinualAnimationGroup):
    CONFIG = {
        "tip_to_tail" : False,
    }
    def __init__(self, oscillating_vector, **kwargs):
        digest_config(self, kwargs)
        vx = Vector(UP, color = GREEN).fade()
        vy = Vector(UP, color = RED).fade()
        kwargs = {
            "frequency" : oscillating_vector.frequency,
            "tail" : oscillating_vector.tail,
        }
        ovx = OscillatingVector(
            vx,
            A_x = oscillating_vector.A_x,
            phi_x = oscillating_vector.phi_x,
            A_y = 0,
            phi_y = 0,
            **kwargs
        )
        ovy = OscillatingVector(
            vy,
            A_x = 0,
            phi_x = 0,
            A_y = oscillating_vector.A_y,
            phi_y = oscillating_vector.phi_y,
            **kwargs
        )
        components = [ovx, ovy]
        self.vectors = VGroup(ovx.vector, ovy.vector)
        if self.tip_to_tail:
            ovy.vector_to_be_added_to = ovx.vector
        else:
            self.lines = VGroup()
            for ov1, ov2 in (ovx, ovy), (ovy, ovx):
                ov_line = ov1.copy()
                ov_line.mobject = ov_line.vector = DashedLine(
                    UP, DOWN, color = ov1.vector.get_color()
                )
                ov_line.vector_to_be_added_to = ov2.vector
                components.append(ov_line)
                self.lines.add(ov_line.line)

        ContinualAnimationGroup.__init__(self, *components, **kwargs)

class EMWave(ContinualAnimationGroup):
    CONFIG = {
        "wave_number" : 1,
        "frequency" : 0.25,
        "n_vectors" : 40,
        "propogation_direction" : RIGHT,
        "start_point" : SPACE_WIDTH*LEFT + DOWN + OUT,
        "length" : 2*SPACE_WIDTH,
        "amplitude" : 1,
        "rotation" : 0,
        "A_vect" : [0, 0, 1],
        "phi_vect" : [0, 0, 0],
        "requires_start_up" : False,
    }
    def __init__(self, **kwargs):
        digest_config(self, kwargs)
        if not all(self.propogation_direction == RIGHT):
            self.matrix_transform = np.dot(
                z_to_vector(self.propogation_direction),
                np.linalg.inv(z_to_vector(RIGHT)),
            )
        else:
            self.matrix_transform = None

        vector_oscillations = []
        self.E_vects = VGroup()
        self.M_vects = VGroup()

        self.A_vect = np.array(self.A_vect)/np.linalg.norm(self.A_vect)
        self.A_vect *= self.amplitude

        for alpha in np.linspace(0, 1, self.n_vectors):
            tail = interpolate(ORIGIN, self.length*RIGHT, alpha)
            phase = -alpha*self.length*self.wave_number
            kwargs = {
                "phi_vect" : np.array(self.phi_vect) + phase,
                "frequency" : self.frequency,
                "tail" : np.array(tail),
            }
            E_ov = OscillatingVector(
                Vector(
                    OUT, color = E_COLOR,
                    normal_vector = UP,
                ),
                A_vect = self.A_vect,
                **kwargs
            )
            M_ov = OscillatingVector(
                Vector(
                    UP, color = M_COLOR,
                    normal_vector = OUT,
                ),
                A_vect = rotate_vector(self.A_vect, np.pi/2, RIGHT),
                **kwargs
            )
            vector_oscillations += [E_ov, M_ov]
            self.E_vects.add(E_ov.vector)
            self.M_vects.add(M_ov.vector)
        ContinualAnimationGroup.__init__(self, *vector_oscillations)

    def update_mobject(self, dt):
        if self.requires_start_up:
            n_wave_lengths = self.length / (2*np.pi*self.wave_number)
            prop_time = n_wave_lengths/self.frequency
            middle_alpha = interpolate(
                0.4, 1.4,
                self.external_time / prop_time
            )
            new_smooth = squish_rate_func(smooth, 0.4, 0.6)

            ovs = self.continual_animations
            for ov, alpha in zip(ovs, np.linspace(0, 1, len(ovs))):
                epsilon = 0.0001
                new_amplitude = np.clip(
                    new_smooth(middle_alpha - alpha), epsilon, 1
                )
                norm = np.linalg.norm(ov.A_vect)
                if norm != 0:
                    ov.A_vect = new_amplitude * np.array(ov.A_vect) / norm

        ContinualAnimationGroup.update_mobject(self, dt)
        self.mobject.rotate(self.rotation, RIGHT)
        if self.matrix_transform:
            self.mobject.apply_matrix(self.matrix_transform)
        self.mobject.shift(self.start_point)

class WavePacket(Animation):
    CONFIG = {
        "EMWave_config" : {
            "wave_number" : 0,
            "start_point" : SPACE_WIDTH*LEFT,
            "phi_vect" : np.ones(3)*np.pi/4,
        },
        "em_wave" : None,
        "run_time" : 4,
        "rate_func" : None,
        "packet_width" : 6,
        "include_E_vects" : True,
        "include_M_vects" : True,
        "filter_distance" : SPACE_WIDTH,
        "get_filtered" : False,
        "remover" : True,
    }
    def __init__(self, **kwargs):
        digest_config(self, kwargs)
        em_wave = self.em_wave
        if em_wave is None:
            em_wave = EMWave(**self.EMWave_config)
            em_wave.update(0)
            self.em_wave = em_wave

        self.vects = VGroup()
        if self.include_E_vects:
            self.vects.add(*em_wave.E_vects)
        if self.include_M_vects:
            self.vects.add(*em_wave.M_vects)
        for vect in self.vects:
            vect.save_state()

        u = em_wave.propogation_direction
        self.wave_packet_start, self.wave_packet_end = [
            em_wave.start_point - u*self.packet_width/2,
            em_wave.start_point + u*(em_wave.length + self.packet_width/2)
        ]
        Animation.__init__(self, self.vects, **kwargs)

    def update_mobject(self, alpha):
        packet_center = interpolate(
            self.wave_packet_start,
            self.wave_packet_end,
            alpha
        )
        em_wave = self.em_wave
        for vect in self.vects:
            tail = vect.get_start()
            distance_from_packet = np.dot(
                tail - packet_center,
                em_wave.propogation_direction
            )
            A = em_wave.amplitude*self.E_func(distance_from_packet)
            distance_from_start = np.linalg.norm(tail - em_wave.start_point)
            if self.get_filtered and distance_from_start > self.filter_distance:
                A = 0
            vect.restore()
            vect.scale(A/vect.get_length(), about_point = tail)

    def E_func(self, x):
        return np.sin(x)*np.exp(-0.25*x*x)

class FilterLabel(TexMobject):
    def __init__(self, tex, degrees, **kwargs):
        TexMobject.__init__(self, tex + " \\uparrow", **kwargs)
        self[-1].rotate(-degrees * np.pi / 180)

class PolarizingFilter(Circle):
    CONFIG = {
        "stroke_color" : DARK_GREY,
        "fill_color" : LIGHT_GREY,
        "fill_opacity" : 0.5,
        "label_tex" : None,
        "filter_angle" : 0,
        "include_arrow_label" : True,
        "arrow_length" : 0.7,
    }
    def __init__(self, **kwargs):
        Circle.__init__(self, **kwargs)

        if self.label_tex:
            self.label = TexMobject(self.label_tex)
            self.label.next_to(self.get_top(), DOWN, MED_SMALL_BUFF)
            self.add(self.label)

        arrow = Arrow(
            ORIGIN, self.arrow_length*UP,
            color = WHITE,
            buff = 0,
        )
        arrow.shift(self.get_top())
        arrow.rotate(-self.filter_angle)
        self.add(arrow)
        self.arrow = arrow
        shade_in_3d(self)

        if self.include_arrow_label:
            arrow_label = TexMobject(
                "%.1f^\\circ"%(self.filter_angle*180/np.pi)
            )
            arrow_label.add_background_rectangle()
            arrow_label.next_to(arrow.get_tip(), UP)
            self.add(arrow_label)
            self.arrow_label = arrow_label

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

class IntroduceElectricField(PiCreatureScene):
    CONFIG = {
        "vector_field_colors" : [BLUE_B, BLUE_D],
        "max_vector_length" : 0.9,
    }
    def construct(self):
        self.write_title()
        self.draw_field()
        self.add_particle()
        self.let_particle_wander()

    def write_title(self):
        morty = self.pi_creature

        title = TextMobject(
            "Electro", "magnetic", " field",
            arg_separator = ""
        )
        title.next_to(morty, UP+LEFT)
        electric = TextMobject("Electric")
        electric.next_to(title[-1], LEFT)
        electric.highlight(BLUE)

        title.save_state()
        title.shift(DOWN)
        title.fade(1)

        self.play(
            title.restore,
            morty.change, "raise_right_hand",
        )
        self.play(
            title[0].highlight, BLUE,
            title[1].highlight, YELLOW,
        )
        self.dither()
        self.play(
            ShrinkToCenter(title[1]),
            Transform(title[0], electric)
        )

        title.add_background_rectangle()
        self.title = title

    def draw_field(self):
        morty = self.pi_creature
        vector_field = self.get_vector_field()
        self.play(
            LaggedStart(
                ShowCreation, vector_field,
                run_time = 3
            ),
            self.title.center,
            self.title.scale, 1.5,
            self.title.to_edge, UP,
            morty.change, "happy", ORIGIN,
        )
        self.dither()

        self.vector_field = vector_field

    def add_particle(self):
        morty = self.pi_creature
        point = UP+LEFT + SMALL_BUFF*(UP+RIGHT)
        particle = self.get_particle()
        particle.move_to(point)

        vector = self.get_vector(particle.get_center())
        vector.highlight(RED)
        vector.scale(1.5, about_point = point)
        vector.shift(SMALL_BUFF*vector.get_vector())
        force = TextMobject("Force")
        force.next_to(ORIGIN, UP+RIGHT, SMALL_BUFF)
        force.rotate(vector.get_angle())
        force.shift(vector.get_start())

        particle.save_state()
        particle.move_to(morty.get_left() + 0.5*UP + 0.2*RIGHT)
        particle.fade(1)

        self.play(
            particle.restore,
            morty.change, "raise_right_hand",
        )
        self.play(morty.change, "thinking", particle)
        self.play(
            ShowCreation(vector),
            Write(force, run_time = 1),
        )
        self.dither(2)

        self.particle = particle
        self.force_vector = VGroup(vector, force)

    def let_particle_wander(self):
        possible_points = [v.get_start() for v in self.vector_field]
        points = random.sample(possible_points, 45)
        points.append(3*UP+3*LEFT)
        particles = VGroup(self.particle, *[
            self.particle.copy().move_to(point)
            for point in points
        ])
        for particle in particles:
            particle.velocity = np.zeros(3)

        self.play(
            FadeOut(self.force_vector),
            LaggedStart(FadeIn, VGroup(*particles[1:]))
        )
        self.moving_particles = particles
        self.add_foreground_mobjects(self.moving_particles, self.pi_creature)
        self.always_continually_update = True
        self.dither(10)

    ###

    def continual_update(self):
        Scene.continual_update(self)
        if hasattr(self, "moving_particles"):
            dt = self.frame_duration
            for p in self.moving_particles:
                vect = self.field_function(p.get_center())
                p.velocity += vect*dt
                p.shift(p.velocity*dt)
            self.pi_creature.look_at(self.moving_particles[-1])

    def get_particle(self):
        particle = Circle(radius = 0.2)
        particle.set_stroke(RED, 3)
        particle.set_fill(RED, 0.5)
        plus = TexMobject("+")
        plus.scale(0.7)
        plus.move_to(particle)
        particle.add(plus)
        return particle

    def get_vector_field(self):
        result = VGroup(*[
            self.get_vector(point)
            for x in np.arange(-9, 9)
            for y in np.arange(-5, 5)
            for point in [x*RIGHT + y*UP]
        ])
        shading_list = list(result)
        shading_list.sort(
            lambda m1, m2 : cmp(m1.get_length(), m2.get_length())
        )
        VGroup(*shading_list).gradient_highlight(*self.vector_field_colors)
        result.set_fill(opacity = 0.75)
        result.sort_submobjects(np.linalg.norm)

        return result

    def get_vector(self, point):
        return Vector(self.field_function(point)).shift(point)

    def field_function(self, point):
        x, y = point[:2]
        result = y*RIGHT + np.sin(x)*UP
        return self.normalized(result)

    def normalized(self, vector):
        norm = np.linalg.norm(vector) or 1
        target_length = self.max_vector_length * sigmoid(0.1*norm)
        return target_length * vector/norm

class IntroduceMagneticField(IntroduceElectricField, ThreeDScene):
    CONFIG = {
        "vector_field_colors" : [YELLOW_C, YELLOW_D]
    }
    def setup(self):
        IntroduceElectricField.setup(self)
        self.remove(self.pi_creature)

    def construct(self):
        self.set_camera_position(0.1, -np.pi/2)
        self.add_title()
        self.add_vector_field()
        self.introduce_moving_charge()
        self.show_force()
        # self.many_charges()

    def add_title(self):
        title = TextMobject("Magnetic", "field")
        title[0].highlight(YELLOW)
        title.scale(1.5)
        title.to_edge(UP)
        title.add_background_rectangle()

        self.add(title)
        self.title = title

    def add_vector_field(self):
        vector_field = self.get_vector_field()

        self.play(
            LaggedStart(ShowCreation, vector_field, run_time = 3),
            Animation(self.title)
        )
        self.dither()

    def introduce_moving_charge(self):
        point = 3*RIGHT + UP
        particle = self.get_particle()
        particle.move_to(point)

        velocity = Vector(2*RIGHT).shift(particle.get_right())
        velocity.highlight(WHITE)
        velocity_word = TextMobject("Velocity")
        velocity_word.highlight(velocity.get_color())
        velocity_word.add_background_rectangle()
        velocity_word.next_to(velocity, UP, 0, LEFT)

        M_vect = self.get_vector(point)
        M_vect.highlight(YELLOW)
        M_vect.shift(SMALL_BUFF*M_vect.get_vector())

        particle.save_state()
        particle.shift(2*SPACE_WIDTH*LEFT)

        self.play(
            particle.restore,
            run_time = 2,
            rate_func = None,
        )
        self.add(velocity)
        self.play(Write(velocity_word, run_time = 0.5))
        # self.play(ShowCreation(M_vect))
        self.dither()

        self.particle = particle

    def show_force(self):
        point = self.particle.get_center()
        F_vect = Vector(
            3*np.cross(self.field_function(point), RIGHT),
            color = GREEN
        )
        F_vect.shift(point)
        F_word = TextMobject("Force")
        F_word.rotate(np.pi/2, RIGHT)
        F_word.next_to(F_vect, OUT)
        F_word.highlight(F_vect.get_color())
        F_eq = TexMobject(
            "=","q", "\\textbf{v}", "\\times", "\\textbf{B}"
        )
        F_eq.highlight_by_tex_to_color_map({
            "q" : RED,
            "B" : YELLOW,
        })
        F_eq.rotate(np.pi/2, RIGHT)
        F_eq.next_to(F_word, RIGHT)

        self.move_camera(0.8*np.pi/2, -0.55*np.pi)
        self.begin_ambient_camera_rotation()
        self.play(ShowCreation(F_vect))
        self.play(Write(F_word))
        self.dither()
        self.play(Write(F_eq))
        self.dither(8)

    def many_charges(self):
        charges = VGroup()
        for y in range(2, 3):
            charge = self.get_particle()
            charge.move_to(3*LEFT + y*UP)
            charge.velocity = (2*RIGHT).astype('float')
            charges.add(charge)

        self.revert_to_original_skipping_status()
        self.add_foreground_mobjects(*charges)
        self.moving_particles = charges
        self.dither(5)

    ###

    def continual_update(self):
        Scene.continual_update(self)
        if hasattr(self, "moving_particles"):
            dt = self.frame_duration
            for p in self.moving_particles:
                M_vect = self.field_function(p.get_center())
                F_vect = 3*np.cross(p.velocity, M_vect)
                p.velocity += F_vect*dt
                p.shift(p.velocity*dt)

    def field_function(self, point):
        x, y = point[:2]
        y += 0.5
        gauss = lambda r : np.exp(-0.5*r**2)
        result = (y**2 - 1)*RIGHT + x*(gauss(y+2) - gauss(y-2))*UP
        return self.normalized(result)

class CurlRelationBetweenFields(ThreeDScene):
    def construct(self):
        self.add_axes()
        self.loop_in_E()
        self.loop_in_M()
        self.second_loop_in_E()

    def add_axes(self):
        self.add(ThreeDAxes(x_axis_radius = SPACE_WIDTH))

    def loop_in_E(self):
        E_vects = VGroup(*[
            Vector(0.5*rotate_vector(vect, np.pi/2)).shift(vect)
            for vect in compass_directions(8)
        ])
        E_vects.highlight(E_COLOR)
        point = 1.2*RIGHT + 2*UP + OUT
        E_vects.shift(point)

        M_vect = Vector(
            IN,
            normal_vector = DOWN,
            color = M_COLOR
        )
        M_vect.shift(point)
        M_vect.save_state()
        M_vect.scale(0.01, about_point = M_vect.get_start())

        self.play(ShowCreation(E_vects, run_time = 2))
        self.dither()
        self.move_camera(0.8*np.pi/2, -0.45*np.pi)
        self.begin_ambient_camera_rotation()
        self.play(M_vect.restore, run_time = 3, rate_func = None)
        self.dither(3)

        self.E_vects = E_vects
        self.E_circle_center = point
        self.M_vect = M_vect

    def loop_in_M(self):
        M_vects = VGroup(*[
            Vector(
                rotate_vector(vect, np.pi/2),
                normal_vector = IN,
                color = M_COLOR
            ).shift(vect)
            for vect in compass_directions(8, LEFT)[1:]
        ])
        M_vects.rotate(np.pi/2, RIGHT)
        new_point = self.E_circle_center + RIGHT
        M_vects.shift(new_point)

        E_vect = self.E_vects[0]

        self.play(
            ShowCreation(M_vects, run_time = 2),
            *map(FadeOut, self.E_vects[1:])
        )
        self.dither()
        self.play(
            E_vect.rotate, np.pi, RIGHT, [], new_point,
            E_vect.scale_about_point, 3, new_point,
            run_time = 4,
            rate_func = None,
        )
        self.dither()

        self.M_circle_center = new_point
        M_vects.add(self.M_vect)
        self.M_vects = M_vects
        self.E_vect = E_vect

    def second_loop_in_E(self):
        E_vects = VGroup(*[
            Vector(1.5*rotate_vector(vect, np.pi/2)).shift(vect)
            for vect in compass_directions(8, LEFT)[1:]
        ])
        E_vects.highlight(E_COLOR)
        point = self.M_circle_center + RIGHT
        E_vects.shift(point)

        M_vect = self.M_vects[3]
        self.M_vects.remove(M_vect)

        self.play(FadeOut(self.M_vects))
        self.play(ShowCreation(E_vects), Animation(M_vect))
        self.play(
            M_vect.rotate, np.pi, RIGHT, [], point,
            run_time = 5,
            rate_func = None,
        )
        self.dither(3)

class WriteCurlEquations(Scene):
    def construct(self):
        eq1 = TexMobject(
            "\\nabla \\times", "\\textbf{E}", "=",
            "-\\frac{1}{c}",
            "\\frac{\\partial \\textbf{B}}{\\partial t}"
        )
        eq2 = TexMobject(
            "\\nabla \\times", "\\textbf{B}", "=^*",
            "\\frac{1}{c}",
            "\\frac{\\partial \\textbf{E}}{\\partial t}"
        )
        footnote = TextMobject("*Ignoring currents")
        footnote.scale(0.7)
        eqs = VGroup(eq1, eq2, footnote)
        eqs.arrange_submobjects(DOWN, buff = LARGE_BUFF)
        eqs.scale_to_fit_height(2*SPACE_HEIGHT - 1)
        for eq in eqs:
            eq.highlight_by_tex_to_color_map({
                "E" : E_COLOR,
                "B" : M_COLOR,
            })

        self.play(Write(eq1, run_time = 2))
        self.dither(3)
        self.play(Write(eq2, run_time = 2))
        self.play(FadeIn(footnote))
        self.dither(3)

class IntroduceEMWave(ThreeDScene):
    CONFIG = {
        "EMWave_config" : {
            "requires_start_up" : True
        }
    }
    def setup(self):
        self.axes = ThreeDAxes()
        self.add(self.axes)
        self.em_wave = EMWave(**self.EMWave_config)
        self.add(self.em_wave)
        self.set_camera_position(0.8*np.pi/2, -0.7*np.pi)
        self.begin_ambient_camera_rotation()

    def construct(self):
        words = TextMobject(
            "Electro", "magnetic", " radiation",
            arg_separator = ""
        )
        words.highlight_by_tex_to_color_map({
            "Electro" : E_COLOR,
            "magnetic" : M_COLOR,
        })
        words.next_to(ORIGIN, LEFT, MED_LARGE_BUFF)
        words.to_edge(UP)
        words.rotate(np.pi/2, RIGHT)

        self.dither(7)
        self.play(Write(words, run_time = 2))
        self.dither(20)

    #####

class SimpleEMWave(IntroduceEMWave):
    def construct(self):
        self.dither(30)

class ListRelevantWaveIdeas(TeacherStudentsScene):
    def construct(self):
        title = TextMobject("Wave","topics")
        title.to_corner(UP + LEFT, LARGE_BUFF)
        title.highlight(BLUE)
        h_line = Line(title.get_left(), title.get_right())
        h_line.next_to(title, DOWN, SMALL_BUFF)

        topics = VGroup(*map(TextMobject, [
            "- Superposition",
            "- Amplitudes",
            "- Phase influences addition",
        ]))
        topics.scale(0.8)
        topics.arrange_submobjects(DOWN, aligned_edge = LEFT)
        topics.next_to(h_line, DOWN, aligned_edge = LEFT)

        quantum = TextMobject("Quantum")
        quantum.highlight(GREEN)
        quantum.move_to(title[0], LEFT)

        wave_point = self.teacher.get_corner(UP+LEFT) + 2*UP
        self.play(
            Animation(VectorizedPoint(wave_point)),
            self.teacher.change, "raise_right_hand"
        )
        self.dither(2)
        self.play(
            Write(title, run_time = 2),
            ShowCreation(h_line)
        )
        self.change_student_modes(
            *["pondering"]*3,
            added_anims = [LaggedStart(
                FadeIn, topics,
                run_time = 3
            )],
            look_at_arg = title
        )
        self.play(
            Animation(title),
            self.teacher.change, "happy"
        )
        self.play(
            title[0].next_to, quantum.copy(), UP, MED_SMALL_BUFF, LEFT,
            title[0].fade, 0.5,
            title[1].next_to, quantum.copy(), RIGHT, 2*SMALL_BUFF,
            Write(quantum),
        )
        self.dither(5)

class DirectWaveOutOfScreen(IntroduceEMWave):
    CONFIG = {
        "EMWave_config" : {
            "requires_start_up" : False,
            "amplitude" : 2,
            "start_point" : SPACE_WIDTH*LEFT,
            "A_vect" : [0, 1, 0],
            "start_up_time" : 0,
        }
    }
    def setup(self):
        IntroduceEMWave.setup(self)
        self.remove(self.axes)
        for ov in self.em_wave.continual_animations:
            ov.vector.normal_vector = RIGHT
        self.set_camera_position(0.9*np.pi/2, -0.3*np.pi)

    def construct(self):
        self.move_into_position()

    def move_into_position(self):
        self.dither(2)
        self.continual_update()
        faded_vectors = VGroup(*[
            ov.vector
            for ov in self.em_wave.continual_animations[:-2]
        ])
        self.move_camera(
            0.99*np.pi/2, -0.01,
            run_time = 2,
            added_anims = [faded_vectors.set_fill, None, 0.5]
        )
        self.stop_ambient_camera_rotation()
        self.move_camera(
            np.pi/2, 0,
            added_anims = [faded_vectors.set_fill, None, 0.05],
            run_time = 2,
        )
        self.play(
            self.em_wave.M_vects.set_fill, None, 0
        )
        self.dither(2)
        self.play(faded_vectors.set_fill, None, 0)
        self.dither(4)

class ShowVectorEquation(Scene):
    def construct(self):
        self.force_skipping()

        self.add_vector()
        self.add_plane()
        self.write_horizontally_polarized()
        self.write_components()
        self.show_graph()
        self.add_phi()
        self.add_amplitude()
        self.add_kets()
        self.switch_to_vertically_polarized_light()

    def add_vector(self):
        self.vector = Vector(2*RIGHT, color = E_COLOR)
        self.oscillating_vector = OscillatingVector(
            self.vector,
            A_vect = [2, 0, 0],
            frequency = 0.25,
        )
        self.add(self.oscillating_vector)
        self.revert_to_original_skipping_status()
        self.dither(3)

    def add_plane(self):
        pass

    def write_horizontally_polarized(self):
        pass

    def write_components(self):
        pass

    def show_graph(self):
        pass

    def add_phi(self):
        pass

    def add_amplitude(self):
        pass

    def add_kets(self):
        pass

    def switch_to_vertically_polarized_light(self):
        pass


import sys
import itertools

input = sys.stdin.readline
rtn = []
for i in range(0,9):
    rtn.append(int(input()))

rtn.sort()

for i in itertools.combinations(rtn, 7):
    if sum(i) == 100 :
        for j in sorted(i):
            print(j)
        break

백준/강의문제_누적합/일곱난쟁이.py


import argparse
import boto3
import json
import os
import sys
from six.moves import urllib
import uuid
import traceback
from botocore.exceptions import ClientError

from dictionary_sorter import divide
from dictionary_sorter import merge
from dictionary_sorter import build

from harness import config
from harness import decider
from harness import worker
from harness import cloudwatch

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--domain", required=True)
    parser.add_argument("-t", "--task-list", required=True)
    parser.add_argument("--div-task", required=True)
    parser.add_argument("--div-task-version", default="1.0")
    parser.add_argument("--merge-task", required=True)
    parser.add_argument("--merge-task-version", default="1.0")
    parser.add_argument("--build-task", default=None)
    parser.add_argument("--build-task-version", default="1.0")
    parser.add_argument("-rd", "--run-decider", action="store_true")
    parser.add_argument("--region", default=None)
    parser.add_argument("--config-bucket", default=None)
    parser.add_argument("--log-group", default=None)
    parser.add_argument("--log-db", default=None)
    parser.add_argument("--kvs-db", default=None)
    parser.add_argument("--profile", default=None)
    parser.add_argument("--role-arn", default=None)
    parser.add_argument("--stdout", default=None)
    args = parser.parse_args()

    try:
        # Fetch instance identity: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html
        with urllib.request.urlopen('http://169.254.169.254/latest/dynamic/instance-identity/document') as response:
            info = json.load(response)
            ec2_region = info['region']
            identity = info['instanceId']
            print("Running on EC2 instance {} in region {}".format(identity, ec2_region))
    except:
        ec2_region = "us-east-1"
        identity = os.environ.get("COMPUTERNAME", "<unavailable>")
        print("Couldn't load EC2 instance data from environment, using computer hostname {}".format(identity))

    if not args.region:
        args.region = ec2_region

    # You can supply a profile to use if you are testing locally.
    session = boto3.Session(region_name=args.region, profile_name=args.profile)

    # You can supply a role arn to use if you are testing locally.
    if args.role_arn:
        sts_result = session.client('sts').assume_role(
            DurationSeconds=3600,
            RoleSessionName="Harness-" + str(uuid.uuid4()),
            RoleArn=args.role_arn
        )['Credentials']
        session = boto3.Session(
            region_name=args.region,
            aws_access_key_id=sts_result['AccessKeyId'],
            aws_secret_access_key=sts_result['SecretAccessKey'],
            aws_session_token=sts_result['SessionToken']
        )

    if args.stdout:
        if args.stdout == 'cloudwatch':
            writeHandler = cloudwatch.OutputHandler('HARNESS-DEBUG', session, args.region, identity, 'decider' if args.run_decider else 'worker')
        else:
            fp = open(args.stdout, "w")
            sys.stdout = fp
            sys.stderr = fp

    divide_task = config.TaskConfig(args.div_task, args.div_task_version, divide.handler)
    merge_task = config.TaskConfig(args.merge_task, args.merge_task_version, merge.handler)
    build_task = config.TaskConfig(args.build_task, args.build_task_version, build.handler) if args.build_task else merge_task
    harness_config = config.Config(session, args.region, args.domain, args.task_list, divide_task, build_task,
                                   merge_task, args.log_group, args.log_db, args.kvs_db, args.config_bucket, identity)

    try:
        if args.run_decider:
            decider.run_decider(harness_config)
        else:
            worker.run_worker(harness_config)
    except Exception as e:
            message = "Error - " + str(e) + "\n" + traceback.format_exc()
            print(message)


from IPython.display import clear_output
import numpy as np
pi = np.pi
from qiskit.circuit.library import QFT
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
import operator

clear_output()

def initialize_qubits(given_circuit, measurement_qubits, target_qubit):
    # move all the qubits to |-> state
    given_circuit.h(measurement_qubits)
    # except the controlled one, to |1>
    given_circuit.x(target_qubit)

def unitary_operator(given_circuit, control_qubit, target_qubit, theta):
    # create a basic unitary operator
    given_circuit.cp(2*pi*theta, control_qubit, target_qubit)

def unitary_operator_exponent(given_circuit, control_qubit, target_qubit, theta, exponent):
    # create a unitary operator which takes into account the exponent
    given_circuit.cp(2*pi*theta*exponent, control_qubit, target_qubit)

def apply_iqft(given_circuit, measurement_qubits, n):
    # applt the quantum fourier transform on all measurement qubits
    given_circuit.append(QFT(n).inverse(), measurement_qubits)

def qpe_program(n, theta):

    # Create a quantum circuit on n+1 qubits (n measurement, 1 target)
    qc = QuantumCircuit(n+1, n)

    # Initialize the qubits
    initialize_qubits(qc, range(n), n)

    # Apply the controlled unitary operators in sequence
    for x in range(n):
        exponent = 2**(n-x-1)
        unitary_operator_exponent(qc, x, n, theta, exponent)

    # Apply the inverse quantum Fourier transform
    apply_iqft(qc, range(n), n)

    # Measure all qubits
    qc.measure(range(n), range(n))

    return qc

def est(n, theta):
    n = 24; theta = 0.5
    mycircuit = qpe_program(n, theta)
    simulator = Aer.get_backend('qasm_simulator')
    counts = execute(mycircuit, backend=simulator).result().get_counts(mycircuit)
    highest_probability_outcome = max(counts.items(), key = operator.itemgetter(1))[0][::-1]
    measured_theta = int(highest_probability_outcome, 2)/2**n
    print("Using %d qubits with theta = %.2f, measured_theta = %.2f." % (n, theta, measured_theta))

def main():
    n = 20; theta = 0.5
    for i in range(32):
        est(n, i)

if __name__ == '__main__':
    print(QFT(4).draw())
    main()


import config
import os
import json
from expertai.nlapi.cloud.client import ExpertAiClient
client = ExpertAiClient()

os.environ["EAI_USERNAME"] = config.expertai_mail
os.environ["EAI_PASSWORD"] = config.expertai_password

def sentiment(text):
    """returns overall sentiment"""
    output = client.specific_resource_analysis(body = {"document":{"text": text}},
                                               params = {'language': 'en','resource': 'sentiment'})
    return output.sentiment.overall

def named_entity_extraction(text):
    """extract named entities"""
    output = client.specific_resource_analysis(body={"document": {"text": text}},
                                               params={'language': 'en', 'resource': 'entities'})
    return [entity.lemma for entity in output.entities]

def key_phrase_extraction(text):
    """extract key phrases"""
    output = client.specific_resource_analysis(body={"document": {"text": text}},
                                               params={'language': 'en', 'resource': 'relevants'})
    return [lemma.value for lemma in output.main_lemmas]

def resource_concept_score_analysis(text):
    """extract concept and provide the score"""
    document = client.specific_resource_analysis(
        body={"document": {"text": text}},
        params={'language': "en", 'resource': 'relevants'})
    # print(f'{"CONCEPT":{20}} {"SCORE":{5}} \n')
    return [f'{main_concept.lemma:{2}}: {main_concept.score:{1}}' for main_concept in document.main_syncons]

def deep_linguistic_analysis(text):
    """returns POS for words in the text"""
    output = client.specific_resource_analysis(
        body={"document": {"text": text}},
        params={'language': 'en', 'resource': 'disambiguation'
                })
    # print(f'{"TEXT":{20}} {"LEMMA":{40}} {"POS":{6}}')
    # print(f'{"----":{20}} {"-----":{40}} {"---":{6}}')
    # return [f'{text[token.start:token.end]:{20}} {token.lemma:{40}} {token.pos:{6}}' for token in output.tokens]
    return [f'{text[token.start:token.end]} {token.lemma} {token.pos}' for token in output.tokens]

def document_classification(text):
    taxonomy = 'iptc'
    document = client.classification(
        body={"document": {"text": text}},
        params={'taxonomy': taxonomy, 'language': 'en'})
    # print(f'{"CATEGORY":{47}} {"IPTC ID":{10}} {"FREQUENCY":{8}}\n')
    return [f'{category.label:{47}} {category.id_:{10}}{category.frequency:{8}}' for category in document.categories]

# Check if a single function can be made for behavioural traits and document classification.
def behavioural_traits(text):
    taxonomy ='behavioral-traits'
    output = client.classification(
        body={"document": {"text": text}},
        params={'taxonomy': taxonomy, 'language': 'en'})
    print("list of categories")
    list = []
    for category in output.categories:
        list.append({"category.id_":category.id_,"category.hierarchy":category.hierarchy})
    return list
    # return [[category.id_,category.hierarchy]for category in output.categories]

def information_detection(text):
    """ add details """
    detector = 'pii'
    output = client.detection(
        body={"document": {"text": text}},
        params={"detector": detector, 'language': 'en'})
    return "extra_data: " + json.dumps(output.extra_data, indent=4, sort_keys = True)

def relation_extraction(text):
    """shows the relations in the text given"""
    output = client.specific_resource_analysis(
        body={"document": {"text": text}},
        params={'language': "en", 'resource': 'relations'})
    print("Output relations' data:")
    output_relations = []
    for relation in output.relations:
        print(relation.verb.lemma, ":");
        for related in relation.related:
            print("\t", "(", related.relation, ")", related.lemma);
    #add return statement

def full_document_analysis(text):
    """ add details"""
    output = client.full_analysis(
        body={"document": {"text": text}},
        params={'language': "en"})
    try:
        print("knowledge: ", len(output.knowledge))
        print("paragraphs: ", len(output.paragraphs))
        print("sentences: ", len(output.sentences))
        print("phrases: ", len(output.phrases))
        print("tokens: ", len(output.tokens))
        print("mainSentences: ", len(output.main_sentences))
        print("mainPhrases: ", len(output.main_phrases))
        print("mainLemmas: ", len(output.main_lemmas))
        print("mainSyncons: ", len(output.main_syncons))
        print("topics: ", len(output.topics))
        print("entities: ", len(output.entities))
        print("relations: ", len(output.relations))
        print("sentiment.items: ", len(output.sentiment.items))
        return 1
    except Exception as e:
        return 0

#
# if __name__ == '__main__':
#
#     t = "This is not a great present"
#     # print(sentiment(t))
#     # print(named_entity_extraction(t))
#     # print(key_phrase_extraction(t))
#     # print(document_classification(t))
#     # print(deep_linguistic_analysis(t))
#     # print(relation_extraction(t))
#     # print(full_document_analysis(t))
#     # print(information_detection(t))
#     # print(resource_concept_score_analysis(t))
#     # print(behavioural_traits(t))


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

import re,urlparse
from liveresolver.modules import client

def resolve(url):
    try:
        try: referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0]
        except: referer = url

        page = urlparse.parse_qs(urlparse.urlparse(url).query)['live'][0]
        page = 'http://www.yotv.co/embed.php?live=%s&vw=620&vh=490' % page

        result = client.request(page, referer=referer)
        rtmp = re.compile('file\s*:\s*(?:\"|\')(.+?)(?:\"|\')').findall(result)[0]
        token = re.compile('securetoken\s*:\s*(?:\"|\')(.+?)(?:\"|\')').findall(result)[0]

        url= rtmp + ' swfUrl=http://p.jwpcdn.com/6/11/jwplayer.flash.swf live=1 token=' + token + ' timeout=14 swfVfy=1 pageUrl=' + page
        return url
    except:
        return


import requests
import json

class PedidoVendaService(object):
    @classmethod
    def get_pedidos(cls, url, access_token, inicio=0, contador=0):
        headers = {'authorization': access_token}
        params = {'sort': 'id', 'start': inicio, 'count': contador}
        lista_resultado = []
        print('headers:\n', headers)
        url_funcao = "/api/v1/venda/pedidos"
        url_api = url + url_funcao
        print('url_api: \n', url_api)
        req = requests.get(url_api, headers=headers, params=params)
        print(req.status_code)
        if req.status_code == 200:
            resultado = json.loads(req.text)
            print('lista dos pedidos!\n')
            contagem = 0
            for item in resultado['items']:
                #print(item['id'], '\n')
                #print(item)
                lista_resultado.append(item)
                contagem += 1
            print('total de itens: ', str(contagem))
            return lista_resultado
        else:
            return None

    @classmethod
    def get_pedido_por_id(cls, url, access_token, id_pedido):
        headers = {'authorization': access_token}
        # params = {'id': id_produto}
        lista_resultado = []
        print('headers:\n', headers)
        url_funcao = "/api/v1/venda/pedidos/"  # aceita auxiliar
        url_api = url + url_funcao + str(id_pedido)
        print('url_api: \n', url_api)
        req = requests.get(url_api, headers=headers)
        print(req.status_code)
        if req.status_code == 200:
            resultado = json.loads(req.text)
            print('lista dos itens!\n')
            return resultado
        else:
            return None

    @classmethod
    def get_atendimentos_pedido(cls):
        pass

    @classmethod
    def post_add_pedido(cls, url, access_token, pedido_json):
        headers = {'authorization': access_token, 'content-type': 'application/json'}
        #data_sent = json.dumps(pedido_json)   alterado, pois utilizo json.dumps em model.Pedido.to_json()
        data_sent = pedido_json
        url_funcao = "/api/v1/venda/pedidos"
        url_api = url + url_funcao
        print('Iniciando inclusão, executando post na url:\n', url_api)
        #print('pedido_json:\n', pedido_json)
        req = requests.post(url_api, data=data_sent, headers=headers)
        print("Resultado: ", req.status_code)
        if req.status_code != 201:
            print('retorno:\n')
            print(req.text)
        ret = req
        req.close()
        return ret

    @classmethod
    def post_cancela_pedido(cls):
        pass


"""
f: frequency
LFUCache(10)
self.head                                   indexNode.head                                indexNode.tail
    |                                          |                                             |
indexmap[1]---->indexNode(f = 1)------------Node(key = 1,f = 1)<-->Node(key = 3,f = 1)<-->Node(key = 4,f = 1)
                        |
                        |                   indexNode.head                                                        indexNode.tail
                        |                       |                                                                    |
indexmap[2]---->indexNode(f = 2)------------Node(key = 5,f = 2)<-->Node(key = 11,f = 2)<-->Node(key = 13,f = 2)<-->Node(key = 15,f = 2)
                        |
                        |                   indexNode.head                               indexNode.tail
                        |                       |                                            |
indexmap[5]---->indexNode(f = 5)------------Node(key = 8,f = 5)<-->Node(key = 9,f = 5)<-->Node(key = 7,f = 5)
    |
self.tail

# remove:each time remove the self.head.head's node
# put:if the key exist for example put(3,4) we just remove the node from indexNode(f = 1) and then add the node to indexNode(f = 2)'s
# tail and update the indexNode'cnt and the node'f
# if the key doesn't exist for example put(100,100),we just remove the self.head.head's node and put the key in the indexNode(f = 1)'s
# tail
# get:get(4) we just remove the node(key = 4,f = 1) from the indexNode(f = 1) and add the node(key = 4,f = 1) to the indexNode(f = 2)'s
# tail and update the indexNode(f = 1)'s cnt and indexNode(f = 2)'s cnt and update node(key = 4,f= 1) to node(key = 4,f = 2)
"""

class Node(object):
    def __init__(self, key, value):
        """
        Node is the base element which present the key and value. and Node will be appended to the indexNode's tail
        f means the node's referenced frequency
        :param key: key
        :param value: value
        """
        self.value = value
        self.pre = None
        self.next = None
        self.key = key
        self.f = 1

# todo  too weird this problem ... amazing
class indexNode(object):
    def __init__(self, f):
        """
        many indexNode will form a double-linked {indexNode list}
        f means the node in the double-linked {Node list} are same
        each indexNode will be appended by a Node list！
        :param f:
        """
        self.f = f
        self.pre = None
        self.next = None
        self.cnt = 0
        self.head = None
        self.tail = None

class LFUCache(object):
    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.capacity = capacity
        self.cnt = 0
        self.keymap = {}
        # each time we replace one element form the LFU, we just need to delete the first indexNode's head
        # self.head reprensents the first indexNode which means the lowest frequency indexNode
        self.head = None
        # self.tail reprensents the last indexNode which means the highest frequency indexNode
        self.tail = None
        self.indexmap = {}

    def addindexnode(self, f):
        """
        just add a f frequency to the indexNode list
        :param f: frequency
        :return: void
        """
        node = indexNode(f)
        self.indexmap[f] = node

        if not self.head and not self.tail:
            self.head = node
            self.tail = node
            return

        if f < self.head.f:
            self.head.pre = node
            node.next = self.head
            self.head = node
        else:
            # each time we add a new indexNode to the double-linked indexNode list
            # we assume the indexNode before this one has the frequency f-1
            inode = self.indexmap[f - 1]
            if inode.next:
                tmp = inode.next
                node.next = tmp
                tmp.pre = node
                inode.next = node
                node.pre = inode
            else:
                inode.next = node
                node.pre = inode
                self.tail = node

    def removeindexnode(self, f):
        """
        when the indexNode's cnt == 0 , we need to remove the indexNode so that to make sure the first indexNode
        always has the lowest frequency.
        :param f: int  remove the indexNode which has the frequency f
        :return:void
        """
        indexnode = self.indexmap[f]
        # delete the f in indexmap.
        del self.indexmap[f]
        if self.head == self.tail:
            self.head = None
            self.tail = None
        elif self.head == indexnode:
            self.head = self.head.next
            self.head.pre = None
        elif self.tail == indexnode:
            self.tail = self.tail.pre
            self.tail.next = None
        else:
            tmp = indexnode.pre
            tmp.next = indexnode.next
            tmp.next.pre = tmp
        del indexnode

    def removenode(self):
        """
        when the cnt equals the capacity, if add a new key to the LFUCache
        we need to remove the first indexNode's first Node
        at the same time we will return a int f, this f will be used in lazy delete because
        when we addindexNode we will need the f-1's indexNode, so after we addindexNode, then
        we can use the f to adjustIndexNode
        :return: int if the return value is -1, don't need to remove the f indexNode else remove the f indexNode
        """
        if not self.head:
            return  -1
        else:
            indexnode = self.head
            node = indexnode.head
            indexnode.cnt -= 1
            if node.next:
                indexnode.head = indexnode.head.next
                indexnode.head.pre = None
                del self.keymap[node.key]
                del node
                return -1
            else:
                f = node.f
                indexnode.head = None
                indexnode.tail = None
                del self.keymap[node.key]
                del node
                return f

    def adjustIndexNode(self,f):
        """
        delete the f indexNode if the indexnode's cnt == 0
        :param f:
        :return: void
        """
        if not self.indexmap.has_key(f):
            return
        inode = self.indexmap[f]
        if inode.cnt == 0:
            self.removeindexnode(f)

    def leave(self, node):
        """
        remove the node from the node.f indexNode if the indexNode's cnt becomes 0 after the node's leave,
        we will delete the indexNode in adjustindexnode(f)
        :param node:
        :return: f  #f represent the f indexNode will be adjust
        """
        f = node.f
        node.f += 1
        indexnode = self.indexmap[f]
        indexnode.cnt -= 1
        if indexnode.head == indexnode.tail:
            indexnode.head = None
            indexnode.tail = None
        elif indexnode.head == node:
            indexnode.head = indexnode.head.next
            indexnode.head.pre = None
        elif indexnode.tail == node:
            indexnode.tail = indexnode.tail.pre
            indexnode.tail.next = None
        else:
            tmpnode = node.pre
            tmpnode.next = node.next
            tmpnode.next.pre = tmpnode
        return f

    def forward(self, node):
        """
        according the node.f to move the node to the node.f indexNode, if there is no node.f indexNode
        then addindexnode(f)
        :param node: the node to be forwarded
        :return: void
        """
        f = node.f
        if not self.indexmap.has_key(f):
            self.addindexnode(f)
        indexnode = self.indexmap[f]
        indexnode.cnt += 1
        if not indexnode.head and not indexnode.tail:
            indexnode.head = node
            indexnode.tail = node
        else:
            indexnode.tail.next = node
            node.pre = indexnode.tail
            indexnode.tail = node

    def add(self, node):
        """
        if cnt < capacity then just forward the node else remove an node to
        keep the capacity then after forward the f indexNode we can lazy
        delete the f indexnode
        :param node: the new node to be added
        :return:void
        """
        if self.cnt < self.capacity:
            self.cnt += 1
            self.forward(node)
        else:
            f = self.removenode()
            self.forward(node)
            if f != -1:
                self.adjustIndexNode(f)

    def get(self, key):
        """
        each time we add the key node's f by 1 and forward the node and adjustIndexNode
        :type key: int
        :rtype: int
        """
        if self.capacity == 0:
            return -1
        if not self.keymap.has_key(key):
            return -1
        node = self.keymap[key]
        tmpf = self.leave(node)
        self.forward(node)
        self.adjustIndexNode(tmpf)
        return node.value

    def put(self, key, value):
        """
        if the key has existed for a while then we just leave the node from the f indexNode and
        forward the node to the f+1 indexNode else we add a new node to the LFUCache, if there is
        a need, we shuld remove the first indexNode's first node
        :param key:
        :param value:
        :return: void
        """
        if self.capacity == 0:
            return -1
        if self.keymap.has_key(key):
            node = self.keymap[key]
            node.value = value
            f = self.leave(node)
            self.forward(node)
            self.adjustIndexNode(f)
        else:
            node = Node(key, value)
            self.keymap[key] = node
            self.add(node)

# hh = LFUCache(10)
# hh.put(1,1)
# hh.put(2,2)
# hh.get(1)
# hh.put(3,3)
# hh.get(2)
# hh.get(3)
# hh.put(4,4)
# hh.put(1,1)
# hh.put(2,2)
# hh.get(1)
# hh.put(3,3)
# hh.get(2)
# hh.get(3)
# hh.put(9,4)
# hh.put(10,1)
# hh.put(12,2)
# hh.get(1)
# hh.put(33,3)
# hh.get(2)
# hh.get(3)
# hh.put(54,4)
# hh.put(313,4)
# hh.put(230,1)
# hh.put(4322,2)
hh = LFUCache(10)
a = ["put","put","put","put","put","get","put","get","get","put","get","put","put","put","get","put","get","get","get","get","put","put","get","get","get","put","put","get","put","get","put","get","get","get","put","put","put","get","put","get","get","put","put","get","put","put","put","put","get","put","put","get","put","put","get","put","put","put","put","put","get","put","put","get","put","get","get","get","put","get","get","put","put","put","put","get","put","put","put","put","get","get","get","put","put","put","get","put","put","put","get","put","put","put","get","get","get","put","put","put","put","get","put","put","put","put","put","put","put"]
b = [[10,13],[3,17],[6,11],[10,5],[9,10],[13],[2,19],[2],[3],[5,25],[8],[9,22],[5,5],[1,30],[11],[9,12],[7],[5],[8],[9],[4,30],[9,3],[9],[10],[10],[6,14],[3,1],[3],[10,11],[8],[2,14],[1],[5],[4],[11,4],[12,24],[5,18],[13],[7,23],[8],[12],[3,27],[2,12],[5],[2,9],[13,4],[8,18],[1,7],[6],[9,29],[8,21],[5],[6,30],[1,12],[10],[4,15],[7,22],[11,26],[8,17],[9,29],[5],[3,4],[11,30],[12],[4,29],[3],[9],[6],[3,4],[1],[10],[3,29],[10,28],[1,20],[11,13],[3],[3,12],[3,8],[10,9],[3,26],[8],[7],[5],[13,17],[2,27],[11,15],[12],[9,19],[2,15],[3,16],[1],[12,17],[9,1],[6,19],[4],[5],[5],[8,1],[11,7],[5,2],[9,28],[1],[2,2],[7,4],[4,22],[7,24],[9,26],[13,28],[11,26]]
for i in range(0,len(a)):
    if i == 46:
        print('as')
    if a[i] == 'put':
        stm = "hh.%s(%s,%s)" % (a[i], b[i][0],b[i][1])
        if b[i][0] == 7:
            print('fuck')
    else:
        stm = "hh.%s(%s)" % (a[i], b[i][0])
    print(stm,i)
    exec(stm)

print(hh.get(4))


from math import copysign

sign = lambda x: int(copysign(1, x))

with open('data/day14.txt') as infile:
    lines = infile.read().splitlines()

    wall_coords = []
    sand_coords = []
    sand_origin = (500, 0)
    max_wall = 0

    voided = False
    # true for p2, false for p1
    # WARNING: p2 takes a bit
    do_bottom = True

    for l in lines:
        wall_formations = l.split(' -> ')
        for i, w in enumerate(wall_formations):
            wall_formations[i] = [int(k) for k in w.split(',')]

        for i, w in enumerate(wall_formations):
            if w[1] > max_wall:
                max_wall = w[1]
            if i < len(wall_formations) - 1:
                x1, y1 = w[0], w[1]
                x2, y2 = wall_formations[i + 1][0], wall_formations[i + 1][1]

                if x1 == x2:
                    for y in range(y1, y2, sign(y2 - y1)):
                        wall_coords.append((x1, y))
                else:
                    for x in range(x1, x2, sign(x2 - x1)):
                        wall_coords.append((x, y1))
            else:
                wall_coords.append((w[0], w[1]))

    sand_list = [sand_origin]
    while not voided and len(sand_list) > 0:
        sand = sand_list[-1]
        while True:
            down = (sand[0], sand[1] + 1)
            left = (sand[0] - 1, sand[1] + 1)
            right = (sand[0] + 1, sand[1] + 1)
            if sand[1] > max_wall and not do_bottom:
                voided = True
                break
            elif sand[1] > max_wall and do_bottom:
                sand_coords.append(tuple(sand))
                sand_list.pop()
                break
            if down not in wall_coords and down not in sand_coords:
                sand = list(down)
                sand_list.append(list(down))
            elif left not in wall_coords and left not in sand_coords:
                sand = list(left)
                sand_list.append(list(left))
            elif right not in wall_coords and right not in sand_coords:
                sand = list(right)
                sand_list.append(list(right))
            else:
                sand_coords.append(tuple(sand))
                sand_list.pop()
                break

    print(len(sand_coords))


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

from tf_explain.utils.display import grid_display
from tf_explain.utils.image import transform_to_normalized_grayscale
from tf_explain.utils.saver import save_grayscale

import matplotlib.pyplot as plt

def min_max_scale(tensor):
    out_tensor = tf.math.divide(
        tf.math.subtract(tensor, tf.reduce_min(tensor)),
        tf.math.subtract(tf.reduce_max(tensor), tf.reduce_min(tensor)),
    )
    return out_tensor

class SmoothGrad:

    """
    Compute SmoothGrad interpretability maps for a given input image
    Paper: [SmoothGrad: removing noise by adding noise](https://arxiv.org/abs/1706.03825)
    adapted from https://github.com/sicara/tf-explain
    """

    def explain(
        self,
        data,
        model,
        class_index,
        num_samples=5,
        noise=1.0,
        ch_specific_grads=False,
        transform_range=False,
    ):
        """ Computes and returns SmoothGrad gradient attribution map for given input data
            Args:
                data: data to analyse in form of numpy array or tf-Tensor
                model: tf.keras.models.Model instance to perform analysis with
                class_index: class index of data sample
                num_samples: the number of noisy samples to compute and average the gradient attribution maps with
                noise: noise standard deviation to apply
                ch_specific_grads: whether to compute channel specific gradient attribution maps
                transform_range: whether to scale output to [0-255] range
        """
        noisy_images = SmoothGrad.generate_noisy_images(data, num_samples, noise)
        smoothed_gradients = SmoothGrad.get_averaged_gradients(
            noisy_images, model, class_index, num_samples
        )

        if ch_specific_grads:
            # normalize
            print("returning channel specific interpretability map")
            normalized_grads = min_max_scale(tf.abs(smoothed_gradients)).numpy()
            out_grad = normalized_grads
            out_gradximg = (normalized_grads * data).squeeze()
            out_gradximg = min_max_scale(out_gradximg).numpy()

        else:
            # sum reduction along channel axis -> normalize
            print("returning channel unspecific interpretability map")
            reduced_grads = tf.reduce_sum(tf.abs(smoothed_gradients), axis=-1)
            normalized_grads = min_max_scale(reduced_grads).numpy()
            out_grad = normalized_grads
            out_gradximg = (
                (normalized_grads * tf.reduce_mean(data, axis=-1)).numpy().squeeze()
            )
            out_grad = np.repeat(
                np.expand_dims(out_grad, axis=-1), repeats=data.shape[-1], axis=-1,
            )
            out_gradximg = np.repeat(
                np.expand_dims(out_gradximg, axis=-1), repeats=data.shape[-1], axis=-1,
            )
            out_gradximg = min_max_scale(out_gradximg).numpy()
        if transform_range:
            out_grad = (out_grad * 255).astype(np.uint8)
            out_gradximg = (out_gradximg * 255).astype(np.uint8)
        return out_grad, out_gradximg

    @staticmethod
    def generate_noisy_images(images, num_samples, noise):
        repeated_images = np.repeat(images, num_samples, axis=0)
        noise = np.random.normal(0, noise, repeated_images.shape).astype(np.float32)

        return repeated_images + noise

    @staticmethod
    @tf.function
    def get_gradients(inputs, targets, model):
        with tf.GradientTape() as tape:
            inputs = tf.cast(inputs, tf.float32)
            tape.watch(inputs)
            predictions = model(inputs)
            loss = tf.keras.losses.binary_crossentropy(targets, predictions)
        grads = tape.gradient(loss, inputs)
        return grads

    @staticmethod
    def get_averaged_gradients(noisy_images, model, class_index, num_samples):
        expected_output = np.expand_dims(
            np.array([class_index], dtype=np.float32), axis=0
        )
        grad_list = []
        for sample in tqdm(noisy_images):
            sample_grad = SmoothGrad.get_gradients(
                inputs=sample[None], targets=expected_output, model=model
            )
            grad_list.append(sample_grad.numpy())
        grads = np.stack(grad_list, axis=0).squeeze()
        averaged_grads = np.mean(grads, axis=0)

        return averaged_grads


# Autocomplete component for Pyjamas
# Ported by Willie Gollino from Autocomplete component for GWT - Originally by Oliver Albers http://gwt.components.googlepages.com/

from ui import TextBox, PopupPanel, ListBox, KeyboardListener, RootPanel

class AutoCompleteTextBox(TextBox):
    def __init__(self):
        self.choicesPopup = PopupPanel(True)
        self.choices = ListBox()
        self.items = SimpleAutoCompletionItems()
        self.popupAdded = False
        self.visible = False

        TextBox.__init__(self)
        self.addKeyboardListener(self)
        self.choices.addChangeListener(self)
        self.setStyleName("AutoCompleteTextBox")

        self.choicesPopup.add(self.choices)
        self.choicesPopup.addStyleName("AutoCompleteChoices")

        self.choices.setStyleName("list")

    def setCompletionItems(self, items):
        if not items.getCompletionItems:
            items = SimpleAutoCompletionItems(items)

        self.items = items

    def getCompletionItems(self):
        return self.items

    def onKeyDown(self, arg0, arg1, arg2):
        pass

    def onKeyPress(self, arg0, arg1, arg2):
        pass

    def onKeyUp(self, arg0, arg1, arg2):
        if arg1 == KeyboardListener.KEY_DOWN:
            selectedIndex = self.choices.getSelectedIndex()
            selectedIndex += 1
            if selectedIndex > self.choices.getItemCount():
                selectedIndex = 0

            self.choices.setSelectedIndex(selectedIndex)
            return

        if arg1 == KeyboardListener.KEY_UP:
            selectedIndex = self.choices.getSelectedIndex()
            selectedIndex -= 1
            if selectedIndex < 0:
                selectedIndex = self.choices.getItemCount()
            self.choices.setSelectedIndex(selectedIndex)
            return

        if arg1 == KeyboardListener.KEY_ENTER:
            if self.visible:
                self.complete()
            return

        if arg1 == KeyboardListener.KEY_ESCAPE:
            self.choices.clear()
            self.choicesPopup.hide()
            self.visible = False
            return

        text = self.getText()
        matches = []
        if len(text) > 0:
            matches = self.items.getCompletionItems(text)

        if len(matches) > 0:
            self.choices.clear()

            for i in range(len(matches)):
                self.choices.addItem(matches[i])

            if len(matches) == 1 and matches[0] == text:
                self.choicesPopup.hide()
            else:
                self.choices.setSelectedIndex(0)
                self.choices.setVisibleItemCount(len(matches) + 1)

                if not self.popupAdded:
                    RootPanel().add(self.choicesPopup)
                    self.popupAdded = True

                self.choicesPopup.show()
                self.visible = True
                self.choicesPopup.setPopupPosition(self.getAbsoluteLeft(), self.getAbsoluteTop() + self.getOffsetHeight())
                self.choices.setWidth(self.getOffsetWidth() + "px")
        else:
            self.visible = False
            self.choicesPopup.hide()

    def onChange(self, arg0):
        self.complete()

    def onClick(self, arg0):
        self.complete()

    def complete(self):
        if self.choices.getItemCount() > 0:
            self.setText(self.choices.getItemText(self.choices.getSelectedIndex()))

        self.choices.clear()
        self.choicesPopup.hide()
        self.setFocus(True)

class SimpleAutoCompletionItems:
    def __init__(self, items = None):
        if items == None:
            items = []
        self.completions = items

    def getCompletionItems(self, match):
        matches = []
        match = match.lower()

        for i in range(len(self.completions)):
            lower = self.completions[i].lower()
            if lower.startswith(match):
                matches.append(self.completions[i])

        return matches


"""
https://practice.geeksforgeeks.org/problems/index-of-the-first-occurrence-of-pattern-in-a-text/1
"""
class Solution:
    def findMatching(self, text, pattern):
        if text[:len(pattern)] == pattern:
            return 0
        window = len(pattern)
        i = 1
        while i < len(text):
            if text[i:window+i] == pattern:
                return i
            i += 1
        return -1

solve = Solution()
print(solve.findMatching(text='gffgfg', pattern='gfg'))


"""Echo the model data to stdout"""
import pandas as pd

import cdf

@cdf.with_config(sections=("whatever",))
def echo(data, key=cdf.inject_config) -> None:
    """The echo publisher

    Args:
        data (cdf.Payload): The data to publish. First pos arg is supplied by cdf based on the from_model
    """
    df: pd.DataFrame = data.payload
    print(df)
    print(key)

__CDF_PUBLISHERS__ = [
    {
        "name": echo.__name__,
        "runner": echo,
        "from_model": "mart.dim_state",
        "mapping": {
            "us_state": "US State",
            "us_latitude_min": "Latitude Min",
            "us_latitude_max": "Latitude Max",
            "us_longitude_min": "Longitude Min",
            "us_longitude_max": "Longitude Max",
            "us_city_count": "City Count",
            "us_zipcode_count": "Zipcode Count",
        },
        "version": 1,
        "owners": ["Alex B"],
        "description": __doc__,
        "tags": ["echo"],
    }
]


from django.urls import include, path
from . import views

urlpatterns = [
    path('personas/', views.PersonasList.as_view()),
    path('personas/<str:id>/', views.OnePerson.as_view()),
    path('proyectos/', views.ProyectosList.as_view()),
    path('proyectos/<str:id>/', views.OneProject.as_view()),
    path('eventos/', views.EventosList.as_view()),
    path('eventos/<str:id_proyecto>/<str:fecha_inicio>/<str:fecha_final>/', views.ProjectEvents.as_view()),
    path('eventos/personas/<str:id_persona>/<str:fecha_inicio>/<str:fecha_final>/', views.PersonEvents.as_view()),
    path('areas/reuniones/<str:fecha_inicio>/<str:fecha_final>/', views.AreaMeetings.as_view()),
    path('eventos/general/tipo_trabajo/<str:fecha_inicio>/<str:fecha_final>/', views.EventsByType.as_view()),

]


# More techniques of 'memoization' (caching)
# x is a hash table where the coordinates are hashed so that calculations
# don't have to be repeated

import sys

# print(sys.getrecursionlimit())
sys.setrecursionlimit(10000)

x = {}
# calls = {}

def lat(m, n):
    if m == 0:
        return 1
    if n == 0:
        return 1
    # print(m, n)
    # Slow:
    # return lattice(m - 1, n) + lattice(m, n - 1)

    # Fast
    if (m, n) in x:
        return x[(m, n)]
    # Since a 19x2 will have the same value as 2x19, we can take advantage of this:
    if (n, m) in x:
        return x[(n, m)]
    x[(m, n)] = lat(m - 1, n) + lat(m, n - 1)
    return x[(m, n)]

print(lat(1200, 1100))
# # # Prints Pascal's triangle using the lattice method
# # [print(" ".join([str(lat(i - j, j)) for j in range(i + 1)])) for i in range(10)]
# for i in range(41):
#     for j in range(i + 1):
#         print(lat(i - j, j), end =" ")
#     print()


import sys
import asyncio
import aiojobs
from pathlib import Path
from base64 import urlsafe_b64decode
from typing import Union
from aiocrawler.distributed.server.admin import Admin
from aiocrawler.distributed.server.server import WebsocketServer
from aiocrawler.distributed.server.utils import login_required

import aiohttp_jinja2
import aiohttp_session
from aiocrawler import logger
from aiohttp import web
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from cryptography import fernet
from jinja2 import FileSystemLoader

@web.middleware
async def status404(request, handler):
    try:
        response = await handler(request)
        if response.status != 404:
            return response
    except web.HTTPException:
        pass

    return aiohttp_jinja2.render_template('404.html', request, {}, status=404)

class Dashboard(object):
    def __init__(self, project_dir: Union[str, Path] = None):
        self.__job_scheduler: aiojobs.Scheduler = aiojobs.Scheduler(close_timeout=0.1,
                                                                    limit=None,
                                                                    pending_limit=10000,
                                                                    exception_handler=None,
                                                                    loop=asyncio.get_event_loop())
        self._project_dir = Path(project_dir) if project_dir else Path()

    @login_required
    async def index(self, request: web.Request):
        return aiohttp_jinja2.render_template('index.html', request, {})

    @login_required
    async def connection(self, request: web.Request):
        return aiohttp_jinja2.render_template('connection.html', request, {})

    @login_required
    async def crawler(self, request: web.Request):
        return aiohttp_jinja2.render_template('crawler.html', request, {})

    @login_required
    async def project(self, request: web.Request):
        return aiohttp_jinja2.render_template('project.html', request, {})

    @login_required
    async def task(self, request: web.Request):
        return aiohttp_jinja2.render_template('task.html', request, {})

    @login_required
    async def get_header(self, request: web.Request):
        return aiohttp_jinja2.render_template('header.html', request, {})

    def create_app(self) -> web.Application:
        """
        create a web app
        :return: app
        """
        app = web.Application(middlewares=[status404, ])
        fernet_key = fernet.Fernet.generate_key()
        secret_key = urlsafe_b64decode(fernet_key)
        aiohttp_session.setup(app, EncryptedCookieStorage(secret_key, cookie_name='aiocrawler_session'))

        aiohttp_jinja2.setup(app, loader=FileSystemLoader('templates'))

        admin = Admin(job_scheduler=self.__job_scheduler)
        app.add_routes(admin.routes())
        app.on_startup.append(admin.on_startup)
        app.on_cleanup.append(admin.on_cleanup)

        server = WebsocketServer(job_scheduler=self.__job_scheduler, admin=admin, project_dir=self._project_dir)
        app.add_routes(server.routes())
        app.on_cleanup.append(server.close_ws_client)

        app.add_routes([
            web.get('/index', self.index, name='index'),
            web.get('/connection', self.connection, name='connection'),
            web.get('/crawler', self.crawler, name='crawler'),
            web.get('/project', self.project, name='project'),
            web.get('/task', self.task, name='task'),

            web.get('/', self.index),
            web.static('/css', 'templates/css'),
            web.static('/fonts', 'templates/fonts'),
            web.static('/img', 'templates/img'),
            web.static('/js', 'templates/js'),
            web.static('/vendor', 'templates/vendor'),
            web.static('/sass', 'templates/sass')
        ])
        return app

    def run(self):
        app = self.create_app()
        web.run_app(app, host='0.0.0.0', port=8989, print=logger.debug)

if __name__ == '__main__':
    current_dir = str(Path().absolute())
    if current_dir not in sys.path:
        sys.path.append(current_dir)
    d = Dashboard(project_dir='demo')
    d.run()


from numpy import extract

def sumofDigit(n):
    assert n >=0 and int(n)==n,'The number must be positive number'
    if n == 0:
        return 0
    else:
        return int(n%10) + sumofDigit(int(n//10))

print(sumofDigit(18))


hargasepatuA = int(input("Masukkan Harga Sepatu A: "))
hargasepatuB = int(input("Masukkan Harga Sepatu B: "))

diskon13 = 13
diskon21 = 21

diskonsepatuA13persen = hargasepatuA - (hargasepatuA * (diskon13 / 100))
diskonsepatuB21persen = hargasepatuB - (hargasepatuB * (diskon21 / 100))
print(f"Harga Sepatu A adalah {int(hargasepatuA)}")
print(f"Harga Sepatu B Adalah {int(hargasepatuB)}")
print(f"Sepatu A Mendapat Diskon {int(diskon13)} Sehingga Harganya Menjadi {int(diskonsepatuA13persen)}")
print(f"Sepatu B Mendapat Diskon {int(diskon21)} Sehingga Harganya Menjadi {int(diskonsepatuB21persen)}")