from manim import *
from manim_cad_drawing_utils import *
from manim.mobject.geometry.tips import *
from manim_gearbox import *
from scipy.optimize import fsolve

class Profile_shift_1(MovingCameraScene):
    def construct(self):
        vt = ValueTracker(0)
        rt = ValueTracker(0)
        m=0.75
        z=8
        P_s = 0.7
        def Gear_constructor(params):
            gear0 = Gear(z,
                         module=m,
                         h_a=1, h_f=1.2,
                         profile_shift=vt.get_value(),
                         fill_color=WHITE,
                         fill_opacity=1,
                         stroke_opacity=0,
                         gen_params=params,
                         make_smooth=False)
            gear0.rotate((1/2+rt.get_value())* gear0.pitch_angle).shift(UP*gear0.rp)
            return gear0
        gear1 = Gear_constructor({})

        gear1.add_updater(lambda mob: mob.match_points(Gear_constructor(gear1.gen_params)))
        rack1 = Rack(5,m,h_a=1.2,h_f=1,fill_color=BLUE_A,fill_opacity=1,stroke_opacity=0).rotate(PI/2)

        Circle_Rb = Circle(radius=gear1.rb,
                           arc_center=gear1.get_center(),
                           color=TEAL,
                           fill_opacity=0)

        # self.add(gear1,rack1,Circle_Rb)
        self.play(FadeIn(gear1),FadeIn(rack1))
        self.play(vt.animate.set_value(P_s),rack1.animate.shift(DOWN*P_s*m))
        self.wait()
        self.play(rt.animate.set_value(0.5), rack1.animate.shift(RIGHT * 0.5 * rack1.pitch))
        self.wait()
        self.play(vt.animate.set_value(0),rack1.animate.shift(-P_s*DOWN*m))
        self.wait()
        # self.play(rt.animate.set_value(0), rack1.animate.shift(RIGHT * (-0.5) * rack1.pitch))

        tmax_0 = gear1.gen_params['tmax_invo']

        def Invo_ref_construc(p, gear_in=None):
            Invo_curve_ref = VMobject()
            if gear_in is None:
                gear0=Gear_constructor(gear1.gen_params)
            else:
                gear0=gear_in
            Invo_curve_ref.points=involute_point_gen(np.linspace(gear0.gen_params['tmin_invo']*0,
                                                                 gear0.gen_params['tmax_invo'],
                                                                 # tmax_0,
                                                                 10),
                                                     gear0.rb)
            Invo_curve_ref.rotate(-gear0.angle_ofs-gear0.pitch_angle/4,about_point=ORIGIN)
            Invo_curve_ref.shift(gear0.get_center())

            Invo_curve_ref.set_color(ORANGE)
            Invo_curve_ref.set_stroke(opacity=0)
            if p:
                Invo_curve_ref.flip(RIGHT,about_point=gear0.get_center())
            Invo_curve_ref.rotate(gear0.get_angle(),about_point=gear0.get_center())
            return Invo_curve_ref

        def Invo_grp_contstruct_right():
            Invo_curve_ref=Invo_ref_construc(0)
            Invo_grp = VGroup()
            Line_grp = VGroup()
            Invo_collect = VDict()
            Invo_collect['invo_curves'] = Invo_grp
            Invo_collect['lines'] = Line_grp
            for k in range(z):
                Invo_grp.add(Invo_curve_ref.copy())
                Line_grp.add(Line(start=gear1.get_center(),
                                  end=Invo_curve_ref.points[0, :]).match_style(Invo_curve_ref))
                Invo_collect.rotate(gear1.pitch_angle,about_point=gear1.get_center())
                Invo_collect.set_color(PURPLE_B)
                Invo_collect.set_stroke(opacity=1,width=5)
            return Invo_collect

        def Invo_grp_contstruct_left():
            Invo_curve_ref = Invo_ref_construc(1)
            Invo_grp = VGroup()
            Line_grp = VGroup()
            Invo_collect = VDict()
            Invo_collect['invo_curves']=Invo_grp
            Invo_collect['lines'] = Line_grp
            for k in range(z):
                Invo_grp.add(Invo_curve_ref.copy())
                Line_grp.add(Line(start=gear1.get_center(),end=Invo_curve_ref.points[0,:]).match_style(Invo_curve_ref))
                Invo_collect.rotate(gear1.pitch_angle, about_point=gear1.get_center())
                Invo_collect.set_stroke(opacity=1,width=5)
            return Invo_collect

        Invo_grp_right = VDict()
        Invo_grp_left = VDict()
        Invo_grp_right.set_color(PURPLE)
        Invo_grp_left.add_updater(lambda mob: mob.become(Invo_grp_contstruct_left()))
        Invo_grp_right.add_updater(lambda mob: mob.become(Invo_grp_contstruct_right()))
        Invo_grp_left.update()
        Invo_grp_right.update()
        # self.add(Invo_curve_ref)
        self.play(Create(Circle_Rb))

        self.play(vt.animate.set_value(P_s), rack1.animate.shift(DOWN * P_s * m))
        self.wait()
        self.play(vt.animate.set_value(0), rack1.animate.shift(-P_s * DOWN * m))
        self.wait()
        Invo_grp_right_2 = Invo_grp_right.copy()
        Invo_grp_right_2.clear_updaters()

        Invo_grp_left_2 = Invo_grp_left.copy()
        Invo_grp_left_2.clear_updaters()

        loc_gear_1 = Gear(z,
                          module=m,
                          h_a=1, h_f=1.2,
                          profile_shift=P_s,
                          make_smooth=False)
        loc_gear_2 = Gear(z,
                          module=m,
                          h_a=1, h_f=1.2,
                          profile_shift=0,
                          make_smooth=False)
        diff_angle = loc_gear_2.angle_ofs-loc_gear_1.angle_ofs

        self.play(Create(Invo_grp_left), Create(Invo_grp_right))
        self.add(Invo_grp_right_2)

        self.play(vt.animate.set_value(P_s),rt.animate.set_value(0.5+diff_angle/gear1.pitch_angle),
                  rack1.animate.shift((DOWN * P_s * m)+ LEFT*(P_s * m * np.tan(gear1.alpha*DEGREES))),run_time=3)

        self.wait()
        self.play(Rotate(Invo_grp_right_2, diff_angle*2,about_point=gear1.get_center()))
        self.wait()
        self.play(Rotate(Invo_grp_right_2, -diff_angle*2, about_point=gear1.get_center()))
        self.wait()

        self.play(FadeOut(rack1),FadeOut(Circle_Rb), FadeOut(Invo_grp_right_2))

        gear2=Gear(30,
                   module=m,
                   h_a=1, h_f=1.2,
                   profile_shift=0,
                   fill_color=WHITE,
                   fill_opacity=1,
                   stroke_opacity=0,
                   make_smooth=False).shift(gear1.rp*UP)
        gear0 = Gear_constructor({})
        gear2.shift(gear2.rp*DOWN)
        gear2.mesh_to(gear0,offset=0.1)

        Invo_ref_3 = Invo_ref_construc(1,gear2)
        Invo_ref_3.set_stroke(opacity=1)
        Invo_ref_3.set_color(ORANGE).rotate(gear2.pitch_angle*8,about_point=gear2.get_center())

        Invo_grp_3 = VGroup()
        for k in range(30):
            Invo_grp_3.add(Invo_ref_3.copy())
            Invo_grp_3.rotate(gear2.pitch_angle,about_point=gear2.get_center())

        # self.camera.frame.move_to(gear2.get_center()).scale(5)

        self.play(FadeIn(gear2))
        self.play(Create(Invo_grp_3,lag_ratio=0))
        gear2_grp = VGroup(gear2,Invo_grp_3)

        self.play(rt.animate.set_value(0.5+diff_angle/gear1.pitch_angle+1),Rotate(gear2_grp,-gear2.pitch_angle,about_point=gear2.get_center()),run_time=2)
        self.wait()
        self.play(rt.animate.set_value(0.5+diff_angle/gear1.pitch_angle),Rotate(gear2_grp,gear2.pitch_angle,about_point=gear2.get_center()),run_time=2)
        self.wait()

        self.play(FadeOut(gear2_grp))
        self.play(FadeIn(rack1),
                  FadeIn(Circle_Rb))

        self.play(vt.animate.set_value(0), rt.animate.set_value(0.5 + 0 * diff_angle / gear1.pitch_angle),
                  rack1.animate.shift(-(DOWN * P_s * m) + LEFT * (-P_s * m * np.tan(gear1.alpha * DEGREES))))
        Pitch_line = DashDot_mobject(Line(start=gear1.get_center()+gear1.rp*DOWN+LEFT*10,
                                          end=gear1.get_center()+gear1.rp*DOWN+RIGHT*10),
                                     num_dashes=30,
                                     dashed_ratio=0.7,
                                     dot_scale=0.5)

        Pitch_line.set_color(RED)
        Pitch_line_shift = Pitch_line.copy().shift(DOWN*P_s*m)
        Pitch_line_shift.add_updater(lambda mob: mob.move_to(Pitch_line).shift(DOWN*vt.get_value()*m))

        Constr_triangle = VMobject()
        Constr_triangle.set_points_as_corners([gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT,
                                               gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT+DOWN*P_s*m+LEFT*P_s*m*np.tan(20*DEGREES),
                                               gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT+LEFT*P_s*m*np.tan(20*DEGREES)*2,
                                               gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT])
        Constr_triangle.set_stroke(color=RED)

        Constr_line_1 = Line(
                             start=gear1.get_center() + gear1.rp * DOWN + gear1.pitch / 4 * LEFT + DOWN * P_s * m + LEFT * P_s * m * np.tan(
                                 20 * DEGREES),
                             end=gear1.get_center() + gear1.rp * DOWN + gear1.pitch / 4 * LEFT + LEFT * P_s * m * np.tan(20 * DEGREES),
                             color=RED,
                             stroke_width=2)
        Invo_grp_right_2.suspend_updating()
        Invo_grp_right.suspend_updating()
        Invo_grp_left.suspend_updating()
        self.play(FadeIn(Pitch_line),
                  FadeIn(Pitch_line_shift),
                  FadeOut(Invo_grp_right_2),
                  FadeOut(Invo_grp_right),
                  FadeOut(Invo_grp_left))
        # self.add(Constr_triangle,Constr_line_1)

        Constr_triangle.set_stroke(width=2)

        # alpha_txt = MathTex(r'\alpha').scale(1/9)
        # alpha_txt.move_to(gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT+DOWN*(P_s*m-0.2)+LEFT*(P_s*m*np.tan(20*DEGREES)-0.04))
        # self.add(alpha_txt)

        h_dim0 = Linear_Dimension(start=Constr_line_1.start, end=Constr_line_1.end, tip_len=0.1,
                                 offset=0.3,
                                 text=MathTex(r'X', color=RED),
                                 stroke_width=2,
                                 color=RED)

        h_dim = Linear_Dimension(start=Constr_line_1.start,end=Constr_line_1.end,tip_len=0.1,
                                 offset=0.3,
                                 text=MathTex(r'xm',color=RED),
                                 stroke_width=2,
                                 color=RED)

        self.play(vt.animate.set_value(P_s), rt.animate.set_value(0.5 + diff_angle / gear1.pitch_angle),
                  rack1.animate.shift((DOWN * P_s * m) + LEFT * (P_s * m * np.tan(gear1.alpha * DEGREES))))

        self.play(Create(h_dim0))
        self.wait()

        self.camera.frame.save_state()
        self.play(self.camera.frame.animate.move_to(Constr_triangle).scale(4 * P_s * m / 9))
        self.wait()
        self.play(ReplacementTransform(h_dim0,h_dim))
        self.play(Create(Constr_triangle))

        ds_dim = Linear_Dimension(start=gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT,
                                 end=gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT+LEFT*P_s*m*np.tan(20*DEGREES)*2,
                                 tip_len=0.1,
                                 offset=-0.1,
                                 text=MathTex(r'\Delta s',color=RED),
                                 stroke_width=2,
                                 color=RED)

        alpha_text = MathTex(r'2\alpha',color=RED).move_to(ds_dim['text'])
        alpha_text.scale(ds_dim['text'].height/alpha_text.height)
        alpha_text.shift(DOWN*P_s*0.6)
        alpha_arc=ArcBetweenPoints(gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT,
                                   gear1.get_center() + gear1.rp * DOWN + gear1.pitch / 4 * LEFT + LEFT * P_s * m * np.tan(
                                       20 * DEGREES) * 2,
                                   arc_center=gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT+DOWN*P_s*m+LEFT*P_s*m*np.tan(20*DEGREES),
                                   color=RED)
        alpha_arc.scale(0.35,about_point=gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT+DOWN*P_s*m+LEFT*P_s*m*np.tan(20*DEGREES))

        self.play(Create(ds_dim),Create(alpha_text),Create(alpha_arc))

        self.wait()

        dS_eq = MathTex(r'\Delta s=2xm \tan(\alpha)',color=RED)

        dS_eq.move_to(ds_dim['text'])
        dS_eq.shift((DOWN*3+RIGHT))
        # phi_eq = MathTex(r'\Delta\phi=\frac{2xm \tan(\alpha)}{r_p}',color=RED)
        # phi_eq.move_to(dS_eq.get_critical_point(DOWN),aligned_edge=UP)
        self.play(self.camera.frame.animate.restore())
        self.play(Create(dS_eq))

        self.play(FadeOut(h_dim),
                  FadeOut(ds_dim),
                  FadeOut(alpha_text),
                  FadeOut(alpha_arc))
        self.wait()

        s_dim = Linear_Dimension(start=gear1.get_center() + gear1.rp * DOWN - gear1.pitch / 4 * LEFT,
                                  end=gear1.get_center() + gear1.rp * DOWN + gear1.pitch / 4 * LEFT + LEFT * P_s * m * np.tan(
                                      20 * DEGREES) * 2,
                                  tip_len=0.1,
                                  offset=2,
                                  text=MathTex(r's', color=RED),
                                  stroke_width=2,
                                  color=RED)
        s_line = Line(start=gear1.get_center() + gear1.rp * DOWN - gear1.pitch / 4 * LEFT,
                      end=gear1.get_center() + gear1.rp * DOWN + gear1.pitch / 4 * LEFT + LEFT * P_s * m * np.tan(
                                      20 * DEGREES) * 2,
                      color=RED)
        S_eq = MathTex(r' s=m \left( \frac{\pi}{2} + 2x\tan(\alpha)\right)', color=RED)
        S_eq.move_to(dS_eq)

        self.play(Create(s_dim),Create(s_line),Transform(dS_eq,S_eq))

        self.wait()
        self.play(FadeOut(Constr_triangle))

        s_arc = Arc(radius=gear1.rp,
                    arc_center=gear1.get_center(),
                    start_angle=-PI/2+gear1.pitch_angle/4,
                    angle=-(gear1.pitch_angle/2+P_s*m*np.tan(20*DEGREES)*2/gear1.rp),
                    color=RED)

        self.wait()
        self.play(self.camera.frame.animate.move_to(s_line).scale(0.3))
        self.play(Transform(s_line,s_arc))
        self.wait()

        # Line_angle_1=Line(start=gear1.get_center(),
        #                   end = gear1.get_center()+gear1.rp*DOWN+gear1.pitch/4*LEFT,
        #                   color=RED)
        # Line_angle_2 = Line_angle_1.copy()
        # self.play(FadeOut(dS_eq))
        # self.play(Create(VGroup(Line_angle_1, Line_angle_2)))
        # self.play(Rotate(Line_angle_2,(-P_s*m*np.tan(20*DEGREES)*2/gear1.rp),about_point=gear1.get_center()))
        # dphi = MathTex(r'\Delta\phi',color=RED).move_to(phi_eq)
        # self.play(Create(dphi))
        # self.wait()

class Profile_shift_calc(MovingCameraScene):
    def construct(self):
        eq_sin2a_1 = MathTex(r"h=r_p \sin^2(\alpha)=r_p-r_d = 1.25m-xm")
        eq_sin2a_2 = MathTex(r"\left(\frac{z}{2} m\right) \sin^2(\alpha)=1.25m-xm")
        eq_sin2a_3 = MathTex(r"x=1.25-\frac{z}{2} \sin^2(\alpha)")
        eq_sin2a_4 = MathTex(r"z_{min}=\frac{2.5}{\sin^2(\alpha)}")
        eq_sin2a_5 = MathTex(r"x=1.25 \left(1-\frac{z}{z_{min}}\right)")

        eq_grp_2 = VGroup(eq_sin2a_1, eq_sin2a_2, eq_sin2a_3,eq_sin2a_4,eq_sin2a_5)
        eq_grp_2.arrange(DOWN)
        for k in range(5):
            self.play(Create(eq_grp_2[k]))
            self.wait()

class Ucut_Pshift_compare(MovingCameraScene):
    def construct(self):
        m0 = 0.08
        teeth_range = range(6,15)
        Undercut_grp = VGroup()
        Pshift_grp = VGroup()
        all_grp = VGroup()
        for k in teeth_range:
            gear1 = Gear(k,
                         module=m0*15/k,
                         h_f=1.25,
                         stroke_opacity=0,
                         fill_opacity=1,
                         fill_color=BLUE_A)

            gear2=Gear(k,
                       module=m0 * 15 / k,
                       stroke_opacity=0,
                       profile_shift=1.25*(1-k/20.5),
                       h_f=1.25,
                       fill_opacity=1,
                       fill_color=BLUE_C)
            num1 = Text(str(k),color=BLACK).scale(0.7).move_to(gear1.get_center())
            num2 = num1.copy().move_to(gear2.get_center())
            # ngear1=VGroup(gear1,num1)
            # ngear2 = VGroup(gear2, num2)
            gear1.add(num1)
            gear2.add(num2)
            loc_grp = VGroup(gear1,gear2).arrange()
            all_grp.add(loc_grp)

        # Undercut_grp.arrange_in_grid(cols=3,rows=3)
        # Pshift_grp.arrange_in_grid(cols=3,rows=3)
        # all_grp = VGroup(Undercut_grp,Pshift_grp)
        all_grp.arrange_in_grid(cols=3,rows=3)
        animations = [FadeIn(mob,lag_ratio=0) for grp in all_grp for mob in grp]
        self.play(AnimationGroup(*animations,lag_ratio=1),run_time=9)
        self.wait()

class Calc_tolerance(MovingCameraScene):
    def construct(self):
        eq_12 = MathTex(r"h_d = 1.25m")
        eq_sin2a_12 = MathTex(r"z_{min}=\frac{2.5}{\sin^2(\alpha)} = 21.3715")
        eq_sin2a_12_2 = MathTex(r" z_{min} \approx 22")
        eq_sin2a_10 = MathTex(r"z_{min}=\frac{2}{\sin^2(\alpha)} = 17.0972")
        eq_sin2a_10_2 = MathTex(r" z_{min} \approx 17")

        eq_10 = MathTex(r"h_d = 1m")
        eq_x_12 = MathTex(r"x=1.25 (1-\frac{z}{z_{min}})")
        eq_x_12_2 = MathTex(r"x \approx 1.25\left(1-\frac{z}{22}\right)")
        eq_x_10 = MathTex(r"x=1-\frac{z}{z_{min}}")
        eq_x_10_2 = MathTex(r"x\approx 1-\frac{z}{17}")

        eq_grp_left = VGroup(Text('with clearance'),
                             eq_12,
                             eq_sin2a_12,
                             eq_sin2a_12_2,
                             eq_x_12,
                             eq_x_12_2).arrange(DOWN)
        eq_grp_right = VGroup(Text('without clearance'),
                              eq_10,
                              eq_sin2a_10,
                              eq_sin2a_10_2,
                              eq_x_10,
                              eq_x_10_2).arrange(DOWN)

        grp_all = VGroup(eq_grp_left,eq_grp_right).arrange(RIGHT,buff=2)

        self.camera.frame.scale(grp_all.width/self.camera.frame.width*1.2)

        vertline = DashedVMobject(Line(start=-10*UP,end=10*UP,color=RED))

        # self.add(grp_all)
        self.play(Create(vertline))
        self.wait()
        self.play(Create(eq_grp_left,lag_ratio=2),run_time=4)
        self.wait()
        self.play(Create(eq_grp_right,lag_ratio=2),run_time=4)
        self.wait()

        self.play(FadeOut(eq_grp_right),FadeOut(eq_grp_left))

        rack1 = Rack(2,module=1,h_a=1.25,h_f=1).rotate(PI/2)
        rack2 = Round_Corners(Rack(2,module=1,h_a=1.25,h_f=1).rotate(PI/2),0.3)

        rack1.shift(LEFT*4)
        rack2.shift(RIGHT*4)
        self.play(Create(rack1),Create(rack2))
        self.wait()
        rack_line_1 = Line(start=rack1.get_center()+3*LEFT,
                           end=rack1.get_center()+3*RIGHT,
                           color=RED)

        rack_line_2 = Line(start=rack2.get_center() + 3 * LEFT,
                           end=rack2.get_center() + 3 * RIGHT,
                           color=RED)

        aux_line_1 = Line(start=rack1.get_center() + rack1.m * UP * 1.249 + LEFT * 12,
                          end=rack1.get_center() + rack1.m * UP * 1.249 + RIGHT * 12)
        aux_line_2 = Line(start=rack1.get_center() + rack1.m * UP + LEFT * 12,
                          end=rack1.get_center() + rack1.m * UP + RIGHT * 12)
        itx_points_0 = curve_intersection(rack_line_1, rack1)
        itx_points_02 = curve_intersection(rack_line_2, rack2)
        itx_points_1 = curve_intersection(aux_line_1,rack1)
        itx_points_2 = curve_intersection(aux_line_1, rack2)
        itx_points_3 = curve_intersection(aux_line_2, rack2)

        dim1 = Linear_Dimension(start=rack_line_1.get_nth_curve_function(0)(itx_points_0[0][0]),
                                end=aux_line_1.get_nth_curve_function(0)(itx_points_1[0][0]),
                                direction=LEFT,
                                offset=0.8,
                                outside_arrow=True,
                                text='1.25 m',
                                color=RED)

        dim2 = Linear_Dimension(start=rack_line_2.get_nth_curve_function(0)(itx_points_0[0][-1]),
                                end=aux_line_2.get_nth_curve_function(0)(itx_points_3[0][-1]),
                                direction=LEFT,
                                offset=-0.8,
                                outside_arrow=True,
                                text=' 1 m ',
                                color=RED)

        self.play(Create(DashedVMobject(rack_line_1)))
        self.play(Create(DashedVMobject(rack_line_2)))
        self.play(Create(dim1))
        self.play(Create(dim2))
        self.wait()
#
# with tempconfig({"quality": "medium_quality", "disable_caching": True, "save_last_frame":True}):
#     scene = Calc_tolerance()
#     scene.render()


import cv2
import matplotlib.pyplot as plt

# resmi içe aktar
img = cv2.imread("sudoku.jpg", 0)
plt.figure(), plt.imshow(img, cmap = "gray"), plt.axis("off"), plt.title("Orijinal Img")

# x gradyan
sobelx = cv2.Sobel(img, ddepth = cv2.CV_16S, dx = 1, dy = 0, ksize = 5)
plt.figure(), plt.imshow(sobelx, cmap = "gray"), plt.axis("off"), plt.title("Sobel X")

# y gradyan
sobely = cv2.Sobel(img, ddepth = cv2.CV_16S, dx = 0, dy =1, ksize = 5)
plt.figure(), plt.imshow(sobely, cmap = "gray"), plt.axis("off"), plt.title("Sobel Y")

# laplacian gradyan
laplacian = cv2.Laplacian(img, ddepth = cv2.CV_16S)
plt.figure(), plt.imshow(laplacian, cmap = "gray" ),plt.axis("off"), plt.title("Laplacian")


# Author: Mitchell Fehr
# Date: 10/5/2016
#
# "Non-Divisible Subset" Python 3 Solution

import sys
n, k = map(int,input().strip().split(" "))
s = map(int,input().strip().split(" "))

def sub(n,k,s):
    d = [0]*k
    for num in s:
        d[num % k] +=1
    tot = min(d[0],1)
    for i in range(1,(k//2)+1):
        if i != (k - i):
            tot += max(d[i],d[k-i])
    if k % 2 == 0:
        tot +=1
    print(tot)

sub(n,k,s)


import module.config.server as server_
from module.base.button import Button, ButtonWrapper, ClickButton, match_template
from module.base.timer import Timer
from module.base.utils import *
from module.config.config import AzurLaneConfig
from module.device.device import Device
from module.logger import logger

class ModuleBase:
    config: AzurLaneConfig
    device: Device

    def __init__(self, config, device=None, task=None):
        """
        Args:
            config (AzurLaneConfig, str):
                Name of the user config under ./config
            device (Device, str):
                To reuse a device.
                If None, create a new Device object.
                If str, create a new Device object and use the given device as serial.
            task (str):
                Bind a task only for dev purpose. Usually to be None for auto task scheduling.
                If None, use default configs.
        """
        if isinstance(config, AzurLaneConfig):
            self.config = config
        elif isinstance(config, str):
            self.config = AzurLaneConfig(config, task=task)
        else:
            logger.warning('Alas ModuleBase received an unknown config, assume it is AzurLaneConfig')
            self.config = config

        if isinstance(device, Device):
            self.device = device
        elif device is None:
            self.device = Device(config=self.config)
        elif isinstance(device, str):
            self.config.override(Emulator_Serial=device)
            self.device = Device(config=self.config)
        else:
            logger.warning('Alas ModuleBase received an unknown device, assume it is Device')
            self.device = device

        self.interval_timer = {}

    def match_template(self, button, interval=0, similarity=0.85):
        """
        Args:
            button (ButtonWrapper):
            interval (int, float): interval between two active events.
            similarity (int, float): 0 to 1.

        Returns:
            bool:

        Examples:
            Image detection:
            ```
            self.device.screenshot()
            self.appear(Button(area=(...), color=(...), button=(...))
            self.appear(Template(file='...')
            ```
        """
        self.device.stuck_record_add(button)

        if interval and not self.interval_is_reached(button, interval=interval):
            return False

        appear = button.match_template(self.device.image, similarity=similarity)

        if appear and interval:
            self.interval_reset(button, interval=interval)

        return appear

    def match_color(self, button, interval=0, threshold=10):
        """
        Args:
            button (ButtonWrapper):
            interval (int, float): interval between two active events.
            threshold (int): 0 to 255, smaller means more similar

        Returns:
            bool:
        """
        self.device.stuck_record_add(button)

        if interval and not self.interval_is_reached(button, interval=interval):
            return False

        appear = button.match_color(self.device.image, threshold=threshold)

        if appear and interval:
            self.interval_reset(button, interval=interval)

        return appear

    def match_template_color(self, button, interval=0, similarity=0.85, threshold=30):
        """
        Args:
            button (ButtonWrapper):
            interval (int, float): interval between two active events.
            similarity (int, float): 0 to 1.
            threshold (int): 0 to 255, smaller means more similar

        Returns:
            bool:
        """
        self.device.stuck_record_add(button)

        if interval and not self.interval_is_reached(button, interval=interval):
            return False

        appear = button.match_template_color(self.device.image, similarity=similarity, threshold=threshold)

        if appear and interval:
            self.interval_reset(button, interval=interval)

        return appear

    appear = match_template

    def appear_then_click(self, button, interval=5, similarity=0.85):
        appear = self.appear(button, interval=interval, similarity=similarity)
        if appear:
            self.device.click(button)
        return appear

    def wait_until_stable(self, button, timer=Timer(0.3, count=1), timeout=Timer(5, count=10)):
        """
        A terrible method, don't rely too much on it.
        """
        logger.info(f'Wait until stable: {button}')
        prev_image = self.image_crop(button)
        timer.reset()
        timeout.reset()
        while 1:
            self.device.screenshot()

            if timeout.reached():
                logger.warning(f'wait_until_stable({button}) timeout')
                break

            image = self.image_crop(button)
            if match_template(image, prev_image):
                if timer.reached():
                    logger.info(f'{button} stabled')
                    break
            else:
                prev_image = image
                timer.reset()

    def image_crop(self, button, copy=True):
        """Extract the area from image.

        Args:
            button(Button, tuple): Button instance or area tuple.
            copy:
        """
        if isinstance(button, Button):
            return crop(self.device.image, button.area, copy=copy)
        elif isinstance(button, ButtonWrapper):
            return crop(self.device.image, button.area, copy=copy)
        elif hasattr(button, 'area'):
            return crop(self.device.image, button.area, copy=copy)
        else:
            return crop(self.device.image, button, copy=copy)

    def image_color_count(self, button, color, threshold=221, count=50):
        """
        Args:
            button (Button, tuple): Button instance or area.
            color (tuple): RGB.
            threshold: 255 means colors are the same, the lower the worse.
            count (int): Pixels count.

        Returns:
            bool:
        """
        if isinstance(button, np.ndarray):
            image = button
        else:
            image = self.image_crop(button, copy=False)
        mask = color_similarity_2d(image, color=color)
        cv2.inRange(mask, threshold, 255, dst=mask)
        sum_ = cv2.countNonZero(mask)
        return sum_ > count

    def image_color_button(self, area, color, color_threshold=250, encourage=5, name='COLOR_BUTTON'):
        """
        Find an area with pure color on image, convert into a Button.

        Args:
            area (tuple[int]): Area to search from
            color (tuple[int]): Target color
            color_threshold (int): 0-255, 255 means exact match
            encourage (int): Radius of button
            name (str): Name of the button

        Returns:
            Button: Or None if nothing matched.
        """
        image = color_similarity_2d(self.image_crop(area), color=color)
        points = np.array(np.where(image > color_threshold)).T[:, ::-1]
        if points.shape[0] < encourage ** 2:
            # Not having enough pixels to match
            return None

        point = fit_points(points, mod=image_size(image), encourage=encourage)
        point = ensure_int(point + area[:2])
        button_area = area_offset((-encourage, -encourage, encourage, encourage), offset=point)
        return ClickButton(button=button_area, name=name)

    def interval_reset(self, button, interval=5):
        if isinstance(button, (list, tuple)):
            for b in button:
                self.interval_reset(b, interval)
            return

        if button is not None:
            if button.name in self.interval_timer:
                self.interval_timer[button.name].reset()
            else:
                self.interval_timer[button.name] = Timer(interval).reset()

    def interval_clear(self, button, interval=5):
        if isinstance(button, (list, tuple)):
            for b in button:
                self.interval_clear(b, interval)
            return

        if button is not None:
            if button.name in self.interval_timer:
                self.interval_timer[button.name].clear()
            else:
                self.interval_timer[button.name] = Timer(interval).clear()

    def interval_is_reached(self, button, interval=5):
        if button.name in self.interval_timer:
            if self.interval_timer[button.name].limit != interval:
                self.interval_timer[button.name] = Timer(interval)
        else:
            self.interval_timer[button.name] = Timer(interval)

        return self.interval_timer[button.name].reached()

    _image_file = ''

    @property
    def image_file(self):
        return self._image_file

    @image_file.setter
    def image_file(self, value):
        """
        For development.
        Load image from local file system and set it to self.device.image
        Test an image without taking a screenshot from emulator.
        """
        if isinstance(value, Image.Image):
            value = np.array(value)
        elif isinstance(value, str):
            value = load_image(value)

        self.device.image = value

    def set_lang(self, lang):
        """
        For development.
        Change lang and affect globally,
        including assets and server specific methods.
        """
        server_.set_lang(lang)
        logger.attr('Lang', self.config.LANG)


from flask import Flask
from flask_mysqldb import MySQL
from flask import jsonify

back = Flask(__name__)

# Configuration of db
back.config["MYSQL_HOST"] = "localhost"
back.config["MYSQL_USER"] = "mdso"
back.config["MYSQL_PASSWORD"] = "mdso1234"
back.config["MYSQL_DB"] = "mdso"

# Extra configs, optional:
back.config["MYSQL_CURSORCLASS"] = "DictCursor"
back.config["MYSQL_CUSTOM_OPTIONS"] = {"ssl": {"ca": "/path/to/ca-file"}}  # https://mysqlclient.readthedocs.io/user_guide.html#functions-and-attributes

mysql = MySQL(back)

@back.route("/")
def home():
    return "<h1 style='text-align: center;'>Welcome to your back app </h1>"

@back.route("/db/")
def db():
    cur = mysql.connection.cursor()
    cur.execute(""" SELECT * FROM mdsoMember""")
    data = cur.fetchall()
    cur.close()
    return jsonify(data)

@back.route('/identify/<name>/<mail>/')
def identify(name, mail):
    cur = mysql.connection.cursor()
    cur.execute(""" SELECT * FROM mdsoMember WHERE name=%s AND mail=%s """,(name, mail))
    data = cur.fetchall()
    cur.close()
    if( data == [ ] ):
        return jsonify("[{status: False}]")
    else:
        return jsonify(data)

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


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 14:25:02 2021

@author: miyawaki
"""
#%%
import h5py
from box import Box
import os
import numpy
#%%
class matHandler:
    __filePath=''
    name=Box({})
    def __init__(self,filePath):
        self.__filePath=os.path.expanduser(filePath)
        with h5py.File(self.__filePath,'r') as f:
            self.name=self.__getName(f,'','');

    def getNum(self,path):
        with h5py.File(self.__filePath,'r') as f:
            res=f[path][()]
            if len(res)==1:
                res=res[0]
            if len(res.T)==1:
                res=res.T[0]
        return res

    def getStr(self,path):
        res=[]
        with h5py.File(self.__filePath,'r') as f:
            if f[path][()].dtype=='u2':
                row=(''.join(map(chr, f[path])))
                res.append(row)
            else:
                for col in f[path][()]:
                    row=[]
                    for rIdx in range(len(col)):
                        row.append(''.join(map(chr, map(int,f[col[rIdx]][:]))))
                    res.append(row)
            res=numpy.array(res)
            if len(res)==1:
                res=res[0]
            if len(res.T)==1:
                res=res.T[0]
        return res

    def __getName(self,h5f,keys,path):
        if keys=='':
            # print('key is empty')
            res=self.__getName(h5f,h5f.keys(),'')
            return Box(res)

        res={}
        for k in keys:
            # print('process ' + k)
            if k[0]=='#':
                # print('  key start with #')
                continue

            if isinstance(h5f[k],h5py.Dataset):
                # print('  ' + k + ' is dataset')
                res[k]=path+'/'+k
                # print(k)

            elif isinstance(h5f[k],h5py.Group):
                # print('  ' + k + ' is group')
                res[k]=self.__getName(h5f[k],h5f[k].keys(),path+'/'+k)
            # else:
                # print('  ' + k + ' is something else')

        return Box(res)


#!/usr/bin/python3
"""
A node that bridges ROS topics to a physical CANbus interface through the socketcan interface.

Ported to Python from the ros2can_bridge package by philippwuestenberg.
https://github.com/ROS4SPACE/ros2can_bridge

Date created: 05/01/2023
Date modified: 05/05/2023

CHANGELOG:
v1.0.0 - Initial Release
v1.0.1 - Changed some of the parameter calls and variable names
v1.0.2 - Updated docs

TODO:
- Add exception handling for KeyboardInterrupt (close CAN bus)
- Add exception handling for can.exceptions.CanOperationError: Failed to transmit: No buffer space available (stop transmitting until bus opens up)
"""

import can
import rclpy
from rclpy.node import Node
from seacat_msg.msg import CANFrame

__author__ = "Braidan Duffy"
__copyright__ = "Copyright 2023, PANTHER Boat Team"
__credits__ = ["Braidan Duffy"]
__license__ = "MIT"
__version__ = "1.0.2"
__maintainer__ = "Braidan Duffy"
__email__ = "bduffy2018@my.fit.edu"
__status__ = "Production"

class ROS2CANNode(Node):
    """
    Node that bridges software ROS topics to the physical world via a physical CAN bus and the socketcan interface

    Parameters:
        bus_name (str): the CAN bus interface the VESC is connected. Default: 'can0'
    """
    BUS_NAME: str
    bus: can.interface.Bus

    def __init__(self):
        super().__init__('ROS2CANNode')

        self.declare_parameter('bus_name', 'can0')

        # Set up the CAN Interface
        self.BUS_NAME = self.get_parameter('bus_name').get_parameter_value().string_value
        self.bus = can.interface.Bus(channel=self.BUS_NAME, bustype='socketcan')
        self.get_logger().info(f"Using bus: {self.BUS_NAME}")

        if not self.bus: # Check if bus successfully created
            self.get_logger().fatal("Bus already open!")
            raise RuntimeError(f"CAN Bus '{self.BUS_NAME}' is already in use!")

        # Set up topic names
        self.topicname_receive = f"CAN/{self.BUS_NAME}/receive"
        self.topicname_transmit = f"CAN/{self.BUS_NAME}/transmit"

        # Set up the ROS2 publisher/subscribers
        self.publisher_ = self.create_publisher(CANFrame,
                                                self.topicname_receive,
                                                10)
        self.get_logger().info(f"Publishing received CAN frames to: {self.topicname_transmit}")

        self.subscription_ = self.create_subscription(CANFrame,
                                                      self.topicname_transmit,
                                                      self.CAN_send,
                                                      10)
        self.get_logger().info(f"Listening for CAN frames at: {self.topicname_receive}")

        # Create a timer to call the listener function at 10 Hz
        self.timer_listener = self.create_timer(0.1, self.CAN_listener)
        self.get_logger().info("Created a timer to check for new CAN bus messages at 10 Hz")

    # =============================
    # === SUBSCRIPTION HANDLERS ===
    # =============================

    def CAN_send(self, msg: CANFrame):
        """
        Formats a CAN bus message from a ROS CAN frame and sends it to the bus through the socketcan interface

        Args:
            msg (CANFrame): A CAN frame sent from within the ROS network
        """
        self.bus.send(can.Message(arbitration_id=msg.id,
                                  is_extended_id=msg.eff,
                                  is_remote_frame=msg.rtr,
                                  is_error_frame=msg.err,
                                  dlc=msg.dlc,
                                  data=msg.data))

        self.get_logger().info(f"Sent CAN message with ID: {msg.id} and Data: {msg.data}")

    def CAN_listener(self):
        """
        Listens for a message from the CAN bus and then publishes it to a ROS topic
        """
        can_msg = self.bus.recv()	                            # Receive a CAN message
        message = CANFrame(id=can_msg.arbitration_id,	        # Extract the CAN ID from the receieved message
                           dlc=can_msg.dlc,                     # Extract the data length
                           data=can_msg.data,		            # Extract the data from the received message
                           err=can_msg.error_state_indicator,   # Extract if the frame is an ERROR f
                           rtr=can_msg.is_remote_frame,         # Extract if the frame is a REQUEST frame
                           eff=can_msg.is_extended_id)          # Extract if the frame uses an extended id
        self.get_logger().info(f'Received CAN message: ID={message.id}, Data={message.data}')

        self.publisher_.publish(message)                        # Publish the ROS2 message to the "can_data" topic

def main(args=None):
    rclpy.init(args=args)
    node = ROS2CANNode()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
	main()


import pytest

from modules.rabbit import setup_rabbit
from pages.bulk_page import BulkPage
from pages.login_page import LoginPage
from pages.main_page import MainPage
from tests.base import run_sql
from modules.selenium_tools import click
from tests.s3_support import S3Interface

@pytest.fixture()
def login(request):
    self = request.node.parent.obj
    lpg = LoginPage(self.driver)
    lpg.login(page=self.login_url_http)

@pytest.fixture()
def test_id(request):
    """
    set self.test_id
    """
    self = request.node.parent.obj
    self.test_id = request.node.name

@pytest.fixture()
def reload(request):
    """
    stop servers, init etsy emulator, load `self.sql_file` to the db, start servers
    """
    self = request.node.parent.obj
    self.stop_all()
    try:
        etsy_testcase = self.etsy_testcase
    except AttributeError:
        etsy_testcase = 'tc1'
    self.set_etsy_testcase(etsy_testcase)
    run_sql('HIVE', self.sql_file, retry=2)
    run_sql('HIVE', 'update_shops_timestamp', retry=2)
    self.restart_all()
    self.driver.get(self.base_url)

@pytest.fixture()
def s3cleanup(request):
    """ Cleanup s3 for a test
    """
    s3interface = S3Interface()

    deleted = s3interface.delete_all_images()
    print('Deleted %d object(s) from S3 bucket "%s" using prefix "%s"' % (
        len(deleted), s3interface.bucket_name, s3interface.prefix))

@pytest.fixture()
def rabbit_init(request):
    """ Setup rabbit queues for a test - in some cases it is necessary to prepare the rabbit setup from scratch
        We should ideally do it for each test to start from a clean slate.
    """
    setup_rabbit()

@pytest.fixture()
def select_listings_to_edit(request):
    """
    select listings for bulk,
      - self.listings_to_select is on of:
            None -> use default
            ["listing1", "listin2"...] -> use this
            "ALL" -> select all
      - self.listing_status  -> e.g. 'Draft'
      - choose `self.bulk_tab`

    """
    self = request.node.parent.obj

    mp = MainPage(self.driver)
    bp = BulkPage(self.driver)

    try:
        listing_status = self.listing_status
    except AttributeError:
        listing_status = None

    try:
        listings_to_select = self.listings_to_select
    except AttributeError:
        listings_to_select = None

    try:
        bulk_tab = self.bulk_tab
    except AttributeError:
        bulk_tab = None

    mp.select_listings_to_edit(listings_to_select, status=listing_status)
    if bulk_tab:
        click(bp.edit_part(bulk_tab))


#!/usr/bin/env python
import os,shutil
from optparse import OptionParser
from pylab import *
from analyse_patchdock_score import *
from plot_data import *

"""

"""

def main():
    parser = OptionParser()

    parser.add_option('-f',dest='pdbfile',
                      help='Protein file')
    parser.add_option('-l',dest='file_pdbfile',
                      help='File with pdbs')

    (options,args) = parser.parse_args()

    # String of atom names from the ligand to be aligned with
    # Set the path to the pdb file
    pdbfile = options.pdbfile

    file_pdbs = options.file_pdbfile

    # Initialize class
    ap = analyse_patchdock()

    if(pdbfile != None):

        pdbname = pdbfile.split('_')[2]

        datafile = ap.get_file(pdbfile)

        ap.get_scores(datafile,pdbname)

    elif(file_pdbs != None):

        fl_list = open(file_pdbs,'r')

        f = [f.strip('\n') for f in fl_list.readlines() ]

        fl_list.close()

        for ln in f:

            pdbname =  ln.split('_')[2]

            pdbfile = ap.get_file(ln)

            ap.get_scores(pdbfile,pdbname)
            ap.print_number_scores()

    test = ap.get_sorted_results()

    plt = plot_data()
    values = plt.get_values(test)
    plt.write_data_to_file(values)

    cutoff_value =  plt.get_cutoff_value(values)
    plt.write_values_above_cutoff(test,cutoff_value)

    plt.plot_histogram(values)

if __name__ == "__main__":
    main()


def part1():
    cnt = 0
    for line in open("inputs/day02.txt", "r").read().splitlines():
        line = line.replace("\n", "")
        [desc, pw] = line.split(": ")
        [amount, char] = desc.split(" ")
        [minv, maxv] = amount.split("-")

        if int(maxv) >= pw.count(char) >= int(minv):
            cnt += 1
    return cnt

def part2():
    cnt = 0
    for line in open("inputs/day02.txt", "r").read().splitlines():
        line = line.replace("\n", "")
        [desc, pw] = line.split(": ")
        [amount, char] = desc.split(" ")
        [pos1, pos2] = amount.split("-")
        if (pw[int(pos1) - 1] == char) != (pw[int(pos2) - 1] == char):
            cnt += 1
    return cnt

# 582
print(part1())
# 729
print(part2())


#!/usr/bin/env python3
import click
import click_log

# Set up logging:
from .. import get_logger

logger = get_logger(__name__)

from . import table

from ...lib import utils

# Parse the expressions:
import ast
import builtins

# Loading the data:
import pyarrow as pa
import pyarrow.parquet as pq
import h5py
import pandas as pd

# Read the arguments:
@table.command()
@click.argument("column_schema", type=click.Path(exists=True))
@click.argument("output_file", type=click.Path(exists=False))
@click.argument("in_paths", nargs=-1, type=click.Path(exists=True))
@click.option(
    "-i",
    "--in-format",
    help="Type of input.",
    type=click.Choice(["TSV", "CSV", "PARQUET", "HDF5", "AUTO"], case_sensitive=False),
    required=False,
    default="auto",
)
@click.option(
    "-o",
    "--out-format",
    help="Type of output_file. Same as input for 'auto'",
    type=click.Choice(["TSV", "CSV", "PARQUET", "HDF5", "AUTO"], case_sensitive=False),
    required=False,
    default="auto",
)
def evaluate(column_schema, output_file, in_paths, in_format, out_format):
    """Create new columns according to the input expression.
    The result of evaluation will be a vector of type column_format with the number of
    entries equal to the input size of array columns.

    Column schema should be tab-separated and contain three columns:
    column_name, column_format and column_expression.

    **Column_name** is the name of the output column with evaluation result.
    **Column expression** is one-liner that does not contain lambda expressions,
    list comprehensions, and can use only column names from input parquets as variables,
    built-in functions and numpy for their evaluation.
    **Column format** is one of the following: str, int, int8, int16, int32, bool.
    """

    import numpy as np  # Import is within the function to guarantee the visibility in vars()

    prohibited_symbols = [":", ".", "-", "/", "!", "?", "&", "|", "'", "%", "@"]
    match = utils.match # define matcher; this now can be used as "match(col, expr)" in the evaluation scheme
    pick_positions = utils.pick_positions
    pick_smallest = utils.pick_smallest
    pick_largest = utils.pick_largest

    # Guess format if not specified:
    if in_format.upper() == "AUTO":
        in_format = utils.guess_format(in_paths[0])
    if out_format.upper() == "AUTO":
        out_format = in_format

    input_tables = utils.load_tables(in_paths, in_format)

    if out_format.upper() == "HDF5":
        h = h5py.File(output_file, "w")

    loaded_arrays = {}
    n_evaluated = 0
    with open(column_schema, "r") as input_file:
        # Iterate over each expression:
        for line in input_file.readlines():
            column_name, column_format, column_expression = line.strip().split("\t")

            assert np.all(
                [x not in column_name for x in prohibited_symbols]
            ), "Check the column name. It cannot contain " + ",".join(
                prohibited_symbols
            )

            # Load dataset keys as variables:
            loaded_ids = []
            syntax_tree = ast.parse(column_expression)
            for node in ast.walk(syntax_tree):
                if type(node) is ast.Name:
                    # The element is not loaded yet and is not a builtin name:
                    if not (
                        (node.id in list(vars().keys())) or (node.id in dir(builtins))
                    ):
                        # Element is already loaded:
                        if node.id in loaded_arrays.keys():
                            if in_format.upper() == "PARQUET":
                                if loaded_arrays[node.id].type == pa.bool_():
                                    vars()[node.id] = loaded_arrays[node.id].to_numpy(
                                        zero_copy_only=False
                                    )
                                else:
                                    vars()[node.id] = loaded_arrays[node.id].to_numpy()
                            elif in_format.upper() == "HDF5":
                                vars()[node.id] = loaded_arrays[node.id][()]
                            else:
                                vars()[node.id] = loaded_arrays[node.id]

                            loaded_ids.append(str(node.id))

                        # Element is not loaded, check the input tables:
                        else:
                            is_found = False
                            for table in input_tables:
                                if in_format.upper() == "PARQUET":
                                    if node.id in table.column_names:
                                        vars()[node.id] = table[node.id].to_numpy()
                                        is_found = True
                                elif in_format.upper() == "HDF5":
                                    if node.id in table.keys():
                                        vars()[node.id] = table[node.id][()]
                                        is_found = True
                                else:
                                    if node.id in table.columns:
                                        vars()[node.id] = table.loc[:, node.id]
                                        is_found = True
                                if is_found:
                                    loaded_ids.append(str(node.id))
                                    break

                            if not is_found:
                                if in_format.upper() == "PARQUET":
                                    avail_colnames = [
                                        list(table.column_names)
                                        for table in input_tables
                                    ] + [list(loaded_arrays.keys())]
                                elif in_format.upper() == "HDF5":
                                    avail_colnames = [
                                        list(table.keys()) for table in input_tables
                                    ] + [list(loaded_arrays.keys())]
                                else:
                                    avail_colnames = [
                                        list(table.columns) for table in input_tables
                                    ] + [list(loaded_arrays.keys())]
                                raise ValueError(
                                    f"Variable {node.id} is not available from input/created pyarrow file. "
                                    f"List of variables that can be loaded:\n{ str( avail_colnames ) }"
                                )

            # Evaluate expression:
            logger.debug(
                f"Evaluating column: {column_name}, expression: {column_expression} "
            )
            result = eval(column_expression)

            # Remove unused variables:
            for v in loaded_ids:
                del vars()[v]

            loaded_arrays.update(
                utils.dump_columns(result, in_format, column_format, column_name)
            )
            n_evaluated += 1

    if n_evaluated > 0:
        logger.info(
            f"Evaluated {n_evaluated} expressions, including columns: {', '.join(loaded_arrays.keys())}"
        )

        utils.dump_arrays(
            loaded_arrays, out_format, h if in_format.upper() == "HDF5" else output_file
        )

    else:
        logger.info(
            "No evaluated expression. Is the input table with expressions empty?"
        )

    return 0


'''
KNN
'''

import numpy as np
import pandas as pd
from sqlalchemy import create_engine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier

def knn(data):
    '''
    K-Nearest Neighbors
    '''
    sql_engine = create_engine('mysql+pymysql://root:root@localhost/heart')

    db_connection = sql_engine.connect()

    # dataset = pd.read_sql("select * from datasets", db_connection)
    dataset = pd.read_sql("select * from heart.datasets", db_connection)

    pd.set_option('display.expand_frame_repr', False)

    # Lori: 1:-1 remove id from db and jump to age and next
    train_feature = dataset.iloc[:, 1:-1].values
    target = dataset.iloc[:, 14].values

    # Scaling and it uses Z-Score
    scaler = StandardScaler()
    scaler.fit(train_feature)
    # Scaling the dataset feature
    train_scaled = scaler.transform(train_feature)
    # user input
    test_input = np.array(data).reshape(1, -1)
    # Scaling the dataset feature
    test_input_scaled = scaler.transform(test_input)

    # PCA WORKS
    # Make an instance of the Model
    pca = PCA(2)
    # FIT the train set only
    pca.fit(train_scaled)
    # Transform pca to train and test
    train_pca = pca.transform(train_scaled)
    test_input_pca = pca.transform(test_input_scaled)

    # Set the KNN and the K with PCA
    classifier = KNeighborsClassifier(n_neighbors=7)
    classifier.fit(train_pca, target)
    # Scoring
    # result=classifier.score(train_pca, target)
    # Prediction
    result = classifier.predict(test_input_pca)

    # # Show result

    return result[0]


def add_review_comment(self, doc, comment):
        """Sets the review comment. Raises CardinalityError if
        already set. OrderError if no reviewer defined before.
        """
        if len(doc.reviews) != 0:
            if not self.review_comment_set:
                self.review_comment_set = True
                doc.reviews[-1].comment = comment
                return True
            else:
                raise CardinalityError('ReviewComment')
        else:
            raise OrderError('ReviewComment')


t = int(input())
res = []
for i in range(t):
    n = int(input())
    a = [int (x) for x in input().split()]

    a.sort()
    min1, min2 = a[:2]
    max1, max2 = a[-2:]

    res.append(max1+max2-min1-min2)

for j in res:
    print(j)


from bs4 import BeautifulSoup
import requests
import urllib.request
import time

'''
被远程主机强制关闭了
'''

pic_link = []
header = {
    'Cookie':'vglnk.Agent.p=b83680e409308d1c7eb0504459135028',
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36'}
def get_one_page(url):
    time.sleep(4)
    web_data = requests.get(url, params= header)
    soup = BeautifulSoup(web_data.content, 'html5lib')
    pic_hrefs = soup.select('img.entry-thumbnail')

    for pic_href in pic_hrefs:
        pics = pic_href.get('src')
        pic_link.append(pics)
    print(pic_link)
    i = 1
    for pic in pic_link:
        urllib.request.urlretrieve(pic,'C:\\Users\\ZhangLi\\Desktop\\123\\1.jpg')
        i+=1
        print(i)

def get_all_pic(start, end):
    urls = ['http://weheartit.com/inspirations/taylorswift?scrolling=true&page={}&b'.format(str(i) for i in range(start,end))]
    for url in urls:
        get_one_page(url)

get_all_pic(1,2)

获取异步加载网页数据_python_spider/异步加载数据网页爬取.py

异步加载数据网页爬取.py


from selenium import webdriver
from selenium.webdriver.common.keys import Keys # 엔터키 치기 위한 라이브러리
import time
import csv

f = open(r"C:\Users\82107\Desktop\data.csv", 'w', encoding='cp949', newline='')
# 경로, 쓰기모드, 인코딩(한글 깨짐 방지), 자동 줄바꿈 없음
csvwriter = csv.writer(f)

browser = webdriver.Chrome('C:/chromedriver.exe') # 브라우져 생성
browser.get('https://www.naver.com') # 웹 사이트 열기
browser.implicitly_wait(10) # 브라우져를 여는데 시간이 많이 걸리면 이어지는 명령어 수행이 불가하므로 시간 초 여유를 준다.

browser.find_element_by_css_selector('a.nav.shop').click() # 네이버 메인에서 쇼핑 클릭
time.sleep(2) # 2초간의 시간 여유를 준다.

search = browser.find_element_by_css_selector('input._searchInput_search_input_QXUFf') # 검색창
search.click()

search.send_keys('아이폰 13')
search.send_keys(Keys.ENTER)

# 스크롤 전 높이(자바스크립트 명령어를 사용할 수 있게 도와줌 execute_script)
before_h = browser.execute_script("return window.scrollY")
# 자바 스크립트로 return window.scrollY를 해준다는 말이다.

# 무한(반복문) 스크롤
while True:
    # 맨 아래로 스크롤을 내린다.
    browser.find_element_by_css_selector("body").send_keys(Keys.END) # END 키를 눌러주기
    time.sleep(2) # 스크롤 사이 페이지 로딩 시간
    after_h = browser.execute_script("return window.scrollY")

    if after_h == before_h:
        break # 더 이상 내릴 수 없을 때까지 내린다는 의미
    before_h = after_h

# 상품 정보 div
items = browser.find_elements_by_css_selector(".basicList_info_area__17Xyo")
for item in items:
    name = item.find_element_by_css_selector(".basicList_title__3P9Q7").text # 검색했을 때 나오는 개수가 같아야 한다.
    try:
        price = item.find_element_by_css_selector("span.price_num__2WUXn").text
    except:
        price = "판매중단" # 가격 정보가 없으면 판매중단 이라고 처리해준다.
    link = item.find_element_by_css_selector(".basicList_title__3P9Q7 > a").get_attribute('href')
    # 자식클래스 선택 basicList_title__3P9Q7 아래 a태그
    # print(name, price, link)
    csvwriter.writerow([name, price, link])

# 파일 닫기
f.close()

f = open(r"C:\Users\82107\Desktop\data.csv", 'r')


#!/usr/bin/env python

"""
This tool creates dummy standard costs and associated SEND model need_setting_costs.csv input file for each state
observed in the input transitions.csv file.

This script can be run from the command line with two arguments. The first is the path to the transitions
history input file, and the second is the path where the output costs file should be written.
e.g:
    ./generate_dummy_costs.py path/to/transitions.csv path/to/dummy_costs.csv

"""

import sys
import pandas as pd
from generate_valid_states import validate_input

if sys.version_info[0] < 3:
    raise Exception("Python 3 is required.")

TRANSITIONS_PATH = sys.argv[1]
DUMMY_COSTS_PATH = sys.argv[2]
FIXED_COST = 1000

def generate_dummy_costs(transitions):
    states = set()
    for row in transitions.iterrows():
        setting_1 = row[1][1]
        need_1 = row[1][2]
        setting_2 = row[1][4]
        need_2 = row[1][5]

        states.add((setting_1, need_1))
        states.add((setting_2, need_2))

    states.discard(('NONSEND', 'NONSEND'))
    costs = pd.DataFrame()

    for state in states:
        setting, need = state
        costs = costs.append({'need': need, 'setting': setting, 'cost': FIXED_COST}, ignore_index=True)

    return costs

if __name__ == '__main__':
    print("reading", TRANSITIONS_PATH)
    in_df = pd.read_csv(TRANSITIONS_PATH)
    validate_input(in_df)
    out_df = generate_dummy_costs(in_df)
    print("writing", DUMMY_COSTS_PATH)
    out_df.to_csv(DUMMY_COSTS_PATH, index=False, columns=['need', 'setting', 'cost'])


# dp + ν¬ν¬μΈν°

def solution(p,a,l):
    p,a = convert(p),convert(a)
    v = [0]*(p+1)

    for i in l:
        v[convert(i.split("-")[0])] += 1
        v[convert(i.split("-")[1])] -= 1
    for i in range(1,len(v)):
        v[i] += v[i-1]
    for i in range(1,len(v)):
        v[i] += v[i-1]

    ans,answer = v[a],0
    for i in range(1,p-a):
        if v[i+a]-v[i] > ans:
            ans = v[i+a] - v[i]
            answer = i+1
    return div(answer)

def convert(t):
    return int(t[0:2])*3600 + int(t[3:5])*60 + int(t[6:])

def div(t):
    time = ""
    time += str(divmod(t,3600)[0]).rjust(2,"0")
    t = divmod(t,3600)[1]
    time += ":"+str(divmod(t,60)[0]).rjust(2,"0") + ":" + str(divmod(t,60)[1]).rjust(2,"0")
    return time

프로그래머스/lv3/광고 삽입.py


from kivy.app import App
from kivy.uix.image import Image, AsyncImage

class MainApp(App):
    def build(self):
        img = AsyncImage(source = 'jeff.png',
                        size_hint = (1, .5),
                        pos_hint = { 'center_x': .5, 'center_y': .5 })
        return img

if __name__ == '__main__':
    app = MainApp()
    app.run()

# from kivy.uix.image import AsyncImage
# class MainApp(App):
#     def build(self):
#         label = Label(text = 'Leonardo Oliveira Santos',
#                       size_hint = (5, .5),
#                       pos_hint = { 'center_x': .5, 'center_y': .5 })
#         return label


'''
This file is using to handle all training data,following the online data structure
'''

import pandas as pd
import numpy as np
from collections import Counter
path = "/Users/songxinyi/Desktop/21chengdu80/Online_Data/trainning_data/corporate_attributes"

def handle_company_base_info(filename):
    data = pd.read_csv(filename,index_col=0)
    data['honor_num'] = data['honor_num'].fillna(data['honor_num'].median())
    data['illegad_num'] = data['illegad_num'].fillna(data['illegad_num'].median())
    data['yea_sub'] = data['yea_sub'].fillna(data['yea_sub'].median())
    data['web_dum'] = data['web_dum'].fillna(data['web_dum'].median())
    data.drop('REGCAP',axis=1, inplace=True)
    data['REGCAPCUR'] = data['REGCAPCUR'].apply(lambda x:1 if x==156 else 0)
    data['RECCAP'] = data['RECCAP'].fillna(data['RECCAP'].median())
    data['PARNUM'] = data['PARNUM'].fillna(data['PARNUM'].median())
    data['LIMPARNUM'] = data['LIMPARNUM'].fillna(data['LIMPARNUM'].median())
    data['PARFORM'] = data['PARFORM'].fillna(data['PARFORM'].median())
    data['EXENUM'] = data['EXENUM'].fillna(data['EXENUM'].median())
    data['brand_num'] = data['brand_num'].fillna(data['brand_num'].median())
    data['cancel_dum'] = data['cancel_dum'].fillna(data['cancel_dum'].median())
    data['certificate_num'] = data['certificate_num'].fillna(data['certificate_num'].median())
    return data

def all_equal(data):
    a = data.to_numpy()
    if (a[0] == a[1:]).all():
        return 0
    else:
        return 1

def handle_company_ar(filename):
    data = pd.read_csv(filename,index_col=0)
    df = data.groupby(by='entid').agg({'EMPNUM':np.mean,'WOMEMPNUM':np.mean})
    df['BUSST'] = data.groupby(by='entid').apply(lambda df: all_equal(df) )
    return df
def handle_company_ar_assetsinfo(filename):
    data = pd.read_csv(filename,index_col=0)
    df = data.groupby(by='entid').agg({'ASSGRO':np.mean,'LIAGRO':np.mean,
                                       'VENDINC':np.mean,'MAIBUSINC':np.mean,
                                       'PROGRO':np.mean,'NETINC':np.mean,
                                       'RATGRO':np.mean,'TOTEQU':np.mean})
    df['ispublic'] = data.groupby(by='entid').apply(lambda df: all_equal(df))
    return df
def handle_company_ar_nz(filename):
    data = pd.read_csv(filename,index_col=0)
    df = data.groupby(by='entid').agg({'MEMNNUM': np.mean, 'FARNUM': np.mean,
                                       'ANNNEWMEM': np.mean, 'ANNREDMEM': np.mean})
    df['MEMNNUM'] = df.fillna(df['MEMNNUM'].median())
    df['FARNUM'] = df.fillna(df['FARNUM'].median())
    df['ANNNEWMEM'] = df.fillna(df['ANNNEWMEM'].median)
    return df
def handle_tax_abnormal(filename):
    data = pd.read_csv(filename)
    print(data.entid)
    data.drop('cdate',axis=1, inplace=True)
    print(data.entid)
    data.drop_duplicates(subset=['entid'], keep='first', inplace=True)
    return data

def handle_company_ar_alterstockinfo(filename):
    df = pd.read_csv(filename)
    df = df.sort_values("entid")
    df1 = df.groupby(by='entid').agg({'INV': np.count_nonzero, 'TRANSAMPR': np.mean, 'TRANSAMAFT': np.mean})
    df1['SUB'] = df1['TRANSAMAFT'] - df1['TRANSAMPR']
    df1['SUB'] = df1['SUB'].fillna(df1['SUB'].median())
    df1['INV'] = df1['INV'].fillna(df1['INV'].median())
    return df1[['INV', 'SUB']]

def handle_company_modify(filename):
    data = pd.read_csv(filename)
    data = data.fillna(0)
    data.drop('ALTDATE',axis=1, inplace=True)
    data.drop_duplicates(subset=['entid'],keep='first', inplace=True)
    return data

def handle_el_company_history_inv(filename):
    df = pd.read_csv(filename)
    def type_not_4(x):
        return len(x) - Counter(x)[4]
    def type_4(x):
        return Counter(x)[4]
    df3 = df.groupby("entid").agg({"ttype": [type_not_4, type_4]})
    df3.columns = df3.columns.droplevel()
    print(df3)
    return df3

def handle_el_company_history_manager(filename):
    df = pd.read_csv(filename)
    table = pd.pivot_table(df, index=["entid"], values=["NAME"], aggfunc=len, fill_value=0)
    return table

def tool1(name,l,temp):
    flag = 0
    for index, row in temp.iterrows():
        if not pd.isnull(row[name]):
            flag = 1
            l.append(row[name])
            break
    if flag==0:
        l.append(np.nan)
    return l
def handle_tax_company(filename):
    tax_company = pd.read_csv(filename)
    new_tax_company = pd.DataFrame(columns=(
    'entid', 'region_id', 'entertype_tax', 'industry_tax', 'registertype', 'economic_type', 'incometax_rate',
    'collection_type', 'avg_EMPNUM', 'std_EMPNUM'))
    entid = tax_company['entid'].unique().tolist()
    print(len(entid))
    print(type(entid))
    for i in entid:
        l = []
        temp = tax_company.loc[tax_company['entid'] == i]

        l.append(i)
        if (all_equal(temp.region_id)):
            l.append(temp.region_id.iloc[0])
        else:
            l.append(0)
        l = tool1('entertype_tax', l, temp)
        l = tool1('industry_tax', l, temp)
        l = tool1('registertype', l, temp)
        l = tool1('economic_type', l, temp)
        l = tool1('incometax_rate', l, temp)
        l = tool1('collection_type', l, temp)

        avg_EMPNUM = temp.EMPNUM.mean()
        std_EMPNUM = temp.EMPNUM.std()
        l.append(avg_EMPNUM)
        l.append(std_EMPNUM)
        new_tax_company.loc[len(new_tax_company)] = l
    return new_tax_company

def handle_tax_year(filename):
    df = pd.read_csv(filename,index_col=0)
    df1 = df.groupby(by='entid').agg({'islatest': np.max,
                                            'profit_loss': np.mean, 'revenue': np.mean, 'sales_cost': np.mean,
                                            'sales_tax': np.mean, 'sales_expense': np.mean, 'G_expense': np.mean,
                                            'finance_expense': np.mean, 'asset_devaluation_losses': np.mean,
                                            'fair_value_change': np.mean, 'investment_income': np.mean,
                                            'operation_profit': np.mean, 'non_operating_income': np.mean,
                                            'non_operating_expense': np.mean, 'total_profit': np.mean,
                                            'assets': np.mean, 'assets_re': np.mean, 'payrol_expense': np.mean,
                                            'welfare_expenses': np.mean, 'education_expenses': np.mean,
                                            'union_funds': np.mean, 'ad_expenses': np.mean,
                                            'entertainment_expenses': np.mean,
                                            'assets_loss': np.mean, 'asset_devaluation_allowance': np.mean,
                                            'main_business_income': np.mean, 'main_business_cost': np.mean,
                                            'other_business_income': np.mean, 'other_operating_cost': np.mean,
                                            'retained_profits': np.mean, 'gross_profit': np.mean,
                                            'main_business_gross': np.mean,
                                            'income_tax_adjuste': np.mean, 'income_taxable': np.mean,
                                            'incometax_taxable': np.mean,
                                            'incometax_amount': np.mean, 'incometax_actual': np.mean})
    df1 = df1.fillna(0)
    df1["welfare_expenses"] = df1["welfare_expenses"].map(lambda x: 1 if x != 0 else 0)
    df1["education_expenses"] = df1["education_expenses"].map(lambda x: 1 if x != 0 else 0)
    df1["union_funds"] = df1["union_funds"].map(lambda x: 1 if x != 0 else 0)
    df1["ad_expenses"] = df1["ad_expenses"].map(lambda x: 1 if x != 0 else 0)
    df1["entertainment_expenses"] = df1["entertainment_expenses"].map(lambda x: 1 if x != 0 else 0)
    df1["assets_loss"] = df1["assets_loss"].map(lambda x: 1 if x != 0 else 0)
    df1["asset_devaluation_allowance"] = df1["asset_devaluation_allowance"].map(lambda x: 1 if x != 0 else 0)
    return df1

out_path = "./newdata"
handle_company_base_info(path+"/"+"company_base_info.csv").to_csv(out_path+"/company_base_info.csv")
handle_company_ar(path+"/"+"company_ar.csv").to_csv(out_path+"/company_ar.csv")
handle_company_ar_assetsinfo(path+"/"+"company_ar_assetsinfo.csv").to_csv(out_path+"/company_ar_assetsinfo")
handle_company_ar_nz(path+"/"+"company_ar_nz.csv").to_csv(out_path+"/company_ar_nz.csv")
handle_tax_abnormal(path+"/"+"tax_abnormal.csv").to_csv(out_path+"/tax_abnormal.csv")
handle_company_ar_alterstockinfo(path+"/"+"company_ar_alterstockinfo.csv").to_csv(out_path+"/company_ar_alterstockinfo.csv")
handle_company_modify(path+"/"+"company_modify.csv").to_csv(out_path+"/company_modify.csv")
handle_el_company_history_inv(path+"/"+"el_company_history_inv.csv").to_csv(out_path+"/el_company_history_inv.csv")
handle_el_company_history_manager(path+"/"+"el_company_history_manager.csv").to_csv(out_path+"/el_company_history_manager.csv")
handle_tax_company(path+"/"+"tax_company.csv").to_csv(out_path+"/tax_company.csv",index=False)
handle_tax_year(path+"/"+"tax_year.csv").to_csv(out_path+"/tax_year.csv")


from django.conf.urls import url
from django.urls import path
from . import views

app_name = "accommodation"

urlpatterns = [
    url(r'^$', views.index_view, name='index'),
    url(r'^index/$', views.index_view, name='index'),
    url(r'^reservation/$', views.reservation_view, name='reservation'),
    url(r'^property/$', views.property_view, name='property'),
    url(r'^imageUploader/$', views.imageUploader_view, name='imageUploader'),
    path('propertyDetailed/<int:pk>/', views.propertyDetailed_view, name='propertyDetailed'),
    path('delete/<int:pk>/', views.deleteReservation_view, name='deleteReservation'),
]