Best Python code snippet using playwright-python
triangle.py
Source:triangle.py  
1import renmas2.switch as proc2from .hitpoint import HitPoint3from .bbox import BBox4from ..core import Vector35from .shape import Shape6class Triangle(Shape):7    def __init__(self, v0, v1, v2, material=None, n0=None, n1=None, n2=None, u=None, v=None):8        self.v0 = v09        self.v1 = v110        self.v2 = v211        self.material = material12        self.normal = None13        self.n0 = n014        self.n1 = n115        self.n2 = n216        self.u = u17        self.v = v18        #TODO think -- raise exception if only one of three normals are passed to constructor19        if n0 is None:20            self.normal = (v1 - v0).cross(v2 - v0)21            self.normal.normalize()22            self.has_normals = False 23        else:24            self.n0.normalize()25            self.n1.normalize()26            self.n2.normalize()27            self.has_normals = True 28        if u is None:29            self.has_uv = False30        else:31            self.has_uv = True32    def isect_b(self, ray, min_dist=999999.0): #ray direction must be normalized33        a = self.v0.x - self.v1.x34        b = self.v0.x - self.v2.x35        c = ray.dir.x 36        d = self.v0.x - ray.origin.x37        e = self.v0.y - self.v1.y38        f = self.v0.y - self.v2.y39        g = ray.dir.y40        h = self.v0.y - ray.origin.y41        i = self.v0.z - self.v1.z42        j = self.v0.z - self.v2.z43        k = ray.dir.z44        l = self.v0.z - ray.origin.z45        m = f * k - g * j46        n = h * k - g * l47        p = f * l - h * j48        q = g * i - e * k49        s = e * j - f * i50        temp3 =  (a * m + b * q + c * s)51        if temp3 == 0.0: return False52        inv_denom = 1.0 / temp353        e1 = d * m - b * n - c * p54        beta = e1 * inv_denom55        if beta < 0.0: return False56        r = e * l - h * i57        e2 = a * n + d * q + c * r58        gamma = e2 * inv_denom59        if gamma < 0.0: return False60        if beta + gamma > 1.0: return False61        e3 = a * p - b * r + d * s62        t = e3 * inv_denom63        if t < 0.00001: return False # self-intersection64        return t65    # eax = pointer to ray structure66    # ebx = pointer to triangle structure67    # ecx = pointer to minimum distance68    @classmethod69    def isect_asm_b(cls, runtimes, label, assembler, structures):70        code = """71            #DATA72        """73        code += structures.structs(('ray', 'triangle', 'hitpoint')) + """74        float epsilon= 0.0000175        float one = 1.000176        #CODE77        """78        if proc.AVX:79            code += " global " + label + ":\n" + """80            vmovaps xmm0, oword [ebx + triangle.v0]81            vsubps xmm1, xmm0, oword [ebx + triangle.v2]82            vsubps xmm3, xmm0, oword [eax + ray.origin]83            vmovaps xmm2, oword [eax + ray.dir]84            vsubps xmm0, xmm0, oword [ebx + triangle.v1]85            vmovlhps xmm4, xmm1, xmm386            vpermilps xmm4, xmm4, 01110101B 87            vmovhlps xmm5, xmm2, xmm388            vpermilps xmm5, xmm5, 00101010B 89            vmulps xmm7, xmm4, xmm590            vmovlhps xmm6, xmm2, xmm391            vpermilps xmm6, xmm6, 11010101B 92            vmovhlps xmm4, xmm1, xmm393            vpermilps xmm4, xmm4, 10001010B 94            vmulps xmm4, xmm4, xmm695            vsubps xmm7, xmm7, xmm496            vmovlhps xmm5, xmm0, xmm397            vpermilps xmm5, xmm5, 00001000B 98            vmulps xmm7, xmm7, xmm599            vmovhlps xmm5, xmm0, xmm3100            vpermilps xmm5, xmm5, 10100010B 101            vmulps xmm6, xmm6, xmm5102            vmovlhps xmm4, xmm0, xmm3103            vpermilps xmm4, xmm4, 01011101B 104            vmovhlps xmm5, xmm2, xmm3105            vpermilps xmm5, xmm5, 00101010B 106            vmulps xmm5, xmm5, xmm4107            vsubps xmm6, xmm6, xmm5108            vmovlhps xmm5, xmm1, xmm3109            vpermilps xmm5, xmm5, 00100000B 110            vmulps xmm6, xmm6, xmm5111            vaddps xmm7, xmm7, xmm6112            vmovhlps xmm5, xmm1, xmm3113            vpermilps xmm5, xmm5, 10001010B 114            vmulps xmm4, xmm4, xmm5115            vmovlhps xmm6, xmm1, xmm3116            vpermilps xmm6, xmm6, 01110101B 117            vmovhlps xmm5, xmm0, xmm3118            vpermilps xmm5, xmm5, 10100010B 119            vmulps xmm6, xmm6, xmm5120            vsubps xmm4, xmm4, xmm6121            vmovlhps xmm5, xmm2, xmm3122            vpermilps xmm5, xmm5, 10000000B 123            vmulps xmm4, xmm4, xmm5124            vaddps xmm7, xmm7, xmm4125            vpermilps xmm3, xmm7, 00000000B 126            vdivps xmm7, xmm7, xmm3127            vpermilps xmm5, xmm7, 10101010B 128            vpermilps xmm4, xmm7, 01010101B 129            vpermilps xmm6, xmm7, 11111111B 130            ; xmm7 = d  xmm6 = td  xmm5 = gamma   xmm4 = beta131            vpxor xmm3, xmm3, xmm3132            macro if xmm4 < xmm3 goto _reject133            macro if xmm5 < xmm3 goto _reject134            vaddss xmm4, xmm4, xmm5135            macro if xmm4 > one goto _reject136            vcomiss xmm6, dword [epsilon]137            jc _reject138            vcomiss xmm6, dword [ecx] ;minimum distance139            jnc _reject140            ;populate hitpoint structure141            ; t is in xmm6142            vmovaps xmm0, xmm6143            mov eax, 1144            ret145            _reject:146            xor eax, eax147            ret148            """149        else:150            code += " global " + label + ":\n" + """151            movaps xmm0, oword [ebx + triangle.v0]152            movaps xmm1, xmm0 153            movaps xmm3, xmm0154            subps xmm0, oword [ebx + triangle.v1]155            movaps xmm2, oword [eax + ray.dir]156            subps xmm1, oword [ebx + triangle.v2]157            subps xmm3, oword [eax + ray.origin]158            movaps xmm4, xmm1159            movlhps xmm4, xmm3160            shufps xmm4, xmm4, 01110101B161            movaps xmm5, xmm2162            movhlps xmm5, xmm3163            shufps xmm5, xmm5, 00101010B 164            movaps xmm7, xmm4165            mulps xmm7, xmm5166            movaps xmm6, xmm2167            movlhps xmm6, xmm3168            shufps xmm6, xmm6, 11010101B169            movaps xmm4, xmm1170            movhlps xmm4, xmm3171            shufps xmm4, xmm4, 10001010B172            mulps xmm4, xmm6173            subps xmm7, xmm4174            movaps xmm5, xmm0175            movlhps xmm5, xmm3176            shufps xmm5, xmm5, 00001000B177            mulps xmm7, xmm5178            movaps xmm5, xmm0179            movhlps xmm5, xmm3180            shufps xmm5, xmm5, 10100010B181            mulps xmm6, xmm5182            movaps xmm4, xmm0183            movlhps xmm4, xmm3184            shufps xmm4, xmm4, 01011101B185            movaps xmm5, xmm2186            movhlps xmm5, xmm3187            shufps xmm5, xmm5, 00101010B 188            mulps xmm5, xmm4189            subps xmm6, xmm5190            movaps xmm5, xmm1191            movlhps xmm5, xmm3192            shufps xmm5, xmm5, 00100000B193            mulps xmm6, xmm5194            addps xmm7, xmm6195            movaps xmm5, xmm1196            movhlps xmm5, xmm3197            shufps xmm5, xmm5, 10001010B198            mulps xmm4, xmm5199            movaps xmm6, xmm1200            movlhps xmm6, xmm3201            shufps xmm6, xmm6, 01110101B202            movaps xmm5, xmm0203            movhlps xmm5, xmm3204            shufps xmm5, xmm5, 10100010B205            mulps xmm6, xmm5206            subps xmm4, xmm6207            movaps xmm5, xmm2208            movlhps xmm5, xmm3209            shufps xmm5, xmm5, 10000000B210            mulps xmm4, xmm5211            addps xmm7, xmm4212            macro broadcast xmm3 = xmm7[0]213            divps xmm7, xmm3214            movhlps xmm5, xmm7215            movaps xmm4, xmm7216            shufps xmm4, xmm4, 0x55 217            movaps xmm6, xmm7218            shufps xmm6, xmm6, 0xFF219            ; xmm7 = d  xmm6 = td  xmm5 = gamma   xmm4 = beta220            pxor xmm3, xmm3221            macro if xmm4 < xmm3 goto _reject222            macro if xmm5 < xmm3 goto _reject223            addss xmm4, xmm5224            macro if xmm4 > one goto _reject225            comiss xmm6, dword [epsilon]226            jc _reject227            comiss xmm6, dword [ecx] ;minimum distance228            jnc _reject229            ;populate hitpoint structure230            ; t is in xmm6231            movaps xmm0, xmm6232            mov eax, 1233            ret234            _reject:235            xor eax, eax236            ret237            """238        mc = assembler.assemble(code, True)239        #mc.print_machine_code()240        name = "ray_triangle_intersection_bool" + str(hash(cls))241        for r in runtimes:242            if not r.global_exists(label):243                r.load(name, mc)244    def isect(self, ray, min_dist=999999.0): #ray direction must be normalized245        a = self.v0.x - self.v1.x246        b = self.v0.x - self.v2.x247        c = ray.dir.x 248        d = self.v0.x - ray.origin.x249        e = self.v0.y - self.v1.y250        f = self.v0.y - self.v2.y251        g = ray.dir.y252        h = self.v0.y - ray.origin.y253        i = self.v0.z - self.v1.z254        j = self.v0.z - self.v2.z255        k = ray.dir.z256        l = self.v0.z - ray.origin.z257        m = f * k - g * j258        n = h * k - g * l259        p = f * l - h * j260        q = g * i - e * k261        s = e * j - f * i262        temp3 =  (a * m + b * q + c * s)263        if temp3 == 0.0: return False264        inv_denom = 1.0 / temp3265        e1 = d * m - b * n - c * p266        beta = e1 * inv_denom267        if beta < 0.0: return False268        r = e * l - h * i269        e2 = a * n + d * q + c * r270        gamma = e2 * inv_denom271        if gamma < 0.0: return False272        if beta + gamma > 1.0: return False273        e3 = a * p - b * r + d * s274        t = e3 * inv_denom275        if t < 0.00001: return False # self-intersection276        hit_point = ray.origin + ray.dir * t277        278        return HitPoint(t, hit_point, self.normal, self.material, ray)279    # eax = pointer to ray structure280    # ebx = pointer to triangle structure281    # ecx = pointer to minimum distance282    # edx = pointer to hitpoint283    @classmethod284    def isect_asm(cls, runtimes, label, assembler, structures):285        code = """286            #DATA287        """288        code += structures.structs(('ray', 'triangle', 'hitpoint')) + """289        float epsilon= 0.00001290        float one = 1.0001291        #CODE292        """293        if proc.AVX:294            code += " global " + label + ":\n" + """295            vmovaps xmm0, oword [ebx + triangle.v0]296            vsubps xmm1, xmm0, oword [ebx + triangle.v2]297            vsubps xmm3, xmm0, oword [eax + ray.origin]298            vmovaps xmm2, oword [eax + ray.dir]299            vsubps xmm0, xmm0, oword [ebx + triangle.v1]300            ; f f h f301            vmovlhps xmm4, xmm1, xmm3302            vpermilps xmm4, xmm4, 01110101B 303            ; k k k l304            vmovhlps xmm5, xmm2, xmm3305            vpermilps xmm5, xmm5, 00101010B 306            ; f f h f * k k k l307            vmulps xmm7, xmm4, xmm5308            ; g g g h309            vmovlhps xmm6, xmm2, xmm3310            vpermilps xmm6, xmm6, 11010101B 311            ; j j l j312            vmovhlps xmm4, xmm1, xmm3313            vpermilps xmm4, xmm4, 10001010B 314            ; g g g h * j j l j315            vmulps xmm4, xmm4, xmm6316            ; f f h f * k k k l - g g g h * j j l j317            vsubps xmm7, xmm7, xmm4318            ; a d a a319            vmovlhps xmm5, xmm0, xmm3320            vpermilps xmm5, xmm5, 00001000B 321            ; a d a a * (f f h f * k k k l - g g g h * j j l j)322            vmulps xmm7, xmm7, xmm5323            ; i l i i324            vmovhlps xmm5, xmm0, xmm3325            vpermilps xmm5, xmm5, 10100010B 326            ; g g g h * i l i i327            vmulps xmm6, xmm6, xmm5328            ; e h e e329            vmovlhps xmm4, xmm0, xmm3330            vpermilps xmm4, xmm4, 01011101B 331            ; k k k l332            vmovhlps xmm5, xmm2, xmm3333            vpermilps xmm5, xmm5, 00101010B 334            ; e h e e * k k k l335            vmulps xmm5, xmm5, xmm4336            ; g g g h * i l i i - e h e e * k k k l337            vsubps xmm6, xmm6, xmm5338            ; b b d b339            vmovlhps xmm5, xmm1, xmm3340            vpermilps xmm5, xmm5, 00100000B 341            ; b b d b * (g g g h * i l i i - e h e e * k k k l)342            vmulps xmm6, xmm6, xmm5343            vaddps xmm7, xmm7, xmm6344            ; j j l j345            vmovhlps xmm5, xmm1, xmm3346            vpermilps xmm5, xmm5, 10001010B 347            ; e e h e * j j l j 348            vmulps xmm4, xmm4, xmm5349            ; f f h f350            vmovlhps xmm6, xmm1, xmm3351            vpermilps xmm6, xmm6, 01110101B 352            ; i l i i353            vmovhlps xmm5, xmm0, xmm3354            vpermilps xmm5, xmm5, 10100010B 355            ; f f h f * i l i i356            vmulps xmm6, xmm6, xmm5357            ; e h e e * j j l j - f f h f * i l i i358            vsubps xmm4, xmm4, xmm6359            ; c c c d360            vmovlhps xmm5, xmm2, xmm3361            vpermilps xmm5, xmm5, 10000000B 362            ; c c c d * (e h e e * j j l j - f f h f * i l i i)363            vmulps xmm4, xmm4, xmm5364            vaddps xmm7, xmm7, xmm4365            vpermilps xmm3, xmm7, 00000000B 366            vdivps xmm7, xmm7, xmm3367            vpermilps xmm5, xmm7, 10101010B 368            vpermilps xmm4, xmm7, 01010101B 369            vpermilps xmm6, xmm7, 11111111B 370            ; xmm7 = d  xmm6 = td  xmm5 = gamma   xmm4 = beta371            vpxor xmm3, xmm3, xmm3372            macro if xmm4 < xmm3 goto _reject373            macro if xmm5 < xmm3 goto _reject374            vaddss xmm4, xmm4, xmm5375            macro if xmm4 > one goto _reject376            vcomiss xmm6, dword [epsilon]377            jc _reject378            vcomiss xmm6, dword [ecx] ;minimum distance379            jnc _reject380            ;populate hitpoint structure381            ; t is in xmm6382            383            vmovaps xmm2, oword [eax + ray.dir]384            vmovaps xmm3, oword [ebx + triangle.normal]385            vmovss xmm4, dword [ebx + triangle.mat_index]386            vmovss dword [edx + hitpoint.t], xmm6 387            vmovaps oword [edx + hitpoint.normal], xmm3388            vmovss dword [edx + hitpoint.mat_index], xmm4389            macro broadcast xmm5 = xmm6[0]390            vmulps xmm5, xmm5, xmm2391            macro eq128 edx.hitpoint.hit = xmm5 + eax.ray.origin {xmm0}392            mov eax, 1393            ret394            _reject:395            xor eax, eax396            ret397            """398        else:399            code += " global " + label + ":\n" + """400            movaps xmm0, oword [ebx + triangle.v0]401            movaps xmm1, xmm0 402            movaps xmm3, xmm0403            subps xmm0, oword [ebx + triangle.v1]404            movaps xmm2, oword [eax + ray.dir]405            subps xmm1, oword [ebx + triangle.v2]406            subps xmm3, oword [eax + ray.origin]407            ; f f h f408            movaps xmm4, xmm1409            movlhps xmm4, xmm3410            shufps xmm4, xmm4, 01110101B411            ; k k k l412            movaps xmm5, xmm2413            movhlps xmm5, xmm3414            shufps xmm5, xmm5, 00101010B 415            ; f f h f * k k k l416            movaps xmm7, xmm4417            mulps xmm7, xmm5418            ; g g g h419            movaps xmm6, xmm2420            movlhps xmm6, xmm3421            shufps xmm6, xmm6, 11010101B422            ; j j l j423            movaps xmm4, xmm1424            movhlps xmm4, xmm3425            shufps xmm4, xmm4, 10001010B426            ; g g g h * j j l j427            mulps xmm4, xmm6428            ; f f h f * k k k l - g g g h * j j l j429            subps xmm7, xmm4430            ; a d a a431            movaps xmm5, xmm0432            movlhps xmm5, xmm3433            shufps xmm5, xmm5, 00001000B434            ; a d a a * (f f h f * k k k l - g g g h * j j l j)435            mulps xmm7, xmm5436            ; i l i i437            movaps xmm5, xmm0438            movhlps xmm5, xmm3439            shufps xmm5, xmm5, 10100010B440            ; g g g h * i l i i441            mulps xmm6, xmm5442            ; e h e e443            movaps xmm4, xmm0444            movlhps xmm4, xmm3445            shufps xmm4, xmm4, 01011101B446            ; k k k l447            movaps xmm5, xmm2448            movhlps xmm5, xmm3449            shufps xmm5, xmm5, 00101010B 450            ; e h e e * k k k l451            mulps xmm5, xmm4452            ; g g g h * i l i i - e h e e * k k k l453            subps xmm6, xmm5454            ; b b d b455            movaps xmm5, xmm1456            movlhps xmm5, xmm3457            shufps xmm5, xmm5, 00100000B458            ; b b d b * (g g g h * i l i i - e h e e * k k k l)459            mulps xmm6, xmm5460            addps xmm7, xmm6461            ; j j l j462            movaps xmm5, xmm1463            movhlps xmm5, xmm3464            shufps xmm5, xmm5, 10001010B465            ; e e h e * j j l j 466            mulps xmm4, xmm5467            ; f f h f468            movaps xmm6, xmm1469            movlhps xmm6, xmm3470            shufps xmm6, xmm6, 01110101B471            ; i l i i472            movaps xmm5, xmm0473            movhlps xmm5, xmm3474            shufps xmm5, xmm5, 10100010B475            ; f f h f * i l i i476            mulps xmm6, xmm5477            ; e h e e * j j l j - f f h f * i l i i478            subps xmm4, xmm6479            ; c c c d480            movaps xmm5, xmm2481            movlhps xmm5, xmm3482            shufps xmm5, xmm5, 10000000B483            ; c c c d * (e h e e * j j l j - f f h f * i l i i)484            mulps xmm4, xmm5485            addps xmm7, xmm4486            macro broadcast xmm3 = xmm7[0]487            divps xmm7, xmm3488            movhlps xmm5, xmm7489            490            movaps xmm4, xmm7491            shufps xmm4, xmm4, 0x55 492            493            movaps xmm6, xmm7494            shufps xmm6, xmm6, 0xFF495            ; xmm7 = d  xmm6 = td  xmm5 = gamma   xmm4 = beta496            497            pxor xmm3, xmm3498            macro if xmm4 < xmm3 goto _reject499            macro if xmm5 < xmm3 goto _reject500            addss xmm4, xmm5501            macro if xmm4 > one goto _reject502            comiss xmm6, dword [epsilon]503            jc _reject504            comiss xmm6, dword [ecx] ;minimum distance505            jnc _reject506            ;populate hitpoint structure507            ; t is in xmm6508            509            movaps xmm2, oword [eax + ray.dir]510            movaps xmm3, oword [ebx + triangle.normal]511            movss xmm4, dword [ebx + triangle.mat_index]512            movss dword [edx + hitpoint.t], xmm6 513            movaps oword [edx + hitpoint.normal], xmm3514            movss dword [edx + hitpoint.mat_index], xmm4515            macro broadcast xmm5 = xmm6[0]516            mulps xmm5, xmm2517            macro eq128 edx.hitpoint.hit = xmm5 + eax.ray.origin {xmm0}518            mov eax, 1519            ret520            _reject:521            xor eax, eax522            ret523            """524        mc = assembler.assemble(code, True)525        #mc.print_machine_code()526        name = "ray_triangle_intersection" + str(hash(cls))527        for r in runtimes:528            if not r.global_exists(label):529                r.load(name, mc)530    def attributes(self):531        d = {}532        d["v0"] = (self.v0.x, self.v0.y, self.v0.z, 0.0)533        d["v1"] = (self.v1.x, self.v1.y, self.v1.z, 0.0)534        d["v2"] = (self.v2.x, self.v2.y, self.v2.z, 0.0)535        d["normal"] = (self.normal.x, self.normal.y, self.normal.z, 0.0)536        if self.material is None:537            d["mat_index"] = 999999 #TODO try to solve this in better way 538        else:539            d["mat_index"] = self.material540        return d541    @classmethod542    def name(cls):543        return "triangle"544    def bbox(self):545        epsilon = 0.0001546        v0 = self.v0 547        v1 = self.v1548        v2 = self.v2549        minx = min(min(v0.x, v1.x), v2.x) - epsilon550        maxx = max(max(v0.x, v1.x), v2.x) + epsilon551        miny = min(min(v0.y, v1.y), v2.y) - epsilon552        maxy = max(max(v0.y, v1.y), v2.y) + epsilon553        minz = min(min(v0.z, v1.z), v2.z) - epsilon554        maxz = max(max(v0.z, v1.z), v2.z) + epsilon555        p0 = Vector3(minx, miny, minz)556        p1 = Vector3(maxx, maxy, maxz)...__init__.py
Source:__init__.py  
...55        self._errbacks = []56    def fulfill(self, value):57        self._fulfill(value)58        return self59    def _reject(self, reason, bubbling=False):60        """61        Reject this promise for a given reason.62        """63        assert self._state == self.PENDING, "Promise state is not pending"64        if not bubbling and log_error(reason):65            exc_info = sys.exc_info()66            self.logger.debug("Promise (%s) rejected: %s", self.name, reason,67                              exc_info=exc_info[0] and exc_info or None)68            self.logger.debug(self._errbacks)69            if self.logger.isEnabledFor(DEBUG):70                print_stack()71        else:72            pass73        self._state = self.REJECTED74        self.reason = reason75        for errback in self._errbacks:76            try:77                errback(reason)78            except Exception:79                self.logger.exception("Error in errback %s", errback)80                # Ignore errors in callbacks81        # We will never call these errbacks again, so allow82        # them to be garbage collected.  This is important since83        # they probably include closures which are binding variables84        # that might otherwise be garbage collected.85        self._errbacks = []86        self._callbacks = []87    def reject(self, reason):88        self._reject(reason)89        return self90    def isPending(self):91        """Indicate whether the Promise is still pending."""92        return self._state == self.PENDING93    def isFulfilled(self):94        """Indicate whether the Promise has been fulfilled."""95        return self._state == self.FULFILLED96    def isRejected(self):97        """Indicate whether the Promise has been rejected."""98        return self._state == self.REJECTED99    def get(self, timeout=None):100        """Get the value of the promise, waiting if necessary."""101        self.wait(timeout)102        if self._state == self.FULFILLED:103            return self.value104        raise self.reason105    def wait(self, timeout=None):106        """107        An implementation of the wait method which doesn't involve108        polling but instead utilizes a "real" synchronization109        scheme.110        """111        import threading112        if self._state != self.PENDING:113            return114        e = threading.Event()115        self.addCallback(lambda v: e.set())116        self.addErrback(lambda r: e.set())117        e.wait(timeout)118    def addCallback(self, f):119        """120        Add a callback for when this promise is fulfilled.  Note that121        if you intend to use the value of the promise somehow in122        the callback, it is more convenient to use the 'then' method.123        """124        self._callbacks.append(f)125    def addErrback(self, f):126        """127        Add a callback for when this promise is rejected.  Note that128        if you intend to use the rejection reason of the promise129        somehow in the callback, it is more convenient to use130        the 'then' method.131        """132        self._errbacks.append(f)133    if platform.python_implementation != "CPython":134        def _invoke(self, func, value):135            try:136                if value is None:137                    args = getfullargspec(func).args138                    arglen = len(args)139                    if not arglen or (arglen == 1 and ismethod(func)):140                        return func()141                return func(value)142            except Exception as e:143                if log_error(e):144                    self.logger.exception("Error in handler %s", func)145                else:146                    self.logger.debug("Error in handler %s: %s", func, e)147                raise148    else:149        def _invoke(self, func, value):150            try:151                if value is None:152                    try:153                        target = func.__func__154                    except AttributeError:155                        argcount = func.__code__.co_argcount156                    else:157                        argcount = target.__code__.co_argcount - 1158                    if argcount == 0:159                        return func()160                return func(value)161            except Exception as e:162                if log_error(e):163                    self.logger.exception("Error in handler %s", func)164                else:165                    self.logger.debug("Error in handler %s: %s", func, repr(e))166                raise167    def __enter__(self):168        return self169    def __exit__(self, exc_type, exc_value, exc_tb):170        if self.isPending():171            if exc_value is not None:172                if log_error(exc_value):173                    self.logger.exception("Promise automatically rejected")174                self._reject(exc_value, bubbling=True)175                return True176            else:177                self.fulfill(None)178    def then(self, success=None, failure=None, name=None):179        """180        This method takes two optional arguments.  The first argument181        is used if the "self promise" is fulfilled and the other is182        used if the "self promise" is rejected.  In either case, this183        method returns another promise that effectively represents184        the result of either the first of the second argument (in the185        case that the "self promise" is fulfilled or rejected,186        respectively).187        Each argument can be either:188          * None - Meaning no action is taken189          * A function - which will be called with either the value190            of the "self promise" or the reason for rejection of191            the "self promise".  The function may return:192            * A value - which will be used to fulfill the promise193              returned by this method.194            * A promise - which, when fulfilled or rejected, will195              cascade its value or reason to the promise returned196              by this method.197          * A value - which will be assigned as either the value198            or the reason for the promise returned by this method199            when the "self promise" is either fulfilled or rejected,200            respectively.201        """202        if name is None:203            try:204                name = success.__name__205            except AttributeError:206                name = str(success)207        ret = Promise(name=name)208        state = self._state209        if state == self.PENDING:210            """211            If this is still pending, then add callbacks to the212            existing promise that call either the success or213            rejected functions supplied and then fulfill the214            promise being returned by this method215            """216            def callAndFulfill(v):217                """218                A callback to be invoked if the "self promise"219                is fulfilled.220                """221                try:222                    # From 3.2.1, don't call non-functions values223                    if callable(success):224                        newvalue = self._invoke(success, v)225                        if _isPromise(newvalue):226                            newvalue.then(ret._fulfill,227                                          ret._reject)228                        else:229                            ret._fulfill(newvalue)230                    else:231                        # From 3.2.6.4232                        ret._fulfill(v)233                except Exception as e:234                    ret._reject(e)235            def callAndReject(r):236                """237                A callback to be invoked if the "self promise"238                is rejected.239                """240                try:241                    if callable(failure):242                        newvalue = failure(r)243                        if _isPromise(newvalue):244                            newvalue.then(ret._fulfill,245                                          ret._reject)246                        else:247                            ret._fulfill(newvalue)248                    else:249                        # From 3.2.6.5250                        ret._reject(r)251                except Exception as e:252                    ret._reject(e)253            self._callbacks.append(callAndFulfill)254            self._errbacks.append(callAndReject)255        elif state == self.FULFILLED:256            # If this promise was already fulfilled, then257            # we need to use the first argument to this method258            # to determine the value to use in fulfilling the259            # promise that we return from this method.260            try:261                if callable(success):262                    newvalue = self._invoke(success, self.value)263                    if _isPromise(newvalue):264                        newvalue.then(ret._fulfill,265                                      lambda r: ret._reject(r, bubbling=True))266                    else:267                        ret._fulfill(newvalue)268                else:269                    # From 3.2.6.4270                    ret._fulfill(self.value)271            except Exception as e:272                ret._reject(e)273        else:274            # If this promise was already rejected, then275            # we need to use the second argument to this method276            # to determine the value to use in fulfilling the277            # promise that we return from this method.278            try:279                if callable(failure):280                    newvalue = self._invoke(failure, self.reason)281                    if _isPromise(newvalue):282                        newvalue.then(ret._fulfill,283                                      ret._reject)284                    else:285                        ret._fulfill(newvalue)286                else:287                    # From 3.2.6.5288                    ret._reject(self.reason, bubbling=True)289            except Exception as e:290                ret._reject(e)291        return ret292def _isPromise(obj):293    """294    A utility function to determine if the specified295    object is a promise using "duck typing".296    """297    if isinstance(obj, Promise):298        return True299    try:300        return callable(obj.fulfill) and callable(obj.reject) and\301            callable(obj.then)302    except AttributeError:303        return False304def listPromise(*args):...csrf.py
Source:csrf.py  
...36        # requires_csrf_token decorator.37        def _accept(self, request):38            request.csrf_processing_done = True39            return None40        def _reject(self, request, reason):41            return _get_failure_view()(request, reason=reason)42        def process_view(self, request, callback, callback_args, callback_kwargs):43            if getattr(request, 'csrf_processing_done', False):44                return None45            try:46                csrf_token = _sanitize_token(47                    request.COOKIES[settings.CSRF_COOKIE_NAME])48                # Use same token next time49                request.META['CSRF_COOKIE'] = csrf_token50            except KeyError:51                if 'state' in request.POST:52                    csrf_token = _sanitize_token(request.POST.get('state'))53                else:54                    csrf_token = None55                    # Generate token and store it in the request, so it's56                    # available to the view.57                    request.META["CSRF_COOKIE"] = _get_new_csrf_key()58            # Wait until request.META["CSRF_COOKIE"] has been manipulated before59            # bailing out, so that get_token still works60            if getattr(callback, 'csrf_exempt', False):61                return None62            # Assume that anything not defined as 'safe' by RC2616 needs protection63            if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):64                if getattr(request, '_dont_enforce_csrf_checks', False):65                    # Mechanism to turn off CSRF checks for test suite.66                    # It comes after the creation of CSRF cookies, so that67                    # everything else continues to work exactly the same68                    # (e.g. cookies are sent, etc.), but before any69                    # branches that call reject().70                    return self._accept(request)71                # let initial signed requests pass72                if request.method == 'POST' and 'signed_request' in request.POST:73                    post = request.POST.copy()74                    post.pop('signed_request')75                    if len(post) == 0:76                        return self._accept(request)77                if request.is_secure() and getattr(settings, 'HTTPS_REFERER_REQUIRED', True):78                    # Suppose user visits http://example.com/79                    # An active network attacker (man-in-the-middle, MITM) sends a80                    referer = request.META.get('HTTP_REFERER')81                    if referer is None:82                        logger.warning('Forbidden (%s): %s',83                                       REASON_NO_REFERER, request.path,84                            extra={85                                'status_code': 403,86                                'request': request,87                            }88                        )89                        return self._reject(request, REASON_NO_REFERER)90                    # Note that request.get_host() includes the port.91                    good_referer = 'https://%s/' % request.get_host()92                    if not same_origin(referer, good_referer):93                        reason = REASON_BAD_REFERER % (referer, good_referer)94                        logger.warning('Forbidden (%s): %s', reason, request.path,95                            extra={96                                'status_code': 403,97                                'request': request,98                            }99                        )100                        return self._reject(request, reason)101                if csrf_token is None:102                    # No CSRF cookie. For POST requests, we insist on a CSRF cookie,103                    # and in this way we can avoid all CSRF attacks, including login104                    # CSRF.105                    logger.warning('Forbidden (%s): %s',106                                   REASON_NO_CSRF_COOKIE, request.path,107                        extra={108                            'status_code': 403,109                            'request': request,110                        }111                    )112                    return self._reject(request, REASON_NO_CSRF_COOKIE)113                # Check non-cookie token for match.114                request_csrf_token = ""115                if request.method == "POST":116                    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')117                if request_csrf_token == "":118                    # Fall back to X-CSRFToken, to make things easier for AJAX,119                    # and possible for PUT/DELETE.120                    request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')121                if not crypto.constant_time_compare(request_csrf_token, csrf_token):122                    logger.warning('Forbidden (%s): %s',123                                   REASON_BAD_TOKEN, request.path,124                        extra={125                            'status_code': 403,126                            'request': request,127                        }128                    )129                    return self._reject(request, REASON_BAD_TOKEN)130            return self._accept(request)131else:132    from django.middleware.csrf import (133        _sanitize_token, _get_new_csrf_key, _make_legacy_session_token,134        REASON_NO_COOKIE, _MAX_CSRF_KEY)135    class CsrfViewMiddleware(DjangoCsrfViewMiddleware):136        def process_view(self, request, callback, callback_args, callback_kwargs):137            if getattr(request, 'csrf_processing_done', False):138                return None139            try:140                request.META["CSRF_COOKIE"] = _sanitize_token(request.COOKIES[settings.CSRF_COOKIE_NAME])141                cookie_is_new = False142            except KeyError:143                request.META["CSRF_COOKIE"] = _get_new_csrf_key()144                cookie_is_new = True145            if getattr(callback, 'csrf_exempt', False):146                return None147            if request.method == 'POST':148                if getattr(request, '_dont_enforce_csrf_checks', False):149                    return self._accept(request)150                # let initial signed requests pass151                if 'signed_request' in request.POST:152                    post = request.POST.copy()153                    post.pop('signed_request')154                    if len(post) == 0:155                        return self._accept(request)156                if request.is_secure() and getattr(settings, 'HTTPS_REFERER_REQUIRED', True):157                    referer = request.META.get('HTTP_REFERER')158                    if referer is None :159                        logger.warning('Forbidden (%s): %s' % (REASON_NO_REFERER, request.path),160                            extra={161                                'status_code': 403,162                                'request': request,163                            }164                        )165                        return self._reject(request, REASON_NO_REFERER)166                    # Note that request.get_host() includes the port167                    good_referer = 'https://%s/' % request.get_host()168                    if not same_origin(referer, good_referer):169                        reason = REASON_BAD_REFERER % (referer, good_referer)170                        logger.warning('Forbidden (%s): %s' % (reason, request.path),171                            extra={172                                'status_code': 403,173                                'request': request,174                            }175                        )176                        return self._reject(request, reason)177                if cookie_is_new:178                    try:179                        session_id = request.COOKIES[settings.SESSION_COOKIE_NAME]180                        csrf_token = _make_legacy_session_token(session_id)181                    except KeyError:182                        logger.warning('Forbidden (%s): %s' % (REASON_NO_COOKIE, request.path),183                            extra={184                                'status_code': 403,185                                'request': request,186                            }187                        )188                        return self._reject(request, REASON_NO_COOKIE)189                else:190                    csrf_token = request.META["CSRF_COOKIE"]191                # check incoming token192                request_csrf_token = request.POST.get('csrfmiddlewaretoken', None)193                if not request_csrf_token:194                    request_csrf_token = request.POST.get('state', '')195                if request_csrf_token == "":196                    # Fall back to X-CSRFToken, to make things easier for AJAX197                    request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')198                if not crypto.constant_time_compare(request_csrf_token, csrf_token):199                    if cookie_is_new:200                        # probably a problem setting the CSRF cookie201                        logger.warning('Forbidden (%s): %s' % (REASON_NO_CSRF_COOKIE, request.path),202                            extra={203                                'status_code': 403,204                                'request': request,205                            }206                        )207                        return self._reject(request, REASON_NO_CSRF_COOKIE)208                    else:209                        logger.warning('Forbidden (%s): %s' % (REASON_BAD_TOKEN, request.path),210                            extra={211                                'status_code': 403,212                                'request': request,213                            }214                        )215                        return self._reject(request, REASON_BAD_TOKEN)216            return self._accept(request)217csrf_protect = decorator_from_middleware(CsrfViewMiddleware)218csrf_protect.__name__ = "csrf_protect"219csrf_protect.__doc__ = """220This decorator adds CSRF protection in exactly the same way as221CsrfViewMiddleware, but it can be used on a per view basis.  Using both, or222using the decorator multiple times, is harmless and efficient....fence.py
Source:fence.py  
...67      self._current_offset = node.col_offset68  def _allow_and_continue(self, node):69    self._track_location(node)70    self.generic_visit(node)71  def _reject(self, node, msg):72    self._track_location(node)73    self._raise_error(msg)74  def visit_Module(self, node):75    self._visited_top_module = True76    self._allow_and_continue(node)77  def visit_Num(self, node):78    self._allow_and_continue(node)79  def visit_Str(self, node):80    self._allow_and_continue(node)81  def visit_FormattedValue(self, node):82    self._reject(node, 'F-Strings are not supported')83  def visit_JoinedStr(self, node):84    self._reject(node, 'F-Strings are not supported')85  def visit_Bytes(self, node):86    self._reject(node, 'Byte Literals are not supported')87  def visit_List(self, node):88    self._allow_and_continue(node)89  def visit_Tuple(self, node):90    # TODO: Make sure none of the original functionality was lost.91    self._allow_and_continue(node)92  def visit_Set(self, node):93    self._reject(node, 'Sets not are supported')94  def visit_Dict(self, node):95    self._allow_and_continue(node)96  def visit_Ellipsis(self, node):97    self._allow_and_continue(node)98  def visit_NameConstant(self, node):99    self._allow_and_continue(node)100  def visit_Name(self, node):101    self._allow_and_continue(node)102  def visit_Load(self, node):103    self._allow_and_continue(node)104  def visit_Store(self, node):105    self._allow_and_continue(node)106  def visit_Del(self, node):107    self._reject(node, 'Deleting variables is not supported')108  def visit_Starred(self, node):109    self._reject(node, 'Unpackings are not supported')110  def visit_Expr(self, node):111    self._allow_and_continue(node)112  def visit_UnaryOp(self, node):113    self._allow_and_continue(node)114  def visit_UAdd(self, node):115    self._reject(node, 'Unary Add operator is not supported')116  def visit_USub(self, node):117    self._allow_and_continue(node)118  def visit_Not(self, node):119    self._reject(node, 'Not operator is not supported')120  def visit_Invert(self, node):121    self._reject(node, 'Invert operator is not supported')122  def visit_BinOp(self, node):123    self._allow_and_continue(node)124  def visit_Add(self, node):125    self._allow_and_continue(node)126  def visit_Sub(self, node):127    self._allow_and_continue(node)128  def visit_Mult(self, node):129    self._allow_and_continue(node)130  def visit_Div(self, node):131    self._allow_and_continue(node)132  def visit_FloorDiv(self, node):133    self._reject(node, 'Floor Div operator is not supported')134  def visit_Mod(self, node):135    self._allow_and_continue(node)136  def visit_Pow(self, node):137    self._allow_and_continue(node)138  def visit_LShift(self, node):139    self._reject(node, 'Left Shift operator is not supported')140  def visit_RShift(self, node):141    self._reject(node, 'Right Shift operator is not supported')142  def visit_BitOr(self, node):143    self._reject(node, 'Bitwise Or operator is not supported')144  def visit_BitXor(self, node):145    self._reject(node, 'Bitwise Xor operator is not supported')146  def visit_BitAnd(self, node):147    self._reject(node, 'Bitwise And operator is not supported')148  def visit_MatMult(self, node):149    # TODO: Add support for this.150    self._reject(node, 'MatMult operator is not supported')151  def visit_BoolOp(self, node):152    self._allow_and_continue(node)153  def visit_And(self, node):154    self._allow_and_continue(node)155  def visit_Or(self, node):156    self._allow_and_continue(node)157  def visit_Compare(self, node):158    self._allow_and_continue(node)159  def visit_Eq(self, node):160    self._allow_and_continue(node)161  def visit_NotEq(self, node):162    self._allow_and_continue(node)163  def visit_Lt(self, node):164    self._allow_and_continue(node)165  def visit_LtE(self, node):166    self._allow_and_continue(node)167  def visit_Gt(self, node):168    self._allow_and_continue(node)169  def visit_GtE(self, node):170    self._allow_and_continue(node)171  def visit_Is(self, node):172    self._allow_and_continue(node)173  def visit_IsNot(self, node):174    self._allow_and_continue(node)175  def visit_In(self, node):176    self._reject(node, 'In operator is not supported')177  def visit_NotIn(self, node):178    self._reject(node, 'Not In operator is not supported')179  def visit_Call(self, node):180    self._allow_and_continue(node)181  def visit_keyword(self, node):182    self._allow_and_continue(node)183  def visit_IfExp(self, node):184    self._reject(node, 'Conditional Expressions are not supported')185  def visit_Attribute(self, node):186    self._allow_and_continue(node)187  def visit_Subscript(self, node):188    self._allow_and_continue(node)189  def visit_Index(self, node):190    self._allow_and_continue(node)191  def visit_Slice(self, node):192    self._allow_and_continue(node)193  def visit_ExtSlice(self, node):194    self._allow_and_continue(node)195  def visit_ListComp(self, node):196    self._allow_and_continue(node)197  def visit_SetComp(self, node):198    self._reject(node, 'Set Comprehensions are not supported')199  def visit_GeneratorExp(self, node):200    self._reject(node, 'Generator Expressions are not supported')201  def visit_DictComp(self, node):202    self._reject(node, 'Dictionary Comprehensions are not supported')203  def visit_comprehension(self, node):204    self._allow_and_continue(node)205  def visit_Assign(self, node):206    self._allow_and_continue(node)207  def visit_AnnAssign(self, node):208    self._reject(node, 'Type-annotated assignment are not supported')209  def visit_AugAssign(self, node):210    self._allow_and_continue(node)211  def visit_Print(self, node):212    self._allow_and_continue(node)213  def visit_Raise(self, node):214    self._allow_and_continue(node)215  def visit_Assert(self, node):216    if __debug__:217      self._allow_and_continue(node)218    else:219      assert False, 'Assert statements should not appear in optimized code'220  def visit_Delete(self, node):221    self._reject(node, 'Delete statements are not supported')222  def visit_Pass(self, node):223    self._allow_and_continue(node)224  def visit_Import(self, node):225    self._reject(node, 'Import statements are not supported')226  def visit_ImportFrom(self, node):227    self._reject(node, 'Import/From statements are not supported')228  def visit_alias(self, node):229    self._reject(node, 'Aliases are not supported')230  def visit_If(self, node):231    self._allow_and_continue(node)232  def visit_For(self, node):233    if node.orelse:234      self._reject(node, 'For/Else block is not supported')235    else:236      self._allow_and_continue(node)237  def visit_While(self, node):238    self._allow_and_continue(node)239  def visit_Break(self, node):240    if self._strict:241      self._reject(node, 'Break statements are not supported in strict mode')242    else:243      self._allow_and_continue(node)244  def visit_Continue(self, node):245    self._reject(node, 'Continue statements are not supported')246  def visit_Try(self, node):247    self._allow_and_continue(node)248  def visit_TryFinally(self, node):249    self._reject(node, 'Try/Finally blocks are not supported')250  def visit_TryExcept(self, node):251    self._reject(node, 'Try/Except blocks are not supported')252  def visit_ExceptHandler(self, node):253    self._allow_and_continue(node)254  def visit_With(self, node):255    self._allow_and_continue(node)256  def visit_withitem(self, node):257    self._allow_and_continue(node)258  def visit_FunctionDef(self, node):259    self._allow_and_continue(node)260  def visit_Lambda(self, node):261    self._reject(node, 'Lambda functions are not supported')262  def visit_arguments(self, node):263    self._allow_and_continue(node)264  def visit_arg(self, node):265    self._allow_and_continue(node)266  def visit_Return(self, node):267    # TODO: Make sure none of the original functionality was lost.268    self._allow_and_continue(node)269  def visit_Yield(self, node):270    self._reject(node, 'Yield statements are not supported')271  def visit_YieldFrom(self, node):272    self._reject(node, 'Yield/From statements are not supported')273  def visit_Global(self, node):274    self._reject(node, 'Global statements are not supported')275  def visit_Nonlocal(self, node):276    self._reject(node, 'Nonlocal statements are not supported')277  def visit_ClassDef(self, node):278    self._reject(node, 'Classes are not supported')279  def visit_AsyncFunctionDef(self, node):280    self._reject(node, 'Async function definitions are not supported')281  def visit_Await(self, node):282    self._reject(node, 'Await statements are not supported')283  def visit_AsyncFor(self, node):284    self._reject(node, 'Async For loops are not supported')285  def visit_AsyncWith(self, node):...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
