How to use sizes method in Playwright Internal

Best JavaScript code snippet using playwright-internal

picture.py

Source:picture.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import os3ccdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))4template = """<!DOCTYPE html>5<meta charset=utf-8>6"""7errors = {8 # missing src on img9 "img-no-src": "<img alt>",10 "img-no-src-with-srcset": "<img srcset=x alt>",11 "img-no-src-with-picture": "<picture><img alt></picture>",12 "img-no-src-with-srcset-and-picture": "<picture><img srcset=x alt></picture>",13 "img-no-src-with-source": "<picture><source srcset=x><img alt></picture>",14 # junk content in picture15 "junk-text-before-img": "<picture>x<img src=x alt></picture>",16 "junk-text-after-img": "<picture><img src=x alt>x</picture>",17 "junk-text-before-source": "<picture>x<source srcset=x><img src=x alt></picture>",18 "junk-text-after-source": "<picture><source srcset=x>x<img src=x alt></picture>",19 "junk-br-before-img": "<picture><br><img src=x alt></picture>",20 "junk-br-after-img": "<picture><img src=x alt><br></picture>",21 "junk-br-before-source": "<picture><br><source srcset=x><img src=x alt></picture>",22 "junk-br-after-source": "<picture><source srcset=x><br><img src=x alt></picture>",23 "junk-video-before": "<picture><video></video><source srcset=x><img src=x alt></picture>",24 "junk-video-no-img": "<picture><video></video></picture>",25 "junk-p-before": "<picture><p></p><source srcset=x><img src=x alt></picture>",26 "junk-p-after": "<picture><source srcset=x><img src=x alt><p></p></picture>",27 "junk-p-wrapping": "<picture><p><source srcset=x><img src=x alt></p></picture>",28 "junk-span-before": "<picture><span></span><source srcset=x><img src=x alt></picture>",29 "junk-span-after": "<picture><source srcset=x><img src=x alt><span></span></picture>",30 "junk-span-wrapping": "<picture><span><source srcset=x><img src=x alt></span></picture>",31 "junk-picture-before": "<picture><picture><img src=x alt></picture><img src=x alt></picture>",32 "junk-picture-wrapping": "<picture><picture><img src=x alt></picture></picture>",33 "junk-figure-wrapping": "<picture><figure><img src=x alt></figure></picture>",34 "junk-input-type-hidden": "<picture><input type=hidden name=x value=x><img src=x alt></picture>",35 "junk-style-scroped": "<picture><style scroped></style><img src=x alt></picture>",36 "junk-noscript": "<picture><img src=x alt><noscript></noscript></picture>",37 "junk-noscript-after-source-no-img": "<picture><source srcset=x><noscript><img src=x alt></noscript></picture>",38 "junk-svg": "<picture><img src=x alt><svg></svg></picture>",39 "junk-svg-no-img": "<picture><svg></svg></picture>",40 "junk-math-nog-img": "<picture><math></math></picture>",41 # parents42 "parent-ul": "<ul><picture><img src=x alt></picture></ul>",43 "parent-dl": "<dl><picture><img src=x alt></picture></dl>",44 "parent-hgroup": "<hgroup><h1>x</h1><picture><img src=x alt></picture></hgroup>",45 "parent-noscript-in-head": "<noscript><picture><img src=x alt></picture></noscript>",46 # invalid html syntax47 "html-syntax-source-end-tag": "<picture><source srcset=x></source><img src=x alt></picture>",48 "html-syntax-img-end-tag": "<picture><img src=x alt></img></picture>",49 "html-syntax-picture-no-end-tag": "<picture><img src=x alt>",50 "html-syntax-picture-slash": "<picture/><img src=x alt></picture>",51 "html-syntax-picture-slash-no-end-tag": "<picture/><img src=x alt>",52 # missing img in picture53 "missing-img-empty-picture": "<picture></picture>",54 "missing-img-only-source": "<picture><source srcset=x></picture>",55 "missing-img-only-script": "<picture><script></script></picture>",56 "missing-img-script-and-source": "<picture><script></script><source srcset=x></picture>",57 "missing-img-source-and-script": "<picture><source srcset=x><script></script></picture>",58 # multiple img in picture59 "multiple-img": "<picture><img src=x alt><img src=x alt></picture>",60 "multiple-img-with-script": "<picture><img src=x alt><script></script><img src=x alt></picture>",61 "multiple-img-with-source": "<picture><source srcset=x><img src=x alt><img src=x alt></picture>",62 "multiple-img-with-source-and-script": "<picture><source srcset=x><img src=x alt><script></script><img src=x alt></picture>",63 # source after img64 "source-after-img": "<picture><img src=x alt><source srcset=x></picture>",65 "source-before-and-after-img": "<picture><source srcset=x><img src=x alt><source srcset=x></picture>",66 # source with following sibling source element or img element with a srcset attribute67 "always-matching-source-with-following-img-srcset": "<picture><source srcset=x><img src=x srcset=x alt></picture>",68 "always-matching-source-with-following-source-srcset": "<picture><source srcset=x><source srcset=x><img src=x alt></picture>",69 "always-matching-source-with-following-source-media": "<picture><source srcset=x><source srcset=x media=screen><img src=x alt></picture>",70 "always-matching-source-with-following-source-type": "<picture><source srcset=x><source srcset=x type=image/gif><img src=x alt></picture>",71 "always-matching-source-media-empty-with-following-source-srcset": "<picture><source srcset=x media><source srcset=x><img src=x alt></picture>",72 "always-matching-source-media-spaces-with-following-source-srcset": "<picture><source srcset=x media=' \n\t'><source srcset=x><img src=x alt></picture>",73 "always-matching-source-media-all-with-following-source-srcset": "<picture><source srcset=x media=all><source srcset=x><img src=x alt></picture>",74 "always-matching-source-media-uppercase-with-following-source-srcset": "<picture><source srcset=x media=ALL><source srcset=x><img src=x alt></picture>",75 "always-matching-source-media-all-spaces-with-following-source-srcset": "<picture><source srcset=x media=' all '><source srcset=x><img src=x alt></picture>",76 "always-matching-source-sizes-with-following-source-srcset": "<picture><source srcset='x 100w' sizes=50vw><source srcset=x><img src=x alt></picture>",77 # sizes present78 "img-srcset-no-descriptor-with-sizes": "<img src=x srcset='x' sizes=50vw alt>",79 "img-srcset-w-and-x-width-sizes": "<img src=x srcset='x 100w, y 2x' sizes=50vw alt>",80 "source-srcset-x-with-sizes": "<picture><source srcset='x 1x, y 2x' sizes=50vw><img src=x alt></picture>",81 "source-srcset-h-with-sizes": "<picture><source srcset='x 100h, y 200h' sizes=50vw><img src=x alt></picture>",82 "source-srcset-w-and-x-with-sizes": "<picture><source srcset='x 100w, y 2x' sizes=50vw><img src=x alt></picture>",83 "img-with-sizes-no-srcset": "<img sizes=50vw src=foo alt>",84 # width descriptor without sizes85 "img-srcset-w-no-sizes": "<img srcset='x 100w, y 200w' src=x alt>",86 "source-srcset-w-no-sizes": "<picture><source srcset='x 100w, y 200w'><img src=x alt></picture>",87 "source-type-srcset-w": "<picture><source srcset='x 100w, y 200w' type=image/gif><img src=x alt></picture>",88 # invalid attributes on source89 "source-src": "<picture><source src=x><img src=x alt></picture>",90 "source-src-srcset": "<picture><source src=x srcset=x><img src=x alt></picture>",91 "source-alt": "<picture><source srcset=x alt><img src=x alt></picture>",92 "source-width": "<picture><source srcset=x width=100><img src=x alt></picture>",93 "source-height": "<picture><source srcset=x height=100><img src=x alt></picture>",94 "source-usemap": "<picture><source srcset=x usemap><img src=x alt></picture>",95 "source-ismap": "<picture><source srcset=x ismap><img src=x alt></picture>",96 "source-crossorigin": "<picture><source srcset=x crossorigin><img src=x alt></picture>",97 "source-name": "<picture><source srcset=x crossorigin><img src=x alt></picture>",98 "source-align": "<picture><source srcset=x align=left><img src=x alt></picture>",99 "source-hspace": "<picture><source srcset=x hspace=1><img src=x alt></picture>",100 "source-vspace": "<picture><source srcset=x vspace=1><img src=x alt></picture>",101 "source-longdesc": "<picture><source srcset=x longdesc=x><img src=x alt></picture>",102 "source-border": "<picture><source srcset=x border=1><img src=x alt></picture>",103 # missing srcset on source104 "source-no-srcset": "<picture><source><img src=x alt></picture>",105 "source-no-srcset-with-sizes": "<picture><source sizes=50vw><img src=x alt></picture>",106 "source-no-srcset-with-media": "<picture><source media=screen><img src=x alt></picture>",107 "source-no-srcset-with-type": "<picture><source type='image/webp'><img src=x alt></picture>",108 # invalid attributes on picture109 "picture-src": "<picture src=x><img src=x alt></picture>",110 "picture-srcset": "<picture srcset=x><img src=x alt></picture>",111 "picture-media": "<picture media=screen><img src=x alt></picture>",112 "picture-sizes": "<picture sizes=50vw><img src=x alt></picture>",113 "picture-alt": "<picture alt><img src=x alt></picture>",114 "picture-width": "<picture width=100><img src=x alt></picture>",115 "picture-height": "<picture height=100><img src=x alt></picture>",116 "picture-usemap": "<picture usemap><img src=x alt></picture>",117 "picture-ismap": "<picture ismap><img src=x alt></picture>",118 "picture-crossorigin": "<picture crossorigin><img src=x alt></picture>",119 "picture-name": "<picture name=x><img src=x alt></picture>",120 "picture-lowsrc": "<picture lowsrc=x><img src=x alt></picture>",121 "picture-align": "<picture align=left><img src=x alt></picture>",122 "picture-hspace": "<picture hspace=1><img src=x alt></picture>",123 "picture-vspace": "<picture vspace=1><img src=x alt></picture>",124 "picture-longdesc": "<picture longdesc=x><img src=x alt></picture>",125 "picture-border": "<picture border=1><img src=x alt></picture>",126 # invalid attributes on source in video127 "video-source-srcset": "<video><source srcset=x></video>",128 "video-source-srcset-src": "<video><source srcset=x src=x></video>",129 "video-source-sizes-srcset": "<video><source sizes=50vw srcset='x 100w'></video>",130 "video-source-media-src": "<video><source media=screen src=x></video>",131 # srcset on other elements132 "link-rel-icon-srcset": "<link rel=icon srcset=x href=x>",133 "input-type-image-srcset": "<input type=image src=x srcset=x alt=x>",134 "object-srcset": "<object data=x srcset=x></object>",135 "video-srcset": "<video src=x srcset=x></video>",136 "audio-srcset": "<audio src=x srcset=x></audio>",137 "track-srcset": "<video src=x><track src=x srcset=x></video>",138 "svg-image-srcset": "<svg><image xlink:href=x srcset=x width=1 height=1 /></svg>",139 # invalid attributes on img140 "img-type": "<img src=x type=image/gif alt>",141 "img-type-with-picture": "<picture><img src=x type=image/gif alt></picture>",142 # sizes microsyntax143 "sizes-microsyntax-media-all": "<img sizes='all 500px, 100vw' srcset='x 100w, y 200w' src=x alt>",144 "sizes-microsyntax-media-all-and-min-width": "<img sizes='all and (min-width:500px) 500px, 100vw' srcset='x 100w, y 200w' src=x alt>",145 "sizes-microsyntax-media-min-width-no-parenthesis": "<img sizes='min-width:500px 500px, 100vw' srcset='x 100w, y 200w' src=x alt>",146 "sizes-microsyntax-media-general-enclosed-junk": "<img sizes='(123) 500px, 100vw' srcset='x 100w, y 200w' src=x alt>",147 "sizes-microsyntax-media-bad-junk": "<img sizes='(}) 500px, 100vw' srcset='x 100w, y 200w' src=x alt>",148 "sizes-microsyntax-two-defaults": "<img sizes='500px, 100vw' srcset='x 100w, y 200w' src=x alt>",149 "sizes-microsyntax-default-first": "<img sizes='100vw, (min-width:500px) 500px' srcset='x 100w, y 200w' src=x alt>",150 "sizes-microsyntax-trailing-comma": "<img sizes='(min-width:500px) 500px, 100vw,' srcset='x 100w, y 200w' src=x alt>",151 "sizes-microsyntax-trailing-junk": "<img sizes='(min-width:500px) 500px, 100vw, foo bar' srcset='x 100w, y 200w' src=x alt>",152 "sizes-microsyntax-junk-in-default": "<img sizes='(min-width:500px) 500px, 100vw foo bar' srcset='x 100w, y 200w' src=x alt>",153 "sizes-microsyntax-junk-in-source-size": "<img sizes='(min-width:500px) 500px foo bar, 100vw' srcset='x 100w, y 200w' src=x alt>",154 "sizes-microsyntax-percent-in-source-size-value": "<img sizes='(min-width:500px) 50%, 100vw' srcset='x 100w, y 200w' src=x alt>",155 "sizes-microsyntax-no-unit-in-source-size-value": "<img sizes='(min-width:500px) 50, 100vw' srcset='x 100w, y 200w' src=x alt>",156 "sizes-microsyntax-deg-source-size-value": "<img sizes='1deg' srcset='x 100w, y 200w' src=x alt>",157 "sizes-microsyntax-grad-source-size-value": "<img sizes='1grad' srcset='x 100w, y 200w' src=x alt>",158 "sizes-microsyntax-rad-source-size-value": "<img sizes='1rad' srcset='x 100w, y 200w' src=x alt>",159 "sizes-microsyntax-turn-source-size-value": "<img sizes='1turn' srcset='x 100w, y 200w' src=x alt>",160 "sizes-microsyntax-s-source-size-value": "<img sizes='1s' srcset='x 100w, y 200w' src=x alt>",161 "sizes-microsyntax-ms-source-size-value": "<img sizes='1ms' srcset='x 100w, y 200w' src=x alt>",162 "sizes-microsyntax-hz-source-size-value": "<img sizes='1Hz' srcset='x 100w, y 200w' src=x alt>",163 "sizes-microsyntax-khz-source-size-value": "<img sizes='1kHz' srcset='x 100w, y 200w' src=x alt>",164 "sizes-microsyntax-dpi-source-size-value": "<img sizes='1dpi' srcset='x 100w, y 200w' src=x alt>",165 "sizes-microsyntax-dpcm-source-size-value": "<img sizes='1dpcm' srcset='x 100w, y 200w' src=x alt>",166 "sizes-microsyntax-dppx-source-size-value": "<img sizes='1dppx' srcset='x 100w, y 200w' src=x alt>",167 "sizes-microsyntax-auto-source-size-value": "<img sizes='auto' srcset='x 100w, y 200w' src=x alt>",168 "sizes-microsyntax-inherit-source-size-value": "<img sizes='inherit' srcset='x 100w, y 200w' src=x alt>",169 "sizes-microsyntax-initial-source-size-value": "<img sizes='initial' srcset='x 100w, y 200w' src=x alt>",170 "sizes-microsyntax-default-source-size-value": "<img sizes='default' srcset='x 100w, y 200w' src=x alt>",171 "sizes-microsyntax-foo-bar-source-size-value": "<img sizes='foo-bar' srcset='x 100w, y 200w' src=x alt>",172 "sizes-microsyntax-negative-source-size-value": "<img sizes='-1px' srcset='x 100w, y 200w' src=x alt>",173 "sizes-microsyntax-empty": "<img sizes='' srcset='x 100w, y 200w' src=x alt>",174 "sizes-microsyntax-comma": "<img sizes=',' srcset='x 100w, y 200w' src=x alt>",175 "sizes-microsyntax-css-comment-after-plus": "<img sizes='+/**/50vw' srcset='x 100w, y 200w' src=x alt>",176 "sizes-microsyntax-css-comment-before-unit": "<img sizes='50/**/vw' srcset='x 100w, y 200w' src=x alt>",177 "sizes-microsyntax-scientific-notation-negative": "<img sizes='-1e+0px' srcset='x 100w, y 200w' src=x alt>",178 "sizes-microsyntax-scientific-notation-non-integer-in-exponent": "<img sizes='1e+1.5px' srcset='x 100w, y 200w' src=x alt>",179 # srcset microsyntax180 "srcset-microsyntax-leading-comma": "<img srcset=',x' src=x alt>",181 "srcset-microsyntax-leading-comma-multiple": "<img srcset=',,,x' src=x alt>",182 "srcset-microsyntax-trailing-comma": "<img srcset='x,' src=x alt>",183 "srcset-microsyntax-trailing-comma-multiple": "<img srcset='x,,,' src=x alt>",184 "srcset-microsyntax-broken-url": "<img srcset='http: 1x' src=x alt>",185 "srcset-microsyntax-non-integer-w": "<img srcset='x 1.5w' sizes=100vw src=x alt>",186 "srcset-microsyntax-uppercase-w": "<img srcset='x 1W' sizes=100vw src=x alt>",187 "srcset-microsyntax-plus-w": "<img srcset='x +1w' sizes=100vw src=x alt>",188 "srcset-microsyntax-scientific-notation-w": "<img srcset='x 1e0w' sizes=100vw src=x alt>",189 "srcset-microsyntax-zero-w": "<img srcset='x 0w' sizes=100vw src=x alt>",190 "srcset-microsyntax-negative-zero-w": "<img srcset='x -0w' sizes=100vw src=x alt>",191 "srcset-microsyntax-negative-w": "<img srcset='x -1w' sizes=100vw src=x alt>",192 "srcset-microsyntax-plus-x": "<img srcset='x +1x' src=x alt>",193 "srcset-microsyntax-negative-x": "<img srcset='x -1x' src=x alt>",194 "srcset-microsyntax-zero-x": "<img srcset='x 0x' src=x alt>",195 "srcset-microsyntax-negative-zero-x": "<img srcset='x -0x' src=x alt>",196 "srcset-microsyntax-leading-dot-x": "<img srcset='x .5x' src=x alt>",197 "srcset-microsyntax-nan-x": "<img srcset='x NaNx' src=x alt>",198 "srcset-microsyntax-infinity-x": "<img srcset='x Infinityx' src=x alt>",199 "srcset-microsyntax-x-and-w": "<img srcset='x 1x 1w' sizes=100vw src=x alt>",200 "srcset-microsyntax-x-and-h": "<img srcset='x 1x 1h' sizes=100vw src=x alt>",201 "srcset-microsyntax-w-and-h": "<img srcset='x 1w 1h' sizes=100vw src=x alt>",202 "srcset-microsyntax-h": "<img srcset='x 1h' sizes=100vw src=x alt>",203 "srcset-microsyntax-function": "<img srcset='x foobar(baz quux, lol), y 1x' src=x alt>",204 "srcset-microsyntax-parenthesis-junk": "<img srcset='x ><(((((o)>, y 1x' src=x alt>",205 "srcset-microsyntax-square-bracket-junk": "<img srcset='x [, y 1x' src=x alt>",206 "srcset-microsyntax-curly-bracket-junk": "<img srcset='x {, y 1x' src=x alt>",207 "srcset-microsyntax-pipe-junk": "<img srcset='x ||, y 1x' src=x alt>",208 "srcset-microsyntax-w-and-no-descriptor": "<img srcset='x 1w, y' sizes=100vw src=x alt>",209 "srcset-microsyntax-unique-descriptors-1x-and-omitted": "<img srcset='x 1x, y' src=x alt>",210 "srcset-microsyntax-unique-descriptors-2x": "<img srcset='x 2x, y 2x' src=x alt>",211 "srcset-microsyntax-unique-descriptors-integer-and-decimals-x": "<img srcset='x 1x, y 1.0x' src=x alt>",212 "srcset-microsyntax-unique-descriptors-w": "<img srcset='x 1w, y 1w' sizes=100vw src=x alt>",213 "srcset-microsyntax-empty": "<img srcset='' src=x alt>",214 "srcset-microsyntax-comma": "<img srcset=',' src=x alt>",215 "srcset-microsyntax-css-comment-after-descriptor": "<img srcset='x 2x/**/' src=x alt>",216 # aria217 "picture-aria-role-img": "<picture role=img><img src=x alt></picture>",218 "picture-aria-role-button": "<picture role=button><img src=x alt></picture>",219 "picture-aria-role-region": "<picture role=region><img src=x alt></picture>",220 "picture-aria-role-application": "<picture role=application><img src=x alt></picture>",221 "source-aria-role-img": "<picture><source role=img srcset=x><img src=x alt></picture>",222 "picture-aria-role-presentation": "<picture role=presentation><img src=x alt></picture>",223 "source-aria-role-presentation": "<picture><source role=presentation srcset=x><img src=x alt></picture>",224}225non_errors_in_head = {226 "parent-template-in-head": "<template><picture><img src=x alt></picture></template>",227}228non_errors = {229 # basic230 "basic-img-src": "<img src=x alt>",231 "basic-picture-img-src": "<picture><img src=x alt></picture>",232 "basic-picture-source": "<picture><source srcset=x><img src=x alt></picture>",233 # inter-element whitespace234 "inter-element-whitespace": "<picture> <!--x--> <source srcset=x> <!--x--> <img src=x alt> <!--x--> </picture>",235 # parents236 "parent-p": "<p><picture><img src=x alt></picture></p>",237 "parent-h1": "<h1><picture><img src=x alt=x></picture></h1>",238 "parent-noscript-in-body": "<noscript><picture><img src=x alt></picture></noscript>",239 "parent-object": "<object data=x><picture><img src=x alt></picture></object>",240 "parent-video": "<video src=x><picture><img src=x alt></picture></video>",241 "parent-section": "<section><h2>x</h2><picture><img src=x alt></picture></section>",242 "parent-main": "<main><picture><img src=x alt></picture></main>",243 "parent-canvas": "<canvas><picture><img src=x alt></picture></canvas>",244 "parent-template-in-body": "<template><picture><img src=x alt></picture></template>",245 "parent-ruby": "<ruby><picture><img src=x alt></picture><rt>x</rt></ruby>",246 "parent-rt": "<ruby>x<rt><picture><img src=x alt></picture></rt></ruby>",247 "parent-rp": "<ruby>x<rp><picture><img src=x alt></picture></rp><rt>x</rt><rp>x</rp></ruby>",248 "parent-a": "<a href=x><picture><img src=x alt></picture></a>",249 "parent-button": "<button><picture><img src=x alt></picture></button>",250 "parent-td": "<table><tr><td><picture><img src=x alt></picture></table>",251 # script-supporting elements252 "script-first": "<picture><script></script><source srcset=x><img src=x alt></picture>",253 "template-first": "<picture><template></template><source srcset=x><img src=x alt></picture>",254 "script-between": "<picture><source srcset=x><script></script><img src=x alt></picture>",255 "script-after": "<picture><source srcset=x><img src=x alt><script></script></picture>",256 "script-before-after": "<picture><script></script><source srcset=x><img src=x alt><script></script></picture>",257 "script-before-between-after": "<picture><script></script><source srcset=x><script></script><img src=x alt><script></script></picture>",258 "script-and-template": "<picture><template></template><source srcset=x><script></script><img src=x alt><template></template></picture>",259 # source with following sibling source element or img element with a srcset attribute260 "source-with-media-img-with-srcset": "<picture><source srcset=x media=screen><img src=x srcset=x alt></picture>",261 "source-with-media-uppercase-img-with-srcset": "<picture><source srcset=x media=SCREEN><img src=x srcset=x alt></picture>",262 "source-with-media-spaces-img-with-srcset": "<picture><source srcset=x media=' \n\tscreen \n\t'><img src=x srcset=x alt></picture>",263 "source-with-media-source-with-srcset": "<picture><source srcset=x media=screen><source srcset=x><img src=x alt></picture>",264 "source-with-type-img-with-srcset": "<picture><source srcset=x type=image/gif><img src=x srcset=x alt></picture>",265 "source-with-type-source-with-srcset": "<picture><source srcset=x type=image/gif><source srcset=x><img src=x alt></picture>",266 # sizes present267 "img-with-sizes": "<img srcset='x 100w, y 200w' sizes=50vw src=x alt>",268 "source-with-sizes": "<picture><source srcset='x 100w, y 200w' sizes=50vw><img src=x alt></picture>",269 # embed allows any attributes270 "embed-srcset-empty": "<embed srcset>",271 "embed-srcset-junk": "<embed srcset='foo bar'>",272 "embed-sizes-empty": "<embed sizes>",273 "embed-sizes-junk": "<embed sizes='foo bar'>",274 # img src also in srcset275 "img-src-also-in-srcset-1x": "<img src=x srcset='x 1x, y 2x' alt>",276 "img-src-also-in-srcset-2x": "<img src=x srcset='y 1x, x 2x' alt>",277 "img-src-also-in-srcset-w": "<img src=x srcset='x 100w, y 200w' sizes=100vw alt>",278 # img src not in srcset279 "img-src-not-in-srcset-x": "<img src=x srcset='y 1x, z 2x' alt>",280 "img-src-not-in-srcset-w": "<img src=x srcset='y 100w, z 200w' sizes=100vw alt>",281 # source type282 "source-type": "<picture><source srcset=x type=image/gif><img src=x alt></picture>",283 "source-type-srcset-x": "<picture><source srcset='x 1x, y 2x' type=image/gif><img src=x alt></picture>",284 "source-type-srcset-w-sizes": "<picture><source srcset='x 100w, y 200w' type=image/gif sizes=50vw><img src=x alt></picture>",285 # sizes microsyntax286 "sizes-microsyntax-media-min-width": "<img sizes='(min-width:500px) 500px, 100vw' srcset='x 100w, y 200w' src=x alt>",287 "sizes-microsyntax-multiple-source-sizes": "<img sizes='(min-width:1500px) 500px, (min-width:1000px) 33vw, (min-width:500px) 50vw, 100vw' srcset='x 100w, y 200w' src=x alt>",288 "sizes-microsyntax-no-default": "<img sizes='(min-width:500px) 500px' srcset='x 100w, y 200w' src=x alt>",289 "sizes-microsyntax-media-not-and": "<img sizes='not (width:500px) and (width:500px) 500px' srcset='x 100w, y 200w' src=x alt>",290 "sizes-microsyntax-only-default": "<img sizes='500px' srcset='x 100w, y 200w' src=x alt>",291 "sizes-microsyntax-calc-in-default": "<img sizes='calc(500px)' srcset='x 100w, y 200w' src=x alt>",292 "sizes-microsyntax-calc-in-source-size-value": "<img sizes='(min-width:500px) calc(500px)' srcset='x 100w, y 200w' src=x alt>",293 "sizes-microsyntax-calc-in-media": "<img sizes='(min-width:calc(500px)) 500px' srcset='x 100w, y 200w' src=x alt>",294 "sizes-microsyntax-zero": "<img sizes='0' srcset='x 100w, y 200w' src=x alt>",295 "sizes-microsyntax-minus-zero": "<img sizes='-0' srcset='x 100w, y 200w' src=x alt>",296 "sizes-microsyntax-em-in-source-size-value": "<img sizes='1em' srcset='x 100w, y 200w' src=x alt>",297 "sizes-microsyntax-ex-in-source-size-value": "<img sizes='1ex' srcset='x 100w, y 200w' src=x alt>",298 "sizes-microsyntax-ch-in-source-size-value": "<img sizes='1ch' srcset='x 100w, y 200w' src=x alt>",299 "sizes-microsyntax-rem-in-source-size-value": "<img sizes='1rem' srcset='x 100w, y 200w' src=x alt>",300 "sizes-microsyntax-vw-in-source-size-value": "<img sizes='1vw' srcset='x 100w, y 200w' src=x alt>",301 "sizes-microsyntax-vh-in-source-size-value": "<img sizes='1vh' srcset='x 100w, y 200w' src=x alt>",302 "sizes-microsyntax-vmin-in-source-size-value": "<img sizes='1vmin' srcset='x 100w, y 200w' src=x alt>",303 "sizes-microsyntax-vmax-in-source-size-value": "<img sizes='1vmax' srcset='x 100w, y 200w' src=x alt>",304 "sizes-microsyntax-cm-in-source-size-value": "<img sizes='1cm' srcset='x 100w, y 200w' src=x alt>",305 "sizes-microsyntax-mm-in-source-size-value": "<img sizes='1mm' srcset='x 100w, y 200w' src=x alt>",306 "sizes-microsyntax-q-in-source-size-value": "<img sizes='1q' srcset='x 100w, y 200w' src=x alt>",307 "sizes-microsyntax-in-in-source-size-value": "<img sizes='1in' srcset='x 100w, y 200w' src=x alt>",308 "sizes-microsyntax-pc-in-source-size-value": "<img sizes='1pc' srcset='x 100w, y 200w' src=x alt>",309 "sizes-microsyntax-pt-in-source-size-value": "<img sizes='1pt' srcset='x 100w, y 200w' src=x alt>",310 "sizes-microsyntax-px-in-source-size-value": "<img sizes='1px' srcset='x 100w, y 200w' src=x alt>",311 "sizes-microsyntax-non-integer-px-in-source-size-value": "<img sizes='0.2px' srcset='x 100w, y 200w' src=x alt>",312 "sizes-microsyntax-leading-css-comment": "<img sizes='/**/50vw' srcset='x 100w, y 200w' src=x alt>",313 "sizes-microsyntax-trailing-css-comment": "<img sizes='50vw/**/' srcset='x 100w, y 200w' src=x alt>",314 "sizes-microsyntax-plus": "<img sizes='+50vw' srcset='x 100w, y 200w' src=x alt>",315 "sizes-microsyntax-non-integer-omitted-zero": "<img sizes='.2px' srcset='x 100w, y 200w' src=x alt>",316 "sizes-microsyntax-scientifi-notation-0": "<img sizes='-0e-0px' srcset='x 100w, y 200w' src=x alt>",317 "sizes-microsyntax-scientifi-notation-1": "<img sizes='+11.11e+11px' srcset='x 100w, y 200w' src=x alt>",318 "sizes-microsyntax-scientifi-notation-2": "<img sizes='2.2e2px' srcset='x 100w, y 200w' src=x alt>",319 "sizes-microsyntax-scientifi-notation-3": "<img sizes='33E33px' srcset='x 100w, y 200w' src=x alt>",320 "sizes-microsyntax-scientifi-notation-4": "<img sizes='.4E4px' srcset='x 100w, y 200w' src=x alt>",321 # srcset microsyntax322 "srcset-microsyntax-comma-in-url": "<img srcset='x,x' src=x alt>",323 "srcset-microsyntax-percent-escaped-leading-comma-in-url": "<img srcset='%2Cx' src=x alt>",324 "srcset-microsyntax-percent-escaped-trailing-comma-in-url": "<img srcset='x%2C' src=x alt>",325 "srcset-microsyntax-percent-escaped-space-in-url": "<img srcset='%20' src=x alt>",326 "srcset-microsyntax-w": "<img srcset='x 1w' sizes=100vw src=x alt>",327 "srcset-microsyntax-x": "<img srcset='x 1x' src=x alt>",328 "srcset-microsyntax-non-integer-x": "<img srcset='x 1.5x' src=x alt>",329 "srcset-microsyntax-scientific-notation-x": "<img srcset='x 1e0x' src=x alt>",330 "srcset-microsyntax-scientific-notation-decimals-x": "<img srcset='x 1.5e0x' src=x alt>",331 "srcset-microsyntax-scientific-notation-e-plus-x": "<img srcset='x 1e+0x' src=x alt>",332 "srcset-microsyntax-scientific-notation-e-minus-x": "<img srcset='x 1e-0x' src=x alt>",333 "srcset-microsyntax-scientific-notation-e-uppercase-x": "<img srcset='x 1E0x' src=x alt>",334 "srcset-microsyntax-no-space-between-candidates": "<img srcset='x 1x,y 2x' src=x alt>",335 # valid attributes on img in picture336 "img-crossorigin-with-picture": "<picture><img crossorigin src=x alt></picture>",337 "img-usemap-with-picture": "<picture><img usemap=#x src=x alt></picture><map name=x></map>",338 "img-ismap-with-picture": "<a href=x><picture><img ismap src=x alt></picture></a>",339 "img-width-height-with-picture": "<picture><img src=x alt width=1 height=1></picture>",340 "img-width-height-zero-with-picture": "<picture><img src=x alt width=0 height=0></picture>",341 # global attributes on picture342 "picture-global-attributes": "<picture title=x class=x dir=ltr hidden id=asdf tabindex=0><img src=x alt></picture>",343}344for key in errors.keys():345 template_error = template346 template_error += '<title>invalid %s</title>\n' % key347 template_error += errors[key]348 file = open(os.path.join(ccdir, "html/elements/picture/%s-novalid.html" % key), 'wb')349 file.write(template_error)350 file.close()351file = open(os.path.join(ccdir, "html/elements/picture/picture-isvalid.html"), 'wb')352file.write(template + '<title>valid picture</title>\n')353for key in non_errors_in_head.keys():354 file.write('%s <!-- %s -->\n' % (non_errors_in_head[key], key))355file.write('<body>\n')356for key in non_errors.keys():357 file.write('%s <!-- %s -->\n' % (non_errors[key], key))358file.close()...

Full Screen

Full Screen

ragged_tensor_shape_test.py

Source:ragged_tensor_shape_test.py Github

copy

Full Screen

...75 expected_dim_sizes=[2, [2, 1], [2, 1, 2]]),76 ])77 def testFromTensor(self, value, expected_dim_sizes):78 shape = RaggedTensorDynamicShape.from_tensor(value)79 expected = RaggedTensorDynamicShape.from_dim_sizes(expected_dim_sizes)80 self.assertShapeEq(shape, expected)81 @parameterized.parameters([82 dict(dim_sizes=[], rank=0, expected_dim_sizes=[]),83 dict(dim_sizes=[], rank=3, expected_dim_sizes=[1, 1, 1]),84 dict(dim_sizes=[3], rank=1, expected_dim_sizes=[3]),85 dict(dim_sizes=[3], rank=3, expected_dim_sizes=[1, 1, 3]),86 dict(dim_sizes=[2, 3], rank=3, expected_dim_sizes=[1, 2, 3]),87 dict(dim_sizes=[3, [3, 2, 4]], rank=2, expected_dim_sizes=[3, [3, 2, 4]]),88 dict(89 dim_sizes=[3, [3, 2, 4]],90 rank=4,91 expected_dim_sizes=[1, 1, 3, [3, 2, 4]]),92 dict(93 dim_sizes=[3, [3, 2, 4], 2, 3],94 rank=5,95 expected_dim_sizes=[1, 3, [3, 2, 4], 2, 3]),96 ])97 def testBroadcastToRank(self, dim_sizes, rank, expected_dim_sizes):98 shape = RaggedTensorDynamicShape.from_dim_sizes(dim_sizes)99 expected = RaggedTensorDynamicShape.from_dim_sizes(expected_dim_sizes)100 broadcasted_shape = shape.broadcast_to_rank(rank)101 self.assertShapeEq(broadcasted_shape, expected)102 self.assertEqual(broadcasted_shape.rank, rank)103 @parameterized.parameters([104 #=========================================================================105 # dimension[axis] is uniform inner; and row_lengths is a scalar106 #=========================================================================107 # shape: [BROADCAST(UNIFORM), UNIFORM, UNIFORM]108 dict(axis=0,109 row_length=3,110 original_dim_sizes=[1, 4, 5],111 broadcast_dim_sizes=[3, 4, 5]),112 # shape: [UNIFORM, UNIFORM, BROADCAST(UNIFORM)]113 dict(axis=2,114 row_length=5,115 original_dim_sizes=[3, 4, 1],116 broadcast_dim_sizes=[3, 4, 5]),117 # shape: [UNIFORM, RAGGED, BROADCAST(UNIFORM)]118 dict(axis=2,119 row_length=5,120 original_dim_sizes=[3, [3, 2, 8], 1],121 broadcast_dim_sizes=[3, [3, 2, 8], 5]),122 # shape: [UNIFORM, RAGGED, RAGGED, UNIFORM, UNIFORM, BROADCAST(UNIFORM)]123 dict(axis=5,124 row_length=5,125 original_dim_sizes=[2, [2, 1], [3, 2, 8], 3, 4, 1],126 broadcast_dim_sizes=[2, [2, 1], [3, 2, 8], 3, 4, 5]),127 #=========================================================================128 # dimension[axis] is uniform inner; and row_lengths is a vector129 #=========================================================================130 # shape: [UNIFORM, BROADCAST(UNIFORM)]131 dict(axis=1,132 row_length=[2, 0, 1],133 original_dim_sizes=[3, 1],134 broadcast_dim_sizes=[3, [2, 0, 1]]),135 # shape: [UNIFORM, BROADCAST(UNIFORM), UNIFORM]136 dict(axis=1,137 row_length=[2, 0, 1],138 original_dim_sizes=[3, 1, 5],139 broadcast_dim_sizes=[3, [2, 0, 1], 5]),140 # shape: [UNIFORM, UNIFORM, BROADCAST(UNIFORM)]141 dict(axis=2,142 row_length=[2, 0, 1, 3, 8, 2, 3, 4, 1, 8, 7, 0],143 original_dim_sizes=[4, 3, 1],144 broadcast_dim_sizes=[4, 3, [2, 0, 1, 3, 8, 2, 3, 4, 1, 8, 7, 0]]),145 # shape: [UNIFORM, RAGGED, BROADCAST(UNIFORM)]146 dict(axis=2,147 row_length=[2, 5, 3],148 original_dim_sizes=[2, [2, 1], 1],149 broadcast_dim_sizes=[2, [2, 1], [2, 5, 3]]),150 # shape: [UNIFORM, RAGGED, UNIFORM, UNIFORM, BROADCAST(UNIFORM), UNIFORM]151 dict(axis=4,152 row_length=list(range(18)),153 original_dim_sizes=[2, [2, 1], 3, 2, 1, 8],154 broadcast_dim_sizes=[2, [2, 1], 3, 2, list(range(18)), 8]),155 #=========================================================================156 # dimension[axis] is uniform partitioned; and row_lengths is a scalar157 #=========================================================================158 # shape: [BROADCAST(UNIFORM), RAGGED]159 dict(axis=0,160 row_length=3,161 original_dim_sizes=[1, [5]],162 broadcast_dim_sizes=[3, [5, 5, 5]]),163 # shape: [BROADCAST(UNIFORM), UNIFORM, RAGGED]164 dict(axis=0,165 row_length=2,166 original_dim_sizes=[1, 3, [3, 0, 2]],167 broadcast_dim_sizes=[2, 3, [3, 0, 2, 3, 0, 2]]),168 # shape: [BROADCAST(UNIFORM), RAGGED, RAGGED, UNIFORM, UNIFORM]169 dict(axis=0,170 row_length=3,171 original_dim_sizes=[1, [3], [3, 5, 2], 9, 4, 5],172 broadcast_dim_sizes=[3, [3, 3, 3], [3, 5, 2, 3, 5, 2, 3, 5, 2],173 9, 4, 5]),174 # shape: [BROADCAST(UNIFORM), UNIFORM, RAGGED, UNIFORM]175 dict(axis=0,176 row_length=2,177 original_dim_sizes=[1, 2, [2, 1], [3, 5, 2], 2],178 broadcast_dim_sizes=[2, 2, [2, 1, 2, 1], [3, 5, 2, 3, 5, 2], 2]),179 # shape: [UNIFORM, BROADCAST(UNIFORM), RAGGED, UNIFORM]180 dict(axis=1,181 row_length=2,182 original_dim_sizes=[3, 1, [4, 0, 2], 5],183 broadcast_dim_sizes=[3, 2, [4, 0, 2, 4, 0, 2], 5]),184 # shape: [UNIFORM, BROADCAST(UNIFORM), RAGGED]185 dict(axis=1,186 row_length=1,187 original_dim_sizes=[2, 3, (1, 2, 3, 4, 5, 6)],188 broadcast_dim_sizes=[2, 3, (1, 2, 3, 4, 5, 6)]),189 #=========================================================================190 # dimension[axis] is uniform partitioned; and row_lengths is a vector191 #=========================================================================192 # shape: [UNIFORM, BROADCAST(UNIFORM), RAGGED, UNIFORM]193 dict(axis=1,194 row_length=[4, 1, 2],195 original_dim_sizes=[196 3, # axis=0197 1, # axis=1 (broadcast)198 [3, 1, 2], # axis=2199 5], # axis=3200 broadcast_dim_sizes=[201 3, # axis=0202 [4, 1, 2], # axis=1 (broadcast)203 [3, 3, 3, 3, 1, 2, 2], # axis=2204 5]), # axis=3205 # shape: [UNIFORM, BROADCAST(UNIFORM), RAGGED, RAGGED]206 dict(axis=1,207 row_length=[2, 0, 3],208 original_dim_sizes=[209 3, # axis=0210 1, # axis=1 (broadcast)211 [3, 1, 2], # axis=2212 [3, 1, 4, 1, 5, 9]], # axis=3213 broadcast_dim_sizes=[214 3, # axis=0215 [2, 0, 3], # axis=1 (broadcast)216 [3, 3, 2, 2, 2], # axis=2217 [3, 1, 4, 3, 1, 4, 5, 9, 5, 9, 5, 9]]), # axis=3218 # shape: [UNIFORM, RAGGED, BROADCAST(UNIFORM), RAGGED, RAGGED, UNIFORM]219 dict(axis=2,220 row_length=[4, 1, 2],221 original_dim_sizes=[222 3, # axis=0223 [2, 0, 1], # axis=1224 1, # axis=2 (broadcast)225 [3, 2, 1], # axis=3226 [1, 0, 1, 0, 2, 3], # axis=4227 5], # axis=5228 broadcast_dim_sizes=[229 3, # axis=0230 [2, 0, 1], # axis=2231 [4, 1, 2], # axis=2 (broadcast)232 [3, 3, 3, 3, 2, 1, 1], # axis=3233 [1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, # axis=4234 2, 3, 3],235 5]), # axis=5236 dict(axis=0,237 row_length=2,238 original_dim_sizes=[1, 1, 2, (2, 1)],239 broadcast_dim_sizes=[2, 1, 2, (2, 1, 2, 1)]),240 dict(axis=1,241 row_length=(2, 1),242 original_dim_sizes=[2, 1, 2, (2, 1, 2, 1)],243 broadcast_dim_sizes=[2, (2, 1), 2, (2, 1, 2, 1, 2, 1)]),244 dict(axis=2,245 row_length=2,246 original_dim_sizes=[2, (2, 1), 2, (2, 1, 2, 1, 2, 1)],247 broadcast_dim_sizes=[2, (2, 1), 2, (2, 1, 2, 1, 2, 1)]),248 dict(axis=3,249 row_length=(2, 1, 2, 1, 2, 1),250 original_dim_sizes=[2, (2, 1), 2, 1],251 broadcast_dim_sizes=[2, (2, 1), 2, (2, 1, 2, 1, 2, 1)]),252 ]) # pyformat: disable253 def testBroadcastDimension(self, axis, row_length, original_dim_sizes,254 broadcast_dim_sizes):255 """Tests for the broadcast_dimension method.256 Verifies that:257 * `original.broadcast_dimension(axis, row_length) == broadcast`258 * `broadcast.broadcast_dimension(axis, row_length) == broadcast`259 * `broadcast.broadcast_dimension(axis, 1) == broadcast`260 Args:261 axis: The axis to broadcast262 row_length: The slice lengths to broadcast to.263 original_dim_sizes: The dimension sizes before broadcasting.264 original_dim_sizes[axis] should be equal to `1` or `row_length`.265 broadcast_dim_sizes: THe dimension sizes after broadcasting.266 """267 original_shape = RaggedTensorDynamicShape.from_dim_sizes(original_dim_sizes)268 bcast_shape = RaggedTensorDynamicShape.from_dim_sizes(broadcast_dim_sizes)269 self.assertEqual(original_shape.rank, bcast_shape.rank)270 # shape[axis].value == 1 and row_length > 1:271 bcast1 = original_shape.broadcast_dimension(axis, row_length)272 # shape[axis].value > 1 and row_length == shape[axis].value:273 bcast2 = bcast_shape.broadcast_dimension(axis, row_length)274 # shape[axis].value > 1 and row_length == 1:275 bcast3 = bcast_shape.broadcast_dimension(axis, 1)276 self.assertShapeEq(bcast1, bcast_shape)277 self.assertShapeEq(bcast2, bcast_shape)278 self.assertShapeEq(bcast3, bcast_shape)279 @parameterized.parameters(280 [281 # Broadcast scalar282 dict(x_dims=[], y_dims=[], expected_dims=[]),283 dict(x_dims=[], y_dims=[2], expected_dims=[2]),284 dict(x_dims=[], y_dims=[2, 3], expected_dims=[2, 3]),285 dict(286 x_dims=[],287 y_dims=[2, (2, 3), (5, 7, 2, 0, 9)],288 expected_dims=[2, (2, 3), (5, 7, 2, 0, 9)]),289 # Broadcast vector290 dict(x_dims=[3], y_dims=[4, 2, 3], expected_dims=[4, 2, 3]),291 dict(x_dims=[1], y_dims=[4, 2, 3], expected_dims=[4, 2, 3]),292 dict(x_dims=[3], y_dims=[4, 2, 1], expected_dims=[4, 2, 3]),293 dict(294 x_dims=[3],295 y_dims=[3, (2, 3, 1), 1],296 expected_dims=[3, (2, 3, 1), 3]),297 dict(x_dims=[1], y_dims=[3, (2, 1, 3)], expected_dims=[3, (2, 1, 3)]),298 dict(299 x_dims=[1],300 y_dims=[3, (2, 1, 3), 8],301 expected_dims=[3, (2, 1, 3), 8]),302 dict(303 x_dims=[1],304 y_dims=[2, (2, 3), (5, 7, 2, 0, 9)],305 expected_dims=[2, (2, 3), (5, 7, 2, 0, 9)]),306 # Mixed broadcasting307 dict(308 x_dims=[309 1, # axis=0310 3, # axis=1311 (3, 0, 2), # axis=2312 1, # axis=3313 2, # axis=4314 ],315 y_dims=[316 2, # axis=0317 1, # axis=1318 1, # axis=2319 (7, 2), # axis=3320 1, # axis=4321 ],322 expected_dims=[323 2, # axis=0324 3, # axis=1325 (3, 0, 2, 3, 0, 2), # axis=2326 (7, 7, 7, 7, 7, 2, 2, 2, 2, 2), # axis=3327 2, # axis=4328 ]),329 dict(330 x_dims=[2, (2, 1), 2, 1],331 y_dims=[1, 1, 2, (2, 1)],332 expected_dims=[2, (2, 1), 2, (2, 1, 2, 1, 2, 1)]),333 ])334 def testBroadcastDynamicShape(self, x_dims, y_dims, expected_dims):335 x_shape = RaggedTensorDynamicShape.from_dim_sizes(x_dims)336 y_shape = RaggedTensorDynamicShape.from_dim_sizes(y_dims)337 expected = RaggedTensorDynamicShape.from_dim_sizes(expected_dims)338 result1 = ragged_tensor_shape.broadcast_dynamic_shape(x_shape, y_shape)339 result2 = ragged_tensor_shape.broadcast_dynamic_shape(y_shape, x_shape)340 self.assertShapeEq(expected, result1)341 self.assertShapeEq(expected, result2)342 def testRepr(self):343 shape = RaggedTensorDynamicShape.from_dim_sizes([2, (2, 1), 2, 1])344 self.assertRegex(345 repr(shape), r'RaggedTensorDynamicShape\('346 r'partitioned_dim_sizes=\(<[^>]+>, <[^>]+>\), '347 r'inner_dim_sizes=<[^>]+>\)')348 @parameterized.parameters([349 dict(350 x=[[10], [20], [30]], # shape=[3, 1]351 dim_sizes=[3, 2],352 expected=[[10, 10], [20, 20], [30, 30]]),353 dict(354 x=[[10], [20], [30]], # shape=[3, 1]355 dim_sizes=[3, [3, 0, 2]],356 expected=ragged_factory_ops.constant_value(357 [[10, 10, 10], [], [30, 30]], dtype=np.int32)),358 dict(359 x=[[[1, 2, 3]], [[4, 5, 6]]], # shape = [2, 1, 3]360 dim_sizes=[2, [2, 3], 3],361 expected=ragged_factory_ops.constant_value(362 [[[1, 2, 3], [1, 2, 3]], [[4, 5, 6], [4, 5, 6], [4, 5, 6]]],363 dtype=np.int32,364 ragged_rank=1)),365 dict(366 x=[[[1]], [[2]]], # shape = [2, 1, 1]367 dim_sizes=[2, [2, 3], [0, 2, 1, 2, 0]],368 expected=ragged_factory_ops.constant_value(369 [[[], [1, 1]], [[2], [2, 2], []]], dtype=np.int32,370 ragged_rank=2)),371 dict(372 x=10,373 dim_sizes=[3, [3, 0, 2]],374 expected=ragged_factory_ops.constant_value([[10, 10, 10], [],375 [10, 10]])),376 dict(377 x=ragged_factory_ops.constant_value([[[1], [2]], [[3]]],378 ragged_rank=1),379 dim_sizes=[2, [2, 1], 2],380 expected=ragged_factory_ops.constant_value(381 [[[1, 1], [2, 2]], [[3, 3]]], ragged_rank=1)),382 ])383 def testRaggedBroadcastTo(self, x, dim_sizes, expected):384 shape = RaggedTensorDynamicShape.from_dim_sizes(dim_sizes)385 result = ragged_tensor_shape.broadcast_to(x, shape)386 self.assertEqual(387 getattr(result, 'ragged_rank', 0), getattr(expected, 'ragged_rank', 0))388 self.assertAllEqual(result, expected)389 @parameterized.parameters(390 [391 dict(392 doc='x.shape=[3, (D1)]; y.shape=[3, 1]; bcast.shape=[3, (D1)]',393 x=ragged_factory_ops.constant_value([[1, 2, 3], [], [4, 5]],394 dtype=np.int32),395 y=[[10], [20], [30]],396 expected=ragged_factory_ops.constant_value([[11, 12, 13], [],397 [34, 35]])),398 dict(...

Full Screen

Full Screen

sampled_multi_dataset.py

Source:sampled_multi_dataset.py Github

copy

Full Screen

...282 [b["tgt_lang_id"] for b in batches]283 )284 return batch285 @property286 def sizes(self):287 if self._sizes is not None:288 return self._sizes289 start_time = time.time()290 in_sub_dataset_indices = [291 self._cur_indices[292 0 if i == 0 else self.cumulated_sizes[i - 1] : self.cumulated_sizes[i]293 ]294 for i in range(len(self.datasets))295 ]296 sub_dataset_sizes = [297 d.sizes[indices]298 for d, indices in zip(self.datasets, in_sub_dataset_indices)299 ]300 self._sizes = np.vstack(sub_dataset_sizes)301 logger.info(f"sizes() calling time: {get_time_gap(start_time, time.time())}")302 return self._sizes303 def ordered_indices(self):304 if self.shuffle:305 indices = np.random.permutation(len(self))306 else:307 indices = np.arange(len(self))308 sizes = self.sizes309 tgt_sizes = sizes[:, 1] if len(sizes.shape) > 0 and sizes.shape[1] > 1 else None310 src_sizes = (311 sizes[:, 0] if len(sizes.shape) > 0 and sizes.shape[1] > 1 else sizes312 )313 # sort by target length, then source length314 if tgt_sizes is not None:315 indices = indices[np.argsort(tgt_sizes[indices], kind="mergesort")]...

Full Screen

Full Screen

conv2d_test.py

Source:conv2d_test.py Github

copy

Full Screen

1# Copyright 2017 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests for Conv2D via the XLA JIT.16The canned results in these tests are created by running each test using the17Tensorflow CPU device and saving the output.18"""19from __future__ import absolute_import20from __future__ import division21from __future__ import print_function22import numpy as np23from tensorflow.compiler.tests.xla_test import XLATestCase24from tensorflow.python.framework import dtypes25from tensorflow.python.ops import array_ops26from tensorflow.python.ops import gen_nn_ops27from tensorflow.python.ops import nn_ops28from tensorflow.python.platform import googletest29class Conv2DTest(XLATestCase):30 def _VerifyValues(self, input_sizes, filter_sizes, stride, padding, expected):31 """Tests that tf.nn.conv2d produces the expected value.32 Args:33 input_sizes: Input tensor dimensions in34 [batch, input_rows, input_cols, input_depth].35 filter_sizes: Filter tensor dimensions in36 [kernel_rows, kernel_cols, input_depth, output_depth].37 stride: Stride.38 padding: Padding type.39 expected: Expected output.40 """41 total_size_1 = np.prod(input_sizes)42 total_size_2 = np.prod(filter_sizes)43 x1 = np.arange(1, total_size_1 + 1, dtype=np.float32).reshape(input_sizes)44 x2 = np.arange(1, total_size_2 + 1, dtype=np.float32).reshape(filter_sizes)45 strides = [1, stride, stride, 1]46 with self.test_session() as sess:47 with self.test_scope():48 t1 = array_ops.placeholder(dtypes.float32, shape=input_sizes)49 t2 = array_ops.placeholder(dtypes.float32, shape=filter_sizes)50 out = nn_ops.conv2d(51 t1, t2, strides=strides, padding=padding, data_format="NHWC")52 value = sess.run(out, {t1: x1, t2: x2})53 self.assertArrayNear(expected, np.ravel(value), 1e-3)54 def testConv2D1x1Filter(self):55 expected_output = [56 30.0, 36.0, 42.0, 66.0, 81.0, 96.0, 102.0, 126.0, 150.0, 138.0, 171.0,57 204.0, 174.0, 216.0, 258.0, 210.0, 261.0, 312.058 ]59 self._VerifyValues(60 input_sizes=[1, 2, 3, 3],61 filter_sizes=[1, 1, 3, 3],62 stride=1,63 padding="VALID",64 expected=expected_output)65 def testConv2D2x2Filter(self):66 expected_output = [2271.0, 2367.0, 2463.0, 2901.0, 3033.0, 3165.0]67 self._VerifyValues(68 input_sizes=[1, 2, 3, 3],69 filter_sizes=[2, 2, 3, 3],70 stride=1,71 padding="VALID",72 expected=expected_output)73 def testConv2D1x2Filter(self):74 expected_output = [75 231.0, 252.0, 273.0, 384.0, 423.0, 462.0, 690.0, 765.0, 840.0, 843.0,76 936.0, 1029.077 ]78 self._VerifyValues(79 input_sizes=[1, 2, 3, 3],80 filter_sizes=[1, 2, 3, 3],81 stride=1,82 padding="VALID",83 expected=expected_output)84 def testConv2D2x2FilterStride2(self):85 expected_output = [2271.0, 2367.0, 2463.0]86 self._VerifyValues(87 input_sizes=[1, 2, 3, 3],88 filter_sizes=[2, 2, 3, 3],89 stride=2,90 padding="VALID",91 expected=expected_output)92 def testConv2D2x2FilterStride2Same(self):93 expected_output = [2271.0, 2367.0, 2463.0, 1230.0, 1305.0, 1380.0]94 self._VerifyValues(95 input_sizes=[1, 2, 3, 3],96 filter_sizes=[2, 2, 3, 3],97 stride=2,98 padding="SAME",99 expected=expected_output)100class Conv2DBackpropInputTest(XLATestCase):101 def _VerifyValues(self, input_sizes, filter_sizes, out_backprop_sizes, stride,102 padding, expected):103 """Tests that gen_nn_ops.conv2d_backprop_input produces the expected output.104 Args:105 input_sizes: Input tensor dimensions in106 [batch, input_rows, input_cols, input_depth].107 filter_sizes: Filter tensor dimensions in108 [kernel_rows, kernel_cols, input_depth, output_depth].109 out_backprop_sizes: Output gradients tensor dimensions.110 stride: Stride.111 padding: Padding type.112 expected: Expected output.113 """114 total_size_1 = np.prod(filter_sizes)115 total_size_2 = np.prod(out_backprop_sizes)116 x1 = np.arange(1, total_size_1 + 1, dtype=np.float32).reshape(filter_sizes)117 x2 = np.arange(118 1, total_size_2 + 1, dtype=np.float32).reshape(out_backprop_sizes)119 strides = [1, stride, stride, 1]120 with self.test_session() as sess:121 with self.test_scope():122 t1 = array_ops.placeholder(dtypes.float32, shape=filter_sizes)123 t2 = array_ops.placeholder(dtypes.float32, shape=out_backprop_sizes)124 out = gen_nn_ops.conv2d_backprop_input(125 input_sizes=input_sizes,126 filter=t1,127 out_backprop=t2,128 strides=strides,129 padding=padding,130 data_format="NHWC")131 value = sess.run(out, {t1: x1, t2: x2})132 self.assertArrayNear(expected, np.ravel(value), 1e-3)133 def testConv2D1x1Filter(self):134 expected_output = [135 5, 11, 17, 11, 25, 39, 17, 39, 61, 23, 53, 83, 29, 67, 105, 35, 81, 127,136 41, 95, 149, 47, 109, 171, 53, 123, 193, 59, 137, 215, 65, 151, 237, 71,137 165, 259, 77, 179, 281, 83, 193, 303, 89, 207, 325, 95, 221, 347.138 ]139 self._VerifyValues(140 input_sizes=[1, 4, 4, 3],141 filter_sizes=[1, 1, 3, 2],142 out_backprop_sizes=[1, 4, 4, 2],143 stride=1,144 padding="VALID",145 expected=expected_output)146 def testConv2D1x2FilterStride3Width5(self):147 expected_output = [1, 2, 0, 2, 4]148 self._VerifyValues(149 input_sizes=[1, 1, 5, 1],150 filter_sizes=[1, 2, 1, 1],151 out_backprop_sizes=[1, 1, 2, 1],152 stride=3,153 padding="VALID",154 expected=expected_output)155 def testConv2D1x2FilterStride3Width6(self):156 expected_output = [1, 2, 0, 2, 4, 0]157 self._VerifyValues(158 input_sizes=[1, 1, 6, 1],159 filter_sizes=[1, 2, 1, 1],160 out_backprop_sizes=[1, 1, 2, 1],161 stride=3,162 padding="VALID",163 expected=expected_output)164 def testConv2D1x2FilterStride3Width7(self):165 expected_output = [1, 2, 0, 2, 4, 0, 0]166 self._VerifyValues(167 input_sizes=[1, 1, 7, 1],168 filter_sizes=[1, 2, 1, 1],169 out_backprop_sizes=[1, 1, 2, 1],170 stride=3,171 padding="VALID",172 expected=expected_output)173 def testConv2D2x2FilterC1Same(self):174 expected_output = [1, 4, 7, 7, 23, 33]175 self._VerifyValues(176 input_sizes=[1, 2, 3, 1],177 filter_sizes=[2, 2, 1, 1],178 out_backprop_sizes=[1, 2, 3, 1],179 stride=1,180 padding="SAME",181 expected=expected_output)182 def testConv2D2x2Filter(self):183 expected_output = [184 14, 32, 50, 100, 163, 226, 167, 212, 257, 122, 140, 158, 478, 541, 604,185 437, 482, 527186 ]187 self._VerifyValues(188 input_sizes=[1, 2, 3, 3],189 filter_sizes=[2, 2, 3, 3],190 out_backprop_sizes=[1, 1, 2, 3],191 stride=1,192 padding="VALID",193 expected=expected_output)194 def testConv2D2x2FilterSame(self):195 expected_output = [196 14, 32, 50, 100, 163, 226, 217, 334, 451, 190, 307, 424, 929, 1217,197 1505, 1487, 1883, 2279198 ]199 self._VerifyValues(200 input_sizes=[1, 2, 3, 3],201 filter_sizes=[2, 2, 3, 3],202 out_backprop_sizes=[1, 2, 3, 3],203 stride=1,204 padding="SAME",205 expected=expected_output)206 def testConv2D1x2Filter(self):207 expected_output = [1, 4, 4, 3, 10, 8, 5, 16, 12]208 self._VerifyValues(209 input_sizes=[1, 3, 3, 1],210 filter_sizes=[1, 2, 1, 1],211 out_backprop_sizes=[1, 3, 2, 1],212 stride=1,213 padding="VALID",214 expected=expected_output)215 def testConv2D1x2FilterSame(self):216 expected_output = [1, 4, 7, 4, 13, 16, 7, 22, 25]217 self._VerifyValues(218 input_sizes=[1, 3, 3, 1],219 filter_sizes=[1, 2, 1, 1],220 out_backprop_sizes=[1, 3, 3, 1],221 stride=1,222 padding="SAME",223 expected=expected_output)224 def testConv2D2x2FilterStride2(self):225 expected_output = [1, 2, 5, 4, 6, 0, 0, 0, 0, 0, 3, 6, 13, 8, 12]226 self._VerifyValues(227 input_sizes=[1, 3, 5, 1],228 filter_sizes=[1, 3, 1, 1],229 out_backprop_sizes=[1, 2, 2, 1],230 stride=2,231 padding="VALID",232 expected=expected_output)233 def testConv2D2x2FilterStride2Same(self):234 expected_output = [1, 2, 2, 3, 4, 6]235 self._VerifyValues(236 input_sizes=[1, 2, 3, 1],237 filter_sizes=[2, 2, 1, 1],238 out_backprop_sizes=[1, 1, 2, 1],239 stride=2,240 padding="SAME",241 expected=expected_output)242class Conv2DBackpropFilterTest(XLATestCase):243 def _VerifyValues(self, input_sizes, filter_sizes, out_backprop_sizes, stride,244 padding, expected):245 """Tests that gen_nn_ops.conv2d_backprop_filter produces the right output.246 Args:247 input_sizes: Input tensor dimensions in248 [batch, input_rows, input_cols, input_depth].249 filter_sizes: Filter tensor dimensions in250 [kernel_rows, kernel_cols, input_depth, output_depth].251 out_backprop_sizes: Output gradients tensor dimensions.252 stride: Stride.253 padding: Padding type.254 expected: Expected output.255 """256 total_size_1 = np.prod(input_sizes)257 total_size_2 = np.prod(out_backprop_sizes)258 x1 = np.arange(1, total_size_1 + 1, dtype=np.float32).reshape(input_sizes)259 x2 = np.arange(260 1, total_size_2 + 1, dtype=np.float32).reshape(out_backprop_sizes)261 strides = [1, stride, stride, 1]262 with self.test_session() as sess:263 with self.test_scope():264 t1 = array_ops.placeholder(dtypes.float32, shape=input_sizes)265 t2 = array_ops.placeholder(dtypes.float32, shape=out_backprop_sizes)266 tensor = gen_nn_ops.conv2d_backprop_filter(267 input=t1,268 filter_sizes=filter_sizes,269 out_backprop=t2,270 strides=strides,271 padding=padding,272 data_format="NHWC")273 value = sess.run(tensor, {t1: x1, t2: x2})274 self.assertArrayNear(expected, np.ravel(value), 1e-3)275 def testConv2D1x1Filter(self):276 expected_output = [8056, 8432, 8312, 8704, 8568, 8976]277 self._VerifyValues(278 input_sizes=[1, 4, 4, 3],279 filter_sizes=[1, 1, 3, 2],280 out_backprop_sizes=[1, 4, 4, 2],281 stride=1,282 padding="VALID",283 expected=expected_output)284 def testConv2D1x2Filter(self):285 expected_output = [120, 141]286 self._VerifyValues(287 input_sizes=[1, 3, 3, 1],288 filter_sizes=[1, 2, 1, 1],289 out_backprop_sizes=[1, 3, 2, 1],290 stride=1,291 padding="VALID",292 expected=expected_output)293 def testConv2D2x2FilterDepth1(self):294 expected_output = [5, 8, 14, 17]295 self._VerifyValues(296 input_sizes=[1, 2, 3, 1],297 filter_sizes=[2, 2, 1, 1],298 out_backprop_sizes=[1, 1, 2, 1],299 stride=1,300 padding="VALID",301 expected=expected_output)302 def testConv2D2x2Filter(self):303 expected_output = [304 17, 22, 27, 22, 29, 36, 27, 36, 45, 32, 43, 54, 37, 50, 63, 42, 57, 72,305 62, 85, 108, 67, 92, 117, 72, 99, 126, 77, 106, 135, 82, 113, 144, 87,306 120, 153307 ]308 self._VerifyValues(309 input_sizes=[1, 2, 3, 3],310 filter_sizes=[2, 2, 3, 3],311 out_backprop_sizes=[1, 1, 2, 3],312 stride=1,313 padding="VALID",314 expected=expected_output)315 def testConv2D1x2FilterStride3Width5(self):316 expected_output = [9, 12]317 self._VerifyValues(318 input_sizes=[1, 1, 5, 1],319 filter_sizes=[1, 2, 1, 1],320 out_backprop_sizes=[1, 1, 2, 1],321 stride=3,322 padding="VALID",323 expected=expected_output)324 def testConv2D1x2FilterStride3Width6(self):325 expected_output = [9, 12]326 self._VerifyValues(327 input_sizes=[1, 1, 6, 1],328 filter_sizes=[1, 2, 1, 1],329 out_backprop_sizes=[1, 1, 2, 1],330 stride=3,331 padding="VALID",332 expected=expected_output)333 def testConv2D1x2FilterStride3Width7(self):334 expected_output = [9, 12]335 self._VerifyValues(336 input_sizes=[1, 1, 7, 1],337 filter_sizes=[1, 2, 1, 1],338 out_backprop_sizes=[1, 1, 2, 1],339 stride=3,340 padding="VALID",341 expected=expected_output)342 def testConv2D1x3Filter(self):343 expected_output = [5, 8, 11]344 self._VerifyValues(345 input_sizes=[1, 1, 4, 1],346 filter_sizes=[1, 3, 1, 1],347 out_backprop_sizes=[1, 1, 2, 1],348 stride=1,349 padding="VALID",350 expected=expected_output)351 def testConv2D1x3FilterSame(self):352 expected_output = [20, 30, 20]353 self._VerifyValues(354 input_sizes=[1, 1, 4, 1],355 filter_sizes=[1, 3, 1, 1],356 out_backprop_sizes=[1, 1, 4, 1],357 stride=1,358 padding="SAME",359 expected=expected_output)360 def testConv2D1x3FilterSameOutbackprop2(self):361 expected_output = [7, 10, 3]362 self._VerifyValues(363 input_sizes=[1, 1, 4, 1],364 filter_sizes=[1, 3, 1, 1],365 out_backprop_sizes=[1, 1, 2, 1],366 stride=2,367 padding="SAME",368 expected=expected_output)369 def testConv2D2x2FilterC1Same(self):370 expected_output = [91, 58, 32, 17]371 self._VerifyValues(372 input_sizes=[1, 2, 3, 1],373 filter_sizes=[2, 2, 1, 1],374 out_backprop_sizes=[1, 2, 3, 1],375 stride=1,376 padding="SAME",377 expected=expected_output)378 def testConv2D2x2FilterStride2(self):379 expected_output = [92, 102, 112]380 self._VerifyValues(381 input_sizes=[1, 3, 5, 1],382 filter_sizes=[1, 3, 1, 1],383 out_backprop_sizes=[1, 2, 2, 1],384 stride=2,385 padding="VALID",386 expected=expected_output)387 def testConv2D2x2FilterStride2Same(self):388 expected_output = [7, 2, 16, 5]389 self._VerifyValues(390 input_sizes=[1, 2, 3, 1],391 filter_sizes=[2, 2, 1, 1],392 out_backprop_sizes=[1, 1, 2, 1],393 stride=2,394 padding="SAME",395 expected=expected_output)396if __name__ == "__main__":...

Full Screen

Full Screen

tt_core.py

Source:tt_core.py Github

copy

Full Screen

1## @package tt_core2# Module caffe2.python.tt_core3from __future__ import absolute_import4from __future__ import division5from __future__ import print_function6import numpy as np7"""8The following methods are various utility methods for using the Tensor-Train9decomposition, or TT-decomposition introduced by I. V. Oseledets (2011) in his10paper (http://epubs.siam.org/doi/abs/10.1137/090752286).11Broadly speaking, these methods are used to replace fully connected layers in12neural networks with Tensor-Train layers introduced by A. Novikov et. al. (2015)13in their paper (http://arxiv.org/abs/1509.06569). More details about each of14the methods are provided in each respective docstring.15"""16def init_tt_cores(inp_sizes, out_sizes, tt_ranks, seed=1234):17 """18 Initialize randomized orthogonalized TT-cores.19 This method should be used when a TT-layer is trained from scratch. The20 sizes of each of the cores are specified by the inp_sizes and out_sizes, and21 the respective tt_ranks will dictate the ranks of each of the cores. Note22 that a larger set of tt_ranks will result in slower computation but will23 result in more accurate approximations. The size of the ith core is:24 tt_ranks[i] * inp_sizes[i] * out_sizes[i] * tt_ranks[i + 1].25 Note that the following relationships of lengths of each input is expected:26 len(inp_sizes) == len(out_sizes) == len(tt_ranks) - 1.27 Args:28 inp_sizes: list of the input dimensions of the respective cores29 out_sizes: list of the output dimensions of the respective cores30 tt_ranks: list of the ranks of the respective cores31 seed: integer to seed the random number generator32 Returns:33 cores: One-dimensional list of cores concatentated along an axis34 """35 np.random.seed(seed)36 # Assert that the sizes of each input is correct37 assert(len(inp_sizes) == len(out_sizes)), \38 "The number of input dimensions (" + str(len(inp_sizes)) + \39 ") must be equal to the number of output dimensions (" + \40 str(len(out_sizes)) + ")."41 assert(len(tt_ranks) == len(inp_sizes) + 1), \42 "The number of tt-ranks (" + str(len(tt_ranks)) + ") must be " + \43 "one more than the number of input and output dims (" + \44 str(len(out_sizes)) + ")."45 # Convert to numpy arrays46 inp_sizes = np.array(inp_sizes)47 out_sizes = np.array(out_sizes)48 tt_ranks = np.array(tt_ranks)49 # Initialize the cores array50 cores_len = np.sum(51 inp_sizes * out_sizes * tt_ranks[1:] * tt_ranks[:-1])52 cores = np.zeros(cores_len)53 cores_idx = 054 rv = 155 # Compute the full list of cores by computing each individual one56 for i in range(inp_sizes.shape[0]):57 shape = [tt_ranks[i],58 inp_sizes[i],59 out_sizes[i],60 tt_ranks[i + 1]]61 # Precompute the shape of each core62 tall_shape = (np.prod(shape[:3]), shape[3])63 # Randomly initialize the current core using a normal distribution64 curr_core = np.dot(rv, np.random.normal(65 0, 1, size=(shape[0], np.prod(shape[1:]))))66 curr_core = curr_core.reshape(tall_shape)67 # Orthogonalize the initialized current core and append to cores list68 if i < inp_sizes.shape[0] - 1:69 curr_core, rv = np.linalg.qr(curr_core)70 cores[cores_idx:cores_idx +71 curr_core.size] = curr_core.flatten()72 cores_idx += curr_core.size73 # Normalize the list of arrays using this Glarot trick74 glarot_style = (np.prod(inp_sizes) *75 np.prod(tt_ranks))**(1.0 / inp_sizes.shape[0])76 return (0.1 / glarot_style) * np.array(cores).astype(np.float32)77def matrix_to_tt(W, inp_sizes, out_sizes, tt_ranks):78 """79 Convert a matrix into the TT-format.80 This method will consume a 2D weight matrix such as those used in fully81 connected layers in a neural network and will compute the TT-decomposition82 of the weight matrix and return the TT-cores of the resulting computation.83 This method should be used when converting a trained, fully connected layer,84 into a TT-layer for increased speed and decreased parameter size. The size85 of the ith core is:86 tt_ranks[i] * inp_sizes[i] * out_sizes[i] * tt_ranks[i + 1].87 Note that the following relationships of lengths of each input is expected:88 len(inp_sizes) == len(out_sizes) == len(tt_ranks) - 1.89 We also require that np.prod(inp_sizes) == W.shape[0] and that90 np.prod(out_sizes) == W.shape[1].91 Args:92 W: two-dimensional weight matrix numpy array representing a fully93 connected layer to be converted to TT-format; note that the weight94 matrix is transposed before decomposed because we want to emulate the95 X * W^T operation that the FC layer performs.96 inp_sizes: list of the input dimensions of the respective cores97 out_sizes: list of the output dimensions of the respective cores98 tt_ranks: list of the ranks of the respective cores99 Returns:100 new_cores: One-dimensional list of cores concatentated along an axis101 """102 # Assert that the sizes of each input is correct103 assert(len(inp_sizes) == len(out_sizes)), \104 "The number of input dimensions (" + str(len(inp_sizes)) + \105 ") must be equal to the number of output dimensions (" + \106 str(len(out_sizes)) + ")."107 assert(len(tt_ranks) == len(inp_sizes) + 1), \108 "The number of tt-ranks (" + str(len(tt_ranks)) + ") must be " + \109 "one more than the number of input and output dimensions (" + \110 str(len(out_sizes)) + ")."111 assert(W.shape[0] == np.prod(inp_sizes)), \112 "The product of the input sizes (" + str(np.prod(inp_sizes)) + \113 ") must be equal to first dimension of W (" + str(W.shape[0]) + ")."114 assert(W.shape[1] == np.prod(out_sizes)), \115 "The product of the output sizes (" + str(np.prod(out_sizes)) + \116 ") must be equal to second dimension of W (" + str(W.shape[1]) + ")."117 # W is transposed so that the multiplication X * W^T can be computed, just118 # as it is in the FC layer.119 W = W.transpose()120 # Convert to numpy arrays121 inp_sizes = np.array(inp_sizes)122 out_sizes = np.array(out_sizes)123 tt_ranks = np.array(tt_ranks)124 # Copy the original weight matrix in order to permute and reshape the weight125 # matrix. In addition, the inp_sizes and out_sizes are combined to a single126 # sizes array to use the tt_svd helper method, which only consumes a single127 # sizes array.128 W_copy = W.copy()129 total_inp_size = inp_sizes.size130 W_copy = np.reshape(W_copy, np.concatenate((inp_sizes, out_sizes)))131 order = np.repeat(np.arange(0, total_inp_size), 2) + \132 np.tile([0, total_inp_size], total_inp_size)133 W_copy = np.transpose(W_copy, axes=order)134 W_copy = np.reshape(W_copy, inp_sizes * out_sizes)135 # Use helper method to convert the W matrix copy into the preliminary136 # cores array.137 cores = tt_svd(W_copy, inp_sizes * out_sizes, tt_ranks)138 # Permute the dimensions of each of the cores to be compatible with the139 # TT-layer.140 new_cores = np.zeros(cores.shape).astype(np.float32)141 idx = 0142 for i in range(len(inp_sizes)):143 shape = (tt_ranks[i], inp_sizes[i], out_sizes[i], tt_ranks[i + 1])144 current_core = cores[idx:idx + np.prod(shape)].reshape(shape)145 current_core = current_core.transpose((1, 3, 0, 2))146 new_cores[new_cores.shape[0] - idx - np.prod(shape):147 new_cores.shape[0] - idx] \148 = current_core.flatten()149 idx += np.prod(shape)150 return new_cores151def tt_svd(W, sizes, tt_ranks):152 """153 Helper method for the matrix_to_tt() method performing the TT-SVD154 decomposition.155 Uses the TT-decomposition algorithm to convert a matrix to TT-format using156 multiple reduced SVD operations.157 Args:158 W: two-dimensional weight matrix representing a fully connected layer to159 be converted to TT-format preprocessed by the matrix_to_tt() method.160 sizes: list of the dimensions of each of the cores161 tt_ranks: list of the ranks of the respective cores162 Returns:163 cores: One-dimensional list of cores concatentated along an axis164 """165 assert(len(tt_ranks) == len(sizes) + 1)166 C = W.copy()167 total_size = sizes.size168 core = np.zeros(np.sum(tt_ranks[:-1] * sizes * tt_ranks[1:]),169 dtype='float32')170 # Compute iterative reduced SVD operations and store each resulting U matrix171 # as an individual core.172 pos = 0173 for i in range(0, total_size - 1):174 shape = tt_ranks[i] * sizes[i]175 C = np.reshape(C, [shape, -1])176 U, S, V = np.linalg.svd(C, full_matrices=False)177 U = U[:, 0:tt_ranks[i + 1]]178 S = S[0:tt_ranks[i + 1]]179 V = V[0:tt_ranks[i + 1], :]180 core[pos:pos + tt_ranks[i] * sizes[i] * tt_ranks[i + 1]] = U.ravel()181 pos += tt_ranks[i] * sizes[i] * tt_ranks[i + 1]182 C = np.dot(np.diag(S), V)183 core[pos:pos + tt_ranks[total_size - 1] *184 sizes[total_size - 1] * tt_ranks[total_size]] = C.ravel()185 return core186# TODO(Surya) Write a method to convert an entire network where all fully187# connected layers are replaced by an TT layer.188def fc_net_to_tt_net(net):...

Full Screen

Full Screen

test_anchors.py

Source:test_anchors.py Github

copy

Full Screen

1import numpy as np2import configparser3from tensorflow import keras4from keras_retinanet.utils.anchors import anchors_for_shape, AnchorParameters5from keras_retinanet.utils.config import read_config_file, parse_anchor_parameters6def test_config_read():7 config = read_config_file('tests/test-data/config/config.ini')8 assert 'anchor_parameters' in config9 assert 'sizes' in config['anchor_parameters']10 assert 'strides' in config['anchor_parameters']11 assert 'ratios' in config['anchor_parameters']12 assert 'scales' in config['anchor_parameters']13 assert config['anchor_parameters']['sizes'] == '32 64 128 256 512'14 assert config['anchor_parameters']['strides'] == '8 16 32 64 128'15 assert config['anchor_parameters']['ratios'] == '0.5 1 2 3'16 assert config['anchor_parameters']['scales'] == '1 1.2 1.6'17def create_anchor_params_config():18 config = configparser.ConfigParser()19 config['anchor_parameters'] = {}20 config['anchor_parameters']['sizes'] = '32 64 128 256 512'21 config['anchor_parameters']['strides'] = '8 16 32 64 128'22 config['anchor_parameters']['ratios'] = '0.5 1'23 config['anchor_parameters']['scales'] = '1 1.2 1.6'24 return config25def test_parse_anchor_parameters():26 config = create_anchor_params_config()27 anchor_params_parsed = parse_anchor_parameters(config)28 sizes = [32, 64, 128, 256, 512]29 strides = [8, 16, 32, 64, 128]30 ratios = np.array([0.5, 1], keras.backend.floatx())31 scales = np.array([1, 1.2, 1.6], keras.backend.floatx())32 assert sizes == anchor_params_parsed.sizes33 assert strides == anchor_params_parsed.strides34 np.testing.assert_equal(ratios, anchor_params_parsed.ratios)35 np.testing.assert_equal(scales, anchor_params_parsed.scales)36def test_anchors_for_shape_dimensions():37 sizes = [32, 64, 128]38 strides = [8, 16, 32]39 ratios = np.array([0.5, 1, 2, 3], keras.backend.floatx())40 scales = np.array([1, 1.2, 1.6], keras.backend.floatx())41 anchor_params = AnchorParameters(sizes, strides, ratios, scales)42 pyramid_levels = [3, 4, 5]43 image_shape = (64, 64)44 all_anchors = anchors_for_shape(image_shape, pyramid_levels=pyramid_levels, anchor_params=anchor_params)45 assert all_anchors.shape == (1008, 4)46def test_anchors_for_shape_values():47 sizes = [12]48 strides = [8]49 ratios = np.array([1, 2], keras.backend.floatx())50 scales = np.array([1, 2], keras.backend.floatx())51 anchor_params = AnchorParameters(sizes, strides, ratios, scales)52 pyramid_levels = [3]53 image_shape = (16, 16)54 all_anchors = anchors_for_shape(image_shape, pyramid_levels=pyramid_levels, anchor_params=anchor_params)55 # using almost_equal for floating point imprecisions56 np.testing.assert_almost_equal(all_anchors[0, :], [57 strides[0] / 2 - (sizes[0] * scales[0] / np.sqrt(ratios[0])) / 2,58 strides[0] / 2 - (sizes[0] * scales[0] * np.sqrt(ratios[0])) / 2,59 strides[0] / 2 + (sizes[0] * scales[0] / np.sqrt(ratios[0])) / 2,60 strides[0] / 2 + (sizes[0] * scales[0] * np.sqrt(ratios[0])) / 2,61 ], decimal=6)62 np.testing.assert_almost_equal(all_anchors[1, :], [63 strides[0] / 2 - (sizes[0] * scales[1] / np.sqrt(ratios[0])) / 2,64 strides[0] / 2 - (sizes[0] * scales[1] * np.sqrt(ratios[0])) / 2,65 strides[0] / 2 + (sizes[0] * scales[1] / np.sqrt(ratios[0])) / 2,66 strides[0] / 2 + (sizes[0] * scales[1] * np.sqrt(ratios[0])) / 2,67 ], decimal=6)68 np.testing.assert_almost_equal(all_anchors[2, :], [69 strides[0] / 2 - (sizes[0] * scales[0] / np.sqrt(ratios[1])) / 2,70 strides[0] / 2 - (sizes[0] * scales[0] * np.sqrt(ratios[1])) / 2,71 strides[0] / 2 + (sizes[0] * scales[0] / np.sqrt(ratios[1])) / 2,72 strides[0] / 2 + (sizes[0] * scales[0] * np.sqrt(ratios[1])) / 2,73 ], decimal=6)74 np.testing.assert_almost_equal(all_anchors[3, :], [75 strides[0] / 2 - (sizes[0] * scales[1] / np.sqrt(ratios[1])) / 2,76 strides[0] / 2 - (sizes[0] * scales[1] * np.sqrt(ratios[1])) / 2,77 strides[0] / 2 + (sizes[0] * scales[1] / np.sqrt(ratios[1])) / 2,78 strides[0] / 2 + (sizes[0] * scales[1] * np.sqrt(ratios[1])) / 2,79 ], decimal=6)80 np.testing.assert_almost_equal(all_anchors[4, :], [81 strides[0] * 3 / 2 - (sizes[0] * scales[0] / np.sqrt(ratios[0])) / 2,82 strides[0] / 2 - (sizes[0] * scales[0] * np.sqrt(ratios[0])) / 2,83 strides[0] * 3 / 2 + (sizes[0] * scales[0] / np.sqrt(ratios[0])) / 2,84 strides[0] / 2 + (sizes[0] * scales[0] * np.sqrt(ratios[0])) / 2,85 ], decimal=6)86 np.testing.assert_almost_equal(all_anchors[5, :], [87 strides[0] * 3 / 2 - (sizes[0] * scales[1] / np.sqrt(ratios[0])) / 2,88 strides[0] / 2 - (sizes[0] * scales[1] * np.sqrt(ratios[0])) / 2,89 strides[0] * 3 / 2 + (sizes[0] * scales[1] / np.sqrt(ratios[0])) / 2,90 strides[0] / 2 + (sizes[0] * scales[1] * np.sqrt(ratios[0])) / 2,91 ], decimal=6)92 np.testing.assert_almost_equal(all_anchors[6, :], [93 strides[0] * 3 / 2 - (sizes[0] * scales[0] / np.sqrt(ratios[1])) / 2,94 strides[0] / 2 - (sizes[0] * scales[0] * np.sqrt(ratios[1])) / 2,95 strides[0] * 3 / 2 + (sizes[0] * scales[0] / np.sqrt(ratios[1])) / 2,96 strides[0] / 2 + (sizes[0] * scales[0] * np.sqrt(ratios[1])) / 2,97 ], decimal=6)98 np.testing.assert_almost_equal(all_anchors[7, :], [99 strides[0] * 3 / 2 - (sizes[0] * scales[1] / np.sqrt(ratios[1])) / 2,100 strides[0] / 2 - (sizes[0] * scales[1] * np.sqrt(ratios[1])) / 2,101 strides[0] * 3 / 2 + (sizes[0] * scales[1] / np.sqrt(ratios[1])) / 2,102 strides[0] / 2 + (sizes[0] * scales[1] * np.sqrt(ratios[1])) / 2,103 ], decimal=6)104 np.testing.assert_almost_equal(all_anchors[8, :], [105 strides[0] / 2 - (sizes[0] * scales[0] / np.sqrt(ratios[0])) / 2,106 strides[0] * 3 / 2 - (sizes[0] * scales[0] * np.sqrt(ratios[0])) / 2,107 strides[0] / 2 + (sizes[0] * scales[0] / np.sqrt(ratios[0])) / 2,108 strides[0] * 3 / 2 + (sizes[0] * scales[0] * np.sqrt(ratios[0])) / 2,109 ], decimal=6)110 np.testing.assert_almost_equal(all_anchors[9, :], [111 strides[0] / 2 - (sizes[0] * scales[1] / np.sqrt(ratios[0])) / 2,112 strides[0] * 3 / 2 - (sizes[0] * scales[1] * np.sqrt(ratios[0])) / 2,113 strides[0] / 2 + (sizes[0] * scales[1] / np.sqrt(ratios[0])) / 2,114 strides[0] * 3 / 2 + (sizes[0] * scales[1] * np.sqrt(ratios[0])) / 2,115 ], decimal=6)116 np.testing.assert_almost_equal(all_anchors[10, :], [117 strides[0] / 2 - (sizes[0] * scales[0] / np.sqrt(ratios[1])) / 2,118 strides[0] * 3 / 2 - (sizes[0] * scales[0] * np.sqrt(ratios[1])) / 2,119 strides[0] / 2 + (sizes[0] * scales[0] / np.sqrt(ratios[1])) / 2,120 strides[0] * 3 / 2 + (sizes[0] * scales[0] * np.sqrt(ratios[1])) / 2,121 ], decimal=6)122 np.testing.assert_almost_equal(all_anchors[11, :], [123 strides[0] / 2 - (sizes[0] * scales[1] / np.sqrt(ratios[1])) / 2,124 strides[0] * 3 / 2 - (sizes[0] * scales[1] * np.sqrt(ratios[1])) / 2,125 strides[0] / 2 + (sizes[0] * scales[1] / np.sqrt(ratios[1])) / 2,126 strides[0] * 3 / 2 + (sizes[0] * scales[1] * np.sqrt(ratios[1])) / 2,127 ], decimal=6)128 np.testing.assert_almost_equal(all_anchors[12, :], [129 strides[0] * 3 / 2 - (sizes[0] * scales[0] / np.sqrt(ratios[0])) / 2,130 strides[0] * 3 / 2 - (sizes[0] * scales[0] * np.sqrt(ratios[0])) / 2,131 strides[0] * 3 / 2 + (sizes[0] * scales[0] / np.sqrt(ratios[0])) / 2,132 strides[0] * 3 / 2 + (sizes[0] * scales[0] * np.sqrt(ratios[0])) / 2,133 ], decimal=6)134 np.testing.assert_almost_equal(all_anchors[13, :], [135 strides[0] * 3 / 2 - (sizes[0] * scales[1] / np.sqrt(ratios[0])) / 2,136 strides[0] * 3 / 2 - (sizes[0] * scales[1] * np.sqrt(ratios[0])) / 2,137 strides[0] * 3 / 2 + (sizes[0] * scales[1] / np.sqrt(ratios[0])) / 2,138 strides[0] * 3 / 2 + (sizes[0] * scales[1] * np.sqrt(ratios[0])) / 2,139 ], decimal=6)140 np.testing.assert_almost_equal(all_anchors[14, :], [141 strides[0] * 3 / 2 - (sizes[0] * scales[0] / np.sqrt(ratios[1])) / 2,142 strides[0] * 3 / 2 - (sizes[0] * scales[0] * np.sqrt(ratios[1])) / 2,143 strides[0] * 3 / 2 + (sizes[0] * scales[0] / np.sqrt(ratios[1])) / 2,144 strides[0] * 3 / 2 + (sizes[0] * scales[0] * np.sqrt(ratios[1])) / 2,145 ], decimal=6)146 np.testing.assert_almost_equal(all_anchors[15, :], [147 strides[0] * 3 / 2 - (sizes[0] * scales[1] / np.sqrt(ratios[1])) / 2,148 strides[0] * 3 / 2 - (sizes[0] * scales[1] * np.sqrt(ratios[1])) / 2,149 strides[0] * 3 / 2 + (sizes[0] * scales[1] / np.sqrt(ratios[1])) / 2,150 strides[0] * 3 / 2 + (sizes[0] * scales[1] * np.sqrt(ratios[1])) / 2,...

Full Screen

Full Screen

concat_dataset.py

Source:concat_dataset.py Github

copy

Full Screen

...54 def attr(self, attr: str, index: int):55 dataset_idx = bisect.bisect_right(self.cumulative_sizes, index)56 return getattr(self.datasets[dataset_idx], attr, None)57 @property58 def sizes(self):59 _dataset_sizes = []60 for ds, sr in zip(self.datasets, self.sample_ratios):61 if isinstance(ds.sizes, np.ndarray):62 _dataset_sizes.append(np.tile(ds.sizes, sr))63 else:64 # Only support underlying dataset with single size array.65 assert isinstance(ds.sizes, list)66 _dataset_sizes.append(np.tile(ds.sizes[0], sr))67 return np.concatenate(_dataset_sizes)68 @property69 def supports_prefetch(self):70 return all(d.supports_prefetch for d in self.datasets)71 def ordered_indices(self):72 """...

Full Screen

Full Screen

product_images.py

Source:product_images.py Github

copy

Full Screen

...5from django.conf import settings6from django.templatetags.static import static7logger = logging.getLogger(__name__)8# cache available sizes at module level9def get_available_sizes():10 rendition_sizes = {}11 keys = settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS12 for dummy_size_group, sizes in keys.items():13 rendition_sizes[dummy_size_group] = {size for _, size in sizes}14 return rendition_sizes15AVAILABLE_SIZES = get_available_sizes()16def get_available_product_sizes() -> List[str]:17 """Get list of available product sizes."""18 sizes = AVAILABLE_SIZES["products"]19 product_sizes = []20 for size in sizes:21 product_sizes.append(size.strip("thumbnail__"))22 return product_sizes23AVAILABLE_PRODUCT_SIZES = get_available_product_sizes()24def choose_placeholder(size=""):25 # type: (str) -> str26 """Assign a placeholder at least as big as provided size if possible.27 When size is bigger than available, return the biggest.28 If size is invalid or not provided, return DEFAULT_PLACEHOLDER.29 """30 placeholder = settings.DEFAULT_PLACEHOLDER31 parsed_sizes = re.match(r"(\d+)x(\d+)", size)32 available_sizes = sorted(settings.PLACEHOLDER_IMAGES.keys())33 if parsed_sizes and available_sizes:34 # check for placeholder equal or bigger than requested picture35 x_size, y_size = parsed_sizes.groups()36 max_size = max([int(x_size), int(y_size)])37 bigger_or_eq = list(filter(lambda x: x >= max_size, available_sizes))...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const sizes = await page.sizes();7 console.log(sizes);8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();9import { test, expect } from '@playwright/test';10test('should display "google" text on page', async ({ page }) => {11 await page.waitForSelector('text="Google"');12 await page.screenshot({ path: `example.png` });13 const title = await page.title();14 expect(title).toBe('Google');15});16const { chromium } = require('playwright');17(async () => {18 const browser = await chromium.launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 await page.screenshot({ path: `example.png` });22 await browser.close();23})();24const { chromium } = require('playwright');25(async () => {26 const browser = await chromium.launch();27 const context = await browser.newContext();28 const page = await context.newPage();29 await page.screenshot({ path: `example.png` });30 await browser.close();31})();32const { chromium } = require('playwright');33(async () => {34 const browser = await chromium.launch();35 const context = await browser.newContext();36 const page = await context.newPage();37 await page.screenshot({ path: `example.png` });38 await browser.close();39})();40const { chromium } = require('playwright');41(async () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await chromium.launch();3 const context = await browser.newContext();4 const page = await context.newPage();5 const sizes = await page.sizes();6 console.log(sizes);7 await browser.close();8})();9![test result](./test-result.png)10[MIT](./LICENSE)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');2const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');3const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');4const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');5const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');6const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');7const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');8const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');9const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');10const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');11const { sizes } = require('playwright/lib/server/chromium/crNetworkManager');

Full Screen

Using AI Code Generation

copy

Full Screen

1const sizes = require('@playwright/test/lib/types').sizes;2const { devices } = require('playwright');3const iPhone = devices['iPhone 11 Pro'];4const iPad = devices['iPad Pro (12.9-inch) (4th generation)'];5const desktop = devices['Desktop Chrome'];6const desktopFirefox = devices['Desktop Firefox'];7const desktopSafari = devices['Desktop Safari'];8const desktopWebkit = devices['Desktop WebKit'];9const desktopIE = devices['Desktop Internet Explorer'];10const desktopEdge = devices['Desktop Edge'];11const desktopAndroid = devices['Desktop Android'];12const desktopAndroidChrome = devices['Desktop Android Chrome'];13const desktopAndroidFirefox = devices['Desktop Android Firefox'];14const desktopAndroidWebkit = devices['Desktop Android WebKit'];15const desktopAndroidSafari = devices['Desktop Android Safari'];16const desktopAndroidSamsung = devices['Desktop Android Samsung'];17const desktopAndroidSamsungChrome = devices['Desktop Android Samsung Chrome'];18const desktopAndroidSamsungFirefox = devices['Desktop Android Samsung Firefox'];19const desktopAndroidSamsungWebkit = devices['Desktop Android Samsung WebKit'];20const desktopAndroidSamsungSafari = devices['Desktop Android Samsung Safari'];21const desktopAndroidSamsungInternet = devices['Desktop Android Samsung Internet'];22const desktopAndroidSamsungEdge = devices['Desktop Android Samsung Edge'];23const desktopAndroidSamsungSamsung = devices['Desktop Android Samsung Samsung'];24const desktopAndroidSamsungSamsungChrome = devices['Desktop Android Samsung Samsung Chrome'];25const desktopAndroidSamsungSamsungFirefox = devices['Desktop Android Samsung Samsung Firefox'];26const desktopAndroidSamsungSamsungWebkit = devices['Desktop Android Samsung Samsung WebKit'];27const desktopAndroidSamsungSamsungSafari = devices['Desktop Android Samsung Samsung Safari'];28const desktopAndroidSamsungSamsungInternet = devices['Desktop Android Samsung Samsung Internet'];29const desktopAndroidSamsungSamsungEdge = devices['Desktop Android Samsung Samsung Edge'];30const desktopAndroidSamsungSamsungSamsung = devices['Desktop Android Samsung Samsung Samsung'];31const desktopAndroidSamsungSamsungSamsungChrome = devices['Desktop Android Samsung Samsung Samsung Chrome'];32const desktopAndroidSamsungSamsungSamsungFirefox = devices['Desktop Android Samsung Samsung Samsung Firefox'];33const desktopAndroidSamsungSamsungSamsungWebkit = sizes['Desktop Android Samsung Samsung Samsung WebKit'];34const desktopAndroidSamsungSamsungSamsungSafari = sizes['Desktop Android Samsung Samsung Samsung Safari'];35const desktopAndroidSamsungSamsungSamsungInternet = sizes['Desktop Android Samsung Samsung Samsung Internet'];36const desktopAndroidSamsungSamsungSamsungEdge = sizes['Desktop Android Samsung Samsung Samsung Edge'];

Full Screen

Using AI Code Generation

copy

Full Screen

1const { sizes } = require('playwright/lib/server/browserType');2console.log(sizes);3const { sizes } = require('playwright-sizes');4console.log(sizes);5{6 '480x320': { width: 480, height: 320 },7 '640x480': { width: 640, height: 480 },8 '720x480': { width: 720, height: 480 },9 '768x576': { width: 768, height: 576 },10 '800x600': { width: 800, height: 600 },11 '1024x768': { width: 1024, height: 768 },12 '1280x720': { width: 1280, height: 720 },13 '1280x800': { width: 1280, height: 800 },14 '1280x1024': { width: 1280, height: 1024 },15 '1366x768': { width: 1366, height: 768 },16 '1440x900': { width: 1440, height: 900 },17 '1600x900': { width: 1600, height: 900 },18 '1680x1050': { width: 1680, height: 1050 },19 '1920x1080': { width: 1920, height: 1080 },20 '1920x1200': { width: 1920, height: 1200 },21 '2560x1440': { width: 2560, height: 1440 },22 '2560x1600': { width: 2560, height: 1600 },23 '3840x2160': { width: 3840, height: 2160 },24 '3840x2400': { width: 3840, height: 2400 },25 '5120x2880': { width: 5120, height: 2880 },26 '5120x3200': {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { sizes } = require('@playwright/test');2console.log(sizes);3#### `sizes.getDeviceSize(deviceName)`4const { sizes } = require('@playwright/test');5const deviceSize = sizes.getDeviceSize('iPhone 11');6console.log(deviceSize);7#### `sizes.getViewportSize(page)`8const { sizes } = require('@playwright/test');9const viewportSize = sizes.getViewportSize(page);10console.log(viewportSize);11#### `sizes.getViewportSize(page, deviceName)`12const { sizes } = require('@playwright/test');13const viewportSize = sizes.getViewportSize(page, 'iPhone 11');14console.log(viewportSize);15#### `sizes.isDeviceSize(deviceName)`16const { sizes } = require('@playwright/test');17const isDeviceSize = sizes.isDeviceSize('iPhone 11');18console.log(isDeviceSize);19#### `sizes.isViewportSize(size)`

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful